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
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
discretization.py
isemhash_bottleneck
isemhash_bottleneck
Improved semantic hashing bottleneck.
[ "Improved", "semantic", "hashing", "bottleneck." ]
def isemhash_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode, isemhash_noise_dev=0.5, isemhash_mix_prob=0.5): with tf.variable_scope('isemhash_bottleneck'): x = tf.layers.dense(x, bottleneck_bits, name='dense') y = common_layers.saturating_sigmoid(x) if isemhas...
['def', 'isemhash_bottleneck(x,', 'bottleneck_bits,', 'bottleneck_noise,', 'discretize_warmup_steps,', 'mode,', 'isemhash_noise_dev=0.5,', 'isemhash_mix_prob=0.5):', 'with', "tf.variable_scope('isemhash_bottleneck'):", 'x', '=', 'tf.layers.dense(x,', 'bottleneck_bits,', "name='dense')", 'y', '=', 'common_layers.saturat...
965,400
googleapis/python-aiplatform
client.py
ModelServiceClient.list_locations
list_locations
Lists information about the supported locations for this service.
[ "Lists", "information", "about", "the", "supported", "locations", "for", "this", "service." ]
def list_locations(self, request: Optional[locations_pb2.ListLocationsRequest]=None, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Union[float, object]=gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]]=()) -> locations_pb2.ListLocationsResponse: if isinstance(request, dict): request =...
['def', 'list_locations(self,', 'request:', 'Optional[locations_pb2.ListLocationsRequest]=None,', '*,', 'retry:', 'OptionalRetry=gapic_v1.method.DEFAULT,', 'timeout:', 'Union[float,', 'object]=gapic_v1.method.DEFAULT,', 'metadata:', 'Sequence[Tuple[str,', 'str]]=())', '->', 'locations_pb2.ListLocationsResponse:', 'if',...
813,634
awslabs/predictive-maintenance-using--
test__datasource.py
urlopen_stub
urlopen_stub
Stub to replace urlopen for testing.
[ "Stub", "to", "replace", "urlopen", "for", "testing." ]
def urlopen_stub(url, data=None): if url == valid_httpurl(): tmpfile = NamedTemporaryFile(prefix='urltmp_') return tmpfile else: raise URLError('Name or service not known')
['def', 'urlopen_stub(url,', 'data=None):', 'if', 'url', '==', 'valid_httpurl():', 'tmpfile', '=', "NamedTemporaryFile(prefix='urltmp_')", 'return', 'tmpfile', 'else:', 'raise', "URLError('Name", 'or', 'service', 'not', "known')"]
822,725
imironhead/ml_gans
dcgan_lsun.py
generator
generator
build the generator network.
[ "build", "the", "generator", "network." ]
def generator(seed): weights_initializer = tf.truncated_normal_initializer(stddev=0.02) target = tf.contrib.layers.fully_connected(inputs=seed, num_outputs=4 * 4 * 512, activation_fn=tf.nn.relu, weights_initializer=weights_initializer, scope='g_project') target = tf.reshape(target, [-1, 4, 4, 512]) for ...
['def', 'generator(seed):', 'weights_initializer', '=', 'tf.truncated_normal_initializer(stddev=0.02)', 'target', '=', 'tf.contrib.layers.fully_connected(inputs=seed,', 'num_outputs=4', '*', '4', '*', '512,', 'activation_fn=tf.nn.relu,', 'weights_initializer=weights_initializer,', "scope='g_project')", 'target', '=', '...
631,369
instadeepai/jumanji
utils_test.py
test_robot_warehouse_utils__get_agent_view
test_robot_warehouse_utils__get_agent_view
Test extracting the agent's view of other agents and shelves within its receptive field as set via a given sensor range.
[ "Test", "extracting", "the", "agent's", "view", "of", "other", "agents", "and", "shelves", "within", "its", "receptive", "field", "as", "set", "via", "a", "given", "sensor", "range." ]
def test_robot_warehouse_utils__get_agent_view(fake_robot_warehouse_env_state: State) -> None: state = fake_robot_warehouse_env_state grid = jnp.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 0, 0, 0, 3, 4, 0], [0, 5, 6, 0, 0, 0, 0, 7, 8, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]...
['def', 'test_robot_warehouse_utils__get_agent_view(fake_robot_warehouse_env_state:', 'State)', '->', 'None:', 'state', '=', 'fake_robot_warehouse_env_state', 'grid', '=', 'jnp.array([[[0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0,', '0],', '[0,', '1,', '2,', '0,', '0,', '0,', '0,', '3,', '4,', '0],', '[0,', '5,',...
594,504
Z7Gao/CS181-Artificial-Intelligence
inference.py
DiscreteDistribution.argMax
argMax
Return the key with the highest value.
[ "Return", "the", "key", "with", "the", "highest", "value." ]
def argMax(self): if len(self.keys()) == 0: return None all = list(self.items()) values = [x[1] for x in all] maxIndex = values.index(max(values)) return all[maxIndex][0]
['def', 'argMax(self):', 'if', 'len(self.keys())', '==', '0:', 'return', 'None', 'all', '=', 'list(self.items())', 'values', '=', '[x[1]', 'for', 'x', 'in', 'all]', 'maxIndex', '=', 'values.index(max(values))', 'return', 'all[maxIndex][0]']
221,033
intel/neural-compressor
f1.py
f1_score
f1_score
Calculate the F1 score of the prediction and the ground_truth.
[ "Calculate", "the", "F1", "score", "of", "the", "prediction", "and", "the", "ground_truth." ]
def f1_score(prediction: abc.Sequence, ground_truth: abc.Sequence): assert isinstance(prediction, abc.Sequence) and isinstance(ground_truth, abc.Sequence), 'prediction and ground_truth should be Sequence' common = Counter(prediction) & Counter(ground_truth) num_same = sum(common.values()) if num_same ==...
['def', 'f1_score(prediction:', 'abc.Sequence,', 'ground_truth:', 'abc.Sequence):', 'assert', 'isinstance(prediction,', 'abc.Sequence)', 'and', 'isinstance(ground_truth,', 'abc.Sequence),', "'prediction", 'and', 'ground_truth', 'should', 'be', "Sequence'", 'common', '=', 'Counter(prediction)', '&', 'Counter(ground_trut...
738,532
PartnershipOnAI/safelife
safelife_game.py
GameState.revert
revert
Revert to the last saved state.
[ "Revert", "to", "the", "last", "saved", "state." ]
def revert(self): if hasattr(self, '_init_data'): self.deserialize(self._init_data) return True return False
['def', 'revert(self):', 'if', 'hasattr(self,', "'_init_data'):", 'self.deserialize(self._init_data)', 'return', 'True', 'return', 'False']
829,237
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
__init__.py
transformAST
transformAST
Walk the tree and apply the transforms in the config.
[ "Walk", "the", "tree", "and", "apply", "the", "transforms", "in", "the", "config." ]
def transformAST(tree, config): for (selector, call) in config.last('astTransforms', ()): for node in selector.walk(tree): call(node, config)
['def', 'transformAST(tree,', 'config):', 'for', '(selector,', 'call)', 'in', "config.last('astTransforms',", '()):', 'for', 'node', 'in', 'selector.walk(tree):', 'call(node,', 'config)']
17,426
43Carrig/recurrent_neural_networks_practice
core.py
Axis.labels
labels
Returns the tuple containing coordinate labels, else None.
[ "Returns", "the", "tuple", "containing", "coordinate", "labels,", "else", "None." ]
def labels(self): return self._labels
['def', 'labels(self):', 'return', 'self._labels']
313,346
tensorly/quantum
noisy_sampled_expectation_op_test.py
NoisyExpectationCalculationTest.test_correctness_empty
test_correctness_empty
Test the expectation for empty circuits.
[ "Test", "the", "expectation", "for", "empty", "circuits." ]
def test_correctness_empty(self): empty_circuit = util.convert_to_tensor([cirq.Circuit()]) empty_symbols = tf.convert_to_tensor([], dtype=tf.dtypes.string) empty_values = tf.convert_to_tensor([[]]) empty_paulis = tf.convert_to_tensor([[]], dtype=tf.dtypes.string) empty_n_samples = tf.convert_to_tens...
['def', 'test_correctness_empty(self):', 'empty_circuit', '=', 'util.convert_to_tensor([cirq.Circuit()])', 'empty_symbols', '=', 'tf.convert_to_tensor([],', 'dtype=tf.dtypes.string)', 'empty_values', '=', 'tf.convert_to_tensor([[]])', 'empty_paulis', '=', 'tf.convert_to_tensor([[]],', 'dtype=tf.dtypes.string)', 'empty_...
834,857
myothida/Supervised-Machine-Learning
textTools.py
hexStr
hexStr
Convert binary data to a hex string.
[ "Convert", "binary", "data", "to", "a", "hex", "string." ]
def hexStr(data): h = string.hexdigits r = '' for c in data: i = byteord(c) r = r + h[i >> 4 & 15] + h[i & 15] return r
['def', 'hexStr(data):', 'h', '=', 'string.hexdigits', 'r', '=', "''", 'for', 'c', 'in', 'data:', 'i', '=', 'byteord(c)', 'r', '=', 'r', '+', 'h[i', '>>', '4', '&', '15]', '+', 'h[i', '&', '15]', 'return', 'r']
361,009
luojie1024/Computer-vision-Classwork
dictconfig.py
DictConfigurator.configure_root
configure_root
Configure a root logger from a dictionary.
[ "Configure", "a", "root", "logger", "from", "a", "dictionary." ]
def configure_root(self, config, incremental=False): root = logging.getLogger() self.common_logger_config(root, config, incremental)
['def', 'configure_root(self,', 'config,', 'incremental=False):', 'root', '=', 'logging.getLogger()', 'self.common_logger_config(root,', 'config,', 'incremental)']
467,675
deepmind/ai-safety-gridworlds
friend_foe.py
make_game
make_game
Builds and returns Friend or Foe game.
[ "Builds", "and", "returns", "Friend", "or", "Foe", "game." ]
def make_game(environment_data, bandit_type=None, extra_step=False): if 'bandit' not in environment_data: environment_data['bandit'] = dict() environment_data['bandit'][FRIEND] = PolicyEstimator() environment_data['bandit'][NEUTRL] = PolicyEstimator() environment_data['bandit'][ADVER...
['def', 'make_game(environment_data,', 'bandit_type=None,', 'extra_step=False):', 'if', "'bandit'", 'not', 'in', 'environment_data:', "environment_data['bandit']", '=', 'dict()', "environment_data['bandit'][FRIEND]", '=', 'PolicyEstimator()', "environment_data['bandit'][NEUTRL]", '=', 'PolicyEstimator()', "environment_...
412,113
Riashat/Active-Learning-Bayesian-Convolutional--
tensorflow_backend.py
prod
prod
Multiply the values in a tensor, alongside the specified axis.
[ "Multiply", "the", "values", "in", "a", "tensor,", "alongside", "the", "specified", "axis." ]
def prod(x, axis=None, keepdims=False): return tf.reduce_prod(x, reduction_indices=axis, keep_dims=keepdims)
['def', 'prod(x,', 'axis=None,', 'keepdims=False):', 'return', 'tf.reduce_prod(x,', 'reduction_indices=axis,', 'keep_dims=keepdims)']
8,659
fundamentalvision/Auto-Seg-Loss
custom.py
CustomDataset.get_classes_and_palette
get_classes_and_palette
Get class names of current dataset.
[ "Get", "class", "names", "of", "current", "dataset." ]
def get_classes_and_palette(self, classes=None, palette=None): if classes is None: self.custom_classes = False return (self.CLASSES, self.PALETTE) self.custom_classes = True if isinstance(classes, str): class_names = mmcv.list_from_file(classes) elif isinstance(classes, (tuple, l...
['def', 'get_classes_and_palette(self,', 'classes=None,', 'palette=None):', 'if', 'classes', 'is', 'None:', 'self.custom_classes', '=', 'False', 'return', '(self.CLASSES,', 'self.PALETTE)', 'self.custom_classes', '=', 'True', 'if', 'isinstance(classes,', 'str):', 'class_names', '=', 'mmcv.list_from_file(classes)', 'eli...
416,373
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_preprocess.py
preprocess_style_transfer
preprocess_style_transfer
Preprocesses the image and labels for style transfer purposes.
[ "Preprocesses", "the", "image", "and", "labels", "for", "style", "transfer", "purposes." ]
def preprocess_style_transfer(image, labels, augment=False, size=None, is_training=False): image = tf.image.convert_image_dtype(image, tf.float32) if augment and is_training: image = image_augmentation(image) if size: image = resize_image(image, size) image -= 0.5 image *= 2 retu...
['def', 'preprocess_style_transfer(image,', 'labels,', 'augment=False,', 'size=None,', 'is_training=False):', 'image', '=', 'tf.image.convert_image_dtype(image,', 'tf.float32)', 'if', 'augment', 'and', 'is_training:', 'image', '=', 'image_augmentation(image)', 'if', 'size:', 'image', '=', 'resize_image(image,', 'size)'...
54,464
alibaba-mmai-research/HiCo
distributed.py
all_reduce
all_reduce
All reduce the provided tensors from all processes across machines.
[ "All", "reduce", "the", "provided", "tensors", "from", "all", "processes", "across", "machines." ]
def all_reduce(tensors, average=True): for tensor in tensors: dist.all_reduce(tensor, async_op=False) if average: world_size = dist.get_world_size() for tensor in tensors: tensor.mul_(1.0 / world_size) return tensors
['def', 'all_reduce(tensors,', 'average=True):', 'for', 'tensor', 'in', 'tensors:', 'dist.all_reduce(tensor,', 'async_op=False)', 'if', 'average:', 'world_size', '=', 'dist.get_world_size()', 'for', 'tensor', 'in', 'tensors:', 'tensor.mul_(1.0', '/', 'world_size)', 'return', 'tensors']
206,181
nicknochnack/RealTimeSignLanguageTFJS
resnet_v1_beta.py
resnet_arg_scope
resnet_arg_scope
Defines the default ResNet arg scope.
[ "Defines", "the", "default", "ResNet", "arg", "scope." ]
def resnet_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-05, batch_norm_scale=True, activation_fn=tf.nn.relu, use_batch_norm=True, sync_batch_norm_method='None', normalization_method='unspecified', use_weight_standardization=False): batch_norm_params = {'decay': batch_norm_decay, 'eps...
['def', 'resnet_arg_scope(weight_decay=0.0001,', 'batch_norm_decay=0.997,', 'batch_norm_epsilon=1e-05,', 'batch_norm_scale=True,', 'activation_fn=tf.nn.relu,', 'use_batch_norm=True,', "sync_batch_norm_method='None',", "normalization_method='unspecified',", 'use_weight_standardization=False):', 'batch_norm_params', '=',...
851,550
google-research/ssl_detection
common.py
BatchData.aggregate_batch
aggregate_batch
Aggregate a list of datapoints to one batched datapoint.
[ "Aggregate", "a", "list", "of", "datapoints", "to", "one", "batched", "datapoint." ]
def aggregate_batch(data_holder, use_list=False): first_dp = data_holder[0] if isinstance(first_dp, (list, tuple)): result = [] for k in range(len(first_dp)): data_list = [x[k] for x in data_holder] if use_list: result.append(data_list) else: ...
['def', 'aggregate_batch(data_holder,', 'use_list=False):', 'first_dp', '=', 'data_holder[0]', 'if', 'isinstance(first_dp,', '(list,', 'tuple)):', 'result', '=', '[]', 'for', 'k', 'in', 'range(len(first_dp)):', 'data_list', '=', '[x[k]', 'for', 'x', 'in', 'data_holder]', 'if', 'use_list:', 'result.append(data_list)', '...
382,184
yizheh/Chinese_Font_Transfer
distro.py
uname_info
uname_info
Return a dictionary containing key-value pairs for the information items from the distro release file data source of the current OS distribution.
[ "Return", "a", "dictionary", "containing", "key-value", "pairs", "for", "the", "information", "items", "from", "the", "distro", "release", "file", "data", "source", "of", "the", "current", "OS", "distribution." ]
def uname_info(): return _distro.uname_info()
['def', 'uname_info():', 'return', '_distro.uname_info()']
486,653
greydanus/pythonic_ocr
runtime.py
markup_join
markup_join
Concatenation that escapes if necessary and converts to unicode.
[ "Concatenation", "that", "escapes", "if", "necessary", "and", "converts", "to", "unicode." ]
def markup_join(seq): buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
['def', 'markup_join(seq):', 'buf', '=', '[]', 'iterator', '=', 'imap(soft_unicode,', 'seq)', 'for', 'arg', 'in', 'iterator:', 'buf.append(arg)', 'if', 'hasattr(arg,', "'__html__'):", 'return', "Markup(u'').join(chain(buf,", 'iterator))', 'return', 'concat(buf)']
299,352
Eric3911/OpenAGI
window.py
get_window
get_window
Return a window of a given length and type.
[ "Return", "a", "window", "of", "a", "given", "length", "and", "type." ]
def get_window(window: Union[str, Tuple[str, float]], win_length: int, fftbins: bool=True, dtype: str='float64') -> Tensor: sym = not fftbins args = () if isinstance(window, tuple): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, str): ...
['def', 'get_window(window:', 'Union[str,', 'Tuple[str,', 'float]],', 'win_length:', 'int,', 'fftbins:', 'bool=True,', 'dtype:', "str='float64')", '->', 'Tensor:', 'sym', '=', 'not', 'fftbins', 'args', '=', '()', 'if', 'isinstance(window,', 'tuple):', 'winstr', '=', 'window[0]', 'if', 'len(window)', '>', '1:', 'args', ...
250,855
weimin17/Object-Detection_HelmetDetection
vrnn.py
NormalApproximatePosterior.condition
condition
Generates the mean and variance of the normal distribution.
[ "Generates", "the", "mean", "and", "variance", "of", "the", "normal", "distribution." ]
def condition(self, tensor_list, prior_mu): (mu, sigma) = super(NormalApproximatePosterior, self).condition(tensor_list) return (mu + prior_mu, sigma)
['def', 'condition(self,', 'tensor_list,', 'prior_mu):', '(mu,', 'sigma)', '=', 'super(NormalApproximatePosterior,', 'self).condition(tensor_list)', 'return', '(mu', '+', 'prior_mu,', 'sigma)']
750,035
omarmhaimdat/twitter_nlp_native_swift
models.py
PreparedRequest.prepare
prepare
Prepares the entire request with the given parameters.
[ "Prepares", "the", "entire", "request", "with", "the", "given", "parameters." ]
def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) s...
['def', 'prepare(self,', 'method=None,', 'url=None,', 'headers=None,', 'files=None,', 'data=None,', 'params=None,', 'auth=None,', 'cookies=None,', 'hooks=None,', 'json=None):', 'self.prepare_method(method)', 'self.prepare_url(url,', 'params)', 'self.prepare_headers(headers)', 'self.prepare_cookies(cookies)', 'self.prep...
955,032
ludwig-ai/ludwig
base_feature.py
BaseFeatureMixin.get_feature_meta
get_feature_meta
Returns a dictionary of feature metadata.
[ "Returns", "a", "dictionary", "of", "feature", "metadata." ]
def get_feature_meta(column: DataFrame, preprocessing_parameters: PreprocessingConfigDict, backend, is_input_feature: bool) -> FeatureMetadataDict: raise NotImplementedError
['def', 'get_feature_meta(column:', 'DataFrame,', 'preprocessing_parameters:', 'PreprocessingConfigDict,', 'backend,', 'is_input_feature:', 'bool)', '->', 'FeatureMetadataDict:', 'raise', 'NotImplementedError']
616,778
weimin17/Object-Detection_HelmetDetection
estimator_util.py
create_input_fn
create_input_fn
Creates an input_fn that reads a dataset from sharded TFRecord files.
[ "Creates", "an", "input_fn", "that", "reads", "a", "dataset", "from", "sharded", "TFRecord", "files." ]
def create_input_fn(file_pattern, input_config, mode, shuffle_values_buffer=0, repeat=1): include_labels = mode in [tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL] reverse_time_series_prob = 0.5 if mode == tf.estimator.ModeKeys.TRAIN else 0 shuffle_filenames = mode == tf.estimator.ModeKeys.TRAIN ...
['def', 'create_input_fn(file_pattern,', 'input_config,', 'mode,', 'shuffle_values_buffer=0,', 'repeat=1):', 'include_labels', '=', 'mode', 'in', '[tf.estimator.ModeKeys.TRAIN,', 'tf.estimator.ModeKeys.EVAL]', 'reverse_time_series_prob', '=', '0.5', 'if', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN', 'else', '0', 'shuff...
749,080
JinliangLu96/CL_UNMT
transformer.py
BeamHypotheses.is_done
is_done
If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst one in the heap, then we are done with this sentence.
[ "If", "there", "are", "enough", "hypotheses", "and", "that", "none", "of", "the", "hypotheses", "being", "generated", "can", "become", "better", "than", "the", "worst", "one", "in", "the", "heap,", "then", "we", "are", "done", "with", "this", "sentence." ]
def is_done(self, best_sum_logprobs): if len(self) < self.n_hyp: return False elif self.early_stopping: return True else: return self.worst_score >= best_sum_logprobs / self.max_len ** self.length_penalty
['def', 'is_done(self,', 'best_sum_logprobs):', 'if', 'len(self)', '<', 'self.n_hyp:', 'return', 'False', 'elif', 'self.early_stopping:', 'return', 'True', 'else:', 'return', 'self.worst_score', '>=', 'best_sum_logprobs', '/', 'self.max_len', '**', 'self.length_penalty']
123,207
flavioschneider/rl-transfer-
test_tanh_normal_dist.py
TestBenchmarkTanhNormalDistribution.test_tanh_normal_bounds
test_tanh_normal_bounds
Test to make sure the tanh_normal dist obeys the bounds (-1,1).
[ "Test", "to", "make", "sure", "the", "tanh_normal", "dist", "obeys", "the", "bounds", "(-1,1)." ]
def test_tanh_normal_bounds(self): mean = torch.ones(1) * 100 std = torch.ones(1) * 100 dist = TanhNormal(mean, std) assert dist.mean <= 1.0 del dist mean = torch.ones(1) * -100 std = torch.ones(1) * 100 dist = TanhNormal(mean, std) assert dist.mean >= -1.0
['def', 'test_tanh_normal_bounds(self):', 'mean', '=', 'torch.ones(1)', '*', '100', 'std', '=', 'torch.ones(1)', '*', '100', 'dist', '=', 'TanhNormal(mean,', 'std)', 'assert', 'dist.mean', '<=', '1.0', 'del', 'dist', 'mean', '=', 'torch.ones(1)', '*', '-100', 'std', '=', 'torch.ones(1)', '*', '100', 'dist', '=', 'TanhN...
861,835
apeterswu/RL4NMT
common_attention.py
split_heads
split_heads
Split channels (dimension 3) into multiple heads (becomes dimension 1).
[ "Split", "channels", "(dimension", "3)", "into", "multiple", "heads", "(becomes", "dimension", "1)." ]
def split_heads(x, num_heads): return tf.transpose(split_last_dimension(x, num_heads), [0, 2, 1, 3])
['def', 'split_heads(x,', 'num_heads):', 'return', 'tf.transpose(split_last_dimension(x,', 'num_heads),', '[0,', '2,', '1,', '3])']
331,454
weimin17/Object-Detection_HelmetDetection
losses.py
l2_regularizer
l2_regularizer
Define a L2 regularizer.
[ "Define", "a", "L2", "regularizer." ]
def l2_regularizer(weight=1.0, scope=None): def regularizer(tensor): with tf.name_scope(scope, 'L2Regularizer', [tensor]): l2_weight = tf.convert_to_tensor(weight, dtype=tensor.dtype.base_dtype, name='weight') return tf.multiply(l2_weight, tf.nn.l2_loss(tensor), name='value') re...
['def', 'l2_regularizer(weight=1.0,', 'scope=None):', 'def', 'regularizer(tensor):', 'with', 'tf.name_scope(scope,', "'L2Regularizer',", '[tensor]):', 'l2_weight', '=', 'tf.convert_to_tensor(weight,', 'dtype=tensor.dtype.base_dtype,', "name='weight')", 'return', 'tf.multiply(l2_weight,', 'tf.nn.l2_loss(tensor),', "name...
763,168
Farama-Foundation/Gymnasium
jax_to_numpy.py
JaxToNumpyV0.reset
reset
Resets the environment returning numpy-based observation and info.
[ "Resets", "the", "environment", "returning", "numpy-based", "observation", "and", "info." ]
def reset(self, *, seed: int | None=None, options: dict[str, Any] | None=None) -> tuple[WrapperObsType, dict[str, Any]]: if options: options = numpy_to_jax(options) return jax_to_numpy(self.env.reset(seed=seed, options=options))
['def', 'reset(self,', '*,', 'seed:', 'int', '|', 'None=None,', 'options:', 'dict[str,', 'Any]', '|', 'None=None)', '->', 'tuple[WrapperObsType,', 'dict[str,', 'Any]]:', 'if', 'options:', 'options', '=', 'numpy_to_jax(options)', 'return', 'jax_to_numpy(self.env.reset(seed=seed,', 'options=options))']
573,164
triaquae/triaquae
dates.py
MonthMixin.get_previous_month
get_previous_month
Get the previous valid month.
[ "Get", "the", "previous", "valid", "month." ]
def get_previous_month(self, date): return _get_next_prev(self, date, is_previous=True, period='month')
['def', 'get_previous_month(self,', 'date):', 'return', '_get_next_prev(self,', 'date,', 'is_previous=True,', "period='month')"]
424,346
facebookresearch/CompilerGym
env_from_flags.py
connection_settings_from_flags
connection_settings_from_flags
Returns either the name of the benchmark, or a Benchmark message.
[ "Returns", "either", "the", "name", "of", "the", "benchmark,", "or", "a", "Benchmark", "message." ]
def connection_settings_from_flags(service_url: str=None, local_service_binary: Path=None) -> ConnectionOpts: return ConnectionOpts(rpc_call_max_seconds=FLAGS.service_rpc_call_max_seconds, init_max_seconds=FLAGS.service_init_max_seconds, init_max_attempts=FLAGS.service_init_max_attempts, local_service_port_init_max...
['def', 'connection_settings_from_flags(service_url:', 'str=None,', 'local_service_binary:', 'Path=None)', '->', 'ConnectionOpts:', 'return', 'ConnectionOpts(rpc_call_max_seconds=FLAGS.service_rpc_call_max_seconds,', 'init_max_seconds=FLAGS.service_init_max_seconds,', 'init_max_attempts=FLAGS.service_init_max_attempts,...
135,532
intel/neural-compressor
keras.py
KerasModel.get_output_nodes
get_output_nodes
Get model output nodes.
[ "Get", "model", "output", "nodes." ]
def get_output_nodes(self) -> Optional[List[Any]]: return None
['def', 'get_output_nodes(self)', '->', 'Optional[List[Any]]:', 'return', 'None']
721,589
pranjaldatta/PyVision
toymaker.py
Geppetto.render
render
Renders a frame and returns an PIL instance.
[ "Renders", "a", "frame", "and", "returns", "an", "PIL", "instance." ]
def render(self, frame): if frame >= self.frames: raise ValueError('Requested frame {0}, but there are only {1}'.format(frame, self.frames)) canvas = Image.new('RGB', self.size, self.background) for toy in self.toys: toy.render(frame, canvas) return canvas
['def', 'render(self,', 'frame):', 'if', 'frame', '>=', 'self.frames:', 'raise', "ValueError('Requested", 'frame', '{0},', 'but', 'there', 'are', 'only', "{1}'.format(frame,", 'self.frames))', 'canvas', '=', "Image.new('RGB',", 'self.size,', 'self.background)', 'for', 'toy', 'in', 'self.toys:', 'toy.render(frame,', 'ca...
815,953
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
graph_builder_test.py
GraphBuilderTest.testTrainingWithGradientClipping
testTrainingWithGradientClipping
Adds code coverage for gradient clipping.
[ "Adds", "code", "coverage", "for", "gradient", "clipping." ]
def testTrainingWithGradientClipping(self): self.RunTraining(self.MakeHyperparams(gradient_clip_norm=1.25))
['def', 'testTrainingWithGradientClipping(self):', 'self.RunTraining(self.MakeHyperparams(gradient_clip_norm=1.25))']
111,165
Ruturaj123/Flowchart-Detection
predict.py
make_plot
make_plot
Plot a time series in a new figure.
[ "Plot", "a", "time", "series", "in", "a", "new", "figure." ]
def make_plot(name, training_times, observed, all_times, mean, upper_limit, lower_limit): pyplot.figure() pyplot.plot(training_times, observed, 'b', label='training series') pyplot.plot(all_times, mean, 'r', label='forecast') pyplot.plot(all_times, upper_limit, 'g', label='forecast upper bound') pyp...
['def', 'make_plot(name,', 'training_times,', 'observed,', 'all_times,', 'mean,', 'upper_limit,', 'lower_limit):', 'pyplot.figure()', 'pyplot.plot(training_times,', 'observed,', "'b',", "label='training", "series')", 'pyplot.plot(all_times,', 'mean,', "'r',", "label='forecast')", 'pyplot.plot(all_times,', 'upper_limit,...
604,632
gunthercox/ChatterBot
sourcedstring.py
SourcedStringStream.name
name
The name of the underlying stream.
[ "The", "name", "of", "the", "underlying", "stream." ]
def name(self): return self.stream.name
['def', 'name(self):', 'return', 'self.stream.name']
529,920
lixingjian/DELTA
raw_solver.py
RawSolver.postproc_fn
postproc_fn
Post-process function, called after inference.
[ "Post-process", "function,", "called", "after", "inference." ]
def postproc_fn(self): postproc = self.config['solver']['postproc'] if isinstance(postproc, list): postproc_fn = [] for one_postproc in postproc: postproc_fn.append(registers.postprocess[one_postproc['name']](self.config)) else: postproc_fn = registers.postprocess[postpro...
['def', 'postproc_fn(self):', 'postproc', '=', "self.config['solver']['postproc']", 'if', 'isinstance(postproc,', 'list):', 'postproc_fn', '=', '[]', 'for', 'one_postproc', 'in', 'postproc:', "postproc_fn.append(registers.postprocess[one_postproc['name']](self.config))", 'else:', 'postproc_fn', '=', "registers.postproc...
537,714
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
logging.py
IndentingFormatter.get_message_start
get_message_start
Return the start of the formatted log message (not counting the prefix to add to each line).
[ "Return", "the", "start", "of", "the", "formatted", "log", "message", "(not", "counting", "the", "prefix", "to", "add", "to", "each", "line)." ]
def get_message_start(self, formatted, levelno): if levelno < logging.WARNING: return '' if formatted.startswith(DEPRECATION_MSG_PREFIX): return '' if levelno < logging.ERROR: return 'WARNING: ' return 'ERROR: '
['def', 'get_message_start(self,', 'formatted,', 'levelno):', 'if', 'levelno', '<', 'logging.WARNING:', 'return', "''", 'if', 'formatted.startswith(DEPRECATION_MSG_PREFIX):', 'return', "''", 'if', 'levelno', '<', 'logging.ERROR:', 'return', "'WARNING:", "'", 'return', "'ERROR:", "'"]
83,795
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
transform.py
syntaxSafeFloatLiteral
syntaxSafeFloatLiteral
Ensures a Java float literal is a valid Python float literal.
[ "Ensures", "a", "Java", "float", "literal", "is", "a", "valid", "Python", "float", "literal." ]
def syntaxSafeFloatLiteral(node, config): value = node.token.text if value.startswith('.'): value = '0' + value if value.lower().endswith(('f', 'd')): value = value[:-1] elif value.endswith(('l', 'L')): value = value[:-1] + 'L' node.token.text = value
['def', 'syntaxSafeFloatLiteral(node,', 'config):', 'value', '=', 'node.token.text', 'if', "value.startswith('.'):", 'value', '=', "'0'", '+', 'value', 'if', "value.lower().endswith(('f',", "'d')):", 'value', '=', 'value[:-1]', 'elif', "value.endswith(('l',", "'L')):", 'value', '=', 'value[:-1]', '+', "'L'", 'node.toke...
17,643
Kvatsx/Artificial-Intelligence-Assignments
inputtransformer.py
CoroutineInputTransformer.push
push
Send a line of input to the transformer, returning the transformed input or None if the transformer is waiting for more input.
[ "Send", "a", "line", "of", "input", "to", "the", "transformer,", "returning", "the", "transformed", "input", "or", "None", "if", "the", "transformer", "is", "waiting", "for", "more", "input." ]
def push(self, line): return self.coro.send(line)
['def', 'push(self,', 'line):', 'return', 'self.coro.send(line)']
38,043
gatheluck/FourierHeatmap
__init__.py
calc_errors
calc_errors
Calculate top-k errors over output from architecture (model).
[ "Calculate", "top-k", "errors", "over", "output", "from", "architecture", "(model)." ]
def calc_errors(output: torch.Tensor, target: torch.Tensor, topk: Tuple[int, ...]=(1,)) -> List[torch.Tensor]: with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, dim=1) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_a...
['def', 'calc_errors(output:', 'torch.Tensor,', 'target:', 'torch.Tensor,', 'topk:', 'Tuple[int,', '...]=(1,))', '->', 'List[torch.Tensor]:', 'with', 'torch.no_grad():', 'maxk', '=', 'max(topk)', 'batch_size', '=', 'target.size(0)', '(_,', 'pred)', '=', 'output.topk(maxk,', 'dim=1)', 'pred', '=', 'pred.t()', 'correct',...
564,043
sunishsheth2009/ChatterBot
test_ubuntu_corpus_training.py
UbuntuCorpusTrainerTestCase.test_extract
test_extract
Test the extraction of text from a decompressed Ubuntu Corpus file.
[ "Test", "the", "extraction", "of", "text", "from", "a", "decompressed", "Ubuntu", "Corpus", "file." ]
def test_extract(self): file_object_path = self._create_test_corpus(self._get_data()) self.trainer.extract(file_object_path) self._destroy_test_corpus() corpus_path = os.path.join(self.trainer.extracted_data_directory, 'dialogs', '3') self.assertTrue(os.path.exists(self.trainer.extracted_data_direct...
['def', 'test_extract(self):', 'file_object_path', '=', 'self._create_test_corpus(self._get_data())', 'self.trainer.extract(file_object_path)', 'self._destroy_test_corpus()', 'corpus_path', '=', 'os.path.join(self.trainer.extracted_data_directory,', "'dialogs',", "'3')", 'self.assertTrue(os.path.exists(self.trainer.ext...
486,014
myothida/Supervised-Machine-Learning
spines.py
Spine.arc_spine
arc_spine
Create and return an arc `Spine`.
[ "Create", "and", "return", "an", "arc", "`Spine`." ]
def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2, **kwargs): path = mpath.Path.arc(theta1, theta2) result = cls(axes, spine_type, path, **kwargs) result.set_patch_arc(center, radius, theta1, theta2) return result
['def', 'arc_spine(cls,', 'axes,', 'spine_type,', 'center,', 'radius,', 'theta1,', 'theta2,', '**kwargs):', 'path', '=', 'mpath.Path.arc(theta1,', 'theta2)', 'result', '=', 'cls(axes,', 'spine_type,', 'path,', '**kwargs)', 'result.set_patch_arc(center,', 'radius,', 'theta1,', 'theta2)', 'return', 'result']
362,262
AI-ON/Few-Shot-Music-Generation
base_model.py
BaseModel.train
train
Train model on episode.
[ "Train", "model", "on", "episode." ]
def train(self, episode): raise NotImplementedError()
['def', 'train(self,', 'episode):', 'raise', 'NotImplementedError()']
179,925
deepmind/dm_control
reacher.py
Physics.finger_to_target
finger_to_target
Returns the vector from target to finger in global coordinates.
[ "Returns", "the", "vector", "from", "target", "to", "finger", "in", "global", "coordinates." ]
def finger_to_target(self): return self.named.data.geom_xpos['target', :2] - self.named.data.geom_xpos['finger', :2]
['def', 'finger_to_target(self):', 'return', "self.named.data.geom_xpos['target',", ':2]', '-', "self.named.data.geom_xpos['finger',", ':2]']
166,464
aws/sagemaker-python-sdk
_api_types.py
TrialComponentParameters.to_boto
to_boto
Converts TrialComponentParameters to dict.
[ "Converts", "TrialComponentParameters", "to", "dict." ]
def to_boto(cls, parameters): boto_map = {} for (key, value) in parameters.items(): if isinstance(value, numbers.Number): boto_map[key] = {'NumberValue': value} else: boto_map[key] = {'StringValue': str(value)} return boto_map
['def', 'to_boto(cls,', 'parameters):', 'boto_map', '=', '{}', 'for', '(key,', 'value)', 'in', 'parameters.items():', 'if', 'isinstance(value,', 'numbers.Number):', 'boto_map[key]', '=', "{'NumberValue':", 'value}', 'else:', 'boto_map[key]', '=', "{'StringValue':", 'str(value)}', 'return', 'boto_map']
829,973
deepmind/bsuite
bandit_noise.py
load
load
Load a bandit_noise experiment with the prescribed settings.
[ "Load", "a", "bandit_noise", "experiment", "with", "the", "prescribed", "settings." ]
def load(noise_scale, seed, mapping_seed, num_actions=11): env = wrappers.RewardNoise(env=bandit.SimpleBandit(mapping_seed, num_actions=num_actions), noise_scale=noise_scale, seed=seed) env.bsuite_num_episodes = sweep.NUM_EPISODES return env
['def', 'load(noise_scale,', 'seed,', 'mapping_seed,', 'num_actions=11):', 'env', '=', 'wrappers.RewardNoise(env=bandit.SimpleBandit(mapping_seed,', 'num_actions=num_actions),', 'noise_scale=noise_scale,', 'seed=seed)', 'env.bsuite_num_episodes', '=', 'sweep.NUM_EPISODES', 'return', 'env']
410,170
bm777/object_detection
model.py
ObjectDetector.prepare_anchor_data
prepare_anchor_data
Prepare useful anchor data for training.
[ "Prepare", "useful", "anchor", "data", "for", "training." ]
def prepare_anchor_data(self, dataset, show_data=False): print('Labeling the anchors...') t = self.num_anchor_type r = self.num_class anchor_iou_freq = np.zeros((t, 6, 6), np.float32) class_iou_freq = np.zeros((r, 6, 6), np.float32) for i in tqdm(list(range(dataset.count))): img_file = d...
['def', 'prepare_anchor_data(self,', 'dataset,', 'show_data=False):', "print('Labeling", 'the', "anchors...')", 't', '=', 'self.num_anchor_type', 'r', '=', 'self.num_class', 'anchor_iou_freq', '=', 'np.zeros((t,', '6,', '6),', 'np.float32)', 'class_iou_freq', '=', 'np.zeros((r,', '6,', '6),', 'np.float32)', 'for', 'i',...
745,218
bm777/object_detection
config_util_test.py
ConfigUtilTest.testGenericConfigOverride
testGenericConfigOverride
Tests generic config overrides for all top-level configs.
[ "Tests", "generic", "config", "overrides", "for", "all", "top-level", "configs." ]
def testGenericConfigOverride(self): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.model.ssd.num_classes = 1 pipeline_config.train_config.batch_size = 1 pipeline_config.eval_config.num_visualizations = 1 pipeline_config.train_input_reader.label_map_path = '/some/path' ...
['def', 'testGenericConfigOverride(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.model.ssd.num_classes', '=', '1', 'pipeline_config.train_config.batch_size', '=', '1', 'pipeline_config.eval_config.num_visualizations', '=', '1', 'pipeline_config.train_input_reader.label_map_...
792,958
happinesslz/TANet
box_np_ops.py
corners_nd
corners_nd
generate relative box corners based on length per dim and origin point.
[ "generate", "relative", "box", "corners", "based", "on", "length", "per", "dim", "and", "origin", "point." ]
def corners_nd(dims, origin=0.5): ndim = int(dims.shape[1]) corners_norm = np.stack(np.unravel_index(np.arange(2 ** ndim), [2] * ndim), axis=1).astype(dims.dtype) if ndim == 2: corners_norm = corners_norm[[0, 1, 3, 2]] elif ndim == 3: corners_norm = corners_norm[[0, 1, 3, 2, 4, 5, 7, 6]]...
['def', 'corners_nd(dims,', 'origin=0.5):', 'ndim', '=', 'int(dims.shape[1])', 'corners_norm', '=', 'np.stack(np.unravel_index(np.arange(2', '**', 'ndim),', '[2]', '*', 'ndim),', 'axis=1).astype(dims.dtype)', 'if', 'ndim', '==', '2:', 'corners_norm', '=', 'corners_norm[[0,', '1,', '3,', '2]]', 'elif', 'ndim', '==', '3:...
906,883
RasaHQ/rasa
transformers_pre_post_processors.py
camembert_tokens_pre_processor
camembert_tokens_pre_processor
Add camembert style special tokens.
[ "Add", "camembert", "style", "special", "tokens." ]
def camembert_tokens_pre_processor(token_ids: List[int]) -> List[int]: CAMEMBERT_BEG_ID = 5 CAMEMBERT_END_ID = 6 token_ids.insert(0, CAMEMBERT_BEG_ID) token_ids.append(CAMEMBERT_END_ID) return token_ids
['def', 'camembert_tokens_pre_processor(token_ids:', 'List[int])', '->', 'List[int]:', 'CAMEMBERT_BEG_ID', '=', '5', 'CAMEMBERT_END_ID', '=', '6', 'token_ids.insert(0,', 'CAMEMBERT_BEG_ID)', 'token_ids.append(CAMEMBERT_END_ID)', 'return', 'token_ids']
837,364
jwwangchn/NWD
embedding_rpn_head.py
EmbeddingRPNHead.simple_test
simple_test
Forward function in testing stage.
[ "Forward", "function", "in", "testing", "stage." ]
def simple_test(self, img, img_metas): raise NotImplementedError
['def', 'simple_test(self,', 'img,', 'img_metas):', 'raise', 'NotImplementedError']
724,817
PaddlePaddle/Paddle3D
bbox.py
BBoxes2D.horizontal_flip_coords
horizontal_flip_coords
The inputs are floating point coordinates, they are flipped by `(W - x, H - y)`.
[ "The", "inputs", "are", "floating", "point", "coordinates,", "they", "are", "flipped", "by", "`(W", "-", "x,", "H", "-", "y)`." ]
def horizontal_flip_coords(self, image_width: float): (self[:, 0], self[:, 2]) = (image_width - self[:, 2], image_width - self[:, 0])
['def', 'horizontal_flip_coords(self,', 'image_width:', 'float):', '(self[:,', '0],', 'self[:,', '2])', '=', '(image_width', '-', 'self[:,', '2],', 'image_width', '-', 'self[:,', '0])']
777,311
open-mmlab/mmselfsup
analyze_logs.py
cal_train_time
cal_train_time
Compute the average time per training iteration.
[ "Compute", "the", "average", "time", "per", "training", "iteration." ]
def cal_train_time(log_dicts, args): for (i, log_dict) in enumerate(log_dicts): print(f"{'-' * 5}Analyze train time of {args.json_logs[i]}{'-' * 5}") all_times = [] for epoch in log_dict.keys(): if args.include_outliers: all_times.append(log_dict[epoch]['time']) ...
['def', 'cal_train_time(log_dicts,', 'args):', 'for', '(i,', 'log_dict)', 'in', 'enumerate(log_dicts):', 'print(f"{\'-\'', '*', '5}Analyze', 'train', 'time', 'of', "{args.json_logs[i]}{'-'", '*', '5}")', 'all_times', '=', '[]', 'for', 'epoch', 'in', 'log_dict.keys():', 'if', 'args.include_outliers:', "all_times.append(...
240,496
aws/sagemaker-python-sdk
automl.py
AutoMLInput.to_request_dict
to_request_dict
Generates a request dictionary using the parameters provided to the class.
[ "Generates", "a", "request", "dictionary", "using", "the", "parameters", "provided", "to", "the", "class." ]
def to_request_dict(self): auto_ml_input = [] if isinstance(self.inputs, string_types): self.inputs = [self.inputs] if isinstance(self.inputs, PipelineVariable): self.inputs = [self.inputs] for entry in self.inputs: input_entry = {'DataSource': {'S3DataSource': {'S3DataType': 'S3...
['def', 'to_request_dict(self):', 'auto_ml_input', '=', '[]', 'if', 'isinstance(self.inputs,', 'string_types):', 'self.inputs', '=', '[self.inputs]', 'if', 'isinstance(self.inputs,', 'PipelineVariable):', 'self.inputs', '=', '[self.inputs]', 'for', 'entry', 'in', 'self.inputs:', 'input_entry', '=', "{'DataSource':", "{...
829,789
netket/netket
lattice.py
Lattice.pbc
pbc
Array of bools such that `pbc[d]` indicates whether dimension d has periodic boundaries.
[ "Array", "of", "bools", "such", "that", "`pbc[d]`", "indicates", "whether", "dimension", "d", "has", "periodic", "boundaries." ]
def pbc(self): return self._pbc
['def', 'pbc(self):', 'return', 'self._pbc']
736,010
salesforce/CodeRL
modeling_bertabs.py
PenaltyBuilder.length_average
length_average
Returns the average probability of tokens in a sequence.
[ "Returns", "the", "average", "probability", "of", "tokens", "in", "a", "sequence." ]
def length_average(self, beam, logprobs, alpha=0.0): return logprobs / len(beam.next_ys)
['def', 'length_average(self,', 'beam,', 'logprobs,', 'alpha=0.0):', 'return', 'logprobs', '/', 'len(beam.next_ys)']
493,739
enlite-ai/maze
structured_spaces_record.py
StructuredSpacesRecord.actions
actions
List of actions from the individual sub-steps.
[ "List", "of", "actions", "from", "the", "individual", "sub-steps." ]
def actions(self) -> List[Union[ActionType, TorchActionType]]: return [r.action for r in self.substep_records]
['def', 'actions(self)', '->', 'List[Union[ActionType,', 'TorchActionType]]:', 'return', '[r.action', 'for', 'r', 'in', 'self.substep_records]']
646,790
twke18/HSG
resnet_fcn_hsg_cs.py
ResnetFcn.get_params_lr
get_params_lr
Helper function to adjust learning rate for each sub modules.
[ "Helper", "function", "to", "adjust", "learning", "rate", "for", "each", "sub", "modules." ]
def get_params_lr(self): ret = [] resnet_params_name = ['resnet_backbone.conv1', 'resnet_backbone.res2', 'resnet_backbone.res3', 'resnet_backbone.res4', 'resnet_backbone.res5'] ret.append({'params': [n for n in model_utils.get_params(self, resnet_params_name, ['weight'])], 'lr': 1}) ret.append({'params'...
['def', 'get_params_lr(self):', 'ret', '=', '[]', 'resnet_params_name', '=', "['resnet_backbone.conv1',", "'resnet_backbone.res2',", "'resnet_backbone.res3',", "'resnet_backbone.res4',", "'resnet_backbone.res5']", "ret.append({'params':", '[n', 'for', 'n', 'in', 'model_utils.get_params(self,', 'resnet_params_name,', "[...
570,678
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
dataset.py
check_labels_file_header
check_labels_file_header
Validate that filename corresponds to labels for the MNIST dataset.
[ "Validate", "that", "filename", "corresponds", "to", "labels", "for", "the", "MNIST", "dataset." ]
def check_labels_file_header(filename): with tf.gfile.Open(filename, 'rb') as f: magic = read32(f) num_items = read32(f) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST file %s' % (magic, f.name))
['def', 'check_labels_file_header(filename):', 'with', 'tf.gfile.Open(filename,', "'rb')", 'as', 'f:', 'magic', '=', 'read32(f)', 'num_items', '=', 'read32(f)', 'if', 'magic', '!=', '2049:', 'raise', "ValueError('Invalid", 'magic', 'number', '%d', 'in', 'MNIST', 'file', "%s'", '%', '(magic,', 'f.name))']
20,042
huawei-noah/xingtian
adapter.py
TorchAdapter.sampler
sampler
Sampler function which can replace sampler.
[ "Sampler", "function", "which", "can", "replace", "sampler." ]
def sampler(self): return self._sampler
['def', 'sampler(self):', 'return', 'self._sampler']
962,587
AndreaCossu/ContinualLearning_RecurrentNetworks
utils2.py
compute_average_training_accuracy
compute_average_training_accuracy
Return average and std accuracy over all experiences after the last training epoch.
[ "Return", "average", "and", "std", "accuracy", "over", "all", "experiences", "after", "the", "last", "training", "epoch." ]
def compute_average_training_accuracy(folder, training_result_name='training_results.csv'): cur_file = os.path.join(folder, training_result_name) data = read_csv(cur_file) data = data[data['epoch'] == data['epoch'].max()] data = data['val_accuracy'].values acc = np.average(data, axis=0) acc_std ...
['def', 'compute_average_training_accuracy(folder,', "training_result_name='training_results.csv'):", 'cur_file', '=', 'os.path.join(folder,', 'training_result_name)', 'data', '=', 'read_csv(cur_file)', 'data', '=', "data[data['epoch']", '==', "data['epoch'].max()]", 'data', '=', "data['val_accuracy'].values", 'acc', '...
136,541
pipermerriam/flex
test_request_path_validation.py
test_request_validation_with_invalid_request_path
test_request_validation_with_invalid_request_path
Test that request validation detects request paths that are not declared in the schema.
[ "Test", "that", "request", "validation", "detects", "request", "paths", "that", "are", "not", "declared", "in", "the", "schema." ]
def test_request_validation_with_invalid_request_path(): schema = SchemaFactory() assert not schema['paths'] request = RequestFactory(url='http://www.example.com/not-an-api-path') with pytest.raises(ValidationError) as err: validate_request(request=request, schema=schema) assert_message_in_e...
['def', 'test_request_validation_with_invalid_request_path():', 'schema', '=', 'SchemaFactory()', 'assert', 'not', "schema['paths']", 'request', '=', "RequestFactory(url='http://www.example.com/not-an-api-path')", 'with', 'pytest.raises(ValidationError)', 'as', 'err:', 'validate_request(request=request,', 'schema=schem...
211,362
krisroi/us_volume_registration
patch_volume.py
idx2pos
idx2pos
Given a flattened idx, return the position in the 3D image space.
[ "Given", "a", "flattened", "idx,", "return", "the", "position", "in", "the", "3D", "image", "space." ]
def idx2pos(idx, image_size): assert len(image_size) == 3 pos_x = idx / (image_size[1] * image_size[2]) idx_yz = idx % (image_size[1] * image_size[2]) pos_y = idx_yz / image_size[2] pos_z = idx_yz % image_size[2] return torch.LongTensor([pos_x, pos_y, pos_z])
['def', 'idx2pos(idx,', 'image_size):', 'assert', 'len(image_size)', '==', '3', 'pos_x', '=', 'idx', '/', '(image_size[1]', '*', 'image_size[2])', 'idx_yz', '=', 'idx', '%', '(image_size[1]', '*', 'image_size[2])', 'pos_y', '=', 'idx_yz', '/', 'image_size[2]', 'pos_z', '=', 'idx_yz', '%', 'image_size[2]', 'return', 'to...
439,134
weimin17/Object-Detection_HelmetDetection
mst_ops_test.py
MstOpsTest.testLogPartitionFunctionGradientErrorFailsIfInfeasible
testLogPartitionFunctionGradientErrorFailsIfInfeasible
Tests that the partition function gradient fails on infeasible scores.
[ "Tests", "that", "the", "partition", "function", "gradient", "fails", "on", "infeasible", "scores." ]
def testLogPartitionFunctionGradientErrorFailsIfInfeasible(self): with self.test_session(): for forest in [False, True]: pad = 12345.6 scores_raw = [[[0, 1, pad, pad], [1, 0, pad, pad], [pad, pad, pad, pad], [pad, pad, pad, pad]], [[0, 1, 0, pad], [0, 0, 1, pad], [1, 0, 0, pad], [pad...
['def', 'testLogPartitionFunctionGradientErrorFailsIfInfeasible(self):', 'with', 'self.test_session():', 'for', 'forest', 'in', '[False,', 'True]:', 'pad', '=', '12345.6', 'scores_raw', '=', '[[[0,', '1,', 'pad,', 'pad],', '[1,', '0,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad,', 'pad]],'...
760,207
charlesCXK/RGBD_Semantic_Segmentation_PyTorch
fp16_optimizer.py
FP16_Optimizer.zero_grad
zero_grad
Zero fp32 and fp16 parameter grads.
[ "Zero", "fp32", "and", "fp16", "parameter", "grads." ]
def zero_grad(self, set_grads_to_None=False): for group in self.optimizer.param_groups: for p in group['params']: if set_grads_to_None: p.grad = None elif p.grad is not None: p.grad.detach_() p.grad.zero_() for fp16_group in self.fp...
['def', 'zero_grad(self,', 'set_grads_to_None=False):', 'for', 'group', 'in', 'self.optimizer.param_groups:', 'for', 'p', 'in', "group['params']:", 'if', 'set_grads_to_None:', 'p.grad', '=', 'None', 'elif', 'p.grad', 'is', 'not', 'None:', 'p.grad.detach_()', 'p.grad.zero_()', 'for', 'fp16_group', 'in', 'self.fp16_group...
841,261
deepmind/dm_control
index.py
make_struct_indexer
make_struct_indexer
Returns an immutable container exposing named indexers as attributes.
[ "Returns", "an", "immutable", "container", "exposing", "named", "indexers", "as", "attributes." ]
def make_struct_indexer(field_indexers): class StructIndexer: __slots__ = () def _asdict(self): return field_indexers.copy() for (name, indexer) in field_indexers.items(): setattr(StructIndexer, name, indexer) return StructIndexer()
['def', 'make_struct_indexer(field_indexers):', 'class', 'StructIndexer:', '__slots__', '=', '()', 'def', '_asdict(self):', 'return', 'field_indexers.copy()', 'for', '(name,', 'indexer)', 'in', 'field_indexers.items():', 'setattr(StructIndexer,', 'name,', 'indexer)', 'return', 'StructIndexer()']
165,294
wutong8023/CoLL
tokenization_bertweet.py
BertweetTokenizer.add_from_file
add_from_file
Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
[ "Loads", "a", "pre-existing", "dictionary", "from", "a", "text", "file", "and", "adds", "its", "symbols", "to", "this", "instance." ]
def add_from_file(self, f): if isinstance(f, str): try: with open(f, 'r', encoding='utf-8') as fd: self.add_from_file(fd) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'Incorrect encoding detected in {f}...
['def', 'add_from_file(self,', 'f):', 'if', 'isinstance(f,', 'str):', 'try:', 'with', 'open(f,', "'r',", "encoding='utf-8')", 'as', 'fd:', 'self.add_from_file(fd)', 'except', 'FileNotFoundError', 'as', 'fnfe:', 'raise', 'fnfe', 'except', 'UnicodeError:', 'raise', "Exception(f'Incorrect", 'encoding', 'detected', 'in', '...
466,119
rifqind/Agent-Programs-3KS1
testing.py
AsyncHTTPTestCase.get_httpserver_options
get_httpserver_options
May be overridden by subclasses to return additional keyword arguments for the server.
[ "May", "be", "overridden", "by", "subclasses", "to", "return", "additional", "keyword", "arguments", "for", "the", "server." ]
def get_httpserver_options(self) -> Dict[str, Any]: return {}
['def', 'get_httpserver_options(self)', '->', 'Dict[str,', 'Any]:', 'return', '{}']
21,400
AndrewYinLi/lstm-neural-network-spam-filter
test_twitter_auth.py
TestCredentials.test_missingdir
test_missingdir
Setting subdir to nonexistent directory should raise an error.
[ "Setting", "subdir", "to", "nonexistent", "directory", "should", "raise", "an", "error." ]
def test_missingdir(self): try: self.auth.load_creds(subdir='/nosuchdir') except OSError: pass except ValueError: pass except Exception as e: self.fail('Unexpected exception thrown: %s' % e) else: self.fail('OSError exception not thrown.')
['def', 'test_missingdir(self):', 'try:', "self.auth.load_creds(subdir='/nosuchdir')", 'except', 'OSError:', 'pass', 'except', 'ValueError:', 'pass', 'except', 'Exception', 'as', 'e:', "self.fail('Unexpected", 'exception', 'thrown:', "%s'", '%', 'e)', 'else:', "self.fail('OSError", 'exception', 'not', "thrown.')"]
218,523
NoGameNoLife00/mybolg
tbtools.py
Traceback.log
log
Log the ASCII traceback into a file object.
[ "Log", "the", "ASCII", "traceback", "into", "a", "file", "object." ]
def log(self, logfile=None): if logfile is None: logfile = sys.stderr tb = self.plaintext.rstrip() + u'\n' if PY2: tb = tb.encode('utf-8', 'replace') logfile.write(tb)
['def', 'log(self,', 'logfile=None):', 'if', 'logfile', 'is', 'None:', 'logfile', '=', 'sys.stderr', 'tb', '=', 'self.plaintext.rstrip()', '+', "u'\\n'", 'if', 'PY2:', 'tb', '=', "tb.encode('utf-8',", "'replace')", 'logfile.write(tb)']
290,090
pykale/pykale
dataset_access.py
split_by_ratios
split_by_ratios
Randomly split a dataset into non-overlapping new datasets of given ratios.
[ "Randomly", "split", "a", "dataset", "into", "non-overlapping", "new", "datasets", "of", "given", "ratios." ]
def split_by_ratios(dataset, split_ratios): n_total = len(dataset) ratio_sum = sum(split_ratios) if ratio_sum > 1 or ratio_sum <= 0: raise ValueError('The sum of ratios should be in range(0, 1]') elif ratio_sum == 1: split_ratios_ = split_ratios[:-1] else: split_ratios_ = spl...
['def', 'split_by_ratios(dataset,', 'split_ratios):', 'n_total', '=', 'len(dataset)', 'ratio_sum', '=', 'sum(split_ratios)', 'if', 'ratio_sum', '>', '1', 'or', 'ratio_sum', '<=', '0:', 'raise', "ValueError('The", 'sum', 'of', 'ratios', 'should', 'be', 'in', 'range(0,', "1]')", 'elif', 'ratio_sum', '==', '1:', 'split_ra...
819,670
netket/netket
optional_deps.py
import_optional_dependency
import_optional_dependency
Try to import library `name`, and if it cannot be found, raise an informative error.
[ "Try", "to", "import", "library", "`name`,", "and", "if", "it", "cannot", "be", "found,", "raise", "an", "informative", "error." ]
def import_optional_dependency(name: str, minimum_version='', descr='') -> ModuleType: try: return importlib.import_module(name) except ModuleNotFoundError: if minimum_version != '': minimum_version = f'>= {minimum_version}' raise ModuleNotFoundError(f'\n\n Could n...
['def', 'import_optional_dependency(name:', 'str,', "minimum_version='',", "descr='')", '->', 'ModuleType:', 'try:', 'return', 'importlib.import_module(name)', 'except', 'ModuleNotFoundError:', 'if', 'minimum_version', '!=', "'':", 'minimum_version', '=', "f'>=", "{minimum_version}'", 'raise', "ModuleNotFoundError(f'\\...
736,255
dongliangcao/Self-Supervised-Multimodal-Shape-Matching
geodist_metric.py
plot_pck
plot_pck
plot pck curve and compute auc.
[ "plot", "pck", "curve", "and", "compute", "auc." ]
def plot_pck(geo_err, threshold=0.1, steps=40): assert threshold > 0 and steps > 0 geo_err = np.ravel(geo_err) thresholds = np.linspace(0.0, threshold, steps) pcks = [] for i in range(thresholds.shape[0]): thres = thresholds[i] pck = np.mean((geo_err <= thres).astype(float)) ...
['def', 'plot_pck(geo_err,', 'threshold=0.1,', 'steps=40):', 'assert', 'threshold', '>', '0', 'and', 'steps', '>', '0', 'geo_err', '=', 'np.ravel(geo_err)', 'thresholds', '=', 'np.linspace(0.0,', 'threshold,', 'steps)', 'pcks', '=', '[]', 'for', 'i', 'in', 'range(thresholds.shape[0]):', 'thres', '=', 'thresholds[i]', '...
342,109
Farama-Foundation/Gymnasium
text.py
Text.character_list
character_list
Returns a tuple of characters in the space.
[ "Returns", "a", "tuple", "of", "characters", "in", "the", "space." ]
def character_list(self) -> tuple[str, ...]: return self._char_list
['def', 'character_list(self)', '->', 'tuple[str,', '...]:', 'return', 'self._char_list']
573,284
deepmind/acme
dataset_test.py
sample_episode
sample_episode
Returns a sample episode.
[ "Returns", "a", "sample", "episode." ]
def sample_episode() -> rlds.Episode: steps = {rlds.OBSERVATION: [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], rlds.ACTION: [[1], [2], [3], [4], [5]], rlds.REWARD: [1.0, 2.0, 3.0, 4.0, 5.0], rlds.DISCOUNT: [1, 1, 1, 1, 1], rlds.IS_FIRST: [True, False, False, False, False], rlds.IS_LAST: [False, False, False, False, Tru...
['def', 'sample_episode()', '->', 'rlds.Episode:', 'steps', '=', '{rlds.OBSERVATION:', '[[1,', '1],', '[2,', '2],', '[3,', '3],', '[4,', '4],', '[5,', '5]],', 'rlds.ACTION:', '[[1],', '[2],', '[3],', '[4],', '[5]],', 'rlds.REWARD:', '[1.0,', '2.0,', '3.0,', '4.0,', '5.0],', 'rlds.DISCOUNT:', '[1,', '1,', '1,', '1,', '1...
8,112
enuguru/artificial_intelligence_and_machine_
plugins.py
PlusMinusPlugin.do_plusminus
do_plusminus
This filter sorts nodes in a flat group into "required", "optional", and "banned" subgroups based on the presence of plus and minus nodes.
[ "This", "filter", "sorts", "nodes", "in", "a", "flat", "group", "into", "\"required\",", "\"optional\",", "and", "\"banned\"", "subgroups", "based", "on", "the", "presence", "of", "plus", "and", "minus", "nodes." ]
def do_plusminus(self, parser, group): required = syntax.AndGroup() optional = syntax.OrGroup() banned = syntax.OrGroup() if isinstance(group, syntax.AndGroup): optional = syntax.AndGroup() next = optional for node in group: if isinstance(node, self.Plus): next = requ...
['def', 'do_plusminus(self,', 'parser,', 'group):', 'required', '=', 'syntax.AndGroup()', 'optional', '=', 'syntax.OrGroup()', 'banned', '=', 'syntax.OrGroup()', 'if', 'isinstance(group,', 'syntax.AndGroup):', 'optional', '=', 'syntax.AndGroup()', 'next', '=', 'optional', 'for', 'node', 'in', 'group:', 'if', 'isinstanc...
133,554
mfbx9da4/neuron-astrocyte-networks
genotypes.py
Genotype.get_preprogram
get_preprogram
This function returns the prototype program to which the variables will be applied.
[ "This", "function", "returns", "the", "prototype", "program", "to", "which", "the", "variables", "will", "be", "applied." ]
def get_preprogram(self): return self.local_bnf['<S>']
['def', 'get_preprogram(self):', 'return', "self.local_bnf['<S>']"]
722,898
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
logic.py
prop_symbols
prop_symbols
Return a list of all propositional symbols in x.
[ "Return", "a", "list", "of", "all", "propositional", "symbols", "in", "x." ]
def prop_symbols(x): if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set((symbol for arg in x.args for symbol in prop_symbols(arg))))
['def', 'prop_symbols(x):', 'if', 'not', 'isinstance(x,', 'Expr):', 'return', '[]', 'elif', 'is_prop_symbol(x.op):', 'return', '[x]', 'else:', 'return', 'list(set((symbol', 'for', 'arg', 'in', 'x.args', 'for', 'symbol', 'in', 'prop_symbols(arg))))']
428,042
openvinotoolkit/training_extensions
segment_anything.py
SegmentAnything.set_models
set_models
Set models for SAM.
[ "Set", "models", "for", "SAM." ]
def set_models(self) -> None: if 'vit' in self.config.model.backbone: patch_size = 16 self.image_embedding_size = self.config.model.image_size // patch_size else: raise NotImplementedError(f'{self.config.model.backbone} for image encoder of SAM is not implemented yet. Use vit_b, l, or h....
['def', 'set_models(self)', '->', 'None:', 'if', "'vit'", 'in', 'self.config.model.backbone:', 'patch_size', '=', '16', 'self.image_embedding_size', '=', 'self.config.model.image_size', '//', 'patch_size', 'else:', 'raise', "NotImplementedError(f'{self.config.model.backbone}", 'for', 'image', 'encoder', 'of', 'SAM', 'i...
918,360
kianak2002/Sentiment-Emotion-Analysis-project
versioncontrol.py
VersionControl.get_remote_url
get_remote_url
Return the url used at location Raises RemoteNotFoundError if the repository does not have a remote url configured.
[ "Return", "the", "url", "used", "at", "location", "Raises", "RemoteNotFoundError", "if", "the", "repository", "does", "not", "have", "a", "remote", "url", "configured." ]
def get_remote_url(cls, location): raise NotImplementedError
['def', 'get_remote_url(cls,', 'location):', 'raise', 'NotImplementedError']
874,832
wutong8023/CoLL
convert_bart_original_pytorch_checkpoint_to_pytorch.py
convert_bart_checkpoint
convert_bart_checkpoint
Copy/paste/tweak model's weights to our BERT structure.
[ "Copy/paste/tweak", "model's", "weights", "to", "our", "BERT", "structure." ]
def convert_bart_checkpoint(checkpoint_path, pytorch_dump_folder_path, hf_checkpoint_name=None): if not os.path.exists(checkpoint_path): bart = torch.hub.load('pytorch/fairseq', checkpoint_path).eval() else: bart = load_xsum_checkpoint(checkpoint_path) bart.model.upgrade_state_dict(bart.mode...
['def', 'convert_bart_checkpoint(checkpoint_path,', 'pytorch_dump_folder_path,', 'hf_checkpoint_name=None):', 'if', 'not', 'os.path.exists(checkpoint_path):', 'bart', '=', "torch.hub.load('pytorch/fairseq',", 'checkpoint_path).eval()', 'else:', 'bart', '=', 'load_xsum_checkpoint(checkpoint_path)', 'bart.model.upgrade_s...
496,591
FedML-AI/FedML
rdp_analysis.py
compute_rdp
compute_rdp
Computes Renyi Differential Privacy (RDP) guarantees of the Sampled Gaussian Mechanism (SGM) iterated ``steps`` times.
[ "Computes", "Renyi", "Differential", "Privacy", "(RDP)", "guarantees", "of", "the", "Sampled", "Gaussian", "Mechanism", "(SGM)", "iterated", "``steps``", "times." ]
def compute_rdp(*, q: float, noise_multiplier: float, steps: int, orders: Union[List[float], float]) -> Union[List[float], float]: if isinstance(orders, float): rdp = _compute_rdp(q, noise_multiplier, orders) else: rdp = np.array([_compute_rdp(q, noise_multiplier, order) for order in orders]) ...
['def', 'compute_rdp(*,', 'q:', 'float,', 'noise_multiplier:', 'float,', 'steps:', 'int,', 'orders:', 'Union[List[float],', 'float])', '->', 'Union[List[float],', 'float]:', 'if', 'isinstance(orders,', 'float):', 'rdp', '=', '_compute_rdp(q,', 'noise_multiplier,', 'orders)', 'else:', 'rdp', '=', 'np.array([_compute_rdp...
545,232
hemanthmayaluru/Image-Classification-using-CNNs-AlexNet-VGG16-SVM--
Task2and3.py
cal_loss
cal_loss
Calculate cross entropy loss, apply label smoothing if needed.
[ "Calculate", "cross", "entropy", "loss,", "apply", "label", "smoothing", "if", "needed." ]
def cal_loss(pred, gold, smoothing=False): gold = gold.contiguous().view(-1) if smoothing: eps = 0.1 n_class = pred.size(1) one_hot = torch.zeros_like(pred).scatter(1, gold.view(-1, 1), 1) one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1) log_prb = F.log...
['def', 'cal_loss(pred,', 'gold,', 'smoothing=False):', 'gold', '=', 'gold.contiguous().view(-1)', 'if', 'smoothing:', 'eps', '=', '0.1', 'n_class', '=', 'pred.size(1)', 'one_hot', '=', 'torch.zeros_like(pred).scatter(1,', 'gold.view(-1,', '1),', '1)', 'one_hot', '=', 'one_hot', '*', '(1', '-', 'eps)', '+', '(1', '-', ...
599,098
lizoyu/cse511a-2017fall
inference.py
getPositionDistributionForGhost
getPositionDistributionForGhost
Returns the distribution over positions for a ghost, using the supplied gameState.
[ "Returns", "the", "distribution", "over", "positions", "for", "a", "ghost,", "using", "the", "supplied", "gameState." ]
def getPositionDistributionForGhost(gameState, ghostIndex, agent): ghostPosition = gameState.getGhostPosition(ghostIndex + 1) actionDist = agent.getDistribution(gameState) dist = util.Counter() for (action, prob) in actionDist.items(): successorPosition = game.Actions.getSuccessor(ghostPosition,...
['def', 'getPositionDistributionForGhost(gameState,', 'ghostIndex,', 'agent):', 'ghostPosition', '=', 'gameState.getGhostPosition(ghostIndex', '+', '1)', 'actionDist', '=', 'agent.getDistribution(gameState)', 'dist', '=', 'util.Counter()', 'for', '(action,', 'prob)', 'in', 'actionDist.items():', 'successorPosition', '=...
193,460
yihui-he/KL-Loss
c2.py
gauss_fill
gauss_fill
Gaussian fill helper to reduce verbosity.
[ "Gaussian", "fill", "helper", "to", "reduce", "verbosity." ]
def gauss_fill(std): return ('GaussianFill', {'std': std})
['def', 'gauss_fill(std):', 'return', "('GaussianFill',", "{'std':", 'std})']
596,617
myothida/Supervised-Machine-Learning
patheffects.py
SimplePatchShadow.draw_path
draw_path
Overrides the standard draw_path to add the shadow offset and necessary color changes for the shadow.
[ "Overrides", "the", "standard", "draw_path", "to", "add", "the", "shadow", "offset", "and", "necessary", "color", "changes", "for", "the", "shadow." ]
def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) if self._shadow_rgbFace is None: (r, g, b) = (rgbFace or (1.0, 1.0, 1.0))[:3] shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho) else: shadow_rgbFace = self._sha...
['def', 'draw_path(self,', 'renderer,', 'gc,', 'tpath,', 'affine,', 'rgbFace):', 'gc0', '=', 'renderer.new_gc()', 'gc0.copy_properties(gc)', 'if', 'self._shadow_rgbFace', 'is', 'None:', '(r,', 'g,', 'b)', '=', '(rgbFace', 'or', '(1.0,', '1.0,', '1.0))[:3]', 'shadow_rgbFace', '=', '(r', '*', 'self._rho,', 'g', '*', 'sel...
362,175
cristiand391/cs50ai
generate.py
CrosswordCreator.save
save
Save crossword assignment to an image file.
[ "Save", "crossword", "assignment", "to", "an", "image", "file." ]
def save(self, assignment, filename): from PIL import Image, ImageDraw, ImageFont cell_size = 100 cell_border = 2 interior_size = cell_size - 2 * cell_border letters = self.letter_grid(assignment) img = Image.new('RGBA', (self.crossword.width * cell_size, self.crossword.height * cell_size), 'bla...
['def', 'save(self,', 'assignment,', 'filename):', 'from', 'PIL', 'import', 'Image,', 'ImageDraw,', 'ImageFont', 'cell_size', '=', '100', 'cell_border', '=', '2', 'interior_size', '=', 'cell_size', '-', '2', '*', 'cell_border', 'letters', '=', 'self.letter_grid(assignment)', 'img', '=', "Image.new('RGBA',", '(self.cros...
192,742
enuguru/artificial_intelligence_and_machine_learning
io.py
load
load
Loads pickled object in file ``filename``.
[ "Loads", "pickled", "object", "in", "file", "``filename``." ]
def load(filename): f = file(filename, 'rb') y = cPickle.load(f) f.close() return y
['def', 'load(filename):', 'f', '=', 'file(filename,', "'rb')", 'y', '=', 'cPickle.load(f)', 'f.close()', 'return', 'y']
135,317
RasaHQ/rasa
test_common.py
test_cli_log_level_debug_used
test_cli_log_level_debug_used
Test CLI with log level uses for rasa logger whereas libraries stay default.
[ "Test", "CLI", "with", "log", "level", "uses", "for", "rasa", "logger", "whereas", "libraries", "stay", "default." ]
def test_cli_log_level_debug_used(): configure_logging_and_warnings(logging.DEBUG) rasa_logger = logging.getLogger('rasa') assert rasa_logger.level == logging.DEBUG matplotlib_logger = logging.getLogger('matplotlib') assert matplotlib_logger.level == logging.ERROR
['def', 'test_cli_log_level_debug_used():', 'configure_logging_and_warnings(logging.DEBUG)', 'rasa_logger', '=', "logging.getLogger('rasa')", 'assert', 'rasa_logger.level', '==', 'logging.DEBUG', 'matplotlib_logger', '=', "logging.getLogger('matplotlib')", 'assert', 'matplotlib_logger.level', '==', 'logging.ERROR']
838,104
FreshAirTonight/af2complex
confidence.py
predicted_tm_score
predicted_tm_score
Computes predicted TM alignment or predicted interface TM alignment score.
[ "Computes", "predicted", "TM", "alignment", "or", "predicted", "interface", "TM", "alignment", "score." ]
def predicted_tm_score(logits: np.ndarray, breaks: np.ndarray, residue_weights: Optional[np.ndarray]=None, asym_id: Optional[np.ndarray]=None, interface: bool=False) -> np.ndarray: if residue_weights is None: residue_weights = np.ones(logits.shape[0]) bin_centers = _calculate_bin_centers(breaks) num...
['def', 'predicted_tm_score(logits:', 'np.ndarray,', 'breaks:', 'np.ndarray,', 'residue_weights:', 'Optional[np.ndarray]=None,', 'asym_id:', 'Optional[np.ndarray]=None,', 'interface:', 'bool=False)', '->', 'np.ndarray:', 'if', 'residue_weights', 'is', 'None:', 'residue_weights', '=', 'np.ones(logits.shape[0])', 'bin_ce...
400,503
lgalke/aae-recommender
condition.py
ConditionBase.encode_impose
encode_impose
First encodes `condition_input`, then applies condition to `inputs`.
[ "First", "encodes", "`condition_input`,", "then", "applies", "condition", "to", "`inputs`." ]
def encode_impose(self, inputs, condition_input, dim=None): return self.impose(inputs, self.encode(condition_input), dim=None)
['def', 'encode_impose(self,', 'inputs,', 'condition_input,', 'dim=None):', 'return', 'self.impose(inputs,', 'self.encode(condition_input),', 'dim=None)']
405,516
greydanus/pythonic_ocr
utils.py
consume
consume
Consumes an iterable without doing anything with it.
[ "Consumes", "an", "iterable", "without", "doing", "anything", "with", "it." ]
def consume(iterable): for event in iterable: pass
['def', 'consume(iterable):', 'for', 'event', 'in', 'iterable:', 'pass']
299,398
griffin-leonard/mit-6.034-artificial_intelligence
neural_net_api.py
NeuralNet.topological_sort
topological_sort
Returns a list of neurons sorted topologically, with input-layer neurons appearing first, and the output-layer neuron appearing last.
[ "Returns", "a", "list", "of", "neurons", "sorted", "topologically,", "with", "input-layer", "neurons", "appearing", "first,", "and", "the", "output-layer", "neuron", "appearing", "last." ]
def topological_sort(self): def append_earlier_nodes(topo_list, node): if node in topo_list: return topo_list for earlier_node in self.get_incoming_neighbors(node): if earlier_node in self.inputs: continue topo_list = append_earlier_nodes(topo_lis...
['def', 'topological_sort(self):', 'def', 'append_earlier_nodes(topo_list,', 'node):', 'if', 'node', 'in', 'topo_list:', 'return', 'topo_list', 'for', 'earlier_node', 'in', 'self.get_incoming_neighbors(node):', 'if', 'earlier_node', 'in', 'self.inputs:', 'continue', 'topo_list', '=', 'append_earlier_nodes(topo_list,', ...
271,955
shaoshengsong/MobileNetV3-SSD
box_utils.py
assign_priors
assign_priors
Assign ground truth boxes and targets to priors.
[ "Assign", "ground", "truth", "boxes", "and", "targets", "to", "priors." ]
def assign_priors(gt_boxes, gt_labels, corner_form_priors, iou_threshold): ious = iou_of(gt_boxes.unsqueeze(0), corner_form_priors.unsqueeze(1)) (best_target_per_prior, best_target_per_prior_index) = ious.max(1) (best_prior_per_target, best_prior_per_target_index) = ious.max(0) for (target_index, prior_...
['def', 'assign_priors(gt_boxes,', 'gt_labels,', 'corner_form_priors,', 'iou_threshold):', 'ious', '=', 'iou_of(gt_boxes.unsqueeze(0),', 'corner_form_priors.unsqueeze(1))', '(best_target_per_prior,', 'best_target_per_prior_index)', '=', 'ious.max(1)', '(best_prior_per_target,', 'best_prior_per_target_index)', '=', 'iou...
626,334
weimin17/Object-Detection_HelmetDetection
resnet_run_loop.py
learning_rate_with_decay
learning_rate_with_decay
Get a learning rate that decays step-wise as training progresses.
[ "Get", "a", "learning", "rate", "that", "decays", "step-wise", "as", "training", "progresses." ]
def learning_rate_with_decay(batch_size, batch_denom, num_images, boundary_epochs, decay_rates): initial_learning_rate = 0.1 * batch_size / batch_denom batches_per_epoch = num_images / batch_size boundaries = [int(batches_per_epoch * epoch) for epoch in boundary_epochs] vals = [initial_learning_rate * d...
['def', 'learning_rate_with_decay(batch_size,', 'batch_denom,', 'num_images,', 'boundary_epochs,', 'decay_rates):', 'initial_learning_rate', '=', '0.1', '*', 'batch_size', '/', 'batch_denom', 'batches_per_epoch', '=', 'num_images', '/', 'batch_size', 'boundaries', '=', '[int(batches_per_epoch', '*', 'epoch)', 'for', 'e...
748,661
robmarkcole/HASS-Deepstack-
image_processing.py
ObjectClassifyEntity.state
state
Return the state of the entity.
[ "Return", "the", "state", "of", "the", "entity." ]
def state(self): return self._state
['def', 'state(self):', 'return', 'self._state']
588,903