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
famura/SimuRLacra
data_sets.py
TimeSeriesDataSet.dim_data
dim_data
Get the data's number of dimensions.
[ "Get", "the", "data's", "number", "of", "dimensions." ]
def dim_data(self) -> int: if not self.data_all.ndim == 2: raise pyrado.ShapeErr(given=self.data_all, expected_match=(-1, 2)) return self.data_all.shape[1]
['def', 'dim_data(self)', '->', 'int:', 'if', 'not', 'self.data_all.ndim', '==', '2:', 'raise', 'pyrado.ShapeErr(given=self.data_all,', 'expected_match=(-1,', '2))', 'return', 'self.data_all.shape[1]']
884,071
lspvic/CopyNet
model_helper.py
compute_perplexity
compute_perplexity
Compute perplexity of the output of the model.
[ "Compute", "perplexity", "of", "the", "output", "of", "the", "model." ]
def compute_perplexity(model, sess, name): total_loss = 0 total_predict_count = 0 start_time = time.time() while True: try: (loss, predict_count, batch_size) = model.eval(sess) total_loss += loss * batch_size total_predict_count += predict_count except...
['def', 'compute_perplexity(model,', 'sess,', 'name):', 'total_loss', '=', '0', 'total_predict_count', '=', '0', 'start_time', '=', 'time.time()', 'while', 'True:', 'try:', '(loss,', 'predict_count,', 'batch_size)', '=', 'model.eval(sess)', 'total_loss', '+=', 'loss', '*', 'batch_size', 'total_predict_count', '+=', 'pr...
137,199
OliverKillane/NuNet-Designer
NuNetLibrary.py
Neuron.giveinput
giveinput
giveinput adds an input to the neuron (used by synapses feeding forwards a value).
[ "giveinput", "adds", "an", "input", "to", "the", "neuron", "(used", "by", "synapses", "feeding", "forwards", "a", "value)." ]
def giveinput(self, value: int) -> None: self._inputValue += value
['def', 'giveinput(self,', 'value:', 'int)', '->', 'None:', 'self._inputValue', '+=', 'value']
730,504
voxel51/fiftyone
plotly.py
plot_pr_curve
plot_pr_curve
Plots a precision-recall (PR) curve.
[ "Plots", "a", "precision-recall", "(PR)", "curve." ]
def plot_pr_curve(precision, recall, thresholds=None, label=None, style='area', figure=None, title=None, **kwargs): if style not in ('line', 'area'): msg = "Unsupported style '%s'; using 'area' instead" % style warnings.warn(msg) style = 'area' if figure is None: figure = go.Figu...
['def', 'plot_pr_curve(precision,', 'recall,', 'thresholds=None,', 'label=None,', "style='area',", 'figure=None,', 'title=None,', '**kwargs):', 'if', 'style', 'not', 'in', "('line',", "'area'):", 'msg', '=', '"Unsupported', 'style', "'%s';", 'using', "'area'", 'instead"', '%', 'style', 'warnings.warn(msg)', 'style', '=...
583,646
kubeflow/pipelines
pipeline_context.py
Pipeline.get_default_pipeline
get_default_pipeline
Gets the default pipeline.
[ "Gets", "the", "default", "pipeline." ]
def get_default_pipeline(): return Pipeline._default_pipeline
['def', 'get_default_pipeline():', 'return', 'Pipeline._default_pipeline']
780,211
nicknochnack/RealTimeSignLanguageTFJS
model.py
get_extra_layer_scopes
get_extra_layer_scopes
Gets the scopes for extra layers.
[ "Gets", "the", "scopes", "for", "extra", "layers." ]
def get_extra_layer_scopes(last_layers_contain_logits_only=False): if last_layers_contain_logits_only: return [LOGITS_SCOPE_NAME] else: return [LOGITS_SCOPE_NAME, IMAGE_POOLING_SCOPE, ASPP_SCOPE, CONCAT_PROJECTION_SCOPE, DECODER_SCOPE, META_ARCHITECTURE_SCOPE]
['def', 'get_extra_layer_scopes(last_layers_contain_logits_only=False):', 'if', 'last_layers_contain_logits_only:', 'return', '[LOGITS_SCOPE_NAME]', 'else:', 'return', '[LOGITS_SCOPE_NAME,', 'IMAGE_POOLING_SCOPE,', 'ASPP_SCOPE,', 'CONCAT_PROJECTION_SCOPE,', 'DECODER_SCOPE,', 'META_ARCHITECTURE_SCOPE]']
851,516
apeterswu/RL4NMT
common_attention.py
local_reduction_attention
local_reduction_attention
Reduce the length dimension using self attention.
[ "Reduce", "the", "length", "dimension", "using", "self", "attention." ]
def local_reduction_attention(x, block_length, multihead_params): @expert_utils.add_name_scope() def dot_product_self_local_attention_flattened(q, k, v): (_, num_head, _, depth) = q.get_shape().as_list() def pad_and_reshape(x): length_x = tf.shape(x)[2] x = tf.pad(x, [[...
['def', 'local_reduction_attention(x,', 'block_length,', 'multihead_params):', '@expert_utils.add_name_scope()', 'def', 'dot_product_self_local_attention_flattened(q,', 'k,', 'v):', '(_,', 'num_head,', '_,', 'depth)', '=', 'q.get_shape().as_list()', 'def', 'pad_and_reshape(x):', 'length_x', '=', 'tf.shape(x)[2]', 'x', ...
330,995
rifqind/Agent-Programs-3KS1
environment.py
Environment.iter_extensions
iter_extensions
Iterates over the extensions by priority.
[ "Iterates", "over", "the", "extensions", "by", "priority." ]
def iter_extensions(self): return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
['def', 'iter_extensions(self):', 'return', 'iter(sorted(self.extensions.values(),', 'key=lambda', 'x:', 'x.priority))']
42,198
netket/netket
S2_operator.py
Renyi2EntanglementEntropy.is_hermitian
is_hermitian
Ignored for this operator.
[ "Ignored", "for", "this", "operator." ]
def is_hermitian(self): return True
['def', 'is_hermitian(self):', 'return', 'True']
735,956
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l1_base
rl_modelrl_l1_base
Parameter set with L1 loss.
[ "Parameter", "set", "with", "L1", "loss." ]
def rl_modelrl_l1_base(): hparams = rl_modelrl_base() hparams.generative_model_params = 'next_frame_l1' return hparams
['def', 'rl_modelrl_l1_base():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.generative_model_params', '=', "'next_frame_l1'", 'return', 'hparams']
965,996
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Expression.isComment
isComment
True if this expression is a comment.
[ "True", "if", "this", "expression", "is", "a", "comment." ]
def isComment(self): try: return self.left.strip().startswith('#') except (AttributeError,): return False
['def', 'isComment(self):', 'try:', 'return', "self.left.strip().startswith('#')", 'except', '(AttributeError,):', 'return', 'False']
10,866
Erfanafshar/Principles-and-Applications-of---graph-coloring
Duration.py
Duration.frame
frame
Return the frame the duration is in.
[ "Return", "the", "frame", "the", "duration", "is", "in." ]
def frame(self): return self._frame
['def', 'frame(self):', 'return', 'self._frame']
307,536
arshpreetsingh/quantopian-machinelearning
application.py
Application.load_config_file
load_config_file
Load config files by filename and path.
[ "Load", "config", "files", "by", "filename", "and", "path." ]
def load_config_file(self, filename, path=None): (filename, ext) = os.path.splitext(filename) new_config = Config() for config in self._load_config_files(filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors): new_config.merge(config) new_config.merge(self.cli...
['def', 'load_config_file(self,', 'filename,', 'path=None):', '(filename,', 'ext)', '=', 'os.path.splitext(filename)', 'new_config', '=', 'Config()', 'for', 'config', 'in', 'self._load_config_files(filename,', 'path=path,', 'log=self.log,', 'raise_config_file_errors=self.raise_config_file_errors):', 'new_config.merge(c...
893,808
aimclub/FEDOT
pipeline_visualization.py
show_complex_colors
show_complex_colors
Show with colors defined by function.
[ "Show", "with", "colors", "defined", "by", "function." ]
def show_complex_colors(pipeline: Pipeline): def nodes_color(labels): if 'xgboost' in labels: return {'xgboost': 'tab:orange', None: 'black'} else: return {'rf': 'tab:green', None: 'black'} pipeline.show(node_color=nodes_color)
['def', 'show_complex_colors(pipeline:', 'Pipeline):', 'def', 'nodes_color(labels):', 'if', "'xgboost'", 'in', 'labels:', 'return', "{'xgboost':", "'tab:orange',", 'None:', "'black'}", 'else:', 'return', "{'rf':", "'tab:green',", 'None:', "'black'}", 'pipeline.show(node_color=nodes_color)']
545,503
cnr-isti-vclab/TagLab
QtBricksWidget.py
QtBricksWidget.setupBricksSize
setupBricksSize
Cpnvert the bricks' size (in cm) to pixels and check if all the values have been inserted.
[ "Cpnvert", "the", "bricks'", "size", "(in", "cm)", "to", "pixels", "and", "check", "if", "all", "the", "values", "have", "been", "inserted." ]
def setupBricksSize(self): txt = self.editMinW.text() if txt == '': return False else: self.min_width = int(int(txt) * 10.0 / self.pixel_size) txt = self.editMaxW.text() if txt == '': return False else: self.max_width = int(int(txt) * 10.0 / self.pixel_size) t...
['def', 'setupBricksSize(self):', 'txt', '=', 'self.editMinW.text()', 'if', 'txt', '==', "'':", 'return', 'False', 'else:', 'self.min_width', '=', 'int(int(txt)', '*', '10.0', '/', 'self.pixel_size)', 'txt', '=', 'self.editMaxW.text()', 'if', 'txt', '==', "'':", 'return', 'False', 'else:', 'self.max_width', '=', 'int(i...
906,808
QData/deepWordBug
networks.py
Network.disconnect
disconnect
Disconnect a container from this network.
[ "Disconnect", "a", "container", "from", "this", "network." ]
def disconnect(self, container, *args, **kwargs): if isinstance(container, Container): container = container.id return self.client.api.disconnect_container_from_network(container, self.id, *args, **kwargs)
['def', 'disconnect(self,', 'container,', '*args,', '**kwargs):', 'if', 'isinstance(container,', 'Container):', 'container', '=', 'container.id', 'return', 'self.client.api.disconnect_container_from_network(container,', 'self.id,', '*args,', '**kwargs)']
541,906
asyml/texar
vocabulary.py
Vocab.unk_token
unk_token
A string of the special token indicating unknown token.
[ "A", "string", "of", "the", "special", "token", "indicating", "unknown", "token." ]
def unk_token(self): return self._unk_token
['def', 'unk_token(self):', 'return', 'self._unk_token']
924,501
flow-project/flow
bottleneck.py
BottleneckNetwork.get_bottleneck_lanes
get_bottleneck_lanes
Return the reduced number of lanes.
[ "Return", "the", "reduced", "number", "of", "lanes." ]
def get_bottleneck_lanes(self, lane): return [int(lane / 2), int(lane / 4)]
['def', 'get_bottleneck_lanes(self,', 'lane):', 'return', '[int(lane', '/', '2),', 'int(lane', '/', '4)]']
211,777
wandb/wandb
dirsnapshot.py
DirectorySnapshotDiff.files_modified
files_modified
List of files that were modified.
[ "List", "of", "files", "that", "were", "modified." ]
def files_modified(self): return self._files_modified
['def', 'files_modified(self):', 'return', 'self._files_modified']
942,198
google/deepvariant
runtime_by_region_vis.py
make_all_charts
make_all_charts
Creates charts and puts them in a list with their ID names.
[ "Creates", "charts", "and", "puts", "them", "in", "a", "list", "with", "their", "ID", "names." ]
def make_all_charts(df: pd.DataFrame, by_task: pd.DataFrame) -> List[Dict[Text, Union[str, alt.Chart]]]: charts = [{'id': 'total_by_stage', 'chart': totals_by_stage(by_task)}, {'id': 'pareto_and_runtimes_by_task', 'chart': pareto_and_runtimes_by_task(df)}, {'id': 'histogram_by_task', 'chart': stage_histogram(by_tas...
['def', 'make_all_charts(df:', 'pd.DataFrame,', 'by_task:', 'pd.DataFrame)', '->', 'List[Dict[Text,', 'Union[str,', 'alt.Chart]]]:', 'charts', '=', "[{'id':", "'total_by_stage',", "'chart':", 'totals_by_stage(by_task)},', "{'id':", "'pareto_and_runtimes_by_task',", "'chart':", 'pareto_and_runtimes_by_task(df)},', "{'id...
540,434
triaquae/triaquae
decorators.py
LoginRequiredTestCase.testView
testView
Check that login_required is assignable to normal views.
[ "Check", "that", "login_required", "is", "assignable", "to", "normal", "views." ]
def testView(self): def normal_view(request): pass login_required(normal_view)
['def', 'testView(self):', 'def', 'normal_view(request):', 'pass', 'login_required(normal_view)']
357,132
weimin17/Object-Detection_HelmetDetection
evaluation.py
segmentation_summaries
segmentation_summaries
Computes segmentation eval summaries for gold and annotated sentences.
[ "Computes", "segmentation", "eval", "summaries", "for", "gold", "and", "annotated", "sentences." ]
def segmentation_summaries(gold_corpus, annotated_corpus): (prec, rec, f1) = calculate_segmentation_metrics(gold_corpus, annotated_corpus) return {'precision': prec, 'recall': rec, 'f1': f1, 'eval_metric': f1}
['def', 'segmentation_summaries(gold_corpus,', 'annotated_corpus):', '(prec,', 'rec,', 'f1)', '=', 'calculate_segmentation_metrics(gold_corpus,', 'annotated_corpus)', 'return', "{'precision':", 'prec,', "'recall':", 'rec,', "'f1':", 'f1,', "'eval_metric':", 'f1}']
760,146
Eric3911/OpenAGI
stage3.py
DeepSpeedZeroOptimizer_Stage3.zero_grad
zero_grad
Zero FP16 parameter grads.
[ "Zero", "FP16", "parameter", "grads." ]
def zero_grad(self, set_to_none=False): self.micro_step_id = 0 for group in self.fp16_groups: for p in group: if set_to_none: if p.grad is not None and get_accelerator().on_accelerator(p.grad): p.grad.record_stream(get_accelerator().current_stream()) ...
['def', 'zero_grad(self,', 'set_to_none=False):', 'self.micro_step_id', '=', '0', 'for', 'group', 'in', 'self.fp16_groups:', 'for', 'p', 'in', 'group:', 'if', 'set_to_none:', 'if', 'p.grad', 'is', 'not', 'None', 'and', 'get_accelerator().on_accelerator(p.grad):', 'p.grad.record_stream(get_accelerator().current_stream()...
252,218
Talendar/multilayer_perceptron
main.py
load_mnist
load_mnist
Loads and shuffles the MNIST data.
[ "Loads", "and", "shuffles", "the", "MNIST", "data." ]
def load_mnist(path): df = pd.read_csv(path).sample(frac=1).reset_index(drop=True) (X, Y) = ([], []) for (i, row) in df.iterrows(): (label, pixels) = (row['label'], row.drop('label').values / 255) X.append(pixels) y = np.zeros(10) y[label] = 1 Y.append(y) return (...
['def', 'load_mnist(path):', 'df', '=', 'pd.read_csv(path).sample(frac=1).reset_index(drop=True)', '(X,', 'Y)', '=', '([],', '[])', 'for', '(i,', 'row)', 'in', 'df.iterrows():', '(label,', 'pixels)', '=', "(row['label'],", "row.drop('label').values", '/', '255)', 'X.append(pixels)', 'y', '=', 'np.zeros(10)', 'y[label]'...
643,596
TonyLianLong/VAI-ReinforcementLearning
c_declarations.py
Struct.wrapper_class
wrapper_class
Generates a Python class containing getter/setter methods for members.
[ "Generates", "a", "Python", "class", "containing", "getter/setter", "methods", "for", "members." ]
def wrapper_class(self): indent = codegen_util.Indenter() lines = [textwrap.dedent('\n class {0.wrapper_name}(util.WrapperBase):\n """{0.docstring}"""'.format(self))] with indent: for member in six.itervalues(self.members): if isinstance(member, AnonymousUnion): f...
['def', 'wrapper_class(self):', 'indent', '=', 'codegen_util.Indenter()', 'lines', '=', "[textwrap.dedent('\\n", 'class', '{0.wrapper_name}(util.WrapperBase):\\n', '"""{0.docstring}"""\'.format(self))]', 'with', 'indent:', 'for', 'member', 'in', 'six.itervalues(self.members):', 'if', 'isinstance(member,', 'AnonymousUni...
439,814
tensorflow/hub
module_spec.py
ModuleSpec.get_tags
get_tags
Lists the graph variants as an iterable of set of tags.
[ "Lists", "the", "graph", "variants", "as", "an", "iterable", "of", "set", "of", "tags." ]
def get_tags(self): return [set()]
['def', 'get_tags(self):', 'return', '[set()]']
570,969
illidanlab/Simulator
IDQN.py
Estimator.update
update
Updates the estimator towards the given targets.
[ "Updates", "the", "estimator", "towards", "the", "given", "targets." ]
def update(self, s, a, y, learning_rate, global_step): sess = self.sess feed_dict = {self.state: s, self.y_pl: y, self.ACTION: a, self.loss_lr: learning_rate} (summaries, _, loss) = sess.run([self.summaries, self.train_op, self.loss], feed_dict) if self.summary_writer: self.summary_writer.add_su...
['def', 'update(self,', 's,', 'a,', 'y,', 'learning_rate,', 'global_step):', 'sess', '=', 'self.sess', 'feed_dict', '=', '{self.state:', 's,', 'self.y_pl:', 'y,', 'self.ACTION:', 'a,', 'self.loss_lr:', 'learning_rate}', '(summaries,', '_,', 'loss)', '=', 'sess.run([self.summaries,', 'self.train_op,', 'self.loss],', 'fe...
883,428
rlworkgroup/garage
dqn_pong.py
dqn_pong
dqn_pong
Train DQN on PongNoFrameskip-v4 environment.
[ "Train", "DQN", "on", "PongNoFrameskip-v4", "environment." ]
def dqn_pong(ctxt=None, seed=1, buffer_size=int(50000.0), max_episode_length=500): set_seed(seed) with TFTrainer(ctxt) as trainer: n_epochs = 100 steps_per_epoch = 20 sampler_batch_size = 500 num_timesteps = n_epochs * steps_per_epoch * sampler_batch_size env = gym.make('...
['def', 'dqn_pong(ctxt=None,', 'seed=1,', 'buffer_size=int(50000.0),', 'max_episode_length=500):', 'set_seed(seed)', 'with', 'TFTrainer(ctxt)', 'as', 'trainer:', 'n_epochs', '=', '100', 'steps_per_epoch', '=', '20', 'sampler_batch_size', '=', '500', 'num_timesteps', '=', 'n_epochs', '*', 'steps_per_epoch', '*', 'sample...
200,270
Trusted-AI/AIX360
gwbe.py
GlobalWBExplainer.fit
fit
Train a surrogate model.
[ "Train", "a", "surrogate", "model." ]
def fit(self, *argv, **kwargs): raise NotImplementedError
['def', 'fit(self,', '*argv,', '**kwargs):', 'raise', 'NotImplementedError']
413,236
CityU-AIM-Group/SIGMA
env.py
setup_custom_environment
setup_custom_environment
Load custom environment setup from a Python source file and run the setup function.
[ "Load", "custom", "environment", "setup", "from", "a", "Python", "source", "file", "and", "run", "the", "setup", "function." ]
def setup_custom_environment(custom_module_path): module = import_file('fcos_core.utils.env.custom_module', custom_module_path) assert hasattr(module, 'setup_environment') and callable(module.setup_environment), "Custom environment module defined in {} does not have the required callable attribute 'setup_enviro...
['def', 'setup_custom_environment(custom_module_path):', 'module', '=', "import_file('fcos_core.utils.env.custom_module',", 'custom_module_path)', 'assert', 'hasattr(module,', "'setup_environment')", 'and', 'callable(module.setup_environment),', '"Custom', 'environment', 'module', 'defined', 'in', '{}', 'does', 'not', ...
934,600
google-research/scenic
cc12m_table_dataset.py
get_default_dataset_config
get_default_dataset_config
Gets default configs for wit_internal (en) dataset.
[ "Gets", "default", "configs", "for", "wit_internal", "(en)", "dataset." ]
def get_default_dataset_config(): dataset_configs = ml_collections.ConfigDict() dataset_configs.dataset_dir = '' dataset_configs.train_split = 'full' dataset_configs.output_max_num_tokens = OUTPUT_MAX_LENGTH dataset_configs.knowledge_max_num_tokens = OUTPUT_MAX_LENGTH dataset_configs.image_size ...
['def', 'get_default_dataset_config():', 'dataset_configs', '=', 'ml_collections.ConfigDict()', 'dataset_configs.dataset_dir', '=', "''", 'dataset_configs.train_split', '=', "'full'", 'dataset_configs.output_max_num_tokens', '=', 'OUTPUT_MAX_LENGTH', 'dataset_configs.knowledge_max_num_tokens', '=', 'OUTPUT_MAX_LENGTH',...
846,801
thaines/helit
exemplars.py
ExemplarSet.exemplars
exemplars
Returns how many exemplars are provided.
[ "Returns", "how", "many", "exemplars", "are", "provided." ]
def exemplars(self): raise NotImplementedError
['def', 'exemplars(self):', 'raise', 'NotImplementedError']
591,284
srai-lab/srai
test_gtfs_loader.py
test_gtfs_loader_skip_validation
test_gtfs_loader_skip_validation
Test GTFSLoader with invalid feed.
[ "Test", "GTFSLoader", "with", "invalid", "feed." ]
def test_gtfs_loader_skip_validation(feed: Any, mocker: MockerFixture, gtfs_validation_ok: pd.DataFrame) -> None: feed.validate.return_value = gtfs_validation_ok mocker.patch('gtfs_kit.read_feed', return_value=feed) loader = GTFSLoader() loader.load(Path('feed.zip').resolve(), skip_validation=True) ...
['def', 'test_gtfs_loader_skip_validation(feed:', 'Any,', 'mocker:', 'MockerFixture,', 'gtfs_validation_ok:', 'pd.DataFrame)', '->', 'None:', 'feed.validate.return_value', '=', 'gtfs_validation_ok', "mocker.patch('gtfs_kit.read_feed',", 'return_value=feed)', 'loader', '=', 'GTFSLoader()', "loader.load(Path('feed.zip')....
372,021
myothida/Supervised-Machine-Learning
common.py
all_none
all_none
Returns a boolean indicating if all arguments are None.
[ "Returns", "a", "boolean", "indicating", "if", "all", "arguments", "are", "None." ]
def all_none(*args) -> bool: return all((arg is None for arg in args))
['def', 'all_none(*args)', '->', 'bool:', 'return', 'all((arg', 'is', 'None', 'for', 'arg', 'in', 'args))']
442,336
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
_DictWrapper.Total
Total
Returns the total of the frequencies/probabilities in the map.
[ "Returns", "the", "total", "of", "the", "frequencies/probabilities", "in", "the", "map." ]
def Total(self): total = sum(self.d.values()) return total
['def', 'Total(self):', 'total', '=', 'sum(self.d.values())', 'return', 'total']
12,904
NJU-LHRS/official-CMID
potsdam.py
PotsdamDataset.pre_eval
pre_eval
Collect eval result from each iteration.
[ "Collect", "eval", "result", "from", "each", "iteration." ]
def pre_eval(self, preds, indices): if not isinstance(indices, list): indices = [indices] if not isinstance(preds, list): preds = [preds] pre_eval_results = [] for (pred, index) in zip(preds, indices): seg_map = self.get_gt_seg_map_by_idx(index) pre_eval_results.append(in...
['def', 'pre_eval(self,', 'preds,', 'indices):', 'if', 'not', 'isinstance(indices,', 'list):', 'indices', '=', '[indices]', 'if', 'not', 'isinstance(preds,', 'list):', 'preds', '=', '[preds]', 'pre_eval_results', '=', '[]', 'for', '(pred,', 'index)', 'in', 'zip(preds,', 'indices):', 'seg_map', '=', 'self.get_gt_seg_map...
250,213
TonghanWang/ROMA
starcraft2.py
StarCraft2Env.seed
seed
Returns the random seed used by the environment.
[ "Returns", "the", "random", "seed", "used", "by", "the", "environment." ]
def seed(self): return self._seed
['def', 'seed(self):', 'return', 'self._seed']
827,242
sek788432/Waymo-2D-Object-Detection
spatial_transform_ops.py
nearest_upsampling
nearest_upsampling
Nearest neighbor upsampling implementation.
[ "Nearest", "neighbor", "upsampling", "implementation." ]
def nearest_upsampling(data, scale): with tf.name_scope('nearest_upsampling'): (bs, _, _, c) = data.get_shape().as_list() shape = tf.shape(input=data) h = shape[1] w = shape[2] bs = -1 if bs is None else bs data = tf.tile(tf.reshape(data, [bs, h, 1, w, 1, c]), [1, 1, ...
['def', 'nearest_upsampling(data,', 'scale):', 'with', "tf.name_scope('nearest_upsampling'):", '(bs,', '_,', '_,', 'c)', '=', 'data.get_shape().as_list()', 'shape', '=', 'tf.shape(input=data)', 'h', '=', 'shape[1]', 'w', '=', 'shape[2]', 'bs', '=', '-1', 'if', 'bs', 'is', 'None', 'else', 'bs', 'data', '=', 'tf.tile(tf....
973,291
liang-hou/slimgan
image_loader.py
sample_dataset_images
sample_dataset_images
Randomly samples the dataset for images.
[ "Randomly", "samples", "the", "dataset", "for", "images." ]
def sample_dataset_images(dataset, num_samples): if len(dataset) < num_samples: raise ValueError('Given dataset has less than num_samples images: {} given but requires at least {}.'.format(len(dataset), num_samples)) choices = random.sample(range(len(dataset)), num_samples) images = [] for i in ...
['def', 'sample_dataset_images(dataset,', 'num_samples):', 'if', 'len(dataset)', '<', 'num_samples:', 'raise', "ValueError('Given", 'dataset', 'has', 'less', 'than', 'num_samples', 'images:', '{}', 'given', 'but', 'requires', 'at', 'least', "{}.'.format(len(dataset),", 'num_samples))', 'choices', '=', 'random.sample(ra...
878,245
brain-research/realistic-ssl-evaluation
train_model.py
make_unlabeled_data_filter_fn
make_unlabeled_data_filter_fn
Make filter for certain classes and a random fraction of unlabeled data.
[ "Make", "filter", "for", "certain", "classes", "and", "a", "random", "fraction", "of", "unlabeled", "data." ]
def make_unlabeled_data_filter_fn(): class_filter = tf_utils.filter_fn_from_comma_delimited(FLAGS.unlabeled_classes_filter) def random_frac_filter(fkey): return tf_utils.hash_float(fkey) < FLAGS.unlabeled_data_random_fraction return lambda _, label, fkey: class_filter(label) & random_frac_filter(fk...
['def', 'make_unlabeled_data_filter_fn():', 'class_filter', '=', 'tf_utils.filter_fn_from_comma_delimited(FLAGS.unlabeled_classes_filter)', 'def', 'random_frac_filter(fkey):', 'return', 'tf_utils.hash_float(fkey)', '<', 'FLAGS.unlabeled_data_random_fraction', 'return', 'lambda', '_,', 'label,', 'fkey:', 'class_filter(l...
308,982
Ruturaj123/Flowchart-Detection
utils.py
flatten
flatten
Takes a list of lists and returns a list of the elements.
[ "Takes", "a", "list", "of", "lists", "and", "returns", "a", "list", "of", "the", "elements." ]
def flatten(list_of_lists): flat_list = [] flat_list_idxs = [] start_idx = 0 for item in list_of_lists: if isinstance(item, list): flat_list += item l = len(item) idxs = range(start_idx, start_idx + l) start_idx = start_idx + l else: ...
['def', 'flatten(list_of_lists):', 'flat_list', '=', '[]', 'flat_list_idxs', '=', '[]', 'start_idx', '=', '0', 'for', 'item', 'in', 'list_of_lists:', 'if', 'isinstance(item,', 'list):', 'flat_list', '+=', 'item', 'l', '=', 'len(item)', 'idxs', '=', 'range(start_idx,', 'start_idx', '+', 'l)', 'start_idx', '=', 'start_id...
585,868
dvlab-research/FocalsConv
utils.py
sort_by_indices2
sort_by_indices2
To sort the sparse features with its indices in a convenient manner.
[ "To", "sort", "the", "sparse", "features", "with", "its", "indices", "in", "a", "convenient", "manner." ]
def sort_by_indices2(features, indices, features_add=None): idx = indices idx_sum = idx.select(1, 0) * idx[:, 1].max() * idx[:, 2].max() * idx[:, 3].max() + idx.select(1, 1) * idx[:, 2].max() * idx[:, 3].max() + idx.select(1, 2) * idx[:, 3].max() + idx.select(1, 3) (_, ind) = idx_sum.sort() features = f...
['def', 'sort_by_indices2(features,', 'indices,', 'features_add=None):', 'idx', '=', 'indices', 'idx_sum', '=', 'idx.select(1,', '0)', '*', 'idx[:,', '1].max()', '*', 'idx[:,', '2].max()', '*', 'idx[:,', '3].max()', '+', 'idx.select(1,', '1)', '*', 'idx[:,', '2].max()', '*', 'idx[:,', '3].max()', '+', 'idx.select(1,', ...
608,275
Erfanafshar/Principles-and-Applications-of---graph-coloring
colors.py
LightSource.direction
direction
The unit vector direction towards the light source.
[ "The", "unit", "vector", "direction", "towards", "the", "light", "source." ]
def direction(self): az = np.radians(90 - self.azdeg) alt = np.radians(self.altdeg) return np.array([np.cos(az) * np.cos(alt), np.sin(az) * np.cos(alt), np.sin(alt)])
['def', 'direction(self):', 'az', '=', 'np.radians(90', '-', 'self.azdeg)', 'alt', '=', 'np.radians(self.altdeg)', 'return', 'np.array([np.cos(az)', '*', 'np.cos(alt),', 'np.sin(az)', '*', 'np.cos(alt),', 'np.sin(alt)])']
306,604
weimin17/Object-Detection_HelmetDetection
show_and_tell_model.py
ShowAndTellModel.is_training
is_training
Returns true if the model is built for training mode.
[ "Returns", "true", "if", "the", "model", "is", "built", "for", "training", "mode." ]
def is_training(self): return self.mode == 'train'
['def', 'is_training(self):', 'return', 'self.mode', '==', "'train'"]
763,066
microsoft/MASS
lowercase_and_remove_accent.py
run_strip_accents
run_strip_accents
Strips accents from a piece of text.
[ "Strips", "accents", "from", "a", "piece", "of", "text." ]
def run_strip_accents(text): text = unicodedata.normalize('NFD', text) output = [] for char in text: cat = unicodedata.category(char) if cat == 'Mn': continue output.append(char) return ''.join(output)
['def', 'run_strip_accents(text):', 'text', '=', "unicodedata.normalize('NFD',", 'text)', 'output', '=', '[]', 'for', 'char', 'in', 'text:', 'cat', '=', 'unicodedata.category(char)', 'if', 'cat', '==', "'Mn':", 'continue', 'output.append(char)', 'return', "''.join(output)"]
646,120
RasaHQ/rasa_core
generator.py
TrackerWithCachedStates.update
update
Modify the state of the tracker according to an ``Event``.
[ "Modify", "the", "state", "of", "the", "tracker", "according", "to", "an", "``Event``." ]
def update(self, event: Event, skip_states: bool=False) -> None: if self._states is None and (not skip_states): self._states = self.past_states(self.domain) super(TrackerWithCachedStates, self).update(event) if not skip_states: if isinstance(event, ActionExecuted): pass e...
['def', 'update(self,', 'event:', 'Event,', 'skip_states:', 'bool=False)', '->', 'None:', 'if', 'self._states', 'is', 'None', 'and', '(not', 'skip_states):', 'self._states', '=', 'self.past_states(self.domain)', 'super(TrackerWithCachedStates,', 'self).update(event)', 'if', 'not', 'skip_states:', 'if', 'isinstance(even...
838,360
thaines/helit
loo_cov.py
PrecisionLOO.solve
solve
Trys all the options, and selects the one that provides the best nll.
[ "Trys", "all", "the", "options,", "and", "selects", "the", "one", "that", "provides", "the", "best", "nll." ]
def solve(self, callback=None): self.best = None bestNLL = None for (i, var) in enumerate(self.grid): if callback != None: callback(i, len(self.grid)) nll = self.calcVar(var) if numpy.isfinite(nll) and (self.best == None or nll < bestNLL): self.best = var ...
['def', 'solve(self,', 'callback=None):', 'self.best', '=', 'None', 'bestNLL', '=', 'None', 'for', '(i,', 'var)', 'in', 'enumerate(self.grid):', 'if', 'callback', '!=', 'None:', 'callback(i,', 'len(self.grid))', 'nll', '=', 'self.calcVar(var)', 'if', 'numpy.isfinite(nll)', 'and', '(self.best', '==', 'None', 'or', 'nll'...
592,041
JonasLandman/QCNN
wheel.py
Wheel.get_formatted_file_tags
get_formatted_file_tags
Return the wheel's tags as a sorted list of strings.
[ "Return", "the", "wheel's", "tags", "as", "a", "sorted", "list", "of", "strings." ]
def get_formatted_file_tags(self): return sorted((format_tag(tag) for tag in self.file_tags))
['def', 'get_formatted_file_tags(self):', 'return', 'sorted((format_tag(tag)', 'for', 'tag', 'in', 'self.file_tags))']
302,804
ameet-1997/AttentionGuidance
test_utils_summarization.py
SummarizationDataProcessingTest.test_process_story_no_highlights
test_process_story_no_highlights
Processing a story with no highlights returns an empty list for the summary.
[ "Processing", "a", "story", "with", "no", "highlights", "returns", "an", "empty", "list", "for", "the", "summary." ]
def test_process_story_no_highlights(self): raw_story = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' (_, summary_lines) = process_story(raw_story) self.assertEqual(summary_l...
['def', 'test_process_story_no_highlights(self):', 'raw_story', '=', "'It", 'was', 'the', 'year', 'of', 'Our', 'Lord', 'one', 'thousand', 'seven', 'hundred', 'and\\n', 'seventy-five.\\n\\nSpiritual', 'revelations', 'were', 'conceded', 'to', 'England', 'at', 'that\\n', 'favoured', 'period,', 'as', 'at', "this.'", '(_,',...
92,826
ldkong1205/LaserMix
handle_objs.py
filter_outside_objs
filter_outside_objs
Function to filter the objects label outside the image.
[ "Function", "to", "filter", "the", "objects", "label", "outside", "the", "image." ]
def filter_outside_objs(gt_bboxes_list: List[Tensor], gt_labels_list: List[Tensor], gt_bboxes_3d_list: List[CameraInstance3DBoxes], gt_labels_3d_list: List[Tensor], centers2d_list: List[Tensor], img_metas: List[dict]) -> None: bs = len(centers2d_list) for i in range(bs): centers2d = centers2d_list[i].cl...
['def', 'filter_outside_objs(gt_bboxes_list:', 'List[Tensor],', 'gt_labels_list:', 'List[Tensor],', 'gt_bboxes_3d_list:', 'List[CameraInstance3DBoxes],', 'gt_labels_3d_list:', 'List[Tensor],', 'centers2d_list:', 'List[Tensor],', 'img_metas:', 'List[dict])', '->', 'None:', 'bs', '=', 'len(centers2d_list)', 'for', 'i', '...
624,317
scikit-learn/scikit-learn
plot_species_distribution_modeling.py
plot_species_distribution
plot_species_distribution
Plot the species distribution.
[ "Plot", "the", "species", "distribution." ]
def plot_species_distribution(species=('bradypus_variegatus_0', 'microryzomys_minutus_0')): if len(species) > 2: print('Note: when more than two species are provided, only the first two will be used') t0 = time() data = fetch_species_distributions() (xgrid, ygrid) = construct_grids(data) (X,...
['def', "plot_species_distribution(species=('bradypus_variegatus_0',", "'microryzomys_minutus_0')):", 'if', 'len(species)', '>', '2:', "print('Note:", 'when', 'more', 'than', 'two', 'species', 'are', 'provided,', 'only', 'the', 'first', 'two', 'will', 'be', "used')", 't0', '=', 'time()', 'data', '=', 'fetch_species_dis...
848,156
intel/neural-compressor
diagnosis.py
Diagnosis.calculate_mse
calculate_mse
Calculate MSE for specified tensors.
[ "Calculate", "MSE", "for", "specified", "tensors." ]
def calculate_mse(self, op_name: str, input_model_tensors: dict, optimized_model_tensors: dict) -> Optional[float]: input_model_op_data = input_model_tensors.get(op_name, None) optimized_model_op_data = optimized_model_tensors.get(op_name, None) if input_model_op_data is None or optimized_model_op_data is N...
['def', 'calculate_mse(self,', 'op_name:', 'str,', 'input_model_tensors:', 'dict,', 'optimized_model_tensors:', 'dict)', '->', 'Optional[float]:', 'input_model_op_data', '=', 'input_model_tensors.get(op_name,', 'None)', 'optimized_model_op_data', '=', 'optimized_model_tensors.get(op_name,', 'None)', 'if', 'input_model_...
721,532
googleapis/python-aiplatform
client.py
ScheduleServiceClient.parse_common_project_path
parse_common_project_path
Parse a project path into its component segments.
[ "Parse", "a", "project", "path", "into", "its", "component", "segments." ]
def parse_common_project_path(path: str) -> Dict[str, str]: m = re.match('^projects/(?P<project>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_common_project_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
813,980
deepmind/ai-safety-gridworlds
rocks_diamonds_test.py
RocksDiamondsTest.testNoSwitch
testNoSwitch
Do not touch switches but put 1 rock and 1 diamond in goal area.
[ "Do", "not", "touch", "switches", "but", "put", "1", "rock", "and", "1", "diamond", "in", "goal", "area." ]
def testNoSwitch(self): env = rocks_diamonds.RocksDiamondsEnvironment() env.reset() actions = 'drrrdrudrurulll' for a in actions: env.step(self._actions_dict[a]) self.assertEqual(env._episode_return, 3) self.assertEqual(env._get_hidden_reward(), 3)
['def', 'testNoSwitch(self):', 'env', '=', 'rocks_diamonds.RocksDiamondsEnvironment()', 'env.reset()', 'actions', '=', "'drrrdrudrurulll'", 'for', 'a', 'in', 'actions:', 'env.step(self._actions_dict[a])', 'self.assertEqual(env._episode_return,', '3)', 'self.assertEqual(env._get_hidden_reward(),', '3)']
412,166
matsu0228/nlp-jp
completer.py
IPCompleter.all_completions
all_completions
Wrapper around the complete method for the benefit of emacs.
[ "Wrapper", "around", "the", "complete", "method", "for", "the", "benefit", "of", "emacs." ]
def all_completions(self, text): return self.complete(text)[1]
['def', 'all_completions(self,', 'text):', 'return', 'self.complete(text)[1]']
786,536
pydsgz/DeepVOG
inferer.py
gaze_inferer.load_eyeball_model
load_eyeball_model
Load eyeball model parameters of json format from path.
[ "Load", "eyeball", "model", "parameters", "of", "json", "format", "from", "path." ]
def load_eyeball_model(self, path): loaded_dict = load_json(path) if self.eyefitter.eye_centre is not None or self.eyefitter.aver_eye_radius is not None: warnings.warn('3D eyeball exists and reloaded') self.eyefitter.eye_centre = np.array(loaded_dict['eye_centre']) self.eyefitter.aver_eye_radius...
['def', 'load_eyeball_model(self,', 'path):', 'loaded_dict', '=', 'load_json(path)', 'if', 'self.eyefitter.eye_centre', 'is', 'not', 'None', 'or', 'self.eyefitter.aver_eye_radius', 'is', 'not', 'None:', "warnings.warn('3D", 'eyeball', 'exists', 'and', "reloaded')", 'self.eyefitter.eye_centre', '=', "np.array(loaded_dic...
180,868
dgaeta/feedforward-neural-net-SDG-backprop
mnist.py
plot_images_separately
plot_images_separately
Plot the six MNIST images separately.
[ "Plot", "the", "six", "MNIST", "images", "separately." ]
def plot_images_separately(images): fig = plt.figure() for j in xrange(1, 7): ax = fig.add_subplot(1, 6, j) ax.matshow(images[j - 1], cmap=matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show()
['def', 'plot_images_separately(images):', 'fig', '=', 'plt.figure()', 'for', 'j', 'in', 'xrange(1,', '7):', 'ax', '=', 'fig.add_subplot(1,', '6,', 'j)', 'ax.matshow(images[j', '-', '1],', 'cmap=matplotlib.cm.binary)', 'plt.xticks(np.array([]))', 'plt.yticks(np.array([]))', 'plt.show()']
581,923
SurturFTW/AI-Practicals
Eightpuzzle.py
EigthPuzzleProblem.is_goal
is_goal
Returns true if a state is the goal state.
[ "Returns", "true", "if", "a", "state", "is", "the", "goal", "state." ]
def is_goal(self, state): return state == GOAL
['def', 'is_goal(self,', 'state):', 'return', 'state', '==', 'GOAL']
95,619
young-geng/m3ae_public
jax_utils.py
wrap_function_with_rng
wrap_function_with_rng
To be used as decorator, automatically bookkeep a RNG for the wrapped function.
[ "To", "be", "used", "as", "decorator,", "automatically", "bookkeep", "a", "RNG", "for", "the", "wrapped", "function." ]
def wrap_function_with_rng(rng): def wrap_function(function): def wrapped(*args, **kwargs): nonlocal rng (rng, split_rng) = jax.random.split(rng) return function(split_rng, *args, **kwargs) return wrapped return wrap_function
['def', 'wrap_function_with_rng(rng):', 'def', 'wrap_function(function):', 'def', 'wrapped(*args,', '**kwargs):', 'nonlocal', 'rng', '(rng,', 'split_rng)', '=', 'jax.random.split(rng)', 'return', 'function(split_rng,', '*args,', '**kwargs)', 'return', 'wrapped', 'return', 'wrap_function']
620,007
KalleHallden/InstaAutomator
test_utils.py
_GenericTest.test_array_rank2_eq
test_array_rank2_eq
Test two equal array of rank 2 are found equal.
[ "Test", "two", "equal", "array", "of", "rank", "2", "are", "found", "equal." ]
def test_array_rank2_eq(self): a = np.array([[1, 2], [3, 4]]) b = np.array([[1, 2], [3, 4]]) self._test_equal(a, b)
['def', 'test_array_rank2_eq(self):', 'a', '=', 'np.array([[1,', '2],', '[3,', '4]])', 'b', '=', 'np.array([[1,', '2],', '[3,', '4]])', 'self._test_equal(a,', 'b)']
231,109
sktime/sktime
test_check_estimator.py
test_check_estimator_does_not_raise
test_check_estimator_does_not_raise
Test that check_estimator does not raise exceptions on examples we know pass.
[ "Test", "that", "check_estimator", "does", "not", "raise", "exceptions", "on", "examples", "we", "know", "pass." ]
def test_check_estimator_does_not_raise(estimator_class): estimator_instance = estimator_class.create_test_instance() check_estimator(estimator_class, raise_exceptions=True, verbose=False) check_estimator(estimator_instance, raise_exceptions=True, verbose=False)
['def', 'test_check_estimator_does_not_raise(estimator_class):', 'estimator_instance', '=', 'estimator_class.create_test_instance()', 'check_estimator(estimator_class,', 'raise_exceptions=True,', 'verbose=False)', 'check_estimator(estimator_instance,', 'raise_exceptions=True,', 'verbose=False)']
878,041
alibaba/EasyCV
ms_utils.py
to_ms_config
to_ms_config
Convert EasyCV config to ModelScope style.
[ "Convert", "EasyCV", "config", "to", "ModelScope", "style." ]
def to_ms_config(cfg, task, ms_model_name, pipeline_name, save_path=None, reserved_keys=[], dump=True): if isinstance(cfg, str): easycv_cfg = Config.fromfile(cfg) if dump and save_path is None: save_dir = os.path.dirname(cfg) save_name = MODELSCOPE_PREFIX + '_' + os.path.spli...
['def', 'to_ms_config(cfg,', 'task,', 'ms_model_name,', 'pipeline_name,', 'save_path=None,', 'reserved_keys=[],', 'dump=True):', 'if', 'isinstance(cfg,', 'str):', 'easycv_cfg', '=', 'Config.fromfile(cfg)', 'if', 'dump', 'and', 'save_path', 'is', 'None:', 'save_dir', '=', 'os.path.dirname(cfg)', 'save_name', '=', 'MODEL...
546,896
Oporto/CS4341_Artificial_Inteligence
__init__.py
get_terminal_size
get_terminal_size
Returns a tuple (x, y) representing the width(x) and the height(x) in characters of the terminal window.
[ "Returns", "a", "tuple", "(x,", "y)", "representing", "the", "width(x)", "and", "the", "height(x)", "in", "characters", "of", "the", "terminal", "window." ]
def get_terminal_size(): def ioctl_GWINSZ(fd): try: import fcntl import termios import struct cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return None if cr == (0, 0): return None ...
['def', 'get_terminal_size():', 'def', 'ioctl_GWINSZ(fd):', 'try:', 'import', 'fcntl', 'import', 'termios', 'import', 'struct', 'cr', '=', "struct.unpack('hh',", 'fcntl.ioctl(fd,', 'termios.TIOCGWINSZ,', "'1234'))", 'except:', 'return', 'None', 'if', 'cr', '==', '(0,', '0):', 'return', 'None', 'return', 'cr', 'cr', '='...
190,893
facebookresearch/fvcore
test_transform.py
TestTransforms.test_grid_sample_img_transform
test_grid_sample_img_transform
Test grid sampling tranformation.
[ "Test", "grid", "sampling", "tranformation." ]
def test_grid_sample_img_transform(self): for interp in ['nearest']: grid_2d = np.stack(np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10)), axis=2).astype(float) grid = np.tile(grid_2d[None, :, :, :], [8, 1, 1, 1]) transformer = T.GridSampleTransform(grid, interp) (img_h, im...
['def', 'test_grid_sample_img_transform(self):', 'for', 'interp', 'in', "['nearest']:", 'grid_2d', '=', 'np.stack(np.meshgrid(np.linspace(-1,', '1,', '10),', 'np.linspace(-1,', '1,', '10)),', 'axis=2).astype(float)', 'grid', '=', 'np.tile(grid_2d[None,', ':,', ':,', ':],', '[8,', '1,', '1,', '1])', 'transformer', '=', ...
566,024
FreshAirTonight/af2complex
data_transforms.py
curry1
curry1
Supply all arguments but the first.
[ "Supply", "all", "arguments", "but", "the", "first." ]
def curry1(f): def fc(*args, **kwargs): return lambda x: f(x, *args, **kwargs) return fc
['def', 'curry1(f):', 'def', 'fc(*args,', '**kwargs):', 'return', 'lambda', 'x:', 'f(x,', '*args,', '**kwargs)', 'return', 'fc']
400,768
ameet-1997/Natural-Language-Processing
multipartiterank.py
MultipartiteRank.candidate_weighting
candidate_weighting
Candidate weight calculation using random walk.
[ "Candidate", "weight", "calculation", "using", "random", "walk." ]
def candidate_weighting(self, threshold=0.74, method='average', alpha=1.1): if not self.candidates: return self.topic_clustering(threshold=threshold, method=method) self.build_topic_graph() if alpha > 0.0: self.weight_adjustment(alpha) self.weights = nx.pagerank_scipy(self.graph)
['def', 'candidate_weighting(self,', 'threshold=0.74,', "method='average',", 'alpha=1.1):', 'if', 'not', 'self.candidates:', 'return', 'self.topic_clustering(threshold=threshold,', 'method=method)', 'self.build_topic_graph()', 'if', 'alpha', '>', '0.0:', 'self.weight_adjustment(alpha)', 'self.weights', '=', 'nx.pageran...
660,098
flavioschneider/rl-transfer-
test_mlp_module.py
TestMLPModel.test_mlp_with_learnable_non_linear_function
test_mlp_with_learnable_non_linear_function
Test MLPModule with learnable non-linear functions.
[ "Test", "MLPModule", "with", "learnable", "non-linear", "functions." ]
def test_mlp_with_learnable_non_linear_function(self): (input_dim, output_dim, hidden_sizes) = (1, 1, (3, 2)) input_val = -torch.ones([1, input_dim], dtype=torch.float32) module = MLPModule(input_dim=input_dim, output_dim=output_dim, hidden_nonlinearity=torch.nn.PReLU(init=10.0), hidden_sizes=hidden_sizes, ...
['def', 'test_mlp_with_learnable_non_linear_function(self):', '(input_dim,', 'output_dim,', 'hidden_sizes)', '=', '(1,', '1,', '(3,', '2))', 'input_val', '=', '-torch.ones([1,', 'input_dim],', 'dtype=torch.float32)', 'module', '=', 'MLPModule(input_dim=input_dim,', 'output_dim=output_dim,', 'hidden_nonlinearity=torch.n...
861,848
declare-lab/speech-adapters
phoneme_recognition.py
seed_worker
seed_worker
Helper function to set worker seed during Dataloader initialization.
[ "Helper", "function", "to", "set", "worker", "seed", "during", "Dataloader", "initialization." ]
def seed_worker(_): worker_seed = torch.initial_seed() % 2 ** 32 set_seed(worker_seed)
['def', 'seed_worker(_):', 'worker_seed', '=', 'torch.initial_seed()', '%', '2', '**', '32', 'set_seed(worker_seed)']
894,861
p-lambda/wilds
wilds_unlabeled_dataset.py
WILDSUnlabeledDataset.split_dict
split_dict
A dictionary mapping splits to integer identifiers (used in split_array), Keys should match up with split_names.
[ "A", "dictionary", "mapping", "splits", "to", "integer", "identifiers", "(used", "in", "split_array),", "Keys", "should", "match", "up", "with", "split_names." ]
def split_dict(self): return getattr(self, '_split_dict', WILDSUnlabeledDataset.DEFAULT_SPLITS)
['def', 'split_dict(self):', 'return', 'getattr(self,', "'_split_dict',", 'WILDSUnlabeledDataset.DEFAULT_SPLITS)']
959,763
sklearn-theano/sklearn-theano
encoder.py
GroupSizer
GroupSizer
Returns a sizer for a group field.
[ "Returns", "a", "sizer", "for", "a", "group", "field." ]
def GroupSizer(field_number, is_repeated, is_packed): tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() return...
['def', 'GroupSizer(field_number,', 'is_repeated,', 'is_packed):', 'tag_size', '=', '_TagSize(field_number)', '*', '2', 'assert', 'not', 'is_packed', 'if', 'is_repeated:', 'def', 'RepeatedFieldSize(value):', 'result', '=', 'tag_size', '*', 'len(value)', 'for', 'element', 'in', 'value:', 'result', '+=', 'element.ByteSiz...
351,153
hyz-xmaster/swa_object_detection
ssd_head.py
SSDHead.loss_single
loss_single
Compute loss of a single image.
[ "Compute", "loss", "of", "a", "single", "image." ]
def loss_single(self, cls_score, bbox_pred, anchor, labels, label_weights, bbox_targets, bbox_weights, num_total_samples): loss_cls_all = F.cross_entropy(cls_score, labels, reduction='none') * label_weights pos_inds = ((labels >= 0) & (labels < self.num_classes)).nonzero().reshape(-1) neg_inds = (labels == ...
['def', 'loss_single(self,', 'cls_score,', 'bbox_pred,', 'anchor,', 'labels,', 'label_weights,', 'bbox_targets,', 'bbox_weights,', 'num_total_samples):', 'loss_cls_all', '=', 'F.cross_entropy(cls_score,', 'labels,', "reduction='none')", '*', 'label_weights', 'pos_inds', '=', '((labels', '>=', '0)', '&', '(labels', '<',...
882,553
erfaneshrati/meta-transfer-learning
misc.py
resnet_conv_block
resnet_conv_block
The function to forward a conv layer.
[ "The", "function", "to", "forward", "a", "conv", "layer." ]
def resnet_conv_block(inp, cweight, bweight, reuse, scope, activation=leaky_relu): (stride, no_stride) = ([1, 2, 2, 1], [1, 1, 1, 1]) if FLAGS.activation == 'leaky_relu': activation = leaky_relu elif FLAGS.activation == 'relu': activation = tf.nn.relu else: activation = None ...
['def', 'resnet_conv_block(inp,', 'cweight,', 'bweight,', 'reuse,', 'scope,', 'activation=leaky_relu):', '(stride,', 'no_stride)', '=', '([1,', '2,', '2,', '1],', '[1,', '1,', '1,', '1])', 'if', 'FLAGS.activation', '==', "'leaky_relu':", 'activation', '=', 'leaky_relu', 'elif', 'FLAGS.activation', '==', "'relu':", 'act...
633,271
PaccMann/fdsa
shapes_data.py
Shapes.datapoints_square
datapoints_square
Generates a set of datapoints sampled from the perimeter of a square.
[ "Generates", "a", "set", "of", "datapoints", "sampled", "from", "the", "perimeter", "of", "a", "square." ]
def datapoints_square(self, set_length: int, sample_id: int, min_radius: int=100) -> Tuple: (cx, cy, radius) = self.datapoints_circle(1, sample_id, use='square') side = np.sqrt(radius * radius * 2) half_side = side * 0.5 (r, c) = draw.rectangle_perimeter((cx - half_side, cy - half_side), extent=(side, s...
['def', 'datapoints_square(self,', 'set_length:', 'int,', 'sample_id:', 'int,', 'min_radius:', 'int=100)', '->', 'Tuple:', '(cx,', 'cy,', 'radius)', '=', 'self.datapoints_circle(1,', 'sample_id,', "use='square')", 'side', '=', 'np.sqrt(radius', '*', 'radius', '*', '2)', 'half_side', '=', 'side', '*', '0.5', '(r,', 'c)'...
560,849
open-mmlab/mmcv
diff_iou_rotated.py
box2corners
box2corners
Convert rotated 2d box coordinate to corners.
[ "Convert", "rotated", "2d", "box", "coordinate", "to", "corners." ]
def box2corners(box: Tensor) -> Tensor: B = box.size()[0] (x, y, w, h, alpha) = box.split([1, 1, 1, 1, 1], dim=-1) x4 = box.new_tensor([0.5, -0.5, -0.5, 0.5]).to(box.device) x4 = x4 * w y4 = box.new_tensor([0.5, 0.5, -0.5, -0.5]).to(box.device) y4 = y4 * h corners = torch.stack([x4, y4], dim...
['def', 'box2corners(box:', 'Tensor)', '->', 'Tensor:', 'B', '=', 'box.size()[0]', '(x,', 'y,', 'w,', 'h,', 'alpha)', '=', 'box.split([1,', '1,', '1,', '1,', '1],', 'dim=-1)', 'x4', '=', 'box.new_tensor([0.5,', '-0.5,', '-0.5,', '0.5]).to(box.device)', 'x4', '=', 'x4', '*', 'w', 'y4', '=', 'box.new_tensor([0.5,', '0.5,...
631,523
pykale/pykale
model.py
get_model
get_model
Builds and returns a model and associated hyper-parameters according to the config object passed.
[ "Builds", "and", "returns", "a", "model", "and", "associated", "hyper-parameters", "according", "to", "the", "config", "object", "passed." ]
def get_model(cfg, dataset, num_channels): config_params = get_config(cfg) train_params = config_params['train_params'] train_params_local = deepcopy(train_params) if cfg.DATASET.NAME.upper() == 'DIGITS': feature_network = SmallCNNFeature(num_channels) else: feature_network = ResNet1...
['def', 'get_model(cfg,', 'dataset,', 'num_channels):', 'config_params', '=', 'get_config(cfg)', 'train_params', '=', "config_params['train_params']", 'train_params_local', '=', 'deepcopy(train_params)', 'if', 'cfg.DATASET.NAME.upper()', '==', "'DIGITS':", 'feature_network', '=', 'SmallCNNFeature(num_channels)', 'else:...
819,612
RasaHQ/rasa
callback.py
RasaTrainingLogger.on_epoch_end
on_epoch_end
Updates the logging output on every epoch end.
[ "Updates", "the", "logging", "output", "on", "every", "epoch", "end." ]
def on_epoch_end(self, epoch: int, logs: Optional[Dict[Text, Any]]=None) -> None: self.progress_bar.update(1) self.progress_bar.set_postfix(logs)
['def', 'on_epoch_end(self,', 'epoch:', 'int,', 'logs:', 'Optional[Dict[Text,', 'Any]]=None)', '->', 'None:', 'self.progress_bar.update(1)', 'self.progress_bar.set_postfix(logs)']
837,889
ivanmontero/autobot
modeling_tf_funnel.py
TFFunnelAttentionStructure.pool_tensor
pool_tensor
Apply 1D pooling to a tensor of size [B x T (x H)].
[ "Apply", "1D", "pooling", "to", "a", "tensor", "of", "size", "[B", "x", "T", "(x", "H)]." ]
def pool_tensor(self, tensor, mode='mean', stride=2): if tensor is None: return None if isinstance(tensor, (tuple, list)): return type(tensor)((self.pool_tensor(tensor, mode=mode, stride=stride) for x in tensor)) if self.separate_cls: suffix = tensor[:, :-1] if self.truncate_seq else...
['def', 'pool_tensor(self,', 'tensor,', "mode='mean',", 'stride=2):', 'if', 'tensor', 'is', 'None:', 'return', 'None', 'if', 'isinstance(tensor,', '(tuple,', 'list)):', 'return', 'type(tensor)((self.pool_tensor(tensor,', 'mode=mode,', 'stride=stride)', 'for', 'x', 'in', 'tensor))', 'if', 'self.separate_cls:', 'suffix',...
418,064
wbsth/cs50ai
generate.py
CrosswordCreator.letter_grid
letter_grid
Return 2D array representing a given assignment.
[ "Return", "2D", "array", "representing", "a", "given", "assignment." ]
def letter_grid(self, assignment): letters = [[None for _ in range(self.crossword.width)] for _ in range(self.crossword.height)] for (variable, word) in assignment.items(): direction = variable.direction for k in range(len(word)): i = variable.i + (k if direction == Variable.DOWN els...
['def', 'letter_grid(self,', 'assignment):', 'letters', '=', '[[None', 'for', '_', 'in', 'range(self.crossword.width)]', 'for', '_', 'in', 'range(self.crossword.height)]', 'for', '(variable,', 'word)', 'in', 'assignment.items():', 'direction', '=', 'variable.direction', 'for', 'k', 'in', 'range(len(word)):', 'i', '=', ...
192,716
fairlearn/fairlearn
utility_parity.py
UtilityParity.default_objective
default_objective
Return the default objective for moments of this kind.
[ "Return", "the", "default", "objective", "for", "moments", "of", "this", "kind." ]
def default_objective(self): return ErrorRate()
['def', 'default_objective(self):', 'return', 'ErrorRate()']
558,433
OpenMDAO/OpenMDAO-Framework
systems.py
SimpleSystem.solve_linear
solve_linear
Single linear solve solution applied to whatever input is sitting in the RHS vector.
[ "Single", "linear", "solve", "solution", "applied", "to", "whatever", "input", "is", "sitting", "in", "the", "RHS", "vector." ]
def solve_linear(self, options=None): self.sol_vec.array[:] = self.rhs_vec.array[:]
['def', 'solve_linear(self,', 'options=None):', 'self.sol_vec.array[:]', '=', 'self.rhs_vec.array[:]']
276,096
KalleHallden/InstaAutomator
msvc.py
RegistryInfo.visualstudio
visualstudio
Microsoft Visual Studio root registry key.
[ "Microsoft", "Visual", "Studio", "root", "registry", "key." ]
def visualstudio(self): return 'VisualStudio'
['def', 'visualstudio(self):', 'return', "'VisualStudio'"]
233,611
wandb/wandb
runset.py
Runset.from_json
from_json
This has a custom implementation because sometimes runsets are missing the project field.
[ "This", "has", "a", "custom", "implementation", "because", "sometimes", "runsets", "are", "missing", "the", "project", "field." ]
def from_json(cls, spec: Dict[str, Any]) -> T: obj = cls() obj._spec = spec project = spec.get('project') if project: obj.entity = project.get('entityName', coalesce(PublicApi().default_entity, '')) obj.project = project.get('name') else: obj.entity = coalesce(PublicApi().def...
['def', 'from_json(cls,', 'spec:', 'Dict[str,', 'Any])', '->', 'T:', 'obj', '=', 'cls()', 'obj._spec', '=', 'spec', 'project', '=', "spec.get('project')", 'if', 'project:', 'obj.entity', '=', "project.get('entityName',", 'coalesce(PublicApi().default_entity,', "''))", 'obj.project', '=', "project.get('name')", 'else:',...
941,490
Speech-Lab-IITM/CCC-wav2vec-2.0
fairseq_optimizer.py
FairseqOptimizer.supports_flat_params
supports_flat_params
Whether the optimizer supports collapsing of the model parameters/gradients into a single contiguous Tensor.
[ "Whether", "the", "optimizer", "supports", "collapsing", "of", "the", "model", "parameters/gradients", "into", "a", "single", "contiguous", "Tensor." ]
def supports_flat_params(self): if hasattr(self.optimizer, 'supports_flat_params'): return self.optimizer.supports_flat_params return False
['def', 'supports_flat_params(self):', 'if', 'hasattr(self.optimizer,', "'supports_flat_params'):", 'return', 'self.optimizer.supports_flat_params', 'return', 'False']
104,050
facebookresearch/CompilerGym
compiler_env.py
CompilerEnv.reward
reward
A view of the available reward spaces that permits on-demand computation of rewards.
[ "A", "view", "of", "the", "available", "reward", "spaces", "that", "permits", "on-demand", "computation", "of", "rewards." ]
def reward(self) -> RewardView: raise NotImplementedError('abstract method')
['def', 'reward(self)', '->', 'RewardView:', 'raise', "NotImplementedError('abstract", "method')"]
125,443
Eric3911/OpenAGI
schedule.py
PipeSchedule.stage
stage
Stage index used to configure this schedule.
[ "Stage", "index", "used", "to", "configure", "this", "schedule." ]
def stage(self): return self.stage_id
['def', 'stage(self):', 'return', 'self.stage_id']
252,174
deepmind/trfl
value_ops_test.py
QVMAXTest.testNoOtherGradients
testNoOtherGradients
Tests no gradient propagates through things other than v_tm1.
[ "Tests", "no", "gradient", "propagates", "through", "things", "other", "than", "v_tm1." ]
def testNoOtherGradients(self): gradients = tf.gradients([self.loss_op], [self.q_t, self.r_t, self.pcont_t]) self.assertEqual(gradients, [None] * len(gradients))
['def', 'testNoOtherGradients(self):', 'gradients', '=', 'tf.gradients([self.loss_op],', '[self.q_t,', 'self.r_t,', 'self.pcont_t])', 'self.assertEqual(gradients,', '[None]', '*', 'len(gradients))']
356,270
arshpreetsingh/quantopian-machinelearning
_precord.py
PRecord.serialize
serialize
Serialize the current PRecord using custom serializer functions for fields where such have been supplied.
[ "Serialize", "the", "current", "PRecord", "using", "custom", "serializer", "functions", "for", "fields", "where", "such", "have", "been", "supplied." ]
def serialize(self, format=None): return dict(((k, serialize(self._precord_fields[k].serializer, format, v)) for (k, v) in self.items()))
['def', 'serialize(self,', 'format=None):', 'return', 'dict(((k,', 'serialize(self._precord_fields[k].serializer,', 'format,', 'v))', 'for', '(k,', 'v)', 'in', 'self.items()))']
892,746
pathak22/noreward-rl
a3c.py
A3C.pull_batch_from_queue
pull_batch_from_queue
Take a rollout from the queue of the thread runner.
[ "Take", "a", "rollout", "from", "the", "queue", "of", "the", "thread", "runner." ]
def pull_batch_from_queue(self): rollout = self.runner.queue.get(timeout=600.0) while not rollout.terminal: try: rollout.extend(self.runner.queue.get_nowait()) except queue.Empty: break return rollout
['def', 'pull_batch_from_queue(self):', 'rollout', '=', 'self.runner.queue.get(timeout=600.0)', 'while', 'not', 'rollout.terminal:', 'try:', 'rollout.extend(self.runner.queue.get_nowait())', 'except', 'queue.Empty:', 'break', 'return', 'rollout']
249,524
matsu0228/nlp-jp
dtmmodel.py
DtmModel.train
train
Train DTM model using specified corpus and time slices.
[ "Train", "DTM", "model", "using", "specified", "corpus", "and", "time", "slices." ]
def train(self, corpus, time_slices, mode, model): self.convert_input(corpus, time_slices) arguments = '--ntopics={p0} --model={mofrl} --mode={p1} --initialize_lda={p2} --corpus_prefix={p3} --outname={p4} --alpha={p5}'.format(p0=self.num_topics, mofrl=model, p1=mode, p2=self.initialize_lda, p3=self.fcorpus(), ...
['def', 'train(self,', 'corpus,', 'time_slices,', 'mode,', 'model):', 'self.convert_input(corpus,', 'time_slices)', 'arguments', '=', "'--ntopics={p0}", '--model={mofrl}', '--mode={p1}', '--initialize_lda={p2}', '--corpus_prefix={p3}', '--outname={p4}', "--alpha={p5}'.format(p0=self.num_topics,", 'mofrl=model,', 'p1=mo...
785,938
PacktPublishing/Learning-OpenCV-5---with-Python-Fourth-Edition
managers.py
CaptureManager.enterFrame
enterFrame
Capture the next frame, if any.
[ "Capture", "the", "next", "frame,", "if", "any." ]
def enterFrame(self): assert not self._enteredFrame, 'previous enterFrame() had no matching exitFrame()' if self._capture is not None: self._enteredFrame = self._capture.grab()
['def', 'enterFrame(self):', 'assert', 'not', 'self._enteredFrame,', "'previous", 'enterFrame()', 'had', 'no', 'matching', "exitFrame()'", 'if', 'self._capture', 'is', 'not', 'None:', 'self._enteredFrame', '=', 'self._capture.grab()']
588,060
seltzerfish/guardyn
gtest_filter_unittest.py
GTestFilterUnitTest.AssertPartitionIsValid
AssertPartitionIsValid
Asserts that list_of_sets is a valid partition of set_var.
[ "Asserts", "that", "list_of_sets", "is", "a", "valid", "partition", "of", "set_var." ]
def AssertPartitionIsValid(self, set_var, list_of_sets): full_partition = [] for slice_var in list_of_sets: full_partition.extend(slice_var) self.assertEqual(len(set_var), len(full_partition)) self.assertEqual(set(set_var), set(full_partition))
['def', 'AssertPartitionIsValid(self,', 'set_var,', 'list_of_sets):', 'full_partition', '=', '[]', 'for', 'slice_var', 'in', 'list_of_sets:', 'full_partition.extend(slice_var)', 'self.assertEqual(len(set_var),', 'len(full_partition))', 'self.assertEqual(set(set_var),', 'set(full_partition))']
572,254
jbwang1997/CrossKD
loading.py
LoadProposals.transform
transform
Transform function to load proposals from file.
[ "Transform", "function", "to", "load", "proposals", "from", "file." ]
def transform(self, results: dict) -> dict: proposals = results['proposals'] assert isinstance(proposals, dict) or isinstance(proposals, BaseDataElement) bboxes = proposals['bboxes'].astype(np.float32) assert bboxes.shape[1] == 4, f'Proposals should have shapes (n, 4), but found {bboxes.shape}' if '...
['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'proposals', '=', "results['proposals']", 'assert', 'isinstance(proposals,', 'dict)', 'or', 'isinstance(proposals,', 'BaseDataElement)', 'bboxes', '=', "proposals['bboxes'].astype(np.float32)", 'assert', 'bboxes.shape[1]', '==', '4,', "f'Proposals", 'should...
490,771
arshpreetsingh/quantopian-machinelearning
tests.py
test_escaped
test_escaped
Check if the value is escaped.
[ "Check", "if", "the", "value", "is", "escaped." ]
def test_escaped(value): return hasattr(value, '__html__')
['def', 'test_escaped(value):', 'return', 'hasattr(value,', "'__html__')"]
887,652
gatheluck/FourierHeatmap
heatmap.py
eval_fourier_heatmap
eval_fourier_heatmap
Evaluate Fourier Heat Map about given architecture and dataset.
[ "Evaluate", "Fourier", "Heat", "Map", "about", "given", "architecture", "and", "dataset." ]
def eval_fourier_heatmap(input_size: int, ignore_edge_size: int, eps: float, arch: nn.Module, dataset: torchvision.datasets.VisionDataset, batch_size: int, device: torch.device, topk: Tuple[int, ...]=(1,), savedir: Optional[pathlib.Path]=None) -> List[torch.Tensor]: if input_size % 2 != 0: raise ValueError(...
['def', 'eval_fourier_heatmap(input_size:', 'int,', 'ignore_edge_size:', 'int,', 'eps:', 'float,', 'arch:', 'nn.Module,', 'dataset:', 'torchvision.datasets.VisionDataset,', 'batch_size:', 'int,', 'device:', 'torch.device,', 'topk:', 'Tuple[int,', '...]=(1,),', 'savedir:', 'Optional[pathlib.Path]=None)', '->', 'List[tor...
564,067
KalleHallden/InstaAutomator
autodist.py
check_gcc_variable_attribute
check_gcc_variable_attribute
Return True if the given variable attribute is supported.
[ "Return", "True", "if", "the", "given", "variable", "attribute", "is", "supported." ]
def check_gcc_variable_attribute(cmd, attribute): cmd._check_compiler() body = '\n#pragma GCC diagnostic error "-Wattributes"\n#pragma clang diagnostic error "-Wattributes"\n\nint %s foo;\n\nint\nmain()\n{\n return 0;\n}\n' % (attribute,) return cmd.try_compile(body, None, None) != 0
['def', 'check_gcc_variable_attribute(cmd,', 'attribute):', 'cmd._check_compiler()', 'body', '=', "'\\n#pragma", 'GCC', 'diagnostic', 'error', '"-Wattributes"\\n#pragma', 'clang', 'diagnostic', 'error', '"-Wattributes"\\n\\nint', '%s', 'foo;\\n\\nint\\nmain()\\n{\\n', 'return', "0;\\n}\\n'", '%', '(attribute,)', 'retur...
243,271
ahthie7u/cockpit
schedules.py
linear
linear
Creates a linear schedule that tracks when ``{offset + n interval | n >= 0}``.
[ "Creates", "a", "linear", "schedule", "that", "tracks", "when", "``{offset", "+", "n", "interval", "|", "n", ">=", "0}``." ]
def linear(interval, offset=0): docstring = 'Track at iterations {' + f'{offset} + n * {interval} ' + '| n >= 0}.' def schedule(global_step): shifted = global_step - offset if shifted < 0: return False else: return shifted % interval == 0 schedule.__doc__ = d...
['def', 'linear(interval,', 'offset=0):', 'docstring', '=', "'Track", 'at', 'iterations', "{'", '+', "f'{offset}", '+', 'n', '*', '{interval}', "'", '+', "'|", 'n', '>=', "0}.'", 'def', 'schedule(global_step):', 'shifted', '=', 'global_step', '-', 'offset', 'if', 'shifted', '<', '0:', 'return', 'False', 'else:', 'retur...
492,733
kubeflow/pipelines
pipeline_cli.py
MyCLI.compile_run
compile_run
Compile and run a Kubeflow pipeline.
[ "Compile", "and", "run", "a", "Kubeflow", "pipeline." ]
def compile_run(path, host, params={}): compiled_path = MyCLI.compile(path) MyCLI.run(compiled_path, host, params)
['def', 'compile_run(path,', 'host,', 'params={}):', 'compiled_path', '=', 'MyCLI.compile(path)', 'MyCLI.run(compiled_path,', 'host,', 'params)']
779,720
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjDataWrapper.stack
stack
stack buffer (nstack mjtNums).
[ "stack", "buffer", "(nstack", "mjtNums)." ]
def stack(self): return util.buf_to_npy(self._ptr.contents.stack, (self.nstack,))
['def', 'stack(self):', 'return', 'util.buf_to_npy(self._ptr.contents.stack,', '(self.nstack,))']
440,530
enuguru/artificial_intelligence_and_machine_
filetables.py
HashReader.all
all
Yields a sequence of values associated with the given key.
[ "Yields", "a", "sequence", "of", "values", "associated", "with", "the", "given", "key." ]
def all(self, key): dbfile = self.dbfile for (datapos, datalen) in self.ranges_for_key(key): yield dbfile.get(datapos, datalen)
['def', 'all(self,', 'key):', 'dbfile', '=', 'self.dbfile', 'for', '(datapos,', 'datalen)', 'in', 'self.ranges_for_key(key):', 'yield', 'dbfile.get(datapos,', 'datalen)']
133,344
replit-archive/empythoned
__init__.py
Logger.makeRecord
makeRecord
A factory method which can be overridden in subclasses to create specialized LogRecords.
[ "A", "factory", "method", "which", "can", "be", "overridden", "in", "subclasses", "to", "create", "specialized", "LogRecords." ]
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None): rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) if extra is not None: for key in extra: if key in ['message', 'asctime'] or key in rv.__dict__: raise KeyError('Attempt to o...
['def', 'makeRecord(self,', 'name,', 'level,', 'fn,', 'lno,', 'msg,', 'args,', 'exc_info,', 'func=None,', 'extra=None):', 'rv', '=', 'LogRecord(name,', 'level,', 'fn,', 'lno,', 'msg,', 'args,', 'exc_info,', 'func)', 'if', 'extra', 'is', 'not', 'None:', 'for', 'key', 'in', 'extra:', 'if', 'key', 'in', "['message',", "'a...
176,931