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
openai/gym
graph.py
Graph.sample
sample
Generates a single sample graph with num_nodes between 1 and 10 sampled from the Graph.
[ "Generates", "a", "single", "sample", "graph", "with", "num_nodes", "between", "1", "and", "10", "sampled", "from", "the", "Graph." ]
def sample(self, mask: Optional[Tuple[Optional[Union[np.ndarray, tuple]], Optional[Union[np.ndarray, tuple]]]]=None, num_nodes: int=10, num_edges: Optional[int]=None) -> GraphInstance: assert num_nodes > 0, f'The number of nodes is expected to be greater than 0, actual value: {num_nodes}' if mask is not None: ...
['def', 'sample(self,', 'mask:', 'Optional[Tuple[Optional[Union[np.ndarray,', 'tuple]],', 'Optional[Union[np.ndarray,', 'tuple]]]]=None,', 'num_nodes:', 'int=10,', 'num_edges:', 'Optional[int]=None)', '->', 'GraphInstance:', 'assert', 'num_nodes', '>', '0,', "f'The", 'number', 'of', 'nodes', 'is', 'expected', 'to', 'be...
234,177
ex4sperans/maggot
containers.py
NestedContainer.to_dict
to_dict
Turn contrainer into a dict.
[ "Turn", "contrainer", "into", "a", "dict." ]
def to_dict(self): nested_dict = dict() def _copy_fields(container, data): for (name, attr) in container.__dict__.items(): if not isinstance(attr, NestedContainer): data[name] = attr else: data[name] = dict() _copy_fields(attr, dat...
['def', 'to_dict(self):', 'nested_dict', '=', 'dict()', 'def', '_copy_fields(container,', 'data):', 'for', '(name,', 'attr)', 'in', 'container.__dict__.items():', 'if', 'not', 'isinstance(attr,', 'NestedContainer):', 'data[name]', '=', 'attr', 'else:', 'data[name]', '=', 'dict()', '_copy_fields(attr,', 'data[name])', '...
209,262
vbelz/audio_classification
package_index.py
PyPIConfig.find_credential
find_credential
If the URL indicated appears to be a repository defined in this config, return the credential for that repository.
[ "If", "the", "URL", "indicated", "appears", "to", "be", "a", "repository", "defined", "in", "this", "config,", "return", "the", "credential", "for", "that", "repository." ]
def find_credential(self, url): for (repository, cred) in self.creds_by_repository.items(): if url.startswith(repository): return cred
['def', 'find_credential(self,', 'url):', 'for', '(repository,', 'cred)', 'in', 'self.creds_by_repository.items():', 'if', 'url.startswith(repository):', 'return', 'cred']
404,273
Nrgeup/EasyNLP
__init__.py
get_html_theme_path
get_html_theme_path
Return list of HTML theme paths.
[ "Return", "list", "of", "HTML", "theme", "paths." ]
def get_html_theme_path(): cur_dir = path.abspath(path.dirname(path.dirname(__file__))) return cur_dir
['def', 'get_html_theme_path():', 'cur_dir', '=', 'path.abspath(path.dirname(path.dirname(__file__)))', 'return', 'cur_dir']
546,945
yukitaka13-1110/NaturalLanguageProcessing
logistic regression for sentiment analysis.py
gradientDescent
gradientDescent
Input: x: matrix of features which is (m,n+1) y: corresponding labels of the input matrix x, dimensions (m,1) theta: weight vector of dimension (n+1,1) alpha: learning rate num_iters: number of iterations you want to train your model for Output: J: the final cost theta: your final weight vector Hint: you might want to ...
[ "Input:", "x:", "matrix", "of", "features", "which", "is", "(m,n+1)", "y:", "corresponding", "labels", "of", "the", "input", "matrix", "x,", "dimensions", "(m,1)", "theta:", "weight", "vector", "of", "dimension", "(n+1,1)", "alpha:", "learning", "rate", "num_ite...
def gradientDescent(x, y, theta, alpha, num_iters): m = x.shape[0] for i in range(0, num_iters): z = np.dot(x, theta) h = sigmoid(z) y_t = np.transpose(y) one_minus_y_t = np.transpose(1 - y) first_dot_prod = np.dot(y_t, np.log(h)) second_dot_prod = np.dot(one_minu...
['def', 'gradientDescent(x,', 'y,', 'theta,', 'alpha,', 'num_iters):', 'm', '=', 'x.shape[0]', 'for', 'i', 'in', 'range(0,', 'num_iters):', 'z', '=', 'np.dot(x,', 'theta)', 'h', '=', 'sigmoid(z)', 'y_t', '=', 'np.transpose(y)', 'one_minus_y_t', '=', 'np.transpose(1', '-', 'y)', 'first_dot_prod', '=', 'np.dot(y_t,', 'np...
675,952
JinliangLu96/CL_UNMT
dataset.py
ParallelDataset.get_batches_iterator
get_batches_iterator
Return a sentences iterator, given the associated sentence batches.
[ "Return", "a", "sentences", "iterator,", "given", "the", "associated", "sentence", "batches." ]
def get_batches_iterator(self, batches=None, return_indices=False, c0=None, T=None, lengths=None, difficulty=None, iter_name=None): assert type(return_indices) is bool for sentence_ids in batches: if 0 < self.max_batch_size < len(sentence_ids): np.random.shuffle(sentence_ids) sen...
['def', 'get_batches_iterator(self,', 'batches=None,', 'return_indices=False,', 'c0=None,', 'T=None,', 'lengths=None,', 'difficulty=None,', 'iter_name=None):', 'assert', 'type(return_indices)', 'is', 'bool', 'for', 'sentence_ids', 'in', 'batches:', 'if', '0', '<', 'self.max_batch_size', '<', 'len(sentence_ids):', 'np.r...
123,255
algoterranean/3dgan
summaries.py
factorization
factorization
Finds factors of n suitable for image montage.
[ "Finds", "factors", "of", "n", "suitable", "for", "image", "montage." ]
def factorization(n): for i in range(int(sqrt(float(n))), 0, -1): if n % i == 0: return (i, int(n / i))
['def', 'factorization(n):', 'for', 'i', 'in', 'range(int(sqrt(float(n))),', '0,', '-1):', 'if', 'n', '%', 'i', '==', '0:', 'return', '(i,', 'int(n', '/', 'i))']
404,894
MushroomRL/mushroom-rl
torch_policy.py
TorchPolicy.log_prob_t
log_prob_t
Compute the logarithm of the probability of taking ``action`` in ``state``.
[ "Compute", "the", "logarithm", "of", "the", "probability", "of", "taking", "``action``", "in", "``state``." ]
def log_prob_t(self, state, action): raise NotImplementedError
['def', 'log_prob_t(self,', 'state,', 'action):', 'raise', 'NotImplementedError']
266,084
PacktPublishing/Hands-On-Artificial--for-Banking
blocks.py
Block.make_block_same_class
make_block_same_class
Wrap given values in a block of same type as self.
[ "Wrap", "given", "values", "in", "a", "block", "of", "same", "type", "as", "self." ]
def make_block_same_class(self, values, placement=None, ndim=None): if placement is None: placement = self.mgr_locs if ndim is None: ndim = self.ndim return type(self)(values, placement=placement, ndim=ndim)
['def', 'make_block_same_class(self,', 'values,', 'placement=None,', 'ndim=None):', 'if', 'placement', 'is', 'None:', 'placement', '=', 'self.mgr_locs', 'if', 'ndim', 'is', 'None:', 'ndim', '=', 'self.ndim', 'return', 'type(self)(values,', 'placement=placement,', 'ndim=ndim)']
236,740
zihuitang/medical_AI_platform
importbench.py
bench
bench
Bench the given statement as many times as necessary until total executions take one second.
[ "Bench", "the", "given", "statement", "as", "many", "times", "as", "necessary", "until", "total", "executions", "take", "one", "second." ]
def bench(name, cleanup=lambda : None, *, seconds=1, repeat=3): stmt = '__import__({!r})'.format(name) timer = timeit.Timer(stmt) for x in range(repeat): total_time = 0 count = 0 while total_time < seconds: try: total_time += timer.timeit(1) fi...
['def', 'bench(name,', 'cleanup=lambda', ':', 'None,', '*,', 'seconds=1,', 'repeat=3):', 'stmt', '=', "'__import__({!r})'.format(name)", 'timer', '=', 'timeit.Timer(stmt)', 'for', 'x', 'in', 'range(repeat):', 'total_time', '=', '0', 'count', '=', '0', 'while', 'total_time', '<', 'seconds:', 'try:', 'total_time', '+=', ...
284,778
AR13ar/Semantic-Segmentation
run_service.py
start_service
start_service
Starts SNET Daemon ("snetd") and the python module of the service at the passed gRPC port.
[ "Starts", "SNET", "Daemon", "(\"snetd\")", "and", "the", "python", "module", "of", "the", "service", "at", "the", "passed", "gRPC", "port." ]
def start_service(cwd, service_module, run_daemon, run_ssl): def add_extra_configs(conf): with open(conf, 'r') as f: _network = 'mainnet' if 'ropsten' in conf: _network = 'ropsten' snetd_configs = json.load(f) if run_ssl: snetd...
['def', 'start_service(cwd,', 'service_module,', 'run_daemon,', 'run_ssl):', 'def', 'add_extra_configs(conf):', 'with', 'open(conf,', "'r')", 'as', 'f:', '_network', '=', "'mainnet'", 'if', "'ropsten'", 'in', 'conf:', '_network', '=', "'ropsten'", 'snetd_configs', '=', 'json.load(f)', 'if', 'run_ssl:', "snetd_configs['...
869,570
piggyandy/artificial-intelligence
core.py
_MaskedBinaryOperation.reduce
reduce
Reduce `target` along the given `axis`.
[ "Reduce", "`target`", "along", "the", "given", "`axis`." ]
def reduce(self, target, axis=0, dtype=None): tclass = get_masked_subclass(target) m = getmask(target) t = filled(target, self.filly) if t.shape == (): t = t.reshape(1) if m is not nomask: m = make_mask(m, copy=1) m.shape = (1,) if m is nomask: tr = se...
['def', 'reduce(self,', 'target,', 'axis=0,', 'dtype=None):', 'tclass', '=', 'get_masked_subclass(target)', 'm', '=', 'getmask(target)', 't', '=', 'filled(target,', 'self.filly)', 'if', 't.shape', '==', '():', 't', '=', 't.reshape(1)', 'if', 'm', 'is', 'not', 'nomask:', 'm', '=', 'make_mask(m,', 'copy=1)', 'm.shape', '...
171,428
coder-mano/Shi-Tomasi-Corner-Detector
_collections.py
HTTPHeaderDict.iteritems
iteritems
Iterate over all header lines, including duplicate ones.
[ "Iterate", "over", "all", "header", "lines,", "including", "duplicate", "ones." ]
def iteritems(self): for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield (vals[0], val)
['def', 'iteritems(self):', 'for', 'key', 'in', 'self:', 'vals', '=', 'self._container[key.lower()]', 'for', 'val', 'in', 'vals[1:]:', 'yield', '(vals[0],', 'val)']
900,519
ViTAE-Transformer/ViTDet
custom.py
CustomDataset.load_annotations
load_annotations
Load annotation from annotation file.
[ "Load", "annotation", "from", "annotation", "file." ]
def load_annotations(self, ann_file): return mmcv.load(ann_file)
['def', 'load_annotations(self,', 'ann_file):', 'return', 'mmcv.load(ann_file)']
945,387
wonheeML/mtl-ssl
ops.py
normalized_to_image_coordinates
normalized_to_image_coordinates
Converts a batch of boxes from normal to image coordinates.
[ "Converts", "a", "batch", "of", "boxes", "from", "normal", "to", "image", "coordinates." ]
def normalized_to_image_coordinates(normalized_boxes, image_shape, parallel_iterations=32): def _to_absolute_coordinates(normalized_boxes): return box_list_ops.to_absolute_coordinates(box_list.BoxList(normalized_boxes), image_shape[1], image_shape[2], check_range=False).get() absolute_boxes = tf.map_fn...
['def', 'normalized_to_image_coordinates(normalized_boxes,', 'image_shape,', 'parallel_iterations=32):', 'def', '_to_absolute_coordinates(normalized_boxes):', 'return', 'box_list_ops.to_absolute_coordinates(box_list.BoxList(normalized_boxes),', 'image_shape[1],', 'image_shape[2],', 'check_range=False).get()', 'absolute...
643,173
luisespino/artificial_intelligence
models.py
Response.is_permanent_redirect
is_permanent_redirect
True if this Response one of the permanent versions of redirect.
[ "True", "if", "this", "Response", "one", "of", "the", "permanent", "versions", "of", "redirect." ]
def is_permanent_redirect(self): return 'location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)
['def', 'is_permanent_redirect(self):', 'return', "'location'", 'in', 'self.headers', 'and', 'self.status_code', 'in', '(codes.moved_permanently,', 'codes.permanent_redirect)']
149,824
facebookresearch/CompilerGym
env_tests.py
env
env
Text fixture that yields an environment.
[ "Text", "fixture", "that", "yields", "an", "environment." ]
def env() -> CompilerEnv: with gym.make('loops-opt-py-v0') as env_: yield env_
['def', 'env()', '->', 'CompilerEnv:', 'with', "gym.make('loops-opt-py-v0')", 'as', 'env_:', 'yield', 'env_']
135,699
cvzone/cvzone
PlotModule.py
LivePlot.drawBackground
drawBackground
Draw the static background elements of the plot.
[ "Draw", "the", "static", "background", "elements", "of", "the", "plot." ]
def drawBackground(self): cv2.rectangle(self.imgPlot, (0, 0), (self.w, self.h), (0, 0, 0), cv2.FILLED) cv2.line(self.imgPlot, (0, self.h // 2), (self.w, self.h // 2), (150, 150, 150), 2) for x in range(0, self.w, 50): cv2.line(self.imgPlot, (x, 0), (x, self.h), (50, 50, 50), 1) for y in range(0,...
['def', 'drawBackground(self):', 'cv2.rectangle(self.imgPlot,', '(0,', '0),', '(self.w,', 'self.h),', '(0,', '0,', '0),', 'cv2.FILLED)', 'cv2.line(self.imgPlot,', '(0,', 'self.h', '//', '2),', '(self.w,', 'self.h', '//', '2),', '(150,', '150,', '150),', '2)', 'for', 'x', 'in', 'range(0,', 'self.w,', '50):', 'cv2.line(s...
524,191
QData/deepWordBug
states.py
Body.text
text
Titles, definition lists, paragraphs.
[ "Titles,", "definition", "lists,", "paragraphs." ]
def text(self, match, context, next_state): return ([match.string], 'Text', [])
['def', 'text(self,', 'match,', 'context,', 'next_state):', 'return', '([match.string],', "'Text',", '[])']
542,181
priorfire4411/artificial_intelligence
ipaddress.py
IPv4Address.packed
packed
The binary representation of this address.
[ "The", "binary", "representation", "of", "this", "address." ]
def packed(self): return v4_int_to_packed(self._ip)
['def', 'packed(self):', 'return', 'v4_int_to_packed(self._ip)']
153,054
MasazI/gan_basic
model_part.py
batch_norm
batch_norm
Adds a Batch Normalization layer.
[ "Adds", "a", "Batch", "Normalization", "layer." ]
def batch_norm(inputs, scope_name, decay=0.999, center=True, scale=False, epsilon=0.001, moving_vars='moving_vars', activation=None, is_training=True, trainable=True, restore=True, scope=None, reuse=None): inputs_shape = inputs.get_shape() with tf.variable_scope(scope_name, [inputs], scope, reuse=reuse): ...
['def', 'batch_norm(inputs,', 'scope_name,', 'decay=0.999,', 'center=True,', 'scale=False,', 'epsilon=0.001,', "moving_vars='moving_vars',", 'activation=None,', 'is_training=True,', 'trainable=True,', 'restore=True,', 'scope=None,', 'reuse=None):', 'inputs_shape', '=', 'inputs.get_shape()', 'with', 'tf.variable_scope(s...
566,956
UAVs-at-Berkeley/flywave
visualization_utils.py
draw_bounding_boxes_on_image_array
draw_bounding_boxes_on_image_array
Draws bounding boxes on image (numpy array).
[ "Draws", "bounding", "boxes", "on", "image", "(numpy", "array)." ]
def draw_bounding_boxes_on_image_array(image, boxes, color='red', thickness=4, display_str_list_list=()): image_pil = Image.fromarray(image) draw_bounding_boxes_on_image(image_pil, boxes, color, thickness, display_str_list_list) np.copyto(image, np.array(image_pil))
['def', 'draw_bounding_boxes_on_image_array(image,', 'boxes,', "color='red',", 'thickness=4,', 'display_str_list_list=()):', 'image_pil', '=', 'Image.fromarray(image)', 'draw_bounding_boxes_on_image(image_pil,', 'boxes,', 'color,', 'thickness,', 'display_str_list_list)', 'np.copyto(image,', 'np.array(image_pil))']
607,347
ArdaGunay99/Key_Detection_Unsupervised_Learning
test_from_template.py
test_from_template
test_from_template
Regression test for gh-10712.
[ "Regression", "test", "for", "gh-10712." ]
def test_from_template(): pyf = process_str(pyf_src) normalized_pyf = normalize_whitespace(pyf) normalized_expected_pyf = normalize_whitespace(expected_pyf) assert_equal(normalized_pyf, normalized_expected_pyf)
['def', 'test_from_template():', 'pyf', '=', 'process_str(pyf_src)', 'normalized_pyf', '=', 'normalize_whitespace(pyf)', 'normalized_expected_pyf', '=', 'normalize_whitespace(expected_pyf)', 'assert_equal(normalized_pyf,', 'normalized_expected_pyf)']
258,499
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
synthetic_data_utils.py
generate_rnn
generate_rnn
Create a (vanilla) RNN with a bunch of hyper parameters for generating chaotic data.
[ "Create", "a", "(vanilla)", "RNN", "with", "a", "bunch", "of", "hyper", "parameters", "for", "generating", "chaotic", "data." ]
def generate_rnn(rng, N, g, tau, dt, max_firing_rate): rnn = {} rnn['N'] = N rnn['W'] = rng.randn(N, N) / np.sqrt(N) rnn['Bin'] = rng.randn(N) / np.sqrt(1.0) rnn['Bin2'] = rng.randn(N) / np.sqrt(1.0) rnn['b'] = np.zeros(N) rnn['g'] = g rnn['tau'] = tau rnn['dt'] = dt rnn['max_fir...
['def', 'generate_rnn(rng,', 'N,', 'g,', 'tau,', 'dt,', 'max_firing_rate):', 'rnn', '=', '{}', "rnn['N']", '=', 'N', "rnn['W']", '=', 'rng.randn(N,', 'N)', '/', 'np.sqrt(N)', "rnn['Bin']", '=', 'rng.randn(N)', '/', 'np.sqrt(1.0)', "rnn['Bin2']", '=', 'rng.randn(N)', '/', 'np.sqrt(1.0)', "rnn['b']", '=', 'np.zeros(N)', ...
56,167
Urinx/ReinforcementLearning
model.py
Agent.act
act
Returns actions for given state as per current policy.
[ "Returns", "actions", "for", "given", "state", "as", "per", "current", "policy." ]
def act(self, state): state = t.from_numpy(state).float() action = self.actor.get_action(state).detach() return action
['def', 'act(self,', 'state):', 'state', '=', 't.from_numpy(state).float()', 'action', '=', 'self.actor.get_action(state).detach()', 'return', 'action']
287,688
ashwanitanwar/nmt-transfer-learning-xlm-r
fairseq_task.py
FairseqTask.train_step
train_step
Do forward and backward, and return the loss as computed by *criterion* for the given *model* and *sample*.
[ "Do", "forward", "and", "backward,", "and", "return", "the", "loss", "as", "computed", "by", "*criterion*", "for", "the", "given", "*model*", "and", "*sample*." ]
def train_step(self, sample, model, criterion, optimizer, ignore_grad=False): model.train() (loss, sample_size, logging_output) = criterion(model, sample) if ignore_grad: loss *= 0 optimizer.backward(loss) return (loss, sample_size, logging_output)
['def', 'train_step(self,', 'sample,', 'model,', 'criterion,', 'optimizer,', 'ignore_grad=False):', 'model.train()', '(loss,', 'sample_size,', 'logging_output)', '=', 'criterion(model,', 'sample)', 'if', 'ignore_grad:', 'loss', '*=', '0', 'optimizer.backward(loss)', 'return', '(loss,', 'sample_size,', 'logging_output)'...
733,876
43Carrig/recurrent_neural_networks_practice
auth.py
HTTPDigestAuth.handle_redirect
handle_redirect
Reset num_401_calls counter on redirects.
[ "Reset", "num_401_calls", "counter", "on", "redirects." ]
def handle_redirect(self, r, **kwargs): if r.is_redirect: self._thread_local.num_401_calls = 1
['def', 'handle_redirect(self,', 'r,', '**kwargs):', 'if', 'r.is_redirect:', 'self._thread_local.num_401_calls', '=', '1']
311,773
gencnis/NaturalLanguageProcessing
modeling_test.py
BertModelTest.assert_all_tensors_reachable
assert_all_tensors_reachable
Checks that all the tensors in the graph are reachable from outputs.
[ "Checks", "that", "all", "the", "tensors", "in", "the", "graph", "are", "reachable", "from", "outputs." ]
def assert_all_tensors_reachable(self, sess, outputs): graph = sess.graph ignore_strings = ['^.*/assert_less_equal/.*$', '^.*/dilation_rate$', '^.*/Tensordot/concat$', '^.*/Tensordot/concat/axis$', '^testing/.*$'] ignore_regexes = [re.compile(x) for x in ignore_strings] unreachable = self.get_unreachabl...
['def', 'assert_all_tensors_reachable(self,', 'sess,', 'outputs):', 'graph', '=', 'sess.graph', 'ignore_strings', '=', "['^.*/assert_less_equal/.*$',", "'^.*/dilation_rate$',", "'^.*/Tensordot/concat$',", "'^.*/Tensordot/concat/axis$',", "'^testing/.*$']", 'ignore_regexes', '=', '[re.compile(x)', 'for', 'x', 'in', 'ign...
713,091
ameet-1997/AttentionGuidance
tokenization_bert.py
whitespace_tokenize
whitespace_tokenize
Runs basic whitespace cleaning and splitting on a piece of text.
[ "Runs", "basic", "whitespace", "cleaning", "and", "splitting", "on", "a", "piece", "of", "text." ]
def whitespace_tokenize(text): text = text.strip() if not text: return [] tokens = text.split() return tokens
['def', 'whitespace_tokenize(text):', 'text', '=', 'text.strip()', 'if', 'not', 'text:', 'return', '[]', 'tokens', '=', 'text.split()', 'return', 'tokens']
93,091
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
download_and_convert_flowers.py
run
run
Runs the download and conversion operation.
[ "Runs", "the", "download", "and", "conversion", "operation." ]
def run(dataset_dir): if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) if _dataset_exists(dataset_dir): print('Dataset files already exist. Exiting without re-creating them.') return dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) (photo_f...
['def', 'run(dataset_dir):', 'if', 'not', 'tf.gfile.Exists(dataset_dir):', 'tf.gfile.MakeDirs(dataset_dir)', 'if', '_dataset_exists(dataset_dir):', "print('Dataset", 'files', 'already', 'exist.', 'Exiting', 'without', 're-creating', "them.')", 'return', 'dataset_utils.download_and_uncompress_tarball(_DATA_URL,', 'datas...
109,761
shaoshengsong/quarkdet
assign_result.py
AssignResult.add_gt_
add_gt_
Add ground truth as assigned results.
[ "Add", "ground", "truth", "as", "assigned", "results." ]
def add_gt_(self, gt_labels): self_inds = torch.arange(1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device) self.gt_inds = torch.cat([self_inds, self.gt_inds]) self.max_overlaps = torch.cat([self.max_overlaps.new_ones(len(gt_labels)), self.max_overlaps]) if self.labels is not None: ...
['def', 'add_gt_(self,', 'gt_labels):', 'self_inds', '=', 'torch.arange(1,', 'len(gt_labels)', '+', '1,', 'dtype=torch.long,', 'device=gt_labels.device)', 'self.gt_inds', '=', 'torch.cat([self_inds,', 'self.gt_inds])', 'self.max_overlaps', '=', 'torch.cat([self.max_overlaps.new_ones(len(gt_labels)),', 'self.max_overlap...
835,583
Kvatsx/Artificial-Intelligence-Assignments
pyparsing.py
ParseBaseException.markInputline
markInputline
Extracts the exception line from the input string, and marks the location of the exception with a special symbol.
[ "Extracts", "the", "exception", "line", "from", "the", "input", "string,", "and", "marks", "the", "location", "of", "the", "exception", "with", "a", "special", "symbol." ]
def markInputline(self, markerString='>!<'): line_str = self.line line_column = self.column - 1 if markerString: line_str = ''.join((line_str[:line_column], markerString, line_str[line_column:])) return line_str.strip()
['def', 'markInputline(self,', "markerString='>!<'):", 'line_str', '=', 'self.line', 'line_column', '=', 'self.column', '-', '1', 'if', 'markerString:', 'line_str', '=', "''.join((line_str[:line_column],", 'markerString,', 'line_str[line_column:]))', 'return', 'line_str.strip()']
75,431
Farama-Foundation/Gymnasium
atari_preprocessing.py
AtariPreprocessing.reset
reset
Resets the environment using preprocessing.
[ "Resets", "the", "environment", "using", "preprocessing." ]
def reset(self, **kwargs): (_, reset_info) = self.env.reset(**kwargs) noops = self.env.unwrapped.np_random.integers(1, self.noop_max + 1) if self.noop_max > 0 else 0 for _ in range(noops): (_, _, terminated, truncated, step_info) = self.env.step(0) reset_info.update(step_info) if ter...
['def', 'reset(self,', '**kwargs):', '(_,', 'reset_info)', '=', 'self.env.reset(**kwargs)', 'noops', '=', 'self.env.unwrapped.np_random.integers(1,', 'self.noop_max', '+', '1)', 'if', 'self.noop_max', '>', '0', 'else', '0', 'for', '_', 'in', 'range(noops):', '(_,', '_,', 'terminated,', 'truncated,', 'step_info)', '=', ...
573,361
jordanlui/NaturalLanguageProcessing
utils.py
lookup
lookup
Input: freqs: a dictionary with the frequency of each pair (or tuple) word: the word to look up label: the label corresponding to the word Output: n: the number of times the word with its corresponding label appears.
[ "Input:", "freqs:", "a", "dictionary", "with", "the", "frequency", "of", "each", "pair", "(or", "tuple)", "word:", "the", "word", "to", "look", "up", "label:", "the", "label", "corresponding", "to", "the", "word", "Output:", "n:", "the", "number", "of", "t...
def lookup(freqs, word, label): n = 0 pair = (word, label) if pair in freqs: n = freqs[pair] return n
['def', 'lookup(freqs,', 'word,', 'label):', 'n', '=', '0', 'pair', '=', '(word,', 'label)', 'if', 'pair', 'in', 'freqs:', 'n', '=', 'freqs[pair]', 'return', 'n']
676,959
ludwig-ai/ludwig
benchmark.py
setup_experiment
setup_experiment
Set up the backend and load the Ludwig config.
[ "Set", "up", "the", "backend", "and", "load", "the", "Ludwig", "config." ]
def setup_experiment(experiment: Dict[str, str]) -> Dict[Any, Any]: shutil.rmtree(os.path.join(experiment['experiment_name']), ignore_errors=True) if 'config_path' not in experiment: experiment['config_path'] = create_default_config(experiment) model_config = load_yaml(experiment['config_path']) ...
['def', 'setup_experiment(experiment:', 'Dict[str,', 'str])', '->', 'Dict[Any,', 'Any]:', "shutil.rmtree(os.path.join(experiment['experiment_name']),", 'ignore_errors=True)', 'if', "'config_path'", 'not', 'in', 'experiment:', "experiment['config_path']", '=', 'create_default_config(experiment)', 'model_config', '=', "l...
616,512
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
show_and_tell_model.py
ShowAndTellModel.build
build
Creates all ops for training and evaluation.
[ "Creates", "all", "ops", "for", "training", "and", "evaluation." ]
def build(self): self.build_inputs() self.build_image_embeddings() self.build_seq_embeddings() self.build_model() self.setup_inception_initializer() self.setup_global_step()
['def', 'build(self):', 'self.build_inputs()', 'self.build_image_embeddings()', 'self.build_seq_embeddings()', 'self.build_model()', 'self.setup_inception_initializer()', 'self.setup_global_step()']
48,739
implus/GFocalV2
builder.py
build_sampler
build_sampler
Builder of box sampler.
[ "Builder", "of", "box", "sampler." ]
def build_sampler(cfg, **default_args): return build_from_cfg(cfg, BBOX_SAMPLERS, default_args)
['def', 'build_sampler(cfg,', '**default_args):', 'return', 'build_from_cfg(cfg,', 'BBOX_SAMPLERS,', 'default_args)']
557,333
arnomoonens/yarll
registration.py
make_agent
make_agent
Make an agent of a given name, possibly using extra arguments.
[ "Make", "an", "agent", "of", "a", "given", "name,", "possibly", "using", "extra", "arguments." ]
def make_agent(name: str, state_dimensions: str, action_space: str, rnn: bool=False, backend: str='tensorflow', **args): try: Agent = agent_registry[name] Agent = next((agent_type for agent_type in Agent if agent_type['action_space'] == action_space and agent_type['state_dimensions'] == state_dimens...
['def', 'make_agent(name:', 'str,', 'state_dimensions:', 'str,', 'action_space:', 'str,', 'rnn:', 'bool=False,', 'backend:', "str='tensorflow',", '**args):', 'try:', 'Agent', '=', 'agent_registry[name]', 'Agent', '=', 'next((agent_type', 'for', 'agent_type', 'in', 'Agent', 'if', "agent_type['action_space']", '==', 'act...
374,651
LucasAlegre/morl-baselines
mo_q_learning.py
MOQLearning.update
update
Updates the Q table.
[ "Updates", "the", "Q", "table." ]
def update(self): obs = tuple(self.obs) next_obs = tuple(self.next_obs) if obs not in self.q_table: self.q_table[obs] = np.zeros((self.action_dim, self.reward_dim)) if next_obs not in self.q_table: self.q_table[next_obs] = np.zeros((self.action_dim, self.reward_dim)) max_q = self.q_t...
['def', 'update(self):', 'obs', '=', 'tuple(self.obs)', 'next_obs', '=', 'tuple(self.next_obs)', 'if', 'obs', 'not', 'in', 'self.q_table:', 'self.q_table[obs]', '=', 'np.zeros((self.action_dim,', 'self.reward_dim))', 'if', 'next_obs', 'not', 'in', 'self.q_table:', 'self.q_table[next_obs]', '=', 'np.zeros((self.action_d...
655,947
MorvanZhou/Computer-Vision
flappybird.py
PipePair.bottom_height_px
bottom_height_px
Get the bottom pipe's height, in pixels.
[ "Get", "the", "bottom", "pipe's", "height,", "in", "pixels." ]
def bottom_height_px(self): return self.bottom_pieces * PipePair.PIECE_HEIGHT
['def', 'bottom_height_px(self):', 'return', 'self.bottom_pieces', '*', 'PipePair.PIECE_HEIGHT']
468,804
bislara/Object-detection-GUI
autoaugment_utils.py
contrast
contrast
Equivalent of PIL Contrast.
[ "Equivalent", "of", "PIL", "Contrast." ]
def contrast(image, factor): degenerate = tf.image.rgb_to_grayscale(image) degenerate = tf.cast(degenerate, tf.int32) hist = tf.histogram_fixed_width(degenerate, [0, 255], nbins=256) mean = tf.reduce_sum(tf.cast(hist, tf.float32)) / 256.0 degenerate = tf.ones_like(degenerate, dtype=tf.float32) * mea...
['def', 'contrast(image,', 'factor):', 'degenerate', '=', 'tf.image.rgb_to_grayscale(image)', 'degenerate', '=', 'tf.cast(degenerate,', 'tf.int32)', 'hist', '=', 'tf.histogram_fixed_width(degenerate,', '[0,', '255],', 'nbins=256)', 'mean', '=', 'tf.reduce_sum(tf.cast(hist,', 'tf.float32))', '/', '256.0', 'degenerate', ...
726,707
zihuitang/medical_AI_platform
server.py
BaseHTTPRequestHandler.date_time_string
date_time_string
Return the current date and time formatted for a message header.
[ "Return", "the", "current", "date", "and", "time", "formatted", "for", "a", "message", "header." ]
def date_time_string(self, timestamp=None): if timestamp is None: timestamp = time.time() return email.utils.formatdate(timestamp, usegmt=True)
['def', 'date_time_string(self,', 'timestamp=None):', 'if', 'timestamp', 'is', 'None:', 'timestamp', '=', 'time.time()', 'return', 'email.utils.formatdate(timestamp,', 'usegmt=True)']
282,656
goncalo120/3DRegNet
transformations.py
arcball_nearest_axis
arcball_nearest_axis
Return axis, which arc is nearest to point.
[ "Return", "axis,", "which", "arc", "is", "nearest", "to", "point." ]
def arcball_nearest_axis(point, axes): point = numpy.array(point, dtype=numpy.float64, copy=False) nearest = None mx = -1.0 for axis in axes: t = numpy.dot(arcball_constrain_to_axis(point, axis), point) if t > mx: nearest = axis mx = t return nearest
['def', 'arcball_nearest_axis(point,', 'axes):', 'point', '=', 'numpy.array(point,', 'dtype=numpy.float64,', 'copy=False)', 'nearest', '=', 'None', 'mx', '=', '-1.0', 'for', 'axis', 'in', 'axes:', 't', '=', 'numpy.dot(arcball_constrain_to_axis(point,', 'axis),', 'point)', 'if', 't', '>', 'mx:', 'nearest', '=', 'axis', ...
405,168
open-mmlab/mmtracking
got10k2coco.py
convert_got10k
convert_got10k
Convert got10k dataset to COCO style.
[ "Convert", "got10k", "dataset", "to", "COCO", "style." ]
def convert_got10k(ann_dir, save_dir, split='test'): assert split in ['train', 'test', 'val'], f'split [{split}] does not exist' got10k = defaultdict(list) records = dict(vid_id=1, img_id=1, ann_id=1, global_instance_id=1) got10k['categories'] = [dict(id=0, name=0)] videos_list = mmcv.list_from_file...
['def', 'convert_got10k(ann_dir,', 'save_dir,', "split='test'):", 'assert', 'split', 'in', "['train',", "'test',", "'val'],", "f'split", '[{split}]', 'does', 'not', "exist'", 'got10k', '=', 'defaultdict(list)', 'records', '=', 'dict(vid_id=1,', 'img_id=1,', 'ann_id=1,', 'global_instance_id=1)', "got10k['categories']", ...
625,938
matsu0228/nlp-jp
read_concern.py
ReadConcern.ok_for_legacy
ok_for_legacy
Return ``True`` if this read concern is compatible with old wire protocol versions.
[ "Return", "``True``", "if", "this", "read", "concern", "is", "compatible", "with", "old", "wire", "protocol", "versions." ]
def ok_for_legacy(self): return self.level is None or self.level == 'local'
['def', 'ok_for_legacy(self):', 'return', 'self.level', 'is', 'None', 'or', 'self.level', '==', "'local'"]
804,995
neardws/Game-Theoretic-Deep-Reinforcement-Learning
agent.py
D4PGBuilder.make_replay_tables
make_replay_tables
Create tables to insert data into.
[ "Create", "tables", "to", "insert", "data", "into." ]
def make_replay_tables(self, environment_spec: specs.EnvironmentSpec) -> List[reverb.Table]: if self._config.samples_per_insert is None: limiter = reverb.rate_limiters.MinSize(self._config.min_replay_size) else: samples_per_insert_tolerance = 0.1 * self._config.samples_per_insert error_b...
['def', 'make_replay_tables(self,', 'environment_spec:', 'specs.EnvironmentSpec)', '->', 'List[reverb.Table]:', 'if', 'self._config.samples_per_insert', 'is', 'None:', 'limiter', '=', 'reverb.rate_limiters.MinSize(self._config.min_replay_size)', 'else:', 'samples_per_insert_tolerance', '=', '0.1', '*', 'self._config.sa...
199,829
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
misc.py
read_chunks
read_chunks
Yield pieces of data from a file-like object until EOF.
[ "Yield", "pieces", "of", "data", "from", "a", "file-like", "object", "until", "EOF." ]
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): while True: chunk = file.read(size) if not chunk: break yield chunk
['def', 'read_chunks(file,', 'size=io.DEFAULT_BUFFER_SIZE):', 'while', 'True:', 'chunk', '=', 'file.read(size)', 'if', 'not', 'chunk:', 'break', 'yield', 'chunk']
950,130
google-research/scenic
mbt.py
MBTClassificationModel.get_metrics_fn
get_metrics_fn
Returns a callable metric function for the model.
[ "Returns", "a", "callable", "metric", "function", "for", "the", "model." ]
def get_metrics_fn(self, split: Optional[str]=None) -> base_model.MetricFn: del split return functools.partial(classification_model.classification_metrics_function, target_is_onehot=self.dataset_meta_data.get('target_is_onehot', False), metrics=_MBT_CLASSIFICATION_METRICS)
['def', 'get_metrics_fn(self,', 'split:', 'Optional[str]=None)', '->', 'base_model.MetricFn:', 'del', 'split', 'return', 'functools.partial(classification_model.classification_metrics_function,', "target_is_onehot=self.dataset_meta_data.get('target_is_onehot',", 'False),', 'metrics=_MBT_CLASSIFICATION_METRICS)']
846,411
instadeepai/jumanji
utils_test.py
test_connected_or_blocked
test_connected_or_blocked
Tests that connected or blocked only returns false when an agent is neither connected nor blocked.
[ "Tests", "that", "connected", "or", "blocked", "only", "returns", "false", "when", "an", "agent", "is", "neither", "connected", "nor", "blocked." ]
def test_connected_or_blocked() -> None: not_connected_agent = Agent(id=jnp.array(0, jnp.int32), start=jnp.array([1, 1]), target=jnp.array([1, 3]), position=jnp.array([1, 2])) connected_agent = Agent(id=jnp.array(0, jnp.int32), start=jnp.array([1, 2]), target=jnp.array([1, 2]), position=jnp.array([1, 2])) n...
['def', 'test_connected_or_blocked()', '->', 'None:', 'not_connected_agent', '=', 'Agent(id=jnp.array(0,', 'jnp.int32),', 'start=jnp.array([1,', '1]),', 'target=jnp.array([1,', '3]),', 'position=jnp.array([1,', '2]))', 'connected_agent', '=', 'Agent(id=jnp.array(0,', 'jnp.int32),', 'start=jnp.array([1,', '2]),', 'targe...
594,341
lhotse-speech/lhotse
himia.py
himia
himia
HI-MIA and HI_MIA_CW download.
[ "HI-MIA", "and", "HI_MIA_CW", "download." ]
def himia(target_dir: Pathlike, dataset_parts: Sequence[str]): if len(dataset_parts) == 1: dataset_parts = dataset_parts[0] download_himia(target_dir, dataset_parts=dataset_parts)
['def', 'himia(target_dir:', 'Pathlike,', 'dataset_parts:', 'Sequence[str]):', 'if', 'len(dataset_parts)', '==', '1:', 'dataset_parts', '=', 'dataset_parts[0]', 'download_himia(target_dir,', 'dataset_parts=dataset_parts)']
600,608
audioku/meta-transfer-learning
train.py
train
train
Train a model on a dataset.
[ "Train", "a", "model", "on", "a", "dataset." ]
def train(sess, model, train_set, test_set, save_dir, num_classes=5, num_shots=5, inner_batch_size=5, inner_iters=20, replacement=False, meta_step_size=0.1, meta_step_size_final=0.1, meta_batch_size=1, meta_iters=400000, eval_inner_batch_size=5, eval_inner_iters=50, eval_interval=1000, weight_decay_rate=1, time_deadlin...
['def', 'train(sess,', 'model,', 'train_set,', 'test_set,', 'save_dir,', 'num_classes=5,', 'num_shots=5,', 'inner_batch_size=5,', 'inner_iters=20,', 'replacement=False,', 'meta_step_size=0.1,', 'meta_step_size_final=0.1,', 'meta_batch_size=1,', 'meta_iters=400000,', 'eval_inner_batch_size=5,', 'eval_inner_iters=50,', '...
633,402
coderIlluminatus/Artificial-Intelligence
utils.py
distance_squared
distance_squared
The square of the distance between two (x, y) points.
[ "The", "square", "of", "the", "distance", "between", "two", "(x,", "y)", "points." ]
def distance_squared(a, b): (xA, yA) = a (xB, yB) = b return (xA - xB) ** 2 + (yA - yB) ** 2
['def', 'distance_squared(a,', 'b):', '(xA,', 'yA)', '=', 'a', '(xB,', 'yB)', '=', 'b', 'return', '(xA', '-', 'xB)', '**', '2', '+', '(yA', '-', 'yB)', '**', '2']
119,472
intel/neural-compressor
run_qa_no_trainer_block.py
save_prefixed_metrics
save_prefixed_metrics
Save results while prefixing metric names.
[ "Save", "results", "while", "prefixing", "metric", "names." ]
def save_prefixed_metrics(results, output_dir, file_name: str='all_results.json', metric_key_prefix: str='eval'): for key in list(results.keys()): if not key.startswith(f'{metric_key_prefix}_'): results[f'{metric_key_prefix}_{key}'] = results.pop(key) with open(os.path.join(output_dir, file_...
['def', 'save_prefixed_metrics(results,', 'output_dir,', 'file_name:', "str='all_results.json',", 'metric_key_prefix:', "str='eval'):", 'for', 'key', 'in', 'list(results.keys()):', 'if', 'not', "key.startswith(f'{metric_key_prefix}_'):", "results[f'{metric_key_prefix}_{key}']", '=', 'results.pop(key)', 'with', 'open(os...
736,783
weimin17/Object-Detection_HelmetDetection
tensorrt.py
batch_from_random
batch_from_random
Produce a batch of random data.
[ "Produce", "a", "batch", "of", "random", "data." ]
def batch_from_random(batch_size, output_height=224, output_width=224, num_channels=3): shape = [batch_size, output_height, output_width, num_channels] return np.random.random_sample(shape).astype(np.float32)
['def', 'batch_from_random(batch_size,', 'output_height=224,', 'output_width=224,', 'num_channels=3):', 'shape', '=', '[batch_size,', 'output_height,', 'output_width,', 'num_channels]', 'return', 'np.random.random_sample(shape).astype(np.float32)']
753,918
lhotse-speech/lhotse
test_custom_attrs.py
test_cut_load_temporal_array
test_cut_load_temporal_array
Check that we can read a TemporalArray from a cut when their durations match.
[ "Check", "that", "we", "can", "read", "a", "TemporalArray", "from", "a", "cut", "when", "their", "durations", "match." ]
def test_cut_load_temporal_array(): alignment = np.random.randint(500, size=131) with TemporaryDirectory() as d, NumpyFilesWriter(d) as writer: manifest = writer.store_array(key='utt1', value=alignment, frame_shift=0.4, temporal_dim=0) expected_duration = 52.4 cut = MonoCut(id='x', start...
['def', 'test_cut_load_temporal_array():', 'alignment', '=', 'np.random.randint(500,', 'size=131)', 'with', 'TemporaryDirectory()', 'as', 'd,', 'NumpyFilesWriter(d)', 'as', 'writer:', 'manifest', '=', "writer.store_array(key='utt1',", 'value=alignment,', 'frame_shift=0.4,', 'temporal_dim=0)', 'expected_duration', '=', ...
601,054
spryor/Natural-Language-Processing
topiccorank.py
TopicCoRank.unify_with_domain_graph
unify_with_domain_graph
Unify the domain graph, built from a reference file, with the topic graph, built from a document.
[ "Unify", "the", "domain", "graph,", "built", "from", "a", "reference", "file,", "with", "the", "topic", "graph,", "built", "from", "a", "document." ]
def unify_with_domain_graph(self, input_file, excluded_file=None): if input_file.endswith('.json'): references = load_references(input_file=input_file, language=self.language) else: logging.warning('{} is not a reference file'.format(input_file)) pass if excluded_file is not None: ...
['def', 'unify_with_domain_graph(self,', 'input_file,', 'excluded_file=None):', 'if', "input_file.endswith('.json'):", 'references', '=', 'load_references(input_file=input_file,', 'language=self.language)', 'else:', "logging.warning('{}", 'is', 'not', 'a', 'reference', "file'.format(input_file))", 'pass', 'if', 'exclud...
658,978
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vgg_preprocessing.py
preprocess_image
preprocess_image
Preprocesses the given image.
[ "Preprocesses", "the", "given", "image." ]
def preprocess_image(image, output_height, output_width, is_training=False, resize_side_min=_RESIZE_SIDE_MIN, resize_side_max=_RESIZE_SIDE_MAX): if is_training: return preprocess_for_train(image, output_height, output_width, resize_side_min, resize_side_max) else: return preprocess_for_eval(imag...
['def', 'preprocess_image(image,', 'output_height,', 'output_width,', 'is_training=False,', 'resize_side_min=_RESIZE_SIDE_MIN,', 'resize_side_max=_RESIZE_SIDE_MAX):', 'if', 'is_training:', 'return', 'preprocess_for_train(image,', 'output_height,', 'output_width,', 'resize_side_min,', 'resize_side_max)', 'else:', 'retur...
14,081
ChenhongyiYang/PPAL
cascade_rpn_head.py
CascadeRPNHead.aug_test_rpn
aug_test_rpn
Augmented forward test function.
[ "Augmented", "forward", "test", "function." ]
def aug_test_rpn(self, x, img_metas): raise NotImplementedError('CascadeRPNHead does not support test-time augmentation')
['def', 'aug_test_rpn(self,', 'x,', 'img_metas):', 'raise', "NotImplementedError('CascadeRPNHead", 'does', 'not', 'support', 'test-time', "augmentation')"]
821,488
deepmind/acme
base.py
ReverbAdder.add_first
add_first
Record the first observation of a trajectory.
[ "Record", "the", "first", "observation", "of", "a", "trajectory." ]
def add_first(self, timestep: dm_env.TimeStep): if not timestep.first(): raise ValueError('adder.add_first with an initial timestep (i.e. one for which timestep.first() is True') self._writer.append(dict(observation=timestep.observation, start_of_episode=timestep.first()), partial_step=True) self._a...
['def', 'add_first(self,', 'timestep:', 'dm_env.TimeStep):', 'if', 'not', 'timestep.first():', 'raise', "ValueError('adder.add_first", 'with', 'an', 'initial', 'timestep', '(i.e.', 'one', 'for', 'which', 'timestep.first()', 'is', "True')", 'self._writer.append(dict(observation=timestep.observation,', 'start_of_episode=...
8,020
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
datasets.py
read_MNIST
read_MNIST
Reads in MNIST images.
[ "Reads", "in", "MNIST", "images." ]
def read_MNIST(binarize=False): with gfile.FastGFile(os.path.join(config.DATA_DIR, config.MNIST_BINARIZED), 'r') as f: ((x_train, _), (x_valid, _), (x_test, _)) = pickle.load(f) if not binarize: with gfile.FastGFile(os.path.join(config.DATA_DIR, config.MNIST_FLOAT), 'r') as f: x_trai...
['def', 'read_MNIST(binarize=False):', 'with', 'gfile.FastGFile(os.path.join(config.DATA_DIR,', 'config.MNIST_BINARIZED),', "'r')", 'as', 'f:', '((x_train,', '_),', '(x_valid,', '_),', '(x_test,', '_))', '=', 'pickle.load(f)', 'if', 'not', 'binarize:', 'with', 'gfile.FastGFile(os.path.join(config.DATA_DIR,', 'config.MN...
109,495
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_task_towers.py
doubling_cnn_class_and_quaternion
doubling_cnn_class_and_quaternion
Alternate conv, pool while doubling filter count.
[ "Alternate", "conv,", "pool", "while", "doubling", "filter", "count." ]
def doubling_cnn_class_and_quaternion(images, num_private_layers=1, num_classes=10, is_training=False, reuse_private=False, private_scope='doubling_cnn', reuse_shared=False, shared_scope='task_model'): net = images depth = 32 layer_id = 1 with tf.variable_scope(private_scope, reuse=reuse_private): ...
['def', 'doubling_cnn_class_and_quaternion(images,', 'num_private_layers=1,', 'num_classes=10,', 'is_training=False,', 'reuse_private=False,', "private_scope='doubling_cnn',", 'reuse_shared=False,', "shared_scope='task_model'):", 'net', '=', 'images', 'depth', '=', '32', 'layer_id', '=', '1', 'with', 'tf.variable_scope...
54,484
piggyandy/artificial-intelligence
test_defmatrix.py
TestAlgebra.test_notimplemented
test_notimplemented
Check that 'not implemented' operations produce a failure.
[ "Check", "that", "'not", "implemented'", "operations", "produce", "a", "failure." ]
def test_notimplemented(self): A = matrix([[1.0, 2.0], [3.0, 4.0]]) with assert_raises(TypeError): 1.0 ** A with assert_raises(TypeError): A * object()
['def', 'test_notimplemented(self):', 'A', '=', 'matrix([[1.0,', '2.0],', '[3.0,', '4.0]])', 'with', 'assert_raises(TypeError):', '1.0', '**', 'A', 'with', 'assert_raises(TypeError):', 'A', '*', 'object()']
172,938
openvinotoolkit/training_extensions
custom_lite_dino.py
CustomLiteDINO.load_state_dict_pre_hook
load_state_dict_pre_hook
Modify official lite dino version's weights before weight loading.
[ "Modify", "official", "lite", "dino", "version's", "weights", "before", "weight", "loading." ]
def load_state_dict_pre_hook(self, model_classes, ckpt_classes, ckpt_dict, *args, **kwargs): super(CustomDINO, self).load_state_dict_pre_hook(model_classes, ckpt_classes, ckpt_dict, *args, *kwargs)
['def', 'load_state_dict_pre_hook(self,', 'model_classes,', 'ckpt_classes,', 'ckpt_dict,', '*args,', '**kwargs):', 'super(CustomDINO,', 'self).load_state_dict_pre_hook(model_classes,', 'ckpt_classes,', 'ckpt_dict,', '*args,', '*kwargs)']
918,106
zcrwind/tgg-pytorch
data_utils.py
ZSL_Dataset.get_firstHop_featureFunc_visual_zsl_test_unseen
get_firstHop_featureFunc_visual_zsl_test_unseen
Get the first-hop feature (use visual feature as input feature) for test seen in zero-shot setting.
[ "Get", "the", "first-hop", "feature", "(use", "visual", "feature", "as", "input", "feature)", "for", "test", "seen", "in", "zero-shot", "setting." ]
def get_firstHop_featureFunc_visual_zsl_test_unseen(self): return self.instanceIdx2visualFeat_zsl_test_unseen
['def', 'get_firstHop_featureFunc_visual_zsl_test_unseen(self):', 'return', 'self.instanceIdx2visualFeat_zsl_test_unseen']
916,012
batra-mlp-lab/visdial-rl
answerer.py
Answerer.forward
forward
Forward pass the last observed answer to compute its log likelihood under the current decoder RNN state.
[ "Forward", "pass", "the", "last", "observed", "answer", "to", "compute", "its", "log", "likelihood", "under", "the", "current", "decoder", "RNN", "state." ]
def forward(self): encStates = self.encoder() if len(self.answers) > 0: decIn = self.answers[-1] elif self.caption is not None: decIn = self.caption else: raise Exception('Must provide an input sequence') logProbs = self.decoder(encStates, inputSeq=decIn) return logProbs
['def', 'forward(self):', 'encStates', '=', 'self.encoder()', 'if', 'len(self.answers)', '>', '0:', 'decIn', '=', 'self.answers[-1]', 'elif', 'self.caption', 'is', 'not', 'None:', 'decIn', '=', 'self.caption', 'else:', 'raise', "Exception('Must", 'provide', 'an', 'input', "sequence')", 'logProbs', '=', 'self.decoder(en...
933,541
sek788432/Waymo-2D-Object-Detection
input_utils.py
normalize_image
normalize_image
Normalizes the image to zero mean and unit variance.
[ "Normalizes", "the", "image", "to", "zero", "mean", "and", "unit", "variance." ]
def normalize_image(image, offset=(0.485, 0.456, 0.406), scale=(0.229, 0.224, 0.225)): image = tf.image.convert_image_dtype(image, dtype=tf.float32) offset = tf.constant(offset) offset = tf.expand_dims(offset, axis=0) offset = tf.expand_dims(offset, axis=0) image -= offset scale = tf.constant(sc...
['def', 'normalize_image(image,', 'offset=(0.485,', '0.456,', '0.406),', 'scale=(0.229,', '0.224,', '0.225)):', 'image', '=', 'tf.image.convert_image_dtype(image,', 'dtype=tf.float32)', 'offset', '=', 'tf.constant(offset)', 'offset', '=', 'tf.expand_dims(offset,', 'axis=0)', 'offset', '=', 'tf.expand_dims(offset,', 'ax...
973,575
clvrai/spirl
spacemouse.py
SpaceMouse.start_control
start_control
Method that should be called externally before controller can start receiving commands.
[ "Method", "that", "should", "be", "called", "externally", "before", "controller", "can", "start", "receiving", "commands." ]
def start_control(self): self._reset_internal_state() self._reset_state = 0 self._enabled = True
['def', 'start_control(self):', 'self._reset_internal_state()', 'self._reset_state', '=', '0', 'self._enabled', '=', 'True']
896,788
Ixiaohuihuihui/AO2-DETR
transforms.py
obb2hbb_le135
obb2hbb_le135
Convert oriented bounding boxes to horizontal bounding boxes.
[ "Convert", "oriented", "bounding", "boxes", "to", "horizontal", "bounding", "boxes." ]
def obb2hbb_le135(rotatex_boxes): polys = obb2poly_le135(rotatex_boxes) (xmin, _) = polys[:, ::2].min(1) (ymin, _) = polys[:, 1::2].min(1) (xmax, _) = polys[:, ::2].max(1) (ymax, _) = polys[:, 1::2].max(1) bboxes = torch.stack([xmin, ymin, xmax, ymax], dim=1) x_ctr = (bboxes[:, 2] + bboxes[:...
['def', 'obb2hbb_le135(rotatex_boxes):', 'polys', '=', 'obb2poly_le135(rotatex_boxes)', '(xmin,', '_)', '=', 'polys[:,', '::2].min(1)', '(ymin,', '_)', '=', 'polys[:,', '1::2].min(1)', '(xmax,', '_)', '=', 'polys[:,', '::2].max(1)', '(ymax,', '_)', '=', 'polys[:,', '1::2].max(1)', 'bboxes', '=', 'torch.stack([xmin,', '...
401,374
YanZiQinKevin/object_detection
visualization_utils.py
draw_bounding_box_on_image_array
draw_bounding_box_on_image_array
Adds a bounding box to an image (numpy array).
[ "Adds", "a", "bounding", "box", "to", "an", "image", "(numpy", "array)." ]
def draw_bounding_box_on_image_array(image, ymin, xmin, ymax, xmax, color='red', thickness=4, display_str_list=(), use_normalized_coordinates=True): image_pil = Image.fromarray(np.uint8(image)).convert('RGB') draw_bounding_box_on_image(image_pil, ymin, xmin, ymax, xmax, color, thickness, display_str_list, use_n...
['def', 'draw_bounding_box_on_image_array(image,', 'ymin,', 'xmin,', 'ymax,', 'xmax,', "color='red',", 'thickness=4,', 'display_str_list=(),', 'use_normalized_coordinates=True):', 'image_pil', '=', "Image.fromarray(np.uint8(image)).convert('RGB')", 'draw_bounding_box_on_image(image_pil,', 'ymin,', 'xmin,', 'ymax,', 'xm...
792,619
coder-mano/Shi-Tomasi-Corner-Detector
test_arraypad.py
TestAsPairs.test_pass_through
test_pass_through
Test if `x` already matching desired output are passed through.
[ "Test", "if", "`x`", "already", "matching", "desired", "output", "are", "passed", "through." ]
def test_pass_through(self): expected = np.arange(12).reshape((6, 2)) assert_equal(_as_pairs(expected, 6), expected)
['def', 'test_pass_through(self):', 'expected', '=', 'np.arange(12).reshape((6,', '2))', 'assert_equal(_as_pairs(expected,', '6),', 'expected)']
899,484
DPerrySvendsen/COS30002
vector2d.py
Vector2D.get_reverse
get_reverse
return a new vector that is the reverse of self.
[ "return", "a", "new", "vector", "that", "is", "the", "reverse", "of", "self." ]
def get_reverse(self): return Vector2D(-self.x, -self.y)
['def', 'get_reverse(self):', 'return', 'Vector2D(-self.x,', '-self.y)']
137,380
AlexGeControl/Artificial-Intelligence-01-Graph-Search-02-Pacman
msvc.py
RegistryInfo.windows_kits_roots
windows_kits_roots
Microsoft Windows Kits Roots registry key.
[ "Microsoft", "Windows", "Kits", "Roots", "registry", "key." ]
def windows_kits_roots(self): return 'Windows Kits\\Installed Roots'
['def', 'windows_kits_roots(self):', 'return', "'Windows", 'Kits\\\\Installed', "Roots'"]
35,928
gopinath-balu/computer_vision
preprocessor.py
convert_class_logits_to_softmax
convert_class_logits_to_softmax
Converts multiclass logits to softmax scores after applying temperature.
[ "Converts", "multiclass", "logits", "to", "softmax", "scores", "after", "applying", "temperature." ]
def convert_class_logits_to_softmax(multiclass_scores, temperature=1.0): multiclass_scores_scaled = tf.divide(multiclass_scores, temperature, name='scale_logits') multiclass_scores = tf.nn.softmax(multiclass_scores_scaled, name='softmax') return multiclass_scores
['def', 'convert_class_logits_to_softmax(multiclass_scores,', 'temperature=1.0):', 'multiclass_scores_scaled', '=', 'tf.divide(multiclass_scores,', 'temperature,', "name='scale_logits')", 'multiclass_scores', '=', 'tf.nn.softmax(multiclass_scores_scaled,', "name='softmax')", 'return', 'multiclass_scores']
505,381
palVikram/Machine-Learning-using-Python
subtensor.py
GpuAdvancedIncSubtensor1_dev20.make_node
make_node
It differs from GpuAdvancedIncSubtensor1 in that it makes sure the indexes are of type long.
[ "It", "differs", "from", "GpuAdvancedIncSubtensor1", "in", "that", "it", "makes", "sure", "the", "indexes", "are", "of", "type", "long." ]
def make_node(self, x, y, ilist): ctx_name = infer_context_name(x, y, ilist) x_ = as_gpuarray_variable(x, ctx_name) y_ = as_gpuarray_variable(y.astype(x.dtype), ctx_name) ilist_ = as_gpuarray_variable(ilist, ctx_name) assert x_.type.ndim >= y_.type.ndim if ilist_.type.dtype not in tensor.integer...
['def', 'make_node(self,', 'x,', 'y,', 'ilist):', 'ctx_name', '=', 'infer_context_name(x,', 'y,', 'ilist)', 'x_', '=', 'as_gpuarray_variable(x,', 'ctx_name)', 'y_', '=', 'as_gpuarray_variable(y.astype(x.dtype),', 'ctx_name)', 'ilist_', '=', 'as_gpuarray_variable(ilist,', 'ctx_name)', 'assert', 'x_.type.ndim', '>=', 'y_...
714,128
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
list_t_bxn_to_tensor_bxtxn
list_t_bxn_to_tensor_bxtxn
Convert a length T list of BxN numpy tensors to single numpy tensor with shape BxTxN.
[ "Convert", "a", "length", "T", "list", "of", "BxN", "numpy", "tensors", "to", "single", "numpy", "tensor", "with", "shape", "BxTxN." ]
def list_t_bxn_to_tensor_bxtxn(values_t_bxn): T = len(values_t_bxn) (B, N) = values_t_bxn[0].shape values_bxtxn = np.zeros([B, T, N]) for t in range(T): values_bxtxn[:, t, :] = values_t_bxn[t] return values_bxtxn
['def', 'list_t_bxn_to_tensor_bxtxn(values_t_bxn):', 'T', '=', 'len(values_t_bxn)', '(B,', 'N)', '=', 'values_t_bxn[0].shape', 'values_bxtxn', '=', 'np.zeros([B,', 'T,', 'N])', 'for', 't', 'in', 'range(T):', 'values_bxtxn[:,', 't,', ':]', '=', 'values_t_bxn[t]', 'return', 'values_bxtxn']
56,101
rifqind/Agent-Programs-3KS1
__init__.py
get_all_filters
get_all_filters
Return a generator of all filter names.
[ "Return", "a", "generator", "of", "all", "filter", "names." ]
def get_all_filters(): for name in FILTERS: yield name for (name, _) in find_plugin_filters(): yield name
['def', 'get_all_filters():', 'for', 'name', 'in', 'FILTERS:', 'yield', 'name', 'for', '(name,', '_)', 'in', 'find_plugin_filters():', 'yield', 'name']
46,155
includebits/Artificial-Intelligence
utils.py
first
first
Return the first element of an iterable; or default.
[ "Return", "the", "first", "element", "of", "an", "iterable;", "or", "default." ]
def first(iterable, default=None): return next(iter(iterable), default)
['def', 'first(iterable,', 'default=None):', 'return', 'next(iter(iterable),', 'default)']
120,034
jaromiru/sr-drl
test_vec_env.py
test_sync_sampling
test_sync_sampling
Test that a SubprocVecEnv running with envs in series outputs the same as DummyVecEnv.
[ "Test", "that", "a", "SubprocVecEnv", "running", "with", "envs", "in", "series", "outputs", "the", "same", "as", "DummyVecEnv." ]
def test_sync_sampling(dtype, num_envs_in_series): num_envs = 12 num_steps = 100 shape = (3, 8) def make_fn(seed): return lambda : SimpleEnv(seed, shape, dtype) fns = [make_fn(i) for i in range(num_envs)] env1 = DummyVecEnv(fns) env2 = SubprocVecEnv(fns, in_series=num_envs_in_series...
['def', 'test_sync_sampling(dtype,', 'num_envs_in_series):', 'num_envs', '=', '12', 'num_steps', '=', '100', 'shape', '=', '(3,', '8)', 'def', 'make_fn(seed):', 'return', 'lambda', ':', 'SimpleEnv(seed,', 'shape,', 'dtype)', 'fns', '=', '[make_fn(i)', 'for', 'i', 'in', 'range(num_envs)]', 'env1', '=', 'DummyVecEnv(fns)...
897,359
scotthuang1989/object_detection_with_tensorflow
imagenet_data.py
ImagenetData.num_classes
num_classes
Returns the number of classes in the data set.
[ "Returns", "the", "number", "of", "classes", "in", "the", "data", "set." ]
def num_classes(self): return 1000
['def', 'num_classes(self):', 'return', '1000']
797,175
Mdominik/artificial_intelligence
tarfile.py
nts
nts
Convert a null-terminated bytes object to a string.
[ "Convert", "a", "null-terminated", "bytes", "object", "to", "a", "string." ]
def nts(s, encoding, errors): p = s.find(b'\x00') if p != -1: s = s[:p] return s.decode(encoding, errors)
['def', 'nts(s,', 'encoding,', 'errors):', 'p', '=', "s.find(b'\\x00')", 'if', 'p', '!=', '-1:', 's', '=', 's[:p]', 'return', 's.decode(encoding,', 'errors)']
154,854
tensorlayer/TensorLayerX
paddle_nn.py
BatchNorm.channel_format
channel_format
return "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC".
[ "return", "\"NC\",", "\"NCL\",", "\"NCHW\",", "\"NCDHW\",", "\"NLC\",", "\"NHWC\"", "or", "\"NDHWC\"." ]
def channel_format(self, inputs): len_in_shape = len(inputs.shape) if len_in_shape == 2: return 'NC' if self.data_format == 'channels_last': if len_in_shape == 3: return 'NLC' if len_in_shape == 4: return 'NHWC' if len_in_shape == 5: return...
['def', 'channel_format(self,', 'inputs):', 'len_in_shape', '=', 'len(inputs.shape)', 'if', 'len_in_shape', '==', '2:', 'return', "'NC'", 'if', 'self.data_format', '==', "'channels_last':", 'if', 'len_in_shape', '==', '3:', 'return', "'NLC'", 'if', 'len_in_shape', '==', '4:', 'return', "'NHWC'", 'if', 'len_in_shape', '...
923,541
43Carrig/recurrent_neural_networks_practice
dataset_serialization_test_base.py
DatasetSerializationTestBase.verify_unused_iterator
verify_unused_iterator
Verifies that saving and restoring an unused iterator works.
[ "Verifies", "that", "saving", "and", "restoring", "an", "unused", "iterator", "works." ]
def verify_unused_iterator(self, ds_fn, num_outputs, sparse_tensors=False, verify_exhausted=True): self.verify_run_with_breaks(ds_fn, [0], num_outputs, sparse_tensors=sparse_tensors, verify_exhausted=verify_exhausted)
['def', 'verify_unused_iterator(self,', 'ds_fn,', 'num_outputs,', 'sparse_tensors=False,', 'verify_exhausted=True):', 'self.verify_run_with_breaks(ds_fn,', '[0],', 'num_outputs,', 'sparse_tensors=sparse_tensors,', 'verify_exhausted=verify_exhausted)']
312,662
ludwig-ai/ludwig
base.py
BaseModel.evaluation_step
evaluation_step
Predict the inputs and update evaluation metrics.
[ "Predict", "the", "inputs", "and", "update", "evaluation", "metrics." ]
def evaluation_step(self, inputs, targets): predictions = self.predictions(inputs) self.update_metrics(targets, predictions) return predictions
['def', 'evaluation_step(self,', 'inputs,', 'targets):', 'predictions', '=', 'self.predictions(inputs)', 'self.update_metrics(targets,', 'predictions)', 'return', 'predictions']
616,834
RLE-Foundation/rllte
prioritized_replay_storage.py
PrioritizedReplayStorage.add
add
Add sampled transitions into storage.
[ "Add", "sampled", "transitions", "into", "storage." ]
def add(self, observations: th.Tensor, actions: th.Tensor, rewards: th.Tensor, terminateds: th.Tensor, truncateds: th.Tensor, infos: Dict[str, Any], next_observations: th.Tensor) -> None: transition = (observations[0].cpu().numpy(), actions[0].cpu().numpy(), rewards[0].cpu().numpy(), terminateds[0].cpu().numpy(), t...
['def', 'add(self,', 'observations:', 'th.Tensor,', 'actions:', 'th.Tensor,', 'rewards:', 'th.Tensor,', 'terminateds:', 'th.Tensor,', 'truncateds:', 'th.Tensor,', 'infos:', 'Dict[str,', 'Any],', 'next_observations:', 'th.Tensor)', '->', 'None:', 'transition', '=', '(observations[0].cpu().numpy(),', 'actions[0].cpu().nu...
333,619
rnjtsh/graphical-object-detector
ds_utils.py
xywh_to_xyxy
xywh_to_xyxy
Convert [x y w h] box format to [x1 y1 x2 y2] format.
[ "Convert", "[x", "y", "w", "h]", "box", "format", "to", "[x1", "y1", "x2", "y2]", "format." ]
def xywh_to_xyxy(boxes): return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1))
['def', 'xywh_to_xyxy(boxes):', 'return', 'np.hstack((boxes[:,', '0:2],', 'boxes[:,', '0:2]', '+', 'boxes[:,', '2:4]', '-', '1))']
580,502
felipessalvatore/MyTwitterBot
RNNLanguageModel.py
RNNLanguageModel.add_training_op
add_training_op
Method to create the graph optimizer.
[ "Method", "to", "create", "the", "graph", "optimizer." ]
def add_training_op(self): optimizer = tf.train.AdamOptimizer(self.config.lr) self.train_op = optimizer.minimize(self.loss)
['def', 'add_training_op(self):', 'optimizer', '=', 'tf.train.AdamOptimizer(self.config.lr)', 'self.train_op', '=', 'optimizer.minimize(self.loss)']
291,103
Hareric/Natural-Language-Processing
RNN_machine_translation.py
TokenizerWrap.text_to_tokens
text_to_tokens
Convert a single text-string to tokens with optional reversal and padding.
[ "Convert", "a", "single", "text-string", "to", "tokens", "with", "optional", "reversal", "and", "padding." ]
def text_to_tokens(self, text, reverse=False, padding=False): tokens = self.texts_to_sequences([text]) tokens = np.array(tokens) if reverse: tokens = np.flip(tokens, axis=1) truncating = 'pre' else: truncating = 'post' if padding: tokens = pad_sequences(tokens, maxlen...
['def', 'text_to_tokens(self,', 'text,', 'reverse=False,', 'padding=False):', 'tokens', '=', 'self.texts_to_sequences([text])', 'tokens', '=', 'np.array(tokens)', 'if', 'reverse:', 'tokens', '=', 'np.flip(tokens,', 'axis=1)', 'truncating', '=', "'pre'", 'else:', 'truncating', '=', "'post'", 'if', 'padding:', 'tokens', ...
709,135
weimin17/Object-Detection_HelmetDetection
seq2seq_attention_decode.py
DecodeIO.Write
Write
Writes the reference and decoded outputs to RKV files.
[ "Writes", "the", "reference", "and", "decoded", "outputs", "to", "RKV", "files." ]
def Write(self, reference, decode): self._ref_file.write('output=%s\n' % reference) self._decode_file.write('output=%s\n' % decode) self._cnt += 1 if self._cnt % DECODE_IO_FLUSH_INTERVAL == 0: self._ref_file.flush() self._decode_file.flush()
['def', 'Write(self,', 'reference,', 'decode):', "self._ref_file.write('output=%s\\n'", '%', 'reference)', "self._decode_file.write('output=%s\\n'", '%', 'decode)', 'self._cnt', '+=', '1', 'if', 'self._cnt', '%', 'DECODE_IO_FLUSH_INTERVAL', '==', '0:', 'self._ref_file.flush()', 'self._decode_file.flush()']
760,793
xiaoaleiBLUE/computer_vision
coco_tools.py
COCOEvalWrapper.GetAgnosticMode
GetAgnosticMode
Returns true if COCO Eval is configured to evaluate in agnostic mode.
[ "Returns", "true", "if", "COCO", "Eval", "is", "configured", "to", "evaluate", "in", "agnostic", "mode." ]
def GetAgnosticMode(self): return self.params.useCats == 0
['def', 'GetAgnosticMode(self):', 'return', 'self.params.useCats', '==', '0']
511,344
intel/neural-compressor
calibrator.py
MinMaxCalibrator.method_name
method_name
Get calibration method name.
[ "Get", "calibration", "method", "name." ]
def method_name(self): return 'minmax'
['def', 'method_name(self):', 'return', "'minmax'"]
737,454
keras-team/keras-nlp
task.py
Task.from_preset
from_preset
Instantiate {{model_task_name}} model from preset architecture and weights.
[ "Instantiate", "{{model_task_name}}", "model", "from", "preset", "architecture", "and", "weights." ]
def from_preset(cls, preset, load_weights=True, **kwargs): if not cls.presets: raise NotImplementedError('No presets have been created for this class.') if preset not in cls.presets: raise ValueError(f"`preset` must be one of {', '.join(cls.presets)}. Received: {preset}.") if 'preprocessor' ...
['def', 'from_preset(cls,', 'preset,', 'load_weights=True,', '**kwargs):', 'if', 'not', 'cls.presets:', 'raise', "NotImplementedError('No", 'presets', 'have', 'been', 'created', 'for', 'this', "class.')", 'if', 'preset', 'not', 'in', 'cls.presets:', 'raise', 'ValueError(f"`preset`', 'must', 'be', 'one', 'of', "{',", "'...
595,622
AndrewSpano/BSc-Thesis
data_prep_utils.py
get_sentences
get_sentences
Split a corpus of Ancient Greek text into sentences.
[ "Split", "a", "corpus", "of", "Ancient", "Greek", "text", "into", "sentences." ]
def get_sentences(text: str) -> List[str]: delimiters_pattern = '([\\.;Ã\x8d¾!])' sentences_and_delimiters = re.split(delimiters_pattern, text) sentences = [(sentences_and_delimiters[i - 1] + sentences_and_delimiters[i]).strip() for i in range(1, len(sentences_and_delimiters), 2)] sentences = [sent.str...
['def', 'get_sentences(text:', 'str)', '->', 'List[str]:', 'delimiters_pattern', '=', "'([\\\\.;Ã\\x8d¾!])'", 'sentences_and_delimiters', '=', 're.split(delimiters_pattern,', 'text)', 'sentences', '=', '[(sentences_and_delimiters[i', '-', '1]', '+', 'sentences_and_delimiters[i]).strip()', 'for', 'i', 'in', 'range(1,',...
410,050
codekansas/gandlf
reversing_gan.py
reverse_generator
reverse_generator
Gradient descent to map images back to their latent vectors.
[ "Gradient", "descent", "to", "map", "images", "back", "to", "their", "latent", "vectors." ]
def reverse_generator(generator, X_sample, y_sample, title): latent_vec = np.random.normal(size=(1, 100)) target = K.placeholder() loss = K.sum(K.square(generator.outputs[0] - target)) grad = K.gradients(loss, generator.inputs[0])[0] update_fn = K.function(generator.inputs + [target], [grad]) xs...
['def', 'reverse_generator(generator,', 'X_sample,', 'y_sample,', 'title):', 'latent_vec', '=', 'np.random.normal(size=(1,', '100))', 'target', '=', 'K.placeholder()', 'loss', '=', 'K.sum(K.square(generator.outputs[0]', '-', 'target))', 'grad', '=', 'K.gradients(loss,', 'generator.inputs[0])[0]', 'update_fn', '=', 'K.f...
566,525
HikariTJU/LD
positional_encoding.py
SinePositionalEncoding.forward
forward
Forward function for `SinePositionalEncoding`.
[ "Forward", "function", "for", "`SinePositionalEncoding`." ]
def forward(self, mask): not_mask = ~mask y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.normalize: y_embed = y_embed / (y_embed[:, -1:, :] + self.eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1:] + self.eps) * self.sca...
['def', 'forward(self,', 'mask):', 'not_mask', '=', '~mask', 'y_embed', '=', 'not_mask.cumsum(1,', 'dtype=torch.float32)', 'x_embed', '=', 'not_mask.cumsum(2,', 'dtype=torch.float32)', 'if', 'self.normalize:', 'y_embed', '=', 'y_embed', '/', '(y_embed[:,', '-1:,', ':]', '+', 'self.eps)', '*', 'self.scale', 'x_embed', '...
587,613
scikit-learn/scikit-learn
test_bisect_k_means.py
test_float32_float64_equivalence
test_float32_float64_equivalence
Check that the results are the same between float32 and float64.
[ "Check", "that", "the", "results", "are", "the", "same", "between", "float32", "and", "float64." ]
def test_float32_float64_equivalence(csr_container): rng = np.random.RandomState(0) X = rng.rand(10, 2) if csr_container is not None: X[X < 0.8] = 0 X = csr_container(X) km64 = BisectingKMeans(n_clusters=3, random_state=0).fit(X) km32 = BisectingKMeans(n_clusters=3, random_state=0).f...
['def', 'test_float32_float64_equivalence(csr_container):', 'rng', '=', 'np.random.RandomState(0)', 'X', '=', 'rng.rand(10,', '2)', 'if', 'csr_container', 'is', 'not', 'None:', 'X[X', '<', '0.8]', '=', '0', 'X', '=', 'csr_container(X)', 'km64', '=', 'BisectingKMeans(n_clusters=3,', 'random_state=0).fit(X)', 'km32', '='...
852,832
sktime/sktime
test_base.py
test_dynamic_tags_reset_properly
test_dynamic_tags_reset_properly
Test that dynamic tags are being reset properly.
[ "Test", "that", "dynamic", "tags", "are", "being", "reset", "properly." ]
def test_dynamic_tags_reset_properly(): from sktime.forecasting.compose import MultiplexForecaster f = MultiplexForecaster([('foo', ThetaForecaster()), ('var', VAR())]) f.set_params(selected_forecaster='var') X_multivariate = _make_series(n_columns=2) f.fit(X_multivariate)
['def', 'test_dynamic_tags_reset_properly():', 'from', 'sktime.forecasting.compose', 'import', 'MultiplexForecaster', 'f', '=', "MultiplexForecaster([('foo',", 'ThetaForecaster()),', "('var',", 'VAR())])', "f.set_params(selected_forecaster='var')", 'X_multivariate', '=', '_make_series(n_columns=2)', 'f.fit(X_multivaria...
877,139
rudranil723/mini-main
symbol_database.py
SymbolDatabase.RegisterFileDescriptor
RegisterFileDescriptor
Registers the given file descriptor in the local database.
[ "Registers", "the", "given", "file", "descriptor", "in", "the", "local", "database." ]
def RegisterFileDescriptor(self, file_descriptor): if api_implementation.Type() == 'python': self.pool._InternalAddFileDescriptor(file_descriptor)
['def', 'RegisterFileDescriptor(self,', 'file_descriptor):', 'if', 'api_implementation.Type()', '==', "'python':", 'self.pool._InternalAddFileDescriptor(file_descriptor)']
318,310
RasaHQ/rasa
test.py
determine_intersection
determine_intersection
Calculates how many characters a given token and entity share.
[ "Calculates", "how", "many", "characters", "a", "given", "token", "and", "entity", "share." ]
def determine_intersection(token: Token, entity: Dict) -> int: pos_token = set(range(token.start, token.end)) pos_entity = set(range(entity['start'], entity['end'])) return len(pos_token.intersection(pos_entity))
['def', 'determine_intersection(token:', 'Token,', 'entity:', 'Dict)', '->', 'int:', 'pos_token', '=', 'set(range(token.start,', 'token.end))', 'pos_entity', '=', "set(range(entity['start'],", "entity['end']))", 'return', 'len(pos_token.intersection(pos_entity))']
837,118
yoonc5536/computer_vision
label_map_util.py
create_class_agnostic_category_index
create_class_agnostic_category_index
Creates a category index with a single `object` class.
[ "Creates", "a", "category", "index", "with", "a", "single", "`object`", "class." ]
def create_class_agnostic_category_index(): return {1: {'id': 1, 'name': 'object'}}
['def', 'create_class_agnostic_category_index():', 'return', '{1:', "{'id':", '1,', "'name':", "'object'}}"]
512,624
weimin17/Object-Detection_HelmetDetection
variables_helper.py
multiply_gradients_matching_regex
multiply_gradients_matching_regex
Multiply gradients whose variable names match a regular expression.
[ "Multiply", "gradients", "whose", "variable", "names", "match", "a", "regular", "expression." ]
def multiply_gradients_matching_regex(grads_and_vars, regex_list, multiplier): variables = [pair[1] for pair in grads_and_vars] matching_vars = filter_variables(variables, regex_list, invert=True) for var in matching_vars: logging.info('Applying multiplier %f to variable [%s]', multiplier, var.op.na...
['def', 'multiply_gradients_matching_regex(grads_and_vars,', 'regex_list,', 'multiplier):', 'variables', '=', '[pair[1]', 'for', 'pair', 'in', 'grads_and_vars]', 'matching_vars', '=', 'filter_variables(variables,', 'regex_list,', 'invert=True)', 'for', 'var', 'in', 'matching_vars:', "logging.info('Applying", 'multiplie...
751,245