sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
aac6ae2f8d6639be1bcd8d2c30a772bd5b98c714f9c51c9f9dc70268eeb86def | Python | 1,360 | 36 | import tensorflow as tf
class GlorotOrthogonal(tf.initializers.Initializer):
"""
This code is extracted from dimenet (https://github.com/gasteigerjo/dimenet).
Generate a weight matrix with variance according to Glorot initialization.
Based on a random (semi-)orthogonal matrix neural networks
are ... |
ac39232005e092e9bb94ec6ec9ab79f14e249436d334b4818d40daf984de9909 | Python | 1,360 | 32 | # *=========================================================================
# *
# * Copyright Erasmus MC Rotterdam and contributors
# *
# * Licensed under the GNU GENERAL PUBLIC LICENSE Version 3;
# * you may not use this file except in compliance with the License.
# *
# * Unless required by applicable law or agre... |
cad7e0912d56259229baf8ea011dd445779bb9a16fd440c5d8134faad875bac8 | Python | 1,360 | 57 |
# %%
import numpy as np
import cfl
from matplotlib import pyplot as plt
sig=cfl.readcfl("sig").real
t=np.linspace(0, 4.0851, 1530)
plt.figure(figsize=(8,3.5))
plt.plot(t,sig)
plt.xticks([0,1,2,3,4])
plt.yticks([-1,-0.5,0,0.5,1])
plt.grid()
plt.xlabel("Time [s]")
plt.ylabel("Signal M(t)/M0")
plt.tight_layout()
plt.s... |
949ca4de98dd2d4608fb0d7a33bdffb714d229f222363727b22dfcbde92962cb | Python | 1,361 | 47 |
from cgatReport.Tracker import *
import sqlite3
class ReadCountSummary (TrackerSQL):
pattern = "reads_under_peaks"
def getTracks(self, subset=None):
return self.getValues("SELECT track FROM reads_under_peaks ")
def getSlices(self, subset=None):
fields = self.getColumns("reads_under_pea... |
bb1623ce46841306048b4bd408eb063eea32a7db85104d4cd9a977ce2b35bc0c | Python | 1,364 | 41 | from ChipseqReport import *
import glob
class BioProspectorMotifs(ChipseqTracker):
pattern = "(.*)_bioprospector$"
def __call__(self, track, slice=None):
resultsdir = os.path.join(EXPORTDIR, "bioprospector")
if not os.path.exists(resultsdir):
return []
data = odict()
... |
4d71279e71bf25b2661ba303416f1dfe7b4aa522f2dcb77a23463f12682fdab2 | Python | 1,365 | 60 | from robot import iCubHelper
icub = iCubHelper()
from pykron.core import Pykron
import yarp
import time
time_closing_eyes = 2
time_opening_eyes = 0.5
time_mutual_gaze = 2
time_avoiding_gaze = 2
soa = 1
icub.initGaze()
for _ in range(0,10):
req1 = icub.CloseEyes()
req2 = icub.lookRest() # wait for comp
... |
89955ad6935981a68ff4d80ea801697ff76b8dc1eb34c61a8c49102d8e02ef2a | Python | 1,365 | 34 | from django.shortcuts import render
from django.contrib import messages
from django.views.generic.edit import FormView
from django.core.exceptions import ValidationError
from .forms import Pl2KilosortForm
from .models import Trial
from .pl2kilosort_code import pl2kilosort
class IndexView(FormView):
model = Trial... |
d7bf889e4df0ccad97bd7f52071cefb76926db6d6f86a5700402de734c97aafd | Python | 1,367 | 33 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
5ecce04c7c4c837ca34a0a06cd18ec93ef490b87b599a246ef50d12a510b7db2 | Python | 1,369 | 37 | import torch
from torch import nn
import sys
sys.path.append("../../")
from TCN.tcn import TemporalConvNet
class TCN(nn.Module):
def __init__(self, input_size, output_size, num_channels,
kernel_size=2, dropout=0.3, emb_dropout=0.1, tied_weights=False):
super(TCN, self).__init__()
... |
a15d035162600e2007af5eb0e5ef82e0f51abd9866e0d1464c4eebdaef97df45 | Python | 1,369 | 35 | import jax
import jax.numpy as jnp
import numpy as np
from chemoxrl.cell import MultiCell
def evaluate_policy(model, num_envs, seed):
rng, rng_reset = jax.random.split(jax.random.PRNGKey(seed))
eval_envs = MultiCell(model.env_params, num_envs)
@jax.jit
def transition_step(carry, rng):
s, env_... |
2e5e030576273c84a8bb89c7c3cc7671c02c98b00d44fffa2c5a1fa502acee7f | Python | 1,371 | 45 | from enum import Enum
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.utils import pre_init
from typing_extensions import override
class EnumOutputParser(BaseOutputParser[Enum]):
"""Parse an output that is one of a set of ... |
8e51255de430872ab3f108fa0953a25784531d2f6870728ae8d9c274b0e3f71e | Python | 1,371 | 49 | # For this you need matlab and the new requirements.txt
import argparse
import matlab
import matlab.engine
import scipy.io
from oset.ecg.peak_detection.peak_det_matched_filter import (
peak_det_matched_filter,
)
import unit_test as testing
mat = scipy.io.loadmat("../../../datasets/sample-data/SampleECG1.mat")["d... |
f0eeccd16b621bcf19d2d2c5f29b37bf1f07fde470c6ce686985fd78a95492b2 | Python | 1,371 | 44 | from pycromanager import JavaBackendAcquisition, multi_d_acquisition_events, ZMQRemoteMMCoreJ, start_headless
import numpy as np
import time
mm_app_path = '/Applications/Micro-Manager-2.0.0-gamma1'
# mm_app_path = 'C:/Program Files/Micro-Manager-2.0gamma'
config_file = mm_app_path + "/MMConfig_demo.cfg"
#Optional: s... |
364af9ce6e4f96ae7ee219748636d2e1982fe8b0442bf8e9a0620e798b574280 | Python | 1,372 | 39 | import os
import shutil
import argparse
def move_to_partition(args, patients, partition):
if not os.path.exists(os.path.join(args.subjects_root_path, partition)):
os.mkdir(os.path.join(args.subjects_root_path, partition))
for patient in patients:
src = os.path.join(args.subjects_root_path, pat... |
d7fb3366e701140fffa8d6b386bca2e0b9286331cdb26463720d22f6b7c8952e | Python | 1,373 | 47 | from pycromanager import XYTiledAcquisition, multi_d_acquisition_events
def event_edit_fn(event):
# row = event["row"]
# col = event["col"]
# TODO: if you want to cancel, dont return anything
return event
def image_callback_fn(image, metadata):
row = metadata["Axes"]["row"]
col = metadata[... |
20aafd93a8a0b861942dfdfcd5f764d53c0465958f6a01df4ab293e1080ee89c | Python | 1,374 | 40 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description: :
@Date : 2022/06/17 12:44:46
@Author : Zilan Yu
@version : 1.0
'''
import pandas as pd
import os
def strict_based(df_train, df_test):
train_cdr3, train_peptide = list(df_train['cdr3']), list(df_train['peptide'])
test_cdr3, t... |
0a188b405858f314eb74360850d2eee4c042e6a03e028b1bbaa5ec8fb0517d7d | Python | 1,375 | 29 | # Generated by Django 3.1.4 on 2021-04-04 10:24
from django.db import migrations, models
import mapping.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Map',
fields=[
('id',... |
c605d417a603a694de5df282045a7b333714e7dcc3619bc35461289f4770ec2e | Python | 1,376 | 23 | """Prose word count per section of paper/main.tex (floats, equations, algorithms and comments removed). Usage: python src/section_wordcount.py"""
import os, re
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
s = open(os.path.join(ROOT, "paper", "main.tex"), encoding="utf-8").read()
s = s[s.index(r... |
1e90d5c7e69059e1f55c9d1aac74ad0a4d1c5165e200b302db620f27428c139a | Python | 1,378 | 55 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# example_use.py
# Jim Bagrow
# Last Modified: 2018-04-22
import sys, os
import itertools
import networkx as nx
import numpy as np
from portrait_divergence import portrait_divergence
# make n ER graphs and n BA graphs:
n = 10
list_ER = [ nx.erdos_renyi_graph(100, 3/99) ... |
6841008a7bbd9bf0b04f942df485ddfced992cb32c2b0bce38c5ee38503ef447 | Python | 1,378 | 44 | """Functions to read in the data and return required inputs to the other analysis functions,
including reordering of the data and matrices according to standard dictionary orders."""
from ..utils import path as pth
def read_dict(filename):
"""read_MEG_dict. Reads a HDF5 file containing a dictionary of MEG data, k... |
e5b77bfd5aae81b4ef946dc70f6241de21990ad53ae6cb0ea33b4abedf60f3a7 | Python | 1,378 | 36 | # Batch acquisition of protein sequence, pocket sequence, and absolute position information of pockets
import os
import pandas as pd
from get_pocket import get_poc_seq
path = os.path.abspath(os.path.dirname(os.getcwd()))
seq_path = path + f'\pre-data\core2016'
seq_data_path = path + r'\data\seq_data_core2016.... |
9ac97f2ca309867427892928b4e4ffaad4f3849f26a466b1b13f65107182e2c8 | Python | 1,379 | 39 | #!/bin/env python
"""
Parse an AMBER OpenMM ffxml file to generate variants of amino acid residue templates with protonated termini
"""
import xml.etree.ElementTree as etree
from xml.etree.ElementTree import Element, ElementTree, SubElement
input_filename = 'protein.ff14SB.xml' # input ffxml filename
output_filename... |
6444ed25fa40bf9abfa5727e680b812e7bcd46e1439b6e16b594d7c086c1d403 | Python | 1,380 | 49 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.callbacks.streamlit.streamlit_callback_handler import (
LLMThought,
LLMThoughtLabeler,
LLMThoughtState,
StreamlitCallbackHandler,
ToolRecord,
... |
07baa3923dc01a23c717c54fac75f0409ecf9a47e27748a3250f1bc1ada95227 | Python | 1,382 | 39 | # Copyright (c) MONAI Consortium
# 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, so... |
910672f092f20af5140eaec2afb9ffa49c00568a18a05e2752fd21a9995223ac | Python | 1,382 | 83 | from enum import Enum
class COCOLabels(Enum):
PERSON = 0
BICYCLE = 1
CAR = 2
MOTORBIKE = 3
AEROPLANE = 4
BUS = 5
TRAIN = 6
TRUCK = 7
BOAT = 8
TRAFFIC_LIGHT = 9
FIRE_HYDRANT = 10
STOP_SIGN = 11
PARKING_METER = 12
BENCH = 13
BIRD = 14
CAT = 15
DOG = 16
... |
a0a54d68583ac44e8afe8bad19a5b16ec5bf0c438062ed456c283732fe862894 | Python | 1,382 | 50 | """Collection of functions to manipulate atlases and ROIs"""
import numpy as np
import os
from ..utils.path import get_root_path
def get_DK_names(cortical_only=False):
"""Return the DK regions in alphabetical ordering.
Args:
cortical_only (Bool): If true, returns 68 cortical regions instead of 86.
... |
a6d9d94a2fe3c7076341061c625922947c768f042416f1114456c1e726a98dbe | Python | 1,382 | 48 | import io
import os
from contextlib import contextmanager
from importlib.resources import Package
from importlib.resources import path
from pathlib import Path
from typing import Any
from typing import BinaryIO
from typing import Dict
from typing import Iterator
from typing import List
from typing import Union
import ... |
be2a8389eb619d2ac9dd0b9e3286c17ddd5b18cdfadaa738223394c14efe6c07 | Python | 1,382 | 68 | from scipy.special import factorial
import numpy as np
import torch
from dreye.api import barycentric
from itertools import combinations_with_replacement, combinations
# transformations for running models
bigA = np.array([
[1, 1, 1, 1],
[1, 1, -1, -1],
[-1, 1, 1, -1],
[1, -1, 1, -1]
]).T
def identi... |
c62f063deb1ab3f1f46dd69f05fa5f44c984852751df05d0679e3bc0028e2415 | Python | 1,382 | 38 | # Copyright 2026 DeepMind Technologies Limited
#
# AlphaFold 3 source code is 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... |
e977a858cc4b3e4a87ea26affa00b620e4fa455c224a81044fe7e57a71c10a49 | Python | 1,382 | 40 | import matplotlib as mpl
mpl.use('pgf')
import matplotlib
from Articles.Sequential_Learning_Striatum.Figures.cfg_color import colors, cm
matplotlib.rcParams.update({
"font.family": "serif",
"pgf.texsystem": "pdflatex",
"pgf.preamble": "\n".join([
r"\usepackage{amsfonts,amssymb,mathtools,amsmath,xc... |
42094550d8eee8332185972684ff0c6062cd0e1536db45f7f22cb777ad6e8904 | Python | 1,383 | 39 | """Chat result schema."""
from typing import Any
from pydantic import BaseModel
from langchain_core.outputs.chat_generation import ChatGeneration
class ChatResult(BaseModel):
"""Use to represent the result of a chat model call with a single prompt.
This container is used internally by some implementations... |
8a092a20573d1129e229e90c2d25d04ca5ae138387dc55cfcd9f993341e663ab | Python | 1,385 | 38 | from langchain_core.callbacks.base import BaseCallbackHandler, BaseCallbackManager
def test_remove_handler() -> None:
"""Test removing handler does not raise an error on removal.
An handler can be inheritable or not. This test checks that
removing a handler does not raise an error if the handler
is n... |
c45bb815da43c32b858bb1b88a14503e62555b2deb8482a898614152aa4d9943 | Python | 1,385 | 42 | #!/usr/bin/env python
import json
import urllib.request
seed_terms = [
"GO:0000166", # nucleotide binding
"GO:0001882", # nucleoside binding
"GO:0003676", # nucleic acid binding
"GO:0090304", # nucleic acid metabolic process
"GO:0006974", # cellular response to DNA damage stimulus
"GO:0022613",... |
5f658049df9981248ebf29df6ec6cc67c667e1a90cd5821d2f7f3fe27c64850c | Python | 1,386 | 53 | """Vector stores."""
from typing import TYPE_CHECKING
from langchain_core._import_utils import import_attr
if TYPE_CHECKING:
from langchain_core.vectorstores.base import VST, VectorStore, VectorStoreRetriever
from langchain_core.vectorstores.in_memory import InMemoryVectorStore
__all__ = (
"VST",
"I... |
b80137a72cb170814c1b753af8853549022527ff013f94f4b5c8354296d8ed76 | Python | 1,386 | 29 | """
Script to aggregate data from multiple raw demographics data files obtained
from Prolific.
"""
import pandas as pd
RAW_DEMOGRAPHICS_DATA_FILES = [
"data/demographic-data/ada-learn_23-02-17/prolific_export_63d95c5a78080dfe9805f20f.csv",
"data/demographic-data/ada-learn_23-02-17/prolific_export_63d95f80f4cc... |
aa3f430099811be92feac0031259e17d9e85a8ff287b59a4cac2894c10659244 | Python | 1,388 | 47 | """Several MCP servers behind one adapter.
An `MCPConfig` dict names each backend. FastMCP connects to all of them and
prefixes every tool with its config key, so two servers exposing the same tool
name stay distinguishable in the list handed to a model.
Each backend is addressed independently, so a fleet can mix tra... |
31ae966201bcb6485531cbe0ec1b08378fa4f896737435766fbffe706e49b65f | Python | 1,391 | 43 | import os
import sys
import socket
import pandas as pd
from configs.configs import get_config_dict
from helpers.kernel_analysis import plot_lengthscale_window_length_relation
if __name__ == "__main__":
data_split = 'all'
kernel_param = 'kernel_lengthscales'
data_dimensionality = sys.argv[1] # 'd15', ... |
4b9dc6f3bf208c5295e0a676b716ba6c29ffb32b5eca85641fa45b092f904a2a | Python | 1,391 | 48 | import torch
def train_step(model, loss_fn, optim, batch, device):
# put model in train mode
model.train()
model.to(device)
# run one forward + backward step
# clear gradient
optim.zero_grad()
# inputs and targets
inputs, targets = batch[0], batch[1]
# move data to DEVICE
inp... |
2c50460248c02935df5c292fbb973f6d41150b7001b398cff858be2fe4cfd38f | Python | 1,393 | 41 | from .mesh import Mesh
from .generate_mesh import generateMesh
from .run_msms import runMSMS
from .run_nanoshaper import runNanoShaper
from .get_pockets import getPockets
from .map_point_features_to_mesh import mapPointFeaturesToMesh
from .get_geometric_edge_features import getGeometricEdgeFeatures
from .map_electrosta... |
4155d9e8ddff940c207409b378bf2bd5d41db3937d885e093d2cc291b49be972 | Python | 1,393 | 38 | from collections import OrderedDict
class OrderedEasyDict(OrderedDict):
"""Using OrderedDict for the `easydict` package
See Also https://pypi.python.org/pypi/easydict/
"""
def __init__(self, d=None, **kwargs):
super(OrderedEasyDict, self).__init__()
if d is None:
d = Ordere... |
c341538fb3d1d9f94d5a750b3c6c1769f90588699289b35f3022de419ef18a8d | Python | 1,393 | 40 | """
This example shows how to use pycromanager to interact with the micro-manager core.
Aside from the setup section, each following section can be run independently
"""
from pycromanager import _Bridge, ZMQRemoteMMCoreJ
import numpy as np
import matplotlib.pyplot as plt
#### Setup ####
# establish communication with ... |
098fc4ba113bac5fd6f8cfe9e45e8a139fea66bc2eb9eb0be2139b1658ec5e77 | Python | 1,394 | 56 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.ifconfig',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.... |
1ea76cdf4a1c3bd451db1481c59935d599ad824d95de15a6bd9b42155374e24c | Python | 1,394 | 42 | import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
def Count():
ratio = ["0.30", "0.29", "0.28", "0.27", "0.26", "0.25", "0.24"]
count = [9206, 9138, 8452, 6926, 5102, 3184, 1740]
proportion = []
for j in range(len(ratio)):
for i in range(coun... |
93ccb4721b4485a1dff18d7f9d9543b1bf4258375121615bf54f34ea69db1afa | Python | 1,394 | 47 | """Example selectors.
**Example selector** implements logic for selecting examples to include them in prompts.
This allows us to select examples that are most relevant to the input.
"""
from typing import TYPE_CHECKING
from langchain_core._import_utils import import_attr
if TYPE_CHECKING:
from langchain_core.ex... |
a0bc9c4d9744a7ee2b447194698f9dd54a4db86304ce3c43466defcd3f2b4680 | Python | 1,395 | 42 | import torch
import itertools
import numpy as np
import os
def generate_binary_permutations(n):
# creates binary permutations of length n for the datasets
perm = itertools.product(range(2), repeat = n)
perm = np.array([list(i) for i in perm])
return perm
def generate_logic_data(args):
inputs = ge... |
f9d1838541a906bc6ccc5d9d8c306ab55cc0a17686d2da20d2f4ab346dd44753 | Python | 1,395 | 47 | import argparse
import os
import numpy as np
import pandas as pd
import keras
import tensorflow as tf
from keras.models import load_model
from pandas.core.frame import DataFrame
parser = argparse.ArgumentParser()
parser.add_argument("--geno", default=None, help="Training genotype *.txt file (m x n matrix)"... |
da5d68cb1aa5215b24c987448eafc63e500c7ce4468824a9391d26fd86773254 | Python | 1,396 | 30 | import mne
import os.path as op
import numpy as np
from config_FaceName import MEG_data_path,group_name,Ids,bids_root
from mne.preprocessing import ICA
from mne_bids import BIDSPath
for subject_id in Ids:
subject = group_name+"%02d" % subject_id
print("processing subject: %s" % subject)
fname=... |
de98d8465c0321916e95a6be7f68ebfbd25ee8ddeee01f03a35c2a38361e99fd | Python | 1,396 | 30 | #TO BE UPDATED
from NeuronModel.NeuronClass import neuronClass
import numpy as np
import matplotlib.pyplot as plt
hsv = plt.get_cmap('hsv')
def colors(n):
return hsv(np.linspace(0., 1.0, len(n)+1))
class poisson(neuronClass) :
parameters = {'save': True, 'spike': True, 'tau': 10., 'R': 10., 'E_l': -65., 'E_r... |
689c62a52947c0ba6f9ab178e8e2375a97ce74f1f20fbeaabff49cc39327e9d3 | Python | 1,398 | 41 | import logging
import os
import sys
import pandas as pd
from configs.configs import get_config_dict
from helpers.icc import compute_icc_scores_pingouin
if __name__ == "__main__":
model_name = 'SVWP_joint'
data_dimensionality = sys.argv[1] # 'd15', 'd50'
cfg = get_config_dict(
data_set_name='... |
1bee45fbcc7f38cfa6be17689721fde54ca658d0e6a09c052eeae074700f006b | Python | 1,399 | 38 | #TO BE UPDATED
from NeuronModel.NeuronClass import neuronClass
import numpy as np
class fitzugh_nagumo(neuronClass) :
parameters = {'save': True,
'spike': False,
'tau' : 1.,
'a' : 0.8,
'b' : 0.7,
'kappa' : None
... |
de0f9f78c7fbe4a591a451be5fcb7319b69472278975a476339ce4fa1ab4048d | Python | 1,399 | 35 | from utils.io import load_test_data_as_tensorflow_datasets_with_wavelengths
from models import LSTMParams
import numpy as np
from paths import MODEL_PATH, TEST_DATA_PATH
import glob
import os
def evaluate(_dataset, _data_path, wl):
for model_path in glob.glob(MODEL_PATH + f"*_{wl}.h5"):
model_name = model... |
e1fcfde9f257f617b33ae26ae0018fb71679df5b4ccfe6b98ff4184424b03b31 | Python | 1,399 | 44 | import numpy as np
import pickle
import h5py
import glob
# load joe
path_files = "pickle"
path_output = "derived_files/HDF5/Data"
# find all pickle files:
pickle_files = glob.glob(path_files + "/*.pickle")
utf8_type = h5py.string_dtype('utf-8', 30)
for file in pickle_files:
with open(file, 'rb') as f:
... |
3a95766c6428dff594193d7cc509170b1d926fb7d801f93c038fbb42a06f882f | Python | 1,400 | 44 | import argparse
import json
import numpy as np
from PIL import Image
from os import path as osp
def compute_mean_std(data_dir, list_dir):
image_list_path = osp.join(list_dir, 'train_images.txt')
image_list = [line.strip() for line in open(image_list_path, 'r')]
np.random.shuffle(image_list)
pixels = [... |
e168e61b841d6be69e9ffefa5beaa21e6b82d9c53663fd030845232619e103d8 | Python | 1,400 | 48 | import re
import pytest
from langchain_classic.evaluation import RegexMatchStringEvaluator
@pytest.fixture
def regex_match_string_evaluator() -> RegexMatchStringEvaluator:
"""Create a RegexMatchStringEvaluator with default configuration."""
return RegexMatchStringEvaluator()
@pytest.fixture
def regex_matc... |
80038850d2d9b7a953f767f71ef8d0643cc469835a79dc40d34dd23ea992c109 | Python | 1,402 | 41 | from django import forms
from django.forms import ModelForm
from django.core.exceptions import ValidationError
from .models import Scene
class SceneForm(ModelForm):
probes_number = forms.IntegerField(min_value=0, required=True)
clusters_sets_number = forms.IntegerField(min_value=1, label = 'Cluster sets numb... |
cf49de740f622dce0541c601baaf572edcc1660fe8d53c4a1c89e5abb088e7a6 | Python | 1,402 | 36 | r"""Comparison evaluators.
This module contains evaluators for comparing the output of two models,
be they LLMs, Chains, or otherwise. This can be used for scoring
preferences, measuring similarity / semantic equivalence between outputs,
or any other comparison task.
Example:
>>> from langchain_openai import Chat... |
e40b8cd248d0fb5716120fd394a2d0797fdd27226c76f44963f32da00ebb6d98 | Python | 1,402 | 49 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
bac... |
616d35233d2e8e4188dd5c61723b3580edb5393ec29ae429dca5ea05d420d3a4 | Python | 1,403 | 50 | import numpy as np
import torch
class Randomize(object):
"""Shuffles pixels of given image
Different shuffle applied for each channel
"""
def __init__(self, dims,p=1.0):
self.dims = dims
self.p = p
def __call__(self, img):
if np.random.rand(1)[0] <= self.p:
shp... |
6c4823891bbb50e5f65f8febeebd556d836eb4ceaf1ae54fc21af4420787fa88 | Python | 1,405 | 47 | import matplotlib.pyplot as plt
from dival.measure import PSNR
from dliplib.utils import Params
from dliplib.utils.helper import load_standard_dataset
from dliplib.utils.plot import plot_iterations
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
# load data
dataset = load_standard_dataset('ellips... |
e632a1df7cafa9eccf42cb95410f31dfaeb9f90dd47b9603b02c0a9498c9b4c6 | Python | 1,405 | 45 | import numpy as np
from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
from dliplib.utils.reports import save_results_tab... |
f6b7f2401a0cdb98ef88712cce8fdade3ab23780377787b16e18630d518b4fc0 | Python | 1,405 | 35 | import unittest
from check_diff import _get_configs_for_single_dir
class TestIntegrationPythonVersions(unittest.TestCase):
def test_pillow_integration_jobs_require_python_311(self) -> None:
for package in ("openai", "perplexity"):
for job in ("compile-integration-tests", "lint"):
... |
25fe0c4c04733ef58aadb16b717bebe4a2c41444b2f070c598b11b6d8c7f5999 | Python | 1,407 | 49 | import json
import pickle
import numpy as np
import torch
from dopp import FeedForwardCell, FeedForwardCurrentCell
from sim import sim # noqa: F402
if __name__ == "__main__":
with open("fig7_params.json", "r") as f:
params = json.load(f)
assert params["in_features"][0] == params["in_features"][1]
... |
3548f1e11486459a10029ab9c356d9aa2ab5b83923593c9ff440f1e0fb132d68 | Python | 1,408 | 25 | import sys, time, warnings; sys.path.insert(0,"."); warnings.filterwarnings("ignore")
import numpy as np
def log(m): print(m, flush=True)
from pydeepmapper.io import load_10x_populations, highly_variable_subset
from sklearn.model_selection import train_test_split
from tabfm import TabFMClassifier, tabfm_v1_0_0_pytorch ... |
e6a70ab322fc622aa13cd6a651ded8ac8a721f0138a9713cb977c4f1e1fb3163 | Python | 1,409 | 48 | ## Examine the overlap between predictive features across brain regions
import functools
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib_venn import venn3
@functools.lru_cache()
def get_rank():
fn = "../../_m/BrainSeq_sex_prediction_median_rank_genes.txt.gz"
return pd.read_csv(fn, sep='\t'... |
d73eefd8ec14730678a553f270a7c11c8552de20933828d4e862dfb97e9d30aa | Python | 1,410 | 43 | import attr
import cattr
from animalai.envs.arena_config import ArenaConfig
from typing import Optional, List, Dict, Any
from mlagents_envs.side_channel.side_channel import SideChannel
from mlagents.trainers.cli_utils import load_config
from mlagents.trainers.exception import TrainerConfigError
@attr.s(auto_attribs=T... |
9c9e7563e5756e9298e83c55c8354e7cf51fdf915db5d9273c917e610a4cf9c0 | Python | 1,412 | 44 | """Point the adapter at a real MCP server on the public internet.
DeepWiki answers questions about public GitHub repositories and serves MCP over
streamable HTTP with no auth. Nothing here is special-cased for it: the URL is
the entire configuration.
uv run examples/mcp/remote_server.py
"""
from __future__ impor... |
4db4f523d1128ed918fa726d302b223c1b5e1b14cfc45f92bad711372a1d9b8c | Python | 1,414 | 40 | import torch.nn as nn
import torch.utils.data
import torch.nn.functional as F
from pointnet_utils import PointNetEncoder, feature_transform_reguliarzer
class get_model(nn.Module):
def __init__(self, k=40, normal_channel=True):
super(get_model, self).__init__()
if normal_channel:
channel... |
dca8aa2aed02d6630ba4d58feab69e2f80e4f76e803d5365bf35b2b9ca776be3 | Python | 1,414 | 42 | import torch
import numpy as np
from networks.resnet import resnet50
from sklearn.metrics import average_precision_score, precision_recall_curve, accuracy_score
from options.test_options import TestOptions
from data import create_dataloader
def validate(model, opt):
data_loader = create_dataloader(opt)
with ... |
b19c651ba5c6c0ff0cd695d839c5bdd97e6b853e8d5fdeed4dd76cf63d01d350 | Python | 1,416 | 38 | import torch
import torch.nn as nn
from torch.nn import functional as F
class Upsample(nn.Module):
def __init__(self, input_dim, output_dim, kernel, stride):
super(Upsample, self).__init__()
self.upsample = nn.ConvTranspose2d(
input_dim, output_dim, kernel_size=kernel, stride=stride, ... |
dcbea5b5189ebd55d9d7733d41a5a4a3db10aaf40c7d27e0341e9394bca74aa5 | Python | 1,416 | 34 | import xml.etree.ElementTree as ET
from os import getcwd
sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonit... |
03b7069215a3fc524a915240fad22eb0bce435c1620ec3eb76ebead60559516b | Python | 1,417 | 48 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.callbacks.utils import (
BaseMetadataCallbackHandler,
_flatten_dict,
flatten_dict,
hash_string,
import_pandas,
import_spacy,
i... |
cad370c26d98d4048301def729fb19e14e55c13fbec826ab85d6807d10fcbea4 | Python | 1,420 | 42 | from src.parsers import NG_parser
from src.neurogym import train_NG, test_NG
from src.PID import runner
if __name__ == "__main__":
"""
************************************************************
Main function to run Neurogym experiments (for 1 seed).
*************************************************... |
433568d4632592422e549e63292c46b8bde5c374eea65cd35c8736189491133d | Python | 1,421 | 44 | #coding=utf-8
import torch
import torch.nn.functional as F
from alg.algs.ERM import ERM
class GroupDRO(ERM):
"""
Robust ERM minimizes the error at the worst minibatch
Algorithm 1 from [https://arxiv.org/pdf/1911.08731.pdf]
"""
def __init__(self,args):
super(GroupDRO, self).__init__(args)
... |
664570301ca3d562a9470ac0461e8c5d0819a0df3faf95c9f29424ca97160aaa | Python | 1,422 | 39 | import numpy as np
import MDAnalysis as mda
def write_cluster_traj(cluster_idx, top_file, trj_file, out_name, start_frame=0):
"""
Writes a trajectory into a separate file for each cluster.
Parameters
----------
cluster_idx : int array
Cluster index for each frame.
top_file... |
8c761b24f1226ded7603494662d0e716e67293e868cf5787dabf0cfe55930235 | Python | 1,423 | 42 | import torch.nn as nn
class ResLayer(nn.Module):
def __init__(self, linear_size):
super(ResLayer, self).__init__()
self.l_size = linear_size
self.nonlin1 = nn.ReLU(inplace=True)
self.nonlin2 = nn.ReLU(inplace=True)
self.dropout1 = nn.Dropout()
self.w1 = nn.Linear(sel... |
fd8a8fd736e3f757e1912fc7f2abe2f3bb795d1e72942667298dd67d41f76ed8 | Python | 1,424 | 40 | from typing import Any
from langchain_core.exceptions import OutputParserException
from langchain_classic.output_parsers import ResponseSchema, StructuredOutputParser
def test_parse() -> None:
"""Test parsing structured output."""
response_schemas = [
ResponseSchema(name="name", description="desc"),... |
b65c9bd3e255128ad8c8fc6581d2e4fddd8efa59b131d050a4f277a1ab7486a0 | Python | 1,426 | 40 | import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, roc_auc_score
from mantis_ml.modules.supervised_learn.core.balanced_datasets_random_generator import BalancedDatasetRandomGenerator
class PrepareTrainTestSets:
def __init__(self, cfg):
self.cfg = cfg
def get_balanc... |
27dc9c318d0828766685cfa0cf20e522eca1e887f6c7f9c09a7ac06bc8f208b9 | Python | 1,427 | 49 | # coding=utf-8
import torch
class _InfiniteSampler(torch.utils.data.Sampler):
"""Wraps another Sampler to yield an infinite stream."""
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
for batch in self.sampler:
yield batch
... |
914ec4018560f000c76c58e9c53f7890b0b1d8134133106b18043c2e4142f216 | Python | 1,428 | 64 | from sys import maxsize as MAX_INT
import socket
import getpass
SEED0 = 2424
HOSTNAME = socket.gethostname()
SERVER = HOSTNAME.split(".")[0]
match SERVER:
case "server name":
DATA_PREFIX = "root path to data on server"
case _:
raise ValueError(f"Unknown server: {SERVER}")
USER... |
d9c455cf8a37c29ecdf2e5244bb8177912c091e0539bcdedba0445863bb7d380 | Python | 1,428 | 41 | from importlib import import_module
def import_attr(
attr_name: str,
module_name: str | None,
package: str | None,
) -> object:
"""Import an attribute from a module located in a package.
This utility function is used in custom `__getattr__` methods within `__init__.py`
files to dynamically im... |
50cbd6ebf999b71f388a9022625b7289f219b5e2ca844bd699b0f5a3ddb8a97f | Python | 1,429 | 42 | import torch.nn as nn
from torchdiffeq import odeint_adjoint, odeint
# from CEL.networks.networks import *
class DerivativeEstimator(nn.Module):
def __init__(self, model_phy, model_aug, is_augmented):
super().__init__()
self.model_phy = model_phy
self.model_aug = model_aug
self.is_... |
58e654fb8a4d11ca9b03571de265a7184c18b39db48e4f6a25458e1489618150 | Python | 1,429 | 38 | import numpy as np
from multiprocessing import Pool
def compute_median_survival_time_last_observed_pmap_helper(args):
# same code logic as lifelines
survival_curve, duration_index = args
if survival_curve[-1] > .5:
return duration_index[-1]
else:
return duration_index[np.searchsorted(-... |
70f1bdf7744981a42efd5e0446a7af74560aab68f7cba9a765123ad67332c65d | Python | 1,429 | 44 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup
# Define package info
name = "pycoMeth"
version = "0.4.25"
description = "DNA methylation analysis downstream to Nanopolish for Oxford Nanopore DNA sequencing datasets"
with open("README.md", "r") as fh:
long_description = fh.read()
# Co... |
856e5f4b4c7b0f24c1b920d8c2ef5cdb198efc41ff0f803b3fc1cbf057b3be0e | Python | 1,429 | 54 | from functools import partial
import pytest
import torch
from chroma.layers.sde import sde_integrate, sde_integrate_heun
@pytest.fixture
def y0():
# try multiple 1D trajectories, then take mean and variance in testing
return torch.zeros(10000)
@pytest.fixture
def tspan():
return (0.5, 0.3)
@pytest.f... |
93cddd4caa874f0a94a119b1e952a8fa748ef6b05fd9795beca16f5584d12bf3 | Python | 1,430 | 47 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
# print(setuptools.find_packages())
setuptools.setup(
name='morgana',
version="0.1.2",
author="Nicola Gritti",
author_email="gritti@embl.es",
description="A machine learning tool to segment org... |
cf544a32573c9904223204a2d5cd874141c2252a18dde475b70b36c5601ed51a | Python | 1,430 | 35 | """Parsing utils to go from string to AgentAction or Agent Finish.
AgentAction means that an action should be taken.
This contains the name of the tool to use, the input to pass to that tool,
and a `log` variable (which contains a log of the agent's thinking).
AgentFinish means that a response should be given.
This c... |
db34f9f87e77b094fc3cf4f9c241b65b3c51e49d175f8be2363e7b94774cd7ba | Python | 1,430 | 35 | import numpy as np
import pandas as pd
def get_feature(input_path,reference_path,save_path):
df = pd.read_csv(input_path+'/expression_rawdata.txt',sep="\t")
sample=list(df.columns[1:])
df['ID']=df['feature'].map(lambda x:x.split('|')[0].split('_PAR_Y')[0])
df_new=df[['ID']+sample].groupby('ID').sum()
... |
4815cb065693d603a07cfc6dfbc4352e8bc8932eefbb3914237f6b1f0aef96b3 | Python | 1,434 | 35 | from langchain_core.prompts.prompt import PromptTemplate
PROMPT_SUFFIX = """Only use the following Elasticsearch indices:
{indices_info}
Question: {input}
ESQuery:"""
DEFAULT_DSL_TEMPLATE = """Given an input question, create a syntactically correct Elasticsearch query to run. Unless the user specifies in their quest... |
de30994fbb06dee63fe6c32feb99d195f5ff2973198319b6425c739929750b26 | Python | 1,435 | 45 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.output_parsers.ernie_functions import (
JsonKeyOutputFunctionsParser,
JsonOutputFunctionsParser,
OutputFunctionsParser,
PydanticAttrOutputFunctionsPar... |
10bce88c87dabeb601c79b593f755ca0cf706a2fc3c24404a4414f75b3ea460e | Python | 1,437 | 52 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('svtyper/version.py') as f:
exec(f.read())
setup(
name='svtyper',
version=__version__,
description='Bayesian genotyper for structural variants',
long_description=readm... |
b9d37538c177b40ca8e25106807189fe2c23b6ab72425c918a58db6a97a53658 | Python | 1,437 | 38 | """" Run pipelines to extract envelope and speech features from the audiobook segments.
Envelopes are directly extracted from the audio files, while speech features are extracted from the output of
the AN model. AN rates are created twice, they were once extracted from the original speech wave, and once from the
inver... |
1d3732aa5f36963ac347fc65b07b4cdf7f5d9bbc9539e98dfb8c611936ea8fd6 | Python | 1,439 | 38 |
from copy import copy
import numpy as np
import pandas as pd
class Input:
def __init__(self, Table, pdata):
""" RPKM for transcriptomics analysis output
RPKM method is composed by a tab-separated file and pdata table.
Following Transcriptomics guidelines, we suggest the use of RPKM/FPKM... |
997e5b2a848dffa58711f3e5a228edc751c66ee7aabcceb9fd5d5ae701583214 | Python | 1,439 | 45 | """A failing MCP tool reaches the model instead of ending the run.
When a server reports `isError=True`, the adapter turns it into a `ToolMessage`
with `status="error"` carrying the server's own message. The agent reads that
and can correct itself. Transport failures still raise, because a model cannot
act on those.
... |
8555d82762a3f2b11782868951a7a261b32a879111100526369f1a7d4c003af5 | Python | 1,441 | 36 | def model_info(info):
task_name_code = info.get('task_name', {}).get('code')
model_name_code = info.get('model_name', {}).get('code')
model_type_code = info.get('model_type', {}).get('code')
# Model full name (Snake-case)
model_function = []
if task_name_code is not None and len(task_name_code)... |
62579b5115f21a5d5ddb0d70da70c77da4a99848a5f616a765ac50a9c2307eec | Python | 1,442 | 50 | """Module to analyze early stopping."""
from jarvis.db.jsonutils import loadjson
import glob
def check_early_stoppping_reached(
validation_file="history_val.json", n_early_stopping=30
):
"""Check if early stopping reached."""
early_stopping_reached = False
maes = loadjson(validation_file)["mae"]
b... |
ead974275d69bba1955e4daa6731bfc11757d9affe28fed1627ce2745bc6dbae | Python | 1,443 | 37 |
def freeze_dense_blocks(freeze_block: bool, model, block_freeze_num: int):
"""
if True, freezes specified dense blocks.
block_freeze_num: specify which blocks should be frozen. will freeze blocks 1 to block_freeze_num
"""
count_frozen_blocks = 0
count_unfrozen_blocks = 0
dense_blocks = [mo... |
02bde9fa2ed01ef7cad7154d81f655235337f37d1fc053557035847a45f77368 | Python | 1,445 | 57 | import argparse
import numpy as np
import os
DESCRIPTION = """
Put some ordering in the strange Bruker Scanlist
Cornelius Eichner 2021
"""
def func(elem):
try:
num = int(elem.split(' (E')[1].split(')>')[0])
except:
num = np.nan
return num
def buildArgsParser():
p = argparse.Ar... |
353b24cb1b043cbf37a831fbb2e537b548747a4a2d8f3ee57775f678219a0150 | Python | 1,445 | 69 | import pytest
from langchain_core.utils.env import get_from_dict_or_env
def test_get_from_dict_or_env() -> None:
assert (
get_from_dict_or_env(
{
"a": "foo",
},
["a"],
"__SOME_KEY_IN_ENV",
)
== "foo"
)
assert (
... |
703f2ae222919e63cf1dba10d10fa94d1f77e5e68ea040da16cf069e40d8ec37 | Python | 1,445 | 39 | # -- coding: utf-8 --
# @Time : 2024/2/1 18:13
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : subsample.py
# @Description: This file is subsampling the origin data
import scanpy as sc
import numpy as np
def obs_key_wise_subsampling(adata, obs_key, N):
'''
Subsample each class to same cell n... |
b2b5ddf0ebdf7734926bfe0e459818516b33056abc7e261b5ece3f64ccaf1e27 | Python | 1,445 | 40 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.