sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
da09c77850b77ced6a00a7725332a427e0fd88d1c55a08859465736161fa79e7
Python
2,051
59
import os from create_embeddings import create_graphs import os from statistics import mean import pandas as pd from math import log2 from statistics import mean import numpy as np import networkx as nx import matplotlib.pyplot as plt from scipy.stats import pearsonr from IPython.display import display from networkx.dr...
4c066557a25964ff61512a154cb4ea90decaf2a899527f59b959d003f27e27ba
Python
2,053
79
from rdkit import Chem from rdkit.Chem.SaltRemover import SaltRemover from rdkit.Chem.MolStandardize import rdMolStandardize from rdkit import RDLogger from rules import ATOMIC_NUMBER, METALS_LIST lg = RDLogger.logger() lg.setLevel(RDLogger.CRITICAL) def remove_metals(mol): mol = Chem.RWMol(mol) ...
f3489f71606c5e80adcf3fb4d5628636a16d4afefac2bcdb036af4264b80e0dd
Python
2,053
85
""" Demonstration on the correctness and efficiency of parameter shift gradient implementation """ import numpy as np import tensorcircuit as tc from tensorcircuit import experimental as E K = tc.set_backend("tensorflow") n = 6 m = 3 def f1(param): c = tc.Circuit(n) for j in range(m): for i in ra...
002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7
Python
2,059
77
import numpy as np import pytest from pandas import ( NA, Categorical, Series, ) import pandas._testing as tm @pytest.mark.parametrize( "keep, expected", [ ("first", Series([False, False, True, False, True], name="name")), ("last", Series([True, True, False, False, False], name="n...
39b6d2517538476a566a31ffff101d8b3003ad4da404a0c30b190357ea150577
Python
2,059
93
""" Test functions for linalg module using the matrix class.""" import numpy as np from numpy.linalg.tests.test_linalg import ( LinalgCase, apply_tag, TestQR as _TestQR, LinalgTestCase, _TestNorm2D, _TestNormDoubleBase, _TestNormSingleBase, _TestNormInt64Base, SolveCases, InvCases, EigvalsCases, EigCases, ...
2c2ce445441bdf6fa81a8cec6c0046e027032b3a4140338b7c66c0435ce2a871
Python
2,060
69
"""contains code for the generation of distances between all records in a given dataset""" # from python import logging # from dependencies import tqdm # from other modules import big_scape.data as bs_data import big_scape.genbank as bs_gbk import big_scape.comparison as bs_comparison def calculate_distances_mix( ...
113e0bc8d108df69e0536b8856a47d6f6fcffefc71efafb904fc99a0d762f2c4
Python
2,061
62
import re from pathlib import Path from typing import List, Optional, Tuple, Union import numpy as np from readimc import TXTFile from ..io.base import FileReaderBase, ImageDimensions from ..models import IMCFileAcquisitionModel, IMCFileModel, IMCFilePanoramaModel class TxtFileReader(FileReaderBase): def __init...
69f8b8075af5ba7783a5c93e14dd1a2bde3a3467cd94941fef5f5c8d406ce3c7
Python
2,061
46
""" Code for creating a multiagent environment with one of the scenarios listed in ./scenarios/. Can be called by using, for example: env = make_env('simple_speaker_listener') After producing the env object, can be used similarly to an OpenAI gym environment. A policy using this environment must output actions in ...
6ea6a6fc9745a3d6d63c822096dd11be6b3e289c46d70679ce74edac09f979a2
Python
2,063
70
import pytest from pandas import ( Index, Series, date_range, ) import pandas._testing as tm class TestSeriesDelItem: def test_delitem(self): # GH#5542 # should delete the item inplace s = Series(range(5)) del s[0] expected = Series(range(1, 5), index=range(1,...
13bb24e8ed0135c3c03b78bcfa9434519e35cb9646258c3936849917a469a4bc
Python
2,064
59
# 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. """ Signature related helpers """ from typing import List from .path import get_full_path class Signature: """Secondary metabolite signature""" def __init__(se...
a0b82d0c4cf4a16b17319ea8a1b139d8e46df2c5cbea59b771d435a2fa6435b1
Python
2,066
67
# -*- coding: utf-8 -*- # @Author : DevinYang(pistonyang@gmail.com) # This file defind the HybridTransform to handle complex objects. import abc from PIL import Image from torch import nn from torchvision.transforms import Compose from torchvision.transforms import functional as pil_functional from . import function...
1eb0a795c3add1d68996ce4e17d7fa33a62237f96340bdf6296fb1487762927b
Python
2,069
59
#!/usr/bin/python import sys import os import commands import time import csv def is_number(s): try: int(s) return True except ValueError: return False if len(sys.argv) != 8: print 'Incorrect number of arguments:', len(sys.argv) print 'Usage:', sys.argv[0], '<tf_name> <encoded_...
8b0779dc40ec1ab8a37d2f47bf11cd41db570655f304fe98c30d18aee655c585
Python
2,070
71
import logging import time import cv2 import numpy as np from app.recording.camera_recorder.source.base_source import CameraSource from util.trace import Trace logger = logging.getLogger("grimace_box."+__name__) class FileCameraSource(CameraSource): @Trace.trace(logger) def __init__(self, video_file: str):...
0beaf0353bf916d52fa37a1607c5cdaae08e6bf5d01dfe91f494585fa255006d
Python
2,071
65
import numpy as np import pytest import pandas as pd import pandas._testing as tm from pandas.core.arrays import FloatingArray from pandas.tests.arrays.masked_shared import ( ComparisonOps, NumericOps, ) class TestComparisonOps(NumericOps, ComparisonOps): @pytest.mark.parametrize("other", [True, False, p...
a13ade26a76e2bda6e49921544958ccfa439e30bf1a66b41363ae0a0d281b137
Python
2,071
58
import pytest import numpy as np from yass import geometry from yass.geometry import (parse, find_channel_neighbors, n_steps_neigh_channels) from yass.threshold import detect def test_can_load_npy(path_to_npy_geometry): geom = geometry.parse(path_to_npy_geometry, n_channels=10) asse...
054d42db5e37f47468ef21f54ac37d99ee960833e93b0450dfb6693700cca82c
Python
2,074
64
""" An enhanced distutils, providing support for Fortran compilers, for BLAS, LAPACK and other common libraries for numerical computing, and more. Public submodules are:: misc_util system_info cpu_info log exec_command For details, please see the *Packaging* and *NumPy Distutils User Guide* secti...
abb2ad970e29d15f4d167ed87bed01d8727c112badebd3712a833f3991510690
Python
2,074
57
import pickle from pathlib import Path import zipfile import tempfile import cv2 from multiprocessing import Pool from tqdm import tqdm from crystal_tracer.algorithm.detection import frame_detection flood_folder = Path('../../data/case1/flood') flood_folder.mkdir(exist_ok=True) detection_folder = Path('../../data/cas...
ef21d5a7c747797348dd5a00c8d4d4d91864965f08eb0a249d95b6313e8e0e13
Python
2,074
65
import torch import torch.nn as nn from torch.nn import TransformerEncoderLayer from omegaconf import DictConfig from .base import BaseModel class GraphTransformer(BaseModel): def __init__(self, cfg: DictConfig): super().__init__() self.attention_list = nn.ModuleList() self.readout = cf...
87028867c85110b2660ba9d23b70e6c1ef3dc187e62dac36d833e39c8ee9e2b5
Python
2,075
62
import pytest import torch from nablaDFT import model_registry from schnetpack.data.loader import AtomsLoader from torch_geometric.data import Batch from tests.decorators import withCUDA @withCUDA @pytest.mark.model @pytest.mark.parametrize( "model_name", [ "DimeNet++", "Equiformer-v2", ...
cfd5755227bdf87e72c0acc27585f8171bef3aad72ec8de41befdf3696ec3574
Python
2,077
73
# ||AUM|| import scipy.io as spio import scipy as sp import numpy as np from fmri_methods_sipi import rot_sub_data from surfproc import view_patch_vtk, patch_color_attrib from dfsio import readdfs import os import glob from brainsync import normalizeData, brainSync from sklearn.manifold import MDS import matplotlib.pyp...
ffe1546257ef5dd94b63f36665af8cc275d6acbfb9b9df8200156ee333fefaea
Python
2,078
55
#!/usr/bin/env python # -*- coding: utf-8 -*- from rna3db.utils import read_json, to_case_insensitive from rna3db.parser import parse_file from pathlib import Path from tqdm import tqdm import argparse def main(args): data = read_json(args.input_json_path) num_chains = sum( len(i.keys()) for s in dat...
b4456abc7e39104d74647a09cab20fa0932148a6017cda2a538d71628adfadbe
Python
2,079
57
import numpy as np import csv # sklearn does things differently and pylint doesn't like that # pylint: disable=no-name-in-module from sklearn.model_selection import train_test_split # pylint: enable=no-name-in-module # CONFIGURATION OPTIONS ''' change these as desired ''' csv_filename = 'full_set.csv' # the ...
35ebf3a3bfa0bcc8394af2f7460eba6ff5327d517a89fc3fa81f43e88327f020
Python
2,080
84
# -*- coding: utf-8 -*- """ Script for randomly separate all the auditory stim of this protocol into 4 sets of 72 stimuli, with 12 of each category per set author: Juan Jesus Torre Tresols e-mail: juan-jesus.torre-tresols@inria.fr """ import os from random import shuffle import shutil # %% PARAMETERS ...
c3df007de9ee994b37c4fa0eaf2fa0a86529564e05a217bf45afc3bd95824fcd
Python
2,083
121
# Copyright (C) 2012-2014,2016-2018 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Utility module defining global default channel sets """ import collections # This is for finding EEG channels given a generic name such as 'C3' # Note that the order is significant: The f...
accbddd0add6ecddb8aa7ed0fed4e4bdbcfb74e7a622fdf0f3d86d85ce9ce58d
Python
2,084
68
from datetime import timezone import numpy as np import pytest from pandas import ( DataFrame, Series, date_range, ) import pandas._testing as tm class TestTZLocalize: # See also: # test_tz_convert_and_localize in test_tz_convert def test_tz_localize(self, frame_or_series): rng = da...
507d701dc607d84c05b27994b8abef26a0b52b1fef40cfbc9d1b24b6a6d2e605
Python
2,085
83
# !/usr/bin/python # -*- Mode: Python; tab-width: 4; py-indent-offset: 4; -*- # # An OpenGL movie class with buffer (buffermovie.py) # # 01-09-2009: sn # A movie class with buffer # import sys from string import * import pygame from pygame.locals import * class buffermovie: """ A class to load and store movie (...
c69f11cd08272d3f163c0388e351d6e2b06fd735aa14d8b7d94f0ea905bacd36
Python
2,089
61
from rdkit import Chem, DataStructs from rdkit.Chem import AllChem import numpy as np import os class Molecule(object): def __init__(self, sid, smiles): self.sid = sid self.smiles = smiles mol = Chem.MolFromSmiles(smiles) if any(a.GetSymbol() in ('B', 'Si') for a in mol.GetAtoms()):...
302ae2df8eaaa356d8c23966df6c47472465f9b00835395f548b9b37a1c3cfaf
Python
2,090
71
import sys from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from sys import platform from os.path...
96eb6f42dd99f0f956b127e57e93d87b4c9dd6fea42e7d4626e56236f256a545
Python
2,090
41
# 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 antismash.common.sec...
2331e8a9d1a63fb0cccb274f74c42a24b00028be604459e2660977d0ab7bd97a
Python
2,091
51
# -*- coding: utf-8 -*- import numpy as np def select_probetype(nsentence_cond, cond_names, dataframe, word_present, word_absent): """ Selection of type of probe, i.e., word_present or word_absent The probe scattering is the following: b = 0, 2, 4: for #nb_sentence_cond = [0;nb_s...
d2f824db6504803f482460807cc2aed536e4fb6197359c1e24cfd27926e3405e
Python
2,091
68
from __future__ import annotations import argparse # noqa: TC003 import logging from cli.lib.common.cli_helper import register_targets, RichHelp, TargetSpec from cli.lib.core.torchtitan.torchtitan_test import TorchtitanTestRunner from cli.lib.core.vllm.vllm_test import VllmTestRunner logger = logging.getLogger(__n...
646196ab76e4564d8f6cd4443a897689b071d3a3e50c3b85c3652ab880053e3f
Python
2,092
71
# ||AUM|| import scipy.io as spio import scipy as sp import numpy as np from fmri_methods_sipi import rot_sub_data from surfproc import view_patch_vtk, patch_color_attrib from dfsio import readdfs import os import glob from brainsync import normalizeData, brainSync from sklearn.manifold import MDS import matplotlib.pyp...
afc4cd685dd66d4be77b8a0951796be4093c3c53c5cf249e5dc3f4f63eda61c2
Python
2,092
65
"""Created on Wed Mar 2 17:26:43 2022. @author: dpm42 """ import json import os import numpy as np def get_activation( filepath, delta_V: float = 60, rounding_precision: int = 5, plot: bool = False, plot_nodes_on_find: bool = False, plot_compiled: bool = False, absolu...
b66304a3e2a30eebb1a47cdb66e1b52fbc76375f504f5a0d53c5dfd8f97f7581
Python
2,092
74
from __future__ import annotations import click import numpy as np from .. import set_log_level from ..tasks import asynchronous as asynchronous_task from ..tasks import baseline as baseline_task from ..tasks import isochronous as isochronous_task from ..tasks import synchronous as synchronous_task from ..tasks._conf...
3ac6dabe62d1c4a34d6d5f129cf11cde654d93d10856332165e46cf67094b135
Python
2,093
40
""" Create the numpy._core.umath namespace for backward compatibility. In v1.16 the multiarray and umath c-extension modules were merged into a single _multiarray_umath extension module. So we replicate the old namespace by importing from the extension module. """ import numpy from . import _multiarray_umath from ._m...
5f8917169228c9f732995d0e4498a6e18fa470ebdb6ad7806b0b4bcff947e652
Python
2,093
68
from ase.calculators.calculator import Calculator from Calculators.device_strategy import DeviceStrategy from Calculators.bonded import DLBondedCalculator from Calculators.combiner import DipeptideCombiner from Calculators.nonbonded import MMNonBondedCalculator from Calculators.pme import PMENonBondedCalculator from u...
d2b36d96b7a43b0472899d29bd63d07066f58a959ccb848e22374f90949b4b38
Python
2,093
41
# 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 antismash.common.sec...
85ad4755176c4427f121f7ab33115cf3156530bac941103f9c85b132631b45d9
Python
2,094
73
import sys sys.path.append('.') from plotting.utils import load_results, mesh_name, sim_name, m3topl import matplotlib.pyplot as plt import seaborn as sns import numpy as np import yaml import pandas as pd import matplotlib.gridspec as gridspec sns.set_theme() sns.set_style(style='ticks') m32fl = 1e18 m2nm = 1e9 m2...
61bd0739179cff070457744d354e116679404d84d442d8c01cc6262f8a6f34bb
Python
2,096
55
from numpy._core import _multiarray_umath from numpy import ufunc for item in _multiarray_umath.__dir__(): # ufuncs appear in pickles with a path in numpy.core._multiarray_umath # and so must import from this namespace without warning or error attr = getattr(_multiarray_umath, item) if isinstance(attr,...
a99a2b00f23fa16733e5674112bd2742e4ff9ab0294e04a1aa0dc9565ce954a5
Python
2,096
77
from datetime import ( datetime, timedelta, ) from pandas import ( DatetimeIndex, NaT, Timestamp, ) import pandas._testing as tm def test_unique(tz_naive_fixture): idx = DatetimeIndex(["2017"] * 2, tz=tz_naive_fixture) expected = idx[:1] result = idx.unique() tm.assert_index_equa...
e81887c7108d5c1be2f3be9a4d8e458fc4dc65c3222818a3ce6e9bf46e372df7
Python
2,097
83
# !/usr/bin/python # -*- Mode: Python; tab-width: 4; py-indent-offset: 4; -*- # # An OpenGL movie class with buffer (buffermovie.py) # # 01-09-2009: sn # A movie class with buffer # import sys from string import * import pygame from pygame.locals import * class buffermovie: """ A class to load and store movie (...
069303ab0f99193fad1d424dee4e97a16cf61f8eac06a4b19a8ba9a5b58c1ec5
Python
2,098
80
import numpy as np import pandas as pd from pandas import ( DataFrame, Index, ) import pandas._testing as tm def test_pipe(): # Test the pipe method of DataFrameGroupBy. # Issue #17871 random_state = np.random.default_rng(2) df = DataFrame( { "A": ["foo", "bar", "foo", "...
21f3ed40e2df2c9e7284e2b897c80ef567e820369efd98b30b7429e8c5528209
Python
2,101
60
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 25 20:29:36 2019 @author: charleshen @note: this code derived from PybioMed<https://github.com/gadsbyfly/PyBioMed>, with a major modified This module mainly implements the calculation of MOE-type descriptors, which include LabuteASA, TPSA, slogP...
b735870a11b6a1c3e7d862f8cd61ab376ebf777b3aae403638ce0c7240094694
Python
2,102
61
import shutil import zipfile import argparse from pathlib import Path import deeplake import numpy as np import requests from tqdm import tqdm from src import constants def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--path", default=constants.sensorium_dir, type=Path) ...
5b12a128142d0f69869987d8211ddb440e7b58e580004bfe42302fe2f3ac4ce3
Python
2,106
64
""" Small PySCF -> TenCirPauli -> TensorCircuit/JAX VQE bridge example. This is a short integration preview. For the complete chemistry workflow, correctness checks, and benchmark study, see: https://github.com/tensorcircuit/TenCirPauli/blob/main/examples/quantum_chemistry_pyscf.py """ from __future__ import annotati...
5cdb5d2e8df74954e341b5de8a62c56b966e773a441309df241368ad56f1bb27
Python
2,106
95
""" ``numpy.linalg`` ================ The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient low level implementations of standard linear algebra algorithms. Those libraries may be provided by NumPy itself using C versions of a subset of their reference implementations but, when possible, high...
6e51ae23d5742f0002b14dbf658f244b193f01e86dbcf47fc3b18a4142a64a9c
Python
2,106
41
from qcportal import PortalClient from qcportal.singlepoint import QCSpecification, SinglepointDatasetNewEntry from qcportal.molecules import Molecule from qcportal.utils import chunk_iterable from openmm.unit import nanometer, bohr import openff.toolkit import numpy as np import h5py import sys dataset_name = sys.arg...
b34333ddb0233eba59b272b186c9332bb9d909bbc53d26646814c17837a986a7
Python
2,110
68
import time def wait_for_data(tbvNetInt, wait_time): """ Control function Waits for all correct initial parameters to run the thermometer. Args: tbvNetInt: TBVNetworkInterface instance wait_time: float - sleep time in seconds Returns: n_rois: int - number of ROIs in TB...
d6c7717222846d2b4707457eabd4f6df63fa834acfe831eb6f280fd076dd0e20
Python
2,112
64
import numpy as np import matplotlib.pyplot as pl from matplotlib.ticker import MaxNLocator # TODO: Add docstrings def principal_curve(adata): """TODO.""" X_curve = adata.uns["principal_curve"]["projections"] ixsort = adata.uns["principal_curve"]["ixsort"] pl.plot(X_curve[ixsort, 0], X_curve[ixsort, ...
ebbac332d64f2a20598ade62e683a59033b944ff531cf4f5985e3d2f9557a0f4
Python
2,112
70
""" ====================================================================== ShinGLMCC_fig.py Author: Yasuhiro Tsubo (tsubo@fc.ritsumei.ac.jp) Version 1.0: 2024.07.13 Version 2.0: 2024.08.28 * Adjusted the script's argument format to match that of ShinGLMCC_main.py. * Modified the program to avoid the "SettingWithC...
ebe95b35b6930f6a605d6676a4daf3a5b8ce8a3600d767b5643577d5c8c3d81c
Python
2,112
65
# 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. """Gene finding using GlimmerHMM mostly for fungi/eukaryotes """ from io import StringIO import logging from helperlibs.bio import seqio from helperlibs.wrappers.io ...
3b8d3fdff44d63e1de5e0c95819030d556d053282b4c640871c9f55b70de9e19
Python
2,114
72
import matplotlib.pyplot as plt import pandas as pd import numpy as np from tqdm import tqdm from joblib import load, dump import time from molmap import dataset from molmap import loadmap from molmap import model as molmodel import molmap #use GPU, if negative value, CPUs will be used import tensorflow as tf import...
50a53fb79a086bf91532ff3d62cf4a37a67f172e5b7aa3c352c0c058f99ca11f
Python
2,114
79
import pytest import subprocess import json import sys from numpy.distutils import _shell_utils from numpy.testing import IS_WASM argv_cases = [ [r'exe'], [r'path/exe'], [r'path\exe'], [r'\\server\path\exe'], [r'path to/exe'], [r'path to\exe'], [r'exe', '--flag'], [r'path/exe', '--fla...
c97505e83ac38623ca11f11724b9dbef56d99f271ba3808a5e4975e15cafdd06
Python
2,114
78
""" Tests that work on both the Python and C engines but do not have a specific classification into the other test modules. """ from io import StringIO import numpy as np import pytest from pandas import ( DataFrame, option_context, ) import pandas._testing as tm pytestmark = pytest.mark.filterwarnings( ...
b942a6a141cde51d5cf8f07406d03e8da166ec4a92511826807f27849780bf36
Python
2,117
51
# 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 more detailed Domain feature """ from collections import OrderedDict from typing import Dict, List from typing import Optional # comment hints, pylint: disable=unu...
bbbd9c3d4b17b5c7257615229e95f1295dc6612ecab823431bfa75e57dff9ff1
Python
2,121
61
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 def decompose_chrstr(peak_str): """ Args: peak_str (str): peak_str. e.g. 'chr...
5bdcb020107d0ca5ce6e93b08477d47fe60f71b9c03ace3e0934183fec9ccacd
Python
2,122
66
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 17:27:25 2019 @author: bxin """ import sys import os import argparse import numpy as np import h5py as h5 import CNN_utils_deeplift as util datadir = "../data/SELEX_" def main(): args = loadargs() for tf in args.tfs: if "train" i...
6322e4db6fcfc8a6412aac595cbbe07646fef21dd41d07a22713601a858c2ae0
Python
2,122
64
import os, gdown, zipfile, pickle def download_file_from_google_drive(file_id, destination): url = f"https://drive.google.com/uc?id={file_id}" try: gdown.download(url, destination, quiet=False) print(f"File downloaded successfully to {destination}") except Exception as e: prin...
aa783f82f57b3923995770a94180af9831232063f4b22e5dc321086e1898ba54
Python
2,124
60
# 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. """Identify TTA codons in BGCs""" from typing import Any, Dict, List, Optional from antismash.common.secmet import Record from antismash.config import ConfigType from an...
768c084cd5771b1abcc01dd776a8b2442b440e7f37fc690b706262427cccd660
Python
2,125
87
__all__ = [ "dtypes", "localize_pydatetime", "NaT", "NaTType", "iNaT", "nat_strings", "OutOfBoundsDatetime", "OutOfBoundsTimedelta", "IncompatibleFrequency", "Period", "Resolution", "Timedelta", "normalize_i8_timestamps", "is_date_array_normalized", "dt64arr_t...
448d3ca52ae6e6d052ccf32f9db4ea6c3f5621a95a3a837977833545398bab56
Python
2,128
76
CONSOLE_HTML_FORMAT = """\ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> {stylesheet} body {{ color: {foreground}; background-color: {background}; }} </style> </head> <body> <pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><code style="font-family:inherit">{c...
d61d671e103c04ba5bb844c4f14a70eea946dc549ff95eded4d9533dc52a94e7
Python
2,128
54
from qcportal import PortalClient import numpy as np import sys # Look for suspect records that should be rerun. dataset_name = sys.argv[1] client = PortalClient.from_file() dataset = client.get_dataset('singlepoint', dataset_name) include_specs = [name for name in dataset.specifications if dataset.specifications[nam...
bc69d4f72a2bde4cce84fa097aba07360d31f08fbf7fefb122e6d941d42fb493
Python
2,129
60
from __future__ import annotations from stimuli.time import Clock, sleep from ..detector import _BUFSIZE from ..utils._checks import check_type from ..utils._docs import fill_doc from ..utils.logs import logger from ._config import BACKEND, SOUND_DURATION, TARGET_DELAY, TRIGGER_TASKS from ._utils import create_sound,...
dd30467f7a3c0d97582129cf5c6b0f22543344aa083b7b0f04c1b86d35c93697
Python
2,132
74
""" Created on Jun 25, 2024 @author: mning """ from dataclasses import dataclass from math import ceil import numpy as np from numpy.random import uniform from sklearn import metrics @dataclass class ScoresTuple: acc: float = 0.0 sen: float = 0.0 spc: float = 0.0 f1: float = 0.0 roc_auc: float =...
e4362cfddbb41d93b801493753d09f8c989e277da57e70765caea6a556ba3f78
Python
2,132
75
""" Bin a point process by the values in a series Author: Drew B. Headley """ import numpy as np def bin_ptser(val_pt, bin_ser, edges, func=np.mean): """ A points are binned together based on shared corresponding values in another series and a function is applied. Parameters ---------- val_...
222570b26ddc0f09c976b934154161ec92c96049d1fc07d859046a58878e14d4
Python
2,133
83
"""Tools for testing implementations of __array_function__ and ufunc overrides """ from numpy._core.overrides import ARRAY_FUNCTIONS as _array_functions from numpy import ufunc as _ufunc import numpy._core.umath as _umath def get_overridable_numpy_ufuncs(): """List all numpy ufuncs overridable via `__array_ufun...
684e42c818fc7aded220607412b162cbeedb78d315c88ee20054cbb2ea0beb12
Python
2,133
58
def train_epoch(model, dataloader, optimizer, criterion, device,epoch): model.train() total_loss = 0 for batch in dataloader: src, tgt, _, _, _, tgt_lens = batch src, tgt = src.to(device), tgt.to(device) #print('tgt,tgt.shape',tgt,tgt.shape) optimizer.z...
b56ecdefe7ae95cd3e32d6e8b0178b96973075b3e341cca6440046af9a95e39c
Python
2,133
74
"""Example of how to run the full CALI pipeline.""" from pathlib import Path from sqlmodel import create_engine from cali.runner import CaliRunner from cali.sqlmodel import ( AnalysisSettings, DetectionSettings, Experiment, ExtractionSettings, ) from cali.sqlmodel._visualize_experiment import print_c...
b4ebee05875c40655847191376f1ecbc5a40a886d7f67eb7ade0bad91eee6d89
Python
2,135
92
""" DQAS for GHZ state preparation circuit, deprecated DQAS implementation """ import numpy as np import tensorflow as tf import cirq import tensorcircuit as tc from tensorcircuit.applications.vags import double_qubits_initial, GHZ_vag, GHZ_vag_tfq from tensorcircuit.applications.dqas import ( set_op_pool, ge...
9e67da1425736d5888390dbe323817b7e6cdf148faef8842822c2be48a25fbf5
Python
2,136
55
from numpy.testing import assert_ import numpy.distutils.fcompiler g77_version_strings = [ ('GNU Fortran 0.5.25 20010319 (prerelease)', '0.5.25'), ('GNU Fortran (GCC 3.2) 3.2 20020814 (release)', '3.2'), ('GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian)', '3.3.3'), ('GNU Fortran (GCC) 3.3.3 (De...
78beaefd6108493057a67e7e625db42235ab7fe63ce71e9bfb8eb534e79381d8
Python
2,141
61
from wordfreq import tokenize from wordfreq.preprocess import preprocess_text def test_transliteration(): # "Well, there's a lot of things you do not understand." # (from somewhere in OpenSubtitles assert tokenize("Па, има ту много ствари које не схваташ.", "sr") == [ "pa", "ima", ...
a6c754d0d997bda2572715b282230123f57ceb0e1b058d959e0f23f61603532b
Python
2,142
60
import numpy as np import scanpy as sc import decoupler as dc import scvi import pandas as pd # Open the RNA merged and filtered adata = sc.read_h5ad(snakemake.input.merged_rna_anndata) doublet_clusters = [] for cluster in adata.obs['leiden_2'].drop_duplicates(): #print(cluster, adata[adata.obs['leiden'] == clust...
9e2b7f913a5c9999888b2599d8161b2672a06080b9ea02c2032f9a5ddd53b8ea
Python
2,143
94
from pydantic import BaseModel from typing import List, Optional, Dict, Any class TripleResponse(BaseModel): head: str relation: str tail: str class NodeProperties(BaseModel): attributes: dict class NodeConnection(BaseModel): relationship_type: str target_node: NodeProperties class Subgr...
19d115589d3caf7d41c6ceacbb25b4073b2a12ffa76dab0f52dd89328edcef37
Python
2,144
76
import importlib import sys import pandas def test_top_level_import_exposes_lightweight_features(): sys.modules.pop("sbmlcore", None) sbmlcore = importlib.import_module("sbmlcore") feature = sbmlcore.AminoAcidMWChange() df = pandas.DataFrame({"mutation": ["A1D"]}) result = feature._add_feature(...
2db4bbabf8fb0225817e4d2d55c6043f96125971279ee6b75610a16ce515ed61
Python
2,145
46
# 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 antismash.common.sec...
b35a6ddce94afc975671a1ecc65b2f4a1df89aa16c478c2b38d030141a39c95c
Python
2,145
56
from datetime import timedelta import numpy as np from pandas import ( DatetimeIndex, date_range, ) import pandas._testing as tm class TestDatetimeIndexReindex: def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): # GH#7774 index = date_range("2013-01-01", periods=3, tz=...
95368a973da105238530a1dc3a0fcc73fdefb6b1951f56f5ea38c7d1609f3433
Python
2,146
48
#!/usr/bin/env python3 """ Production Server Runner for iAODE Serves the static frontend build and API backend together """ import uvicorn import os import sys if __name__ == "__main__": # Ensure we are running from the api directory # This helps with relative path resolution for static files current_dir ...
2a3b15eedb3deb7452c8d1062c64258b2a731c9fe1b37993b2558f3176691a91
Python
2,151
66
from __future__ import annotations import warnings import numpy as np import pyarrow from pandas.errors import PerformanceWarning from pandas.util._exceptions import find_stack_level def fallback_performancewarning(version: str | None = None) -> None: """ Raise a PerformanceWarning for falling back to Exte...
1b5183c2602e02ac9dea2eb8c1032b192c87af146bb7a2a2b978d57ff42d7e1e
Python
2,152
59
import logging import time from typing import Optional import backoff from sqlalchemy import CursorResult, create_engine, engine, text class Db: """SQLAlchemy database connection.""" def __init__(self, url: engine.URL): logging.debug("Creating SQL Alchemy engine to database: %s", url) self._...
91bf92b536cf3d0fe78d25a2989de55238670a44174e0500d2264dcab5a4d40c
Python
2,154
71
"""Helper functions for tests.""" import zipfile from pathlib import Path from nibabel import Nifti1Image from numpy.testing import assert_allclose def set_up_cmb_data(zipped_data_path: Path, cmb_path: Path) -> None: """Set up the CMB data directory by extracting the contents of a zipped file. Parameters ...
c22bda8033b39327665c35e6d93e80fdaed0ccbb4caa2ecf2efb01367c9b8824
Python
2,154
78
#!/usr/bin/env python3 """ PostToolUse hook to automatically add the bot-triaged label after any issue mutation. This hook runs after successful GitHub issue mutations (label/comment/close/transfer) and directly applies the `bot-triaged` label via the gh CLI. Exit codes: 0 - Success """ import json import os impor...
c255b699e073b2492b05830bb8b65fb83e1dce472fd78cd85c305754868d7499
Python
2,156
64
#!/usr/bin/env python3 """macOS arm64 build environment setup (runs once per Python before the build). Mirrors .ci/wheel/linux/build_env_setup.py for the macOS CD wheel build. macOS needs far less toolchain wiring than the manylinux path: there is no CUDA/ROCm/XPU split and the heavy deps come from the runner image or...
654eea52dcd5105806b7dc78841bab6541b268a85b63d2a29c2f89baab821dc6
Python
2,157
59
import pandas as pd import matplotlib.pyplot as plt import numpy as np import os # Create output directory os.makedirs('paper_graphs/Edge_Weight_Plots', exist_ok=True) # Read the data control_df = pd.read_csv('table/CT2_log/concise/control.csv') deletion_df = pd.read_csv('table/CT2_log/concise/large_deletion.csv') #...
98dd45235c026c6a70792b16444d06c2a4c7c5ad3f7d739619ac91e7454c30ff
Python
2,158
61
import logging import sys from pathlib import Path from typing import Any from cli.lib.common.cli_helper import BaseRunner from cli.lib.common.pip_helper import pip_install_packages from cli.lib.common.utils import working_directory from cli.lib.core.torchtitan.lib import ( clone_torchtitan, load_torchtitan_te...
b85c90c2b394951d7b2255ed4511e25ed9d9bd32778bc84e8ab39de46cd090cc
Python
2,158
63
from pytest import approx from wordfreq import word_frequency from wordfreq.numbers import digit_freq, smash_numbers def test_number_smashing(): assert smash_numbers("1") == "1" assert smash_numbers("3.14") == "0.00" assert smash_numbers("24601") == "00000" def test_decimals(): assert word_frequency...
b872c57f55dabf38069d99e61520ccb79e2e86d39322ad63e66ab099d676bdfe
Python
2,160
67
"""Splits data into train, validation, and test sets.""" import csv import os import sys from typing import Tuple from tap import Tap # pip install typed-argument-parser (https://github.com/swansonk14/typed-argument-parser) from tqdm import tqdm from typing_extensions import Literal sys.path.append(os.path.dirname(...
729232a5058ebc9eb63bd71675085441c197ccaaf8ae72d3545c8eb167b13921
Python
2,161
72
# coding: utf-8 # See notebook: # https://github.com/paninski-lab/yass-examples/blob/master/batch/multi_channel_apply_disk.ipynb """ Applying transformations to large files in batches: BatchProcessor.multi_channel_apply lets you apply transformations to batches of data where every batch has observations from every c...
1205833f3144dcbe74b374f4edc4a96854a475fafd8c826a83c99aa178289526
Python
2,162
64
import logging import json from rna3db.utils import PathLike, write_json class Filterer: def __init__( self, min_length: int = 32, max_resolution: float = 9.0, single_ratio_cutoff: float = 0.8, max_unknown_ratio: float = 0.3, ): self.min_length = min_length ...
d3ec9a149bddba0117ec71832b193e7b706983a4eb80bcec3e74b216f183ae8b
Python
2,163
80
""" A plain QAOA optimization example with given graphs using networkx. """ import networkx as nx import tensorflow as tf import tensorcircuit as tc K = tc.set_backend("tensorflow") ## 1. define the graph def dict2graph(d): g = nx.to_networkx_graph(d) for e in g.edges: if not g[e[0]][e[1]].get("wei...
6edc8df7cf0b6ae20d3db31dbe188df9f816b7b22a9e5a726efaa61e4993b114
Python
2,164
55
from scanip_api3 import * # 2022-06-16 14:52:31 - Background to mask copy App.GetDocument().CopyBackgroundToMask() # 2022-06-16 14:52:34 - Background removal App.GetDocument().RemoveBackground(App.GetDocument().GetBackgroundByName("Stack")) # 2022-06-16 14:52:38 - Mask renaming App.GetDocument().GetGenericMaskByName...
eecfa7de3ca9f9ed22915c6422ac5fdf146dc64dda055e21e45b27308712b4c6
Python
2,166
86
""" Tests for the pseudo-public API implemented in internals/api.py and exposed in core.internals """ import pytest import pandas as pd import pandas._testing as tm from pandas.core import internals from pandas.core.internals import api def test_internals_api(): assert internals.make_block is api.make_block d...
58e35e8aa8cb192728e89fdc521e356cf920133810632ff037cb00bd81c25a0a
Python
2,167
64
import os import numpy as np from pyfaidx import Fasta from typing import Tuple def get_chr_seq(genome: str, chrom: int) -> np.ndarray: genome_seq = Fasta(genome) if f'chr{chrom}' in genome_seq.keys(): chr_seq = genome_seq[f'chr{chrom}'][:].seq else: chr_seq = genome_seq[f'{chrom}'][:].se...
7e538530a8d9457c66c3aea895355f19c18dc99b3dcff540664185e86c927f43
Python
2,167
65
# coding: utf-8 import math import torch import torch.nn.functional as F """ IMPORTANT NOTE: The cutoff and the switch function are numerically a bit tricky: Right at the "seems" of these functions, i.e. where the piecewise definition changes, there is formally a division by 0 (i.e. 0/0). This is of no i...
87c10a276b741ee3e49845a19b5c60a77cc38c7c25402067d6452c7800603d58
Python
2,167
68
import einops import numpy as np def Rx(angles_degrees: np.ndarray) -> np.ndarray: """Affine matrix for a rotation around the X-axis.""" angles_degrees = np.asarray(angles_degrees).reshape(-1) c = np.cos(np.deg2rad(angles_degrees)) s = np.sin(np.deg2rad(angles_degrees)) matrices = einops.repeat( ...
5390aa725685694134695c11caea9acc422e7008b5e997366151e0ac3bb1ea79
Python
2,168
70
"""Conversion utilities between VTK, PyVista, and Trimesh mesh representations.""" import vtk from vtk.util.numpy_support import numpy_to_vtkIdTypeArray, numpy_to_vtk import trimesh import pyvista as pv import numpy as np def trimesh_to_vtk_polydata(mesh: trimesh.Trimesh): """Convert a Trimesh object to a VTK Po...
135bfa1eacb3b2a6f21600afb5da973c9875399cdb41139e489fafd4a7cde03b
Python
2,173
64
from dfsio import readdfs, writedfs import os from surfproc import mean_curvature, view_patch_vtk, patch_color_attrib, smooth_patch import numpy as np from scipy.io import loadmat # load mat file /home/ajoshi/Downloads/c.mat cmat = loadmat("/home/ajoshi/Downloads/c.mat") c = cmat["c"] lsurf = readdfs("/home/ajoshi/...
0b52ca274cf0376e399ee5b130ac989d83fae44a57bbf37206e48e43b67a7d5d
Python
2,175
63
"""Script to compare two source spaces and check for equality.""" import pickle from pathlib import Path from numpy.testing import assert_allclose, assert_array_equal # Set paths to the reference and new source space files here. reference_src_path = Path(__file__).parent / "reference_src.pkl" new_src_path = Path(__f...
68fead3005869eca070993eedcc68664f8b1b5b0a01b1a3542f6cb3bffacb7a1
Python
2,175
105
""" Global constants for the gridworld env. """ # ============================================================================= # set the value of interface # ============================================================================= FPS = 25 WinWidth = 340 #window width WinHeight = 260 #window width BoxSize = 20 ...
d13d32e2d81a052c50b1f2bc426a5bbc2398c4bfe72a7d9c16e53fb877d7d004
Python
2,175
59
# 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. """ Individual tools/methods for detection of gene functions """ import os from typing import List from antismash.common.secmet import CDSFeature, Record from antismash....
8181a5f70f5476d71f376e8a531d50c98e268e1e80d26e02b24de0b0221c768b
Python
2,176
72
import pytest from pandas import TimedeltaIndex from pandas.tseries.offsets import ( DateOffset, Day, Hour, MonthEnd, ) class TestFreq: @pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []]) @pytest.mark.parametrize("freq", ["2D", Day(2), "48h", Hour(48)]) def test_freq...