sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
06d9e8016799756b394f19f2e87f6987679a08c76fc93417a657f90b0c25a0d0 | Python | 614 | 13 | """multimodal_ad: package foundation for the multimodal AD detection project.
Scientific code from the five legacy Colab notebooks (preserved
byte-for-byte under notebooks/legacy/) has been ported into `data` (typed
manifest, labeling, OASIS-3 adapter, volume preprocessing, augmentation,
splitting) and `models` (3D CN... |
0d3686210bdda2f46747b65afa7da57f2ba2a6ecf9418febe0e0f3461696a233 | Python | 614 | 19 | import os
import msgpack
from . import parent_classes
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return True #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def get(self, savedir):
with open(os.path.join(savedir, 'to_pickle_dump'), '... |
3995180fc3edeaea93c21fc3fb8cbcaaaaea499b0fb7ada058ff9955644ff7a3 | Python | 615 | 24 | import torch
from abc import ABC, abstractmethod
class Posttransformations(ABC):
"""
Parent class for pretransformations, abstract methods are
defined here.
"""
__slots__ = "inferred_tensor"
def __init__(self, inferred_tensor: torch.Tensor) -> None:
"""
Construc... |
690caa7602bcd07e222ec193c9661146c4c556249527392bd11cb1c7166d68a7 | Python | 615 | 24 | from abc import ABCMeta, abstractmethod
from EventController import EventController
class BasicStimulationProcess:
def __init__(self) -> None:
pass
@abstractmethod
def initial(self, controller, viewcontainer, messenager):
self.controller = controller
self.messenager =... |
6ed20a7a595300a8b01b15269f641452b3d5a83c018154e1ef0b36416182b4c4 | Python | 615 | 14 | __all__ = ['integration']
from ._integration import integral
from .integration import integral as integral_py
from ._convolution import convolution1, convolution,slice_test
from .dyson import dyson
from .Pipeline import Pipeline
from .Fconn import Fconn
from .Anatlas import Anatlas
from .Funatlas import Funatlas
from ... |
ecf9141d66b1b2a515b5c06b8ea8d3f5b95e371ba176fc21c941e8505824ceeb | Python | 615 | 23 | from defs import *
from values import *
import numpy as np
def compute_cotransport (cell,delmu,jsol):
numLA = len(cell.dLA)
flux = np.zeros(numLA)
for i in range(numLA):
sid = list(cell.dLA[i].solute_id)
mid = cell.dLA[i].membrane_id
this_delmu = list(delmu[i][mid[0]][mid... |
4b11f917d7f8a89512c3ecf0b4f2419d8fb1db3ea4564e00dedb6e4594d4330c | Python | 616 | 23 | from setuptools import setup
setup(
name='fastMRI Prostate',
version='1.0',
description='A large scale dataset and reconstruction script of both raw prostate MRI measurements and images',
install_requires=[
'h5py==3.7.0',
'numpy==1.23.5',
'scikit-image==0.19.2',
'torchvi... |
e37eb33a8b87a2d2b1966e375c177e4223bed64c8bf9d9e2fb098a72e024c662 | Python | 617 | 25 | import pkg_resources
import prettytable
def get_pkg_license(pkg):
try:
lines = pkg.get_metadata_lines("METADATA")
except:
lines = pkg.get_metadata_lines("PKG-INFO")
for line in lines:
if line.startswith("License:"):
return line[9:]
return "(Licence not found)"
de... |
27e6fa9b25f2a04635bc4c2ec569fcbebd11f03a3c7864aa5497b384ba2de70e | Python | 619 | 15 | """Module defining encoders."""
from onmt.encoders.encoder import EncoderBase
from onmt.encoders.transformer import TransformerEncoder
from onmt.encoders.ggnn_encoder import GGNNEncoder
from onmt.encoders.rnn_encoder import RNNEncoder
from onmt.encoders.cnn_encoder import CNNEncoder
from onmt.encoders.mean_encoder impo... |
5dcfc275df52902b0999696c25789b6680c144f3f271266ee790a850cc2b4395 | Python | 619 | 19 | """Classification task — PyCaret 4.0.
PyCaret 4.0 is OOP-only; the 3.x module-level functional API
(``setup``/``compare_models``/…) was removed. Import the experiment class:
from pycaret.classification import ClassificationExperiment
# equivalent:
from pycaret.tasks import ClassificationExperiment
Then c... |
eef6e5d847ba313b9fa9d283528b4590f05e1ea1dc00b7f3c35c5a6a7ccdd98c | Python | 619 | 22 | import os
from flask import request, got_request_exception
from app import create_app, db
from app.models import *
from config.globals import ENVIRONMENT
app = create_app(os.environ.get('FLASK_CONFIG', ENVIRONMENT))
if __name__ == '__main__':
with app.app_context():
db.create_all()
def log_exceptio... |
0935f81f817ec37f7b3a8a0a4cbe64dc33d033b24c4eb26a4d73cbe004fcceb3 | Python | 620 | 25 | # pyaging/preprocess/__init__.py
from ._preprocess import bigwig_to_df, df_to_adata, epicv2_probe_aggregation
from ._preprocess_utils import (
add_metadata_to_anndata,
add_unstructured_data,
create_anndata_object,
impute_missing_values,
load_ensembl_metadata,
log_data_statistics,
)
from ._tage ... |
9200391a2372081232edacec45f441943f1a68d3504c51b815addb65119343b9 | Python | 622 | 16 | from datetime import datetime
import sys
import enum
sys.path.append("..")
from app import db
class FileType(db.Model):
__tablename__ = 'file_type'
id = db.Column(db.Integer, primary_key=True)
designation = db.Column(db.String(255))
preprocess_task_file = db.relationship('PreprocessTaskFile', backref=... |
f03bcb76cbcf39c09e2c85e8ab25bc2a5230f9a4c479e58095e6db69c6f1f234 | Python | 623 | 18 | #
# from os.path import dirname, basename, isfile
# import glob
# modules = glob.glob(dirname(__file__)+"/*.py")
# print [basename(f)[:-3] for f in modules if isfile(f)]
# #__all__ = [basename(f)[:-3] for f in modules if isfile(f)]
#from average_std import average_std
#from histogram import histogram
#from manyline... |
77e686a9082f8201b846eb2450ee26f3fcc06a411bf9bb97a16cf2754e1d39ed | Python | 624 | 20 | """
Benchmarks for pandas at the package-level.
"""
import subprocess
import sys
class TimeImport:
def time_import(self):
# on py37+ we the "-X importtime" usage gives us a more precise
# measurement of the import time we actually care about,
# without the subprocess or interpreter over... |
b9df332f312de17d1958aa3307b2c44f5cc8623f77946cf289c488dcda20222f | Python | 624 | 15 | from Surfaces import surfaces
def load():
#path = '/Volumes/project/biocard/data/phase_1_surface_mapping_new_structure/'
path = '/Users/younes/MorphingData/Biocard/'
sub1 = '0186193_1_L'
#sub2 = '1449400_1_L'
sub2 = '2105688_1_L'
f0 = []
f0.append(surfaces.Surface(filename =path + 'hippoca... |
45ff826c5f7feac683e5be1d75ae6d78d7b3c2a602ed15e8c2551990da02e0af | Python | 625 | 20 | """Generate fixtures for tests."""
import os
import pytest
from nimare.dataset import Dataset
from nimare.tests.utils import get_test_data_path
@pytest.fixture(scope="session")
def testdata_laird():
"""Load data from dataset into global variables."""
return Dataset(os.path.join(get_test_data_path(), "neurosy... |
c4021a2a536e6ccbb3ee4e9e0149e9a0bc512a3fec3e8bc884e20f4d3d871236 | Python | 625 | 20 | """Password hashing via bcrypt."""
from __future__ import annotations
import bcrypt
def hash_password(plain: str) -> str:
"""Hash a plaintext password with bcrypt (cost=12 by default)."""
salt = bcrypt.gensalt(rounds=12)
return bcrypt.hashpw(plain.encode("utf-8"), salt).decode("utf-8")
def verify_pass... |
1b0de2556a682ba3c39743ef3301db105895bdc4f591b80656eb97a633497ffa | Python | 626 | 21 | """Generate fixtures for tests."""
import os
import pytest
from nimare.dataset import Dataset
from nimare.tests.utils import get_test_data_path
@pytest.fixture(scope="session")
def testdata_laird():
"""Load data from dataset into global variables."""
return Dataset(os.path.join(get_test_data_path(), "neuros... |
3a8bab3bfbe6058e70c41f55353e7a096784d75d75e1bf3f2609020f2b7d674f | Python | 626 | 23 | from model.oslmm import *
from model.exp_analysis import *
if __name__ == "__main__":
args = dict()
# args["domain"] = "jura"
# args["domain"] = "concrete"
args["domain"] = "equity"
# args["domain"] = "pm25"
# args["domain"] = "neuron"
args["kernel"] = "SEiso"
args["Q"] = 2... |
7ea11dd97a4547606479d2d4ea9947850722807764ebfbe3469a42fb311dd282 | Python | 626 | 32 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.16.0
# kernelspec:
# display_name: ol-connectome
# language: python
# name: ol-connectome
# ---
# %%
from pathlib import Path
import sys
... |
a2208f0607c8b470b738f2a3bca535639d1e1eee02673cca4575acff01bdc8f2 | Python | 626 | 26 | from abc import ABC, abstractmethod
import typing
import torch
import numpy as np
class Normalisation(ABC):
__slots__ = "unnormalised_data"
def __init__(
self, unnormalised_data: typing.Union[torch.Tensor, np.ndarray]
) -> None:
"""
The unnormalised tensor or array ... |
e1ee065feb11fdc1ab6b1f9ba7a5b6fba7471a1a829a9a2b5aa088a92d31ce92 | Python | 626 | 18 | """Phase 10 alert-delivery package.
Pure-function delivery for each ``destination_kind``:
- ``slack`` — POST a JSON body with ``text`` to a webhook URL.
- ``webhook`` — generic JSON POST.
- ``email`` — SMTP via ``smtplib``, configured per-server via
``PYCARET_SMTP_*`` env vars.
Best-effort by design: a destinati... |
587d887a392787065149ffc5e3ed1bc458f8187a51e28c876c3a490c70ff94ab | Python | 627 | 22 | """Numerical phantoms and datasets."""
from mrpro.phantoms.EllipsePhantom import EllipsePhantom
from mrpro.phantoms.b0map import random_b0map
from mrpro.phantoms.phantom_elements import EllipseParameters
from mrpro.phantoms import brainweb
from mrpro.phantoms.m4raw import M4RawDataset
from mrpro.phantoms import mdcnn
... |
93583c5dd10d57b90334a120c0946f29f5b0ff3947ec45533f8f12d7c218e3ef | Python | 627 | 26 | import numpy as np
import pandas as pd
import pandas._testing as tm
def test_pop():
# GH#6600
ser = pd.Series([0, 4, 0], index=["A", "B", "C"], name=4)
result = ser.pop("B")
assert result == 4
expected = pd.Series([0, 0], index=["A", "C"], name=4)
tm.assert_series_equal(ser, expected)
def... |
345cfc342fa7cc040f60866f9f131453c3a632ad24dcd142bfdb711f308990f8 | Python | 629 | 31 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.16.0
# kernelspec:
# display_name: ol-connectome
# language: python
# name: ol-connectome
# ---
# %%
from pathlib import Path
import sys
... |
53576b89df2aabafb72ead13ad2f1951b4466542910590ebd7a90ef1f5936729 | Python | 631 | 14 | MACS_VERSION = "3.1.0"
MAX_PAIRNUM = 1000
MAX_LAMBDA = 100000
FESTEP = 20
BUFFER_SIZE = 100000 # np array will increase at step of 1 million items
READ_BUFFER_SIZE = 10000000 # 10M bytes for read buffer size
N_MP = 2 # Number of processers
# Effective genome size, collected from
# https://d... |
857e3c060f7b3f9c0f5c9359c79ac8d51ab4ccfc59932965ad2bd20debae19c3 | Python | 631 | 25 | import sys
import configparser
sys.path.append(sys.argv[1])
from dtsr.formula import Formula
config = configparser.ConfigParser()
config.optionxform = str
config.readfp(sys.stdin)
cols = ['word', 'time', 'subject']
cols += config['data']['series_ids'].strip().split()
if 'split_ids' in config['data']:
cols += co... |
fae6610d9edb18f164b920120051df64cd6b8e59c6a181b4541538b013f7334e | Python | 631 | 19 | __all__ = [
'bin_log_data', 'derivation', 'dict_utils', 'extract_cosmo_data',
'get_mapgeo_terrain', 'interpolation', 'kwargs_handling', 'load_model',
'loiter_detection', 'rescale_tensor', 'terrain_factor', 'ulog_utils', 'yaml_tools',
]
from .bin_log_data import *
from .derivation import *
from .dict_ut... |
2268bbea35299cc4defafbf0c7358fe9fe00182ee149b588b99847df9b42d930 | Python | 632 | 22 | import setuptools
with open("README.md") as fh:
long_description = fh.read()
setuptools.setup(
name="roost",
version="0.0.2",
author="Rhys Goodall",
author_email="reag2@cam.ac.uk",
description="Representation Learning from Stoichiometry",
long_description=long_description,
long_descrip... |
72ad7d621b32bec9d78f0cd173fe4ca9b9c74aa737dc946fe990dd883fafb5e6 | Python | 633 | 15 | # MOFTransformer version 2.0.0
import os
from moftransformer import __root_dir__
DEFAULT_PRETRAIN_MODEL_PATH = os.path.join(
__root_dir__, "database/"
)
DEFAULT_MOFTRANSFORMER_PATH = os.path.join(__root_dir__, "database/moftransformer.ckpt")
DEFAULT_PMTRANSFORMER_PATH = os.path.join(__root_dir__, "databa... |
82f8a719e4c8df814496e82d4a9ea1de18b568daa4f994bec1bd23c6e6acfacb | Python | 635 | 18 | import pandas as pd
import pandas._testing as tm
from pandas.core.construction import extract_array
def test_extract_array_rangeindex():
ri = pd.Index(range(5))
expected = ri._values
res = extract_array(ri, extract_numpy=True, extract_range=True)
tm.assert_numpy_array_equal(res, expected)
res = e... |
60f86733c73b0bdae292b52e8efd14b76edf67bd32001069fe97428a4180380f | Python | 636 | 31 | """
Functions for defining unary operations.
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
)
from pandas.core.dtypes.generic import ABCExtensionArray
if TYPE_CHECKING:
from pandas._typing import ArrayLike
def should_extension_dispatch(left: ArrayLike, right: Any) -> b... |
3432a3e7256748121835307e5653c440fdeec56fa28803cb11491e2297a68893 | Python | 637 | 20 | import pandas as pd
import seaborn as sns
import numpy
mutationMap = pd.read_csv('mutations.tsv', sep='\t', low_memory=False, index_col=0)
simplifiedIndex = mutationMap.index.copy()
simplifiedIndex = [x.replace('MUT_MutAA[', '').replace(']','') for x in simplifiedIndex]
simplifiedIndex = [x.split('-')[1] + '-' + x.... |
7670ee0c8553668ae47ea8e4f08a3205c1dafff3923432d9d4e1cbc0a8882742 | Python | 637 | 20 | #!/opt/local/bin/python2.6
import sys
from Common import diffeo
import numpy as np
def main():
if not (len(sys.argv) == 5):
print 'Usage: computeMomentumFromLDDMM LDDMM_Template.vtk LDDMM_Deformed_Target.vtk LDDMM_map_Jacobian.vtk result.vtk'
sys.exit(0)
I0 = diffeo.gridScalars(fileName=sys.arg... |
7eaa2d4064df5287de29cbff9181f6d2ce842966d798167b32d955427f66f997 | Python | 637 | 29 | from abc import ABC
class MicroStructModel(ABC):
"""Microstructure model."""
def __init__(self, name):
"""Initialize the name of the microstructure model."""
self.name = name
def __str__(self):
"""Representation of the model."""
return self.name
@classmethod
def ... |
c3bcf85e4f972a752253c4eb9373e237bcec2dd434dad90b7be745cfc7da69cf | Python | 639 | 35 | PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def _colour(col):
return col + "{}" + ENDC
def green(s):
return _colour(GREEN).format(s)
def blue(s):
return _colour(BLUE).format(s)
def underline(s):
... |
cc7105340089ace7bf82ae8401b46fdfe7d0c1d4cc047c71e4c4e4ee53afae4a | Python | 639 | 25 | def get_groupby_method_args(name, obj):
"""
Get required arguments for a groupby method.
When parametrizing a test over groupby methods (e.g. "sum", "mean"),
it is often the case that arguments are required for certain methods.
Parameters
----------
name: str
Name of the method.
... |
ff1583955841592e18ca029c2d0875c06eadabd14a0af18078c91bb6f0c75047 | Python | 640 | 31 | import brian2 as b2
gL0 = 5e-5*b2.siemens/b2.cm**2
Cm = 0.5*b2.uF/b2.cm**2
Ri = 150*b2.ohm*b2.cm
gf0 = 2*gL0
gs0 = 4*gL0
EL0 = -60*b2.mV
Es = -80*b2.mV
Dn = 8.7*b2.mV
An = 12.0*b2.mV
Dm = 9.0*b2.mV
Am = -1.2*b2.mV
Ef = 120.0*b2.mV
phi = 1/(15*b2.ms)
eqs = '''
Im = gL * (EL-v) + gf*minf*(Ef-v)+gs*n*(Es-v) + Is: amp/me... |
aacc6463042acb3f079b11732408ccf90c1b8817ae423ade7a247e1e24bbf247 | Python | 642 | 16 | from datetime import datetime
import sys
sys.path.append("..")
from app import db
class SourceDatasetCondition(db.Model):
__tablename__ = 'source_dataset_condition'
id = db.Column(db.Integer, primary_key=True)
source_dataset_id = db.Column(db.Integer, db.ForeignKey('source_dataset.id'), index=True)
co... |
6f0cbd6c7783d1b4620b0ae96657235e9b2fc53dcd71cdc484b0f7a8f37817bb | Python | 643 | 34 | #
# posterity.py -- Michael Pun
#
# File for recording reproducibility metadata
#
import random
import sys
import git
import time
def get_metadata():
metadata = {}
# posterity info
# command line arguments
metadata['command_line'] = ' '.join(sys.argv)
# git hash
repo = git.Repo(search_parent... |
ccb68e94fee627e67e61ea344b703ac8efa14459d376b75476d3f2a93f6237bb | Python | 643 | 19 | import os
# import cloudpickle
import compatibility
from . import parent_classes
import model_data_base
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return obj is None #isinstance(obj, np) #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def ge... |
3526075e02d2d91b3d389b1363057cec7481de3d12a5273e048b292361b05b2b | Python | 644 | 21 | import pandas as pd
import sys
# pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
# interleave ITEM-5 and condition for sentid; HC MC LC
# position -> sentpos; SUM_3RT -> fdur
def main():
df = pd.read_csv(sys.argv[1])
df = df.rename(columns={"SUB": "subject", "critical_word":... |
c059eaa85905b538c76b5486e6a8a8c7b28380a85174e9e1edf8a4d995441453 | Python | 646 | 22 | from tests.conftest import MIC_PLATES_PATH, IMAGES_PATH, DRUG_NAME
from aigarmic._img_utils import get_image_paths, convert_cv2_to_keras
import pytest
from os import path
deep_path = path.join(MIC_PLATES_PATH, DRUG_NAME)
@pytest.mark.assets_required
def test_get_image_paths():
for i in get_image_paths(deep_path)... |
d46bc7dac03a20d23cf3c7b1ca95f31836a7d371001d06600a285fa405fa5de3 | Python | 646 | 23 | from __future__ import print_function # makes this work for python2 and 3
import vegas
import ffcn_f2py
import numpy as np
USE_BATCH = True
def main():
integ = vegas.Integrator(4 *[[0,1]])
if USE_BATCH:
batch_fcn = vegas.batchintegrand(ffcn_f2py.batch_fcn)
print(integ(batch_fcn, neval=1e5, ... |
f48b6c275ceb401a91fb2f3a606271e1b14ba60c39098e261d7d3ce4ad3c2cfd | Python | 646 | 16 | """Publish downloaded files only after their contents are complete."""
from contextlib import contextmanager
from pathlib import Path
from tempfile import TemporaryDirectory
@contextmanager
def atomic_output_path(destination):
"""Yield a temporary sibling path, then atomically replace the destination."""
des... |
513dea4ef9389efd347144defadc7ad1cfd52df403309e86018e5a7586db3dec | Python | 647 | 20 | import pandas as pd
import numpy as np
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy.sparse import csr_matrix
def immupute_dis(data, data_pca, k):
sim = squareform(pdist(data_pca))
sim = np.max(sim) - sim
KK = np.sum(sim, axis=0)
twom = np.sum(KK)
sim_norm = sim... |
287eb9c47d4f1ed41727e0c90e449d9e82d93ed8cad03998ea0d7fd4dc6e5c19 | Python | 649 | 27 | import os
import re
import sys
import csv
import warnings
import tempfile
import json
import queue
import argparse
import torch
import tifffile
import copy
import shutil
import logging
import SimpleITK as sitk
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.opt... |
0329d4462d15257f1a6a87d45af20e9f39986b615512761dff631fa4198b49fa | Python | 650 | 31 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 16:30:29 2019
@author: vman
"""
import numpy as np
import pickle
import fnmatch
def save_obj(obj, name ):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open(name,... |
71c1f8d02ddbfc1079942bd2f65e0da7cc55ab6310983fcac51160207fa1a1ae | Python | 650 | 22 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sequence-models",
version="1.8.0",
author="Kevin Yang",
author_email="yang.kevin@microsoft.com",
description="Machine learning for sequences.",
long_description=long_description,
l... |
407b57f4b103030d7472fe4dd553dec2802fa70a60d7b4c01a1b304f80b98bdb | Python | 651 | 23 | import sys
model = {}
print('word unigramsurp')
with open(sys.argv[1],'r') as f:
for line in f:
if len(line) > 0 and line[0] == '-':
##only load lines that begin with logprobs
sline = line[:-1].split('\t')
if len(sline) > 1: model[sline[1]] = float(sline[0])
with open(sys.argv[2],'r') as f:
... |
4636110874b6e434093ae87bd28f24ac9e1ec33afafe67d079712c722ddcc80b | Python | 651 | 17 | """
This module contains all files required by the pykilosort GUI.
"""
from .data_view_box import DataViewBox
from .header_box import HeaderBox
from .message_log_box import MessageLogBox
from .minor_gui_elements import ProbeBuilder, controls_popup_text, help_popup_text
from .palettes import COLORMAP_COLORS, DarkPalette... |
561e9a3ddbe2c8b7f0065dc10e4f6420e6955aa007f0e23a67d8418a929ac19e | Python | 651 | 19 | import pytest
import pandas as pd
class TestGetValue:
def test_get_set_value_no_partial_indexing(self):
# partial w/ MultiIndex raise exception
index = pd.MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)])
df = pd.DataFrame(index=index, columns=range(4))
with pytest.raises(K... |
b6d276aa0e4c03a95f6664886ca587dcf5d722e38750f645a0e22ab859605dbf | Python | 651 | 23 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
blockify.py: make sure input and output FDs are in blocking mode before running a command.
"""
import os
import sys
import fcntl
# Check input
if len(sys.argv) < 2:
raise RuntimeError("A program to execute is required")
# Fix up standard file descriptors (0, 1, 2) ... |
19d4bc02c16f1fcaf0a5e4c9163c65f7485cf127e5fda1d236b188bef65175c2 | Python | 652 | 23 | import setuptools
import os
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name='protein_holography',
version='0.0',
author='Michael Pun',
author_email='mpun@uw.edu',
description='learning protein neighborhoods by incorporating rotational symmetry',
long_de... |
bff87162f4a961fd6934ed84a2e0d336010a48ff8f08824b5394ebd37fb48766 | Python | 652 | 26 |
import glob
import random
from skimage import transform, util
from skimage import io as skio
import cine
import tube2
names = glob.glob("data2/**/*.cine", recursive=True)
for i, name in enumerate(names):
video = cine.Cine(name)
for j in range(10):
idx = random.randint(0, video.image_count - 1)
... |
2ff6855e41fad5aeb4a784cc8e44b9b42eaf64421709bd0ab1c8be30144c2f5e | Python | 654 | 18 | import pandas as pd
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from app import create_app, db
from app.models import Subject, SourceDataset
from config.globals import ENVIRONMENT
... |
499cd39476759c05474b620d9ad6eb601d7143da22aa6dbde334d18c5238f28a | Python | 655 | 25 | from setuptools import setup, find_packages
setup(
name='spit',
version='2.1.2',
description='Comprehensive Python package for detecting differential transcript usage (DTU) in RNA-seq data.',
packages=find_packages(),
include_package_data=True,
install_requires=[
'matplotlib>=3.4.3',
... |
0e8ccbb74b7a89ae94f3fa46db1da9365396363ad8fde7a02d46eee76309d75a | Python | 656 | 27 | from time import time
from psychopy import parallel
import time
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()
... |
16a8c8387ec83bf1c5aaac8394d89ec5dd01e8d9767a0773e1d5913554e2a99c | Python | 656 | 24 | __all__ = ["AttentionSum"]
import torch
class AttentionSum(torch.nn.Module):
def __init__(self, gate_nn, feat_nn=None):
super().__init__()
self.gate_nn = gate_nn
self.feat_nn = feat_nn
def forward(self, feat, get_attention=False):
gate = self.gate_nn(feat)
assert gate... |
3a8746926d3dccc53b596559fb501ccc88539ff7bad9834344efaa22d40a587a | Python | 656 | 32 | #Run sweeps over number of fields
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
N0 = 500 # number of cells
percell= 1.0 # probability that each field is accepted
phi=1.0 # multiply by this constant to adjust overall activity ... |
a414be4feacd97ee3cbe8aedb80dfc3af6bb6b701506ce717da30ec36a6fa5f4 | Python | 656 | 20 | import torch
from torch_geometric.transforms import BaseTransform
class DownselectEdges(BaseTransform):
"""Given a particle data with a set of edges/bonds,
downselect the edges that are shorter than the specified cutoff.
"""
def __init__(self, cutoff, cell=None):
self.cutoff = cutoff
... |
c375e40f453e311f7f783b2139afa3c7ae51d8969d1dc088985258fc11d7e425 | Python | 656 | 15 | import os
cts_outfile = snakemake.output[0]
prefix__annotations = snakemake.params['prefix__annotations']
chromosome = snakemake.params['chromosome']
file_ldscore = snakemake.input[0] # e.g. <SOMEPATH>/nn_lira_sema.yellow.22.l2.ldscore.gz | output files from make_annot_from_geneset_all_chr.py follow the pattern <PRE... |
349d4b1961e2ca5dd0caabad58250de57390815e89dd55aee708c7779a252adb | Python | 657 | 26 | #!/usr/bin/env python
from setuptools import setup
from setuptools import find_packages
setup(
name='cdrnn',
python_requires='>=3',
version='0.8.5',
description='A toolkit for continuous-time deconvolutional regression (CDR)',
author='Cory Shain',
author_email='cory.shain@gmail.com',
url='h... |
75f249ca5fb696f7eaeb4f1aab08fea9a8b8cfc7753f3f66d8b855028997e5cc | Python | 658 | 21 | import os
# import cloudpickle
import compatibility
import numpy as np
from . import parent_classes
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return isinstance(obj, np) #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def get(self, savedir):... |
1d9ab784d016fef65421946a448466d83b7bc5200297fbdc052ea5071da1f549 | Python | 660 | 14 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... |
5f6f10eb2a09905583be4ce3853d6e8eb8c0cee3e81961cd0a2ae19a268399f3 | Python | 660 | 21 | import torch.nn as nn
import darts.functional as F
from darts.api.metrics.average import MultitaskAveragingSupervisedMetric
class MultitaskLoss(MultitaskAveragingSupervisedMetric):
""" Multitask Classification loss """
def __init__(self, scope="train", criterion=nn.CrossEntropyLoss()):
super().__ini... |
13b1e20b5f35c5bb2fcc3fa33cc3bcb94a7c1f7a3d64e66e7d2e4d6b5736a787 | Python | 661 | 18 | # %%
import urllib.request
from pathlib import Path
to_download = [
"https://zenodo.org/record/7716839/files/ixi.S4_R4.csv?download=1",
"https://zenodo.org/record/7716839/files/ixi.S4_R8.csv?download=1",
"https://zenodo.org/record/7716839/files/ixi.S8_R4.csv?download=1",
"https://zenodo.org/record/7716... |
a17aad851e97a6922d89ff50c270c3e5a2ef9c624a8a248c390e44b8c8203a8f | Python | 661 | 18 | from pathlib import Path
from global_config import config as global_config
config = global_config.copy()
config.update({
'worker_pool_job_timeout': 1080,
'max_serann_per_gpu': 112,
'encodings_dataset_path': str(Path(global_config['encodings_datasets_dir'],
'generate... |
aa82f91e15b520ecff561ca7b59770bccf8c93687a71e4a374e33af3666af89a | Python | 661 | 25 | """
Tests for Timestamp timezone-related methods
"""
from datetime import datetime
from pandas._libs.tslibs import timezones
import pandas as pd
class TestTimestampTZOperations:
# ------------------------------------------------------------------
def test_timestamp_timetz_equivalent_with_datetime_tz(self,... |
36c1f184e99efca239a0c5d5bf44e6b598416e623690e85c1430cfe512134f06 | Python | 662 | 21 | """Phase 5 Git integration package.
Exports YAML for Experiment / Trial / Run and pushes to a repo via
``git`` over HTTPS with a PAT.
Layout:
- ``exporter`` — pure function ``serialise_*`` that turns an ORM row
into the wire YAML shape. No I/O, no Git, no DB writes.
- ``service`` — high-level "publish project to r... |
437e17a9fc6e9fd59f5273d5ef470e6cddce41515496257c487d004d4c267e68 | Python | 662 | 21 | # %%
import os
os.chdir("..")
print(os.getcwd())
# %%
from deepglyco.chem.common.elements import ElementCollection
from deepglyco.chem.pep.aminoacids import AminoAcidCollection
from deepglyco.chem.pep.mods import ModificationCollection
from deepglyco.speclib.pep.parser import MaxQuantReportParser
from deepglyco.util.... |
8ecc9382d92738f4e923f997ff94694d6a45e8de5a902d170649e67a9bc48b87 | Python | 664 | 29 | import mojimoji
import pandas as pd
def zen2han(text: str) -> str:
return mojimoji.zen_to_han(text, kana=False)
def normal_bracket2ptb_bracket(text: str) -> str:
return text.replace("(", "-LRB-").replace(")", "-RRB-")
def filter_bccwj_eyetrack(unit: str, bccwj_eyetrack: pd.DataFrame) -> pd.DataFrame:
... |
c6bfd24eb9d5dd761d0008983dc9fa05bad439649684d86df66772199635cf0f | Python | 666 | 21 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
d8c1dc0e92d18ab8faa9f24786313d248a26a382e0eec7eeb0ac3efda3f2b177 | Python | 666 | 23 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
599321ed6faf545ec92c5deee98306ee5c4c73efd16ee31bab694e7eddb011e0 | Python | 667 | 25 | __all__ = ["list_files"]
import os
import re
import itertools
def list_files(path=".", pattern=None, recursive=False, include_dirs=False):
if recursive:
return list(
itertools.chain.from_iterable(
[
os.path.join(t[0], x)
for x in (t[1] +... |
20e5f2dfc5aa37b82de286c33aa8e706b850c97dba48f1768ec77ac00568c60e | Python | 668 | 19 | import torch.nn as nn
from tnn.layers import LinearLayer
class FullyConnected(nn.Sequential):
def __init__(self, layer_widths, activation=None, bias=True, device=None, dtype=None):
factory_kwargs = {'device': device, 'dtype': dtype}
super(FullyConnected, self).__init__()
self.depth = len... |
9f6c3f0db9d1d2059b1ae4530a4496b90f9ec79ab12dab7a2b184bf73034956b | Python | 670 | 19 | from dataknead import Knead
# Print single sheet Excel
Knead("input/cities.xlsx").write("output/cities-excel.csv")
# Print multisheet Excel
Knead("input/cities-multisheet.xlsx").write("output/cities-multisheet-excel.json", indent = 4)
# Print multisheet Excel and use the header for dict keys
Knead("input/cities-mult... |
1218ebf418b219b65c9dc56bac4ee6c2ca6582768571b7ef9e311029e637307a | Python | 671 | 37 | """
All of pandas' ExtensionArrays.
See :ref:`extending.extension-types` for more.
"""
from pandas.core.arrays import (
ArrowExtensionArray,
ArrowStringArray,
BooleanArray,
Categorical,
DatetimeArray,
FloatingArray,
IntegerArray,
IntervalArray,
NumpyExtensionArray,
PeriodArray,... |
f03164d50e3c409e3196c0460181d85243a2ce0517b830d6fd047ede5c67c2e0 | Python | 671 | 21 | import sqlalchemy as db
import pandas as pd
import os
from app import create_app
from config.globals import ENVIRONMENT
# Set up connection to DB
current_app = create_app(os.environ.get('FLASK_CONFIG', ENVIRONMENT))
engine = db.create_engine(current_app.config['SQLALCHEMY_DATABASE_URI'])
# Execute alter command to u... |
9e542897454621aa48adbaa7da55d94ee4343a2e1d9f5db710085e305998620b | Python | 672 | 26 | from typing import Dict
import torch.nn as nn
class MultitaskClassifier(nn.Module):
def __init__(self, input_dim: int, tasks: Dict[str, int]):
super(MultitaskClassifier, self).__init__()
self.tasks = tasks
for task, num_classes in tasks.items():
self.add_module(
... |
ff1bbdbacfe74ba660096cd1fcc8625ad588aab716f0b2925653673d9472e71a | Python | 672 | 24 | from __future__ import print_function, division
import numpy as np
import tables
from combinato import NcsFile
from signalviewer import expandts
Q = 16
def main(fname):
fid = NcsFile(fname)
nrec = fid.num_recs
# out_size = (nrec + 1) * 512/Q
times = fid.read(0, fid.num_recs, mode='timestamp')
times... |
a6cf6d3d699dc8e9a1e785d886cb7668b353268bc3135a5a2f1dbdcf2761ebea | Python | 673 | 17 | # Copyright 2026 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
b160c0fc3733cd3fb5c04044e177f9c112f6b41eddd912ad6db1ebc02359c9e3 | Python | 673 | 27 | __all__ = [
"Interval",
"NaT",
"NaTType",
"OutOfBoundsDatetime",
"Period",
"Timedelta",
"Timestamp",
"iNaT",
]
# Below imports needs to happen first to ensure pandas top level
# module gets monkeypatched with the pandas_datetime_CAPI
# see pandas_datetime_exec in pd_datetime.c
import p... |
6037ac0382dc975872be6423669cb82f595d45e4b289c51a523cfcf6221b50be | Python | 677 | 24 | import numpy as np
import pytest
import pandas as pd
# Note: identical the "multi" entry in the top-level "index" fixture
@pytest.fixture
def idx():
# a MultiIndex used to test the general functionality of the
# general functionality of this object
major_axis = pd.Index(["foo", "bar", "baz", "qux"])
... |
8c8c14da2051a2e31a4f306edef88937f18f40d01232a2ead118d5428bdcba6f | Python | 677 | 31 | # -*- coding: utf-8 -*-
import pytest
from emcee import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = [
"test_normal_stretch",
"test_uniform_stretch",
"test_nsplits_stretch",
]
@pytest.mark.parametrize("blobs", [True, False])
def test_normal_stretch(blobs, **kwargs):
kwarg... |
4532f9d1fea1192f13dec4d85479929c38adab2a152227276bc0b2565f4b41b3 | Python | 678 | 24 | import sys
import math
from wordfreq import word_frequency
print("word unigramsurp")
lang_dict = {"du": "nl",
"ge": "de",
"gr": "el",
"no": "nb",
"sp": "es"}
lang = sys.argv[1]
if lang in lang_dict:
lang = lang_dict[lang]
with open(sys.argv[2], "r") as f:
... |
5a86b77e7280a335e38f3559c253171e1ac0e6c05ac1387415b5027676fdd1e2 | Python | 678 | 25 | from abc import ABC, abstractmethod
from dataclasses import dataclass
import gadgetron
@dataclass
class Parser(ABC):
"""
This base class is responsible for parsing basic information
from the acquisition. DO NOT ALTER THE INFORMATION IN THIS
BASE CLASS - ALTER IN STRUCTMAKER CLASSES (e.g., ... |
662ca011a9a3d12b7e1cca38c807980a00866f6932335c848a305e54033fbe20 | Python | 678 | 27 | #!/bin/bash
import sys
import random
def random_sampler(fn, k):
"""
See http://metadatascience.com/2014/02/27/random-sampling-from-very-large-files/
"""
sample = []
k = int(k)
random.seed(100)
with open(fn, 'rb') as f:
f.seek(0, 2)
filesize = f.tell()
random_set = sorted(random.s... |
3b0ec78faa97460f739091c237de0ba385f4ac07d0e4a4d6fcf3f0f78805e139 | Python | 680 | 29 | import torch
import torch.distributions as dist
def d_kl_discrete(p, q):
# p = target, q = online
# categorical distribution parametrized by logits
logits_diff = p - q
p_probs = torch.exp(p)
d_kl = (p_probs * logits_diff).sum(-1)
return d_kl
def d_kl_discrete_list(p, q):
d_kl = 0
fo... |
5e235bf7bc56afb5241d4ec814b94285b2a16c5edd270e7a284912e5a2ba3550 | Python | 680 | 16 | # -*- coding: utf-8 -*-
import numpy as np
from utils import format_filename
from config import PROCESSED_DATA_DIR, TRAIN_DATA_TEMPLATE, DEV_DATA_TEMPLATE, TEST_DATA_TEMPLATE
def load_data(dataset: str, data_type: str):
if data_type == 'train':
return np.load(format_filename(PROCESSED_DATA_DIR, TRAIN_DAT... |
35cd30d116e07e545eb15968966d52a4a394c84891e5951ec6d3814a445a95a6 | Python | 681 | 15 | # flake8: noqa: F401
from .bg_thread import run_async
from .double_spin_box_nan import DoubleSpinBoxNan
from .feature_combobox import FeatureComboBox
from .get_path import get_directory
from .key_value_table_widget import KeyValueTableWidget
from .mdi_subwindow_wo_close import MDISubWindowWOButtons
from .qrangeslider i... |
a9bbfdde85c809e9393eff3c2a33135e5d6e73642d29594988e61053f367543d | Python | 681 | 31 | from __future__ import absolute_import, division
import numpy as np
def spikeDist(a, b):
d = np.sqrt( ( (a - b)**2 ).sum() )
f = min(a.max(), b.max())
return d/f
def correlation(times1, times2, up_to_lag, auto_corr=False):
"""
calculate the correlation in a loop
"""
l1 = len(times1)
... |
d6b392933f6671734b45dad793ec033d3c9ac1214b8260ad383bab46038607ca | Python | 681 | 19 | # Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
765c976f649a11d7200b1837d64a28d8846f9f468d86688c2ecd8bc3711dda11 | Python | 683 | 26 | from setuptools import setup, find_packages
dependencies =[
'seaborn',
'statsmodels',
'scipy',
'patsy',
'matplotlib',
'pandas',
'numpy'
]
VERSION = "0.1.3"
setup(
name = 'pymatch',
packages = ['pymatch'],
version = VERSION,
description = 'Matching techniques for Observational Studies',
auth... |
2f575fa088f7c1a6f38ecf6ee03894182e15f75602c7ac56cf352b17d5fd2fe6 | Python | 684 | 27 | import pytest
import pandas as pd
import pandas._testing as tm
class TestGet:
def test_get(self, float_frame):
b = float_frame.get("B")
tm.assert_series_equal(b, float_frame["B"])
assert float_frame.get("foo") is None
tm.assert_series_equal(
float_frame.get("foo", flo... |
f79274a92a6c8b1cb9ea7e40b1c0eec9129efcfaf85e7c3a503ed9097503eee6 | Python | 684 | 28 | """support numpy compatibility across versions"""
import numpy as np
from pandas.util.version import Version
# numpy versioning
_np_version = np.__version__
_nlv = Version(_np_version)
np_version_gt2_2 = _nlv >= Version("2.2.0")
np_version_gt2_3 = _nlv >= Version("2.3.0")
np_version_gt2_5 = _nlv >= Version("2.5.0")
... |
3c16f026c152508cf4b6c2bdd6a09155bfdf24b917e9707652335fc8a3efa074 | Python | 685 | 33 | """
Public API for extending pandas objects.
"""
from pandas._libs.lib import no_default
from pandas.core.dtypes.base import (
ExtensionDtype,
register_extension_dtype,
)
from pandas.core.accessor import (
register_dataframe_accessor,
register_index_accessor,
register_series_accessor,
)
from pand... |
14024afe124c32fc5d4d7114e3085220eba61495fe6182f0af4dfe7fcfaf1368 | Python | 686 | 20 | """PyCaret 4.0 pytest conftest.
The 3.x conftest wired up fixtures that depended on the module-level
functional API (`pycaret.*.functional._CURRENT_EXPERIMENT`). That API is
removed in 4.0 — experiments are OOP-only and stateless at the module level,
so no between-test reset is needed.
Remaining fixtures are minimal:... |
77ce06acfcc7189bd5a40f328ff5ac884c0741175e7b77055730798744856d18 | Python | 687 | 19 | import os
# import cloudpickle
import compatibility
import numpy as np
from . import parent_classes
def check(obj):
'''checks wherther obj can be saved with this dumper'''
return isinstance(obj, np) #basically everything can be saved with pickle
class Loader(parent_classes.Loader):
def get(self, savedir):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.