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
ai-forever/SEGM-model
prepare_dataset.py
preprocess_data
preprocess_data
Create and save targets for Unet training.
[ "Create", "and", "save", "targets", "for", "Unet", "training." ]
def preprocess_data(config, json_path, image_root, save_data_path): target_folder = Path('targets') image_processed_folder = Path('images_processed') save_root = Path(save_data_path).parent target_dir = save_root / target_folder os.makedirs(str(target_dir), exist_ok=True) image_processed_dir = s...
['def', 'preprocess_data(config,', 'json_path,', 'image_root,', 'save_data_path):', 'target_folder', '=', "Path('targets')", 'image_processed_folder', '=', "Path('images_processed')", 'save_root', '=', 'Path(save_data_path).parent', 'target_dir', '=', 'save_root', '/', 'target_folder', 'os.makedirs(str(target_dir),', '...
842,432
matsu0228/nlp-jp
colors.py
is_color_like
is_color_like
Return whether `c` can be interpreted as an RGB(A) color.
[ "Return", "whether", "`c`", "can", "be", "interpreted", "as", "an", "RGB(A)", "color." ]
def is_color_like(c): if _is_nth_color(c): return True try: to_rgba(c) except ValueError: return False else: return True
['def', 'is_color_like(c):', 'if', '_is_nth_color(c):', 'return', 'True', 'try:', 'to_rgba(c)', 'except', 'ValueError:', 'return', 'False', 'else:', 'return', 'True']
788,613
paulorauber/rl
utils.py
distance_loss
distance_loss
Computes a distance loss between two tensors.
[ "Computes", "a", "distance", "loss", "between", "two", "tensors." ]
def distance_loss(v1: torch.Tensor, v2: torch.Tensor, loss_function: str, strict_shape: bool=True) -> torch.Tensor: if v1.shape != v2.shape and strict_shape: raise RuntimeError(f'The input tensors have shapes {v1.shape} and {v2.shape} which are incompatible.') if loss_function == 'l2': value_los...
['def', 'distance_loss(v1:', 'torch.Tensor,', 'v2:', 'torch.Tensor,', 'loss_function:', 'str,', 'strict_shape:', 'bool=True)', '->', 'torch.Tensor:', 'if', 'v1.shape', '!=', 'v2.shape', 'and', 'strict_shape:', 'raise', "RuntimeError(f'The", 'input', 'tensors', 'have', 'shapes', '{v1.shape}', 'and', '{v2.shape}', 'which...
859,361
matsu0228/nlp-jp
manager.py
ContentsManager.delete
delete
Delete a file/directory and any associated checkpoints.
[ "Delete", "a", "file/directory", "and", "any", "associated", "checkpoints." ]
def delete(self, path): path = path.strip('/') if not path: raise HTTPError(400, "Can't delete root") self.delete_file(path) self.checkpoints.delete_all_checkpoints(path)
['def', 'delete(self,', 'path):', 'path', '=', "path.strip('/')", 'if', 'not', 'path:', 'raise', 'HTTPError(400,', '"Can\'t', 'delete', 'root")', 'self.delete_file(path)', 'self.checkpoints.delete_all_checkpoints(path)']
790,681
clvrai/spirl
sawyer_robot.py
Sawyer.set_base_xpos
set_base_xpos
Places the robot on position @pos.
[ "Places", "the", "robot", "on", "position", "@pos." ]
def set_base_xpos(self, pos): node = self.worldbody.find("./body[@name='base']") node.set('pos', array_to_string(pos - self.bottom_offset))
['def', 'set_base_xpos(self,', 'pos):', 'node', '=', 'self.worldbody.find("./body[@name=\'base\']")', "node.set('pos',", 'array_to_string(pos', '-', 'self.bottom_offset))']
896,860
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
replay_buffer.py
ReplayBuffer.add
add
Add episodes to buffer.
[ "Add", "episodes", "to", "buffer." ]
def add(self, episodes, *args): idx = 0 while self.cur_size < self.max_size and idx < len(episodes): self.buffer[self.cur_size] = episodes[idx] self.cur_size += 1 idx += 1 if idx < len(episodes): remove_idxs = self.remove_n(len(episodes) - idx) for remove_idx in remov...
['def', 'add(self,', 'episodes,', '*args):', 'idx', '=', '0', 'while', 'self.cur_size', '<', 'self.max_size', 'and', 'idx', '<', 'len(episodes):', 'self.buffer[self.cur_size]', '=', 'episodes[idx]', 'self.cur_size', '+=', '1', 'idx', '+=', '1', 'if', 'idx', '<', 'len(episodes):', 'remove_idxs', '=', 'self.remove_n(len(...
58,933
AxeldeRomblay/MLBox
test_drift_estimator.py
test_fit_drift_estimator
test_fit_drift_estimator
Test fit method of DriftEstimator class.
[ "Test", "fit", "method", "of", "DriftEstimator", "class." ]
def test_fit_drift_estimator(): df_train = pd.read_csv('data_for_tests/clean_train.csv') df_test = pd.read_csv('data_for_tests/clean_test.csv') drift_estimator = DriftEstimator() drift_estimator.fit(df_train, df_test) assert drift_estimator._DriftEstimator__fitOK
['def', 'test_fit_drift_estimator():', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'df_test', '=', "pd.read_csv('data_for_tests/clean_test.csv')", 'drift_estimator', '=', 'DriftEstimator()', 'drift_estimator.fit(df_train,', 'df_test)', 'assert', 'drift_estimator._DriftEstimator__fitOK']
630,021
openvinotoolkit/training_extensions
torchvision_backbones.py
replace_norm
replace_norm
Replace Norm function (copy from mmdet).
[ "Replace", "Norm", "function", "(copy", "from", "mmdet)." ]
def replace_norm(model, cfg): for (name, module) in model._modules.items(): if len(list(module.children())) > 0: model._modules[name] = replace_norm(module, cfg) if name == 'bn': model._modules[name] = build_norm_layer(cfg, num_features=module.num_features)[1] return mode...
['def', 'replace_norm(model,', 'cfg):', 'for', '(name,', 'module)', 'in', 'model._modules.items():', 'if', 'len(list(module.children()))', '>', '0:', 'model._modules[name]', '=', 'replace_norm(module,', 'cfg)', 'if', 'name', '==', "'bn':", 'model._modules[name]', '=', 'build_norm_layer(cfg,', 'num_features=module.num_f...
917,871
sek788432/Waymo-2D-Object-Detection
models.py
create_nhnet_model
create_nhnet_model
A helper to create NHNet model.
[ "A", "helper", "to", "create", "NHNet", "model." ]
def create_nhnet_model(params: configs.NHNetConfig, cls=NHNet, init_checkpoint: Optional[Text]=None) -> tf.keras.Model: (bert_layer, decoder_layer) = get_nhnet_layers(params=params) model = cls(params=params, bert_layer=bert_layer, decoder_layer=decoder_layer, name='nhnet') if init_checkpoint: loggi...
['def', 'create_nhnet_model(params:', 'configs.NHNetConfig,', 'cls=NHNet,', 'init_checkpoint:', 'Optional[Text]=None)', '->', 'tf.keras.Model:', '(bert_layer,', 'decoder_layer)', '=', 'get_nhnet_layers(params=params)', 'model', '=', 'cls(params=params,', 'bert_layer=bert_layer,', 'decoder_layer=decoder_layer,', "name='...
972,737
KalleHallden/InstaAutomator
_tifffile.py
read_json
read_json
Read JSON tag data from file and return as object.
[ "Read", "JSON", "tag", "data", "from", "file", "and", "return", "as", "object." ]
def read_json(fh, byteorder, dtype, count): data = fh.read(count) try: return json.loads(unicode(stripnull(data), 'utf-8')) except ValueError: warnings.warn("invalid JSON '%s'" % data)
['def', 'read_json(fh,', 'byteorder,', 'dtype,', 'count):', 'data', '=', 'fh.read(count)', 'try:', 'return', 'json.loads(unicode(stripnull(data),', "'utf-8'))", 'except', 'ValueError:', 'warnings.warn("invalid', 'JSON', '\'%s\'"', '%', 'data)']
229,998
tensorly/quantum
linear_combination_test.py
LinearCombinationTest.test_analytic_functional
test_analytic_functional
Test that the differentiate_analytic function WORKS.
[ "Test", "that", "the", "differentiate_analytic", "function", "WORKS." ]
def test_analytic_functional(self, diff): differentiable_op = diff.generate_differentiable_op(analytic_op=circuit_execution_ops.get_expectation_op()) (circuit, names, values, ops, _, true_f, true_g) = _simple_op_inputs() with tf.GradientTape() as g: g.watch(values) res = differentiable_op(ci...
['def', 'test_analytic_functional(self,', 'diff):', 'differentiable_op', '=', 'diff.generate_differentiable_op(analytic_op=circuit_execution_ops.get_expectation_op())', '(circuit,', 'names,', 'values,', 'ops,', '_,', 'true_f,', 'true_g)', '=', '_simple_op_inputs()', 'with', 'tf.GradientTape()', 'as', 'g:', 'g.watch(val...
835,231
stefan-rz/udacity-aind
utils.py
removeall
removeall
Return a copy of seq (or string) with all occurences of item removed.
[ "Return", "a", "copy", "of", "seq", "(or", "string)", "with", "all", "occurences", "of", "item", "removed." ]
def removeall(item, seq): if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item]
['def', 'removeall(item,', 'seq):', 'if', 'isinstance(seq,', 'str):', 'return', 'seq.replace(item,', "'')", 'else:', 'return', '[x', 'for', 'x', 'in', 'seq', 'if', 'x', '!=', 'item]']
427,825
43Carrig/recurrent_neural_networks_practice
test_util.py
TensorFlowTestCase.assertAllGreaterEqual
assertAllGreaterEqual
Assert element values are all greater than a target value.
[ "Assert", "element", "values", "are", "all", "greater", "than", "a", "target", "value." ]
def assertAllGreaterEqual(self, a, comparison_target): a = self._GetNdArray(a) self.assertGreaterEqual(np.min(a), comparison_target)
['def', 'assertAllGreaterEqual(self,', 'a,', 'comparison_target):', 'a', '=', 'self._GetNdArray(a)', 'self.assertGreaterEqual(np.min(a),', 'comparison_target)']
336,631
rail-berkeley/softlearning
console_scripts.py
run_example_debug_cmd
run_example_debug_cmd
The debug mode limits tune trial runs to enable use of debugger.
[ "The", "debug", "mode", "limits", "tune", "trial", "runs", "to", "enable", "use", "of", "debugger." ]
def run_example_debug_cmd(example_module_name, example_argv): example_argv = (*example_argv, '--mode=debug') return run_example_debug(example_module_name, example_argv)
['def', 'run_example_debug_cmd(example_module_name,', 'example_argv):', 'example_argv', '=', '(*example_argv,', "'--mode=debug')", 'return', 'run_example_debug(example_module_name,', 'example_argv)']
879,316
kubeflow/pipelines
type_utils.py
get_input_artifact_type_schema
get_input_artifact_type_schema
Find the input artifact type by input name.
[ "Find", "the", "input", "artifact", "type", "by", "input", "name." ]
def get_input_artifact_type_schema(input_name: str, inputs: List[_structures.InputSpec]) -> Optional[str]: for component_input in inputs: if component_input.name == input_name: assert not is_parameter_type(component_input.type), 'Input is not an artifact type.' return get_artifact_ty...
['def', 'get_input_artifact_type_schema(input_name:', 'str,', 'inputs:', 'List[_structures.InputSpec])', '->', 'Optional[str]:', 'for', 'component_input', 'in', 'inputs:', 'if', 'component_input.name', '==', 'input_name:', 'assert', 'not', 'is_parameter_type(component_input.type),', "'Input", 'is', 'not', 'an', 'artifa...
780,102
sjtu-marl/malib
episode.py
Episode.to_numpy
to_numpy
Convert episode to numpy array-like data.
[ "Convert", "episode", "to", "numpy", "array-like", "data." ]
def to_numpy(self) -> Dict[AgentID, Dict[str, np.ndarray]]: res = {} for (agent, agent_trajectory) in self.agent_entry.items(): if len(agent_trajectory[Episode.CUR_OBS]) < 2: continue tmp = {} try: for (k, v) in agent_trajectory.items(): if k in [E...
['def', 'to_numpy(self)', '->', 'Dict[AgentID,', 'Dict[str,', 'np.ndarray]]:', 'res', '=', '{}', 'for', '(agent,', 'agent_trajectory)', 'in', 'self.agent_entry.items():', 'if', 'len(agent_trajectory[Episode.CUR_OBS])', '<', '2:', 'continue', 'tmp', '=', '{}', 'try:', 'for', '(k,', 'v)', 'in', 'agent_trajectory.items():...
627,593
adamshamsudeen/vision.ai
environment.py
Template.stream
stream
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
[ "Works", "exactly", "like", ":meth:`generate`", "but", "returns", "a", ":class:`TemplateStream`." ]
def stream(self, *args, **kwargs): return TemplateStream(self.generate(*args, **kwargs))
['def', 'stream(self,', '*args,', '**kwargs):', 'return', 'TemplateStream(self.generate(*args,', '**kwargs))']
942,988
specdrake/SimpleNeuralNets
networkf.py
Network.feedforward
feedforward
Return the output of the network if ``a`` is input.
[ "Return", "the", "output", "of", "the", "network", "if", "``a``", "is", "input." ]
def feedforward(self, a): for (b, w) in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a) + b) return a
['def', 'feedforward(self,', 'a):', 'for', '(b,', 'w)', 'in', 'zip(self.biases,', 'self.weights):', 'a', '=', 'sigmoid(np.dot(w,', 'a)', '+', 'b)', 'return', 'a']
883,216
triaquae/triaquae
sites.py
DatabrowsePlugin.model_index_html
model_index_html
Returns a snippet of HTML to include on the model index page.
[ "Returns", "a", "snippet", "of", "HTML", "to", "include", "on", "the", "model", "index", "page." ]
def model_index_html(self, request, model, site): return ''
['def', 'model_index_html(self,', 'request,', 'model,', 'site):', 'return', "''"]
357,256
Ruturaj123/Flowchart-Detection
resources.py
GetSyntaxNetResourceAsFile
GetSyntaxNetResourceAsFile
Returns a resource as an opened read-only file.
[ "Returns", "a", "resource", "as", "an", "opened", "read-only", "file." ]
def GetSyntaxNetResourceAsFile(path): path = os.path.join(_ROOT_DIR, path) if os.path.isdir(path): raise IOError('Resource "{}" is not a file'.format(path)) if not os.path.isfile(path): raise IOError('Resource "{}" not found; is it a data dependency?'.format(path)) return open(path, 'rb'...
['def', 'GetSyntaxNetResourceAsFile(path):', 'path', '=', 'os.path.join(_ROOT_DIR,', 'path)', 'if', 'os.path.isdir(path):', 'raise', "IOError('Resource", '"{}"', 'is', 'not', 'a', "file'.format(path))", 'if', 'not', 'os.path.isfile(path):', 'raise', "IOError('Resource", '"{}"', 'not', 'found;', 'is', 'it', 'a', 'data',...
586,730
rouge8/20questions
admin.py
retrain.GET
GET
Renders a page with all of the questions and values for a specified object_id so that it can be retrained manually.
[ "Renders", "a", "page", "with", "all", "of", "the", "questions", "and", "values", "for", "a", "specified", "object_id", "so", "that", "it", "can", "be", "retrained", "manually." ]
def GET(self, object_id): object = model.get_object_by_id(object_id) questions = model.get_questions() data = model.get_data_dictionary() if object: return render.retrain(object, list(questions), data) else: raise web.seeother('/')
['def', 'GET(self,', 'object_id):', 'object', '=', 'model.get_object_by_id(object_id)', 'questions', '=', 'model.get_questions()', 'data', '=', 'model.get_data_dictionary()', 'if', 'object:', 'return', 'render.retrain(object,', 'list(questions),', 'data)', 'else:', 'raise', "web.seeother('/')"]
4,371
SamsungLabs/fcaf3d
transforms.py
bbox3d2roi
bbox3d2roi
Convert a list of bounding boxes to roi format.
[ "Convert", "a", "list", "of", "bounding", "boxes", "to", "roi", "format." ]
def bbox3d2roi(bbox_list): rois_list = [] for (img_id, bboxes) in enumerate(bbox_list): if bboxes.size(0) > 0: img_inds = bboxes.new_full((bboxes.size(0), 1), img_id) rois = torch.cat([img_inds, bboxes], dim=-1) else: rois = torch.zeros_like(bboxes) ro...
['def', 'bbox3d2roi(bbox_list):', 'rois_list', '=', '[]', 'for', '(img_id,', 'bboxes)', 'in', 'enumerate(bbox_list):', 'if', 'bboxes.size(0)', '>', '0:', 'img_inds', '=', 'bboxes.new_full((bboxes.size(0),', '1),', 'img_id)', 'rois', '=', 'torch.cat([img_inds,', 'bboxes],', 'dim=-1)', 'else:', 'rois', '=', 'torch.zeros_...
560,131
open-mmlab/mmselfsup
ema.py
CosineEMA.avg_func
avg_func
Compute the moving average of the parameters using the cosine momentum strategy.
[ "Compute", "the", "moving", "average", "of", "the", "parameters", "using", "the", "cosine", "momentum", "strategy." ]
def avg_func(self, averaged_param: torch.Tensor, source_param: torch.Tensor, steps: int) -> None: message_hub = MessageHub.get_current_instance() max_iters = message_hub.get_info('max_iters') momentum = self.end_momentum - (self.end_momentum - self.momentum) * (cos(pi * steps / float(max_iters)) + 1) / 2 ...
['def', 'avg_func(self,', 'averaged_param:', 'torch.Tensor,', 'source_param:', 'torch.Tensor,', 'steps:', 'int)', '->', 'None:', 'message_hub', '=', 'MessageHub.get_current_instance()', 'max_iters', '=', "message_hub.get_info('max_iters')", 'momentum', '=', 'self.end_momentum', '-', '(self.end_momentum', '-', 'self.mom...
240,466
aws/sagemaker-inference-toolkit
default_handler_service.py
DefaultHandlerService.handle
handle
Handles an inference request with input data and makes a prediction.
[ "Handles", "an", "inference", "request", "with", "input", "data", "and", "makes", "a", "prediction." ]
def handle(self, data, context): return self._service.transform(data, context)
['def', 'handle(self,', 'data,', 'context):', 'return', 'self._service.transform(data,', 'context)']
829,297
mkusner/grammarVAE
cc.py
get_c_extract
get_c_extract
Wrapper around c_extract that initializes py_name from storage.
[ "Wrapper", "around", "c_extract", "that", "initializes", "py_name", "from", "storage." ]
def get_c_extract(r, name, sub): if any([getattr(c.op, 'check_input', config.check_input) for (c, _) in r.clients if not isinstance(c, string_types)]): if any([getattr(c.op, 'check_broadcast', True) for (c, _) in r.clients if not isinstance(c, string_types)]): c_extract = r.type.c_extract(name, ...
['def', 'get_c_extract(r,', 'name,', 'sub):', 'if', 'any([getattr(c.op,', "'check_input',", 'config.check_input)', 'for', '(c,', '_)', 'in', 'r.clients', 'if', 'not', 'isinstance(c,', 'string_types)]):', 'if', 'any([getattr(c.op,', "'check_broadcast',", 'True)', 'for', '(c,', '_)', 'in', 'r.clients', 'if', 'not', 'isin...
579,197
Farama-Foundation/D4RL
configurable.py
ConfigCache.get_config
get_config
Returns the configuration for the given env name.
[ "Returns", "the", "configuration", "for", "the", "given", "env", "name." ]
def get_config(self, cls_or_env_id): config_key = self._get_config_key(cls_or_env_id) config = dict(self._default_config) config.update(self._configs.get(config_key, {})) return config
['def', 'get_config(self,', 'cls_or_env_id):', 'config_key', '=', 'self._get_config_key(cls_or_env_id)', 'config', '=', 'dict(self._default_config)', 'config.update(self._configs.get(config_key,', '{}))', 'return', 'config']
126,330
danaugrs/huskarl
core.py
Agent.save
save
Saves the model parameters to the specified file.
[ "Saves", "the", "model", "parameters", "to", "the", "specified", "file." ]
def save(self, filename, overwrite=False): raise NotImplementedError()
['def', 'save(self,', 'filename,', 'overwrite=False):', 'raise', 'NotImplementedError()']
206,786
flybywind/neural-networks-and-deep-learning
mnist.py
load_data
load_data
Return the MNIST data as a tuple containing the training data, the validation data, and the test data.
[ "Return", "the", "MNIST", "data", "as", "a", "tuple", "containing", "the", "training", "data,", "the", "validation", "data,", "and", "the", "test", "data." ]
def load_data(): f = open('../data/mnist.pkl', 'rb') (training_set, validation_set, test_set) = cPickle.load(f) f.close() return (training_set, validation_set, test_set)
['def', 'load_data():', 'f', '=', "open('../data/mnist.pkl',", "'rb')", '(training_set,', 'validation_set,', 'test_set)', '=', 'cPickle.load(f)', 'f.close()', 'return', '(training_set,', 'validation_set,', 'test_set)']
722,088
wangck20/OPERA
vision_transformer_hybrid.py
vit_tiny_r_s16_p8_224
vit_tiny_r_s16_p8_224
R+ViT-Ti/S16 w/ 8x8 patch hybrid @ 224 x 224.
[ "R+ViT-Ti/S16", "w/", "8x8", "patch", "hybrid", "@", "224", "x", "224." ]
def vit_tiny_r_s16_p8_224(pretrained=False, **kwargs): backbone = _resnetv2(layers=(), **kwargs) model_kwargs = dict(patch_size=8, embed_dim=192, depth=12, num_heads=3, **kwargs) model = _create_vision_transformer_hybrid('vit_tiny_r_s16_p8_224', backbone=backbone, pretrained=pretrained, **model_kwargs) ...
['def', 'vit_tiny_r_s16_p8_224(pretrained=False,', '**kwargs):', 'backbone', '=', '_resnetv2(layers=(),', '**kwargs)', 'model_kwargs', '=', 'dict(patch_size=8,', 'embed_dim=192,', 'depth=12,', 'num_heads=3,', '**kwargs)', 'model', '=', "_create_vision_transformer_hybrid('vit_tiny_r_s16_p8_224',", 'backbone=backbone,', ...
253,209
flavioschneider/rl-transfer-
_functions.py
flatten_tensors
flatten_tensors
Flatten a list of tensors.
[ "Flatten", "a", "list", "of", "tensors." ]
def flatten_tensors(tensors): if tensors: return np.concatenate([np.reshape(x, [-1]) for x in tensors]) return np.asarray([])
['def', 'flatten_tensors(tensors):', 'if', 'tensors:', 'return', 'np.concatenate([np.reshape(x,', '[-1])', 'for', 'x', 'in', 'tensors])', 'return', 'np.asarray([])']
861,180
songlab-cal/tape
modeling_utils.py
ProteinConfig.from_dict
from_dict
Constructs a `Config` from a Python dictionary of parameters.
[ "Constructs", "a", "`Config`", "from", "a", "Python", "dictionary", "of", "parameters." ]
def from_dict(cls, json_object): config = cls(vocab_size_or_config_json_file=-1) for (key, value) in json_object.items(): config.__dict__[key] = value return config
['def', 'from_dict(cls,', 'json_object):', 'config', '=', 'cls(vocab_size_or_config_json_file=-1)', 'for', '(key,', 'value)', 'in', 'json_object.items():', 'config.__dict__[key]', '=', 'value', 'return', 'config']
365,366
suarez12138/AI-Reversi_IMP_TextDichotomy
backend_wx.py
GraphicsContextWx.select
select
Select the current bitmap into this wxDC instance.
[ "Select", "the", "current", "bitmap", "into", "this", "wxDC", "instance." ]
def select(self): if sys.platform == 'win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True
['def', 'select(self):', 'if', 'sys.platform', '==', "'win32':", 'self.dc.SelectObject(self.bitmap)', 'self.IsSelected', '=', 'True']
97,149
scikit-multiflow/scikit-multiflow
mixed_generator.py
MIXEDGenerator.generate_drift
generate_drift
Generate drift by switching the classification function.
[ "Generate", "drift", "by", "switching", "the", "classification", "function." ]
def generate_drift(self): self.classification_function = 1 - self.classification_function
['def', 'generate_drift(self):', 'self.classification_function', '=', '1', '-', 'self.classification_function']
854,600
hamza-murad/AALU
speech_to_text_v1.py
Corpora.from_dict
from_dict
Initialize a Corpora object from a json dictionary.
[ "Initialize", "a", "Corpora", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'Corpora': args = {} valid_keys = ['corpora'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class Corpora: ' + ', '.join(bad_keys)) if 'corpora' in _dict: args['corpora'] =...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'Corpora':", 'args', '=', '{}', 'valid_keys', '=', "['corpora']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Corpora:', "'", '+', "',", ...
6,035
maxim-zhivodrov/Natural-Language-
base.py
LoadFile.add_candidate
add_candidate
Add a keyphrase candidate to the candidates container.
[ "Add", "a", "keyphrase", "candidate", "to", "the", "candidates", "container." ]
def add_candidate(self, words, stems, pos, offset, sentence_id): lexical_form = ' '.join(stems) self.candidates[lexical_form].surface_forms.append(words) self.candidates[lexical_form].lexical_form = stems self.candidates[lexical_form].pos_patterns.append(pos) self.candidates[lexical_form].offsets.ap...
['def', 'add_candidate(self,', 'words,', 'stems,', 'pos,', 'offset,', 'sentence_id):', 'lexical_form', '=', "'", "'.join(stems)", 'self.candidates[lexical_form].surface_forms.append(words)', 'self.candidates[lexical_form].lexical_form', '=', 'stems', 'self.candidates[lexical_form].pos_patterns.append(pos)', 'self.candi...
637,948
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
nb_007a.py
maybe_copy
maybe_copy
Copies the `old_fnames` to `new_fnames` location if new_fnames don't exist or are less recent.
[ "Copies", "the", "`old_fnames`", "to", "`new_fnames`", "location", "if", "new_fnames", "don't", "exist", "or", "are", "less", "recent." ]
def maybe_copy(old_fnames: Collection[PathOrStr], new_fnames: Collection[PathOrStr]): os.makedirs(os.path.dirname(new_fnames[0]), exist_ok=True) for (old_fname, new_fname) in zip(old_fnames, new_fnames): if not os.path.isfile(new_fname) or os.path.getmtime(new_fname) < os.path.getmtime(old_fname): ...
['def', 'maybe_copy(old_fnames:', 'Collection[PathOrStr],', 'new_fnames:', 'Collection[PathOrStr]):', 'os.makedirs(os.path.dirname(new_fnames[0]),', 'exist_ok=True)', 'for', '(old_fname,', 'new_fname)', 'in', 'zip(old_fnames,', 'new_fnames):', 'if', 'not', 'os.path.isfile(new_fname)', 'or', 'os.path.getmtime(new_fname)...
32,427
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
beam_reader_ops_test.py
ParsingReaderOpsTest.MakeGraph
MakeGraph
Constructs a structured learning graph.
[ "Constructs", "a", "structured", "learning", "graph." ]
def MakeGraph(self, max_steps=10, beam_size=2, batch_size=1, **kwargs): assert max_steps > 0, 'Empty network not supported.' logging.info('MakeGraph + %s', kwargs) with self.test_session(graph=tf.Graph()) as sess: (feature_sizes, domain_sizes, embedding_dims, num_actions) = sess.run(gen_parser_ops.f...
['def', 'MakeGraph(self,', 'max_steps=10,', 'beam_size=2,', 'batch_size=1,', '**kwargs):', 'assert', 'max_steps', '>', '0,', "'Empty", 'network', 'not', "supported.'", "logging.info('MakeGraph", '+', "%s',", 'kwargs)', 'with', 'self.test_session(graph=tf.Graph())', 'as', 'sess:', '(feature_sizes,', 'domain_sizes,', 'em...
111,675
prof-fabriciogmc/artificial_intelligence
tarfile.py
_Stream.write
write
Write string s to the stream.
[ "Write", "string", "s", "to", "the", "stream." ]
def write(self, s): if self.comptype == 'gz': self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != 'tar': s = self.cmp.compress(s) self.__write(s)
['def', 'write(self,', 's):', 'if', 'self.comptype', '==', "'gz':", 'self.crc', '=', 'self.zlib.crc32(s,', 'self.crc)', 'self.pos', '+=', 'len(s)', 'if', 'self.comptype', '!=', "'tar':", 's', '=', 'self.cmp.compress(s)', 'self.__write(s)']
144,470
zhang614/MicroGrid
player.py
PlayerGroup.pause
pause
Pause all players in the group simultaneously.
[ "Pause", "all", "players", "in", "the", "group", "simultaneously." ]
def pause(self): audio_players = [p._audio_player for p in self.players if p._audio_player] if audio_players: audio_players[0]._stop_group(audio_players) for player in self.players: player.pause()
['def', 'pause(self):', 'audio_players', '=', '[p._audio_player', 'for', 'p', 'in', 'self.players', 'if', 'p._audio_player]', 'if', 'audio_players:', 'audio_players[0]._stop_group(audio_players)', 'for', 'player', 'in', 'self.players:', 'player.pause()']
668,841
rudranil723/mini-main
_win32_console.py
GetStdHandle
GetStdHandle
Retrieves a handle to the specified standard device (standard input, standard output, or standard error).
[ "Retrieves", "a", "handle", "to", "the", "specified", "standard", "device", "(standard", "input,", "standard", "output,", "or", "standard", "error)." ]
def GetStdHandle(handle: int=STDOUT) -> wintypes.HANDLE: return cast(wintypes.HANDLE, _GetStdHandle(handle))
['def', 'GetStdHandle(handle:', 'int=STDOUT)', '->', 'wintypes.HANDLE:', 'return', 'cast(wintypes.HANDLE,', '_GetStdHandle(handle))']
269,024
OpenMDAO/OpenMDAO-Framework
adaptivesampledriver.py
AdaptiveSampleDriver.add_parameter
add_parameter
We need to create our special variable trees.
[ "We", "need", "to", "create", "our", "special", "variable", "trees." ]
def add_parameter(self, target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None): super(AdaptiveSampleDriver, self).add_parameter(target, low, high, scaler, adder, start, fd_step, name, scope) if name is not None: target = name elif isinstance(target, tu...
['def', 'add_parameter(self,', 'target,', 'low=None,', 'high=None,', 'scaler=None,', 'adder=None,', 'start=None,', 'fd_step=None,', 'name=None,', 'scope=None):', 'super(AdaptiveSampleDriver,', 'self).add_parameter(target,', 'low,', 'high,', 'scaler,', 'adder,', 'start,', 'fd_step,', 'name,', 'scope)', 'if', 'name', 'is...
275,547
TonyLianLong/VAI-ReinforcementLearning
pitch.py
Pitch.detected_goal
detected_goal
Returning the team that scored a goal.
[ "Returning", "the", "team", "that", "scored", "a", "goal." ]
def detected_goal(self): if self._home_goal.detected_entities: return team.Team.AWAY if self._away_goal.detected_entities: return team.Team.HOME return None
['def', 'detected_goal(self):', 'if', 'self._home_goal.detected_entities:', 'return', 'team.Team.AWAY', 'if', 'self._away_goal.detected_entities:', 'return', 'team.Team.HOME', 'return', 'None']
439,955
voxel51/fiftyone
models.py
PromptMixin.can_embed_prompts
can_embed_prompts
Whether this instance can generate prompt embeddings.
[ "Whether", "this", "instance", "can", "generate", "prompt", "embeddings." ]
def can_embed_prompts(self): raise NotImplementedError('subclasses must implement can_embed_prompts')
['def', 'can_embed_prompts(self):', 'raise', "NotImplementedError('subclasses", 'must', 'implement', "can_embed_prompts')"]
583,206
SamsungLabs/imvoxelnet
shape_aware_head.py
ShapeAwareHead.get_bboxes
get_bboxes
Get bboxes of anchor head.
[ "Get", "bboxes", "of", "anchor", "head." ]
def get_bboxes(self, cls_scores, bbox_preds, dir_cls_preds, input_metas, cfg=None, rescale=False): assert len(cls_scores) == len(bbox_preds) assert len(cls_scores) == len(dir_cls_preds) num_levels = len(cls_scores) assert num_levels == 1, 'Only support single level inference.' device = cls_scores[0]...
['def', 'get_bboxes(self,', 'cls_scores,', 'bbox_preds,', 'dir_cls_preds,', 'input_metas,', 'cfg=None,', 'rescale=False):', 'assert', 'len(cls_scores)', '==', 'len(bbox_preds)', 'assert', 'len(cls_scores)', '==', 'len(dir_cls_preds)', 'num_levels', '=', 'len(cls_scores)', 'assert', 'num_levels', '==', '1,', "'Only", 's...
612,024
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
ga_lib.py
tokens_list_repr
tokens_list_repr
Make human readable representation of program IO.
[ "Make", "human", "readable", "representation", "of", "program", "IO." ]
def tokens_list_repr(tokens, repr_type, base): if isinstance(repr_type, CustomType): return repr_type(tokens) elif repr_type == IOType.string: chars = [ALPHANUM_CHARS[t] for t in tokens] if base < len(ALPHANUM_CHARS) else [chr(t) for t in tokens] return ''.join(chars) elif repr_type ...
['def', 'tokens_list_repr(tokens,', 'repr_type,', 'base):', 'if', 'isinstance(repr_type,', 'CustomType):', 'return', 'repr_type(tokens)', 'elif', 'repr_type', '==', 'IOType.string:', 'chars', '=', '[ALPHANUM_CHARS[t]', 'for', 't', 'in', 'tokens]', 'if', 'base', '<', 'len(ALPHANUM_CHARS)', 'else', '[chr(t)', 'for', 't',...
46,457
zehuichen123/AutoAlignV2
indoor_eval.py
eval_det_cls
eval_det_cls
Generic functions to compute precision/recall for object detection for a single class.
[ "Generic", "functions", "to", "compute", "precision/recall", "for", "object", "detection", "for", "a", "single", "class." ]
def eval_det_cls(pred, gt, iou_thr=None): class_recs = {} npos = 0 for img_id in gt.keys(): cur_gt_num = len(gt[img_id]) if cur_gt_num != 0: gt_cur = torch.zeros([cur_gt_num, 7], dtype=torch.float32) for i in range(cur_gt_num): gt_cur[i] = gt[img_id][i...
['def', 'eval_det_cls(pred,', 'gt,', 'iou_thr=None):', 'class_recs', '=', '{}', 'npos', '=', '0', 'for', 'img_id', 'in', 'gt.keys():', 'cur_gt_num', '=', 'len(gt[img_id])', 'if', 'cur_gt_num', '!=', '0:', 'gt_cur', '=', 'torch.zeros([cur_gt_num,', '7],', 'dtype=torch.float32)', 'for', 'i', 'in', 'range(cur_gt_num):', '...
416,597
jwwangchn/NWD
kd_loss.py
knowledge_distillation_kl_div_loss
knowledge_distillation_kl_div_loss
Loss function for knowledge distilling using KL divergence.
[ "Loss", "function", "for", "knowledge", "distilling", "using", "KL", "divergence." ]
def knowledge_distillation_kl_div_loss(pred, soft_label, T, detach_target=True): assert pred.size() == soft_label.size() target = F.softmax(soft_label / T, dim=1) if detach_target: target = target.detach() kd_loss = F.kl_div(F.log_softmax(pred / T, dim=1), target, reduction='none').mean(1) * (T ...
['def', 'knowledge_distillation_kl_div_loss(pred,', 'soft_label,', 'T,', 'detach_target=True):', 'assert', 'pred.size()', '==', 'soft_label.size()', 'target', '=', 'F.softmax(soft_label', '/', 'T,', 'dim=1)', 'if', 'detach_target:', 'target', '=', 'target.detach()', 'kd_loss', '=', 'F.kl_div(F.log_softmax(pred', '/', '...
724,962
Katja-M/Python_NaturalLanguageProcessing
backend_bases.py
GraphicsContextBase.get_joinstyle
get_joinstyle
Return the line join style as one of ('miter', 'round', 'bevel').
[ "Return", "the", "line", "join", "style", "as", "one", "of", "('miter',", "'round',", "'bevel')." ]
def get_joinstyle(self): return self._joinstyle
['def', 'get_joinstyle(self):', 'return', 'self._joinstyle']
864,236
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tiles.py
tiles_from_slippy_map
tiles_from_slippy_map
Loads files from an on-disk slippy map directory structure.
[ "Loads", "files", "from", "an", "on-disk", "slippy", "map", "directory", "structure." ]
def tiles_from_slippy_map(root): for z in os.listdir(root): for x in os.listdir(os.path.join(root, z)): for name in os.listdir(os.path.join(root, z, x)): y = os.path.splitext(name)[0] tile = mercantile.Tile(x=int(x), y=int(y), z=int(z)) path = os.p...
['def', 'tiles_from_slippy_map(root):', 'for', 'z', 'in', 'os.listdir(root):', 'for', 'x', 'in', 'os.listdir(os.path.join(root,', 'z)):', 'for', 'name', 'in', 'os.listdir(os.path.join(root,', 'z,', 'x)):', 'y', '=', 'os.path.splitext(name)[0]', 'tile', '=', 'mercantile.Tile(x=int(x),', 'y=int(y),', 'z=int(z))', 'path',...
11,948
mideind/GreynirServer
__init__.py
query_geocode_api_coords
query_geocode_api_coords
Look up coordinates in Google's geocode API.
[ "Look", "up", "coordinates", "in", "Google's", "geocode", "API." ]
def query_geocode_api_coords(lat: float, lon: float) -> Optional[Dict[str, Any]]: key = read_txt_api_key('GoogleServerKey') if not key: logging.warning('No API key for coordinates lookup') return None return cast(Optional[Dict[str, Any]], query_json_api(_MAPS_API_COORDS_URL.format(lat, lon, ...
['def', 'query_geocode_api_coords(lat:', 'float,', 'lon:', 'float)', '->', 'Optional[Dict[str,', 'Any]]:', 'key', '=', "read_txt_api_key('GoogleServerKey')", 'if', 'not', 'key:', "logging.warning('No", 'API', 'key', 'for', 'coordinates', "lookup')", 'return', 'None', 'return', 'cast(Optional[Dict[str,', 'Any]],', 'quer...
581,226
DongChen06/MARL_CAVs
graphics.py
EnvViewer.window_position
window_position
the world position of the center of the displayed window.
[ "the", "world", "position", "of", "the", "center", "of", "the", "displayed", "window." ]
def window_position(self) -> np.ndarray: return np.array([310, 4])
['def', 'window_position(self)', '->', 'np.ndarray:', 'return', 'np.array([310,', '4])']
627,994
openvinotoolkit/training_extensions
primitive_parameters.py
configurable_integer
configurable_integer
Constructs a configurable integer attribute, with the appropriate metadata.
[ "Constructs", "a", "configurable", "integer", "attribute,", "with", "the", "appropriate", "metadata." ]
def configurable_integer(default_value: int, header: str, min_value: int=0, max_value: int=255, description: str='Default integer description', warning: str=None, editable: bool=True, visible_in_ui: bool=True, affects_outcome_of: ModelLifecycle=ModelLifecycle.NONE, ui_rules: UIRules=NullUIRules(), auto_hpo_state: AutoH...
['def', 'configurable_integer(default_value:', 'int,', 'header:', 'str,', 'min_value:', 'int=0,', 'max_value:', 'int=255,', 'description:', "str='Default", 'integer', "description',", 'warning:', 'str=None,', 'editable:', 'bool=True,', 'visible_in_ui:', 'bool=True,', 'affects_outcome_of:', 'ModelLifecycle=ModelLifecycl...
918,413
adamshamsudeen/vision.ai
runtime.py
Context.call
call
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.
[ "Call", "the", "callable", "with", "the", "arguments", "and", "keyword", "arguments", "provided", "but", "inject", "the", "active", "context", "or", "environment", "as", "first", "argument", "if", "the", "callable", "is", "a", ":func:`contextfunction`", "or", ":...
def call(__self, __obj, *args, **kwargs): if __debug__: __traceback_hide__ = True if hasattr(__obj, '__call__'): fn = __obj.__call__ for fn_type in ('contextfunction', 'evalcontextfunction', 'environmentfunction'): if hasattr(fn, fn_type): __obj = fn ...
['def', 'call(__self,', '__obj,', '*args,', '**kwargs):', 'if', '__debug__:', '__traceback_hide__', '=', 'True', 'if', 'hasattr(__obj,', "'__call__'):", 'fn', '=', '__obj.__call__', 'for', 'fn_type', 'in', "('contextfunction',", "'evalcontextfunction',", "'environmentfunction'):", 'if', 'hasattr(fn,', 'fn_type):', '__o...
943,120
openvinotoolkit/training_extensions
label.py
LabelEntity.color
color
Returns the Color object for the label.
[ "Returns", "the", "Color", "object", "for", "the", "label." ]
def color(self) -> Color: return self._color
['def', 'color(self)', '->', 'Color:', 'return', 'self._color']
918,538
enuguru/artificial_intelligence_and_machine_
plugin_base.py
post_begin
post_begin
things to set up later, once we know coverage is running.
[ "things", "to", "set", "up", "later,", "once", "we", "know", "coverage", "is", "running." ]
def post_begin(): for fn in post_configure: fn(options, file_config) global util, fixtures, engines, exclusions, assertions, warnings, profiling, config, testing from sqlalchemy import testing from sqlalchemy.testing import fixtures, engines, exclusions from sqlalchemy.testing import asserti...
['def', 'post_begin():', 'for', 'fn', 'in', 'post_configure:', 'fn(options,', 'file_config)', 'global', 'util,', 'fixtures,', 'engines,', 'exclusions,', 'assertions,', 'warnings,', 'profiling,', 'config,', 'testing', 'from', 'sqlalchemy', 'import', 'testing', 'from', 'sqlalchemy.testing', 'import', 'fixtures,', 'engine...
160,970
ludwig-ai/ludwig
test_visualization.py
test_visualization_precision_recall_curves_output_saved
test_visualization_precision_recall_curves_output_saved
Ensure pdf and png figures for precision recall curves from the experiments can be saved.
[ "Ensure", "pdf", "and", "png", "figures", "for", "precision", "recall", "curves", "from", "the", "experiments", "can", "be", "saved." ]
def test_visualization_precision_recall_curves_output_saved(csv_filename, binary_output_type): input_features = [category_feature(encoder={'vocab_size': 10})] if binary_output_type: output_features = [binary_feature()] else: output_features = [category_feature(decoder={'vocab_size': 3}, redu...
['def', 'test_visualization_precision_recall_curves_output_saved(csv_filename,', 'binary_output_type):', 'input_features', '=', "[category_feature(encoder={'vocab_size':", '10})]', 'if', 'binary_output_type:', 'output_features', '=', '[binary_feature()]', 'else:', 'output_features', '=', "[category_feature(decoder={'vo...
617,322
sek788432/Waymo-2D-Object-Detection
preprocess_ops.py
random_crop_with_resize
random_crop_with_resize
Randomly crop and resize an image.
[ "Randomly", "crop", "and", "resize", "an", "image." ]
def random_crop_with_resize(image, height, width, p=1.0): def _transform(image): image = crop_and_resize(image, height, width) return image return random_apply(_transform, p=p, x=image)
['def', 'random_crop_with_resize(image,', 'height,', 'width,', 'p=1.0):', 'def', '_transform(image):', 'image', '=', 'crop_and_resize(image,', 'height,', 'width)', 'return', 'image', 'return', 'random_apply(_transform,', 'p=p,', 'x=image)']
973,377
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_process.py
test_find_cmd_fail
test_find_cmd_fail
Make sure that FindCmdError is raised if we can't find the cmd.
[ "Make", "sure", "that", "FindCmdError", "is", "raised", "if", "we", "can't", "find", "the", "cmd." ]
def test_find_cmd_fail(): nt.assert_raises(FindCmdError, find_cmd, 'asdfasdf')
['def', 'test_find_cmd_fail():', 'nt.assert_raises(FindCmdError,', 'find_cmd,', "'asdfasdf')"]
449,076
arshpreetsingh/quantopian-machinelearning
call_tip_widget.py
CallTipWidget.enterEvent
enterEvent
Reimplemented to cancel the hide timer.
[ "Reimplemented", "to", "cancel", "the", "hide", "timer." ]
def enterEvent(self, event): super(CallTipWidget, self).enterEvent(event) self._hide_timer.stop()
['def', 'enterEvent(self,', 'event):', 'super(CallTipWidget,', 'self).enterEvent(event)', 'self._hide_timer.stop()']
892,806
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
EditWrapper.range_
range_
element range (min>=max: ignore).
[ "element", "range", "(min>=max:", "ignore)." ]
def range_(self): return util.buf_to_npy(self._ptr.contents.range_, (5, 2))
['def', 'range_(self):', 'return', 'util.buf_to_npy(self._ptr.contents.range_,', '(5,', '2))']
440,685
rishab-sharma/object_detection
vis.py
vis_bbox
vis_bbox
Visualizes a bounding box.
[ "Visualizes", "a", "bounding", "box." ]
def vis_bbox(img, bbox, thick=1): (x0, y0, w, h) = bbox (x1, y1) = (int(x0 + w), int(y0 + h)) (x0, y0) = (int(x0), int(y0)) cv2.rectangle(img, (x0, y0), (x1, y1), _GREEN, thickness=thick) return img
['def', 'vis_bbox(img,', 'bbox,', 'thick=1):', '(x0,', 'y0,', 'w,', 'h)', '=', 'bbox', '(x1,', 'y1)', '=', '(int(x0', '+', 'w),', 'int(y0', '+', 'h))', '(x0,', 'y0)', '=', '(int(x0),', 'int(y0))', 'cv2.rectangle(img,', '(x0,', 'y0),', '(x1,', 'y1),', '_GREEN,', 'thickness=thick)', 'return', 'img']
773,686
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vecs.py
Vecs.similarity
similarity
Computes the similarity of two tokens.
[ "Computes", "the", "similarity", "of", "two", "tokens." ]
def similarity(self, word1, word2): idx1 = self.word_to_idx.get(word1) idx2 = self.word_to_idx.get(word2) if not idx1 or not idx2: return None return float(self.vecs[idx1] * self.vecs[idx2].transpose())
['def', 'similarity(self,', 'word1,', 'word2):', 'idx1', '=', 'self.word_to_idx.get(word1)', 'idx2', '=', 'self.word_to_idx.get(word2)', 'if', 'not', 'idx1', 'or', 'not', 'idx2:', 'return', 'None', 'return', 'float(self.vecs[idx1]', '*', 'self.vecs[idx2].transpose())']
110,814
facebookresearch/CompilerGym
module_id_test.py
test_no_module_id_builtin_benchmark
test_no_module_id_builtin_benchmark
Test that the module and source IDs are stripped in shipped benchmark.
[ "Test", "that", "the", "module", "and", "source", "IDs", "are", "stripped", "in", "shipped", "benchmark." ]
def test_no_module_id_builtin_benchmark(env: LlvmEnv): env.reset('cbench-v1/crc32') ir = env.ir print(ir) assert "; ModuleID = '-'\n" in ir assert '\nsource_filename = "-"\n' in ir
['def', 'test_no_module_id_builtin_benchmark(env:', 'LlvmEnv):', "env.reset('cbench-v1/crc32')", 'ir', '=', 'env.ir', 'print(ir)', 'assert', '";', 'ModuleID', '=', '\'-\'\\n"', 'in', 'ir', 'assert', "'\\nsource_filename", '=', '"-"\\n\'', 'in', 'ir']
125,929
weimin17/Object-Detection_HelmetDetection
model_optimization.py
create_reinforce_gen_train_op
create_reinforce_gen_train_op
Create the Generator train_op when using REINFORCE.
[ "Create", "the", "Generator", "train_op", "when", "using", "REINFORCE." ]
def create_reinforce_gen_train_op(hparams, learning_rate, final_gen_reward, averages_op, global_step): del hparams with tf.name_scope('train_generator'): if FLAGS.generator_optimizer == 'sgd': gen_optimizer = tf.train.GradientDescentOptimizer(learning_rate) elif FLAGS.generator_optim...
['def', 'create_reinforce_gen_train_op(hparams,', 'learning_rate,', 'final_gen_reward,', 'averages_op,', 'global_step):', 'del', 'hparams', 'with', "tf.name_scope('train_generator'):", 'if', 'FLAGS.generator_optimizer', '==', "'sgd':", 'gen_optimizer', '=', 'tf.train.GradientDescentOptimizer(learning_rate)', 'elif', 'F...
763,776
suarez12138/AI-Reversi_IMP_TextDichotomy
common.py
check_termination
check_termination
Check termination condition for nonlinear least squares.
[ "Check", "termination", "condition", "for", "nonlinear", "least", "squares." ]
def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol): ftol_satisfied = dF < ftol * F and ratio > 0.25 xtol_satisfied = dx_norm < xtol * (xtol + x_norm) if ftol_satisfied and xtol_satisfied: return 4 elif ftol_satisfied: return 2 elif xtol_satisfied: return 3 e...
['def', 'check_termination(dF,', 'F,', 'dx_norm,', 'x_norm,', 'ratio,', 'ftol,', 'xtol):', 'ftol_satisfied', '=', 'dF', '<', 'ftol', '*', 'F', 'and', 'ratio', '>', '0.25', 'xtol_satisfied', '=', 'dx_norm', '<', 'xtol', '*', '(xtol', '+', 'x_norm)', 'if', 'ftol_satisfied', 'and', 'xtol_satisfied:', 'return', '4', 'elif'...
99,917
jshankman/Artificial-Intelligence
searchAgents.py
ClosestDotSearchAgent.findPathToClosestDot
findPathToClosestDot
Returns a path (a list of actions) to the closest dot, starting from gameState.
[ "Returns", "a", "path", "(a", "list", "of", "actions)", "to", "the", "closest", "dot,", "starting", "from", "gameState." ]
def findPathToClosestDot(self, gameState): startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) return search.uniformCostSearch(problem)
['def', 'findPathToClosestDot(self,', 'gameState):', 'startPosition', '=', 'gameState.getPacmanPosition()', 'food', '=', 'gameState.getFood()', 'walls', '=', 'gameState.getWalls()', 'problem', '=', 'AnyFoodSearchProblem(gameState)', 'return', 'search.uniformCostSearch(problem)']
114,337
RasaHQ/rasa
model_data.py
RasaModelData.does_feature_exist
does_feature_exist
Check if feature key (and sub-key) is present and features are available.
[ "Check", "if", "feature", "key", "(and", "sub-key)", "is", "present", "and", "features", "are", "available." ]
def does_feature_exist(self, key: Text, sub_key: Optional[Text]=None) -> bool: return not self.does_feature_not_exist(key, sub_key)
['def', 'does_feature_exist(self,', 'key:', 'Text,', 'sub_key:', 'Optional[Text]=None)', '->', 'bool:', 'return', 'not', 'self.does_feature_not_exist(key,', 'sub_key)']
837,953
Megvii-BaseDetection/DynamicRouting
imports.py
dynamic_import
dynamic_import
Dynamic import a project.
[ "Dynamic", "import", "a", "project." ]
def dynamic_import(config_name, config_path): (fp, pth, desc) = imp.find_module(config_name, [config_path]) return imp.load_module(config_name, fp, pth, desc)
['def', 'dynamic_import(config_name,', 'config_path):', '(fp,', 'pth,', 'desc)', '=', 'imp.find_module(config_name,', '[config_path])', 'return', 'imp.load_module(config_name,', 'fp,', 'pth,', 'desc)']
555,318
TobyPDE/FRRN
hybrid_training.py
compile_gd_step
compile_gd_step
Compiles the backward pass.
[ "Compiles", "the", "backward", "pass." ]
def compile_gd_step(network, loss_fn, input_vars, update_fn): bn_updates = collections.OrderedDict() split_outputs = get_split_outputs(network, batch_norm_update_averages=bn_updates) (param_blocks, _) = split_params(network) (all_predictions, split_outputs, split_shapes) = split_outputs split_update...
['def', 'compile_gd_step(network,', 'loss_fn,', 'input_vars,', 'update_fn):', 'bn_updates', '=', 'collections.OrderedDict()', 'split_outputs', '=', 'get_split_outputs(network,', 'batch_norm_update_averages=bn_updates)', '(param_blocks,', '_)', '=', 'split_params(network)', '(all_predictions,', 'split_outputs,', 'split_...
564,666
yxtay/char-rnn-text-generation
keras_model.py
generate_text
generate_text
generates text of specified length from trained model with given seed character sequence.
[ "generates", "text", "of", "specified", "length", "from", "trained", "model", "with", "given", "seed", "character", "sequence." ]
def generate_text(model, seed, length=512, top_n=10): logger.info('generating %s characters from top %s choices.', length, top_n) logger.info('generating with seed: "%s".', seed) generated = seed encoded = encode_text(seed) model.reset_states() for idx in encoded[:-1]: x = np.array([[idx...
['def', 'generate_text(model,', 'seed,', 'length=512,', 'top_n=10):', "logger.info('generating", '%s', 'characters', 'from', 'top', '%s', "choices.',", 'length,', 'top_n)', "logger.info('generating", 'with', 'seed:', '"%s".\',', 'seed)', 'generated', '=', 'seed', 'encoded', '=', 'encode_text(seed)', 'model.reset_states...
104,665
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_subprocess.py
MiscTests.test__all__
test__all__
Ensure that __all__ is populated properly.
[ "Ensure", "that", "__all__", "is", "populated", "properly." ]
def test__all__(self): intentionally_excluded = {'list2cmdline', 'STARTUPINFO', 'Handle'} exported = set(subprocess.__all__) possible_exports = set() import types for (name, value) in subprocess.__dict__.items(): if name.startswith('_'): continue if isinstance(value, (typ...
['def', 'test__all__(self):', 'intentionally_excluded', '=', "{'list2cmdline',", "'STARTUPINFO',", "'Handle'}", 'exported', '=', 'set(subprocess.__all__)', 'possible_exports', '=', 'set()', 'import', 'types', 'for', '(name,', 'value)', 'in', 'subprocess.__dict__.items():', 'if', "name.startswith('_'):", 'continue', 'if...
376,411
visinf/dense-ulearn-vos
config.py
merge_cfg_from_file
merge_cfg_from_file
Load a yaml config file and merge it into the global config.
[ "Load", "a", "yaml", "config", "file", "and", "merge", "it", "into", "the", "global", "config." ]
def merge_cfg_from_file(cfg_filename): with open(cfg_filename, 'r') as f: yaml_cfg = AttrDict(yaml.load(f, Loader=yaml.FullLoader)) _merge_a_into_b(yaml_cfg, __C)
['def', 'merge_cfg_from_file(cfg_filename):', 'with', 'open(cfg_filename,', "'r')", 'as', 'f:', 'yaml_cfg', '=', 'AttrDict(yaml.load(f,', 'Loader=yaml.FullLoader))', '_merge_a_into_b(yaml_cfg,', '__C)']
183,779
aeon-toolkit/aeon
test_window_forecasters.py
test_last_window
test_last_window
Test window forecaster common API points.
[ "Test", "window", "forecaster", "common", "API", "points." ]
def test_last_window(Forecaster): f = Forecaster.create_test_instance() n_columns = 1 f = Forecaster.create_test_instance() y_train = _make_series(n_columns=n_columns) f.fit(y_train, fh=FH0) (actual, _) = f._get_last_window() expected = y_train.iloc[-f.window_length_:] np.testing.assert_...
['def', 'test_last_window(Forecaster):', 'f', '=', 'Forecaster.create_test_instance()', 'n_columns', '=', '1', 'f', '=', 'Forecaster.create_test_instance()', 'y_train', '=', '_make_series(n_columns=n_columns)', 'f.fit(y_train,', 'fh=FH0)', '(actual,', '_)', '=', 'f._get_last_window()', 'expected', '=', 'y_train.iloc[-f...
399,767
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
input_generator.py
get
get
Provides input data for a specified dataset and split.
[ "Provides", "input", "data", "for", "a", "specified", "dataset", "and", "split." ]
def get(dataset_dir, dataset_name, split_name, shuffle=True, num_readers=1, common_queue_capacity=64, common_queue_min=50): dataset_to_kwargs = {'shapenet_chair': {'file_pattern': '03001627_%s.tfrecords' % split_name, 'num_views': 24, 'image_size': 64, 'vox_size': 32}, 'shapenet_all': {'file_pattern': '*_%s.tfrecor...
['def', 'get(dataset_dir,', 'dataset_name,', 'split_name,', 'shuffle=True,', 'num_readers=1,', 'common_queue_capacity=64,', 'common_queue_min=50):', 'dataset_to_kwargs', '=', "{'shapenet_chair':", "{'file_pattern':", "'03001627_%s.tfrecords'", '%', 'split_name,', "'num_views':", '24,', "'image_size':", '64,', "'vox_siz...
109,117
cagbal/ros_people_object_detection_tensorflow
model_test.py
ModelTflearnTest.testExperiment
testExperiment
Tests that the `Experiment` object is constructed correctly.
[ "Tests", "that", "the", "`Experiment`", "object", "is", "constructed", "correctly." ]
def testExperiment(self): experiment = model_test_util.BuildExperiment() model_dir = experiment.estimator.model_dir pipeline_config_path = os.path.join(model_dir, 'pipeline.config') self.assertTrue(tf.gfile.Exists(pipeline_config_path))
['def', 'testExperiment(self):', 'experiment', '=', 'model_test_util.BuildExperiment()', 'model_dir', '=', 'experiment.estimator.model_dir', 'pipeline_config_path', '=', 'os.path.join(model_dir,', "'pipeline.config')", 'self.assertTrue(tf.gfile.Exists(pipeline_config_path))']
827,352
kianak2002/Sentiment-Emotion-Analysis-project
install.py
install.convert_paths
convert_paths
Call `convert_path` over `names`.
[ "Call", "`convert_path`", "over", "`names`." ]
def convert_paths(self, *names): for name in names: attr = 'install_' + name setattr(self, attr, convert_path(getattr(self, attr)))
['def', 'convert_paths(self,', '*names):', 'for', 'name', 'in', 'names:', 'attr', '=', "'install_'", '+', 'name', 'setattr(self,', 'attr,', 'convert_path(getattr(self,', 'attr)))']
875,929
danaugrs/huskarl
memory.py
ExperienceReplay.get
get
Samples the specified number of traces uniformly from the buffer.
[ "Samples", "the", "specified", "number", "of", "traces", "uniformly", "from", "the", "buffer." ]
def get(self, batch_size): traces = random.sample(self.traces, batch_size) return unpack(traces)
['def', 'get(self,', 'batch_size):', 'traces', '=', 'random.sample(self.traces,', 'batch_size)', 'return', 'unpack(traces)']
206,821
apple/ml-cvnets
chain_sampler.py
ChainSampler.add_arguments
add_arguments
Add arguments for chain sampler.
[ "Add", "arguments", "for", "chain", "sampler." ]
def add_arguments(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser: if cls != ChainSampler: return parser group = parser.add_argument_group(cls.__name__) group.add_argument('--sampler.chain-sampler', type=json.loads, action='append') group.add_argument('--sampler.chain-sampler-mo...
['def', 'add_arguments(cls,', 'parser:', 'argparse.ArgumentParser)', '->', 'argparse.ArgumentParser:', 'if', 'cls', '!=', 'ChainSampler:', 'return', 'parser', 'group', '=', 'parser.add_argument_group(cls.__name__)', "group.add_argument('--sampler.chain-sampler',", 'type=json.loads,', "action='append')", "group.add_argu...
671,474
lixingjian/DELTA
register.py
Register.register
register
Decorator to register a function or class.
[ "Decorator", "to", "register", "a", "function", "or", "class." ]
def register(self, param): def decorator(key, value): self[key] = value return value if callable(param): return decorator(None, param) return lambda x: decorator(param, x)
['def', 'register(self,', 'param):', 'def', 'decorator(key,', 'value):', 'self[key]', '=', 'value', 'return', 'value', 'if', 'callable(param):', 'return', 'decorator(None,', 'param)', 'return', 'lambda', 'x:', 'decorator(param,', 'x)']
537,601
googleapis/python-aiplatform
models.py
ModelRegistry.update_version
update_version
Updates a model version.
[ "Updates", "a", "model", "version." ]
def update_version(self, version: str, version_description: Optional[str]=None, labels: Optional[Dict[str, str]]=None) -> None: current_model_proto = self.get_model(version).gca_resource copied_model_proto = current_model_proto.__class__(current_model_proto) update_mask: List[str] = [] if version_descri...
['def', 'update_version(self,', 'version:', 'str,', 'version_description:', 'Optional[str]=None,', 'labels:', 'Optional[Dict[str,', 'str]]=None)', '->', 'None:', 'current_model_proto', '=', 'self.get_model(version).gca_resource', 'copied_model_proto', '=', 'current_model_proto.__class__(current_model_proto)', 'update_m...
809,822
ruhyadi/YOLO3D
wandb_utils.py
WandbLogger.log_model
log_model
Log the model checkpoint as W&B artifact arguments: path (Path) -- Path of directory containing the checkpoints opt (namespace) -- Command line arguments for this run epoch (int) -- Current epoch number fitness_score (float) -- fitness score for current epoch best_model (boolean) -- Boolean representing if the curre...
[ "Log", "the", "model", "checkpoint", "as", "W&B", "artifact", "arguments:", "path", "(Path)", "--", "Path", "of", "directory", "containing", "the", "checkpoints", "opt", "(namespace)", "--", "Command", "line", "arguments", "for", "this", "run", "epoch", "(int)",...
def log_model(self, path, opt, epoch, fitness_score, best_model=False): model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={'original_url': str(path), 'epochs_trained': epoch + 1, 'save period': opt.save_period, 'project': opt.project, 'total_epochs': opt.epochs, 'fitness_score...
['def', 'log_model(self,', 'path,', 'opt,', 'epoch,', 'fitness_score,', 'best_model=False):', 'model_artifact', '=', "wandb.Artifact('run_'", '+', 'wandb.run.id', '+', "'_model',", "type='model',", "metadata={'original_url':", 'str(path),', "'epochs_trained':", 'epoch', '+', '1,', "'save", "period':", 'opt.save_period,...
969,278
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
losses.py
add_volume_proj_loss
add_volume_proj_loss
Computes the projection loss of voxel generation model.
[ "Computes", "the", "projection", "loss", "of", "voxel", "generation", "model." ]
def add_volume_proj_loss(inputs, outputs, num_views, weight_scale): batch_size = tf.shape(inputs['images_1'])[0] proj_loss = 0 for k in range(num_views): proj_loss += tf.nn.l2_loss(outputs['masks_%d' % (k + 1)] - outputs['projs_%d' % (k + 1)]) proj_loss /= tf.to_float(num_views * batch_size) ...
['def', 'add_volume_proj_loss(inputs,', 'outputs,', 'num_views,', 'weight_scale):', 'batch_size', '=', "tf.shape(inputs['images_1'])[0]", 'proj_loss', '=', '0', 'for', 'k', 'in', 'range(num_views):', 'proj_loss', '+=', "tf.nn.l2_loss(outputs['masks_%d'", '%', '(k', '+', '1)]', '-', "outputs['projs_%d'", '%', '(k', '+',...
109,141
gunthercox/ChatterBot
reading.py
TermInfo.max_length
max_length
Returns the length of the longest field value the term appears in.
[ "Returns", "the", "length", "of", "the", "longest", "field", "value", "the", "term", "appears", "in." ]
def max_length(self): return self._maxlength
['def', 'max_length(self):', 'return', 'self._maxlength']
526,331
voxel51/fiftyone
cvat.py
CVATVideoPolyline.from_polyline_dict
from_polyline_dict
Creates a :class:`CVATVideoPolyline` from a ``<polyline>`` tag of a CVAT video annotation XML file.
[ "Creates", "a", ":class:`CVATVideoPolyline`", "from", "a", "``<polyline>``", "tag", "of", "a", "CVAT", "video", "annotation", "XML", "file." ]
def from_polyline_dict(cls, label, d): frame = int(d['@frame']) points = cls._parse_cvat_points_str(d['@points']) (outside, occluded, keyframe, attributes) = cls._parse_anno_dict(d) return cls(frame, label, points, outside=outside, occluded=occluded, keyframe=keyframe, attributes=attributes)
['def', 'from_polyline_dict(cls,', 'label,', 'd):', 'frame', '=', "int(d['@frame'])", 'points', '=', "cls._parse_cvat_points_str(d['@points'])", '(outside,', 'occluded,', 'keyframe,', 'attributes)', '=', 'cls._parse_anno_dict(d)', 'return', 'cls(frame,', 'label,', 'points,', 'outside=outside,', 'occluded=occluded,', 'k...
583,978
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
imagenet_test.py
BaseTest.tensor_shapes_helper
tensor_shapes_helper
Checks the tensor shapes after each phase of the ResNet model.
[ "Checks", "the", "tensor", "shapes", "after", "each", "phase", "of", "the", "ResNet", "model." ]
def tensor_shapes_helper(self, resnet_size, with_gpu=False): def reshape(shape): if with_gpu: return shape return (shape[0], shape[2], shape[3], shape[1]) graph = tf.Graph() with graph.as_default(), self.test_session(use_gpu=with_gpu, force_gpu=with_gpu): model = resnet_...
['def', 'tensor_shapes_helper(self,', 'resnet_size,', 'with_gpu=False):', 'def', 'reshape(shape):', 'if', 'with_gpu:', 'return', 'shape', 'return', '(shape[0],', 'shape[2],', 'shape[3],', 'shape[1])', 'graph', '=', 'tf.Graph()', 'with', 'graph.as_default(),', 'self.test_session(use_gpu=with_gpu,', 'force_gpu=with_gpu):...
20,133
instadeepai/jumanji
env_test.py
test_snake__does_not_smoke
test_snake__does_not_smoke
Test that we can run an episode without any errors.
[ "Test", "that", "we", "can", "run", "an", "episode", "without", "any", "errors." ]
def test_snake__does_not_smoke(snake: Snake) -> None: check_env_does_not_smoke(snake)
['def', 'test_snake__does_not_smoke(snake:', 'Snake)', '->', 'None:', 'check_env_does_not_smoke(snake)']
594,518
jason718/game-feature-learning
cpp_lint.py
Match
Match
Matches the string with the pattern, caching the compiled regexp.
[ "Matches", "the", "string", "with", "the", "pattern,", "caching", "the", "compiled", "regexp." ]
def Match(pattern, s): if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s)
['def', 'Match(pattern,', 's):', 'if', 'pattern', 'not', 'in', '_regexp_compile_cache:', '_regexp_compile_cache[pattern]', '=', 'sre_compile.compile(pattern)', 'return', '_regexp_compile_cache[pattern].match(s)']
199,506
davidesj97/Artificial-Intelligence
utils.py
probability
probability
Return true with probability p.
[ "Return", "true", "with", "probability", "p." ]
def probability(p): return p > random.uniform(0.0, 1.0)
['def', 'probability(p):', 'return', 'p', '>', 'random.uniform(0.0,', '1.0)']
121,665
cangermueller/deepcpg
test_hdf.py
TestReader.test_read_reader
test_read_reader
Test if read and reader yield the same data.
[ "Test", "if", "read", "and", "reader", "yield", "the", "same", "data." ]
def test_read_reader(self): nb_sample = 7777 nb_loop = 10 names = ['pos', 'chromo', '/outputs/cpg/BS27_4_SER'] data = hdf.read(self.data_files, names, nb_sample=nb_sample) reader = hdf.reader(self.data_files, names, nb_sample=nb_sample, loop=True) for loop in range(nb_loop): data_loop = ...
['def', 'test_read_reader(self):', 'nb_sample', '=', '7777', 'nb_loop', '=', '10', 'names', '=', "['pos',", "'chromo',", "'/outputs/cpg/BS27_4_SER']", 'data', '=', 'hdf.read(self.data_files,', 'names,', 'nb_sample=nb_sample)', 'reader', '=', 'hdf.reader(self.data_files,', 'names,', 'nb_sample=nb_sample,', 'loop=True)',...
520,288
EarthNets/RSI-Segmentation
class_names.py
stare_classes
stare_classes
stare class names for external use.
[ "stare", "class", "names", "for", "external", "use." ]
def stare_classes(): return ['background', 'vessel']
['def', 'stare_classes():', 'return', "['background',", "'vessel']"]
828,001
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vgsl_model.py
VGSLImageModel.Restore
Restore
Restores the model from the given checkpoint path into the session.
[ "Restores", "the", "model", "from", "the", "given", "checkpoint", "path", "into", "the", "session." ]
def Restore(self, checkpoint_path, sess): self.saver.restore(sess, checkpoint_path) return tf.train.global_step(sess, self.global_step)
['def', 'Restore(self,', 'checkpoint_path,', 'sess):', 'self.saver.restore(sess,', 'checkpoint_path)', 'return', 'tf.train.global_step(sess,', 'self.global_step)']
110,699
louiscb/Artificial-Intelligence
search.py
boggle_hill_climbing
boggle_hill_climbing
Solve inverse Boggle by hill-climbing: find a high-scoring board by starting with a random one and changing it.
[ "Solve", "inverse", "Boggle", "by", "hill-climbing:", "find", "a", "high-scoring", "board", "by", "starting", "with", "a", "random", "one", "and", "changing", "it." ]
def boggle_hill_climbing(board=None, ntimes=100, verbose=True): finder = BoggleFinder() if board is None: board = random_boggle() best = len(finder.set_board(board)) for _ in range(ntimes): (i, oldc) = mutate_boggle(board) new = len(finder.set_board(board)) if new > best:...
['def', 'boggle_hill_climbing(board=None,', 'ntimes=100,', 'verbose=True):', 'finder', '=', 'BoggleFinder()', 'if', 'board', 'is', 'None:', 'board', '=', 'random_boggle()', 'best', '=', 'len(finder.set_board(board))', 'for', '_', 'in', 'range(ntimes):', '(i,', 'oldc)', '=', 'mutate_boggle(board)', 'new', '=', 'len(find...
118,678
tensorflow/privacy
data_structures.py
AttackResults.get_result_with_max_auc
get_result_with_max_auc
Get the result with maximum AUC for all attacks and slices.
[ "Get", "the", "result", "with", "maximum", "AUC", "for", "all", "attacks", "and", "slices." ]
def get_result_with_max_auc(self) -> Optional[SingleAttackResult]: if not self.single_attack_results: return None aucs = [result.get_auc() for result in self.single_attack_results] if min(aucs) < 0.4: logging.info('Suspiciously low AUC detected: %.2f. There might be a bug in the classifier',...
['def', 'get_result_with_max_auc(self)', '->', 'Optional[SingleAttackResult]:', 'if', 'not', 'self.single_attack_results:', 'return', 'None', 'aucs', '=', '[result.get_auc()', 'for', 'result', 'in', 'self.single_attack_results]', 'if', 'min(aucs)', '<', '0.4:', "logging.info('Suspiciously", 'low', 'AUC', 'detected:', '...
824,895
andreabac3/study-transfer-learning-covid-19
utils.py
gpus
gpus
Utility to determine the number of GPUs to use.
[ "Utility", "to", "determine", "the", "number", "of", "GPUs", "to", "use." ]
def gpus(conf: DictConfig) -> int: return conf.train.pl_trainer.gpus if torch.cuda.is_available() else 0
['def', 'gpus(conf:', 'DictConfig)', '->', 'int:', 'return', 'conf.train.pl_trainer.gpus', 'if', 'torch.cuda.is_available()', 'else', '0']
910,311
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_func_inspect.py
test_bound_methods
test_bound_methods
Make sure that calling the same method on two different instances of the same class does resolv to different signatures.
[ "Make", "sure", "that", "calling", "the", "same", "method", "on", "two", "different", "instances", "of", "the", "same", "class", "does", "resolv", "to", "different", "signatures." ]
def test_bound_methods(): a = Klass() b = Klass() assert filter_args(a.f, [], (1,)) != filter_args(b.f, [], (1,))
['def', 'test_bound_methods():', 'a', '=', 'Klass()', 'b', '=', 'Klass()', 'assert', 'filter_args(a.f,', '[],', '(1,))', '!=', 'filter_args(b.f,', '[],', '(1,))']
256,457
RasaHQ/rasa
trackers.py
DialogueStateTracker.interrupt_loop
interrupt_loop
Interrupt loop and mark that we entered an unhappy path in the conversation.
[ "Interrupt", "loop", "and", "mark", "that", "we", "entered", "an", "unhappy", "path", "in", "the", "conversation." ]
def interrupt_loop(self, is_interrupted: bool) -> None: if self.active_loop is not None: self.active_loop.is_interrupted = is_interrupted
['def', 'interrupt_loop(self,', 'is_interrupted:', 'bool)', '->', 'None:', 'if', 'self.active_loop', 'is', 'not', 'None:', 'self.active_loop.is_interrupted', '=', 'is_interrupted']
837,528
bhateharsh/computer_vision
config_util_test.py
ConfigUtilTest.testNewBatchSizeWithClipping
testNewBatchSizeWithClipping
Tests that batch size is clipped to 1 from below.
[ "Tests", "that", "batch", "size", "is", "clipped", "to", "1", "from", "below." ]
def testNewBatchSizeWithClipping(self): original_batch_size = 2 hparams = tf.contrib.training.HParams(batch_size=0.5) pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config') pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.train_config.batch_size = origina...
['def', 'testNewBatchSizeWithClipping(self):', 'original_batch_size', '=', '2', 'hparams', '=', 'tf.contrib.training.HParams(batch_size=0.5)', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.train_...
512,340
greydanus/mr_london
test_multiarray_assignment.py
test_overlapping_assignments
test_overlapping_assignments
Test automatically generated assignments which overlap in memory.
[ "Test", "automatically", "generated", "assignments", "which", "overlap", "in", "memory." ]
def test_overlapping_assignments(): inds = _indices(ndims) for ind in inds: srcidx = tuple([a[0] for a in ind]) dstidx = tuple([a[1] for a in ind]) yield (_check_assignment, srcidx, dstidx)
['def', 'test_overlapping_assignments():', 'inds', '=', '_indices(ndims)', 'for', 'ind', 'in', 'inds:', 'srcidx', '=', 'tuple([a[0]', 'for', 'a', 'in', 'ind])', 'dstidx', '=', 'tuple([a[1]', 'for', 'a', 'in', 'ind])', 'yield', '(_check_assignment,', 'srcidx,', 'dstidx)']
262,653
enuguru/artificial_intelligence_and_machine_learning
mcore.py
Matcher.weight
weight
Returns the weight of the current posting.
[ "Returns", "the", "weight", "of", "the", "current", "posting." ]
def weight(self): return self.value_as('weight')
['def', 'weight(self):', 'return', "self.value_as('weight')"]
133,475
pfnet/pfrl
replay_buffer.py
batch_experiences
batch_experiences
Takes a batch of k experiences each of which contains j consecutive transitions and vectorizes them, where j is between 1 and n.
[ "Takes", "a", "batch", "of", "k", "experiences", "each", "of", "which", "contains", "j", "consecutive", "transitions", "and", "vectorizes", "them,", "where", "j", "is", "between", "1", "and", "n." ]
def batch_experiences(experiences, device, phi, gamma, batch_states=batch_states): batch_exp = {'state': batch_states([elem[0]['state'] for elem in experiences], device, phi), 'action': torch.as_tensor([elem[0]['action'] for elem in experiences], device=device), 'reward': torch.as_tensor([sum((gamma ** i * exp[i]['...
['def', 'batch_experiences(experiences,', 'device,', 'phi,', 'gamma,', 'batch_states=batch_states):', 'batch_exp', '=', "{'state':", "batch_states([elem[0]['state']", 'for', 'elem', 'in', 'experiences],', 'device,', 'phi),', "'action':", "torch.as_tensor([elem[0]['action']", 'for', 'elem', 'in', 'experiences],', 'devic...
304,750