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
rudranil723/mini-main
options.py
ModelAdmin.delete_model
delete_model
Given a model instance delete it from the database.
[ "Given", "a", "model", "instance", "delete", "it", "from", "the", "database." ]
def delete_model(self, request, obj): obj.delete()
['def', 'delete_model(self,', 'request,', 'obj):', 'obj.delete()']
314,775
gugarosa/nalp
text.py
TextDiscriminator.call
call
Method that holds vital information whenever this class is called.
[ "Method", "that", "holds", "vital", "information", "whenever", "this", "class", "is", "called." ]
def call(self, x: tf.Tensor, training: Optional[bool]=True) -> tf.Tensor: x = self.embedding(x) x = tf.expand_dims(x, -1) convs = [tf.squeeze(tf.nn.relu(conv(x)), 2) for conv in self.conv] pools = [pool(conv) for (pool, conv) in zip(self.pool, convs)] x = tf.concat(pools, 2) hw = self.highway(x)...
['def', 'call(self,', 'x:', 'tf.Tensor,', 'training:', 'Optional[bool]=True)', '->', 'tf.Tensor:', 'x', '=', 'self.embedding(x)', 'x', '=', 'tf.expand_dims(x,', '-1)', 'convs', '=', '[tf.squeeze(tf.nn.relu(conv(x)),', '2)', 'for', 'conv', 'in', 'self.conv]', 'pools', '=', '[pool(conv)', 'for', '(pool,', 'conv)', 'in', ...
651,748
MarkYangjiayi/Semantic-Quantization
loss.py
loss
loss
Calculate the loss from the logits and the labels.
[ "Calculate", "the", "loss", "from", "the", "logits", "and", "the", "labels." ]
def loss(logits, labels, num_classes, head=None, ignore_label=0): with tf.name_scope('loss'): loss_weight = 1.0 scaled_labels = tf.reshape(labels, shape=[-1]) not_ignore_mask = tf.to_float(tf.not_equal(scaled_labels, ignore_label)) * loss_weight one_hot_labels = tf.contrib.layers.one...
['def', 'loss(logits,', 'labels,', 'num_classes,', 'head=None,', 'ignore_label=0):', 'with', "tf.name_scope('loss'):", 'loss_weight', '=', '1.0', 'scaled_labels', '=', 'tf.reshape(labels,', 'shape=[-1])', 'not_ignore_mask', '=', 'tf.to_float(tf.not_equal(scaled_labels,', 'ignore_label))', '*', 'loss_weight', 'one_hot_l...
844,049
openvinotoolkit/training_extensions
argument_checks.py
get_bases
get_bases
Function to get set of all base classes of parameter.
[ "Function", "to", "get", "set", "of", "all", "base", "classes", "of", "parameter." ]
def get_bases(parameter) -> set: def __get_bases(parameter_type): return [parameter_type.__name__] + list(itertools.chain.from_iterable((__get_bases(t1) for t1 in parameter_type.__bases__))) return set(__get_bases(type(parameter)))
['def', 'get_bases(parameter)', '->', 'set:', 'def', '__get_bases(parameter_type):', 'return', '[parameter_type.__name__]', '+', 'list(itertools.chain.from_iterable((__get_bases(t1)', 'for', 't1', 'in', 'parameter_type.__bases__)))', 'return', 'set(__get_bases(type(parameter)))']
918,841
matsu0228/nlp-jp
scale.py
LogScale.set_default_locators_and_formatters
set_default_locators_and_formatters
Set the locators and formatters to specialized versions for log scaling.
[ "Set", "the", "locators", "and", "formatters", "to", "specialized", "versions", "for", "log", "scaling." ]
def set_default_locators_and_formatters(self, axis): axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(LogFormatterSciNotation(self.base, labelOnlyBase=self.subs is ...
['def', 'set_default_locators_and_formatters(self,', 'axis):', 'axis.set_major_locator(LogLocator(self.base))', 'axis.set_major_formatter(LogFormatterSciNotation(self.base))', 'axis.set_minor_locator(LogLocator(self.base,', 'self.subs))', 'axis.set_minor_formatter(LogFormatterSciNotation(self.base,', 'labelOnlyBase=sel...
789,188
f-dangel/cockpit
data.py
load_toy_data
load_toy_data
Build a ``DataLoader`` with specified batch size from the toy data.
[ "Build", "a", "``DataLoader``", "with", "specified", "batch", "size", "from", "the", "toy", "data." ]
def load_toy_data(batch_size): return DataLoader(ToyData(), batch_size=batch_size)
['def', 'load_toy_data(batch_size):', 'return', 'DataLoader(ToyData(),', 'batch_size=batch_size)']
492,917
deepmind/meltingpot
boat_race.py
get_config
get_config
Configuration for the boat_race substrate.
[ "Configuration", "for", "the", "boat_race", "substrate." ]
def get_config(): config = configdict.ConfigDict() config.recommended_num_players = MANDATED_NUM_PLAYERS config.action_set = ACTION_SET config.individual_observation_names = ['RGB'] config.global_observation_names = ['WORLD.RGB'] config.action_spec = specs.action(len(ACTION_SET)) config.time...
['def', 'get_config():', 'config', '=', 'configdict.ConfigDict()', 'config.recommended_num_players', '=', 'MANDATED_NUM_PLAYERS', 'config.action_set', '=', 'ACTION_SET', 'config.individual_observation_names', '=', "['RGB']", 'config.global_observation_names', '=', "['WORLD.RGB']", 'config.action_spec', '=', 'specs.acti...
285,640
TobyPDE/FRRN
nnet.py
NeuralNetwork.save_model
save_model
Stores the network parameters in a model file.
[ "Stores", "the", "network", "parameters", "in", "a", "model", "file." ]
def save_model(self, filename): np.savez(filename, *lasagne.layers.get_all_param_values(self.output_layers))
['def', 'save_model(self,', 'filename):', 'np.savez(filename,', '*lasagne.layers.get_all_param_values(self.output_layers))']
564,690
mfbx9da4/neuron-astrocyte-networks
discretesde.py
DiscreteStateDependentExplorer.newEpisode
newEpisode
Inform the explorer about the start of a new episode.
[ "Inform", "the", "explorer", "about", "the", "start", "of", "a", "new", "episode." ]
def newEpisode(self): self.explorerModule = deepcopy(self.module) if isinstance(self.explorerModule, ActionValueNetwork): self.explorerModule.network.mutationStd = 0.01 self.explorerModule.network.mutate() elif isinstance(self.explorerModule, ActionValueTable): self.explorerModule.mu...
['def', 'newEpisode(self):', 'self.explorerModule', '=', 'deepcopy(self.module)', 'if', 'isinstance(self.explorerModule,', 'ActionValueNetwork):', 'self.explorerModule.network.mutationStd', '=', '0.01', 'self.explorerModule.network.mutate()', 'elif', 'isinstance(self.explorerModule,', 'ActionValueTable):', 'self.explor...
722,625
BMW-InnovationLab/BMW-Semantic--Training-GUI
anchor.py
LiteAnchorGenerator.num_depth
num_depth
Number of anchors at each pixel.
[ "Number", "of", "anchors", "at", "each", "pixel." ]
def num_depth(self): if self._index == 0: return len(self._ratios) else: return len(self._sizes) + len(self._ratios) - 1
['def', 'num_depth(self):', 'if', 'self._index', '==', '0:', 'return', 'len(self._ratios)', 'else:', 'return', 'len(self._sizes)', '+', 'len(self._ratios)', '-', '1']
463,598
deepmind/dm_control
physics.py
Physics.is_dirty
is_dirty
Whether this physics' internal state needs to be recalculated.
[ "Whether", "this", "physics'", "internal", "state", "needs", "to", "be", "recalculated." ]
def is_dirty(self): return self._dirty
['def', 'is_dirty(self):', 'return', 'self._dirty']
166,136
zihuitang/medical_AI_platform
ssl.py
SSLObject.compression
compression
Return the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers.
[ "Return", "the", "current", "compression", "algorithm", "in", "use,", "or", "``None``", "if", "compression", "was", "not", "negotiated", "or", "not", "supported", "by", "one", "of", "the", "peers." ]
def compression(self): return self._sslobj.compression()
['def', 'compression(self):', 'return', 'self._sslobj.compression()']
281,457
openai/gym
test_spaces.py
test_space_pickling
test_space_pickling
Tests the spaces can be pickled with the unpickled version being equivalent to the original.
[ "Tests", "the", "spaces", "can", "be", "pickled", "with", "the", "unpickled", "version", "being", "equivalent", "to", "the", "original." ]
def test_space_pickling(space): space.seed(0) pickled_space = pickle.dumps(space) unpickled_space = pickle.loads(pickled_space) assert space == unpickled_space with tempfile.TemporaryFile() as f: pickle.dump(space, f) f.seek(0) file_unpickled_space = pickle.load(f) assert...
['def', 'test_space_pickling(space):', 'space.seed(0)', 'pickled_space', '=', 'pickle.dumps(space)', 'unpickled_space', '=', 'pickle.loads(pickled_space)', 'assert', 'space', '==', 'unpickled_space', 'with', 'tempfile.TemporaryFile()', 'as', 'f:', 'pickle.dump(space,', 'f)', 'f.seek(0)', 'file_unpickled_space', '=', 'p...
234,386
zomux/deepy
trainers.py
GeneralNeuralTrainer.optimization_updates
optimization_updates
Return updates from optimization.
[ "Return", "updates", "from", "optimization." ]
def optimization_updates(self, params, gradients): (updates, free_parameters) = optimize_updates(params, gradients, self.config) self.network.free_parameters.extend(free_parameters) logging.info('Added %d free parameters for optimization' % len(free_parameters)) return updates
['def', 'optimization_updates(self,', 'params,', 'gradients):', '(updates,', 'free_parameters)', '=', 'optimize_updates(params,', 'gradients,', 'self.config)', 'self.network.free_parameters.extend(free_parameters)', "logging.info('Added", '%d', 'free', 'parameters', 'for', "optimization'", '%', 'len(free_parameters))',...
181,013
zhiyong1997/Semantic-Alignment-for-Hierarchical-Image-Captioning
nn_utils.py
dropout
dropout
Apply a dropout layer.
[ "Apply", "a", "dropout", "layer." ]
def dropout(x, keep_prob, is_train): return tf.cond(is_train, lambda : tf.nn.dropout(x, keep_prob), lambda : x)
['def', 'dropout(x,', 'keep_prob,', 'is_train):', 'return', 'tf.cond(is_train,', 'lambda', ':', 'tf.nn.dropout(x,', 'keep_prob),', 'lambda', ':', 'x)']
843,979
akandykeller/NeuralWaveMachines
eval_metric.py
calculate_symetric_score
calculate_symetric_score
Finds minimal polynomial expansion to explain data using Lasso regression, gets the Jacobian of the mapping and calculates how symplectic the map is.
[ "Finds", "minimal", "polynomial", "expansion", "to", "explain", "data", "using", "Lasso", "regression,", "gets", "the", "Jacobian", "of", "the", "mapping", "and", "calculates", "how", "symplectic", "the", "map", "is." ]
def calculate_symetric_score(gt_data, model_data, max_poly_order, max_sym_score, rsq_threshold, sym_threshold, evaluation_point_n, trajectory_n=1, weight_tolerance=1e-05, alpha_sweep=None, max_iter=1000, cv=2): model_data = model_data[..., :gt_data.shape[0], :] print('Finding best polynomial expansion...') ...
['def', 'calculate_symetric_score(gt_data,', 'model_data,', 'max_poly_order,', 'max_sym_score,', 'rsq_threshold,', 'sym_threshold,', 'evaluation_point_n,', 'trajectory_n=1,', 'weight_tolerance=1e-05,', 'alpha_sweep=None,', 'max_iter=1000,', 'cv=2):', 'model_data', '=', 'model_data[...,', ':gt_data.shape[0],', ':]', "pr...
293,518
mfbx9da4/neuron-astrocyte-networks
fitness.py
FitnessList.median
median
This function returns the median fitness value.
[ "This", "function", "returns", "the", "median", "fitness", "value." ]
def median(self): sort_list = self.sorted() length = len(self) half = int(length / 2) if half - length % 2 == 0: return (sort_list[half - 1][0] + sort_list[half][0]) / 2.0 else: return sort_list[half][0]
['def', 'median(self):', 'sort_list', '=', 'self.sorted()', 'length', '=', 'len(self)', 'half', '=', 'int(length', '/', '2)', 'if', 'half', '-', 'length', '%', '2', '==', '0:', 'return', '(sort_list[half', '-', '1][0]', '+', 'sort_list[half][0])', '/', '2.0', 'else:', 'return', 'sort_list[half][0]']
722,870
TrellixVulnTeam/Unsupervised_Learning_HFI7
common.py
setup_autokill
setup_autokill
Timeout based suiciding thread to kill the test runner process If some subprocess dies in an unexpected way we don't want the parent process to block indefinitely.
[ "Timeout", "based", "suiciding", "thread", "to", "kill", "the", "test", "runner", "process", "If", "some", "subprocess", "dies", "in", "an", "unexpected", "way", "we", "don't", "want", "the", "parent", "process", "to", "block", "indefinitely." ]
def setup_autokill(module_name, timeout=30): if 'NO_AUTOKILL' in os.environ or '--pdb' in sys.argv: return teardown_autokill(module_name) def autokill(): pid = os.getpid() print('Timeout exceeded: terminating stalled process: %d' % pid) os.kill(pid, signal.SIGTERM) t...
['def', 'setup_autokill(module_name,', 'timeout=30):', 'if', "'NO_AUTOKILL'", 'in', 'os.environ', 'or', "'--pdb'", 'in', 'sys.argv:', 'return', 'teardown_autokill(module_name)', 'def', 'autokill():', 'pid', '=', 'os.getpid()', "print('Timeout", 'exceeded:', 'terminating', 'stalled', 'process:', "%d'", '%', 'pid)', 'os....
449,656
voxel51/fiftyone
stages.py
MatchLabels.labels
labels
A list of dicts specifying the labels to match.
[ "A", "list", "of", "dicts", "specifying", "the", "labels", "to", "match." ]
def labels(self): return self._labels
['def', 'labels(self):', 'return', 'self._labels']
583,330
BMW-InnovationLab/BMW-Semantic--Training-GUI
plot_history.py
TrainingHistory.update
update
Update the training history Parameters --------- values: list of float List of metric scores for each label.
[ "Update", "the", "training", "history", "Parameters", "---------", "values:", "list", "of", "float", "List", "of", "metric", "scores", "for", "each", "label." ]
def update(self, values): assert len(values) == self.l for (i, v) in enumerate(values): label = self.labels[i] self.history[label].append(v) self.epochs += 1
['def', 'update(self,', 'values):', 'assert', 'len(values)', '==', 'self.l', 'for', '(i,', 'v)', 'in', 'enumerate(values):', 'label', '=', 'self.labels[i]', 'self.history[label].append(v)', 'self.epochs', '+=', '1']
463,026
google-research/scenic
trainer.py
init_from_mtv_checkpoint
init_from_mtv_checkpoint
Initialize train state from a MTV checkpoint.
[ "Initialize", "train", "state", "from", "a", "MTV", "checkpoint." ]
def init_from_mtv_checkpoint(config: ml_collections.ConfigDict, model: model_lib.MTVClassificationModel, train_state: train_utils.TrainState) -> train_utils.TrainState: if config.init_from.get('model_cfg') is None: logging.info('model_cfg is empty. Using current model_cfg.') restored_model_cfg = cop...
['def', 'init_from_mtv_checkpoint(config:', 'ml_collections.ConfigDict,', 'model:', 'model_lib.MTVClassificationModel,', 'train_state:', 'train_utils.TrainState)', '->', 'train_utils.TrainState:', 'if', "config.init_from.get('model_cfg')", 'is', 'None:', "logging.info('model_cfg", 'is', 'empty.', 'Using', 'current', "m...
847,063
google/deepvariant
allele_frequency.py
get_allele_frequency
get_allele_frequency
Gets allele frequency of the index-th alt_base of a Variant proto.
[ "Gets", "allele", "frequency", "of", "the", "index-th", "alt_base", "of", "a", "Variant", "proto." ]
def get_allele_frequency(variant, index): if variant.info.get('AF'): if index < len(variant.info['AF'].values): return variant.info['AF'].values[index].number_value else: raise ValueError('Invalid index', index, 'for the info[AF] field', variant.info['AF'].values) raise V...
['def', 'get_allele_frequency(variant,', 'index):', 'if', "variant.info.get('AF'):", 'if', 'index', '<', "len(variant.info['AF'].values):", 'return', "variant.info['AF'].values[index].number_value", 'else:', 'raise', "ValueError('Invalid", "index',", 'index,', "'for", 'the', 'info[AF]', "field',", "variant.info['AF'].v...
540,230
Farama-Foundation/Gymnasium
play.py
PlayPlot.callback
callback
The callback that calls the provided data callback and adds the data to the plots.
[ "The", "callback", "that", "calls", "the", "provided", "data", "callback", "and", "adds", "the", "data", "to", "the", "plots." ]
def callback(self, obs_t: ObsType, obs_tp1: ObsType, action: ActType, rew: float, terminated: bool, truncated: bool, info: dict): points = self.data_callback(obs_t, obs_tp1, action, rew, terminated, truncated, info) for (point, data_series) in zip(points, self.data): data_series.append(point) self.t...
['def', 'callback(self,', 'obs_t:', 'ObsType,', 'obs_tp1:', 'ObsType,', 'action:', 'ActType,', 'rew:', 'float,', 'terminated:', 'bool,', 'truncated:', 'bool,', 'info:', 'dict):', 'points', '=', 'self.data_callback(obs_t,', 'obs_tp1,', 'action,', 'rew,', 'terminated,', 'truncated,', 'info)', 'for', '(point,', 'data_seri...
573,318
rlworkgroup/garage
maml.py
MAML.train
train
Obtain samples and start training for each epoch.
[ "Obtain", "samples", "and", "start", "training", "for", "each", "epoch." ]
def train(self, trainer): last_return = None for _ in trainer.step_epochs(): (all_samples, all_params) = self._obtain_samples(trainer) last_return = self._train_once(trainer, all_samples, all_params) trainer.step_itr += 1 return last_return
['def', 'train(self,', 'trainer):', 'last_return', '=', 'None', 'for', '_', 'in', 'trainer.step_epochs():', '(all_samples,', 'all_params)', '=', 'self._obtain_samples(trainer)', 'last_return', '=', 'self._train_once(trainer,', 'all_samples,', 'all_params)', 'trainer.step_itr', '+=', '1', 'return', 'last_return']
200,755
Kvatsx/Artificial-Intelligence-Assignments
trait_types.py
datetime_from_json
datetime_from_json
Deserialize a Python datetime object from json.
[ "Deserialize", "a", "Python", "datetime", "object", "from", "json." ]
def datetime_from_json(js, manager): if js is None: return None else: return dt.datetime(js['year'], js['month'] + 1, js['date'], js['hours'], js['minutes'], js['seconds'], js['milliseconds'] * 1000)
['def', 'datetime_from_json(js,', 'manager):', 'if', 'js', 'is', 'None:', 'return', 'None', 'else:', 'return', "dt.datetime(js['year'],", "js['month']", '+', '1,', "js['date'],", "js['hours'],", "js['minutes'],", "js['seconds'],", "js['milliseconds']", '*', '1000)']
38,993
hchasestevens/monkeys
search.py
tournament_select
tournament_select
Perform tournament selection on population of trees, using the specified objective function for comparison, and conducting tournaments of the specified selection size.
[ "Perform", "tournament", "selection", "on", "population", "of", "trees,", "using", "the", "specified", "objective", "function", "for", "comparison,", "and", "conducting", "tournaments", "of", "the", "specified", "selection", "size." ]
def tournament_select(trees, scoring_fn, selection_size, requires_population=False, optimizations=DEFAULT_OPTIMIZATIONS, random_parsimony_prob=0.33, score_callback=None): _scoring_fn = scoring_fn(trees) if requires_population else scoring_fn avg_size = 0 sizes = {} using_covariant_parsimony = Optimizati...
['def', 'tournament_select(trees,', 'scoring_fn,', 'selection_size,', 'requires_population=False,', 'optimizations=DEFAULT_OPTIMIZATIONS,', 'random_parsimony_prob=0.33,', 'score_callback=None):', '_scoring_fn', '=', 'scoring_fn(trees)', 'if', 'requires_population', 'else', 'scoring_fn', 'avg_size', '=', '0', 'sizes', '...
241,110
srai-lab/srai
test_neighbour_dataset.py
test_raises_with_incorrect_sample_k_distance
test_raises_with_incorrect_sample_k_distance
Test if NeighbourDataset checks negative_sample_k_distance correctness.
[ "Test", "if", "NeighbourDataset", "checks", "negative_sample_k_distance", "correctness." ]
def test_raises_with_incorrect_sample_k_distance(negative_sample_k_distance: int, expectation: Any, mocker: 'MockerFixture') -> None: data = pd.DataFrame() neighbourhood = mocker.Mock() with expectation: NeighbourDataset(data, neighbourhood, negative_sample_k_distance=negative_sample_k_distance)
['def', 'test_raises_with_incorrect_sample_k_distance(negative_sample_k_distance:', 'int,', 'expectation:', 'Any,', 'mocker:', "'MockerFixture')", '->', 'None:', 'data', '=', 'pd.DataFrame()', 'neighbourhood', '=', 'mocker.Mock()', 'with', 'expectation:', 'NeighbourDataset(data,', 'neighbourhood,', 'negative_sample_k_d...
371,982
xiaoaleiBLUE/computer_vision
cpp_lint.py
CleansedLines.NumLines
NumLines
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented." ]
def NumLines(self): return self.num_lines
['def', 'NumLines(self):', 'return', 'self.num_lines']
473,559
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
ssl.py
SSLObject.do_handshake
do_handshake
Start the SSL/TLS handshake.
[ "Start", "the", "SSL/TLS", "handshake." ]
def do_handshake(self): self._sslobj.do_handshake() if self.context.check_hostname: if not self.server_hostname: raise ValueError('check_hostname needs server_hostname argument') match_hostname(self.getpeercert(), self.server_hostname)
['def', 'do_handshake(self):', 'self._sslobj.do_handshake()', 'if', 'self.context.check_hostname:', 'if', 'not', 'self.server_hostname:', 'raise', "ValueError('check_hostname", 'needs', 'server_hostname', "argument')", 'match_hostname(self.getpeercert(),', 'self.server_hostname)']
429,548
Vixsec/Feedforward-Neural-Network
fnn.py
d_relu
d_relu
Compute the derivative of RELU given activation (a) or input (x).
[ "Compute", "the", "derivative", "of", "RELU", "given", "activation", "(a)", "or", "input", "(x)." ]
def d_relu(a=None, x=None): if a is not None: d = np.zeros_like(a) d[np.where(a > 0.0)] = 1.0 return d else: return d_relu(a=relu(x))
['def', 'd_relu(a=None,', 'x=None):', 'if', 'a', 'is', 'not', 'None:', 'd', '=', 'np.zeros_like(a)', 'd[np.where(a', '>', '0.0)]', '=', '1.0', 'return', 'd', 'else:', 'return', 'd_relu(a=relu(x))']
582,100
google/balloon-learning-environment
wind_gp.py
WindGP.query_batch
query_batch
Returns the GP's wind prediction for a batch of queries.
[ "Returns", "the", "GP's", "wind", "prediction", "for", "a", "batch", "of", "queries." ]
def query_batch(self, locations: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: if not self.measurement_locations: means = np.zeros((locations.shape[0], 2)) deviations = np.zeros(locations.shape[0]) else: if len(self.measurement_locations) == 1: inputs = np.expand_dims(self.me...
['def', 'query_batch(self,', 'locations:', 'np.ndarray)', '->', 'Tuple[np.ndarray,', 'np.ndarray]:', 'if', 'not', 'self.measurement_locations:', 'means', '=', 'np.zeros((locations.shape[0],', '2))', 'deviations', '=', 'np.zeros(locations.shape[0])', 'else:', 'if', 'len(self.measurement_locations)', '==', '1:', 'inputs'...
422,397
google-research/s4l
labeling_utils.py
create_labels
create_labels
Creates a new set of labels for a single chunk.
[ "Creates", "a", "new", "set", "of", "labels", "for", "a", "single", "chunk." ]
def create_labels(input_tfrecord_path, output_tfrecord_path, dataset_preprocess_fn, embedding_fn, label_fn, write_fn=None, batch_size=64, parallel_calls=1): tf.logging.info('Input: {}\nOutput: {}'.format(input_tfrecord_path, output_tfrecord_path)) if write_fn is None: write_fn = write_imagenet if FL...
['def', 'create_labels(input_tfrecord_path,', 'output_tfrecord_path,', 'dataset_preprocess_fn,', 'embedding_fn,', 'label_fn,', 'write_fn=None,', 'batch_size=64,', 'parallel_calls=1):', "tf.logging.info('Input:", '{}\\nOutput:', "{}'.format(input_tfrecord_path,", 'output_tfrecord_path))', 'if', 'write_fn', 'is', 'None:'...
328,051
cheind/gcsl
mjpy_renderer.py
MjPyRenderer.refresh_window
refresh_window
Refreshes the rendered window if one is present.
[ "Refreshes", "the", "rendered", "window", "if", "one", "is", "present." ]
def refresh_window(self): if self._onscreen_renderer is None: return self._onscreen_renderer.render()
['def', 'refresh_window(self):', 'if', 'self._onscreen_renderer', 'is', 'None:', 'return', 'self._onscreen_renderer.render()']
202,021
enuguru/artificial_intelligence_and_machine_learning
python.py
PythonFileReporter.should_be_python
should_be_python
Does it seem like this file should contain Python? This is used to decide if a file reported as part of the execution of a program was really likely to have contained Python in the first place.
[ "Does", "it", "seem", "like", "this", "file", "should", "contain", "Python?", "This", "is", "used", "to", "decide", "if", "a", "file", "reported", "as", "part", "of", "the", "execution", "of", "a", "program", "was", "really", "likely", "to", "have", "con...
def should_be_python(self): (_, ext) = os.path.splitext(self.filename) if ext.startswith('.py'): return True if not ext: return True return False
['def', 'should_be_python(self):', '(_,', 'ext)', '=', 'os.path.splitext(self.filename)', 'if', "ext.startswith('.py'):", 'return', 'True', 'if', 'not', 'ext:', 'return', 'True', 'return', 'False']
147,897
thaines/helit
document.py
Document.regionSizeVec
regionSizeVec
Returns a vector of the average size of each region, as sampled when sampling the region probabilities.
[ "Returns", "a", "vector", "of", "the", "average", "size", "of", "each", "region,", "as", "sampled", "when", "sampling", "the", "region", "probabilities." ]
def regionSizeVec(self): return self.sizeRegion
['def', 'regionSizeVec(self):', 'return', 'self.sizeRegion']
592,375
Gorilla-Lab-SCUT/frustum-convnet
sunrgbd_utils.py
compute_box_3d_obj_array
compute_box_3d_obj_array
cx, cy, cz, l, w, h, heading_angle Returns: corners_3d: (8,3) array in in upright depth coord.
[ "cx,", "cy,", "cz,", "l,", "w,", "h,", "heading_angle", "Returns:", "corners_3d:", "(8,3)", "array", "in", "in", "upright", "depth", "coord." ]
def compute_box_3d_obj_array(obj_array): (cx, cy, cz, l, w, h, heading_angle) = obj_array center = (cx, cy, cz) R = rotz(-1 * heading_angle) x_corners = [-l, l, l, -l, -l, l, l, -l] y_corners = [w, w, -w, -w, w, w, -w, -w] z_corners = [h, h, h, h, -h, -h, -h, -h] corners_3d = np.dot(R, np.vs...
['def', 'compute_box_3d_obj_array(obj_array):', '(cx,', 'cy,', 'cz,', 'l,', 'w,', 'h,', 'heading_angle)', '=', 'obj_array', 'center', '=', '(cx,', 'cy,', 'cz)', 'R', '=', 'rotz(-1', '*', 'heading_angle)', 'x_corners', '=', '[-l,', 'l,', 'l,', '-l,', '-l,', 'l,', 'l,', '-l]', 'y_corners', '=', '[w,', 'w,', '-w,', '-w,',...
564,873
intel/neural-compressor
utility.py
check_log_exists
check_log_exists
Check whether the log file exists.
[ "Check", "whether", "the", "log", "file", "exists." ]
def check_log_exists(task_id: str, task_log_path): log_path = '{}/task_{}.txt'.format(task_log_path, task_id) if os.path.exists(log_path): return True else: return False
['def', 'check_log_exists(task_id:', 'str,', 'task_log_path):', 'log_path', '=', "'{}/task_{}.txt'.format(task_log_path,", 'task_id)', 'if', 'os.path.exists(log_path):', 'return', 'True', 'else:', 'return', 'False']
721,829
google-research/rigl
mask_factory_test.py
MaskFactoryTest.test_mask_supported
test_mask_supported
Tests supported mask types.
[ "Tests", "supported", "mask", "types." ]
def test_mask_supported(self, mask_type): mask = self._create_mask(mask_type) with self.subTest(name='test_mask_type'): self.assertIsInstance(mask, dict)
['def', 'test_mask_supported(self,', 'mask_type):', 'mask', '=', 'self._create_mask(mask_type)', 'with', "self.subTest(name='test_mask_type'):", 'self.assertIsInstance(mask,', 'dict)']
841,511
devashish-patel/webcam-motion-detector
process.py
Subprocess.uninitialize
uninitialize
Removes the ``SIGCHLD`` handler.
[ "Removes", "the", "``SIGCHLD``", "handler." ]
def uninitialize(cls): if not cls._initialized: return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
['def', 'uninitialize(cls):', 'if', 'not', 'cls._initialized:', 'return', 'signal.signal(signal.SIGCHLD,', 'cls._old_sigchld)', 'cls._initialized', '=', 'False']
985,080
JahJajaka/afternoon_cleaner
model_builder_test.py
ModelBuilderTest.create_default_faster_rcnn_model_proto
create_default_faster_rcnn_model_proto
Creates a DetectionModel proto with FasterRCNN model fields populated.
[ "Creates", "a", "DetectionModel", "proto", "with", "FasterRCNN", "model", "fields", "populated." ]
def create_default_faster_rcnn_model_proto(self): model_text_proto = "\n faster_rcnn {\n inplace_batchnorm_update: false\n num_classes: 3\n image_resizer {\n keep_aspect_ratio_resizer {\n min_dimension: 600\n max_dimension: 1024\n }\n }\n ...
['def', 'create_default_faster_rcnn_model_proto(self):', 'model_text_proto', '=', '"\\n', 'faster_rcnn', '{\\n', 'inplace_batchnorm_update:', 'false\\n', 'num_classes:', '3\\n', 'image_resizer', '{\\n', 'keep_aspect_ratio_resizer', '{\\n', 'min_dimension:', '600\\n', 'max_dimension:', '1024\\n', '}\\n', '}\\n', 'featur...
400,941
AtlantixJJ/LinearGAN
api.py
create_fewshot_LSE
create_fewshot_LSE
Create a LSE model for fewshot learning purpose.
[ "Create", "a", "LSE", "model", "for", "fewshot", "learning", "purpose." ]
def create_fewshot_LSE(G, n_class=36): with torch.no_grad(): (_, features) = sample_image_feature(G) layers = [i for i in range(len(features)) if i % 2 == 1 and features[i].size(3) >= 32] dims = [features[i].size(1) for i in layers] return LSE(n_class=n_class, dims=dims, layers=layers)
['def', 'create_fewshot_LSE(G,', 'n_class=36):', 'with', 'torch.no_grad():', '(_,', 'features)', '=', 'sample_image_feature(G)', 'layers', '=', '[i', 'for', 'i', 'in', 'range(len(features))', 'if', 'i', '%', '2', '==', '1', 'and', 'features[i].size(3)', '>=', '32]', 'dims', '=', '[features[i].size(1)', 'for', 'i', 'in'...
602,539
ryoungj/optdom
query.py
Q.group_map
group_map
Group elements by selector, apply fn to each group, and return a list of the results.
[ "Group", "elements", "by", "selector,", "apply", "fn", "to", "each", "group,", "and", "return", "a", "list", "of", "the", "results." ]
def group_map(self, selector, fn): return self.group(selector).map(fn)
['def', 'group_map(self,', 'selector,', 'fn):', 'return', 'self.group(selector).map(fn)']
253,312
microsoft/InnerEye-DeepLearning
runner.py
Runner.create_ml_runner
create_ml_runner
Create and return an ML runner using the attributes of this Runner object.
[ "Create", "and", "return", "an", "ML", "runner", "using", "the", "attributes", "of", "this", "Runner", "object." ]
def create_ml_runner(self) -> MLRunner: return MLRunner(model_config=self.model_config, container=self.lightning_container, azure_config=self.azure_config, project_root=self.project_root, post_cross_validation_hook=self.post_cross_validation_hook, model_deployment_hook=self.model_deployment_hook)
['def', 'create_ml_runner(self)', '->', 'MLRunner:', 'return', 'MLRunner(model_config=self.model_config,', 'container=self.lightning_container,', 'azure_config=self.azure_config,', 'project_root=self.project_root,', 'post_cross_validation_hook=self.post_cross_validation_hook,', 'model_deployment_hook=self.model_deploym...
613,055
rwth-i6/returnn
meta.py
MetaDataset.finish_epoch
finish_epoch
This would get called at the end of the epoch.
[ "This", "would", "get", "called", "at", "the", "end", "of", "the", "epoch." ]
def finish_epoch(self): super(MetaDataset, self).finish_epoch() for (_, dataset) in self.datasets.items(): assert isinstance(dataset, Dataset) dataset.finish_epoch()
['def', 'finish_epoch(self):', 'super(MetaDataset,', 'self).finish_epoch()', 'for', '(_,', 'dataset)', 'in', 'self.datasets.items():', 'assert', 'isinstance(dataset,', 'Dataset)', 'dataset.finish_epoch()']
346,540
deepmind/dm_control
fruitfly_v2.py
FruitFlyObservables.orientation
orientation
Return orientation of world z-axis in local frame.
[ "Return", "orientation", "of", "world", "z-axis", "in", "local", "frame." ]
def orientation(self): return [self.world_zaxis, self.world_zaxis_abdomen, self.world_zaxis_head]
['def', 'orientation(self):', 'return', '[self.world_zaxis,', 'self.world_zaxis_abdomen,', 'self.world_zaxis_head]']
166,020
xavialex/Streamlit-TF-Real-Time-Object-
model_lib.py
create_estimator_and_inputs
create_estimator_and_inputs
Creates `Estimator`, input functions, and steps.
[ "Creates", "`Estimator`,", "input", "functions,", "and", "steps." ]
def create_estimator_and_inputs(run_config, hparams, pipeline_config_path, config_override=None, train_steps=None, sample_1_of_n_eval_examples=1, sample_1_of_n_eval_on_train_examples=1, model_fn_creator=create_model_fn, use_tpu_estimator=False, use_tpu=False, num_shards=1, params=None, override_eval_num_epochs=True, sa...
['def', 'create_estimator_and_inputs(run_config,', 'hparams,', 'pipeline_config_path,', 'config_override=None,', 'train_steps=None,', 'sample_1_of_n_eval_examples=1,', 'sample_1_of_n_eval_on_train_examples=1,', 'model_fn_creator=create_model_fn,', 'use_tpu_estimator=False,', 'use_tpu=False,', 'num_shards=1,', 'params=N...
909,388
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Text.peer_names
peer_names
Returns a list of peers of this widget (this does not include the widget itself).
[ "Returns", "a", "list", "of", "peers", "of", "this", "widget", "(this", "does", "not", "include", "the", "widget", "itself)." ]
def peer_names(self): return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
['def', 'peer_names(self):', 'return', 'self.tk.splitlist(self.tk.call(self._w,', "'peer',", "'names'))"]
377,070
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
glow_ops.py
squeeze
squeeze
Block-wise spatial squeezing of x to increase the number of channels.
[ "Block-wise", "spatial", "squeezing", "of", "x", "to", "increase", "the", "number", "of", "channels." ]
def squeeze(name, x, factor=2, reverse=True): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): shape = common_layers.shape_list(x) if factor == 1: return x height = int(shape[1]) width = int(shape[2]) n_channels = int(shape[3]) if not reverse: ...
['def', 'squeeze(name,', 'x,', 'factor=2,', 'reverse=True):', 'with', 'tf.variable_scope(name,', 'reuse=tf.AUTO_REUSE):', 'shape', '=', 'common_layers.shape_list(x)', 'if', 'factor', '==', '1:', 'return', 'x', 'height', '=', 'int(shape[1])', 'width', '=', 'int(shape[2])', 'n_channels', '=', 'int(shape[3])', 'if', 'not'...
965,821
43Carrig/recurrent_neural_networks_practice
batch_ops_test.py
BatchOpsTest.testBasicUnbatch
testBasicUnbatch
Tests that batch and unbatch work together.
[ "Tests", "that", "batch", "and", "unbatch", "work", "together." ]
def testBasicUnbatch(self): with self.test_session() as sess: inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1]) (batched, index, id_t) = batch_ops.batch([inp], num_batch_threads=1, max_batch_size=10, batch_timeout_micros=100000, allowed_batch_sizes=[3, 10], grad_timeout_micros=0, batching_q...
['def', 'testBasicUnbatch(self):', 'with', 'self.test_session()', 'as', 'sess:', 'inp', '=', 'array_ops.placeholder(dtype=dtypes.int32,', 'shape=[1])', '(batched,', 'index,', 'id_t)', '=', 'batch_ops.batch([inp],', 'num_batch_threads=1,', 'max_batch_size=10,', 'batch_timeout_micros=100000,', 'allowed_batch_sizes=[3,', ...
312,455
ryu-ed/SpaceInvaders_Ros
python3.py
Python3Checker.visit_raise
visit_raise
Visit a raise statement and check for raising strings or old-raise-syntax.
[ "Visit", "a", "raise", "statement", "and", "check", "for", "raising", "strings", "or", "old-raise-syntax." ]
def visit_raise(self, node): if node.exc is None: return expr = node.exc if self._check_raise_value(node, expr): return try: value = next(astroid.unpack_infer(expr)) except astroid.InferenceError: return self._check_raise_value(node, value)
['def', 'visit_raise(self,', 'node):', 'if', 'node.exc', 'is', 'None:', 'return', 'expr', '=', 'node.exc', 'if', 'self._check_raise_value(node,', 'expr):', 'return', 'try:', 'value', '=', 'next(astroid.unpack_infer(expr))', 'except', 'astroid.InferenceError:', 'return', 'self._check_raise_value(node,', 'value)']
369,956
intel/neural-compressor
utils.py
process_yaml_config
process_yaml_config
Process the yaml configuration file.
[ "Process", "the", "yaml", "configuration", "file." ]
def process_yaml_config(global_config, local_configs, default_config): pruners_info = [] default_all = global_config for key in default_config.keys(): default_all[key] = reset_none_to_default(default_all, key, default_config[key]) if len(local_configs) == 0: update_params(default_all) ...
['def', 'process_yaml_config(global_config,', 'local_configs,', 'default_config):', 'pruners_info', '=', '[]', 'default_all', '=', 'global_config', 'for', 'key', 'in', 'default_config.keys():', 'default_all[key]', '=', 'reset_none_to_default(default_all,', 'key,', 'default_config[key])', 'if', 'len(local_configs)', '==...
738,073
rudranil723/mini-main
pycodestyle.py
BaseReport.increment_logical_line
increment_logical_line
Signal a new logical line.
[ "Signal", "a", "new", "logical", "line." ]
def increment_logical_line(self): self.counters['logical lines'] += 1
['def', 'increment_logical_line(self):', "self.counters['logical", "lines']", '+=', '1']
314,023
cpnota/autonomous-learning-library
state.py
MultiagentState.from_zoo
from_zoo
Constructs a State object given the return value of an OpenAI gym reset()/step(action) call.
[ "Constructs", "a", "State", "object", "given", "the", "return", "value", "of", "an", "OpenAI", "gym", "reset()/step(action)", "call." ]
def from_zoo(cls, agent, state, device='cpu', dtype=np.float32): if not isinstance(state, tuple): return MultiagentState({'agent': agent, 'observation': torch.from_numpy(np.array(state, dtype=dtype)).to(device)}, device=device) (observation, reward, done, info) = state observation = torch.from_numpy...
['def', 'from_zoo(cls,', 'agent,', 'state,', "device='cpu',", 'dtype=np.float32):', 'if', 'not', 'isinstance(state,', 'tuple):', 'return', "MultiagentState({'agent':", 'agent,', "'observation':", 'torch.from_numpy(np.array(state,', 'dtype=dtype)).to(device)},', 'device=device)', '(observation,', 'reward,', 'done,', 'in...
93,572
NJU-LHRS/official-CMID
optimizer_hook.py
patch_norm_fp32
patch_norm_fp32
Recursively convert normalization layers from FP16 to FP32.
[ "Recursively", "convert", "normalization", "layers", "from", "FP16", "to", "FP32." ]
def patch_norm_fp32(module): if isinstance(module, (nn.modules.batchnorm._BatchNorm, nn.GroupNorm)): module.float() for child in module.children(): patch_norm_fp32(child) return module
['def', 'patch_norm_fp32(module):', 'if', 'isinstance(module,', '(nn.modules.batchnorm._BatchNorm,', 'nn.GroupNorm)):', 'module.float()', 'for', 'child', 'in', 'module.children():', 'patch_norm_fp32(child)', 'return', 'module']
250,171
Gradiant/pyodi
train_config_evaluation.py
train_config_evaluation
train_config_evaluation
Evaluates the fitness between `ground_truth_file` and `anchor_config_file`.
[ "Evaluates", "the", "fitness", "between", "`ground_truth_file`", "and", "`anchor_config_file`." ]
def train_config_evaluation(ground_truth_file: Union[str, pd.DataFrame], anchor_config: str, input_size: Tuple[int, int]=(1280, 720), show: bool=True, output: Optional[str]=None, output_size: Tuple[int, int]=(1600, 900), keep_ratio: bool=False) -> None: if output is not None: Path(output).mkdir(parents=True...
['def', 'train_config_evaluation(ground_truth_file:', 'Union[str,', 'pd.DataFrame],', 'anchor_config:', 'str,', 'input_size:', 'Tuple[int,', 'int]=(1280,', '720),', 'show:', 'bool=True,', 'output:', 'Optional[str]=None,', 'output_size:', 'Tuple[int,', 'int]=(1600,', '900),', 'keep_ratio:', 'bool=False)', '->', 'None:',...
820,838
YanZiQinKevin/object_detection
test.py
im_detect_keypoints_aspect_ratio
im_detect_keypoints_aspect_ratio
Detects keypoints at the given width-relative aspect ratio.
[ "Detects", "keypoints", "at", "the", "given", "width-relative", "aspect", "ratio." ]
def im_detect_keypoints_aspect_ratio(model, im, aspect_ratio, boxes, hflip=False): im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio) boxes_ar = box_utils.aspect_ratio(boxes, aspect_ratio) if hflip: heatmaps_ar = im_detect_keypoints_hflip(model, im_ar, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes_ar...
['def', 'im_detect_keypoints_aspect_ratio(model,', 'im,', 'aspect_ratio,', 'boxes,', 'hflip=False):', 'im_ar', '=', 'image_utils.aspect_ratio_rel(im,', 'aspect_ratio)', 'boxes_ar', '=', 'box_utils.aspect_ratio(boxes,', 'aspect_ratio)', 'if', 'hflip:', 'heatmaps_ar', '=', 'im_detect_keypoints_hflip(model,', 'im_ar,', 'c...
772,279
Eric3911/OpenAGI
data_simulation_utils.py
DataAnnotator.create_new_json_entry
create_new_json_entry
Create new JSON entries (to write to output json file).
[ "Create", "new", "JSON", "entries", "(to", "write", "to", "output", "json", "file)." ]
def create_new_json_entry(self, text: List[str], wav_filename: str, start: float, length: float, speaker_id: int, rttm_filepath: str, ctm_filepath: str) -> dict: start = round(float(start), self._params.data_simulator.outputs.output_precision) length = round(float(length), self._params.data_simulator.outputs.ou...
['def', 'create_new_json_entry(self,', 'text:', 'List[str],', 'wav_filename:', 'str,', 'start:', 'float,', 'length:', 'float,', 'speaker_id:', 'int,', 'rttm_filepath:', 'str,', 'ctm_filepath:', 'str)', '->', 'dict:', 'start', '=', 'round(float(start),', 'self._params.data_simulator.outputs.output_precision)', 'length',...
272,857
uber-archive/focuson
test.py
TestAcrossFilesDataflow.test3_file_and_classes
test3_file_and_classes
A more complex test across 3 files and a few classes This is a pretty robust test, see code for full details.
[ "A", "more", "complex", "test", "across", "3", "files", "and", "a", "few", "classes", "This", "is", "a", "pretty", "robust", "test,", "see", "code", "for", "full", "details." ]
def test3_file_and_classes(self): target_dir = os.getcwd() + os.sep + 'across_files_dflow2' self.engine.ingest(target_dir) self.engine.process_funcs() self.engine.main_analysis() self.assertTrue(len(self.engine.issues_found) == 1) self.assertEqual(self.engine.issues_found[0].cf.name, 'lib.lib_tw...
['def', 'test3_file_and_classes(self):', 'target_dir', '=', 'os.getcwd()', '+', 'os.sep', '+', "'across_files_dflow2'", 'self.engine.ingest(target_dir)', 'self.engine.process_funcs()', 'self.engine.main_analysis()', 'self.assertTrue(len(self.engine.issues_found)', '==', '1)', 'self.assertEqual(self.engine.issues_found[...
213,029
gunthercox/ChatterBot
test_core.py
TestMaskedArray.test_fancy_printoptions
test_fancy_printoptions
Test printing a masked array w/ fancy dtype.
[ "Test", "printing", "a", "masked", "array", "w/", "fancy", "dtype." ]
def test_fancy_printoptions(self): fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) test = array([(1, (2, 3.0)), (4, (5, 6.0))], mask=[(1, (0, 1)), (0, (1, 0))], dtype=fancydtype) control = '[(--, (2, --)) (4, (--, 6.0))]' assert_equal(str(test), control)
['def', 'test_fancy_printoptions(self):', 'fancydtype', '=', "np.dtype([('x',", 'int),', "('y',", "[('t',", 'int),', "('s',", 'float)])])', 'test', '=', 'array([(1,', '(2,', '3.0)),', '(4,', '(5,', '6.0))],', 'mask=[(1,', '(0,', '1)),', '(0,', '(1,', '0))],', 'dtype=fancydtype)', 'control', '=', "'[(--,", '(2,', '--))'...
531,987
datamllab/rlcard
dqn_agent.py
DQNAgent.eval_step
eval_step
Predict the action for evaluation purpose.
[ "Predict", "the", "action", "for", "evaluation", "purpose." ]
def eval_step(self, state): q_values = self.predict(state) best_action = np.argmax(q_values) info = {} info['values'] = {state['raw_legal_actions'][i]: float(q_values[list(state['legal_actions'].keys())[i]]) for i in range(len(state['legal_actions']))} return (best_action, info)
['def', 'eval_step(self,', 'state):', 'q_values', '=', 'self.predict(state)', 'best_action', '=', 'np.argmax(q_values)', 'info', '=', '{}', "info['values']", '=', "{state['raw_legal_actions'][i]:", "float(q_values[list(state['legal_actions'].keys())[i]])", 'for', 'i', 'in', "range(len(state['legal_actions']))}", 'retur...
331,847
RLE-Foundation/rllte
base_agent.py
BaseAgent.freeze
freeze
Freeze the agent and get ready for training.
[ "Freeze", "the", "agent", "and", "get", "ready", "for", "training." ]
def freeze(self, **kwargs) -> None: self.policy.freeze(encoder=self.encoder, dist=self.dist) self.policy_name = self.policy.__class__.__name__ if kwargs.get('th_compile', False): self.policy = th.compile(self.policy) self.policy.to(self.device) self.mode(training=True) self.check() i...
['def', 'freeze(self,', '**kwargs)', '->', 'None:', 'self.policy.freeze(encoder=self.encoder,', 'dist=self.dist)', 'self.policy_name', '=', 'self.policy.__class__.__name__', 'if', "kwargs.get('th_compile',", 'False):', 'self.policy', '=', 'th.compile(self.policy)', 'self.policy.to(self.device)', 'self.mode(training=Tru...
333,242
matsu0228/nlp-jp
test_formatters.py
test_precision
test_precision
test various values for float_precision.
[ "test", "various", "values", "for", "float_precision." ]
def test_precision(): f = PlainTextFormatter() nt.assert_equal(f(pi), repr(pi)) f.float_precision = 0 if numpy: po = numpy.get_printoptions() nt.assert_equal(po['precision'], 0) nt.assert_equal(f(pi), '3') f.float_precision = 2 if numpy: po = numpy.get_printoptions() ...
['def', 'test_precision():', 'f', '=', 'PlainTextFormatter()', 'nt.assert_equal(f(pi),', 'repr(pi))', 'f.float_precision', '=', '0', 'if', 'numpy:', 'po', '=', 'numpy.get_printoptions()', "nt.assert_equal(po['precision'],", '0)', 'nt.assert_equal(f(pi),', "'3')", 'f.float_precision', '=', '2', 'if', 'numpy:', 'po', '='...
786,990
PacktPublishing/Hands-On-Artificial--for-Banking
test_decomp.py
TestEigTridiagonal.test_eigvalsh_tridiagonal
test_eigvalsh_tridiagonal
Compare eigenvalues of eigvalsh_tridiagonal with those of eig.
[ "Compare", "eigenvalues", "of", "eigvalsh_tridiagonal", "with", "those", "of", "eig." ]
def test_eigvalsh_tridiagonal(self): for driver in ('sterf', 'stev', 'stebz', 'stemr', 'auto'): w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver) assert_array_almost_equal(sort(w), self.w) for driver in ('sterf', 'stev'): assert_raises(ValueError, eigvalsh_tridiagonal, self....
['def', 'test_eigvalsh_tridiagonal(self):', 'for', 'driver', 'in', "('sterf',", "'stev',", "'stebz',", "'stemr',", "'auto'):", 'w', '=', 'eigvalsh_tridiagonal(self.d,', 'self.e,', 'lapack_driver=driver)', 'assert_array_almost_equal(sort(w),', 'self.w)', 'for', 'driver', 'in', "('sterf',", "'stev'):", 'assert_raises(Val...
238,592
unixpickle/anyrl-py
test_env.py
test_env_exception
test_env_exception
Test an environment that throws.
[ "Test", "an", "environment", "that", "throws." ]
def test_env_exception(): try: def raiser(): raise ValueError('hello world') AsyncGymEnv(raiser, None) except RuntimeError: return pytest.fail('should have gotten exception')
['def', 'test_env_exception():', 'try:', 'def', 'raiser():', 'raise', "ValueError('hello", "world')", 'AsyncGymEnv(raiser,', 'None)', 'except', 'RuntimeError:', 'return', "pytest.fail('should", 'have', 'gotten', "exception')"]
33,713
nosmokingbandit/watcher
_cpwsgi.py
AppResponse.run
run
Create a Request object using environ.
[ "Create", "a", "Request", "object", "using", "environ." ]
def run(self): env = self.environ.get local = httputil.Host('', int(env('SERVER_PORT', 80) or -1), env('SERVER_NAME', '')) remote = httputil.Host(env('REMOTE_ADDR', ''), int(env('REMOTE_PORT', -1) or -1), env('REMOTE_HOST', '')) scheme = env('wsgi.url_scheme') sproto = env('ACTUAL_SERVER_PROTOCOL', ...
['def', 'run(self):', 'env', '=', 'self.environ.get', 'local', '=', "httputil.Host('',", "int(env('SERVER_PORT',", '80)', 'or', '-1),', "env('SERVER_NAME',", "''))", 'remote', '=', "httputil.Host(env('REMOTE_ADDR',", "''),", "int(env('REMOTE_PORT',", '-1)', 'or', '-1),', "env('REMOTE_HOST',", "''))", 'scheme', '=', "en...
381,355
s3prl/s3prl
common.py
load_yaml_config
load_yaml_config
Loads yaml configuration settings as an EasyDict object.
[ "Loads", "yaml", "configuration", "settings", "as", "an", "EasyDict", "object." ]
def load_yaml_config(path_to_config): path_to_config = Path(path_to_config) assert path_to_config.is_file() with open(path_to_config) as f: yaml_contents = yaml.safe_load(f) cfg = Namespace(**yaml_contents) return cfg
['def', 'load_yaml_config(path_to_config):', 'path_to_config', '=', 'Path(path_to_config)', 'assert', 'path_to_config.is_file()', 'with', 'open(path_to_config)', 'as', 'f:', 'yaml_contents', '=', 'yaml.safe_load(f)', 'cfg', '=', 'Namespace(**yaml_contents)', 'return', 'cfg']
327,675
enlite-ai/maze
dummy_core_env.py
DummyCoreEnvironment.agent_counts_dict
agent_counts_dict
Single-step, single agent env.
[ "Single-step,", "single", "agent", "env." ]
def agent_counts_dict(self) -> Dict[StepKeyType, int]: return {0: 1}
['def', 'agent_counts_dict(self)', '->', 'Dict[StepKeyType,', 'int]:', 'return', '{0:', '1}']
647,299
greydanus/pythonic_ocr
data.py
CoverageData.write_fileobj
write_fileobj
Write the coverage data to `file_obj`.
[ "Write", "the", "coverage", "data", "to", "`file_obj`." ]
def write_fileobj(self, file_obj): file_data = {} if self._has_arcs(): file_data['arcs'] = self._arcs if self._has_lines(): file_data['lines'] = self._lines if self._file_tracers: file_data['file_tracers'] = self._file_tracers if self._runs: file_data['runs'] = self._...
['def', 'write_fileobj(self,', 'file_obj):', 'file_data', '=', '{}', 'if', 'self._has_arcs():', "file_data['arcs']", '=', 'self._arcs', 'if', 'self._has_lines():', "file_data['lines']", '=', 'self._lines', 'if', 'self._file_tracers:', "file_data['file_tracers']", '=', 'self._file_tracers', 'if', 'self._runs:', "file_da...
298,878
openai/gym
core.py
ActionWrapper.reverse_action
reverse_action
Returns a reversed ``action``.
[ "Returns", "a", "reversed", "``action``." ]
def reverse_action(self, action): raise NotImplementedError
['def', 'reverse_action(self,', 'action):', 'raise', 'NotImplementedError']
234,125
voxel51/fiftyone
view.py
DatasetView.group_slices
group_slices
The list of group slices of the view, or None if the view is not grouped.
[ "The", "list", "of", "group", "slices", "of", "the", "view,", "or", "None", "if", "the", "view", "is", "not", "grouped." ]
def group_slices(self): if not self._has_slices: return None return self._dataset.group_slices
['def', 'group_slices(self):', 'if', 'not', 'self._has_slices:', 'return', 'None', 'return', 'self._dataset.group_slices']
583,485
sek788432/Waymo-2D-Object-Detection
calibration_evaluation_tf1_test.py
CalibrationDetectionEvaluationTest.testGetECEWithMatchingGroundtruthAndDetections
testGetECEWithMatchingGroundtruthAndDetections
Tests that ECE is calculated correctly when box matches exist.
[ "Tests", "that", "ECE", "is", "calculated", "correctly", "when", "box", "matches", "exist." ]
def testGetECEWithMatchingGroundtruthAndDetections(self): calibration_evaluator = calibration_evaluation.CalibrationDetectionEvaluator(_get_categories_list(), iou_threshold=0.5) input_data_fields = standard_fields.InputDataFields detection_fields = standard_fields.DetectionResultFields base_eval_dict = ...
['def', 'testGetECEWithMatchingGroundtruthAndDetections(self):', 'calibration_evaluator', '=', 'calibration_evaluation.CalibrationDetectionEvaluator(_get_categories_list(),', 'iou_threshold=0.5)', 'input_data_fields', '=', 'standard_fields.InputDataFields', 'detection_fields', '=', 'standard_fields.DetectionResultField...
975,096
lhotse-speech/lhotse
test_custom_attrs.py
test_cut_load_temporal_array_pad
test_cut_load_temporal_array_pad
Check the array loaded via TemporalArray is padded along with the cut.
[ "Check", "the", "array", "loaded", "via", "TemporalArray", "is", "padded", "along", "with", "the", "cut." ]
def test_cut_load_temporal_array_pad(pad_value): with TemporaryDirectory() as d, NumpyFilesWriter(d) as writer: cut = MonoCut(id='x', start=0, duration=52.4, channel=0, recording=dummy_recording(1)) alignment = np.random.randint(500, size=131) cut.alignment = writer.store_array(key='utt1', v...
['def', 'test_cut_load_temporal_array_pad(pad_value):', 'with', 'TemporaryDirectory()', 'as', 'd,', 'NumpyFilesWriter(d)', 'as', 'writer:', 'cut', '=', "MonoCut(id='x',", 'start=0,', 'duration=52.4,', 'channel=0,', 'recording=dummy_recording(1))', 'alignment', '=', 'np.random.randint(500,', 'size=131)', 'cut.alignment'...
601,056
salesforce/CodeRL
tests_fetcher.py
get_module_dependencies
get_module_dependencies
Get the dependencies of a module.
[ "Get", "the", "dependencies", "of", "a", "module." ]
def get_module_dependencies(module_fname): with open(os.path.join(PATH_TO_TRANFORMERS, module_fname), 'r', encoding='utf-8') as f: content = f.read() module_parts = module_fname.split(os.path.sep) imported_modules = [] relative_imports = re.findall('from\\s+(\\.+\\S+)\\s+import\\s+([^\\n]+)\\n',...
['def', 'get_module_dependencies(module_fname):', 'with', 'open(os.path.join(PATH_TO_TRANFORMERS,', 'module_fname),', "'r',", "encoding='utf-8')", 'as', 'f:', 'content', '=', 'f.read()', 'module_parts', '=', 'module_fname.split(os.path.sep)', 'imported_modules', '=', '[]', 'relative_imports', '=', "re.findall('from\\\\...
495,796
Ruturaj123/Flowchart-Detection
linear_test.py
LinearClassifierTest.testCustomOptimizerByString
testCustomOptimizerByString
Tests multi-class classification using matrix data as input.
[ "Tests", "multi-class", "classification", "using", "matrix", "data", "as", "input." ]
def testCustomOptimizerByString(self): feature_column = feature_column_lib.real_valued_column('feature', dimension=4) def _optimizer(): return ftrl.FtrlOptimizer(learning_rate=0.1) classifier = linear.LinearClassifier(n_classes=3, optimizer=_optimizer, feature_columns=[feature_column]) classifi...
['def', 'testCustomOptimizerByString(self):', 'feature_column', '=', "feature_column_lib.real_valued_column('feature',", 'dimension=4)', 'def', '_optimizer():', 'return', 'ftrl.FtrlOptimizer(learning_rate=0.1)', 'classifier', '=', 'linear.LinearClassifier(n_classes=3,', 'optimizer=_optimizer,', 'feature_columns=[featur...
604,022
eddylau328/fyp-artificial-intelligence-ac-control-device
__init__.py
ssl_server_credentials
ssl_server_credentials
Creates a ServerCredentials for use with an SSL-enabled Server.
[ "Creates", "a", "ServerCredentials", "for", "use", "with", "an", "SSL-enabled", "Server." ]
def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False): if not private_key_certificate_chain_pairs: raise ValueError('At least one private key-certificate chain pair is required!') elif require_client_auth and root_certificates is None: ...
['def', 'ssl_server_credentials(private_key_certificate_chain_pairs,', 'root_certificates=None,', 'require_client_auth=False):', 'if', 'not', 'private_key_certificate_chain_pairs:', 'raise', "ValueError('At", 'least', 'one', 'private', 'key-certificate', 'chain', 'pair', 'is', "required!')", 'elif', 'require_client_aut...
215,555
sunishsheth2009/ChatterBot
environment.py
TemplateStream.disable_buffering
disable_buffering
Disable the output buffering.
[ "Disable", "the", "output", "buffering." ]
def disable_buffering(self): self._next = get_next(self._gen) self.buffered = False
['def', 'disable_buffering(self):', 'self._next', '=', 'get_next(self._gen)', 'self.buffered', '=', 'False']
529,225
sek788432/Waymo-2D-Object-Detection
sgnn.py
fused_project
fused_project
A wrapper to fuse project method when converting to TFLite model.
[ "A", "wrapper", "to", "fuse", "project", "method", "when", "converting", "to", "TFLite", "model." ]
def fused_project(ngrams, hash_seed, buckets): hash_seed_attr = ' '.join(['i: %d' % seed for seed in hash_seed]) experimental_implements = ['name: "tftext:custom:SgnnProjection"', 'attr { key: "hash_seed" value { list {%s} } }' % hash_seed_attr, 'attr { key: "buckets" value { i: %d } }' % buckets] experimen...
['def', 'fused_project(ngrams,', 'hash_seed,', 'buckets):', 'hash_seed_attr', '=', "'", "'.join(['i:", "%d'", '%', 'seed', 'for', 'seed', 'in', 'hash_seed])', 'experimental_implements', '=', "['name:", '"tftext:custom:SgnnProjection"\',', "'attr", '{', 'key:', '"hash_seed"', 'value', '{', 'list', '{%s}', '}', "}'", '%'...
975,697
CAMeL-Lab/camel_tools
dediac.py
dediac_xmlbw
dediac_xmlbw
Dediacritize XML Buckwalter encoded string.
[ "Dediacritize", "XML", "Buckwalter", "encoded", "string." ]
def dediac_xmlbw(s): return _DIAC_RE_XMLBW.sub(u'', s)
['def', 'dediac_xmlbw(s):', 'return', "_DIAC_RE_XMLBW.sub(u'',", 's)']
411,160
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.buffer_
buffer_
main buffer; all pointers point in it (nbuffer).
[ "main", "buffer;", "all", "pointers", "point", "in", "it", "(nbuffer)." ]
def buffer_(self): return self._ptr.contents.buffer_
['def', 'buffer_(self):', 'return', 'self._ptr.contents.buffer_']
440,232
thaines/helit
iris.py
Iris1D.getVectors
getVectors
Returns a numpy vector of float32 that contains the single parameter extracted from PCA for each entry.
[ "Returns", "a", "numpy", "vector", "of", "float32", "that", "contains", "the", "single", "parameter", "extracted", "from", "PCA", "for", "each", "entry." ]
def getVectors(self): return self.vec
['def', 'getVectors(self):', 'return', 'self.vec']
592,324
Eric3911/OpenAGI
prototypical_verbalizer.py
ProtoVerbalizer.normalize
normalize
Given logits regarding the entire vocabulary, return the probs over the label words set.
[ "Given", "logits", "regarding", "the", "entire", "vocabulary,", "return", "the", "probs", "over", "the", "label", "words", "set." ]
def normalize(self, logits: torch.Tensor) -> torch.Tensor: batch_size = logits.shape[0] return F.softmax(logits.reshape(batch_size, -1), dim=-1).reshape(*logits.shape)
['def', 'normalize(self,', 'logits:', 'torch.Tensor)', '->', 'torch.Tensor:', 'batch_size', '=', 'logits.shape[0]', 'return', 'F.softmax(logits.reshape(batch_size,', '-1),', 'dim=-1).reshape(*logits.shape)']
274,621
TrellixVulnTeam/Unsupervised_Learning_HFI7
conftest.py
compression_only
compression_only
Fixture for trying common compression types in compression tests excluding uncompressed case.
[ "Fixture", "for", "trying", "common", "compression", "types", "in", "compression", "tests", "excluding", "uncompressed", "case." ]
def compression_only(request): return request.param
['def', 'compression_only(request):', 'return', 'request.param']
452,406
B0-B/markov
__init__.py
sequence.trainSeq
trainSeq
Sequence must be a list object.
[ "Sequence", "must", "be", "a", "list", "object." ]
def trainSeq(self, sequence): self.train(' '.join(sequence), endings=False)
['def', 'trainSeq(self,', 'sequence):', "self.train('", "'.join(sequence),", 'endings=False)']
627,772
deepmind/acme
running_statistics.py
get_clip_config_for_path
get_clip_config_for_path
Returns the config for a subtree from the leaf defined by the path.
[ "Returns", "the", "config", "for", "a", "subtree", "from", "the", "leaf", "defined", "by", "the", "path." ]
def get_clip_config_for_path(config: NestClippingConfig, path: Path) -> NestClippingConfig: path_map = [] for (map_path, max_abs_value) in config.path_map: if _is_prefix(map_path, path): return NestClippingConfig(path_map=(((), max_abs_value),)) if _is_prefix(path, map_path): ...
['def', 'get_clip_config_for_path(config:', 'NestClippingConfig,', 'path:', 'Path)', '->', 'NestClippingConfig:', 'path_map', '=', '[]', 'for', '(map_path,', 'max_abs_value)', 'in', 'config.path_map:', 'if', '_is_prefix(map_path,', 'path):', 'return', 'NestClippingConfig(path_map=(((),', 'max_abs_value),))', 'if', '_is...
8,320
ryu-ed/SpaceInvaders_Ros
utils.py
get_rst_title
get_rst_title
Permit to get a title formatted as ReStructuredText test (underlined with a chosen character).
[ "Permit", "to", "get", "a", "title", "formatted", "as", "ReStructuredText", "test", "(underlined", "with", "a", "chosen", "character)." ]
def get_rst_title(title, character): return '%s\n%s\n' % (title, character * len(title))
['def', 'get_rst_title(title,', 'character):', 'return', "'%s\\n%s\\n'", '%', '(title,', 'character', '*', 'len(title))']
370,246
openml-labs/gama
test_gamaregressor.py
test_missing_value_regression
test_missing_value_regression
GamaRegressor works when missing values are present.
[ "GamaRegressor", "works", "when", "missing", "values", "are", "present." ]
def test_missing_value_regression(): data = diabetes metric = 'neg_mean_squared_error' (X, y) = data['load'](return_X_y=True) (X_train, X_test, y_train, y_test) = train_test_split(X, y, random_state=0) X_train[1:300:2, 0] = X_train[2:300:5, 1] = float('NaN') X_test[1:100:2, 0] = X_test[2:100:5, ...
['def', 'test_missing_value_regression():', 'data', '=', 'diabetes', 'metric', '=', "'neg_mean_squared_error'", '(X,', 'y)', '=', "data['load'](return_X_y=True)", '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X,', 'y,', 'random_state=0)', 'X_train[1:300:2,', '0]', '=', 'X_train[2:300:5,', '1]', ...
566,224
foxis/EasyVision
fixcode.py
fixcode
fixcode
auto pep8 format all python file in ``source code`` and ``tests`` dir.
[ "auto", "pep8", "format", "all", "python", "file", "in", "``source", "code``", "and", "``tests``", "dir." ]
def fixcode(**kwargs): repo_dir = Path(__file__).parent.absolute() source_dir = Path(repo_dir, package.__name__) if source_dir.exists(): print("Source code locate at: '%s'." % source_dir) print('Auto pep8 all python file ...') source_dir.autopep8(**kwargs) else: print('So...
['def', 'fixcode(**kwargs):', 'repo_dir', '=', 'Path(__file__).parent.absolute()', 'source_dir', '=', 'Path(repo_dir,', 'package.__name__)', 'if', 'source_dir.exists():', 'print("Source', 'code', 'locate', 'at:', '\'%s\'."', '%', 'source_dir)', "print('Auto", 'pep8', 'all', 'python', 'file', "...')", 'source_dir.autope...
547,213
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
__init__.py
buildJavaDocAST
buildJavaDocAST
Returns an AST for the given javadoc source.
[ "Returns", "an", "AST", "for", "the", "given", "javadoc", "source." ]
def buildJavaDocAST(source): from java2python.lang.JavaDocLexer import JavaDocLexer from java2python.lang.JavaDocParser import JavaDocParser lexer = JavaDocLexer(StringStream(source)) parser = JavaDocParser(TokenStream(lexer)) scope = parser.commentBody() return scope.tree
['def', 'buildJavaDocAST(source):', 'from', 'java2python.lang.JavaDocLexer', 'import', 'JavaDocLexer', 'from', 'java2python.lang.JavaDocParser', 'import', 'JavaDocParser', 'lexer', '=', 'JavaDocLexer(StringStream(source))', 'parser', '=', 'JavaDocParser(TokenStream(lexer))', 'scope', '=', 'parser.commentBody()', 'retur...
11,308
SamsungLabs/fcaf3d
load_scannet_data.py
export
export
Export original files to vert, ins_label, sem_label and bbox file.
[ "Export", "original", "files", "to", "vert,", "ins_label,", "sem_label", "and", "bbox", "file." ]
def export(mesh_file, agg_file, seg_file, meta_file, label_map_file, output_file=None, test_mode=False): label_map = scannet_utils.read_label_mapping(label_map_file, label_from='raw_category', label_to='nyu40id') mesh_vertices = scannet_utils.read_mesh_vertices_rgb(mesh_file) lines = open(meta_file).readlin...
['def', 'export(mesh_file,', 'agg_file,', 'seg_file,', 'meta_file,', 'label_map_file,', 'output_file=None,', 'test_mode=False):', 'label_map', '=', 'scannet_utils.read_label_mapping(label_map_file,', "label_from='raw_category',", "label_to='nyu40id')", 'mesh_vertices', '=', 'scannet_utils.read_mesh_vertices_rgb(mesh_fi...
560,078
flavioschneider/rl-transfer-
ray_sampler.py
RaySampler.obtain_samples
obtain_samples
Sample the policy for new episodes.
[ "Sample", "the", "policy", "for", "new", "episodes." ]
def obtain_samples(self, itr, num_samples, agent_update, env_update=None): active_workers = [] completed_samples = 0 batches = [] idle_worker_ids = [] updating_workers = self._update_workers(agent_update, env_update) with click.progressbar(length=num_samples, label='Sampling') as pbar: w...
['def', 'obtain_samples(self,', 'itr,', 'num_samples,', 'agent_update,', 'env_update=None):', 'active_workers', '=', '[]', 'completed_samples', '=', '0', 'batches', '=', '[]', 'idle_worker_ids', '=', '[]', 'updating_workers', '=', 'self._update_workers(agent_update,', 'env_update)', 'with', 'click.progressbar(length=nu...
861,270
AboudyKreidieh/h-baselines
test_envs.py
TestSNN4HRL.test_swimmer_gather
test_swimmer_gather
Validate the functionality of the SwimmerGather environment.
[ "Validate", "the", "functionality", "of", "the", "SwimmerGather", "environment." ]
def test_swimmer_gather(self): env = SwimmerGatherEnv() np.testing.assert_almost_equal(env.action_space.low, np.array([-50.0, -50.0])) np.testing.assert_almost_equal(env.action_space.high, np.array([50.0, 50.0])) np.testing.assert_almost_equal(env.observation_space.low, np.array([-1000000.0] * 33)) ...
['def', 'test_swimmer_gather(self):', 'env', '=', 'SwimmerGatherEnv()', 'np.testing.assert_almost_equal(env.action_space.low,', 'np.array([-50.0,', '-50.0]))', 'np.testing.assert_almost_equal(env.action_space.high,', 'np.array([50.0,', '50.0]))', 'np.testing.assert_almost_equal(env.observation_space.low,', 'np.array([-...
574,036
apple/ml-cvnets
base_zero_shot.py
BaseZeroShotDataset.generate_text_prompts
generate_text_prompts
Return a list of prompts for the given class name.
[ "Return", "a", "list", "of", "prompts", "for", "the", "given", "class", "name." ]
def generate_text_prompts(class_name: str) -> List[str]: raise NotImplementedError('Sub-classes should define `generate_text_prompts` that creates a list of prompts for a given class name.')
['def', 'generate_text_prompts(class_name:', 'str)', '->', 'List[str]:', 'raise', "NotImplementedError('Sub-classes", 'should', 'define', '`generate_text_prompts`', 'that', 'creates', 'a', 'list', 'of', 'prompts', 'for', 'a', 'given', 'class', "name.')"]
671,439
xuannianz/FSAF
coco.py
CocoGenerator.size
size
Size of the COCO dataset.
[ "Size", "of", "the", "COCO", "dataset." ]
def size(self): return len(self.image_ids)
['def', 'size(self):', 'return', 'len(self.image_ids)']
565,201
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Listbox.get
get
Get list of items from FIRST to LAST (included).
[ "Get", "list", "of", "items", "from", "FIRST", "to", "LAST", "(included)." ]
def get(self, first, last=None): if last is not None: return self.tk.splitlist(self.tk.call(self._w, 'get', first, last)) else: return self.tk.call(self._w, 'get', first)
['def', 'get(self,', 'first,', 'last=None):', 'if', 'last', 'is', 'not', 'None:', 'return', 'self.tk.splitlist(self.tk.call(self._w,', "'get',", 'first,', 'last))', 'else:', 'return', 'self.tk.call(self._w,', "'get',", 'first)']
376,996
clvrai/spirl
spacemouse.py
to_int16
to_int16
Convert two 8 bit bytes to a signed 16 bit integer.
[ "Convert", "two", "8", "bit", "bytes", "to", "a", "signed", "16", "bit", "integer." ]
def to_int16(y1, y2): x = y1 | y2 << 8 if x >= 32768: x = -(65536 - x) return x
['def', 'to_int16(y1,', 'y2):', 'x', '=', 'y1', '|', 'y2', '<<', '8', 'if', 'x', '>=', '32768:', 'x', '=', '-(65536', '-', 'x)', 'return', 'x']
896,785
deepmind/bsuite
analysis.py
plot_learning
plot_learning
Plots the average return through time by cartpole swingup.
[ "Plots", "the", "average", "return", "through", "time", "by", "cartpole", "swingup." ]
def plot_learning(df: pd.DataFrame, sweep_vars: Optional[Sequence[str]]=None) -> gg.ggplot: df = cp_swingup_preprocess(df_in=df) p = plotting.plot_regret_group_nosmooth(df_in=df, group_col='height_threshold', sweep_vars=sweep_vars, regret_col='perfection_regret', max_episode=sweep.NUM_EPISODES) return p
['def', 'plot_learning(df:', 'pd.DataFrame,', 'sweep_vars:', 'Optional[Sequence[str]]=None)', '->', 'gg.ggplot:', 'df', '=', 'cp_swingup_preprocess(df_in=df)', 'p', '=', 'plotting.plot_regret_group_nosmooth(df_in=df,', "group_col='height_threshold',", 'sweep_vars=sweep_vars,', "regret_col='perfection_regret',", 'max_ep...
410,186
sunishsheth2009/ChatterBot
expression.py
Select.append_prefix
append_prefix
append the given columns clause prefix expression to this select() construct.
[ "append", "the", "given", "columns", "clause", "prefix", "expression", "to", "this", "select()", "construct." ]
def append_prefix(self, clause): clause = _literal_as_text(clause) self._prefixes = self._prefixes + (clause,)
['def', 'append_prefix(self,', 'clause):', 'clause', '=', '_literal_as_text(clause)', 'self._prefixes', '=', 'self._prefixes', '+', '(clause,)']
534,933
Ruturaj123/Flowchart-Detection
quantize_graph_test.py
test_conv
test_conv
Tests a Conv replacement.
[ "Tests", "a", "Conv", "replacement." ]
def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values): input_constant_name = 'input_constant' filter_constant_name = 'filter_constant' conv_name = 'conv' float_graph_def = graph_pb2.GraphDef() input_constant = quan...
['def', 'test_conv(depth,', 'image_width,', 'image_height,', 'image_batch_count,', 'filter_size,', 'filter_count,', 'stride,', 'padding,', 'input_values,', 'filter_values):', 'input_constant_name', '=', "'input_constant'", 'filter_constant_name', '=', "'filter_constant'", 'conv_name', '=', "'conv'", 'float_graph_def', ...
606,811
otoofim/ObjLocalisation
VOC2012DataProvider.py
DataProvider.reset
reset
Resets the provider to the initial state.
[ "Resets", "the", "provider", "to", "the", "initial", "state." ]
def reset(self): inv_perm = np.argsort(self._current_order) self._current_order = self._current_order[inv_perm] self.inputs = self.inputs[inv_perm] self.targets = self.targets[inv_perm] self.new_epoch()
['def', 'reset(self):', 'inv_perm', '=', 'np.argsort(self._current_order)', 'self._current_order', '=', 'self._current_order[inv_perm]', 'self.inputs', '=', 'self.inputs[inv_perm]', 'self.targets', '=', 'self.targets[inv_perm]', 'self.new_epoch()']
739,906
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
transformer.py
transformer_parsing_big
transformer_parsing_big
HParams for parsing on WSJ semi-supervised.
[ "HParams", "for", "parsing", "on", "WSJ", "semi-supervised." ]
def transformer_parsing_big(): hparams = transformer_big() hparams.max_length = 512 hparams.shared_source_target_embedding = False hparams.learning_rate_warmup_steps = 4000 hparams.layer_prepostprocess_dropout = 0.1 hparams.batch_size = 2048 hparams.learning_rate = 0.05 return hparams
['def', 'transformer_parsing_big():', 'hparams', '=', 'transformer_big()', 'hparams.max_length', '=', '512', 'hparams.shared_source_target_embedding', '=', 'False', 'hparams.learning_rate_warmup_steps', '=', '4000', 'hparams.layer_prepostprocess_dropout', '=', '0.1', 'hparams.batch_size', '=', '2048', 'hparams.learning...
965,701