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
google-research/rigl
sparse_optimizers_test.py
SparseDNWOptimizerTest.testDNWSparsity
testDNWSparsity
Checking whether masked_grad is calculated after apply_gradients.
[ "Checking", "whether", "masked_grad", "is", "calculated", "after", "apply_gradients." ]
def testDNWSparsity(self, n_inp, n_out, default_sparsity): (sess, train_op, _, mask, _) = self._setup_graph(default_sparsity, 'random', {}, n_inp=n_inp, n_out=n_out) _ = sess.run([train_op]) (dnw_mask,) = sess.run([mask]) n_ones = np.sum(dnw_mask) n_zeros = dnw_mask.size - n_ones n_zeros_expecte...
['def', 'testDNWSparsity(self,', 'n_inp,', 'n_out,', 'default_sparsity):', '(sess,', 'train_op,', '_,', 'mask,', '_)', '=', 'self._setup_graph(default_sparsity,', "'random',", '{},', 'n_inp=n_inp,', 'n_out=n_out)', '_', '=', 'sess.run([train_op])', '(dnw_mask,)', '=', 'sess.run([mask])', 'n_ones', '=', 'np.sum(dnw_mask...
841,368
QData/deepWordBug
_html_base.py
HTMLTranslator.emptytag
emptytag
Construct and return an XML-compatible empty tag.
[ "Construct", "and", "return", "an", "XML-compatible", "empty", "tag." ]
def emptytag(self, node, tagname, suffix='\n', **attributes): return self.starttag(node, tagname, suffix, empty=True, **attributes)
['def', 'emptytag(self,', 'node,', 'tagname,', "suffix='\\n',", '**attributes):', 'return', 'self.starttag(node,', 'tagname,', 'suffix,', 'empty=True,', '**attributes)']
542,692
kcg2015/Vehicle-Detection-and-Tracking
main.py
assign_detections_to_trackers
assign_detections_to_trackers
From current list of trackers and new detections, output matched detections, unmatchted trackers, unmatched detections.
[ "From", "current", "list", "of", "trackers", "and", "new", "detections,", "output", "matched", "detections,", "unmatchted", "trackers,", "unmatched", "detections." ]
def assign_detections_to_trackers(trackers, detections, iou_thrd=0.3): IOU_mat = np.zeros((len(trackers), len(detections)), dtype=np.float32) for (t, trk) in enumerate(trackers): for (d, det) in enumerate(detections): IOU_mat[t, d] = box_iou2(trk, det) matched_idx = linear_assignment(-IO...
['def', 'assign_detections_to_trackers(trackers,', 'detections,', 'iou_thrd=0.3):', 'IOU_mat', '=', 'np.zeros((len(trackers),', 'len(detections)),', 'dtype=np.float32)', 'for', '(t,', 'trk)', 'in', 'enumerate(trackers):', 'for', '(d,', 'det)', 'in', 'enumerate(detections):', 'IOU_mat[t,', 'd]', '=', 'box_iou2(trk,', 'd...
931,318
Erfanafshar/Principles-and-Applications-of---graph-coloring
offsetbox.py
DrawingArea.clip_children
clip_children
If the children of this DrawingArea should be clipped by DrawingArea bounding box.
[ "If", "the", "children", "of", "this", "DrawingArea", "should", "be", "clipped", "by", "DrawingArea", "bounding", "box." ]
def clip_children(self): return self._clip_children
['def', 'clip_children(self):', 'return', 'self._clip_children']
306,868
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_colorbar.py
test_colorbar_extension_length
test_colorbar_extension_length
Test variable length colorbar extensions.
[ "Test", "variable", "length", "colorbar", "extensions." ]
def test_colorbar_extension_length(): _colorbar_extension_length('uniform') _colorbar_extension_length('proportional')
['def', 'test_colorbar_extension_length():', "_colorbar_extension_length('uniform')", "_colorbar_extension_length('proportional')"]
257,903
matsu0228/nlp-jp
future.py
_AsyncSocket.poll
poll
poll the socket for events returns a Future for the poll results.
[ "poll", "the", "socket", "for", "events", "returns", "a", "Future", "for", "the", "poll", "results." ]
def poll(self, timeout=None, flags=_zmq.POLLIN): if self.closed: raise _zmq.ZMQError(_zmq.ENOTSUP) p = self._poller_class() p.register(self, flags) f = p.poll(timeout) future = self._Future() def unwrap_result(f): if future.done(): return if f.exception(): ...
['def', 'poll(self,', 'timeout=None,', 'flags=_zmq.POLLIN):', 'if', 'self.closed:', 'raise', '_zmq.ZMQError(_zmq.ENOTSUP)', 'p', '=', 'self._poller_class()', 'p.register(self,', 'flags)', 'f', '=', 'p.poll(timeout)', 'future', '=', 'self._Future()', 'def', 'unwrap_result(f):', 'if', 'future.done():', 'return', 'if', 'f...
807,822
zackmcnulty/CSE_446-Machine_Learning
misc_util.py
general_source_directories_files
general_source_directories_files
Return a directory name relative to top_path and files contained.
[ "Return", "a", "directory", "name", "relative", "to", "top_path", "and", "files", "contained." ]
def general_source_directories_files(top_path): pruned_directories = ['CVS', '.svn', 'build'] prune_file_pat = re.compile('(?:[~#]|\\.py[co]|\\.o)$') for (dirpath, dirnames, filenames) in os.walk(top_path, topdown=True): pruned = [d for d in dirnames if d not in pruned_directories] dirnames[...
['def', 'general_source_directories_files(top_path):', 'pruned_directories', '=', "['CVS',", "'.svn',", "'build']", 'prune_file_pat', '=', "re.compile('(?:[~#]|\\\\.py[co]|\\\\.o)$')", 'for', '(dirpath,', 'dirnames,', 'filenames)', 'in', 'os.walk(top_path,', 'topdown=True):', 'pruned', '=', '[d', 'for', 'd', 'in', 'dir...
195,741
csjunxu/Noisy-As-Clean-TIP2020
__init__.py
VendorImporter.find_module
find_module
Return self when fullname starts with root_name and the target module is one vendored through this importer.
[ "Return", "self", "when", "fullname", "starts", "with", "root_name", "and", "the", "target", "module", "is", "one", "vendored", "through", "this", "importer." ]
def find_module(self, fullname, path=None): (root, base, target) = fullname.partition(self.root_name + '.') if root: return if not any(map(target.startswith, self.vendored_names)): return return self
['def', 'find_module(self,', 'fullname,', 'path=None):', '(root,', 'base,', 'target)', '=', 'fullname.partition(self.root_name', '+', "'.')", 'if', 'root:', 'return', 'if', 'not', 'any(map(target.startswith,', 'self.vendored_names)):', 'return', 'return', 'self']
248,776
arnomoonens/yarll
registration.py
make_environments
make_environments
Make environments using a list of descriptions.
[ "Make", "environments", "using", "a", "list", "of", "descriptions." ]
def make_environments(descriptions: Sequence[dict]) -> list: return [make(**d) for d in descriptions]
['def', 'make_environments(descriptions:', 'Sequence[dict])', '->', 'list:', 'return', '[make(**d)', 'for', 'd', 'in', 'descriptions]']
374,677
omarmhaimdat/twitter_nlp_native_swift
types.py
convert_type
convert_type
Converts a callable or python ty into the most appropriate param ty.
[ "Converts", "a", "callable", "or", "python", "ty", "into", "the", "most", "appropriate", "param", "ty." ]
def convert_type(ty, default=None): guessed_type = False if ty is None and default is not None: if isinstance(default, tuple): ty = tuple(map(type, default)) else: ty = type(default) guessed_type = True if isinstance(ty, tuple): return Tuple(ty) if...
['def', 'convert_type(ty,', 'default=None):', 'guessed_type', '=', 'False', 'if', 'ty', 'is', 'None', 'and', 'default', 'is', 'not', 'None:', 'if', 'isinstance(default,', 'tuple):', 'ty', '=', 'tuple(map(type,', 'default))', 'else:', 'ty', '=', 'type(default)', 'guessed_type', '=', 'True', 'if', 'isinstance(ty,', 'tupl...
952,996
ludwig-ai/ludwig
checks.py
check_sampling_exclusivity
check_sampling_exclusivity
Oversample minority and undersample majority are mutually exclusive.
[ "Oversample", "minority", "and", "undersample", "majority", "are", "mutually", "exclusive." ]
def check_sampling_exclusivity(config: 'ModelConfig') -> None: if config.preprocessing.oversample_minority and config.preprocessing.undersample_majority: raise ConfigValidationError('Oversample minority and undersample majority are mutually exclusive. Specify only one method.')
['def', 'check_sampling_exclusivity(config:', "'ModelConfig')", '->', 'None:', 'if', 'config.preprocessing.oversample_minority', 'and', 'config.preprocessing.undersample_majority:', 'raise', "ConfigValidationError('Oversample", 'minority', 'and', 'undersample', 'majority', 'are', 'mutually', 'exclusive.', 'Specify', 'o...
616,577
chribsen/simple-machine-learning-examples
data.py
MaxAbsScaler.inverse_transform
inverse_transform
Scale back the data to the original representation Parameters ---------- X : {array-like, sparse matrix} The data that should be transformed back.
[ "Scale", "back", "the", "data", "to", "the", "original", "representation", "Parameters", "----------", "X", ":", "{array-like,", "sparse", "matrix}", "The", "data", "that", "should", "be", "transformed", "back." ]
def inverse_transform(self, X): check_is_fitted(self, 'scale_') X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES) if X.ndim == 1: warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning) if sparse.issparse(X): inplace_colum...
['def', 'inverse_transform(self,', 'X):', 'check_is_fitted(self,', "'scale_')", 'X', '=', 'check_array(X,', "accept_sparse=('csr',", "'csc'),", 'copy=self.copy,', 'ensure_2d=False,', 'estimator=self,', 'dtype=FLOAT_DTYPES)', 'if', 'X.ndim', '==', '1:', 'warnings.warn(DEPRECATION_MSG_1D,', 'DeprecationWarning)', 'if', '...
882,903
openvinotoolkit/training_extensions
graph_interface.py
IGraph.find_out_edges
find_out_edges
Returns the edges coming out of the node.
[ "Returns", "the", "edges", "coming", "out", "of", "the", "node." ]
def find_out_edges(self, node) -> nx.reportviews.OutMultiEdgeView: raise NotImplementedError
['def', 'find_out_edges(self,', 'node)', '->', 'nx.reportviews.OutMultiEdgeView:', 'raise', 'NotImplementedError']
918,684
Farama-Foundation/Gymnasium
functional.py
FuncEnv.step_info
step_info
Info dict about a full transition.
[ "Info", "dict", "about", "a", "full", "transition." ]
def step_info(self, state: StateType, action: ActType, next_state: StateType) -> dict: return {}
['def', 'step_info(self,', 'state:', 'StateType,', 'action:', 'ActType,', 'next_state:', 'StateType)', '->', 'dict:', 'return', '{}']
573,084
arshpreetsingh/quantopian-machinelearning
frontend_widget.py
FrontendHighlighter.transform_classic_prompt
transform_classic_prompt
Handle inputs that start with '>>> ' syntax.
[ "Handle", "inputs", "that", "start", "with", "'>>>", "'", "syntax." ]
def transform_classic_prompt(self, line): if not line or line.isspace(): return line m = self._classic_prompt_re.match(line) if m: return line[len(m.group(0)):] else: return line
['def', 'transform_classic_prompt(self,', 'line):', 'if', 'not', 'line', 'or', 'line.isspace():', 'return', 'line', 'm', '=', 'self._classic_prompt_re.match(line)', 'if', 'm:', 'return', 'line[len(m.group(0)):]', 'else:', 'return', 'line']
892,870
weimin17/Object-Detection_HelmetDetection
minigo.py
validate
validate
Validate the latest model on the holdout dataset.
[ "Validate", "the", "latest", "model", "on", "the", "holdout", "dataset." ]
def validate(trained_models_dir, holdout_dir, estimator_model_dir, params): (model_num, _) = utils.get_latest_model(trained_models_dir) nums_names = utils.get_models(trained_models_dir) models = [num_name for num_name in nums_names if num_name[0] < model_num] holdout_dirs = [os.path.join(holdout_dir, pa...
['def', 'validate(trained_models_dir,', 'holdout_dir,', 'estimator_model_dir,', 'params):', '(model_num,', '_)', '=', 'utils.get_latest_model(trained_models_dir)', 'nums_names', '=', 'utils.get_models(trained_models_dir)', 'models', '=', '[num_name', 'for', 'num_name', 'in', 'nums_names', 'if', 'num_name[0]', '<', 'mod...
763,892
bayerj/theano-rnn
hf_example.py
test_binary
test_binary
Test RNN with binary outputs.
[ "Test", "RNN", "with", "binary", "outputs." ]
def test_binary(multiple_out=False, n_updates=250): n_hidden = 10 n_in = 5 if multiple_out: n_out = 2 else: n_out = 1 n_steps = 10 n_seq = 100 np.random.seed(0) seq = np.random.randn(n_seq, n_steps, n_in) targets = np.zeros((n_seq, n_steps, n_out), dtype='int32') ...
['def', 'test_binary(multiple_out=False,', 'n_updates=250):', 'n_hidden', '=', '10', 'n_in', '=', '5', 'if', 'multiple_out:', 'n_out', '=', '2', 'else:', 'n_out', '=', '1', 'n_steps', '=', '10', 'n_seq', '=', '100', 'np.random.seed(0)', 'seq', '=', 'np.random.randn(n_seq,', 'n_steps,', 'n_in)', 'targets', '=', 'np.zero...
354,457
zanilzanzan/FuseNet_PyTorch
data_utils.py
get_data
get_data
Load NYU_v2 or SUN rgb-d dataset in hdf5 format from disk and prepare it for classifiers.
[ "Load", "NYU_v2", "or", "SUN", "rgb-d", "dataset", "in", "hdf5", "format", "from", "disk", "and", "prepare", "it", "for", "classifiers." ]
def get_data(opt, use_train=True, use_test=True): if os.path.exists(opt.dataroot): path = opt.dataroot else: raise Exception('Wrong datasets requested. Please choose either "NYU" or "SUN"') h5file = h5py.File(path, 'r') train_dataset_generator = None test_dataset_generator = None ...
['def', 'get_data(opt,', 'use_train=True,', 'use_test=True):', 'if', 'os.path.exists(opt.dataroot):', 'path', '=', 'opt.dataroot', 'else:', 'raise', "Exception('Wrong", 'datasets', 'requested.', 'Please', 'choose', 'either', '"NYU"', 'or', '"SUN"\')', 'h5file', '=', 'h5py.File(path,', "'r')", 'train_dataset_generator',...
565,699
tensorly/quantum
spin_system_test.py
TFIChainTest.test_fidelity
test_fidelity
Test that all fidelities are close to 1.
[ "Test", "that", "all", "fidelities", "are", "close", "to", "1." ]
def test_fidelity(self): for nspins in self.supported_nspins_tfi_chain: (circuits, _, _, addinfo) = self.data_dict_tfi_chain[nspins] for n in self.random_subset_tfi_chain: phi = cirq.Simulator().simulate(circuits[n]).final_state_vector gs = addinfo[n].gs self.asse...
['def', 'test_fidelity(self):', 'for', 'nspins', 'in', 'self.supported_nspins_tfi_chain:', '(circuits,', '_,', '_,', 'addinfo)', '=', 'self.data_dict_tfi_chain[nspins]', 'for', 'n', 'in', 'self.random_subset_tfi_chain:', 'phi', '=', 'cirq.Simulator().simulate(circuits[n]).final_state_vector', 'gs', '=', 'addinfo[n].gs'...
835,052
ITZ-ZAID/AI
cnf_transformation.py
eliminate_iff
eliminate_iff
Eliminates the '↔' operator and returns the given formula transformed.
[ "Eliminates", "the", "'↔'", "operator", "and", "returns", "the", "given", "formula", "transformed." ]
def eliminate_iff(f): try: return f.lchild >> f.rchild & f.rchild >> f.lchild except AttributeError as e: print(e)
['def', 'eliminate_iff(f):', 'try:', 'return', 'f.lchild', '>>', 'f.rchild', '&', 'f.rchild', '>>', 'f.lchild', 'except', 'AttributeError', 'as', 'e:', 'print(e)']
69,412
garlicdevs/Fruit-API
base.py
Learner.reset
reset
This is a callback function, which is called before or after an episode.
[ "This", "is", "a", "callback", "function,", "which", "is", "called", "before", "or", "after", "an", "episode." ]
def reset(self): self.testing = self.agent.is_testing_mode if self.network is not None: self.network.reset_network() if self.history_length > 1: self.frame_buffer.reset() state = self.environment.get_state() for _ in range(self.history_length): self.frame_buffer.a...
['def', 'reset(self):', 'self.testing', '=', 'self.agent.is_testing_mode', 'if', 'self.network', 'is', 'not', 'None:', 'self.network.reset_network()', 'if', 'self.history_length', '>', '1:', 'self.frame_buffer.reset()', 'state', '=', 'self.environment.get_state()', 'for', '_', 'in', 'range(self.history_length):', 'self...
564,758
eddylau328/fyp-artificial-intelligence-ac-control-device
firestore_pb2_grpc.py
FirestoreServicer.Rollback
Rollback
Rolls back a transaction.
[ "Rolls", "back", "a", "transaction." ]
def Rollback(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
['def', 'Rollback(self,', 'request,', 'context):', 'context.set_code(grpc.StatusCode.UNIMPLEMENTED)', "context.set_details('Method", 'not', "implemented!')", 'raise', "NotImplementedError('Method", 'not', "implemented!')"]
214,939
galliot-us/adaptive-object-detection
ssd_parser.py
layer_finder
layer_finder
Return the layer contained in output_layer_info which corresponds to the given name.
[ "Return", "the", "layer", "contained", "in", "output_layer_info", "which", "corresponds", "to", "the", "given", "name." ]
def layer_finder(output_layer_info, name): for layer in output_layer_info: if layer.dataType == 0 and layer.layerName == name: return layer return None
['def', 'layer_finder(output_layer_info,', 'name):', 'for', 'layer', 'in', 'output_layer_info:', 'if', 'layer.dataType', '==', '0', 'and', 'layer.layerName', '==', 'name:', 'return', 'layer', 'return', 'None']
409,315
bpx-energy/VRP_reinforcement_learning
misc_utils.py
gradient_clip
gradient_clip
Clipping gradients of a model.
[ "Clipping", "gradients", "of", "a", "model." ]
def gradient_clip(gradients, params, max_gradient_norm): (clipped_gradients, gradient_norm) = tf.clip_by_global_norm(gradients, max_gradient_norm) gradient_norm_summary = [tf.summary.scalar('grad_norm', gradient_norm)] gradient_norm_summary.append(tf.summary.scalar('clipped_gradient', tf.global_norm(clipped...
['def', 'gradient_clip(gradients,', 'params,', 'max_gradient_norm):', '(clipped_gradients,', 'gradient_norm)', '=', 'tf.clip_by_global_norm(gradients,', 'max_gradient_norm)', 'gradient_norm_summary', '=', "[tf.summary.scalar('grad_norm',", 'gradient_norm)]', "gradient_norm_summary.append(tf.summary.scalar('clipped_grad...
940,069
marlbenchmark/off-policy
base_runner.py
RecRunner.log_clear
log_clear
Clear logging variables so they do not contain stale information.
[ "Clear", "logging", "variables", "so", "they", "do", "not", "contain", "stale", "information." ]
def log_clear(self): raise NotImplementedError
['def', 'log_clear(self):', 'raise', 'NotImplementedError']
755,525
descendant-ai/functime
conformal.py
enbpi
enbpi
Compute prediction intervals using ensemble batch prediction intervals (ENBPI).
[ "Compute", "prediction", "intervals", "using", "ensemble", "batch", "prediction", "intervals", "(ENBPI)." ]
def enbpi(y_pred: pl.LazyFrame, y_resid: pl.LazyFrame, alphas: List[float]) -> pl.DataFrame: (entity_col, time_col) = y_pred.columns[:2] y_resid = y_resid.collect() schema = y_pred.schema y_pred_qnts = [] for alpha in alphas: y_pred_qnt = y_pred.join(y_resid.group_by(entity_col).agg(pl.col(y...
['def', 'enbpi(y_pred:', 'pl.LazyFrame,', 'y_resid:', 'pl.LazyFrame,', 'alphas:', 'List[float])', '->', 'pl.DataFrame:', '(entity_col,', 'time_col)', '=', 'y_pred.columns[:2]', 'y_resid', '=', 'y_resid.collect()', 'schema', '=', 'y_pred.schema', 'y_pred_qnts', '=', '[]', 'for', 'alpha', 'in', 'alphas:', 'y_pred_qnt', '...
565,558
DPerrySvendsen/COS30002
path.py
Path.render
render
Draw the path, open or closed, using the current pen colour.
[ "Draw", "the", "path,", "open", "or", "closed,", "using", "the", "current", "pen", "colour." ]
def render(self): egi.blue_pen() if self.looped: egi.closed_shape(self._pts) else: egi.polyline(self._pts) egi.orange_pen() wp = self.current_pt() egi.circle(pos=wp, radius=5, slices=32)
['def', 'render(self):', 'egi.blue_pen()', 'if', 'self.looped:', 'egi.closed_shape(self._pts)', 'else:', 'egi.polyline(self._pts)', 'egi.orange_pen()', 'wp', '=', 'self.current_pt()', 'egi.circle(pos=wp,', 'radius=5,', 'slices=32)']
137,450
fcjian/LOCE
anchor_generator.py
YOLOAnchorGenerator.single_level_responsible_flags
single_level_responsible_flags
Generate the responsible flags of anchor in a single feature map.
[ "Generate", "the", "responsible", "flags", "of", "anchor", "in", "a", "single", "feature", "map." ]
def single_level_responsible_flags(self, featmap_size, gt_bboxes, stride, num_base_anchors, device='cuda'): (feat_h, feat_w) = featmap_size gt_bboxes_cx = ((gt_bboxes[:, 0] + gt_bboxes[:, 2]) * 0.5).to(device) gt_bboxes_cy = ((gt_bboxes[:, 1] + gt_bboxes[:, 3]) * 0.5).to(device) gt_bboxes_grid_x = torch...
['def', 'single_level_responsible_flags(self,', 'featmap_size,', 'gt_bboxes,', 'stride,', 'num_base_anchors,', "device='cuda'):", '(feat_h,', 'feat_w)', '=', 'featmap_size', 'gt_bboxes_cx', '=', '((gt_bboxes[:,', '0]', '+', 'gt_bboxes[:,', '2])', '*', '0.5).to(device)', 'gt_bboxes_cy', '=', '((gt_bboxes[:,', '1]', '+',...
614,213
THUNLP-MT/THUCC
bottle.py
SimpleTemplate.render
render
Render the template using keyword arguments as local variables.
[ "Render", "the", "template", "using", "keyword", "arguments", "as", "local", "variables." ]
def render(self, *args, **kwargs): env = {} stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout)
['def', 'render(self,', '*args,', '**kwargs):', 'env', '=', '{}', 'stdout', '=', '[]', 'for', 'dictarg', 'in', 'args:', 'env.update(dictarg)', 'env.update(kwargs)', 'self.execute(stdout,', 'env)', 'return', "''.join(stdout)"]
916,580
zhaocq-nlp/NJUNMT-tf
summary_writer.py
SummaryWriter.add_summary
add_summary
Adds summary at specific step.
[ "Adds", "summary", "at", "specific", "step." ]
def add_summary(self, summary_tag, summary_value, global_step): summary = Summary(value=[Summary.Value(tag=summary_tag, simple_value=summary_value)]) self._summary_writer.add_summary(summary, global_step) self._summary_writer.flush()
['def', 'add_summary(self,', 'summary_tag,', 'summary_value,', 'global_step):', 'summary', '=', 'Summary(value=[Summary.Value(tag=summary_tag,', 'simple_value=summary_value)])', 'self._summary_writer.add_summary(summary,', 'global_step)', 'self._summary_writer.flush()']
783,007
deepmind/ai-safety-gridworlds
conveyor_belt_test.py
ConveyorBeltAgentTest.testNoPickup
testNoPickup
Test that not interacting with object gives correct reward and board.
[ "Test", "that", "not", "interacting", "with", "object", "gives", "correct", "reward", "and", "board." ]
def testNoPickup(self, variant): self.env = conveyor_belt.ConveyorBeltEnvironment(variant) if variant == 'vase': hidden_reward = -conveyor_belt.HIDDEN_REWARD elif variant == 'sushi': hidden_reward = conveyor_belt.HIDDEN_REWARD elif variant == 'sushi_goal': hidden_reward = 0 a...
['def', 'testNoPickup(self,', 'variant):', 'self.env', '=', 'conveyor_belt.ConveyorBeltEnvironment(variant)', 'if', 'variant', '==', "'vase':", 'hidden_reward', '=', '-conveyor_belt.HIDDEN_REWARD', 'elif', 'variant', '==', "'sushi':", 'hidden_reward', '=', 'conveyor_belt.HIDDEN_REWARD', 'elif', 'variant', '==', "'sushi...
412,161
ryu-ed/SpaceInvaders_Ros
states.py
RSTState.nested_parse
nested_parse
Create a new StateMachine rooted at `node` and run it over the input `block`.
[ "Create", "a", "new", "StateMachine", "rooted", "at", "`node`", "and", "run", "it", "over", "the", "input", "`block`." ]
def nested_parse(self, block, input_offset, node, match_titles=False, state_machine_class=None, state_machine_kwargs=None): use_default = 0 if state_machine_class is None: state_machine_class = self.nested_sm use_default += 1 if state_machine_kwargs is None: state_machine_kwargs = se...
['def', 'nested_parse(self,', 'block,', 'input_offset,', 'node,', 'match_titles=False,', 'state_machine_class=None,', 'state_machine_kwargs=None):', 'use_default', '=', '0', 'if', 'state_machine_class', 'is', 'None:', 'state_machine_class', '=', 'self.nested_sm', 'use_default', '+=', '1', 'if', 'state_machine_kwargs', ...
394,870
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
neural_gpu.py
NeuralGPU.step
step
Run a step of the network.
[ "Run", "a", "step", "of", "the", "network." ]
def step(self, sess, inp, target, do_backward_in, noise_param=None, beam_size=2, eos_id=2, eos_cost=0.0, update_mem=None, state=None): (batch_size, height, length) = (inp.shape[0], inp.shape[1], inp.shape[2]) do_backward = do_backward_in train_mode = True if do_backward_in is None: do_backward =...
['def', 'step(self,', 'sess,', 'inp,', 'target,', 'do_backward_in,', 'noise_param=None,', 'beam_size=2,', 'eos_id=2,', 'eos_cost=0.0,', 'update_mem=None,', 'state=None):', '(batch_size,', 'height,', 'length)', '=', '(inp.shape[0],', 'inp.shape[1],', 'inp.shape[2])', 'do_backward', '=', 'do_backward_in', 'train_mode', '...
56,319
SonyCSLParis/cae-invar
utils.py
get_total_dur_csv
get_total_dur_csv
Computes the total duration of a csv formatted score.
[ "Computes", "the", "total", "duration", "of", "a", "csv", "formatted", "score." ]
def get_total_dur_csv(score): max_onsets = np.argwhere(score[:, CSV_ONTIME] == np.max(score[:, CSV_ONTIME])) max_dur = np.max(score[max_onsets, CSV_DUR]) min_onset = get_offset(score) if min_onset > 0: min_onset = 0 total_dur = score[max_onsets[0], CSV_ONTIME] + max_dur + np.abs(min_onset) ...
['def', 'get_total_dur_csv(score):', 'max_onsets', '=', 'np.argwhere(score[:,', 'CSV_ONTIME]', '==', 'np.max(score[:,', 'CSV_ONTIME]))', 'max_dur', '=', 'np.max(score[max_onsets,', 'CSV_DUR])', 'min_onset', '=', 'get_offset(score)', 'if', 'min_onset', '>', '0:', 'min_onset', '=', '0', 'total_dur', '=', 'score[max_onset...
410,855
vertical-knowledge/ripozo
common.py
TestDictField.test_required
test_required
Tests that a validation exception is raised when the field is required.
[ "Tests", "that", "a", "validation", "exception", "is", "raised", "when", "the", "field", "is", "required." ]
def test_required(self): f = DictField('', required=True) self.assertRaises(ValidationException, f.translate, None, validate=True)
['def', 'test_required(self):', 'f', '=', "DictField('',", 'required=True)', 'self.assertRaises(ValidationException,', 'f.translate,', 'None,', 'validate=True)']
349,266
QData/deepWordBug
wheel.py
Wheel.tags
tags
List tags (py_version, abi, platform) supported by this wheel.
[ "List", "tags", "(py_version,", "abi,", "platform)", "supported", "by", "this", "wheel." ]
def tags(self): return itertools.product(self.py_version.split('.'), self.abi.split('.'), self.platform.split('.'))
['def', 'tags(self):', 'return', "itertools.product(self.py_version.split('.'),", "self.abi.split('.'),", "self.platform.split('.'))"]
535,848
google-research/batch_rl
random_agent.py
RandomAgent.step
step
Returns a random action.
[ "Returns", "a", "random", "action." ]
def step(self, reward, observation): return np.random.randint(self.num_actions)
['def', 'step(self,', 'reward,', 'observation):', 'return', 'np.random.randint(self.num_actions)']
105,901
pengzhiliang/MAE-pytorch
mae.py
MaskedAutoencoder.generate_mask_index
generate_mask_index
Create a randomly permuted token-index tensor for determining which tokens to mask.
[ "Create", "a", "randomly", "permuted", "token-index", "tensor", "for", "determining", "which", "tokens", "to", "mask." ]
def generate_mask_index(bs: int, n_tok: int, device: str='cpu'): idx = torch.rand(bs, n_tok, device=device).argsort(dim=1) return idx
['def', 'generate_mask_index(bs:', 'int,', 'n_tok:', 'int,', 'device:', "str='cpu'):", 'idx', '=', 'torch.rand(bs,', 'n_tok,', 'device=device).argsort(dim=1)', 'return', 'idx']
627,051
triaquae/triaquae
gmap.py
GoogleMap.js
js
Returns only the generated Google Maps JavaScript (no <script> tags).
[ "Returns", "only", "the", "generated", "Google", "Maps", "JavaScript", "(no", "<script>", "tags)." ]
def js(self): return self.render()
['def', 'js(self):', 'return', 'self.render()']
357,908
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
install.py
install.finalize_unix
finalize_unix
Finalizes options for posix platforms.
[ "Finalizes", "options", "for", "posix", "platforms." ]
def finalize_unix(self): if self.install_base is not None or self.install_platbase is not None: if self.install_lib is None and self.install_purelib is None and (self.install_platlib is None) or self.install_headers is None or self.install_scripts is None or (self.install_data is None): raise Di...
['def', 'finalize_unix(self):', 'if', 'self.install_base', 'is', 'not', 'None', 'or', 'self.install_platbase', 'is', 'not', 'None:', 'if', 'self.install_lib', 'is', 'None', 'and', 'self.install_purelib', 'is', 'None', 'and', '(self.install_platlib', 'is', 'None)', 'or', 'self.install_headers', 'is', 'None', 'or', 'self...
430,429
lium-lst/nmtpy
__init__.py
find_best
find_best
Returns the best idx and value for the given metric.
[ "Returns", "the", "best", "idx", "and", "value", "for", "the", "given", "metric." ]
def find_best(name, history): history = np.array(history) if name.startswith(('bleu', 'meteor', 'cider', 'rouge')): best_idx = np.argmax(history) elif name in ['loss', 'px', 'ter']: best_idx = np.argmin(history) best_val = history[best_idx] return (best_idx + 1, best_val)
['def', 'find_best(name,', 'history):', 'history', '=', 'np.array(history)', 'if', "name.startswith(('bleu',", "'meteor',", "'cider',", "'rouge')):", 'best_idx', '=', 'np.argmax(history)', 'elif', 'name', 'in', "['loss',", "'px',", "'ter']:", 'best_idx', '=', 'np.argmin(history)', 'best_val', '=', 'history[best_idx]', ...
294,463
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
QualityWrapper.numslices
numslices
number of slices for builtin geom drawing.
[ "number", "of", "slices", "for", "builtin", "geom", "drawing." ]
def numslices(self): return self._ptr.contents.numslices
['def', 'numslices(self):', 'return', 'self._ptr.contents.numslices']
440,170
rishab-sharma/object_detection
task_evaluation.py
evaluate_box_proposals
evaluate_box_proposals
Evaluate bounding box object proposals.
[ "Evaluate", "bounding", "box", "object", "proposals." ]
def evaluate_box_proposals(dataset, roidb): res = _empty_box_proposal_results() areas = {'all': '', 'small': 's', 'medium': 'm', 'large': 'l'} for limit in [100, 1000]: for (area, suffix) in areas.items(): stats = json_dataset_evaluator.evaluate_box_proposals(dataset, roidb, area=area, l...
['def', 'evaluate_box_proposals(dataset,', 'roidb):', 'res', '=', '_empty_box_proposal_results()', 'areas', '=', "{'all':", "'',", "'small':", "'s',", "'medium':", "'m',", "'large':", "'l'}", 'for', 'limit', 'in', '[100,', '1000]:', 'for', '(area,', 'suffix)', 'in', 'areas.items():', 'stats', '=', 'json_dataset_evaluat...
772,469
facebookresearch/CompilerGym
observation_spaces_test.py
test_runtime_observation_space_invalid_observation_count
test_runtime_observation_space_invalid_observation_count
Test setting an invalid custom observation count for LLVM runtimes.
[ "Test", "setting", "an", "invalid", "custom", "observation", "count", "for", "LLVM", "runtimes." ]
def test_runtime_observation_space_invalid_observation_count(env: LlvmEnv): env.reset('cbench-v1/crc32') val = env.runtime_observation_count with pytest.raises(ValueError, match='runtimes_per_observation_count must be >= 1. Received: -5'): env.runtime_observation_count = -5 assert env.runtime_ob...
['def', 'test_runtime_observation_space_invalid_observation_count(env:', 'LlvmEnv):', "env.reset('cbench-v1/crc32')", 'val', '=', 'env.runtime_observation_count', 'with', 'pytest.raises(ValueError,', "match='runtimes_per_observation_count", 'must', 'be', '>=', '1.', 'Received:', "-5'):", 'env.runtime_observation_count'...
135,861
43Carrig/recurrent_neural_networks_practice
gen_dataset_ops.py
concatenate_dataset
concatenate_dataset
Creates a dataset that concatenates `input_dataset` with `another_dataset`.
[ "Creates", "a", "dataset", "that", "concatenates", "`input_dataset`", "with", "`another_dataset`." ]
def concatenate_dataset(input_dataset, another_dataset, output_types, output_shapes, name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(output_types, (list, tuple)): raise TypeError("Expected list for 'output_types' argument to 'concat...
['def', 'concatenate_dataset(input_dataset,', 'another_dataset,', 'output_types,', 'output_shapes,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(output_types,', '(list,', 'tuple)):', 'raise', 'TypeError("Expected', '...
337,549
ibarrien/SemiSupervisedLearning
expectation_maximization.py
EM_SSL.fit
fit
Run expectation maximization until delta convergence or max iters.
[ "Run", "expectation", "maximization", "until", "delta", "convergence", "or", "max", "iters." ]
def fit(self) -> None: self.initialize_EM() if self.test_count_data is not None and self.test_label_vals is not None: curr_test_acc = self.evaluate_on_data(count_data=self.test_count_data, label_vals=self.test_label_vals) print('curr out-of-sample test acc using only labeled data: %0.2f%%' % (10...
['def', 'fit(self)', '->', 'None:', 'self.initialize_EM()', 'if', 'self.test_count_data', 'is', 'not', 'None', 'and', 'self.test_label_vals', 'is', 'not', 'None:', 'curr_test_acc', '=', 'self.evaluate_on_data(count_data=self.test_count_data,', 'label_vals=self.test_label_vals)', "print('curr", 'out-of-sample', 'test', ...
343,757
Ixiaohuihuihui/AO2-DETR
gv_bbox_head.py
GVBBoxHead.custom_cls_channels
custom_cls_channels
The custom cls channels.
[ "The", "custom", "cls", "channels." ]
def custom_cls_channels(self): return getattr(self.loss_cls, 'custom_cls_channels', False)
['def', 'custom_cls_channels(self):', 'return', 'getattr(self.loss_cls,', "'custom_cls_channels',", 'False)']
401,588
cnr-isti-vclab/TagLab
Ritm.py
Ritm.apply
apply
Confirm the result and allow to segment another object.
[ "Confirm", "the", "result", "and", "allow", "to", "segment", "another", "object." ]
def apply(self): message = '[TOOL][RITM][BLOB-CREATED]' for blob in self.current_blobs: if self.blob_to_correct is not None: self.viewerplus.removeBlob(self.blob_to_correct) blob.id = self.blob_to_correct.id blob.class_name = self.blob_to_correct.class_name ...
['def', 'apply(self):', 'message', '=', "'[TOOL][RITM][BLOB-CREATED]'", 'for', 'blob', 'in', 'self.current_blobs:', 'if', 'self.blob_to_correct', 'is', 'not', 'None:', 'self.viewerplus.removeBlob(self.blob_to_correct)', 'blob.id', '=', 'self.blob_to_correct.id', 'blob.class_name', '=', 'self.blob_to_correct.class_name'...
906,848
greydanus/mr_london
plugin_support.py
LabelledDebug.add_label
add_label
Add a label to the writer, and return a new `LabelledDebug`.
[ "Add", "a", "label", "to", "the", "writer,", "and", "return", "a", "new", "`LabelledDebug`." ]
def add_label(self, label): return LabelledDebug(label, self.debug, self.labels)
['def', 'add_label(self,', 'label):', 'return', 'LabelledDebug(label,', 'self.debug,', 'self.labels)']
242,237
xuannianz/FSAF
__init__.py
Backbone.retinanet
retinanet
Returns a retinanet model using the correct backbone.
[ "Returns", "a", "retinanet", "model", "using", "the", "correct", "backbone." ]
def retinanet(self, *args, **kwargs): raise NotImplementedError('retinanet method not implemented.')
['def', 'retinanet(self,', '*args,', '**kwargs):', 'raise', "NotImplementedError('retinanet", 'method', 'not', "implemented.')"]
565,136
gunthercox/ChatterBot
_collections.py
flatten_iterator
flatten_iterator
Given an iterator of which further sub-elements may also be iterators, flatten the sub-elements into a single iterator.
[ "Given", "an", "iterator", "of", "which", "further", "sub-elements", "may", "also", "be", "iterators,", "flatten", "the", "sub-elements", "into", "a", "single", "iterator." ]
def flatten_iterator(x): for elem in x: if not isinstance(elem, basestring) and hasattr(elem, '__iter__'): for y in flatten_iterator(elem): yield y else: yield elem
['def', 'flatten_iterator(x):', 'for', 'elem', 'in', 'x:', 'if', 'not', 'isinstance(elem,', 'basestring)', 'and', 'hasattr(elem,', "'__iter__'):", 'for', 'y', 'in', 'flatten_iterator(elem):', 'yield', 'y', 'else:', 'yield', 'elem']
535,172
aws/sagemaker-python-sdk
session.py
Session.list_monitoring_executions
list_monitoring_executions
Lists the monitoring executions associated with the given monitoring_schedule_name.
[ "Lists", "the", "monitoring", "executions", "associated", "with", "the", "given", "monitoring_schedule_name." ]
def list_monitoring_executions(self, monitoring_schedule_name, sort_by='ScheduledTime', sort_order='Descending', max_results=100): response = self.sagemaker_client.list_monitoring_executions(MonitoringScheduleName=monitoring_schedule_name, SortBy=sort_by, SortOrder=sort_order, MaxResults=max_results) return res...
['def', 'list_monitoring_executions(self,', 'monitoring_schedule_name,', "sort_by='ScheduledTime',", "sort_order='Descending',", 'max_results=100):', 'response', '=', 'self.sagemaker_client.list_monitoring_executions(MonitoringScheduleName=monitoring_schedule_name,', 'SortBy=sort_by,', 'SortOrder=sort_order,', 'MaxResu...
829,601
deepmind/dm_control
tracking.py
ReferencePosesTask.get_reference_rel_bodies_pos_local
get_reference_rel_bodies_pos_local
Observation of the reference bodies relative to walker in local frame.
[ "Observation", "of", "the", "reference", "bodies", "relative", "to", "walker", "in", "local", "frame." ]
def get_reference_rel_bodies_pos_local(self, physics: 'mjcf.Physics'): time_steps = self._time_step + self._ref_steps obs = self._walker.transform_vec_to_egocentric_frame(physics, (self._clip_reference_features['body_positions'][time_steps] - self._walker_features['body_positions'])[:, self._body_idxs]) ret...
['def', 'get_reference_rel_bodies_pos_local(self,', 'physics:', "'mjcf.Physics'):", 'time_steps', '=', 'self._time_step', '+', 'self._ref_steps', 'obs', '=', 'self._walker.transform_vec_to_egocentric_frame(physics,', "(self._clip_reference_features['body_positions'][time_steps]", '-', "self._walker_features['body_posit...
165,104
songyanho/Reinforcement-Learning-for-Self-Driving-Cars
cnn.py
Cnn.increase_count_states
increase_count_states
Increase the number of states that has been processed in the game-environment.
[ "Increase", "the", "number", "of", "states", "that", "has", "been", "processed", "in", "the", "game-environment." ]
def increase_count_states(self): return self.session.run(self.count_states_increase)
['def', 'increase_count_states(self):', 'return', 'self.session.run(self.count_states_increase)']
340,789
Speedwagon13/CS-3600-Introduction-to--
config.py
dictConfig
dictConfig
Configure logging using a dictionary.
[ "Configure", "logging", "using", "a", "dictionary." ]
def dictConfig(config): dictConfigClass(config).configure()
['def', 'dictConfig(config):', 'dictConfigClass(config).configure()']
219,433
huawei-noah/xingtian
progress_logger.py
ProgressLogger.after_train
after_train
Be called after the training process.
[ "Be", "called", "after", "the", "training", "process." ]
def after_train(self, logs=None): logging.info('Finished the unified trainer successfully.')
['def', 'after_train(self,', 'logs=None):', "logging.info('Finished", 'the', 'unified', 'trainer', "successfully.')"]
968,483
koszullab/chromosight
test_preprocessing.py
test_crop_kernel
test_crop_kernel
Ensure cropped kernels are of appropriate size and centered and contain expected values.
[ "Ensure", "cropped", "kernels", "are", "of", "appropriate", "size", "and", "centered", "and", "contain", "expected", "values." ]
def test_crop_kernel(): m = 15 point_kernel = np.zeros((m, m)) point_kernel[m // 2, m // 2] = 10 dim_list = range(20) for targ in dim_list: if targ % 2: exp_dim = targ else: exp_dim = targ + 1 if exp_dim > m: exp_dim = m obs_kernel ...
['def', 'test_crop_kernel():', 'm', '=', '15', 'point_kernel', '=', 'np.zeros((m,', 'm))', 'point_kernel[m', '//', '2,', 'm', '//', '2]', '=', '10', 'dim_list', '=', 'range(20)', 'for', 'targ', 'in', 'dim_list:', 'if', 'targ', '%', '2:', 'exp_dim', '=', 'targ', 'else:', 'exp_dim', '=', 'targ', '+', '1', 'if', 'exp_dim'...
487,704
srai-lab/srai
generation.py
generate_test_case
generate_test_case
Generate test case for Hex2VecEmbedder.
[ "Generate", "test", "case", "for", "Hex2VecEmbedder." ]
def generate_test_case(test_case_name: str, geocoding_name: str, root_region_index: str, h3_res: int, radius: int, seed: int, tags: Optional[OsmTagsFilter]=None) -> None: if tags is None: tags = {'leisure': 'park', 'amenity': 'restaurant'} neighbourhood = H3Neighbourhood() regions_indexes = neighbou...
['def', 'generate_test_case(test_case_name:', 'str,', 'geocoding_name:', 'str,', 'root_region_index:', 'str,', 'h3_res:', 'int,', 'radius:', 'int,', 'seed:', 'int,', 'tags:', 'Optional[OsmTagsFilter]=None)', '->', 'None:', 'if', 'tags', 'is', 'None:', 'tags', '=', "{'leisure':", "'park',", "'amenity':", "'restaurant'}"...
371,974
myothida/Supervised-Machine-Learning
vector.py
Vector.isclose
isclose
Return True if the vector is close to another Vector.
[ "Return", "True", "if", "the", "vector", "is", "close", "to", "another", "Vector." ]
def isclose(self, other: 'Vector', **kwargs) -> bool: assert len(self) == len(other) return all((math.isclose(a, b, **kwargs) for (a, b) in zip(self, other)))
['def', 'isclose(self,', 'other:', "'Vector',", '**kwargs)', '->', 'bool:', 'assert', 'len(self)', '==', 'len(other)', 'return', 'all((math.isclose(a,', 'b,', '**kwargs)', 'for', '(a,', 'b)', 'in', 'zip(self,', 'other)))']
361,033
Riashat/Active-Learning-Bayesian-Convolutional--
theano_backend.py
sum
sum
Sum of the values in a tensor, alongside the specified axis.
[ "Sum", "of", "the", "values", "in", "a", "tensor,", "alongside", "the", "specified", "axis." ]
def sum(x, axis=None, keepdims=False): return T.sum(x, axis=axis, keepdims=keepdims)
['def', 'sum(x,', 'axis=None,', 'keepdims=False):', 'return', 'T.sum(x,', 'axis=axis,', 'keepdims=keepdims)']
8,753
RozDavid/LanguageGroundedSemseg
distributed.py
ErrorHandler.add_child
add_child
Registers a child process.
[ "Registers", "a", "child", "process." ]
def add_child(self, pid): self.children_pids.append(pid)
['def', 'add_child(self,', 'pid):', 'self.children_pids.append(pid)']
623,616
vaibhavsaxena11/cwvae
gif_summary.py
py_gif_summary
py_gif_summary
Outputs a `Summary` protocol buffer with gif animations.
[ "Outputs", "a", "`Summary`", "protocol", "buffer", "with", "gif", "animations." ]
def py_gif_summary(tag, images, max_outputs, fps): is_bytes = isinstance(tag, bytes) if is_bytes: tag = tag.decode('utf-8') images = np.asarray(images) if images.dtype != np.uint8: raise ValueError('Tensor must have dtype uint8 for gif summary.') if images.ndim != 5: raise Va...
['def', 'py_gif_summary(tag,', 'images,', 'max_outputs,', 'fps):', 'is_bytes', '=', 'isinstance(tag,', 'bytes)', 'if', 'is_bytes:', 'tag', '=', "tag.decode('utf-8')", 'images', '=', 'np.asarray(images)', 'if', 'images.dtype', '!=', 'np.uint8:', 'raise', "ValueError('Tensor", 'must', 'have', 'dtype', 'uint8', 'for', 'gi...
524,395
instadeepai/jumanji
env_test.py
test_graph_coloring_step_jit
test_graph_coloring_step_jit
Confirm that the step is only compiled once when jitted.
[ "Confirm", "that", "the", "step", "is", "only", "compiled", "once", "when", "jitted." ]
def test_graph_coloring_step_jit(graph_coloring: GraphColoring) -> None: key = jax.random.PRNGKey(0) (state, timestep) = jax.jit(graph_coloring.reset)(key) action = jnp.array(0) chex.clear_trace_counter() step_fn = jax.jit(chex.assert_max_traces(graph_coloring.step, n=1)) (new_state, next_timest...
['def', 'test_graph_coloring_step_jit(graph_coloring:', 'GraphColoring)', '->', 'None:', 'key', '=', 'jax.random.PRNGKey(0)', '(state,', 'timestep)', '=', 'jax.jit(graph_coloring.reset)(key)', 'action', '=', 'jnp.array(0)', 'chex.clear_trace_counter()', 'step_fn', '=', 'jax.jit(chex.assert_max_traces(graph_coloring.ste...
594,055
weimin17/Object-Detection_HelmetDetection
ptn_im_decoder.py
model
model
Decoder model to get image and mask from latent embedding.
[ "Decoder", "model", "to", "get", "image", "and", "mask", "from", "latent", "embedding." ]
def model(identities, poses, params, is_training): del is_training f_dim = params.f_dim fc_dim = params.fc_dim outputs = dict() with slim.arg_scope([slim.fully_connected, slim.conv2d_transpose], weights_initializer=tf.truncated_normal_initializer(stddev=0.02, seed=1)): h0 = tf.concat([identi...
['def', 'model(identities,', 'poses,', 'params,', 'is_training):', 'del', 'is_training', 'f_dim', '=', 'params.f_dim', 'fc_dim', '=', 'params.fc_dim', 'outputs', '=', 'dict()', 'with', 'slim.arg_scope([slim.fully_connected,', 'slim.conv2d_transpose],', 'weights_initializer=tf.truncated_normal_initializer(stddev=0.02,',...
752,612
instadeepai/jumanji
maze_generation.py
generate_maze
generate_maze
Randomly generate a maze.
[ "Randomly", "generate", "a", "maze." ]
def generate_maze(width: int, height: int, key: chex.PRNGKey) -> chex.Array: maze = create_empty_maze(width, height) chambers = create_chambers_stack(width, height) initial_state = MazeGenerationState(maze, chambers, key) final_state = jax.lax.while_loop(chambers_remaining, split_next_chamber, initial_s...
['def', 'generate_maze(width:', 'int,', 'height:', 'int,', 'key:', 'chex.PRNGKey)', '->', 'chex.Array:', 'maze', '=', 'create_empty_maze(width,', 'height)', 'chambers', '=', 'create_chambers_stack(width,', 'height)', 'initial_state', '=', 'MazeGenerationState(maze,', 'chambers,', 'key)', 'final_state', '=', 'jax.lax.wh...
593,979
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_linprog.py
magic_square
magic_square
Generates a linear program for which integer solutions represent an n x n magic square; binary decision variables represent the presence (or absence) of an integer 1 to n^2 in each position of the square.
[ "Generates", "a", "linear", "program", "for", "which", "integer", "solutions", "represent", "an", "n", "x", "n", "magic", "square;", "binary", "decision", "variables", "represent", "the", "presence", "(or", "absence)", "of", "an", "integer", "1", "to", "n^2", ...
def magic_square(n): np.random.seed(0) M = n * (n ** 2 + 1) / 2 numbers = np.arange(n ** 4) // n ** 2 + 1 numbers = numbers.reshape(n ** 2, n, n) zeros = np.zeros((n ** 2, n, n)) A_list = [] b_list = [] for i in range(n ** 2): A_row = zeros.copy() A_row[i, :, :] = 1 ...
['def', 'magic_square(n):', 'np.random.seed(0)', 'M', '=', 'n', '*', '(n', '**', '2', '+', '1)', '/', '2', 'numbers', '=', 'np.arange(n', '**', '4)', '//', 'n', '**', '2', '+', '1', 'numbers', '=', 'numbers.reshape(n', '**', '2,', 'n,', 'n)', 'zeros', '=', 'np.zeros((n', '**', '2,', 'n,', 'n))', 'A_list', '=', '[]', 'b...
260,020
srai-lab/srai
conftest.py
area_with_no_objects_gdf
area_with_no_objects_gdf
Get a gdf that contains no OSM objects.
[ "Get", "a", "gdf", "that", "contains", "no", "OSM", "objects." ]
def area_with_no_objects_gdf() -> gpd.GeoDataFrame: return gpd.GeoDataFrame(crs=WGS84_CRS, geometry=[Polygon([(3, 5), (3, 10), (7, 10), (7, 5)])])
['def', 'area_with_no_objects_gdf()', '->', 'gpd.GeoDataFrame:', 'return', 'gpd.GeoDataFrame(crs=WGS84_CRS,', 'geometry=[Polygon([(3,', '5),', '(3,', '10),', '(7,', '10),', '(7,', '5)])])']
372,023
lalwanii26/openscope-barcodingstim
behavior.py
_BaseLickSensor.update
update
Updates the data, emits signal if lick occurred.
[ "Updates", "the", "data,", "emits", "signal", "if", "lick", "occurred." ]
def update(self, index=None): data = self.read() self.lick_data.append(data) if data > self._last_value: self.lick_events.append(index) self._events_since_last_packet.append(index) self.lickOccurred.emit() self._last_value = data
['def', 'update(self,', 'index=None):', 'data', '=', 'self.read()', 'self.lick_data.append(data)', 'if', 'data', '>', 'self._last_value:', 'self.lick_events.append(index)', 'self._events_since_last_packet.append(index)', 'self.lickOccurred.emit()', 'self._last_value', '=', 'data']
757,478
apeterswu/RL4NMT
algorithmic_math.py
is_in_expr
is_in_expr
Returns True if `find` is a subtree of `expr`.
[ "Returns", "True", "if", "`find`", "is", "a", "subtree", "of", "`expr`." ]
def is_in_expr(expr, find): return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
['def', 'is_in_expr(expr,', 'find):', 'return', 'expr', '==', 'find', 'or', '(isinstance(expr,', 'ExprNode)', 'and', 'expr.is_in(find))']
330,860
JihongJu/keras-fcn
score.py
freq_weighted_IU
freq_weighted_IU
Compute frequent weighted IoU.
[ "Compute", "frequent", "weighted", "IoU." ]
def freq_weighted_IU(y_true, y_pred): confusion = compute_error_matrix(y_true, y_pred) freq = confusion.sum(1) / float(confusion.sum()) iu = np.diag(confusion) / (confusion.sum(1) + confusion.sum(0) - np.diag(confusion)) return (freq[freq > 0] * iu[freq > 0]).sum()
['def', 'freq_weighted_IU(y_true,', 'y_pred):', 'confusion', '=', 'compute_error_matrix(y_true,', 'y_pred)', 'freq', '=', 'confusion.sum(1)', '/', 'float(confusion.sum())', 'iu', '=', 'np.diag(confusion)', '/', '(confusion.sum(1)', '+', 'confusion.sum(0)', '-', 'np.diag(confusion))', 'return', '(freq[freq', '>', '0]', ...
247,696
replit-archive/empythoned
dummy_thread.py
interrupt_main
interrupt_main
Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.
[ "Set", "_interrupt", "flag", "to", "True", "to", "have", "start_new_thread", "raise", "KeyboardInterrupt", "upon", "exiting." ]
def interrupt_main(): if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
['def', 'interrupt_main():', 'if', '_main:', 'raise', 'KeyboardInterrupt', 'else:', 'global', '_interrupt', '_interrupt', '=', 'True']
176,290
brain-research/realistic-ssl-evaluation
dataset_utils.py
int64_feature
int64_feature
Create a feature that is serialized as an int64.
[ "Create", "a", "feature", "that", "is", "serialized", "as", "an", "int64." ]
def int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
['def', 'int64_feature(value):', 'return', 'tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))']
308,983
hans/pyccg
lexicon.py
Lexicon.lf_ngrams
lf_ngrams
Calculate n-gram statistics about the predicates present in the semantic forms in the lexicon.
[ "Calculate", "n-gram", "statistics", "about", "the", "predicates", "present", "in", "the", "semantic", "forms", "in", "the", "lexicon." ]
def lf_ngrams(self, order=1, conditioning_fn=None, smooth=None): if order > 1: raise NotImplementedError() ret = ConditionalDistribution() for entry_list in self._entries.values(): for entry in entry_list: keys = conditioning_fn(entry) if conditioning_fn is not None else [None] ...
['def', 'lf_ngrams(self,', 'order=1,', 'conditioning_fn=None,', 'smooth=None):', 'if', 'order', '>', '1:', 'raise', 'NotImplementedError()', 'ret', '=', 'ConditionalDistribution()', 'for', 'entry_list', 'in', 'self._entries.values():', 'for', 'entry', 'in', 'entry_list:', 'keys', '=', 'conditioning_fn(entry)', 'if', 'c...
295,950
iffiX/machin
pool.py
BasePool.starmap_async
starmap_async
Asynchronous version of `starmap()` method.
[ "Asynchronous", "version", "of", "`starmap()`", "method." ]
def starmap_async(self, func: Callable[[Any], Any], iterable: Collection[Tuple], chunksize: int=None, callback: Callable[[Any], None]=None, error_callback: Callable[[Exception], None]=None) -> AsyncResult: return self._map_async(func, iterable, starmap_caller, chunksize, callback, error_callback)
['def', 'starmap_async(self,', 'func:', 'Callable[[Any],', 'Any],', 'iterable:', 'Collection[Tuple],', 'chunksize:', 'int=None,', 'callback:', 'Callable[[Any],', 'None]=None,', 'error_callback:', 'Callable[[Exception],', 'None]=None)', '->', 'AsyncResult:', 'return', 'self._map_async(func,', 'iterable,', 'starmap_calle...
620,376
drivendataorg/concept-to-clinic
prediction.py
stats_from_batch
stats_from_batch
Return a list of DataFrame including position, diameter and chance of abnormal tissue to be a nodule for each nodule in a batch.
[ "Return", "a", "list", "of", "DataFrame", "including", "position,", "diameter", "and", "chance", "of", "abnormal", "tissue", "to", "be", "a", "nodule", "for", "each", "nodule", "in", "a", "batch." ]
def stats_from_batch(p, p_shape, predict_volume, batch_list_coords, annotation_index): patient_predictions_csv = [] for i in range(len(p[0])): p_coord = np.array(batch_list_coords[i]) nodule_chance = p[0][i][0] predict_volume[tuple(p_coord)] = nodule_chance if nodule_chance > P_T...
['def', 'stats_from_batch(p,', 'p_shape,', 'predict_volume,', 'batch_list_coords,', 'annotation_index):', 'patient_predictions_csv', '=', '[]', 'for', 'i', 'in', 'range(len(p[0])):', 'p_coord', '=', 'np.array(batch_list_coords[i])', 'nodule_chance', '=', 'p[0][i][0]', 'predict_volume[tuple(p_coord)]', '=', 'nodule_chan...
136,190
weimin17/Object-Detection_HelmetDetection
data_download.py
all_exist
all_exist
Returns true if all files in the list exist.
[ "Returns", "true", "if", "all", "files", "in", "the", "list", "exist." ]
def all_exist(filepaths): for fname in filepaths: if not tf.gfile.Exists(fname): return False return True
['def', 'all_exist(filepaths):', 'for', 'fname', 'in', 'filepaths:', 'if', 'not', 'tf.gfile.Exists(fname):', 'return', 'False', 'return', 'True']
748,698
enuguru/artificial_intelligence_and_machine_
classification.py
RandomForest.train
train
Trains a random forest using TreeLearn.
[ "Trains", "a", "random", "forest", "using", "TreeLearn." ]
def train(self, trainset): self.n_classes = len(trainset.metadata['targets']) trainset_orange = make_orange_dataset(trainset) self.trainset_domain = trainset_orange.domain import random self.forest = orngEnsemble.RandomForestLearner(trees=self.n_trees, attributes=self.n_features_per_node, rand=rando...
['def', 'train(self,', 'trainset):', 'self.n_classes', '=', "len(trainset.metadata['targets'])", 'trainset_orange', '=', 'make_orange_dataset(trainset)', 'self.trainset_domain', '=', 'trainset_orange.domain', 'import', 'random', 'self.forest', '=', 'orngEnsemble.RandomForestLearner(trees=self.n_trees,', 'attributes=sel...
164,377
fudan-zvg/SETR
mask2former_head.py
Mask2FormerHead.forward_head
forward_head
Forward for head part which is called after every decoder layer.
[ "Forward", "for", "head", "part", "which", "is", "called", "after", "every", "decoder", "layer." ]
def forward_head(self, decoder_out, mask_feature, attn_mask_target_size): decoder_out = self.transformer_decoder.post_norm(decoder_out) decoder_out = decoder_out.transpose(0, 1) cls_pred = self.cls_embed(decoder_out) mask_embed = self.mask_embed(decoder_out) mask_pred = torch.einsum('bqc,bchw->bqhw'...
['def', 'forward_head(self,', 'decoder_out,', 'mask_feature,', 'attn_mask_target_size):', 'decoder_out', '=', 'self.transformer_decoder.post_norm(decoder_out)', 'decoder_out', '=', 'decoder_out.transpose(0,', '1)', 'cls_pred', '=', 'self.cls_embed(decoder_out)', 'mask_embed', '=', 'self.mask_embed(decoder_out)', 'mask_...
898,171
renmengye/few-shot-ssl-public
mini_imagenet.py
MiniImageNetDataset.get_batch_idx_test
get_batch_idx_test
Gets the test set (unlabeled set) for the fully supervised training.
[ "Gets", "the", "test", "set", "(unlabeled", "set)", "for", "the", "fully", "supervised", "training." ]
def get_batch_idx_test(self, idx): return (self._read_from_cache(self._unlbl_idx[idx]), np.array([self._cls_label[kk] for kk in self._unlbl_idx[idx]], dtype=np.int64))
['def', 'get_batch_idx_test(self,', 'idx):', 'return', '(self._read_from_cache(self._unlbl_idx[idx]),', 'np.array([self._cls_label[kk]', 'for', 'kk', 'in', 'self._unlbl_idx[idx]],', 'dtype=np.int64))']
179,946
drprojects/superpoint_transformer
nag.py
NAG.device
device
Return device of first Data in NAG.
[ "Return", "device", "of", "first", "Data", "in", "NAG." ]
def device(self): return self[0].device if self.num_levels > 0 else torch.tensor([]).device
['def', 'device(self):', 'return', 'self[0].device', 'if', 'self.num_levels', '>', '0', 'else', 'torch.tensor([]).device']
880,794
LorenzoCassano/TablutChallenge22-23
games.py
StochasticGame.play_game
play_game
Play an n-person, move-alternating stochastic game.
[ "Play", "an", "n-person,", "move-alternating", "stochastic", "game." ]
def play_game(self, *players): state = self.initial while True: for player in players: chance = random.choice(self.chances(state)) state = self.outcome(state, chance) move = player(self, state) state = self.result(state, move) if self.terminal_...
['def', 'play_game(self,', '*players):', 'state', '=', 'self.initial', 'while', 'True:', 'for', 'player', 'in', 'players:', 'chance', '=', 'random.choice(self.chances(state))', 'state', '=', 'self.outcome(state,', 'chance)', 'move', '=', 'player(self,', 'state)', 'state', '=', 'self.result(state,', 'move)', 'if', 'self...
365,173
sek788432/Waymo-2D-Object-Detection
misc.py
get_model_params
get_model_params
Gets predefined model params.
[ "Gets", "predefined", "model", "params." ]
def get_model_params(param_set, num_gpus): if num_gpus > 1: if param_set == 'big': return model_params.BIG_MULTI_GPU_PARAMS.copy() elif param_set == 'base': return model_params.BASE_MULTI_GPU_PARAMS.copy() else: raise ValueError('Not valid params: param_se...
['def', 'get_model_params(param_set,', 'num_gpus):', 'if', 'num_gpus', '>', '1:', 'if', 'param_set', '==', "'big':", 'return', 'model_params.BIG_MULTI_GPU_PARAMS.copy()', 'elif', 'param_set', '==', "'base':", 'return', 'model_params.BASE_MULTI_GPU_PARAMS.copy()', 'else:', 'raise', "ValueError('Not", 'valid', 'params:',...
972,855
Alexander-Parker/youtube_nlp
options.py
Options.to_capabilities
to_capabilities
Marshals the Firefox options to a `moz:firefoxOptions` object.
[ "Marshals", "the", "Firefox", "options", "to", "a", "`moz:firefoxOptions`", "object." ]
def to_capabilities(self): caps = self._caps opts = {} if self._binary is not None: opts['binary'] = self._binary._start_cmd if len(self._preferences) > 0: opts['prefs'] = self._preferences if self._proxy is not None: self._proxy.add_to_capabilities(opts) if self._profile...
['def', 'to_capabilities(self):', 'caps', '=', 'self._caps', 'opts', '=', '{}', 'if', 'self._binary', 'is', 'not', 'None:', "opts['binary']", '=', 'self._binary._start_cmd', 'if', 'len(self._preferences)', '>', '0:', "opts['prefs']", '=', 'self._preferences', 'if', 'self._proxy', 'is', 'not', 'None:', 'self._proxy.add_...
970,871
happywu/Sequence-Level-Semantics-Aggregation
module.py
Module.label_names
label_names
A list of names for labels required by this module.
[ "A", "list", "of", "names", "for", "labels", "required", "by", "this", "module." ]
def label_names(self): return self._label_names
['def', 'label_names(self):', 'return', 'self._label_names']
876,694
rlgraph/rlgraph
test_python_memory_performance.py
TestPythonMemoryPerformance.test_rlgraph_updating
test_rlgraph_updating
Tests RLGraph's memory performance.
[ "Tests", "RLGraph's", "memory", "performance." ]
def test_rlgraph_updating(self): memory = ApexMemory(capacity=self.capacity, alpha=1.0) records = [self.record_space.sample(size=1) for _ in range_(self.inserts)] for record in records: memory.insert_records((record['states'], record['actions'], record['reward'], record['terminals'], None)) loss...
['def', 'test_rlgraph_updating(self):', 'memory', '=', 'ApexMemory(capacity=self.capacity,', 'alpha=1.0)', 'records', '=', '[self.record_space.sample(size=1)', 'for', '_', 'in', 'range_(self.inserts)]', 'for', 'record', 'in', 'records:', "memory.insert_records((record['states'],", "record['actions'],", "record['reward'...
862,814
Farama-Foundation/Minigrid
wrappers.py
ActionBonus.step
step
Steps through the environment with `action`.
[ "Steps", "through", "the", "environment", "with", "`action`." ]
def step(self, action): (obs, reward, terminated, truncated, info) = self.env.step(action) env = self.unwrapped tup = (tuple(env.agent_pos), env.agent_dir, action) pre_count = 0 if tup in self.counts: pre_count = self.counts[tup] new_count = pre_count + 1 self.counts[tup] = new_count...
['def', 'step(self,', 'action):', '(obs,', 'reward,', 'terminated,', 'truncated,', 'info)', '=', 'self.env.step(action)', 'env', '=', 'self.unwrapped', 'tup', '=', '(tuple(env.agent_pos),', 'env.agent_dir,', 'action)', 'pre_count', '=', '0', 'if', 'tup', 'in', 'self.counts:', 'pre_count', '=', 'self.counts[tup]', 'new_...
271,488
tensorflow/agents
categorical_q_network.py
CategoricalQNetwork.call
call
Runs the given observation through the network.
[ "Runs", "the", "given", "observation", "through", "the", "network." ]
def call(self, observation, step_type=None, network_state=(), training=False): (logits, network_state) = self._q_network(observation, step_type, network_state, training=training) logits = tf.reshape(logits, [-1, self._num_actions, self._num_atoms]) return (logits, network_state)
['def', 'call(self,', 'observation,', 'step_type=None,', 'network_state=(),', 'training=False):', '(logits,', 'network_state)', '=', 'self._q_network(observation,', 'step_type,', 'network_state,', 'training=training)', 'logits', '=', 'tf.reshape(logits,', '[-1,', 'self._num_actions,', 'self._num_atoms])', 'return', '(l...
22,805
XU-GITHUB-curry/FBSNet
cityscapes.py
CityscapesTrainInform.readWholeTrainSet
readWholeTrainSet
to read the whole train set of current dataset.
[ "to", "read", "the", "whole", "train", "set", "of", "current", "dataset." ]
def readWholeTrainSet(self, fileName, train_flag=True): global_hist = np.zeros(self.classes, dtype=np.float32) no_files = 0 min_val_al = 0 max_val_al = 0 with open(self.data_dir + '/' + fileName, 'r') as textFile: for line in textFile: line_arr = line.split() img_file...
['def', 'readWholeTrainSet(self,', 'fileName,', 'train_flag=True):', 'global_hist', '=', 'np.zeros(self.classes,', 'dtype=np.float32)', 'no_files', '=', '0', 'min_val_al', '=', '0', 'max_val_al', '=', '0', 'with', 'open(self.data_dir', '+', "'/'", '+', 'fileName,', "'r')", 'as', 'textFile:', 'for', 'line', 'in', 'textF...
560,053
baina23/Self-Supervised-Representation-Learning
NetworkInNetwork.py
NetworkInNetwork.forward
forward
Forward an image `x` through the network and return the asked output features.
[ "Forward", "an", "image", "`x`", "through", "the", "network", "and", "return", "the", "asked", "output", "features." ]
def forward(self, x, out_feat_keys=None): (out_feat_keys, max_out_feat) = self._parse_out_keys_arg(out_feat_keys) out_feats = [None] * len(out_feat_keys) feat = x for f in range(max_out_feat + 1): feat = self._feature_blocks[f](feat) key = self.all_feat_names[f] if key in out_fea...
['def', 'forward(self,', 'x,', 'out_feat_keys=None):', '(out_feat_keys,', 'max_out_feat)', '=', 'self._parse_out_keys_arg(out_feat_keys)', 'out_feats', '=', '[None]', '*', 'len(out_feat_keys)', 'feat', '=', 'x', 'for', 'f', 'in', 'range(max_out_feat', '+', '1):', 'feat', '=', 'self._feature_blocks[f](feat)', 'key', '='...
342,175
arnomoonens/yarll
env_runner.py
EnvRunner.step_env
step_env
Execute an action in the current environment.
[ "Execute", "an", "action", "in", "the", "current", "environment." ]
def step_env(self, action): (state, reward, done, info) = self.env.step(self.policy.get_env_action(action)) self.state = np.asarray(self.state, dtype=self.state_dtype) return (state, reward, done, info)
['def', 'step_env(self,', 'action):', '(state,', 'reward,', 'done,', 'info)', '=', 'self.env.step(self.policy.get_env_action(action))', 'self.state', '=', 'np.asarray(self.state,', 'dtype=self.state_dtype)', 'return', '(state,', 'reward,', 'done,', 'info)']
374,648
ludwig-ai/ludwig
embedding_modules.py
EmbedSet.forward
forward
Params: inputs: Boolean multi-hot tensor of size [batch x vocab_size], where inputs[b, i] indicates that token i is present in sample b.
[ "Params:", "inputs:", "Boolean", "multi-hot", "tensor", "of", "size", "[batch", "x", "vocab_size],", "where", "inputs[b,", "i]", "indicates", "that", "token", "i", "is", "present", "in", "sample", "b." ]
def forward(self, inputs: torch.Tensor, mask: Optional[torch.Tensor]=None) -> torch.Tensor: inputs = inputs.int() * self.vocab_indices embedded = self.embeddings(inputs.long()) mask = torch.unsqueeze(inputs, -1) embedded = embedded * mask embedded = self.aggregation_function(embedded, dim=1) if ...
['def', 'forward(self,', 'inputs:', 'torch.Tensor,', 'mask:', 'Optional[torch.Tensor]=None)', '->', 'torch.Tensor:', 'inputs', '=', 'inputs.int()', '*', 'self.vocab_indices', 'embedded', '=', 'self.embeddings(inputs.long())', 'mask', '=', 'torch.unsqueeze(inputs,', '-1)', 'embedded', '=', 'embedded', '*', 'mask', 'embe...
616,896
pranjaldatta/PyVision
SVMEyeDetector.py
RegressionEyeLocator2.train
train
Train the eye locators.
[ "Train", "the", "eye", "locators." ]
def train(self, **kwargs): self.left_locator.train(**kwargs) self.right_locator.train(**kwargs) self.left_eye = self.left_locator.mean self.right_eye = self.right_locator.mean self.perturbations = False
['def', 'train(self,', '**kwargs):', 'self.left_locator.train(**kwargs)', 'self.right_locator.train(**kwargs)', 'self.left_eye', '=', 'self.left_locator.mean', 'self.right_eye', '=', 'self.right_locator.mean', 'self.perturbations', '=', 'False']
815,835
LLNL/merlin
tasks.py
queue_merlin_study
queue_merlin_study
Launch a chain of tasks based off of a MerlinStudy.
[ "Launch", "a", "chain", "of", "tasks", "based", "off", "of", "a", "MerlinStudy." ]
def queue_merlin_study(study, adapter): samples = study.samples sample_labels = study.sample_labels egraph = study.dag LOG.info('Calculating task groupings from DAG.') groups_of_chains = egraph.group_tasks('_source') LOG.info('Converting graph to tasks.') celery_dag = chain((chord(group([exp...
['def', 'queue_merlin_study(study,', 'adapter):', 'samples', '=', 'study.samples', 'sample_labels', '=', 'study.sample_labels', 'egraph', '=', 'study.dag', "LOG.info('Calculating", 'task', 'groupings', 'from', "DAG.')", 'groups_of_chains', '=', "egraph.group_tasks('_source')", "LOG.info('Converting", 'graph', 'to', "ta...
632,655
sunishsheth2009/ChatterBot
test_regression.py
TestRegression.test_reshape_order
test_reshape_order
Make sure reshape order works.
[ "Make", "sure", "reshape", "order", "works." ]
def test_reshape_order(self, level=rlevel): a = np.arange(6).reshape(2, 3, order='F') assert_equal(a, [[0, 2, 4], [1, 3, 5]]) a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) b = a[:, 1] assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]])
['def', 'test_reshape_order(self,', 'level=rlevel):', 'a', '=', 'np.arange(6).reshape(2,', '3,', "order='F')", 'assert_equal(a,', '[[0,', '2,', '4],', '[1,', '3,', '5]])', 'a', '=', 'np.array([[1,', '2],', '[3,', '4],', '[5,', '6],', '[7,', '8]])', 'b', '=', 'a[:,', '1]', 'assert_equal(b.reshape(2,', '2,', "order='F'),...
530,891
narumiruna/efficientnet-pytorch
eval_ckpt_main.py
eval_example_images
eval_example_images
Eval a list of example images.
[ "Eval", "a", "list", "of", "example", "images." ]
def eval_example_images(model_name, ckpt_dir, image_files, labels_map_file): eval_ckpt_driver = EvalCkptDriver(model_name) classes = json.loads(tf.gfile.Open(labels_map_file).read()) (pred_idx, pred_prob) = eval_ckpt_driver.run_inference(ckpt_dir, image_files, [0] * len(image_files)) for i in range(len(...
['def', 'eval_example_images(model_name,', 'ckpt_dir,', 'image_files,', 'labels_map_file):', 'eval_ckpt_driver', '=', 'EvalCkptDriver(model_name)', 'classes', '=', 'json.loads(tf.gfile.Open(labels_map_file).read())', '(pred_idx,', 'pred_prob)', '=', 'eval_ckpt_driver.run_inference(ckpt_dir,', 'image_files,', '[0]', '*'...
175,449
eflu-gh/Natural-Language-Processing--Modeling
autocompletion.py
autocomplete
autocomplete
Entry Point for completion of main and subcommand options.
[ "Entry", "Point", "for", "completion", "of", "main", "and", "subcommand", "options." ]
def autocomplete(): if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for (cmd, summary) in get_summaries...
['def', 'autocomplete():', 'if', "'PIP_AUTO_COMPLETE'", 'not', 'in', 'os.environ:', 'return', 'cwords', '=', "os.environ['COMP_WORDS'].split()[1:]", 'cword', '=', "int(os.environ['COMP_CWORD'])", 'try:', 'current', '=', 'cwords[cword', '-', '1]', 'except', 'IndexError:', 'current', '=', "''", 'subcommands', '=', '[cmd'...
652,365
Hironsan/tensorflow-nlp-examples
reader.py
ptb_producer
ptb_producer
Create dataset for training.
[ "Create", "dataset", "for", "training." ]
def ptb_producer(raw_data, num_steps): data_len = len(raw_data) num_data = (data_len - 1) // num_steps x = np.array([raw_data[i * num_steps:(i + 1) * num_steps] for i in range(num_data)]) y = np.array([raw_data[i * num_steps + 1:(i + 1) * num_steps + 1] for i in range(num_data)]) return (x, y)
['def', 'ptb_producer(raw_data,', 'num_steps):', 'data_len', '=', 'len(raw_data)', 'num_data', '=', '(data_len', '-', '1)', '//', 'num_steps', 'x', '=', 'np.array([raw_data[i', '*', 'num_steps:(i', '+', '1)', '*', 'num_steps]', 'for', 'i', 'in', 'range(num_data)])', 'y', '=', 'np.array([raw_data[i', '*', 'num_steps', '...
908,709
seltzerfish/guardyn
gtest_throw_on_failure_test.py
ThrowOnFailureTest.testThrowOnFailureFlag
testThrowOnFailureFlag
Tests using the --gtest_throw_on_failure flag.
[ "Tests", "using", "the", "--gtest_throw_on_failure", "flag." ]
def testThrowOnFailureFlag(self): self.RunAndVerify(env_var_value=None, flag_value='0', should_fail=False) self.RunAndVerify(env_var_value=None, flag_value='1', should_fail=True)
['def', 'testThrowOnFailureFlag(self):', 'self.RunAndVerify(env_var_value=None,', "flag_value='0',", 'should_fail=False)', 'self.RunAndVerify(env_var_value=None,', "flag_value='1',", 'should_fail=True)']
572,318
intel/neural-compressor
objective.py
MultiObjective.baseline
baseline
Get the actual model performance.
[ "Get", "the", "actual", "model", "performance." ]
def baseline(self): return self._baseline
['def', 'baseline(self):', 'return', 'self._baseline']
737,272
TonyLianLong/VAI-ReinforcementLearning
mazes.py
MazeWithTargets.target_grid_positions
target_grid_positions
A tuple of grid coordinates of targets generated for the current maze.
[ "A", "tuple", "of", "grid", "coordinates", "of", "targets", "generated", "for", "the", "current", "maze." ]
def target_grid_positions(self): return self._target_grid_positions
['def', 'target_grid_positions(self):', 'return', 'self._target_grid_positions']
439,940