project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
voxel51/fiftyone
cvat.py
CVATTrack.has_polylines
has_polylines
Whether this track has polygons or polylines.
[ "Whether", "this", "track", "has", "polygons", "or", "polylines." ]
def has_polylines(self): return bool(self.polygons) or bool(self.polylines)
['def', 'has_polylines(self):', 'return', 'bool(self.polygons)', 'or', 'bool(self.polylines)']
583,964
matsu0228/nlp-jp
server_description.py
ServerDescription.server_type
server_type
The type of this server.
[ "The", "type", "of", "this", "server." ]
def server_type(self): return self._server_type
['def', 'server_type(self):', 'return', 'self._server_type']
805,036
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds
palette.py
get_palette
get_palette
Get palette from various inputs.
[ "Get", "palette", "from", "various", "inputs." ]
def get_palette(palette, num_classes): assert isinstance(num_classes, int) if isinstance(palette, list): dataset_palette = palette elif isinstance(palette, tuple): dataset_palette = [palette] * num_classes elif palette == 'random' or palette is None: state = np.random.get_state()...
['def', 'get_palette(palette,', 'num_classes):', 'assert', 'isinstance(num_classes,', 'int)', 'if', 'isinstance(palette,', 'list):', 'dataset_palette', '=', 'palette', 'elif', 'isinstance(palette,', 'tuple):', 'dataset_palette', '=', '[palette]', '*', 'num_classes', 'elif', 'palette', '==', "'random'", 'or', 'palette',...
650,718
tryolabs/luminoth
config.py
types_compatible
types_compatible
Checks that config value types are compatible.
[ "Checks", "that", "config", "value", "types", "are", "compatible." ]
def types_compatible(new_config_value, base_config_value): if base_config_value is None: return True if new_config_value is None or new_config_value is False: return True if is_basestring(new_config_value) and is_basestring(base_config_value): return True return isinstance(new_co...
['def', 'types_compatible(new_config_value,', 'base_config_value):', 'if', 'base_config_value', 'is', 'None:', 'return', 'True', 'if', 'new_config_value', 'is', 'None', 'or', 'new_config_value', 'is', 'False:', 'return', 'True', 'if', 'is_basestring(new_config_value)', 'and', 'is_basestring(base_config_value):', 'retur...
617,547
Xianpeng919/MonoCon
inference.py
show_result_meshlab
show_result_meshlab
Show result by meshlab.
[ "Show", "result", "by", "meshlab." ]
def show_result_meshlab(data, result, out_dir, score_thr=0.0, show=False, snapshot=False, task='det', palette=None): assert task in ['det', 'multi_modality-det', 'seg', 'mono-det'], f'unsupported visualization task {task}' assert out_dir is not None, 'Expect out_dir, got none.' if task in ['det', 'multi_mod...
['def', 'show_result_meshlab(data,', 'result,', 'out_dir,', 'score_thr=0.0,', 'show=False,', 'snapshot=False,', "task='det',", 'palette=None):', 'assert', 'task', 'in', "['det',", "'multi_modality-det',", "'seg',", "'mono-det'],", "f'unsupported", 'visualization', 'task', "{task}'", 'assert', 'out_dir', 'is', 'not', 'N...
654,212
trenton3983/Programming_Computer__with_Python
lktrack.py
LKTracker.detect_points
detect_points
Detect 'good features to track' (corners) in the current frame using sub-pixel accuracy.
[ "Detect", "'good", "features", "to", "track'", "(corners)", "in", "the", "current", "frame", "using", "sub-pixel", "accuracy." ]
def detect_points(self): self.image = cv2.imread(self.imnames[self.current_frame]) self.gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY) features = cv2.goodFeaturesToTrack(self.gray, **feature_params) cv2.cornerSubPix(self.gray, features, **subpix_params) self.features = features self.tracks ...
['def', 'detect_points(self):', 'self.image', '=', 'cv2.imread(self.imnames[self.current_frame])', 'self.gray', '=', 'cv2.cvtColor(self.image,', 'cv2.COLOR_BGR2GRAY)', 'features', '=', 'cv2.goodFeaturesToTrack(self.gray,', '**feature_params)', 'cv2.cornerSubPix(self.gray,', 'features,', '**subpix_params)', 'self.featur...
817,297
sktime/sktime
test_temporaltraintest.py
test_temporal_train_test_split_int_only_y
test_temporal_train_test_split_int_only_y
Test temporal_train_test_split expected output on float size inputs.
[ "Test", "temporal_train_test_split", "expected", "output", "on", "float", "size", "inputs." ]
def test_temporal_train_test_split_int_only_y(): y = load_airline() (y_train, y_test) = temporal_train_test_split(y, test_size=29) assert isinstance(y_train, pd.Series) assert isinstance(y_test, pd.Series) assert len(y_train) == 115 assert len(y_test) == 29 assert (y[:115] == y_train).all() ...
['def', 'test_temporal_train_test_split_int_only_y():', 'y', '=', 'load_airline()', '(y_train,', 'y_test)', '=', 'temporal_train_test_split(y,', 'test_size=29)', 'assert', 'isinstance(y_train,', 'pd.Series)', 'assert', 'isinstance(y_test,', 'pd.Series)', 'assert', 'len(y_train)', '==', '115', 'assert', 'len(y_test)', '...
877,593
facebookresearch/CompilerGym
minimize_trajectory_test.py
test_bisect_explicit_hypothesis
test_bisect_explicit_hypothesis
Test that bisection chops off the tail.
[ "Test", "that", "bisection", "chops", "off", "the", "tail." ]
def test_bisect_explicit_hypothesis(n: int): env = MockEnv(actions=list(range(10))) list(mt.bisect_trajectory(env, make_hypothesis(n))) assert env.actions == list(range(n + 1))
['def', 'test_bisect_explicit_hypothesis(n:', 'int):', 'env', '=', 'MockEnv(actions=list(range(10)))', 'list(mt.bisect_trajectory(env,', 'make_hypothesis(n)))', 'assert', 'env.actions', '==', 'list(range(n', '+', '1))']
126,000
Farama-Foundation/Minigrid
baby_ai_bot.py
Subgoal.update_agent_attributes
update_agent_attributes
Should be called at each step before the replanning methods.
[ "Should", "be", "called", "at", "each", "step", "before", "the", "replanning", "methods." ]
def update_agent_attributes(self): self.pos = self.bot.mission.unwrapped.agent_pos self.dir_vec = self.bot.mission.unwrapped.dir_vec self.right_vec = self.bot.mission.unwrapped.right_vec self.fwd_pos = self.pos + self.dir_vec self.fwd_cell = self.bot.mission.unwrapped.grid.get(*self.fwd_pos) sel...
['def', 'update_agent_attributes(self):', 'self.pos', '=', 'self.bot.mission.unwrapped.agent_pos', 'self.dir_vec', '=', 'self.bot.mission.unwrapped.dir_vec', 'self.right_vec', '=', 'self.bot.mission.unwrapped.right_vec', 'self.fwd_pos', '=', 'self.pos', '+', 'self.dir_vec', 'self.fwd_cell', '=', 'self.bot.mission.unwra...
271,538
facebookresearch/Detectron
c2.py
BlobReferenceList
BlobReferenceList
Ensure that the argument is returned as a list of BlobReferences.
[ "Ensure", "that", "the", "argument", "is", "returned", "as", "a", "list", "of", "BlobReferences." ]
def BlobReferenceList(blob_ref_or_list): if isinstance(blob_ref_or_list, core.BlobReference): return [blob_ref_or_list] elif type(blob_ref_or_list) in (list, tuple): for b in blob_ref_or_list: assert isinstance(b, core.BlobReference) return blob_ref_or_list else: ...
['def', 'BlobReferenceList(blob_ref_or_list):', 'if', 'isinstance(blob_ref_or_list,', 'core.BlobReference):', 'return', '[blob_ref_or_list]', 'elif', 'type(blob_ref_or_list)', 'in', '(list,', 'tuple):', 'for', 'b', 'in', 'blob_ref_or_list:', 'assert', 'isinstance(b,', 'core.BlobReference)', 'return', 'blob_ref_or_list'...
548,988
facebookresearch/detectron2
benchmark.py
DataLoaderBenchmark.benchmark_dataset
benchmark_dataset
Benchmark the speed of taking raw samples from the dataset.
[ "Benchmark", "the", "speed", "of", "taking", "raw", "samples", "from", "the", "dataset." ]
def benchmark_dataset(self, num_iter, warmup=5): def loader(): while True: for k in self.sampler: yield self.dataset[k] self._benchmark(loader(), num_iter, warmup, 'Dataset Alone')
['def', 'benchmark_dataset(self,', 'num_iter,', 'warmup=5):', 'def', 'loader():', 'while', 'True:', 'for', 'k', 'in', 'self.sampler:', 'yield', 'self.dataset[k]', 'self._benchmark(loader(),', 'num_iter,', 'warmup,', "'Dataset", "Alone')"]
549,088
openvinotoolkit/training_extensions
mmov_ssd_head.py
MMOVSSDHead.forward
forward
Forward function for MMOVSSDHead.
[ "Forward", "function", "for", "MMOVSSDHead." ]
def forward(self, feats): cls_scores = [] bbox_preds = [] for (feat, reg_conv, cls_conv) in zip(feats, self.reg_convs, self.cls_convs): cls_score = cls_conv(feat) bbox_pred = reg_conv(feat) if self._transpose_cls: shape = cls_score.shape cls_score = cls_score....
['def', 'forward(self,', 'feats):', 'cls_scores', '=', '[]', 'bbox_preds', '=', '[]', 'for', '(feat,', 'reg_conv,', 'cls_conv)', 'in', 'zip(feats,', 'self.reg_convs,', 'self.cls_convs):', 'cls_score', '=', 'cls_conv(feat)', 'bbox_pred', '=', 'reg_conv(feat)', 'if', 'self._transpose_cls:', 'shape', '=', 'cls_score.shape...
918,099
google/deepvariant
realigner.py
copy_read
copy_read
Copies a read proto to create a new read part.
[ "Copies", "a", "read", "proto", "to", "create", "a", "new", "read", "part." ]
def copy_read(read, part): new_read = reads_pb2.Read() new_read.CopyFrom(read) new_read.alignment.Clear() new_read.aligned_quality[:] = [] new_read.aligned_sequence = '' new_read.alignment.position.reference_name = read.alignment.position.reference_name new_read.alignment.position.reverse_st...
['def', 'copy_read(read,', 'part):', 'new_read', '=', 'reads_pb2.Read()', 'new_read.CopyFrom(read)', 'new_read.alignment.Clear()', 'new_read.aligned_quality[:]', '=', '[]', 'new_read.aligned_sequence', '=', "''", 'new_read.alignment.position.reference_name', '=', 'read.alignment.position.reference_name', 'new_read.alig...
540,476
open-mmlab/mmrotate
enn.py
build_enn_norm_layer
build_enn_norm_layer
build an enn normalizion layer.
[ "build", "an", "enn", "normalizion", "layer." ]
def build_enn_norm_layer(num_features, postfix=''): in_type = build_enn_divide_feature(num_features) return ('bn' + str(postfix), enn.InnerBatchNorm(in_type))
['def', 'build_enn_norm_layer(num_features,', "postfix=''):", 'in_type', '=', 'build_enn_divide_feature(num_features)', 'return', "('bn'", '+', 'str(postfix),', 'enn.InnerBatchNorm(in_type))']
625,237
intel/neural-compressor
utility.py
recover
recover
Get offline recover tuned model.
[ "Get", "offline", "recover", "tuned", "model." ]
def recover(fp32_model, tuning_history_path, num, **kwargs): tuning_history = get_tuning_history(tuning_history_path) target_history = tuning_history[0]['history'] q_config = target_history[num]['q_config'] try: framework = tuning_history[0]['cfg']['model']['framework'] except Exception as e...
['def', 'recover(fp32_model,', 'tuning_history_path,', 'num,', '**kwargs):', 'tuning_history', '=', 'get_tuning_history(tuning_history_path)', 'target_history', '=', "tuning_history[0]['history']", 'q_config', '=', "target_history[num]['q_config']", 'try:', 'framework', '=', "tuning_history[0]['cfg']['model']['framewor...
721,495
Erfanafshar/Principles-and-Applications-of---graph-coloring
afm.py
AFM.get_height_char
get_height_char
Get the bounding box (ink) height of character *c* (space is 0).
[ "Get", "the", "bounding", "box", "(ink)", "height", "of", "character", "*c*", "(space", "is", "0)." ]
def get_height_char(self, c, isord=False): if not isord: c = ord(c) return self._metrics[c].bbox[-1]
['def', 'get_height_char(self,', 'c,', 'isord=False):', 'if', 'not', 'isord:', 'c', '=', 'ord(c)', 'return', 'self._metrics[c].bbox[-1]']
306,232
zihuitang/medical_AI_platform
pathlib.py
PurePath.is_reserved
is_reserved
Return True if the path contains one of the special names reserved by the system, if any.
[ "Return", "True", "if", "the", "path", "contains", "one", "of", "the", "special", "names", "reserved", "by", "the", "system,", "if", "any." ]
def is_reserved(self): return self._flavour.is_reserved(self._parts)
['def', 'is_reserved(self):', 'return', 'self._flavour.is_reserved(self._parts)']
280,967
weimin17/Object-Detection_HelmetDetection
contextual_bandit.py
ContextualBandit.reset
reset
Randomly shuffle the order of the contexts to deliver.
[ "Randomly", "shuffle", "the", "order", "of", "the", "contexts", "to", "deliver." ]
def reset(self): self.order = np.random.permutation(self.number_contexts)
['def', 'reset(self):', 'self.order', '=', 'np.random.permutation(self.number_contexts)']
762,327
akandykeller/NeuralWaveMachines
base.py
SequenceModel.init
init
Initializes the whole model parameters and state.
[ "Initializes", "the", "whole", "model", "parameters", "and", "state." ]
def init(self, rng: jnp.ndarray, inputs_or_shape: Union[jnp.ndarray, Mapping[str, jnp.ndarray], Sequence[int]]) -> Tuple[utils.Params, hk.State]: if isinstance(inputs_or_shape, (tuple, list)) and isinstance(inputs_or_shape[0], int): images = jnp.zeros(inputs_or_shape) else: images = utils.extrac...
['def', 'init(self,', 'rng:', 'jnp.ndarray,', 'inputs_or_shape:', 'Union[jnp.ndarray,', 'Mapping[str,', 'jnp.ndarray],', 'Sequence[int]])', '->', 'Tuple[utils.Params,', 'hk.State]:', 'if', 'isinstance(inputs_or_shape,', '(tuple,', 'list))', 'and', 'isinstance(inputs_or_shape[0],', 'int):', 'images', '=', 'jnp.zeros(inp...
293,664
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
util.py
NoDuplicatesConstructor
NoDuplicatesConstructor
Check for duplicate keys.
[ "Check", "for", "duplicate", "keys." ]
def NoDuplicatesConstructor(loader, node, deep=False): mapping = {} for (key_node, value_node) in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ConstructorError('while constructin...
['def', 'NoDuplicatesConstructor(loader,', 'node,', 'deep=False):', 'mapping', '=', '{}', 'for', '(key_node,', 'value_node)', 'in', 'node.value:', 'key', '=', 'loader.construct_object(key_node,', 'deep=deep)', 'value', '=', 'loader.construct_object(value_node,', 'deep=deep)', 'if', 'key', 'in', 'mapping:', 'raise', "Co...
29,816
GGmorello/fl_gan
mnist_shard_descriptor.py
MnistShardDescriptor.get_shard_dataset_types
get_shard_dataset_types
Get available shard dataset types.
[ "Get", "available", "shard", "dataset", "types." ]
def get_shard_dataset_types(self) -> List[str]: return list(self.data_by_type)
['def', 'get_shard_dataset_types(self)', '->', 'List[str]:', 'return', 'list(self.data_by_type)']
607,927
chaitanya100100/Feedforward-Neural-Network
check_grad.py
loss
loss
Compute loss with given parameter vector.
[ "Compute", "loss", "with", "given", "parameter", "vector." ]
def loss(params_vec, model, data, labels): use_params_vec(params_vec, model) (probs, loss) = model.forwardprop(data, labels) return loss
['def', 'loss(params_vec,', 'model,', 'data,', 'labels):', 'use_params_vec(params_vec,', 'model)', '(probs,', 'loss)', '=', 'model.forwardprop(data,', 'labels)', 'return', 'loss']
581,966
AxeldeRomblay/MLBox
test_regression_feature_selector.py
test_fit_transform_Reg_feature_selector
test_fit_transform_Reg_feature_selector
Test fit_transform method of Reg_feature_selector class.
[ "Test", "fit_transform", "method", "of", "Reg_feature_selector", "class." ]
def test_fit_transform_Reg_feature_selector(): feature_selector = Reg_feature_selector(threshold=0) df_train = pd.read_csv('data_for_tests/clean_train.csv') y_train = pd.read_csv('data_for_tests/clean_target.csv', squeeze=True) df_transformed = feature_selector.fit_transform(df_train, y_train) asser...
['def', 'test_fit_transform_Reg_feature_selector():', 'feature_selector', '=', 'Reg_feature_selector(threshold=0)', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'y_train', '=', "pd.read_csv('data_for_tests/clean_target.csv',", 'squeeze=True)', 'df_transformed', '=', 'feature_selector.fit_transform(...
630,062
43Carrig/recurrent_neural_networks_practice
context.py
Context.ones_rank_cache
ones_rank_cache
Per-device cache for scalars.
[ "Per-device", "cache", "for", "scalars." ]
def ones_rank_cache(self): return self._eager_context.ones_rank_cache
['def', 'ones_rank_cache(self):', 'return', 'self._eager_context.ones_rank_cache']
336,103
sek788432/Waymo-2D-Object-Detection
distribute_utils.py
configure_cluster
configure_cluster
Set multi-worker cluster spec in TF_CONFIG environment variable.
[ "Set", "multi-worker", "cluster", "spec", "in", "TF_CONFIG", "environment", "variable." ]
def configure_cluster(worker_hosts=None, task_index=-1): tf_config = json.loads(os.environ.get('TF_CONFIG', '{}')) if tf_config: num_workers = len(tf_config['cluster'].get('chief', [])) + len(tf_config['cluster'].get('worker', [])) elif worker_hosts: workers = worker_hosts.split(',') ...
['def', 'configure_cluster(worker_hosts=None,', 'task_index=-1):', 'tf_config', '=', "json.loads(os.environ.get('TF_CONFIG',", "'{}'))", 'if', 'tf_config:', 'num_workers', '=', "len(tf_config['cluster'].get('chief',", '[]))', '+', "len(tf_config['cluster'].get('worker',", '[]))', 'elif', 'worker_hosts:', 'workers', '='...
972,287
matsu0228/nlp-jp
figure.py
Figure.clear
clear
Clear the figure -- synonym for :meth:`clf`.
[ "Clear", "the", "figure", "--", "synonym", "for", ":meth:`clf`." ]
def clear(self, keep_observers=False): self.clf(keep_observers=keep_observers)
['def', 'clear(self,', 'keep_observers=False):', 'self.clf(keep_observers=keep_observers)']
788,741
DLR-RM/stable-baselines3
logger.py
Logger.to_tuple
to_tuple
Helper function to convert str to tuple of str.
[ "Helper", "function", "to", "convert", "str", "to", "tuple", "of", "str." ]
def to_tuple(string_or_tuple: Optional[Union[str, Tuple[str, ...]]]) -> Tuple[str, ...]: if string_or_tuple is None: return ('',) if isinstance(string_or_tuple, tuple): return string_or_tuple return (string_or_tuple,)
['def', 'to_tuple(string_or_tuple:', 'Optional[Union[str,', 'Tuple[str,', '...]]])', '->', 'Tuple[str,', '...]:', 'if', 'string_or_tuple', 'is', 'None:', 'return', "('',)", 'if', 'isinstance(string_or_tuple,', 'tuple):', 'return', 'string_or_tuple', 'return', '(string_or_tuple,)']
383,059
lopez-lab/PyRAI2MD
error.py
find_max_relative_error
find_max_relative_error
Find maximum error and its relative value if possible.
[ "Find", "maximum", "error", "and", "its", "relative", "value", "if", "possible." ]
def find_max_relative_error(preds, yval): pred = np.reshape(preds, (preds.shape[0], -1)) flat_yval = np.reshape(yval, (yval.shape[0], -1)) maxerr_ind = np.expand_dims(np.argmax(np.abs(pred - flat_yval), axis=0), axis=0) pred_err = np.abs(np.take_along_axis(pred, maxerr_ind, axis=0) - np.take_along_axis(...
['def', 'find_max_relative_error(preds,', 'yval):', 'pred', '=', 'np.reshape(preds,', '(preds.shape[0],', '-1))', 'flat_yval', '=', 'np.reshape(yval,', '(yval.shape[0],', '-1))', 'maxerr_ind', '=', 'np.expand_dims(np.argmax(np.abs(pred', '-', 'flat_yval),', 'axis=0),', 'axis=0)', 'pred_err', '=', 'np.abs(np.take_along_...
297,141
intel/neural-compressor
utils_model.py
ORTModel.evaluation_loop
evaluation_loop
Run evaluation and returns metrics and predictions.
[ "Run", "evaluation", "and", "returns", "metrics", "and", "predictions." ]
def evaluation_loop(self, dataset: Dataset): logger.info(f'***** Running evaluation *****') all_preds = None all_labels = None for (step, inputs) in tqdm.tqdm(enumerate(dataset), desc='eval'): has_labels = all((inputs.get(k) is not None for k in self.label_names)) if has_labels: ...
['def', 'evaluation_loop(self,', 'dataset:', 'Dataset):', "logger.info(f'*****", 'Running', 'evaluation', "*****')", 'all_preds', '=', 'None', 'all_labels', '=', 'None', 'for', '(step,', 'inputs)', 'in', 'tqdm.tqdm(enumerate(dataset),', "desc='eval'):", 'has_labels', '=', 'all((inputs.get(k)', 'is', 'not', 'None', 'for...
736,475
sek788432/Waymo-2D-Object-Detection
resnet_deeplab_test.py
ResNetTest.test_network_creation
test_network_creation
Test creation of ResNet models.
[ "Test", "creation", "of", "ResNet", "models." ]
def test_network_creation(self, input_size, model_id, endpoint_filter_scale, output_stride): tf.keras.backend.set_image_data_format('channels_last') network = resnet_deeplab.DilatedResNet(model_id=model_id, output_stride=output_stride) inputs = tf.keras.Input(shape=(input_size, input_size, 3), batch_size=1)...
['def', 'test_network_creation(self,', 'input_size,', 'model_id,', 'endpoint_filter_scale,', 'output_stride):', "tf.keras.backend.set_image_data_format('channels_last')", 'network', '=', 'resnet_deeplab.DilatedResNet(model_id=model_id,', 'output_stride=output_stride)', 'inputs', '=', 'tf.keras.Input(shape=(input_size,'...
973,133
googleapis/python-aiplatform
base_execution.py
BaseExecutionSchema.create
create
Creates a new Metadata Execution.
[ "Creates", "a", "new", "Metadata", "Execution." ]
def create(self, *, metadata_store_id: Optional[str]='default', project: Optional[str]=None, location: Optional[str]=None, credentials: Optional[auth_credentials.Credentials]=None) -> 'execution.Execution': base_constants.USER_AGENT_SDK_COMMAND = 'aiplatform.metadata.schema.base_execution.BaseExecutionSchema.create...
['def', 'create(self,', '*,', 'metadata_store_id:', "Optional[str]='default',", 'project:', 'Optional[str]=None,', 'location:', 'Optional[str]=None,', 'credentials:', 'Optional[auth_credentials.Credentials]=None)', '->', "'execution.Execution':", 'base_constants.USER_AGENT_SDK_COMMAND', '=', "'aiplatform.metadata.schem...
810,075
mfbx9da4/neuron-astrocyte-networks
trainer.py
Trainer.train
train
Train on the current dataset, for a single epoch.
[ "Train", "on", "the", "current", "dataset,", "for", "a", "single", "epoch." ]
def train(self): abstractMethod()
['def', 'train(self):', 'abstractMethod()']
723,262
TUMFTM/CamRaDepth
runner.py
save_files
save_files
If you decide to use this functionality, you'll have to set the relevant paths first.
[ "If", "you", "decide", "to", "use", "this", "functionality,", "you'll", "have", "to", "set", "the", "relevant", "paths", "first." ]
def save_files(model, output_path): project_files_path = Path(output_path) / 'project_files' os.makedirs(project_files_path, exist_ok=True) this_dir = os.path.dirname(__file__) model_file = None assert model, 'Model is None' if type(model) == CamRaDepth: model_file = os.path.join(this_di...
['def', 'save_files(model,', 'output_path):', 'project_files_path', '=', 'Path(output_path)', '/', "'project_files'", 'os.makedirs(project_files_path,', 'exist_ok=True)', 'this_dir', '=', 'os.path.dirname(__file__)', 'model_file', '=', 'None', 'assert', 'model,', "'Model", 'is', "None'", 'if', 'type(model)', '==', 'Cam...
454,751
jonathanking/sidechainnet
organize.py
get_validation_split_identifiers_from_pnid_list
get_validation_split_identifiers_from_pnid_list
Return a sorted list of validation set identifiers given a list of ProteinNet IDs.
[ "Return", "a", "sorted", "list", "of", "validation", "set", "identifiers", "given", "a", "list", "of", "ProteinNet", "IDs." ]
def get_validation_split_identifiers_from_pnid_list(pnids): matches = (re.match('(\\d+)#\\S+', s) for s in pnids) matches = set((m.group(1) for m in filter(lambda s: s is not None, matches))) return sorted(map(int, matches))
['def', 'get_validation_split_identifiers_from_pnid_list(pnids):', 'matches', '=', "(re.match('(\\\\d+)#\\\\S+',", 's)', 'for', 's', 'in', 'pnids)', 'matches', '=', 'set((m.group(1)', 'for', 'm', 'in', 'filter(lambda', 's:', 's', 'is', 'not', 'None,', 'matches)))', 'return', 'sorted(map(int,', 'matches))']
934,139
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
reader.py
Reader.get_prompt
get_prompt
Return what should be in the left-hand margin for line `lineno'.
[ "Return", "what", "should", "be", "in", "the", "left-hand", "margin", "for", "line", "`lineno'." ]
def get_prompt(self, lineno, cursor_on_line): if self.arg is not None and cursor_on_line: return '(arg: %s) ' % self.arg if '\n' in self.buffer: if lineno == 0: res = self.ps2 elif lineno == self.buffer.count('\n'): res = self.ps4 else: res = s...
['def', 'get_prompt(self,', 'lineno,', 'cursor_on_line):', 'if', 'self.arg', 'is', 'not', 'None', 'and', 'cursor_on_line:', 'return', "'(arg:", '%s)', "'", '%', 'self.arg', 'if', "'\\n'", 'in', 'self.buffer:', 'if', 'lineno', '==', '0:', 'res', '=', 'self.ps2', 'elif', 'lineno', '==', "self.buffer.count('\\n'):", 'res'...
377,452
blakeblackshear/frigate
log.py
LogPipe.run
run
Run the thread, logging everything.
[ "Run", "the", "thread,", "logging", "everything." ]
def run(self) -> None: for line in iter(self.pipeReader.readline, ''): self.deque.append(self.cleanup_log(line)) self.pipeReader.close()
['def', 'run(self)', '->', 'None:', 'for', 'line', 'in', 'iter(self.pipeReader.readline,', "''):", 'self.deque.append(self.cleanup_log(line))', 'self.pipeReader.close()']
564,453
aws/sagemaker-python-sdk
model_card.py
ModelOverview.from_model_name
from_model_name
Initialize a model overview object from auto-discovered data.
[ "Initialize", "a", "model", "overview", "object", "from", "auto-discovered", "data." ]
def from_model_name(cls, model_name: str, sagemaker_session: Session=None, **kwargs): def call_describe_model(): try: model_response = sagemaker_session.sagemaker_client.describe_model(ModelName=model_name) except ClientError as e: if e.response['Error']['Message'].startswit...
['def', 'from_model_name(cls,', 'model_name:', 'str,', 'sagemaker_session:', 'Session=None,', '**kwargs):', 'def', 'call_describe_model():', 'try:', 'model_response', '=', 'sagemaker_session.sagemaker_client.describe_model(ModelName=model_name)', 'except', 'ClientError', 'as', 'e:', 'if', "e.response['Error']['Message'...
830,375
hsim13372/QCompress
qae_engine_test.py
test_trying_to_predict_without_training
test_trying_to_predict_without_training
Test user trying to predict/test without training first.
[ "Test", "user", "trying", "to", "predict/test", "without", "training", "first." ]
def test_trying_to_predict_without_training(full_no_reset_inst): with pytest.raises(QAutoencoderError): test_loss = full_no_reset_inst.predict()
['def', 'test_trying_to_predict_without_training(full_no_reset_inst):', 'with', 'pytest.raises(QAutoencoderError):', 'test_loss', '=', 'full_no_reset_inst.predict()']
816,024
rudranil723/mini-main
build_tracker.py
BuildTracker.add
add
Add an InstallRequirement to build tracking.
[ "Add", "an", "InstallRequirement", "to", "build", "tracking." ]
def add(self, req: InstallRequirement) -> None: assert req.link entry_path = self._entry_path(req.link) try: with open(entry_path) as fp: contents = fp.read() except FileNotFoundError: pass else: message = '{} is already being built: {}'.format(req.link, contents)...
['def', 'add(self,', 'req:', 'InstallRequirement)', '->', 'None:', 'assert', 'req.link', 'entry_path', '=', 'self._entry_path(req.link)', 'try:', 'with', 'open(entry_path)', 'as', 'fp:', 'contents', '=', 'fp.read()', 'except', 'FileNotFoundError:', 'pass', 'else:', 'message', '=', "'{}", 'is', 'already', 'being', 'buil...
268,048
shery322/Lunar-Lander-ANN
transform_test.py
TransformModuleTest.test_threshold__subclassed_surface
test_threshold__subclassed_surface
Ensure threshold accepts subclassed surfaces.
[ "Ensure", "threshold", "accepts", "subclassed", "surfaces." ]
def test_threshold__subclassed_surface(self): expected_size = (13, 11) expected_flags = 0 expected_depth = 32 expected_color = (90, 80, 70, 255) expected_count = 0 surface = test_utils.SurfaceSubclass(expected_size, expected_flags, expected_depth) dest_surface = test_utils.SurfaceSubclass(ex...
['def', 'test_threshold__subclassed_surface(self):', 'expected_size', '=', '(13,', '11)', 'expected_flags', '=', '0', 'expected_depth', '=', '32', 'expected_color', '=', '(90,', '80,', '70,', '255)', 'expected_count', '=', '0', 'surface', '=', 'test_utils.SurfaceSubclass(expected_size,', 'expected_flags,', 'expected_de...
619,201
rudranil723/mini-main
srs.py
SpatialReference.wkt
wkt
Return the WKT representation of this Spatial Reference.
[ "Return", "the", "WKT", "representation", "of", "this", "Spatial", "Reference." ]
def wkt(self): return capi.to_wkt(self.ptr, byref(c_char_p()))
['def', 'wkt(self):', 'return', 'capi.to_wkt(self.ptr,', 'byref(c_char_p()))']
315,190
kianak2002/Sentiment-Emotion-Analysis-project
misc.py
redact_auth_from_url
redact_auth_from_url
Replace the password in a given url with ****.
[ "Replace", "the", "password", "in", "a", "given", "url", "with", "****." ]
def redact_auth_from_url(url): return _transform_url(url, _redact_netloc)[0]
['def', 'redact_auth_from_url(url):', 'return', '_transform_url(url,', '_redact_netloc)[0]']
874,749
deepmind/dm_alchemy
event_unpacking.py
get_potions
get_potions
Gets a list of Potion objects from creation events.
[ "Gets", "a", "list", "of", "Potion", "objects", "from", "creation", "events." ]
def get_potions(creation_events: Sequence[events_pb2.WorldEvent]) -> List[Tuple[stones_and_potions.PerceivedPotion, int]]: potions = [] for event in creation_events: if 'PotionCreated' in event.name: potion_event = alchemy_pb2.PotionCreated() event.detail.Unpack(potion_event) ...
['def', 'get_potions(creation_events:', 'Sequence[events_pb2.WorldEvent])', '->', 'List[Tuple[stones_and_potions.PerceivedPotion,', 'int]]:', 'potions', '=', '[]', 'for', 'event', 'in', 'creation_events:', 'if', "'PotionCreated'", 'in', 'event.name:', 'potion_event', '=', 'alchemy_pb2.PotionCreated()', 'event.detail.Un...
522,236
myothida/Supervised-Machine-Learning
test_kernel_pca.py
test_kernel_pca_deterministic_output
test_kernel_pca_deterministic_output
Test that Kernel PCA produces deterministic output Tests that the same inputs and random state produce the same output.
[ "Test", "that", "Kernel", "PCA", "produces", "deterministic", "output", "Tests", "that", "the", "same", "inputs", "and", "random", "state", "produce", "the", "same", "output." ]
def test_kernel_pca_deterministic_output(): rng = np.random.RandomState(0) X = rng.rand(10, 10) eigen_solver = ('arpack', 'dense') for solver in eigen_solver: transformed_X = np.zeros((20, 2)) for i in range(20): kpca = KernelPCA(n_components=2, eigen_solver=solver, random_st...
['def', 'test_kernel_pca_deterministic_output():', 'rng', '=', 'np.random.RandomState(0)', 'X', '=', 'rng.rand(10,', '10)', 'eigen_solver', '=', "('arpack',", "'dense')", 'for', 'solver', 'in', 'eigen_solver:', 'transformed_X', '=', 'np.zeros((20,', '2))', 'for', 'i', 'in', 'range(20):', 'kpca', '=', 'KernelPCA(n_compo...
363,670
tjfontaine/linode-python
api.py
Api.valid_commands
valid_commands
Returns a list of API commands supported by this class.
[ "Returns", "a", "list", "of", "API", "commands", "supported", "by", "this", "class." ]
def valid_commands(): return list(ApiInfo.valid_commands.keys())
['def', 'valid_commands():', 'return', 'list(ApiInfo.valid_commands.keys())']
216,808
ipazc/vrpwrp
image_helper.py
crop_by_bbox
crop_by_bbox
Crops the specified PIL image with the given bounding box :param pil_image: PIL image to crop :param bbox: bounding box object to crop by :return: PIL image cropped.
[ "Crops", "the", "specified", "PIL", "image", "with", "the", "given", "bounding", "box", ":param", "pil_image:", "PIL", "image", "to", "crop", ":param", "bbox:", "bounding", "box", "object", "to", "crop", "by", ":return:", "PIL", "image", "cropped." ]
def crop_by_bbox(pil_image, bbox): box = bbox.get_box() box[2] += box[0] box[3] += box[1] crop_result = pil_image.crop((box[0], box[1], box[2], box[3])) return crop_result
['def', 'crop_by_bbox(pil_image,', 'bbox):', 'box', '=', 'bbox.get_box()', 'box[2]', '+=', 'box[0]', 'box[3]', '+=', 'box[1]', 'crop_result', '=', 'pil_image.crop((box[0],', 'box[1],', 'box[2],', 'box[3]))', 'return', 'crop_result']
940,003
nicknochnack/RealTimeSignLanguageTFJS
base_config_test.py
BaseConfigTest.assertHasSameTypes
assertHasSameTypes
Checks if a Config has the same structure as a given dict.
[ "Checks", "if", "a", "Config", "has", "the", "same", "structure", "as", "a", "given", "dict." ]
def assertHasSameTypes(self, c, d, msg=''): self.assertNotIsInstance(d, base_config.Config) if isinstance(d, base_config.Config.IMMUTABLE_TYPES): self.assertEqual(pprint.pformat(c), pprint.pformat(d), msg=msg) elif isinstance(d, base_config.Config.SEQUENCE_TYPES): self.assertEqual(type(c), t...
['def', 'assertHasSameTypes(self,', 'c,', 'd,', "msg=''):", 'self.assertNotIsInstance(d,', 'base_config.Config)', 'if', 'isinstance(d,', 'base_config.Config.IMMUTABLE_TYPES):', 'self.assertEqual(pprint.pformat(c),', 'pprint.pformat(d),', 'msg=msg)', 'elif', 'isinstance(d,', 'base_config.Config.SEQUENCE_TYPES):', 'self....
850,225
ppriyank/Bert-Coref-Resolution-Lee-
remove_lstm.py
CorefModel.bucket_distance
bucket_distance
Places the given values (designed for distances) into 10 semi-logscale buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].
[ "Places", "the", "given", "values", "(designed", "for", "distances)", "into", "10", "semi-logscale", "buckets:", "[0,", "1,", "2,", "3,", "4,", "5-7,", "8-15,", "16-31,", "32-63,", "64+]." ]
def bucket_distance(self, distances): logspace_idx = tf.to_int32(tf.floor(tf.log(tf.to_float(distances)) / math.log(2))) + 3 use_identity = tf.to_int32(distances <= 4) combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx return tf.clip_by_value(combined_idx, 0, 9)
['def', 'bucket_distance(self,', 'distances):', 'logspace_idx', '=', 'tf.to_int32(tf.floor(tf.log(tf.to_float(distances))', '/', 'math.log(2)))', '+', '3', 'use_identity', '=', 'tf.to_int32(distances', '<=', '4)', 'combined_idx', '=', 'use_identity', '*', 'distances', '+', '(1', '-', 'use_identity)', '*', 'logspace_idx...
434,143
sbjelogr/TransferBoost
loss_functions.py
loss_from_leaves
loss_from_leaves
Calculate the gradients and hessian of the logloss functions.
[ "Calculate", "the", "gradients", "and", "hessian", "of", "the", "logloss", "functions." ]
def loss_from_leaves(y_leaf, y_true, loss_func): prob = _logistic(y_leaf) return loss_func(prob, y_true)
['def', 'loss_from_leaves(y_leaf,', 'y_true,', 'loss_func):', 'prob', '=', '_logistic(y_leaf)', 'return', 'loss_func(prob,', 'y_true)']
930,178
tobegit3hub/deep_image_model
server_test.py
TensorboardServerTest.testSampleScalarsWithLargeSampleCount
testSampleScalarsWithLargeSampleCount
Test using a large sample_count.
[ "Test", "using", "a", "large", "sample_count." ]
def testSampleScalarsWithLargeSampleCount(self): samples = self._getJson('/data/scalars?sample_count=999999') values = samples['run1']['simple_values'] self.assertEqual(len(values), self._SCALAR_COUNT)
['def', 'testSampleScalarsWithLargeSampleCount(self):', 'samples', '=', "self._getJson('/data/scalars?sample_count=999999')", 'values', '=', "samples['run1']['simple_values']", 'self.assertEqual(len(values),', 'self._SCALAR_COUNT)']
183,481
sek788432/Waymo-2D-Object-Detection
model.py
Model.create_summaries
create_summaries
Creates all summaries for the model.
[ "Creates", "all", "summaries", "for", "the", "model." ]
def create_summaries(self, data, endpoints, charset, is_training): def sname(label): prefix = 'train' if is_training else 'eval' return '%s/%s' % (prefix, label) max_outputs = 4 tf.compat.v1.summary.image(sname('image'), data.images, max_outputs=max_outputs) if is_training: tf.c...
['def', 'create_summaries(self,', 'data,', 'endpoints,', 'charset,', 'is_training):', 'def', 'sname(label):', 'prefix', '=', "'train'", 'if', 'is_training', 'else', "'eval'", 'return', "'%s/%s'", '%', '(prefix,', 'label)', 'max_outputs', '=', '4', "tf.compat.v1.summary.image(sname('image'),", 'data.images,', 'max_outpu...
973,942
albertomontesg/probabilistic-ai-exercises
sampling.py
GibbsSampler.update_fgraph
update_fgraph
Should be called when the associated factor graph is updated.
[ "Should", "be", "called", "when", "the", "associated", "factor", "graph", "is", "updated." ]
def update_fgraph(self): self.vs = self.fgraph.vs self.vobs = self.fgraph.vobs
['def', 'update_fgraph(self):', 'self.vs', '=', 'self.fgraph.vs', 'self.vobs', '=', 'self.fgraph.vobs']
295,462
imranparuk/speaker-recognition-3d-cnn
speechpy.py
mfe
mfe
Compute Mel-filterbank energy features from an audio signal.
[ "Compute", "Mel-filterbank", "energy", "features", "from", "an", "audio", "signal." ]
def mfe(signal, sampling_frequency, frame_length=0.02, frame_stride=0.01, num_filters=40, fft_length=512, low_frequency=0, high_frequency=None): signal = signal.astype(float) frames = stack_frames(signal, sampling_frequency=sampling_frequency, frame_length=frame_length, frame_stride=frame_stride, filter=lambda ...
['def', 'mfe(signal,', 'sampling_frequency,', 'frame_length=0.02,', 'frame_stride=0.01,', 'num_filters=40,', 'fft_length=512,', 'low_frequency=0,', 'high_frequency=None):', 'signal', '=', 'signal.astype(float)', 'frames', '=', 'stack_frames(signal,', 'sampling_frequency=sampling_frequency,', 'frame_length=frame_length,...
894,790
anjanatiha/Generative-Open-Domain-Chatbot-Application-with--Learning
apply_bpe.py
recursive_split
recursive_split
Recursively split segment into smaller units (by reversing BPE merges) until all units are either in-vocabulary, or cannot be split futher.
[ "Recursively", "split", "segment", "into", "smaller", "units", "(by", "reversing", "BPE", "merges)", "until", "all", "units", "are", "either", "in-vocabulary,", "or", "cannot", "be", "split", "futher." ]
def recursive_split(segment, bpe_codes, vocab, separator, final=False): try: if final: (left, right) = bpe_codes[segment + '</w>'] right = right[:-4] else: (left, right) = bpe_codes[segment] except: yield segment return if left + separator ...
['def', 'recursive_split(segment,', 'bpe_codes,', 'vocab,', 'separator,', 'final=False):', 'try:', 'if', 'final:', '(left,', 'right)', '=', 'bpe_codes[segment', '+', "'</w>']", 'right', '=', 'right[:-4]', 'else:', '(left,', 'right)', '=', 'bpe_codes[segment]', 'except:', 'yield', 'segment', 'return', 'if', 'left', '+',...
556,471
scikit-learn/scikit-learn
test_column_transformer.py
test_feature_name_validation_missing_columns_drop_passthough
test_feature_name_validation_missing_columns_drop_passthough
Test the interaction between {'drop', 'passthrough'} and missing column names.
[ "Test", "the", "interaction", "between", "{'drop',", "'passthrough'}", "and", "missing", "column", "names." ]
def test_feature_name_validation_missing_columns_drop_passthough(): pd = pytest.importorskip('pandas') X = np.ones(shape=(3, 4)) df = pd.DataFrame(X, columns=['a', 'b', 'c', 'd']) df_dropped = df.drop('c', axis=1) tf = ColumnTransformer([('bycol', Trans(), [1])], remainder='passthrough') tf.fit(...
['def', 'test_feature_name_validation_missing_columns_drop_passthough():', 'pd', '=', "pytest.importorskip('pandas')", 'X', '=', 'np.ones(shape=(3,', '4))', 'df', '=', 'pd.DataFrame(X,', "columns=['a',", "'b',", "'c',", "'d'])", 'df_dropped', '=', "df.drop('c',", 'axis=1)', 'tf', '=', "ColumnTransformer([('bycol',", 'T...
852,891
weimin17/Object-Detection_HelmetDetection
mcts.py
MCTSNode.maybe_add_child
maybe_add_child
Add child node for fcoord if it doesn't already exist, and returns it.
[ "Add", "child", "node", "for", "fcoord", "if", "it", "doesn't", "already", "exist,", "and", "returns", "it." ]
def maybe_add_child(self, fcoord): if fcoord not in self.children: new_position = self.position.play_move(coords.from_flat(self.board_size, fcoord)) self.children[fcoord] = MCTSNode(self.board_size, new_position, fmove=fcoord, parent=self) return self.children[fcoord]
['def', 'maybe_add_child(self,', 'fcoord):', 'if', 'fcoord', 'not', 'in', 'self.children:', 'new_position', '=', 'self.position.play_move(coords.from_flat(self.board_size,', 'fcoord))', 'self.children[fcoord]', '=', 'MCTSNode(self.board_size,', 'new_position,', 'fmove=fcoord,', 'parent=self)', 'return', 'self.children[...
763,876
vuptran/cardiac-segmentation
fcn_model.py
crop
crop
List of 2 tensors, the second tensor having larger spatial dimensions.
[ "List", "of", "2", "tensors,", "the", "second", "tensor", "having", "larger", "spatial", "dimensions." ]
def crop(tensors): (h_dims, w_dims) = ([], []) for t in tensors: (b, h, w, d) = K.get_variable_shape(t) h_dims.append(h) w_dims.append(w) (crop_h, crop_w) = (h_dims[1] - h_dims[0], w_dims[1] - w_dims[0]) rem_h = crop_h % 2 rem_w = crop_w % 2 crop_h_dims = (crop_h / 2, cro...
['def', 'crop(tensors):', '(h_dims,', 'w_dims)', '=', '([],', '[])', 'for', 't', 'in', 'tensors:', '(b,', 'h,', 'w,', 'd)', '=', 'K.get_variable_shape(t)', 'h_dims.append(h)', 'w_dims.append(w)', '(crop_h,', 'crop_w)', '=', '(h_dims[1]', '-', 'h_dims[0],', 'w_dims[1]', '-', 'w_dims[0])', 'rem_h', '=', 'crop_h', '%', '2...
102,974
TrellixVulnTeam/Unsupervised_Learning_HFI7
image.py
_ImageBase.get_filternorm
get_filternorm
Return whether the resize filter normalizes the weights.
[ "Return", "whether", "the", "resize", "filter", "normalizes", "the", "weights." ]
def get_filternorm(self): return self._filternorm
['def', 'get_filternorm(self):', 'return', 'self._filternorm']
450,525
google-research/tensor2robot
visualization.py
tf_put_text
tf_put_text
Adds text to an image tensor.
[ "Adds", "text", "to", "an", "image", "tensor." ]
def tf_put_text(imgs, texts, text_size=1, text_pos=(0, 30), text_color=(0, 0, 1)): def _put_text(imgs, texts): result = np.empty_like(imgs) for i in range(imgs.shape[0]): text = texts[i] if isinstance(text, bytes): text = six.ensure_text(text) res...
['def', 'tf_put_text(imgs,', 'texts,', 'text_size=1,', 'text_pos=(0,', '30),', 'text_color=(0,', '0,', '1)):', 'def', '_put_text(imgs,', 'texts):', 'result', '=', 'np.empty_like(imgs)', 'for', 'i', 'in', 'range(imgs.shape[0]):', 'text', '=', 'texts[i]', 'if', 'isinstance(text,', 'bytes):', 'text', '=', 'six.ensure_text...
908,384
google-research/batch_rl
fixed_replay_runner_test.py
FixedReplayRunnerIntegrationTest.quickFixedReplayREMFlags
quickFixedReplayREMFlags
Assign flags for a quick run of FixedReplay agent.
[ "Assign", "flags", "for", "a", "quick", "run", "of", "FixedReplay", "agent." ]
def quickFixedReplayREMFlags(self): FLAGS.gin_bindings = ["create_runner.schedule='continuous_train_and_eval'", 'FixedReplayRunner.training_steps=100', 'FixedReplayRunner.evaluation_steps=10', 'FixedReplayRunner.num_iterations=1', 'FixedReplayRunner.max_steps_per_episode=100'] FLAGS.alsologtostderr = True F...
['def', 'quickFixedReplayREMFlags(self):', 'FLAGS.gin_bindings', '=', '["create_runner.schedule=\'continuous_train_and_eval\'",', "'FixedReplayRunner.training_steps=100',", "'FixedReplayRunner.evaluation_steps=10',", "'FixedReplayRunner.num_iterations=1',", "'FixedReplayRunner.max_steps_per_episode=100']", 'FLAGS.alsol...
105,896
ziberna/i3-py
i3.py
container
container
Turns keyword arguments into a formatted container criteria.
[ "Turns", "keyword", "arguments", "into", "a", "formatted", "container", "criteria." ]
def container(**criteria): criteria = ['%s="%s"' % (key, val) for (key, val) in criteria.items()] return '[%s]' % ' '.join(criteria)
['def', 'container(**criteria):', 'criteria', '=', '[\'%s="%s"\'', '%', '(key,', 'val)', 'for', '(key,', 'val)', 'in', 'criteria.items()]', 'return', "'[%s]'", '%', "'", "'.join(criteria)"]
228,191
shiwt03/SSformer
class_names.py
stare_palette
stare_palette
STARE palette for external use.
[ "STARE", "palette", "for", "external", "use." ]
def stare_palette(): return [[120, 120, 120], [6, 230, 230]]
['def', 'stare_palette():', 'return', '[[120,', '120,', '120],', '[6,', '230,', '230]]']
871,877
greydanus/mr_london
repr.py
debug_repr
debug_repr
Creates a debug repr of an object as HTML unicode string.
[ "Creates", "a", "debug", "repr", "of", "an", "object", "as", "HTML", "unicode", "string." ]
def debug_repr(obj): return DebugReprGenerator().repr(obj)
['def', 'debug_repr(obj):', 'return', 'DebugReprGenerator().repr(obj)']
264,364
chenyuntc/dsod.pytorch
vis_image.py
vis_image
vis_image
Visualize a color image.
[ "Visualize", "a", "color", "image." ]
def vis_image(img, boxes=None, label_names=None, scores=None): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if isinstance(img, torch.Tensor): img = torchvision.transforms.ToPILImage()(img) ax.imshow(img) if boxes is not None: for (i, bb) in enumerate(boxes): xy = (bb[...
['def', 'vis_image(img,', 'boxes=None,', 'label_names=None,', 'scores=None):', 'fig', '=', 'plt.figure()', 'ax', '=', 'fig.add_subplot(1,', '1,', '1)', 'if', 'isinstance(img,', 'torch.Tensor):', 'img', '=', 'torchvision.transforms.ToPILImage()(img)', 'ax.imshow(img)', 'if', 'boxes', 'is', 'not', 'None:', 'for', '(i,', ...
173,942
JahJajaka/afternoon_cleaner
ops.py
bfloat16_to_float32_nested
bfloat16_to_float32_nested
Convert float32 tensors in a nested structure to bfloat16.
[ "Convert", "float32", "tensors", "in", "a", "nested", "structure", "to", "bfloat16." ]
def bfloat16_to_float32_nested(tensor_nested): if isinstance(tensor_nested, tf.Tensor): if tensor_nested.dtype == tf.bfloat16: return tf.cast(tensor_nested, dtype=tf.float32) else: return tensor_nested elif isinstance(tensor_nested, (list, tuple)): out_tensor_dict...
['def', 'bfloat16_to_float32_nested(tensor_nested):', 'if', 'isinstance(tensor_nested,', 'tf.Tensor):', 'if', 'tensor_nested.dtype', '==', 'tf.bfloat16:', 'return', 'tf.cast(tensor_nested,', 'dtype=tf.float32)', 'else:', 'return', 'tensor_nested', 'elif', 'isinstance(tensor_nested,', '(list,', 'tuple)):', 'out_tensor_d...
411,547
weimin17/Object-Detection_HelmetDetection
dataset_loader.py
KittiRaw.collect_train_frames
collect_train_frames
Creates a list of training frames.
[ "Creates", "a", "list", "of", "training", "frames." ]
def collect_train_frames(self): all_frames = [] for date in self.date_list: date_dir = os.path.join(self.dataset_dir, date) drive_set = os.listdir(date_dir) for dr in drive_set: drive_dir = os.path.join(date_dir, dr) if os.path.isdir(drive_dir): if...
['def', 'collect_train_frames(self):', 'all_frames', '=', '[]', 'for', 'date', 'in', 'self.date_list:', 'date_dir', '=', 'os.path.join(self.dataset_dir,', 'date)', 'drive_set', '=', 'os.listdir(date_dir)', 'for', 'dr', 'in', 'drive_set:', 'drive_dir', '=', 'os.path.join(date_dir,', 'dr)', 'if', 'os.path.isdir(drive_dir...
754,058
greydanus/mr_london
runtime.py
Context.derived
derived
Internal helper function to create a derived context.
[ "Internal", "helper", "function", "to", "create", "a", "derived", "context." ]
def derived(self, locals=None): context = new_context(self.environment, self.name, {}, self.parent, True, None, locals) context.vars.update(self.vars) context.eval_ctx = self.eval_ctx context.blocks.update(((k, list(v)) for (k, v) in iteritems(self.blocks))) return context
['def', 'derived(self,', 'locals=None):', 'context', '=', 'new_context(self.environment,', 'self.name,', '{},', 'self.parent,', 'True,', 'None,', 'locals)', 'context.vars.update(self.vars)', 'context.eval_ctx', '=', 'self.eval_ctx', 'context.blocks.update(((k,', 'list(v))', 'for', '(k,', 'v)', 'in', 'iteritems(self.blo...
262,436
tensorflow/privacy
generate_secrets.py
generate_text_secrets_and_references
generate_text_secrets_and_references
Generates a sequence of text secret sets given a sequence of configurations.
[ "Generates", "a", "sequence", "of", "text", "secret", "sets", "given", "a", "sequence", "of", "configurations." ]
def generate_text_secrets_and_references(secret_configs: Sequence[SecretConfig], seed: int=0) -> MutableSequence[SecretsSet]: secrets_sets = [] for (i, secret_config) in enumerate(secret_configs): n = secret_config.num_references + sum(secret_config.num_secrets_for_repetitions) seqs = generate_r...
['def', 'generate_text_secrets_and_references(secret_configs:', 'Sequence[SecretConfig],', 'seed:', 'int=0)', '->', 'MutableSequence[SecretsSet]:', 'secrets_sets', '=', '[]', 'for', '(i,', 'secret_config)', 'in', 'enumerate(secret_configs):', 'n', '=', 'secret_config.num_references', '+', 'sum(secret_config.num_secrets...
824,944
kornia/kornia
conversions.py
Rt_to_matrix4x4
Rt_to_matrix4x4
Combines 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.
[ "Combines", "3x3", "rotation", "matrix", "R", "and", "1x3", "translation", "vector", "t", "into", "4x4", "extrinsics." ]
def Rt_to_matrix4x4(R: Tensor, t: Tensor) -> Tensor: KORNIA_CHECK_SHAPE(R, ['B', '3', '3']) KORNIA_CHECK_SHAPE(t, ['B', '3', '1']) Rt = concatenate([R, t], dim=2) return convert_affinematrix_to_homography3d(Rt)
['def', 'Rt_to_matrix4x4(R:', 'Tensor,', 't:', 'Tensor)', '->', 'Tensor:', 'KORNIA_CHECK_SHAPE(R,', "['B',", "'3',", "'3'])", 'KORNIA_CHECK_SHAPE(t,', "['B',", "'3',", "'1'])", 'Rt', '=', 'concatenate([R,', 't],', 'dim=2)', 'return', 'convert_affinematrix_to_homography3d(Rt)']
621,886
enlite-ai/maze
hydra_helper_functions.py
check_random_sampling
check_random_sampling
Check if random sampling in instantiated env works.
[ "Check", "if", "random", "sampling", "in", "instantiated", "env", "works." ]
def check_random_sampling(config_module: str, config: str, overrides: Dict[str, str]) -> None: env = make_env_from_hydra(config_module, config, **overrides) if isinstance(env, ObservationNormalizationWrapper): normalization_statistics = obtain_normalization_statistics(env=env, n_samples=100) env...
['def', 'check_random_sampling(config_module:', 'str,', 'config:', 'str,', 'overrides:', 'Dict[str,', 'str])', '->', 'None:', 'env', '=', 'make_env_from_hydra(config_module,', 'config,', '**overrides)', 'if', 'isinstance(env,', 'ObservationNormalizationWrapper):', 'normalization_statistics', '=', 'obtain_normalization_...
647,266
tensorflow/agents
numpy_storage.py
NumpyStorage.set
set
Set table_idx to value.
[ "Set", "table_idx", "to", "value." ]
def set(self, table_idx, value): for (nest_idx, element) in enumerate(tf.nest.flatten(value)): self._array(nest_idx)[table_idx] = element
['def', 'set(self,', 'table_idx,', 'value):', 'for', '(nest_idx,', 'element)', 'in', 'enumerate(tf.nest.flatten(value)):', 'self._array(nest_idx)[table_idx]', '=', 'element']
23,147
chribsen/simple-machine-learning-examples
ast_tools.py
tuples_to_lists
tuples_to_lists
Convert an ast object tree in tuple form to list form.
[ "Convert", "an", "ast", "object", "tree", "in", "tuple", "form", "to", "list", "form." ]
def tuples_to_lists(ast_tuple): if not issequence(ast_tuple): return ast_tuple new_list = [] for item in ast_tuple: new_list.append(tuples_to_lists(item)) return new_list
['def', 'tuples_to_lists(ast_tuple):', 'if', 'not', 'issequence(ast_tuple):', 'return', 'ast_tuple', 'new_list', '=', '[]', 'for', 'item', 'in', 'ast_tuple:', 'new_list.append(tuples_to_lists(item))', 'return', 'new_list']
938,627
dbash/zerowaste
events.py
EventStorage.put_image
put_image
Add an `img_tensor` associated with `img_name`, to be shown on tensorboard.
[ "Add", "an", "`img_tensor`", "associated", "with", "`img_name`,", "to", "be", "shown", "on", "tensorboard." ]
def put_image(self, img_name, img_tensor): self._vis_data.append((img_name, img_tensor, self._iter))
['def', 'put_image(self,', 'img_name,', 'img_tensor):', 'self._vis_data.append((img_name,', 'img_tensor,', 'self._iter))']
971,566
cfernandezlab/Category-Specific-Keypoints
helper.py
normalize_data
normalize_data
center models and normalize [-1,1].
[ "center", "models", "and", "normalize", "[-1,1]." ]
def normalize_data(pc): pc_shift = np.sum(pc, axis=0) / len(pc) pc = pc - pc_shift dimX = np.max(pc[:, 0]) - np.min(pc[:, 0]) dimY = np.max(pc[:, 1]) - np.min(pc[:, 1]) dimZ = np.max(pc[:, 2]) - np.min(pc[:, 2]) scale = 2 / np.max([dimX, dimY, dimZ]) pc = pc * scale return pc
['def', 'normalize_data(pc):', 'pc_shift', '=', 'np.sum(pc,', 'axis=0)', '/', 'len(pc)', 'pc', '=', 'pc', '-', 'pc_shift', 'dimX', '=', 'np.max(pc[:,', '0])', '-', 'np.min(pc[:,', '0])', 'dimY', '=', 'np.max(pc[:,', '1])', '-', 'np.min(pc[:,', '1])', 'dimZ', '=', 'np.max(pc[:,', '2])', '-', 'np.min(pc[:,', '2])', 'scal...
103,216
StanfordVL/taskonomy
encoder_decoder_cgan.py
EDWithCGAN.build_discriminator
build_discriminator
Build the descriminator for GAN loss.
[ "Build", "the", "descriminator", "for", "GAN", "loss." ]
def build_discriminator(self, input_imgs, decoder_output, is_training, reuse=False): discriminator_kwargs = {} if 'discriminator_kwargs' in self.cfg: discriminator_kwargs = self.cfg['discriminator_kwargs'] else: print("Not using 'kwargs' arguments for discriminator_kwargs.") if 'instance...
['def', 'build_discriminator(self,', 'input_imgs,', 'decoder_output,', 'is_training,', 'reuse=False):', 'discriminator_kwargs', '=', '{}', 'if', "'discriminator_kwargs'", 'in', 'self.cfg:', 'discriminator_kwargs', '=', "self.cfg['discriminator_kwargs']", 'else:', 'print("Not', 'using', "'kwargs'", 'arguments', 'for', '...
907,539
microsoft/fastseq
benchmark_fairseq_optimizer.py
FairseqBeamSearchOptimizerBenchmark.setUp
setUp
Set up the test environment.
[ "Set", "up", "the", "test", "environment." ]
def setUp(self): super(FairseqBeamSearchOptimizerBenchmark, self).setUp() if not os.path.exists(CACHED_BART_MODEL_PATHS['bart.large.cnn']): make_dirs(CACHED_BART_MODEL_DIR, exist_ok=True) tar_model_path = os.path.join(CACHED_BART_MODEL_DIR, 'bart.large.cnn.tar.gz') with open(tar_model_pa...
['def', 'setUp(self):', 'super(FairseqBeamSearchOptimizerBenchmark,', 'self).setUp()', 'if', 'not', "os.path.exists(CACHED_BART_MODEL_PATHS['bart.large.cnn']):", 'make_dirs(CACHED_BART_MODEL_DIR,', 'exist_ok=True)', 'tar_model_path', '=', 'os.path.join(CACHED_BART_MODEL_DIR,', "'bart.large.cnn.tar.gz')", 'with', 'open(...
559,928
SergiosKar/Deep-Learning-models
sagemaker_utils.py
launch_sagemaker_job
launch_sagemaker_job
Create a SageMaker job connected to FSx and Horovod.
[ "Create", "a", "SageMaker", "job", "connected", "to", "FSx", "and", "Horovod." ]
def launch_sagemaker_job(job_name: str, source_dir: str, entry_point: str, instance_type: str, instance_count: int, hyperparameters: Dict[str, Any], role: str, image_name: str, fsx_id: str, subnet_ids: List[str], security_group_ids: List[str]) -> None: hvd_processes_per_host = {'ml.p3dn.24xlarge': 8, 'ml.p3.16xlarg...
['def', 'launch_sagemaker_job(job_name:', 'str,', 'source_dir:', 'str,', 'entry_point:', 'str,', 'instance_type:', 'str,', 'instance_count:', 'int,', 'hyperparameters:', 'Dict[str,', 'Any],', 'role:', 'str,', 'image_name:', 'str,', 'fsx_id:', 'str,', 'subnet_ids:', 'List[str],', 'security_group_ids:', 'List[str])', '->...
518,781
HuiGuanLab/HiCo
tensor.py
tensor2cuda
tensor2cuda
Put Tensor in iterable data into gpu.
[ "Put", "Tensor", "in", "iterable", "data", "into", "gpu." ]
def tensor2cuda(data): if type(data) == torch.Tensor: return data.cuda(non_blocking=True) elif type(data) == dict: keys = list(data.keys()) for k in keys: data[k] = tensor2cuda(data[k]) elif type(data) == list: for i in range(len(data)): data[i] = tens...
['def', 'tensor2cuda(data):', 'if', 'type(data)', '==', 'torch.Tensor:', 'return', 'data.cuda(non_blocking=True)', 'elif', 'type(data)', '==', 'dict:', 'keys', '=', 'list(data.keys())', 'for', 'k', 'in', 'keys:', 'data[k]', '=', 'tensor2cuda(data[k])', 'elif', 'type(data)', '==', 'list:', 'for', 'i', 'in', 'range(len(d...
206,307
gunthercox/ChatterBot
utils.py
func_args_as_dict
func_args_as_dict
Returns given function positional and key value arguments as an ordered dictionary.
[ "Returns", "given", "function", "positional", "and", "key", "value", "arguments", "as", "an", "ordered", "dictionary." ]
def func_args_as_dict(func, args, kwargs): arg_names = list(OrderedDict.fromkeys(itertools.chain(inspect.getargspec(func)[0], kwargs.keys()))) return OrderedDict(list(six.moves.zip(arg_names, args)) + list(kwargs.items()))
['def', 'func_args_as_dict(func,', 'args,', 'kwargs):', 'arg_names', '=', 'list(OrderedDict.fromkeys(itertools.chain(inspect.getargspec(func)[0],', 'kwargs.keys())))', 'return', 'OrderedDict(list(six.moves.zip(arg_names,', 'args))', '+', 'list(kwargs.items()))']
483,001
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
dataset.py
check_image_file_header
check_image_file_header
Validate that filename corresponds to images for the MNIST dataset.
[ "Validate", "that", "filename", "corresponds", "to", "images", "for", "the", "MNIST", "dataset." ]
def check_image_file_header(filename): with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) num_images = read32(f) rows = read32(f) cols = read32(f) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, f.name)) if r...
['def', 'check_image_file_header(filename):', 'with', 'tf.gfile.Open(filename,', "'rb')", 'as', 'f:', 'magic', '=', 'read32(f)', 'num_images', '=', 'read32(f)', 'rows', '=', 'read32(f)', 'cols', '=', 'read32(f)', 'if', 'magic', '!=', '2051:', 'raise', "ValueError('Invalid", 'magic', 'number', '%d', 'in', 'MNIST', 'file...
20,053
Niv-Kor/Target-Score-Detector
HitsManager.py
Hit.increase_rep
increase_rep
Increase the hit's reputation.
[ "Increase", "the", "hit's", "reputation." ]
def increase_rep(self): self.reputation += 1
['def', 'increase_rep(self):', 'self.reputation', '+=', '1']
907,350
facebookresearch/CompilerGym
environment.py
EnvironmentWrapperConfig.wrapper_class
wrapper_class
Return the wrapper class type.
[ "Return", "the", "wrapper", "class", "type." ]
def wrapper_class(self): return self._to_class(self.wrapper)
['def', 'wrapper_class(self):', 'return', 'self._to_class(self.wrapper)']
125,758
ivanmontero/autobot
test_modeling_xxx.py
XxxModelTest.test_lm_outputs_same_as_reference_model
test_lm_outputs_same_as_reference_model
Write something that could help someone fixing this here.
[ "Write", "something", "that", "could", "help", "someone", "fixing", "this", "here." ]
def test_lm_outputs_same_as_reference_model(self): checkpoint_path = 'XXX/bart-large' model = self.big_model tokenizer = AutoTokenizer.from_pretrained(checkpoint_path) batch = tokenizer(['I went to the <mask> yesterday']).to(torch_device) desired_mask_result = tokenizer.decode('store') logits = ...
['def', 'test_lm_outputs_same_as_reference_model(self):', 'checkpoint_path', '=', "'XXX/bart-large'", 'model', '=', 'self.big_model', 'tokenizer', '=', 'AutoTokenizer.from_pretrained(checkpoint_path)', 'batch', '=', "tokenizer(['I", 'went', 'to', 'the', '<mask>', "yesterday']).to(torch_device)", 'desired_mask_result', ...
418,585
openai/gym
core.py
Wrapper.step
step
Steps through the environment with action.
[ "Steps", "through", "the", "environment", "with", "action." ]
def step(self, action: ActType) -> Tuple[ObsType, float, bool, bool, dict]: return self.env.step(action)
['def', 'step(self,', 'action:', 'ActType)', '->', 'Tuple[ObsType,', 'float,', 'bool,', 'bool,', 'dict]:', 'return', 'self.env.step(action)']
234,115
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
sample_generation_tools.py
apply_psd
apply_psd
Take a signal in the time domain, and a precalculated Power Spectral Density, and color the signal according to the given PSD.
[ "Take", "a", "signal", "in", "the", "time", "domain,", "and", "a", "precalculated", "Power", "Spectral", "Density,", "and", "color", "the", "signal", "according", "to", "the", "given", "PSD." ]
def apply_psd(signal_t, psd, sampling_rate=4096, apply_butter=True): signal_size = len(signal_t) delta_t = 1 / sampling_rate frequencies = np.fft.rfftfreq(signal_size, delta_t) signal_f = np.fft.rfft(signal_t) color_signal_f = signal_f / np.sqrt(psd(frequencies) / delta_t / 2) color_signal_t = n...
['def', 'apply_psd(signal_t,', 'psd,', 'sampling_rate=4096,', 'apply_butter=True):', 'signal_size', '=', 'len(signal_t)', 'delta_t', '=', '1', '/', 'sampling_rate', 'frequencies', '=', 'np.fft.rfftfreq(signal_size,', 'delta_t)', 'signal_f', '=', 'np.fft.rfft(signal_t)', 'color_signal_f', '=', 'signal_f', '/', 'np.sqrt(...
18,487
gunthercox/ChatterBot
text.py
prefix_encode_all
prefix_encode_all
Compresses the given list of (unicode) strings by storing each string (except the first one) as an integer (encoded in a byte) representing the prefix it shares with its predecessor, followed by the suffix encoded as UTF-8.
[ "Compresses", "the", "given", "list", "of", "(unicode)", "strings", "by", "storing", "each", "string", "(except", "the", "first", "one)", "as", "an", "integer", "(encoded", "in", "a", "byte)", "representing", "the", "prefix", "it", "shares", "with", "its", "...
def prefix_encode_all(ls): last = u('') for w in ls: i = first_diff(last, w) yield (chr(i) + w[i:].encode('utf-8')) last = w
['def', 'prefix_encode_all(ls):', 'last', '=', "u('')", 'for', 'w', 'in', 'ls:', 'i', '=', 'first_diff(last,', 'w)', 'yield', '(chr(i)', '+', "w[i:].encode('utf-8'))", 'last', '=', 'w']
527,071
facebookresearch/DeeperCluster
eval_pretrain.py
train_network
train_network
Train the models on the dataset.
[ "Train", "the", "models", "on", "the", "dataset." ]
def train_network(args, model, optimizer, dataset): model.train() sampler = torch.utils.data.distributed.DistributedSampler(dataset) loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=args.workers, pin_memory=True) batch_time = AverageMeter() data_...
['def', 'train_network(args,', 'model,', 'optimizer,', 'dataset):', 'model.train()', 'sampler', '=', 'torch.utils.data.distributed.DistributedSampler(dataset)', 'loader', '=', 'torch.utils.data.DataLoader(dataset,', 'sampler=sampler,', 'batch_size=args.batch_size,', 'num_workers=args.workers,', 'pin_memory=True)', 'bat...
128,435
takuseno/d3rlpy
writers.py
ExperienceWriter.write
write
Writes state tuple to buffer.
[ "Writes", "state", "tuple", "to", "buffer." ]
def write(self, observation: Observation, action: Union[int, np.ndarray], reward: Union[float, np.ndarray]) -> None: self._active_episode.append(observation, action, reward) if self._active_episode.transition_count > 0: self._buffer.append(episode=self._active_episode, index=self._active_episode.transit...
['def', 'write(self,', 'observation:', 'Observation,', 'action:', 'Union[int,', 'np.ndarray],', 'reward:', 'Union[float,', 'np.ndarray])', '->', 'None:', 'self._active_episode.append(observation,', 'action,', 'reward)', 'if', 'self._active_episode.transition_count', '>', '0:', 'self._buffer.append(episode=self._active_...
197,967
jbwang1997/CrossKD
pisa_roi_head.py
PISARoIHead.loss
loss
Perform forward propagation and loss calculation of the detection roi on the features of the upstream network.
[ "Perform", "forward", "propagation", "and", "loss", "calculation", "of", "the", "detection", "roi", "on", "the", "features", "of", "the", "upstream", "network." ]
def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_data_samples: List[DetDataSample]) -> dict: assert len(rpn_results_list) == len(batch_data_samples) outputs = unpack_gt_instances(batch_data_samples) (batch_gt_instances, batch_gt_instances_ignore, _) = outputs num_imgs = len(batch_d...
['def', 'loss(self,', 'x:', 'Tuple[Tensor],', 'rpn_results_list:', 'InstanceList,', 'batch_data_samples:', 'List[DetDataSample])', '->', 'dict:', 'assert', 'len(rpn_results_list)', '==', 'len(batch_data_samples)', 'outputs', '=', 'unpack_gt_instances(batch_data_samples)', '(batch_gt_instances,', 'batch_gt_instances_ign...
491,399
PyRetri/PyRetri
helper.py
EvaluateHelper.show_results
show_results
Show the evaluate results.
[ "Show", "the", "evaluate", "results." ]
def show_results(self, mAP: float, recall_at_k: Dict) -> None: repr_str = 'mAP: {:.1f}\n'.format(mAP) for k in self.recall_k: repr_str += 'R@{}: {:.1f}\t'.format(k, recall_at_k[k]) print('--------------- Retrieval Evaluation ------------') print(repr_str)
['def', 'show_results(self,', 'mAP:', 'float,', 'recall_at_k:', 'Dict)', '->', 'None:', 'repr_str', '=', "'mAP:", "{:.1f}\\n'.format(mAP)", 'for', 'k', 'in', 'self.recall_k:', 'repr_str', '+=', "'R@{}:", "{:.1f}\\t'.format(k,", 'recall_at_k[k])', "print('---------------", 'Retrieval', 'Evaluation', "------------')", 'p...
297,188
Eric3911/OpenAGI
duplex_decoder.py
DuplexDecoderModel.training_step
training_step
Lightning calls this inside the training loop with the data from the training dataloader passed in as `batch`.
[ "Lightning", "calls", "this", "inside", "the", "training", "loop", "with", "the", "data", "from", "the", "training", "dataloader", "passed", "in", "as", "`batch`." ]
def training_step(self, batch, batch_idx): if batch['input_ids'].ndim == 3: batch = {k: v.squeeze(dim=0) for (k, v) in batch.items()} train_loss = self.forward(input_ids=batch['input_ids'], decoder_input_ids=batch['decoder_input_ids'], attention_mask=batch['attention_mask'], labels=batch['labels']) ...
['def', 'training_step(self,', 'batch,', 'batch_idx):', 'if', "batch['input_ids'].ndim", '==', '3:', 'batch', '=', '{k:', 'v.squeeze(dim=0)', 'for', '(k,', 'v)', 'in', 'batch.items()}', 'train_loss', '=', "self.forward(input_ids=batch['input_ids'],", "decoder_input_ids=batch['decoder_input_ids'],", "attention_mask=batc...
273,491
Ruturaj123/Flowchart-Detection
layout_optimizer_test.py
bias
bias
bias generates a bias of a given shape.
[ "bias", "generates", "a", "bias", "of", "a", "given", "shape." ]
def bias(shape): return constant_op.constant(0.1, shape=shape)
['def', 'bias(shape):', 'return', 'constant_op.constant(0.1,', 'shape=shape)']
605,567
matsu0228/nlp-jp
connection.py
MWSConnection.get_inbound_service_status
get_inbound_service_status
Returns the operational status of the Fulfillment Inbound Shipment API section.
[ "Returns", "the", "operational", "status", "of", "the", "Fulfillment", "Inbound", "Shipment", "API", "section." ]
def get_inbound_service_status(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'get_inbound_service_status(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,952
Erfanafshar/Principles-and-Applications-of---graph-coloring
image.py
NonUniformImage.set_interpolation
set_interpolation
Parameters ---------- s : str, None Either 'nearest', 'bilinear', or ``None``.
[ "Parameters", "----------", "s", ":", "str,", "None", "Either", "'nearest',", "'bilinear',", "or", "``None``." ]
def set_interpolation(self, s): if s is not None and s not in ('nearest', 'bilinear'): raise NotImplementedError('Only nearest neighbor and bilinear interpolations are supported') AxesImage.set_interpolation(self, s)
['def', 'set_interpolation(self,', 's):', 'if', 's', 'is', 'not', 'None', 'and', 's', 'not', 'in', "('nearest',", "'bilinear'):", 'raise', "NotImplementedError('Only", 'nearest', 'neighbor', 'and', 'bilinear', 'interpolations', 'are', "supported')", 'AxesImage.set_interpolation(self,', 's)']
306,797
wvangansbeke/Revisiting-Contrastive-SSL
functional.py
adjust_contrast
adjust_contrast
Adjust contrast of an image.
[ "Adjust", "contrast", "of", "an", "image." ]
def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: if not isinstance(img, torch.Tensor): return F_pil.adjust_contrast(img, contrast_factor) return F_t.adjust_contrast(img, contrast_factor)
['def', 'adjust_contrast(img:', 'Tensor,', 'contrast_factor:', 'float)', '->', 'Tensor:', 'if', 'not', 'isinstance(img,', 'torch.Tensor):', 'return', 'F_pil.adjust_contrast(img,', 'contrast_factor)', 'return', 'F_t.adjust_contrast(img,', 'contrast_factor)']
348,686
TrellixVulnTeam/Unsupervised_Learning_HFI7
axis.py
Axis.get_majorticklocs
get_majorticklocs
Get the array of major tick locations in data coordinates.
[ "Get", "the", "array", "of", "major", "tick", "locations", "in", "data", "coordinates." ]
def get_majorticklocs(self): return self.major.locator()
['def', 'get_majorticklocs(self):', 'return', 'self.major.locator()']
450,045
dvlab-research/FocalsConv
misc.py
is_str
is_str
Whether the input is an string instance.
[ "Whether", "the", "input", "is", "an", "string", "instance." ]
def is_str(x): return isinstance(x, six.string_types)
['def', 'is_str(x):', 'return', 'isinstance(x,', 'six.string_types)']
608,193
pipermerriam/flex
test_produces_validation.py
test_produces_validation_valid_mimetype_from_global_definition
test_produces_validation_valid_mimetype_from_global_definition
Test that a response content_type that is in the global api produces definitions is valid.
[ "Test", "that", "a", "response", "content_type", "that", "is", "in", "the", "global", "api", "produces", "definitions", "is", "valid." ]
def test_produces_validation_valid_mimetype_from_global_definition(): response = ResponseFactory(content_type='application/json', url='http://www.example.com/get') schema = SchemaFactory(produces=['application/json'], paths={'/get': {'get': {'responses': {'200': {'description': 'Success'}}}}}) validate_resp...
['def', 'test_produces_validation_valid_mimetype_from_global_definition():', 'response', '=', "ResponseFactory(content_type='application/json',", "url='http://www.example.com/get')", 'schema', '=', "SchemaFactory(produces=['application/json'],", "paths={'/get':", "{'get':", "{'responses':", "{'200':", "{'description':"...
211,373
RyanWangZf/PyTrial
ft_transformer.py
FeatureTokenizer.d_token
d_token
The size of one token.
[ "The", "size", "of", "one", "token." ]
def d_token(self) -> int: return self.cat_tokenizer.d_token if self.num_tokenizer is None else self.num_tokenizer.d_token
['def', 'd_token(self)', '->', 'int:', 'return', 'self.cat_tokenizer.d_token', 'if', 'self.num_tokenizer', 'is', 'None', 'else', 'self.num_tokenizer.d_token']
302,359
astooke/rlpyt
epsilon_greedy.py
EpsilonGreedyAgentMixin.eval_mode
eval_mode
Extend method to set epsilon for evaluation, using 1 for pre-training eval.
[ "Extend", "method", "to", "set", "epsilon", "for", "evaluation,", "using", "1", "for", "pre-training", "eval." ]
def eval_mode(self, itr): super().eval_mode(itr) logger.log(f'Agent at itr {itr}, eval eps {(self.eps_eval if itr > 0 else 1.0)}') self.distribution.set_epsilon(self.eps_eval if itr > 0 else 1.0)
['def', 'eval_mode(self,', 'itr):', 'super().eval_mode(itr)', "logger.log(f'Agent", 'at', 'itr', '{itr},', 'eval', 'eps', '{(self.eps_eval', 'if', 'itr', '>', '0', 'else', "1.0)}')", 'self.distribution.set_epsilon(self.eps_eval', 'if', 'itr', '>', '0', 'else', '1.0)']
334,461