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
omarmhaimdat/twitter_nlp_native_swift
sandbox.py
SandboxedEnvironment.call
call
Call an object from sandboxed code.
[ "Call", "an", "object", "from", "sandboxed", "code." ]
def call(__self, __context, __obj, *args, **kwargs): fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs, __obj) if not __self.is_safe_callable(__obj): raise SecurityError('%r is not safely callable' % (__obj,)) return __context.call(__obj...
['def', 'call(__self,', '__context,', '__obj,', '*args,', '**kwargs):', 'fmt', '=', 'inspect_format_method(__obj)', 'if', 'fmt', 'is', 'not', 'None:', 'return', '__self.format_string(fmt,', 'args,', 'kwargs,', '__obj)', 'if', 'not', '__self.is_safe_callable(__obj):', 'raise', "SecurityError('%r", 'is', 'not', 'safely',...
954,029
atulkum/object_detection
trainer_test.py
FakeDetectionModel.predict
predict
Prediction tensors from inputs tensor.
[ "Prediction", "tensors", "from", "inputs", "tensor." ]
def predict(self, preprocessed_inputs): flattened_inputs = tf.contrib.layers.flatten(preprocessed_inputs) class_prediction = tf.contrib.layers.fully_connected(flattened_inputs, self._num_classes) box_prediction = tf.contrib.layers.fully_connected(flattened_inputs, 4) return {'class_predictions_with_back...
['def', 'predict(self,', 'preprocessed_inputs):', 'flattened_inputs', '=', 'tf.contrib.layers.flatten(preprocessed_inputs)', 'class_prediction', '=', 'tf.contrib.layers.fully_connected(flattened_inputs,', 'self._num_classes)', 'box_prediction', '=', 'tf.contrib.layers.fully_connected(flattened_inputs,', '4)', 'return',...
745,262
aws/sagemaker-python-sdk
types.py
JumpStartECRSpecs.to_json
to_json
Returns json representation of JumpStartECRSpecs object.
[ "Returns", "json", "representation", "of", "JumpStartECRSpecs", "object." ]
def to_json(self) -> Dict[str, Any]: json_obj = {att: getattr(self, att) for att in self.__slots__ if hasattr(self, att)} return json_obj
['def', 'to_json(self)', '->', 'Dict[str,', 'Any]:', 'json_obj', '=', '{att:', 'getattr(self,', 'att)', 'for', 'att', 'in', 'self.__slots__', 'if', 'hasattr(self,', 'att)}', 'return', 'json_obj']
830,183
Ruturaj123/Flowchart-Detection
ops.py
EagerTensor.as_cpu_tensor
as_cpu_tensor
A copy of this Tensor with contents backed by host memory.
[ "A", "copy", "of", "this", "Tensor", "with", "contents", "backed", "by", "host", "memory." ]
def as_cpu_tensor(self): return self._copy(context.context(), 'CPU:0')
['def', 'as_cpu_tensor(self):', 'return', 'self._copy(context.context(),', "'CPU:0')"]
605,424
sandialabs/bcnn
train.py
schedule
schedule
Defines exponentially decaying learning rate.
[ "Defines", "exponentially", "decaying", "learning", "rate." ]
def schedule(epoch, initial_learning_rate, lr_decay_start_epoch): if epoch < lr_decay_start_epoch: return initial_learning_rate else: return initial_learning_rate * math.exp(10 * initial_learning_rate * (lr_decay_start_epoch - epoch))
['def', 'schedule(epoch,', 'initial_learning_rate,', 'lr_decay_start_epoch):', 'if', 'epoch', '<', 'lr_decay_start_epoch:', 'return', 'initial_learning_rate', 'else:', 'return', 'initial_learning_rate', '*', 'math.exp(10', '*', 'initial_learning_rate', '*', '(lr_decay_start_epoch', '-', 'epoch))']
105,975
zomux/deepy
layer.py
NeuralLayer.register_external_inputs
register_external_inputs
Register external input variables.
[ "Register", "external", "input", "variables." ]
def register_external_inputs(self, *variables): self.external_inputs.extend(variables)
['def', 'register_external_inputs(self,', '*variables):', 'self.external_inputs.extend(variables)']
180,962
43Carrig/recurrent_neural_networks_practice
l2hmc.py
Dynamics.apply_transition
apply_transition
Propose a new state and perform the accept or reject step.
[ "Propose", "a", "new", "state", "and", "perform", "the", "accept", "or", "reject", "step." ]
def apply_transition(self, position): (position_f, momentum_f, accept_prob_f) = self.transition_kernel(position, forward=True) (position_b, momentum_b, accept_prob_b) = self.transition_kernel(position, forward=False) batch_size = tf.shape(position)[0] forward_mask = tf.cast(tf.random_uniform((batch_size...
['def', 'apply_transition(self,', 'position):', '(position_f,', 'momentum_f,', 'accept_prob_f)', '=', 'self.transition_kernel(position,', 'forward=True)', '(position_b,', 'momentum_b,', 'accept_prob_b)', '=', 'self.transition_kernel(position,', 'forward=False)', 'batch_size', '=', 'tf.shape(position)[0]', 'forward_mask...
312,975
weimin17/Object-Detection_HelmetDetection
utils.py
eqzip
eqzip
Zip but raises error if lengths don't match.
[ "Zip", "but", "raises", "error", "if", "lengths", "don't", "match." ]
def eqzip(*args): sizes = [len(x) for x in args] if not all([sizes[0] == x for x in sizes]): raise ValueError('Lists are of different sizes. \n %s' % str(sizes)) return zip(*args)
['def', 'eqzip(*args):', 'sizes', '=', '[len(x)', 'for', 'x', 'in', 'args]', 'if', 'not', 'all([sizes[0]', '==', 'x', 'for', 'x', 'in', 'sizes]):', 'raise', "ValueError('Lists", 'are', 'of', 'different', 'sizes.', '\\n', "%s'", '%', 'str(sizes))', 'return', 'zip(*args)']
750,440
blakechen97/SASA
augmentor_utils.py
corner_to_standup_nd_jit
corner_to_standup_nd_jit
Convert boxes_corner to aligned (min-max) boxes.
[ "Convert", "boxes_corner", "to", "aligned", "(min-max)", "boxes." ]
def corner_to_standup_nd_jit(boxes_corner): num_boxes = boxes_corner.shape[0] ndim = boxes_corner.shape[-1] result = np.zeros((num_boxes, ndim * 2), dtype=boxes_corner.dtype) for i in range(num_boxes): for j in range(ndim): result[i, j] = np.min(boxes_corner[i, :, j]) for j i...
['def', 'corner_to_standup_nd_jit(boxes_corner):', 'num_boxes', '=', 'boxes_corner.shape[0]', 'ndim', '=', 'boxes_corner.shape[-1]', 'result', '=', 'np.zeros((num_boxes,', 'ndim', '*', '2),', 'dtype=boxes_corner.dtype)', 'for', 'i', 'in', 'range(num_boxes):', 'for', 'j', 'in', 'range(ndim):', 'result[i,', 'j]', '=', 'n...
845,564
LucasAlegre/sumo-rl
env.py
SumoEnvironment.action_spaces
action_spaces
Return the action space of a traffic signal.
[ "Return", "the", "action", "space", "of", "a", "traffic", "signal." ]
def action_spaces(self, ts_id: str) -> gym.spaces.Discrete: return self.traffic_signals[ts_id].action_space
['def', 'action_spaces(self,', 'ts_id:', 'str)', '->', 'gym.spaces.Discrete:', 'return', 'self.traffic_signals[ts_id].action_space']
910,449
google-research/tensor2robot
ensemble_exported_savedmodel_predictor.py
EnsembleExportedSavedModelPredictor.predict
predict
Featurize once, then pass through predictor ensemble.
[ "Featurize", "once,", "then", "pass", "through", "predictor", "ensemble." ]
def predict(self, features): self.assert_is_loaded() flattened_feature_spec = tensorspec_utils.flatten_spec_structure(self.get_feature_specification()) def _maybe_expand_dim(path, val): model_spec = flattened_feature_spec.get(path) if model_spec and model_spec.shape.as_list() == list(val.sh...
['def', 'predict(self,', 'features):', 'self.assert_is_loaded()', 'flattened_feature_spec', '=', 'tensorspec_utils.flatten_spec_structure(self.get_feature_specification())', 'def', '_maybe_expand_dim(path,', 'val):', 'model_spec', '=', 'flattened_feature_spec.get(path)', 'if', 'model_spec', 'and', 'model_spec.shape.as_...
908,279
Kvatsx/Artificial-Intelligence-Assignments
named_commands.py
backward_delete_char
backward_delete_char
Delete the character behind the cursor.
[ "Delete", "the", "character", "behind", "the", "cursor." ]
def backward_delete_char(event): if event.arg < 0: deleted = event.current_buffer.delete(count=-event.arg) else: deleted = event.current_buffer.delete_before_cursor(count=event.arg) if not deleted: event.app.output.bell()
['def', 'backward_delete_char(event):', 'if', 'event.arg', '<', '0:', 'deleted', '=', 'event.current_buffer.delete(count=-event.arg)', 'else:', 'deleted', '=', 'event.current_buffer.delete_before_cursor(count=event.arg)', 'if', 'not', 'deleted:', 'event.app.output.bell()']
75,913
rudranil723/mini-main
_base.py
_AxesBase.get_frame_on
get_frame_on
Get whether the Axes rectangle patch is drawn.
[ "Get", "whether", "the", "Axes", "rectangle", "patch", "is", "drawn." ]
def get_frame_on(self): return self._frameon
['def', 'get_frame_on(self):', 'return', 'self._frameon']
319,969
tensorly/quantum
op_serializer_test.py
get_val
get_val
Get value of op.
[ "Get", "value", "of", "op." ]
def get_val(op): return op.gate.get_val()
['def', 'get_val(op):', 'return', 'op.gate.get_val()']
834,907
OPEN-AIR-SUN/Viewpoint-Bottleneck
pc_utils.py
Camera.camera2world
camera2world
Transform from camera coordinates (3D) to world coordinates (3D).
[ "Transform", "from", "camera", "coordinates", "(3D)", "to", "world", "coordinates", "(3D)." ]
def camera2world(self, extrinsics, points_3d): return self._transform_points(points_3d, extrinsics, self._camera2world_transform)
['def', 'camera2world(self,', 'extrinsics,', 'points_3d):', 'return', 'self._transform_points(points_3d,', 'extrinsics,', 'self._camera2world_transform)']
380,085
segmind/cral
semantic_segmentation_pipeline.py
SemanticSegPipe.lock_data
lock_data
Parse Data and makes tf-records and creates meta-data.
[ "Parse", "Data", "and", "makes", "tf-records", "and", "creates", "meta-data." ]
def lock_data(self): meta_info = create_tfrecords_semantic_segmentation(self.data_dict, self.dataset_csv_path) self.update_project_file(meta_info)
['def', 'lock_data(self):', 'meta_info', '=', 'create_tfrecords_semantic_segmentation(self.data_dict,', 'self.dataset_csv_path)', 'self.update_project_file(meta_info)']
490,655
loicmarie/hands-detection
model_voxel_generation.py
Im2Vox.preprocess
preprocess
Selects the subset of viewpoints to train on.
[ "Selects", "the", "subset", "of", "viewpoints", "to", "train", "on." ]
def preprocess(self, raw_inputs, step_size): (quantity, num_views) = raw_inputs['images'].get_shape().as_list()[:2] inputs = dict() inputs['voxels'] = raw_inputs['voxels'] for k in xrange(step_size): inputs['images_%d' % (k + 1)] = [] inputs['matrix_%d' % (k + 1)] = [] for n in xrang...
['def', 'preprocess(self,', 'raw_inputs,', 'step_size):', '(quantity,', 'num_views)', '=', "raw_inputs['images'].get_shape().as_list()[:2]", 'inputs', '=', 'dict()', "inputs['voxels']", '=', "raw_inputs['voxels']", 'for', 'k', 'in', 'xrange(step_size):', "inputs['images_%d'", '%', '(k', '+', '1)]', '=', '[]', "inputs['...
575,152
ChenhongyiYang/PGD
cornernet.py
CornerNet.merge_aug_results
merge_aug_results
Merge augmented detection bboxes and score.
[ "Merge", "augmented", "detection", "bboxes", "and", "score." ]
def merge_aug_results(self, aug_results, img_metas): (recovered_bboxes, aug_labels) = ([], []) for (bboxes_labels, img_info) in zip(aug_results, img_metas): img_shape = img_info[0]['img_shape'] scale_factor = img_info[0]['scale_factor'] flip = img_info[0]['flip'] (bboxes, labels)...
['def', 'merge_aug_results(self,', 'aug_results,', 'img_metas):', '(recovered_bboxes,', 'aug_labels)', '=', '([],', '[])', 'for', '(bboxes_labels,', 'img_info)', 'in', 'zip(aug_results,', 'img_metas):', 'img_shape', '=', "img_info[0]['img_shape']", 'scale_factor', '=', "img_info[0]['scale_factor']", 'flip', '=', "img_i...
768,141
TongzheZhang/Reinforcement_Learning_for_trading
get_data.py
plot_selected
plot_selected
Plot the desired columns over index values in the given range.
[ "Plot", "the", "desired", "columns", "over", "index", "values", "in", "the", "given", "range." ]
def plot_selected(df, columns, start_index, end_index): df = df.ix[start_index:end_index, columns] plot_data(df)
['def', 'plot_selected(df,', 'columns,', 'start_index,', 'end_index):', 'df', '=', 'df.ix[start_index:end_index,', 'columns]', 'plot_data(df)']
833,966
prashantp86/Artificial-Intelligence
utils.py
count
count
Count the number of items in sequence that are interpreted as true.
[ "Count", "the", "number", "of", "items", "in", "sequence", "that", "are", "interpreted", "as", "true." ]
def count(seq): return sum(map(bool, seq))
['def', 'count(seq):', 'return', 'sum(map(bool,', 'seq))']
121,500
TengXiaoDai/DistributedCrawling
operator.py
iadd
iadd
Same as a += b.
[ "Same", "as", "a", "+=", "b." ]
def iadd(a, b): a += b return a
['def', 'iadd(a,', 'b):', 'a', '+=', 'b', 'return', 'a']
187,912
jwyang/fpn.pytorch
resnet.py
resnet101
resnet101
Constructs a ResNet-101 model.
[ "Constructs", "a", "ResNet-101", "model." ]
def resnet101(pretrained=False): model = ResNet(Bottleneck, [3, 4, 23, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
['def', 'resnet101(pretrained=False):', 'model', '=', 'ResNet(Bottleneck,', '[3,', '4,', '23,', '3])', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))", 'return', 'model']
564,276
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_core.py
test_combining_enclosing
test_combining_enclosing
CYRILLIC CAPITAL LETTER A + COMBINING CYRILLIC HUNDRED THOUSANDS SIGN is А҈ of length 1.
[ "CYRILLIC", "CAPITAL", "LETTER", "A", "+", "COMBINING", "CYRILLIC", "HUNDRED", "THOUSANDS", "SIGN", "is", "А҈", "of", "length", "1." ]
def test_combining_enclosing(): phrase = u'А҈' expect_length_each = (1, 0) expect_length_phrase = 1 length_each = tuple(map(wcwidth.wcwidth, phrase)) length_phrase = wcwidth.wcswidth(phrase, len(phrase)) assert length_each == expect_length_each assert length_phrase == expect_length_phrase
['def', 'test_combining_enclosing():', 'phrase', '=', "u'А҈'", 'expect_length_each', '=', '(1,', '0)', 'expect_length_phrase', '=', '1', 'length_each', '=', 'tuple(map(wcwidth.wcwidth,', 'phrase))', 'length_phrase', '=', 'wcwidth.wcswidth(phrase,', 'len(phrase))', 'assert', 'length_each', '==', 'expect_length_each', 'a...
437,983
weimin17/Object-Detection_HelmetDetection
svtcn_loss.py
masked_minimum
masked_minimum
Computes the axis wise minimum over chosen elements.
[ "Computes", "the", "axis", "wise", "minimum", "over", "chosen", "elements." ]
def masked_minimum(data, mask, dim=1): axis_maximums = tf.reduce_max(data, dim, keep_dims=True) masked_minimums = tf.reduce_min(tf.multiply(data - axis_maximums, mask), dim, keep_dims=True) + axis_maximums return masked_minimums
['def', 'masked_minimum(data,', 'mask,', 'dim=1):', 'axis_maximums', '=', 'tf.reduce_max(data,', 'dim,', 'keep_dims=True)', 'masked_minimums', '=', 'tf.reduce_min(tf.multiply(data', '-', 'axis_maximums,', 'mask),', 'dim,', 'keep_dims=True)', '+', 'axis_maximums', 'return', 'masked_minimums']
760,706
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
vq_discrete.py
DiscreteBottleneck.nearest_neighbor
nearest_neighbor
Find the nearest element in means to elements in x.
[ "Find", "the", "nearest", "element", "in", "means", "to", "elements", "in", "x." ]
def nearest_neighbor(self, x, means): x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True) means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True) scalar_prod = tf.matmul(tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1])) scalar_prod = tf.transpose(scalar_...
['def', 'nearest_neighbor(self,', 'x,', 'means):', 'x_norm_sq', '=', 'tf.reduce_sum(tf.square(x),', 'axis=-1,', 'keep_dims=True)', 'means_norm_sq', '=', 'tf.reduce_sum(tf.square(means),', 'axis=-1,', 'keep_dims=True)', 'scalar_prod', '=', 'tf.matmul(tf.transpose(x,', 'perm=[1,', '0,', '2]),', 'tf.transpose(means,', 'pe...
965,440
jialeli1/lidarseg3d
preprocess.py
global_translate_
global_translate_
Apply global translation to gt_boxes and points.
[ "Apply", "global", "translation", "to", "gt_boxes", "and", "points." ]
def global_translate_(gt_boxes, points, noise_translate_std): if not isinstance(noise_translate_std, (list, tuple, np.ndarray)): noise_translate_std = np.array([noise_translate_std, noise_translate_std, noise_translate_std]) if all([e == 0 for e in noise_translate_std]): return (gt_boxes, points...
['def', 'global_translate_(gt_boxes,', 'points,', 'noise_translate_std):', 'if', 'not', 'isinstance(noise_translate_std,', '(list,', 'tuple,', 'np.ndarray)):', 'noise_translate_std', '=', 'np.array([noise_translate_std,', 'noise_translate_std,', 'noise_translate_std])', 'if', 'all([e', '==', '0', 'for', 'e', 'in', 'noi...
601,417
p-venkatesh/NaturalLanguageProcessing
create_pretraining_data.py
create_training_instances
create_training_instances
Create `TrainingInstance`s from raw text.
[ "Create", "`TrainingInstance`s", "from", "raw", "text." ]
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): all_documents = [[]] for input_file in input_files: with tf.gfile.GFile(input_file, 'r') as reader: while True: line = tokenizatio...
['def', 'create_training_instances(input_files,', 'tokenizer,', 'max_seq_length,', 'dupe_factor,', 'short_seq_prob,', 'masked_lm_prob,', 'max_predictions_per_seq,', 'rng):', 'all_documents', '=', '[[]]', 'for', 'input_file', 'in', 'input_files:', 'with', 'tf.gfile.GFile(input_file,', "'r')", 'as', 'reader:', 'while', '...
710,197
ArdaGunay99/Key_Detection_Unsupervised_Learning
__init__.py
RevOptions.make_new
make_new
Make a copy of the current instance, but with a new rev.
[ "Make", "a", "copy", "of", "the", "current", "instance,", "but", "with", "a", "new", "rev." ]
def make_new(self, rev): return self.vcs.make_rev_options(rev, extra_args=self.extra_args)
['def', 'make_new(self,', 'rev):', 'return', 'self.vcs.make_rev_options(rev,', 'extra_args=self.extra_args)']
259,061
lebrice/Sequoia
policy_head_test.py
test_loss_is_nonzero_at_episode_end_iterate
test_loss_is_nonzero_at_episode_end_iterate
Test that when *iterating* through the env (active-dataloader style), when the episode ends, a non-zero loss is returned by the output head.
[ "Test", "that", "when", "*iterating*", "through", "the", "env", "(active-dataloader", "style),", "when", "the", "episode", "ends,", "a", "non-zero", "loss", "is", "returned", "by", "the", "output", "head." ]
def test_loss_is_nonzero_at_episode_end_iterate(batch_size: int): with gym.make('CartPole-v0') as temp_env: temp_env = AddDoneToObservation(temp_env) obs_space = temp_env.observation_space action_space = temp_env.action_space reward_space = getattr(temp_env, 'reward_space', spaces.Bo...
['def', 'test_loss_is_nonzero_at_episode_end_iterate(batch_size:', 'int):', 'with', "gym.make('CartPole-v0')", 'as', 'temp_env:', 'temp_env', '=', 'AddDoneToObservation(temp_env)', 'obs_space', '=', 'temp_env.observation_space', 'action_space', '=', 'temp_env.action_space', 'reward_space', '=', 'getattr(temp_env,', "'r...
344,376
danamyu/hedgehog_detector
webcam.py
capture_webcam
capture_webcam
Captures images from simultaneous webcams, writes them to queues.
[ "Captures", "images", "from", "simultaneous", "webcams,", "writes", "them", "to", "queues." ]
def capture_webcam(camera, display_queue, reconcile_queue): for i in range(60): tf.logging.info('Taking ramp image %d.' % i) get_image(camera) cnt = 0 start = time.time() while True: im = get_image(camera) display_queue.append(im) reconcile_queue.append(im) ...
['def', 'capture_webcam(camera,', 'display_queue,', 'reconcile_queue):', 'for', 'i', 'in', 'range(60):', "tf.logging.info('Taking", 'ramp', 'image', "%d.'", '%', 'i)', 'get_image(camera)', 'cnt', '=', '0', 'start', '=', 'time.time()', 'while', 'True:', 'im', '=', 'get_image(camera)', 'display_queue.append(im)', 'reconc...
590,795
asyml/texar-pytorch
embedders_test.py
EmbedderTest.test_embedder_multi_calls
test_embedder_multi_calls
Tests embedders called by multiple times.
[ "Tests", "embedders", "called", "by", "multiple", "times." ]
def test_embedder_multi_calls(self): hparams = {'dim': 26, 'dropout_rate': 0.3, 'dropout_strategy': 'item'} embedder = WordEmbedder(vocab_size=100, hparams=hparams) inputs = torch.randint(embedder.vocab_size, (64, 16), dtype=torch.long) outputs = embedder(inputs) if isinstance(embedder.dim, (list, t...
['def', 'test_embedder_multi_calls(self):', 'hparams', '=', "{'dim':", '26,', "'dropout_rate':", '0.3,', "'dropout_strategy':", "'item'}", 'embedder', '=', 'WordEmbedder(vocab_size=100,', 'hparams=hparams)', 'inputs', '=', 'torch.randint(embedder.vocab_size,', '(64,', '16),', 'dtype=torch.long)', 'outputs', '=', 'embed...
924,930
arshpreetsingh/quantopian-machinelearning
screen.py
screen.erase_line
erase_line
Erases the entire current line.
[ "Erases", "the", "entire", "current", "line." ]
def erase_line(self): self.fill_region(self.cur_r, 1, self.cur_r, self.cols)
['def', 'erase_line(self):', 'self.fill_region(self.cur_r,', '1,', 'self.cur_r,', 'self.cols)']
890,997
caiiiac/Machine-Learning-with-Python
__init__.py
get_projection_names
get_projection_names
Get a list of acceptable projection names.
[ "Get", "a", "list", "of", "acceptable", "projection", "names." ]
def get_projection_names(): return projection_registry.get_projection_names()
['def', 'get_projection_names():', 'return', 'projection_registry.get_projection_names()']
716,551
rudranil723/mini-main
ttFont.py
TTFont.ensureDecompiled
ensureDecompiled
Decompile all the tables, even if a TTFont was opened in 'lazy' mode.
[ "Decompile", "all", "the", "tables,", "even", "if", "a", "TTFont", "was", "opened", "in", "'lazy'", "mode." ]
def ensureDecompiled(self, recurse=None): for tag in self.keys(): table = self[tag] if recurse is None: recurse = self.lazy is not False if recurse and hasattr(table, 'ensureDecompiled'): table.ensureDecompiled(recurse=recurse) self.lazy = False
['def', 'ensureDecompiled(self,', 'recurse=None):', 'for', 'tag', 'in', 'self.keys():', 'table', '=', 'self[tag]', 'if', 'recurse', 'is', 'None:', 'recurse', '=', 'self.lazy', 'is', 'not', 'False', 'if', 'recurse', 'and', 'hasattr(table,', "'ensureDecompiled'):", 'table.ensureDecompiled(recurse=recurse)', 'self.lazy', ...
317,406
whatdhack/computer_vision
config_util.py
check_and_parse_input_config_key
check_and_parse_input_config_key
Checks key and returns specific fields if key is valid input config update.
[ "Checks", "key", "and", "returns", "specific", "fields", "if", "key", "is", "valid", "input", "config", "update." ]
def check_and_parse_input_config_key(configs, key): key_name = None input_name = None field_name = None fields = key.split(':') if len(fields) == 1: field_name = key return _check_and_convert_legacy_input_config_key(key) elif len(fields) == 3: key_name = fields[0] ...
['def', 'check_and_parse_input_config_key(configs,', 'key):', 'key_name', '=', 'None', 'input_name', '=', 'None', 'field_name', '=', 'None', 'fields', '=', "key.split(':')", 'if', 'len(fields)', '==', '1:', 'field_name', '=', 'key', 'return', '_check_and_convert_legacy_input_config_key(key)', 'elif', 'len(fields)', '==...
512,136
rudranil723/mini-main
test_util.py
SetAllExtensions
SetAllExtensions
Sets every extension in the message to a unique value.
[ "Sets", "every", "extension", "in", "the", "message", "to", "a", "unique", "value." ]
def SetAllExtensions(message): extensions = message.Extensions pb2 = unittest_pb2 import_pb2 = unittest_import_pb2 extensions[pb2.optional_int32_extension] = 101 extensions[pb2.optional_int64_extension] = 102 extensions[pb2.optional_uint32_extension] = 103 extensions[pb2.optional_uint64_exte...
['def', 'SetAllExtensions(message):', 'extensions', '=', 'message.Extensions', 'pb2', '=', 'unittest_pb2', 'import_pb2', '=', 'unittest_import_pb2', 'extensions[pb2.optional_int32_extension]', '=', '101', 'extensions[pb2.optional_int64_extension]', '=', '102', 'extensions[pb2.optional_uint32_extension]', '=', '103', 'e...
318,435
cuiziteng/ICCV_MAET
anchor_generator.py
YOLOAnchorGenerator.gen_single_level_base_anchors
gen_single_level_base_anchors
Generate base anchors of a single level.
[ "Generate", "base", "anchors", "of", "a", "single", "level." ]
def gen_single_level_base_anchors(self, base_sizes_per_level, center=None): (x_center, y_center) = center base_anchors = [] for base_size in base_sizes_per_level: (w, h) = base_size base_anchor = torch.Tensor([x_center - 0.5 * w, y_center - 0.5 * h, x_center + 0.5 * w, y_center + 0.5 * h]) ...
['def', 'gen_single_level_base_anchors(self,', 'base_sizes_per_level,', 'center=None):', '(x_center,', 'y_center)', '=', 'center', 'base_anchors', '=', '[]', 'for', 'base_size', 'in', 'base_sizes_per_level:', '(w,', 'h)', '=', 'base_size', 'base_anchor', '=', 'torch.Tensor([x_center', '-', '0.5', '*', 'w,', 'y_center',...
228,347
devashish-patel/webcam-motion-detector
core.py
_MaskedPrintOption.enable
enable
Set the enabling shrink to `shrink`.
[ "Set", "the", "enabling", "shrink", "to", "`shrink`." ]
def enable(self, shrink=1): self._enabled = shrink
['def', 'enable(self,', 'shrink=1):', 'self._enabled', '=', 'shrink']
981,342
rahulrao011/Generative-Adversarial-Networks-GANs-
segmentation.py
post_process_mask
post_process_mask
Helper function for automatic mask (produced by the segmentation model) cleaning using heuristics.
[ "Helper", "function", "for", "automatic", "mask", "(produced", "by", "the", "segmentation", "model)", "cleaning", "using", "heuristics." ]
def post_process_mask(mask): kernel = np.ones((13, 13), np.uint8) opened_mask = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel) (num_labels, labels, stats, _) = cv.connectedComponentsWithStats(opened_mask) if num_labels > 1: (h, _) = labels.shape discriminant_subspace = labels[:int(h / 10),...
['def', 'post_process_mask(mask):', 'kernel', '=', 'np.ones((13,', '13),', 'np.uint8)', 'opened_mask', '=', 'cv.morphologyEx(mask,', 'cv.MORPH_OPEN,', 'kernel)', '(num_labels,', 'labels,', 'stats,', '_)', '=', 'cv.connectedComponentsWithStats(opened_mask)', 'if', 'num_labels', '>', '1:', '(h,', '_)', '=', 'labels.shape...
568,026
RasaHQ/rasa
nlu_training_data_provider.py
NLUTrainingDataProvider.create
create
Creates a new NLU training data provider.
[ "Creates", "a", "new", "NLU", "training", "data", "provider." ]
def create(cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> NLUTrainingDataProvider: return cls(config, model_storage, resource)
['def', 'create(cls,', 'config:', 'Dict[Text,', 'Any],', 'model_storage:', 'ModelStorage,', 'resource:', 'Resource,', 'execution_context:', 'ExecutionContext)', '->', 'NLUTrainingDataProvider:', 'return', 'cls(config,', 'model_storage,', 'resource)']
837,075
loicmarie/hands-detection
nav_env.py
GridWorld.valid_fn_vec
valid_fn_vec
Returns if the given set of nodes is valid or not.
[ "Returns", "if", "the", "given", "set", "of", "nodes", "is", "valid", "or", "not." ]
def valid_fn_vec(self, pqr): xyt = self.to_actual_xyt_vec(np.array(pqr)) height = self.traversible.shape[0] width = self.traversible.shape[1] x = np.round(xyt[:, [0]]).astype(np.int32) y = np.round(xyt[:, [1]]).astype(np.int32) is_inside = np.all(np.concatenate((x >= 0, y >= 0, x < width, y < he...
['def', 'valid_fn_vec(self,', 'pqr):', 'xyt', '=', 'self.to_actual_xyt_vec(np.array(pqr))', 'height', '=', 'self.traversible.shape[0]', 'width', '=', 'self.traversible.shape[1]', 'x', '=', 'np.round(xyt[:,', '[0]]).astype(np.int32)', 'y', '=', 'np.round(xyt[:,', '[1]]).astype(np.int32)', 'is_inside', '=', 'np.all(np.co...
574,470
arshpreetsingh/quantopian-machinelearning
prompt.py
confirm
confirm
Display a confirmation prompt that returns True/False.
[ "Display", "a", "confirmation", "prompt", "that", "returns", "True/False." ]
def confirm(message='Confirm?', suffix=' (y/n) '): session = create_confirm_session(message, suffix) return session.prompt()
['def', "confirm(message='Confirm?',", "suffix='", '(y/n)', "'):", 'session', '=', 'create_confirm_session(message,', 'suffix)', 'return', 'session.prompt()']
892,550
zackmcnulty/CSE_446-Machine_Learning
connectionpool.py
HTTPConnectionPool.close
close
Close all pooled connections and disable the pool.
[ "Close", "all", "pooled", "connections", "and", "disable", "the", "pool." ]
def close(self): if self.pool is None: return (old_pool, self.pool) = (self.pool, None) try: while True: conn = old_pool.get(block=False) if conn: conn.close() except queue.Empty: pass
['def', 'close(self):', 'if', 'self.pool', 'is', 'None:', 'return', '(old_pool,', 'self.pool)', '=', '(self.pool,', 'None)', 'try:', 'while', 'True:', 'conn', '=', 'old_pool.get(block=False)', 'if', 'conn:', 'conn.close()', 'except', 'queue.Empty:', 'pass']
196,855
AbhinandanVellanki/Pacman-Artificial-
pacman.py
GameState.getLegalActions
getLegalActions
Returns the legal actions for the agent specified.
[ "Returns", "the", "legal", "actions", "for", "the", "agent", "specified." ]
def getLegalActions(self, agentIndex=0): if self.isWin() or self.isLose(): return [] if agentIndex == 0: return PacmanRules.getLegalActions(self) else: return GhostRules.getLegalActions(self, agentIndex)
['def', 'getLegalActions(self,', 'agentIndex=0):', 'if', 'self.isWin()', 'or', 'self.isLose():', 'return', '[]', 'if', 'agentIndex', '==', '0:', 'return', 'PacmanRules.getLegalActions(self)', 'else:', 'return', 'GhostRules.getLegalActions(self,', 'agentIndex)']
254,241
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
translate.py
create_model
create_model
Create translation model and initialize or load parameters in session.
[ "Create", "translation", "model", "and", "initialize", "or", "load", "parameters", "in", "session." ]
def create_model(session, forward_only): dtype = tf.float16 if FLAGS.use_fp16 else tf.float32 model = seq2seq_model.Seq2SeqModel(FLAGS.from_vocab_size, FLAGS.to_vocab_size, _buckets, FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size, FLAGS.learning_rate, FLAGS.learning_rate_decay_factor, f...
['def', 'create_model(session,', 'forward_only):', 'dtype', '=', 'tf.float16', 'if', 'FLAGS.use_fp16', 'else', 'tf.float32', 'model', '=', 'seq2seq_model.Seq2SeqModel(FLAGS.from_vocab_size,', 'FLAGS.to_vocab_size,', '_buckets,', 'FLAGS.size,', 'FLAGS.num_layers,', 'FLAGS.max_gradient_norm,', 'FLAGS.batch_size,', 'FLAGS...
30,576
tencent-ailab/TriNet
file_io.py
PathManager.opena
opena
Return file descriptor with asynchronous write operations.
[ "Return", "file", "descriptor", "with", "asynchronous", "write", "operations." ]
def opena(path: str, mode: str='r', buffering: int=-1, encoding: Optional[str]=None, errors: Optional[str]=None, newline: Optional[str]=None): global IOPathManager if not IOPathManager: logging.info('ioPath is initializing PathManager.') try: from iopath.common.file_io import PathMan...
['def', 'opena(path:', 'str,', 'mode:', "str='r',", 'buffering:', 'int=-1,', 'encoding:', 'Optional[str]=None,', 'errors:', 'Optional[str]=None,', 'newline:', 'Optional[str]=None):', 'global', 'IOPathManager', 'if', 'not', 'IOPathManager:', "logging.info('ioPath", 'is', 'initializing', "PathManager.')", 'try:', 'from',...
424,989
cagbal/ros_people_object_detection_tensorflow
box_list.py
BoxList.transpose_coordinates
transpose_coordinates
Transpose the coordinate representation in a boxlist.
[ "Transpose", "the", "coordinate", "representation", "in", "a", "boxlist." ]
def transpose_coordinates(self, scope=None): with tf.name_scope(scope, 'transpose_coordinates'): (y_min, x_min, y_max, x_max) = tf.split(value=self.get(), num_or_size_splits=4, axis=1) self.set(tf.concat([x_min, y_min, x_max, y_max], 1))
['def', 'transpose_coordinates(self,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'transpose_coordinates'):", '(y_min,', 'x_min,', 'y_max,', 'x_max)', '=', 'tf.split(value=self.get(),', 'num_or_size_splits=4,', 'axis=1)', 'self.set(tf.concat([x_min,', 'y_min,', 'x_max,', 'y_max],', '1))']
827,408
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
model.py
StackedAttentionLSTM.forward
forward
Propogate input through the layer.
[ "Propogate", "input", "through", "the", "layer." ]
def forward(self, input, hidden, ctx, ctx_mask=None): (h_0, c_0) = hidden (h_1, c_1) = ([], []) for (i, layer) in enumerate(self.layers): if ctx_mask is not None: ctx_mask = torch.ByteTensor(ctx_mask.data.cpu().numpy().astype(np.int32).tolist()).cuda() (output, (h_1_i, c_1_i)) = ...
['def', 'forward(self,', 'input,', 'hidden,', 'ctx,', 'ctx_mask=None):', '(h_0,', 'c_0)', '=', 'hidden', '(h_1,', 'c_1)', '=', '([],', '[])', 'for', '(i,', 'layer)', 'in', 'enumerate(self.layers):', 'if', 'ctx_mask', 'is', 'not', 'None:', 'ctx_mask', '=', 'torch.ByteTensor(ctx_mask.data.cpu().numpy().astype(np.int32).t...
15,027
thfylsty/imagefusion_Perceptual_FusionGan
utils.py
make_data
make_data
Make input data as h5 file format Depending on 'is_train' (flag value), savepath would be changed.
[ "Make", "input", "data", "as", "h5", "file", "format", "Depending", "on", "'is_train'", "(flag", "value),", "savepath", "would", "be", "changed." ]
def make_data(sess, data, label, data_dir): if FLAGS.is_train: savepath = os.path.join('.', os.path.join('checkpoint_20', data_dir, 'train.h5')) if not os.path.exists(os.path.join('.', os.path.join('checkpoint_20', data_dir))): os.makedirs(os.path.join('.', os.path.join('checkpoint_20', ...
['def', 'make_data(sess,', 'data,', 'label,', 'data_dir):', 'if', 'FLAGS.is_train:', 'savepath', '=', "os.path.join('.',", "os.path.join('checkpoint_20',", 'data_dir,', "'train.h5'))", 'if', 'not', "os.path.exists(os.path.join('.',", "os.path.join('checkpoint_20',", 'data_dir))):', "os.makedirs(os.path.join('.',", "os....
599,439
PratikRamdasi/Computer-Vision
keras_yolo.py
yolo
yolo
Generate a complete YOLO_v2 localization model.
[ "Generate", "a", "complete", "YOLO_v2", "localization", "model." ]
def yolo(inputs, anchors, num_classes): num_anchors = len(anchors) body = yolo_body(inputs, num_anchors, num_classes) outputs = yolo_head(body.output, anchors, num_classes) return outputs
['def', 'yolo(inputs,', 'anchors,', 'num_classes):', 'num_anchors', '=', 'len(anchors)', 'body', '=', 'yolo_body(inputs,', 'num_anchors,', 'num_classes)', 'outputs', '=', 'yolo_head(body.output,', 'anchors,', 'num_classes)', 'return', 'outputs']
469,681
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
scopes.py
has_arg_scope
has_arg_scope
Checks whether a func has been decorated with @add_arg_scope or not.
[ "Checks", "whether", "a", "func", "has", "been", "decorated", "with", "@add_arg_scope", "or", "not." ]
def has_arg_scope(func): key_op = (func.__module__, func.__name__) return key_op in _DECORATED_OPS
['def', 'has_arg_scope(func):', 'key_op', '=', '(func.__module__,', 'func.__name__)', 'return', 'key_op', 'in', '_DECORATED_OPS']
55,366
mahossam/OptiGAN
states.py
FighterState.roll
roll
Return the current roll angle phi.
[ "Return", "the", "current", "roll", "angle", "phi." ]
def roll(self): return self.phi
['def', 'roll(self):', 'return', 'self.phi']
776,289
xuwei95/transfer-learning
test_inc.py
test_tf_image_classification_quantization
test_tf_image_classification_quantization
Given a valid directory for the output dir, test the quantization function with the actual Intel Neural Compressor call mocked out.
[ "Given", "a", "valid", "directory", "for", "the", "output", "dir,", "test", "the", "quantization", "function", "with", "the", "actual", "Intel", "Neural", "Compressor", "call", "mocked", "out." ]
def test_tf_image_classification_quantization(): try: output_dir = tempfile.mkdtemp() model = model_factory.get_model('efficientnet_b0', 'tensorflow') with patch('tlt.models.image_classification.tf_image_classification_model.TFCustomImageClassificationDataset') as mock_dataset: w...
['def', 'test_tf_image_classification_quantization():', 'try:', 'output_dir', '=', 'tempfile.mkdtemp()', 'model', '=', "model_factory.get_model('efficientnet_b0',", "'tensorflow')", 'with', "patch('tlt.models.image_classification.tf_image_classification_model.TFCustomImageClassificationDataset')", 'as', 'mock_dataset:'...
927,034
intel/neural-compressor
quantize_wrapper.py
QuantizeWrapperBase.query_input_index
query_input_index
Query QuantizeConfig to check if there is any designated input index for this layer.
[ "Query", "QuantizeConfig", "to", "check", "if", "there", "is", "any", "designated", "input", "index", "for", "this", "layer." ]
def query_input_index(self): quantize_config = global_config['quantize_config'] custom_layer_config = quantize_config.query_layer(self.layer) if custom_layer_config and 'index' in custom_layer_config: self.index = custom_layer_config['index']
['def', 'query_input_index(self):', 'quantize_config', '=', "global_config['quantize_config']", 'custom_layer_config', '=', 'quantize_config.query_layer(self.layer)', 'if', 'custom_layer_config', 'and', "'index'", 'in', 'custom_layer_config:', 'self.index', '=', "custom_layer_config['index']"]
737,798
michiyasunaga/BIFI
fairseq_model.py
FairseqLanguageModel.max_positions
max_positions
Maximum length supported by the model.
[ "Maximum", "length", "supported", "by", "the", "model." ]
def max_positions(self): return self.decoder.max_positions()
['def', 'max_positions(self):', 'return', 'self.decoder.max_positions()']
107,440
lisovskey/filmach
dump.py
load_alphabet
load_alphabet
Unserialize `chars_indices` and `indices_chars`.
[ "Unserialize", "`chars_indices`", "and", "`indices_chars`." ]
def load_alphabet(directory, filename): with open(path.join(directory, filename), 'rb') as file: (chars_indices, indices_chars) = pickle.load(file) return (chars_indices, indices_chars)
['def', 'load_alphabet(directory,', 'filename):', 'with', 'open(path.join(directory,', 'filename),', "'rb')", 'as', 'file:', '(chars_indices,', 'indices_chars)', '=', 'pickle.load(file)', 'return', '(chars_indices,', 'indices_chars)']
210,342
googleapis/python-aiplatform
grpc_asyncio.py
IndexEndpointServiceGrpcAsyncIOTransport.list_operations
list_operations
Return a callable for the list_operations method over gRPC.
[ "Return", "a", "callable", "for", "the", "list_operations", "method", "over", "gRPC." ]
def list_operations(self) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: if 'list_operations' not in self._stubs: self._stubs['list_operations'] = self.grpc_channel.unary_unary('/google.longrunning.Operations/ListOperations', request_serializer=operations_pb2.Lis...
['def', 'list_operations(self)', '->', 'Callable[[operations_pb2.ListOperationsRequest],', 'operations_pb2.ListOperationsResponse]:', 'if', "'list_operations'", 'not', 'in', 'self._stubs:', "self._stubs['list_operations']", '=', "self.grpc_channel.unary_unary('/google.longrunning.Operations/ListOperations',", 'request_...
810,788
zzndream/ShipRSImageNet
custom.py
CustomDataset.get_cat_ids
get_cat_ids
Get category ids by index.
[ "Get", "category", "ids", "by", "index." ]
def get_cat_ids(self, idx): return self.data_infos[idx]['ann']['labels'].astype(np.int).tolist()
['def', 'get_cat_ids(self,', 'idx):', 'return', "self.data_infos[idx]['ann']['labels'].astype(np.int).tolist()"]
901,239
sktime/sktime
test_pipeline.py
test_mul_sklearn_autoadapt
test_mul_sklearn_autoadapt
Test auto-adapter for sklearn in mul.
[ "Test", "auto-adapter", "for", "sklearn", "in", "mul." ]
def test_mul_sklearn_autoadapt(): RAND_SEED = 42 X = _make_panel_X(n_instances=10, n_timepoints=12, random_state=RAND_SEED) X_test = X t1 = ExponentTransformer(power=2) t2 = StandardScaler() c = TimeSeriesDBSCAN(FlatDist.create_test_instance(), eps=4, min_samples=1) t12c_1 = t1 * (t2 * c) ...
['def', 'test_mul_sklearn_autoadapt():', 'RAND_SEED', '=', '42', 'X', '=', '_make_panel_X(n_instances=10,', 'n_timepoints=12,', 'random_state=RAND_SEED)', 'X_test', '=', 'X', 't1', '=', 'ExponentTransformer(power=2)', 't2', '=', 'StandardScaler()', 'c', '=', 'TimeSeriesDBSCAN(FlatDist.create_test_instance(),', 'eps=4,'...
886,072
JuliaSzymanska/Artificial-Intelligence
utils.py
argmin_random_tie
argmin_random_tie
Return a minimum element of seq; break ties at random.
[ "Return", "a", "minimum", "element", "of", "seq;", "break", "ties", "at", "random." ]
def argmin_random_tie(seq, key=identity): return min(shuffled(seq), key=key)
['def', 'argmin_random_tie(seq,', 'key=identity):', 'return', 'min(shuffled(seq),', 'key=key)']
119,745
rhythmcao/slu-dual-learning
Beam.py
Beam.get_current_state
get_current_state
Get the outputs for the current timestep.
[ "Get", "the", "outputs", "for", "the", "current", "timestep." ]
def get_current_state(self): return self.next_ys[-1]
['def', 'get_current_state(self):', 'return', 'self.next_ys[-1]']
352,015
enuguru/artificial_intelligence_and_machine_
version.py
VersionInfo.version_string
version_string
Return the short version minus any alpha/beta tags.
[ "Return", "the", "short", "version", "minus", "any", "alpha/beta", "tags." ]
def version_string(self): return self.semantic_version().brief_string()
['def', 'version_string(self):', 'return', 'self.semantic_version().brief_string()']
159,675
zihuitang/medical_AI_platform
tabbedpages.py
TabbedPageSet.change_page
change_page
Show the page whose name is given in page_name.
[ "Show", "the", "page", "whose", "name", "is", "given", "in", "page_name." ]
def change_page(self, page_name): if self._current_page == page_name: return if page_name is not None and page_name not in self.pages: raise KeyError("No such TabPage: '%s'" % page_name) if self._current_page is not None: self.pages[self._current_page]._hide() self._current_page ...
['def', 'change_page(self,', 'page_name):', 'if', 'self._current_page', '==', 'page_name:', 'return', 'if', 'page_name', 'is', 'not', 'None', 'and', 'page_name', 'not', 'in', 'self.pages:', 'raise', 'KeyError("No', 'such', 'TabPage:', '\'%s\'"', '%', 'page_name)', 'if', 'self._current_page', 'is', 'not', 'None:', 'self...
282,892
NVlabs/VAEBM
datasets.py
get_loaders
get_loaders
Get data loaders for required dataset.
[ "Get", "data", "loaders", "for", "required", "dataset." ]
def get_loaders(args, dataset=None): if dataset is None: dataset = args.dataset return get_loaders_eval(dataset, args)
['def', 'get_loaders(args,', 'dataset=None):', 'if', 'dataset', 'is', 'None:', 'dataset', '=', 'args.dataset', 'return', 'get_loaders_eval(dataset,', 'args)']
930,780
omonimus1/super-computer-
config.py
ConfigMetadataHandler.parsers
parsers
Metadata item name to parser function mapping.
[ "Metadata", "item", "name", "to", "parser", "function", "mapping." ]
def parsers(self): parse_list = self._parse_list parse_file = self._parse_file parse_dict = self._parse_dict exclude_files_parser = self._exclude_files_parser return {'platforms': parse_list, 'keywords': parse_list, 'provides': parse_list, 'requires': self._deprecated_config_handler(parse_list, 'The...
['def', 'parsers(self):', 'parse_list', '=', 'self._parse_list', 'parse_file', '=', 'self._parse_file', 'parse_dict', '=', 'self._parse_dict', 'exclude_files_parser', '=', 'self._exclude_files_parser', 'return', "{'platforms':", 'parse_list,', "'keywords':", 'parse_list,', "'provides':", 'parse_list,', "'requires':", '...
913,451
xiaoiker/GCN-NAS
rotation.py
rotation_matrix
rotation_matrix
Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians.
[ "Return", "the", "rotation", "matrix", "associated", "with", "counterclockwise", "rotation", "about", "the", "given", "axis", "by", "theta", "radians." ]
def rotation_matrix(axis, theta): if np.abs(axis).sum() < 1e-06 or np.abs(theta) < 1e-06: return np.eye(3) axis = np.asarray(axis) axis = axis / math.sqrt(np.dot(axis, axis)) a = math.cos(theta / 2.0) (b, c, d) = -axis * math.sin(theta / 2.0) (aa, bb, cc, dd) = (a * a, b * b, c * c, d * ...
['def', 'rotation_matrix(axis,', 'theta):', 'if', 'np.abs(axis).sum()', '<', '1e-06', 'or', 'np.abs(theta)', '<', '1e-06:', 'return', 'np.eye(3)', 'axis', '=', 'np.asarray(axis)', 'axis', '=', 'axis', '/', 'math.sqrt(np.dot(axis,', 'axis))', 'a', '=', 'math.cos(theta', '/', '2.0)', '(b,', 'c,', 'd)', '=', '-axis', '*',...
201,290
matsu0228/nlp-jp
contour.py
ContourLabeler.print_label
print_label
Return *False* if contours are too short for a label.
[ "Return", "*False*", "if", "contours", "are", "too", "short", "for", "a", "label." ]
def print_label(self, linecontour, labelwidth): return len(linecontour) > 10 * labelwidth or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()
['def', 'print_label(self,', 'linecontour,', 'labelwidth):', 'return', 'len(linecontour)', '>', '10', '*', 'labelwidth', 'or', '(np.ptp(linecontour,', 'axis=0)', '>', '1.2', '*', 'labelwidth).any()']
788,652
RasaHQ/rasa
mitie_tokenizer.py
MitieTokenizer.create
create
Creates a new component (see parent class for full docstring).
[ "Creates", "a", "new", "component", "(see", "parent", "class", "for", "full", "docstring)." ]
def create(cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> MitieTokenizer: return cls(config)
['def', 'create(cls,', 'config:', 'Dict[Text,', 'Any],', 'model_storage:', 'ModelStorage,', 'resource:', 'Resource,', 'execution_context:', 'ExecutionContext)', '->', 'MitieTokenizer:', 'return', 'cls(config)']
837,315
matsu0228/nlp-jp
test_basic.py
TestEllip.test_ellipj_nan
test_ellipj_nan
Regression test for #912.
[ "Regression", "test", "for", "#912." ]
def test_ellipj_nan(self): special.ellipj(0.5, np.nan)
['def', 'test_ellipj_nan(self):', 'special.ellipj(0.5,', 'np.nan)']
805,953
Oneflow-Inc/vision
video_utils.py
VideoClips.get_clip_location
get_clip_location
Converts a flattened representation of the indices into a video_idx, clip_idx representation.
[ "Converts", "a", "flattened", "representation", "of", "the", "indices", "into", "a", "video_idx,", "clip_idx", "representation." ]
def get_clip_location(self, idx: int) -> Tuple[int, int]: video_idx = bisect.bisect_right(self.cumulative_sizes, idx) if video_idx == 0: clip_idx = idx else: clip_idx = idx - self.cumulative_sizes[video_idx - 1] return (video_idx, clip_idx)
['def', 'get_clip_location(self,', 'idx:', 'int)', '->', 'Tuple[int,', 'int]:', 'video_idx', '=', 'bisect.bisect_right(self.cumulative_sizes,', 'idx)', 'if', 'video_idx', '==', '0:', 'clip_idx', '=', 'idx', 'else:', 'clip_idx', '=', 'idx', '-', 'self.cumulative_sizes[video_idx', '-', '1]', 'return', '(video_idx,', 'cli...
958,298
Eric3911/OpenAGI
checkpoint.py
save_parameters
save_parameters
Checkpoint the latest trained model parameters.
[ "Checkpoint", "the", "latest", "trained", "model", "parameters." ]
def save_parameters(checkpoint_dir, iteration, model, optimizer=None): checkpoint_path = os.path.join(checkpoint_dir, 'step-{}'.format(iteration)) model_dict = model.state_dict() params_path = checkpoint_path + '.pdparams' paddle.save(model_dict, params_path) print('[checkpoint] Saved model to {}'.f...
['def', 'save_parameters(checkpoint_dir,', 'iteration,', 'model,', 'optimizer=None):', 'checkpoint_path', '=', 'os.path.join(checkpoint_dir,', "'step-{}'.format(iteration))", 'model_dict', '=', 'model.state_dict()', 'params_path', '=', 'checkpoint_path', '+', "'.pdparams'", 'paddle.save(model_dict,', 'params_path)', "p...
251,868
nilearn/nilearn
utils.py
figure_to_svg_quoted
figure_to_svg_quoted
Save figure as svg and return it as quoted string.
[ "Save", "figure", "as", "svg", "and", "return", "it", "as", "quoted", "string." ]
def figure_to_svg_quoted(fig): return urllib.parse.quote(figure_to_svg_bytes(fig).decode('utf-8'))
['def', 'figure_to_svg_quoted(fig):', 'return', "urllib.parse.quote(figure_to_svg_bytes(fig).decode('utf-8'))"]
724,256
qiujiali/lattice_rnn
train.py
Trainer.xent_onebest
xent_onebest
Compute confidence score binary cross entropy.
[ "Compute", "confidence", "score", "binary", "cross", "entropy." ]
def xent_onebest(self, output, indices, reference): assert len(indices) == len(reference), 'inconsistent one-best sequence.' (loss, count) = (0, 0) (pred_onebest, ref_onebest) = ([], []) if indices: prediction = [output[i] for i in indices] for (pred, ref) in zip(prediction, reference): ...
['def', 'xent_onebest(self,', 'output,', 'indices,', 'reference):', 'assert', 'len(indices)', '==', 'len(reference),', "'inconsistent", 'one-best', "sequence.'", '(loss,', 'count)', '=', '(0,', '0)', '(pred_onebest,', 'ref_onebest)', '=', '([],', '[])', 'if', 'indices:', 'prediction', '=', '[output[i]', 'for', 'i', 'in...
261,983
jianlong-yuan/SimpleBaseline
env.py
seed_all_rng
seed_all_rng
Set the random seed for the RNG in torch, numpy and python.
[ "Set", "the", "random", "seed", "for", "the", "RNG", "in", "torch,", "numpy", "and", "python." ]
def seed_all_rng(seed=None): if seed is None: seed = os.getpid() + int(datetime.now().strftime('%S%f')) + int.from_bytes(os.urandom(2), 'big') logger = logging.getLogger(__name__) logger.info('Using a generated random seed {}'.format(seed)) np.random.seed(seed) torch.set_rng_state(to...
['def', 'seed_all_rng(seed=None):', 'if', 'seed', 'is', 'None:', 'seed', '=', 'os.getpid()', '+', "int(datetime.now().strftime('%S%f'))", '+', 'int.from_bytes(os.urandom(2),', "'big')", 'logger', '=', 'logging.getLogger(__name__)', "logger.info('Using", 'a', 'generated', 'random', 'seed', "{}'.format(seed))", 'np.rando...
883,120
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
telnetlib.py
Telnet.mt_interact
mt_interact
Multithreaded version of interact().
[ "Multithreaded", "version", "of", "interact()." ]
def mt_interact(self): import _thread _thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if not line: break self.write(line.encode('ascii'))
['def', 'mt_interact(self):', 'import', '_thread', '_thread.start_new_thread(self.listener,', '())', 'while', '1:', 'line', '=', 'sys.stdin.readline()', 'if', 'not', 'line:', 'break', "self.write(line.encode('ascii'))"]
429,673
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
stackless.py
getcurrent
getcurrent
getcurrent() -- return the currently executing tasklet.
[ "getcurrent()", "--", "return", "the", "currently", "executing", "tasklet." ]
def getcurrent(): curr = coroutine.getcurrent() if curr is _main_coroutine: return _main_tasklet else: return curr
['def', 'getcurrent():', 'curr', '=', 'coroutine.getcurrent()', 'if', 'curr', 'is', '_main_coroutine:', 'return', '_main_tasklet', 'else:', 'return', 'curr']
377,374
ashwanitanwar/nmt-transfer-learning-xlm-r
learned_positional_embedding.py
LearnedPositionalEmbedding.forward
forward
Input is expected to be of size [bsz x seqlen].
[ "Input", "is", "expected", "to", "be", "of", "size", "[bsz", "x", "seqlen]." ]
def forward(self, input, incremental_state=None, positions=None): assert positions is None or self.padding_idx is None, 'If positions is pre-computed then padding_idx should not be set.' if positions is None: if incremental_state is not None: positions = input.data.new(1, 1).fill_(self.paddi...
['def', 'forward(self,', 'input,', 'incremental_state=None,', 'positions=None):', 'assert', 'positions', 'is', 'None', 'or', 'self.padding_idx', 'is', 'None,', "'If", 'positions', 'is', 'pre-computed', 'then', 'padding_idx', 'should', 'not', 'be', "set.'", 'if', 'positions', 'is', 'None:', 'if', 'incremental_state', 'i...
733,039
ahmedfgad/CIFAR10CNNFlask
CIFAR10_CNN_Test.py
get_dataset_images
get_dataset_images
Similar to the one used in training except that there is just a single testing binary file for testing the CIFAR10 trained models.
[ "Similar", "to", "the", "one", "used", "in", "training", "except", "that", "there", "is", "just", "a", "single", "testing", "binary", "file", "for", "testing", "the", "CIFAR10", "trained", "models." ]
def get_dataset_images(test_path_path, im_dim=32, num_channels=3): print('Working on testing patch') data_dict = unpickle_patch(test_path_path) images_data = data_dict[b'data'] dataset_array = numpy.reshape(images_data, newshape=(len(images_data), im_dim, im_dim, num_channels)) return (dataset_array...
['def', 'get_dataset_images(test_path_path,', 'im_dim=32,', 'num_channels=3):', "print('Working", 'on', 'testing', "patch')", 'data_dict', '=', 'unpickle_patch(test_path_path)', 'images_data', '=', "data_dict[b'data']", 'dataset_array', '=', 'numpy.reshape(images_data,', 'newshape=(len(images_data),', 'im_dim,', 'im_di...
105,239
sktime/sktime
test_all_forecasters.py
TestAllForecasters.test_predict_time_index_with_X
test_predict_time_index_with_X
Check that predicted time index matches forecasting horizon.
[ "Check", "that", "predicted", "time", "index", "matches", "forecasting", "horizon." ]
def test_predict_time_index_with_X(self, estimator_instance, n_columns, index_fh_comb, fh_int_oos): (index_type, fh_type, is_relative) = index_fh_comb if fh_type == 'timedelta': return None (z, X) = make_forecasting_problem(index_type=index_type, make_X=True) y = _make_series(n_columns=n_columns...
['def', 'test_predict_time_index_with_X(self,', 'estimator_instance,', 'n_columns,', 'index_fh_comb,', 'fh_int_oos):', '(index_type,', 'fh_type,', 'is_relative)', '=', 'index_fh_comb', 'if', 'fh_type', '==', "'timedelta':", 'return', 'None', '(z,', 'X)', '=', 'make_forecasting_problem(index_type=index_type,', 'make_X=T...
877,283
rifqind/Agent-Programs-3KS1
web.py
RequestHandler.get_status
get_status
Returns the status code for our response.
[ "Returns", "the", "status", "code", "for", "our", "response." ]
def get_status(self) -> int: return self._status_code
['def', 'get_status(self)', '->', 'int:', 'return', 'self._status_code']
21,427
danielajisafe/Real-Time-Object-detection-API
ops_test.py
MeshgridTest.test_meshgrid_numpy_comparison
test_meshgrid_numpy_comparison
Tests meshgrid op with vectors, for which it should match numpy.
[ "Tests", "meshgrid", "op", "with", "vectors,", "for", "which", "it", "should", "match", "numpy." ]
def test_meshgrid_numpy_comparison(self): x = np.arange(4) y = np.arange(6) (exp_xgrid, exp_ygrid) = np.meshgrid(x, y) (xgrid, ygrid) = ops.meshgrid(x, y) with self.test_session() as sess: (xgrid_output, ygrid_output) = sess.run([xgrid, ygrid]) self.assertAllEqual(xgrid_output, exp_x...
['def', 'test_meshgrid_numpy_comparison(self):', 'x', '=', 'np.arange(4)', 'y', '=', 'np.arange(6)', '(exp_xgrid,', 'exp_ygrid)', '=', 'np.meshgrid(x,', 'y)', '(xgrid,', 'ygrid)', '=', 'ops.meshgrid(x,', 'y)', 'with', 'self.test_session()', 'as', 'sess:', '(xgrid_output,', 'ygrid_output)', '=', 'sess.run([xgrid,', 'ygr...
849,691
asyml/texar-pytorch
vocabulary.py
map_ids_to_strs
map_ids_to_strs
Transforms ``int`` indexes to strings by mapping ids to tokens, concatenating tokens into sentences, and stripping special tokens, etc.
[ "Transforms", "``int``", "indexes", "to", "strings", "by", "mapping", "ids", "to", "tokens,", "concatenating", "tokens", "into", "sentences,", "and", "stripping", "special", "tokens,", "etc." ]
def map_ids_to_strs(ids: Union[np.ndarray, Sequence[int]], vocab: Vocab, join: bool=True, strip_pad: Optional[str]='<PAD>', strip_bos: Optional[str]='<BOS>', strip_eos: Optional[str]='<EOS>') -> Union[np.ndarray, List[str]]: tokens = vocab.map_ids_to_tokens_py(ids) if isinstance(ids, (list, tuple)): tok...
['def', 'map_ids_to_strs(ids:', 'Union[np.ndarray,', 'Sequence[int]],', 'vocab:', 'Vocab,', 'join:', 'bool=True,', 'strip_pad:', "Optional[str]='<PAD>',", 'strip_bos:', "Optional[str]='<BOS>',", 'strip_eos:', "Optional[str]='<EOS>')", '->', 'Union[np.ndarray,', 'List[str]]:', 'tokens', '=', 'vocab.map_ids_to_tokens_py(...
925,017
cedkoffeto/artificial-intelligence
mrecords.py
MaskedRecords.harden_mask
harden_mask
Forces the mask to hard.
[ "Forces", "the", "mask", "to", "hard." ]
def harden_mask(self): self._hardmask = True
['def', 'harden_mask(self):', 'self._hardmask', '=', 'True']
172,318
enuguru/artificial_intelligence_and_machine_learning
fields.py
FieldType.clean
clean
Clears any cached information in the field and any child objects.
[ "Clears", "any", "cached", "information", "in", "the", "field", "and", "any", "child", "objects." ]
def clean(self): if self.format and hasattr(self.format, 'clean'): self.format.clean()
['def', 'clean(self):', 'if', 'self.format', 'and', 'hasattr(self.format,', "'clean'):", 'self.format.clean()']
132,860
jimtin/Stock_Comparison
test_latextools.py
test_latex_to_png_mpl_runs
test_latex_to_png_mpl_runs
Test that latex_to_png_mpl just runs without error.
[ "Test", "that", "latex_to_png_mpl", "just", "runs", "without", "error." ]
def test_latex_to_png_mpl_runs(): def mock_kpsewhich(filename): nt.assert_equals(filename, 'breqn.sty') return None for (s, wrap) in [('$x^2$', False), ('x^2', True)]: yield (latextools.latex_to_png_mpl, s, wrap) with patch.object(latextools, 'kpsewhich', mock_kpsewhich): ...
['def', 'test_latex_to_png_mpl_runs():', 'def', 'mock_kpsewhich(filename):', 'nt.assert_equals(filename,', "'breqn.sty')", 'return', 'None', 'for', '(s,', 'wrap)', 'in', "[('$x^2$',", 'False),', "('x^2',", 'True)]:', 'yield', '(latextools.latex_to_png_mpl,', 's,', 'wrap)', 'with', 'patch.object(latextools,', "'kpsewhic...
385,305
sshleifer/object_detection_kitti
show_and_tell_model.py
ShowAndTellModel.setup_inception_initializer
setup_inception_initializer
Sets up the function to restore inception variables from checkpoint.
[ "Sets", "up", "the", "function", "to", "restore", "inception", "variables", "from", "checkpoint." ]
def setup_inception_initializer(self): if self.mode != 'inference': saver = tf.train.Saver(self.inception_variables) def restore_fn(sess): tf.logging.info('Restoring Inception variables from checkpoint file %s', self.config.inception_checkpoint_file) saver.restore(sess, self...
['def', 'setup_inception_initializer(self):', 'if', 'self.mode', '!=', "'inference':", 'saver', '=', 'tf.train.Saver(self.inception_variables)', 'def', 'restore_fn(sess):', "tf.logging.info('Restoring", 'Inception', 'variables', 'from', 'checkpoint', 'file', "%s',", 'self.config.inception_checkpoint_file)', 'saver.rest...
794,812
saghul/evergreen
_base.py
wait
wait
Wait for the futures in the given sequence to complete.
[ "Wait", "for", "the", "futures", "in", "the", "given", "sequence", "to", "complete." ]
def wait(fs, timeout=None, return_when=ALL_COMPLETED): with _AcquireFutures(fs): done = set((f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])) not_done = set(fs) - done if return_when == FIRST_COMPLETED and done: return (done, not_done) elif return_when ==...
['def', 'wait(fs,', 'timeout=None,', 'return_when=ALL_COMPLETED):', 'with', '_AcquireFutures(fs):', 'done', '=', 'set((f', 'for', 'f', 'in', 'fs', 'if', 'f._state', 'in', '[CANCELLED_AND_NOTIFIED,', 'FINISHED]))', 'not_done', '=', 'set(fs)', '-', 'done', 'if', 'return_when', '==', 'FIRST_COMPLETED', 'and', 'done:', 're...
178,469
enuguru/artificial_intelligence_and_machine_
pytracer.py
PyTracer.get_stats
get_stats
Return a dictionary of statistics, or None.
[ "Return", "a", "dictionary", "of", "statistics,", "or", "None." ]
def get_stats(self): return None
['def', 'get_stats(self):', 'return', 'None']
157,582
gunthercox/ChatterBot
posixpath.py
normpath
normpath
Normalize path, eliminating double slashes, etc.
[ "Normalize", "path,", "eliminating", "double", "slashes,", "etc." ]
def normpath(path): (slash, dot) = (u'/', u'.') if isinstance(path, unicode) else ('/', '.') if path == '': return dot initial_slashes = path.startswith('/') if initial_slashes and path.startswith('//') and (not path.startswith('///')): initial_slashes = 2 comps = path.split('/') ...
['def', 'normpath(path):', '(slash,', 'dot)', '=', "(u'/',", "u'.')", 'if', 'isinstance(path,', 'unicode)', 'else', "('/',", "'.')", 'if', 'path', '==', "'':", 'return', 'dot', 'initial_slashes', '=', "path.startswith('/')", 'if', 'initial_slashes', 'and', "path.startswith('//')", 'and', '(not', "path.startswith('///')...
528,071
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
wmt_utils.py
prepare_wmt_data
prepare_wmt_data
Get WMT data into data_dir, create vocabularies and tokenize data.
[ "Get", "WMT", "data", "into", "data_dir,", "create", "vocabularies", "and", "tokenize", "data." ]
def prepare_wmt_data(data_dir, vocabulary_size, tokenizer=None, normalize_digits=False): train_path = get_wmt_enfr_train_set(data_dir) dev_path = get_wmt_enfr_dev_set(data_dir) vocab_path = os.path.join(data_dir, 'vocab%d.txt' % vocabulary_size) create_vocabulary(vocab_path, train_path, vocabulary_size,...
['def', 'prepare_wmt_data(data_dir,', 'vocabulary_size,', 'tokenizer=None,', 'normalize_digits=False):', 'train_path', '=', 'get_wmt_enfr_train_set(data_dir)', 'dev_path', '=', 'get_wmt_enfr_dev_set(data_dir)', 'vocab_path', '=', 'os.path.join(data_dir,', "'vocab%d.txt'", '%', 'vocabulary_size)', 'create_vocabulary(voc...
56,509
google-research/s4l
datasets.py
get_data
get_data
Produces image/label tensors for a given dataset.
[ "Produces", "image/label", "tensors", "for", "a", "given", "dataset." ]
def get_data(params, split_name, is_training, shuffle=True, num_epochs=None, drop_remainder=False, preprocessing=None): batch_mult = FLAGS.unsup_batch_mult if is_training else 1 filename_list = None data = get_data_batch(int(params['batch_size'] * batch_mult), split_name, is_training, preprocessing, filenam...
['def', 'get_data(params,', 'split_name,', 'is_training,', 'shuffle=True,', 'num_epochs=None,', 'drop_remainder=False,', 'preprocessing=None):', 'batch_mult', '=', 'FLAGS.unsup_batch_mult', 'if', 'is_training', 'else', '1', 'filename_list', '=', 'None', 'data', '=', "get_data_batch(int(params['batch_size']", '*', 'batc...
328,002
lojzezust/WaSR-T
train.py
LitModel.add_argparse_args
add_argparse_args
Adds model specific parameters to parser.
[ "Adds", "model", "specific", "parameters", "to", "parser." ]
def add_argparse_args(parser): parser.add_argument('--learning-rate', type=float, default=LEARNING_RATE, help='Base learning rate for training with polynomial decay.') parser.add_argument('--momentum', type=float, default=MOMENTUM, help='Momentum component of the optimiser.') parser.add_argument('--epochs',...
['def', 'add_argparse_args(parser):', "parser.add_argument('--learning-rate',", 'type=float,', 'default=LEARNING_RATE,', "help='Base", 'learning', 'rate', 'for', 'training', 'with', 'polynomial', "decay.')", "parser.add_argument('--momentum',", 'type=float,', 'default=MOMENTUM,', "help='Momentum", 'component', 'of', 't...
942,330
weimin17/Object-Detection_HelmetDetection
get_dataset_colormap_test.py
VisualizationUtilTest.testUnExpectedLabelValueForLabelToPASCALColorImage
testUnExpectedLabelValueForLabelToPASCALColorImage
Raise ValueError when input value exceeds range.
[ "Raise", "ValueError", "when", "input", "value", "exceeds", "range." ]
def testUnExpectedLabelValueForLabelToPASCALColorImage(self): label = np.array([[120], [300]]) with self.assertRaises(ValueError): get_dataset_colormap.label_to_color_image(label, get_dataset_colormap.get_pascal_name())
['def', 'testUnExpectedLabelValueForLabelToPASCALColorImage(self):', 'label', '=', 'np.array([[120],', '[300]])', 'with', 'self.assertRaises(ValueError):', 'get_dataset_colormap.label_to_color_image(label,', 'get_dataset_colormap.get_pascal_name())']
762,186
ChenhongyiYang/PGD
xml_style.py
XMLDataset.get_cat_ids
get_cat_ids
Get category ids in XML file by index.
[ "Get", "category", "ids", "in", "XML", "file", "by", "index." ]
def get_cat_ids(self, idx): cat_ids = [] img_id = self.data_infos[idx]['id'] xml_path = osp.join(self.img_prefix, 'Annotations', f'{img_id}.xml') tree = ET.parse(xml_path) root = tree.getroot() for obj in root.findall('object'): name = obj.find('name').text if name not in self.CL...
['def', 'get_cat_ids(self,', 'idx):', 'cat_ids', '=', '[]', 'img_id', '=', "self.data_infos[idx]['id']", 'xml_path', '=', 'osp.join(self.img_prefix,', "'Annotations',", "f'{img_id}.xml')", 'tree', '=', 'ET.parse(xml_path)', 'root', '=', 'tree.getroot()', 'for', 'obj', 'in', "root.findall('object'):", 'name', '=', "obj....
767,884
Kvatsx/Artificial-Intelligence-Assignments
afm.py
AFM.get_kern_dist
get_kern_dist
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
[ "Return", "the", "kerning", "pair", "distance", "(possibly", "0)", "for", "chars", "*c1*", "and", "*c2*." ]
def get_kern_dist(self, c1, c2): (name1, name2) = (self.get_name_char(c1), self.get_name_char(c2)) return self.get_kern_dist_from_name(name1, name2)
['def', 'get_kern_dist(self,', 'c1,', 'c2):', '(name1,', 'name2)', '=', '(self.get_name_char(c1),', 'self.get_name_char(c2))', 'return', 'self.get_kern_dist_from_name(name1,', 'name2)']
32
myothida/Supervised-Machine-Learning
pangomarkup.py
escape_special_chars
escape_special_chars
Escape & and < for Pango Markup.
[ "Escape", "&", "and", "<", "for", "Pango", "Markup." ]
def escape_special_chars(text, table=_escape_table): return text.translate(table)
['def', 'escape_special_chars(text,', 'table=_escape_table):', 'return', 'text.translate(table)']
444,767
megvii-research/CR-DA-DET
nms_wrapper.py
nms
nms
Dispatch to either CPU or GPU NMS implementations.
[ "Dispatch", "to", "either", "CPU", "or", "GPU", "NMS", "implementations." ]
def nms(dets, thresh, force_cpu=False): if dets.shape[0] == 0: return [] return nms_gpu(dets, thresh) if force_cpu == False else nms_cpu(dets, thresh)
['def', 'nms(dets,', 'thresh,', 'force_cpu=False):', 'if', 'dets.shape[0]', '==', '0:', 'return', '[]', 'return', 'nms_gpu(dets,', 'thresh)', 'if', 'force_cpu', '==', 'False', 'else', 'nms_cpu(dets,', 'thresh)']
490,429
zackmcnulty/CSE_446-Machine_Learning
__init__.py
show_fcompilers
show_fcompilers
Print list of available compilers (used by the "--help-fcompiler" option to "config_fc").
[ "Print", "list", "of", "available", "compilers", "(used", "by", "the", "\"--help-fcompiler\"", "option", "to", "\"config_fc\")." ]
def show_fcompilers(dist=None): if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] ...
['def', 'show_fcompilers(dist=None):', 'if', 'dist', 'is', 'None:', 'from', 'distutils.dist', 'import', 'Distribution', 'from', 'numpy.distutils.command.config_compiler', 'import', 'config_fc', 'dist', '=', 'Distribution()', 'dist.script_name', '=', 'os.path.basename(sys.argv[0])', 'dist.script_args', '=', "['config_fc...
195,811
atulkum/object_detection
tf_example_decoder.py
TfExampleDecoder.decode
decode
Decodes serialized tensorflow example and returns a tensor dictionary.
[ "Decodes", "serialized", "tensorflow", "example", "and", "returns", "a", "tensor", "dictionary." ]
def decode(self, tf_example_string_tensor): serialized_example = tf.reshape(tf_example_string_tensor, shape=[]) decoder = slim_example_decoder.TFExampleDecoder(self.keys_to_features, self.items_to_handlers) keys = decoder.list_items() tensors = decoder.decode(serialized_example, items=keys) tensor_d...
['def', 'decode(self,', 'tf_example_string_tensor):', 'serialized_example', '=', 'tf.reshape(tf_example_string_tensor,', 'shape=[])', 'decoder', '=', 'slim_example_decoder.TFExampleDecoder(self.keys_to_features,', 'self.items_to_handlers)', 'keys', '=', 'decoder.list_items()', 'tensors', '=', 'decoder.decode(serialized...
791,553
OpenMDAO/OpenMDAO-Framework
flow.py
FlowSolution.shape
shape
Data index limits, not including 'ghost/rind' planes.
[ "Data", "index", "limits,", "not", "including", "'ghost/rind'", "planes." ]
def shape(self): ijk = self.real_shape if len(ijk) < 1: return () ghosts = self._ghosts imax = ijk[0] - (ghosts[0] + ghosts[1]) if len(ijk) < 2: return (imax,) jmax = ijk[1] - (ghosts[2] + ghosts[3]) if len(ijk) < 3: return (imax, jmax) kmax = ijk[2] - (ghosts[4] ...
['def', 'shape(self):', 'ijk', '=', 'self.real_shape', 'if', 'len(ijk)', '<', '1:', 'return', '()', 'ghosts', '=', 'self._ghosts', 'imax', '=', 'ijk[0]', '-', '(ghosts[0]', '+', 'ghosts[1])', 'if', 'len(ijk)', '<', '2:', 'return', '(imax,)', 'jmax', '=', 'ijk[1]', '-', '(ghosts[2]', '+', 'ghosts[3])', 'if', 'len(ijk)',...
275,475