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
ToruOwO/marl-ae-comm
yacs.py
CfgNode.merge_from_file
merge_from_file
Load a yaml config file and merge it this CfgNode.
[ "Load", "a", "yaml", "config", "file", "and", "merge", "it", "this", "CfgNode." ]
def merge_from_file(self, cfg_filename): with open(cfg_filename, 'r') as f: cfg = self.load_cfg(f) self.merge_from_other_cfg(cfg)
['def', 'merge_from_file(self,', 'cfg_filename):', 'with', 'open(cfg_filename,', "'r')", 'as', 'f:', 'cfg', '=', 'self.load_cfg(f)', 'self.merge_from_other_cfg(cfg)']
627,838
myothida/Supervised-Machine-Learning
test_legend.py
test_handler_numpoints
test_handler_numpoints
Test legend handler with numpoints <= 1.
[ "Test", "legend", "handler", "with", "numpoints", "<=", "1." ]
def test_handler_numpoints(): (fig, ax) = plt.subplots() ax.plot(range(5), label='test') ax.legend(numpoints=0.5)
['def', 'test_handler_numpoints():', '(fig,', 'ax)', '=', 'plt.subplots()', 'ax.plot(range(5),', "label='test')", 'ax.legend(numpoints=0.5)']
362,883
Eric3911/OpenAGI
ctc_models.py
EncDecCTCModel.setup_test_data
setup_test_data
Sets up the test data loader via a Dict-like object.
[ "Sets", "up", "the", "test", "data", "loader", "via", "a", "Dict-like", "object." ]
def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): if 'shuffle' not in test_data_config: test_data_config['shuffle'] = False self._update_dataset_config(dataset_name='test', config=test_data_config) self._test_dl = self._setup_dataloader_from_config(config=test_data_conf...
['def', 'setup_test_data(self,', 'test_data_config:', 'Optional[Union[DictConfig,', 'Dict]]):', 'if', "'shuffle'", 'not', 'in', 'test_data_config:', "test_data_config['shuffle']", '=', 'False', "self._update_dataset_config(dataset_name='test',", 'config=test_data_config)', 'self._test_dl', '=', 'self._setup_dataloader_...
272,405
gunthercox/ChatterBot
ma.py
new_take
new_take
returns selection of items from a.
[ "returns", "selection", "of", "items", "from", "a." ]
def new_take(a, indices, axis=None, out=None, mode='raise'): m = getmask(a) d = masked_array(a).data if m is nomask: return masked_array(numeric.take(d, indices, axis)) else: return masked_array(numeric.take(d, indices, axis), mask=numeric.take(m, indices, axis))
['def', 'new_take(a,', 'indices,', 'axis=None,', 'out=None,', "mode='raise'):", 'm', '=', 'getmask(a)', 'd', '=', 'masked_array(a).data', 'if', 'm', 'is', 'nomask:', 'return', 'masked_array(numeric.take(d,', 'indices,', 'axis))', 'else:', 'return', 'masked_array(numeric.take(d,', 'indices,', 'axis),', 'mask=numeric.tak...
532,416
43Carrig/recurrent_neural_networks_practice
pfor.py
PFor.loop_len_vector
loop_len_vector
Returns a single element vector whose value is number of iterations.
[ "Returns", "a", "single", "element", "vector", "whose", "value", "is", "number", "of", "iterations." ]
def loop_len_vector(self): return self._loop_len_vector
['def', 'loop_len_vector(self):', 'return', 'self._loop_len_vector']
339,337
deepmind/meltingpot
rationalizable_coordination_in_the_matrix__repeated.py
create_avatar_objects
create_avatar_objects
Returns list of avatar objects of length 'num_players'.
[ "Returns", "list", "of", "avatar", "objects", "of", "length", "'num_players'." ]
def create_avatar_objects(num_players, turn_off_default_reward: bool=False): all_source_sprite_names = get_all_source_sprite_names(num_players) avatar_objects = [] for player_idx in range(0, num_players): game_object = create_avatar_object(player_idx, all_source_sprite_names, TARGET_SPRITE_SELF, TAR...
['def', 'create_avatar_objects(num_players,', 'turn_off_default_reward:', 'bool=False):', 'all_source_sprite_names', '=', 'get_all_source_sprite_names(num_players)', 'avatar_objects', '=', '[]', 'for', 'player_idx', 'in', 'range(0,', 'num_players):', 'game_object', '=', 'create_avatar_object(player_idx,', 'all_source_s...
285,442
clips/pattern
__init__.py
parsetree
parsetree
Returns a parsed Text from the given string.
[ "Returns", "a", "parsed", "Text", "from", "the", "given", "string." ]
def parsetree(s, *args, **kwargs): return Text(parse(s, *args, **kwargs))
['def', 'parsetree(s,', '*args,', '**kwargs):', 'return', 'Text(parse(s,', '*args,', '**kwargs))']
765,011
CAMeL-Lab/camel_tools
model6.py
label_to_region
label_to_region
Converts a dialect prediction using labels to use region names instead.
[ "Converts", "a", "dialect", "prediction", "using", "labels", "to", "use", "region", "names", "instead." ]
def label_to_region(prediction): scores = {i: 0.0 for i in _DEFAULT_REGIONS} for (label, prob) in prediction.scores.items(): scores[_LABEL_TO_REGION_MAP[label]] += prob top = max(scores.items(), key=lambda x: x[1]) return DIDPred(top[0], scores)
['def', 'label_to_region(prediction):', 'scores', '=', '{i:', '0.0', 'for', 'i', 'in', '_DEFAULT_REGIONS}', 'for', '(label,', 'prob)', 'in', 'prediction.scores.items():', 'scores[_LABEL_TO_REGION_MAP[label]]', '+=', 'prob', 'top', '=', 'max(scores.items(),', 'key=lambda', 'x:', 'x[1])', 'return', 'DIDPred(top[0],', 'sc...
411,099
Kvatsx/Artificial-Intelligence-Assignments
msvc.py
RegistryInfo.vs
vs
Microsoft Visual Studio VS7 registry key.
[ "Microsoft", "Visual", "Studio", "VS7", "registry", "key." ]
def vs(self): return os.path.join(self.sxs, 'VS7')
['def', 'vs(self):', 'return', 'os.path.join(self.sxs,', "'VS7')"]
78,221
coldmanck/CS5242-Neural-Network-and--Learning-Assignments
net2.py
update_params
update_params
Function to update the parameters of the given layers with the given gradients by gradient descent with the given learning rate.
[ "Function", "to", "update", "the", "parameters", "of", "the", "given", "layers", "with", "the", "given", "gradients", "by", "gradient", "descent", "with", "the", "given", "learning", "rate." ]
def update_params(layers, param_grads, learning_rate): for (layer, layer_backprop_grads) in zip(layers, param_grads): for (param, grad) in zip(layer.get_params_iter(), layer_backprop_grads): param -= learning_rate * grad
['def', 'update_params(layers,', 'param_grads,', 'learning_rate):', 'for', '(layer,', 'layer_backprop_grads)', 'in', 'zip(layers,', 'param_grads):', 'for', '(param,', 'grad)', 'in', 'zip(layer.get_params_iter(),', 'layer_backprop_grads):', 'param', '-=', 'learning_rate', '*', 'grad']
508,275
weimin17/Object-Detection_HelmetDetection
losses.py
regularization_loss
regularization_loss
Computes the weight decay as regularization during training.
[ "Computes", "the", "weight", "decay", "as", "regularization", "during", "training." ]
def regularization_loss(scopes, params): reg_loss = tf.zeros(dtype=tf.float32, shape=[]) if params.weight_decay > 0: is_trainable = lambda x: x in tf.trainable_variables() is_weights = lambda x: 'weights' in x.name for scope in scopes: scope_vars = filter(is_trainable, tf.con...
['def', 'regularization_loss(scopes,', 'params):', 'reg_loss', '=', 'tf.zeros(dtype=tf.float32,', 'shape=[])', 'if', 'params.weight_decay', '>', '0:', 'is_trainable', '=', 'lambda', 'x:', 'x', 'in', 'tf.trainable_variables()', 'is_weights', '=', 'lambda', 'x:', "'weights'", 'in', 'x.name', 'for', 'scope', 'in', 'scopes...
759,435
songw-zju/Meta-RangeSeg
utils.py
load_files
load_files
Load all files in a folder and sort.
[ "Load", "all", "files", "in", "a", "folder", "and", "sort." ]
def load_files(folder): file_paths = [os.path.join(dp, f) for (dp, dn, fn) in os.walk(os.path.expanduser(folder)) for f in fn] file_paths.sort() return file_paths
['def', 'load_files(folder):', 'file_paths', '=', '[os.path.join(dp,', 'f)', 'for', '(dp,', 'dn,', 'fn)', 'in', 'os.walk(os.path.expanduser(folder))', 'for', 'f', 'in', 'fn]', 'file_paths.sort()', 'return', 'file_paths']
632,972
weimin17/Object-Detection_HelmetDetection
datum_io.py
ReadFromFile
ReadFromFile
Helper function to load data from a DatumProto format in a file.
[ "Helper", "function", "to", "load", "data", "from", "a", "DatumProto", "format", "in", "a", "file." ]
def ReadFromFile(file_path): with tf.gfile.FastGFile(file_path, 'rb') as f: return ParseFromString(f.read())
['def', 'ReadFromFile(file_path):', 'with', 'tf.gfile.FastGFile(file_path,', "'rb')", 'as', 'f:', 'return', 'ParseFromString(f.read())']
749,628
omonimus1/super-computer-
req_command.py
RequirementCommand.make_requirement_preparer
make_requirement_preparer
Create a RequirementPreparer instance for the given parameters.
[ "Create", "a", "RequirementPreparer", "instance", "for", "the", "given", "parameters." ]
def make_requirement_preparer(temp_build_dir, options, req_tracker, session, finder, use_user_site, download_dir=None, wheel_download_dir=None): downloader = Downloader(session, progress_bar=options.progress_bar) temp_build_dir_path = temp_build_dir.path assert temp_build_dir_path is not None return Req...
['def', 'make_requirement_preparer(temp_build_dir,', 'options,', 'req_tracker,', 'session,', 'finder,', 'use_user_site,', 'download_dir=None,', 'wheel_download_dir=None):', 'downloader', '=', 'Downloader(session,', 'progress_bar=options.progress_bar)', 'temp_build_dir_path', '=', 'temp_build_dir.path', 'assert', 'temp_...
913,087
pangsu0613/CLOCs
voxelnet.py
VoxelNet.forward
forward
module's forward should always accept dict and return loss.
[ "module's", "forward", "should", "always", "accept", "dict", "and", "return", "loss." ]
def forward(self, example, detection_2d_path): voxels = example['voxels'] num_points = example['num_points'] coors = example['coordinates'] batch_anchors = example['anchors'] batch_size_dev = batch_anchors.shape[0] t = time.time() self.start_timer('voxel_feature_extractor') voxel_feature...
['def', 'forward(self,', 'example,', 'detection_2d_path):', 'voxels', '=', "example['voxels']", 'num_points', '=', "example['num_points']", 'coors', '=', "example['coordinates']", 'batch_anchors', '=', "example['anchors']", 'batch_size_dev', '=', 'batch_anchors.shape[0]', 't', '=', 'time.time()', "self.start_timer('vox...
488,362
Xianpeng919/MonoCon
pillar_scatter.py
PointPillarsScatter.forward
forward
Foraward function to scatter features.
[ "Foraward", "function", "to", "scatter", "features." ]
def forward(self, voxel_features, coors, batch_size=None): if batch_size is not None: return self.forward_batch(voxel_features, coors, batch_size) else: return self.forward_single(voxel_features, coors)
['def', 'forward(self,', 'voxel_features,', 'coors,', 'batch_size=None):', 'if', 'batch_size', 'is', 'not', 'None:', 'return', 'self.forward_batch(voxel_features,', 'coors,', 'batch_size)', 'else:', 'return', 'self.forward_single(voxel_features,', 'coors)']
654,603
Ixiaohuihuihui/AO2-DETR
gmm.py
GaussianMixture.update_pi
update_pi
Updates pi to the provided value.
[ "Updates", "pi", "to", "the", "provided", "value." ]
def update_pi(self, pi): assert pi.size() == (self.T, self.n_components, 1), 'Input pi does not have required tensor dimensions (%i, %i, %i)' % (self.T, self.n_components, 1) self.pi = pi.clone()
['def', 'update_pi(self,', 'pi):', 'assert', 'pi.size()', '==', '(self.T,', 'self.n_components,', '1),', "'Input", 'pi', 'does', 'not', 'have', 'required', 'tensor', 'dimensions', '(%i,', '%i,', "%i)'", '%', '(self.T,', 'self.n_components,', '1)', 'self.pi', '=', 'pi.clone()']
401,436
scikit-learn-contrib/imbalanced-learn
test_param_validation.py
test_instances_of_type_human_readable
test_instances_of_type_human_readable
Check the string representation of the _InstancesOf constraint.
[ "Check", "the", "string", "representation", "of", "the", "_InstancesOf", "constraint." ]
def test_instances_of_type_human_readable(type, expected_type_name): constraint = _InstancesOf(type) assert str(constraint) == f"an instance of '{expected_type_name}'"
['def', 'test_instances_of_type_human_readable(type,', 'expected_type_name):', 'constraint', '=', '_InstancesOf(type)', 'assert', 'str(constraint)', '==', 'f"an', 'instance', 'of', '\'{expected_type_name}\'"']
610,706
gunthercox/ChatterBot
test_core.py
TestMaskedArray.test_oddfeatures_2
test_oddfeatures_2
Tests some more features.
[ "Tests", "some", "more", "features." ]
def test_oddfeatures_2(self): x = array([1.0, 2.0, 3.0, 4.0, 5.0]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_equal(z, [1.0, 2.0, 0.0, -4.0, -5]) c[0] = masked z = where(c, x, -x) assert_equal(z, [1.0, 2.0, 0.0, -4.0, -5]) assert_(z[0] is masked) assert_(...
['def', 'test_oddfeatures_2(self):', 'x', '=', 'array([1.0,', '2.0,', '3.0,', '4.0,', '5.0])', 'c', '=', 'array([1,', '1,', '1,', '0,', '0])', 'x[2]', '=', 'masked', 'z', '=', 'where(c,', 'x,', '-x)', 'assert_equal(z,', '[1.0,', '2.0,', '0.0,', '-4.0,', '-5])', 'c[0]', '=', 'masked', 'z', '=', 'where(c,', 'x,', '-x)', ...
531,980
myothida/Supervised-Machine-Learning
afmLib.py
AFM.kernpairs
kernpairs
Returns a list of all kern pairs in the kerning dictionary.
[ "Returns", "a", "list", "of", "all", "kern", "pairs", "in", "the", "kerning", "dictionary." ]
def kernpairs(self): return list(self._kerning.keys())
['def', 'kernpairs(self):', 'return', 'list(self._kerning.keys())']
360,708
thaines/helit
line_overlay_layer.py
LineOverlayLayer.set_segment
set_segment
Call this to set which segment is game.
[ "Call", "this", "to", "set", "which", "segment", "is", "game." ]
def set_segment(self, segment): self.segment = segment self.bound = None
['def', 'set_segment(self,', 'segment):', 'self.segment', '=', 'segment', 'self.bound', '=', 'None']
591,995
greydanus/pythonic_ocr
environment.py
create_cache
create_cache
Return the cache class for the given size.
[ "Return", "the", "cache", "class", "for", "the", "given", "size." ]
def create_cache(size): if size == 0: return None if size < 0: return {} return LRUCache(size)
['def', 'create_cache(size):', 'if', 'size', '==', '0:', 'return', 'None', 'if', 'size', '<', '0:', 'return', '{}', 'return', 'LRUCache(size)']
299,216
flow-project/flow
aimsun.py
AimsunKernelVehicle.remove_observed
remove_observed
Remove a vehicle from the list of observed vehicles.
[ "Remove", "a", "vehicle", "from", "the", "list", "of", "observed", "vehicles." ]
def remove_observed(self, veh_id): if veh_id in self.__observed_ids: self.__observed_ids.remove(veh_id)
['def', 'remove_observed(self,', 'veh_id):', 'if', 'veh_id', 'in', 'self.__observed_ids:', 'self.__observed_ids.remove(veh_id)']
212,156
openvinotoolkit/training_extensions
utils.py
get_op_name
get_op_name
Get op name string.
[ "Get", "op", "name", "string." ]
def get_op_name(op_node: Node) -> str: op_name = op_node.get_friendly_name() op_name = normalize_name(op_name) return op_name
['def', 'get_op_name(op_node:', 'Node)', '->', 'str:', 'op_name', '=', 'op_node.get_friendly_name()', 'op_name', '=', 'normalize_name(op_name)', 'return', 'op_name']
919,073
QData/deepWordBug
environment.py
env_vars_from_file
env_vars_from_file
Read in a line delimited file of environment variables.
[ "Read", "in", "a", "line", "delimited", "file", "of", "environment", "variables." ]
def env_vars_from_file(filename): if not os.path.exists(filename): raise ConfigurationError("Couldn't find env file: %s" % filename) elif not os.path.isfile(filename): raise ConfigurationError('%s is not a file.' % filename) env = {} with contextlib.closing(codecs.open(filename, 'r', 'ut...
['def', 'env_vars_from_file(filename):', 'if', 'not', 'os.path.exists(filename):', 'raise', 'ConfigurationError("Couldn\'t', 'find', 'env', 'file:', '%s"', '%', 'filename)', 'elif', 'not', 'os.path.isfile(filename):', 'raise', "ConfigurationError('%s", 'is', 'not', 'a', "file.'", '%', 'filename)', 'env', '=', '{}', 'wi...
541,788
NoGameNoLife00/mybolg
runtime.py
Context.get_all
get_all
Return a copy of the complete context as dict including the exported variables.
[ "Return", "a", "copy", "of", "the", "complete", "context", "as", "dict", "including", "the", "exported", "variables." ]
def get_all(self): return dict(self.parent, **self.vars)
['def', 'get_all(self):', 'return', 'dict(self.parent,', '**self.vars)']
289,591
arshpreetsingh/quantopian-machinelearning
series.py
Series.dtypes
dtypes
Return the dtype object of the underlying data.
[ "Return", "the", "dtype", "object", "of", "the", "underlying", "data." ]
def dtypes(self): return self._data.dtype
['def', 'dtypes(self):', 'return', 'self._data.dtype']
889,666
OlafenwaMoses/ImageAI
coco.py
CocoGenerator.label_to_coco_label
label_to_coco_label
Map label as used by the network to labels as used by COCO.
[ "Map", "label", "as", "used", "by", "the", "network", "to", "labels", "as", "used", "by", "COCO." ]
def label_to_coco_label(self, label): return self.coco_labels[label]
['def', 'label_to_coco_label(self,', 'label):', 'return', 'self.coco_labels[label]']
599,290
salesforce/CodeRL
tokenization_pegasus.py
PegasusTokenizer.get_special_tokens_mask
get_special_tokens_mask
Get list where entries are [1] if a token is [eos] or [pad] else 0.
[ "Get", "list", "where", "entries", "are", "[1]", "if", "a", "token", "is", "[eos]", "or", "[pad]", "else", "0." ]
def get_special_tokens_mask(self, token_ids_0: List, token_ids_1: Optional[List]=None, already_has_special_tokens: bool=False) -> List[int]: if already_has_special_tokens: return self._special_token_mask(token_ids_0) elif token_ids_1 is None: return self._special_token_mask(token_ids_0) + [1] ...
['def', 'get_special_tokens_mask(self,', 'token_ids_0:', 'List,', 'token_ids_1:', 'Optional[List]=None,', 'already_has_special_tokens:', 'bool=False)', '->', 'List[int]:', 'if', 'already_has_special_tokens:', 'return', 'self._special_token_mask(token_ids_0)', 'elif', 'token_ids_1', 'is', 'None:', 'return', 'self._speci...
494,975
tensorflow/agents
common.py
check_no_shared_variables
check_no_shared_variables
Checks that there are no shared trainable variables in the two networks.
[ "Checks", "that", "there", "are", "no", "shared", "trainable", "variables", "in", "the", "two", "networks." ]
def check_no_shared_variables(network_1, network_2): variables_1 = object_identity.ObjectIdentitySet(network_1.trainable_variables) variables_2 = object_identity.ObjectIdentitySet(network_2.trainable_variables) shared_variables = variables_1 & variables_2 if shared_variables: raise ValueError("A...
['def', 'check_no_shared_variables(network_1,', 'network_2):', 'variables_1', '=', 'object_identity.ObjectIdentitySet(network_1.trainable_variables)', 'variables_2', '=', 'object_identity.ObjectIdentitySet(network_2.trainable_variables)', 'shared_variables', '=', 'variables_1', '&', 'variables_2', 'if', 'shared_variabl...
23,801
sktime/sktime
base.py
BaseResults.load_predictions
load_predictions
Load predictions for all datasets and strategies iteratively.
[ "Load", "predictions", "for", "all", "datasets", "and", "strategies", "iteratively." ]
def load_predictions(self, cv_fold, train_or_test): raise NotImplementedError()
['def', 'load_predictions(self,', 'cv_fold,', 'train_or_test):', 'raise', 'NotImplementedError()']
885,811
intelligent-environments-lab/CityLearn
wrappers.py
StableBaselines3ObservationWrapper.observation
observation
Returns observations as 1-dimensional numpy array.
[ "Returns", "observations", "as", "1-dimensional", "numpy", "array." ]
def observation(self, observations: List[List[float]]) -> np.ndarray: return np.array(observations[0], dtype='float32')
['def', 'observation(self,', 'observations:', 'List[List[float]])', '->', 'np.ndarray:', 'return', 'np.array(observations[0],', "dtype='float32')"]
105,784
csjunxu/Noisy-As-Clean-TIP2020
glibc.py
glibc_version_string_ctypes
glibc_version_string_ctypes
Fallback implementation of glibc_version_string using ctypes.
[ "Fallback", "implementation", "of", "glibc_version_string", "using", "ctypes." ]
def glibc_version_string_ctypes(): try: import ctypes except ImportError: return None process_namespace = ctypes.CDLL(None) try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: return None gnu_get_libc_version.restype = ctypes....
['def', 'glibc_version_string_ctypes():', 'try:', 'import', 'ctypes', 'except', 'ImportError:', 'return', 'None', 'process_namespace', '=', 'ctypes.CDLL(None)', 'try:', 'gnu_get_libc_version', '=', 'process_namespace.gnu_get_libc_version', 'except', 'AttributeError:', 'return', 'None', 'gnu_get_libc_version.restype', '...
294,799
eth-sri/debin
descriptions.py
describe_CFI_instructions
describe_CFI_instructions
Given a CFI entry (CIE or FDE), return the textual description of its instructions.
[ "Given", "a", "CFI", "entry", "(CIE", "or", "FDE),", "return", "the", "textual", "description", "of", "its", "instructions." ]
def describe_CFI_instructions(entry): def _assert_FDE_instruction(instr): dwarf_assert(isinstance(entry, FDE), 'Unexpected instruction "%s" for a CIE' % instr) def _full_reg_name(regnum): regname = describe_reg_name(regnum, _MACHINE_ARCH, False) if regname: return 'r%s (%s)...
['def', 'describe_CFI_instructions(entry):', 'def', '_assert_FDE_instruction(instr):', 'dwarf_assert(isinstance(entry,', 'FDE),', "'Unexpected", 'instruction', '"%s"', 'for', 'a', "CIE'", '%', 'instr)', 'def', '_full_reg_name(regnum):', 'regname', '=', 'describe_reg_name(regnum,', '_MACHINE_ARCH,', 'False)', 'if', 'reg...
516,552
kristogj/deep_learning
dataloader.py
display_face
display_face
Display the input image and optionally save as a PNG.
[ "Display", "the", "input", "image", "and", "optionally", "save", "as", "a", "PNG." ]
def display_face(img): if type(img) == np.ndarray: print('Converting from array to PIL Image') img = Image.fromarray(img) img.show()
['def', 'display_face(img):', 'if', 'type(img)', '==', 'np.ndarray:', "print('Converting", 'from', 'array', 'to', 'PIL', "Image')", 'img', '=', 'Image.fromarray(img)', 'img.show()']
536,562
csjunxu/Noisy-As-Clean-TIP2020
config.py
config.check_header
check_header
Determine if the system header file named by 'header_file' exists and can be found by the preprocessor; return true if so, false otherwise.
[ "Determine", "if", "the", "system", "header", "file", "named", "by", "'header_file'", "exists", "and", "can", "be", "found", "by", "the", "preprocessor;", "return", "true", "if", "so,", "false", "otherwise." ]
def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'): return self.try_cpp(body='/* No body */', headers=[header], include_dirs=include_dirs)
['def', 'check_header(self,', 'header,', 'include_dirs=None,', 'library_dirs=None,', "lang='c'):", 'return', "self.try_cpp(body='/*", 'No', 'body', "*/',", 'headers=[header],', 'include_dirs=include_dirs)']
249,257
lishunyao97/Pun-GAN
train.py
process_stats
process_stats
Update info and check for overflow.
[ "Update", "info", "and", "check", "for", "overflow." ]
def process_stats(stats, info, global_step, steps_per_stats, log_f): info['avg_step_time'] = stats['step_time'] / steps_per_stats info['avg_grad_norm'] = stats['grad_norm'] / steps_per_stats info['train_ppl'] = utils.safe_exp(stats['loss'] / stats['predict_count']) info['speed'] = stats['total_count'] /...
['def', 'process_stats(stats,', 'info,', 'global_step,', 'steps_per_stats,', 'log_f):', "info['avg_step_time']", '=', "stats['step_time']", '/', 'steps_per_stats', "info['avg_grad_norm']", '=', "stats['grad_norm']", '/', 'steps_per_stats', "info['train_ppl']", '=', "utils.safe_exp(stats['loss']", '/', "stats['predict_c...
818,806
giacbrd/ShallowLearn
word2vec.py
LabeledWord2Vec.update_weights
update_weights
Copy all the existing weights, and reset the weights for the newly added vocabulary.
[ "Copy", "all", "the", "existing", "weights,", "and", "reset", "the", "weights", "for", "the", "newly", "added", "vocabulary." ]
def update_weights(self, inputs=True, outputs=True): logger.info('updating layer weights') if inputs: gained_vocab = len(self.wv.vocab) - len(self.wv.syn0) newsyn0 = empty((gained_vocab, self.vector_size), dtype=REAL) for i in range(len(self.wv.syn0), len(self.wv.vocab)): new...
['def', 'update_weights(self,', 'inputs=True,', 'outputs=True):', "logger.info('updating", 'layer', "weights')", 'if', 'inputs:', 'gained_vocab', '=', 'len(self.wv.vocab)', '-', 'len(self.wv.syn0)', 'newsyn0', '=', 'empty((gained_vocab,', 'self.vector_size),', 'dtype=REAL)', 'for', 'i', 'in', 'range(len(self.wv.syn0),'...
350,148
tommytracey/DeepRL-P3-Collaboration-Competition
trainer.py
Trainer.update_model
update_model
Uses training_buffer to update model.
[ "Uses", "training_buffer", "to", "update", "model." ]
def update_model(self): raise UnityTrainerException('The update_model method was not implemented.')
['def', 'update_model(self):', 'raise', "UnityTrainerException('The", 'update_model', 'method', 'was', 'not', "implemented.')"]
539,595
llSourcell/AI_Artist
pyparsing.py
ParseResults.iterkeys
iterkeys
Returns all named result keys.
[ "Returns", "all", "named", "result", "keys." ]
def iterkeys(self): if hasattr(self.__tokdict, 'iterkeys'): return self.__tokdict.iterkeys() else: return iter(self.__tokdict)
['def', 'iterkeys(self):', 'if', 'hasattr(self.__tokdict,', "'iterkeys'):", 'return', 'self.__tokdict.iterkeys()', 'else:', 'return', 'iter(self.__tokdict)']
414,253
AlbertoCasadoPeguero/recurrent_neural_
basic_word2vec.py
build_dataset
build_dataset
Process raw inputs into a dataset.
[ "Process", "raw", "inputs", "into", "a", "dataset." ]
def build_dataset(words, n_words): count = [['UNK', -1]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = dict() for (word, _) in count: dictionary[word] = len(dictionary) data = list() unk_count = 0 for word in words: index = dictionary.get(word...
['def', 'build_dataset(words,', 'n_words):', 'count', '=', "[['UNK',", '-1]]', 'count.extend(collections.Counter(words).most_common(n_words', '-', '1))', 'dictionary', '=', 'dict()', 'for', '(word,', '_)', 'in', 'count:', 'dictionary[word]', '=', 'len(dictionary)', 'data', '=', 'list()', 'unk_count', '=', '0', 'for', '...
309,526
nilearn/nilearn
test_plot_anat.py
test_plot_anat_3d_img
test_plot_anat_3d_img
Smoke test for plot_anat.
[ "Smoke", "test", "for", "plot_anat." ]
def test_plot_anat_3d_img(img_3d_mni, tmp_path): filename = tmp_path / 'test.png' slicer = plot_anat(img_3d_mni, dim='auto') slicer.savefig(filename) plt.close()
['def', 'test_plot_anat_3d_img(img_3d_mni,', 'tmp_path):', 'filename', '=', 'tmp_path', '/', "'test.png'", 'slicer', '=', 'plot_anat(img_3d_mni,', "dim='auto')", 'slicer.savefig(filename)', 'plt.close()']
724,151
rudranil723/mini-main
_base.py
_AxesBase.get_autoscale_on
get_autoscale_on
Return True if each axis is autoscaled, False otherwise.
[ "Return", "True", "if", "each", "axis", "is", "autoscaled,", "False", "otherwise." ]
def get_autoscale_on(self): return all((axis._get_autoscale_on() for axis in self._axis_map.values()))
['def', 'get_autoscale_on(self):', 'return', 'all((axis._get_autoscale_on()', 'for', 'axis', 'in', 'self._axis_map.values()))']
319,960
43Carrig/recurrent_neural_networks_practice
debugger_cli_common.py
CommandHandlerRegistry.is_registered
is_registered
Test if a command prefix or its alias is has a registered handler.
[ "Test", "if", "a", "command", "prefix", "or", "its", "alias", "is", "has", "a", "registered", "handler." ]
def is_registered(self, prefix): return self._resolve_prefix(prefix) is not None
['def', 'is_registered(self,', 'prefix):', 'return', 'self._resolve_prefix(prefix)', 'is', 'not', 'None']
335,886
zihuitang/medical_AI_platform
__init__.py
Canvas.bbox
bbox
Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments.
[ "Return", "a", "tuple", "of", "X1,Y1,X2,Y2", "coordinates", "for", "a", "rectangle", "which", "encloses", "all", "items", "with", "tags", "specified", "as", "arguments." ]
def bbox(self, *args): return self._getints(self.tk.call((self._w, 'bbox') + args)) or None
['def', 'bbox(self,', '*args):', 'return', 'self._getints(self.tk.call((self._w,', "'bbox')", '+', 'args))', 'or', 'None']
284,208
weimin17/Object-Detection_HelmetDetection
census_test.py
BaseTest.build_and_test_estimator
build_and_test_estimator
Ensure that model trains and minimizes loss.
[ "Ensure", "that", "model", "trains", "and", "minimizes", "loss." ]
def build_and_test_estimator(self, model_type): model = census_main.build_estimator(self.temp_dir, model_type, model_column_fn=census_dataset.build_model_columns) def get_input_fn(num_epochs, shuffle, batch_size): def input_fn(): return census_dataset.input_fn(TEST_CSV, num_epochs=num_epoc...
['def', 'build_and_test_estimator(self,', 'model_type):', 'model', '=', 'census_main.build_estimator(self.temp_dir,', 'model_type,', 'model_column_fn=census_dataset.build_model_columns)', 'def', 'get_input_fn(num_epochs,', 'shuffle,', 'batch_size):', 'def', 'input_fn():', 'return', 'census_dataset.input_fn(TEST_CSV,', ...
761,370
scottemmons/rvs
step.py
rollout_and_render
rollout_and_render
Roll the policy out in the environment and render every step.
[ "Roll", "the", "policy", "out", "in", "the", "environment", "and", "render", "every", "step." ]
def rollout_and_render(policy: Union[policies.RvS, Callable[[np.ndarray, np.ndarray], np.ndarray]], env: gym.Env, max_episode_steps: int, fixed_goal: Optional[np.ndarray]=None, dynamic_kitchen_goal: bool=False) -> List[np.ndarray]: frames = [] if not max_episode_steps: max_episode_steps = sys.maxsize ...
['def', 'rollout_and_render(policy:', 'Union[policies.RvS,', 'Callable[[np.ndarray,', 'np.ndarray],', 'np.ndarray]],', 'env:', 'gym.Env,', 'max_episode_steps:', 'int,', 'fixed_goal:', 'Optional[np.ndarray]=None,', 'dynamic_kitchen_goal:', 'bool=False)', '->', 'List[np.ndarray]:', 'frames', '=', '[]', 'if', 'not', 'max_...
326,999
arshpreetsingh/quantopian-machinelearning
element.py
PageElement.find_parents
find_parents
Returns the parents of this Tag that match the given criteria.
[ "Returns", "the", "parents", "of", "this", "Tag", "that", "match", "the", "given", "criteria." ]
def find_parents(self, name=None, attrs={}, limit=None, **kwargs): return self._find_all(name, attrs, None, limit, self.parents, **kwargs)
['def', 'find_parents(self,', 'name=None,', 'attrs={},', 'limit=None,', '**kwargs):', 'return', 'self._find_all(name,', 'attrs,', 'None,', 'limit,', 'self.parents,', '**kwargs)']
816,492
ludwig-ai/ludwig
dataset_loader.py
DatasetLoader.get_mtime
get_mtime
Last modified time of the processed dataset after downloading successfully.
[ "Last", "modified", "time", "of", "the", "processed", "dataset", "after", "downloading", "successfully." ]
def get_mtime(self) -> float: return os.path.getmtime(self.processed_dataset_path)
['def', 'get_mtime(self)', '->', 'float:', 'return', 'os.path.getmtime(self.processed_dataset_path)']
616,697
triaquae/triaquae
srs.py
SpatialReference.semi_minor
semi_minor
Returns the Semi Minor Axis for this Spatial Reference.
[ "Returns", "the", "Semi", "Minor", "Axis", "for", "this", "Spatial", "Reference." ]
def semi_minor(self): return capi.semi_minor(self.ptr, byref(c_int()))
['def', 'semi_minor(self):', 'return', 'capi.semi_minor(self.ptr,', 'byref(c_int()))']
357,651
nilearn/nilearn
regression.py
SimpleRegressionResults.residuals
residuals
Residuals from the fit.
[ "Residuals", "from", "the", "fit." ]
def residuals(self, Y): return Y - self.predicted
['def', 'residuals(self,', 'Y):', 'return', 'Y', '-', 'self.predicted']
723,806
catlab-team/latentclr
util.py
Logger.close
close
Flush, close possible files, and remove stdout/stderr mirroring.
[ "Flush,", "close", "possible", "files,", "and", "remove", "stdout/stderr", "mirroring." ]
def close(self) -> None: self.flush() if sys.stdout is self: sys.stdout = self.stdout if sys.stderr is self: sys.stderr = self.stderr if self.file is not None: self.file.close()
['def', 'close(self)', '->', 'None:', 'self.flush()', 'if', 'sys.stdout', 'is', 'self:', 'sys.stdout', '=', 'self.stdout', 'if', 'sys.stderr', 'is', 'self:', 'sys.stderr', '=', 'self.stderr', 'if', 'self.file', 'is', 'not', 'None:', 'self.file.close()']
261,953
heynemann/pyvows
version.py
to_str
to_str
Returns a string containing PyVows' version number.
[ "Returns", "a", "string", "containing", "PyVows'", "version", "number." ]
def to_str(): return '.'.join([str(item) for item in __version__])
['def', 'to_str():', 'return', "'.'.join([str(item)", 'for', 'item', 'in', '__version__])']
302,614
open-mmlab/mmtracking
stark_head.py
CornerPredictorHead.soft_argmax
soft_argmax
Get soft-argmax coordinate for the given score map.
[ "Get", "soft-argmax", "coordinate", "for", "the", "given", "score", "map." ]
def soft_argmax(self, score_map): score_vec = score_map.view((-1, self.feat_size * self.feat_size)) prob_vec = nn.functional.softmax(score_vec, dim=1) if not hasattr(self, 'coord_x'): self.indice = torch.arange(0, self.feat_size, device=score_map.device).view(-1, 1) * self.stride self.coord_...
['def', 'soft_argmax(self,', 'score_map):', 'score_vec', '=', 'score_map.view((-1,', 'self.feat_size', '*', 'self.feat_size))', 'prob_vec', '=', 'nn.functional.softmax(score_vec,', 'dim=1)', 'if', 'not', 'hasattr(self,', "'coord_x'):", 'self.indice', '=', 'torch.arange(0,', 'self.feat_size,', 'device=score_map.device)....
625,906
frapa/tbcnn
sampling.py
traverse_nodes
traverse_nodes
Return a generator that traverses all nodes of a tree.
[ "Return", "a", "generator", "that", "traverses", "all", "nodes", "of", "a", "tree." ]
def traverse_nodes(tree): queue = [tree] while queue: current_node = queue.pop(0) children = list(ast.iter_child_nodes(current_node)) queue.extend(children) yield current_node
['def', 'traverse_nodes(tree):', 'queue', '=', '[tree]', 'while', 'queue:', 'current_node', '=', 'queue.pop(0)', 'children', '=', 'list(ast.iter_child_nodes(current_node))', 'queue.extend(children)', 'yield', 'current_node']
365,586
aws/sagemaker-python-sdk
test_async_inference_response.py
mock_s3_client
mock_s3_client
This function returns a mocked S3 client object that has a get_object method with a side_effect that returns a dictionary with a Body key that points to a mocked response body object.
[ "This", "function", "returns", "a", "mocked", "S3", "client", "object", "that", "has", "a", "get_object", "method", "with", "a", "side_effect", "that", "returns", "a", "dictionary", "with", "a", "Body", "key", "that", "points", "to", "a", "mocked", "response...
def mock_s3_client(): s3_client = Mock(name='s3-client') response_body = Mock('body') response_body.read = Mock('read', return_value=RETURN_VALUE) response_body.close = Mock('close', return_value=None) s3_client.get_object = Mock(name='get_object', side_effect=[{'Body': response_body}]) return s...
['def', 'mock_s3_client():', 's3_client', '=', "Mock(name='s3-client')", 'response_body', '=', "Mock('body')", 'response_body.read', '=', "Mock('read',", 'return_value=RETURN_VALUE)', 'response_body.close', '=', "Mock('close',", 'return_value=None)', 's3_client.get_object', '=', "Mock(name='get_object',", "side_effect=...
844,862
Ruturaj123/Flowchart-Detection
util.py
get_logits_and_probs
get_logits_and_probs
Converts logit to probabilities (or vice-versa), and returns both.
[ "Converts", "logit", "to", "probabilities", "(or", "vice-versa),", "and", "returns", "both." ]
def get_logits_and_probs(logits=None, probs=None, multidimensional=False, validate_args=False, name='get_logits_and_probs'): with ops.name_scope(name, values=[probs, logits]): if (probs is None) == (logits is None): raise ValueError('Must pass probs or logits, but not both.') if probs is...
['def', 'get_logits_and_probs(logits=None,', 'probs=None,', 'multidimensional=False,', 'validate_args=False,', "name='get_logits_and_probs'):", 'with', 'ops.name_scope(name,', 'values=[probs,', 'logits]):', 'if', '(probs', 'is', 'None)', '==', '(logits', 'is', 'None):', 'raise', "ValueError('Must", 'pass', 'probs', 'or...
606,293
aleju/self-driving-truck
models.py
add_white_noise
add_white_noise
Layer that adds white/gaussian noise to its input.
[ "Layer", "that", "adds", "white/gaussian", "noise", "to", "its", "input." ]
def add_white_noise(x, std, training): if training: noise = Variable(x.data.new().resize_as_(x.data).normal_(mean=0, std=std), volatile=x.volatile, requires_grad=False).type_as(x) x = x + noise return x
['def', 'add_white_noise(x,', 'std,', 'training):', 'if', 'training:', 'noise', '=', 'Variable(x.data.new().resize_as_(x.data).normal_(mean=0,', 'std=std),', 'volatile=x.volatile,', 'requires_grad=False).type_as(x)', 'x', '=', 'x', '+', 'noise', 'return', 'x']
843,251
xiaoaleiBLUE/computer_vision
resnet.py
ResnetBuilder.build
build
Builds a custom ResNet like architecture.
[ "Builds", "a", "custom", "ResNet", "like", "architecture." ]
def build(input, input_shape, num_outputs, block_fn, repetitions): _handle_dim_ordering() if len(input_shape) != 3: raise Exception('Input shape should be a tuple (nb_channels, nb_rows, nb_cols)') block_fn = _get_block(block_fn) conv1 = _conv_bn_relu(filters=64, kernel_size=(7, 7), strides=(2, 2...
['def', 'build(input,', 'input_shape,', 'num_outputs,', 'block_fn,', 'repetitions):', '_handle_dim_ordering()', 'if', 'len(input_shape)', '!=', '3:', 'raise', "Exception('Input", 'shape', 'should', 'be', 'a', 'tuple', '(nb_channels,', 'nb_rows,', "nb_cols)')", 'block_fn', '=', '_get_block(block_fn)', 'conv1', '=', '_co...
502,810
Visual-Attention-Network/SegNeXt
class_names.py
loveda_classes
loveda_classes
LoveDA class names for external use.
[ "LoveDA", "class", "names", "for", "external", "use." ]
def loveda_classes(): return ['background', 'building', 'road', 'water', 'barren', 'forest', 'agricultural']
['def', 'loveda_classes():', 'return', "['background',", "'building',", "'road',", "'water',", "'barren',", "'forest',", "'agricultural']"]
842,941
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
graphs.py
VatxtModel.eval_graph
eval_graph
Constructs classifier evaluation graph.
[ "Constructs", "classifier", "evaluation", "graph." ]
def eval_graph(self, dataset='test'): inputs = _inputs(dataset, pretrain=False) embedded = self.layers['embedding'](inputs.tokens) (_, next_state, logits, _) = self.cl_loss_from_embedding(embedded, inputs=inputs, return_intermediates=True) eval_ops = {'accuracy': tf.contrib.metrics.streaming_accuracy(la...
['def', 'eval_graph(self,', "dataset='test'):", 'inputs', '=', '_inputs(dataset,', 'pretrain=False)', 'embedded', '=', "self.layers['embedding'](inputs.tokens)", '(_,', 'next_state,', 'logits,', '_)', '=', 'self.cl_loss_from_embedding(embedded,', 'inputs=inputs,', 'return_intermediates=True)', 'eval_ops', '=', "{'accur...
14,210
myothida/Supervised-Machine-Learning
__init__.py
evaluateRule
evaluateRule
Return True if any of the rule's conditionsets matches the given location.
[ "Return", "True", "if", "any", "of", "the", "rule's", "conditionsets", "matches", "the", "given", "location." ]
def evaluateRule(rule, location): return any((evaluateConditions(c, location) for c in rule.conditionSets))
['def', 'evaluateRule(rule,', 'location):', 'return', 'any((evaluateConditions(c,', 'location)', 'for', 'c', 'in', 'rule.conditionSets))']
360,773
coder-mano/Shi-Tomasi-Corner-Detector
test_extint128.py
exc_iter
exc_iter
Iterate over Cartesian product of *args, and if an exception is raised, add information of the current iterate.
[ "Iterate", "over", "Cartesian", "product", "of", "*args,", "and", "if", "an", "exception", "is", "raised,", "add", "information", "of", "the", "current", "iterate." ]
def exc_iter(*args): value = [None] def iterate(): for v in itertools.product(*args): value[0] = v yield v try: yield iterate() except Exception: import traceback msg = 'At: %r\n%s' % (repr(value[0]), traceback.format_exc()) raise Assertio...
['def', 'exc_iter(*args):', 'value', '=', '[None]', 'def', 'iterate():', 'for', 'v', 'in', 'itertools.product(*args):', 'value[0]', '=', 'v', 'yield', 'v', 'try:', 'yield', 'iterate()', 'except', 'Exception:', 'import', 'traceback', 'msg', '=', "'At:", "%r\\n%s'", '%', '(repr(value[0]),', 'traceback.format_exc())', 'ra...
899,197
arshpreetsingh/quantopian-machinelearning
utils.py
to_str
to_str
Turn callable or string into string.
[ "Turn", "callable", "or", "string", "into", "string." ]
def to_str(value): if callable(value): return to_str(value()) else: return text_type(value)
['def', 'to_str(value):', 'if', 'callable(value):', 'return', 'to_str(value())', 'else:', 'return', 'text_type(value)']
892,101
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
wide_deep.py
input_fn
input_fn
Generate an input function for the Estimator.
[ "Generate", "an", "input", "function", "for", "the", "Estimator." ]
def input_fn(data_file, num_epochs, shuffle, batch_size): assert tf.gfile.Exists(data_file), '%s not found. Please make sure you have either run data_download.py or set both arguments --train_data and --test_data.' % data_file def parse_csv(value): print('Parsing', data_file) columns = tf.decod...
['def', 'input_fn(data_file,', 'num_epochs,', 'shuffle,', 'batch_size):', 'assert', 'tf.gfile.Exists(data_file),', "'%s", 'not', 'found.', 'Please', 'make', 'sure', 'you', 'have', 'either', 'run', 'data_download.py', 'or', 'set', 'both', 'arguments', '--train_data', 'and', "--test_data.'", '%', 'data_file', 'def', 'par...
14,099
NICTA/MLSS
tututils.py
load_2d_hard
load_2d_hard
Returns non-isotropoic data to motivate the use of non-euclidean norms (as well as the ground truth).
[ "Returns", "non-isotropoic", "data", "to", "motivate", "the", "use", "of", "non-euclidean", "norms", "(as", "well", "as", "the", "ground", "truth)." ]
def load_2d_hard(): centres = np.array([[3.0, -1.0], [-2.0, 1.0], [2.0, 5.0]]) covs = [] covs.append(np.array([[4.0, 2.0], [2.0, 1.5]])) covs.append(np.array([[1, -1.5], [-1.5, 3.0]])) covs.append(np.array([[1.0, 0.0], [0.0, 1.0]])) N = [1000, 500, 300] X = [np.random.randn(n, 2).dot(la.chol...
['def', 'load_2d_hard():', 'centres', '=', 'np.array([[3.0,', '-1.0],', '[-2.0,', '1.0],', '[2.0,', '5.0]])', 'covs', '=', '[]', 'covs.append(np.array([[4.0,', '2.0],', '[2.0,', '1.5]]))', 'covs.append(np.array([[1,', '-1.5],', '[-1.5,', '3.0]]))', 'covs.append(np.array([[1.0,', '0.0],', '[0.0,', '1.0]]))', 'N', '=', '...
630,964
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pygame_console.py
PyGameConsole.wait
wait
Wait for an event.
[ "Wait", "for", "an", "event." ]
def wait(self): raise Exception('erp!')
['def', 'wait(self):', 'raise', "Exception('erp!')"]
377,441
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
interaction.py
Interaction.shuffle
shuffle
Shuffle current interaction inplace.
[ "Shuffle", "current", "interaction", "inplace." ]
def shuffle(self): index = torch.randperm(self.length) self._reindex(index)
['def', 'shuffle(self):', 'index', '=', 'torch.randperm(self.length)', 'self._reindex(index)']
341,776
Rshcaroline/FDU-Artificial-Intelligence
util.py
brain_restart
brain_restart
Restart the game, set all squares to zero.
[ "Restart", "the", "game,", "set", "all", "squares", "to", "zero." ]
def brain_restart(): for x in range(pp.width): for y in range(pp.height): board[x][y] = 0 pp.pipeOut('OK')
['def', 'brain_restart():', 'for', 'x', 'in', 'range(pp.width):', 'for', 'y', 'in', 'range(pp.height):', 'board[x][y]', '=', '0', "pp.pipeOut('OK')"]
179,101
AndrewYinLi/lstm-neural-network-spam-filter
grammar.py
FeatureGrammar.leftcorner_parents
leftcorner_parents
Return the set of all categories for which the given category is a left corner.
[ "Return", "the", "set", "of", "all", "categories", "for", "which", "the", "given", "category", "is", "a", "left", "corner." ]
def leftcorner_parents(self, cat): raise NotImplementedError('Not implemented yet')
['def', 'leftcorner_parents(self,', 'cat):', 'raise', "NotImplementedError('Not", 'implemented', "yet')"]
217,298
TrellixVulnTeam/Unsupervised_Learning_HFI7
figure.py
_AxesStack.as_list
as_list
Return a list of the Axes instances that have been added to the figure.
[ "Return", "a", "list", "of", "the", "Axes", "instances", "that", "have", "been", "added", "to", "the", "figure." ]
def as_list(self): ia_list = [a for (k, a) in self._elements] ia_list.sort() return [a for (i, a) in ia_list]
['def', 'as_list(self):', 'ia_list', '=', '[a', 'for', '(k,', 'a)', 'in', 'self._elements]', 'ia_list.sort()', 'return', '[a', 'for', '(i,', 'a)', 'in', 'ia_list]']
450,394
myothida/Supervised-Machine-Learning
indexing.py
check_dict_or_set_indexers
check_dict_or_set_indexers
Check if the indexer is or contains a dict or set, which is no longer allowed.
[ "Check", "if", "the", "indexer", "is", "or", "contains", "a", "dict", "or", "set,", "which", "is", "no", "longer", "allowed." ]
def check_dict_or_set_indexers(key) -> None: if isinstance(key, set) or (isinstance(key, tuple) and any((isinstance(x, set) for x in key))): raise TypeError('Passing a set as an indexer is not supported. Use a list instead.') if isinstance(key, dict) or (isinstance(key, tuple) and any((isinstance(x, dic...
['def', 'check_dict_or_set_indexers(key)', '->', 'None:', 'if', 'isinstance(key,', 'set)', 'or', '(isinstance(key,', 'tuple)', 'and', 'any((isinstance(x,', 'set)', 'for', 'x', 'in', 'key))):', 'raise', "TypeError('Passing", 'a', 'set', 'as', 'an', 'indexer', 'is', 'not', 'supported.', 'Use', 'a', 'list', "instead.')", ...
442,391
weimin17/Object-Detection_HelmetDetection
trainer_lib_test.py
TrainerLibTest.testImmutabilityOfArguments
testImmutabilityOfArguments
Tests that training schedule generation does not change its arguments.
[ "Tests", "that", "training", "schedule", "generation", "does", "not", "change", "its", "arguments." ]
def testImmutabilityOfArguments(self): pretrain_steps = [1, 2, 3] train_steps = [5, 5, 5] trainer_lib.generate_target_per_step_schedule(pretrain_steps, train_steps) self.assertEqual(pretrain_steps, [1, 2, 3]) self.assertEqual(train_steps, [5, 5, 5])
['def', 'testImmutabilityOfArguments(self):', 'pretrain_steps', '=', '[1,', '2,', '3]', 'train_steps', '=', '[5,', '5,', '5]', 'trainer_lib.generate_target_per_step_schedule(pretrain_steps,', 'train_steps)', 'self.assertEqual(pretrain_steps,', '[1,', '2,', '3])', 'self.assertEqual(train_steps,', '[5,', '5,', '5])']
753,506
sktime/sktime
test_series_to_panel_converters.py
test_convert_numpy_series_to_panel
test_convert_numpy_series_to_panel
Test output format of series-to-panel for numpy type input.
[ "Test", "output", "format", "of", "series-to-panel", "for", "numpy", "type", "input." ]
def test_convert_numpy_series_to_panel(): X_series = _make_series(n_columns=2, return_mtype='np.ndarray') (n_time, n_var) = X_series.shape X_panel = convert_Series_to_Panel(X_series) assert isinstance(X_panel, np.ndarray) assert X_panel.ndim == 3 assert X_panel.shape == (1, n_var, n_time)
['def', 'test_convert_numpy_series_to_panel():', 'X_series', '=', '_make_series(n_columns=2,', "return_mtype='np.ndarray')", '(n_time,', 'n_var)', '=', 'X_series.shape', 'X_panel', '=', 'convert_Series_to_Panel(X_series)', 'assert', 'isinstance(X_panel,', 'np.ndarray)', 'assert', 'X_panel.ndim', '==', '3', 'assert', 'X...
886,158
TonyLianLong/VAI-ReinforcementLearning
engine.py
Physics.time
time
Returns episode time in seconds.
[ "Returns", "episode", "time", "in", "seconds." ]
def time(self): return self.data.time
['def', 'time(self):', 'return', 'self.data.time']
440,076
myothida/Supervised-Machine-Learning
test_tightlayout.py
test_tight_layout3
test_tight_layout3
Test tight_layout for multiple subplots.
[ "Test", "tight_layout", "for", "multiple", "subplots." ]
def test_tight_layout3(): ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout()
['def', 'test_tight_layout3():', 'ax1', '=', 'plt.subplot(221)', 'ax2', '=', 'plt.subplot(223)', 'ax3', '=', 'plt.subplot(122)', 'example_plot(ax1)', 'example_plot(ax2)', 'example_plot(ax3)', 'plt.tight_layout()']
362,961
intel/neural-compressor
metric.py
WrapONNXRTMetric.reset
reset
Clear the predictions and labels.
[ "Clear", "the", "predictions", "and", "labels." ]
def reset(self): self._metric_cls.reset()
['def', 'reset(self):', 'self._metric_cls.reset()']
738,548
deepmind/acme
resnet.py
make_downsampling_layer
make_downsampling_layer
Returns a sequence of modules corresponding to the desired downsampling.
[ "Returns", "a", "sequence", "of", "modules", "corresponding", "to", "the", "desired", "downsampling." ]
def make_downsampling_layer(strategy: Union[str, DownsamplingStrategy], output_channels: int) -> hk.SupportsCall: strategy = DownsamplingStrategy(strategy) if strategy is DownsamplingStrategy.AVG_POOL: return hk.AvgPool(window_shape=(3, 3, 1), strides=(2, 2, 1), padding='SAME') elif strategy is Down...
['def', 'make_downsampling_layer(strategy:', 'Union[str,', 'DownsamplingStrategy],', 'output_channels:', 'int)', '->', 'hk.SupportsCall:', 'strategy', '=', 'DownsamplingStrategy(strategy)', 'if', 'strategy', 'is', 'DownsamplingStrategy.AVG_POOL:', 'return', 'hk.AvgPool(window_shape=(3,', '3,', '1),', 'strides=(2,', '2,...
7,837
FriedRonaldo/EditableGAN
compare_ops.py
spectral_norm
spectral_norm
Performs Spectral Normalization on a weight tensor.
[ "Performs", "Spectral", "Normalization", "on", "a", "weight", "tensor." ]
def spectral_norm(input_): if len(input_.shape) < 2: raise ValueError('Spectral norm can only be applied to multi-dimensional tensors') w = tf.reshape(input_, (-1, input_.shape[-1])) u_var = tf.get_variable(input_.name.replace(':', '') + '/u_var', shape=(w.shape[0], 1), dtype=w.dtype, initializer=tf...
['def', 'spectral_norm(input_):', 'if', 'len(input_.shape)', '<', '2:', 'raise', "ValueError('Spectral", 'norm', 'can', 'only', 'be', 'applied', 'to', 'multi-dimensional', "tensors')", 'w', '=', 'tf.reshape(input_,', '(-1,', 'input_.shape[-1]))', 'u_var', '=', "tf.get_variable(input_.name.replace(':',", "'')", '+', "'/...
548,281
FedML-AI/FedML
invert_gradient_attack.py
reconstruction_costs
reconstruction_costs
Input gradient is given data.
[ "Input", "gradient", "is", "given", "data." ]
def reconstruction_costs(gradients, input_gradient, cost_fn='l2', indices='def', weights='equal'): if isinstance(indices, list): pass elif indices == 'def': indices = torch.arange(len(input_gradient)) elif indices == 'top10': (_, indices) = torch.topk(torch.stack([p.norm() for p in i...
['def', 'reconstruction_costs(gradients,', 'input_gradient,', "cost_fn='l2',", "indices='def',", "weights='equal'):", 'if', 'isinstance(indices,', 'list):', 'pass', 'elif', 'indices', '==', "'def':", 'indices', '=', 'torch.arange(len(input_gradient))', 'elif', 'indices', '==', "'top10':", '(_,', 'indices)', '=', 'torch...
545,248
Ruturaj123/Flowchart-Detection
monitors.py
ValidationMonitor.early_stopped
early_stopped
Returns True if this monitor caused an early stop.
[ "Returns", "True", "if", "this", "monitor", "caused", "an", "early", "stop." ]
def early_stopped(self): return self._early_stopped
['def', 'early_stopped(self):', 'return', 'self._early_stopped']
603,807
LiqunChen0606/Triangle-GAN
model_mnist_utils.py
standard_normal
standard_normal
Create a standard Normal StochasticTensor.
[ "Create", "a", "standard", "Normal", "StochasticTensor." ]
def standard_normal(shape, **kwargs): return tf.cast(st.StochasticTensor(ds.MultivariateNormalDiag(mu=tf.zeros(shape), diag_stdev=tf.ones(shape), **kwargs)), tf.float32)
['def', 'standard_normal(shape,', '**kwargs):', 'return', 'tf.cast(st.StochasticTensor(ds.MultivariateNormalDiag(mu=tf.zeros(shape),', 'diag_stdev=tf.ones(shape),', '**kwargs)),', 'tf.float32)']
951,570
IBM/vsrl-framework
expr_helpers.py
fresh_formula_dots
fresh_formula_dots
Generates `num_requested` FormulaDots that do not already occur in `e`.
[ "Generates", "`num_requested`", "FormulaDots", "that", "do", "not", "already", "occur", "in", "`e`." ]
def fresh_formula_dots(e: Expression, num_requested=1) -> List[DotFormula]: dots = all_dots(e) new_dots = [] i = 0 while len(new_dots) != num_requested: while DotFormula(i) in dots: i = i + 1 new_dots.append(DotFormula(i)) i = i + 1 assert len(new_dots) == num_req...
['def', 'fresh_formula_dots(e:', 'Expression,', 'num_requested=1)', '->', 'List[DotFormula]:', 'dots', '=', 'all_dots(e)', 'new_dots', '=', '[]', 'i', '=', '0', 'while', 'len(new_dots)', '!=', 'num_requested:', 'while', 'DotFormula(i)', 'in', 'dots:', 'i', '=', 'i', '+', '1', 'new_dots.append(DotFormula(i))', 'i', '=',...
940,189
aws/sagemaker-python-sdk
session.py
Session.list_feature_groups
list_feature_groups
List all FeatureGroups satisfying given filters.
[ "List", "all", "FeatureGroups", "satisfying", "given", "filters." ]
def list_feature_groups(self, name_contains, feature_group_status_equals, offline_store_status_equals, creation_time_after, creation_time_before, sort_order, sort_by, max_results, next_token) -> Dict[str, Any]: list_feature_groups_args = {} def check_object(key, value): if value is not None: ...
['def', 'list_feature_groups(self,', 'name_contains,', 'feature_group_status_equals,', 'offline_store_status_equals,', 'creation_time_after,', 'creation_time_before,', 'sort_order,', 'sort_by,', 'max_results,', 'next_token)', '->', 'Dict[str,', 'Any]:', 'list_feature_groups_args', '=', '{}', 'def', 'check_object(key,',...
829,663
tensorforce/tensorforce
conjugate_gradient.py
ConjugateGradient.start
start
Initialization step preparing the arguments for the first iteration of the loop body: $x_0, 0, p_0, r_0, r_0^2$.
[ "Initialization", "step", "preparing", "the", "arguments", "for", "the", "first", "iteration", "of", "the", "loop", "body:", "$x_0,", "0,", "p_0,", "r_0,", "r_0^2$." ]
def start(self, *, arguments, x_init, b): fx = self.fn_x(arguments, x_init) subtract = functools.partial(tf_util.lift_indexedslices, tf.math.subtract, with_assertions=self.config.create_tf_assertions) conjugate = residual = b.fmap(function=subtract, zip_values=fx) multiply = functools.partial(tf_util.li...
['def', 'start(self,', '*,', 'arguments,', 'x_init,', 'b):', 'fx', '=', 'self.fn_x(arguments,', 'x_init)', 'subtract', '=', 'functools.partial(tf_util.lift_indexedslices,', 'tf.math.subtract,', 'with_assertions=self.config.create_tf_assertions)', 'conjugate', '=', 'residual', '=', 'b.fmap(function=subtract,', 'zip_valu...
365,814
bachiraoun/fullrmc
GroupSelector.py
RecursiveGroupSelector.lastSelectedIndex
lastSelectedIndex
The last selected group index.
[ "The", "last", "selected", "group", "index." ]
def lastSelectedIndex(self): return self.__lastSelectedIndex
['def', 'lastSelectedIndex(self):', 'return', 'self.__lastSelectedIndex']
213,850
openvinotoolkit/training_extensions
checkpoint_hook.py
CheckpointHookWithValResults.after_train_iter
after_train_iter
Checkpoint stuffs after train iteration.
[ "Checkpoint", "stuffs", "after", "train", "iteration." ]
def after_train_iter(self, runner): if self.by_epoch or not self.every_n_iters(runner, self.interval): return if hasattr(runner, 'save_ckpt'): if runner.save_ckpt: runner.logger.info(f'Saving checkpoint at {runner.iter + 1} iterations') if self.sync_buffer: ...
['def', 'after_train_iter(self,', 'runner):', 'if', 'self.by_epoch', 'or', 'not', 'self.every_n_iters(runner,', 'self.interval):', 'return', 'if', 'hasattr(runner,', "'save_ckpt'):", 'if', 'runner.save_ckpt:', "runner.logger.info(f'Saving", 'checkpoint', 'at', '{runner.iter', '+', '1}', "iterations')", 'if', 'self.sync...
917,797
The-Compiler/pytest-vw
pytest_vw.py
pytest_runtest_makereport
pytest_runtest_makereport
Failing test cases are not a problem anymore.
[ "Failing", "test", "cases", "are", "not", "a", "problem", "anymore." ]
def pytest_runtest_makereport(item): outcome = (yield) rep = outcome.get_result() examinators = EXAMINATORS for examinator in item.config.getini('vw_examinators').split('\n'): examinators.append(examinator.strip()) if any((os.environ.get(gaze, False) for gaze in examinators)): rep.ou...
['def', 'pytest_runtest_makereport(item):', 'outcome', '=', '(yield)', 'rep', '=', 'outcome.get_result()', 'examinators', '=', 'EXAMINATORS', 'for', 'examinator', 'in', "item.config.getini('vw_examinators').split('\\n'):", 'examinators.append(examinator.strip())', 'if', 'any((os.environ.get(gaze,', 'False)', 'for', 'ga...
297,415
microsoft/InnerEye-DeepLearning
test_weight_standardization.py
test_standardize_ones
test_standardize_ones
Smoke test for normalization.
[ "Smoke", "test", "for", "normalization." ]
def test_standardize_ones() -> None: size = (5, 3, 3, 3) weights = torch.ones(size) result = WeightStandardizedConv2d.standardize(weights) assert result.shape == weights.shape assert torch.allclose(result, torch.zeros(size=size))
['def', 'test_standardize_ones()', '->', 'None:', 'size', '=', '(5,', '3,', '3,', '3)', 'weights', '=', 'torch.ones(size)', 'result', '=', 'WeightStandardizedConv2d.standardize(weights)', 'assert', 'result.shape', '==', 'weights.shape', 'assert', 'torch.allclose(result,', 'torch.zeros(size=size))']
613,723
SapienzaNLP/xl-amr
file.py
s3_request
s3_request
Wrapper function for s3 requests in order to create more helpful error messages.
[ "Wrapper", "function", "for", "s3", "requests", "in", "order", "to", "create", "more", "helpful", "error", "messages." ]
def s3_request(func: Callable): @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response['Error']['Code']) == 404: raise FileNotFoundError('file {} not found'.format(url)) ...
['def', 's3_request(func:', 'Callable):', '@wraps(func)', 'def', 'wrapper(url:', 'str,', '*args,', '**kwargs):', 'try:', 'return', 'func(url,', '*args,', '**kwargs)', 'except', 'ClientError', 'as', 'exc:', 'if', "int(exc.response['Error']['Code'])", '==', '404:', 'raise', "FileNotFoundError('file", '{}', 'not', "found'...
968,642
secretflow/secretflow
split_tree_actor.py
SplitTreeActor.do_split_list_wise
do_split_list_wise
record split info and generate next level's left children select.
[ "record", "split", "info", "and", "generate", "next", "level's", "left", "children", "select." ]
def do_split_list_wise(self, split_features: List[Tuple[int, int]], split_points: List[float], left_child_selects: List[np.ndarray], gain_is_cost_effective: List[bool], node_indices: List[int]): lchild_selects = [] for (key, s) in enumerate(split_points): if not gain_is_cost_effective[key]: ...
['def', 'do_split_list_wise(self,', 'split_features:', 'List[Tuple[int,', 'int]],', 'split_points:', 'List[float],', 'left_child_selects:', 'List[np.ndarray],', 'gain_is_cost_effective:', 'List[bool],', 'node_indices:', 'List[int]):', 'lchild_selects', '=', '[]', 'for', '(key,', 's)', 'in', 'enumerate(split_points):', ...
856,499
zhoroh/ObjectDetection
test.py
apply_nms
apply_nms
Apply non-maximum suppression to all predicted boxes output by the test_net method.
[ "Apply", "non-maximum", "suppression", "to", "all", "predicted", "boxes", "output", "by", "the", "test_net", "method." ]
def apply_nms(all_boxes, thresh): num_classes = len(all_boxes) num_images = len(all_boxes[0]) nms_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)] for cls_ind in range(num_classes): for im_ind in range(num_images): dets = np.array(all_boxes[cls_ind][im_ind], dtyp...
['def', 'apply_nms(all_boxes,', 'thresh):', 'num_classes', '=', 'len(all_boxes)', 'num_images', '=', 'len(all_boxes[0])', 'nms_boxes', '=', '[[[]', 'for', '_', 'in', 'range(num_images)]', 'for', '_', 'in', 'range(num_classes)]', 'for', 'cls_ind', 'in', 'range(num_classes):', 'for', 'im_ind', 'in', 'range(num_images):',...
754,976
marcsto/rl
transforms.py
Transform.transform_input_spec
transform_input_spec
Transforms the input spec such that the resulting spec matches transform mapping.
[ "Transforms", "the", "input", "spec", "such", "that", "the", "resulting", "spec", "matches", "transform", "mapping." ]
def transform_input_spec(self, input_spec: TensorSpec) -> TensorSpec: return input_spec
['def', 'transform_input_spec(self,', 'input_spec:', 'TensorSpec)', '->', 'TensorSpec:', 'return', 'input_spec']
859,111
propublica/Capitol-Words
crec_parser.py
CRECParser.title
title
Title of CREC document.
[ "Title", "of", "CREC", "document." ]
def title(self): return self._get_by_xpath(self._xml_tree, 'string(ns:titleInfo/ns:title)')
['def', 'title(self):', 'return', 'self._get_by_xpath(self._xml_tree,', "'string(ns:titleInfo/ns:title)')"]
109,017
PacktPublishing/Hands-On-Artificial--for-Banking
test.py
EnvironBuilder.form
form
A :class:`MultiDict` of form values.
[ "A", ":class:`MultiDict`", "of", "form", "values." ]
def form(self): return self._get_form('_form', MultiDict)
['def', 'form(self):', 'return', "self._get_form('_form',", 'MultiDict)']
204,930
Ori226/p300_lstm
run_multi_subject_experiment.py
prepare_data_for_experiment
prepare_data_for_experiment
prepare the data for the experiment.
[ "prepare", "the", "data", "for", "the", "experiment." ]
def prepare_data_for_experiment(all_subjects, add_time_domain_noise, current_experiment_setting, downsample_params, number_of_k_fold, cross_validation_iter): train_data_all_subject = [] test_data_all_subject = [] train_tags_all_subject = [] test_tags_all_subject = [] test_data_all_subject_with_noise...
['def', 'prepare_data_for_experiment(all_subjects,', 'add_time_domain_noise,', 'current_experiment_setting,', 'downsample_params,', 'number_of_k_fold,', 'cross_validation_iter):', 'train_data_all_subject', '=', '[]', 'test_data_all_subject', '=', '[]', 'train_tags_all_subject', '=', '[]', 'test_tags_all_subject', '=', ...
253,756
rwl/pyreto
rlopf.py
CaseEnvironment.getSensors
getSensors
Returns the currently visible state of the world as a numpy array of doubles.
[ "Returns", "the", "currently", "visible", "state", "of", "the", "world", "as", "a", "numpy", "array", "of", "doubles." ]
def getSensors(self): Pd = array([b.p_demand for b in self.case.buses if b.type == PQ]) logger.info('State: %s' % list(Pd)) return Pd
['def', 'getSensors(self):', 'Pd', '=', 'array([b.p_demand', 'for', 'b', 'in', 'self.case.buses', 'if', 'b.type', '==', 'PQ])', "logger.info('State:", "%s'", '%', 'list(Pd))', 'return', 'Pd']
809,099
vanderschaarlab/mlforhealthlabpub
PBP_net.py
PBP_net.sample_weights
sample_weights
Function that draws a sample from the posterior approximation to the weights distribution.
[ "Function", "that", "draws", "a", "sample", "from", "the", "posterior", "approximation", "to", "the", "weights", "distribution." ]
def sample_weights(self): self.pbp_instance.sample_w()
['def', 'sample_weights(self):', 'self.pbp_instance.sample_w()']
240,041
tensorly/quantum
tfq_ps_util_ops_test.py
PSSymbolReplaceTest.test_error
test_error
Ensure that errors happen with bad inputs.
[ "Ensure", "that", "errors", "happen", "with", "bad", "inputs." ]
def test_error(self): bit = cirq.GridQubit(0, 0) circuit = cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 2)) inputs = util.convert_to_tensor([[circuit]]) symbols = tf.convert_to_tensor(['test']) replacements = tf.convert_to_tensor(['nothing']) with self.assertRaisesRegex(Exception, expect...
['def', 'test_error(self):', 'bit', '=', 'cirq.GridQubit(0,', '0)', 'circuit', '=', 'cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', '2))', 'inputs', '=', 'util.convert_to_tensor([[circuit]])', 'symbols', '=', "tf.convert_to_tensor(['test'])", 'replacements', '=', "tf.convert_to_tensor(['nothing'])", 'w...
834,688
Newbeeer/TRM
grad_fun.py
vjp
vjp
Function that computes the dot product between a vector ``v`` and the Jacobian of the given function at the point given by the inputs.
[ "Function", "that", "computes", "the", "dot", "product", "between", "a", "vector", "``v``", "and", "the", "Jacobian", "of", "the", "given", "function", "at", "the", "point", "given", "by", "the", "inputs." ]
def vjp(func, inputs, v=None, create_graph=False, strict=False): (is_inputs_tuple, inputs) = _as_tuple(inputs, 'inputs', 'vjp') inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True) outputs = func(*inputs) (is_outputs_tuple, outputs) = _as_tuple(outputs, 'outputs of the user-prov...
['def', 'vjp(func,', 'inputs,', 'v=None,', 'create_graph=False,', 'strict=False):', '(is_inputs_tuple,', 'inputs)', '=', '_as_tuple(inputs,', "'inputs',", "'vjp')", 'inputs', '=', '_grad_preprocess(inputs,', 'create_graph=create_graph,', 'need_graph=True)', 'outputs', '=', 'func(*inputs)', '(is_outputs_tuple,', 'output...
951,616