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 |
|---|---|---|---|---|---|---|---|---|
kvfrans/variational-autoencoder | plot.py | make_spread_gif | make_spread_gif | Creates and saves gif from images generated by make_spread(). | [
"Creates",
"and",
"saves",
"gif",
"from",
"images",
"generated",
"by",
"make_spread()."
] | def make_spread_gif():
images = [imread('../figs/spread/' + file) for file in sorted(os.listdir(path='../figs/spread/')) if file != '.gitkeep']
clip = ImageSequenceClip(images, fps=5)
clip.write_gif('../spread.gif') | ['def', 'make_spread_gif():', 'images', '=', "[imread('../figs/spread/'", '+', 'file)', 'for', 'file', 'in', "sorted(os.listdir(path='../figs/spread/'))", 'if', 'file', '!=', "'.gitkeep']", 'clip', '=', 'ImageSequenceClip(images,', 'fps=5)', "clip.write_gif('../spread.gif')"] | 930,911 |
myothida/Supervised-Machine-Learning | arrayTools.py | pointInRect | pointInRect | Test if a point is inside a bounding rectangle. | [
"Test",
"if",
"a",
"point",
"is",
"inside",
"a",
"bounding",
"rectangle."
] | def pointInRect(p, rect):
(x, y) = p
(xMin, yMin, xMax, yMax) = rect
return xMin <= x <= xMax and yMin <= y <= yMax | ['def', 'pointInRect(p,', 'rect):', '(x,', 'y)', '=', 'p', '(xMin,', 'yMin,', 'xMax,', 'yMax)', '=', 'rect', 'return', 'xMin', '<=', 'x', '<=', 'xMax', 'and', 'yMin', '<=', 'y', '<=', 'yMax'] | 360,905 |
tensorflow/privacy | mnist_dpsgd_tutorial_vectorized.py | compute_epsilon | compute_epsilon | Computes epsilon value for given hyperparameters. | [
"Computes",
"epsilon",
"value",
"for",
"given",
"hyperparameters."
] | def compute_epsilon(steps):
if FLAGS.noise_multiplier == 0.0:
return float('inf')
orders = [1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64))
accountant = dp_accounting.rdp.RdpAccountant(orders)
sampling_probability = FLAGS.batch_size / 60000
event = dp_accounting.SelfComposedDpEven... | ['def', 'compute_epsilon(steps):', 'if', 'FLAGS.noise_multiplier', '==', '0.0:', 'return', "float('inf')", 'orders', '=', '[1', '+', 'x', '/', '10.0', 'for', 'x', 'in', 'range(1,', '100)]', '+', 'list(range(12,', '64))', 'accountant', '=', 'dp_accounting.rdp.RdpAccountant(orders)', 'sampling_probability', '=', 'FLAGS.b... | 824,958 |
google-research/scenic | vqa_dataset.py | get_default_dataset_config | get_default_dataset_config | Gets default configs for CC12M dataset. | [
"Gets",
"default",
"configs",
"for",
"CC12M",
"dataset."
] | def get_default_dataset_config(runlocal=False):
dataset_configs = ml_collections.ConfigDict()
dataset_configs.dataset = 'vqa'
dataset_configs.dataset_dir = ''
dataset_configs.train_split = 'train+validation[5000:]'
dataset_configs.question_max_num_tokens = QUESTION_LENGTH
dataset_configs.answer_... | ['def', 'get_default_dataset_config(runlocal=False):', 'dataset_configs', '=', 'ml_collections.ConfigDict()', 'dataset_configs.dataset', '=', "'vqa'", 'dataset_configs.dataset_dir', '=', "''", 'dataset_configs.train_split', '=', "'train+validation[5000:]'", 'dataset_configs.question_max_num_tokens', '=', 'QUESTION_LENG... | 846,818 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | cmd.py | Cmd.cmdloop | cmdloop | Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. | [
"Repeatedly",
"issue",
"a",
"prompt,",
"accept",
"input,",
"parse",
"an",
"initial",
"prefix",
"off",
"the",
"received",
"input,",
"and",
"dispatch",
"to",
"action",
"methods,",
"passing",
"them",
"the",
"remainder",
"of",
"the",
"line",
"as",
"argument."
] | def cmdloop(self, intro=None):
self.preloop()
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey + ': complete')
... | ['def', 'cmdloop(self,', 'intro=None):', 'self.preloop()', 'if', 'self.use_rawinput', 'and', 'self.completekey:', 'try:', 'import', 'readline', 'self.old_completer', '=', 'readline.get_completer()', 'readline.set_completer(self.complete)', 'readline.parse_and_bind(self.completekey', '+', "':", "complete')", 'except', '... | 428,290 |
ldfaiztt/CSE473 | multiAgents.py | MinimaxAgent.MaxMinValue | MaxMinValue | This function calculate greatest(smallest) value pacman(ghost) can get among all the successor states. | [
"This",
"function",
"calculate",
"greatest(smallest)",
"value",
"pacman(ghost)",
"can",
"get",
"among",
"all",
"the",
"successor",
"states."
] | def MaxMinValue(self, gameState, agentIdx, numAgents, depth):
if gameState.isWin() or gameState.isLose() or depth == 0:
return self.evaluationFunction(gameState)
actions = gameState.getLegalActions(agentIdx)
if agentIdx == 0:
if Directions.STOP in actions:
actions.remove(Directio... | ['def', 'MaxMinValue(self,', 'gameState,', 'agentIdx,', 'numAgents,', 'depth):', 'if', 'gameState.isWin()', 'or', 'gameState.isLose()', 'or', 'depth', '==', '0:', 'return', 'self.evaluationFunction(gameState)', 'actions', '=', 'gameState.getLegalActions(agentIdx)', 'if', 'agentIdx', '==', '0:', 'if', 'Directions.STOP',... | 193,169 |
lijian-ml/CS373-Programming-a-Robotic-Car | robot.py | robot.move_in_circle | move_in_circle | This function is used to advance the runaway target bot. | [
"This",
"function",
"is",
"used",
"to",
"advance",
"the",
"runaway",
"target",
"bot."
] | def move_in_circle(self):
self.move(self.turning, self.distance) | ['def', 'move_in_circle(self):', 'self.move(self.turning,', 'self.distance)'] | 228,064 |
GatorEducator/GatorMiner | test_analyzer.py | test_part_of_speech | test_part_of_speech | Test if it return correct part of speech information. | [
"Test",
"if",
"it",
"return",
"correct",
"part",
"of",
"speech",
"information."
] | def test_part_of_speech():
text = 'The greatest technical challenge that I faced was getting the program to run'
output = az.part_of_speech(text)
assert output == [('The', 'DET'), ('greatest', 'ADJ'), ('technical', 'ADJ'), ('challenge', 'NOUN'), ('that', 'DET'), ('I', 'PRON'), ('faced', 'VERB'), ('was', 'AU... | ['def', 'test_part_of_speech():', 'text', '=', "'The", 'greatest', 'technical', 'challenge', 'that', 'I', 'faced', 'was', 'getting', 'the', 'program', 'to', "run'", 'output', '=', 'az.part_of_speech(text)', 'assert', 'output', '==', "[('The',", "'DET'),", "('greatest',", "'ADJ'),", "('technical',", "'ADJ'),", "('challe... | 567,456 |
Speedwagon13/CS-3600-Introduction-to-- | test_pep352.py | UsageTests.raise_fails | raise_fails | Make sure that raising 'object_' triggers a TypeError. | [
"Make",
"sure",
"that",
"raising",
"'object_'",
"triggers",
"a",
"TypeError."
] | def raise_fails(self, object_):
try:
raise object_
except TypeError:
return
self.fail('TypeError expected for raising %s' % type(object_)) | ['def', 'raise_fails(self,', 'object_):', 'try:', 'raise', 'object_', 'except', 'TypeError:', 'return', "self.fail('TypeError", 'expected', 'for', 'raising', "%s'", '%', 'type(object_))'] | 219,630 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_multivariate.py | TestInvwishart.test_logpdf_4x4 | test_logpdf_4x4 | Regression test for gh-8844. | [
"Regression",
"test",
"for",
"gh-8844."
] | def test_logpdf_4x4(self):
X = np.array([[2, 1, 0, 0.5], [1, 2, 0.5, 0.5], [0, 0.5, 3, 1], [0.5, 0.5, 1, 2]])
Psi = np.array([[9, 7, 3, 1], [7, 9, 5, 1], [3, 5, 8, 2], [1, 1, 2, 9]])
nu = 6
prob = invwishart.logpdf(X, nu, Psi)
p = X.shape[0]
(sig, logdetX) = np.linalg.slogdet(X)
(sig, logdet... | ['def', 'test_logpdf_4x4(self):', 'X', '=', 'np.array([[2,', '1,', '0,', '0.5],', '[1,', '2,', '0.5,', '0.5],', '[0,', '0.5,', '3,', '1],', '[0.5,', '0.5,', '1,', '2]])', 'Psi', '=', 'np.array([[9,', '7,', '3,', '1],', '[7,', '9,', '5,', '1],', '[3,', '5,', '8,', '2],', '[1,', '1,', '2,', '9]])', 'nu', '=', '6', 'prob'... | 100,316 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | core.py | simplify | simplify | Simplifies a polygon to minimize the polygon's vertices. | [
"Simplifies",
"a",
"polygon",
"to",
"minimize",
"the",
"polygon's",
"vertices."
] | def simplify(polygon, eps):
assert 0 <= eps <= 1, 'approximation accuracy is percentage in [0, 1]'
epsilon = eps * cv2.arcLength(polygon, closed=True)
return cv2.approxPolyDP(polygon, epsilon=epsilon, closed=True) | ['def', 'simplify(polygon,', 'eps):', 'assert', '0', '<=', 'eps', '<=', '1,', "'approximation", 'accuracy', 'is', 'percentage', 'in', '[0,', "1]'", 'epsilon', '=', 'eps', '*', 'cv2.arcLength(polygon,', 'closed=True)', 'return', 'cv2.approxPolyDP(polygon,', 'epsilon=epsilon,', 'closed=True)'] | 12,056 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | common.py | is_true_slices | is_true_slices | Find non-trivial slices in "line": return a list of booleans with same length. | [
"Find",
"non-trivial",
"slices",
"in",
"\"line\":",
"return",
"a",
"list",
"of",
"booleans",
"with",
"same",
"length."
] | def is_true_slices(line):
return [isinstance(k, slice) and (not is_null_slice(k)) for k in line] | ['def', 'is_true_slices(line):', 'return', '[isinstance(k,', 'slice)', 'and', '(not', 'is_null_slice(k))', 'for', 'k', 'in', 'line]'] | 452,579 |
pfnet/pfrl | copy_param.py | soft_copy_param | soft_copy_param | Soft-copy parameters of a link to another link. | [
"Soft-copy",
"parameters",
"of",
"a",
"link",
"to",
"another",
"link."
] | def soft_copy_param(target_link, source_link, tau):
target_dict = target_link.state_dict()
source_dict = source_link.state_dict()
for (k, target_value) in target_dict.items():
source_value = source_dict[k]
if source_value.dtype in [torch.float32, torch.float64, torch.float16]:
as... | ['def', 'soft_copy_param(target_link,', 'source_link,', 'tau):', 'target_dict', '=', 'target_link.state_dict()', 'source_dict', '=', 'source_link.state_dict()', 'for', '(k,', 'target_value)', 'in', 'target_dict.items():', 'source_value', '=', 'source_dict[k]', 'if', 'source_value.dtype', 'in', '[torch.float32,', 'torch... | 304,826 |
RasaHQ/rasa_core | agent.py | Agent.create_processor | create_processor | Instantiates a processor based on the set state of the agent. | [
"Instantiates",
"a",
"processor",
"based",
"on",
"the",
"set",
"state",
"of",
"the",
"agent."
] | def create_processor(self, preprocessor: Optional[Callable[[Text], Text]]=None) -> MessageProcessor:
self._ensure_agent_is_ready()
return MessageProcessor(self.interpreter, self.policy_ensemble, self.domain, self.tracker_store, self.nlg, action_endpoint=self.action_endpoint, message_preprocessor=preprocessor) | ['def', 'create_processor(self,', 'preprocessor:', 'Optional[Callable[[Text],', 'Text]]=None)', '->', 'MessageProcessor:', 'self._ensure_agent_is_ready()', 'return', 'MessageProcessor(self.interpreter,', 'self.policy_ensemble,', 'self.domain,', 'self.tracker_store,', 'self.nlg,', 'action_endpoint=self.action_endpoint,'... | 838,154 |
microsoft/maro | item_meta.py | BinaryMeta.time_zone | time_zone | Time zone of this meta, used to correct timestamp. | [
"Time",
"zone",
"of",
"this",
"meta,",
"used",
"to",
"correct",
"timestamp."
] | def time_zone(self):
return self._tzone | ['def', 'time_zone(self):', 'return', 'self._tzone'] | 628,394 |
salesforce/CodeRL | tokenization_xlm_roberta.py | XLMRobertaTokenizer.convert_tokens_to_string | convert_tokens_to_string | Converts a sequence of tokens (strings for sub-words) in a single string. | [
"Converts",
"a",
"sequence",
"of",
"tokens",
"(strings",
"for",
"sub-words)",
"in",
"a",
"single",
"string."
] | def convert_tokens_to_string(self, tokens):
out_string = ''.join(tokens).replace(SPIECE_UNDERLINE, ' ').strip()
return out_string | ['def', 'convert_tokens_to_string(self,', 'tokens):', 'out_string', '=', "''.join(tokens).replace(SPIECE_UNDERLINE,", "'", "').strip()", 'return', 'out_string'] | 495,495 |
Wuziyi616/Artificial_Intelligence_Project1 | search_algorithm.py | Mask.connectivity_area_is_valid | connectivity_area_is_valid | The connectivity areas should have areas == 4 or 5. | [
"The",
"connectivity",
"areas",
"should",
"have",
"areas",
"==",
"4",
"or",
"5."
] | def connectivity_area_is_valid(self, element):
grid = copy.deepcopy(self.grid)
for i in range(element.area):
grid[element.coordinates[i][0], element.coordinates[i][1]] = 255
mask = np.zeros_like(grid, dtype=np.uint8)
mask[grid == 0] = 255
connectivity = skimage.measure.label(mask, connectivi... | ['def', 'connectivity_area_is_valid(self,', 'element):', 'grid', '=', 'copy.deepcopy(self.grid)', 'for', 'i', 'in', 'range(element.area):', 'grid[element.coordinates[i][0],', 'element.coordinates[i][1]]', '=', '255', 'mask', '=', 'np.zeros_like(grid,', 'dtype=np.uint8)', 'mask[grid', '==', '0]', '=', '255', 'connectivi... | 92,196 |
weimin17/Object-Detection_HelmetDetection | astro_model_test.py | AstroModelTest.assertShapeEquals | assertShapeEquals | Asserts that a Tensor or Numpy array has the expected shape. | [
"Asserts",
"that",
"a",
"Tensor",
"or",
"Numpy",
"array",
"has",
"the",
"expected",
"shape."
] | def assertShapeEquals(self, shape, tensor_or_array):
if isinstance(tensor_or_array, (np.ndarray, np.generic)):
self.assertAllEqual(shape, tensor_or_array.shape)
elif isinstance(tensor_or_array, (tf.Tensor, tf.Variable)):
self.assertAllEqual(shape, tensor_or_array.shape.as_list())
else:
... | ['def', 'assertShapeEquals(self,', 'shape,', 'tensor_or_array):', 'if', 'isinstance(tensor_or_array,', '(np.ndarray,', 'np.generic)):', 'self.assertAllEqual(shape,', 'tensor_or_array.shape)', 'elif', 'isinstance(tensor_or_array,', '(tf.Tensor,', 'tf.Variable)):', 'self.assertAllEqual(shape,', 'tensor_or_array.shape.as_... | 749,023 |
rudranil723/mini-main | test_arraypad.py | TestWrap.test_repeated_wrapping | test_repeated_wrapping | Check wrapping on each side individually if the wrapped area is longer than the original array. | [
"Check",
"wrapping",
"on",
"each",
"side",
"individually",
"if",
"the",
"wrapped",
"area",
"is",
"longer",
"than",
"the",
"original",
"array."
] | def test_repeated_wrapping(self):
a = np.arange(5)
b = np.pad(a, (12, 0), mode='wrap')
assert_array_equal(np.r_[a, a, a, a][3:], b)
a = np.arange(5)
b = np.pad(a, (0, 12), mode='wrap')
assert_array_equal(np.r_[a, a, a, a][:-3], b) | ['def', 'test_repeated_wrapping(self):', 'a', '=', 'np.arange(5)', 'b', '=', 'np.pad(a,', '(12,', '0),', "mode='wrap')", 'assert_array_equal(np.r_[a,', 'a,', 'a,', 'a][3:],', 'b)', 'a', '=', 'np.arange(5)', 'b', '=', 'np.pad(a,', '(0,', '12),', "mode='wrap')", 'assert_array_equal(np.r_[a,', 'a,', 'a,', 'a][:-3],', 'b)'... | 322,786 |
alteryx/compose | extension.py | DataSliceContext.count | count | Alias for the data slice number. | [
"Alias",
"for",
"the",
"data",
"slice",
"number."
] | def count(self):
return self.slice_number | ['def', 'count(self):', 'return', 'self.slice_number'] | 136,035 |
lululxvi/deepxde | geometry.py | Geometry.uniform_boundary_points | uniform_boundary_points | Compute the equispaced point locations on the boundary. | [
"Compute",
"the",
"equispaced",
"point",
"locations",
"on",
"the",
"boundary."
] | def uniform_boundary_points(self, n):
print('Warning: {}.uniform_boundary_points not implemented. Use random_boundary_points instead.'.format(self.idstr))
return self.random_boundary_points(n) | ['def', 'uniform_boundary_points(self,', 'n):', "print('Warning:", '{}.uniform_boundary_points', 'not', 'implemented.', 'Use', 'random_boundary_points', "instead.'.format(self.idstr))", 'return', 'self.random_boundary_points(n)'] | 536,230 |
shenyunhang/PDSL | events.py | EventStorage.name_scope | name_scope | Yields: A context within which all the events added to this storage will be prefixed by the name scope. | [
"Yields:",
"A",
"context",
"within",
"which",
"all",
"the",
"events",
"added",
"to",
"this",
"storage",
"will",
"be",
"prefixed",
"by",
"the",
"name",
"scope."
] | def name_scope(self, name):
old_prefix = self._current_prefix
self._current_prefix = name.rstrip('/') + '/'
yield
self._current_prefix = old_prefix | ['def', 'name_scope(self,', 'name):', 'old_prefix', '=', 'self._current_prefix', 'self._current_prefix', '=', "name.rstrip('/')", '+', "'/'", 'yield', 'self._current_prefix', '=', 'old_prefix'] | 279,240 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | application.py | Application.emit_options_help | emit_options_help | Yield the lines for the options part of the help. | [
"Yield",
"the",
"lines",
"for",
"the",
"options",
"part",
"of",
"the",
"help."
] | def emit_options_help(self):
if not self.flags and (not self.aliases):
return
header = 'Options'
yield header
yield ('=' * len(header))
for p in wrap_paragraphs(self.option_description):
yield p
yield ''
for l in self.emit_flag_help():
yield l
for l in self.em... | ['def', 'emit_options_help(self):', 'if', 'not', 'self.flags', 'and', '(not', 'self.aliases):', 'return', 'header', '=', "'Options'", 'yield', 'header', 'yield', "('='", '*', 'len(header))', 'for', 'p', 'in', 'wrap_paragraphs(self.option_description):', 'yield', 'p', 'yield', "''", 'for', 'l', 'in', 'self.emit_flag_hel... | 437,882 |
jiga5633/Natural-Language-Processing | Spell_checker.py | Spell_Checker.Language_Model.build_model | build_model | Populates the instance variable model_dict. | [
"Populates",
"the",
"instance",
"variable",
"model_dict."
] | def build_model(self, text):
normalized_text = normalize_text(text)
self.model_dict = {}
if not self.chars:
str_parts = normalized_text.split()
else:
str_parts = [char for char in normalized_text]
self.WORDS = self.build_word_vocabulary(str_parts) if not self.chars else self.build_wo... | ['def', 'build_model(self,', 'text):', 'normalized_text', '=', 'normalize_text(text)', 'self.model_dict', '=', '{}', 'if', 'not', 'self.chars:', 'str_parts', '=', 'normalized_text.split()', 'else:', 'str_parts', '=', '[char', 'for', 'char', 'in', 'normalized_text]', 'self.WORDS', '=', 'self.build_word_vocabulary(str_pa... | 707,082 |
ryu-ed/SpaceInvaders_Ros | autodist.py | check_inline | check_inline | Return the inline identifier (may be empty). | [
"Return",
"the",
"inline",
"identifier",
"(may",
"be",
"empty)."
] | def check_inline(cmd):
cmd._check_compiler()
body = textwrap.dedent('\n #ifndef __cplusplus\n static %(inline)s int static_func (void)\n {\n return 0;\n }\n %(inline)s int nostatic_func (void)\n {\n return 0;\n }\n #endif')
for kw... | ['def', 'check_inline(cmd):', 'cmd._check_compiler()', 'body', '=', "textwrap.dedent('\\n", '#ifndef', '__cplusplus\\n', 'static', '%(inline)s', 'int', 'static_func', '(void)\\n', '{\\n', 'return', '0;\\n', '}\\n', '%(inline)s', 'int', 'nostatic_func', '(void)\\n', '{\\n', 'return', '0;\\n', '}\\n', "#endif')", 'for', ... | 396,521 |
openvinotoolkit/training_extensions | basic_operations.py | recall_per_class | recall_per_class | Compute the recall per class based on the confusion matrix. | [
"Compute",
"the",
"recall",
"per",
"class",
"based",
"on",
"the",
"confusion",
"matrix."
] | def recall_per_class(matrix: np.ndarray) -> np.ndarray:
tp_per_class = matrix.diagonal()
sum_tp_fn_per_class = matrix.sum(1)
return divide_arrays_with_possible_zeros(tp_per_class, sum_tp_fn_per_class) | ['def', 'recall_per_class(matrix:', 'np.ndarray)', '->', 'np.ndarray:', 'tp_per_class', '=', 'matrix.diagonal()', 'sum_tp_fn_per_class', '=', 'matrix.sum(1)', 'return', 'divide_arrays_with_possible_zeros(tp_per_class,', 'sum_tp_fn_per_class)'] | 918,743 |
greydanus/pythonic_ocr | html.py | data | data | Return the contents of a data file of ours. | [
"Return",
"the",
"contents",
"of",
"a",
"data",
"file",
"of",
"ours."
] | def data(fname):
with open(data_filename(fname)) as data_file:
return data_file.read() | ['def', 'data(fname):', 'with', 'open(data_filename(fname))', 'as', 'data_file:', 'return', 'data_file.read()'] | 298,920 |
microsoft/maro | cim_data_dump.py | CimDataDumpUtil.dump | dump | Dump cim data into specified folder. | [
"Dump",
"cim",
"data",
"into",
"specified",
"folder."
] | def dump(self, output_folder: str):
vessel_idx2name_dict = {idx: name for (name, idx) in self._data_collection.vessel_mapping.items()}
port_idx2name_dict = {idx: name for (name, idx) in self._data_collection.port_mapping.items()}
route_idx2name_dict = {idx: name for (name, idx) in self._data_collection.rout... | ['def', 'dump(self,', 'output_folder:', 'str):', 'vessel_idx2name_dict', '=', '{idx:', 'name', 'for', '(name,', 'idx)', 'in', 'self._data_collection.vessel_mapping.items()}', 'port_idx2name_dict', '=', '{idx:', 'name', 'for', '(name,', 'idx)', 'in', 'self._data_collection.port_mapping.items()}', 'route_idx2name_dict', ... | 628,431 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tf_utils.py | dense_resample | dense_resample | Resample reward at particular locations. | [
"Resample",
"reward",
"at",
"particular",
"locations."
] | def dense_resample(im, flow_im, output_valid_mask, name='dense_resample'):
with tf.name_scope(name):
valid_mask = None
(x, y) = tf.unstack(flow_im, axis=-1)
x = tf.cast(tf.reshape(x, [-1]), tf.float32)
y = tf.cast(tf.reshape(y, [-1]), tf.float32)
shape = tf.unstack(tf.shape(i... | ['def', 'dense_resample(im,', 'flow_im,', 'output_valid_mask,', "name='dense_resample'):", 'with', 'tf.name_scope(name):', 'valid_mask', '=', 'None', '(x,', 'y)', '=', 'tf.unstack(flow_im,', 'axis=-1)', 'x', '=', 'tf.cast(tf.reshape(x,', '[-1]),', 'tf.float32)', 'y', '=', 'tf.cast(tf.reshape(y,', '[-1]),', 'tf.float32)... | 47,357 |
PaddlePaddle/PaddleSpeech | infer.py | SSLExecutor.postprocess | postprocess | Output postprocess and return human-readable results such as texts and audio files. | [
"Output",
"postprocess",
"and",
"return",
"human-readable",
"results",
"such",
"as",
"texts",
"and",
"audio",
"files."
] | def postprocess(self) -> Union[str, os.PathLike]:
return self._outputs['result'] | ['def', 'postprocess(self)', '->', 'Union[str,', 'os.PathLike]:', 'return', "self._outputs['result']"] | 276,540 |
yinguobing/cnn-facial-landmark | pose_estimator.py | PoseEstimator.solve_pose_by_68_points | solve_pose_by_68_points | Solve pose from all the 68 image points Return (rotation_vector, translation_vector) as pose. | [
"Solve",
"pose",
"from",
"all",
"the",
"68",
"image",
"points",
"Return",
"(rotation_vector,",
"translation_vector)",
"as",
"pose."
] | def solve_pose_by_68_points(self, image_points):
if self.r_vec is None:
(_, rotation_vector, translation_vector) = cv2.solvePnP(self.model_points_68, image_points, self.camera_matrix, self.dist_coeefs)
self.r_vec = rotation_vector
self.t_vec = translation_vector
(_, rotation_vector, tran... | ['def', 'solve_pose_by_68_points(self,', 'image_points):', 'if', 'self.r_vec', 'is', 'None:', '(_,', 'rotation_vector,', 'translation_vector)', '=', 'cv2.solvePnP(self.model_points_68,', 'image_points,', 'self.camera_matrix,', 'self.dist_coeefs)', 'self.r_vec', '=', 'rotation_vector', 'self.t_vec', '=', 'translation_ve... | 123,577 |
Eric3911/OpenAGI | t5_dataset.py | T5Dataset.pad_and_convert_to_numpy | pad_and_convert_to_numpy | Pad sequences and convert them to numpy. | [
"Pad",
"sequences",
"and",
"convert",
"them",
"to",
"numpy."
] | def pad_and_convert_to_numpy(cls, output_tokens, masked_positions, masked_labels, sentinel_tokens, bos_id, eos_id, pad_id, max_seq_length, max_seq_length_dec, masked_spans=None):
sentinel_tokens = collections.deque(sentinel_tokens)
t5_input = []
(t5_decoder_in, t5_decoder_out) = ([bos_id], [])
(start_in... | ['def', 'pad_and_convert_to_numpy(cls,', 'output_tokens,', 'masked_positions,', 'masked_labels,', 'sentinel_tokens,', 'bos_id,', 'eos_id,', 'pad_id,', 'max_seq_length,', 'max_seq_length_dec,', 'masked_spans=None):', 'sentinel_tokens', '=', 'collections.deque(sentinel_tokens)', 't5_input', '=', '[]', '(t5_decoder_in,', ... | 273,318 |
open-mmlab/mmselfsup | test_svm.py | get_chosen_costs | get_chosen_costs | get the chosen cost that maximizes the cross-validation AP per class. | [
"get",
"the",
"chosen",
"cost",
"that",
"maximizes",
"the",
"cross-validation",
"AP",
"per",
"class."
] | def get_chosen_costs(opts, num_classes):
costs_list = svm_helper.parse_cost_list(opts.costs_list)
train_ap_matrix = np.zeros((num_classes, len(costs_list)))
for cls in range(num_classes):
for cost_idx in range(len(costs_list)):
cost = costs_list[cost_idx]
(_, ap_out_file) = s... | ['def', 'get_chosen_costs(opts,', 'num_classes):', 'costs_list', '=', 'svm_helper.parse_cost_list(opts.costs_list)', 'train_ap_matrix', '=', 'np.zeros((num_classes,', 'len(costs_list)))', 'for', 'cls', 'in', 'range(num_classes):', 'for', 'cost_idx', 'in', 'range(len(costs_list)):', 'cost', '=', 'costs_list[cost_idx]', ... | 240,531 |
triaquae/triaquae | tests.py | AdminSeleniumWebDriverTestCase.wait_page_loaded | wait_page_loaded | Block until page has started to load. | [
"Block",
"until",
"page",
"has",
"started",
"to",
"load."
] | def wait_page_loaded(self):
from selenium.common.exceptions import TimeoutException
try:
self.wait_loaded_tag('body')
except TimeoutException:
pass | ['def', 'wait_page_loaded(self):', 'from', 'selenium.common.exceptions', 'import', 'TimeoutException', 'try:', "self.wait_loaded_tag('body')", 'except', 'TimeoutException:', 'pass'] | 357,006 |
utiasASRL/hero_radar_odometry | oxford.py | OxfordDataset.get_frames_with_gt | get_frames_with_gt | Retrieves the subset of frames that have groundtruth Note: For the Oxford Dataset we do a search from the end backwards because some of the sequences don't have GT as the end, but they all have GT at the beginning. | [
"Retrieves",
"the",
"subset",
"of",
"frames",
"that",
"have",
"groundtruth",
"Note:",
"For",
"the",
"Oxford",
"Dataset",
"we",
"do",
"a",
"search",
"from",
"the",
"end",
"backwards",
"because",
"some",
"of",
"the",
"sequences",
"don't",
"have",
"GT",
"as",
... | def get_frames_with_gt(self, frames, gt_path):
def check_if_frame_has_gt(frame, gt_lines):
for i in range(len(gt_lines) - 1, -1, -1):
line = gt_lines[i].split(',')
if frame == int(line[9]):
return True
return False
frames_out = frames
with open(gt_pat... | ['def', 'get_frames_with_gt(self,', 'frames,', 'gt_path):', 'def', 'check_if_frame_has_gt(frame,', 'gt_lines):', 'for', 'i', 'in', 'range(len(gt_lines)', '-', '1,', '-1,', '-1):', 'line', '=', "gt_lines[i].split(',')", 'if', 'frame', '==', 'int(line[9]):', 'return', 'True', 'return', 'False', 'frames_out', '=', 'frames... | 205,930 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | win.py | valuestodict | valuestodict | Convert a registry key's values to a dictionary. | [
"Convert",
"a",
"registry",
"key's",
"values",
"to",
"a",
"dictionary."
] | def valuestodict(key):
dout = {}
size = winreg.QueryInfoKey(key)[1]
tz_res = None
for i in range(size):
(key_name, value, dtype) = winreg.EnumValue(key, i)
if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
if value & 1 << 31:
value = val... | ['def', 'valuestodict(key):', 'dout', '=', '{}', 'size', '=', 'winreg.QueryInfoKey(key)[1]', 'tz_res', '=', 'None', 'for', 'i', 'in', 'range(size):', '(key_name,', 'value,', 'dtype)', '=', 'winreg.EnumValue(key,', 'i)', 'if', 'dtype', '==', 'winreg.REG_DWORD', 'or', 'dtype', '==', 'winreg.REG_DWORD_LITTLE_ENDIAN:', 'if... | 447,743 |
Eric3911/OpenAGI | optimization_utils.py | linear_sum_assignment | linear_sum_assignment | Launch the linear sum assignment algorithm on a cost matrix. | [
"Launch",
"the",
"linear",
"sum",
"assignment",
"algorithm",
"on",
"a",
"cost",
"matrix."
] | def linear_sum_assignment(cost_matrix: torch.Tensor, max_size: int=100):
cost_matrix = cost_matrix.clone().detach()
if len(cost_matrix.shape) != 2:
raise ValueError(f'2-d tensor is expected but got a {cost_matrix.shape} tensor')
if max(cost_matrix.shape) > max_size:
raise ValueError(f'Cost m... | ['def', 'linear_sum_assignment(cost_matrix:', 'torch.Tensor,', 'max_size:', 'int=100):', 'cost_matrix', '=', 'cost_matrix.clone().detach()', 'if', 'len(cost_matrix.shape)', '!=', '2:', 'raise', "ValueError(f'2-d", 'tensor', 'is', 'expected', 'but', 'got', 'a', '{cost_matrix.shape}', "tensor')", 'if', 'max(cost_matrix.s... | 272,969 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | analysis.py | logmgf_from_counts | logmgf_from_counts | ReportNoisyMax mechanism with noise_eps with 2*noise_eps-DP in our setting where one count can go up by one and another can go down by 1. | [
"ReportNoisyMax",
"mechanism",
"with",
"noise_eps",
"with",
"2*noise_eps-DP",
"in",
"our",
"setting",
"where",
"one",
"count",
"can",
"go",
"up",
"by",
"one",
"and",
"another",
"can",
"go",
"down",
"by",
"1."
] | def logmgf_from_counts(counts, noise_eps, l):
q = compute_q_noisy_max(counts, noise_eps)
return logmgf_exact(q, 2.0 * noise_eps, l) | ['def', 'logmgf_from_counts(counts,', 'noise_eps,', 'l):', 'q', '=', 'compute_q_noisy_max(counts,', 'noise_eps)', 'return', 'logmgf_exact(q,', '2.0', '*', 'noise_eps,', 'l)'] | 47,666 |
wuga214/Boundary-Detection-via-Convolution-Deconvolution--Network-with-BMA | theano_backend.py | variable | variable | Instantiate a tensor variable. | [
"Instantiate",
"a",
"tensor",
"variable."
] | def variable(value, dtype=_FLOATX, name=None):
value = np.asarray(value, dtype=dtype)
return theano.shared(value=value, name=name, strict=False) | ['def', 'variable(value,', 'dtype=_FLOATX,', 'name=None):', 'value', '=', 'np.asarray(value,', 'dtype=dtype)', 'return', 'theano.shared(value=value,', 'name=name,', 'strict=False)'] | 107,919 |
srai-lab/srai | test_count_embedder.py | test_correct_embedding | test_correct_embedding | Test if CountEmbedder returns correct result with different parameters. | [
"Test",
"if",
"CountEmbedder",
"returns",
"correct",
"result",
"with",
"different",
"parameters."
] | def test_correct_embedding(regions_fixture: str, features_fixture: str, joint_fixture: str, expected_embedding_fixture: str, count_subcategories: bool, expected_features_fixture: Union[str, None], request: Any) -> None:
expected_output_features = None if expected_features_fixture is None else request.getfixturevalu... | ['def', 'test_correct_embedding(regions_fixture:', 'str,', 'features_fixture:', 'str,', 'joint_fixture:', 'str,', 'expected_embedding_fixture:', 'str,', 'count_subcategories:', 'bool,', 'expected_features_fixture:', 'Union[str,', 'None],', 'request:', 'Any)', '->', 'None:', 'expected_output_features', '=', 'None', 'if'... | 371,960 |
flavioschneider/rl-transfer- | _functions.py | stack_tensor_dict_list | stack_tensor_dict_list | Stack a list of dictionaries of {tensors or dictionary of tensors}. | [
"Stack",
"a",
"list",
"of",
"dictionaries",
"of",
"{tensors",
"or",
"dictionary",
"of",
"tensors}."
] | def stack_tensor_dict_list(tensor_dict_list):
keys = list(tensor_dict_list[0].keys())
ret = dict()
for k in keys:
example = tensor_dict_list[0][k]
dict_list = [x[k] if k in x else [] for x in tensor_dict_list]
if isinstance(example, dict):
v = stack_tensor_dict_list(dict_... | ['def', 'stack_tensor_dict_list(tensor_dict_list):', 'keys', '=', 'list(tensor_dict_list[0].keys())', 'ret', '=', 'dict()', 'for', 'k', 'in', 'keys:', 'example', '=', 'tensor_dict_list[0][k]', 'dict_list', '=', '[x[k]', 'if', 'k', 'in', 'x', 'else', '[]', 'for', 'x', 'in', 'tensor_dict_list]', 'if', 'isinstance(example... | 861,184 |
ChenhongyiYang/PPAL | region_assigner.py | anchor_ctr_inside_region_flags | anchor_ctr_inside_region_flags | Get the flag indicate whether anchor centers are inside regions. | [
"Get",
"the",
"flag",
"indicate",
"whether",
"anchor",
"centers",
"are",
"inside",
"regions."
] | def anchor_ctr_inside_region_flags(anchors, stride, region):
(x1, y1, x2, y2) = region
f_anchors = anchors / stride
x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5
y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5
flags = (x >= x1) & (x <= x2) & (y >= y1) & (y <= y2)
return flags | ['def', 'anchor_ctr_inside_region_flags(anchors,', 'stride,', 'region):', '(x1,', 'y1,', 'x2,', 'y2)', '=', 'region', 'f_anchors', '=', 'anchors', '/', 'stride', 'x', '=', '(f_anchors[:,', '0]', '+', 'f_anchors[:,', '2])', '*', '0.5', 'y', '=', '(f_anchors[:,', '1]', '+', 'f_anchors[:,', '3])', '*', '0.5', 'flags', '='... | 821,237 |
brendanm12345/imageSequenceGeneration | logging.py | add_handler | add_handler | adds a handler to the HuggingFace Diffusers' root logger. | [
"adds",
"a",
"handler",
"to",
"the",
"HuggingFace",
"Diffusers'",
"root",
"logger."
] | def add_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler) | ['def', 'add_handler(handler:', 'logging.Handler)', '->', 'None:', '_configure_library_root_logger()', 'assert', 'handler', 'is', 'not', 'None', '_get_library_root_logger().addHandler(handler)'] | 599,915 |
rudranil723/mini-main | _normalize.py | convert_to_line_delimits | convert_to_line_delimits | Helper function that converts JSON lists to line delimited JSON. | [
"Helper",
"function",
"that",
"converts",
"JSON",
"lists",
"to",
"line",
"delimited",
"JSON."
] | def convert_to_line_delimits(s: str) -> str:
if not s[0] == '[' and s[-1] == ']':
return s
s = s[1:-1]
return convert_json_to_lines(s) | ['def', 'convert_to_line_delimits(s:', 'str)', '->', 'str:', 'if', 'not', 's[0]', '==', "'['", 'and', 's[-1]', '==', "']':", 'return', 's', 's', '=', 's[1:-1]', 'return', 'convert_json_to_lines(s)'] | 267,302 |
zihuitang/medical_AI_platform | autoexpand.py | AutoExpand.getwords | getwords | Return a list of words that match the prefix before the cursor. | [
"Return",
"a",
"list",
"of",
"words",
"that",
"match",
"the",
"prefix",
"before",
"the",
"cursor."
] | def getwords(self):
word = self.getprevword()
if not word:
return []
before = self.text.get('1.0', 'insert wordstart')
wbefore = re.findall('\\b' + word + '\\w+\\b', before)
del before
after = self.text.get('insert wordend', 'end')
wafter = re.findall('\\b' + word + '\\w+\\b', after)... | ['def', 'getwords(self):', 'word', '=', 'self.getprevword()', 'if', 'not', 'word:', 'return', '[]', 'before', '=', "self.text.get('1.0',", "'insert", "wordstart')", 'wbefore', '=', "re.findall('\\\\b'", '+', 'word', '+', "'\\\\w+\\\\b',", 'before)', 'del', 'before', 'after', '=', "self.text.get('insert", "wordend',", "... | 282,680 |
dmcnamee/FlexModEHC | utils.py | cart2pol | cart2pol | Convert from cartesian to polar coordinates (uses radians). | [
"Convert",
"from",
"cartesian",
"to",
"polar",
"coordinates",
"(uses",
"radians)."
] | def cart2pol(x, y):
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x)
return (rho, phi) | ['def', 'cart2pol(x,', 'y):', 'rho', '=', 'np.sqrt(x', '**', '2', '+', 'y', '**', '2)', 'phi', '=', 'np.arctan2(y,', 'x)', 'return', '(rho,', 'phi)'] | 585,263 |
rlpy/rlpy | LSPI.py | LSPI.store_samples | store_samples | Process one transition instance. | [
"Process",
"one",
"transition",
"instance."
] | def store_samples(self, s, a, r, ns, na, terminal):
if self.fixedRep:
if terminal:
phi_s = self.representation.phi(s, False)
phi_s_a = self.representation.phi_sa(s, False, a, phi_s=phi_s)
elif self.use_sparse:
phi_s = self.all_phi_ns[self.samples_count - 1, :].tod... | ['def', 'store_samples(self,', 's,', 'a,', 'r,', 'ns,', 'na,', 'terminal):', 'if', 'self.fixedRep:', 'if', 'terminal:', 'phi_s', '=', 'self.representation.phi(s,', 'False)', 'phi_s_a', '=', 'self.representation.phi_sa(s,', 'False,', 'a,', 'phi_s=phi_s)', 'elif', 'self.use_sparse:', 'phi_s', '=', 'self.all_phi_ns[self.s... | 333,739 |
matsu0228/nlp-jp | storage_uri.py | BucketStorageUri.set_xml_acl | set_xml_acl | Sets or updates a bucket's ACL with an XML string. | [
"Sets",
"or",
"updates",
"a",
"bucket's",
"ACL",
"with",
"an",
"XML",
"string."
] | def set_xml_acl(self, xmlstring, key_name='', validate=False, headers=None, version_id=None, if_generation=None, if_metageneration=None):
self._check_bucket_uri('set_xml_acl')
key_name = key_name or self.object_name or ''
bucket = self.get_bucket(validate, headers)
if self.generation:
bucket.set... | ['def', 'set_xml_acl(self,', 'xmlstring,', "key_name='',", 'validate=False,', 'headers=None,', 'version_id=None,', 'if_generation=None,', 'if_metageneration=None):', "self._check_bucket_uri('set_xml_acl')", 'key_name', '=', 'key_name', 'or', 'self.object_name', 'or', "''", 'bucket', '=', 'self.get_bucket(validate,', 'h... | 783,889 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | fairseq_dataset.py | FairseqDataset.supports_prefetch | supports_prefetch | Whether this dataset supports prefetching. | [
"Whether",
"this",
"dataset",
"supports",
"prefetching."
] | def supports_prefetch(self):
return False | ['def', 'supports_prefetch(self):', 'return', 'False'] | 103,622 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_glm.py | test_glm_fit_intercept_argument | test_glm_fit_intercept_argument | Test GLM for invalid fit_intercept argument. | [
"Test",
"GLM",
"for",
"invalid",
"fit_intercept",
"argument."
] | def test_glm_fit_intercept_argument(fit_intercept):
y = np.array([1, 2])
X = np.array([[1], [1]])
glm = GeneralizedLinearRegressor(fit_intercept=fit_intercept)
with pytest.raises(ValueError, match='fit_intercept must be bool'):
glm.fit(X, y) | ['def', 'test_glm_fit_intercept_argument(fit_intercept):', 'y', '=', 'np.array([1,', '2])', 'X', '=', 'np.array([[1],', '[1]])', 'glm', '=', 'GeneralizedLinearRegressor(fit_intercept=fit_intercept)', 'with', 'pytest.raises(ValueError,', "match='fit_intercept", 'must', 'be', "bool'):", 'glm.fit(X,', 'y)'] | 437,094 |
apletea/Computer-Vision | keras_darknet19.py | darknet_body | darknet_body | Generate first 18 conv layers of Darknet-19. | [
"Generate",
"first",
"18",
"conv",
"layers",
"of",
"Darknet-19."
] | def darknet_body():
return compose(DarknetConv2D_BN_Leaky(32, (3, 3)), MaxPooling2D(), DarknetConv2D_BN_Leaky(64, (3, 3)), MaxPooling2D(), bottleneck_block(128, 64), MaxPooling2D(), bottleneck_block(256, 128), MaxPooling2D(), bottleneck_x2_block(512, 256), MaxPooling2D(), bottleneck_x2_block(1024, 512)) | ['def', 'darknet_body():', 'return', 'compose(DarknetConv2D_BN_Leaky(32,', '(3,', '3)),', 'MaxPooling2D(),', 'DarknetConv2D_BN_Leaky(64,', '(3,', '3)),', 'MaxPooling2D(),', 'bottleneck_block(128,', '64),', 'MaxPooling2D(),', 'bottleneck_block(256,', '128),', 'MaxPooling2D(),', 'bottleneck_x2_block(512,', '256),', 'MaxP... | 469,974 |
myothida/Supervised-Machine-Learning | common.py | get_rename_function | get_rename_function | Returns a function that will map names/labels, dependent if mapper is a dict, Series or just a function. | [
"Returns",
"a",
"function",
"that",
"will",
"map",
"names/labels,",
"dependent",
"if",
"mapper",
"is",
"a",
"dict,",
"Series",
"or",
"just",
"a",
"function."
] | def get_rename_function(mapper):
def f(x):
if x in mapper:
return mapper[x]
else:
return x
return f if isinstance(mapper, (abc.Mapping, ABCSeries)) else mapper | ['def', 'get_rename_function(mapper):', 'def', 'f(x):', 'if', 'x', 'in', 'mapper:', 'return', 'mapper[x]', 'else:', 'return', 'x', 'return', 'f', 'if', 'isinstance(mapper,', '(abc.Mapping,', 'ABCSeries))', 'else', 'mapper'] | 442,350 |
google-research/tensor2robot | tensorspec_utils.py | make_random_tensors | make_random_tensors | Create random inputs for tensor_spec (for unit testing). | [
"Create",
"random",
"inputs",
"for",
"tensor_spec",
"(for",
"unit",
"testing)."
] | def make_random_tensors(spec_structure, batch_size=2):
assert_valid_spec_structure(spec_structure)
def make_random(t):
maxval = 255 if t.dtype in [tf.uint8, tf.int32, tf.int64] else 1.0
dtype = tf.int32 if t.dtype == tf.uint8 else t.dtype
shape = tuple(t.shape.as_list())
if batc... | ['def', 'make_random_tensors(spec_structure,', 'batch_size=2):', 'assert_valid_spec_structure(spec_structure)', 'def', 'make_random(t):', 'maxval', '=', '255', 'if', 't.dtype', 'in', '[tf.uint8,', 'tf.int32,', 'tf.int64]', 'else', '1.0', 'dtype', '=', 'tf.int32', 'if', 't.dtype', '==', 'tf.uint8', 'else', 't.dtype', 's... | 908,460 |
qdraw/tensorflow-object-detection-tutorial | object_detection_evaluation.py | ObjectDetectionEvaluation.add_single_ground_truth_image_info | add_single_ground_truth_image_info | Add ground truth info of a single image into the evaluation database. | [
"Add",
"ground",
"truth",
"info",
"of",
"a",
"single",
"image",
"into",
"the",
"evaluation",
"database."
] | def add_single_ground_truth_image_info(self, image_key, groundtruth_boxes, groundtruth_class_labels, groundtruth_is_difficult_list=None):
if image_key in self.groundtruth_boxes:
logging.warn('image %s has already been added to the ground truth database.', image_key)
return
self.groundtruth_boxes... | ['def', 'add_single_ground_truth_image_info(self,', 'image_key,', 'groundtruth_boxes,', 'groundtruth_class_labels,', 'groundtruth_is_difficult_list=None):', 'if', 'image_key', 'in', 'self.groundtruth_boxes:', "logging.warn('image", '%s', 'has', 'already', 'been', 'added', 'to', 'the', 'ground', 'truth', "database.',", ... | 921,617 |
KalleHallden/InstaAutomator | _swf.py | build_file | build_file | Give the given file (as bytes) a header. | [
"Give",
"the",
"given",
"file",
"(as",
"bytes)",
"a",
"header."
] | def build_file(fp, taglist, nframes=1, framesize=(500, 500), fps=10, version=8):
bb = binary_type()
bb += 'F'.encode('ascii')
bb += 'WS'.encode('ascii')
bb += int2uint8(version)
bb += '0000'.encode('ascii')
bb += Tag().make_rect_record(0, framesize[0], 0, framesize[1]).tobytes()
bb += int2ui... | ['def', 'build_file(fp,', 'taglist,', 'nframes=1,', 'framesize=(500,', '500),', 'fps=10,', 'version=8):', 'bb', '=', 'binary_type()', 'bb', '+=', "'F'.encode('ascii')", 'bb', '+=', "'WS'.encode('ascii')", 'bb', '+=', 'int2uint8(version)', 'bb', '+=', "'0000'.encode('ascii')", 'bb', '+=', 'Tag().make_rect_record(0,', 'f... | 242,485 |
jeromewang-github/computer_vision | trainer.py | train | train | Training function for detection models. | [
"Training",
"function",
"for",
"detection",
"models."
] | def train(create_tensor_dict_fn, create_model_fn, train_config, master, task, num_clones, worker_replicas, clone_on_cpu, ps_tasks, worker_job_name, is_chief, train_dir, graph_hook_fn=None):
detection_model = create_model_fn()
data_augmentation_options = [preprocessor_builder.build(step) for step in train_config... | ['def', 'train(create_tensor_dict_fn,', 'create_model_fn,', 'train_config,', 'master,', 'task,', 'num_clones,', 'worker_replicas,', 'clone_on_cpu,', 'ps_tasks,', 'worker_job_name,', 'is_chief,', 'train_dir,', 'graph_hook_fn=None):', 'detection_model', '=', 'create_model_fn()', 'data_augmentation_options', '=', '[prepro... | 506,114 |
Ruturaj123/Flowchart-Detection | relaxed_onehot_categorical.py | ExpRelaxedOneHotCategorical.event_size | event_size | Scalar `int32` tensor: the number of classes. | [
"Scalar",
"`int32`",
"tensor:",
"the",
"number",
"of",
"classes."
] | def event_size(self):
return self._event_size | ['def', 'event_size(self):', 'return', 'self._event_size'] | 602,921 |
shery322/Lunar-Lander-ANN | cdrom_test.py | CDROMModuleTest.test_quit__multiple | test_quit__multiple | Ensure module still not initialized after multiple quit() calls. | [
"Ensure",
"module",
"still",
"not",
"initialized",
"after",
"multiple",
"quit()",
"calls."
] | def test_quit__multiple(self):
pygame.cdrom.quit()
pygame.cdrom.quit()
self.assertFalse(pygame.cdrom.get_init()) | ['def', 'test_quit__multiple(self):', 'pygame.cdrom.quit()', 'pygame.cdrom.quit()', 'self.assertFalse(pygame.cdrom.get_init())'] | 618,896 |
hideyukiinada/transfer-learning | tf_dataset.py | TFDataset.get_batch | get_batch | Get a single batch of images and labels from the dataset. | [
"Get",
"a",
"single",
"batch",
"of",
"images",
"and",
"labels",
"from",
"the",
"dataset."
] | def get_batch(self, subset='all'):
if subset == 'all' and self._dataset is not None:
return next(iter(self._dataset))
elif subset == 'train' and self._train_subset is not None:
return next(iter(self._train_subset))
elif subset == 'validation' and self._validation_subset is not None:
... | ['def', 'get_batch(self,', "subset='all'):", 'if', 'subset', '==', "'all'", 'and', 'self._dataset', 'is', 'not', 'None:', 'return', 'next(iter(self._dataset))', 'elif', 'subset', '==', "'train'", 'and', 'self._train_subset', 'is', 'not', 'None:', 'return', 'next(iter(self._train_subset))', 'elif', 'subset', '==', "'val... | 927,707 |
ldkong1205/LaserMix | encoder_decoder.py | EncoderDecoder3D.whole_inference | whole_inference | Inference with full scene (one forward pass without sliding). | [
"Inference",
"with",
"full",
"scene",
"(one",
"forward",
"pass",
"without",
"sliding)."
] | def whole_inference(self, points: Tensor, batch_input_metas: List[dict], rescale: bool) -> Tensor:
seg_logit = self.encode_decode(points, batch_input_metas)
return seg_logit | ['def', 'whole_inference(self,', 'points:', 'Tensor,', 'batch_input_metas:', 'List[dict],', 'rescale:', 'bool)', '->', 'Tensor:', 'seg_logit', '=', 'self.encode_decode(points,', 'batch_input_metas)', 'return', 'seg_logit'] | 624,248 |
thaines/helit | df.py | mpGrowTree | mpGrowTree | Part of the multiprocessing system - grows and returns a tree. | [
"Part",
"of",
"the",
"multiprocessing",
"system",
"-",
"grows",
"and",
"returns",
"a",
"tree."
] | def mpGrowTree(data):
(self, es, weightChannel, treesDone, seed) = data
numpy.random.seed(seed)
ret = self.addTree(es, weightChannel, True)
treesDone.value += 1
return ret | ['def', 'mpGrowTree(data):', '(self,', 'es,', 'weightChannel,', 'treesDone,', 'seed)', '=', 'data', 'numpy.random.seed(seed)', 'ret', '=', 'self.addTree(es,', 'weightChannel,', 'True)', 'treesDone.value', '+=', '1', 'return', 'ret'] | 591,244 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Cdf.Values | Values | Returns a sorted list of values. | [
"Returns",
"a",
"sorted",
"list",
"of",
"values."
] | def Values(self):
return self.xs | ['def', 'Values(self):', 'return', 'self.xs'] | 19,423 |
TheCurryMan/MedicAI | keys.py | WheelKeys.signers | signers | Return list of signing key(s). | [
"Return",
"list",
"of",
"signing",
"key(s)."
] | def signers(self, scope):
sign = [(x['scope'], x['vk']) for x in self.data['signers'] if x['scope'] in (scope, '+')]
sign.sort(key=lambda x: x[0])
sign.reverse()
return sign | ['def', 'signers(self,', 'scope):', 'sign', '=', "[(x['scope'],", "x['vk'])", 'for', 'x', 'in', "self.data['signers']", 'if', "x['scope']", 'in', '(scope,', "'+')]", 'sign.sort(key=lambda', 'x:', 'x[0])', 'sign.reverse()', 'return', 'sign'] | 649,949 |
onnx/onnx | reference_evaluator.py | ReferenceEvaluator.has_linked_attribute | has_linked_attribute | Checks if the graph has a linked attribute (= an attribute whose value is defined by a function attribute. | [
"Checks",
"if",
"the",
"graph",
"has",
"a",
"linked",
"attribute",
"(=",
"an",
"attribute",
"whose",
"value",
"is",
"defined",
"by",
"a",
"function",
"attribute."
] | def has_linked_attribute(self):
return any((node.has_linked_attribute for node in self.rt_nodes_)) | ['def', 'has_linked_attribute(self):', 'return', 'any((node.has_linked_attribute', 'for', 'node', 'in', 'self.rt_nodes_))'] | 756,524 |
sktime/sktime | test_mbb.py | test_get_series_name | test_get_series_name | Test _get_series_name returns the right string. | [
"Test",
"_get_series_name",
"returns",
"the",
"right",
"string."
] | def test_get_series_name(ts):
assert _get_series_name(ts) == 'Number of airline passengers' | ['def', 'test_get_series_name(ts):', 'assert', '_get_series_name(ts)', '==', "'Number", 'of', 'airline', "passengers'"] | 877,643 |
nicknochnack/RealTimeSignLanguageTFJS | utils.py | quantize_op | quantize_op | Inserts a fake quantization op after inputs. | [
"Inserts",
"a",
"fake",
"quantization",
"op",
"after",
"inputs."
] | def quantize_op(inputs, is_training=True, is_quantized=True, default_min=0, default_max=6, ema_decay=0.999, scope='quant'):
if not is_quantized:
return inputs
with tf.variable_scope(scope):
min_var = _quant_var('min', default_min)
max_var = _quant_var('max', default_max)
if not i... | ['def', 'quantize_op(inputs,', 'is_training=True,', 'is_quantized=True,', 'default_min=0,', 'default_max=6,', 'ema_decay=0.999,', "scope='quant'):", 'if', 'not', 'is_quantized:', 'return', 'inputs', 'with', 'tf.variable_scope(scope):', 'min_var', '=', "_quant_var('min',", 'default_min)', 'max_var', '=', "_quant_var('ma... | 851,893 |
multi-commander/Multi-Commander | vtrace_test.py | VtraceTest.test_inconsistent_rank_inputs_for_importance_weights | test_inconsistent_rank_inputs_for_importance_weights | Test one of many possible errors in shape of inputs. | [
"Test",
"one",
"of",
"many",
"possible",
"errors",
"in",
"shape",
"of",
"inputs."
] | def test_inconsistent_rank_inputs_for_importance_weights(self):
placeholders = {'log_rhos': tf.placeholder(dtype=tf.float32, shape=[None, None, 1]), 'discounts': tf.placeholder(dtype=tf.float32, shape=[None, None, 1]), 'rewards': tf.placeholder(dtype=tf.float32, shape=[None, None, 42]), 'values': tf.placeholder(dty... | ['def', 'test_inconsistent_rank_inputs_for_importance_weights(self):', 'placeholders', '=', "{'log_rhos':", 'tf.placeholder(dtype=tf.float32,', 'shape=[None,', 'None,', '1]),', "'discounts':", 'tf.placeholder(dtype=tf.float32,', 'shape=[None,', 'None,', '1]),', "'rewards':", 'tf.placeholder(dtype=tf.float32,', 'shape=[... | 643,420 |
devashish-patel/webcam-motion-detector | filters.py | do_trim | do_trim | Strip leading and trailing whitespace. | [
"Strip",
"leading",
"and",
"trailing",
"whitespace."
] | def do_trim(value):
return soft_unicode(value).strip() | ['def', 'do_trim(value):', 'return', 'soft_unicode(value).strip()'] | 979,757 |
fudan-zvg/DeepInteraction | regnet2mmdet.py | convert | convert | Convert keys in pycls pretrained RegNet models to mmdet style. | [
"Convert",
"keys",
"in",
"pycls",
"pretrained",
"RegNet",
"models",
"to",
"mmdet",
"style."
] | def convert(src, dst):
regnet_model = torch.load(src)
blobs = regnet_model['model_state']
state_dict = OrderedDict()
converted_names = set()
for (key, weight) in blobs.items():
if 'stem' in key:
convert_stem(key, weight, state_dict, converted_names)
elif 'head' in key:
... | ['def', 'convert(src,', 'dst):', 'regnet_model', '=', 'torch.load(src)', 'blobs', '=', "regnet_model['model_state']", 'state_dict', '=', 'OrderedDict()', 'converted_names', '=', 'set()', 'for', '(key,', 'weight)', 'in', 'blobs.items():', 'if', "'stem'", 'in', 'key:', 'convert_stem(key,', 'weight,', 'state_dict,', 'conv... | 521,232 |
nicknochnack/RealTimeSignLanguageTFJS | model.py | Model.depth_smoothness | depth_smoothness | Computes image-aware depth smoothness loss. | [
"Computes",
"image-aware",
"depth",
"smoothness",
"loss."
] | def depth_smoothness(self, depth, img):
depth_dx = self.gradient_x(depth)
depth_dy = self.gradient_y(depth)
image_dx = self.gradient_x(img)
image_dy = self.gradient_y(img)
weights_x = tf.exp(-tf.reduce_mean(tf.abs(image_dx), 3, keepdims=True))
weights_y = tf.exp(-tf.reduce_mean(tf.abs(image_dy),... | ['def', 'depth_smoothness(self,', 'depth,', 'img):', 'depth_dx', '=', 'self.gradient_x(depth)', 'depth_dy', '=', 'self.gradient_y(depth)', 'image_dx', '=', 'self.gradient_x(img)', 'image_dy', '=', 'self.gradient_y(img)', 'weights_x', '=', 'tf.exp(-tf.reduce_mean(tf.abs(image_dx),', '3,', 'keepdims=True))', 'weights_y',... | 831,362 |
wuzheng-sjtu/FastFPN | gprof2dot.py | Event.format | format | Format an event value. | [
"Format",
"an",
"event",
"value."
] | def format(self, val):
assert val is not None
return self._formatter(val) | ['def', 'format(self,', 'val):', 'assert', 'val', 'is', 'not', 'None', 'return', 'self._formatter(val)'] | 559,723 |
Yuting-Gao/DisCo-pytorch | resnet.py | resnet50d | resnet50d | Constructs a ResNet-50-D model. | [
"Constructs",
"a",
"ResNet-50-D",
"model."
] | def resnet50d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], stem_width=32, stem_type='deep', avg_down=True, **kwargs)
return _create_resnet('resnet50d', pretrained, **model_args) | ['def', 'resnet50d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '6,', '3],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', '**kwargs)', 'return', "_create_resnet('resnet50d',", 'pretrained,', '**model_args)'] | 187,437 |
pokaxpoka/sunrise | utils.py | ensure_sequence | ensure_sequence | If `obj` isn't a tuple or list, return a tuple containing `obj`. | [
"If",
"`obj`",
"isn't",
"a",
"tuple",
"or",
"list,",
"return",
"a",
"tuple",
"containing",
"`obj`."
] | def ensure_sequence(obj):
if isinstance(obj, (tuple, list)):
return obj
else:
return (obj,) | ['def', 'ensure_sequence(obj):', 'if', 'isinstance(obj,', '(tuple,', 'list)):', 'return', 'obj', 'else:', 'return', '(obj,)'] | 911,855 |
sunishsheth2009/ChatterBot | environment.py | Template.debug_info | debug_info | The debug info mapping. | [
"The",
"debug",
"info",
"mapping."
] | def debug_info(self):
return [tuple(imap(int, x.split('='))) for x in self._debug_info.split('&')] | ['def', 'debug_info(self):', 'return', '[tuple(imap(int,', "x.split('=')))", 'for', 'x', 'in', "self._debug_info.split('&')]"] | 479,035 |
spite-triangle/artificial_intelligence | tarfile.py | TarInfo.tobuf | tobuf | Return a tar header as a string of 512 byte blocks. | [
"Return",
"a",
"tar",
"header",
"as",
"a",
"string",
"of",
"512",
"byte",
"blocks."
] | def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape'):
info = self.get_info()
if format == USTAR_FORMAT:
return self.create_ustar_header(info, encoding, errors)
elif format == GNU_FORMAT:
return self.create_gnu_header(info, encoding, errors)
elif format == P... | ['def', 'tobuf(self,', 'format=DEFAULT_FORMAT,', 'encoding=ENCODING,', "errors='surrogateescape'):", 'info', '=', 'self.get_info()', 'if', 'format', '==', 'USTAR_FORMAT:', 'return', 'self.create_ustar_header(info,', 'encoding,', 'errors)', 'elif', 'format', '==', 'GNU_FORMAT:', 'return', 'self.create_gnu_header(info,',... | 144,269 |
explosion/spaCy | test_tokenizer.py | test_issue2626_2835 | test_issue2626_2835 | Check that sentence doesn't cause an infinite loop in the tokenizer. | [
"Check",
"that",
"sentence",
"doesn't",
"cause",
"an",
"infinite",
"loop",
"in",
"the",
"tokenizer."
] | def test_issue2626_2835(en_tokenizer, text):
doc = en_tokenizer(text)
assert doc | ['def', 'test_issue2626_2835(en_tokenizer,', 'text):', 'doc', '=', 'en_tokenizer(text)', 'assert', 'doc'] | 894,375 |
bhateharsh/computer_vision | io_utils.py | write_csv | write_csv | Writes metrics key-value pairs to CSV file. | [
"Writes",
"metrics",
"key-value",
"pairs",
"to",
"CSV",
"file."
] | def write_csv(fid, metrics):
metrics_writer = csv.writer(fid, delimiter=',')
for (metric_name, metric_value) in metrics.items():
metrics_writer.writerow([metric_name, str(metric_value)]) | ['def', 'write_csv(fid,', 'metrics):', 'metrics_writer', '=', 'csv.writer(fid,', "delimiter=',')", 'for', '(metric_name,', 'metric_value)', 'in', 'metrics.items():', 'metrics_writer.writerow([metric_name,', 'str(metric_value)])'] | 511,381 |
openai/baselines | rollout.py | RolloutWorker.save_policy | save_policy | Pickles the current policy for later inspection. | [
"Pickles",
"the",
"current",
"policy",
"for",
"later",
"inspection."
] | def save_policy(self, path):
with open(path, 'wb') as f:
pickle.dump(self.policy, f) | ['def', 'save_policy(self,', 'path):', 'with', 'open(path,', "'wb')", 'as', 'f:', 'pickle.dump(self.policy,', 'f)'] | 94,509 |
matsu0228/nlp-jp | periodic_executor.py | PeriodicExecutor.wake | wake | Execute the target function soon. | [
"Execute",
"the",
"target",
"function",
"soon."
] | def wake(self):
self._event = True | ['def', 'wake(self):', 'self._event', '=', 'True'] | 804,970 |
arshpreetsingh/quantopian-machinelearning | converter.py | PandasAutoDateLocator.get_locator | get_locator | Pick the best locator based on a distance. | [
"Pick",
"the",
"best",
"locator",
"based",
"on",
"a",
"distance."
] | def get_locator(self, dmin, dmax):
_check_implicitly_registered()
delta = relativedelta(dmax, dmin)
num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.days
num_sec = (delta.hours * 60.0 + delta.minutes) * 60.0 + delta.seconds
tot_sec = num_days * 86400.0 + num_sec
if abs(tot_sec) < se... | ['def', 'get_locator(self,', 'dmin,', 'dmax):', '_check_implicitly_registered()', 'delta', '=', 'relativedelta(dmax,', 'dmin)', 'num_days', '=', '(delta.years', '*', '12.0', '+', 'delta.months)', '*', '31.0', '+', 'delta.days', 'num_sec', '=', '(delta.hours', '*', '60.0', '+', 'delta.minutes)', '*', '60.0', '+', 'delta... | 890,535 |
LorenzoCassano/TablutChallenge22-23 | game.py | TablutGame.result | result | Return the state that results from making a move from a state. | [
"Return",
"the",
"state",
"that",
"results",
"from",
"making",
"a",
"move",
"from",
"a",
"state."
] | def result(self, state, move):
board = state.board
(new_board, win) = self.manager.board_updater(board, move)
new_color = 'BLACK' if state.to_move == 'WHITE' else 'WHITE'
if win == None:
win = self.manager.heuristics(new_board)
self.manager.set_color(new_color)
return GameState(to_move=n... | ['def', 'result(self,', 'state,', 'move):', 'board', '=', 'state.board', '(new_board,', 'win)', '=', 'self.manager.board_updater(board,', 'move)', 'new_color', '=', "'BLACK'", 'if', 'state.to_move', '==', "'WHITE'", 'else', "'WHITE'", 'if', 'win', '==', 'None:', 'win', '=', 'self.manager.heuristics(new_board)', 'self.m... | 365,307 |
agrabeli/artificial-intelligence | req_uninstall.py | UninstallPathSet.rollback | rollback | Rollback the changes previously made by remove(). | [
"Rollback",
"the",
"changes",
"previously",
"made",
"by",
"remove()."
] | def rollback(self):
if self.save_dir.path is None:
logger.error("Can't roll back %s; was not uninstalled", self.dist.project_name)
return False
logger.info('Rolling back uninstall of %s', self.dist.project_name)
for path in self._moved_paths:
tmp_path = self._stash(path)
logg... | ['def', 'rollback(self):', 'if', 'self.save_dir.path', 'is', 'None:', 'logger.error("Can\'t', 'roll', 'back', '%s;', 'was', 'not', 'uninstalled",', 'self.dist.project_name)', 'return', 'False', "logger.info('Rolling", 'back', 'uninstall', 'of', "%s',", 'self.dist.project_name)', 'for', 'path', 'in', 'self._moved_paths:... | 88,998 |
pykao/QuantumMolGAN-PyTorch | solver.py | Solver.update_lr | update_lr | Decay learning rates of the generator and discriminator. | [
"Decay",
"learning",
"rates",
"of",
"the",
"generator",
"and",
"discriminator."
] | def update_lr(self, gamma):
for param_group in self.d_optimizer.param_groups:
param_group['lr'] *= gamma
for param_group in self.g_optimizer.param_groups:
param_group['lr'] *= gamma | ['def', 'update_lr(self,', 'gamma):', 'for', 'param_group', 'in', 'self.d_optimizer.param_groups:', "param_group['lr']", '*=', 'gamma', 'for', 'param_group', 'in', 'self.g_optimizer.param_groups:', "param_group['lr']", '*=', 'gamma'] | 835,511 |
mkelly12/google_closure_compiler | calcdeps.py | IsDirectory | IsDirectory | Returns true if the provided reference is a directory. | [
"Returns",
"true",
"if",
"the",
"provided",
"reference",
"is",
"a",
"directory."
] | def IsDirectory(ref):
return os.path.isdir(ref) | ['def', 'IsDirectory(ref):', 'return', 'os.path.isdir(ref)'] | 202,614 |
chainer/chainer | inception.py | Inception.forward | forward | Computes the output of the Inception module. | [
"Computes",
"the",
"output",
"of",
"the",
"Inception",
"module."
] | def forward(self, x):
out1 = self.conv1(x)
out3 = self.conv3(relu.relu(self.proj3(x)))
out5 = self.conv5(relu.relu(self.proj5(x)))
pool = self.projp(max_pooling_nd.max_pooling_2d(x, 3, stride=1, pad=1))
y = relu.relu(concat.concat((out1, out3, out5, pool), axis=1))
return y | ['def', 'forward(self,', 'x):', 'out1', '=', 'self.conv1(x)', 'out3', '=', 'self.conv3(relu.relu(self.proj3(x)))', 'out5', '=', 'self.conv5(relu.relu(self.proj5(x)))', 'pool', '=', 'self.projp(max_pooling_nd.max_pooling_2d(x,', '3,', 'stride=1,', 'pad=1))', 'y', '=', 'relu.relu(concat.concat((out1,', 'out3,', 'out5,', ... | 477,432 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_magic.py | test_parse_options | test_parse_options | Tests for basic options parsing in magics. | [
"Tests",
"for",
"basic",
"options",
"parsing",
"in",
"magics."
] | def test_parse_options():
m = DummyMagics(_ip)
nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') | ['def', 'test_parse_options():', 'm', '=', 'DummyMagics(_ip)', "nt.assert_equal(m.parse_options('foo',", "'')[1],", "'foo')", "nt.assert_equal(m.parse_options(u'foo',", "'')[1],", "u'foo')"] | 448,561 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | image_utils.py | ImageProblem.num_channels | num_channels | Number of color channels. | [
"Number",
"of",
"color",
"channels."
] | def num_channels(self):
return 3 | ['def', 'num_channels(self):', 'return', '3'] | 964,906 |
NoGameNoLife00/mybolg | helpers.py | get_render_ctx | get_render_ctx | Get view template context. | [
"Get",
"view",
"template",
"context."
] | def get_render_ctx():
return getattr(g, '_admin_render_ctx', None) | ['def', 'get_render_ctx():', 'return', 'getattr(g,', "'_admin_render_ctx',", 'None)'] | 289,192 |
myothida/Supervised-Machine-Learning | iup.py | iup_segment | iup_segment | Given two reference coordinates `rc1` & `rc2` and their respective delta vectors `rd1` & `rd2`, returns interpolated deltas for the set of coordinates `coords`. | [
"Given",
"two",
"reference",
"coordinates",
"`rc1`",
"&",
"`rc2`",
"and",
"their",
"respective",
"delta",
"vectors",
"`rd1`",
"&",
"`rd2`,",
"returns",
"interpolated",
"deltas",
"for",
"the",
"set",
"of",
"coordinates",
"`coords`."
] | def iup_segment(coords: _PointSegment, rc1: _Point, rd1: _Delta, rc2: _Point, rd2: _Delta):
out_arrays = [None, None]
for j in (0, 1):
out_arrays[j] = out = []
(x1, x2, d1, d2) = (rc1[j], rc2[j], rd1[j], rd2[j])
if x1 == x2:
n = len(coords)
if d1 == d2:
... | ['def', 'iup_segment(coords:', '_PointSegment,', 'rc1:', '_Point,', 'rd1:', '_Delta,', 'rc2:', '_Point,', 'rd2:', '_Delta):', 'out_arrays', '=', '[None,', 'None]', 'for', 'j', 'in', '(0,', '1):', 'out_arrays[j]', '=', 'out', '=', '[]', '(x1,', 'x2,', 'd1,', 'd2)', '=', '(rc1[j],', 'rc2[j],', 'rd1[j],', 'rd2[j])', 'if',... | 361,349 |
TengXiaoDai/DistributedCrawling | os.py | execle | execle | execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. | [
"execle(file,",
"*args,",
"env)",
"Execute",
"the",
"executable",
"file",
"with",
"argument",
"list",
"args",
"and",
"environment",
"env,",
"replacing",
"the",
"current",
"process."
] | def execle(file, *args):
env = args[-1]
execve(file, args[:-1], env) | ['def', 'execle(file,', '*args):', 'env', '=', 'args[-1]', 'execve(file,', 'args[:-1],', 'env)'] | 187,930 |
omonimus1/super-computer- | Transitions.py | TransitionMap.add_set | add_set | Add transitions to the states in |new_set| on |event|. | [
"Add",
"transitions",
"to",
"the",
"states",
"in",
"|new_set|",
"on",
"|event|."
] | def add_set(self, event, new_set, TupleType=tuple):
if type(event) is TupleType:
(code0, code1) = event
i = self.split(code0)
j = self.split(code1)
map = self.map
while i < j:
map[i + 1].update(new_set)
i += 2
else:
self.get_special(event).... | ['def', 'add_set(self,', 'event,', 'new_set,', 'TupleType=tuple):', 'if', 'type(event)', 'is', 'TupleType:', '(code0,', 'code1)', '=', 'event', 'i', '=', 'self.split(code0)', 'j', '=', 'self.split(code1)', 'map', '=', 'self.map', 'while', 'i', '<', 'j:', 'map[i', '+', '1].update(new_set)', 'i', '+=', '2', 'else:', 'sel... | 912,991 |
amazon-science/semimtr-text-recognition | transformer.py | TransformerDecoderLayer.forward | forward | Pass the inputs (and mask) through the decoder layer. | [
"Pass",
"the",
"inputs",
"(and",
"mask)",
"through",
"the",
"decoder",
"layer."
] | def forward(self, tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, memory2=None, memory_mask2=None, memory_key_padding_mask2=None):
if self.has_self_attn:
(tgt2, attn) = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_m... | ['def', 'forward(self,', 'tgt,', 'memory,', 'tgt_mask=None,', 'memory_mask=None,', 'tgt_key_padding_mask=None,', 'memory_key_padding_mask=None,', 'memory2=None,', 'memory_mask2=None,', 'memory_key_padding_mask2=None):', 'if', 'self.has_self_attn:', '(tgt2,', 'attn)', '=', 'self.self_attn(tgt,', 'tgt,', 'tgt,', 'attn_ma... | 343,577 |
Farama-Foundation/Gymnasium | blackjack.py | usable_ace | usable_ace | Checks to se if a hand has a usable ace. | [
"Checks",
"to",
"se",
"if",
"a",
"hand",
"has",
"a",
"usable",
"ace."
] | def usable_ace(hand):
return jnp.logical_and(jnp.count_nonzero(hand == 1) > 0, sum(hand) + 10 <= 21) | ['def', 'usable_ace(hand):', 'return', 'jnp.logical_and(jnp.count_nonzero(hand', '==', '1)', '>', '0,', 'sum(hand)', '+', '10', '<=', '21)'] | 573,056 |
tensorflow/agents | release_builder.py | ReleaseBuilder.create_release_branch | create_release_branch | Creates a release branch and optionally an updated version file. | [
"Creates",
"a",
"release",
"branch",
"and",
"optionally",
"an",
"updated",
"version",
"file."
] | def create_release_branch(self):
logging.info('Create release branch %s.', self.branch_name)
logging.info('Starting active branch:%s.', self.repo.active_branch)
self._checkout_or_create_branch()
if self.version_file:
updated = self._update_version_file()
if updated:
self.repo... | ['def', 'create_release_branch(self):', "logging.info('Create", 'release', 'branch', "%s.',", 'self.branch_name)', "logging.info('Starting", 'active', "branch:%s.',", 'self.repo.active_branch)', 'self._checkout_or_create_branch()', 'if', 'self.version_file:', 'updated', '=', 'self._update_version_file()', 'if', 'update... | 23,894 |
microsoft/nni | data.py | get_id | get_id | Given word, return word id. | [
"Given",
"word,",
"return",
"word",
"id."
] | def get_id(word_dict, word):
if word in word_dict.keys():
return word_dict[word]
return word_dict['<unk>'] | ['def', 'get_id(word_dict,', 'word):', 'if', 'word', 'in', 'word_dict.keys():', 'return', 'word_dict[word]', 'return', "word_dict['<unk>']"] | 728,046 |
rlworkgroup/garage | test_functions.py | TestOptimizerInterface.test_torch_make_optimizer_with_tuple | test_torch_make_optimizer_with_tuple | Test make_optimizer function with tuple as first argument. | [
"Test",
"make_optimizer",
"function",
"with",
"tuple",
"as",
"first",
"argument."
] | def test_torch_make_optimizer_with_tuple(self):
optimizer_type = (torch.optim.Adam, {'lr': 0.1})
module = torch.nn.Linear(2, 1)
optimizer = make_optimizer(optimizer_type, module=module)
assert isinstance(optimizer, optimizer_type)
assert optimizer.defaults['lr'] == optimizer_type[1]['lr'] | ['def', 'test_torch_make_optimizer_with_tuple(self):', 'optimizer_type', '=', '(torch.optim.Adam,', "{'lr':", '0.1})', 'module', '=', 'torch.nn.Linear(2,', '1)', 'optimizer', '=', 'make_optimizer(optimizer_type,', 'module=module)', 'assert', 'isinstance(optimizer,', 'optimizer_type)', 'assert', "optimizer.defaults['lr'... | 200,896 |
43Carrig/recurrent_neural_networks_practice | tpu.py | replicate | replicate | Builds a graph operator that runs a replicated TPU computation. | [
"Builds",
"a",
"graph",
"operator",
"that",
"runs",
"a",
"replicated",
"TPU",
"computation."
] | def replicate(computation, inputs=None, infeed_queue=None, device_assignment=None, name=None):
return split_compile_and_replicate(computation, inputs, infeed_queue, device_assignment, name)[1] | ['def', 'replicate(computation,', 'inputs=None,', 'infeed_queue=None,', 'device_assignment=None,', 'name=None):', 'return', 'split_compile_and_replicate(computation,', 'inputs,', 'infeed_queue,', 'device_assignment,', 'name)[1]'] | 335,584 |
SamsungLabs/fcaf3d | lidar_box3d.py | LiDARInstance3DBoxes.enlarged_box | enlarged_box | Enlarge the length, width and height boxes. | [
"Enlarge",
"the",
"length,",
"width",
"and",
"height",
"boxes."
] | def enlarged_box(self, extra_width):
enlarged_boxes = self.tensor.clone()
enlarged_boxes[:, 3:6] += extra_width * 2
enlarged_boxes[:, 2] -= extra_width
return self.new_box(enlarged_boxes) | ['def', 'enlarged_box(self,', 'extra_width):', 'enlarged_boxes', '=', 'self.tensor.clone()', 'enlarged_boxes[:,', '3:6]', '+=', 'extra_width', '*', '2', 'enlarged_boxes[:,', '2]', '-=', 'extra_width', 'return', 'self.new_box(enlarged_boxes)'] | 560,208 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | util.py | mnist_cross_entropy | mnist_cross_entropy | Returns the cross entropy loss of the classifier on images. | [
"Returns",
"the",
"cross",
"entropy",
"loss",
"of",
"the",
"classifier",
"on",
"images."
] | def mnist_cross_entropy(images, one_hot_labels, graph_def_filename=None, input_tensor=INPUT_TENSOR, output_tensor=OUTPUT_TENSOR):
graph_def = _graph_def_from_par_or_disk(graph_def_filename)
logits = tfgan.eval.run_image_classifier(images, graph_def, input_tensor, output_tensor)
return tf.losses.softmax_cros... | ['def', 'mnist_cross_entropy(images,', 'one_hot_labels,', 'graph_def_filename=None,', 'input_tensor=INPUT_TENSOR,', 'output_tensor=OUTPUT_TENSOR):', 'graph_def', '=', '_graph_def_from_par_or_disk(graph_def_filename)', 'logits', '=', 'tfgan.eval.run_image_classifier(images,', 'graph_def,', 'input_tensor,', 'output_tenso... | 54,900 |
jcklie/keras-autoencoder | dmp.py | DMP.fit | fit | Fits the weights of the DMPs RBF to the trajectories given. | [
"Fits",
"the",
"weights",
"of",
"the",
"DMPs",
"RBF",
"to",
"the",
"trajectories",
"given."
] | def fit(self, q_im, qd_im, qdd_im, dt, tau=1.0, goal=None, regularizer=0.0):
if not q_im.shape == qd_im.shape == qdd_im.shape:
raise ValueError('Joint matrices have to be all equal sized!')
(nsteps, dof) = q_im.shape
if goal is None:
goal = q_im[-1, :]
elif goal.shape != (dof,):
... | ['def', 'fit(self,', 'q_im,', 'qd_im,', 'qdd_im,', 'dt,', 'tau=1.0,', 'goal=None,', 'regularizer=0.0):', 'if', 'not', 'q_im.shape', '==', 'qd_im.shape', '==', 'qdd_im.shape:', 'raise', "ValueError('Joint", 'matrices', 'have', 'to', 'be', 'all', 'equal', "sized!')", '(nsteps,', 'dof)', '=', 'q_im.shape', 'if', 'goal', '... | 595,016 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.