name
stringlengths 1
152
| class_name
stringlengths 1
51
| class_bases
stringlengths 0
159
⌀ | is_member
bool 2
classes | args
stringlengths 0
804
| class_docstr
stringlengths 4
8.19k
⌀ | class_docstr_tok
stringlengths 2
11.6k
⌀ | docstr
stringlengths 0
11.4k
⌀ | docstr_tok
stringlengths 2
13.4k
⌀ | returns
stringlengths 0
260
⌀ | code
stringlengths 21
52.4k
⌀ | code_tok
stringlengths 33
92.8k
⌀ | lstart
int64 1
1.75k
| lend
int64 5
1.75k
| raises
stringclasses 16
values | filename
stringlengths 5
66
| file_path
stringlengths 12
161
| imports
stringlengths 0
1.77k
| total_objects
int64 15
15
| num_classes
float64 1
7
⌀ | num_imports
int64 0
14
| num_functions
int64 0
15
| num_all_bases
float64 0
9
⌀ | num_methods
float64 1
14
⌀ | num_bases
float64 1
7
⌀ | label_desc
stringlengths 69
1.05k
| label_desc_len
int64 69
1.05k
| label_id
stringclasses 15
values | __index_level_0__
int64 468
2.35M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from_config | DenseRetrievalDataSource | DataSource | true | cls,config,schema | Data source for DPR (https://github.com/facebookresearch/DPR).
Expects multiline json for lazy loading and improved memory usage.
The original DPR files can be converted to multiline json using `jq -c .[]` | ["Data","source","for","DPR","(","https",":","\/\/github.com\/facebookresearch\/DPR",")",".","Expects","multiline","json","for","lazy","loading","and","improved","memory","usage",".","The","original","DPR","files","can","be","converted","to","multiline","json","using","`","jq","-c",".","[","]","`"] | null | null | cls | def from_config(cls, config: Config, schema=DEFAULT_SCHEMA):
return cls(
schema=schema,
train_filename=config.train_filename,
test_filename=config.test_filename,
eval_filename=config.eval_filename,
num_negative_ctxs=config.num_negative_ctxs,
use_title=config.use_title,
use_cache=config.use_cache,
)
| ["def","from_config","(","cls",",","config",":","Config",",","schema=DEFAULT_SCHEMA",")",":","return","cls","(","schema=schema",",","train_filename=config.train_filename",",","test_filename=config.test_filename",",","eval_filename=config.eval_filename",",","num_negative_ctxs=config.num_negative_ctxs",",","use_title=config.use_title",",","use_cache=config.use_cache",",",")"] | 31 | 40 | null | dense_retrieval.py | pytext/pytext/data/sources/dense_retrieval.py | import json
import random
from typing import List, Optional
from pytext.data.sources.data_source import DataSource, generator_property
from pytext.utils.file_io import PathManager | 15 | 1 | 5 | 1 | 1 | 7 | 1 | Use image node_id 1 for calling the DenseRetrievalDataSource obj's underlying member method code with example usage: obj.from_config(cls, config, schema) and returns: cls | 170 | node_id 1 | 1,680,322 |
get_parser | global | null | false | null | null | null | null | parser | def get_parser() -> argparse.Namespace:
"""Get argument parser."""
parser = argparse.ArgumentParser(
description="Convert standard rttm file to ESPnet format"
)
parser.add_argument(
"--rttm", required=True, type=str, help="Path of rttm file"
)
parser.add_argument(
"--wavscp",
required=True,
type=str,
help="Path of corresponding scp file",
)
parser.add_argument(
"--output_path",
required=True,
type=str,
help="Output directory to storry espnet_rttm",
)
parser.add_argument(
"--sampling_rate",
type=str_or_int,
default=16000,
help="Sampling rate of the audio",
)
parser.add_argument(
"--verbose",
default=1,
type=int,
help="Verbosity level. Higher is more logging.",
)
return parser
| ["def","get_parser","(",")","-",">","argparse.Namespace",":","``","''","''","Get","argument","parser",".","''","''","''","parser","=","argparse.ArgumentParser","(","description=","''","Convert","standard","rttm","file","to","ESPnet","format","''",")","parser.add_argument","(","``","--","rttm","''",",","required=True",",","type=str",",","help=","''","Path","of","rttm","file","''",")","parser.add_argument","(","``","--","wavscp","''",",","required=True",",","type=str",",","help=","''","Path","of","corresponding","scp","file","''",",",")","parser.add_argument","(","``","--","output_path","''",",","required=True",",","type=str",",","help=","''","Output","directory","to","storry","espnet_rttm","''",",",")","parser.add_argument","(","``","--","sampling_rate","''",",","type=str_or_int",",","default=16000",",","help=","''","Sampling","rate","of","the","audio","''",",",")","parser.add_argument","(","``","--","verbose","''",",","default=1",",","type=int",",","help=","''","Verbosity","level",".","Higher","is","more","logging",".","``",",",")","return","parser"] | 78 | 108 | null | convert_rttm.py | espnet/egs2/thchs30/asr1/pyscripts/utils/convert_rttm.py | import argparse
import collections.abc
import logging
import os
import re
from pathlib import Path
from typing import Union
import humanfriendly
import numpy
import soundfile
from typeguard import check_argument_types
from espnet2.utils.types import str_or_int | 15 | null | 12 | 3 | null | null | null | Use image node_id 2 for calling a global function with example usage: get_parser() and returns: parser | 102 | node_id 2 | 981,193 |
|
punctuation_error_rate | global | null | false | references,hypotheses,punctuation_marks,punctuation_mask | null | null | null | null | dper_obj | def punctuation_error_rate(
references: list[str],
hypotheses: list[str],
punctuation_marks: list[str],
punctuation_mask: str = "[PUNCT]",
) -> None:
"""
Computes Punctuation Error Rate
Args:
references (list[str]) - list of references
hypotheses (list[str]) - list of hypotheses
punctuation_marks (list[str]) - list of punctuation marks for computing metrics
punctuation_mask (str, by default "[PUNCT]") - mask token that will be applied to
given punctuation marks while edit distance calculation
Return:
punct_er (float) - Punctuation Error Rate
"""
dper_obj = DatasetPunctuationErrorRate(
references=references,
hypotheses=hypotheses,
punctuation_marks=punctuation_marks,
punctuation_mask=punctuation_mask,
)
dper_obj.compute()
return dper_obj.punct_er
| ["def","punctuation_error_rate","(","references",":","list","[","str","]",",","hypotheses",":","list","[","str","]",",","punctuation_marks",":","list","[","str","]",",","punctuation_mask",":","str","=","``","[","PUNCT","]","''",",",")","-",">","None",":","``","''","''","Computes","Punctuation","Error","Rate","Args",":","references","(","list","[","str","]",")","-","list","of","references","hypotheses","(","list","[","str","]",")","-","list","of","hypotheses","punctuation_marks","(","list","[","str","]",")","-","list","of","punctuation","marks","for","computing","metrics","punctuation_mask","(","str",",","by","default","``","[","PUNCT","]","''",")","-","mask","token","that","will","be","applied","to","given","punctuation","marks","while","edit","distance","calculation","Return",":","punct_er","(","float",")","-","Punctuation","Error","Rate","``","''","''","dper_obj","=","DatasetPunctuationErrorRate","(","references=references",",","hypotheses=hypotheses",",","punctuation_marks=punctuation_marks",",","punctuation_mask=punctuation_mask",",",")","dper_obj.compute","(",")","return","dper_obj.punct_er"] | 30 | 57 | null | punct_er.py | NeMo/nemo/collections/common/metrics/punct_er.py | import re
from collections import namedtuple
from tqdm import tqdm
from nemo.utils import logging | 15 | null | 4 | 1 | null | null | null | Use image node_id 1 for calling a global function with example usage: punctuation_error_rate(references, hypotheses, punctuation_marks, punctuation_mask) and returns: dper_obj | 175 | node_id 1 | 135,832 |
learn | QMixAgent | parl | true | self,state_batch,actions_batch,reward_batch,terminated_batch,obs_batch,available_actions_batch,filled_batch | null | null | Args:
state (np.ndarray): (batch_size, T, state_shape)
actions (np.ndarray): (batch_size, T, n_agents)
reward (np.ndarray): (batch_size, T, 1)
terminated (np.ndarray): (batch_size, T, 1)
obs (np.ndarray): (batch_size, T, n_agents, obs_shape)
available_actions_batch (np.ndarray): (batch_size, T, n_agents, n_actions)
filled_batch (np.ndarray): (batch_size, T, 1)
Returns:
mean_loss (float): train loss
mean_td_error (float): train TD error | ["Args",":","state","(","np.ndarray",")",":","(","batch_size",",","T",",","state_shape",")","actions","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",")","reward","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","terminated","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","obs","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",",","obs_shape",")","available_actions_batch","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",",","n_actions",")","filled_batch","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","Returns",":","mean_loss","(","float",")",":","train","loss","mean_td_error","(","float",")",":","train","TD","error"] | mean_loss, mean_td_error | def learn(
self,
state_batch,
actions_batch,
reward_batch,
terminated_batch,
obs_batch,
available_actions_batch,
filled_batch,
):
"""
Args:
state (np.ndarray): (batch_size, T, state_shape)
actions (np.ndarray): (batch_size, T, n_agents)
reward (np.ndarray): (batch_size, T, 1)
terminated (np.ndarray): (batch_size, T, 1)
obs (np.ndarray): (batch_size, T, n_agents, obs_shape)
available_actions_batch (np.ndarray): (batch_size, T, n_agents, n_actions)
filled_batch (np.ndarray): (batch_size, T, 1)
Returns:
mean_loss (float): train loss
mean_td_error (float): train TD error
"""
if self.global_step % self.update_target_interval == 0:
self.update_target()
self.target_update_count += 1
self.global_step += 1
state_batch = torch.tensor(
state_batch, dtype=torch.float32, device=self.device
)
actions_batch = torch.tensor(
actions_batch, dtype=torch.long, device=self.device
)
reward_batch = torch.tensor(
reward_batch, dtype=torch.float32, device=self.device
)
terminated_batch = torch.tensor(
terminated_batch, dtype=torch.float32, device=self.device
)
obs_batch = torch.tensor(
obs_batch, dtype=torch.float32, device=self.device
)
available_actions_batch = torch.tensor(
available_actions_batch,
dtype=torch.float32,
device=self.device,
)
filled_batch = torch.tensor(
filled_batch, dtype=torch.float32, device=self.device
)
mean_loss, mean_td_error = self.alg.learn(
state_batch,
actions_batch,
reward_batch,
terminated_batch,
obs_batch,
available_actions_batch,
filled_batch,
)
return mean_loss, mean_td_error
| ["def","learn","(","self",",","state_batch",",","actions_batch",",","reward_batch",",","terminated_batch",",","obs_batch",",","available_actions_batch",",","filled_batch",",",")",":","``","''","''","Args",":","state","(","np.ndarray",")",":","(","batch_size",",","T",",","state_shape",")","actions","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",")","reward","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","terminated","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","obs","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",",","obs_shape",")","available_actions_batch","(","np.ndarray",")",":","(","batch_size",",","T",",","n_agents",",","n_actions",")","filled_batch","(","np.ndarray",")",":","(","batch_size",",","T",",","1",")","Returns",":","mean_loss","(","float",")",":","train","loss","mean_td_error","(","float",")",":","train","TD","error","``","''","''","if","self.global_step","%","self.update_target_interval","==","0",":","self.update_target","(",")","self.target_update_count","+=","1","self.global_step","+=","1","state_batch","=","torch.tensor","(","state_batch",",","dtype=torch.float32",",","device=self.device",")","actions_batch","=","torch.tensor","(","actions_batch",",","dtype=torch.long",",","device=self.device",")","reward_batch","=","torch.tensor","(","reward_batch",",","dtype=torch.float32",",","device=self.device",")","terminated_batch","=","torch.tensor","(","terminated_batch",",","dtype=torch.float32",",","device=self.device",")","obs_batch","=","torch.tensor","(","obs_batch",",","dtype=torch.float32",",","device=self.device",")","available_actions_batch","=","torch.tensor","(","available_actions_batch",",","dtype=torch.float32",",","device=self.device",",",")","filled_batch","=","torch.tensor","(","filled_batch",",","dtype=torch.float32",",","device=self.device",")","mean_loss",",","mean_td_error","=","self.alg.learn","(","state_batch",",","actions_batch",",","reward_batch",",","terminated_batch",",","obs_batch",",","available_actions_batch",",","filled_batch",",",")","return","mean_loss",",","mean_td_error"] | 96 | 134 | null | qmix_agent.py | PARL/benchmark/torch/qmix/qmix_agent.py | import parl
import torch
import numpy
import os
import torch | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 8 for calling the QMixAgent obj's underlying member method code with example usage: obj.learn(state_batch, actions_batch, reward_batch, terminated_batch, obs_batch, available_actions_batch, filled_batch) and returns: mean_loss, mean_td_error | 260 | node_id 8 | 154,112 |
test_unary_ops_resolve_correctly | TestTypeDeclaration | AllenNlpTestCase | true | self | null | null | null | null | null | def test_unary_ops_resolve_correctly(self):
unary_type = UnaryOpType()
# Resolution should fail against a basic type
assert unary_type.resolve(ROW_TYPE) is None
# Resolution should fail against a complex type where the argument and return types are not same
assert (
unary_type.resolve(ComplexType(CELL_TYPE, ROW_TYPE)) is None
)
# Resolution should resolve ANY_TYPE given the other type
resolution = unary_type.resolve(ComplexType(ANY_TYPE, ROW_TYPE))
assert resolution == UnaryOpType(ROW_TYPE)
resolution = unary_type.resolve(ComplexType(CELL_TYPE, ANY_TYPE))
assert resolution == UnaryOpType(CELL_TYPE)
reverse_type = ComplexType(
ComplexType(CELL_TYPE, ROW_TYPE),
ComplexType(CELL_TYPE, ROW_TYPE),
)
resolution = unary_type.resolve(reverse_type)
assert resolution == UnaryOpType(ComplexType(CELL_TYPE, ROW_TYPE))
| ["def","test_unary_ops_resolve_correctly","(","self",")",":","unary_type","=","UnaryOpType","(",")","#","Resolution","should","fail","against","a","basic","type","assert","unary_type.resolve","(","ROW_TYPE",")","is","None","#","Resolution","should","fail","against","a","complex","type","where","the","argument","and","return","types","are","not","same","assert","(","unary_type.resolve","(","ComplexType","(","CELL_TYPE",",","ROW_TYPE",")",")","is","None",")","#","Resolution","should","resolve","ANY_TYPE","given","the","other","type","resolution","=","unary_type.resolve","(","ComplexType","(","ANY_TYPE",",","ROW_TYPE",")",")","assert","resolution","==","UnaryOpType","(","ROW_TYPE",")","resolution","=","unary_type.resolve","(","ComplexType","(","CELL_TYPE",",","ANY_TYPE",")",")","assert","resolution","==","UnaryOpType","(","CELL_TYPE",")","reverse_type","=","ComplexType","(","ComplexType","(","CELL_TYPE",",","ROW_TYPE",")",",","ComplexType","(","CELL_TYPE",",","ROW_TYPE",")",",",")","resolution","=","unary_type.resolve","(","reverse_type",")","assert","resolution","==","UnaryOpType","(","ComplexType","(","CELL_TYPE",",","ROW_TYPE",")",")"] | 26 | 43 | null | type_declaration_test.py | magnitude/pymagnitude/third_party/allennlp/tests/semparse/type_declarations/type_declaration_test.py | from __future__ import absolute_import
from allennlp.common.testing import AllenNlpTestCase
from allennlp.semparse.type_declarations import type_declaration
from allennlp.semparse.type_declarations.type_declaration import ANY_TYPE, BinaryOpType, ComplexType, NamedBasicType, UnaryOpType
from allennlp.semparse.type_declarations import wikitables_type_declaration
from allennlp.semparse.type_declarations.wikitables_type_declaration import CELL_TYPE, ROW_TYPE | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 2 for calling the TestTypeDeclaration obj's underlying member method code with example usage: obj.test_unary_ops_resolve_correctly() without return types | 171 | node_id 2 | 1,297,351 |
test_basic_types_conflict_on_names | TestTypeDeclaration | AllenNlpTestCase | true | self | null | null | null | null | null | def test_basic_types_conflict_on_names(self):
type_a = NamedBasicType("A")
type_b = NamedBasicType("B")
assert type_a.resolve(type_b) is None
| ["def","test_basic_types_conflict_on_names","(","self",")",":","type_a","=","NamedBasicType","(","``","A","''",")","type_b","=","NamedBasicType","(","``","B","''",")","assert","type_a.resolve","(","type_b",")","is","None"] | 21 | 24 | null | type_declaration_test.py | magnitude/pymagnitude/third_party/allennlp/tests/semparse/type_declarations/type_declaration_test.py | from __future__ import absolute_import
from allennlp.common.testing import AllenNlpTestCase
from allennlp.semparse.type_declarations import type_declaration
from allennlp.semparse.type_declarations.type_declaration import ANY_TYPE, BinaryOpType, ComplexType, NamedBasicType, UnaryOpType
from allennlp.semparse.type_declarations import wikitables_type_declaration
from allennlp.semparse.type_declarations.wikitables_type_declaration import CELL_TYPE, ROW_TYPE | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 1 for calling the TestTypeDeclaration obj's underlying member method code with example usage: obj.test_basic_types_conflict_on_names() without return types | 173 | node_id 1 | 1,297,350 |
test_sg_k_core | global | null | false | dask_client,benchmark,input_expected_output | null | null | null | null | null | def test_sg_k_core(dask_client, benchmark, input_expected_output):
# This test is only for benchmark purposes.
sg_k_core = None
G = input_expected_output["SGGraph"]
core_number = input_expected_output["core_number"]
degree_type = input_expected_output["degree_type"]
sg_k_core = benchmark(
cugraph.k_core,
G,
core_number=core_number,
degree_type=degree_type,
)
assert sg_k_core is not None
| ["def","test_sg_k_core","(","dask_client",",","benchmark",",","input_expected_output",")",":","#","This","test","is","only","for","benchmark","purposes",".","sg_k_core","=","None","G","=","input_expected_output","[","``","SGGraph","''","]","core_number","=","input_expected_output","[","``","core_number","''","]","degree_type","=","input_expected_output","[","``","degree_type","''","]","sg_k_core","=","benchmark","(","cugraph.k_core",",","G",",","core_number=core_number",",","degree_type=degree_type",",",")","assert","sg_k_core","is","not","None"] | 126 | 136 | null | test_k_core_mg.py | cugraph/python/cugraph/cugraph/tests/core/test_k_core_mg.py | import gc
import pytest
import dask_cudf
import cugraph
import cugraph.dask
from cugraph.testing import utils
from cudf.testing.testing import assert_frame_equal
from cugraph.structure.symmetrize import symmetrize_df
from pylibcugraph.testing import gen_fixture_params_product | 15 | null | 9 | 6 | null | null | null | Use image node_id 4 for calling a global function with example usage: test_sg_k_core(dask_client, benchmark, input_expected_output) without return types | 152 | node_id 4 | 686,801 |
setUpClass | DecisionTreeRegressorBostonHousingScikitNumericTest | unittest | true | self | Unit test class for testing scikit-learn converter and running both models | ["Unit","test","class","for","testing","scikit-learn","converter","and","running","both","models"] | Set up the unit test by loading the dataset and training a model. | ["Set","up","the","unit","test","by","loading","the","dataset","and","training","a","model","."] | null | def setUpClass(self):
"""
Set up the unit test by loading the dataset and training a model.
"""
from sklearn.datasets import load_boston
from sklearn.tree import DecisionTreeRegressor
# Load data and train model
scikit_data = load_boston()
self.scikit_data = scikit_data
self.X = scikit_data["data"]
self.target = scikit_data["target"]
self.feature_names = scikit_data.feature_names
self.output_name = "target"
| ["def","setUpClass","(","self",")",":","``","''","''","Set","up","the","unit","test","by","loading","the","dataset","and","training","a","model.","``","''","''","from","sklearn.datasets","import","load_boston","from","sklearn.tree","import","DecisionTreeRegressor","#","Load","data","and","train","model","scikit_data","=","load_boston","(",")","self.scikit_data","=","scikit_data","self.X","=","scikit_data","[","``","data","''","]","self.target","=","scikit_data","[","``","target","''","]","self.feature_names","=","scikit_data.feature_names","self.output_name","=","``","target","''"] | 27 | 40 | null | test_decision_tree_regression_numeric.py | turicreate/src/external/coremltools_wrap/coremltools/coremltools/test/xgboost_tests/test_decision_tree_regression_numeric.py | import unittest
from coremltools.converters import sklearn
from coremltools.models.utils import evaluate_regressor
import pandas
import os
from coremltools.models.utils import evaluate_regressor, _macos_version, _is_macos
from coremltools._deps import _HAS_SKLEARN
import pytest | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 1 for calling the DecisionTreeRegressorBostonHousingScikitNumericTest obj's underlying member method code with example usage: obj.setUpClass() without return types | 181 | node_id 1 | 2,281,186 |
__init__ | FeatureEmbedder | nn | true | self,cardinalities,embedding_dims | null | null | null | null | FeatureEmbedder | def __init__(
self,
cardinalities: List[int],
embedding_dims: List[int],
) -> None:
super().__init__()
self._num_features = len(cardinalities)
self._embedders = nn.ModuleList(
[
nn.Embedding(c, d)
for c, d in zip(cardinalities, embedding_dims)
]
)
| ["def","__init__","(","self",",","cardinalities",":","List","[","int","]",",","embedding_dims",":","List","[","int","]",",",")","-",">","None",":","super","(",")",".__init__","(",")","self._num_features","=","len","(","cardinalities",")","self._embedders","=","nn.ModuleList","(","[","nn.Embedding","(","c",",","d",")","for","c",",","d","in","zip","(","cardinalities",",","embedding_dims",")","]",")"] | 21 | 31 | null | feature.py | gluonts/src/gluonts/torch/modules/feature.py | from typing import List, Optional
import torch
import torch.nn | 15 | 2 | 3 | 0 | 2 | 2 | 1 | Use image node_id 1 to create a new FeatureEmbedder object from inherited base classes: nn with example: obj = FeatureEmbedder(cardinalities, embedding_dims) | 157 | node_id 1 | 1,103,823 |
check | ProbabilityRandomDesign | AbstractRandomDesign | true | self,iteration | Interleave a random configuration according to a given probability.
Parameters
----------
probability : float
Probability that a configuration will be drawn at random.
seed : int, defaults to 0
Integer used to initialize the random state. | ["Interleave","a","random","configuration","according","to","a","given","probability",".","Parameters","--","--","--","--","--","probability",":","float","Probability","that","a","configuration","will","be","drawn","at","random",".","seed",":","int",",","defaults","to","0","Integer","used","to","initialize","the","random","state","."] | null | null | True,False | def check(self, iteration: int) -> bool: # noqa: D102
assert iteration >= 0
if self._rng.rand() < self._probability:
return True
else:
return False
| ["def","check","(","self",",","iteration",":","int",")","-",">","bool",":","#","noqa",":","D102","assert","iteration",">","=","0","if","self._rng.rand","(",")","<","self._probability",":","return","True","else",":","return","False"] | 37 | 43 | null | probability_design.py | SMAC3/smac/random_design/probability_design.py | from __future__ import annotations
from typing import Any
from smac.random_design.abstract_random_design import AbstractRandomDesign
from smac.utils.logging import get_logger | 15 | 2 | 4 | 0 | 2 | 3 | 1 | Use image node_id 3 for calling the ProbabilityRandomDesign obj's underlying member method code with example usage: obj.check(iteration) and returns: True, False | 161 | node_id 3 | 202,957 |
__init__ | DynamicProbabilityRandomDesign | AbstractRandomDesign | true | self,probability,factor,seed | Interleave a random configuration according to a given probability which is decreased over time.
Parameters
----------
probability : float
Probability that a configuration will be drawn at random.
factor : float
Multiply the `probability` by `factor` in each iteration.
seed : int, defaults to 0
Integer used to initialize the random state. | ["Interleave","a","random","configuration","according","to","a","given","probability","which","is","decreased","over","time",".","Parameters","--","--","--","--","--","probability",":","float","Probability","that","a","configuration","will","be","drawn","at","random",".","factor",":","float","Multiply","the","`","probability","`","by","`","factor","`","in","each","iteration",".","seed",":","int",",","defaults","to","0","Integer","used","to","initialize","the","random","state","."] | null | null | DynamicProbabilityRandomDesign | def __init__(self, probability: float, factor: float, seed: int = 0):
super().__init__(seed)
assert 0 <= probability <= 1
assert factor > 0
self._probability = probability
self._factor = factor
| ["def","__init__","(","self",",","probability",":","float",",","factor",":","float",",","seed",":","int","=","0",")",":","super","(",")",".__init__","(","seed",")","assert","0","<","=","probability","<","=","1","assert","factor",">","0","self._probability","=","probability","self._factor","=","factor"] | 59 | 65 | null | probability_design.py | SMAC3/smac/random_design/probability_design.py | from __future__ import annotations
from typing import Any
from smac.random_design.abstract_random_design import AbstractRandomDesign
from smac.utils.logging import get_logger | 15 | 2 | 4 | 0 | 2 | 4 | 1 | Use image node_id 1 to create a new DynamicProbabilityRandomDesign object from inherited base classes: AbstractRandomDesign with example: obj = DynamicProbabilityRandomDesign(probability, factor, seed) | 201 | node_id 1 | 202,958 |
test_get_assistant_files | global | null | false | null | null | null | null | null | def test_get_assistant_files():
"""
Test function to create a new GPTAssistantAgent, set its instructions, retrieve the instructions,
and assert that the retrieved instructions match the set instructions.
"""
current_file_path = os.path.abspath(__file__)
openai_client = OpenAIWrapper(config_list=config_list)._clients[0]
file = openai_client.files.create(
file=open(current_file_path, "rb"), purpose="assistants"
)
name = "For test_get_assistant_files"
assistant = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config={
"config_list": config_list,
"tools": [{"type": "retrieval"}],
"file_ids": [file.id],
},
)
files = assistant.openai_client.beta.assistants.files.list(
assistant_id=assistant.assistant_id
)
retrieved_file_ids = [fild.id for fild in files]
expected_file_id = file.id
assistant.delete_assistant()
openai_client.files.delete(file.id)
assert expected_file_id in retrieved_file_ids
| ["def","test_get_assistant_files","(",")",":","``","''","''","Test","function","to","create","a","new","GPTAssistantAgent",",","set","its","instructions",",","retrieve","the","instructions",",","and","assert","that","the","retrieved","instructions","match","the","set","instructions.","``","''","''","current_file_path","=","os.path.abspath","(","__file__",")","openai_client","=","OpenAIWrapper","(","config_list=config_list",")","._clients","[","0","]","file","=","openai_client.files.create","(","file=open","(","current_file_path",",","``","rb","''",")",",","purpose=","''","assistants","''",")","name","=","``","For","test_get_assistant_files","''","assistant","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=","{","``","config_list","''",":","config_list",",","``","tools","''",":","[","{","``","type","''",":","``","retrieval","''","}","]",",","``","file_ids","''",":","[","file.id","]",",","}",",",")","files","=","assistant.openai_client.beta.assistants.files.list","(","assistant_id=assistant.assistant_id",")","retrieved_file_ids","=","[","fild.id","for","fild","in","files","]","expected_file_id","=","file.id","assistant.delete_assistant","(",")","openai_client.files.delete","(","file.id",")","assert","expected_file_id","in","retrieved_file_ids"] | 189 | 216 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 6 for calling a global function with example usage: test_get_assistant_files() without return types | 117 | node_id 6 | 319,271 |
|
sign_array | global | null | false | p_values,alpha | null | null | null | null | p_values | def sign_array(
p_values: Union[List, np.ndarray], alpha: float = 0.05
) -> np.ndarray:
"""Significance array.
Converts an array with p values to a significance array where
0 is False (not significant), 1 is True (significant),
and -1 is for diagonal elements.
Parameters
----------
p_values : Union[List, np.ndarray]
Any object exposing the array interface and containing
p values.
alpha : float = 0.05
Significance level. Default is 0.05.
Returns
-------
result : numpy.ndarray
Array where 0 is False (not significant), 1 is True (significant),
and -1 is for diagonal elements.
Examples
--------
>>> p_values = np.array([[ 1. , 0.00119517, 0.00278329],
[ 0.00119517, 1. , 0.18672227],
[ 0.00278329, 0.18672227, 1. ]])
>>> ph.sign_array(p_values)
array([[1, 1, 1],
[1, 1, 0],
[1, 0, 1]])
"""
p_values = np.array(p_values)
p_values[p_values > alpha] = 0
p_values[(p_values < alpha) & (p_values > 0)] = 1
np.fill_diagonal(p_values, 1)
return p_values
| ["def","sign_array","(","p_values",":","Union","[","List",",","np.ndarray","]",",","alpha",":","float","=","0.05",")","-",">","np.ndarray",":","``","''","''","Significance","array",".","Converts","an","array","with","p","values","to","a","significance","array","where","0","is","False","(","not","significant",")",",","1","is","True","(","significant",")",",","and","-1","is","for","diagonal","elements",".","Parameters","--","--","--","--","--","p_values",":","Union","[","List",",","np.ndarray","]","Any","object","exposing","the","array","interface","and","containing","p","values",".","alpha",":","float","=","0.05","Significance","level",".","Default","is","0.05",".","Returns","--","--","--","-","result",":","numpy.ndarray","Array","where","0","is","False","(","not","significant",")",",","1","is","True","(","significant",")",",","and","-1","is","for","diagonal","elements",".","Examples","--","--","--","--",">",">",">","p_values","=","np.array","(","[","[","1.",",","0.00119517",",","0.00278329","]",",","[","0.00119517",",","1.",",","0.18672227","]",",","[","0.00278329",",","0.18672227",",","1",".","]","]",")",">",">",">","ph.sign_array","(","p_values",")","array","(","[","[","1",",","1",",","1","]",",","[","1",",","1",",","0","]",",","[","1",",","0",",","1","]","]",")","``","''","''","p_values","=","np.array","(","p_values",")","p_values","[","p_values",">","alpha","]","=","0","p_values","[","(","p_values","<","alpha",")","&","(","p_values",">","0",")","]","=","1","np.fill_diagonal","(","p_values",",","1",")","return","p_values"] | 13 | 52 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 1 for calling a global function with example usage: sign_array(p_values, alpha) and returns: p_values | 119 | node_id 1 | 1,881,818 |
sign_table | global | null | false | p_values,lower,upper | null | null | null | null | pv | def sign_table(
p_values: Union[List, np.ndarray, DataFrame],
lower: bool = True,
upper: bool = True,
) -> Union[DataFrame, np.ndarray]:
"""Significance table.
Returns table that can be used in a publication. P values are replaced
with asterisks: \\* - p < 0.05, \\*\\* - p < 0.01, \\*\\*\\* - p < 0.001.
Parameters
----------
p_values : Union[List, np.ndarray, DataFrame]
Any object exposing the array interface and containing
p values.
lower : bool
Defines whether to return the lower triangle.
upper : bool
Defines whether to return the upper triangle.
Returns
-------
result : Union[DataFrame, np.ndarray]
P values masked with asterisks.
Examples
--------
>>> p_values = np.array([[-1. , 0.00119517, 0.00278329],
[ 0.00119517, -1. , 0.18672227],
[ 0.00278329, 0.18672227, -1. ]])
>>> ph.sign_table(p_values)
array([['-', '**', '**'],
['**', '-', 'NS'],
['**', 'NS', '-']], dtype=object)
"""
if not any([lower, upper]):
raise ValueError(
"Either lower or upper triangle must be returned"
)
pv = (
DataFrame(p_values, copy=True)
if not isinstance(p_values, DataFrame)
else p_values.copy()
)
ns = pv > 0.05
three = (pv < 0.001) & (pv >= 0)
two = (pv < 0.01) & (pv >= 0.001)
one = (pv < 0.05) & (pv >= 0.01)
pv = pv.astype(str)
pv[ns] = "NS"
pv[three] = "***"
pv[two] = "**"
pv[one] = "*"
np.fill_diagonal(pv.values, "-")
if not lower:
pv.values[np.tril_indices(pv.shape[0], -1)] = ""
elif not upper:
pv.values[np.triu_indices(pv.shape[0], 1)] = ""
return pv
| ["def","sign_table","(","p_values",":","Union","[","List",",","np.ndarray",",","DataFrame","]",",","lower",":","bool","=","True",",","upper",":","bool","=","True",",",")","-",">","Union","[","DataFrame",",","np.ndarray","]",":","``","''","''","Significance","table",".","Returns","table","that","can","be","used","in","a","publication",".","P","values","are","replaced","with","asterisks",":","\\\\","*","-","p","<","0.05",",","\\\\","*","\\\\","*","-","p","<","0.01",",","\\\\","*","\\\\","*","\\\\","*","-","p","<","0.001",".","Parameters","--","--","--","--","--","p_values",":","Union","[","List",",","np.ndarray",",","DataFrame","]","Any","object","exposing","the","array","interface","and","containing","p","values",".","lower",":","bool","Defines","whether","to","return","the","lower","triangle",".","upper",":","bool","Defines","whether","to","return","the","upper","triangle",".","Returns","--","--","--","-","result",":","Union","[","DataFrame",",","np.ndarray","]","P","values","masked","with","asterisks",".","Examples","--","--","--","--",">",">",">","p_values","=","np.array","(","[","[","-1.",",","0.00119517",",","0.00278329","]",",","[","0.00119517",",","-1.",",","0.18672227","]",",","[","0.00278329",",","0.18672227",",","-1",".","]","]",")",">",">",">","ph.sign_table","(","p_values",")","array","(","[","[","'-","'",",","'","*","*","'",",","'","*","*","'","]",",","[","'","*","*","'",",","'-","'",",","'NS","'","]",",","[","'","*","*","'",",","'NS","'",",","'-","'","]","]",",","dtype=object",")","``","''","''","if","not","any","(","[","lower",",","upper","]",")",":","raise","ValueError","(","``","Either","lower","or","upper","triangle","must","be","returned","''",")","pv","=","(","DataFrame","(","p_values",",","copy=True",")","if","not","isinstance","(","p_values",",","DataFrame",")","else","p_values.copy","(",")",")","ns","=","pv",">","0.05","three","=","(","pv","<","0.001",")","&","(","pv",">","=","0",")","two","=","(","pv","<","0.01",")","&","(","pv",">","=","0.001",")","one","=","(","pv","<","0.05",")","&","(","pv",">","=","0.01",")","pv","=","pv.astype","(","str",")","pv","[","ns","]","=","``","NS","''","pv","[","three","]","=","``","*","*","*","''","pv","[","two","]","=","``","*","*","''","pv","[","one","]","=","``","*","''","np.fill_diagonal","(","pv.values",",","``","-","''",")","if","not","lower",":","pv.values","[","np.tril_indices","(","pv.shape","[","0","]",",","-1",")","]","=","``","''","elif","not","upper",":","pv.values","[","np.triu_indices","(","pv.shape","[","0","]",",","1",")","]","=","``","''","return","pv"] | 55 | 115 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 2 for calling a global function with example usage: sign_table(p_values, lower, upper) and returns: pv | 120 | node_id 2 | 1,881,819 |
sign_plot | global | null | false | x,g,flat,labels,cmap,cbar_ax_bbox,ax | null | null | null | null | hax,hax, cbar | def sign_plot(
x: Union[List, np.ndarray, DataFrame],
g: Union[List, np.ndarray] = None,
flat: bool = False,
labels: bool = True,
cmap: List = None,
cbar_ax_bbox: List = None,
ax: SubplotBase = None,
**kwargs,
) -> Union[SubplotBase, Tuple[SubplotBase, Colorbar]]:
"""Significance plot, a heatmap of p values (based on Seaborn).
Parameters
----------
x : Union[List, np.ndarray, DataFrame]
If flat is False (default), x must be an array, any object exposing
the array interface, containing p values. If flat is True, x must be
a sign_array (returned by :py:meth:`scikit_posthocs.sign_array`
function).
g : Union[List, np.ndarray]
An array, any object exposing the array interface, containing
group names.
flat : bool
If `flat` is True, plots a significance array as a heatmap using
seaborn. If `flat` is False (default), plots an array of p values.
Non-flat mode is useful if you need to differentiate significance
levels visually. It is the preferred mode.
labels : bool
Plot axes labels (default) or not.
cmap : list
1) If flat is False (default):
List consisting of five elements, that will be exported to
ListedColormap method of matplotlib. First is for diagonal
elements, second is for non-significant elements, third is for
p < 0.001, fourth is for p < 0.01, fifth is for p < 0.05.
2) If flat is True:
List consisting of three elements, that will be exported to
ListedColormap method of matplotlib. First is for diagonal
elements, second is for non-significant elements, third is for
significant ones.
3) If not defined, default colormaps will be used.
cbar_ax_bbox : list
Colorbar axes position rect [left, bottom, width, height] where
all quantities are in fractions of figure width and height.
Refer to `matplotlib.figure.Figure.add_axes` for more information.
Default is [0.95, 0.35, 0.04, 0.3].
ax : SubplotBase
Axes in which to draw the plot, otherwise use the currently-active
Axes.
kwargs
Keyword arguments to be passed to seaborn heatmap method. These
keyword args cannot be used: cbar, vmin, vmax, center.
Returns
-------
ax : matplotlib.axes._subplots.AxesSubplot
Axes object with the heatmap.
cbar : matplotlib.colorbar.Colorbar
ColorBar object if `flat` is set to False.
Examples
--------
>>> x = np.array([[ 1, 1, 1],
[ 1, 1, 0],
[ 1, 0, 1]])
>>> ph.sign_plot(x, flat = True)
"""
for key in ["cbar", "vmin", "vmax", "center"]:
if key in kwargs:
del kwargs[key]
if isinstance(x, DataFrame):
df = x.copy()
else:
x = np.array(x)
g = g or np.arange(x.shape[0])
df = DataFrame(np.copy(x), index=g, columns=g)
dtype = df.values.dtype
if not np.issubdtype(dtype, np.integer) and flat:
raise ValueError(
"X should be a sign_array or DataFrame of integers"
)
elif not np.issubdtype(dtype, np.floating) and not flat:
raise ValueError(
"X should be an array or DataFrame of float p values"
)
if not cmap and flat:
# format: diagonal, non-significant, significant
cmap = ["1", "#fbd7d4", "#1a9641"]
elif not cmap and not flat:
# format: diagonal, non-significant, p<0.001, p<0.01, p<0.05
cmap = ["1", "#fbd7d4", "#005a32", "#238b45", "#a1d99b"]
if flat:
np.fill_diagonal(df.values, -1)
hax = heatmap(
df,
vmin=-1,
vmax=1,
cmap=ListedColormap(cmap),
cbar=False,
ax=ax,
**kwargs,
)
if not labels:
hax.set_xlabel("")
hax.set_ylabel("")
return hax
else:
df[(x < 0.001) & (x >= 0)] = 1
df[(x < 0.01) & (x >= 0.001)] = 2
df[(x < 0.05) & (x >= 0.01)] = 3
df[(x >= 0.05)] = 0
np.fill_diagonal(df.values, -1)
if len(cmap) != 5:
raise ValueError("Cmap list must contain 5 items")
hax = heatmap(
df,
vmin=-1,
vmax=3,
cmap=ListedColormap(cmap),
center=1,
cbar=False,
ax=ax,
**kwargs,
)
if not labels:
hax.set_xlabel("")
hax.set_ylabel("")
cbar_ax = hax.figure.add_axes(
cbar_ax_bbox or [0.95, 0.35, 0.04, 0.3]
)
cbar = ColorbarBase(
cbar_ax,
cmap=(ListedColormap(cmap[2:] + [cmap[1]])),
norm=colors.NoNorm(),
boundaries=[0, 1, 2, 3, 4],
)
cbar.set_ticks(
list(np.linspace(0, 3, 4)),
labels=["p < 0.001", "p < 0.01", "p < 0.05", "NS"],
)
cbar.outline.set_linewidth(1)
cbar.outline.set_edgecolor("0.5")
cbar.ax.tick_params(size=0)
return hax, cbar
| ["def","sign_plot","(","x",":","Union","[","List",",","np.ndarray",",","DataFrame","]",",","g",":","Union","[","List",",","np.ndarray","]","=","None",",","flat",":","bool","=","False",",","labels",":","bool","=","True",",","cmap",":","List","=","None",",","cbar_ax_bbox",":","List","=","None",",","ax",":","SubplotBase","=","None",",","*","*","kwargs",",",")","-",">","Union","[","SubplotBase",",","Tuple","[","SubplotBase",",","Colorbar","]","]",":","``","''","''","Significance","plot",",","a","heatmap","of","p","values","(","based","on","Seaborn",")",".","Parameters","--","--","--","--","--","x",":","Union","[","List",",","np.ndarray",",","DataFrame","]","If","flat","is","False","(","default",")",",","x","must","be","an","array",",","any","object","exposing","the","array","interface",",","containing","p","values",".","If","flat","is","True",",","x","must","be","a","sign_array","(","returned","by",":","py",":","meth",":","`","scikit_posthocs.sign_array","`","function",")",".","g",":","Union","[","List",",","np.ndarray","]","An","array",",","any","object","exposing","the","array","interface",",","containing","group","names",".","flat",":","bool","If","`","flat","`","is","True",",","plots","a","significance","array","as","a","heatmap","using","seaborn",".","If","`","flat","`","is","False","(","default",")",",","plots","an","array","of","p","values",".","Non-flat","mode","is","useful","if","you","need","to","differentiate","significance","levels","visually",".","It","is","the","preferred","mode",".","labels",":","bool","Plot","axes","labels","(","default",")","or","not",".","cmap",":","list","1",")","If","flat","is","False","(","default",")",":","List","consisting","of","five","elements",",","that","will","be","exported","to","ListedColormap","method","of","matplotlib",".","First","is","for","diagonal","elements",",","second","is","for","non-significant","elements",",","third","is","for","p","<","0.001",",","fourth","is","for","p","<","0.01",",","fifth","is","for","p","<","0.05",".","2",")","If","flat","is","True",":","List","consisting","of","three","elements",",","that","will","be","exported","to","ListedColormap","method","of","matplotlib",".","First","is","for","diagonal","elements",",","second","is","for","non-significant","elements",",","third","is","for","significant","ones",".","3",")","If","not","defined",",","default","colormaps","will","be","used",".","cbar_ax_bbox",":","list","Colorbar","axes","position","rect","[","left",",","bottom",",","width",",","height","]","where","all","quantities","are","in","fractions","of","figure","width","and","height",".","Refer","to","`","matplotlib.figure.Figure.add_axes","`","for","more","information",".","Default","is","[","0.95",",","0.35",",","0.04",",","0.3","]",".","ax",":","SubplotBase","Axes","in","which","to","draw","the","plot",",","otherwise","use","the","currently-active","Axes",".","kwargs","Keyword","arguments","to","be","passed","to","seaborn","heatmap","method",".","These","keyword","args","can","not","be","used",":","cbar",",","vmin",",","vmax",",","center",".","Returns","--","--","--","-","ax",":","matplotlib.axes._subplots.AxesSubplot","Axes","object","with","the","heatmap",".","cbar",":","matplotlib.colorbar.Colorbar","ColorBar","object","if","`","flat","`","is","set","to","False",".","Examples","--","--","--","--",">",">",">","x","=","np.array","(","[","[","1",",","1",",","1","]",",","[","1",",","1",",","0","]",",","[","1",",","0",",","1","]","]",")",">",">",">","ph.sign_plot","(","x",",","flat","=","True",")","``","''","''","for","key","in","[","``","cbar","''",",","``","vmin","''",",","``","vmax","''",",","``","center","''","]",":","if","key","in","kwargs",":","del","kwargs","[","key","]","if","isinstance","(","x",",","DataFrame",")",":","df","=","x.copy","(",")","else",":","x","=","np.array","(","x",")","g","=","g","or","np.arange","(","x.shape","[","0","]",")","df","=","DataFrame","(","np.copy","(","x",")",",","index=g",",","columns=g",")","dtype","=","df.values.dtype","if","not","np.issubdtype","(","dtype",",","np.integer",")","and","flat",":","raise","ValueError","(","``","X","should","be","a","sign_array","or","DataFrame","of","integers","''",")","elif","not","np.issubdtype","(","dtype",",","np.floating",")","and","not","flat",":","raise","ValueError","(","``","X","should","be","an","array","or","DataFrame","of","float","p","values","''",")","if","not","cmap","and","flat",":","#","format",":","diagonal",",","non-significant",",","significant","cmap","=","[","``","1","''",",","``","#","fbd7d4","''",",","``","#","1a9641","''","]","elif","not","cmap","and","not","flat",":","#","format",":","diagonal",",","non-significant",",","p","<","0.001",",","p","<","0.01",",","p","<","0.05","cmap","=","[","``","1","''",",","``","#","fbd7d4","''",",","``","#","005a32","''",",","``","#","238b45","''",",","``","#","a1d99b","''","]","if","flat",":","np.fill_diagonal","(","df.values",",","-1",")","hax","=","heatmap","(","df",",","vmin=-1",",","vmax=1",",","cmap=ListedColormap","(","cmap",")",",","cbar=False",",","ax=ax",",","*","*","kwargs",",",")","if","not","labels",":","hax.set_xlabel","(","``","''",")","hax.set_ylabel","(","``","''",")","return","hax","else",":","df","[","(","x","<","0.001",")","&","(","x",">","=","0",")","]","=","1","df","[","(","x","<","0.01",")","&","(","x",">","=","0.001",")","]","=","2","df","[","(","x","<","0.05",")","&","(","x",">","=","0.01",")","]","=","3","df","[","(","x",">","=","0.05",")","]","=","0","np.fill_diagonal","(","df.values",",","-1",")","if","len","(","cmap",")","!","=","5",":","raise","ValueError","(","``","Cmap","list","must","contain","5","items","''",")","hax","=","heatmap","(","df",",","vmin=-1",",","vmax=3",",","cmap=ListedColormap","(","cmap",")",",","center=1",",","cbar=False",",","ax=ax",",","*","*","kwargs",",",")","if","not","labels",":","hax.set_xlabel","(","``","''",")","hax.set_ylabel","(","``","''",")","cbar_ax","=","hax.figure.add_axes","(","cbar_ax_bbox","or","[","0.95",",","0.35",",","0.04",",","0.3","]",")","cbar","=","ColorbarBase","(","cbar_ax",",","cmap=","(","ListedColormap","(","cmap","[","2",":","]","+","[","cmap","[","1","]","]",")",")",",","norm=colors.NoNorm","(",")",",","boundaries=","[","0",",","1",",","2",",","3",",","4","]",",",")","cbar.set_ticks","(","list","(","np.linspace","(","0",",","3",",","4",")",")",",","labels=","[","``","p","<","0.001","''",",","``","p","<","0.01","''",",","``","p","<","0.05","''",",","``","NS","''","]",",",")","cbar.outline.set_linewidth","(","1",")","cbar.outline.set_edgecolor","(","``","0.5","''",")","cbar.ax.tick_params","(","size=0",")","return","hax",",","cbar"] | 118 | 255 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 3 for calling a global function with example usage: sign_plot(x, g, flat, labels, cmap, cbar_ax_bbox, ax) and returns: hax, hax, cbar | 152 | node_id 3 | 1,881,820 |
test_gpt_assistant_existing_no_instructions | global | null | false | null | null | null | null | null | def test_gpt_assistant_existing_no_instructions():
"""
Test function to check if the GPTAssistantAgent can retrieve instructions for an existing assistant
even if the assistant was created with no instructions initially.
"""
name = "For test_gpt_assistant_existing_no_instructions"
instructions = "This is a test #1"
assistant = GPTAssistantAgent(
name,
instructions=instructions,
llm_config={
"config_list": config_list,
},
)
assistant_id = assistant.assistant_id
# create a new assistant with the same ID but no instructions
assistant = GPTAssistantAgent(
name,
llm_config={
"config_list": config_list,
"assistant_id": assistant_id,
},
)
instruction_match = (
assistant.get_assistant_instructions() == instructions
)
assistant.delete_assistant()
assert instruction_match is True
| ["def","test_gpt_assistant_existing_no_instructions","(",")",":","``","''","''","Test","function","to","check","if","the","GPTAssistantAgent","can","retrieve","instructions","for","an","existing","assistant","even","if","the","assistant","was","created","with","no","instructions","initially.","``","''","''","name","=","``","For","test_gpt_assistant_existing_no_instructions","''","instructions","=","``","This","is","a","test","#","1","''","assistant","=","GPTAssistantAgent","(","name",",","instructions=instructions",",","llm_config=","{","``","config_list","''",":","config_list",",","}",",",")","assistant_id","=","assistant.assistant_id","#","create","a","new","assistant","with","the","same","ID","but","no","instructions","assistant","=","GPTAssistantAgent","(","name",",","llm_config=","{","``","config_list","''",":","config_list",",","``","assistant_id","''",":","assistant_id",",","}",",",")","instruction_match","=","(","assistant.get_assistant_instructions","(",")","==","instructions",")","assistant.delete_assistant","(",")","assert","instruction_match","is","True"] | 153 | 182 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 5 for calling a global function with example usage: test_gpt_assistant_existing_no_instructions() without return types | 136 | node_id 5 | 319,270 |
|
test_gpt_assistant_instructions_overwrite | global | null | false | null | null | null | null | null | def test_gpt_assistant_instructions_overwrite():
"""
Test that the instructions of a GPTAssistantAgent can be overwritten or not depending on the value of the
`overwrite_instructions` parameter when creating a new assistant with the same ID.
Steps:
1. Create a new GPTAssistantAgent with some instructions.
2. Get the ID of the assistant.
3. Create a new GPTAssistantAgent with the same ID but different instructions and `overwrite_instructions=True`.
4. Check that the instructions of the assistant have been overwritten with the new ones.
"""
name = "For test_gpt_assistant_instructions_overwrite"
instructions1 = "This is a test #1"
instructions2 = "This is a test #2"
assistant = GPTAssistantAgent(
name,
instructions=instructions1,
llm_config={
"config_list": config_list,
},
)
assistant_id = assistant.assistant_id
assistant = GPTAssistantAgent(
name,
instructions=instructions2,
llm_config={
"config_list": config_list,
"assistant_id": assistant_id,
},
overwrite_instructions=True,
)
instruction_match = (
assistant.get_assistant_instructions() == instructions2
)
assistant.delete_assistant()
assert instruction_match is True
| ["def","test_gpt_assistant_instructions_overwrite","(",")",":","``","''","''","Test","that","the","instructions","of","a","GPTAssistantAgent","can","be","overwritten","or","not","depending","on","the","value","of","the","`","overwrite_instructions","`","parameter","when","creating","a","new","assistant","with","the","same","ID",".","Steps",":","1",".","Create","a","new","GPTAssistantAgent","with","some","instructions",".","2",".","Get","the","ID","of","the","assistant",".","3",".","Create","a","new","GPTAssistantAgent","with","the","same","ID","but","different","instructions","and","`","overwrite_instructions=True","`",".","4",".","Check","that","the","instructions","of","the","assistant","have","been","overwritten","with","the","new","ones.","``","''","''","name","=","``","For","test_gpt_assistant_instructions_overwrite","''","instructions1","=","``","This","is","a","test","#","1","''","instructions2","=","``","This","is","a","test","#","2","''","assistant","=","GPTAssistantAgent","(","name",",","instructions=instructions1",",","llm_config=","{","``","config_list","''",":","config_list",",","}",",",")","assistant_id","=","assistant.assistant_id","assistant","=","GPTAssistantAgent","(","name",",","instructions=instructions2",",","llm_config=","{","``","config_list","''",":","config_list",",","``","assistant_id","''",":","assistant_id",",","}",",","overwrite_instructions=True",",",")","instruction_match","=","(","assistant.get_assistant_instructions","(",")","==","instructions2",")","assistant.delete_assistant","(",")","assert","instruction_match","is","True"] | 108 | 146 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 4 for calling a global function with example usage: test_gpt_assistant_instructions_overwrite() without return types | 134 | node_id 4 | 319,269 |
|
test_get_assistant_instructions | global | null | false | null | null | null | null | null | def test_get_assistant_instructions():
"""
Test function to create a new GPTAssistantAgent, set its instructions, retrieve the instructions,
and assert that the retrieved instructions match the set instructions.
"""
name = "For test_get_assistant_instructions"
assistant = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config={
"config_list": config_list,
},
)
instruction_match = (
assistant.get_assistant_instructions() == "This is a test"
)
assistant.delete_assistant()
assert instruction_match is True
| ["def","test_get_assistant_instructions","(",")",":","``","''","''","Test","function","to","create","a","new","GPTAssistantAgent",",","set","its","instructions",",","retrieve","the","instructions",",","and","assert","that","the","retrieved","instructions","match","the","set","instructions.","``","''","''","name","=","``","For","test_get_assistant_instructions","''","assistant","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=","{","``","config_list","''",":","config_list",",","}",",",")","instruction_match","=","(","assistant.get_assistant_instructions","(",")","==","``","This","is","a","test","''",")","assistant.delete_assistant","(",")","assert","instruction_match","is","True"] | 84 | 101 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 3 for calling a global function with example usage: test_get_assistant_instructions() without return types | 124 | node_id 3 | 319,268 |
|
_find_maximal_cliques | global | null | false | adj_matrix | null | null | null | null | result | def _find_maximal_cliques(adj_matrix: DataFrame) -> List[Set]:
"""Wrapper function over the recursive Bron-Kerbosch algorithm.
Will be used to find points that are under the same crossbar in critical
difference diagrams.
Parameters
----------
adj_matrix : pandas.DataFrame
Binary matrix with 1 if row item and column item do NOT significantly
differ. Values in the main diagonal are not considered.
Returns
-------
list[set]
Largest fully connected subgraphs, represented as sets of indices of
adj_matrix.
Raises
------
ValueError
If the input matrix is empty or not symmetric.
If the input matrix is not binary.
"""
if (adj_matrix.index != adj_matrix.columns).any():
raise ValueError(
"adj_matrix must be symmetric, indices do not match"
)
if not adj_matrix.isin((0, 1)).values.all():
raise ValueError("Input matrix must be binary")
if (
adj_matrix.empty
or not (adj_matrix.T == adj_matrix).values.all()
):
raise ValueError(
"Input matrix must be non-empty and symmetric"
)
result = []
_bron_kerbosch(
current_clique=set(),
candidates=set(adj_matrix.index),
visited=set(),
adj_matrix=adj_matrix,
result=result,
)
return result
| ["def","_find_maximal_cliques","(","adj_matrix",":","DataFrame",")","-",">","List","[","Set","]",":","``","''","''","Wrapper","function","over","the","recursive","Bron-Kerbosch","algorithm",".","Will","be","used","to","find","points","that","are","under","the","same","crossbar","in","critical","difference","diagrams",".","Parameters","--","--","--","--","--","adj_matrix",":","pandas.DataFrame","Binary","matrix","with","1","if","row","item","and","column","item","do","NOT","significantly","differ",".","Values","in","the","main","diagonal","are","not","considered",".","Returns","--","--","--","-","list","[","set","]","Largest","fully","connected","subgraphs",",","represented","as","sets","of","indices","of","adj_matrix",".","Raises","--","--","--","ValueError","If","the","input","matrix","is","empty","or","not","symmetric",".","If","the","input","matrix","is","not","binary.","``","''","''","if","(","adj_matrix.index","!","=","adj_matrix.columns",")",".any","(",")",":","raise","ValueError","(","``","adj_matrix","must","be","symmetric",",","indices","do","not","match","''",")","if","not","adj_matrix.isin","(","(","0",",","1",")",")",".values.all","(",")",":","raise","ValueError","(","``","Input","matrix","must","be","binary","''",")","if","(","adj_matrix.empty","or","not","(","adj_matrix.T","==","adj_matrix",")",".values.all","(",")",")",":","raise","ValueError","(","``","Input","matrix","must","be","non-empty","and","symmetric","''",")","result","=","[","]","_bron_kerbosch","(","current_clique=set","(",")",",","candidates=set","(","adj_matrix.index",")",",","visited=set","(",")",",","adj_matrix=adj_matrix",",","result=result",",",")","return","result"] | 258 | 298 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 4 for calling a global function with example usage: _find_maximal_cliques(adj_matrix) and returns: result | 123 | node_id 4 | 1,881,821 |
_bron_kerbosch | global | null | false | current_clique,candidates,visited,adj_matrix,result | null | null | null | null | null | def _bron_kerbosch(
current_clique: Set,
candidates: Set,
visited: Set,
adj_matrix: DataFrame,
result: List[Set],
) -> None:
"""Recursive algorithm to find the maximal fully connected subgraphs.
See [1]_ for more information.
Parameters
----------
current_clique : set
A set of vertices known to be fully connected.
candidates : set
Set of vertices that could potentially be added to the clique.
visited : set
Set of vertices already known to be part of another previously explored
clique, that is not current_clique.
adj_matrix : pandas.DataFrame
Binary matrix with 1 if row item and column item do NOT significantly
differ. Diagonal must be zeroed.
result : list[set]
List where to append the maximal cliques.
Returns
-------
None
References
----------
.. [1] https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm
"""
while candidates:
v = candidates.pop()
_bron_kerbosch(
current_clique | {v},
# Restrict candidate vertices to the neighbors of v
{n for n in candidates if adj_matrix.loc[v, n]},
# Restrict visited vertices to the neighbors of v
{n for n in visited if adj_matrix.loc[v, n]},
adj_matrix,
result,
)
visited.add(v)
# We do not need to report a clique if a children call aready did it.
if not visited:
# If this is not a terminal call, i.e. if any clique was reported.
result.append(current_clique)
| ["def","_bron_kerbosch","(","current_clique",":","Set",",","candidates",":","Set",",","visited",":","Set",",","adj_matrix",":","DataFrame",",","result",":","List","[","Set","]",",",")","-",">","None",":","``","''","''","Recursive","algorithm","to","find","the","maximal","fully","connected","subgraphs",".","See","[","1","]","_","for","more","information",".","Parameters","--","--","--","--","--","current_clique",":","set","A","set","of","vertices","known","to","be","fully","connected",".","candidates",":","set","Set","of","vertices","that","could","potentially","be","added","to","the","clique",".","visited",":","set","Set","of","vertices","already","known","to","be","part","of","another","previously","explored","clique",",","that","is","not","current_clique",".","adj_matrix",":","pandas.DataFrame","Binary","matrix","with","1","if","row","item","and","column","item","do","NOT","significantly","differ",".","Diagonal","must","be","zeroed",".","result",":","list","[","set","]","List","where","to","append","the","maximal","cliques",".","Returns","--","--","--","-","None","References","--","--","--","--","--","..","[","1","]","https",":","\/\/en.wikipedia.org\/wiki\/Bron","%","E2","%","80","%","93Kerbosch_algorithm","``","''","''","while","candidates",":","v","=","candidates.pop","(",")","_bron_kerbosch","(","current_clique","|","{","v","}",",","#","Restrict","candidate","vertices","to","the","neighbors","of","v","{","n","for","n","in","candidates","if","adj_matrix.loc","[","v",",","n","]","}",",","#","Restrict","visited","vertices","to","the","neighbors","of","v","{","n","for","n","in","visited","if","adj_matrix.loc","[","v",",","n","]","}",",","adj_matrix",",","result",",",")","visited.add","(","v",")","#","We","do","not","need","to","report","a","clique","if","a","children","call","aready","did","it",".","if","not","visited",":","#","If","this","is","not","a","terminal","call",",","i.e",".","if","any","clique","was","reported",".","result.append","(","current_clique",")"] | 301 | 350 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 5 for calling a global function with example usage: _bron_kerbosch(current_clique, candidates, visited, adj_matrix, result) without return types | 162 | node_id 5 | 1,881,822 |
critical_difference_diagram | global | null | false | ranks,sig_matrix | null | null | null | null | dict | def critical_difference_diagram(
ranks: Union[dict, Series],
sig_matrix: DataFrame,
*,
ax: SubplotBase = None,
label_fmt_left: str = "{label} ({rank:.2g})",
label_fmt_right: str = "({rank:.2g}) {label}",
label_props: dict = None,
marker_props: dict = None,
elbow_props: dict = None,
crossbar_props: dict = None,
color_palette: Union[Dict[str, str], List] = {},
text_h_margin: float = 0.01,
) -> Dict[str, list]:
"""Plot a Critical Difference diagram from ranks and post-hoc results.
The diagram arranges the average ranks of multiple groups on the x axis
in order to facilitate performance comparisons between them. The groups
that could not be statistically deemed as different are linked by a
horizontal crossbar [1]_, [2]_.
::
rank markers
X axis ---------O----O-------------------O-O------------O---------
|----| | | |
| | |---crossbar---|
clf1 ----| | | | |---- clf3
clf2 ---------| | |----------------- clf4
|------------------- clf5
|____|
text_h_margin
In the drawing above, the two crossbars indicate that clf1 and clf2 cannot
be statistically differentiated, the same occurring between clf3, clf4 and
clf5. However, clf1 and clf2 are each significantly lower ranked than clf3,
clf4 and clf5.
Parameters
----------
ranks : dict or Series
Indicates the rank value for each sample or estimator (as keys or index).
sig_matrix : DataFrame
The corresponding p-value matrix outputted by post-hoc tests, with
indices matching the labels in the ranks argument.
ax : matplotlib.SubplotBase, optional
The object in which the plot will be built. Gets the current Axes
by default (if None is passed).
label_fmt_left : str, optional
The format string to apply to the labels on the left side. The keywords
label and rank can be used to specify the sample/estimator name and
rank value, respectively, by default '{label} ({rank:.2g})'.
label_fmt_right : str, optional
The same, but for the labels on the right side of the plot.
By default '({rank:.2g}) {label}'.
label_props : dict, optional
Parameters to be passed to pyplot.text() when creating the labels,
by default None.
marker_props : dict, optional
Parameters to be passed to pyplot.scatter() when plotting the rank
markers on the axis, by default None.
elbow_props : dict, optional
Parameters to be passed to pyplot.plot() when creating the elbow lines,
by default None.
crossbar_props : dict, optional
Parameters to be passed to pyplot.plot() when creating the crossbars
that indicate lack of statistically significant difference. By default
None.
text_h_margin : float, optional
Space between the text labels and the nearest vertical line of an
elbow, by default 0.01.
color_palette: dict, optional
Parameters to be passed when you need specific colors for each category
Returns
-------
dict[str, list[matplotlib.Artist]]
Lists of Artists created.
Examples
--------
See the :doc:`/tutorial`.
References
----------
.. [1] Demšar, J. (2006). Statistical comparisons of classifiers over multiple
data sets. The Journal of Machine learning research, 7, 1-30.
.. [2] https://mirkobunse.github.io/CriticalDifferenceDiagrams.jl/stable/
"""
## check color_palette consistency
if len(color_palette) == 0:
pass
elif isinstance(color_palette, Dict) and (
(len(set(ranks.keys()) & set(color_palette.keys())))
== len(ranks)
):
pass
elif isinstance(color_palette, List) and (
len(ranks) <= len(color_palette)
):
pass
else:
raise ValueError(
"color_palette keys are not consistent, or list size too small"
)
elbow_props = elbow_props or {}
marker_props = {"zorder": 3, **(marker_props or {})}
label_props = {"va": "center", **(label_props or {})}
crossbar_props = {
"color": "k",
"zorder": 3,
"linewidth": 2,
**(crossbar_props or {}),
}
ax = ax or pyplot.gca()
ax.yaxis.set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.xaxis.set_ticks_position("top")
ax.spines["top"].set_position("zero")
# lists of artists to be returned
markers = []
elbows = []
labels = []
crossbars = []
# True if pairwise comparison is NOT significant
adj_matrix = DataFrame(
1 - sign_array(sig_matrix),
index=sig_matrix.index,
columns=sig_matrix.columns,
dtype=bool,
)
ranks = Series(ranks) # Standardize if ranks is dict
points_left, points_right = np.array_split(ranks.sort_values(), 2)
# Sets of points under the same crossbar
crossbar_sets = _find_maximal_cliques(adj_matrix)
# Sort by lowest rank and filter single-valued sets
crossbar_sets = sorted(
(x for x in crossbar_sets if len(x) > 1),
key=lambda x: ranks[list(x)].min(),
)
# Create stacking of crossbars: for each level, try to fit the crossbar,
# so that it does not intersect with any other in the level. If it does not
# fit in any level, create a new level for it.
crossbar_levels: list[list[set]] = []
for bar in crossbar_sets:
for level, bars_in_level in enumerate(crossbar_levels):
if not any(
bool(bar & bar_in_lvl) for bar_in_lvl in bars_in_level
):
ypos = -level - 1
bars_in_level.append(bar)
break
else:
ypos = -len(crossbar_levels) - 1
crossbar_levels.append([bar])
crossbars.append(
ax.plot(
# Adding a separate line between each pair enables showing a
# marker over each elbow with crossbar_props={'marker': 'o'}.
[ranks[i] for i in bar],
[ypos] * len(bar),
**crossbar_props,
)
)
lowest_crossbar_ypos = -len(crossbar_levels)
def plot_items(
points, xpos, label_fmt, color_palette, label_props
):
"""Plot each marker + elbow + label."""
ypos = lowest_crossbar_ypos - 1
for idx, (label, rank) in enumerate(points.items()):
if len(color_palette) == 0:
elbow, *_ = ax.plot(
[xpos, rank, rank],
[ypos, ypos, 0],
**elbow_props,
)
else:
elbow, *_ = ax.plot(
[xpos, rank, rank],
[ypos, ypos, 0],
c=color_palette[label]
if isinstance(color_palette, Dict)
else color_palette[idx],
**elbow_props,
)
elbows.append(elbow)
curr_color = elbow.get_color()
markers.append(
ax.scatter(
rank, 0, **{"color": curr_color, **marker_props}
)
)
labels.append(
ax.text(
xpos,
ypos,
label_fmt.format(label=label, rank=rank),
**{"color": curr_color, **label_props},
)
)
ypos -= 1
plot_items(
points_left,
xpos=points_left.iloc[0] - text_h_margin,
label_fmt=label_fmt_left,
color_palette=color_palette,
label_props={
"ha": "right",
**label_props,
},
)
plot_items(
points_right[::-1],
xpos=points_right.iloc[-1] + text_h_margin,
label_fmt=label_fmt_right,
color_palette=color_palette,
label_props={"ha": "left", **label_props},
)
return {
"markers": markers,
"elbows": elbows,
"labels": labels,
"crossbars": crossbars,
}
| ["def","critical_difference_diagram","(","ranks",":","Union","[","dict",",","Series","]",",","sig_matrix",":","DataFrame",",","*",",","ax",":","SubplotBase","=","None",",","label_fmt_left",":","str","=","``","{","label","}","(","{","rank",":",".2g","}",")","''",",","label_fmt_right",":","str","=","``","(","{","rank",":",".2g","}",")","{","label","}","''",",","label_props",":","dict","=","None",",","marker_props",":","dict","=","None",",","elbow_props",":","dict","=","None",",","crossbar_props",":","dict","=","None",",","color_palette",":","Union","[","Dict","[","str",",","str","]",",","List","]","=","{","}",",","text_h_margin",":","float","=","0.01",",",")","-",">","Dict","[","str",",","list","]",":","``","''","''","Plot","a","Critical","Difference","diagram","from","ranks","and","post-hoc","results",".","The","diagram","arranges","the","average","ranks","of","multiple","groups","on","the","x","axis","in","order","to","facilitate","performance","comparisons","between","them",".","The","groups","that","could","not","be","statistically","deemed","as","different","are","linked","by","a","horizontal","crossbar","[","1","]","_",",","[","2","]","_.",":",":","rank","markers","X","axis","--","--","--","--","-O","--","--","O","--","--","--","--","--","--","--","--","--","-O-O","--","--","--","--","--","--","O","--","--","--","--","-","|","--","--","|","|","|","|","|","|","|","--","-crossbar","--","-|","clf1","--","--","|","|","|","|","|","--","--","clf3","clf2","--","--","--","--","-|","|","|","--","--","--","--","--","--","--","--","-","clf4","|","--","--","--","--","--","--","--","--","--","-","clf5","|____|","text_h_margin","In","the","drawing","above",",","the","two","crossbars","indicate","that","clf1","and","clf2","can","not","be","statistically","differentiated",",","the","same","occurring","between","clf3",",","clf4","and","clf5",".","However",",","clf1","and","clf2","are","each","significantly","lower","ranked","than","clf3",",","clf4","and","clf5",".","Parameters","--","--","--","--","--","ranks",":","dict","or","Series","Indicates","the","rank","value","for","each","sample","or","estimator","(","as","keys","or","index",")",".","sig_matrix",":","DataFrame","The","corresponding","p-value","matrix","outputted","by","post-hoc","tests",",","with","indices","matching","the","labels","in","the","ranks","argument",".","ax",":","matplotlib.SubplotBase",",","optional","The","object","in","which","the","plot","will","be","built",".","Gets","the","current","Axes","by","default","(","if","None","is","passed",")",".","label_fmt_left",":","str",",","optional","The","format","string","to","apply","to","the","labels","on","the","left","side",".","The","keywords","label","and","rank","can","be","used","to","specify","the","sample\/estimator","name","and","rank","value",",","respectively",",","by","default","'","{","label","}","(","{","rank",":",".2g","}",")","'",".","label_fmt_right",":","str",",","optional","The","same",",","but","for","the","labels","on","the","right","side","of","the","plot",".","By","default","'","(","{","rank",":",".2g","}",")","{","label","}","'",".","label_props",":","dict",",","optional","Parameters","to","be","passed","to","pyplot.text","(",")","when","creating","the","labels",",","by","default","None",".","marker_props",":","dict",",","optional","Parameters","to","be","passed","to","pyplot.scatter","(",")","when","plotting","the","rank","markers","on","the","axis",",","by","default","None",".","elbow_props",":","dict",",","optional","Parameters","to","be","passed","to","pyplot.plot","(",")","when","creating","the","elbow","lines",",","by","default","None",".","crossbar_props",":","dict",",","optional","Parameters","to","be","passed","to","pyplot.plot","(",")","when","creating","the","crossbars","that","indicate","lack","of","statistically","significant","difference",".","By","default","None",".","text_h_margin",":","float",",","optional","Space","between","the","text","labels","and","the","nearest","vertical","line","of","an","elbow",",","by","default","0.01.","color_palette",":","dict",",","optional","Parameters","to","be","passed","when","you","need","specific","colors","for","each","category","Returns","--","--","--","-","dict","[","str",",","list","[","matplotlib.Artist","]","]","Lists","of","Artists","created",".","Examples","--","--","--","--","See","the",":","doc",":","`","\/tutorial","`",".","References","--","--","--","--","--","..","[","1","]","Dem\u0161ar",",","J",".","(","2006",")",".","Statistical","comparisons","of","classifiers","over","multiple","data","sets",".","The","Journal","of","Machine","learning","research",",","7",",","1-30",".","..","[","2","]","https",":","\/\/mirkobunse.github.io\/CriticalDifferenceDiagrams.jl\/stable\/","``","''","''","#","#","check","color_palette","consistency","if","len","(","color_palette",")","==","0",":","pass","elif","isinstance","(","color_palette",",","Dict",")","and","(","(","len","(","set","(","ranks.keys","(",")",")","&","set","(","color_palette.keys","(",")",")",")",")","==","len","(","ranks",")",")",":","pass","elif","isinstance","(","color_palette",",","List",")","and","(","len","(","ranks",")","<","=","len","(","color_palette",")",")",":","pass","else",":","raise","ValueError","(","``","color_palette","keys","are","not","consistent",",","or","list","size","too","small","''",")","elbow_props","=","elbow_props","or","{","}","marker_props","=","{","``","zorder","''",":","3",",","*","*","(","marker_props","or","{","}",")","}","label_props","=","{","``","va","''",":","``","center","''",",","*","*","(","label_props","or","{","}",")","}","crossbar_props","=","{","``","color","''",":","``","k","''",",","``","zorder","''",":","3",",","``","linewidth","''",":","2",",","*","*","(","crossbar_props","or","{","}",")",",","}","ax","=","ax","or","pyplot.gca","(",")","ax.yaxis.set_visible","(","False",")","ax.spines","[","``","right","''","]",".set_visible","(","False",")","ax.spines","[","``","left","''","]",".set_visible","(","False",")","ax.spines","[","``","bottom","''","]",".set_visible","(","False",")","ax.xaxis.set_ticks_position","(","``","top","''",")","ax.spines","[","``","top","''","]",".set_position","(","``","zero","''",")","#","lists","of","artists","to","be","returned","markers","=","[","]","elbows","=","[","]","labels","=","[","]","crossbars","=","[","]","#","True","if","pairwise","comparison","is","NOT","significant","adj_matrix","=","DataFrame","(","1","-","sign_array","(","sig_matrix",")",",","index=sig_matrix.index",",","columns=sig_matrix.columns",",","dtype=bool",",",")","ranks","=","Series","(","ranks",")","#","Standardize","if","ranks","is","dict","points_left",",","points_right","=","np.array_split","(","ranks.sort_values","(",")",",","2",")","#","Sets","of","points","under","the","same","crossbar","crossbar_sets","=","_find_maximal_cliques","(","adj_matrix",")","#","Sort","by","lowest","rank","and","filter","single-valued","sets","crossbar_sets","=","sorted","(","(","x","for","x","in","crossbar_sets","if","len","(","x",")",">","1",")",",","key=lambda","x",":","ranks","[","list","(","x",")","]",".min","(",")",",",")","#","Create","stacking","of","crossbars",":","for","each","level",",","try","to","fit","the","crossbar",",","#","so","that","it","does","not","intersect","with","any","other","in","the","level",".","If","it","does","not","#","fit","in","any","level",",","create","a","new","level","for","it",".","crossbar_levels",":","list","[","list","[","set","]","]","=","[","]","for","bar","in","crossbar_sets",":","for","level",",","bars_in_level","in","enumerate","(","crossbar_levels",")",":","if","not","any","(","bool","(","bar","&","bar_in_lvl",")","for","bar_in_lvl","in","bars_in_level",")",":","ypos","=","-level","-","1","bars_in_level.append","(","bar",")","break","else",":","ypos","=","-len","(","crossbar_levels",")","-","1","crossbar_levels.append","(","[","bar","]",")","crossbars.append","(","ax.plot","(","#","Adding","a","separate","line","between","each","pair","enables","showing","a","#","marker","over","each","elbow","with","crossbar_props=","{","'marker","'",":","'","o","'","}",".","[","ranks","[","i","]","for","i","in","bar","]",",","[","ypos","]","*","len","(","bar",")",",","*","*","crossbar_props",",",")",")","lowest_crossbar_ypos","=","-len","(","crossbar_levels",")","def","plot_items","(","points",",","xpos",",","label_fmt",",","color_palette",",","label_props",")",":","``","''","''","Plot","each","marker","+","elbow","+","label",".","''","''","''","ypos","=","lowest_crossbar_ypos","-","1","for","idx",",","(","label",",","rank",")","in","enumerate","(","points.items","(",")",")",":","if","len","(","color_palette",")","==","0",":","elbow",",","*","_","=","ax.plot","(","[","xpos",",","rank",",","rank","]",",","[","ypos",",","ypos",",","0","]",",","*","*","elbow_props",",",")","else",":","elbow",",","*","_","=","ax.plot","(","[","xpos",",","rank",",","rank","]",",","[","ypos",",","ypos",",","0","]",",","c=color_palette","[","label","]","if","isinstance","(","color_palette",",","Dict",")","else","color_palette","[","idx","]",",","*","*","elbow_props",",",")","elbows.append","(","elbow",")","curr_color","=","elbow.get_color","(",")","markers.append","(","ax.scatter","(","rank",",","0",",","*","*","{","``","color","''",":","curr_color",",","*","*","marker_props","}",")",")","labels.append","(","ax.text","(","xpos",",","ypos",",","label_fmt.format","(","label=label",",","rank=rank",")",",","*","*","{","``","color","''",":","curr_color",",","*","*","label_props","}",",",")",")","ypos","-=","1","plot_items","(","points_left",",","xpos=points_left.iloc","[","0","]","-","text_h_margin",",","label_fmt=label_fmt_left",",","color_palette=color_palette",",","label_props=","{","``","ha","''",":","``","right","''",",","*","*","label_props",",","}",",",")","plot_items","(","points_right","[",":",":-1","]",",","xpos=points_right.iloc","[","-1","]","+","text_h_margin",",","label_fmt=label_fmt_right",",","color_palette=color_palette",",","label_props=","{","``","ha","''",":","``","left","''",",","*","*","label_props","}",",",")","return","{","``","markers","''",":","markers",",","``","elbows","''",":","elbows",",","``","labels","''",":","labels",",","``","crossbars","''",":","crossbars",",","}"] | 353 | 579 | null | _plotting.py | scikit-posthocs/scikit_posthocs/_plotting.py | from typing import Union, List, Tuple, Dict, Set
import numpy
from matplotlib import colors
from matplotlib.axes import SubplotBase
from matplotlib.colorbar import ColorbarBase, Colorbar
from matplotlib.colors import ListedColormap
from matplotlib import pyplot
from pandas import DataFrame, Series
from seaborn import heatmap | 15 | null | 9 | 6 | null | null | null | Use image node_id 6 for calling a global function with example usage: critical_difference_diagram(ranks, sig_matrix) and returns: dict | 134 | node_id 6 | 1,881,823 |
__init__ | PSERandomCrop | null | true | self,size | null | null | null | null | PSERandomCrop | def __init__(self, size):
self.size = size
| ["def","__init__","(","self",",","size",")",":","self.size","=","size"] | 164 | 165 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 2 | null | Use image node_id 1 to create a new PSERandomCrop object with example: obj = PSERandomCrop(size) | 97 | node_id 1 | 176,895 |
crop_area | EastRandomCropData | null | true | self,im,text_polys | null | null | null | null | int, int, w, h,int, int, w, h,xmin, ymin, unknown, unknown | def crop_area(self, im, text_polys):
h, w = im.shape[:2]
h_array = np.zeros(h, dtype=np.int32)
w_array = np.zeros(w, dtype=np.int32)
for points in text_polys:
points = np.round(points, decimals=0).astype(np.int32)
minx = np.min(points[:, 0])
maxx = np.max(points[:, 0])
w_array[minx:maxx] = 1
miny = np.min(points[:, 1])
maxy = np.max(points[:, 1])
h_array[miny:maxy] = 1
# ensure the cropped area not across a text
h_axis = np.where(h_array == 0)[0]
w_axis = np.where(w_array == 0)[0]
if len(h_axis) == 0 or len(w_axis) == 0:
return 0, 0, w, h
h_regions = self.split_regions(h_axis)
w_regions = self.split_regions(w_axis)
for i in range(self.max_tries):
if len(w_regions) > 1:
xmin, xmax = self.region_wise_random_select(w_regions, w)
else:
xmin, xmax = self.random_select(w_axis, w)
if len(h_regions) > 1:
ymin, ymax = self.region_wise_random_select(h_regions, h)
else:
ymin, ymax = self.random_select(h_axis, h)
if (
xmax - xmin < self.min_crop_side_ratio * w
or ymax - ymin < self.min_crop_side_ratio * h
):
# area too small
continue
num_poly_in_rect = 0
for poly in text_polys:
if not self.is_poly_outside_rect(
poly, xmin, ymin, xmax - xmin, ymax - ymin
):
num_poly_in_rect += 1
break
if num_poly_in_rect > 0:
return xmin, ymin, xmax - xmin, ymax - ymin
return 0, 0, w, h
| ["def","crop_area","(","self",",","im",",","text_polys",")",":","h",",","w","=","im.shape","[",":2","]","h_array","=","np.zeros","(","h",",","dtype=np.int32",")","w_array","=","np.zeros","(","w",",","dtype=np.int32",")","for","points","in","text_polys",":","points","=","np.round","(","points",",","decimals=0",")",".astype","(","np.int32",")","minx","=","np.min","(","points","[",":",",","0","]",")","maxx","=","np.max","(","points","[",":",",","0","]",")","w_array","[","minx",":","maxx","]","=","1","miny","=","np.min","(","points","[",":",",","1","]",")","maxy","=","np.max","(","points","[",":",",","1","]",")","h_array","[","miny",":","maxy","]","=","1","#","ensure","the","cropped","area","not","across","a","text","h_axis","=","np.where","(","h_array","==","0",")","[","0","]","w_axis","=","np.where","(","w_array","==","0",")","[","0","]","if","len","(","h_axis",")","==","0","or","len","(","w_axis",")","==","0",":","return","0",",","0",",","w",",","h","h_regions","=","self.split_regions","(","h_axis",")","w_regions","=","self.split_regions","(","w_axis",")","for","i","in","range","(","self.max_tries",")",":","if","len","(","w_regions",")",">","1",":","xmin",",","xmax","=","self.region_wise_random_select","(","w_regions",",","w",")","else",":","xmin",",","xmax","=","self.random_select","(","w_axis",",","w",")","if","len","(","h_regions",")",">","1",":","ymin",",","ymax","=","self.region_wise_random_select","(","h_regions",",","h",")","else",":","ymin",",","ymax","=","self.random_select","(","h_axis",",","h",")","if","(","xmax","-","xmin","<","self.min_crop_side_ratio","*","w","or","ymax","-","ymin","<","self.min_crop_side_ratio","*","h",")",":","#","area","too","small","continue","num_poly_in_rect","=","0","for","poly","in","text_polys",":","if","not","self.is_poly_outside_rect","(","poly",",","xmin",",","ymin",",","xmax","-","xmin",",","ymax","-","ymin",")",":","num_poly_in_rect","+=","1","break","if","num_poly_in_rect",">","0",":","return","xmin",",","ymin",",","xmax","-","xmin",",","ymax","-","ymin","return","0",",","0",",","w",",","h"] | 115 | 160 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 8 | null | Use image node_id 8 for calling the EastRandomCropData obj's underlying member method code with example usage: obj.crop_area(im, text_polys) and returns: int, int, w, h, int, int, w, h, xmin, ymin, unknown, unknown | 223 | node_id 8 | 176,894 |
region_wise_random_select | EastRandomCropData | null | true | self,regions,max_size | null | null | null | null | xmin, xmax | def region_wise_random_select(self, regions, max_size):
selected_index = list(np.random.choice(len(regions), 2))
selected_values = []
for index in selected_index:
axis = regions[index]
xx = int(np.random.choice(axis, size=1))
selected_values.append(xx)
xmin = min(selected_values)
xmax = max(selected_values)
return xmin, xmax
| ["def","region_wise_random_select","(","self",",","regions",",","max_size",")",":","selected_index","=","list","(","np.random.choice","(","len","(","regions",")",",","2",")",")","selected_values","=","[","]","for","index","in","selected_index",":","axis","=","regions","[","index","]","xx","=","int","(","np.random.choice","(","axis",",","size=1",")",")","selected_values.append","(","xx",")","xmin","=","min","(","selected_values",")","xmax","=","max","(","selected_values",")","return","xmin",",","xmax"] | 104 | 113 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 8 | null | Use image node_id 7 for calling the EastRandomCropData obj's underlying member method code with example usage: obj.region_wise_random_select(regions, max_size) and returns: xmin, xmax | 184 | node_id 7 | 176,893 |
random_select | EastRandomCropData | null | true | self,axis,max_size | null | null | null | null | xmin, xmax | def random_select(self, axis, max_size):
xx = np.random.choice(axis, size=2)
xmin = np.min(xx)
xmax = np.max(xx)
xmin = np.clip(xmin, 0, max_size - 1)
xmax = np.clip(xmax, 0, max_size - 1)
return xmin, xmax
| ["def","random_select","(","self",",","axis",",","max_size",")",":","xx","=","np.random.choice","(","axis",",","size=2",")","xmin","=","np.min","(","xx",")","xmax","=","np.max","(","xx",")","xmin","=","np.clip","(","xmin",",","0",",","max_size","-","1",")","xmax","=","np.clip","(","xmax",",","0",",","max_size","-","1",")","return","xmin",",","xmax"] | 96 | 102 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 8 | null | Use image node_id 6 for calling the EastRandomCropData obj's underlying member method code with example usage: obj.random_select(axis, max_size) and returns: xmin, xmax | 169 | node_id 6 | 176,892 |
split_regions | EastRandomCropData | null | true | self,axis | null | null | null | null | regions | def split_regions(self, axis):
regions = []
min_axis = 0
for i in range(1, axis.shape[0]):
if axis[i] != axis[i - 1] + 1:
region = axis[min_axis:i]
min_axis = i
regions.append(region)
return regions
| ["def","split_regions","(","self",",","axis",")",":","regions","=","[","]","min_axis","=","0","for","i","in","range","(","1",",","axis.shape","[","0","]",")",":","if","axis","[","i","]","!","=","axis","[","i","-","1","]","+","1",":","region","=","axis","[","min_axis",":","i","]","min_axis","=","i","regions.append","(","region",")","return","regions"] | 86 | 94 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 8 | null | Use image node_id 5 for calling the EastRandomCropData obj's underlying member method code with example usage: obj.split_regions(axis) and returns: regions | 155 | node_id 5 | 176,891 |
is_poly_outside_rect | EastRandomCropData | null | true | self,poly,x,y,w,h | null | null | null | null | False,True,True | def is_poly_outside_rect(self, poly, x, y, w, h):
poly = np.array(poly)
if poly[:, 0].max() < x or poly[:, 0].min() > x + w:
return True
if poly[:, 1].max() < y or poly[:, 1].min() > y + h:
return True
return False
| ["def","is_poly_outside_rect","(","self",",","poly",",","x",",","y",",","w",",","h",")",":","poly","=","np.array","(","poly",")","if","poly","[",":",",","0","]",".max","(",")","<","x","or","poly","[",":",",","0","]",".min","(",")",">","x","+","w",":","return","True","if","poly","[",":",",","1","]",".max","(",")","<","y","or","poly","[",":",",","1","]",".min","(",")",">","y","+","h",":","return","True","return","False"] | 78 | 84 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 8 | null | Use image node_id 4 for calling the EastRandomCropData obj's underlying member method code with example usage: obj.is_poly_outside_rect(poly, x, y, w, h) and returns: False, True, True | 184 | node_id 4 | 176,890 |
on_response | RerankModelPlugin | Plugin | true | self,response,db_row | Base class for reranker models | ["Base","class","for","reranker","models"] | null | null | null | def on_response(
self, response: ResponseDelegate, db_row: DatabaseRow
):
if response.request.rerank_cids:
db_row.server_mrr = calculate_mrr(
correct=response.request.rerank_cids.list,
guesses=response.cids,
)
start_time = time.perf_counter()
ranks, scores = self.rank(
query=response.request.query,
choices=response.cvalues,
filter_results=response.request.filter_results,
)
db_row.rerank_time = time.perf_counter() - start_time
# remove ranks which are higher than total choices
ranks = [rank for rank in ranks if rank < len(response.choices)]
reranked_choices = [response.choices[rank] for rank in ranks]
response.choices = reranked_choices
response.set_path(
"body.nboost.scores", list([float(score) for score in scores])
)
if response.request.rerank_cids:
db_row.model_mrr = calculate_mrr(
correct=response.request.rerank_cids.list,
guesses=response.cids,
)
response.choices = response.choices[: db_row.topk]
| ["def","on_response","(","self",",","response",":","ResponseDelegate",",","db_row",":","DatabaseRow",")",":","if","response.request.rerank_cids",":","db_row.server_mrr","=","calculate_mrr","(","correct=response.request.rerank_cids.list",",","guesses=response.cids",",",")","start_time","=","time.perf_counter","(",")","ranks",",","scores","=","self.rank","(","query=response.request.query",",","choices=response.cvalues",",","filter_results=response.request.filter_results",",",")","db_row.rerank_time","=","time.perf_counter","(",")","-","start_time","#","remove","ranks","which","are","higher","than","total","choices","ranks","=","[","rank","for","rank","in","ranks","if","rank","<","len","(","response.choices",")","]","reranked_choices","=","[","response.choices","[","rank","]","for","rank","in","ranks","]","response.choices","=","reranked_choices","response.set_path","(","``","body.nboost.scores","''",",","list","(","[","float","(","score",")","for","score","in","scores","]",")",")","if","response.request.rerank_cids",":","db_row.model_mrr","=","calculate_mrr","(","correct=response.request.rerank_cids.list",",","guesses=response.cids",",",")","response.choices","=","response.choices","[",":","db_row.topk","]"] | 21 | 51 | null | base.py | nboost/nboost/plugins/rerank/base.py | from typing import List, Tuple
import time
from nboost.plugins import Plugin
from nboost.delegates import RequestDelegate, ResponseDelegate
from nboost.helpers import calculate_mrr
from nboost.database import DatabaseRow
from nboost import defaults
import numpy | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 2 for calling the RerankModelPlugin obj's underlying member method code with example usage: obj.on_response(response, db_row) without return types | 164 | node_id 2 | 1,408,508 |
_check_metrics | DecisionTreeRegressorBostonHousingScikitNumericTest | unittest | true | self,metrics,params | Unit test class for testing scikit-learn converter and running both models | ["Unit","test","class","for","testing","scikit-learn","converter","and","running","both","models"] | Check the metrics | ["Check","the","metrics"] | null | def _check_metrics(self, metrics, params={}):
"""
Check the metrics
"""
self.assertAlmostEquals(
metrics["rmse"],
0,
delta=1e-5,
msg="Failed case %s. Results %s" % (params, metrics),
)
self.assertAlmostEquals(
metrics["max_error"],
0,
delta=1e-5,
msg="Failed case %s. Results %s" % (params, metrics),
)
| ["def","_check_metrics","(","self",",","metrics",",","params=","{","}",")",":","``","''","''","Check","the","metrics","``","''","''","self.assertAlmostEquals","(","metrics","[","``","rmse","''","]",",","0",",","delta=1e-5",",","msg=","''","Failed","case","%","s",".","Results","%","s","''","%","(","params",",","metrics",")",",",")","self.assertAlmostEquals","(","metrics","[","``","max_error","''","]",",","0",",","delta=1e-5",",","msg=","''","Failed","case","%","s",".","Results","%","s","''","%","(","params",",","metrics",")",",",")"] | 42 | 57 | null | test_decision_tree_regression_numeric.py | turicreate/src/external/coremltools_wrap/coremltools/coremltools/test/xgboost_tests/test_decision_tree_regression_numeric.py | import unittest
from coremltools.converters import sklearn
from coremltools.models.utils import evaluate_regressor
import pandas
import os
from coremltools.models.utils import evaluate_regressor, _macos_version, _is_macos
from coremltools._deps import _HAS_SKLEARN
import pytest | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 2 for calling the DecisionTreeRegressorBostonHousingScikitNumericTest obj's underlying member method code with example usage: obj._check_metrics(metrics, params) without return types | 200 | node_id 2 | 2,281,187 |
dirichlet | global | null | false | null | null | null | null | jax | def dirichlet(
alpha: Union[JaxArray, float, Sequence[float]],
/,
*,
size: Optional[Union[ivy.NativeShape, Sequence[int]]] = None,
dtype: Optional[jnp.dtype] = None,
seed: Optional[int] = None,
out: Optional[JaxArray] = None,
) -> JaxArray:
if seed is not None:
rng_input = jax.random.PRNGKey(seed)
else:
RNG_, rng_input = jax.random.split(_getRNG())
_setRNG(RNG_)
return jax.random.dirichlet(
rng_input, alpha, shape=size, dtype=dtype
)
| ["def","dirichlet","(","alpha",":","Union","[","JaxArray",",","float",",","Sequence","[","float","]","]",",","\/",",","*",",","size",":","Optional","[","Union","[","ivy.NativeShape",",","Sequence","[","int","]","]","]","=","None",",","dtype",":","Optional","[","jnp.dtype","]","=","None",",","seed",":","Optional","[","int","]","=","None",",","out",":","Optional","[","JaxArray","]","=","None",",",")","-",">","JaxArray",":","if","seed","is","not","None",":","rng_input","=","jax.random.PRNGKey","(","seed",")","else",":","RNG_",",","rng_input","=","jax.random.split","(","_getRNG","(",")",")","_setRNG","(","RNG_",")","return","jax.random.dirichlet","(","rng_input",",","alpha",",","shape=size",",","dtype=dtype",")"] | 23 | 37 | null | random.py | ivy/ivy/functional/backends/jax/experimental/random.py | from typing import Optional, Union, Sequence
import jax.numpy
import jax
import jaxlib.xla_extension
import ivy
from ivy.functional.backends.jax import JaxArray
from ivy.functional.backends.jax.random import RNG, _setRNG, _getRNG
from ivy.functional.ivy.random import _check_bounds_and_get_shape, _check_shapes_broadcastable
from ivy.func_wrapper import with_unsupported_dtypes
from ..None import backend_version | 15 | null | 10 | 5 | null | null | null | Use image node_id 1 for calling a global function with example usage: dirichlet() and returns: jax | 98 | node_id 1 | 1,194,964 |
|
beta | global | null | false | null | null | null | null | jax | def beta(
a: Union[float, JaxArray],
b: Union[float, JaxArray],
/,
*,
shape: Optional[Union[ivy.NativeShape, Sequence[int]]] = None,
device: Optional[jaxlib.xla_extension.Device] = None,
dtype: Optional[jnp.dtype] = None,
seed: Optional[int] = None,
out: Optional[JaxArray] = None,
) -> JaxArray:
shape = _check_bounds_and_get_shape(a, b, shape).shape
RNG_, rng_input = jax.random.split(_getRNG())
_setRNG(RNG_)
if seed is not None:
jax.random.PRNGKey(seed)
return jax.random.beta(rng_input, a, b, shape, dtype)
| ["def","beta","(","a",":","Union","[","float",",","JaxArray","]",",","b",":","Union","[","float",",","JaxArray","]",",","\/",",","*",",","shape",":","Optional","[","Union","[","ivy.NativeShape",",","Sequence","[","int","]","]","]","=","None",",","device",":","Optional","[","jaxlib.xla_extension.Device","]","=","None",",","dtype",":","Optional","[","jnp.dtype","]","=","None",",","seed",":","Optional","[","int","]","=","None",",","out",":","Optional","[","JaxArray","]","=","None",",",")","-",">","JaxArray",":","shape","=","_check_bounds_and_get_shape","(","a",",","b",",","shape",")",".shape","RNG_",",","rng_input","=","jax.random.split","(","_getRNG","(",")",")","_setRNG","(","RNG_",")","if","seed","is","not","None",":","jax.random.PRNGKey","(","seed",")","return","jax.random.beta","(","rng_input",",","a",",","b",",","shape",",","dtype",")"] | 40 | 56 | null | random.py | ivy/ivy/functional/backends/jax/experimental/random.py | from typing import Optional, Union, Sequence
import jax.numpy
import jax
import jaxlib.xla_extension
import ivy
from ivy.functional.backends.jax import JaxArray
from ivy.functional.backends.jax.random import RNG, _setRNG, _getRNG
from ivy.functional.ivy.random import _check_bounds_and_get_shape, _check_shapes_broadcastable
from ivy.func_wrapper import with_unsupported_dtypes
from ..None import backend_version | 15 | null | 10 | 5 | null | null | null | Use image node_id 2 for calling a global function with example usage: beta() and returns: jax | 93 | node_id 2 | 1,194,965 |
|
CostFactory | Circle | AbstractModel | true | self,target,npts | Computes 2D array representation of a circle
where the circle minimally bounds the 2D data points
data points with [minimal, sparse, or dense] packing=[~0.2, ~1.0, or ~5.0]
setting packing = None will constrain all points to the circle's radius | ["Computes","2D","array","representation","of","a","circle","where","the","circle","minimally","bounds","the","2D","data","points","data","points","with","[","minimal",",","sparse",",","or","dense","]","packing=","[","~0.2",",","~1.0",",","or","~5.0","]","setting","packing","=","None","will","constrain","all","points","to","the","circle","'s","radius"] | generate a cost function from target coefficients
Args:
target (list[float]): (x, y, and radius) defining the target circle
npts (int, default=None): number of points to generate
Returns:
a function returning cost of minimum enclosing circle for npts
Notes:
default ``npts`` is ``packing * floor(pi * radius**2)``
| ["generate","a","cost","function","from","target","coefficients","Args",":","target","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","the","target","circle","npts","(","int",",","default=None",")",":","number","of","points","to","generate","Returns",":","a","function","returning","cost","of","minimum","enclosing","circle","for","npts","Notes",":","default","``","npts","``","is","``","packing","*","floor","(","pi","*","radius","*","*","2",")","``"] | self,unknown,unknown | def CostFactory(self, target, npts=None):
"""generate a cost function from target coefficients
Args:
target (list[float]): (x, y, and radius) defining the target circle
npts (int, default=None): number of points to generate
Returns:
a function returning cost of minimum enclosing circle for npts
Notes:
default ``npts`` is ``packing * floor(pi * radius**2)``
"""
datapts = self.forward(target, npts)
def cost(params):
"""cost of minimum enclosing circle for a 2D set of points
Args:
params (list[float]): (x, y, and radius) defining a circle
Returns:
a float representing radius and number of points outside the circle
Notes:
fit to points generated on the circle defined by (x,y,r) = (%s,%s,%s)
""" % (
target[0],
target[1],
target[2],
)
x, y, r = params
if r < 0:
return -999.0 * r
penalty = 0
for xx, yy in datapts:
# compute distance to origin
d = sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y))
if d > r:
# each violation adds 1 to the cost plus amount of violation
penalty += 1 + d - r
return self.__sigma__ * (r + penalty)
self.__cost__ = cost
return self.__cost__
| ["def","CostFactory","(","self",",","target",",","npts=None",")",":","``","''","''","generate","a","cost","function","from","target","coefficients","Args",":","target","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","the","target","circle","npts","(","int",",","default=None",")",":","number","of","points","to","generate","Returns",":","a","function","returning","cost","of","minimum","enclosing","circle","for","npts","Notes",":","default","``","npts","``","is","``","packing","*","floor","(","pi","*","radius","*","*","2",")","``","``","''","''","datapts","=","self.forward","(","target",",","npts",")","def","cost","(","params",")",":","``","''","''","cost","of","minimum","enclosing","circle","for","a","2D","set","of","points","Args",":","params","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","a","circle","Returns",":","a","float","representing","radius","and","number","of","points","outside","the","circle","Notes",":","fit","to","points","generated","on","the","circle","defined","by","(","x",",","y",",","r",")","=","(","%","s",",","%","s",",","%","s",")","``","''","''","%","(","target","[","0","]",",","target","[","1","]",",","target","[","2","]",",",")","x",",","y",",","r","=","params","if","r","<","0",":","return","-999.0","*","r","penalty","=","0","for","xx",",","yy","in","datapts",":","#","compute","distance","to","origin","d","=","sqrt","(","(","xx","-","x",")","*","(","xx","-","x",")","+","(","yy","-","y",")","*","(","yy","-","y",")",")","if","d",">","r",":","#","each","violation","adds","1","to","the","cost","plus","amount","of","violation","penalty","+=","1","+","d","-","r","return","self.__sigma__","*","(","r","+","penalty",")","self.__cost__","=","cost","return","self.__cost__"] | 86 | 124 | null | circle.py | mystic/mystic/models/circle.py | from .abstract_model import AbstractModel
from numpy import array, pi, arange
from numpy import sin, cos
from math import floor, sqrt
import random | 15 | 1 | 5 | 2 | 1 | 6 | 1 | Use image node_id 5 for calling the Circle obj's underlying member method code with example usage: obj.CostFactory(target, npts) and returns: self, unknown, unknown | 164 | node_id 5 | 1,407,076 |
test_dask_mg_k_core | global | null | false | dask_client,benchmark,input_expected_output | null | null | null | null | null | def test_dask_mg_k_core(
dask_client, benchmark, input_expected_output
):
dg = input_expected_output["MGGraph"]
core_number = input_expected_output["core_number"]
k_core_results = benchmark(
dcg.k_core, dg, core_number=core_number
)
expected_k_core_results = input_expected_output[
"sg_k_core_results"
]
k_core_results = (
k_core_results.compute()
.sort_values(["src", "dst"])
.reset_index(drop=True)
.rename(columns={"weights": "weight"})
)
assert_frame_equal(
expected_k_core_results,
k_core_results,
check_dtype=False,
check_like=True,
)
| ["def","test_dask_mg_k_core","(","dask_client",",","benchmark",",","input_expected_output",")",":","dg","=","input_expected_output","[","``","MGGraph","''","]","core_number","=","input_expected_output","[","``","core_number","''","]","k_core_results","=","benchmark","(","dcg.k_core",",","dg",",","core_number=core_number",")","expected_k_core_results","=","input_expected_output","[","``","sg_k_core_results","''","]","k_core_results","=","(","k_core_results.compute","(",")",".sort_values","(","[","``","src","''",",","``","dst","''","]",")",".reset_index","(","drop=True",")",".rename","(","columns=","{","``","weights","''",":","``","weight","''","}",")",")","assert_frame_equal","(","expected_k_core_results",",","k_core_results",",","check_dtype=False",",","check_like=True",",",")"] | 140 | 158 | null | test_k_core_mg.py | cugraph/python/cugraph/cugraph/tests/core/test_k_core_mg.py | import gc
import pytest
import dask_cudf
import cugraph
import cugraph.dask
from cugraph.testing import utils
from cudf.testing.testing import assert_frame_equal
from cugraph.structure.symmetrize import symmetrize_df
from pylibcugraph.testing import gen_fixture_params_product | 15 | null | 9 | 6 | null | null | null | Use image node_id 5 for calling a global function with example usage: test_dask_mg_k_core(dask_client, benchmark, input_expected_output) without return types | 157 | node_id 5 | 686,802 |
test_get_all_logical_forms | ActionSpaceWalkerTest | AllenNlpTestCase | true | self | null | null | null | null | null | def test_get_all_logical_forms(self):
# get_all_logical_forms should sort logical forms by length.
ten_shortest_logical_forms = self.walker.get_all_logical_forms(
max_num_logical_forms=10
)
shortest_logical_form = ten_shortest_logical_forms[0]
assert shortest_logical_form == "(object_exists all_objects)"
length_three_logical_forms = ten_shortest_logical_forms[1:4]
assert set(length_three_logical_forms) == set(
[
"(object_exists (black all_objects))",
"(object_exists (touch_wall all_objects))",
"(object_exists (triangle all_objects))",
]
)
| ["def","test_get_all_logical_forms","(","self",")",":","#","get_all_logical_forms","should","sort","logical","forms","by","length",".","ten_shortest_logical_forms","=","self.walker.get_all_logical_forms","(","max_num_logical_forms=10",")","shortest_logical_form","=","ten_shortest_logical_forms","[","0","]","assert","shortest_logical_form","==","``","(","object_exists","all_objects",")","''","length_three_logical_forms","=","ten_shortest_logical_forms","[","1:4","]","assert","set","(","length_three_logical_forms",")","==","set","(","[","``","(","object_exists","(","black","all_objects",")",")","''",",","``","(","object_exists","(","touch_wall","all_objects",")",")","''",",","``","(","object_exists","(","triangle","all_objects",")",")","''",",","]",")"] | 65 | 73 | null | action_space_walker_test.py | magnitude/pymagnitude/third_party/allennlp/tests/semparse/action_space_walker_test.py | from __future__ import absolute_import
from nltk.sem.logic import TRUTH_TYPE
from allennlp.common.testing import AllenNlpTestCase
from allennlp.semparse.worlds.world import World
from allennlp.semparse import ActionSpaceWalker | 15 | 2 | 5 | 0 | 2 | 3 | 1 | Use image node_id 3 for calling the ActionSpaceWalkerTest obj's underlying member method code with example usage: obj.test_get_all_logical_forms() without return types | 167 | node_id 3 | 1,297,325 |
test_assistant_mismatch_retrieval | global | null | false | null | null | null | null | null | def test_assistant_mismatch_retrieval():
"""Test function to check if the GPTAssistantAgent can filter out the mismatch assistant"""
name = "For test_assistant_retrieval"
function_1_schema = {
"name": "call_function",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
"description": "This is a test function 1",
}
function_2_schema = {
"name": "call_function",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
"description": "This is a test function 2",
}
function_3_schema = {
"name": "call_function_other",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
"description": "This is a test function 3",
}
openai_client = OpenAIWrapper(config_list=config_list)._clients[0]
current_file_path = os.path.abspath(__file__)
file_1 = openai_client.files.create(
file=open(current_file_path, "rb"), purpose="assistants"
)
file_2 = openai_client.files.create(
file=open(current_file_path, "rb"), purpose="assistants"
)
all_llm_config = {
"tools": [
{"type": "function", "function": function_1_schema},
{"type": "function", "function": function_2_schema},
{"type": "retrieval"},
{"type": "code_interpreter"},
],
"file_ids": [file_1.id, file_2.id],
"config_list": config_list,
}
name = "For test_gpt_assistant_chat"
assistant_first = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config=all_llm_config,
)
candidate_first = retrieve_assistants_by_name(
assistant_first.openai_client, name
)
assert len(candidate_first) == 1
# test instructions mismatch
assistant_instructions_mistaching = GPTAssistantAgent(
name,
instructions="This is a test for mismatch instructions",
llm_config=all_llm_config,
)
candidate_instructions_mistaching = retrieve_assistants_by_name(
assistant_instructions_mistaching.openai_client, name
)
assert len(candidate_instructions_mistaching) == 2
# test mismatch fild ids
file_ids_mismatch_llm_config = {
"tools": [
{"type": "code_interpreter"},
{"type": "retrieval"},
{"type": "function", "function": function_2_schema},
{"type": "function", "function": function_1_schema},
],
"file_ids": [file_2.id],
"config_list": config_list,
}
assistant_file_ids_mismatch = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config=file_ids_mismatch_llm_config,
)
candidate_file_ids_mismatch = retrieve_assistants_by_name(
assistant_file_ids_mismatch.openai_client, name
)
assert len(candidate_file_ids_mismatch) == 3
# test tools mismatch
tools_mismatch_llm_config = {
"tools": [
{"type": "code_interpreter"},
{"type": "retrieval"},
{"type": "function", "function": function_3_schema},
],
"file_ids": [file_2.id, file_1.id],
"config_list": config_list,
}
assistant_tools_mistaching = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config=tools_mismatch_llm_config,
)
candidate_tools_mismatch = retrieve_assistants_by_name(
assistant_tools_mistaching.openai_client, name
)
assert len(candidate_tools_mismatch) == 4
openai_client.files.delete(file_1.id)
openai_client.files.delete(file_2.id)
assistant_first.delete_assistant()
assistant_instructions_mistaching.delete_assistant()
assistant_file_ids_mismatch.delete_assistant()
assistant_tools_mistaching.delete_assistant()
candidates = retrieve_assistants_by_name(openai_client, name)
assert len(candidates) == 0
| ["def","test_assistant_mismatch_retrieval","(",")",":","``","''","''","Test","function","to","check","if","the","GPTAssistantAgent","can","filter","out","the","mismatch","assistant","''","''","''","name","=","``","For","test_assistant_retrieval","''","function_1_schema","=","{","``","name","''",":","``","call_function","''",",","``","parameters","''",":","{","``","type","''",":","``","object","''",",","``","properties","''",":","{","}",",","``","required","''",":","[","]",",","}",",","``","description","''",":","``","This","is","a","test","function","1","''",",","}","function_2_schema","=","{","``","name","''",":","``","call_function","''",",","``","parameters","''",":","{","``","type","''",":","``","object","''",",","``","properties","''",":","{","}",",","``","required","''",":","[","]",",","}",",","``","description","''",":","``","This","is","a","test","function","2","''",",","}","function_3_schema","=","{","``","name","''",":","``","call_function_other","''",",","``","parameters","''",":","{","``","type","''",":","``","object","''",",","``","properties","''",":","{","}",",","``","required","''",":","[","]",",","}",",","``","description","''",":","``","This","is","a","test","function","3","''",",","}","openai_client","=","OpenAIWrapper","(","config_list=config_list",")","._clients","[","0","]","current_file_path","=","os.path.abspath","(","__file__",")","file_1","=","openai_client.files.create","(","file=open","(","current_file_path",",","``","rb","''",")",",","purpose=","''","assistants","''",")","file_2","=","openai_client.files.create","(","file=open","(","current_file_path",",","``","rb","''",")",",","purpose=","''","assistants","''",")","all_llm_config","=","{","``","tools","''",":","[","{","``","type","''",":","``","function","''",",","``","function","''",":","function_1_schema","}",",","{","``","type","''",":","``","function","''",",","``","function","''",":","function_2_schema","}",",","{","``","type","''",":","``","retrieval","''","}",",","{","``","type","''",":","``","code_interpreter","''","}",",","]",",","``","file_ids","''",":","[","file_1.id",",","file_2.id","]",",","``","config_list","''",":","config_list",",","}","name","=","``","For","test_gpt_assistant_chat","''","assistant_first","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=all_llm_config",",",")","candidate_first","=","retrieve_assistants_by_name","(","assistant_first.openai_client",",","name",")","assert","len","(","candidate_first",")","==","1","#","test","instructions","mismatch","assistant_instructions_mistaching","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","for","mismatch","instructions","''",",","llm_config=all_llm_config",",",")","candidate_instructions_mistaching","=","retrieve_assistants_by_name","(","assistant_instructions_mistaching.openai_client",",","name",")","assert","len","(","candidate_instructions_mistaching",")","==","2","#","test","mismatch","fild","ids","file_ids_mismatch_llm_config","=","{","``","tools","''",":","[","{","``","type","''",":","``","code_interpreter","''","}",",","{","``","type","''",":","``","retrieval","''","}",",","{","``","type","''",":","``","function","''",",","``","function","''",":","function_2_schema","}",",","{","``","type","''",":","``","function","''",",","``","function","''",":","function_1_schema","}",",","]",",","``","file_ids","''",":","[","file_2.id","]",",","``","config_list","''",":","config_list",",","}","assistant_file_ids_mismatch","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=file_ids_mismatch_llm_config",",",")","candidate_file_ids_mismatch","=","retrieve_assistants_by_name","(","assistant_file_ids_mismatch.openai_client",",","name",")","assert","len","(","candidate_file_ids_mismatch",")","==","3","#","test","tools","mismatch","tools_mismatch_llm_config","=","{","``","tools","''",":","[","{","``","type","''",":","``","code_interpreter","''","}",",","{","``","type","''",":","``","retrieval","''","}",",","{","``","type","''",":","``","function","''",",","``","function","''",":","function_3_schema","}",",","]",",","``","file_ids","''",":","[","file_2.id",",","file_1.id","]",",","``","config_list","''",":","config_list",",","}","assistant_tools_mistaching","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=tools_mismatch_llm_config",",",")","candidate_tools_mismatch","=","retrieve_assistants_by_name","(","assistant_tools_mistaching.openai_client",",","name",")","assert","len","(","candidate_tools_mismatch",")","==","4","openai_client.files.delete","(","file_1.id",")","openai_client.files.delete","(","file_2.id",")","assistant_first.delete_assistant","(",")","assistant_instructions_mistaching.delete_assistant","(",")","assistant_file_ids_mismatch.delete_assistant","(",")","assistant_tools_mistaching.delete_assistant","(",")","candidates","=","retrieve_assistants_by_name","(","openai_client",",","name",")","assert","len","(","candidates",")","==","0"] | 294 | 398 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 8 for calling a global function with example usage: test_assistant_mismatch_retrieval() without return types | 126 | node_id 8 | 319,273 |
|
test_dask_mg_k_core_invalid_input | global | null | false | dask_client | null | null | null | null | null | def test_dask_mg_k_core_invalid_input(dask_client):
input_data_path = datasets[0]
chunksize = dcg.get_chunksize(input_data_path)
ddf = dask_cudf.read_csv(
input_data_path,
chunksize=chunksize,
delimiter=" ",
names=["src", "dst", "value"],
dtype=["int32", "int32", "float32"],
)
dg = cugraph.Graph(directed=True)
dg.from_dask_cudf_edgelist(
ddf,
source="src",
destination="dst",
edge_attr="value",
renumber=True,
store_transposed=True,
)
with pytest.raises(ValueError):
dcg.k_core(dg)
dg = cugraph.Graph(directed=False)
dg.from_dask_cudf_edgelist(
ddf,
source="src",
destination="dst",
edge_attr="value",
store_transposed=True,
)
degree_type = "invalid"
with pytest.raises(ValueError):
dcg.k_core(dg, degree_type=degree_type)
| ["def","test_dask_mg_k_core_invalid_input","(","dask_client",")",":","input_data_path","=","datasets","[","0","]","chunksize","=","dcg.get_chunksize","(","input_data_path",")","ddf","=","dask_cudf.read_csv","(","input_data_path",",","chunksize=chunksize",",","delimiter=","''","``",",","names=","[","``","src","''",",","``","dst","''",",","``","value","''","]",",","dtype=","[","``","int32","''",",","``","int32","''",",","``","float32","''","]",",",")","dg","=","cugraph.Graph","(","directed=True",")","dg.from_dask_cudf_edgelist","(","ddf",",","source=","''","src","''",",","destination=","''","dst","''",",","edge_attr=","''","value","''",",","renumber=True",",","store_transposed=True",",",")","with","pytest.raises","(","ValueError",")",":","dcg.k_core","(","dg",")","dg","=","cugraph.Graph","(","directed=False",")","dg.from_dask_cudf_edgelist","(","ddf",",","source=","''","src","''",",","destination=","''","dst","''",",","edge_attr=","''","value","''",",","store_transposed=True",",",")","degree_type","=","``","invalid","''","with","pytest.raises","(","ValueError",")",":","dcg.k_core","(","dg",",","degree_type=degree_type",")"] | 162 | 196 | null | test_k_core_mg.py | cugraph/python/cugraph/cugraph/tests/core/test_k_core_mg.py | import gc
import pytest
import dask_cudf
import cugraph
import cugraph.dask
from cugraph.testing import utils
from cudf.testing.testing import assert_frame_equal
from cugraph.structure.symmetrize import symmetrize_df
from pylibcugraph.testing import gen_fixture_params_product | 15 | null | 9 | 6 | null | null | null | Use image node_id 6 for calling a global function with example usage: test_dask_mg_k_core_invalid_input(dask_client) without return types | 137 | node_id 6 | 686,803 |
__init__ | Circle | AbstractModel | true | self,packing,name,sigma | Computes 2D array representation of a circle
where the circle minimally bounds the 2D data points
data points with [minimal, sparse, or dense] packing=[~0.2, ~1.0, or ~5.0]
setting packing = None will constrain all points to the circle's radius | ["Computes","2D","array","representation","of","a","circle","where","the","circle","minimally","bounds","the","2D","data","points","data","points","with","[","minimal",",","sparse",",","or","dense","]","packing=","[","~0.2",",","~1.0",",","or","~5.0","]","setting","packing","=","None","will","constrain","all","points","to","the","circle","'s","radius"] | null | null | Circle | def __init__(self, packing=None, name="circle", sigma=1.0):
AbstractModel.__init__(self, name, sigma)
if packing == None:
packing = 0.0
self.__packing__ = packing
return
| ["def","__init__","(","self",",","packing=None",",","name=","''","circle","''",",","sigma=1.0",")",":","AbstractModel.__init__","(","self",",","name",",","sigma",")","if","packing","==","None",":","packing","=","0.0","self.__packing__","=","packing","return"] | 34 | 38 | null | circle.py | mystic/mystic/models/circle.py | from .abstract_model import AbstractModel
from numpy import array, pi, arange
from numpy import sin, cos
from math import floor, sqrt
import random | 15 | 1 | 5 | 2 | 1 | 6 | 1 | Use image node_id 1 to create a new Circle object from inherited base classes: AbstractModel with example: obj = Circle(packing, name, sigma) | 141 | node_id 1 | 1,407,072 |
test_assistant_retrieval | global | null | false | null | null | null | null | null | def test_assistant_retrieval():
"""
Test function to check if the GPTAssistantAgent can retrieve the same assistant
"""
name = "For test_assistant_retrieval"
function_1_schema = {
"name": "call_function_1",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
"description": "This is a test function 1",
}
function_2_schema = {
"name": "call_function_1",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
"description": "This is a test function 2",
}
openai_client = OpenAIWrapper(config_list=config_list)._clients[0]
current_file_path = os.path.abspath(__file__)
file_1 = openai_client.files.create(
file=open(current_file_path, "rb"), purpose="assistants"
)
file_2 = openai_client.files.create(
file=open(current_file_path, "rb"), purpose="assistants"
)
all_llm_config = {
"tools": [
{"type": "function", "function": function_1_schema},
{"type": "function", "function": function_2_schema},
{"type": "retrieval"},
{"type": "code_interpreter"},
],
"file_ids": [file_1.id, file_2.id],
"config_list": config_list,
}
name = "For test_gpt_assistant_chat"
assistant_first = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config=all_llm_config,
)
candidate_first = retrieve_assistants_by_name(
assistant_first.openai_client, name
)
assistant_second = GPTAssistantAgent(
name,
instructions="This is a test",
llm_config=all_llm_config,
)
candidate_second = retrieve_assistants_by_name(
assistant_second.openai_client, name
)
try:
assistant_first.delete_assistant()
assistant_second.delete_assistant()
except openai.NotFoundError:
# Not found error is expected because the same assistant can not be deleted twice
pass
openai_client.files.delete(file_1.id)
openai_client.files.delete(file_2.id)
assert candidate_first == candidate_second
assert len(candidate_first) == 1
candidates = retrieve_assistants_by_name(openai_client, name)
assert len(candidates) == 0
| ["def","test_assistant_retrieval","(",")",":","``","''","''","Test","function","to","check","if","the","GPTAssistantAgent","can","retrieve","the","same","assistant","``","''","''","name","=","``","For","test_assistant_retrieval","''","function_1_schema","=","{","``","name","''",":","``","call_function_1","''",",","``","parameters","''",":","{","``","type","''",":","``","object","''",",","``","properties","''",":","{","}",",","``","required","''",":","[","]",",","}",",","``","description","''",":","``","This","is","a","test","function","1","''",",","}","function_2_schema","=","{","``","name","''",":","``","call_function_1","''",",","``","parameters","''",":","{","``","type","''",":","``","object","''",",","``","properties","''",":","{","}",",","``","required","''",":","[","]",",","}",",","``","description","''",":","``","This","is","a","test","function","2","''",",","}","openai_client","=","OpenAIWrapper","(","config_list=config_list",")","._clients","[","0","]","current_file_path","=","os.path.abspath","(","__file__",")","file_1","=","openai_client.files.create","(","file=open","(","current_file_path",",","``","rb","''",")",",","purpose=","''","assistants","''",")","file_2","=","openai_client.files.create","(","file=open","(","current_file_path",",","``","rb","''",")",",","purpose=","''","assistants","''",")","all_llm_config","=","{","``","tools","''",":","[","{","``","type","''",":","``","function","''",",","``","function","''",":","function_1_schema","}",",","{","``","type","''",":","``","function","''",",","``","function","''",":","function_2_schema","}",",","{","``","type","''",":","``","retrieval","''","}",",","{","``","type","''",":","``","code_interpreter","''","}",",","]",",","``","file_ids","''",":","[","file_1.id",",","file_2.id","]",",","``","config_list","''",":","config_list",",","}","name","=","``","For","test_gpt_assistant_chat","''","assistant_first","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=all_llm_config",",",")","candidate_first","=","retrieve_assistants_by_name","(","assistant_first.openai_client",",","name",")","assistant_second","=","GPTAssistantAgent","(","name",",","instructions=","''","This","is","a","test","''",",","llm_config=all_llm_config",",",")","candidate_second","=","retrieve_assistants_by_name","(","assistant_second.openai_client",",","name",")","try",":","assistant_first.delete_assistant","(",")","assistant_second.delete_assistant","(",")","except","openai.NotFoundError",":","#","Not","found","error","is","expected","because","the","same","assistant","can","not","be","deleted","twice","pass","openai_client.files.delete","(","file_1.id",")","openai_client.files.delete","(","file_2.id",")","assert","candidate_first","==","candidate_second","assert","len","(","candidate_first",")","==","1","candidates","=","retrieve_assistants_by_name","(","openai_client",",","name",")","assert","len","(","candidates",")","==","0"] | 223 | 287 | null | test_gpt_assistant.py | autogen/test/agentchat/contrib/test_gpt_assistant.py | import pytest
import os
import sys
import autogen
from autogen import OpenAIWrapper
from conftest import skip_openai
from test_assistant_agent import KEY_LOC, OAI_CONFIG_LIST | 15 | null | 7 | 8 | null | null | null | Use image node_id 7 for calling a global function with example usage: test_assistant_retrieval() without return types | 117 | node_id 7 | 319,272 |
|
test_boston_housing_parameter_stress_test | DecisionTreeRegressorBostonHousingScikitNumericTest | unittest | true | self | Unit test class for testing scikit-learn converter and running both models | ["Unit","test","class","for","testing","scikit-learn","converter","and","running","both","models"] | null | null | null | def test_boston_housing_parameter_stress_test(self):
## These are all the options in decision tree regression of scikit-learn
options = dict(
criterion=["mse"],
splitter=["best"],
max_depth=[1, 10, None],
min_samples_split=[2, 10, 0.5],
min_samples_leaf=[1, 5],
min_weight_fraction_leaf=[0.0, 0.5],
max_features=[None, 1, 5],
max_leaf_nodes=[None, 20],
min_impurity_decrease=[0.0, 1e-07, 0.1],
presort=[False, True],
)
# Make a cartesian product of all options
import itertools
product = itertools.product(*options.values())
args = [dict(zip(options.keys(), p)) for p in product]
print(
"Testing a total of %s cases. This could take a while"
% len(args)
)
for it, arg in enumerate(args):
self._train_convert_evaluate_assert(**arg)
| ["def","test_boston_housing_parameter_stress_test","(","self",")",":","#","#","These","are","all","the","options","in","decision","tree","regression","of","scikit-learn","options","=","dict","(","criterion=","[","``","mse","''","]",",","splitter=","[","``","best","''","]",",","max_depth=","[","1",",","10",",","None","]",",","min_samples_split=","[","2",",","10",",","0.5","]",",","min_samples_leaf=","[","1",",","5","]",",","min_weight_fraction_leaf=","[","0.0",",","0.5","]",",","max_features=","[","None",",","1",",","5","]",",","max_leaf_nodes=","[","None",",","20","]",",","min_impurity_decrease=","[","0.0",",","1e-07",",","0.1","]",",","presort=","[","False",",","True","]",",",")","#","Make","a","cartesian","product","of","all","options","import","itertools","product","=","itertools.product","(","*","options.values","(",")",")","args","=","[","dict","(","zip","(","options.keys","(",")",",","p",")",")","for","p","in","product","]","print","(","``","Testing","a","total","of","%","s","cases",".","This","could","take","a","while","''","%","len","(","args",")",")","for","it",",","arg","in","enumerate","(","args",")",":","self._train_convert_evaluate_assert","(","*","*","arg",")"] | 82 | 106 | null | test_decision_tree_regression_numeric.py | turicreate/src/external/coremltools_wrap/coremltools/coremltools/test/xgboost_tests/test_decision_tree_regression_numeric.py | import unittest
from coremltools.converters import sklearn
from coremltools.models.utils import evaluate_regressor
import pandas
import os
from coremltools.models.utils import evaluate_regressor, _macos_version, _is_macos
from coremltools._deps import _HAS_SKLEARN
import pytest | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 5 for calling the DecisionTreeRegressorBostonHousingScikitNumericTest obj's underlying member method code with example usage: obj.test_boston_housing_parameter_stress_test() without return types | 212 | node_id 5 | 2,281,190 |
__call__ | Circle | AbstractModel | true | self,x,y,r | Computes 2D array representation of a circle
where the circle minimally bounds the 2D data points
data points with [minimal, sparse, or dense] packing=[~0.2, ~1.0, or ~5.0]
setting packing = None will constrain all points to the circle's radius | ["Computes","2D","array","representation","of","a","circle","where","the","circle","minimally","bounds","the","2D","data","points","data","points","with","[","minimal",",","sparse",",","or","dense","]","packing=","[","~0.2",",","~1.0",",","or","~5.0","]","setting","packing","=","None","will","constrain","all","points","to","the","circle","'s","radius"] | null | null | self | def __call__(self, x, y, r, *args, **kwds):
return self.forward((x, y, r), *args, **kwds)
| ["def","__call__","(","self",",","x",",","y",",","r",",","*","args",",","*","*","kwds",")",":","return","self.forward","(","(","x",",","y",",","r",")",",","*","args",",","*","*","kwds",")"] | 40 | 41 | null | circle.py | mystic/mystic/models/circle.py | from .abstract_model import AbstractModel
from numpy import array, pi, arange
from numpy import sin, cos
from math import floor, sqrt
import random | 15 | 1 | 5 | 2 | 1 | 6 | 1 | Use image node_id 2 for calling the Circle obj's underlying member method code with example usage: obj.__call__(x, y, r) and returns: self | 138 | node_id 2 | 1,407,073 |
test_mixed_dtypes | global | null | false | df_from_dict | null | null | null | null | null | def test_mixed_dtypes(df_from_dict):
df = df_from_dict(
{
"a": [1, 2, 3], # dtype kind INT = 0
"b": [3, 4, 5], # dtype kind INT = 0
"c": [1.5, 2.5, 3.5], # dtype kind FLOAT = 2
"d": [9, 10, 11], # dtype kind INT = 0
"e": [True, False, True], # dtype kind BOOLEAN = 20
"f": ["a", "", "c"], # dtype kind STRING = 21
}
)
dfX = df.__dataframe__()
# for meanings of dtype[0] see the spec; we cannot import the spec here as this
# file is expected to be vendored *anywhere*;
# values for dtype[0] are explained above
columns = {"a": 0, "b": 0, "c": 2, "d": 0, "e": 20, "f": 21}
for column, kind in columns.items():
colX = dfX.get_column_by_name(column)
assert colX.null_count == 0
assert isinstance(colX.null_count, int)
assert colX.size() == 3
assert colX.offset == 0
assert colX.dtype[0] == kind
assert dfX.get_column_by_name("c").dtype[1] == 64
| ["def","test_mixed_dtypes","(","df_from_dict",")",":","df","=","df_from_dict","(","{","``","a","''",":","[","1",",","2",",","3","]",",","#","dtype","kind","INT","=","0","``","b","''",":","[","3",",","4",",","5","]",",","#","dtype","kind","INT","=","0","``","c","''",":","[","1.5",",","2.5",",","3.5","]",",","#","dtype","kind","FLOAT","=","2","``","d","''",":","[","9",",","10",",","11","]",",","#","dtype","kind","INT","=","0","``","e","''",":","[","True",",","False",",","True","]",",","#","dtype","kind","BOOLEAN","=","20","``","f","''",":","[","``","a","''",",","``","''",",","``","c","''","]",",","#","dtype","kind","STRING","=","21","}",")","dfX","=","df.__dataframe__","(",")","#","for","meanings","of","dtype","[","0","]","see","the","spec",";","we","can","not","import","the","spec","here","as","this","#","file","is","expected","to","be","vendored","*","anywhere","*",";","#","values","for","dtype","[","0","]","are","explained","above","columns","=","{","``","a","''",":","0",",","``","b","''",":","0",",","``","c","''",":","2",",","``","d","''",":","0",",","``","e","''",":","20",",","``","f","''",":","21","}","for","column",",","kind","in","columns.items","(",")",":","colX","=","dfX.get_column_by_name","(","column",")","assert","colX.null_count","==","0","assert","isinstance","(","colX.null_count",",","int",")","assert","colX.size","(",")","==","3","assert","colX.offset","==","0","assert","colX.dtype","[","0","]","==","kind","assert","dfX.get_column_by_name","(","``","c","''",")",".dtype","[","1","]","==","64"] | 45 | 71 | null | test_spec_conformance.py | pandas/pandas/tests/interchange/test_spec_conformance.py | import ctypes
import math
import pytest
import pandas | 15 | null | 4 | 11 | null | null | null | Use image node_id 3 for calling a global function with example usage: test_mixed_dtypes(df_from_dict) without return types | 122 | node_id 3 | 1,516,679 |
test_only_one_dtype | global | null | false | test_data,df_from_dict | null | null | null | null | null | def test_only_one_dtype(test_data, df_from_dict):
columns = list(test_data.keys())
df = df_from_dict(test_data)
dfX = df.__dataframe__()
column_size = len(test_data[columns[0]])
for column in columns:
null_count = dfX.get_column_by_name(column).null_count
assert null_count == 0
assert isinstance(null_count, int)
assert dfX.get_column_by_name(column).size() == column_size
assert dfX.get_column_by_name(column).offset == 0
| ["def","test_only_one_dtype","(","test_data",",","df_from_dict",")",":","columns","=","list","(","test_data.keys","(",")",")","df","=","df_from_dict","(","test_data",")","dfX","=","df.__dataframe__","(",")","column_size","=","len","(","test_data","[","columns","[","0","]","]",")","for","column","in","columns",":","null_count","=","dfX.get_column_by_name","(","column",")",".null_count","assert","null_count","==","0","assert","isinstance","(","null_count",",","int",")","assert","dfX.get_column_by_name","(","column",")",".size","(",")","==","column_size","assert","dfX.get_column_by_name","(","column",")",".offset","==","0"] | 31 | 42 | null | test_spec_conformance.py | pandas/pandas/tests/interchange/test_spec_conformance.py | import ctypes
import math
import pytest
import pandas | 15 | null | 4 | 11 | null | null | null | Use image node_id 2 for calling a global function with example usage: test_only_one_dtype(test_data, df_from_dict) without return types | 135 | node_id 2 | 1,516,678 |
setup_function | global | null | false | null | null | null | null | null | def setup_function():
gc.collect()
| ["def","setup_function","(",")",":","gc.collect","(",")"] | 30 | 31 | null | test_k_core_mg.py | cugraph/python/cugraph/cugraph/tests/core/test_k_core_mg.py | import gc
import pytest
import dask_cudf
import cugraph
import cugraph.dask
from cugraph.testing import utils
from cudf.testing.testing import assert_frame_equal
from cugraph.structure.symmetrize import symmetrize_df
from pylibcugraph.testing import gen_fixture_params_product | 15 | null | 9 | 6 | null | null | null | Use image node_id 1 for calling a global function with example usage: setup_function() without return types | 107 | node_id 1 | 686,798 |
|
forward | Circle | AbstractModel | true | self,coeffs,npts | Computes 2D array representation of a circle
where the circle minimally bounds the 2D data points
data points with [minimal, sparse, or dense] packing=[~0.2, ~1.0, or ~5.0]
setting packing = None will constrain all points to the circle's radius | ["Computes","2D","array","representation","of","a","circle","where","the","circle","minimally","bounds","the","2D","data","points","data","points","with","[","minimal",",","sparse",",","or","dense","]","packing=","[","~0.2",",","~1.0",",","or","~5.0","]","setting","packing","=","None","will","constrain","all","points","to","the","circle","'s","radius"] | generate a 2D array of points contained within a circle
Args:
coeffs (list[float]): (x, y, and radius) defining a circle
npts (int, default=None): number of points to generate
Returns:
a 2D array of points contained within the defined circle
Notes:
default ``npts`` is ``packing * floor(pi * radius**2)``
| ["generate","a","2D","array","of","points","contained","within","a","circle","Args",":","coeffs","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","a","circle","npts","(","int",",","default=None",")",":","number","of","points","to","generate","Returns",":","a","2D","array","of","points","contained","within","the","defined","circle","Notes",":","default","``","npts","``","is","``","packing","*","floor","(","pi","*","radius","*","*","2",")","``"] | gendata | def forward(self, coeffs, npts=None):
"""generate a 2D array of points contained within a circle
Args:
coeffs (list[float]): (x, y, and radius) defining a circle
npts (int, default=None): number of points to generate
Returns:
a 2D array of points contained within the defined circle
Notes:
default ``npts`` is ``packing * floor(pi * radius**2)``
"""
if not npts:
# generate # of points based on packing and given radius
npts = self.__packing__ * floor(pi * (coeffs[-1]) ** 2)
return gendata(coeffs, npts)
| ["def","forward","(","self",",","coeffs",",","npts=None",")",":","``","''","''","generate","a","2D","array","of","points","contained","within","a","circle","Args",":","coeffs","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","a","circle","npts","(","int",",","default=None",")",":","number","of","points","to","generate","Returns",":","a","2D","array","of","points","contained","within","the","defined","circle","Notes",":","default","``","npts","``","is","``","packing","*","floor","(","pi","*","radius","*","*","2",")","``","``","''","''","if","not","npts",":","#","generate","#","of","points","based","on","packing","and","given","radius","npts","=","self.__packing__","*","floor","(","pi","*","(","coeffs","[","-1","]",")","*","*","2",")","return","gendata","(","coeffs",",","npts",")"] | 43 | 59 | null | circle.py | mystic/mystic/models/circle.py | from .abstract_model import AbstractModel
from numpy import array, pi, arange
from numpy import sin, cos
from math import floor, sqrt
import random | 15 | 1 | 5 | 2 | 1 | 6 | 1 | Use image node_id 3 for calling the Circle obj's underlying member method code with example usage: obj.forward(coeffs, npts) and returns: gendata | 145 | node_id 3 | 1,407,074 |
__init__ | DiceLoss | nn | true | self,eps | Loss function from https://arxiv.org/abs/1707.03237,
where iou computation is introduced heatmap manner to measure the
diversity bwtween tow heatmaps. | ["Loss","function","from","https",":","\/\/arxiv.org\/abs\/1707.03237",",","where","iou","computation","is","introduced","heatmap","manner","to","measure","the","diversity","bwtween","tow","heatmaps","."] | null | null | DiceLoss | def __init__(self, eps=1e-6):
super(DiceLoss, self).__init__()
self.eps = eps
| ["def","__init__","(","self",",","eps=1e-6",")",":","super","(","DiceLoss",",","self",")",".__init__","(",")","self.eps","=","eps"] | 60 | 62 | null | basic_loss.py | PaddleOCR/benchmark/PaddleOCR_DBNet/models/losses/basic_loss.py | import paddle
import paddle.nn | 15 | 3 | 2 | 0 | 3 | 3 | 1 | Use image node_id 1 to create a new DiceLoss object from inherited base classes: nn with example: obj = DiceLoss(eps) | 117 | node_id 1 | 176,930 |
forward | BalanceCrossEntropyLoss | nn | true | self,pred,gt,mask,return_origin | Balanced cross entropy loss.
Shape:
- Input: :math:`(N, 1, H, W)`
- GT: :math:`(N, 1, H, W)`, same shape as the input
- Mask: :math:`(N, H, W)`, same spatial shape as the input
- Output: scalar. | ["Balanced","cross","entropy","loss",".","Shape",":","-","Input",":",":","math",":","`","(","N",",","1",",","H",",","W",")","`","-","GT",":",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","same","shape","as","the","input","-","Mask",":",":","math",":","`","(","N",",","H",",","W",")","`",",","same","spatial","shape","as","the","input","-","Output",":","scalar","."] | Args:
pred: shape :math:`(N, 1, H, W)`, the prediction of network
gt: shape :math:`(N, 1, H, W)`, the target
mask: shape :math:`(N, H, W)`, the mask indicates positive regions | ["Args",":","pred",":","shape",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","the","prediction","of","network","gt",":","shape",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","the","target","mask",":","shape",":","math",":","`","(","N",",","H",",","W",")","`",",","the","mask","indicates","positive","regions"] | balance_loss,balance_loss, loss | def forward(
self,
pred: paddle.Tensor,
gt: paddle.Tensor,
mask: paddle.Tensor,
return_origin=False,
):
"""
Args:
pred: shape :math:`(N, 1, H, W)`, the prediction of network
gt: shape :math:`(N, 1, H, W)`, the target
mask: shape :math:`(N, H, W)`, the mask indicates positive regions
"""
positive = gt * mask
negative = (1 - gt) * mask
positive_count = int(positive.sum())
negative_count = min(
int(negative.sum()), int(positive_count * self.negative_ratio)
)
loss = nn.functional.binary_cross_entropy(
pred, gt, reduction="none"
)
positive_loss = loss * positive
negative_loss = loss * negative
negative_loss, _ = negative_loss.reshape([-1]).topk(
negative_count
)
balance_loss = (positive_loss.sum() + negative_loss.sum()) / (
positive_count + negative_count + self.eps
)
if return_origin:
return balance_loss, loss
return balance_loss
| ["def","forward","(","self",",","pred",":","paddle.Tensor",",","gt",":","paddle.Tensor",",","mask",":","paddle.Tensor",",","return_origin=False",",",")",":","``","''","''","Args",":","pred",":","shape",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","the","prediction","of","network","gt",":","shape",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","the","target","mask",":","shape",":","math",":","`","(","N",",","H",",","W",")","`",",","the","mask","indicates","positive","regions","``","''","''","positive","=","gt","*","mask","negative","=","(","1","-","gt",")","*","mask","positive_count","=","int","(","positive.sum","(",")",")","negative_count","=","min","(","int","(","negative.sum","(",")",")",",","int","(","positive_count","*","self.negative_ratio",")",")","loss","=","nn.functional.binary_cross_entropy","(","pred",",","gt",",","reduction=","''","none","''",")","positive_loss","=","loss","*","positive","negative_loss","=","loss","*","negative","negative_loss",",","_","=","negative_loss.reshape","(","[","-1","]",")",".topk","(","negative_count",")","balance_loss","=","(","positive_loss.sum","(",")","+","negative_loss.sum","(",")",")","\/","(","positive_count","+","negative_count","+","self.eps",")","if","return_origin",":","return","balance_loss",",","loss","return","balance_loss"] | 24 | 50 | null | basic_loss.py | PaddleOCR/benchmark/PaddleOCR_DBNet/models/losses/basic_loss.py | import paddle
import paddle.nn | 15 | 3 | 2 | 0 | 3 | 2 | 1 | Use image node_id 2 for calling the BalanceCrossEntropyLoss obj's underlying member method code with example usage: obj.forward(pred, gt, mask, return_origin) and returns: balance_loss, balance_loss, loss | 205 | node_id 2 | 176,929 |
test_boston_housing_simple_regression | DecisionTreeRegressorBostonHousingScikitNumericTest | unittest | true | self | Unit test class for testing scikit-learn converter and running both models | ["Unit","test","class","for","testing","scikit-learn","converter","and","running","both","models"] | null | null | null | def test_boston_housing_simple_regression(self):
self._train_convert_evaluate_assert(max_depth=20)
| ["def","test_boston_housing_simple_regression","(","self",")",":","self._train_convert_evaluate_assert","(","max_depth=20",")"] | 78 | 79 | null | test_decision_tree_regression_numeric.py | turicreate/src/external/coremltools_wrap/coremltools/coremltools/test/xgboost_tests/test_decision_tree_regression_numeric.py | import unittest
from coremltools.converters import sklearn
from coremltools.models.utils import evaluate_regressor
import pandas
import os
from coremltools.models.utils import evaluate_regressor, _macos_version, _is_macos
from coremltools._deps import _HAS_SKLEARN
import pytest | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 4 for calling the DecisionTreeRegressorBostonHousingScikitNumericTest obj's underlying member method code with example usage: obj.test_boston_housing_simple_regression() without return types | 208 | node_id 4 | 2,281,189 |
__init__ | BalanceCrossEntropyLoss | nn | true | self,negative_ratio,eps | Balanced cross entropy loss.
Shape:
- Input: :math:`(N, 1, H, W)`
- GT: :math:`(N, 1, H, W)`, same shape as the input
- Mask: :math:`(N, H, W)`, same spatial shape as the input
- Output: scalar. | ["Balanced","cross","entropy","loss",".","Shape",":","-","Input",":",":","math",":","`","(","N",",","1",",","H",",","W",")","`","-","GT",":",":","math",":","`","(","N",",","1",",","H",",","W",")","`",",","same","shape","as","the","input","-","Mask",":",":","math",":","`","(","N",",","H",",","W",")","`",",","same","spatial","shape","as","the","input","-","Output",":","scalar","."] | null | null | BalanceCrossEntropyLoss | def __init__(self, negative_ratio=3.0, eps=1e-6):
super(BalanceCrossEntropyLoss, self).__init__()
self.negative_ratio = negative_ratio
self.eps = eps
| ["def","__init__","(","self",",","negative_ratio=3.0",",","eps=1e-6",")",":","super","(","BalanceCrossEntropyLoss",",","self",")",".__init__","(",")","self.negative_ratio","=","negative_ratio","self.eps","=","eps"] | 19 | 22 | null | basic_loss.py | PaddleOCR/benchmark/PaddleOCR_DBNet/models/losses/basic_loss.py | import paddle
import paddle.nn | 15 | 3 | 2 | 0 | 3 | 2 | 1 | Use image node_id 1 to create a new BalanceCrossEntropyLoss object from inherited base classes: nn with example: obj = BalanceCrossEntropyLoss(negative_ratio, eps) | 163 | node_id 1 | 176,928 |
_train_convert_evaluate_assert | DecisionTreeRegressorBostonHousingScikitNumericTest | unittest | true | self | Unit test class for testing scikit-learn converter and running both models | ["Unit","test","class","for","testing","scikit-learn","converter","and","running","both","models"] | Train a scikit-learn model, convert it and then evaluate it with CoreML | ["Train","a","scikit-learn","model",",","convert","it","and","then","evaluate","it","with","CoreML"] | null | def _train_convert_evaluate_assert(self, **scikit_params):
"""
Train a scikit-learn model, convert it and then evaluate it with CoreML
"""
scikit_model = DecisionTreeRegressor(
random_state=1, **scikit_params
)
scikit_model.fit(self.X, self.target)
# Convert the model
spec = skl_converter.convert(
scikit_model, self.feature_names, self.output_name
)
if _is_macos() and _macos_version() >= (10, 13):
# Get predictions
df = pd.DataFrame(self.X, columns=self.feature_names)
df["prediction"] = scikit_model.predict(self.X)
# Evaluate it
metrics = evaluate_regressor(
spec, df, target="target", verbose=False
)
self._check_metrics(metrics, scikit_params)
| ["def","_train_convert_evaluate_assert","(","self",",","*","*","scikit_params",")",":","``","''","''","Train","a","scikit-learn","model",",","convert","it","and","then","evaluate","it","with","CoreML","``","''","''","scikit_model","=","DecisionTreeRegressor","(","random_state=1",",","*","*","scikit_params",")","scikit_model.fit","(","self.X",",","self.target",")","#","Convert","the","model","spec","=","skl_converter.convert","(","scikit_model",",","self.feature_names",",","self.output_name",")","if","_is_macos","(",")","and","_macos_version","(",")",">","=","(","10",",","13",")",":","#","Get","predictions","df","=","pd.DataFrame","(","self.X",",","columns=self.feature_names",")","df","[","``","prediction","''","]","=","scikit_model.predict","(","self.X",")","#","Evaluate","it","metrics","=","evaluate_regressor","(","spec",",","df",",","target=","''","target","''",",","verbose=False",")","self._check_metrics","(","metrics",",","scikit_params",")"] | 59 | 76 | null | test_decision_tree_regression_numeric.py | turicreate/src/external/coremltools_wrap/coremltools/coremltools/test/xgboost_tests/test_decision_tree_regression_numeric.py | import unittest
from coremltools.converters import sklearn
from coremltools.models.utils import evaluate_regressor
import pandas
import os
from coremltools.models.utils import evaluate_regressor, _macos_version, _is_macos
from coremltools._deps import _HAS_SKLEARN
import pytest | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 3 for calling the DecisionTreeRegressorBostonHousingScikitNumericTest obj's underlying member method code with example usage: obj._train_convert_evaluate_assert() without return types | 201 | node_id 3 | 2,281,188 |
poisson | global | null | false | lam | null | null | null | null | ret | def poisson(
lam: Union[float, JaxArray],
*,
shape: Optional[Union[ivy.NativeShape, Sequence[int]]] = None,
device: Optional[jaxlib.xla_extension.Device] = None,
dtype: Optional[jnp.dtype] = None,
seed: Optional[int] = None,
fill_value: Optional[Union[float, int]] = 0,
out: Optional[JaxArray] = None,
) -> JaxArray:
lam = jnp.array(lam)
if seed:
rng_input = jax.random.PRNGKey(seed)
else:
RNG_, rng_input = jax.random.split(_getRNG())
_setRNG(RNG_)
if shape is not None:
shape = jnp.array(shape)
list_shape = shape.tolist()
_check_shapes_broadcastable(lam.shape, list_shape)
else:
list_shape = None
if jnp.any(lam < 0):
pos_lam = jnp.where(lam < 0, 0, lam)
ret = jax.random.poisson(
rng_input, pos_lam, shape=list_shape
).astype(dtype)
ret = jnp.where(lam < 0, fill_value, ret)
else:
ret = jax.random.poisson(
rng_input, lam, shape=list_shape
).astype(dtype)
return ret
| ["def","poisson","(","lam",":","Union","[","float",",","JaxArray","]",",","*",",","shape",":","Optional","[","Union","[","ivy.NativeShape",",","Sequence","[","int","]","]","]","=","None",",","device",":","Optional","[","jaxlib.xla_extension.Device","]","=","None",",","dtype",":","Optional","[","jnp.dtype","]","=","None",",","seed",":","Optional","[","int","]","=","None",",","fill_value",":","Optional","[","Union","[","float",",","int","]","]","=","0",",","out",":","Optional","[","JaxArray","]","=","None",",",")","-",">","JaxArray",":","lam","=","jnp.array","(","lam",")","if","seed",":","rng_input","=","jax.random.PRNGKey","(","seed",")","else",":","RNG_",",","rng_input","=","jax.random.split","(","_getRNG","(",")",")","_setRNG","(","RNG_",")","if","shape","is","not","None",":","shape","=","jnp.array","(","shape",")","list_shape","=","shape.tolist","(",")","_check_shapes_broadcastable","(","lam.shape",",","list_shape",")","else",":","list_shape","=","None","if","jnp.any","(","lam","<","0",")",":","pos_lam","=","jnp.where","(","lam","<","0",",","0",",","lam",")","ret","=","jax.random.poisson","(","rng_input",",","pos_lam",",","shape=list_shape",")",".astype","(","dtype",")","ret","=","jnp.where","(","lam","<","0",",","fill_value",",","ret",")","else",":","ret","=","jax.random.poisson","(","rng_input",",","lam",",","shape=list_shape",")",".astype","(","dtype",")","return","ret"] | 79 | 107 | null | random.py | ivy/ivy/functional/backends/jax/experimental/random.py | from typing import Optional, Union, Sequence
import jax.numpy
import jax
import jaxlib.xla_extension
import ivy
from ivy.functional.backends.jax import JaxArray
from ivy.functional.backends.jax.random import RNG, _setRNG, _getRNG
from ivy.functional.ivy.random import _check_bounds_and_get_shape, _check_shapes_broadcastable
from ivy.func_wrapper import with_unsupported_dtypes
from ..None import backend_version | 15 | null | 10 | 5 | null | null | null | Use image node_id 4 for calling a global function with example usage: poisson(lam) and returns: ret | 99 | node_id 4 | 1,194,967 |
rank | RerankModelPlugin | Plugin | true | self,query,choices,filter_results | Base class for reranker models | ["Base","class","for","reranker","models"] | assign relative ranks to each choice | ["assign","relative","ranks","to","each","choice"] | sorted_indices, unknown,list, list | def rank(
self,
query: str,
choices: List[str],
filter_results=defaults.filter_results,
) -> Tuple[List[int], List[float]]:
"""assign relative ranks to each choice"""
if len(choices) == 0:
return [], []
logits = self.get_logits(query, choices)
scores = []
all_scores = []
index_map = []
for i, logit in enumerate(logits):
neg_logit = logit[0]
score = logit[1]
all_scores.append(score)
if score > neg_logit or not filter_results:
scores.append(score)
index_map.append(i)
sorted_indices = [index_map[i] for i in np.argsort(scores)[::-1]]
return sorted_indices, [all_scores[i] for i in sorted_indices]
| ["def","rank","(","self",",","query",":","str",",","choices",":","List","[","str","]",",","filter_results=defaults.filter_results",",",")","-",">","Tuple","[","List","[","int","]",",","List","[","float","]","]",":","``","''","''","assign","relative","ranks","to","each","choice","''","''","''","if","len","(","choices",")","==","0",":","return","[","]",",","[","]","logits","=","self.get_logits","(","query",",","choices",")","scores","=","[","]","all_scores","=","[","]","index_map","=","[","]","for","i",",","logit","in","enumerate","(","logits",")",":","neg_logit","=","logit","[","0","]","score","=","logit","[","1","]","all_scores.append","(","score",")","if","score",">","neg_logit","or","not","filter_results",":","scores.append","(","score",")","index_map.append","(","i",")","sorted_indices","=","[","index_map","[","i","]","for","i","in","np.argsort","(","scores",")","[",":",":-1","]","]","return","sorted_indices",",","[","all_scores","[","i","]","for","i","in","sorted_indices","]"] | 53 | 72 | null | base.py | nboost/nboost/plugins/rerank/base.py | from typing import List, Tuple
import time
from nboost.plugins import Plugin
from nboost.delegates import RequestDelegate, ResponseDelegate
from nboost.helpers import calculate_mrr
from nboost.database import DatabaseRow
from nboost import defaults
import numpy | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 3 for calling the RerankModelPlugin obj's underlying member method code with example usage: obj.rank(query, choices, filter_results) and returns: sorted_indices, unknown, list, list | 201 | node_id 3 | 1,408,509 |
__call__ | PSERandomCrop | null | true | self,data | null | null | null | null | data,imgs | def __call__(self, data):
imgs = data["imgs"]
h, w = imgs[0].shape[0:2]
th, tw = self.size
if w == tw and h == th:
return imgs
# label中存在文本实例,并且按照概率进行裁剪,使用threshold_label_map控制
if np.max(imgs[2]) > 0 and random.random() > 3 / 8:
# 文本实例的左上角点
tl = np.min(np.where(imgs[2] > 0), axis=1) - self.size
tl[tl < 0] = 0
# 文本实例的右下角点
br = np.max(np.where(imgs[2] > 0), axis=1) - self.size
br[br < 0] = 0
# 保证选到右下角点时,有足够的距离进行crop
br[0] = min(br[0], h - th)
br[1] = min(br[1], w - tw)
for _ in range(50000):
i = random.randint(tl[0], br[0])
j = random.randint(tl[1], br[1])
# 保证shrink_label_map有文本
if imgs[1][i : i + th, j : j + tw].sum() <= 0:
continue
else:
break
else:
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
# return i, j, th, tw
for idx in range(len(imgs)):
if len(imgs[idx].shape) == 3:
imgs[idx] = imgs[idx][i : i + th, j : j + tw, :]
else:
imgs[idx] = imgs[idx][i : i + th, j : j + tw]
data["imgs"] = imgs
return data
| ["def","__call__","(","self",",","data",")",":","imgs","=","data","[","``","imgs","''","]","h",",","w","=","imgs","[","0","]",".shape","[","0:2","]","th",",","tw","=","self.size","if","w","==","tw","and","h","==","th",":","return","imgs","#","label\u4e2d\u5b58\u5728\u6587\u672c\u5b9e\u4f8b\uff0c\u5e76\u4e14\u6309\u7167\u6982\u7387\u8fdb\u884c\u88c1\u526a\uff0c\u4f7f\u7528threshold_label_map\u63a7\u5236","if","np.max","(","imgs","[","2","]",")",">","0","and","random.random","(",")",">","3","\/","8",":","#","\u6587\u672c\u5b9e\u4f8b\u7684\u5de6\u4e0a\u89d2\u70b9","tl","=","np.min","(","np.where","(","imgs","[","2","]",">","0",")",",","axis=1",")","-","self.size","tl","[","tl","<","0","]","=","0","#","\u6587\u672c\u5b9e\u4f8b\u7684\u53f3\u4e0b\u89d2\u70b9","br","=","np.max","(","np.where","(","imgs","[","2","]",">","0",")",",","axis=1",")","-","self.size","br","[","br","<","0","]","=","0","#","\u4fdd\u8bc1\u9009\u5230\u53f3\u4e0b\u89d2\u70b9\u65f6\uff0c\u6709\u8db3\u591f\u7684\u8ddd\u79bb\u8fdb\u884ccrop","br","[","0","]","=","min","(","br","[","0","]",",","h","-","th",")","br","[","1","]","=","min","(","br","[","1","]",",","w","-","tw",")","for","_","in","range","(","50000",")",":","i","=","random.randint","(","tl","[","0","]",",","br","[","0","]",")","j","=","random.randint","(","tl","[","1","]",",","br","[","1","]",")","#","\u4fdd\u8bc1shrink_label_map\u6709\u6587\u672c","if","imgs","[","1","]","[","i",":","i","+","th",",","j",":","j","+","tw","]",".sum","(",")","<","=","0",":","continue","else",":","break","else",":","i","=","random.randint","(","0",",","h","-","th",")","j","=","random.randint","(","0",",","w","-","tw",")","#","return","i",",","j",",","th",",","tw","for","idx","in","range","(","len","(","imgs",")",")",":","if","len","(","imgs","[","idx","]",".shape",")","==","3",":","imgs","[","idx","]","=","imgs","[","idx","]","[","i",":","i","+","th",",","j",":","j","+","tw",",",":","]","else",":","imgs","[","idx","]","=","imgs","[","idx","]","[","i",":","i","+","th",",","j",":","j","+","tw","]","data","[","``","imgs","''","]","=","imgs","return","data"] | 167 | 206 | null | random_crop_data.py | PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/random_crop_data.py | import random
import cv2
import numpy | 15 | 2 | 3 | 0 | 0 | 2 | null | Use image node_id 2 for calling the PSERandomCrop obj's underlying member method code with example usage: obj.__call__(data) and returns: data, imgs | 148 | node_id 2 | 176,896 |
gamma | global | null | false | null | null | null | null | unknown | def gamma(
alpha: Union[float, JaxArray],
beta: Union[float, JaxArray],
/,
*,
shape: Optional[Union[ivy.NativeShape, Sequence[int]]] = None,
device: Optional[jaxlib.xla_extension.Device] = None,
dtype: Optional[jnp.dtype] = None,
seed: Optional[int] = None,
out: Optional[JaxArray] = None,
) -> JaxArray:
shape = _check_bounds_and_get_shape(alpha, beta, shape).shape
RNG_, rng_input = jax.random.split(_getRNG())
_setRNG(RNG_)
if seed is not None:
jax.random.PRNGKey(seed)
return jax.random.gamma(rng_input, alpha, shape, dtype) / beta
| ["def","gamma","(","alpha",":","Union","[","float",",","JaxArray","]",",","beta",":","Union","[","float",",","JaxArray","]",",","\/",",","*",",","shape",":","Optional","[","Union","[","ivy.NativeShape",",","Sequence","[","int","]","]","]","=","None",",","device",":","Optional","[","jaxlib.xla_extension.Device","]","=","None",",","dtype",":","Optional","[","jnp.dtype","]","=","None",",","seed",":","Optional","[","int","]","=","None",",","out",":","Optional","[","JaxArray","]","=","None",",",")","-",">","JaxArray",":","shape","=","_check_bounds_and_get_shape","(","alpha",",","beta",",","shape",")",".shape","RNG_",",","rng_input","=","jax.random.split","(","_getRNG","(",")",")","_setRNG","(","RNG_",")","if","seed","is","not","None",":","jax.random.PRNGKey","(","seed",")","return","jax.random.gamma","(","rng_input",",","alpha",",","shape",",","dtype",")","\/","beta"] | 60 | 76 | null | random.py | ivy/ivy/functional/backends/jax/experimental/random.py | from typing import Optional, Union, Sequence
import jax.numpy
import jax
import jaxlib.xla_extension
import ivy
from ivy.functional.backends.jax import JaxArray
from ivy.functional.backends.jax.random import RNG, _setRNG, _getRNG
from ivy.functional.ivy.random import _check_bounds_and_get_shape, _check_shapes_broadcastable
from ivy.func_wrapper import with_unsupported_dtypes
from ..None import backend_version | 15 | null | 10 | 5 | null | null | null | Use image node_id 3 for calling a global function with example usage: gamma() and returns: unknown | 98 | node_id 3 | 1,194,966 |
|
ForwardFactory | Circle | AbstractModel | true | self,coeffs | Computes 2D array representation of a circle
where the circle minimally bounds the 2D data points
data points with [minimal, sparse, or dense] packing=[~0.2, ~1.0, or ~5.0]
setting packing = None will constrain all points to the circle's radius | ["Computes","2D","array","representation","of","a","circle","where","the","circle","minimally","bounds","the","2D","data","points","data","points","with","[","minimal",",","sparse",",","or","dense","]","packing=","[","~0.2",",","~1.0",",","or","~5.0","]","setting","packing","=","None","will","constrain","all","points","to","the","circle","'s","radius"] | generate a circle instance from a sequence of coefficients
Args:
coeffs (list[float]): (x, y, and radius) defining a circle
Returns:
a function returning a 2D array of points contained within the circle
| ["generate","a","circle","instance","from","a","sequence","of","coefficients","Args",":","coeffs","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","a","circle","Returns",":","a","function","returning","a","2D","array","of","points","contained","within","the","circle"] | forward_circle,self | def ForwardFactory(self, coeffs):
"""generate a circle instance from a sequence of coefficients
Args:
coeffs (list[float]): (x, y, and radius) defining a circle
Returns:
a function returning a 2D array of points contained within the circle
"""
x, y, r = coeffs
def forward_circle(npts=None):
"""generate a 2D array of points within the defined circle
Args:
npts (int, default=None): number of points to generate
Returns:
a 2D array of points contained within the circle (x,y,r) = (%s,%s,%s)
Notes:
default ``npts`` is ``packing * floor(pi * radius**2)``
""" % (
x,
y,
r,
)
return self.forward((x, y, r), npts)
return forward_circle
| ["def","ForwardFactory","(","self",",","coeffs",")",":","``","''","''","generate","a","circle","instance","from","a","sequence","of","coefficients","Args",":","coeffs","(","list","[","float","]",")",":","(","x",",","y",",","and","radius",")","defining","a","circle","Returns",":","a","function","returning","a","2D","array","of","points","contained","within","the","circle","``","''","''","x",",","y",",","r","=","coeffs","def","forward_circle","(","npts=None",")",":","``","''","''","generate","a","2D","array","of","points","within","the","defined","circle","Args",":","npts","(","int",",","default=None",")",":","number","of","points","to","generate","Returns",":","a","2D","array","of","points","contained","within","the","circle","(","x",",","y",",","r",")","=","(","%","s",",","%","s",",","%","s",")","Notes",":","default","``","npts","``","is","``","packing","*","floor","(","pi","*","radius","*","*","2",")","``","``","''","''","%","(","x",",","y",",","r",",",")","return","self.forward","(","(","x",",","y",",","r",")",",","npts",")","return","forward_circle"] | 61 | 84 | null | circle.py | mystic/mystic/models/circle.py | from .abstract_model import AbstractModel
from numpy import array, pi, arange
from numpy import sin, cos
from math import floor, sqrt
import random | 15 | 1 | 5 | 2 | 1 | 6 | 1 | Use image node_id 4 for calling the Circle obj's underlying member method code with example usage: obj.ForwardFactory(coeffs) and returns: forward_circle, self | 159 | node_id 4 | 1,407,075 |
df_from_dict | global | null | false | null | null | null | null | maker,unknown | def df_from_dict():
def maker(dct, is_categorical=False):
df = pd.DataFrame(dct)
return df.astype("category") if is_categorical else df
return maker
| ["def","df_from_dict","(",")",":","def","maker","(","dct",",","is_categorical=False",")",":","df","=","pd.DataFrame","(","dct",")","return","df.astype","(","``","category","''",")","if","is_categorical","else","df","return","maker"] | 14 | 19 | null | test_spec_conformance.py | pandas/pandas/tests/interchange/test_spec_conformance.py | import ctypes
import math
import pytest
import pandas | 15 | null | 4 | 11 | null | null | null | Use image node_id 1 for calling a global function with example usage: df_from_dict() and returns: maker, unknown | 112 | node_id 1 | 1,516,677 |
|
on_request | RerankModelPlugin | Plugin | true | self,request,db_row | Base class for reranker models | ["Base","class","for","reranker","models"] | null | null | null | def on_request(self, request: RequestDelegate, db_row: DatabaseRow):
db_row.topk = (
request.topk if request.topk else request.default_topk
)
request.topk = request.topn
| ["def","on_request","(","self",",","request",":","RequestDelegate",",","db_row",":","DatabaseRow",")",":","db_row.topk","=","(","request.topk","if","request.topk","else","request.default_topk",")","request.topk","=","request.topn"] | 17 | 19 | null | base.py | nboost/nboost/plugins/rerank/base.py | from typing import List, Tuple
import time
from nboost.plugins import Plugin
from nboost.delegates import RequestDelegate, ResponseDelegate
from nboost.helpers import calculate_mrr
from nboost.database import DatabaseRow
from nboost import defaults
import numpy | 15 | 1 | 8 | 0 | 1 | 5 | 1 | Use image node_id 1 for calling the RerankModelPlugin obj's underlying member method code with example usage: obj.on_request(request, db_row) without return types | 162 | node_id 1 | 1,408,507 |
__torch_dispatch__ | MetaTensor | torch | true | cls,func,types,args,kwargs | A wrapping tensor that hacks `torch.autograd` without patching more `torch.ops.aten` ops.
`fake_device` is the device that `MetaTensor` is supposed to run on. | ["A","wrapping","tensor","that","hacks","`","torch.autograd","`","without","patching","more","`","torch.ops.aten","`","ops",".","`","fake_device","`","is","the","device","that","`","MetaTensor","`","is","supposed","to","run","on","."] | null | null | tree_map,x,unknown | def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
fake_device = None
def unwrap(x):
nonlocal fake_device
if isinstance(x, MetaTensor):
fake_device = x.device
x = x._tensor
elif isinstance(x, torch.Tensor):
fake_device = x.device
x = x.to(torch.device("meta"))
return x
args = tree_map(unwrap, args)
kwargs = tree_map(unwrap, kwargs)
if "device" in kwargs:
fake_device = kwargs["device"]
kwargs["device"] = torch.device("meta")
# run aten for backend=CPU but actually on backend=Meta
out = func(*args, **kwargs)
# here we keep the uuid of input because ALIAS_ATEN do not generate a physical copy
# of the input
if func in ALIAS_ATEN:
out.data_ptr = args[0].data_ptr
# Now, we want to continue propagating this tensor, so we rewrap Tensors in
# our custom tensor subclass
def wrap(x):
if isinstance(x, torch.Tensor):
nonlocal fake_device
if not x.is_meta:
x = x.to(torch.device("meta"))
return (
MetaTensor(x, fake_device=fake_device)
if isinstance(x, torch.Tensor)
else x
)
return tree_map(wrap, out)
| ["def","__torch_dispatch__","(","cls",",","func",",","types",",","args=","(",")",",","kwargs=None",")",":","fake_device","=","None","def","unwrap","(","x",")",":","nonlocal","fake_device","if","isinstance","(","x",",","MetaTensor",")",":","fake_device","=","x.device","x","=","x._tensor","elif","isinstance","(","x",",","torch.Tensor",")",":","fake_device","=","x.device","x","=","x.to","(","torch.device","(","``","meta","''",")",")","return","x","args","=","tree_map","(","unwrap",",","args",")","kwargs","=","tree_map","(","unwrap",",","kwargs",")","if","``","device","''","in","kwargs",":","fake_device","=","kwargs","[","``","device","''","]","kwargs","[","``","device","''","]","=","torch.device","(","``","meta","''",")","#","run","aten","for","backend=CPU","but","actually","on","backend=Meta","out","=","func","(","*","args",",","*","*","kwargs",")","#","here","we","keep","the","uuid","of","input","because","ALIAS_ATEN","do","not","generate","a","physical","copy","#","of","the","input","if","func","in","ALIAS_ATEN",":","out.data_ptr","=","args","[","0","]",".data_ptr","#","Now",",","we","want","to","continue","propagating","this","tensor",",","so","we","rewrap","Tensors","in","#","our","custom","tensor","subclass","def","wrap","(","x",")",":","if","isinstance","(","x",",","torch.Tensor",")",":","nonlocal","fake_device","if","not","x.is_meta",":","x","=","x.to","(","torch.device","(","``","meta","''",")",")","return","(","MetaTensor","(","x",",","fake_device=fake_device",")","if","isinstance","(","x",",","torch.Tensor",")","else","x",")","return","tree_map","(","wrap",",","out",")"] | 63 | 100 | null | tensor.py | ColossalAI/colossalai/fx/profiler/tensor.py | import uuid
import torch
from torch.types import _device
from torch.utils._pytree import tree_map
from .._compatibility import compatibility
from .constants import ALIAS_ATEN | 15 | 1 | 6 | 1 | 1 | 6 | 1 | Use image node_id 3 for calling the MetaTensor obj's underlying member method code with example usage: obj.__torch_dispatch__(cls, func, types, args, kwargs) and returns: tree_map, x, unknown | 191 | node_id 3 | 41,012 |
test_multiple_footnotes | TestFootnotes | TestCase | true | self | null | null | null | null | null | def test_multiple_footnotes(self):
self.assertMarkdownRenders(
self.dedent(
"""
foo[^1]
bar[^2]
[^1]: Footnote 1
[^2]: Footnote 2
"""
),
'<p>foo<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup></p>\n'
'<p>bar<sup id="fnref:2"><a class="footnote-ref" href="#fn:2">2</a></sup></p>\n'
'<div class="footnote">\n'
"<hr />\n"
"<ol>\n"
'<li id="fn:1">\n'
'<p>Footnote 1 <a class="footnote-backref" href="#fnref:1"'
' title="Jump back to footnote 1 in the text">↩</a></p>\n'
"</li>\n"
'<li id="fn:2">\n'
'<p>Footnote 2 <a class="footnote-backref" href="#fnref:2"'
' title="Jump back to footnote 2 in the text">↩</a></p>\n'
"</li>\n"
"</ol>\n"
"</div>",
)
| ["def","test_multiple_footnotes","(","self",")",":","self.assertMarkdownRenders","(","self.dedent","(","``","''","''","foo","[","^1","]","bar","[","^2","]","[","^1","]",":","Footnote","1","[","^2","]",":","Footnote","2","``","''","''",")",",","'","<","p",">","foo","<","sup","id=","''","fnref:1","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn:1","''",">","1","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","p",">","bar","<","sup","id=","''","fnref:2","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn:2","''",">","2","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","div","class=","''","footnote","''",">","\\n'","``","<","hr","\/",">","\\n","''","``","<","ol",">","\\n","''","'","<","li","id=","''","fn:1","''",">","\\n'","'","<","p",">","Footnote","1","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref:1","''","'","'","title=","''","Jump","back","to","footnote","1","in","the","text","''",">","&","#","8617",";","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","'","<","li","id=","''","fn:2","''",">","\\n'","'","<","p",">","Footnote","2","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref:2","''","'","'","title=","''","Jump","back","to","footnote","2","in","the","text","''",">","&","#","8617",";","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","``","<","\/ol",">","\\n","''","``","<","\/div",">","''",",",")"] | 51 | 78 | null | test_footnotes.py | markdown/tests/test_syntax/extensions/test_footnotes.py | from markdown.test_tools import TestCase | 15 | 1 | 1 | 0 | 1 | 12 | 1 | Use image node_id 2 for calling the TestFootnotes obj's underlying member method code with example usage: obj.test_multiple_footnotes() without return types | 156 | node_id 2 | 1,299,335 |
test_backlink_text | TestFootnotes | TestCase | true | self | null | null | Test back-link configuration. | ["Test","back-link","configuration","."] | null | def test_backlink_text(self):
"""Test back-link configuration."""
self.assertMarkdownRenders(
"paragraph[^1]\n\n[^1]: A Footnote",
'<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup></p>\n'
'<div class="footnote">\n'
"<hr />\n"
"<ol>\n"
'<li id="fn:1">\n'
'<p>A Footnote <a class="footnote-backref" href="#fnref:1"'
' title="Jump back to footnote 1 in the text">back</a></p>\n'
"</li>\n"
"</ol>\n"
"</div>",
extension_configs={"footnotes": {"BACKLINK_TEXT": "back"}},
)
| ["def","test_backlink_text","(","self",")",":","``","''","''","Test","back-link","configuration",".","''","''","''","self.assertMarkdownRenders","(","``","paragraph","[","^1","]","\\n\\n","[","^1","]",":","A","Footnote","''",",","'","<","p",">","paragraph","<","sup","id=","''","fnref:1","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn:1","''",">","1","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","div","class=","''","footnote","''",">","\\n'","``","<","hr","\/",">","\\n","''","``","<","ol",">","\\n","''","'","<","li","id=","''","fn:1","''",">","\\n'","'","<","p",">","A","Footnote","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref:1","''","'","'","title=","''","Jump","back","to","footnote","1","in","the","text","''",">","back","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","``","<","\/ol",">","\\n","''","``","<","\/div",">","''",",","extension_configs=","{","``","footnotes","''",":","{","``","BACKLINK_TEXT","''",":","``","back","''","}","}",",",")"] | 268 | 284 | null | test_footnotes.py | markdown/tests/test_syntax/extensions/test_footnotes.py | from markdown.test_tools import TestCase | 15 | 1 | 1 | 0 | 1 | 12 | 1 | Use image node_id 9 for calling the TestFootnotes obj's underlying member method code with example usage: obj.test_backlink_text() without return types | 151 | node_id 9 | 1,299,342 |
_format_arg | MatlabCommand | CommandLine | true | self,name,trait_spec,value | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | null | null | super,self | def _format_arg(self, name, trait_spec, value):
if name in ["script"]:
argstr = trait_spec.argstr
if self.inputs.uses_mcr:
argstr = "%s"
return self._gen_matlab_command(argstr, value)
return super()._format_arg(name, trait_spec, value)
| ["def","_format_arg","(","self",",","name",",","trait_spec",",","value",")",":","if","name","in","[","``","script","''","]",":","argstr","=","trait_spec.argstr","if","self.inputs.uses_mcr",":","argstr","=","``","%","s","''","return","self._gen_matlab_command","(","argstr",",","value",")","return","super","(",")","._format_arg","(","name",",","trait_spec",",","value",")"] | 166 | 172 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 6 for calling the MatlabCommand obj's underlying member method code with example usage: obj._format_arg(name, trait_spec, value) and returns: super, self | 171 | node_id 6 | 1,440,238 |
pytest_addoption | global | null | false | parser | null | null | null | null | null | def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup("terminal reporting")
group._addoption(
"--pastebin",
metavar="mode",
action="store",
dest="pastebin",
default=None,
choices=["failed", "all"],
help="Send failed|all info to bpaste.net pastebin service",
)
| ["def","pytest_addoption","(","parser",":","Parser",")","-",">","None",":","group","=","parser.getgroup","(","``","terminal","reporting","''",")","group._addoption","(","``","--","pastebin","''",",","metavar=","''","mode","''",",","action=","''","store","''",",","dest=","''","pastebin","''",",","default=None",",","choices=","[","``","failed","''",",","``","all","''","]",",","help=","''","Send","failed|all","info","to","bpaste.net","pastebin","service","''",",",")"] | 18 | 28 | null | pastebin.py | pytest/src/_pytest/pastebin.py | import tempfile
from io import StringIO
from typing import IO
from typing import Union
import pytest
from _pytest.config import Config
from _pytest.config import create_terminal_writer
from _pytest.config.argparsing import Parser
from _pytest.stash import StashKey
from _pytest.terminal import TerminalReporter | 15 | null | 10 | 5 | null | null | null | Use image node_id 1 for calling a global function with example usage: pytest_addoption(parser) without return types | 115 | node_id 1 | 1,676,293 |
compute_composite_distance | global | null | false | distance,x,y | null | null | null | null | ans | def compute_composite_distance(distance, x, y):
"""
Compute the value of a composite distance function on two dictionaries,
typically SFrame rows.
Parameters
----------
distance : list[list]
A composite distance function. Composite distance functions are a
weighted sum of standard distance functions, each of which applies to
its own subset of features. Composite distance functions are specified
as a list of distance components, each of which is itself a list
containing three items:
1. list or tuple of feature names (strings)
2. standard distance name (string)
3. scaling factor (int or float)
x, y : dict
Individual observations, typically rows of an SFrame, in dictionary
form. Must include the features specified by `distance`.
Returns
-------
out : float
The distance between `x` and `y`, as specified by `distance`.
Examples
--------
>>> sf = turicreate.SFrame({'X1': [0.98, 0.62, 0.11],
... 'X2': [0.69, 0.58, 0.36],
... 'species': ['cat', 'dog', 'fossa']})
...
>>> dist_spec = [[('X1', 'X2'), 'euclidean', 2],
... [('species',), 'levenshtein', 0.4]]
...
>>> d = turicreate.distances.compute_composite_distance(dist_spec, sf[0], sf[1])
>>> print d
1.95286120899
"""
## Validate inputs
_validate_composite_distance(distance)
distance = _convert_distance_names_to_functions(distance)
if not isinstance(x, dict) or not isinstance(y, dict):
raise TypeError(
"Inputs 'x' and 'y' must be in dictionary form. "
+ "Selecting individual rows of an SFrame yields the "
+ "correct format."
)
ans = 0.0
for d in distance:
ftrs, dist, weight = d
## Special check for multiple columns with levenshtein distance.
if dist == _tc.distances.levenshtein and len(ftrs) > 1:
raise ValueError(
"levenshtein distance cannot be used with multiple"
+ "columns. Please concatenate strings into a single "
+ "column before computing the distance."
)
## Extract values for specified features.
a = {}
b = {}
for ftr in ftrs:
if type(x[ftr]) != type(y[ftr]):
if not isinstance(
x[ftr], (int, float)
) or not isinstance(y[ftr], (int, float)):
raise ValueError(
"Input data has different types."
)
if isinstance(x[ftr], (int, float, str)):
a[ftr] = x[ftr]
b[ftr] = y[ftr]
elif isinstance(x[ftr], dict):
for key, val in _six.iteritems(x[ftr]):
a["{}.{}".format(ftr, key)] = val
for key, val in _six.iteritems(y[ftr]):
b["{}.{}".format(ftr, key)] = val
elif isinstance(x[ftr], (list, _array.array)):
for i, val in enumerate(x[ftr]):
a[i] = val
for i, val in enumerate(y[ftr]):
b[i] = val
else:
raise TypeError(
"Type of feature '{}' not understood.".format(ftr)
)
## Pull out the raw values for levenshtein
if dist == _tc.distances.levenshtein:
a = list(a.values())[0]
b = list(b.values())[0]
## Compute component distance and add to the total distance.
ans += weight * dist(a, b)
return ans
| ["def","compute_composite_distance","(","distance",",","x",",","y",")",":","``","''","''","Compute","the","value","of","a","composite","distance","function","on","two","dictionaries",",","typically","SFrame","rows",".","Parameters","--","--","--","--","--","distance",":","list","[","list","]","A","composite","distance","function",".","Composite","distance","functions","are","a","weighted","sum","of","standard","distance","functions",",","each","of","which","applies","to","its","own","subset","of","features",".","Composite","distance","functions","are","specified","as","a","list","of","distance","components",",","each","of","which","is","itself","a","list","containing","three","items",":","1.","list","or","tuple","of","feature","names","(","strings",")","2.","standard","distance","name","(","string",")","3.","scaling","factor","(","int","or","float",")","x",",","y",":","dict","Individual","observations",",","typically","rows","of","an","SFrame",",","in","dictionary","form",".","Must","include","the","features","specified","by","`","distance","`",".","Returns","--","--","--","-","out",":","float","The","distance","between","`","x","`","and","`","y","`",",","as","specified","by","`","distance","`",".","Examples","--","--","--","--",">",">",">","sf","=","turicreate.SFrame","(","{","'X1","'",":","[","0.98",",","0.62",",","0.11","]",",","...","'X2","'",":","[","0.69",",","0.58",",","0.36","]",",","...","'species","'",":","[","'cat","'",",","'dog","'",",","'fossa","'","]","}",")","...",">",">",">","dist_spec","=","[","[","(","'X1","'",",","'X2","'",")",",","'euclidean","'",",","2","]",",","...","[","(","'species","'",",",")",",","'levenshtein","'",",","0.4","]","]","...",">",">",">","d","=","turicreate.distances.compute_composite_distance","(","dist_spec",",","sf","[","0","]",",","sf","[","1","]",")",">",">",">","print","d","1.95286120899","``","''","''","#","#","Validate","inputs","_validate_composite_distance","(","distance",")","distance","=","_convert_distance_names_to_functions","(","distance",")","if","not","isinstance","(","x",",","dict",")","or","not","isinstance","(","y",",","dict",")",":","raise","TypeError","(","``","Inputs","'","x","'","and","'","y","'","must","be","in","dictionary","form.","``","+","``","Selecting","individual","rows","of","an","SFrame","yields","the","``","+","``","correct","format",".","''",")","ans","=","0.0","for","d","in","distance",":","ftrs",",","dist",",","weight","=","d","#","#","Special","check","for","multiple","columns","with","levenshtein","distance",".","if","dist","==","_tc.distances.levenshtein","and","len","(","ftrs",")",">","1",":","raise","ValueError","(","``","levenshtein","distance","can","not","be","used","with","multiple","''","+","``","columns",".","Please","concatenate","strings","into","a","single","``","+","``","column","before","computing","the","distance",".","''",")","#","#","Extract","values","for","specified","features",".","a","=","{","}","b","=","{","}","for","ftr","in","ftrs",":","if","type","(","x","[","ftr","]",")","!","=","type","(","y","[","ftr","]",")",":","if","not","isinstance","(","x","[","ftr","]",",","(","int",",","float",")",")","or","not","isinstance","(","y","[","ftr","]",",","(","int",",","float",")",")",":","raise","ValueError","(","``","Input","data","has","different","types",".","''",")","if","isinstance","(","x","[","ftr","]",",","(","int",",","float",",","str",")",")",":","a","[","ftr","]","=","x","[","ftr","]","b","[","ftr","]","=","y","[","ftr","]","elif","isinstance","(","x","[","ftr","]",",","dict",")",":","for","key",",","val","in","_six.iteritems","(","x","[","ftr","]",")",":","a","[","``","{","}",".","{","}","''",".format","(","ftr",",","key",")","]","=","val","for","key",",","val","in","_six.iteritems","(","y","[","ftr","]",")",":","b","[","``","{","}",".","{","}","''",".format","(","ftr",",","key",")","]","=","val","elif","isinstance","(","x","[","ftr","]",",","(","list",",","_array.array",")",")",":","for","i",",","val","in","enumerate","(","x","[","ftr","]",")",":","a","[","i","]","=","val","for","i",",","val","in","enumerate","(","y","[","ftr","]",")",":","b","[","i","]","=","val","else",":","raise","TypeError","(","``","Type","of","feature","'","{","}","'","not","understood",".","``",".format","(","ftr",")",")","#","#","Pull","out","the","raw","values","for","levenshtein","if","dist","==","_tc.distances.levenshtein",":","a","=","list","(","a.values","(",")",")","[","0","]","b","=","list","(","b.values","(",")",")","[","0","]","#","#","Compute","component","distance","and","add","to","the","total","distance",".","ans","+=","weight","*","dist","(","a",",","b",")","return","ans"] | 26 | 133 | null | _util.py | turicreate/src/python/turicreate/toolkits/distances/_util.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import copy
import array
import six
from operator import iadd
import turicreate
import sys | 15 | null | 9 | 6 | null | null | null | Use image node_id 1 for calling a global function with example usage: compute_composite_distance(distance, x, y) and returns: ans | 129 | node_id 1 | 2,285,729 |
create_app_session_from_tty | global | null | false | null | null | null | null | null | def create_app_session_from_tty() -> (
Generator[AppSession, None, None]
):
"""
Create `AppSession` that always prefers the TTY input/output.
Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes,
this will still use the terminal for interaction (because `sys.stderr` is
still connected to the terminal).
Usage::
from prompt_toolkit.shortcuts import prompt
with create_app_session_from_tty():
prompt('>')
"""
from prompt_toolkit.input.defaults import create_input
from prompt_toolkit.output.defaults import create_output
input = create_input(always_prefer_tty=True)
output = create_output(always_prefer_tty=True)
with create_app_session(
input=input, output=output
) as app_session:
yield app_session
| ["def","create_app_session_from_tty","(",")","-",">","(","Generator","[","AppSession",",","None",",","None","]",")",":","``","''","''","Create","`","AppSession","`","that","always","prefers","the","TTY","input\/output",".","Even","if","`","sys.stdin","`","and","`","sys.stdout","`","are","connected","to","input\/output","pipes",",","this","will","still","use","the","terminal","for","interaction","(","because","`","sys.stderr","`","is","still","connected","to","the","terminal",")",".","Usage",":",":","from","prompt_toolkit.shortcuts","import","prompt","with","create_app_session_from_tty","(",")",":","prompt","(","'",">","'",")","``","''","''","from","prompt_toolkit.input.defaults","import","create_input","from","prompt_toolkit.output.defaults","import","create_output","input","=","create_input","(","always_prefer_tty=True",")","output","=","create_output","(","always_prefer_tty=True",")","with","create_app_session","(","input=input",",","output=output",")","as","app_session",":","yield","app_session"] | 167 | 189 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 6 for calling a global function with example usage: create_app_session_from_tty() without return types | 120 | node_id 6 | 500,082 |
|
__init__ | BeatsAudioProcessor | BaseProcessor | true | self,model_name,sampling_rate,n_frames,frame_length,is_eval | null | null | Adapted from https://github.com/NINAnor/rare_species_detections/blob/main/BEATs/BEATs.py | ["Adapted","from","https",":","\/\/github.com\/NINAnor\/rare_species_detections\/blob\/main\/BEATs\/BEATs.py"] | BeatsAudioProcessor | def __init__(
self, model_name, sampling_rate, n_frames, frame_length, is_eval
):
"""
Adapted from https://github.com/NINAnor/rare_species_detections/blob/main/BEATs/BEATs.py
"""
super().__init__()
self.model_name = model_name
self.sampling_rate = sampling_rate
self.n_frames = n_frames
self.frame_length = frame_length
self.fbank_mean = 15.41663
self.fbank_std = 6.55582
self.is_eval = is_eval
| ["def","__init__","(","self",",","model_name",",","sampling_rate",",","n_frames",",","frame_length",",","is_eval",")",":","``","''","''","Adapted","from","https",":","\/\/github.com\/NINAnor\/rare_species_detections\/blob\/main\/BEATs\/BEATs.py","``","''","''","super","(",")",".__init__","(",")","self.model_name","=","model_name","self.sampling_rate","=","sampling_rate","self.n_frames","=","n_frames","self.frame_length","=","frame_length","self.fbank_mean","=","15.41663","self.fbank_std","=","6.55582","self.is_eval","=","is_eval"] | 24 | 36 | null | audio_processors.py | lavis/lavis/processors/audio_processors.py | import torch
import torchaudio
import torchaudio.transforms
from moviepy.editor import VideoFileClip
from omegaconf import OmegaConf
import torchaudio.compliance.kaldi
from lavis.common.registry import registry
from lavis.processors.base_processor import BaseProcessor
from lavis.models.beats.Tokenizers import TokenizersConfig, Tokenizers | 15 | 1 | 9 | 0 | 1 | 4 | 1 | Use image node_id 1 to create a new BeatsAudioProcessor object from inherited base classes: BaseProcessor with example: obj = BeatsAudioProcessor(model_name, sampling_rate, n_frames, frame_length, is_eval) | 205 | node_id 1 | 1,253,425 |
test_local_mode | TestLLavaCallBinaryWithConfig | unittest | true | self,mock_post | null | null | null | null | null | def test_local_mode(self, mock_post):
# Mocking the response of requests.post
mock_response = MagicMock()
mock_response.iter_lines.return_value = [
b'{"text":"response text"}'
]
mock_post.return_value = mock_response
# Calling the function
output = _llava_call_binary_with_config(
prompt="Test Prompt",
images=[],
config={
"base_url": "http://0.0.0.0/api",
"model": "test-model",
},
max_new_tokens=1000,
temperature=0.5,
seed=1,
)
# Verifying the results
self.assertEqual(output, "response text")
mock_post.assert_called_once_with(
"http://0.0.0.0/api/worker_generate_stream",
headers={"User-Agent": "LLaVA Client"},
json={
"model": "test-model",
"prompt": "Test Prompt",
"max_new_tokens": 1000,
"temperature": 0.5,
"stop": "###",
"images": [],
},
stream=False,
)
| ["def","test_local_mode","(","self",",","mock_post",")",":","#","Mocking","the","response","of","requests.post","mock_response","=","MagicMock","(",")","mock_response.iter_lines.return_value","=","[","b","'","{","``","text","''",":","''","response","text","''","}","'","]","mock_post.return_value","=","mock_response","#","Calling","the","function","output","=","_llava_call_binary_with_config","(","prompt=","''","Test","Prompt","''",",","images=","[","]",",","config=","{","``","base_url","''",":","``","http",":","\/\/0.0.0.0\/api","''",",","``","model","''",":","``","test-model","''",",","}",",","max_new_tokens=1000",",","temperature=0.5",",","seed=1",",",")","#","Verifying","the","results","self.assertEqual","(","output",",","``","response","text","''",")","mock_post.assert_called_once_with","(","``","http",":","\/\/0.0.0.0\/api\/worker_generate_stream","''",",","headers=","{","``","User-Agent","''",":","``","LLaVA","Client","''","}",",","json=","{","``","model","''",":","``","test-model","''",",","``","prompt","''",":","``","Test","Prompt","''",",","``","max_new_tokens","''",":","1000",",","``","temperature","''",":","0.5",",","``","stop","''",":","``","#","#","#","''",",","``","images","''",":","[","]",",","}",",","stream=False",",",")"] | 40 | 70 | null | test_llava.py | autogen/test/agentchat/contrib/test_llava.py | import unittest
from unittest.mock import MagicMock, patch
import pytest
import autogen | 15 | 3 | 4 | 0 | 3 | 2 | 1 | Use image node_id 1 for calling the TestLLavaCallBinaryWithConfig obj's underlying member method code with example usage: obj.test_local_mode(mock_post) without return types | 173 | node_id 1 | 319,289 |
_load_audio | BeatsAudioProcessor | BaseProcessor | true | self,aupath | null | null | null | null | waveform | def _load_audio(self, aupath):
if aupath.endswith(".mp4"):
video = VideoFileClip(aupath)
audio_np = video.audio.to_soundarray(fps=self.sampling_rate)
if len(audio_np.shape) == 2:
audio_np = audio_np.mean(axis=1) # Convert to mono
waveform = torch.tensor(audio_np).float()
sr = self.sampling_rate
else:
waveform, sr = torchaudio.load(aupath)
if waveform.shape[0] == 2:
waveform = torch.mean(waveform, dim=0)
if sr != self.sampling_rate:
resampler = torchaudio.transforms.Resample(
sr, self.sampling_rate
)
waveform = resampler(waveform)
return waveform
| ["def","_load_audio","(","self",",","aupath",")",":","if","aupath.endswith","(","``",".mp4","''",")",":","video","=","VideoFileClip","(","aupath",")","audio_np","=","video.audio.to_soundarray","(","fps=self.sampling_rate",")","if","len","(","audio_np.shape",")","==","2",":","audio_np","=","audio_np.mean","(","axis=1",")","#","Convert","to","mono","waveform","=","torch.tensor","(","audio_np",")",".float","(",")","sr","=","self.sampling_rate","else",":","waveform",",","sr","=","torchaudio.load","(","aupath",")","if","waveform.shape","[","0","]","==","2",":","waveform","=","torch.mean","(","waveform",",","dim=0",")","if","sr","!","=","self.sampling_rate",":","resampler","=","torchaudio.transforms.Resample","(","sr",",","self.sampling_rate",")","waveform","=","resampler","(","waveform",")","return","waveform"] | 38 | 53 | null | audio_processors.py | lavis/lavis/processors/audio_processors.py | import torch
import torchaudio
import torchaudio.transforms
from moviepy.editor import VideoFileClip
from omegaconf import OmegaConf
import torchaudio.compliance.kaldi
from lavis.common.registry import registry
from lavis.processors.base_processor import BaseProcessor
from lavis.models.beats.Tokenizers import TokenizersConfig, Tokenizers | 15 | 1 | 9 | 0 | 1 | 4 | 1 | Use image node_id 2 for calling the BeatsAudioProcessor obj's underlying member method code with example usage: obj._load_audio(aupath) and returns: waveform | 157 | node_id 2 | 1,253,426 |
__call__ | BeatsAudioProcessor | BaseProcessor | true | self,aupath,start_sec,end_sec | null | null | Args:
aupath: path to audio file
Returns:
torch.tensor: audio clip after transforms. | ["Args",":","aupath",":","path","to","audio","file","Returns",":","torch.tensor",":","audio","clip","after","transforms","."] | torch,torch,empty_audio_tensor,empty_audio_tensor,empty_audio_tensor | def __call__(self, aupath, start_sec=None, end_sec=None):
"""
Args:
aupath: path to audio file
Returns:
torch.tensor: audio clip after transforms.
"""
# Helper function to return empty tensor for invalid audio
def empty_audio_tensor():
return torch.zeros((self.n_frames, self.frame_length, 128))
try:
# Handle MP4 files
if aupath.endswith(".mp4"):
video = VideoFileClip(aupath)
if start_sec is not None and end_sec is not None:
video = video.subclip(start_sec, end_sec)
audio_np = video.audio.to_soundarray(
fps=self.sampling_rate
)
if audio_np.ndim == 2:
audio_np = audio_np.mean(axis=1) # Convert to mono
waveform = torch.tensor(audio_np).float()
sr = self.sampling_rate
else:
waveform, sr = torchaudio.load(aupath)
# Validate waveform
if len(waveform.shape) == 0:
return empty_audio_tensor()
# Convert stereo to mono
if waveform.shape[0] == 2:
waveform = torch.mean(waveform, dim=0)
# Resample waveform if necessary
if sr != self.sampling_rate:
resampler = torchaudio.transforms.Resample(
sr, self.sampling_rate
)
waveform = resampler(waveform)
except:
return empty_audio_tensor()
if waveform.ndim == 1:
waveform = waveform.unsqueeze(0)
waveform = waveform * 2**15
# Compute fbank features
try:
fbank = ta_kaldi.fbank(
waveform,
num_mel_bins=128,
sample_frequency=self.sampling_rate,
frame_length=25,
frame_shift=10,
)
fbank = (fbank - self.fbank_mean) / (2 * self.fbank_std)
except:
return empty_audio_tensor()
# Handle padding and frames extraction differently for eval and training modes
if not self.is_eval:
fbank_pad_len = (
self.frame_length * self.n_frames - fbank.shape[0]
)
if fbank_pad_len > 0:
fbank = torch.nn.ZeroPad2d((0, 0, 0, fbank_pad_len))(
fbank
)
fbank = fbank[: self.frame_length * self.n_frames]
frames = [
fbank[
i * self.frame_length : (i + 1) * self.frame_length
].unsqueeze(0)
for i in range(self.n_frames)
]
else:
fbank_pad_len = fbank.shape[0] % self.frame_length
if fbank_pad_len > 0:
fbank = torch.nn.ZeroPad2d((0, 0, 0, fbank_pad_len))(
fbank
)
curr_frames = fbank.shape[0] // self.frame_length
frames = [
fbank[
i * self.frame_length : (i + 1) * self.frame_length
].unsqueeze(0)
for i in range(curr_frames)
]
return torch.cat(frames, dim=0)
| ["def","__call__","(","self",",","aupath",",","start_sec=None",",","end_sec=None",")",":","``","''","''","Args",":","aupath",":","path","to","audio","file","Returns",":","torch.tensor",":","audio","clip","after","transforms.","``","''","''","#","Helper","function","to","return","empty","tensor","for","invalid","audio","def","empty_audio_tensor","(",")",":","return","torch.zeros","(","(","self.n_frames",",","self.frame_length",",","128",")",")","try",":","#","Handle","MP4","files","if","aupath.endswith","(","``",".mp4","''",")",":","video","=","VideoFileClip","(","aupath",")","if","start_sec","is","not","None","and","end_sec","is","not","None",":","video","=","video.subclip","(","start_sec",",","end_sec",")","audio_np","=","video.audio.to_soundarray","(","fps=self.sampling_rate",")","if","audio_np.ndim","==","2",":","audio_np","=","audio_np.mean","(","axis=1",")","#","Convert","to","mono","waveform","=","torch.tensor","(","audio_np",")",".float","(",")","sr","=","self.sampling_rate","else",":","waveform",",","sr","=","torchaudio.load","(","aupath",")","#","Validate","waveform","if","len","(","waveform.shape",")","==","0",":","return","empty_audio_tensor","(",")","#","Convert","stereo","to","mono","if","waveform.shape","[","0","]","==","2",":","waveform","=","torch.mean","(","waveform",",","dim=0",")","#","Resample","waveform","if","necessary","if","sr","!","=","self.sampling_rate",":","resampler","=","torchaudio.transforms.Resample","(","sr",",","self.sampling_rate",")","waveform","=","resampler","(","waveform",")","except",":","return","empty_audio_tensor","(",")","if","waveform.ndim","==","1",":","waveform","=","waveform.unsqueeze","(","0",")","waveform","=","waveform","*","2","*","*","15","#","Compute","fbank","features","try",":","fbank","=","ta_kaldi.fbank","(","waveform",",","num_mel_bins=128",",","sample_frequency=self.sampling_rate",",","frame_length=25",",","frame_shift=10",",",")","fbank","=","(","fbank","-","self.fbank_mean",")","\/","(","2","*","self.fbank_std",")","except",":","return","empty_audio_tensor","(",")","#","Handle","padding","and","frames","extraction","differently","for","eval","and","training","modes","if","not","self.is_eval",":","fbank_pad_len","=","(","self.frame_length","*","self.n_frames","-","fbank.shape","[","0","]",")","if","fbank_pad_len",">","0",":","fbank","=","torch.nn.ZeroPad2d","(","(","0",",","0",",","0",",","fbank_pad_len",")",")","(","fbank",")","fbank","=","fbank","[",":","self.frame_length","*","self.n_frames","]","frames","=","[","fbank","[","i","*","self.frame_length",":","(","i","+","1",")","*","self.frame_length","]",".unsqueeze","(","0",")","for","i","in","range","(","self.n_frames",")","]","else",":","fbank_pad_len","=","fbank.shape","[","0","]","%","self.frame_length","if","fbank_pad_len",">","0",":","fbank","=","torch.nn.ZeroPad2d","(","(","0",",","0",",","0",",","fbank_pad_len",")",")","(","fbank",")","curr_frames","=","fbank.shape","[","0","]","\/\/","self.frame_length","frames","=","[","fbank","[","i","*","self.frame_length",":","(","i","+","1",")","*","self.frame_length","]",".unsqueeze","(","0",")","for","i","in","range","(","curr_frames",")","]","return","torch.cat","(","frames",",","dim=0",")"] | 55 | 128 | null | audio_processors.py | lavis/lavis/processors/audio_processors.py | import torch
import torchaudio
import torchaudio.transforms
from moviepy.editor import VideoFileClip
from omegaconf import OmegaConf
import torchaudio.compliance.kaldi
from lavis.common.registry import registry
from lavis.processors.base_processor import BaseProcessor
from lavis.models.beats.Tokenizers import TokenizersConfig, Tokenizers | 15 | 1 | 9 | 0 | 1 | 4 | 1 | Use image node_id 3 for calling the BeatsAudioProcessor obj's underlying member method code with example usage: obj.__call__(aupath, start_sec, end_sec) and returns: torch, torch, empty_audio_tensor, empty_audio_tensor, empty_audio_tensor | 238 | node_id 3 | 1,253,427 |
_gen_matlab_command | MatlabCommand | CommandLine | true | self,argstr,script_lines | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | Generates commands and, if mfile specified, writes it to disk. | ["Generates","commands","and",",","if","mfile","specified",",","writes","it","to","disk","."] | unknown | def _gen_matlab_command(self, argstr, script_lines):
"""Generates commands and, if mfile specified, writes it to disk."""
cwd = os.getcwd()
mfile = self.inputs.mfile or self.inputs.uses_mcr
paths = []
if isdefined(self.inputs.paths):
paths = self.inputs.paths
# prescript
prescript = self.inputs.prescript
postscript = self.inputs.postscript
# prescript takes different default value depending on the mfile argument
if mfile:
prescript.insert(
0,
"fprintf(1,'Executing %s at %s:\\n',mfilename(),datestr(now));",
)
else:
prescript.insert(
0, "fprintf(1,'Executing code at %s:\\n',datestr(now));"
)
for path in paths:
# addpath() is not available after compilation
# https://www.mathworks.com/help/compiler/ismcc.html
# https://www.mathworks.com/help/compiler/isdeployed.html
prescript.append(
"if ~(ismcc || isdeployed), addpath('%s'); end;\n" % path
)
if not mfile:
# clean up the code of comments and replace newlines with commas
script_lines = ",".join(
[
line
for line in script_lines.split("\n")
if not line.strip().startswith("%")
]
)
script_lines = (
"\n".join(prescript) + script_lines + "\n".join(postscript)
)
if mfile:
with open(
os.path.join(cwd, self.inputs.script_file), "w"
) as mfile:
mfile.write(script_lines)
if self.inputs.uses_mcr:
script = "%s" % (
os.path.join(cwd, self.inputs.script_file)
)
else:
script = "addpath('{}');{}".format(
cwd,
self.inputs.script_file.split(".")[0],
)
else:
script = "".join(script_lines.split("\n"))
return argstr % script
| ["def","_gen_matlab_command","(","self",",","argstr",",","script_lines",")",":","``","''","''","Generates","commands","and",",","if","mfile","specified",",","writes","it","to","disk",".","''","''","''","cwd","=","os.getcwd","(",")","mfile","=","self.inputs.mfile","or","self.inputs.uses_mcr","paths","=","[","]","if","isdefined","(","self.inputs.paths",")",":","paths","=","self.inputs.paths","#","prescript","prescript","=","self.inputs.prescript","postscript","=","self.inputs.postscript","#","prescript","takes","different","default","value","depending","on","the","mfile","argument","if","mfile",":","prescript.insert","(","0",",","``","fprintf","(","1",",","'Executing","%","s","at","%","s",":","\\\\n","'",",","mfilename","(",")",",","datestr","(","now",")",")",";","''",",",")","else",":","prescript.insert","(","0",",","``","fprintf","(","1",",","'Executing","code","at","%","s",":","\\\\n","'",",","datestr","(","now",")",")",";","''",")","for","path","in","paths",":","#","addpath","(",")","is","not","available","after","compilation","#","https",":","\/\/www.mathworks.com\/help\/compiler\/ismcc.html","#","https",":","\/\/www.mathworks.com\/help\/compiler\/isdeployed.html","prescript.append","(","``","if","~","(","ismcc","||","isdeployed",")",",","addpath","(","'","%","s","'",")",";","end",";","\\n","''","%","path",")","if","not","mfile",":","#","clean","up","the","code","of","comments","and","replace","newlines","with","commas","script_lines","=","``",",","''",".join","(","[","line","for","line","in","script_lines.split","(","``","\\n","''",")","if","not","line.strip","(",")",".startswith","(","``","%","''",")","]",")","script_lines","=","(","``","\\n","''",".join","(","prescript",")","+","script_lines","+","``","\\n","''",".join","(","postscript",")",")","if","mfile",":","with","open","(","os.path.join","(","cwd",",","self.inputs.script_file",")",",","``","w","''",")","as","mfile",":","mfile.write","(","script_lines",")","if","self.inputs.uses_mcr",":","script","=","``","%","s","''","%","(","os.path.join","(","cwd",",","self.inputs.script_file",")",")","else",":","script","=","``","addpath","(","'","{","}","'",")",";","{","}","''",".format","(","cwd",",","self.inputs.script_file.split","(","``",".","``",")","[","0","]",",",")","else",":","script","=","``","''",".join","(","script_lines.split","(","``","\\n","''",")",")","return","argstr","%","script"] | 174 | 221 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 7 for calling the MatlabCommand obj's underlying member method code with example usage: obj._gen_matlab_command(argstr, script_lines) and returns: unknown | 172 | node_id 7 | 1,440,239 |
get_matlab_command | global | null | false | null | null | null | null | which | def get_matlab_command():
"""Determine whether Matlab is installed and can be executed."""
if "NIPYPE_NO_MATLAB" not in os.environ:
from nipype.utils.filemanip import which
return which(os.getenv("MATLABCMD", "matlab"))
| ["def","get_matlab_command","(",")",":","``","''","''","Determine","whether","Matlab","is","installed","and","can","be","executed",".","''","''","''","if","``","NIPYPE_NO_MATLAB","''","not","in","os.environ",":","from","nipype.utils.filemanip","import","which","return","which","(","os.getenv","(","``","MATLABCMD","''",",","``","matlab","''",")",")"] | 18 | 23 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | null | 3 | 1 | null | null | null | Use image node_id 1 for calling a global function with example usage: get_matlab_command() and returns: which | 109 | node_id 1 | 1,440,240 |
|
test_inverse | global | null | false | trn | null | null | null | null | null | def test_inverse(trn):
rng = np.random.RandomState(0)
N = 20
x = rng.normal(size=(N, 3))
pw = rng.normal(size=(N, 3), scale=3)
pos = x * 10**pw
assert_allclose(
pos, trn.inverse.map(trn.map(pos))[:, :3], atol=1e-7
)
| ["def","test_inverse","(","trn",")",":","rng","=","np.random.RandomState","(","0",")","N","=","20","x","=","rng.normal","(","size=","(","N",",","3",")",")","pw","=","rng.normal","(","size=","(","N",",","3",")",",","scale=3",")","pos","=","x","*","10","*","*","pw","assert_allclose","(","pos",",","trn.inverse.map","(","trn.map","(","pos",")",")","[",":",",",":3","]",",","atol=1e-7",")"] | 228 | 235 | null | test_transforms.py | vispy/vispy/visuals/transforms/tests/test_transforms.py | import numpy
from numpy.testing import assert_allclose
import pytest
import vispy.visuals.transforms
from vispy.geometry import Rect
from vispy.testing import run_tests_if_main | 15 | null | 6 | 9 | null | null | null | Use image node_id 9 for calling a global function with example usage: test_inverse(trn) without return types | 108 | node_id 9 | 2,321,323 |
test_affine_mapping | global | null | false | null | null | null | null | null | def test_affine_mapping():
t = tr.MatrixTransform()
p1 = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]])
# test pure translation
p2 = p1 + 5.5
t.set_mapping(p1, p2)
assert np.allclose(t.map(p1)[:, : p2.shape[1]], p2)
# test pure scaling
p2 = p1 * 5.5
t.set_mapping(p1, p2)
assert np.allclose(t.map(p1)[:, : p2.shape[1]], p2)
# test scale + translate
p2 = (p1 * 5.5) + 3.5
t.set_mapping(p1, p2)
assert np.allclose(t.map(p1)[:, : p2.shape[1]], p2)
# test SRT
p2 = np.array([[10, 5, 3], [10, 15, 3], [30, 5, 3], [10, 5, 3.5]])
t.set_mapping(p1, p2)
assert np.allclose(t.map(p1)[:, : p2.shape[1]], p2)
| ["def","test_affine_mapping","(",")",":","t","=","tr.MatrixTransform","(",")","p1","=","np.array","(","[","[","0",",","0",",","0","]",",","[","1",",","0",",","0","]",",","[","0",",","1",",","0","]",",","[","0",",","0",",","1","]","]",")","#","test","pure","translation","p2","=","p1","+","5.5","t.set_mapping","(","p1",",","p2",")","assert","np.allclose","(","t.map","(","p1",")","[",":",",",":","p2.shape","[","1","]","]",",","p2",")","#","test","pure","scaling","p2","=","p1","*","5.5","t.set_mapping","(","p1",",","p2",")","assert","np.allclose","(","t.map","(","p1",")","[",":",",",":","p2.shape","[","1","]","]",",","p2",")","#","test","scale","+","translate","p2","=","(","p1","*","5.5",")","+","3.5","t.set_mapping","(","p1",",","p2",")","assert","np.allclose","(","t.map","(","p1",")","[",":",",",":","p2.shape","[","1","]","]",",","p2",")","#","test","SRT","p2","=","np.array","(","[","[","10",",","5",",","3","]",",","[","10",",","15",",","3","]",",","[","30",",","5",",","3","]",",","[","10",",","5",",","3.5","]","]",")","t.set_mapping","(","p1",",","p2",")","assert","np.allclose","(","t.map","(","p1",")","[",":",",",":","p2.shape","[","1","]","]",",","p2",")"] | 187 | 215 | null | test_transforms.py | vispy/vispy/visuals/transforms/tests/test_transforms.py | import numpy
from numpy.testing import assert_allclose
import pytest
import vispy.visuals.transforms
from vispy.geometry import Rect
from vispy.testing import run_tests_if_main | 15 | null | 6 | 9 | null | null | null | Use image node_id 8 for calling a global function with example usage: test_affine_mapping() without return types | 112 | node_id 8 | 2,321,322 |
|
test_st_mapping | global | null | false | null | null | null | null | null | def test_st_mapping():
p1 = [[5.0, 7.0], [23.0, 8.0]]
p2 = [[-1.3, -1.4], [1.1, 1.2]]
t = tr.STTransform()
t.set_mapping(p1, p2)
assert np.allclose(t.map(p1)[:, : len(p2)], p2)
| ["def","test_st_mapping","(",")",":","p1","=","[","[","5.0",",","7.0","]",",","[","23.0",",","8.0","]","]","p2","=","[","[","-1.3",",","-1.4","]",",","[","1.1",",","1.2","]","]","t","=","tr.STTransform","(",")","t.set_mapping","(","p1",",","p2",")","assert","np.allclose","(","t.map","(","p1",")","[",":",",",":","len","(","p2",")","]",",","p2",")"] | 177 | 184 | null | test_transforms.py | vispy/vispy/visuals/transforms/tests/test_transforms.py | import numpy
from numpy.testing import assert_allclose
import pytest
import vispy.visuals.transforms
from vispy.geometry import Rect
from vispy.testing import run_tests_if_main | 15 | null | 6 | 9 | null | null | null | Use image node_id 7 for calling a global function with example usage: test_st_mapping() without return types | 108 | node_id 7 | 2,321,321 |
|
test_init | TestLLaVAAgent | unittest | true | self | null | null | null | null | null | def test_init(self):
self.assertIsInstance(self.agent, LLaVAAgent)
| ["def","test_init","(","self",")",":","self.assertIsInstance","(","self.agent",",","LLaVAAgent",")"] | 33 | 34 | null | test_llava.py | autogen/test/agentchat/contrib/test_llava.py | import unittest
from unittest.mock import MagicMock, patch
import pytest
import autogen | 15 | 3 | 4 | 0 | 3 | 2 | 1 | Use image node_id 2 for calling the TestLLaVAAgent obj's underlying member method code with example usage: obj.test_init() without return types | 143 | node_id 2 | 319,288 |
_validate_composite_distance | global | null | false | distance | null | null | null | null | null | def _validate_composite_distance(distance):
"""
Check that composite distance function is in valid form. Don't modify the
composite distance in any way.
"""
if not isinstance(distance, list):
raise TypeError(
"Input 'distance' must be a composite distance."
)
if len(distance) < 1:
raise ValueError(
"Composite distances must have a least one distance "
"component, consisting of a list of feature names, "
"a distance function (string or function handle), "
"and a weight."
)
for d in distance:
## Extract individual pieces of the distance component
try:
ftrs, dist, weight = d
except:
raise TypeError(
"Elements of a composite distance function must "
+ "have three items: a set of feature names (tuple or list), "
+ "a distance function (string or function handle), "
+ "and a weight."
)
## Validate feature names
if len(ftrs) == 0:
raise ValueError(
"An empty list of features cannot be passed "
+ "as part of a composite distance function."
)
if not isinstance(ftrs, (list, tuple)):
raise TypeError(
"Feature names must be specified in a list or tuple."
)
if not all([isinstance(x, str) for x in ftrs]):
raise TypeError(
"Feature lists must contain only strings."
)
## Validate standard distance function
if not isinstance(dist, str) and not hasattr(
dist, "__call__"
):
raise ValueError(
"Standard distances must be the name of a distance "
+ "function (string) or a distance function handle"
)
if isinstance(dist, str):
try:
_tc.distances.__dict__[dist]
except:
raise ValueError(
"Distance '{}' not recognized".format(dist)
)
## Validate weight
if not isinstance(weight, (int, float)):
raise ValueError(
"The weight of each distance component must be a single "
+ "integer or a float value."
)
if weight < 0:
raise ValueError(
"The weight on each distance component must be "
+ "greater than or equal to zero."
)
| ["def","_validate_composite_distance","(","distance",")",":","``","''","''","Check","that","composite","distance","function","is","in","valid","form",".","Do","n't","modify","the","composite","distance","in","any","way.","``","''","''","if","not","isinstance","(","distance",",","list",")",":","raise","TypeError","(","``","Input","'distance","'","must","be","a","composite","distance",".","''",")","if","len","(","distance",")","<","1",":","raise","ValueError","(","``","Composite","distances","must","have","a","least","one","distance","``","``","component",",","consisting","of","a","list","of","feature","names",",","``","``","a","distance","function","(","string","or","function","handle",")",",","``","``","and","a","weight",".","''",")","for","d","in","distance",":","#","#","Extract","individual","pieces","of","the","distance","component","try",":","ftrs",",","dist",",","weight","=","d","except",":","raise","TypeError","(","``","Elements","of","a","composite","distance","function","must","``","+","``","have","three","items",":","a","set","of","feature","names","(","tuple","or","list",")",",","``","+","``","a","distance","function","(","string","or","function","handle",")",",","``","+","``","and","a","weight",".","''",")","#","#","Validate","feature","names","if","len","(","ftrs",")","==","0",":","raise","ValueError","(","``","An","empty","list","of","features","can","not","be","passed","``","+","``","as","part","of","a","composite","distance","function",".","''",")","if","not","isinstance","(","ftrs",",","(","list",",","tuple",")",")",":","raise","TypeError","(","``","Feature","names","must","be","specified","in","a","list","or","tuple",".","''",")","if","not","all","(","[","isinstance","(","x",",","str",")","for","x","in","ftrs","]",")",":","raise","TypeError","(","``","Feature","lists","must","contain","only","strings",".","''",")","#","#","Validate","standard","distance","function","if","not","isinstance","(","dist",",","str",")","and","not","hasattr","(","dist",",","``","__call__","''",")",":","raise","ValueError","(","``","Standard","distances","must","be","the","name","of","a","distance","``","+","``","function","(","string",")","or","a","distance","function","handle","''",")","if","isinstance","(","dist",",","str",")",":","try",":","_tc.distances.__dict__","[","dist","]","except",":","raise","ValueError","(","``","Distance","'","{","}","'","not","recognized","''",".format","(","dist",")",")","#","#","Validate","weight","if","not","isinstance","(","weight",",","(","int",",","float",")",")",":","raise","ValueError","(","``","The","weight","of","each","distance","component","must","be","a","single","``","+","``","integer","or","a","float","value",".","''",")","if","weight","<","0",":","raise","ValueError","(","``","The","weight","on","each","distance","component","must","be","``","+","``","greater","than","or","equal","to","zero",".","''",")"] | 136 | 203 | null | _util.py | turicreate/src/python/turicreate/toolkits/distances/_util.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import copy
import array
import six
from operator import iadd
import turicreate
import sys | 15 | null | 9 | 6 | null | null | null | Use image node_id 2 for calling a global function with example usage: _validate_composite_distance(distance) without return types | 129 | node_id 2 | 2,285,730 |
test_st_transform | global | null | false | null | null | null | null | null | def test_st_transform():
# Check that STTransform maps exactly like MatrixTransform
pts = np.random.normal(size=(10, 4))
scale = (1, 7.5, -4e-8)
translate = (1e6, 0.2, 0)
st = tr.STTransform(scale=scale, translate=translate)
at = tr.MatrixTransform()
at.scale(scale)
at.translate(translate)
assert np.allclose(st.map(pts), at.map(pts))
assert np.allclose(st.inverse.map(pts), at.inverse.map(pts))
| ["def","test_st_transform","(",")",":","#","Check","that","STTransform","maps","exactly","like","MatrixTransform","pts","=","np.random.normal","(","size=","(","10",",","4",")",")","scale","=","(","1",",","7.5",",","-4e-8",")","translate","=","(","1e6",",","0.2",",","0",")","st","=","tr.STTransform","(","scale=scale",",","translate=translate",")","at","=","tr.MatrixTransform","(",")","at.scale","(","scale",")","at.translate","(","translate",")","assert","np.allclose","(","st.map","(","pts",")",",","at.map","(","pts",")",")","assert","np.allclose","(","st.inverse.map","(","pts",")",",","at.inverse.map","(","pts",")",")"] | 162 | 174 | null | test_transforms.py | vispy/vispy/visuals/transforms/tests/test_transforms.py | import numpy
from numpy.testing import assert_allclose
import pytest
import vispy.visuals.transforms
from vispy.geometry import Rect
from vispy.testing import run_tests_if_main | 15 | null | 6 | 9 | null | null | null | Use image node_id 6 for calling a global function with example usage: test_st_transform() without return types | 110 | node_id 6 | 2,321,320 |
|
_scrub_composite_distance_features | global | null | false | distance,feature_denylist | null | null | null | null | dist_out | def _scrub_composite_distance_features(distance, feature_denylist):
"""
Remove feature names from the feature lists in a composite distance
function.
"""
dist_out = []
for i, d in enumerate(distance):
ftrs, dist, weight = d
new_ftrs = [x for x in ftrs if x not in feature_denylist]
if len(new_ftrs) > 0:
dist_out.append([new_ftrs, dist, weight])
return dist_out
| ["def","_scrub_composite_distance_features","(","distance",",","feature_denylist",")",":","``","''","''","Remove","feature","names","from","the","feature","lists","in","a","composite","distance","function.","``","''","''","dist_out","=","[","]","for","i",",","d","in","enumerate","(","distance",")",":","ftrs",",","dist",",","weight","=","d","new_ftrs","=","[","x","for","x","in","ftrs","if","x","not","in","feature_denylist","]","if","len","(","new_ftrs",")",">","0",":","dist_out.append","(","[","new_ftrs",",","dist",",","weight","]",")","return","dist_out"] | 206 | 219 | null | _util.py | turicreate/src/python/turicreate/toolkits/distances/_util.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import copy
import array
import six
from operator import iadd
import turicreate
import sys | 15 | null | 9 | 6 | null | null | null | Use image node_id 3 for calling a global function with example usage: _scrub_composite_distance_features(distance, feature_denylist) and returns: dist_out | 154 | node_id 3 | 2,285,731 |
_convert_distance_names_to_functions | global | null | false | distance | null | null | null | null | dist_out | def _convert_distance_names_to_functions(distance):
"""
Convert function names in a composite distance function into function
handles.
"""
dist_out = _copy.deepcopy(distance)
for i, d in enumerate(distance):
_, dist, _ = d
if isinstance(dist, str):
try:
dist_out[i][1] = _tc.distances.__dict__[dist]
except:
raise ValueError(
"Distance '{}' not recognized.".format(dist)
)
return dist_out
| ["def","_convert_distance_names_to_functions","(","distance",")",":","``","''","''","Convert","function","names","in","a","composite","distance","function","into","function","handles.","``","''","''","dist_out","=","_copy.deepcopy","(","distance",")","for","i",",","d","in","enumerate","(","distance",")",":","_",",","dist",",","_","=","d","if","isinstance","(","dist",",","str",")",":","try",":","dist_out","[","i","]","[","1","]","=","_tc.distances.__dict__","[","dist","]","except",":","raise","ValueError","(","``","Distance","'","{","}","'","not","recognized",".","``",".format","(","dist",")",")","return","dist_out"] | 222 | 237 | null | _util.py | turicreate/src/python/turicreate/toolkits/distances/_util.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import copy
import array
import six
from operator import iadd
import turicreate
import sys | 15 | null | 9 | 6 | null | null | null | Use image node_id 4 for calling a global function with example usage: _convert_distance_names_to_functions(distance) and returns: dist_out | 138 | node_id 4 | 2,285,732 |
__new__ | Configurable | object | true | cls | Base class for configurable interfaces.
A configurable interface is an (abstract) class whose constructor
acts as a factory function for one of its implementation subclasses.
The implementation subclass as well as optional keyword arguments to
its initializer can be set globally at runtime with `configure`.
By using the constructor as the factory method, the interface
looks like a normal class, `isinstance` works as usual, etc. This
pattern is most useful when the choice of implementation is likely
to be a global decision (e.g. when `~select.epoll` is available,
always use it instead of `~select.select`), or when a
previously-monolithic class has been split into specialized
subclasses.
Configurable subclasses must define the class methods
`configurable_base` and `configurable_default`, and use the instance
method `initialize` instead of ``__init__``. | ["Base","class","for","configurable","interfaces",".","A","configurable","interface","is","an","(","abstract",")","class","whose","constructor","acts","as","a","factory","function","for","one","of","its","implementation","subclasses",".","The","implementation","subclass","as","well","as","optional","keyword","arguments","to","its","initializer","can","be","set","globally","at","runtime","with","`","configure","`",".","By","using","the","constructor","as","the","factory","method",",","the","interface","looks","like","a","normal","class",",","`","isinstance","`","works","as","usual",",","etc",".","This","pattern","is","most","useful","when","the","choice","of","implementation","is","likely","to","be","a","global","decision","(","e.g",".","when","`","~select.epoll","`","is","available",",","always","use","it","instead","of","`","~select.select","`",")",",","or","when","a","previously-monolithic","class","has","been","split","into","specialized","subclasses",".","Configurable","subclasses","must","define","the","class","methods","`","configurable_base","`","and","`","configurable_default","`",",","and","use","the","instance","method","`","initialize","`","instead","of","``","__init__","``","."] | null | null | instance | def __new__(cls, *args, **kwargs):
base = cls.configurable_base()
init_kwargs = {}
if cls is base:
impl = cls.configured_class()
if base.__impl_kwargs:
init_kwargs.update(base.__impl_kwargs)
else:
impl = cls
init_kwargs.update(kwargs)
instance = super(Configurable, cls).__new__(impl)
# initialize vs __init__ chosen for compatibility with AsyncHTTPClient
# singleton magic. If we get rid of that we can switch to __init__
# here too.
instance.initialize(*args, **init_kwargs)
return instance
| ["def","__new__","(","cls",",","*","args",",","*","*","kwargs",")",":","base","=","cls.configurable_base","(",")","init_kwargs","=","{","}","if","cls","is","base",":","impl","=","cls.configured_class","(",")","if","base.__impl_kwargs",":","init_kwargs.update","(","base.__impl_kwargs",")","else",":","impl","=","cls","init_kwargs.update","(","kwargs",")","instance","=","super","(","Configurable",",","cls",")",".__new__","(","impl",")","#","initialize","vs","__init__","chosen","for","compatibility","with","AsyncHTTPClient","#","singleton","magic",".","If","we","get","rid","of","that","we","can","switch","to","__init__","#","here","too",".","instance.initialize","(","*","args",",","*","*","init_kwargs",")","return","instance"] | 138 | 153 | null | util.py | catboost/contrib/python/pyzmq/py2/zmq/eventloop/minitornado/util.py | from __future__ import absolute_import, division, print_function, with_statement
import sys | 15 | 1 | 2 | 3 | 1 | 8 | 1 | Use image node_id 1 for calling the Configurable obj's underlying member method code with example usage: obj.__new__(cls) and returns: instance | 143 | node_id 1 | 515,109 |
setUp | TestLLaVAAgent | unittest | true | self | null | null | null | null | null | def setUp(self):
self.agent = LLaVAAgent(
name="TestAgent",
llm_config={
"timeout": 600,
"seed": 42,
"config_list": [
{
"model": "llava-fake",
"base_url": "localhost:8000",
"api_key": "Fake",
}
],
},
)
| ["def","setUp","(","self",")",":","self.agent","=","LLaVAAgent","(","name=","''","TestAgent","''",",","llm_config=","{","``","timeout","''",":","600",",","``","seed","''",":","42",",","``","config_list","''",":","[","{","``","model","''",":","``","llava-fake","''",",","``","base_url","''",":","``","localhost:8000","''",",","``","api_key","''",":","``","Fake","''",",","}","]",",","}",",",")"] | 23 | 31 | null | test_llava.py | autogen/test/agentchat/contrib/test_llava.py | import unittest
from unittest.mock import MagicMock, patch
import pytest
import autogen | 15 | 3 | 4 | 0 | 3 | 2 | 1 | Use image node_id 1 for calling the TestLLaVAAgent obj's underlying member method code with example usage: obj.setUp() without return types | 139 | node_id 1 | 319,287 |
test_footnote_separator | TestFootnotes | TestCase | true | self | null | null | Test separator configuration. | ["Test","separator","configuration","."] | null | def test_footnote_separator(self):
"""Test separator configuration."""
self.assertMarkdownRenders(
"paragraph[^1]\n\n[^1]: A Footnote",
'<p>paragraph<sup id="fnref-1"><a class="footnote-ref" href="#fn-1">1</a></sup></p>\n'
'<div class="footnote">\n'
"<hr />\n"
"<ol>\n"
'<li id="fn-1">\n'
'<p>A Footnote <a class="footnote-backref" href="#fnref-1"'
' title="Jump back to footnote 1 in the text">↩</a></p>\n'
"</li>\n"
"</ol>\n"
"</div>",
extension_configs={"footnotes": {"SEPARATOR": "-"}},
)
| ["def","test_footnote_separator","(","self",")",":","``","''","''","Test","separator","configuration",".","''","''","''","self.assertMarkdownRenders","(","``","paragraph","[","^1","]","\\n\\n","[","^1","]",":","A","Footnote","''",",","'","<","p",">","paragraph","<","sup","id=","''","fnref-1","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn-1","''",">","1","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","div","class=","''","footnote","''",">","\\n'","``","<","hr","\/",">","\\n","''","``","<","ol",">","\\n","''","'","<","li","id=","''","fn-1","''",">","\\n'","'","<","p",">","A","Footnote","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref-1","''","'","'","title=","''","Jump","back","to","footnote","1","in","the","text","''",">","&","#","8617",";","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","``","<","\/ol",">","\\n","''","``","<","\/div",">","''",",","extension_configs=","{","``","footnotes","''",":","{","``","SEPARATOR","''",":","``","-","''","}","}",",",")"] | 286 | 302 | null | test_footnotes.py | markdown/tests/test_syntax/extensions/test_footnotes.py | from markdown.test_tools import TestCase | 15 | 1 | 1 | 0 | 1 | 12 | 1 | Use image node_id 10 for calling the TestFootnotes obj's underlying member method code with example usage: obj.test_footnote_separator() without return types | 157 | node_id 10 | 1,299,343 |
_get_composite_distance_features | global | null | false | distance | null | null | null | null | list | def _get_composite_distance_features(distance):
"""
Return the union of feature names across all components in a composite
distance specification.
"""
return list(set(reduce(iadd, [x[0] for x in distance], [])))
| ["def","_get_composite_distance_features","(","distance",")",":","``","''","''","Return","the","union","of","feature","names","across","all","components","in","a","composite","distance","specification.","``","''","''","return","list","(","set","(","reduce","(","iadd",",","[","x","[","0","]","for","x","in","distance","]",",","[","]",")",")",")"] | 240 | 245 | null | _util.py | turicreate/src/python/turicreate/toolkits/distances/_util.py | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import copy
import array
import six
from operator import iadd
import turicreate
import sys | 15 | null | 9 | 6 | null | null | null | Use image node_id 5 for calling a global function with example usage: _get_composite_distance_features(distance) and returns: list | 130 | node_id 5 | 2,285,733 |
test_backlink_title | TestFootnotes | TestCase | true | self | null | null | Test back-link title configuration without placeholder. | ["Test","back-link","title","configuration","without","placeholder","."] | null | def test_backlink_title(self):
"""Test back-link title configuration without placeholder."""
self.assertMarkdownRenders(
"paragraph[^1]\n\n[^1]: A Footnote",
'<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup></p>\n'
'<div class="footnote">\n'
"<hr />\n"
"<ol>\n"
'<li id="fn:1">\n'
'<p>A Footnote <a class="footnote-backref" href="#fnref:1"'
' title="Jump back to footnote">↩</a></p>\n'
"</li>\n"
"</ol>\n"
"</div>",
extension_configs={
"footnotes": {"BACKLINK_TITLE": "Jump back to footnote"}
},
)
| ["def","test_backlink_title","(","self",")",":","``","''","''","Test","back-link","title","configuration","without","placeholder",".","''","''","''","self.assertMarkdownRenders","(","``","paragraph","[","^1","]","\\n\\n","[","^1","]",":","A","Footnote","''",",","'","<","p",">","paragraph","<","sup","id=","''","fnref:1","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn:1","''",">","1","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","div","class=","''","footnote","''",">","\\n'","``","<","hr","\/",">","\\n","''","``","<","ol",">","\\n","''","'","<","li","id=","''","fn:1","''",">","\\n'","'","<","p",">","A","Footnote","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref:1","''","'","'","title=","''","Jump","back","to","footnote","''",">","&","#","8617",";","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","``","<","\/ol",">","\\n","''","``","<","\/div",">","''",",","extension_configs=","{","``","footnotes","''",":","{","``","BACKLINK_TITLE","''",":","``","Jump","back","to","footnote","''","}","}",",",")"] | 304 | 320 | null | test_footnotes.py | markdown/tests/test_syntax/extensions/test_footnotes.py | from markdown.test_tools import TestCase | 15 | 1 | 1 | 0 | 1 | 12 | 1 | Use image node_id 11 for calling the TestFootnotes obj's underlying member method code with example usage: obj.test_backlink_title() without return types | 153 | node_id 11 | 1,299,344 |
test_superscript_text | TestFootnotes | TestCase | true | self | null | null | Test superscript text configuration. | ["Test","superscript","text","configuration","."] | null | def test_superscript_text(self):
"""Test superscript text configuration."""
self.assertMarkdownRenders(
"paragraph[^1]\n\n[^1]: A Footnote",
'<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">[1]</a></sup></p>\n'
'<div class="footnote">\n'
"<hr />\n"
"<ol>\n"
'<li id="fn:1">\n'
'<p>A Footnote <a class="footnote-backref" href="#fnref:1"'
' title="Jump back to footnote 1 in the text">↩</a></p>\n'
"</li>\n"
"</ol>\n"
"</div>",
extension_configs={"footnotes": {"SUPERSCRIPT_TEXT": "[{}]"}},
)
| ["def","test_superscript_text","(","self",")",":","``","''","''","Test","superscript","text","configuration",".","''","''","''","self.assertMarkdownRenders","(","``","paragraph","[","^1","]","\\n\\n","[","^1","]",":","A","Footnote","''",",","'","<","p",">","paragraph","<","sup","id=","''","fnref:1","''",">","<","a","class=","''","footnote-ref","''","href=","''","#","fn:1","''",">","[","1","]","<","\/a",">","<","\/sup",">","<","\/p",">","\\n'","'","<","div","class=","''","footnote","''",">","\\n'","``","<","hr","\/",">","\\n","''","``","<","ol",">","\\n","''","'","<","li","id=","''","fn:1","''",">","\\n'","'","<","p",">","A","Footnote","&","#","160",";","<","a","class=","''","footnote-backref","''","href=","''","#","fnref:1","''","'","'","title=","''","Jump","back","to","footnote","1","in","the","text","''",">","&","#","8617",";","<","\/a",">","<","\/p",">","\\n'","``","<","\/li",">","\\n","''","``","<","\/ol",">","\\n","''","``","<","\/div",">","''",",","extension_configs=","{","``","footnotes","''",":","{","``","SUPERSCRIPT_TEXT","''",":","``","[","{","}","]","''","}","}",",",")"] | 322 | 338 | null | test_footnotes.py | markdown/tests/test_syntax/extensions/test_footnotes.py | from markdown.test_tools import TestCase | 15 | 1 | 1 | 0 | 1 | 12 | 1 | Use image node_id 12 for calling the TestFootnotes obj's underlying member method code with example usage: obj.test_superscript_text() without return types | 155 | node_id 12 | 1,299,345 |
__init__ | AppSession | null | true | self,input,output | An AppSession is an interactive session, usually connected to one terminal.
Within one such session, interaction with many applications can happen, one
after the other.
The input/output device is not supposed to change during one session.
Warning: Always use the `create_app_session` function to create an
instance, so that it gets activated correctly.
:param input: Use this as a default input for all applications
running in this session, unless an input is passed to the `Application`
explicitly.
:param output: Use this as a default output. | ["An","AppSession","is","an","interactive","session",",","usually","connected","to","one","terminal",".","Within","one","such","session",",","interaction","with","many","applications","can","happen",",","one","after","the","other",".","The","input\/output","device","is","not","supposed","to","change","during","one","session",".","Warning",":","Always","use","the","`","create_app_session","`","function","to","create","an","instance",",","so","that","it","gets","activated","correctly",".",":","param","input",":","Use","this","as","a","default","input","for","all","applications","running","in","this","session",",","unless","an","input","is","passed","to","the","`","Application","`","explicitly",".",":","param","output",":","Use","this","as","a","default","output","."] | null | null | AppSession | def __init__(
self, input: Input | None = None, output: Output | None = None
) -> None:
self._input = input
self._output = output
# The application will be set dynamically by the `set_app` context
# manager. This is called in the application itself.
self.app: Application[Any] | None = None
| ["def","__init__","(","self",",","input",":","Input","|","None","=","None",",","output",":","Output","|","None","=","None",")","-",">","None",":","self._input","=","input","self._output","=","output","#","The","application","will","be","set","dynamically","by","the","`","set_app","`","context","#","manager",".","This","is","called","in","the","application","itself",".","self.app",":","Application","[","Any","]","|","None","=","None"] | 41 | 49 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | 1 | 4 | 6 | 0 | 4 | null | Use image node_id 1 to create a new AppSession object with example: obj = AppSession(input, output) | 100 | node_id 1 | 500,073 |
__repr__ | AppSession | null | true | self | An AppSession is an interactive session, usually connected to one terminal.
Within one such session, interaction with many applications can happen, one
after the other.
The input/output device is not supposed to change during one session.
Warning: Always use the `create_app_session` function to create an
instance, so that it gets activated correctly.
:param input: Use this as a default input for all applications
running in this session, unless an input is passed to the `Application`
explicitly.
:param output: Use this as a default output. | ["An","AppSession","is","an","interactive","session",",","usually","connected","to","one","terminal",".","Within","one","such","session",",","interaction","with","many","applications","can","happen",",","one","after","the","other",".","The","input\/output","device","is","not","supposed","to","change","during","one","session",".","Warning",":","Always","use","the","`","create_app_session","`","function","to","create","an","instance",",","so","that","it","gets","activated","correctly",".",":","param","input",":","Use","this","as","a","default","input","for","all","applications","running","in","this","session",",","unless","an","input","is","passed","to","the","`","Application","`","explicitly",".",":","param","output",":","Use","this","as","a","default","output","."] | null | null | str+self+str | def __repr__(self) -> str:
return f"AppSession(app={self.app!r})"
| ["def","__repr__","(","self",")","-",">","str",":","return","f","''","AppSession","(","app=","{","self.app","!","r","}",")","''"] | 51 | 52 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | 1 | 4 | 6 | 0 | 4 | null | Use image node_id 2 for calling the AppSession obj's underlying member method code with example usage: obj.__repr__() and returns: str, self, str | 145 | node_id 2 | 500,074 |
input | AppSession | null | true | self | An AppSession is an interactive session, usually connected to one terminal.
Within one such session, interaction with many applications can happen, one
after the other.
The input/output device is not supposed to change during one session.
Warning: Always use the `create_app_session` function to create an
instance, so that it gets activated correctly.
:param input: Use this as a default input for all applications
running in this session, unless an input is passed to the `Application`
explicitly.
:param output: Use this as a default output. | ["An","AppSession","is","an","interactive","session",",","usually","connected","to","one","terminal",".","Within","one","such","session",",","interaction","with","many","applications","can","happen",",","one","after","the","other",".","The","input\/output","device","is","not","supposed","to","change","during","one","session",".","Warning",":","Always","use","the","`","create_app_session","`","function","to","create","an","instance",",","so","that","it","gets","activated","correctly",".",":","param","input",":","Use","this","as","a","default","input","for","all","applications","running","in","this","session",",","unless","an","input","is","passed","to","the","`","Application","`","explicitly",".",":","param","output",":","Use","this","as","a","default","output","."] | null | null | self | def input(self) -> Input:
if self._input is None:
from prompt_toolkit.input.defaults import create_input
self._input = create_input()
return self._input
| ["def","input","(","self",")","-",">","Input",":","if","self._input","is","None",":","from","prompt_toolkit.input.defaults","import","create_input","self._input","=","create_input","(",")","return","self._input"] | 55 | 60 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | 1 | 4 | 6 | 0 | 4 | null | Use image node_id 3 for calling the AppSession obj's underlying member method code with example usage: obj.input() and returns: self | 132 | node_id 3 | 500,075 |
output | AppSession | null | true | self | An AppSession is an interactive session, usually connected to one terminal.
Within one such session, interaction with many applications can happen, one
after the other.
The input/output device is not supposed to change during one session.
Warning: Always use the `create_app_session` function to create an
instance, so that it gets activated correctly.
:param input: Use this as a default input for all applications
running in this session, unless an input is passed to the `Application`
explicitly.
:param output: Use this as a default output. | ["An","AppSession","is","an","interactive","session",",","usually","connected","to","one","terminal",".","Within","one","such","session",",","interaction","with","many","applications","can","happen",",","one","after","the","other",".","The","input\/output","device","is","not","supposed","to","change","during","one","session",".","Warning",":","Always","use","the","`","create_app_session","`","function","to","create","an","instance",",","so","that","it","gets","activated","correctly",".",":","param","input",":","Use","this","as","a","default","input","for","all","applications","running","in","this","session",",","unless","an","input","is","passed","to","the","`","Application","`","explicitly",".",":","param","output",":","Use","this","as","a","default","output","."] | null | null | self | def output(self) -> Output:
if self._output is None:
from prompt_toolkit.output.defaults import create_output
self._output = create_output()
return self._output
| ["def","output","(","self",")","-",">","Output",":","if","self._output","is","None",":","from","prompt_toolkit.output.defaults","import","create_output","self._output","=","create_output","(",")","return","self._output"] | 63 | 68 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | 1 | 4 | 6 | 0 | 4 | null | Use image node_id 4 for calling the AppSession obj's underlying member method code with example usage: obj.output() and returns: self | 133 | node_id 4 | 500,076 |
get_app_session | global | null | false | null | null | null | null | _current_app_session | def get_app_session() -> AppSession:
return _current_app_session.get()
| ["def","get_app_session","(",")","-",">","AppSession",":","return","_current_app_session.get","(",")"] | 76 | 77 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 1 for calling a global function with example usage: get_app_session() and returns: _current_app_session | 121 | node_id 1 | 500,077 |
|
get_app | global | null | false | null | null | null | null | DummyApplication,session | def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
| ["def","get_app","(",")","-",">","Application","[","Any","]",":","``","''","''","Get","the","current","active","(","running",")","Application",".","An",":","class",":","`",".Application","`","is","active","during","the",":","meth",":","`",".Application.run_async","`","call",".","We","assume","that","there","can","only","be","one",":","class",":","`",".Application","`","active","at","the","same","time",".","There","is","only","one","terminal","window",",","with","only","one","stdin","and","stdout",".","This","makes","the","code","significantly","easier","than","passing","around","the",":","class",":","`",".Application","`","everywhere",".","If","no",":","class",":","`",".Application","`","is","running",",","then","return","by","default","a",":","class",":","`",".DummyApplication","`",".","For","practical","reasons",",","we","prefer","to","not","raise","an","exception",".","This","way",",","we","do","n't","have","to","check","all","over","the","place","whether","an","actual","`","Application","`","was","returned",".","(","For","applications","like","pymux","where","we","can","have","more","than","one","`","Application","`",",","we","'ll","use","a","work-around","to","handle","that",".",")","``","``","''","session","=","_current_app_session.get","(",")","if","session.app","is","not","None",":","return","session.app","from",".dummy","import","DummyApplication","return","DummyApplication","(",")"] | 80 | 105 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 2 for calling a global function with example usage: get_app() and returns: DummyApplication, session | 118 | node_id 2 | 500,078 |
|
get_app_or_none | global | null | false | null | null | null | null | session | def get_app_or_none() -> Application[Any] | None:
"""
Get the current active (running) Application, or return `None` if no
application is running.
"""
session = _current_app_session.get()
return session.app
| ["def","get_app_or_none","(",")","-",">","Application","[","Any","]","|","None",":","``","''","''","Get","the","current","active","(","running",")","Application",",","or","return","`","None","`","if","no","application","is","running.","``","''","''","session","=","_current_app_session.get","(",")","return","session.app"] | 108 | 114 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 3 for calling a global function with example usage: get_app_or_none() and returns: session | 108 | node_id 3 | 500,079 |
|
set_app | global | null | false | app | null | null | null | null | null | def set_app(app: Application[Any]) -> Generator[None, None, None]:
"""
Context manager that sets the given :class:`.Application` active in an
`AppSession`.
This should only be called by the `Application` itself.
The application will automatically be active while its running. If you want
the application to be active in other threads/coroutines, where that's not
the case, use `contextvars.copy_context()`, or use `Application.context` to
run it in the appropriate context.
"""
session = _current_app_session.get()
previous_app = session.app
session.app = app
try:
yield
finally:
session.app = previous_app
| ["def","set_app","(","app",":","Application","[","Any","]",")","-",">","Generator","[","None",",","None",",","None","]",":","``","''","''","Context","manager","that","sets","the","given",":","class",":","`",".Application","`","active","in","an","`","AppSession","`",".","This","should","only","be","called","by","the","`","Application","`","itself",".","The","application","will","automatically","be","active","while","its","running",".","If","you","want","the","application","to","be","active","in","other","threads\/coroutines",",","where","that","'s","not","the","case",",","use","`","contextvars.copy_context","(",")","`",",","or","use","`","Application.context","`","to","run","it","in","the","appropriate","context.","``","''","''","session","=","_current_app_session.get","(",")","previous_app","=","session.app","session.app","=","app","try",":","yield","finally",":","session.app","=","previous_app"] | 118 | 136 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 4 for calling a global function with example usage: set_app(app) without return types | 103 | node_id 4 | 500,080 |
create_app_session | global | null | false | input,output | null | null | null | null | null | def create_app_session(
input: Input | None = None, output: Output | None = None
) -> Generator[AppSession, None, None]:
"""
Create a separate AppSession.
This is useful if there can be multiple individual `AppSession`s going on.
Like in the case of an Telnet/SSH server.
"""
# If no input/output is specified, fall back to the current input/output,
# whatever that is.
if input is None:
input = get_app_session().input
if output is None:
output = get_app_session().output
# Create new `AppSession` and activate.
session = AppSession(input=input, output=output)
token = _current_app_session.set(session)
try:
yield session
finally:
_current_app_session.reset(token)
| ["def","create_app_session","(","input",":","Input","|","None","=","None",",","output",":","Output","|","None","=","None",")","-",">","Generator","[","AppSession",",","None",",","None","]",":","``","''","''","Create","a","separate","AppSession",".","This","is","useful","if","there","can","be","multiple","individual","`","AppSession","`","s","going","on",".","Like","in","the","case","of","an","Telnet\/SSH","server.","``","''","''","#","If","no","input\/output","is","specified",",","fall","back","to","the","current","input\/output",",","#","whatever","that","is",".","if","input","is","None",":","input","=","get_app_session","(",")",".input","if","output","is","None",":","output","=","get_app_session","(",")",".output","#","Create","new","`","AppSession","`","and","activate",".","session","=","AppSession","(","input=input",",","output=output",")","token","=","_current_app_session.set","(","session",")","try",":","yield","session","finally",":","_current_app_session.reset","(","token",")"] | 140 | 163 | null | current.py | catboost/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py | from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator | 15 | null | 4 | 6 | null | null | null | Use image node_id 5 for calling a global function with example usage: create_app_session(input, output) without return types | 124 | node_id 5 | 500,081 |
test_cmd_remove_gitignore_single_stage | global | null | false | tmp_dir,scm,dvc,run_copy | null | null | null | null | null | def test_cmd_remove_gitignore_single_stage(
tmp_dir, scm, dvc, run_copy
):
stage = dvc.run(
name="my", cmd='echo "hello" > out', deps=[], outs=["out"]
)
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert not (stage.dvcfile._lockfile).exists()
assert not (tmp_dir / ".gitignore").exists()
| ["def","test_cmd_remove_gitignore_single_stage","(","tmp_dir",",","scm",",","dvc",",","run_copy",")",":","stage","=","dvc.run","(","name=","''","my","''",",","cmd='echo","``","hello","''",">","out","'",",","deps=","[","]",",","outs=","[","``","out","''","]",")","assert","(","tmp_dir","\/","``",".gitignore","''",")",".exists","(",")","assert","main","(","[","``","remove","''",",","stage.addressing","]",")","==","0","assert","not","(","tmp_dir","\/","stage.relpath",")",".exists","(",")","assert","not","(","stage.dvcfile._lockfile",")",".exists","(",")","assert","not","(","tmp_dir","\/","``",".gitignore","''",")",".exists","(",")"] | 86 | 94 | null | test_remove.py | dvc/tests/func/test_remove.py | import os
import pytest
from dvc.cli import main
from dvc.fs import system
from dvc.stage.exceptions import StageFileDoesNotExistError, StageFileIsNotDvcFileError
from dvc.utils.fs import remove
from dvc_objects.errors import ObjectDBError
from tests.utils import get_gitignore_content | 15 | null | 8 | 7 | null | null | null | Use image node_id 6 for calling a global function with example usage: test_cmd_remove_gitignore_single_stage(tmp_dir, scm, dvc, run_copy) without return types | 158 | node_id 6 | 806,509 |
test_cmd_remove_gitignore_multistage | global | null | false | tmp_dir,scm,dvc,run_copy | null | null | null | null | null | def test_cmd_remove_gitignore_multistage(tmp_dir, scm, dvc, run_copy):
(stage,) = tmp_dir.dvc_gen("foo", "foo")
stage1 = run_copy("foo", "foo1", name="copy-foo-foo1")
stage2 = run_copy("foo1", "foo2", name="copy-foo1-foo2")
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage2.addressing]) == 0
assert main(["remove", stage1.addressing]) == 0
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / ".gitignore").exists()
| ["def","test_cmd_remove_gitignore_multistage","(","tmp_dir",",","scm",",","dvc",",","run_copy",")",":","(","stage",",",")","=","tmp_dir.dvc_gen","(","``","foo","''",",","``","foo","''",")","stage1","=","run_copy","(","``","foo","''",",","``","foo1","''",",","name=","''","copy-foo-foo1","''",")","stage2","=","run_copy","(","``","foo1","''",",","``","foo2","''",",","name=","''","copy-foo1-foo2","''",")","assert","(","tmp_dir","\/","``",".gitignore","''",")",".exists","(",")","assert","main","(","[","``","remove","''",",","stage2.addressing","]",")","==","0","assert","main","(","[","``","remove","''",",","stage1.addressing","]",")","==","0","assert","main","(","[","``","remove","''",",","stage.addressing","]",")","==","0","assert","not","(","tmp_dir","\/","``",".gitignore","''",")",".exists","(",")"] | 97 | 107 | null | test_remove.py | dvc/tests/func/test_remove.py | import os
import pytest
from dvc.cli import main
from dvc.fs import system
from dvc.stage.exceptions import StageFileDoesNotExistError, StageFileIsNotDvcFileError
from dvc.utils.fs import remove
from dvc_objects.errors import ObjectDBError
from tests.utils import get_gitignore_content | 15 | null | 8 | 7 | null | null | null | Use image node_id 7 for calling a global function with example usage: test_cmd_remove_gitignore_multistage(tmp_dir, scm, dvc, run_copy) without return types | 156 | node_id 7 | 806,510 |
__init__ | MatlabCommand | CommandLine | true | self,matlab_cmd | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | initializes interface to matlab
(default 'matlab -nodesktop -nosplash') | ["initializes","interface","to","matlab","(","default","'matlab","-nodesktop","-nosplash","'",")"] | MatlabCommand | def __init__(self, matlab_cmd=None, **inputs):
"""initializes interface to matlab
(default 'matlab -nodesktop -nosplash')
"""
super().__init__(**inputs)
if matlab_cmd and isdefined(matlab_cmd):
self._cmd = matlab_cmd
elif self._default_matlab_cmd:
self._cmd = self._default_matlab_cmd
if self._default_mfile and not isdefined(self.inputs.mfile):
self.inputs.mfile = self._default_mfile
if self._default_paths and not isdefined(self.inputs.paths):
self.inputs.paths = self._default_paths
if not isdefined(
self.inputs.single_comp_thread
) and not isdefined(self.inputs.uses_mcr):
if config.getboolean("execution", "single_thread_matlab"):
self.inputs.single_comp_thread = True
# For matlab commands force all output to be returned since matlab
# does not have a clean way of notifying an error
self.terminal_output = "allatonce"
| ["def","__init__","(","self",",","matlab_cmd=None",",","*","*","inputs",")",":","``","''","''","initializes","interface","to","matlab","(","default","'matlab","-nodesktop","-nosplash","'",")","``","''","''","super","(",")",".__init__","(","*","*","inputs",")","if","matlab_cmd","and","isdefined","(","matlab_cmd",")",":","self._cmd","=","matlab_cmd","elif","self._default_matlab_cmd",":","self._cmd","=","self._default_matlab_cmd","if","self._default_mfile","and","not","isdefined","(","self.inputs.mfile",")",":","self.inputs.mfile","=","self._default_mfile","if","self._default_paths","and","not","isdefined","(","self.inputs.paths",")",":","self.inputs.paths","=","self._default_paths","if","not","isdefined","(","self.inputs.single_comp_thread",")","and","not","isdefined","(","self.inputs.uses_mcr",")",":","if","config.getboolean","(","``","execution","''",",","``","single_thread_matlab","''",")",":","self.inputs.single_comp_thread","=","True","#","For","matlab","commands","force","all","output","to","be","returned","since","matlab","#","does","not","have","a","clean","way","of","notifying","an","error","self.terminal_output","=","``","allatonce","''"] | 95 | 118 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 1 to create a new MatlabCommand object from inherited base classes: CommandLine with example: obj = MatlabCommand(matlab_cmd) | 143 | node_id 1 | 1,440,233 |
_clone_param | LBFGS | Optimizer | true | self | Implements L-BFGS algorithm.
Heavily inspired by `minFunc
<https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`_.
.. warning::
This optimizer doesn't support per-parameter options and parameter
groups (there can be only one).
.. warning::
Right now all parameters have to be on a single device. This will be
improved in the future.
.. note::
This is a very memory intensive optimizer (it requires additional
``param_bytes * (history_size + 1)`` bytes). If it doesn't fit in memory
try reducing the history size, or use a different algorithm.
Args:
lr (float): learning rate (default: 1)
max_iter (int): maximal number of iterations per optimization step
(default: 20)
max_eval (int): maximal number of function evaluations per optimization
step (default: max_iter * 1.25).
tolerance_grad (float): termination tolerance on first order optimality
(default: 1e-7).
tolerance_change (float): termination tolerance on function
value/parameter changes (default: 1e-9).
history_size (int): update history size (default: 100).
line_search_fn (str): either 'strong_wolfe' or None (default: None). | ["Implements","L-BFGS","algorithm",".","Heavily","inspired","by","`","minFunc","<","https",":","\/\/www.cs.ubc.ca\/~schmidtm\/Software\/minFunc.html",">","`","_",".","..","warning",":",":","This","optimizer","does","n't","support","per-parameter","options","and","parameter","groups","(","there","can","be","only","one",")",".","..","warning",":",":","Right","now","all","parameters","have","to","be","on","a","single","device",".","This","will","be","improved","in","the","future",".","..","note",":",":","This","is","a","very","memory","intensive","optimizer","(","it","requires","additional","``","param_bytes","*","(","history_size","+","1",")","``","bytes",")",".","If","it","does","n't","fit","in","memory","try","reducing","the","history","size",",","or","use","a","different","algorithm",".","Args",":","lr","(","float",")",":","learning","rate","(","default",":","1",")","max_iter","(","int",")",":","maximal","number","of","iterations","per","optimization","step","(","default",":","20",")","max_eval","(","int",")",":","maximal","number","of","function","evaluations","per","optimization","step","(","default",":","max_iter","*","1.25",")",".","tolerance_grad","(","float",")",":","termination","tolerance","on","first","order","optimality","(","default",":","1e-7",")",".","tolerance_change","(","float",")",":","termination","tolerance","on","function","value\/parameter","changes","(","default",":","1e-9",")",".","history_size","(","int",")",":","update","history","size","(","default",":","100",")",".","line_search_fn","(","str",")",":","either","'strong_wolfe","'","or","None","(","default",":","None",")","."] | null | null | unknown | def _clone_param(self):
return [
p.clone(memory_format=torch.contiguous_format)
for p in self._params
]
| ["def","_clone_param","(","self",")",":","return","[","p.clone","(","memory_format=torch.contiguous_format",")","for","p","in","self._params","]"] | 271 | 272 | null | lbfgs.py | pytorch/torch/optim/lbfgs.py | import torch
from functools import reduce
from .optimizer import Optimizer | 15 | 1 | 3 | 2 | 1 | 8 | 1 | Use image node_id 5 for calling the LBFGS obj's underlying member method code with example usage: obj._clone_param() and returns: unknown | 137 | node_id 5 | 1,759,983 |
set_default_matlab_cmd | MatlabCommand | CommandLine | true | cls,matlab_cmd | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | Set the default MATLAB command line for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.matlab_cmd. | ["Set","the","default","MATLAB","command","line","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.matlab_cmd","."] | null | def set_default_matlab_cmd(cls, matlab_cmd):
"""Set the default MATLAB command line for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.matlab_cmd.
"""
cls._default_matlab_cmd = matlab_cmd
| ["def","set_default_matlab_cmd","(","cls",",","matlab_cmd",")",":","``","''","''","Set","the","default","MATLAB","command","line","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.matlab_cmd.","``","''","''","cls._default_matlab_cmd","=","matlab_cmd"] | 121 | 129 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 2 for calling the MatlabCommand obj's underlying member method code with example usage: obj.set_default_matlab_cmd(cls, matlab_cmd) without return types | 170 | node_id 2 | 1,440,234 |
set_default_mfile | MatlabCommand | CommandLine | true | cls,mfile | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | Set the default MATLAB script file format for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.mfile. | ["Set","the","default","MATLAB","script","file","format","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.mfile","."] | null | def set_default_mfile(cls, mfile):
"""Set the default MATLAB script file format for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.mfile.
"""
cls._default_mfile = mfile
| ["def","set_default_mfile","(","cls",",","mfile",")",":","``","''","''","Set","the","default","MATLAB","script","file","format","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.mfile.","``","''","''","cls._default_mfile","=","mfile"] | 132 | 140 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 3 for calling the MatlabCommand obj's underlying member method code with example usage: obj.set_default_mfile(cls, mfile) without return types | 160 | node_id 3 | 1,440,235 |
set_default_paths | MatlabCommand | CommandLine | true | cls,paths | Interface that runs matlab code
>>> import nipype.interfaces.matlab as matlab
>>> mlab = matlab.MatlabCommand(mfile=False) # don't write script file
>>> mlab.inputs.script = "which('who')"
>>> out = mlab.run() # doctest: +SKIP | ["Interface","that","runs","matlab","code",">",">",">","import","nipype.interfaces.matlab","as","matlab",">",">",">","mlab","=","matlab.MatlabCommand","(","mfile=False",")","#","do","n't","write","script","file",">",">",">","mlab.inputs.script","=","``","which","(","'who","'",")","''",">",">",">","out","=","mlab.run","(",")","#","doctest",":","+SKIP"] | Set the default MATLAB paths for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.paths. | ["Set","the","default","MATLAB","paths","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.paths","."] | null | def set_default_paths(cls, paths):
"""Set the default MATLAB paths for MATLAB classes.
This method is used to set values for all MATLAB
subclasses. However, setting this will not update the output
type for any existing instances. For these, assign the
<instance>.inputs.paths.
"""
cls._default_paths = paths
| ["def","set_default_paths","(","cls",",","paths",")",":","``","''","''","Set","the","default","MATLAB","paths","for","MATLAB","classes",".","This","method","is","used","to","set","values","for","all","MATLAB","subclasses",".","However",",","setting","this","will","not","update","the","output","type","for","any","existing","instances",".","For","these",",","assign","the","<","instance",">",".inputs.paths.","``","''","''","cls._default_paths","=","paths"] | 143 | 151 | null | matlab.py | nipype/nipype/interfaces/matlab.py | import os
from ..None import config
from .base import CommandLineInputSpec, InputMultiPath, isdefined, CommandLine, traits, File, Directory | 15 | 2 | 3 | 1 | 2 | 7 | 1 | Use image node_id 4 for calling the MatlabCommand obj's underlying member method code with example usage: obj.set_default_paths(cls, paths) without return types | 160 | node_id 4 | 1,440,236 |
_set_param | LBFGS | Optimizer | true | self,params_data | Implements L-BFGS algorithm.
Heavily inspired by `minFunc
<https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`_.
.. warning::
This optimizer doesn't support per-parameter options and parameter
groups (there can be only one).
.. warning::
Right now all parameters have to be on a single device. This will be
improved in the future.
.. note::
This is a very memory intensive optimizer (it requires additional
``param_bytes * (history_size + 1)`` bytes). If it doesn't fit in memory
try reducing the history size, or use a different algorithm.
Args:
lr (float): learning rate (default: 1)
max_iter (int): maximal number of iterations per optimization step
(default: 20)
max_eval (int): maximal number of function evaluations per optimization
step (default: max_iter * 1.25).
tolerance_grad (float): termination tolerance on first order optimality
(default: 1e-7).
tolerance_change (float): termination tolerance on function
value/parameter changes (default: 1e-9).
history_size (int): update history size (default: 100).
line_search_fn (str): either 'strong_wolfe' or None (default: None). | ["Implements","L-BFGS","algorithm",".","Heavily","inspired","by","`","minFunc","<","https",":","\/\/www.cs.ubc.ca\/~schmidtm\/Software\/minFunc.html",">","`","_",".","..","warning",":",":","This","optimizer","does","n't","support","per-parameter","options","and","parameter","groups","(","there","can","be","only","one",")",".","..","warning",":",":","Right","now","all","parameters","have","to","be","on","a","single","device",".","This","will","be","improved","in","the","future",".","..","note",":",":","This","is","a","very","memory","intensive","optimizer","(","it","requires","additional","``","param_bytes","*","(","history_size","+","1",")","``","bytes",")",".","If","it","does","n't","fit","in","memory","try","reducing","the","history","size",",","or","use","a","different","algorithm",".","Args",":","lr","(","float",")",":","learning","rate","(","default",":","1",")","max_iter","(","int",")",":","maximal","number","of","iterations","per","optimization","step","(","default",":","20",")","max_eval","(","int",")",":","maximal","number","of","function","evaluations","per","optimization","step","(","default",":","max_iter","*","1.25",")",".","tolerance_grad","(","float",")",":","termination","tolerance","on","first","order","optimality","(","default",":","1e-7",")",".","tolerance_change","(","float",")",":","termination","tolerance","on","function","value\/parameter","changes","(","default",":","1e-9",")",".","history_size","(","int",")",":","update","history","size","(","default",":","100",")",".","line_search_fn","(","str",")",":","either","'strong_wolfe","'","or","None","(","default",":","None",")","."] | null | null | null | def _set_param(self, params_data):
for p, pdata in zip(self._params, params_data):
p.copy_(pdata)
| ["def","_set_param","(","self",",","params_data",")",":","for","p",",","pdata","in","zip","(","self._params",",","params_data",")",":","p.copy_","(","pdata",")"] | 274 | 276 | null | lbfgs.py | pytorch/torch/optim/lbfgs.py | import torch
from functools import reduce
from .optimizer import Optimizer | 15 | 1 | 3 | 2 | 1 | 8 | 1 | Use image node_id 6 for calling the LBFGS obj's underlying member method code with example usage: obj._set_param(params_data) without return types | 146 | node_id 6 | 1,759,984 |