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
huawei-noah/xingtian
share_memory.py
ClusterShareMemory.delete
delete
Delete data according to name.
[ "Delete", "data", "according", "to", "name." ]
def delete(self): self.var.delete()
['def', 'delete(self):', 'self.var.delete()']
968,366
napratin/lumos
rpc.py
start_server_thread
start_server_thread
Start RPC server thread (asynchronous), return Thread object immediately.
[ "Start", "RPC", "server", "thread", "(asynchronous),", "return", "Thread", "object", "immediately." ]
def start_server_thread(daemon=True, *args, **kwargs): rpcServerThread = Thread(target=start_server, name='RPC-Server', args=args, kwargs=kwargs) rpcServerThread.daemon = daemon rpcServerThread.start() time.sleep(0.01) return rpcServerThread
['def', 'start_server_thread(daemon=True,', '*args,', '**kwargs):', 'rpcServerThread', '=', 'Thread(target=start_server,', "name='RPC-Server',", 'args=args,', 'kwargs=kwargs)', 'rpcServerThread.daemon', '=', 'daemon', 'rpcServerThread.start()', 'time.sleep(0.01)', 'return', 'rpcServerThread']
617,603
thaines/helit
viewer.py
Viewer.del_layer
del_layer
Terminates a layer given an ident.
[ "Terminates", "a", "layer", "given", "an", "ident." ]
def del_layer(self, ident): self.layers[ident] = None
['def', 'del_layer(self,', 'ident):', 'self.layers[ident]', '=', 'None']
592,740
carlos-ferras/Sequence-ToolKit
NodeLibrary.py
NodeLibrary.reload
reload
Reload Node classes in this library.
[ "Reload", "Node", "classes", "in", "this", "library." ]
def reload(self): raise NotImplementedError()
['def', 'reload(self):', 'raise', 'NotImplementedError()']
876,784
instadeepai/jumanji
utils.py
init_graph_merge
init_graph_merge
Merge two graphs and initialize the setting to add new edges.
[ "Merge", "two", "graphs", "and", "initialize", "the", "setting", "to", "add", "new", "edges." ]
def init_graph_merge(graph_a: Graph, graph_b: Graph, num_edges: int, max_degree: int) -> Graph: edges = jnp.ones((num_edges, 2), dtype=jnp.int32) * EMPTY_EDGE num_edges_a = graph_a.edges.shape[0] num_edges_b = graph_b.edges.shape[0] num_edges_ab = num_edges_a + num_edges_b edges = edges.at[0:num_edg...
['def', 'init_graph_merge(graph_a:', 'Graph,', 'graph_b:', 'Graph,', 'num_edges:', 'int,', 'max_degree:', 'int)', '->', 'Graph:', 'edges', '=', 'jnp.ones((num_edges,', '2),', 'dtype=jnp.int32)', '*', 'EMPTY_EDGE', 'num_edges_a', '=', 'graph_a.edges.shape[0]', 'num_edges_b', '=', 'graph_b.edges.shape[0]', 'num_edges_ab'...
594,411
YuriyGuts/snake-ai-reinforcement
environment.py
Environment.new_episode
new_episode
Reset the environment and begin a new episode.
[ "Reset", "the", "environment", "and", "begin", "a", "new", "episode." ]
def new_episode(self): self.field.create_level() self.stats.reset() self.timestep_index = 0 self.snake = Snake(self.field.find_snake_head(), length=self.initial_snake_length) self.field.place_snake(self.snake) self.generate_fruit() self.current_action = None self.is_game_over = False ...
['def', 'new_episode(self):', 'self.field.create_level()', 'self.stats.reset()', 'self.timestep_index', '=', '0', 'self.snake', '=', 'Snake(self.field.find_snake_head(),', 'length=self.initial_snake_length)', 'self.field.place_snake(self.snake)', 'self.generate_fruit()', 'self.current_action', '=', 'None', 'self.is_gam...
352,170
google/balloon-learning-environment
vae.py
FieldShape.num_flow_fields
num_flow_fields
Returns the number of flow fields generated by the decoder.
[ "Returns", "the", "number", "of", "flow", "fields", "generated", "by", "the", "decoder." ]
def num_flow_fields(self) -> int: return self.pressure_slices * self.time_slices
['def', 'num_flow_fields(self)', '->', 'int:', 'return', 'self.pressure_slices', '*', 'self.time_slices']
422,442
tensorflow/hub
tf_utils.py
get_composite_tensor_type_spec
get_composite_tensor_type_spec
Returns the TypeSpec for `x`, or `None` if it's not a composite tensor.
[ "Returns", "the", "TypeSpec", "for", "`x`,", "or", "`None`", "if", "it's", "not", "a", "composite", "tensor." ]
def get_composite_tensor_type_spec(x): type_spec = getattr(x, '__tf_type_spec__', None) if type_spec is None: return getattr(x, '_type_spec', None) else: return type_spec()
['def', 'get_composite_tensor_type_spec(x):', 'type_spec', '=', 'getattr(x,', "'__tf_type_spec__',", 'None)', 'if', 'type_spec', 'is', 'None:', 'return', 'getattr(x,', "'_type_spec',", 'None)', 'else:', 'return', 'type_spec()']
571,052
RonMcKay/OODRetrieval
discover.py
Discovery.get_nearest_neighbors
get_nearest_neighbors
Computes nearest neighbors to the specified index in the collection of segment crops.
[ "Computes", "nearest", "neighbors", "to", "the", "specified", "index", "in", "the", "collection", "of", "segment", "crops." ]
def get_nearest_neighbors(self, ind, metric='cos'): if metric == 'euclid': dists = self.lp_dist(self.embeddings[ind], self.embeddings, d=2) else: dists = self.cos_dist(self.embeddings[ind], self.embeddings) return np.argsort(dists)[1:self.n_neighbors + 1]
['def', 'get_nearest_neighbors(self,', 'ind,', "metric='cos'):", 'if', 'metric', '==', "'euclid':", 'dists', '=', 'self.lp_dist(self.embeddings[ind],', 'self.embeddings,', 'd=2)', 'else:', 'dists', '=', 'self.cos_dist(self.embeddings[ind],', 'self.embeddings)', 'return', 'np.argsort(dists)[1:self.n_neighbors', '+', '1]...
756,660
dstallmann/transfer_learning_twinvae
DeepView.py
DeepView.get_artist_sample
get_artist_sample
Maps the location of an embedded point to it's image.
[ "Maps", "the", "location", "of", "an", "embedded", "point", "to", "it's", "image." ]
def get_artist_sample(self, point): sample_id = np.argmin(np.linalg.norm(self.embedded - point, axis=1)) sample = self.samples[sample_id] sample = sample + np.abs(sample.min()) sample = sample / sample.max() (yp, yt) = (int(self.y_pred[sample_id]), int(self.y_true[sample_id])) return (sample, yp...
['def', 'get_artist_sample(self,', 'point):', 'sample_id', '=', 'np.argmin(np.linalg.norm(self.embedded', '-', 'point,', 'axis=1))', 'sample', '=', 'self.samples[sample_id]', 'sample', '=', 'sample', '+', 'np.abs(sample.min())', 'sample', '=', 'sample', '/', 'sample.max()', '(yp,', 'yt)', '=', '(int(self.y_pred[sample_...
964,689
flavioschneider/rl-transfer-
test_conjugate_gradient_optimizer.py
TestFiniteDifferenceHVP.test_finite_difference_hvp_2x2_non_diagonal
test_finite_difference_hvp_2x2_non_diagonal
Test Hessian-vector product for a function with two variables whose Hessian is non-diagonal.
[ "Test", "Hessian-vector", "product", "for", "a", "function", "with", "two", "variables", "whose", "Hessian", "is", "non-diagonal." ]
def test_finite_difference_hvp_2x2_non_diagonal(self, a_val, b_val, x_val, y_val, vector): a_val = [a_val] b_val = [b_val] vector = np.array([vector], dtype=np.float32) policy = HelperPolicy(n_vars=2) params = policy.get_params() (x, y) = (params[0], params[1]) a = tf.constant(a_val) b =...
['def', 'test_finite_difference_hvp_2x2_non_diagonal(self,', 'a_val,', 'b_val,', 'x_val,', 'y_val,', 'vector):', 'a_val', '=', '[a_val]', 'b_val', '=', '[b_val]', 'vector', '=', 'np.array([vector],', 'dtype=np.float32)', 'policy', '=', 'HelperPolicy(n_vars=2)', 'params', '=', 'policy.get_params()', '(x,', 'y)', '=', '(...
861,773
scikit-learn/scikit-learn
test_set_output.py
test__wrap_in_pandas_container_column_errors
test__wrap_in_pandas_container_column_errors
If a callable `columns` errors, it has the same semantics as columns=None.
[ "If", "a", "callable", "`columns`", "errors,", "it", "has", "the", "same", "semantics", "as", "columns=None." ]
def test__wrap_in_pandas_container_column_errors(): pd = pytest.importorskip('pandas') def get_columns(): raise ValueError('No feature names defined') X_df = pd.DataFrame({'feat1': [1, 2, 3], 'feat2': [3, 4, 5]}) X_wrapped = _wrap_in_pandas_container(X_df, columns=get_columns) assert_array_...
['def', 'test__wrap_in_pandas_container_column_errors():', 'pd', '=', "pytest.importorskip('pandas')", 'def', 'get_columns():', 'raise', "ValueError('No", 'feature', 'names', "defined')", 'X_df', '=', "pd.DataFrame({'feat1':", '[1,', '2,', '3],', "'feat2':", '[3,', '4,', '5]})', 'X_wrapped', '=', '_wrap_in_pandas_conta...
854,375
aisingapore/PeekingDuck
utils.py
letterbox
letterbox
Resizes a rectangular image to a padded rectangular image.
[ "Resizes", "a", "rectangular", "image", "to", "a", "padded", "rectangular", "image." ]
def letterbox(image: np.ndarray, height: int, width: int, color: Tuple[float, float, float]=(127.5, 127.5, 127.5)) -> np.ndarray: shape = image.shape[:2] ratio = min(float(height) / shape[0], float(width) / shape[1]) new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) width_padding = (width -...
['def', 'letterbox(image:', 'np.ndarray,', 'height:', 'int,', 'width:', 'int,', 'color:', 'Tuple[float,', 'float,', 'float]=(127.5,', '127.5,', '127.5))', '->', 'np.ndarray:', 'shape', '=', 'image.shape[:2]', 'ratio', '=', 'min(float(height)', '/', 'shape[0],', 'float(width)', '/', 'shape[1])', 'new_shape', '=', '(roun...
766,984
Speedwagon13/CS-3600-Introduction-to--
_ast_gen.py
ASTCodeGenerator.generate
generate
Generates the code into file, an open file buffer.
[ "Generates", "the", "code", "into", "file,", "an", "open", "file", "buffer." ]
def generate(self, file=None): src = Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename) src += _PROLOGUE_CODE for node_cfg in self.node_cfg: src += node_cfg.generate_source() + '\n\n' file.write(src)
['def', 'generate(self,', 'file=None):', 'src', '=', 'Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename)', 'src', '+=', '_PROLOGUE_CODE', 'for', 'node_cfg', 'in', 'self.node_cfg:', 'src', '+=', 'node_cfg.generate_source()', '+', "'\\n\\n'", 'file.write(src)']
219,786
devashish-patel/webcam-motion-detector
parse.py
splitport
splitport
splitport('host:port') --> 'host', 'port'.
[ "splitport('host:port')", "-->", "'host',", "'port'." ]
def splitport(host): global _portprog if _portprog is None: import re _portprog = re.compile('^(.*):([0-9]+)$') match = _portprog.match(host) if match: return match.group(1, 2) return (host, None)
['def', 'splitport(host):', 'global', '_portprog', 'if', '_portprog', 'is', 'None:', 'import', 're', '_portprog', '=', "re.compile('^(.*):([0-9]+)$')", 'match', '=', '_portprog.match(host)', 'if', 'match:', 'return', 'match.group(1,', '2)', 'return', '(host,', 'None)']
978,118
openvinotoolkit/training_extensions
random_augment.py
contrast
contrast
Applies contrast adjustment to an image.
[ "Applies", "contrast", "adjustment", "to", "an", "image." ]
def contrast(img, value, max_value, bias=0): value = _float_parameter(value, max_value) + bias return (PIL.ImageEnhance.Contrast(img).enhance(value), value)
['def', 'contrast(img,', 'value,', 'max_value,', 'bias=0):', 'value', '=', '_float_parameter(value,', 'max_value)', '+', 'bias', 'return', '(PIL.ImageEnhance.Contrast(img).enhance(value),', 'value)']
903,989
GeekLiB/keras
generic_utils.py
func_dump
func_dump
Serialize user defined function.
[ "Serialize", "user", "defined", "function." ]
def func_dump(func): code = marshal.dumps(func.__code__).decode('raw_unicode_escape') defaults = func.__defaults__ if func.__closure__: closure = tuple((c.cell_contents for c in func.__closure__)) else: closure = None return (code, defaults, closure)
['def', 'func_dump(func):', 'code', '=', "marshal.dumps(func.__code__).decode('raw_unicode_escape')", 'defaults', '=', 'func.__defaults__', 'if', 'func.__closure__:', 'closure', '=', 'tuple((c.cell_contents', 'for', 'c', 'in', 'func.__closure__))', 'else:', 'closure', '=', 'None', 'return', '(code,', 'defaults,', 'clos...
247,888
43Carrig/recurrent_neural_networks_practice
event_file_writer_v2.py
EventFileWriterV2.add_event
add_event
Adds an event to the event file.
[ "Adds", "an", "event", "to", "the", "event", "file." ]
def add_event(self, event): if not self._closed: event_pb = event.SerializeToString() self._session.run(self._add_event_op, feed_dict={self._event_placeholder: event_pb})
['def', 'add_event(self,', 'event):', 'if', 'not', 'self._closed:', 'event_pb', '=', 'event.SerializeToString()', 'self._session.run(self._add_event_op,', 'feed_dict={self._event_placeholder:', 'event_pb})']
339,455
aws/sagemaker-python-sdk
cache.py
LRUCache.clear
clear
Deletes all elements from the cache.
[ "Deletes", "all", "elements", "from", "the", "cache." ]
def clear(self) -> None: self._lru_cache.clear()
['def', 'clear(self)', '->', 'None:', 'self._lru_cache.clear()']
830,562
rudranil723/mini-main
base.py
GeoIP2.info
info
Return information about the GeoIP library and databases in use.
[ "Return", "information", "about", "the", "GeoIP", "library", "and", "databases", "in", "use." ]
def info(self): meta = self._reader.metadata() return 'GeoIP Library:\n\t%s.%s\n' % (meta.binary_format_major_version, meta.binary_format_minor_version)
['def', 'info(self):', 'meta', '=', 'self._reader.metadata()', 'return', "'GeoIP", "Library:\\n\\t%s.%s\\n'", '%', '(meta.binary_format_major_version,', 'meta.binary_format_minor_version)']
315,257
sek788432/Waymo-2D-Object-Detection
maskrcnn.py
MaskRCNNTask.build_losses
build_losses
Build Mask R-CNN losses.
[ "Build", "Mask", "R-CNN", "losses." ]
def build_losses(self, outputs: Mapping[str, Any], labels: Mapping[str, Any], aux_losses: Optional[Any]=None): params = self.task_config cascade_ious = params.model.roi_sampler.cascade_iou_thresholds rpn_score_loss_fn = maskrcnn_losses.RpnScoreLoss(tf.shape(outputs['box_outputs'])[1]) rpn_box_loss_fn = ...
['def', 'build_losses(self,', 'outputs:', 'Mapping[str,', 'Any],', 'labels:', 'Mapping[str,', 'Any],', 'aux_losses:', 'Optional[Any]=None):', 'params', '=', 'self.task_config', 'cascade_ious', '=', 'params.model.roi_sampler.cascade_iou_thresholds', 'rpn_score_loss_fn', '=', "maskrcnn_losses.RpnScoreLoss(tf.shape(output...
973,459
openvinotoolkit/training_extensions
cross_focal_loss.py
OrdinaryFocalLoss.forward
forward
Forward function for focal loss.
[ "Forward", "function", "for", "focal", "loss." ]
def forward(self, input, target, label_weights=None, avg_factor=None, reduction='mean', **kwars): if target.numel() == 0: return 0.0 * input.sum() CE = F.cross_entropy(input, target, reduction='none') p = torch.exp(-CE) loss = (1 - p) ** self.gamma * CE if label_weights is not None: ...
['def', 'forward(self,', 'input,', 'target,', 'label_weights=None,', 'avg_factor=None,', "reduction='mean',", '**kwars):', 'if', 'target.numel()', '==', '0:', 'return', '0.0', '*', 'input.sum()', 'CE', '=', 'F.cross_entropy(input,', 'target,', "reduction='none')", 'p', '=', 'torch.exp(-CE)', 'loss', '=', '(1', '-', 'p)...
918,193
QData/deepWordBug
__init__.py
percentage
percentage
Check for an integer percentage value with optional percent sign.
[ "Check", "for", "an", "integer", "percentage", "value", "with", "optional", "percent", "sign." ]
def percentage(argument): try: argument = argument.rstrip(' %') except AttributeError: pass return nonnegative_int(argument)
['def', 'percentage(argument):', 'try:', 'argument', '=', "argument.rstrip('", "%')", 'except', 'AttributeError:', 'pass', 'return', 'nonnegative_int(argument)']
542,227
YiSyuanChen/MTL-ABS
loss.py
LossComputeBase.monolithic_compute_loss
monolithic_compute_loss
Compute the forward loss for the batch.
[ "Compute", "the", "forward", "loss", "for", "the", "batch." ]
def monolithic_compute_loss(self, batch, output): shard_state = self._make_shard_state(batch, output) (_, batch_stats) = self._compute_loss(batch, **shard_state) return batch_stats
['def', 'monolithic_compute_loss(self,', 'batch,', 'output):', 'shard_state', '=', 'self._make_shard_state(batch,', 'output)', '(_,', 'batch_stats)', '=', 'self._compute_loss(batch,', '**shard_state)', 'return', 'batch_stats']
642,801
chainer/chainer
evaluator.py
Evaluator.get_iterator
get_iterator
Returns the iterator of the given name.
[ "Returns", "the", "iterator", "of", "the", "given", "name." ]
def get_iterator(self, name): return self._iterators[name]
['def', 'get_iterator(self,', 'name):', 'return', 'self._iterators[name]']
477,535
Eric3911/OpenAGI
msdd_diarizer.py
MSDD_module.conv_scale_weights
conv_scale_weights
Use multiple Convnet layers to estimate the scale weights based on the cluster-average embedding and input embedding sequence.
[ "Use", "multiple", "Convnet", "layers", "to", "estimate", "the", "scale", "weights", "based", "on", "the", "cluster-average", "embedding", "and", "input", "embedding", "sequence." ]
def conv_scale_weights(self, ms_avg_embs_perm, ms_emb_seq_single): ms_cnn_input_seq = torch.cat([ms_avg_embs_perm, ms_emb_seq_single], dim=2) ms_cnn_input_seq = ms_cnn_input_seq.unsqueeze(2).flatten(0, 1) conv_out = self.conv_forward(ms_cnn_input_seq, conv_module=self.conv[0], bn_module=self.conv_bn[0], fir...
['def', 'conv_scale_weights(self,', 'ms_avg_embs_perm,', 'ms_emb_seq_single):', 'ms_cnn_input_seq', '=', 'torch.cat([ms_avg_embs_perm,', 'ms_emb_seq_single],', 'dim=2)', 'ms_cnn_input_seq', '=', 'ms_cnn_input_seq.unsqueeze(2).flatten(0,', '1)', 'conv_out', '=', 'self.conv_forward(ms_cnn_input_seq,', 'conv_module=self.c...
272,589
atulkum/object_detection
FPN.py
add_topdown_lateral_module
add_topdown_lateral_module
Add a top-down lateral module.
[ "Add", "a", "top-down", "lateral", "module." ]
def add_topdown_lateral_module(model, fpn_top, fpn_lateral, fpn_bottom, dim_top, dim_lateral): lat = model.Conv(fpn_lateral, fpn_bottom + '_lateral', dim_in=dim_lateral, dim_out=dim_top, kernel=1, pad=0, stride=1, weight_init=const_fill(0.0) if cfg.FPN.ZERO_INIT_LATERAL else ('XavierFill', {}), bias_init=const_fill...
['def', 'add_topdown_lateral_module(model,', 'fpn_top,', 'fpn_lateral,', 'fpn_bottom,', 'dim_top,', 'dim_lateral):', 'lat', '=', 'model.Conv(fpn_lateral,', 'fpn_bottom', '+', "'_lateral',", 'dim_in=dim_lateral,', 'dim_out=dim_top,', 'kernel=1,', 'pad=0,', 'stride=1,', 'weight_init=const_fill(0.0)', 'if', 'cfg.FPN.ZERO_...
772,667
jogisuda/QuantumSentenceTransformer
QuantumSentenceTransformer.py
QuantumSentenceTransformer.forward
forward
Defining how tensors are supposed to move through the *dressed* quantum net.
[ "Defining", "how", "tensors", "are", "supposed", "to", "move", "through", "the", "*dressed*", "quantum", "net." ]
def forward(self, input_text): input_features = self.sentence_transformer.encode(input_text, convert_to_tensor=True) pre_out = self.pre_net(input_features) q_in = torch.tanh(pre_out) * np.pi / 2.0 q_out = torch.Tensor(0, n_qubits) q_out = q_out.to(self.device) for elem in q_in: q_out_ele...
['def', 'forward(self,', 'input_text):', 'input_features', '=', 'self.sentence_transformer.encode(input_text,', 'convert_to_tensor=True)', 'pre_out', '=', 'self.pre_net(input_features)', 'q_in', '=', 'torch.tanh(pre_out)', '*', 'np.pi', '/', '2.0', 'q_out', '=', 'torch.Tensor(0,', 'n_qubits)', 'q_out', '=', 'q_out.to(s...
835,530
ldkong1205/LaserMix
base_points.py
BasePoints.to
to
Convert current points to a specific device.
[ "Convert", "current", "points", "to", "a", "specific", "device." ]
def to(self, device: Union[str, torch.device], *args, **kwargs) -> 'BasePoints': original_type = type(self) return original_type(self.tensor.to(device, *args, **kwargs), points_dim=self.points_dim, attribute_dims=self.attribute_dims)
['def', 'to(self,', 'device:', 'Union[str,', 'torch.device],', '*args,', '**kwargs)', '->', "'BasePoints':", 'original_type', '=', 'type(self)', 'return', 'original_type(self.tensor.to(device,', '*args,', '**kwargs),', 'points_dim=self.points_dim,', 'attribute_dims=self.attribute_dims)']
624,442
ChenhongyiYang/PGD
gaussian_target.py
get_topk_from_heatmap
get_topk_from_heatmap
Get top k positions from heatmap.
[ "Get", "top", "k", "positions", "from", "heatmap." ]
def get_topk_from_heatmap(scores, k=20): (batch, _, height, width) = scores.size() (topk_scores, topk_inds) = torch.topk(scores.view(batch, -1), k) topk_clses = topk_inds // (height * width) topk_inds = topk_inds % (height * width) topk_ys = topk_inds // width topk_xs = (topk_inds % width).int()...
['def', 'get_topk_from_heatmap(scores,', 'k=20):', '(batch,', '_,', 'height,', 'width)', '=', 'scores.size()', '(topk_scores,', 'topk_inds)', '=', 'torch.topk(scores.view(batch,', '-1),', 'k)', 'topk_clses', '=', 'topk_inds', '//', '(height', '*', 'width)', 'topk_inds', '=', 'topk_inds', '%', '(height', '*', 'width)', ...
768,266
Kvatsx/Artificial-Intelligence-Assignments
zmqstream.py
ZMQStream.set_close_callback
set_close_callback
Call the given callback when the stream is closed.
[ "Call", "the", "given", "callback", "when", "the", "stream", "is", "closed." ]
def set_close_callback(self, callback): self._close_callback = stack_context.wrap(callback)
['def', 'set_close_callback(self,', 'callback):', 'self._close_callback', '=', 'stack_context.wrap(callback)']
79,204
megvii-research/MSCL
bsn.py
PEM.forward_train
forward_train
Define the computation performed at every call when training.
[ "Define", "the", "computation", "performed", "at", "every", "call", "when", "training." ]
def forward_train(self, bsp_feature, reference_temporal_iou): pem_output = self._forward(bsp_feature) reference_temporal_iou = torch.cat(list(reference_temporal_iou)) device = pem_output.device reference_temporal_iou = reference_temporal_iou.to(device) anchors_temporal_iou = pem_output.view(-1) ...
['def', 'forward_train(self,', 'bsp_feature,', 'reference_temporal_iou):', 'pem_output', '=', 'self._forward(bsp_feature)', 'reference_temporal_iou', '=', 'torch.cat(list(reference_temporal_iou))', 'device', '=', 'pem_output.device', 'reference_temporal_iou', '=', 'reference_temporal_iou.to(device)', 'anchors_temporal_...
264,934
devashish-patel/webcam-motion-detector
document.py
Document.template
template
A Jinja2 template to use for rendering this document.
[ "A", "Jinja2", "template", "to", "use", "for", "rendering", "this", "document." ]
def template(self): return self._template
['def', 'template(self):', 'return', 'self._template']
977,286
ivanmontero/autobot
test_utils_summarization.py
SummarizationDataProcessingTest.test_fit_to_block_sequence_fit_exactly
test_fit_to_block_sequence_fit_exactly
Do nothing if the sequence is the right size.
[ "Do", "nothing", "if", "the", "sequence", "is", "the", "right", "size." ]
def test_fit_to_block_sequence_fit_exactly(self): sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] expected_output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(sequence, self.block_size, 0), expected_output)
['def', 'test_fit_to_block_sequence_fit_exactly(self):', 'sequence', '=', '[1,', '2,', '3,', '4,', '5,', '6,', '7,', '8,', '9,', '10]', 'expected_output', '=', '[1,', '2,', '3,', '4,', '5,', '6,', '7,', '8,', '9,', '10]', 'self.assertEqual(truncate_or_pad(sequence,', 'self.block_size,', '0),', 'expected_output)']
417,767
aws/sagemaker-python-sdk
image_uris.py
ImageURIRetrieveImportFromRenamer.node_should_be_modified
node_should_be_modified
Checks if the import statement imports ``get_image_uri`` from the correct module.
[ "Checks", "if", "the", "import", "statement", "imports", "``get_image_uri``", "from", "the", "correct", "module." ]
def node_should_be_modified(self, node): return node is not None and node.module in GET_IMAGE_URI_NAMESPACES and any((name.name == GET_IMAGE_URI_NAME for name in node.names))
['def', 'node_should_be_modified(self,', 'node):', 'return', 'node', 'is', 'not', 'None', 'and', 'node.module', 'in', 'GET_IMAGE_URI_NAMESPACES', 'and', 'any((name.name', '==', 'GET_IMAGE_URI_NAME', 'for', 'name', 'in', 'node.names))']
829,836
jbwang1997/CrossKD
augment_wrappers.py
level_to_mag
level_to_mag
Map from level to magnitude.
[ "Map", "from", "level", "to", "magnitude." ]
def level_to_mag(level: Optional[int], min_mag: float, max_mag: float) -> float: if level is None: return round(np.random.rand() * (max_mag - min_mag) + min_mag, 1) else: return round(level / _MAX_LEVEL * (max_mag - min_mag) + min_mag, 1)
['def', 'level_to_mag(level:', 'Optional[int],', 'min_mag:', 'float,', 'max_mag:', 'float)', '->', 'float:', 'if', 'level', 'is', 'None:', 'return', 'round(np.random.rand()', '*', '(max_mag', '-', 'min_mag)', '+', 'min_mag,', '1)', 'else:', 'return', 'round(level', '/', '_MAX_LEVEL', '*', '(max_mag', '-', 'min_mag)', '...
490,762
klickmal/ContextNet
layer.py
SELayer.forward
forward
Forward propagate a `inputs` for SE Layer.
[ "Forward", "propagate", "a", "`inputs`", "for", "SE", "Layer." ]
def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]: residual = inputs seq_lengths = inputs.size(2) inputs = inputs.sum(dim=2) / input_lengths.unsqueeze(1) output = self.sequential(inputs) output = output.sigmoid().unsqueeze(2) output = output.repeat(1, 1, seq_lengt...
['def', 'forward(self,', 'inputs:', 'Tensor,', 'input_lengths:', 'Tensor)', '->', 'Tuple[Tensor,', 'Tensor]:', 'residual', '=', 'inputs', 'seq_lengths', '=', 'inputs.size(2)', 'inputs', '=', 'inputs.sum(dim=2)', '/', 'input_lengths.unsqueeze(1)', 'output', '=', 'self.sequential(inputs)', 'output', '=', 'output.sigmoid(...
136,368
rlgraph/rlgraph
sac_networks.py
SACValueNetwork.build_value_function
build_value_function
Builds a dense stack and optionally an image stack.
[ "Builds", "a", "dense", "stack", "and", "optionally", "an", "image", "stack." ]
def build_value_function(self): if self.use_image_stack: image_components = [] dense_components = [] for layer_spec in self.network_spec: if layer_spec['type'] in ['conv2d', 'reshape']: image_components.append(Layer.from_spec(layer_spec)) self.image_stack ...
['def', 'build_value_function(self):', 'if', 'self.use_image_stack:', 'image_components', '=', '[]', 'dense_components', '=', '[]', 'for', 'layer_spec', 'in', 'self.network_spec:', 'if', "layer_spec['type']", 'in', "['conv2d',", "'reshape']:", 'image_components.append(Layer.from_spec(layer_spec))', 'self.image_stack', ...
862,514
google-research/rigl
shuffled_mask_test.py
ShuffledMaskTest.test_run_conv
test_run_conv
Tests if the driver for shuffled training runs correctly with CNN.
[ "Tests", "if", "the", "driver", "for", "shuffled", "training", "runs", "correctly", "with", "CNN." ]
def test_run_conv(self): experiment_dir = tempfile.mkdtemp() eval_flags = dict(epochs=1, experiment_dir=experiment_dir, model='MNIST_CNN') with flagsaver.flagsaver(**eval_flags): shuffled_mask.main([]) outfile = path.join(experiment_dir, '*', 'events.out.tfevents.*') files = glob.glob(outfil...
['def', 'test_run_conv(self):', 'experiment_dir', '=', 'tempfile.mkdtemp()', 'eval_flags', '=', 'dict(epochs=1,', 'experiment_dir=experiment_dir,', "model='MNIST_CNN')", 'with', 'flagsaver.flagsaver(**eval_flags):', 'shuffled_mask.main([])', 'outfile', '=', 'path.join(experiment_dir,', "'*',", "'events.out.tfevents.*')...
841,400
devashish-patel/webcam-motion-detector
bccache.py
Bucket.bytecode_to_string
bytecode_to_string
Return the bytecode as string.
[ "Return", "the", "bytecode", "as", "string." ]
def bytecode_to_string(self): out = BytesIO() self.write_bytecode(out) return out.getvalue()
['def', 'bytecode_to_string(self):', 'out', '=', 'BytesIO()', 'self.write_bytecode(out)', 'return', 'out.getvalue()']
979,630
Djaizz/Djaizz
token_classification.py
PreTrainedHuggingFaceTokenClassifier.predict
predict
Classify Tokens in Text(s).
[ "Classify", "Tokens", "in", "Text(s)." ]
def predict(self, text_or_texts: Union[TokenClassificationInputType, Sequence[TokenClassificationInputType]]) -> Union[TokenClassificationOutputType, Sequence[TokenClassificationOutputType]]: single_text: bool = isinstance(text_or_texts, str) if not (single_text or isinstance(text_or_texts, list)): text...
['def', 'predict(self,', 'text_or_texts:', 'Union[TokenClassificationInputType,', 'Sequence[TokenClassificationInputType]])', '->', 'Union[TokenClassificationOutputType,', 'Sequence[TokenClassificationOutputType]]:', 'single_text:', 'bool', '=', 'isinstance(text_or_texts,', 'str)', 'if', 'not', '(single_text', 'or', 'i...
189,457
voxel51/fiftyone
utils.py
extract_kwargs_for_function
extract_kwargs_for_function
Extracts keyword arguments for the given function from the given kwargs.
[ "Extracts", "keyword", "arguments", "for", "the", "given", "function", "from", "the", "given", "kwargs." ]
def extract_kwargs_for_function(fcn, kwargs): return _extract_kwargs(fcn, kwargs)
['def', 'extract_kwargs_for_function(fcn,', 'kwargs):', 'return', '_extract_kwargs(fcn,', 'kwargs)']
583,425
omarmhaimdat/twitter_nlp_native_swift
api.py
Api.GetListTimeline
GetListTimeline
Fetch the sequence of Status messages for a given List ID.
[ "Fetch", "the", "sequence", "of", "Status", "messages", "for", "a", "given", "List", "ID." ]
def GetListTimeline(self, list_id=None, slug=None, owner_id=None, owner_screen_name=None, since_id=None, max_id=None, count=None, include_rts=True, include_entities=True, return_json=False): url = '%s/lists/statuses.json' % self.base_url parameters = {} parameters.update(self._IDList(list_id=list_id, slug=s...
['def', 'GetListTimeline(self,', 'list_id=None,', 'slug=None,', 'owner_id=None,', 'owner_screen_name=None,', 'since_id=None,', 'max_id=None,', 'count=None,', 'include_rts=True,', 'include_entities=True,', 'return_json=False):', 'url', '=', "'%s/lists/statuses.json'", '%', 'self.base_url', 'parameters', '=', '{}', 'para...
955,159
zihuitang/medical_AI_platform
mailbox.py
Mailbox.update
update
Change the messages that correspond to certain keys.
[ "Change", "the", "messages", "that", "correspond", "to", "certain", "keys." ]
def update(self, arg=None): if hasattr(arg, 'iteritems'): source = arg.iteritems() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for (key, message) in source: try: self[key] = message except KeyError: ...
['def', 'update(self,', 'arg=None):', 'if', 'hasattr(arg,', "'iteritems'):", 'source', '=', 'arg.iteritems()', 'elif', 'hasattr(arg,', "'items'):", 'source', '=', 'arg.items()', 'else:', 'source', '=', 'arg', 'bad_key', '=', 'False', 'for', '(key,', 'message)', 'in', 'source:', 'try:', 'self[key]', '=', 'message', 'exc...
280,719
flavioschneider/rl-transfer-
td3_pendulum.py
td3_pendulum
td3_pendulum
Train TD3 with InvertedDoublePendulum-v2 environment.
[ "Train", "TD3", "with", "InvertedDoublePendulum-v2", "environment." ]
def td3_pendulum(ctxt=None, seed=1): set_seed(seed) n_epochs = 750 steps_per_epoch = 40 sampler_batch_size = 100 num_timesteps = n_epochs * steps_per_epoch * sampler_batch_size trainer = Trainer(ctxt) env = normalize(GymEnv('InvertedDoublePendulum-v2')) policy = DeterministicMLPPolicy(en...
['def', 'td3_pendulum(ctxt=None,', 'seed=1):', 'set_seed(seed)', 'n_epochs', '=', '750', 'steps_per_epoch', '=', '40', 'sampler_batch_size', '=', '100', 'num_timesteps', '=', 'n_epochs', '*', 'steps_per_epoch', '*', 'sampler_batch_size', 'trainer', '=', 'Trainer(ctxt)', 'env', '=', "normalize(GymEnv('InvertedDoublePend...
861,146
Ruturaj123/Flowchart-Detection
stats_accumulator_ops.py
StatsAccumulator.add
add
Updates the stats accumulator.
[ "Updates", "the", "stats", "accumulator." ]
def add(self, stamp_token, partition_ids, feature_ids, gradients, hessians): (partition_ids, feature_ids, gradients, hessians) = self._make_summary(partition_ids, feature_ids, gradients, hessians) if self._is_scalar: return gen_stats_accumulator_ops.stats_accumulator_scalar_add([self._resource_handle], ...
['def', 'add(self,', 'stamp_token,', 'partition_ids,', 'feature_ids,', 'gradients,', 'hessians):', '(partition_ids,', 'feature_ids,', 'gradients,', 'hessians)', '=', 'self._make_summary(partition_ids,', 'feature_ids,', 'gradients,', 'hessians)', 'if', 'self._is_scalar:', 'return', 'gen_stats_accumulator_ops.stats_accum...
586,889
liaorongfan/DeepPersonality
draw.py
pil_to_tensor
pil_to_tensor
Convert a PIL image to a tensor.
[ "Convert", "a", "PIL", "image", "to", "a", "tensor." ]
def pil_to_tensor(pil_image): pil_image = np.array(pil_image) if len(pil_image.shape) == 2: pil_image = pil_image[:, :, None] return torch.tensor(pil_image, dtype=torch.float32).permute(2, 0, 1) / 255
['def', 'pil_to_tensor(pil_image):', 'pil_image', '=', 'np.array(pil_image)', 'if', 'len(pil_image.shape)', '==', '2:', 'pil_image', '=', 'pil_image[:,', ':,', 'None]', 'return', 'torch.tensor(pil_image,', 'dtype=torch.float32).permute(2,', '0,', '1)', '/', '255']
539,242
ludwig-ai/ludwig
metrics_printed_table.py
get_metric_value_or_empty
get_metric_value_or_empty
Returns the metric value if it exists or empty.
[ "Returns", "the", "metric", "value", "if", "it", "exists", "or", "empty." ]
def get_metric_value_or_empty(metrics_log: Dict[str, List[TrainerMetric]], metric_name: str): if metric_name not in metrics_log: return '' return metrics_log[metric_name][-1][-1]
['def', 'get_metric_value_or_empty(metrics_log:', 'Dict[str,', 'List[TrainerMetric]],', 'metric_name:', 'str):', 'if', 'metric_name', 'not', 'in', 'metrics_log:', 'return', "''", 'return', 'metrics_log[metric_name][-1][-1]']
617,121
gunthercox/ChatterBot
reading.py
IndexReader.doc_count_all
doc_count_all
Returns the total number of documents, DELETED OR UNDELETED, in this reader.
[ "Returns", "the", "total", "number", "of", "documents,", "DELETED", "OR", "UNDELETED,", "in", "this", "reader." ]
def doc_count_all(self): raise NotImplementedError
['def', 'doc_count_all(self):', 'raise', 'NotImplementedError']
526,356
ludwig-ai/ludwig
utils.py
register_parameter_config
register_parameter_config
Register a parameter config class by name.
[ "Register", "a", "parameter", "config", "class", "by", "name." ]
def register_parameter_config(name: str) -> Callable: def wrap(cls: Type['BaseParameterConfig']) -> Type['BaseParameterConfig']: parameter_config_registry[name] = cls return cls return wrap
['def', 'register_parameter_config(name:', 'str)', '->', 'Callable:', 'def', 'wrap(cls:', "Type['BaseParameterConfig'])", '->', "Type['BaseParameterConfig']:", 'parameter_config_registry[name]', '=', 'cls', 'return', 'cls', 'return', 'wrap']
616,991
dustin/twitty-twister
test_twitter.py
TwitterMonitorTest.test_connectConnecting
test_connectConnecting
Don't connect while connecting.
[ "Don't", "connect", "while", "connecting." ]
def test_connectConnecting(self): self.setUpState('connecting') self.assertRaises(twitter.Error, self.monitor.connect) self.clock.advance(0) self.assertEqual(1, len(self.api.filterCalls), 'Extra connect')
['def', 'test_connectConnecting(self):', "self.setUpState('connecting')", 'self.assertRaises(twitter.Error,', 'self.monitor.connect)', 'self.clock.advance(0)', 'self.assertEqual(1,', 'len(self.api.filterCalls),', "'Extra", "connect')"]
426,523
wonheeML/mtl-ssl
box_list.py
BoxList.get_lefttop_coordinates_and_sizes
get_lefttop_coordinates_and_sizes
Computes the left-top coordinates, height and width of the boxes.
[ "Computes", "the", "left-top", "coordinates,", "height", "and", "width", "of", "the", "boxes." ]
def get_lefttop_coordinates_and_sizes(self, scope=None): with tf.name_scope(scope, 'get_lefttop_coordinates_and_sizes'): box_corners = self.get() (ymin, xmin, ymax, xmax) = tf.unstack(tf.transpose(box_corners)) width = xmax - xmin height = ymax - ymin return [ymin, xmin, heig...
['def', 'get_lefttop_coordinates_and_sizes(self,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'get_lefttop_coordinates_and_sizes'):", 'box_corners', '=', 'self.get()', '(ymin,', 'xmin,', 'ymax,', 'xmax)', '=', 'tf.unstack(tf.transpose(box_corners))', 'width', '=', 'xmax', '-', 'xmin', 'height', '=', 'ymax', '-', ...
642,965
Farama-Foundation/Gymnasium
test_shared_memory.py
test_non_space
test_non_space
Test the use of non-space types on the shared memory functions.
[ "Test", "the", "use", "of", "non-space", "types", "on", "the", "shared", "memory", "functions." ]
def test_non_space(): with pytest.raises(TypeError, match=re.escape("The space provided to `create_shared_memory` is not a gymnasium Space instance, type: <class 'str'>, space")): create_shared_memory('space') with pytest.raises(TypeError, match=re.escape("The space provided to `read_from_shared_memory`...
['def', 'test_non_space():', 'with', 'pytest.raises(TypeError,', 'match=re.escape("The', 'space', 'provided', 'to', '`create_shared_memory`', 'is', 'not', 'a', 'gymnasium', 'Space', 'instance,', 'type:', '<class', "'str'>,", 'space")):', "create_shared_memory('space')", 'with', 'pytest.raises(TypeError,', 'match=re.esc...
573,553
Atharv24/DanceGeneration
animate_view.py
generate
generate
Generates Z data for the points in the X, Y meshgrid and parameter phi.
[ "Generates", "Z", "data", "for", "the", "points", "in", "the", "X,", "Y", "meshgrid", "and", "parameter", "phi." ]
def generate(X, Y, phi): R = 1 - np.sqrt(X ** 2 + Y ** 2) return np.cos(2 * np.pi * X + phi) * R
['def', 'generate(X,', 'Y,', 'phi):', 'R', '=', '1', '-', 'np.sqrt(X', '**', '2', '+', 'Y', '**', '2)', 'return', 'np.cos(2', '*', 'np.pi', '*', 'X', '+', 'phi)', '*', 'R']
497,021
Eric3911/OpenAGI
numba_utils.py
numba_cuda_is_supported
numba_cuda_is_supported
Tests if an appropriate version of numba is installed, and if it is, if cuda is supported properly within it.
[ "Tests", "if", "an", "appropriate", "version", "of", "numba", "is", "installed,", "and", "if", "it", "is,", "if", "cuda", "is", "supported", "properly", "within", "it." ]
def numba_cuda_is_supported(min_version: str) -> bool: module_available = numba_cpu_is_supported(min_version) if module_available is None: return False if module_available is True: from numba import cuda if hasattr(cuda, 'is_supported_version'): try: cuda_...
['def', 'numba_cuda_is_supported(min_version:', 'str)', '->', 'bool:', 'module_available', '=', 'numba_cpu_is_supported(min_version)', 'if', 'module_available', 'is', 'None:', 'return', 'False', 'if', 'module_available', 'is', 'True:', 'from', 'numba', 'import', 'cuda', 'if', 'hasattr(cuda,', "'is_supported_version'):"...
274,098
robustness-gym/robustness-gym
testbench.py
TestBench.load
load
Load a testbench from disk.
[ "Load", "a", "testbench", "from", "disk." ]
def load(cls, path: str) -> TestBench: savedir = pathlib.Path(path) slices = [] for sl_path in tqdm(list((savedir / 'slices').glob('*'))): try: slices.append(DataPanel.load_from_disk(str(sl_path))) except FileNotFoundError: continue metrics = dill.load(open(str(sa...
['def', 'load(cls,', 'path:', 'str)', '->', 'TestBench:', 'savedir', '=', 'pathlib.Path(path)', 'slices', '=', '[]', 'for', 'sl_path', 'in', 'tqdm(list((savedir', '/', "'slices').glob('*'))):", 'try:', 'slices.append(DataPanel.load_from_disk(str(sl_path)))', 'except', 'FileNotFoundError:', 'continue', 'metrics', '=', '...
826,297
sktime/sktime
test_window_summarizer.py
count_gt100
count_gt100
Count how many observations lie above threshold 100.
[ "Count", "how", "many", "observations", "lie", "above", "threshold", "100." ]
def count_gt100(x): return np.sum((x > 100)[::-1])
['def', 'count_gt100(x):', 'return', 'np.sum((x', '>', '100)[::-1])']
877,926
jimtin/Stock_Comparison
compiler.py
Identifiers.add_special
add_special
Register a special name like `loop`.
[ "Register", "a", "special", "name", "like", "`loop`." ]
def add_special(self, name): self.undeclared.discard(name) self.declared.add(name)
['def', 'add_special(self,', 'name):', 'self.undeclared.discard(name)', 'self.declared.add(name)']
385,705
dustin/twitty-twister
test_twitter.py
TwitterMonitorTest.test_stopServiceAfterReconnect
test_stopServiceAfterReconnect
Stopping the service after waiting is fine.
[ "Stopping", "the", "service", "after", "waiting", "is", "fine." ]
def test_stopServiceAfterReconnect(self): self.setUpState('waiting') self.clock.advance(DELAY_INITIAL) self.assertEqual(2, len(self.api.filterCalls)) self.monitor.stopService() self.clock.advance(0)
['def', 'test_stopServiceAfterReconnect(self):', "self.setUpState('waiting')", 'self.clock.advance(DELAY_INITIAL)', 'self.assertEqual(2,', 'len(self.api.filterCalls))', 'self.monitor.stopService()', 'self.clock.advance(0)']
426,519
mnielsen/neural-networks-and-deep-learning
mnist.py
plot_mnist_digit
plot_mnist_digit
Plot a single MNIST image.
[ "Plot", "a", "single", "MNIST", "image." ]
def plot_mnist_digit(image): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.matshow(image, cmap=matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show()
['def', 'plot_mnist_digit(image):', 'fig', '=', 'plt.figure()', 'ax', '=', 'fig.add_subplot(1,', '1,', '1)', 'ax.matshow(image,', 'cmap=matplotlib.cm.binary)', 'plt.xticks(np.array([]))', 'plt.yticks(np.array([]))', 'plt.show()']
722,057
siddhanthaldar/PyTorch_Object_Detection
encoder.py
DataEncoder.iou
iou
Compute the intersection over union of two set of boxes, each box is [x1,y1,x2,y2].
[ "Compute", "the", "intersection", "over", "union", "of", "two", "set", "of", "boxes,", "each", "box", "is", "[x1,y1,x2,y2]." ]
def iou(self, box1, box2): N = box1.size(0) M = box2.size(0) lt = torch.max(box1[:, :2].unsqueeze(1).expand(N, M, 2), box2[:, :2].unsqueeze(0).expand(N, M, 2)) rb = torch.min(box1[:, 2:].unsqueeze(1).expand(N, M, 2), box2[:, 2:].unsqueeze(0).expand(N, M, 2)) wh = rb - lt wh[wh < 0] = 0 inter...
['def', 'iou(self,', 'box1,', 'box2):', 'N', '=', 'box1.size(0)', 'M', '=', 'box2.size(0)', 'lt', '=', 'torch.max(box1[:,', ':2].unsqueeze(1).expand(N,', 'M,', '2),', 'box2[:,', ':2].unsqueeze(0).expand(N,', 'M,', '2))', 'rb', '=', 'torch.min(box1[:,', '2:].unsqueeze(1).expand(N,', 'M,', '2),', 'box2[:,', '2:].unsqueez...
815,552
dojoteef/dvae
rbm.py
MarginalRBMType1Generic.cross_entropy_from_hierarchical
cross_entropy_from_hierarchical
Computes a sampling-based estimate of the cross-entropy from a hierarchical posterior to marginal.
[ "Computes", "a", "sampling-based", "estimate", "of", "the", "cross-entropy", "from", "a", "hierarchical", "posterior", "to", "marginal." ]
def cross_entropy_from_hierarchical(self, post_samples, is_training=False): neg_log_prob = -self.log_prob(post_samples, is_training) return neg_log_prob
['def', 'cross_entropy_from_hierarchical(self,', 'post_samples,', 'is_training=False):', 'neg_log_prob', '=', '-self.log_prob(post_samples,', 'is_training)', 'return', 'neg_log_prob']
554,863
TengXiaoDai/DistributedCrawling
punycode.py
selective_len
selective_len
Return the length of str, considering only characters below max.
[ "Return", "the", "length", "of", "str,", "considering", "only", "characters", "below", "max." ]
def selective_len(str, max): res = 0 for c in str: if ord(c) < max: res += 1 return res
['def', 'selective_len(str,', 'max):', 'res', '=', '0', 'for', 'c', 'in', 'str:', 'if', 'ord(c)', '<', 'max:', 'res', '+=', '1', 'return', 'res']
188,184
greydanus/mr_london
OleFileIO.py
OleMetadata.dump
dump
Dump all metadata, for debugging purposes.
[ "Dump", "all", "metadata,", "for", "debugging", "purposes." ]
def dump(self): print('Properties from SummaryInformation stream:') for prop in self.SUMMARY_ATTRIBS: value = getattr(self, prop) print('- %s: %s' % (prop, repr(value))) print('Properties from DocumentSummaryInformation stream:') for prop in self.DOCSUM_ATTRIBS: value = getattr(s...
['def', 'dump(self):', "print('Properties", 'from', 'SummaryInformation', "stream:')", 'for', 'prop', 'in', 'self.SUMMARY_ATTRIBS:', 'value', '=', 'getattr(self,', 'prop)', "print('-", '%s:', "%s'", '%', '(prop,', 'repr(value)))', "print('Properties", 'from', 'DocumentSummaryInformation', "stream:')", 'for', 'prop', 'i...
263,258
instadeepai/jumanji
env.py
RubiksCube.animate
animate
Creates an animated gif of the cube based on the sequence of states.
[ "Creates", "an", "animated", "gif", "of", "the", "cube", "based", "on", "the", "sequence", "of", "states." ]
def animate(self, states: Sequence[State], interval: int=200, save_path: Optional[str]=None) -> matplotlib.animation.FuncAnimation: return self._viewer.animate(states=states, interval=interval, save_path=save_path)
['def', 'animate(self,', 'states:', 'Sequence[State],', 'interval:', 'int=200,', 'save_path:', 'Optional[str]=None)', '->', 'matplotlib.animation.FuncAnimation:', 'return', 'self._viewer.animate(states=states,', 'interval=interval,', 'save_path=save_path)']
594,097
microsoft/maro
grass_executor.py
GrassExecutor.push_data
push_data
Push data from local to remote MARO Cluster.
[ "Push", "data", "from", "local", "to", "remote", "MARO", "Cluster." ]
def push_data(self, local_path: str, remote_path: str) -> None: if not remote_path.startswith('/'): raise FileOperationError(f"Invalid remote path: {remote_path}\nShould be started with '/'") FileSynchronizer.copy_files_to_node(local_path=local_path, remote_dir=f'{GlobalPaths.MARO_SHARED}/clusters/{self...
['def', 'push_data(self,', 'local_path:', 'str,', 'remote_path:', 'str)', '->', 'None:', 'if', 'not', "remote_path.startswith('/'):", 'raise', 'FileOperationError(f"Invalid', 'remote', 'path:', '{remote_path}\\nShould', 'be', 'started', 'with', '\'/\'")', 'FileSynchronizer.copy_files_to_node(local_path=local_path,', "r...
628,161
microsoft/logrl
train_atari.py
create_agent
create_agent
Creates a DQN agent.
[ "Creates", "a", "DQN", "agent." ]
def create_agent(sess, environment, summary_writer=None): if not FLAGS.debug_mode: summary_writer = None if FLAGS.agent_name == 'dqn': return dqn_agent.DQNAgent(sess, num_actions=environment.action_space.n, summary_writer=summary_writer) elif FLAGS.agent_name == 'log_dqn': return log...
['def', 'create_agent(sess,', 'environment,', 'summary_writer=None):', 'if', 'not', 'FLAGS.debug_mode:', 'summary_writer', '=', 'None', 'if', 'FLAGS.agent_name', '==', "'dqn':", 'return', 'dqn_agent.DQNAgent(sess,', 'num_actions=environment.action_space.n,', 'summary_writer=summary_writer)', 'elif', 'FLAGS.agent_name',...
615,712
santhoshkolloju/Abstractive-Summarization-With-Transfer-
data_decoders.py
TextDataDecoder.decode
decode
Decodes the data to return the tensors specified by the list of items.
[ "Decodes", "the", "data", "to", "return", "the", "tensors", "specified", "by", "the", "list", "of", "items." ]
def decode(self, data, items): if self._split_level == 'word': tokens = tf.string_split([data], delimiter=self._delimiter).values elif self._split_level == 'char': raise NotImplementedError else: raise ValueError('Unknown split level: %s' % self._split_level) if self._max_seq_len...
['def', 'decode(self,', 'data,', 'items):', 'if', 'self._split_level', '==', "'word':", 'tokens', '=', 'tf.string_split([data],', 'delimiter=self._delimiter).values', 'elif', 'self._split_level', '==', "'char':", 'raise', 'NotImplementedError', 'else:', 'raise', "ValueError('Unknown", 'split', 'level:', "%s'", '%', 'se...
406,003
aeon-toolkit/aeon
test_benchmarks.py
test_add_task_string_entrypoint
test_add_task_string_entrypoint
Test adding task using string of entrypoint.
[ "Test", "adding", "task", "using", "string", "of", "entrypoint." ]
def test_add_task_string_entrypoint(tmp_path): benchmark = benchmarks.BaseBenchmark() benchmark.add_estimator(NaiveForecaster(strategy='drift')) benchmark._add_task('aeon.benchmarking.tests.test_benchmarks:factory_estimator_class_task') results_file = tmp_path / 'results.csv' results_df = benchmark....
['def', 'test_add_task_string_entrypoint(tmp_path):', 'benchmark', '=', 'benchmarks.BaseBenchmark()', "benchmark.add_estimator(NaiveForecaster(strategy='drift'))", "benchmark._add_task('aeon.benchmarking.tests.test_benchmarks:factory_estimator_class_task')", 'results_file', '=', 'tmp_path', '/', "'results.csv'", 'resul...
399,188
Megvii-BaseDetection/cvpods
mobilenet.py
make_stage
make_stage
Create a mobilenetv2 stage by creating many blocks.
[ "Create", "a", "mobilenetv2", "stage", "by", "creating", "many", "blocks." ]
def make_stage(num_blocks, input_channels, output_channels, stride, expand_ratio, norm, activation): blocks = [] blocks.append(InvertedResBlock(input_channels, output_channels, stride=stride, expand_ratio=expand_ratio, norm=norm, activation=activation, use_shortcut=False)) for i in range(num_blocks - 1): ...
['def', 'make_stage(num_blocks,', 'input_channels,', 'output_channels,', 'stride,', 'expand_ratio,', 'norm,', 'activation):', 'blocks', '=', '[]', 'blocks.append(InvertedResBlock(input_channels,', 'output_channels,', 'stride=stride,', 'expand_ratio=expand_ratio,', 'norm=norm,', 'activation=activation,', 'use_shortcut=F...
522,945
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
mtf_image_transformer.py
MtfImageTransformer.create_positional_emb_2d
create_positional_emb_2d
Learned 2d positional embedding for images.
[ "Learned", "2d", "positional", "embedding", "for", "images." ]
def create_positional_emb_2d(self, targets, max_length_dim, model_dim): mesh = targets.mesh hparams = self._hparams activation_dtype = self.set_activation_type() rows_dim = mtf.Dimension('rows', hparams.img_len) cols_dim = mtf.Dimension('cols', hparams.img_len * hparams.num_channels) positional_...
['def', 'create_positional_emb_2d(self,', 'targets,', 'max_length_dim,', 'model_dim):', 'mesh', '=', 'targets.mesh', 'hparams', '=', 'self._hparams', 'activation_dtype', '=', 'self.set_activation_type()', 'rows_dim', '=', "mtf.Dimension('rows',", 'hparams.img_len)', 'cols_dim', '=', "mtf.Dimension('cols',", 'hparams.im...
965,532
sktime/sktime
test_fh.py
test_empty_range_in_fh
test_empty_range_in_fh
Test when ``range`` has zero length.
[ "Test", "when", "``range``", "has", "zero", "length." ]
def test_empty_range_in_fh(): empty_range = ForecastingHorizon(values=range(-5)) assert (empty_range == ForecastingHorizon(values=[])).all()
['def', 'test_empty_range_in_fh():', 'empty_range', '=', 'ForecastingHorizon(values=range(-5))', 'assert', '(empty_range', '==', 'ForecastingHorizon(values=[])).all()']
877,180
arshpreetsingh/quantopian-machinelearning
frontend_widget.py
FrontendHighlighter.rehighlightBlock
rehighlightBlock
Reimplemented to temporarily enable highlighting if disabled.
[ "Reimplemented", "to", "temporarily", "enable", "highlighting", "if", "disabled." ]
def rehighlightBlock(self, block): old = self.highlighting_on self.highlighting_on = True super(FrontendHighlighter, self).rehighlightBlock(block) self.highlighting_on = old
['def', 'rehighlightBlock(self,', 'block):', 'old', '=', 'self.highlighting_on', 'self.highlighting_on', '=', 'True', 'super(FrontendHighlighter,', 'self).rehighlightBlock(block)', 'self.highlighting_on', '=', 'old']
892,873
lhotse-speech/lhotse
stcmds.py
stcmds
stcmds
Stcmds ASR data preparation.
[ "Stcmds", "ASR", "data", "preparation." ]
def stcmds(corpus_dir: Pathlike, output_dir: Pathlike): prepare_stcmds(corpus_dir, output_dir=output_dir)
['def', 'stcmds(corpus_dir:', 'Pathlike,', 'output_dir:', 'Pathlike):', 'prepare_stcmds(corpus_dir,', 'output_dir=output_dir)']
600,628
deon-gracias/artificial-intelligence-practicals
node.py
Node.child_node
child_node
Get the child node from applying the given action.
[ "Get", "the", "child", "node", "from", "applying", "the", "given", "action." ]
def child_node(self, problem, action): next_node = problem.result(self.state, action) return Node(next_node, self, action)
['def', 'child_node(self,', 'problem,', 'action):', 'next_node', '=', 'problem.result(self.state,', 'action)', 'return', 'Node(next_node,', 'self,', 'action)']
91,349
Ikomia-dev/IkomiaApi
datadictIO.py
DataDictIO.save
save
Save data dict as JSON.
[ "Save", "data", "dict", "as", "JSON." ]
def save(self, path): with open(path, 'w') as outfile: json.dump(self.data, outfile)
['def', 'save(self,', 'path):', 'with', 'open(path,', "'w')", 'as', 'outfile:', 'json.dump(self.data,', 'outfile)']
598,668
43Carrig/recurrent_neural_networks_practice
conversion.py
node_to_graph
node_to_graph
Convert Python code to equivalent TF graph mode code.
[ "Convert", "Python", "code", "to", "equivalent", "TF", "graph", "mode", "code." ]
def node_to_graph(node, context, rewrite_errors=True): node = converter.standard_analysis(node, context, is_initial=True) context.info.source_code = None node = converter.apply_(node, context, decorators) node = converter.apply_(node, context, directives) node = converter.apply_(node, context, break...
['def', 'node_to_graph(node,', 'context,', 'rewrite_errors=True):', 'node', '=', 'converter.standard_analysis(node,', 'context,', 'is_initial=True)', 'context.info.source_code', '=', 'None', 'node', '=', 'converter.apply_(node,', 'context,', 'decorators)', 'node', '=', 'converter.apply_(node,', 'context,', 'directives)...
312,359
microsoft/nni
data.py
get_buckets
get_buckets
Get bucket by length.
[ "Get", "bucket", "by", "length." ]
def get_buckets(min_length, max_length, bucket_count): if bucket_count <= 0: return [max_length] unit_length = int((max_length - min_length) // bucket_count) buckets = [min_length + unit_length * (i + 1) for i in range(0, bucket_count)] buckets[-1] = max_length return buckets
['def', 'get_buckets(min_length,', 'max_length,', 'bucket_count):', 'if', 'bucket_count', '<=', '0:', 'return', '[max_length]', 'unit_length', '=', 'int((max_length', '-', 'min_length)', '//', 'bucket_count)', 'buckets', '=', '[min_length', '+', 'unit_length', '*', '(i', '+', '1)', 'for', 'i', 'in', 'range(0,', 'bucket...
728,047
thaines/helit
model.py
Model.getSample
getSample
Returns the sample associated with the given index.
[ "Returns", "the", "sample", "associated", "with", "the", "given", "index." ]
def getSample(self, s): return self.sample[s]
['def', 'getSample(self,', 's):', 'return', 'self.sample[s]']
591,460
hamza-murad/AALU
compare_comply_v1.py
Contexts.from_dict
from_dict
Initialize a Contexts object from a json dictionary.
[ "Initialize", "a", "Contexts", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'Contexts': args = {} valid_keys = ['text', 'location'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class Contexts: ' + ', '.join(bad_keys)) if 'text' in _dict: args['tex...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'Contexts':", 'args', '=', '{}', 'valid_keys', '=', "['text',", "'location']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Contexts:', "'...
5,370
open-mmlab/mmsegmentation
amg.py
rle_to_mask
rle_to_mask
Compute a binary mask from an uncompressed RLE.
[ "Compute", "a", "binary", "mask", "from", "an", "uncompressed", "RLE." ]
def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: (h, w) = rle['size'] mask = np.empty(h * w, dtype=bool) idx = 0 parity = False for count in rle['counts']: mask[idx:idx + count] = parity idx += count parity ^= True mask = mask.reshape(w, h) return mask.transpose()
['def', 'rle_to_mask(rle:', 'Dict[str,', 'Any])', '->', 'np.ndarray:', '(h,', 'w)', '=', "rle['size']", 'mask', '=', 'np.empty(h', '*', 'w,', 'dtype=bool)', 'idx', '=', '0', 'parity', '=', 'False', 'for', 'count', 'in', "rle['counts']:", 'mask[idx:idx', '+', 'count]', '=', 'parity', 'idx', '+=', 'count', 'parity', '^='...
625,576
sunishsheth2009/ChatterBot
debug.py
ProcessedTraceback.render_as_text
render_as_text
Return a string with the traceback.
[ "Return", "a", "string", "with", "the", "traceback." ]
def render_as_text(self, limit=None): lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip()
['def', 'render_as_text(self,', 'limit=None):', 'lines', '=', 'traceback.format_exception(self.exc_type,', 'self.exc_value,', 'self.frames[0],', 'limit=limit)', 'return', "''.join(lines).rstrip()"]
478,988
MegEngine/Transfer-Learning-Library
dst.py
shift_log
shift_log
First shift, then calculate log for numerical stability.
[ "First", "shift,", "then", "calculate", "log", "for", "numerical", "stability." ]
def shift_log(x, offset=1e-06): return torch.log(torch.clamp(x + offset, max=1.0))
['def', 'shift_log(x,', 'offset=1e-06):', 'return', 'torch.log(torch.clamp(x', '+', 'offset,', 'max=1.0))']
921,223
jason718/game-feature-learning
tools.py
SimpleTransformer.set_mean
set_mean
Set the mean to subtract for centering the data.
[ "Set", "the", "mean", "to", "subtract", "for", "centering", "the", "data." ]
def set_mean(self, mean): self.mean = mean
['def', 'set_mean(self,', 'mean):', 'self.mean', '=', 'mean']
199,445
gunthercox/ChatterBot
interfaces.py
MapperProperty.create_row_processor
create_row_processor
Return a 3-tuple consisting of three row processing functions.
[ "Return", "a", "3-tuple", "consisting", "of", "three", "row", "processing", "functions." ]
def create_row_processor(self, context, path, reduced_path, mapper, row, adapter): return (None, None, None)
['def', 'create_row_processor(self,', 'context,', 'path,', 'reduced_path,', 'mapper,', 'row,', 'adapter):', 'return', '(None,', 'None,', 'None)']
481,366
cslu-nlp/nlup
perceptron.py
Perceptron.predict
predict
Predicts most likely class for a feature vector.
[ "Predicts", "most", "likely", "class", "for", "a", "feature", "vector." ]
def predict(self, phi): scores = self.scores(phi) (argmax_score, _) = max(scores.items(), key=itemgetter(1)) return argmax_score
['def', 'predict(self,', 'phi):', 'scores', '=', 'self.scores(phi)', '(argmax_score,', '_)', '=', 'max(scores.items(),', 'key=itemgetter(1))', 'return', 'argmax_score']
731,728
kubeflow/pipelines
pipeline_with_nested_conditions_yaml.py
random_num_op
random_num_op
Generate a random number between low and high.
[ "Generate", "a", "random", "number", "between", "low", "and", "high." ]
def random_num_op(low, high): return components.load_component_from_text('\n name: Generate random number\n outputs:\n - {name: output, type: Integer}\n implementation:\n container:\n image: python:alpine3.6\n command:\n - sh\n - -c\n args:\n ...
['def', 'random_num_op(low,', 'high):', 'return', "components.load_component_from_text('\\n", 'name:', 'Generate', 'random', 'number\\n', 'outputs:\\n', '-', '{name:', 'output,', 'type:', 'Integer}\\n', 'implementation:\\n', 'container:\\n', 'image:', 'python:alpine3.6\\n', 'command:\\n', '-', 'sh\\n', '-', '-c\\n', 'a...
780,336
43Carrig/recurrent_neural_networks_practice
stats_ops.py
FertileStatsVariableSavable.restore
restore
Restores the associated tree from 'restored_tensors'.
[ "Restores", "the", "associated", "tree", "from", "'restored_tensors'." ]
def restore(self, restored_tensors, unused_restored_shapes): with ops.control_dependencies([self._create_op]): return gen_stats_ops.fertile_stats_deserialize(self._stats_handle, restored_tensors[0], params=self.params.serialized_params_proto)
['def', 'restore(self,', 'restored_tensors,', 'unused_restored_shapes):', 'with', 'ops.control_dependencies([self._create_op]):', 'return', 'gen_stats_ops.fertile_stats_deserialize(self._stats_handle,', 'restored_tensors[0],', 'params=self.params.serialized_params_proto)']
335,375
aimclub/FEDOT
base_cache_db.py
BaseCacheDB.reset
reset
Drops all scores from working table and resets efficiency table values to zero.
[ "Drops", "all", "scores", "from", "working", "table", "and", "resets", "efficiency", "table", "values", "to", "zero." ]
def reset(self): with closing(sqlite3.connect(self.db_path)) as conn: with conn: cur = conn.cursor() if self.use_stats: self._reset_eff(cur) self._reset_main(cur)
['def', 'reset(self):', 'with', 'closing(sqlite3.connect(self.db_path))', 'as', 'conn:', 'with', 'conn:', 'cur', '=', 'conn.cursor()', 'if', 'self.use_stats:', 'self._reset_eff(cur)', 'self._reset_main(cur)']
545,618
shankyb9/College-Information-Chatbot-System
Utils.py
sentences
sentences
Split the string s into a list of sentences.
[ "Split", "the", "string", "s", "into", "a", "list", "of", "sentences." ]
def sentences(s): try: s + '' except: raise TypeError('s must be a string') pos = 0 sentenceList = [] l = len(s) while pos < l: try: q = s.index('?', pos) except: q = l + 1 try: e = s.index('!', pos) except: ...
['def', 'sentences(s):', 'try:', 's', '+', "''", 'except:', 'raise', "TypeError('s", 'must', 'be', 'a', "string')", 'pos', '=', '0', 'sentenceList', '=', '[]', 'l', '=', 'len(s)', 'while', 'pos', '<', 'l:', 'try:', 'q', '=', "s.index('?',", 'pos)', 'except:', 'q', '=', 'l', '+', '1', 'try:', 'e', '=', "s.index('!',", '...
125,053
Ruturaj123/Flowchart-Detection
variable_scope.py
VariableScope.reuse_variables
reuse_variables
Reuse variables in this scope.
[ "Reuse", "variables", "in", "this", "scope." ]
def reuse_variables(self): self._reuse = True
['def', 'reuse_variables(self):', 'self._reuse', '=', 'True']
606,199
Jittor/JDet
representation.py
Representation.is_trivial
is_trivial
Whether this representation is trivial or not.
[ "Whether", "this", "representation", "is", "trivial", "or", "not." ]
def is_trivial(self) -> bool: return self.irreducible and self.group.trivial_representation.name == self.irreps[0]
['def', 'is_trivial(self)', '->', 'bool:', 'return', 'self.irreducible', 'and', 'self.group.trivial_representation.name', '==', 'self.irreps[0]']
577,850
google-research/scenic
dataset_utils.py
add_image_and_boxes
add_image_and_boxes
Same as add_image with additional support boxes.
[ "Same", "as", "add_image", "with", "additional", "support", "boxes." ]
def add_image_and_boxes(parser_builder: builders.BaseParserBuilder, sampler_builder: builders.SamplerBuilder, decoder_builder: builders.DecoderBuilder, preprocessor_builder: builders.PreprocessorBuilder, postprocessor_builder: builders.PostprocessorBuilder, input_feature_name: str='image/encoded', output_feature_name: ...
['def', 'add_image_and_boxes(parser_builder:', 'builders.BaseParserBuilder,', 'sampler_builder:', 'builders.SamplerBuilder,', 'decoder_builder:', 'builders.DecoderBuilder,', 'preprocessor_builder:', 'builders.PreprocessorBuilder,', 'postprocessor_builder:', 'builders.PostprocessorBuilder,', 'input_feature_name:', "str=...
847,107
rifqind/Agent-Programs-3KS1
mask_test.py
MaskTypeTest.test_set_at__default_value
test_set_at__default_value
Ensure individual mask bits are set using the default value.
[ "Ensure", "individual", "mask", "bits", "are", "set", "using", "the", "default", "value." ]
def test_set_at__default_value(self): (width, height) = (3, 21) mask0 = pygame.mask.Mask((width, height)) mask1 = pygame.mask.Mask((width, height), fill=True) mask0_expected_count = 1 mask1_expected_count = mask1.count() expected_bit = 1 pos = (width - 1, height - 1) mask0.set_at(pos) ...
['def', 'test_set_at__default_value(self):', '(width,', 'height)', '=', '(3,', '21)', 'mask0', '=', 'pygame.mask.Mask((width,', 'height))', 'mask1', '=', 'pygame.mask.Mask((width,', 'height),', 'fill=True)', 'mask0_expected_count', '=', '1', 'mask1_expected_count', '=', 'mask1.count()', 'expected_bit', '=', '1', 'pos',...
45,812
microsoft/InnerEye-DeepLearning
run_ml.py
MLRunner.is_normal_run_or_crossval_child_0
is_normal_run_or_crossval_child_0
Returns True if the present run is a non-crossvalidation run, or child run 0 of a crossvalidation run.
[ "Returns", "True", "if", "the", "present", "run", "is", "a", "non-crossvalidation", "run,", "or", "child", "run", "0", "of", "a", "crossvalidation", "run." ]
def is_normal_run_or_crossval_child_0(self) -> bool: if self.container.perform_cross_validation: return self.container.cross_validation_split_index == 0 return True
['def', 'is_normal_run_or_crossval_child_0(self)', '->', 'bool:', 'if', 'self.container.perform_cross_validation:', 'return', 'self.container.cross_validation_split_index', '==', '0', 'return', 'True']
613,067
ratschlab/dpsom
somvae_model.py
SOMVAE.z_q
z_q
Aggregates the respective closest embedding for every encoding.
[ "Aggregates", "the", "respective", "closest", "embedding", "for", "every", "encoding." ]
def z_q(self): k_1 = self.k // self.som_dim[1] k_2 = self.k % self.som_dim[1] k_stacked = tf.stack([k_1, k_2], axis=1) z_q = tf.gather_nd(self.embeddings, k_stacked) return z_q
['def', 'z_q(self):', 'k_1', '=', 'self.k', '//', 'self.som_dim[1]', 'k_2', '=', 'self.k', '%', 'self.som_dim[1]', 'k_stacked', '=', 'tf.stack([k_1,', 'k_2],', 'axis=1)', 'z_q', '=', 'tf.gather_nd(self.embeddings,', 'k_stacked)', 'return', 'z_q']
167,018
jimtin/Stock_Comparison
frontend_widget.py
FrontendWidget.copy_raw
copy_raw
Copy the currently selected text to the clipboard without attempting to remove prompts or otherwise alter the text.
[ "Copy", "the", "currently", "selected", "text", "to", "the", "clipboard", "without", "attempting", "to", "remove", "prompts", "or", "otherwise", "alter", "the", "text." ]
def copy_raw(self): self._control.copy()
['def', 'copy_raw(self):', 'self._control.copy()']
358,561
thaines/helit
line_overlay_layer.py
LineOverlayLayer.get_line
get_line
Returns the LineGraph object being rendered, or None if there is none.
[ "Returns", "the", "LineGraph", "object", "being", "rendered,", "or", "None", "if", "there", "is", "none." ]
def get_line(self): return self.line
['def', 'get_line(self):', 'return', 'self.line']
591,993
acutesoftware/AIKIF
cls_context.py
where_am_i
where_am_i
high level function that can estimate where user is based on predefined setups.
[ "high", "level", "function", "that", "can", "estimate", "where", "user", "is", "based", "on", "predefined", "setups." ]
def where_am_i(): locations = {'Work': 0, 'Home': 0} for ssid in scan_for_ssids(): for l in logged_ssids: if l['name'] == ssid: locations[l['location']] += 1 print('Where Am I: SSIDS Matching Home = ', locations['Home'], ' SSIDs matching Work = ', locations['Work']) r...
['def', 'where_am_i():', 'locations', '=', "{'Work':", '0,', "'Home':", '0}', 'for', 'ssid', 'in', 'scan_for_ssids():', 'for', 'l', 'in', 'logged_ssids:', 'if', "l['name']", '==', 'ssid:', "locations[l['location']]", '+=', '1', "print('Where", 'Am', 'I:', 'SSIDS', 'Matching', 'Home', '=', "',", "locations['Home'],", "'...
85,806
google/deepvariant
testdata.py
init
init
Initialize global variables from flag values.
[ "Initialize", "global", "variables", "from", "flag", "values." ]
def init(): global CHR20_FASTA global CHR20_BAM global CHR20_BAM_FIRST_HALF global CHR20_BAM_SECOND_HALF global NOCHR20_BAM global CHR20_CRAM global GOLDEN_TRAINING_EXAMPLES global GOLDEN_CALLING_CANDIDATES global GOLDEN_CANDIDATE_POSITIONS global GOLDEN_CALLING_EXAMPLES glob...
['def', 'init():', 'global', 'CHR20_FASTA', 'global', 'CHR20_BAM', 'global', 'CHR20_BAM_FIRST_HALF', 'global', 'CHR20_BAM_SECOND_HALF', 'global', 'NOCHR20_BAM', 'global', 'CHR20_CRAM', 'global', 'GOLDEN_TRAINING_EXAMPLES', 'global', 'GOLDEN_CALLING_CANDIDATES', 'global', 'GOLDEN_CANDIDATE_POSITIONS', 'global', 'GOLDEN_...
540,441