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
tensorflow/agents
system_multiprocessing.py
get_context
get_context
Get a context: an object with the same API as multiprocessing module.
[ "Get", "a", "context:", "an", "object", "with", "the", "same", "API", "as", "multiprocessing", "module." ]
def get_context(method: Text=None) -> _multiprocessing.context.BaseContext: if not multiprocessing_core.initialized(): raise RuntimeError(_NOT_INITIALIZED_ERROR) return _rewrite_target_with_state(multiprocessing_core.get_context(method))
['def', 'get_context(method:', 'Text=None)', '->', '_multiprocessing.context.BaseContext:', 'if', 'not', 'multiprocessing_core.initialized():', 'raise', 'RuntimeError(_NOT_INITIALIZED_ERROR)', 'return', '_rewrite_target_with_state(multiprocessing_core.get_context(method))']
23,713
Megvii-BaseDetection/cvpods
history_buffer.py
HistoryBuffer.avg
avg
Return the mean of the latest `window_size` values in the buffer.
[ "Return", "the", "mean", "of", "the", "latest", "`window_size`", "values", "in", "the", "buffer." ]
def avg(self, window_size: int): return np.mean([x[0] for x in self._data[-window_size:]])
['def', 'avg(self,', 'window_size:', 'int):', 'return', 'np.mean([x[0]', 'for', 'x', 'in', 'self._data[-window_size:]])']
523,187
voxel51/fiftyone
database.py
sync_database
sync_database
Syncs all pending database writes to disk.
[ "Syncs", "all", "pending", "database", "writes", "to", "disk." ]
def sync_database(): if _client is not None: _client.admin.command('fsync')
['def', 'sync_database():', 'if', '_client', 'is', 'not', 'None:', "_client.admin.command('fsync')"]
583,526
ldkong1205/LaserMix
mink_resnet.py
MinkResNet.forward
forward
Forward pass of ResNet.
[ "Forward", "pass", "of", "ResNet." ]
def forward(self, x: SparseTensor) -> List[SparseTensor]: x = self.conv1(x) x = self.norm1(x) x = self.relu(x) if self.pool: x = self.maxpool(x) outs = [] for i in range(self.num_stages): x = getattr(self, f'layer{i + 1}')(x) outs.append(x) return outs
['def', 'forward(self,', 'x:', 'SparseTensor)', '->', 'List[SparseTensor]:', 'x', '=', 'self.conv1(x)', 'x', '=', 'self.norm1(x)', 'x', '=', 'self.relu(x)', 'if', 'self.pool:', 'x', '=', 'self.maxpool(x)', 'outs', '=', '[]', 'for', 'i', 'in', 'range(self.num_stages):', 'x', '=', 'getattr(self,', "f'layer{i", '+', "1}')...
623,925
LiWentomng/OrientedRepPoints
hooks.py
patch_forward_method
patch_forward_method
Patch the forward method of a module.
[ "Patch", "the", "forward", "method", "of", "a", "module." ]
def patch_forward_method(func, src_type, dst_type, convert_output=True): def new_forward(*args, **kwargs): output = func(*cast_tensor_type(args, src_type, dst_type), **cast_tensor_type(kwargs, src_type, dst_type)) if convert_output: output = cast_tensor_type(output, dst_type, src_type) ...
['def', 'patch_forward_method(func,', 'src_type,', 'dst_type,', 'convert_output=True):', 'def', 'new_forward(*args,', '**kwargs):', 'output', '=', 'func(*cast_tensor_type(args,', 'src_type,', 'dst_type),', '**cast_tensor_type(kwargs,', 'src_type,', 'dst_type))', 'if', 'convert_output:', 'output', '=', 'cast_tensor_type...
776,541
JayantGoel001/Artificial-
search.py
OnlineSearchProblem.c
c
Returns a cost estimate for an agent to move from state 's' to state 's1'.
[ "Returns", "a", "cost", "estimate", "for", "an", "agent", "to", "move", "from", "state", "'s'", "to", "state", "'s1'." ]
def c(self, s, a, s1): return 1
['def', 'c(self,', 's,', 'a,', 's1):', 'return', '1']
117,533
triaquae/triaquae
six.py
iterkeys
iterkeys
Return an iterator over the keys of a dictionary.
[ "Return", "an", "iterator", "over", "the", "keys", "of", "a", "dictionary." ]
def iterkeys(d): return iter(getattr(d, _iterkeys)())
['def', 'iterkeys(d):', 'return', 'iter(getattr(d,', '_iterkeys)())']
356,745
rlgraph/rlgraph
component_test.py
ComponentTest.read_variable_values
read_variable_values
Executes a session to retrieve the values of the provided variables.
[ "Executes", "a", "session", "to", "retrieve", "the", "values", "of", "the", "provided", "variables." ]
def read_variable_values(self, *variables): if len(variables) == 0: variables = self.component.variable_registry ret = self.graph_executor.read_variable_values(variables) if len(variables) == 1: return ret[0] return ret
['def', 'read_variable_values(self,', '*variables):', 'if', 'len(variables)', '==', '0:', 'variables', '=', 'self.component.variable_registry', 'ret', '=', 'self.graph_executor.read_variable_values(variables)', 'if', 'len(variables)', '==', '1:', 'return', 'ret[0]', 'return', 'ret']
862,657
heartkilla/yolo-v3
yolo_v3.py
darknet53_residual_block
darknet53_residual_block
Creates a residual block for Darknet.
[ "Creates", "a", "residual", "block", "for", "Darknet." ]
def darknet53_residual_block(inputs, filters, training, data_format, strides=1): shortcut = inputs inputs = conv2d_fixed_padding(inputs, filters=filters, kernel_size=1, strides=strides, data_format=data_format) inputs = batch_norm(inputs, training=training, data_format=data_format) inputs = tf.nn.leaky_...
['def', 'darknet53_residual_block(inputs,', 'filters,', 'training,', 'data_format,', 'strides=1):', 'shortcut', '=', 'inputs', 'inputs', '=', 'conv2d_fixed_padding(inputs,', 'filters=filters,', 'kernel_size=1,', 'strides=strides,', 'data_format=data_format)', 'inputs', '=', 'batch_norm(inputs,', 'training=training,', '...
969,159
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_004b.py
MixedPrecision.on_backward_end
on_backward_end
Convert the gradients back to FP32 and divide them by the scale.
[ "Convert", "the", "gradients", "back", "to", "FP32", "and", "divide", "them", "by", "the", "scale." ]
def on_backward_end(self, **kwargs: Any): model_g2master_g(self.model_params, self.master_params, self.flat_master) for group in self.master_params: for param in group: param.grad.div_(self.loss_scale)
['def', 'on_backward_end(self,', '**kwargs:', 'Any):', 'model_g2master_g(self.model_params,', 'self.master_params,', 'self.flat_master)', 'for', 'group', 'in', 'self.master_params:', 'for', 'param', 'in', 'group:', 'param.grad.div_(self.loss_scale)']
81,237
jimtin/Stock_Comparison
parser.py
Parser.parse_if
parse_if
Parse an if construct.
[ "Parse", "an", "if", "construct." ]
def parse_if(self): node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', 'name:endif')) token = next(self.stream) if token.test('name:elif'): ...
['def', 'parse_if(self):', 'node', '=', 'result', '=', "nodes.If(lineno=self.stream.expect('name:if').lineno)", 'while', '1:', 'node.test', '=', 'self.parse_tuple(with_condexpr=False)', 'node.body', '=', "self.parse_statements(('name:elif',", "'name:else',", "'name:endif'))", 'token', '=', 'next(self.stream)', 'if', "t...
385,878
rishab-sharma/object_detection
c2.py
const_fill
const_fill
Constant fill helper to reduce verbosity.
[ "Constant", "fill", "helper", "to", "reduce", "verbosity." ]
def const_fill(value): return ('ConstantFill', {'value': value})
['def', 'const_fill(value):', 'return', "('ConstantFill',", "{'value':", 'value})']
773,218
scikit-learn/scikit-learn
test_glm.py
test_newton_solver_verbosity
test_newton_solver_verbosity
Test the std output of verbose newton solvers.
[ "Test", "the", "std", "output", "of", "verbose", "newton", "solvers." ]
def test_newton_solver_verbosity(capsys, verbose): y = np.array([1, 2], dtype=float) X = np.array([[1.0, 0], [0, 1]], dtype=float) linear_loss = LinearModelLoss(base_loss=HalfPoissonLoss(), fit_intercept=False) sol = NewtonCholeskySolver(coef=linear_loss.init_zero_coef(X), linear_loss=linear_loss, l2_re...
['def', 'test_newton_solver_verbosity(capsys,', 'verbose):', 'y', '=', 'np.array([1,', '2],', 'dtype=float)', 'X', '=', 'np.array([[1.0,', '0],', '[0,', '1]],', 'dtype=float)', 'linear_loss', '=', 'LinearModelLoss(base_loss=HalfPoissonLoss(),', 'fit_intercept=False)', 'sol', '=', 'NewtonCholeskySolver(coef=linear_loss....
853,637
weimin17/Object-Detection_HelmetDetection
convolutional.py
data_type
data_type
Return the type of the activations, weights, and placeholder variables.
[ "Return", "the", "type", "of", "the", "activations,", "weights,", "and", "placeholder", "variables." ]
def data_type(): if FLAGS.use_fp16: return tf.float16 else: return tf.float32
['def', 'data_type():', 'if', 'FLAGS.use_fp16:', 'return', 'tf.float16', 'else:', 'return', 'tf.float32']
754,222
ShuLiu1993/PANet
training_stats.py
TrainingStats.LogIterStats
LogIterStats
Log the tracked statistics.
[ "Log", "the", "tracked", "statistics." ]
def LogIterStats(self, cur_iter, lr): if cur_iter % self.LOG_PERIOD == 0 or cur_iter == cfg.SOLVER.MAX_ITER - 1: stats = self.GetStats(cur_iter, lr) log_stats(stats, self.misc_args) if self.tblogger: self.tb_log_stats(stats, cur_iter)
['def', 'LogIterStats(self,', 'cur_iter,', 'lr):', 'if', 'cur_iter', '%', 'self.LOG_PERIOD', '==', '0', 'or', 'cur_iter', '==', 'cfg.SOLVER.MAX_ITER', '-', '1:', 'stats', '=', 'self.GetStats(cur_iter,', 'lr)', 'log_stats(stats,', 'self.misc_args)', 'if', 'self.tblogger:', 'self.tb_log_stats(stats,', 'cur_iter)']
778,952
omarmhaimdat/twitter_nlp_native_swift
ipaddress.py
v4_int_to_packed
v4_int_to_packed
Represent an address as 4 packed bytes in network (big-endian) order.
[ "Represent", "an", "address", "as", "4", "packed", "bytes", "in", "network", "(big-endian)", "order." ]
def v4_int_to_packed(address): try: return _compat_to_bytes(address, 4, 'big') except (struct.error, OverflowError): raise ValueError('Address negative or too large for IPv4')
['def', 'v4_int_to_packed(address):', 'try:', 'return', '_compat_to_bytes(address,', '4,', "'big')", 'except', '(struct.error,', 'OverflowError):', 'raise', "ValueError('Address", 'negative', 'or', 'too', 'large', 'for', "IPv4')"]
954,467
rohanpsingh/LearningHumanoidWalking
robot_interface.py
RobotInterface.step
step
Increment simulation by one step.
[ "Increment", "simulation", "by", "one", "step." ]
def step(self): mujoco.mj_step(self.model, self.data)
['def', 'step(self):', 'mujoco.mj_step(self.model,', 'self.data)']
588,277
google/deepvariant
model_train_test.py
ModelTrainTest.test_end2end_inception_v3_warm_up_allow_different_num_channels
test_end2end_inception_v3_warm_up_allow_different_num_channels
End-to-end test of model_train script.
[ "End-to-end", "test", "of", "model_train", "script." ]
def test_end2end_inception_v3_warm_up_allow_different_num_channels(self): FLAGS.allow_warmstart_from_different_num_channels = True checkpoint_dir = tf_test_utils.test_tmpdir('inception_v3_warm_up_allow_different_num_channels') tf_test_utils.write_fake_checkpoint('inception_v3', self.test_session(), checkpoi...
['def', 'test_end2end_inception_v3_warm_up_allow_different_num_channels(self):', 'FLAGS.allow_warmstart_from_different_num_channels', '=', 'True', 'checkpoint_dir', '=', "tf_test_utils.test_tmpdir('inception_v3_warm_up_allow_different_num_channels')", "tf_test_utils.write_fake_checkpoint('inception_v3',", 'self.test_se...
540,380
jaywalnut310/Vector-Quantized-Autoencoders
transformer_vq.py
residual_conv
residual_conv
A stack of convolution blocks with residual connections.
[ "A", "stack", "of", "convolution", "blocks", "with", "residual", "connections." ]
def residual_conv(x, repeat, k, hparams, name, reuse=None): with tf.variable_scope(name, reuse=reuse): dilations_and_kernels = [(1, k) for _ in range(3)] for i in range(repeat): with tf.variable_scope('repeat_%d' % i): y = commons.conv_block(commons.layer_norm(x, name='ln...
['def', 'residual_conv(x,', 'repeat,', 'k,', 'hparams,', 'name,', 'reuse=None):', 'with', 'tf.variable_scope(name,', 'reuse=reuse):', 'dilations_and_kernels', '=', '[(1,', 'k)', 'for', '_', 'in', 'range(3)]', 'for', 'i', 'in', 'range(repeat):', 'with', "tf.variable_scope('repeat_%d'", '%', 'i):', 'y', '=', 'commons.con...
931,053
okfn-brasil/serenata-de-amor
fetch_receipts.py
Receipts.all
all
List generator with Receipt objects containing the path of the receipt image (to be used when saving it, for example) and the URL of the receipt at the Lower House servers.
[ "List", "generator", "with", "Receipt", "objects", "containing", "the", "path", "of", "the", "receipt", "image", "(to", "be", "used", "when", "saving", "it,", "for", "example)", "and", "the", "URL", "of", "the", "receipt", "at", "the", "Lower", "House", "s...
def all(self): dtype = {'document_id': np.str, 'congressperson_id': np.str, 'congressperson_document': np.str, 'term_id': np.str, 'cnpj_cpf': np.str, 'reimbursement_number': np.str} for dataset in self.datasets: df = pd.read_csv(dataset, parse_dates=[16], dtype=dtype) rows = filter(self.is_valid...
['def', 'all(self):', 'dtype', '=', "{'document_id':", 'np.str,', "'congressperson_id':", 'np.str,', "'congressperson_document':", 'np.str,', "'term_id':", 'np.str,', "'cnpj_cpf':", 'np.str,', "'reimbursement_number':", 'np.str}', 'for', 'dataset', 'in', 'self.datasets:', 'df', '=', 'pd.read_csv(dataset,', 'parse_dates...
349,801
Akash671/AI
inference.py
JointParticleFilter.initialize
initialize
Store information about the game, then initialize particles.
[ "Store", "information", "about", "the", "game,", "then", "initialize", "particles." ]
def initialize(self, gameState, legalPositions): self.numGhosts = gameState.getNumAgents() - 1 self.ghostAgents = [] self.legalPositions = legalPositions self.initializeUniformly(gameState)
['def', 'initialize(self,', 'gameState,', 'legalPositions):', 'self.numGhosts', '=', 'gameState.getNumAgents()', '-', '1', 'self.ghostAgents', '=', '[]', 'self.legalPositions', '=', 'legalPositions', 'self.initializeUniformly(gameState)']
67,403
weimin17/Object-Detection_HelmetDetection
graph_rewriter_builder.py
build
build
Returns a function that modifies default graph based on options.
[ "Returns", "a", "function", "that", "modifies", "default", "graph", "based", "on", "options." ]
def build(graph_rewriter_config, is_training): def graph_rewrite_fn(): if graph_rewriter_config.quantization.weight_bits != 8 or graph_rewriter_config.quantization.activation_bits != 8: raise ValueError('Only 8bit quantization is supported') if is_training: tf.contrib.quanti...
['def', 'build(graph_rewriter_config,', 'is_training):', 'def', 'graph_rewrite_fn():', 'if', 'graph_rewriter_config.quantization.weight_bits', '!=', '8', 'or', 'graph_rewriter_config.quantization.activation_bits', '!=', '8:', 'raise', "ValueError('Only", '8bit', 'quantization', 'is', "supported')", 'if', 'is_training:'...
758,503
sktime/sktime
base.py
BaseDistribution.shape
shape
Shape of self, a pair (2-tuple).
[ "Shape", "of", "self,", "a", "pair", "(2-tuple)." ]
def shape(self): return (len(self.index), len(self.columns))
['def', 'shape(self):', 'return', '(len(self.index),', 'len(self.columns))']
877,455
suarez12138/AI-Reversi_IMP_TextDichotomy
backend_tools.py
ToolViewsPositions.forward
forward
Forward one step in the stack of views and positions.
[ "Forward", "one", "step", "in", "the", "stack", "of", "views", "and", "positions." ]
def forward(self): self.views[self.figure].forward() self.positions[self.figure].forward()
['def', 'forward(self):', 'self.views[self.figure].forward()', 'self.positions[self.figure].forward()']
96,290
ryu-ed/SpaceInvaders_Ros
system_info.py
combine_paths
combine_paths
Return a list of existing paths composed by all combinations of items from arguments.
[ "Return", "a", "list", "of", "existing", "paths", "composed", "by", "all", "combinations", "of", "items", "from", "arguments." ]
def combine_paths(*args, **kws): r = [] for a in args: if not a: continue if is_string(a): a = [a] r.append(a) args = r if not args: return [] if len(args) == 1: result = reduce(lambda a, b: a + b, map(glob, args[0]), []) elif len(a...
['def', 'combine_paths(*args,', '**kws):', 'r', '=', '[]', 'for', 'a', 'in', 'args:', 'if', 'not', 'a:', 'continue', 'if', 'is_string(a):', 'a', '=', '[a]', 'r.append(a)', 'args', '=', 'r', 'if', 'not', 'args:', 'return', '[]', 'if', 'len(args)', '==', '1:', 'result', '=', 'reduce(lambda', 'a,', 'b:', 'a', '+', 'b,', '...
396,507
mkusner/grammarVAE
test_blocksparse.py
BlockSparse_Gemv_and_Outer.test_sparseblockdot
test_sparseblockdot
Compares the numpy version of sparseblockgemv to sparse_block_dot.
[ "Compares", "the", "numpy", "version", "of", "sparseblockgemv", "to", "sparse_block_dot." ]
def test_sparseblockdot(self): b = tensor.fmatrix() W = tensor.ftensor4() h = tensor.ftensor3() iIdx = tensor.imatrix() oIdx = tensor.imatrix() o = sparse_block_dot(W, h, iIdx, b, oIdx) f = theano.function([W, h, iIdx, b, oIdx], o, mode=self.mode) (W_val, h_val, iIdx_val, b_val, oIdx_val...
['def', 'test_sparseblockdot(self):', 'b', '=', 'tensor.fmatrix()', 'W', '=', 'tensor.ftensor4()', 'h', '=', 'tensor.ftensor3()', 'iIdx', '=', 'tensor.imatrix()', 'oIdx', '=', 'tensor.imatrix()', 'o', '=', 'sparse_block_dot(W,', 'h,', 'iIdx,', 'b,', 'oIdx)', 'f', '=', 'theano.function([W,', 'h,', 'iIdx,', 'b,', 'oIdx],...
580,069
rudranil723/mini-main
options.py
ModelAdmin.response_post_save_change
response_post_save_change
Figure out where to redirect after the 'Save' button has been pressed when editing an existing object.
[ "Figure", "out", "where", "to", "redirect", "after", "the", "'Save'", "button", "has", "been", "pressed", "when", "editing", "an", "existing", "object." ]
def response_post_save_change(self, request, obj): opts = self.model._meta if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) ...
['def', 'response_post_save_change(self,', 'request,', 'obj):', 'opts', '=', 'self.model._meta', 'if', 'self.has_change_permission(request,', 'None):', 'post_url', '=', "reverse('admin:%s_%s_changelist'", '%', '(opts.app_label,', 'opts.model_name),', 'current_app=self.admin_site.name)', 'preserved_filters', '=', 'self....
314,782
PacktPublishing/Hands-On-Generative-Adversarial--with-PyTorch-1.x
utils.py
create_folder
create_folder
Create a folder if it does not exist.
[ "Create", "a", "folder", "if", "it", "does", "not", "exist." ]
def create_folder(folder_path): try: os.makedirs(folder_path) except OSError as _e: if _e.errno != errno.EEXIST: raise
['def', 'create_folder(folder_path):', 'try:', 'os.makedirs(folder_path)', 'except', 'OSError', 'as', '_e:', 'if', '_e.errno', '!=', 'errno.EEXIST:', 'raise']
575,632
kubeflow/pipelines
bigquery_util.py
back_quoted_if_needed
back_quoted_if_needed
Enclose resource name with ` if it's not yet.
[ "Enclose", "resource", "name", "with", "`", "if", "it's", "not", "yet." ]
def back_quoted_if_needed(resource_name) -> str: if not resource_name or resource_name.startswith('`'): return resource_name return '`{}`'.format(resource_name)
['def', 'back_quoted_if_needed(resource_name)', '->', 'str:', 'if', 'not', 'resource_name', 'or', "resource_name.startswith('`'):", 'return', 'resource_name', 'return', "'`{}`'.format(resource_name)"]
770,782
dawdleryang/object_detection
detector.py
DetectionModelHelper.ConvAffine
ConvAffine
ConvAffine adds a Conv op followed by a AffineChannel op (which replaces BN during fine tuning).
[ "ConvAffine", "adds", "a", "Conv", "op", "followed", "by", "a", "AffineChannel", "op", "(which", "replaces", "BN", "during", "fine", "tuning)." ]
def ConvAffine(self, blob_in, prefix, dim_in, dim_out, kernel, stride, pad, group=1, dilation=1, weight_init=None, bias_init=None, suffix='_bn', inplace=False): conv_blob = self.Conv(blob_in, prefix, dim_in, dim_out, kernel, stride=stride, pad=pad, group=group, dilation=dilation, weight_init=weight_init, bias_init=...
['def', 'ConvAffine(self,', 'blob_in,', 'prefix,', 'dim_in,', 'dim_out,', 'kernel,', 'stride,', 'pad,', 'group=1,', 'dilation=1,', 'weight_init=None,', 'bias_init=None,', "suffix='_bn',", 'inplace=False):', 'conv_blob', '=', 'self.Conv(blob_in,', 'prefix,', 'dim_in,', 'dim_out,', 'kernel,', 'stride=stride,', 'pad=pad,'...
772,597
ludwig-ai/ludwig
base.py
BaseModel.build_single_input
build_single_input
Builds a single input feature from the input feature definition.
[ "Builds", "a", "single", "input", "feature", "from", "the", "input", "feature", "definition." ]
def build_single_input(feature_config: BaseInputFeatureConfig, other_input_features: Optional[Dict[str, InputFeature]]) -> InputFeature: logger.debug(f'Input {feature_config.type} feature {feature_config.name}') encoder_obj = None if feature_config.tied is not None: tied_input_feature_name = feature...
['def', 'build_single_input(feature_config:', 'BaseInputFeatureConfig,', 'other_input_features:', 'Optional[Dict[str,', 'InputFeature]])', '->', 'InputFeature:', "logger.debug(f'Input", '{feature_config.type}', 'feature', "{feature_config.name}')", 'encoder_obj', '=', 'None', 'if', 'feature_config.tied', 'is', 'not', '...
616,823
QData/deepWordBug
proxy.py
ProxyConfig.get_environment
get_environment
Return a dictionary representing the environment variables used to set the proxy settings.
[ "Return", "a", "dictionary", "representing", "the", "environment", "variables", "used", "to", "set", "the", "proxy", "settings." ]
def get_environment(self): env = {} if self.http: env['http_proxy'] = env['HTTP_PROXY'] = self.http if self.https: env['https_proxy'] = env['HTTPS_PROXY'] = self.https if self.ftp: env['ftp_proxy'] = env['FTP_PROXY'] = self.ftp if self.no_proxy: env['no_proxy'] = env[...
['def', 'get_environment(self):', 'env', '=', '{}', 'if', 'self.http:', "env['http_proxy']", '=', "env['HTTP_PROXY']", '=', 'self.http', 'if', 'self.https:', "env['https_proxy']", '=', "env['HTTPS_PROXY']", '=', 'self.https', 'if', 'self.ftp:', "env['ftp_proxy']", '=', "env['FTP_PROXY']", '=', 'self.ftp', 'if', 'self.n...
541,945
huawei-noah/xingtian
register.py
path_to_module_format
path_to_module_format
Transform a python/file/path to module format match to the importlib.
[ "Transform", "a", "python/file/path", "to", "module", "format", "match", "to", "the", "importlib." ]
def path_to_module_format(py_path): return os.path.splitext(py_path)[0].replace('/', '.')
['def', 'path_to_module_format(py_path):', 'return', "os.path.splitext(py_path)[0].replace('/',", "'.')"]
962,457
beancount/smart_importer
pipelines.py
txn_attr_getter
txn_attr_getter
Return attribute getter for a transaction that also handles metadata.
[ "Return", "attribute", "getter", "for", "a", "transaction", "that", "also", "handles", "metadata." ]
def txn_attr_getter(attribute_name: str): if attribute_name.startswith('meta.'): meta_attr = attribute_name[5:] def getter(txn): return txn.meta.get(meta_attr) return getter return operator.attrgetter(attribute_name)
['def', 'txn_attr_getter(attribute_name:', 'str):', 'if', "attribute_name.startswith('meta.'):", 'meta_attr', '=', 'attribute_name[5:]', 'def', 'getter(txn):', 'return', 'txn.meta.get(meta_attr)', 'return', 'getter', 'return', 'operator.attrgetter(attribute_name)']
878,701
tensorflow/data-validation
stats_util.py
load_statistics
load_statistics
Loads data statistics proto from file.
[ "Loads", "data", "statistics", "proto", "from", "file." ]
def load_statistics(input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList: if not tf.io.gfile.exists(input_path): raise IOError('Invalid input path {}.'.format(input_path)) try: return load_stats_tfrecord(input_path) except Exception: logging.info('File %s did not look lik...
['def', 'load_statistics(input_path:', 'Text)', '->', 'statistics_pb2.DatasetFeatureStatisticsList:', 'if', 'not', 'tf.io.gfile.exists(input_path):', 'raise', "IOError('Invalid", 'input', 'path', "{}.'.format(input_path))", 'try:', 'return', 'load_stats_tfrecord(input_path)', 'except', 'Exception:', "logging.info('File...
497,658
weimin17/Object-Detection_HelmetDetection
model_callbacks.py
ExamplesPerSecondCallback.on_batch_end
on_batch_end
Log the examples_per_sec metric every_n_steps.
[ "Log", "the", "examples_per_sec", "metric", "every_n_steps." ]
def on_batch_end(self, batch, logs=None): self._global_step += 1 current_time = time.time() if self._global_step % self._every_n_steps == 0: average_examples_per_sec = self._batch_size * (self._global_step / (current_time - self._train_start_time)) self._logger.log_metric('average_examples_p...
['def', 'on_batch_end(self,', 'batch,', 'logs=None):', 'self._global_step', '+=', '1', 'current_time', '=', 'time.time()', 'if', 'self._global_step', '%', 'self._every_n_steps', '==', '0:', 'average_examples_per_sec', '=', 'self._batch_size', '*', '(self._global_step', '/', '(current_time', '-', 'self._train_start_time...
761,026
deepmind/meltingpot
paintball__capture_the_flag.py
create_ground_prefab
create_ground_prefab
Return a prefab for a colorable ground prefab.
[ "Return", "a", "prefab", "for", "a", "colorable", "ground", "prefab." ]
def create_ground_prefab(): sprite_names = ['RedGround', 'BlueGround'] sprite_colors = [DARKEST_RED_COLOR, DARKEST_BLUE_COLOR] prefab = {'name': 'ground', 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'clean', 'stateConfigs': [{'state': 'clean', 'layer': 'alternateLogic'}, {'state'...
['def', 'create_ground_prefab():', 'sprite_names', '=', "['RedGround',", "'BlueGround']", 'sprite_colors', '=', '[DARKEST_RED_COLOR,', 'DARKEST_BLUE_COLOR]', 'prefab', '=', "{'name':", "'ground',", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'clean',", "'stateConfigs':", "[{'...
285,385
myothida/Supervised-Machine-Learning
test_array_api.py
test_get_namespace_ndarray
test_get_namespace_ndarray
Test get_namespace on NumPy ndarrays.
[ "Test", "get_namespace", "on", "NumPy", "ndarrays." ]
def test_get_namespace_ndarray(): pytest.importorskip('numpy.array_api') X_np = numpy.asarray([[1, 2, 3]]) for array_api_dispatch in [True, False]: with config_context(array_api_dispatch=array_api_dispatch): (xp_out, is_array_api) = get_namespace(X_np) assert not is_array_api...
['def', 'test_get_namespace_ndarray():', "pytest.importorskip('numpy.array_api')", 'X_np', '=', 'numpy.asarray([[1,', '2,', '3]])', 'for', 'array_api_dispatch', 'in', '[True,', 'False]:', 'with', 'config_context(array_api_dispatch=array_api_dispatch):', '(xp_out,', 'is_array_api)', '=', 'get_namespace(X_np)', 'assert',...
364,734
SurakshaRV/AI-Lab1BM17CS108
lab8-forward-reasoning.py
parse_definite_clause
parse_definite_clause
Return the antecedents and the consequent of a definite clause.
[ "Return", "the", "antecedents", "and", "the", "consequent", "of", "a", "definite", "clause." ]
def parse_definite_clause(s): assert is_definite_clause(s) if is_symbol(s.op): return ([], s) else: (antecedent, consequent) = s.args return (conjuncts(antecedent), consequent)
['def', 'parse_definite_clause(s):', 'assert', 'is_definite_clause(s)', 'if', 'is_symbol(s.op):', 'return', '([],', 's)', 'else:', '(antecedent,', 'consequent)', '=', 's.args', 'return', '(conjuncts(antecedent),', 'consequent)']
24,690
rudranil723/mini-main
req_command.py
RequirementCommand.trace_basic_info
trace_basic_info
Trace basic information about the provided objects.
[ "Trace", "basic", "information", "about", "the", "provided", "objects." ]
def trace_basic_info(finder: PackageFinder) -> None: search_scope = finder.search_scope locations = search_scope.get_formatted_locations() if locations: logger.info(locations)
['def', 'trace_basic_info(finder:', 'PackageFinder)', '->', 'None:', 'search_scope', '=', 'finder.search_scope', 'locations', '=', 'search_scope.get_formatted_locations()', 'if', 'locations:', 'logger.info(locations)']
267,920
BlissChapman/ICW-fMRI-GAN
transformations.py
Transformer.add
add
Add a named linear transformation.
[ "Add", "a", "named", "linear", "transformation." ]
def add(self, name, mat): self.transformations[name] = mat
['def', 'add(self,', 'name,', 'mat):', 'self.transformations[name]', '=', 'mat']
597,100
bachiraoun/fullrmc
Collection.py
RandomIntegerGenerator.upperLimit
upperLimit
Upper limit of the number generation.
[ "Upper", "limit", "of", "the", "number", "generation." ]
def upperLimit(self): return self.__upperLimit
['def', 'upperLimit(self):', 'return', 'self.__upperLimit']
213,732
ilya16/MultINN
multinn_jamming.py
MultINNJamming.train_generators
train_generators
Constructs training ops for training per-track MultINN Generators.
[ "Constructs", "training", "ops", "for", "training", "per-track", "MultINN", "Generators." ]
def train_generators(self, optimizer, lr, separate_losses=False): (init_ops, update_ops, metrics, metrics_upd, summaries) = self._train_generators(optimizer, lr, pretrain=False, separate_losses=separate_losses) summaries['metrics'] = tf.summary.merge([self.summaries['metrics'], summaries['metrics']]) metric...
['def', 'train_generators(self,', 'optimizer,', 'lr,', 'separate_losses=False):', '(init_ops,', 'update_ops,', 'metrics,', 'metrics_upd,', 'summaries)', '=', 'self._train_generators(optimizer,', 'lr,', 'pretrain=False,', 'separate_losses=separate_losses)', "summaries['metrics']", '=', "tf.summary.merge([self.summaries[...
644,311
guxm2021/ALT_SpeechBrain
encoder.py
TextEncoder.limited_labelset_from_iterable
limited_labelset_from_iterable
Change default for sequence_input to True.
[ "Change", "default", "for", "sequence_input", "to", "True." ]
def limited_labelset_from_iterable(self, iterable, sequence_input=True, n_most_common=None, min_count=1): return super().limited_labelset_from_iterable(iterable, sequence_input=True, n_most_common=None, min_count=1)
['def', 'limited_labelset_from_iterable(self,', 'iterable,', 'sequence_input=True,', 'n_most_common=None,', 'min_count=1):', 'return', 'super().limited_labelset_from_iterable(iterable,', 'sequence_input=True,', 'n_most_common=None,', 'min_count=1)']
415,486
YanZiQinKevin/object_detection
config_util_test.py
ConfigUtilTest.test_save_pipeline_config
test_save_pipeline_config
Tests that the pipeline config is properly saved to disk.
[ "Tests", "that", "the", "pipeline", "config", "is", "properly", "saved", "to", "disk." ]
def test_save_pipeline_config(self): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.model.faster_rcnn.num_classes = 10 pipeline_config.train_config.batch_size = 32 pipeline_config.train_input_reader.label_map_path = 'path/to/label_map' pipeline_config.eval_config.num_exampl...
['def', 'test_save_pipeline_config(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.model.faster_rcnn.num_classes', '=', '10', 'pipeline_config.train_config.batch_size', '=', '32', 'pipeline_config.train_input_reader.label_map_path', '=', "'path/to/label_map'", 'pipeline_confi...
792,841
zomux/deepy
network.py
NeuralNetwork.save_params
save_params
Save parameters to file.
[ "Save", "parameters", "to", "file." ]
def save_params(self, path, new_thread=False): save_logger.info(path) param_variables = self.all_parameters params = [p.get_value().copy() for p in param_variables] if new_thread: thread = Thread(target=save_network_params, args=(params, path)) thread.start() else: save_netwo...
['def', 'save_params(self,', 'path,', 'new_thread=False):', 'save_logger.info(path)', 'param_variables', '=', 'self.all_parameters', 'params', '=', '[p.get_value().copy()', 'for', 'p', 'in', 'param_variables]', 'if', 'new_thread:', 'thread', '=', 'Thread(target=save_network_params,', 'args=(params,', 'path))', 'thread....
180,979
sek788432/Waymo-2D-Object-Detection
ddpg_agent.py
TD3Agent.critic_net
critic_net
Returns the output of the critic network.
[ "Returns", "the", "output", "of", "the", "critic", "network." ]
def critic_net(self, states, actions, for_critic_loss=False): values1 = self._critic_net(states, actions, for_critic_loss=for_critic_loss) values2 = self._critic_net2(states, actions, for_critic_loss=for_critic_loss) if for_critic_loss: return (values1, values2) return values1
['def', 'critic_net(self,', 'states,', 'actions,', 'for_critic_loss=False):', 'values1', '=', 'self._critic_net(states,', 'actions,', 'for_critic_loss=for_critic_loss)', 'values2', '=', 'self._critic_net2(states,', 'actions,', 'for_critic_loss=for_critic_loss)', 'if', 'for_critic_loss:', 'return', '(values1,', 'values2...
974,365
google-research/scenic
ops.py
tf_apply_to_image_mask_box
tf_apply_to_image_mask_box
Applies a function to a single element or each element in a batch.
[ "Applies", "a", "function", "to", "a", "single", "element", "or", "each", "element", "in", "a", "batch." ]
def tf_apply_to_image_mask_box(fn, image_or_images, mask_or_masks, box_or_boxes): static_rank = len(image_or_images.get_shape().as_list()) if static_rank == 3: return fn(image_or_images, mask_or_masks, box_or_boxes) elif static_rank == 4: aux = [fn(x, y, z) for (x, y, z) in zip(tf.unstack(im...
['def', 'tf_apply_to_image_mask_box(fn,', 'image_or_images,', 'mask_or_masks,', 'box_or_boxes):', 'static_rank', '=', 'len(image_or_images.get_shape().as_list())', 'if', 'static_rank', '==', '3:', 'return', 'fn(image_or_images,', 'mask_or_masks,', 'box_or_boxes)', 'elif', 'static_rank', '==', '4:', 'aux', '=', '[fn(x,'...
846,998
lanej5/bm
RBM.py
RBM.from_Values
from_Values
Initialize with trained weights.
[ "Initialize", "with", "trained", "weights." ]
def from_Values(cls, weights): (W, a, b) = (weights['W'], weights['a'], weights['b']) assert W.shape[0] == a.shape[0] and W.shape[1] == b.shape[0] rbm = cls(W.shape[0], W.shape[1]) rbm.W = W rbm.a = a rbm.b = b return rbm
['def', 'from_Values(cls,', 'weights):', '(W,', 'a,', 'b)', '=', "(weights['W'],", "weights['a'],", "weights['b'])", 'assert', 'W.shape[0]', '==', 'a.shape[0]', 'and', 'W.shape[1]', '==', 'b.shape[0]', 'rbm', '=', 'cls(W.shape[0],', 'W.shape[1])', 'rbm.W', '=', 'W', 'rbm.a', '=', 'a', 'rbm.b', '=', 'b', 'return', 'rbm'...
461,833
tensorflow/data-validation
natural_language_stats_generator_test.py
NaturalLanguageStatsGeneratorTest.test_nl_generator_invalidation_check_empty_nld
test_nl_generator_invalidation_check_empty_nld
Tests generator invalidation whith empty natural language domain.
[ "Tests", "generator", "invalidation", "whith", "empty", "natural", "language", "domain." ]
def test_nl_generator_invalidation_check_empty_nld(self): generator = nlsg.NLStatsGenerator(self._schema, None, 0, 0, 0) generator.setup() accumulator = generator.create_accumulator() self.assertFalse(accumulator.invalidate) valid_input = pa.array([[0], [1]]) accumulator = generator.add_input(ac...
['def', 'test_nl_generator_invalidation_check_empty_nld(self):', 'generator', '=', 'nlsg.NLStatsGenerator(self._schema,', 'None,', '0,', '0,', '0)', 'generator.setup()', 'accumulator', '=', 'generator.create_accumulator()', 'self.assertFalse(accumulator.invalidate)', 'valid_input', '=', 'pa.array([[0],', '[1]])', 'accu...
497,508
zhoroh/ObjectDetection
functionalCV.py
resize
resize
Resize the input CV2 Image to the given size.
[ "Resize", "the", "input", "CV2", "Image", "to", "the", "given", "size." ]
def resize(img, size, interpolation=cv2.INTER_LINEAR): if not _is_numpy_image(img): raise TypeError('img should be nparrary Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg...
['def', 'resize(img,', 'size,', 'interpolation=cv2.INTER_LINEAR):', 'if', 'not', '_is_numpy_image(img):', 'raise', "TypeError('img", 'should', 'be', 'nparrary', 'Image.', 'Got', "{}'.format(type(img)))", 'if', 'not', '(isinstance(size,', 'int)', 'or', '(isinstance(size,', 'collections.Iterable)', 'and', 'len(size)', '=...
743,332
tobegit3hub/deep_image_model
topn_ops.py
Load
Load
Load the TopN ops library and return the loaded module.
[ "Load", "the", "TopN", "ops", "library", "and", "return", "the", "loaded", "module." ]
def Load(): with _ops_lock: global _topn_ops if not _topn_ops: ops_path = tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE) tf.logging.info('data path: %s', ops_path) _topn_ops = tf.load_op_library(ops_path) assert _topn_ops, 'Could not load topn_...
['def', 'Load():', 'with', '_ops_lock:', 'global', '_topn_ops', 'if', 'not', '_topn_ops:', 'ops_path', '=', 'tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE)', "tf.logging.info('data", 'path:', "%s',", 'ops_path)', '_topn_ops', '=', 'tf.load_op_library(ops_path)', 'assert', '_topn_ops,', "'Could", 'not', 'load', ...
182,122
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
generator_utils.py
tfrecord_iterator
tfrecord_iterator
Yields records from TFRecord files.
[ "Yields", "records", "from", "TFRecord", "files." ]
def tfrecord_iterator(filenames, gzipped=False, example_spec=None): with tf.Graph().as_default(): dataset = tf.data.Dataset.from_tensor_slices(filenames) def _load_records(filename): return tf.data.TFRecordDataset(filename, compression_type=tf.constant('GZIP') if gzipped else None, buff...
['def', 'tfrecord_iterator(filenames,', 'gzipped=False,', 'example_spec=None):', 'with', 'tf.Graph().as_default():', 'dataset', '=', 'tf.data.Dataset.from_tensor_slices(filenames)', 'def', '_load_records(filename):', 'return', 'tf.data.TFRecordDataset(filename,', "compression_type=tf.constant('GZIP')", 'if', 'gzipped',...
964,870
joaquimcampos/DeepSplines
ds_utils.py
json_load
json_load
Load a json file.
[ "Load", "a", "json", "file." ]
def json_load(json_filename): try: with open(json_filename) as jsonfile: results_dict = json.load(jsonfile) except FileNotFoundError: print(f'File {json_filename} not found...') raise return results_dict
['def', 'json_load(json_filename):', 'try:', 'with', 'open(json_filename)', 'as', 'jsonfile:', 'results_dict', '=', 'json.load(jsonfile)', 'except', 'FileNotFoundError:', "print(f'File", '{json_filename}', 'not', "found...')", 'raise', 'return', 'results_dict']
540,049
myothida/Supervised-Machine-Learning
test_kernel_pca.py
test_kernel_pca_invalid_parameters
test_kernel_pca_invalid_parameters
Check that kPCA raises an error if the parameters are invalid Tests fitting inverse transform with a precomputed kernel raises a ValueError.
[ "Check", "that", "kPCA", "raises", "an", "error", "if", "the", "parameters", "are", "invalid", "Tests", "fitting", "inverse", "transform", "with", "a", "precomputed", "kernel", "raises", "a", "ValueError." ]
def test_kernel_pca_invalid_parameters(): estimator = KernelPCA(n_components=10, fit_inverse_transform=True, kernel='precomputed') err_ms = 'Cannot fit_inverse_transform with a precomputed kernel' with pytest.raises(ValueError, match=err_ms): estimator.fit(np.random.randn(10, 10))
['def', 'test_kernel_pca_invalid_parameters():', 'estimator', '=', 'KernelPCA(n_components=10,', 'fit_inverse_transform=True,', "kernel='precomputed')", 'err_ms', '=', "'Cannot", 'fit_inverse_transform', 'with', 'a', 'precomputed', "kernel'", 'with', 'pytest.raises(ValueError,', 'match=err_ms):', 'estimator.fit(np.rand...
363,668
arshpreetsingh/quantopian-machinelearning
magic_arguments.py
construct_parser
construct_parser
Construct an argument parser using the function decorations.
[ "Construct", "an", "argument", "parser", "using", "the", "function", "decorations." ]
def construct_parser(magic_func): kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) group = None for deco in magic_func.dec...
['def', 'construct_parser(magic_func):', 'kwds', '=', 'getattr(magic_func,', "'argcmd_kwds',", '{})', 'if', "'description'", 'not', 'in', 'kwds:', "kwds['description']", '=', 'getattr(magic_func,', "'__doc__',", 'None)', 'arg_name', '=', 'real_name(magic_func)', 'parser', '=', 'MagicArgumentParser(arg_name,', '**kwds)'...
886,380
david8862/tf-keras-deeplabv3p-model-set
layers.py
DeeplabDepthwiseConv2D
DeeplabDepthwiseConv2D
Wrapper to set Deeplab parameters for DepthwiseConv2D.
[ "Wrapper", "to", "set", "Deeplab", "parameters", "for", "DepthwiseConv2D." ]
def DeeplabDepthwiseConv2D(*args, **kwargs): deeplab_conv_kwargs = {'kernel_regularizer': l2(L2_FACTOR)} deeplab_conv_kwargs['bias_regularizer'] = l2(L2_FACTOR) deeplab_conv_kwargs.update(kwargs) return DepthwiseConv2D(*args, **deeplab_conv_kwargs)
['def', 'DeeplabDepthwiseConv2D(*args,', '**kwargs):', 'deeplab_conv_kwargs', '=', "{'kernel_regularizer':", 'l2(L2_FACTOR)}', "deeplab_conv_kwargs['bias_regularizer']", '=', 'l2(L2_FACTOR)', 'deeplab_conv_kwargs.update(kwargs)', 'return', 'DepthwiseConv2D(*args,', '**deeplab_conv_kwargs)']
914,165
Speedwagon13/CS-3600-Introduction-to--
tclobj.py
FromObj
FromObj
Convert a TclObj pointer into a Python object.
[ "Convert", "a", "TclObj", "pointer", "into", "a", "Python", "object." ]
def FromObj(app, value): typeCache = app._typeCache if not value.typePtr: buf = tkffi.buffer(value.bytes, value.length) return FromTclString(buf[:]) if value.typePtr in (typeCache.BooleanType, typeCache.OldBooleanType): value_ptr = tkffi.new('int*') if tklib.Tcl_GetBooleanFro...
['def', 'FromObj(app,', 'value):', 'typeCache', '=', 'app._typeCache', 'if', 'not', 'value.typePtr:', 'buf', '=', 'tkffi.buffer(value.bytes,', 'value.length)', 'return', 'FromTclString(buf[:])', 'if', 'value.typePtr', 'in', '(typeCache.BooleanType,', 'typeCache.OldBooleanType):', 'value_ptr', '=', "tkffi.new('int*')", ...
219,801
cvhciKIT/sloth
container.py
JsonContainer.serializeToFile
serializeToFile
Overwritten to write JSON files.
[ "Overwritten", "to", "write", "JSON", "files." ]
def serializeToFile(self, fname, annotations): f = open(fname, 'w') json.dump(annotations, f, indent=4, separators=(',', ': '), sort_keys=True) f.write('\n')
['def', 'serializeToFile(self,', 'fname,', 'annotations):', 'f', '=', 'open(fname,', "'w')", 'json.dump(annotations,', 'f,', 'indent=4,', "separators=(',',", "':", "'),", 'sort_keys=True)', "f.write('\\n')"]
878,361
billstark/receipt-scanner
image_to_records.py
TFRecordsConverter.write_tfrecords_file
write_tfrecords_file
Writes out TFRecords file.
[ "Writes", "out", "TFRecords", "file." ]
def write_tfrecords_file(self, output_path, indices): writer = tf.python_io.TFRecordWriter(output_path) for i in indices: filename = self.filenames[i] label = self.labels[i] with tf.gfile.FastGFile(filename, 'rb') as f: im_data = f.read() example = tf.train.Example(fe...
['def', 'write_tfrecords_file(self,', 'output_path,', 'indices):', 'writer', '=', 'tf.python_io.TFRecordWriter(output_path)', 'for', 'i', 'in', 'indices:', 'filename', '=', 'self.filenames[i]', 'label', '=', 'self.labels[i]', 'with', 'tf.gfile.FastGFile(filename,', "'rb')", 'as', 'f:', 'im_data', '=', 'f.read()', 'exam...
832,060
surafelml/adapt-mnmt
reducer.py
pad_n_with_identity
pad_n_with_identity
Pads each input tensors with identity values up to ``max(sequence_lengths)`` for each batch.
[ "Pads", "each", "input", "tensors", "with", "identity", "values", "up", "to", "``max(sequence_lengths)``", "for", "each", "batch." ]
def pad_n_with_identity(inputs, sequence_lengths, identity_values=0): max_sequence_length = tf.reduce_max(sequence_lengths, axis=0) maxlen = tf.reduce_max([tf.shape(x)[1] for x in inputs]) padded = [pad_with_identity(x, length, max_sequence_length, identity_values=identity_values, maxlen=maxlen) for (x, len...
['def', 'pad_n_with_identity(inputs,', 'sequence_lengths,', 'identity_values=0):', 'max_sequence_length', '=', 'tf.reduce_max(sequence_lengths,', 'axis=0)', 'maxlen', '=', 'tf.reduce_max([tf.shape(x)[1]', 'for', 'x', 'in', 'inputs])', 'padded', '=', '[pad_with_identity(x,', 'length,', 'max_sequence_length,', 'identity_...
407,960
triaquae/triaquae
cookie.py
CookieTest.test_max_cookie_length
test_max_cookie_length
Tests that, if the data exceeds what is allowed in a cookie, older messages are removed before saving (and returned by the ``update`` method).
[ "Tests", "that,", "if", "the", "data", "exceeds", "what", "is", "allowed", "in", "a", "cookie,", "older", "messages", "are", "removed", "before", "saving", "(and", "returned", "by", "the", "``update``", "method)." ]
def test_max_cookie_length(self): storage = self.get_storage() response = self.get_response() msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37) for i in range(5): storage.add(constants.INFO, str(i) * msg_size) unstored_messages = storage.update(response) cookie_storing = se...
['def', 'test_max_cookie_length(self):', 'storage', '=', 'self.get_storage()', 'response', '=', 'self.get_response()', 'msg_size', '=', 'int((CookieStorage.max_cookie_size', '-', '54)', '/', '4.5', '-', '37)', 'for', 'i', 'in', 'range(5):', 'storage.add(constants.INFO,', 'str(i)', '*', 'msg_size)', 'unstored_messages',...
358,134
xiaoxiong74/Object-Detection-and-Tracking
sort.py
KalmanBoxTracker.predict
predict
Advances the state vector and returns the predicted bounding box estimate.
[ "Advances", "the", "state", "vector", "and", "returns", "the", "predicted", "bounding", "box", "estimate." ]
def predict(self): if self.kf.x[6] + self.kf.x[2] <= 0: self.kf.x[6] *= 0.0 self.kf.predict() self.age += 1 if self.time_since_update > 0: self.hit_streak = 0 self.time_since_update += 1 self.history.append(convert_x_to_bbox(self.kf.x)) return self.history[-1]
['def', 'predict(self):', 'if', 'self.kf.x[6]', '+', 'self.kf.x[2]', '<=', '0:', 'self.kf.x[6]', '*=', '0.0', 'self.kf.predict()', 'self.age', '+=', '1', 'if', 'self.time_since_update', '>', '0:', 'self.hit_streak', '=', '0', 'self.time_since_update', '+=', '1', 'self.history.append(convert_x_to_bbox(self.kf.x))', 'ret...
726,080
huawei-noah/xingtian
learner.py
TrainWorker.record_reward
record_reward
Record reward in train.
[ "Record", "reward", "in", "train." ]
def record_reward(self, train_data): broker_id = get_msg_info(train_data, 'broker_id') explorer_id = get_msg_info(train_data, 'explorer_id') agent_id = get_msg_info(train_data, 'agent_id') key = (broker_id, explorer_id, agent_id) self._train_data_counter[key] += 1 self.alg.dist_model_policy.add_...
['def', 'record_reward(self,', 'train_data):', 'broker_id', '=', 'get_msg_info(train_data,', "'broker_id')", 'explorer_id', '=', 'get_msg_info(train_data,', "'explorer_id')", 'agent_id', '=', 'get_msg_info(train_data,', "'agent_id')", 'key', '=', '(broker_id,', 'explorer_id,', 'agent_id)', 'self._train_data_counter[key...
962,214
sktime/sktime
test_all_estimators.py
TestAllEstimators.test_save_estimators_to_file
test_save_estimators_to_file
Check if saved estimators onto disk can be loaded correctly.
[ "Check", "if", "saved", "estimators", "onto", "disk", "can", "be", "loaded", "correctly." ]
def test_save_estimators_to_file(self, estimator_instance, scenario, method_nsc_arraylike): method_nsc = method_nsc_arraylike if isinstance(estimator_instance, BaseForecaster) and method_nsc == 'predict_proba': return None estimator = estimator_instance set_random_state(estimator) scenario.r...
['def', 'test_save_estimators_to_file(self,', 'estimator_instance,', 'scenario,', 'method_nsc_arraylike):', 'method_nsc', '=', 'method_nsc_arraylike', 'if', 'isinstance(estimator_instance,', 'BaseForecaster)', 'and', 'method_nsc', '==', "'predict_proba':", 'return', 'None', 'estimator', '=', 'estimator_instance', 'set_...
877,624
tensorflow/privacy
common_test_utils.py
get_computed_and_true_norms_from_model
get_computed_and_true_norms_from_model
Generates relevant norms from an input model and other specs.
[ "Generates", "relevant", "norms", "from", "an", "input", "model", "and", "other", "specs." ]
def get_computed_and_true_norms_from_model(model: tf.keras.Model, per_example_loss_fn: Optional[Callable[[tf.Tensor, tf.Tensor], tf.Tensor]], num_microbatches: Optional[int], x_batch: tf.Tensor, weight_batch: Optional[tf.Tensor]=None, rng_seed: int=777, registry: layer_registry.LayerRegistry=None, partial: bool=False):...
['def', 'get_computed_and_true_norms_from_model(model:', 'tf.keras.Model,', 'per_example_loss_fn:', 'Optional[Callable[[tf.Tensor,', 'tf.Tensor],', 'tf.Tensor]],', 'num_microbatches:', 'Optional[int],', 'x_batch:', 'tf.Tensor,', 'weight_batch:', 'Optional[tf.Tensor]=None,', 'rng_seed:', 'int=777,', 'registry:', 'layer_...
824,771
43Carrig/recurrent_neural_networks_practice
control_flow_ops.py
CondContext.AddValue
AddValue
Add `val` to the current context and its outer context recursively.
[ "Add", "`val`", "to", "the", "current", "context", "and", "its", "outer", "context", "recursively." ]
def AddValue(self, val): if val.name in self._values: result = self._external_values.get(val.name) result = val if result is None else result else: result = val self._values.add(val.name) if self._outer_context: result = self._outer_context.AddValue(val) ...
['def', 'AddValue(self,', 'val):', 'if', 'val.name', 'in', 'self._values:', 'result', '=', 'self._external_values.get(val.name)', 'result', '=', 'val', 'if', 'result', 'is', 'None', 'else', 'result', 'else:', 'result', '=', 'val', 'self._values.add(val.name)', 'if', 'self._outer_context:', 'result', '=', 'self._outer_c...
337,170
LPRowe/artificial-intelligence-snake
visualize.py
plot_stats
plot_stats
Plots the population's average and best fitness.
[ "Plots", "the", "population's", "average", "and", "best", "fitness." ]
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'): if plt is None: warnings.warn('This display is not available due to a missing optional dependency (matplotlib)') return generation = range(len(statistics.most_fit_genomes)) best_fitness = [c.fitness for c in stat...
['def', 'plot_stats(statistics,', 'ylog=False,', 'view=False,', "filename='avg_fitness.svg'):", 'if', 'plt', 'is', 'None:', "warnings.warn('This", 'display', 'is', 'not', 'available', 'due', 'to', 'a', 'missing', 'optional', 'dependency', "(matplotlib)')", 'return', 'generation', '=', 'range(len(statistics.most_fit_gen...
91,512
caiiiac/Machine-Learning-with-Python
artist.py
Artist.get_snap
get_snap
Returns the snap setting which may be: * True: snap vertices to the nearest pixel center * False: leave vertices as-is * None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center Only supported by the Agg and MacOSX backends.
[ "Returns", "the", "snap", "setting", "which", "may", "be:", "*", "True:", "snap", "vertices", "to", "the", "nearest", "pixel", "center", "*", "False:", "leave", "vertices", "as-is", "*", "None:", "(auto)", "If", "the", "path", "contains", "only", "rectilinea...
def get_snap(self): if rcParams['path.snap']: return self._snap else: return False
['def', 'get_snap(self):', 'if', "rcParams['path.snap']:", 'return', 'self._snap', 'else:', 'return', 'False']
714,902
RasaHQ/rasa
trackers.py
DialogueStateTracker.is_paused
is_paused
State whether the tracker is currently paused.
[ "State", "whether", "the", "tracker", "is", "currently", "paused." ]
def is_paused(self) -> bool: return self._paused
['def', 'is_paused(self)', '->', 'bool:', 'return', 'self._paused']
837,537
THUNLP-MT/THUCC
bottle.py
BaseResponse.charset
charset
Return the charset specified in the content-type header (default: utf8).
[ "Return", "the", "charset", "specified", "in", "the", "content-type", "header", "(default:", "utf8)." ]
def charset(self, default='UTF-8'): if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return default
['def', 'charset(self,', "default='UTF-8'):", 'if', "'charset='", 'in', 'self.content_type:', 'return', "self.content_type.split('charset=')[-1].split(';')[0].strip()", 'return', 'default']
916,436
fanoping/Computer-Vision
thread_demo.py
noThreading
noThreading
Grab and show video frames without multithreading.
[ "Grab", "and", "show", "video", "frames", "without", "multithreading." ]
def noThreading(source=0): cap = cv2.VideoCapture(source) cps = CountsPerSec().start() while True: (grabbed, frame) = cap.read() if not grabbed or cv2.waitKey(1) == ord('q'): break frame = putIterationsPerSec(frame, cps.countsPerSec()) cv2.imshow('Video', frame) ...
['def', 'noThreading(source=0):', 'cap', '=', 'cv2.VideoCapture(source)', 'cps', '=', 'CountsPerSec().start()', 'while', 'True:', '(grabbed,', 'frame)', '=', 'cap.read()', 'if', 'not', 'grabbed', 'or', 'cv2.waitKey(1)', '==', "ord('q'):", 'break', 'frame', '=', 'putIterationsPerSec(frame,', 'cps.countsPerSec())', "cv2....
459,834
xiaoaleiBLUE/computer_vision
eval.py
label2str
label2str
Predicted sequence to string.
[ "Predicted", "sequence", "to", "string." ]
def label2str(preds, probs, label_dict, eos='EOS'): results = [] for idx in preds: if label_dict[idx] == eos: break results.append(label_dict[idx]) probabilities = probs[:min(len(results) + 1, cfg.seq_len + 1)] return (''.join(results), probabilities)
['def', 'label2str(preds,', 'probs,', 'label_dict,', "eos='EOS'):", 'results', '=', '[]', 'for', 'idx', 'in', 'preds:', 'if', 'label_dict[idx]', '==', 'eos:', 'break', 'results.append(label_dict[idx])', 'probabilities', '=', 'probs[:min(len(results)', '+', '1,', 'cfg.seq_len', '+', '1)]', 'return', "(''.join(results),"...
501,415
yinyunie/ScenePriors
camera_visualization.py
plot_cameras
plot_cameras
Plots a set of `cameras` objects into the maplotlib axis `ax` with color `color`.
[ "Plots", "a", "set", "of", "`cameras`", "objects", "into", "the", "maplotlib", "axis", "`ax`", "with", "color", "`color`." ]
def plot_cameras(ax, cameras, color: str='blue'): cam_wires_canonical = get_camera_wireframe().cuda()[None] cam_trans = cameras.get_world_to_view_transform().inverse() cam_wires_trans = cam_trans.transform_points(cam_wires_canonical) plot_handles = [] for wire in cam_wires_trans: (x_, z_, y_...
['def', 'plot_cameras(ax,', 'cameras,', 'color:', "str='blue'):", 'cam_wires_canonical', '=', 'get_camera_wireframe().cuda()[None]', 'cam_trans', '=', 'cameras.get_world_to_view_transform().inverse()', 'cam_wires_trans', '=', 'cam_trans.transform_points(cam_wires_canonical)', 'plot_handles', '=', '[]', 'for', 'wire', '...
329,572
KalleHallden/InstaAutomator
test_half.py
TestHalf.test_half_correctness
test_half_correctness
Take every finite float16, and check the casting functions with a manual conversion.
[ "Take", "every", "finite", "float16,", "and", "check", "the", "casting", "functions", "with", "a", "manual", "conversion." ]
def test_half_correctness(self): a_bits = self.finite_f16.view(dtype=uint16) a_sgn = (-1.0) ** ((a_bits & 32768) >> 15) a_exp = np.array((a_bits & 31744) >> 10, dtype=np.int32) - 15 a_man = (a_bits & 1023) * 2.0 ** (-10) a_man[a_exp != -15] += 1 a_exp[a_exp == -15] = -14 a_manual = a_sgn * a...
['def', 'test_half_correctness(self):', 'a_bits', '=', 'self.finite_f16.view(dtype=uint16)', 'a_sgn', '=', '(-1.0)', '**', '((a_bits', '&', '32768)', '>>', '15)', 'a_exp', '=', 'np.array((a_bits', '&', '31744)', '>>', '10,', 'dtype=np.int32)', '-', '15', 'a_man', '=', '(a_bits', '&', '1023)', '*', '2.0', '**', '(-10)',...
243,124
erikdelange/Reinforcement-Learning-Maze
qtable.py
QTableModel.q
q
Get q values for all actions for a certain state.
[ "Get", "q", "values", "for", "all", "actions", "for", "a", "certain", "state." ]
def q(self, state): if type(state) == np.ndarray: state = tuple(state.flatten()) return np.array([self.Q.get((state, action), 0.0) for action in self.environment.actions])
['def', 'q(self,', 'state):', 'if', 'type(state)', '==', 'np.ndarray:', 'state', '=', 'tuple(state.flatten())', 'return', 'np.array([self.Q.get((state,', 'action),', '0.0)', 'for', 'action', 'in', 'self.environment.actions])']
286,500
JonasLandman/QCNN
link.py
Link.netloc
netloc
This can contain auth information.
[ "This", "can", "contain", "auth", "information." ]
def netloc(self): return self._parsed_url.netloc
['def', 'netloc(self):', 'return', 'self._parsed_url.netloc']
302,833
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
LeastSquares
LeastSquares
Computes a linear least squares fit for ys as a function of xs.
[ "Computes", "a", "linear", "least", "squares", "fit", "for", "ys", "as", "a", "function", "of", "xs." ]
def LeastSquares(xs, ys): (meanx, varx) = MeanVar(xs) meany = Mean(ys) slope = Cov(xs, ys, meanx, meany) / varx inter = meany - slope * meanx return (inter, slope)
['def', 'LeastSquares(xs,', 'ys):', '(meanx,', 'varx)', '=', 'MeanVar(xs)', 'meany', '=', 'Mean(ys)', 'slope', '=', 'Cov(xs,', 'ys,', 'meanx,', 'meany)', '/', 'varx', 'inter', '=', 'meany', '-', 'slope', '*', 'meanx', 'return', '(inter,', 'slope)']
19,719
tensorflow/agents
tf_driver.py
TFDriver.run
run
Run policy in environment given initial time_step and policy_state.
[ "Run", "policy", "in", "environment", "given", "initial", "time_step", "and", "policy_state." ]
def run(self, time_step: ts.TimeStep, policy_state: types.NestedTensor=()) -> Tuple[ts.TimeStep, types.NestedTensor]: num_steps = tf.constant(0.0) num_episodes = tf.constant(0.0) while num_steps < self._max_steps and num_episodes < self._max_episodes: action_step = self.policy.action(time_step, poli...
['def', 'run(self,', 'time_step:', 'ts.TimeStep,', 'policy_state:', 'types.NestedTensor=())', '->', 'Tuple[ts.TimeStep,', 'types.NestedTensor]:', 'num_steps', '=', 'tf.constant(0.0)', 'num_episodes', '=', 'tf.constant(0.0)', 'while', 'num_steps', '<', 'self._max_steps', 'and', 'num_episodes', '<', 'self._max_episodes:'...
23,404
AgnostiqHQ/covalent
runtime_sampler.py
QiskitRuntimeSampler.post_process
post_process
Post-process a single circuit result.
[ "Post-process", "a", "single", "circuit", "result." ]
def post_process(self, *args): results = [] metadatas = [] for (i, circuit) in enumerate(self._active_circuits): circuit = self._active_circuits[i] job = self._active_jobs[i] job_result = job.result() self._num_executions += 1 assert len(job_result.quasi_dists) == 1 ...
['def', 'post_process(self,', '*args):', 'results', '=', '[]', 'metadatas', '=', '[]', 'for', '(i,', 'circuit)', 'in', 'enumerate(self._active_circuits):', 'circuit', '=', 'self._active_circuits[i]', 'job', '=', 'self._active_jobs[i]', 'job_result', '=', 'job.result()', 'self._num_executions', '+=', '1', 'assert', 'len...
489,419
ZhAnGToNG1/transfer_learning_cspt
sabl_head.py
SABLHead.attention_pool
attention_pool
Extract direction-specific features fx and fy with attention methanism.
[ "Extract", "direction-specific", "features", "fx", "and", "fy", "with", "attention", "methanism." ]
def attention_pool(self, reg_x): reg_fx = reg_x reg_fy = reg_x reg_fx_att = self.reg_conv_att_x(reg_fx).sigmoid() reg_fy_att = self.reg_conv_att_y(reg_fy).sigmoid() reg_fx_att = reg_fx_att / reg_fx_att.sum(dim=2).unsqueeze(2) reg_fy_att = reg_fy_att / reg_fy_att.sum(dim=3).unsqueeze(3) reg_f...
['def', 'attention_pool(self,', 'reg_x):', 'reg_fx', '=', 'reg_x', 'reg_fy', '=', 'reg_x', 'reg_fx_att', '=', 'self.reg_conv_att_x(reg_fx).sigmoid()', 'reg_fy_att', '=', 'self.reg_conv_att_y(reg_fy).sigmoid()', 'reg_fx_att', '=', 'reg_fx_att', '/', 'reg_fx_att.sum(dim=2).unsqueeze(2)', 'reg_fy_att', '=', 'reg_fy_att', ...
964,254
43Carrig/recurrent_neural_networks_practice
training.py
_TrainingExecutor.run_ps
run_ps
Runs task parameter server (in training cluster spec).
[ "Runs", "task", "parameter", "server", "(in", "training", "cluster", "spec)." ]
def run_ps(self): config = self._estimator.config server = self._start_std_server(config) server.join()
['def', 'run_ps(self):', 'config', '=', 'self._estimator.config', 'server', '=', 'self._start_std_server(config)', 'server.join()']
336,198
muhanzhang/D-VAE
test_mlp.py
run_conv_nnet2_classif
run_conv_nnet2_classif
Run the train function returned by build_conv_nnet2_classif on one device.
[ "Run", "the", "train", "function", "returned", "by", "build_conv_nnet2_classif", "on", "one", "device." ]
def run_conv_nnet2_classif(use_gpu, seed, isize, ksize, bsize, n_train=10, check_isfinite=True, pickle=False, verbose=0, version=-1): utt.seed_rng(seed) (train, params, x_shape, y_shape, mode) = build_conv_nnet2_classif(use_gpu=use_gpu, isize=isize, ksize=ksize, n_batch=bsize, verbose=verbose, version=version, ...
['def', 'run_conv_nnet2_classif(use_gpu,', 'seed,', 'isize,', 'ksize,', 'bsize,', 'n_train=10,', 'check_isfinite=True,', 'pickle=False,', 'verbose=0,', 'version=-1):', 'utt.seed_rng(seed)', '(train,', 'params,', 'x_shape,', 'y_shape,', 'mode)', '=', 'build_conv_nnet2_classif(use_gpu=use_gpu,', 'isize=isize,', 'ksize=ks...
525,177
microsoft/maro
client.py
StreamitClient.close
close
Close current client connection.
[ "Close", "current", "client", "connection." ]
def close(self): if self._is_started and self._sender is not None and self._sender.is_alive(): self._put(MessageType.Close, None) self._sender.join() self._is_started = False
['def', 'close(self):', 'if', 'self._is_started', 'and', 'self._sender', 'is', 'not', 'None', 'and', 'self._sender.is_alive():', 'self._put(MessageType.Close,', 'None)', 'self._sender.join()', 'self._is_started', '=', 'False']
628,707
aisingapore/PeekingDuck
base.py
ThresholdCheckerMixin.check_bounds
check_bounds
Checks if the configuration value(s) specified by `key` satisfies the specified bounds.
[ "Checks", "if", "the", "configuration", "value(s)", "specified", "by", "`key`", "satisfies", "the", "specified", "bounds." ]
def check_bounds(self, key: Union[str, List[str]], interval: str) -> None: if self.interval_pattern.match(interval) is None: raise ValueError('Badly formatted interval') left_bracket = interval[0] right_bracket = interval[-1] (lower, upper) = [float(value.strip()) for value in interval[1:-1].spl...
['def', 'check_bounds(self,', 'key:', 'Union[str,', 'List[str]],', 'interval:', 'str)', '->', 'None:', 'if', 'self.interval_pattern.match(interval)', 'is', 'None:', 'raise', "ValueError('Badly", 'formatted', "interval')", 'left_bracket', '=', 'interval[0]', 'right_bracket', '=', 'interval[-1]', '(lower,', 'upper)', '='...
766,808
som-shahlab/femr
jax.py
embedding_dot_bwd
embedding_dot_bwd
The backward pass for embedding dot.
[ "The", "backward", "pass", "for", "embedding", "dot." ]
def embedding_dot_bwd(res: Tuple[Array, Array, Array], g: Array) -> Tuple[Array, Array, None]: (a, b, indices) = res (da, db) = embedding_dot_backward_p.bind(a, b, indices, g) return (da, db, None)
['def', 'embedding_dot_bwd(res:', 'Tuple[Array,', 'Array,', 'Array],', 'g:', 'Array)', '->', 'Tuple[Array,', 'Array,', 'None]:', '(a,', 'b,', 'indices)', '=', 'res', '(da,', 'db)', '=', 'embedding_dot_backward_p.bind(a,', 'b,', 'indices,', 'g)', 'return', '(da,', 'db,', 'None)']
179,738
sktime/sktime
t.py
TDistribution.ppf
ppf
Quantile function = percent point function = inverse cdf.
[ "Quantile", "function", "=", "percent", "point", "function", "=", "inverse", "cdf." ]
def ppf(self, p): d = self.loc[p.index, p.columns] ppf_arr = p.to_numpy(copy=True) ppf_arr[p.values == 0.5] = 0.0 ppf_arr[p.values <= 0] = -np.inf ppf_arr[p.values >= 1] = np.inf mask1 = (p.values < 0.5) & (p.values > 0) mask2 = (p.values < 1) & (p.values > 0.5) ppf_arr[mask1] = 1 / beta...
['def', 'ppf(self,', 'p):', 'd', '=', 'self.loc[p.index,', 'p.columns]', 'ppf_arr', '=', 'p.to_numpy(copy=True)', 'ppf_arr[p.values', '==', '0.5]', '=', '0.0', 'ppf_arr[p.values', '<=', '0]', '=', '-np.inf', 'ppf_arr[p.values', '>=', '1]', '=', 'np.inf', 'mask1', '=', '(p.values', '<', '0.5)', '&', '(p.values', '>', '0...
877,487
Eric3911/OpenAGI
pann_model.py
init_layer
init_layer
Initialize a Linear or Convolutional layer.
[ "Initialize", "a", "Linear", "or", "Convolutional", "layer." ]
def init_layer(layer): nn.init.xavier_uniform_(layer.weight) if hasattr(layer, 'bias'): if layer.bias is not None: layer.bias.data.fill_(0.0)
['def', 'init_layer(layer):', 'nn.init.xavier_uniform_(layer.weight)', 'if', 'hasattr(layer,', "'bias'):", 'if', 'layer.bias', 'is', 'not', 'None:', 'layer.bias.data.fill_(0.0)']
250,748
rudranil723/mini-main
_regex_core.py
is_hexadecimal
is_hexadecimal
Checks whether a string is hexadecimal.
[ "Checks", "whether", "a", "string", "is", "hexadecimal." ]
def is_hexadecimal(string): return all((ch in HEX_DIGITS for ch in string))
['def', 'is_hexadecimal(string):', 'return', 'all((ch', 'in', 'HEX_DIGITS', 'for', 'ch', 'in', 'string))']
269,807
yahoo/Prototrain
stanford_online_products.py
parse
parse
Replace paths to images with the images themselves, cropped to bounding boxes if available and distorted if augmentation (otherwise only resized).
[ "Replace", "paths", "to", "images", "with", "the", "images", "themselves,", "cropped", "to", "bounding", "boxes", "if", "available", "and", "distorted", "if", "augmentation", "(otherwise", "only", "resized)." ]
def parse(path_dict, augmentation=True): result = {} for (key, val) in path_dict.items(): if key + '_bbox' in path_dict: result[key] = get_image(val, augmentation=augmentation, bbox=path_dict[key + '_bbox']) elif key == 'id' or key == 'url' or key == 'labels' or (key == 'category'): ...
['def', 'parse(path_dict,', 'augmentation=True):', 'result', '=', '{}', 'for', '(key,', 'val)', 'in', 'path_dict.items():', 'if', 'key', '+', "'_bbox'", 'in', 'path_dict:', 'result[key]', '=', 'get_image(val,', 'augmentation=augmentation,', 'bbox=path_dict[key', '+', "'_bbox'])", 'elif', 'key', '==', "'id'", 'or', 'key...
818,092
georghess/voxel-mae
encoder_decoder.py
EncoderDecoder3D.extract_feat
extract_feat
Extract features from points.
[ "Extract", "features", "from", "points." ]
def extract_feat(self, points): x = self.backbone(points) if self.with_neck: x = self.neck(x) return x
['def', 'extract_feat(self,', 'points):', 'x', '=', 'self.backbone(points)', 'if', 'self.with_neck:', 'x', '=', 'self.neck(x)', 'return', 'x']
380,756
salesforce/CodeRL
check_repo.py
check_models_are_in_init
check_models_are_in_init
Checks all models defined in the library are in the main init.
[ "Checks", "all", "models", "defined", "in", "the", "library", "are", "in", "the", "main", "init." ]
def check_models_are_in_init(): models_not_in_init = [] dir_transformers = dir(transformers) for module in get_model_modules(): models_not_in_init += [model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers] models_not_in_init = [model for model in m...
['def', 'check_models_are_in_init():', 'models_not_in_init', '=', '[]', 'dir_transformers', '=', 'dir(transformers)', 'for', 'module', 'in', 'get_model_modules():', 'models_not_in_init', '+=', '[model[0]', 'for', 'model', 'in', 'get_models(module,', 'include_pretrained=True)', 'if', 'model[0]', 'not', 'in', 'dir_transf...
495,741
intel/neural-compressor
gptq.py
trace_gptq_target_blocks
trace_gptq_target_blocks
Search transformer stacked structures, which is critical in LLMs and GPTQ execution.
[ "Search", "transformer", "stacked", "structures,", "which", "is", "critical", "in", "LLMs", "and", "GPTQ", "execution." ]
def trace_gptq_target_blocks(module, module_types=[torch.nn.ModuleList]): gptq_related_blocks = {'embeddings': {}, 'transformers_pre': {}, 'transformers_name': '', 'transformers': [], 'transformers_post': {}} for (n, m) in module.named_modules(): if type(m) in module_types: gptq_related_bloc...
['def', 'trace_gptq_target_blocks(module,', 'module_types=[torch.nn.ModuleList]):', 'gptq_related_blocks', '=', "{'embeddings':", '{},', "'transformers_pre':", '{},', "'transformers_name':", "'',", "'transformers':", '[],', "'transformers_post':", '{}}', 'for', '(n,', 'm)', 'in', 'module.named_modules():', 'if', 'type(...
737,863
tonybeltramelli/Graphics-And-Vision
Image.py
Image.Right
Right
Set the image provided by the right camera.
[ "Set", "the", "image", "provided", "by", "the", "right", "camera." ]
def Right(self, value): self.__right = value
['def', 'Right(self,', 'value):', 'self.__right', '=', 'value']
580,632
NREL/sup3r
surface.py
SurfaceSpatialMetModel.feature_inds_rh
feature_inds_rh
Get the feature index values for the relative humidity features.
[ "Get", "the", "feature", "index", "values", "for", "the", "relative", "humidity", "features." ]
def feature_inds_rh(self): inds = [i for (i, name) in enumerate(self._features) if fnmatch(name, 'relativehumidity_*')] return inds
['def', 'feature_inds_rh(self):', 'inds', '=', '[i', 'for', '(i,', 'name)', 'in', 'enumerate(self._features)', 'if', 'fnmatch(name,', "'relativehumidity_*')]", 'return', 'inds']
912,062
shivendrapratap2/Computer-Vision
data_load.py
resize
resize
Resize the input PIL image to the given size.
[ "Resize", "the", "input", "PIL", "image", "to", "the", "given", "size." ]
def resize(img, boxes, size, max_size=1000): (w, h) = img.size if isinstance(size, int): size_min = min(w, h) size_max = max(w, h) sw = sh = float(size) / size_min if sw * size_max > max_size: sw = sh = float(max_size) / size_max ow = int(w * sw + 0.5) ...
['def', 'resize(img,', 'boxes,', 'size,', 'max_size=1000):', '(w,', 'h)', '=', 'img.size', 'if', 'isinstance(size,', 'int):', 'size_min', '=', 'min(w,', 'h)', 'size_max', '=', 'max(w,', 'h)', 'sw', '=', 'sh', '=', 'float(size)', '/', 'size_min', 'if', 'sw', '*', 'size_max', '>', 'max_size:', 'sw', '=', 'sh', '=', 'floa...
458,155
asyml/texar
xlnet_classifier_test.py
XLNetClassifierTest.test_model_loading
test_model_loading
Tests model loading functionality.
[ "Tests", "model", "loading", "functionality." ]
def test_model_loading(self): inputs = tf.placeholder(dtype=tf.int32, shape=[None, None]) for pretrained_model_name in XLNetClassifier.available_checkpoints(): classifier = XLNetClassifier(pretrained_model_name=pretrained_model_name) (_, _) = classifier(inputs)
['def', 'test_model_loading(self):', 'inputs', '=', 'tf.placeholder(dtype=tf.int32,', 'shape=[None,', 'None])', 'for', 'pretrained_model_name', 'in', 'XLNetClassifier.available_checkpoints():', 'classifier', '=', 'XLNetClassifier(pretrained_model_name=pretrained_model_name)', '(_,', '_)', '=', 'classifier(inputs)']
924,350
victordibia/data2vis
beam_search.py
hyp_score
hyp_score
Calculates scores for beam search hypotheses.
[ "Calculates", "scores", "for", "beam", "search", "hypotheses." ]
def hyp_score(log_probs, sequence_lengths, config): length_penality_ = length_penalty(sequence_lengths=sequence_lengths, penalty_factor=config.length_penalty_weight) score = log_probs / length_penality_ return score
['def', 'hyp_score(log_probs,', 'sequence_lengths,', 'config):', 'length_penality_', '=', 'length_penalty(sequence_lengths=sequence_lengths,', 'penalty_factor=config.length_penalty_weight)', 'score', '=', 'log_probs', '/', 'length_penality_', 'return', 'score']
126,851
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
aggregate_experiment_results.py
print_results_table
print_results_table
Print human readable results table to stdout.
[ "Print", "human", "readable", "results", "table", "to", "stdout." ]
def print_results_table(results_table): print('') print('=== Results Table ===') print('Format: # reps [success rate, avg total NPE]') def info_str(info_row): if not info_row[0]: return '0' return '%s [%s, %s]' % (str(info_row[0]).ljust(2), info_row[1], info_row[2]) nc =...
['def', 'print_results_table(results_table):', "print('')", "print('===", 'Results', 'Table', "===')", "print('Format:", '#', 'reps', '[success', 'rate,', 'avg', 'total', "NPE]')", 'def', 'info_str(info_row):', 'if', 'not', 'info_row[0]:', 'return', "'0'", 'return', "'%s", '[%s,', "%s]'", '%', '(str(info_row[0]).ljust(...
52,666
xuannianz/SAPD
pascal.py
PascalVocGenerator.load_annotations
load_annotations
Load annotations for an image_index.
[ "Load", "annotations", "for", "an", "image_index." ]
def load_annotations(self, image_index): filename = self.image_names[image_index] + '.xml' try: tree = ET.parse(os.path.join(self.data_dir, 'Annotations', filename)) return self.__parse_annotations(tree.getroot()) except ET.ParseError as e: raise_from(ValueError('invalid annotations ...
['def', 'load_annotations(self,', 'image_index):', 'filename', '=', 'self.image_names[image_index]', '+', "'.xml'", 'try:', 'tree', '=', 'ET.parse(os.path.join(self.data_dir,', "'Annotations',", 'filename))', 'return', 'self.__parse_annotations(tree.getroot())', 'except', 'ET.ParseError', 'as', 'e:', "raise_from(ValueE...
845,466