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 |
|---|---|---|---|---|---|---|---|---|
enuguru/artificial_intelligence_and_machine_learning | sandbox.py | SandboxedEnvironment.unsafe_undefined | unsafe_undefined | Return an undefined object for unsafe attributes. | [
"Return",
"an",
"undefined",
"object",
"for",
"unsafe",
"attributes."
] | def unsafe_undefined(self, obj, attribute):
return self.undefined('access to attribute %r of %r object is unsafe.' % (attribute, obj.__class__.__name__), name=attribute, obj=obj, exc=SecurityError) | ['def', 'unsafe_undefined(self,', 'obj,', 'attribute):', 'return', "self.undefined('access", 'to', 'attribute', '%r', 'of', '%r', 'object', 'is', "unsafe.'", '%', '(attribute,', 'obj.__class__.__name__),', 'name=attribute,', 'obj=obj,', 'exc=SecurityError)'] | 129,417 |
nilearn/nilearn | test_plot_connectome.py | test_plot_connectome_non_symmetric | test_plot_connectome_non_symmetric | Tests for plot_connectome with non symmetric adjacency matrices. | [
"Tests",
"for",
"plot_connectome",
"with",
"non",
"symmetric",
"adjacency",
"matrices."
] | def test_plot_connectome_non_symmetric(node_coords, non_symmetric_matrix):
ax = plot_connectome(non_symmetric_matrix, node_coords, display_mode='ortho')
for direction in ['x', 'y', 'z']:
assert len([patch for patch in ax.axes[direction].ax.patches if isinstance(patch, FancyArrow)]) == np.prod(non_symmet... | ['def', 'test_plot_connectome_non_symmetric(node_coords,', 'non_symmetric_matrix):', 'ax', '=', 'plot_connectome(non_symmetric_matrix,', 'node_coords,', "display_mode='ortho')", 'for', 'direction', 'in', "['x',", "'y',", "'z']:", 'assert', 'len([patch', 'for', 'patch', 'in', 'ax.axes[direction].ax.patches', 'if', 'isin... | 724,170 |
gunthercox/ChatterBot | ctypeslib.py | prep_simple | prep_simple | Given a ctypes simple type, construct and attach an __array_interface__ property to it if it does not yet have one. | [
"Given",
"a",
"ctypes",
"simple",
"type,",
"construct",
"and",
"attach",
"an",
"__array_interface__",
"property",
"to",
"it",
"if",
"it",
"does",
"not",
"yet",
"have",
"one."
] | def prep_simple(simple_type, dtype):
try:
simple_type.__array_interface__
except AttributeError:
pass
else:
return
typestr = _dtype(dtype).str
_typecodes[typestr] = simple_type
def __array_interface__(self):
return {'descr': [('', typestr)], '__ref': self, 'strid... | ['def', 'prep_simple(simple_type,', 'dtype):', 'try:', 'simple_type.__array_interface__', 'except', 'AttributeError:', 'pass', 'else:', 'return', 'typestr', '=', '_dtype(dtype).str', '_typecodes[typestr]', '=', 'simple_type', 'def', '__array_interface__(self):', 'return', "{'descr':", "[('',", 'typestr)],', "'__ref':",... | 530,542 |
TangJiahui/6.034_Artificial_Intelligence | lab0.py | fibonacci | fibonacci | Given a positive int n, uses recursion to return the nth Fibonacci number. | [
"Given",
"a",
"positive",
"int",
"n,",
"uses",
"recursion",
"to",
"return",
"the",
"nth",
"Fibonacci",
"number."
] | def fibonacci(n):
if n < 1 or type(n) != int:
raise ValueError('fibonacci: input must be a positive integer')
else:
return fibonacci(n - 2) + fibonacci(n - 1) if n >= 3 else 1 | ['def', 'fibonacci(n):', 'if', 'n', '<', '1', 'or', 'type(n)', '!=', 'int:', 'raise', "ValueError('fibonacci:", 'input', 'must', 'be', 'a', 'positive', "integer')", 'else:', 'return', 'fibonacci(n', '-', '2)', '+', 'fibonacci(n', '-', '1)', 'if', 'n', '>=', '3', 'else', '1'] | 4,806 |
dguo98/DiffPruning | tokenization_utils.py | PreTrainedTokenizer.batch_encode_plus | batch_encode_plus | Returns a dictionary containing the encoded sequence or sequence pair and additional information: the mask for sequence classification and the overflowing elements if a ``max_length`` is specified. | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"encoded",
"sequence",
"or",
"sequence",
"pair",
"and",
"additional",
"information:",
"the",
"mask",
"for",
"sequence",
"classification",
"and",
"the",
"overflowing",
"elements",
"if",
"a",
"``max_length``",
"is",
... | def batch_encode_plus(self, batch_text_or_text_pairs: Union[str, List[str]], add_special_tokens: bool=True, max_length: Optional[int]=None, stride: int=0, truncation_strategy: str='longest_first', pad_to_max_length: bool=False, return_tensors: Optional[str]=None, return_token_type_ids: Optional[bool]=None, return_atten... | ['def', 'batch_encode_plus(self,', 'batch_text_or_text_pairs:', 'Union[str,', 'List[str]],', 'add_special_tokens:', 'bool=True,', 'max_length:', 'Optional[int]=None,', 'stride:', 'int=0,', 'truncation_strategy:', "str='longest_first',", 'pad_to_max_length:', 'bool=False,', 'return_tensors:', 'Optional[str]=None,', 'ret... | 550,761 |
Kvatsx/Artificial-Intelligence-Assignments | kill_ring.py | KillRing.kill | kill | Adds some killed text to the ring. | [
"Adds",
"some",
"killed",
"text",
"to",
"the",
"ring."
] | def kill(self, text):
self._ring.append(text) | ['def', 'kill(self,', 'text):', 'self._ring.append(text)'] | 77,281 |
georghess/voxel-mae | box_np_ops.py | points_cam2img | points_cam2img | Project points in camera coordinates to image coordinates. | [
"Project",
"points",
"in",
"camera",
"coordinates",
"to",
"image",
"coordinates."
] | def points_cam2img(points_3d, proj_mat, with_depth=False):
points_shape = list(points_3d.shape)
points_shape[-1] = 1
assert len(proj_mat.shape) == 2, f'The dimension of the projection matrix should be 2 instead of {len(proj_mat.shape)}.'
(d1, d2) = proj_mat.shape[:2]
assert d1 == 3 and d2 == 3 or (d... | ['def', 'points_cam2img(points_3d,', 'proj_mat,', 'with_depth=False):', 'points_shape', '=', 'list(points_3d.shape)', 'points_shape[-1]', '=', '1', 'assert', 'len(proj_mat.shape)', '==', '2,', "f'The", 'dimension', 'of', 'the', 'projection', 'matrix', 'should', 'be', '2', 'instead', 'of', "{len(proj_mat.shape)}.'", '(d... | 380,326 |
arshpreetsingh/quantopian-machinelearning | prefilter.py | PrefilterManager.transformers | transformers | Return a list of checkers, sorted by priority. | [
"Return",
"a",
"list",
"of",
"checkers,",
"sorted",
"by",
"priority."
] | def transformers(self):
return self._transformers | ['def', 'transformers(self):', 'return', 'self._transformers'] | 886,421 |
imoscovitz/wittgenstein | base.py | Ruleset.predict | predict | Predict classes of data using a fit Ruleset model. | [
"Predict",
"classes",
"of",
"data",
"using",
"a",
"fit",
"Ruleset",
"model."
] | def predict(self, X_df, give_reasons=False):
covered_indices = set(self.covers(X_df).index.tolist())
predictions = [i in covered_indices for i in X_df.index]
if not give_reasons:
return predictions
else:
reasons = []
for (i, p) in zip(X_df.index, predictions):
example... | ['def', 'predict(self,', 'X_df,', 'give_reasons=False):', 'covered_indices', '=', 'set(self.covers(X_df).index.tolist())', 'predictions', '=', '[i', 'in', 'covered_indices', 'for', 'i', 'in', 'X_df.index]', 'if', 'not', 'give_reasons:', 'return', 'predictions', 'else:', 'reasons', '=', '[]', 'for', '(i,', 'p)', 'in', '... | 959,825 |
zihuitang/medical_AI_platform | pathlib.py | Path.write_bytes | write_bytes | Open the file in bytes mode, write to it, and close the file. | [
"Open",
"the",
"file",
"in",
"bytes",
"mode,",
"write",
"to",
"it,",
"and",
"close",
"the",
"file."
] | def write_bytes(self, data):
view = memoryview(data)
with self.open(mode='wb') as f:
return f.write(view) | ['def', 'write_bytes(self,', 'data):', 'view', '=', 'memoryview(data)', 'with', "self.open(mode='wb')", 'as', 'f:', 'return', 'f.write(view)'] | 280,983 |
Katja-M/Python_NaturalLanguageProcessing | test_axes.py | test_violin_point_mass | test_violin_point_mass | Violin plot should handle point mass pdf gracefully. | [
"Violin",
"plot",
"should",
"handle",
"point",
"mass",
"pdf",
"gracefully."
] | def test_violin_point_mass():
plt.violinplot(np.array([0, 0])) | ['def', 'test_violin_point_mass():', 'plt.violinplot(np.array([0,', '0]))'] | 865,426 |
zihuitang/medical_AI_platform | __init__.py | Checkbutton.select | select | Put the button in on-state. | [
"Put",
"the",
"button",
"in",
"on-state."
] | def select(self):
self.tk.call(self._w, 'select') | ['def', 'select(self):', 'self.tk.call(self._w,', "'select')"] | 284,254 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | test_constraints.py | TestHelperRoutines.test_packing | test_packing | Ensures the list of lists of tensors gets packed correctly. | [
"Ensures",
"the",
"list",
"of",
"lists",
"of",
"tensors",
"gets",
"packed",
"correctly."
] | def test_packing(self):
for (batch_constraints, expected_tensor) in self.examples:
packed = pack_constraints(batch_constraints)
assert torch.equal(packed, expected_tensor) | ['def', 'test_packing(self):', 'for', '(batch_constraints,', 'expected_tensor)', 'in', 'self.examples:', 'packed', '=', 'pack_constraints(batch_constraints)', 'assert', 'torch.equal(packed,', 'expected_tensor)'] | 104,181 |
tobegit3hub/deep_image_model | analyzer_cli_test.py | assert_node_attribute_lines | assert_node_attribute_lines | Check RichTextLines output for node_info commands. | [
"Check",
"RichTextLines",
"output",
"for",
"node_info",
"commands."
] | def assert_node_attribute_lines(tst, out, node_name, op_type, device, input_op_type_node_name_pairs, ctrl_input_op_type_node_name_pairs, recipient_op_type_node_name_pairs, ctrl_recipient_op_type_node_name_pairs, attr_key_val_pairs=None, num_dumped_tensors=None):
line_iter = iter(out.lines)
tst.assertEqual('Node... | ['def', 'assert_node_attribute_lines(tst,', 'out,', 'node_name,', 'op_type,', 'device,', 'input_op_type_node_name_pairs,', 'ctrl_input_op_type_node_name_pairs,', 'recipient_op_type_node_name_pairs,', 'ctrl_recipient_op_type_node_name_pairs,', 'attr_key_val_pairs=None,', 'num_dumped_tensors=None):', 'line_iter', '=', 'i... | 182,367 |
zihuitang/medical_AI_platform | __init__.py | Text.tag_remove | tag_remove | Remove tag TAGNAME from all characters between INDEX1 and INDEX2. | [
"Remove",
"tag",
"TAGNAME",
"from",
"all",
"characters",
"between",
"INDEX1",
"and",
"INDEX2."
] | def tag_remove(self, tagName, index1, index2=None):
self.tk.call(self._w, 'tag', 'remove', tagName, index1, index2) | ['def', 'tag_remove(self,', 'tagName,', 'index1,', 'index2=None):', 'self.tk.call(self._w,', "'tag',", "'remove',", 'tagName,', 'index1,', 'index2)'] | 284,363 |
pantelis/artificial-intelligence | __init__.py | FCompiler.get_flags_f77 | get_flags_f77 | List of Fortran 77 specific flags. | [
"List",
"of",
"Fortran",
"77",
"specific",
"flags."
] | def get_flags_f77(self):
return self._get_command_flags('compiler_f77') | ['def', 'get_flags_f77(self):', 'return', "self._get_command_flags('compiler_f77')"] | 168,618 |
weimin17/Object-Detection_HelmetDetection | graph_builder.py | EmbeddingLookupFeatures | EmbeddingLookupFeatures | Computes embeddings for each entry of sparse features sparse_features. | [
"Computes",
"embeddings",
"for",
"each",
"entry",
"of",
"sparse",
"features",
"sparse_features."
] | def EmbeddingLookupFeatures(params, sparse_features, allow_weights):
if not isinstance(params, list):
params = [params]
sparse_features = tf.convert_to_tensor(sparse_features)
(indices, ids, weights) = gen_parser_ops.unpack_syntax_net_sparse_features(sparse_features)
embeddings = tf.nn.embedding... | ['def', 'EmbeddingLookupFeatures(params,', 'sparse_features,', 'allow_weights):', 'if', 'not', 'isinstance(params,', 'list):', 'params', '=', '[params]', 'sparse_features', '=', 'tf.convert_to_tensor(sparse_features)', '(indices,', 'ids,', 'weights)', '=', 'gen_parser_ops.unpack_syntax_net_sparse_features(sparse_featur... | 760,424 |
jeromewang-github/computer_vision | image_iter.py | FaceImageIter.next_sample | next_sample | Helper function for reading in next sample. | [
"Helper",
"function",
"for",
"reading",
"in",
"next",
"sample."
] | def next_sample(self):
if self.seq is not None:
while True:
if self.cur >= len(self.seq):
raise StopIteration
idx = self.seq[self.cur]
self.cur += 1
if self.imgrec is not None:
s = self.imgrec.read_idx(idx)
(head... | ['def', 'next_sample(self):', 'if', 'self.seq', 'is', 'not', 'None:', 'while', 'True:', 'if', 'self.cur', '>=', 'len(self.seq):', 'raise', 'StopIteration', 'idx', '=', 'self.seq[self.cur]', 'self.cur', '+=', '1', 'if', 'self.imgrec', 'is', 'not', 'None:', 's', '=', 'self.imgrec.read_idx(idx)', '(header,', 'img)', '=', ... | 500,617 |
sktime/sktime | test_mlflow_sktime_model_export.py | auto_arima_model | auto_arima_model | Create instance of fitted auto arima model. | [
"Create",
"instance",
"of",
"fitted",
"auto",
"arima",
"model."
] | def auto_arima_model(test_data_airline):
return AutoARIMA(sp=12, d=0, max_p=2, max_q=2, suppress_warnings=True).fit(test_data_airline, fh=[1, 2, 3]) | ['def', 'auto_arima_model(test_data_airline):', 'return', 'AutoARIMA(sp=12,', 'd=0,', 'max_p=2,', 'max_q=2,', 'suppress_warnings=True).fit(test_data_airline,', 'fh=[1,', '2,', '3])'] | 878,050 |
abrarrhine/Artificial-Intelligence-PacmanGames | capture.py | GameState.getAgentDistances | getAgentDistances | Returns a noisy distance to each agent. | [
"Returns",
"a",
"noisy",
"distance",
"to",
"each",
"agent."
] | def getAgentDistances(self):
if 'agentDistances' in dir(self):
return self.agentDistances
else:
return None | ['def', 'getAgentDistances(self):', 'if', "'agentDistances'", 'in', 'dir(self):', 'return', 'self.agentDistances', 'else:', 'return', 'None'] | 90,920 |
rifqind/Agent-Programs-3KS1 | iptestcontroller.py | TestController.cleanup_process | cleanup_process | Cleanup on exit by killing any leftover processes. | [
"Cleanup",
"on",
"exit",
"by",
"killing",
"any",
"leftover",
"processes."
] | def cleanup_process(self):
subp = self.process
if subp is None or subp.poll() is not None:
return
try:
print('Cleaning up stale PID: %d' % subp.pid)
subp.kill()
except:
pass
else:
for i in range(10):
if subp.poll() is None:
time.sle... | ['def', 'cleanup_process(self):', 'subp', '=', 'self.process', 'if', 'subp', 'is', 'None', 'or', 'subp.poll()', 'is', 'not', 'None:', 'return', 'try:', "print('Cleaning", 'up', 'stale', 'PID:', "%d'", '%', 'subp.pid)', 'subp.kill()', 'except:', 'pass', 'else:', 'for', 'i', 'in', 'range(10):', 'if', 'subp.poll()', 'is',... | 41,769 |
cyberdelia/metrology | meter.py | Meter.mean_rate | mean_rate | Returns the mean rate of the events since the start of the process. | [
"Returns",
"the",
"mean",
"rate",
"of",
"the",
"events",
"since",
"the",
"start",
"of",
"the",
"process."
] | def mean_rate(self):
if self.counter.value == 0:
return 0.0
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed | ['def', 'mean_rate(self):', 'if', 'self.counter.value', '==', '0:', 'return', '0.0', 'else:', 'elapsed', '=', 'time()', '-', 'self.start_time', 'return', 'self.counter.value', '/', 'elapsed'] | 286,122 |
neokarn/computer_vision | sast_process.py | SASTProcessTrain.poly2quads | poly2quads | Split poly into quads. | [
"Split",
"poly",
"into",
"quads."
] | def poly2quads(self, poly):
quad_list = []
point_num = poly.shape[0]
point_pair_list = []
for idx in range(point_num // 2):
point_pair = [poly[idx], poly[point_num - 1 - idx]]
point_pair_list.append(point_pair)
quad_num = point_num // 2 - 1
for idx in range(quad_num):
qua... | ['def', 'poly2quads(self,', 'poly):', 'quad_list', '=', '[]', 'point_num', '=', 'poly.shape[0]', 'point_pair_list', '=', '[]', 'for', 'idx', 'in', 'range(point_num', '//', '2):', 'point_pair', '=', '[poly[idx],', 'poly[point_num', '-', '1', '-', 'idx]]', 'point_pair_list.append(point_pair)', 'quad_num', '=', 'point_num... | 502,053 |
sunishsheth2009/ChatterBot | verbnet.py | VerbnetCorpusReader.lemmas | lemmas | Return a list of all verb lemmas that appear in any class, or in the ``classid`` if specified. | [
"Return",
"a",
"list",
"of",
"all",
"verb",
"lemmas",
"that",
"appear",
"in",
"any",
"class,",
"or",
"in",
"the",
"``classid``",
"if",
"specified."
] | def lemmas(self, classid=None):
if classid is None:
return sorted(self._lemma_to_class.keys())
else:
vnclass = self.vnclass(classid)
return [member.get('name') for member in vnclass.findall('MEMBERS/MEMBER')] | ['def', 'lemmas(self,', 'classid=None):', 'if', 'classid', 'is', 'None:', 'return', 'sorted(self._lemma_to_class.keys())', 'else:', 'vnclass', '=', 'self.vnclass(classid)', 'return', "[member.get('name')", 'for', 'member', 'in', "vnclass.findall('MEMBERS/MEMBER')]"] | 527,567 |
fairlearn/fairlearn | package_test_common.py | run_thresholdoptimizer_classification | run_thresholdoptimizer_classification | Run classification test with ThresholdOptimizer. | [
"Run",
"classification",
"test",
"with",
"ThresholdOptimizer."
] | def run_thresholdoptimizer_classification(estimator):
(X_train, Y_train, A_train, X_test, Y_test, A_test) = fetch_adult()
unmitigated = copy.deepcopy(estimator)
unmitigated.fit(X_train, Y_train)
unmitigated_predictions = unmitigated.predict(X_test)
to = ThresholdOptimizer(estimator=estimator, prefit... | ['def', 'run_thresholdoptimizer_classification(estimator):', '(X_train,', 'Y_train,', 'A_train,', 'X_test,', 'Y_test,', 'A_test)', '=', 'fetch_adult()', 'unmitigated', '=', 'copy.deepcopy(estimator)', 'unmitigated.fit(X_train,', 'Y_train)', 'unmitigated_predictions', '=', 'unmitigated.predict(X_test)', 'to', '=', 'Thre... | 558,484 |
sktime/sktime | test_plotting.py | test_plot_series_invalid_label_kwarg_len_raises_error | test_plot_series_invalid_label_kwarg_len_raises_error | Tests whether plot_series raises error for inconsistent series/labels. | [
"Tests",
"whether",
"plot_series",
"raises",
"error",
"for",
"inconsistent",
"series/labels."
] | def test_plot_series_invalid_label_kwarg_len_raises_error(series_to_plot):
match = 'There must be one label for each time series,\n but found inconsistent numbers of series and\n labels.'
with pytest.raises(ValueError, match=match):
if isinstance(series_to_plot, pd.Series):... | ['def', 'test_plot_series_invalid_label_kwarg_len_raises_error(series_to_plot):', 'match', '=', "'There", 'must', 'be', 'one', 'label', 'for', 'each', 'time', 'series,\\n', 'but', 'found', 'inconsistent', 'numbers', 'of', 'series', 'and\\n', "labels.'", 'with', 'pytest.raises(ValueError,', 'match=match):', 'if', 'isins... | 878,076 |
matsu0228/nlp-jp | connection.py | MWSConnection.update_subscription | update_subscription | Updates the subscription for the specified notification type and destination. | [
"Updates",
"the",
"subscription",
"for",
"the",
"specified",
"notification",
"type",
"and",
"destination."
] | def update_subscription(self, request, response, **kw):
return self._post_request(request, kw, response) | ['def', 'update_subscription(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)'] | 785,004 |
DLR-RM/AugmentedAutoencoder | transform.py | arcball_constrain_to_axis | arcball_constrain_to_axis | Return sphere point perpendicular to axis. | [
"Return",
"sphere",
"point",
"perpendicular",
"to",
"axis."
] | def arcball_constrain_to_axis(point, axis):
v = numpy.array(point, dtype=numpy.float64, copy=True)
a = numpy.array(axis, dtype=numpy.float64, copy=True)
v -= a * numpy.dot(a, v)
n = vector_norm(v)
if n > _EPS:
if v[2] < 0.0:
numpy.negative(v, v)
v /= n
return v
... | ['def', 'arcball_constrain_to_axis(point,', 'axis):', 'v', '=', 'numpy.array(point,', 'dtype=numpy.float64,', 'copy=True)', 'a', '=', 'numpy.array(axis,', 'dtype=numpy.float64,', 'copy=True)', 'v', '-=', 'a', '*', 'numpy.dot(a,', 'v)', 'n', '=', 'vector_norm(v)', 'if', 'n', '>', '_EPS:', 'if', 'v[2]', '<', '0.0:', 'num... | 404,541 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | seq2seq_attention_decode.py | BSDecoder.DecodeLoop | DecodeLoop | Decoding loop for long running process. | [
"Decoding",
"loop",
"for",
"long",
"running",
"process."
] | def DecodeLoop(self):
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
step = 0
while step < FLAGS.max_decode_steps:
time.sleep(DECODE_LOOP_DELAY_SECS)
if not self._Decode(self._saver, sess):
continue
step += 1 | ['def', 'DecodeLoop(self):', 'sess', '=', 'tf.Session(config=tf.ConfigProto(allow_soft_placement=True))', 'step', '=', '0', 'while', 'step', '<', 'FLAGS.max_decode_steps:', 'time.sleep(DECODE_LOOP_DELAY_SECS)', 'if', 'not', 'self._Decode(self._saver,', 'sess):', 'continue', 'step', '+=', '1'] | 112,733 |
zihuitang/medical_AI_platform | datetime.py | tzinfo.fromutc | fromutc | datetime in UTC -> datetime in local time. | [
"datetime",
"in",
"UTC",
"->",
"datetime",
"in",
"local",
"time."
] | def fromutc(self, dt):
if not isinstance(dt, datetime):
raise TypeError('fromutc() requires a datetime argument')
if dt.tzinfo is not self:
raise ValueError('dt.tzinfo is not self')
dtoff = dt.utcoffset()
if dtoff is None:
raise ValueError('fromutc() requires a non-None utcoffset... | ['def', 'fromutc(self,', 'dt):', 'if', 'not', 'isinstance(dt,', 'datetime):', 'raise', "TypeError('fromutc()", 'requires', 'a', 'datetime', "argument')", 'if', 'dt.tzinfo', 'is', 'not', 'self:', 'raise', "ValueError('dt.tzinfo", 'is', 'not', "self')", 'dtoff', '=', 'dt.utcoffset()', 'if', 'dtoff', 'is', 'None:', 'raise... | 280,294 |
xiaoaleiBLUE/computer_vision | PPOCRLabel.py | MainWindow.toggleDrawingSensitive | toggleDrawingSensitive | In the middle of drawing, toggling between modes should be disabled. | [
"In",
"the",
"middle",
"of",
"drawing,",
"toggling",
"between",
"modes",
"should",
"be",
"disabled."
] | def toggleDrawingSensitive(self, drawing=True):
self.actions.editMode.setEnabled(not drawing)
if not drawing and self.beginner():
print('Cancel creation.')
self.canvas.setEditing(True)
self.canvas.restoreCursor()
self.actions.create.setEnabled(True) | ['def', 'toggleDrawingSensitive(self,', 'drawing=True):', 'self.actions.editMode.setEnabled(not', 'drawing)', 'if', 'not', 'drawing', 'and', 'self.beginner():', "print('Cancel", "creation.')", 'self.canvas.setEditing(True)', 'self.canvas.restoreCursor()', 'self.actions.create.setEnabled(True)'] | 474,578 |
deepmind/meltingpot | chicken_in_the_matrix__arena.py | create_resource_prefab | create_resource_prefab | Creates resource prefab with provided `resource_id` (num) and color. | [
"Creates",
"resource",
"prefab",
"with",
"provided",
"`resource_id`",
"(num)",
"and",
"color."
] | def create_resource_prefab(resource_id, color_data):
resource_name = 'resource_class{}'.format(resource_id)
resource_prefab = {'name': resource_name, 'components': [{'component': 'StateManager', 'kwargs': {'initialState': resource_name, 'stateConfigs': [{'state': resource_name + '_wait', 'groups': ['resourceWai... | ['def', 'create_resource_prefab(resource_id,', 'color_data):', 'resource_name', '=', "'resource_class{}'.format(resource_id)", 'resource_prefab', '=', "{'name':", 'resource_name,', "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", 'resource_name,', "'stateConfigs':", "[{'state':", '... | 285,286 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | input_ops.py | prefetch_input_data | prefetch_input_data | Prefetches string values from disk into an input queue. | [
"Prefetches",
"string",
"values",
"from",
"disk",
"into",
"an",
"input",
"queue."
] | def prefetch_input_data(reader, file_pattern, shuffle, capacity, num_reader_threads=1):
data_files = []
for pattern in file_pattern.split(','):
data_files.extend(tf.gfile.Glob(pattern))
if not data_files:
tf.logging.fatal('Found no input files matching %s', file_pattern)
else:
tf... | ['def', 'prefetch_input_data(reader,', 'file_pattern,', 'shuffle,', 'capacity,', 'num_reader_threads=1):', 'data_files', '=', '[]', 'for', 'pattern', 'in', "file_pattern.split(','):", 'data_files.extend(tf.gfile.Glob(pattern))', 'if', 'not', 'data_files:', "tf.logging.fatal('Found", 'no', 'input', 'files', 'matching', ... | 109,692 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_binop.py | isRat | isRat | Test wheter an object is an instance of the Rat class. | [
"Test",
"wheter",
"an",
"object",
"is",
"an",
"instance",
"of",
"the",
"Rat",
"class."
] | def isRat(x):
return isinstance(x, Rat) | ['def', 'isRat(x):', 'return', 'isinstance(x,', 'Rat)'] | 431,286 |
google/deepvariant | variantcall_utils.py | set_gt | set_gt | Sets the genotypes of the VariantCall. | [
"Sets",
"the",
"genotypes",
"of",
"the",
"VariantCall."
] | def set_gt(variant_call, gt):
variant_call.genotype[:] = gt | ['def', 'set_gt(variant_call,', 'gt):', 'variant_call.genotype[:]', '=', 'gt'] | 540,698 |
ldkong1205/LaserMix | base_points.py | BasePoints.in_range_bev | in_range_bev | Check whether the points are in the given range. | [
"Check",
"whether",
"the",
"points",
"are",
"in",
"the",
"given",
"range."
] | def in_range_bev(self, point_range: Union[Tensor, np.ndarray, Sequence[float]]) -> Tensor:
in_range_flags = (self.bev[:, 0] > point_range[0]) & (self.bev[:, 1] > point_range[1]) & (self.bev[:, 0] < point_range[2]) & (self.bev[:, 1] < point_range[3])
return in_range_flags | ['def', 'in_range_bev(self,', 'point_range:', 'Union[Tensor,', 'np.ndarray,', 'Sequence[float]])', '->', 'Tensor:', 'in_range_flags', '=', '(self.bev[:,', '0]', '>', 'point_range[0])', '&', '(self.bev[:,', '1]', '>', 'point_range[1])', '&', '(self.bev[:,', '0]', '<', 'point_range[2])', '&', '(self.bev[:,', '1]', '<', '... | 624,437 |
myothida/Supervised-Machine-Learning | colors.py | to_rgb | to_rgb | Convert *c* to an RGB color, silently dropping the alpha channel. | [
"Convert",
"*c*",
"to",
"an",
"RGB",
"color,",
"silently",
"dropping",
"the",
"alpha",
"channel."
] | def to_rgb(c):
return to_rgba(c)[:3] | ['def', 'to_rgb(c):', 'return', 'to_rgba(c)[:3]'] | 361,895 |
AgnostiqHQ/covalent | write_result_to_db_test.py | test_insert_lattices_data | test_insert_lattices_data | Test the function that inserts the lattices data in the DB. | [
"Test",
"the",
"function",
"that",
"inserts",
"the",
"lattices",
"data",
"in",
"the",
"DB."
] | def test_insert_lattices_data(test_db, mocker):
mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db', test_db)
timestamps = []
for i in range(2):
cur_time = dt.now(timezone.utc)
timestamps.append(cur_time)
lattice_args = get_lattice_kwargs(dispatch_id=f'dispatch_{i +... | ['def', 'test_insert_lattices_data(test_db,', 'mocker):', "mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db',", 'test_db)', 'timestamps', '=', '[]', 'for', 'i', 'in', 'range(2):', 'cur_time', '=', 'dt.now(timezone.utc)', 'timestamps.append(cur_time)', 'lattice_args', '=', "get_lattice_kwargs(dispatc... | 489,739 |
lebrice/Sequoia | batch_test.py | test_remove_batch_dim | test_remove_batch_dim | Removing an extra batch dimension. | [
"Removing",
"an",
"extra",
"batch",
"dimension."
] | def test_remove_batch_dim():
bob = Observations(x=torch.tensor([[0, 1, 2, 3, 4]], dtype=int), task_labels=np.array([1]))
expected = Observations(x=torch.arange(5), task_labels=1)
for expanded in [bob.remove_batch_dimension(), bob[:, 0]]:
assert str(expanded) == str(expected)
bob = Observations(x... | ['def', 'test_remove_batch_dim():', 'bob', '=', 'Observations(x=torch.tensor([[0,', '1,', '2,', '3,', '4]],', 'dtype=int),', 'task_labels=np.array([1]))', 'expected', '=', 'Observations(x=torch.arange(5),', 'task_labels=1)', 'for', 'expanded', 'in', '[bob.remove_batch_dimension(),', 'bob[:,', '0]]:', 'assert', 'str(exp... | 344,100 |
amiratag/DataShapley | shap_utils.py | one_iteration | one_iteration | Runs one iteration of TMC-Shapley. | [
"Runs",
"one",
"iteration",
"of",
"TMC-Shapley."
] | def one_iteration(clf, X, y, X_test, y_test, mean_score, tol=0.0, c=None, metric='accuracy'):
if metric == 'auc':
def score_func(clf, a, b):
return roc_auc_score(b, clf.predict_proba(a)[:, 1])
elif metric == 'accuracy':
def score_func(clf, a, b):
return clf.score(a, b)
... | ['def', 'one_iteration(clf,', 'X,', 'y,', 'X_test,', 'y_test,', 'mean_score,', 'tol=0.0,', 'c=None,', "metric='accuracy'):", 'if', 'metric', '==', "'auc':", 'def', 'score_func(clf,', 'a,', 'b):', 'return', 'roc_auc_score(b,', 'clf.predict_proba(a)[:,', '1])', 'elif', 'metric', '==', "'accuracy':", 'def', 'score_func(cl... | 497,997 |
arnomoonens/yarll | reporter.py | Reporter.draw_rewards | draw_rewards | Draw a plot with the mean reward for each batch of episodes. | [
"Draw",
"a",
"plot",
"with",
"the",
"mean",
"reward",
"for",
"each",
"batch",
"of",
"episodes."
] | def draw_rewards(self, mean_rewards):
if not self.fig:
self.fig = plt.figure()
if not self.ax1:
self.ax1 = self.fig.add_subplot(1, 1, 1)
self.ax1.clear()
self.ax1.plot(range(len(mean_rewards)), mean_rewards)
self.fig.canvas.draw()
self.fig.canvas.flush_events()
plt.show(block... | ['def', 'draw_rewards(self,', 'mean_rewards):', 'if', 'not', 'self.fig:', 'self.fig', '=', 'plt.figure()', 'if', 'not', 'self.ax1:', 'self.ax1', '=', 'self.fig.add_subplot(1,', '1,', '1)', 'self.ax1.clear()', 'self.ax1.plot(range(len(mean_rewards)),', 'mean_rewards)', 'self.fig.canvas.draw()', 'self.fig.canvas.flush_ev... | 374,761 |
flavioschneider/rl-transfer- | metaworld_set_task_env.py | MetaWorldSetTaskEnv.visualize | visualize | Creates a visualization of the wrapped environment. | [
"Creates",
"a",
"visualization",
"of",
"the",
"wrapped",
"environment."
] | def visualize(self):
self._current_env.visualize() | ['def', 'visualize(self):', 'self._current_env.visualize()'] | 861,021 |
matsu0228/nlp-jp | database.py | Database.client | client | The client instance for this :class:`Database`. | [
"The",
"client",
"instance",
"for",
"this",
":class:`Database`."
] | def client(self):
return self.__client | ['def', 'client(self):', 'return', 'self.__client'] | 804,843 |
Kvatsx/Artificial-Intelligence-Assignments | interactiveshell.py | InteractiveShell.init_history | init_history | Sets up the command history, and starts regular autosaves. | [
"Sets",
"up",
"the",
"command",
"history,",
"and",
"starts",
"regular",
"autosaves."
] | def init_history(self):
self.history_manager = HistoryManager(shell=self, parent=self)
self.configurables.append(self.history_manager) | ['def', 'init_history(self):', 'self.history_manager', '=', 'HistoryManager(shell=self,', 'parent=self)', 'self.configurables.append(self.history_manager)'] | 38,089 |
enuguru/artificial_intelligence_and_machine_ | xri.py | toIRINormal | toIRINormal | Transform an XRI to IRI-normal form. | [
"Transform",
"an",
"XRI",
"to",
"IRI-normal",
"form."
] | def toIRINormal(xri):
if not xri.startswith('xri://'):
xri = 'xri://' + xri
return escapeForIRI(xri) | ['def', 'toIRINormal(xri):', 'if', 'not', "xri.startswith('xri://'):", 'xri', '=', "'xri://'", '+', 'xri', 'return', 'escapeForIRI(xri)'] | 130,497 |
sek788432/Waymo-2D-Object-Detection | anchor.py | Anchor.unpack_labels | unpack_labels | Unpacks an array of labels into multiscales labels. | [
"Unpacks",
"an",
"array",
"of",
"labels",
"into",
"multiscales",
"labels."
] | def unpack_labels(self, labels):
unpacked_labels = collections.OrderedDict()
count = 0
for level in range(self.min_level, self.max_level + 1):
feat_size_y = tf.cast(self.image_size[0] / 2 ** level, tf.int32)
feat_size_x = tf.cast(self.image_size[1] / 2 ** level, tf.int32)
steps = fea... | ['def', 'unpack_labels(self,', 'labels):', 'unpacked_labels', '=', 'collections.OrderedDict()', 'count', '=', '0', 'for', 'level', 'in', 'range(self.min_level,', 'self.max_level', '+', '1):', 'feat_size_y', '=', 'tf.cast(self.image_size[0]', '/', '2', '**', 'level,', 'tf.int32)', 'feat_size_x', '=', 'tf.cast(self.image... | 973,199 |
QData/deepWordBug | screen.py | _AbstractCanvas.scroll | scroll | Scroll the abstract canvas up one line. | [
"Scroll",
"the",
"abstract",
"canvas",
"up",
"one",
"line."
] | def scroll(self):
self._start_line += 1 | ['def', 'scroll(self):', 'self._start_line', '+=', '1'] | 542,755 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | pdb.py | Pdb.displayhook | displayhook | Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. | [
"Custom",
"displayhook",
"for",
"the",
"exec",
"in",
"default(),",
"which",
"prevents",
"assignment",
"of",
"the",
"_",
"variable",
"in",
"the",
"builtins."
] | def displayhook(self, obj):
if obj is not None:
self.message(repr(obj)) | ['def', 'displayhook(self,', 'obj):', 'if', 'obj', 'is', 'not', 'None:', 'self.message(repr(obj))'] | 429,104 |
intel/neural-compressor | keras.py | KerasModel.supports_path | supports_path | Check if given path is of supported model. | [
"Check",
"if",
"given",
"path",
"is",
"of",
"supported",
"model."
] | def supports_path(path: str) -> bool:
return 'keras' == get_model_type(path) | ['def', 'supports_path(path:', 'str)', '->', 'bool:', 'return', "'keras'", '==', 'get_model_type(path)'] | 721,590 |
Katja-M/Python_NaturalLanguageProcessing | test_mlab.py | test_psd_oversampling | test_psd_oversampling | Test the case len(x) < NFFT for psd(). | [
"Test",
"the",
"case",
"len(x)",
"<",
"NFFT",
"for",
"psd()."
] | def test_psd_oversampling():
u = np.array([0, 1, 2, 3, 1, 2, 1])
dt = 1.0
Su = np.abs(np.fft.fft(u) * dt) ** 2 / (dt * u.size)
(P, f) = mlab.psd(u, NFFT=u.size * 2, Fs=1 / dt, window=mlab.window_none, detrend=mlab.detrend_none, noverlap=0, pad_to=None, scale_by_freq=None, sides='onesided')
Su_1side ... | ['def', 'test_psd_oversampling():', 'u', '=', 'np.array([0,', '1,', '2,', '3,', '1,', '2,', '1])', 'dt', '=', '1.0', 'Su', '=', 'np.abs(np.fft.fft(u)', '*', 'dt)', '**', '2', '/', '(dt', '*', 'u.size)', '(P,', 'f)', '=', 'mlab.psd(u,', 'NFFT=u.size', '*', '2,', 'Fs=1', '/', 'dt,', 'window=mlab.window_none,', 'detrend=m... | 865,531 |
IBM/graph4nlp | bleu_scorer.py | cook_refs | cook_refs | Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. | [
"Takes",
"a",
"list",
"of",
"reference",
"sentences",
"for",
"a",
"single",
"segment",
"and",
"returns",
"an",
"object",
"that",
"encapsulates",
"everything",
"that",
"BLEU",
"needs",
"to",
"know",
"about",
"them."
] | def cook_refs(refs, eff=None, n=4):
reflen = []
maxcounts = dict()
for ref in refs:
(rl, counts) = precook(ref, n)
reflen.append(rl)
for (ngram, count) in counts.items():
maxcounts[ngram] = max(maxcounts.get(ngram, 0), count)
if eff == 'shortest':
reflen = min... | ['def', 'cook_refs(refs,', 'eff=None,', 'n=4):', 'reflen', '=', '[]', 'maxcounts', '=', 'dict()', 'for', 'ref', 'in', 'refs:', '(rl,', 'counts)', '=', 'precook(ref,', 'n)', 'reflen.append(rl)', 'for', '(ngram,', 'count)', 'in', 'counts.items():', 'maxcounts[ngram]', '=', 'max(maxcounts.get(ngram,', '0),', 'count)', 'if... | 580,468 |
enuguru/artificial_intelligence_and_machine_learning | testing.py | is_abstract_method | is_abstract_method | Returns True if the given object has __isabstractmethod__ == True. | [
"Returns",
"True",
"if",
"the",
"given",
"object",
"has",
"__isabstractmethod__",
"==",
"True."
] | def is_abstract_method(attr):
return hasattr(attr, '__isabstractmethod__') and getattr(attr, '__isabstractmethod__') | ['def', 'is_abstract_method(attr):', 'return', 'hasattr(attr,', "'__isabstractmethod__')", 'and', 'getattr(attr,', "'__isabstractmethod__')"] | 162,795 |
zhengye1995/underwater-object-detection | anchor_head.py | AnchorHead.get_bboxes_single | get_bboxes_single | Transform outputs for a single batch item into labeled boxes. | [
"Transform",
"outputs",
"for",
"a",
"single",
"batch",
"item",
"into",
"labeled",
"boxes."
] | def get_bboxes_single(self, cls_score_list, bbox_pred_list, mlvl_anchors, img_shape, scale_factor, cfg, rescale=False):
assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors)
mlvl_bboxes = []
mlvl_scores = []
for (cls_score, bbox_pred, anchors) in zip(cls_score_list, bbox_pred_list, mlvl... | ['def', 'get_bboxes_single(self,', 'cls_score_list,', 'bbox_pred_list,', 'mlvl_anchors,', 'img_shape,', 'scale_factor,', 'cfg,', 'rescale=False):', 'assert', 'len(cls_score_list)', '==', 'len(bbox_pred_list)', '==', 'len(mlvl_anchors)', 'mlvl_bboxes', '=', '[]', 'mlvl_scores', '=', '[]', 'for', '(cls_score,', 'bbox_pre... | 947,758 |
open-mmlab/mmrotate | image.py | imshow_det_rbboxes | imshow_det_rbboxes | Draw bboxes and class labels (with scores) on an image. | [
"Draw",
"bboxes",
"and",
"class",
"labels",
"(with",
"scores)",
"on",
"an",
"image."
] | def imshow_det_rbboxes(img, bboxes=None, labels=None, segms=None, class_names=None, score_thr=0, bbox_color='green', text_color='green', mask_color=None, thickness=2, font_size=13, win_name='', show=True, wait_time=0, out_file=None):
assert bboxes is None or bboxes.ndim == 2, f' bboxes ndim should be 2, but its ndi... | ['def', 'imshow_det_rbboxes(img,', 'bboxes=None,', 'labels=None,', 'segms=None,', 'class_names=None,', 'score_thr=0,', "bbox_color='green',", "text_color='green',", 'mask_color=None,', 'thickness=2,', 'font_size=13,', "win_name='',", 'show=True,', 'wait_time=0,', 'out_file=None):', 'assert', 'bboxes', 'is', 'None', 'or... | 625,077 |
rudranil723/mini-main | feature.py | Feature.fields | fields | Return a list of fields in the Feature. | [
"Return",
"a",
"list",
"of",
"fields",
"in",
"the",
"Feature."
] | def fields(self):
return [force_text(capi.get_field_name(capi.get_field_defn(self._layer._ldefn, i)), self.encoding, strings_only=True) for i in range(self.num_fields)] | ['def', 'fields(self):', 'return', '[force_text(capi.get_field_name(capi.get_field_defn(self._layer._ldefn,', 'i)),', 'self.encoding,', 'strings_only=True)', 'for', 'i', 'in', 'range(self.num_fields)]'] | 315,072 |
rlberry-py/rlberry | plot_mirror_bandit.py | MirrorBandit.step | step | Sample the reward associated to the action. | [
"Sample",
"the",
"reward",
"associated",
"to",
"the",
"action."
] | def step(self, action):
assert action < self.n_arms
reward = -get_time(self.url_list[action])
terminated = True
truncated = False
return (0, reward, terminated, truncated, {}) | ['def', 'step(self,', 'action):', 'assert', 'action', '<', 'self.n_arms', 'reward', '=', '-get_time(self.url_list[action])', 'terminated', '=', 'True', 'truncated', '=', 'False', 'return', '(0,', 'reward,', 'terminated,', 'truncated,', '{})'] | 861,997 |
intel/neural-compressor | model.py | OnnxrtModel.filtered_input_nodes | filtered_input_nodes | Get filtered input nodes. | [
"Get",
"filtered",
"input",
"nodes."
] | def filtered_input_nodes(self) -> List[Any]:
input_nodes = self.nc_model_instance.graph().input
name_to_input = {}
for input in input_nodes:
name_to_input[input.name] = input
for initializer in self.nc_model_instance.graph().initializer:
if initializer.name in name_to_input:
... | ['def', 'filtered_input_nodes(self)', '->', 'List[Any]:', 'input_nodes', '=', 'self.nc_model_instance.graph().input', 'name_to_input', '=', '{}', 'for', 'input', 'in', 'input_nodes:', 'name_to_input[input.name]', '=', 'input', 'for', 'initializer', 'in', 'self.nc_model_instance.graph().initializer:', 'if', 'initializer... | 721,579 |
jxhe/unify-parameter-efficient-tuning | check_dummies.py | find_backend | find_backend | Find one (or multiple) backend in a code line of the init. | [
"Find",
"one",
"(or",
"multiple)",
"backend",
"in",
"a",
"code",
"line",
"of",
"the",
"init."
] | def find_backend(line):
if _re_test_backend.search(line) is None:
return None
backends = [b[0] for b in _re_backend.findall(line)]
backends.sort()
return '_and_'.join(backends) | ['def', 'find_backend(line):', 'if', '_re_test_backend.search(line)', 'is', 'None:', 'return', 'None', 'backends', '=', '[b[0]', 'for', 'b', 'in', '_re_backend.findall(line)]', 'backends.sort()', 'return', "'_and_'.join(backends)"] | 949,558 |
aalgirdas/Artificial-Intelligence-Course | notebook.py | Canvas.arc_n | arc_n | Similar to arc(), but the dimensions are normalized to fall between 0 and 1 The normalizing factor for radius is selected between width and height by seeing which is smaller. | [
"Similar",
"to",
"arc(),",
"but",
"the",
"dimensions",
"are",
"normalized",
"to",
"fall",
"between",
"0",
"and",
"1",
"The",
"normalizing",
"factor",
"for",
"radius",
"is",
"selected",
"between",
"width",
"and",
"height",
"by",
"seeing",
"which",
"is",
"smal... | def arc_n(self, xn, yn, rn, start, stop):
x = round(xn * self.width)
y = round(yn * self.height)
r = round(rn * min(self.width, self.height))
self.arc(x, y, r, start, stop) | ['def', 'arc_n(self,', 'xn,', 'yn,', 'rn,', 'start,', 'stop):', 'x', '=', 'round(xn', '*', 'self.width)', 'y', '=', 'round(yn', '*', 'self.height)', 'r', '=', 'round(rn', '*', 'min(self.width,', 'self.height))', 'self.arc(x,', 'y,', 'r,', 'start,', 'stop)'] | 79,682 |
scikit-learn/scikit-learn | test_validation.py | test_check_response_method_not_supported_response_method | test_check_response_method_not_supported_response_method | Check the error message when a response method is not supported by the estimator. | [
"Check",
"the",
"error",
"message",
"when",
"a",
"response",
"method",
"is",
"not",
"supported",
"by",
"the",
"estimator."
] | def test_check_response_method_not_supported_response_method(response_method):
err_msg = f'EstimatorWithFit has none of the following attributes: {response_method}.'
with pytest.raises(AttributeError, match=err_msg):
_check_response_method(EstimatorWithFit(), response_method) | ['def', 'test_check_response_method_not_supported_response_method(response_method):', 'err_msg', '=', "f'EstimatorWithFit", 'has', 'none', 'of', 'the', 'following', 'attributes:', "{response_method}.'", 'with', 'pytest.raises(AttributeError,', 'match=err_msg):', '_check_response_method(EstimatorWithFit(),', 'response_m... | 854,416 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | asserts.py | assert_not_islink | assert_not_islink | Assert that path exists but is not a symlink. | [
"Assert",
"that",
"path",
"exists",
"but",
"is",
"not",
"a",
"symlink."
] | def assert_not_islink(path, msg=None):
path = _strpath(path)
st = _stat_for_assert(path, False, msg)
if stat.S_ISLNK(st.st_mode):
if msg is None:
msg = 'Path is a symlink: %r' % path
raise AssertionError(msg) | ['def', 'assert_not_islink(path,', 'msg=None):', 'path', '=', '_strpath(path)', 'st', '=', '_stat_for_assert(path,', 'False,', 'msg)', 'if', 'stat.S_ISLNK(st.st_mode):', 'if', 'msg', 'is', 'None:', 'msg', '=', "'Path", 'is', 'a', 'symlink:', "%r'", '%', 'path', 'raise', 'AssertionError(msg)'] | 437,454 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | test_readers.py | engine_and_read_ext | engine_and_read_ext | Fixture for Excel reader engine and read_ext, only including valid pairs. | [
"Fixture",
"for",
"Excel",
"reader",
"engine",
"and",
"read_ext,",
"only",
"including",
"valid",
"pairs."
] | def engine_and_read_ext(request):
return request.param | ['def', 'engine_and_read_ext(request):', 'return', 'request.param'] | 83,496 |
CosmiQ/solaris | test_mask.py | TestContactMask.test_make_contact_mask_w_save | test_make_contact_mask_w_save | test creating a contact point mask. | [
"test",
"creating",
"a",
"contact",
"point",
"mask."
] | def test_make_contact_mask_w_save(self):
output_mask = contact_mask(os.path.join(data_dir, 'sample.csv'), geom_col='PolygonWKT_Pix', contact_spacing=10, reference_im=os.path.join(data_dir, 'sample_geotiff.tif'), out_file=os.path.join(data_dir, 'test_out.tif'))
truth_mask = skimage.io.imread(os.path.join(data_di... | ['def', 'test_make_contact_mask_w_save(self):', 'output_mask', '=', 'contact_mask(os.path.join(data_dir,', "'sample.csv'),", "geom_col='PolygonWKT_Pix',", 'contact_spacing=10,', 'reference_im=os.path.join(data_dir,', "'sample_geotiff.tif'),", 'out_file=os.path.join(data_dir,', "'test_out.tif'))", 'truth_mask', '=', 'sk... | 879,459 |
ivanmontero/autobot | utils.py | use_task_specific_params | use_task_specific_params | Update config with summarization specific params. | [
"Update",
"config",
"with",
"summarization",
"specific",
"params."
] | def use_task_specific_params(model, task):
task_specific_params = model.config.task_specific_params
if task_specific_params is not None:
pars = task_specific_params.get(task, {})
logger.info(f'using task specific params for {task}: {pars}')
model.config.update(pars) | ['def', 'use_task_specific_params(model,', 'task):', 'task_specific_params', '=', 'model.config.task_specific_params', 'if', 'task_specific_params', 'is', 'not', 'None:', 'pars', '=', 'task_specific_params.get(task,', '{})', "logger.info(f'using", 'task', 'specific', 'params', 'for', '{task}:', "{pars}')", 'model.confi... | 417,742 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | console_widget.py | ConsoleWidget.print_ | print_ | Print the contents of the ConsoleWidget to the specified QPrinter. | [
"Print",
"the",
"contents",
"of",
"the",
"ConsoleWidget",
"to",
"the",
"specified",
"QPrinter."
] | def print_(self, printer=None):
if not printer:
printer = QtPrintSupport.QPrinter()
if QtPrintSupport.QPrintDialog(printer).exec_() != QtPrintSupport.QPrintDialog.Accepted:
return
self._control.print_(printer) | ['def', 'print_(self,', 'printer=None):', 'if', 'not', 'printer:', 'printer', '=', 'QtPrintSupport.QPrinter()', 'if', 'QtPrintSupport.QPrintDialog(printer).exec_()', '!=', 'QtPrintSupport.QPrintDialog.Accepted:', 'return', 'self._control.print_(printer)'] | 435,824 |
awslabs/mxnet-lambda | pildriver.py | PILDriver.do_clear | do_clear | usage: clear Clear the stack. | [
"usage:",
"clear",
"Clear",
"the",
"stack."
] | def do_clear(self):
self.stack = [] | ['def', 'do_clear(self):', 'self.stack', '=', '[]'] | 266,887 |
sunishsheth2009/ChatterBot | sessions.py | SessionStore.save_if_modified | save_if_modified | Save if a session class wants an update. | [
"Save",
"if",
"a",
"session",
"class",
"wants",
"an",
"update."
] | def save_if_modified(self, session):
if session.should_save:
self.save(session) | ['def', 'save_if_modified(self,', 'session):', 'if', 'session.should_save:', 'self.save(session)'] | 483,734 |
ChenhongyiYang/PPAL | test_head.py | test_retinanet_head_onnx_export | test_retinanet_head_onnx_export | Test RetinaNet Head _get_bboxes() in torch and onnxruntime env. | [
"Test",
"RetinaNet",
"Head",
"_get_bboxes()",
"in",
"torch",
"and",
"onnxruntime",
"env."
] | def test_retinanet_head_onnx_export():
retina_model = retinanet_config()
s = 128
img_metas = [{'img_shape_for_onnx': torch.Tensor([s, s]), 'scale_factor': np.ones(4), 'pad_shape': (s, s, 3), 'img_shape': (s, s, 2)}]
retina_head_data = 'retina_head_get_bboxes.pkl'
feats = mmcv.load(osp.join(data_path... | ['def', 'test_retinanet_head_onnx_export():', 'retina_model', '=', 'retinanet_config()', 's', '=', '128', 'img_metas', '=', "[{'img_shape_for_onnx':", 'torch.Tensor([s,', 's]),', "'scale_factor':", 'np.ones(4),', "'pad_shape':", '(s,', 's,', '3),', "'img_shape':", '(s,', 's,', '2)}]', 'retina_head_data', '=', "'retina_... | 821,892 |
Kvatsx/Artificial-Intelligence-Assignments | _tifffile.py | TiffFile.pilatus_metadata | pilatus_metadata | Return Pilatus metadata from image description as dict. | [
"Return",
"Pilatus",
"metadata",
"from",
"image",
"description",
"as",
"dict."
] | def pilatus_metadata(self):
if not self.is_pilatus:
return
return pilatus_description_metadata(self.pages[0].description) | ['def', 'pilatus_metadata(self):', 'if', 'not', 'self.is_pilatus:', 'return', 'return', 'pilatus_description_metadata(self.pages[0].description)'] | 37,588 |
liaorongfan/DeepPersonality | config_mm.py | Config.fromstring | fromstring | Generate config from config str. | [
"Generate",
"config",
"from",
"config",
"str."
] | def fromstring(cfg_str, file_format):
if file_format not in ['.py', '.json', '.yaml', '.yml']:
raise IOError('Only py/yml/yaml/json type are supported now!')
if file_format != '.py' and 'dict(' in cfg_str:
warnings.warn('Please check "file_format", the file format may be .py')
with tempfile.... | ['def', 'fromstring(cfg_str,', 'file_format):', 'if', 'file_format', 'not', 'in', "['.py',", "'.json',", "'.yaml',", "'.yml']:", 'raise', "IOError('Only", 'py/yml/yaml/json', 'type', 'are', 'supported', "now!')", 'if', 'file_format', '!=', "'.py'", 'and', "'dict('", 'in', 'cfg_str:', "warnings.warn('Please", 'check', '... | 539,239 |
brohrer/autoencoder_visualization | construct_viz.py | plot_connection | plot_connection | Represent the weights connecting nodes in one layer to nodes in the next. | [
"Represent",
"the",
"weights",
"connecting",
"nodes",
"in",
"one",
"layer",
"to",
"nodes",
"in",
"the",
"next."
] | def plot_connection(ax_boss, x0, x1, y0, y1, width=1, weight=None):
x = np.linspace(x0, x1, num=50)
y = y0 + (y1 - y0) * (-np.cos(np.pi * (x - x0) / (x1 - x0)) + 1) / 2
if weight is None:
weight = np.random.sample() * 2 - 1
if weight > 0:
linewidth = width * weight
ax_boss.plot(x... | ['def', 'plot_connection(ax_boss,', 'x0,', 'x1,', 'y0,', 'y1,', 'width=1,', 'weight=None):', 'x', '=', 'np.linspace(x0,', 'x1,', 'num=50)', 'y', '=', 'y0', '+', '(y1', '-', 'y0)', '*', '(-np.cos(np.pi', '*', '(x', '-', 'x0)', '/', '(x1', '-', 'x0))', '+', '1)', '/', '2', 'if', 'weight', 'is', 'None:', 'weight', '=', 'n... | 419,706 |
sunishsheth2009/ChatterBot | sessions.py | SessionInterface.get_cookie_domain | get_cookie_domain | Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used. | [
"Helpful",
"helper",
"method",
"that",
"returns",
"the",
"cookie",
"domain",
"that",
"should",
"be",
"used",
"for",
"the",
"session",
"cookie",
"if",
"session",
"cookies",
"are",
"used."
] | def get_cookie_domain(self, app):
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
if app.config['SERVER_NAME'] is not None:
return '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] | ['def', 'get_cookie_domain(self,', 'app):', 'if', "app.config['SESSION_COOKIE_DOMAIN']", 'is', 'not', 'None:', 'return', "app.config['SESSION_COOKIE_DOMAIN']", 'if', "app.config['SERVER_NAME']", 'is', 'not', 'None:', 'return', "'.'", '+', "app.config['SERVER_NAME'].rsplit(':',", '1)[0]'] | 478,797 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | graph_builder.py | MasterBuilder.add_post_restore_hook | add_post_restore_hook | Adds the post restore ops. | [
"Adds",
"the",
"post",
"restore",
"ops."
] | def add_post_restore_hook(self, name_scope):
with tf.name_scope(name_scope):
return self.build_post_restore_hook() | ['def', 'add_post_restore_hook(self,', 'name_scope):', 'with', 'tf.name_scope(name_scope):', 'return', 'self.build_post_restore_hook()'] | 28,265 |
ryu-ed/SpaceInvaders_Ros | tableparser.py | GridTableParser.structure_from_cells | structure_from_cells | From the data collected by `scan_cell()`, convert to the final data structure. | [
"From",
"the",
"data",
"collected",
"by",
"`scan_cell()`,",
"convert",
"to",
"the",
"final",
"data",
"structure."
] | def structure_from_cells(self):
rowseps = sorted(self.rowseps.keys())
rowindex = {}
for i in range(len(rowseps)):
rowindex[rowseps[i]] = i
colseps = sorted(self.colseps.keys())
colindex = {}
for i in range(len(colseps)):
colindex[colseps[i]] = i
colspecs = [colseps[i] - colse... | ['def', 'structure_from_cells(self):', 'rowseps', '=', 'sorted(self.rowseps.keys())', 'rowindex', '=', '{}', 'for', 'i', 'in', 'range(len(rowseps)):', 'rowindex[rowseps[i]]', '=', 'i', 'colseps', '=', 'sorted(self.colseps.keys())', 'colindex', '=', '{}', 'for', 'i', 'in', 'range(len(colseps)):', 'colindex[colseps[i]]',... | 394,926 |
Ruturaj123/Flowchart-Detection | deprecation.py | deprecated_argument_lookup | deprecated_argument_lookup | Looks up deprecated argument name and ensures both are not used. | [
"Looks",
"up",
"deprecated",
"argument",
"name",
"and",
"ensures",
"both",
"are",
"not",
"used."
] | def deprecated_argument_lookup(new_name, new_value, old_name, old_value):
if old_value is not None:
if new_value is not None:
raise ValueError("Cannot specify both '%s' and '%s'" % (old_name, new_name))
return old_value
return new_value | ['def', 'deprecated_argument_lookup(new_name,', 'new_value,', 'old_name,', 'old_value):', 'if', 'old_value', 'is', 'not', 'None:', 'if', 'new_value', 'is', 'not', 'None:', 'raise', 'ValueError("Cannot', 'specify', 'both', "'%s'", 'and', '\'%s\'"', '%', '(old_name,', 'new_name))', 'return', 'old_value', 'return', 'new_v... | 606,643 |
omarmhaimdat/twitter_nlp_native_swift | exceptions.py | HTTPException.get_body | get_body | Get the HTML body. | [
"Get",
"the",
"HTML",
"body."
] | def get_body(self, environ=None):
return text_type(u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>%(code)s %(name)s</title>\n<h1>%(name)s</h1>\n%(description)s\n' % {'code': self.code, 'name': escape(self.name), 'description': self.get_description(environ)}) | ['def', 'get_body(self,', 'environ=None):', 'return', "text_type(u'<!DOCTYPE", 'HTML', 'PUBLIC', '"-//W3C//DTD', 'HTML', '3.2', 'Final//EN">\\n<title>%(code)s', "%(name)s</title>\\n<h1>%(name)s</h1>\\n%(description)s\\n'", '%', "{'code':", 'self.code,', "'name':", 'escape(self.name),', "'description':", 'self.get_descr... | 955,292 |
rlgraph/rlgraph | test_single_components.py | TestSingleComponents.test_1to2_component | test_1to2_component | Adds a single component with 1-to-2 graph_fn to the core and passes a value through it. | [
"Adds",
"a",
"single",
"component",
"with",
"1-to-2",
"graph_fn",
"to",
"the",
"core",
"and",
"passes",
"a",
"value",
"through",
"it."
] | def test_1to2_component(self):
component = Dummy1To2(scope='dummy', constant_value=1.3)
test = ComponentTest(component=component, input_spaces=dict(input_=float))
test.test(('run', 1.0), expected_outputs=[2.3, 1.3])
test.test(('run', 4.6), expected_outputs=[5.9, 5.98], decimals=3) | ['def', 'test_1to2_component(self):', 'component', '=', "Dummy1To2(scope='dummy',", 'constant_value=1.3)', 'test', '=', 'ComponentTest(component=component,', 'input_spaces=dict(input_=float))', "test.test(('run',", '1.0),', 'expected_outputs=[2.3,', '1.3])', "test.test(('run',", '4.6),', 'expected_outputs=[5.9,', '5.98... | 862,774 |
sek788432/Waymo-2D-Object-Detection | yamnet.py | yamnet_frames_model | yamnet_frames_model | Defines the YAMNet waveform-to-class-scores model. | [
"Defines",
"the",
"YAMNet",
"waveform-to-class-scores",
"model."
] | def yamnet_frames_model(params):
waveform = layers.Input(batch_shape=(None,), dtype=tf.float32)
waveform_padded = features_lib.pad_waveform(waveform, params)
(log_mel_spectrogram, features) = features_lib.waveform_to_log_mel_spectrogram_patches(waveform_padded, params)
(predictions, embeddings) = yamnet... | ['def', 'yamnet_frames_model(params):', 'waveform', '=', 'layers.Input(batch_shape=(None,),', 'dtype=tf.float32)', 'waveform_padded', '=', 'features_lib.pad_waveform(waveform,', 'params)', '(log_mel_spectrogram,', 'features)', '=', 'features_lib.waveform_to_log_mel_spectrogram_patches(waveform_padded,', 'params)', '(pr... | 973,994 |
surafelml/adapt-mnmt | vocab.py | Vocab.load | load | Loads a serialized vocabulary. | [
"Loads",
"a",
"serialized",
"vocabulary."
] | def load(self, path, file_format='default'):
with compat.gfile_open(path, mode='rb') as vocab:
for line in vocab:
if file_format == 'default':
self.add(line[:-1])
elif file_format == 'sentencepiece':
(token, _) = line.rstrip().split(b'\t')
... | ['def', 'load(self,', 'path,', "file_format='default'):", 'with', 'compat.gfile_open(path,', "mode='rb')", 'as', 'vocab:', 'for', 'line', 'in', 'vocab:', 'if', 'file_format', '==', "'default':", 'self.add(line[:-1])', 'elif', 'file_format', '==', "'sentencepiece':", '(token,', '_)', '=', "line.rstrip().split(b'\\t')", ... | 407,890 |
cvhciKIT/sloth | cli.py | BaseCommand.create_parser | create_parser | Create and return the ``OptionParser`` which will be used to parse the arguments to this command. | [
"Create",
"and",
"return",
"the",
"``OptionParser``",
"which",
"will",
"be",
"used",
"to",
"parse",
"the",
"arguments",
"to",
"this",
"command."
] | def create_parser(self, prog_name, subcommand):
return OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.option_list) | ['def', 'create_parser(self,', 'prog_name,', 'subcommand):', 'return', 'OptionParser(prog=prog_name,', 'usage=self.usage(subcommand),', 'version=self.get_version(),', 'option_list=self.option_list)'] | 878,368 |
aeon-toolkit/aeon | test_segmentation_metrics.py | exact_match | exact_match | Change points with exact match. | [
"Change",
"points",
"with",
"exact",
"match."
] | def exact_match():
change_points = list(range(5))
return (change_points, change_points) | ['def', 'exact_match():', 'change_points', '=', 'list(range(5))', 'return', '(change_points,', 'change_points)'] | 399,791 |
rudranil723/mini-main | logging_pool.py | pool | pool | Creates a thread pool that logs exceptions raised by the tasks within it. | [
"Creates",
"a",
"thread",
"pool",
"that",
"logs",
"exceptions",
"raised",
"by",
"the",
"tasks",
"within",
"it."
] | def pool(max_workers):
return _LoggingPool(futures.ThreadPoolExecutor(max_workers)) | ['def', 'pool(max_workers):', 'return', '_LoggingPool(futures.ThreadPoolExecutor(max_workers))'] | 318,666 |
ADLab3Ds/TiG-BEV | cam_points.py | CameraPoints.convert_to | convert_to | Convert self to ``dst`` mode. | [
"Convert",
"self",
"to",
"``dst``",
"mode."
] | def convert_to(self, dst, rt_mat=None):
from mmdet3d.core.bbox import Coord3DMode
return Coord3DMode.convert_point(point=self, src=Coord3DMode.CAM, dst=dst, rt_mat=rt_mat) | ['def', 'convert_to(self,', 'dst,', 'rt_mat=None):', 'from', 'mmdet3d.core.bbox', 'import', 'Coord3DMode', 'return', 'Coord3DMode.convert_point(point=self,', 'src=Coord3DMode.CAM,', 'dst=dst,', 'rt_mat=rt_mat)'] | 916,846 |
ADLab3Ds/TiG-BEV | delta_xyzwhlr_bbox_coder.py | DeltaXYZWLHRBBoxCoder.encode | encode | Get box regression transformation deltas (dx, dy, dz, dw, dh, dl, dr, dv*) that can be used to transform the `src_boxes` into the `target_boxes`. | [
"Get",
"box",
"regression",
"transformation",
"deltas",
"(dx,",
"dy,",
"dz,",
"dw,",
"dh,",
"dl,",
"dr,",
"dv*)",
"that",
"can",
"be",
"used",
"to",
"transform",
"the",
"`src_boxes`",
"into",
"the",
"`target_boxes`."
] | def encode(src_boxes, dst_boxes):
box_ndim = src_boxes.shape[-1]
(cas, cgs, cts) = ([], [], [])
if box_ndim > 7:
(xa, ya, za, wa, la, ha, ra, *cas) = torch.split(src_boxes, 1, dim=-1)
(xg, yg, zg, wg, lg, hg, rg, *cgs) = torch.split(dst_boxes, 1, dim=-1)
cts = [g - a for (g, a) in zi... | ['def', 'encode(src_boxes,', 'dst_boxes):', 'box_ndim', '=', 'src_boxes.shape[-1]', '(cas,', 'cgs,', 'cts)', '=', '([],', '[],', '[])', 'if', 'box_ndim', '>', '7:', '(xa,', 'ya,', 'za,', 'wa,', 'la,', 'ha,', 'ra,', '*cas)', '=', 'torch.split(src_boxes,', '1,', 'dim=-1)', '(xg,', 'yg,', 'zg,', 'wg,', 'lg,', 'hg,', 'rg,'... | 916,716 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | graph_builder.py | GreedyParser.AddPretrainedEmbeddings | AddPretrainedEmbeddings | Embeddings at the given index will be set to pretrained values. | [
"Embeddings",
"at",
"the",
"given",
"index",
"will",
"be",
"set",
"to",
"pretrained",
"values."
] | def AddPretrainedEmbeddings(self, index, embeddings_path, task_context):
def _Initializer(shape, dtype=tf.float32, partition_info=None):
unused_dtype = dtype
(seed1, seed2) = tf.get_seed(self._seed)
t = gen_parser_ops.word_embedding_initializer(vectors=embeddings_path, task_context=task_con... | ['def', 'AddPretrainedEmbeddings(self,', 'index,', 'embeddings_path,', 'task_context):', 'def', '_Initializer(shape,', 'dtype=tf.float32,', 'partition_info=None):', 'unused_dtype', '=', 'dtype', '(seed1,', 'seed2)', '=', 'tf.get_seed(self._seed)', 't', '=', 'gen_parser_ops.word_embedding_initializer(vectors=embeddings_... | 111,738 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | manager.py | KernelManager.has_kernel | has_kernel | Has a kernel been started that we are managing. | [
"Has",
"a",
"kernel",
"been",
"started",
"that",
"we",
"are",
"managing."
] | def has_kernel(self):
return self.kernel is not None | ['def', 'has_kernel(self):', 'return', 'self.kernel', 'is', 'not', 'None'] | 449,836 |
voxel51/fiftyone | iou.py | compute_segment_ious | compute_segment_ious | Computes the pairwise IoUs between the predicted and ground truth temporal detections. | [
"Computes",
"the",
"pairwise",
"IoUs",
"between",
"the",
"predicted",
"and",
"ground",
"truth",
"temporal",
"detections."
] | def compute_segment_ious(preds, gts):
if not preds or not gts:
return np.zeros((len(preds), len(gts)))
return _compute_segment_ious(preds, gts) | ['def', 'compute_segment_ious(preds,', 'gts):', 'if', 'not', 'preds', 'or', 'not', 'gts:', 'return', 'np.zeros((len(preds),', 'len(gts)))', 'return', '_compute_segment_ious(preds,', 'gts)'] | 584,073 |
kubeflow/pipelines | _container_op.py | Container.set_tty | set_tty | Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. | [
"Whether",
"this",
"container",
"should",
"allocate",
"a",
"TTY",
"for",
"itself,",
"also",
"requires",
"'stdin'",
"to",
"be",
"true."
] | def set_tty(self, tty: bool=True) -> 'Container':
self.tty = tty
return self | ['def', 'set_tty(self,', 'tty:', 'bool=True)', '->', "'Container':", 'self.tty', '=', 'tty', 'return', 'self'] | 780,131 |
tobegit3hub/deep_image_model | base.py | load_csv_without_header | load_csv_without_header | Load dataset from CSV file without a header row. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"without",
"a",
"header",
"row."
] | def load_csv_without_header(filename, target_dtype, features_dtype, target_column=-1):
with gfile.Open(filename) as csv_file:
data_file = csv.reader(csv_file)
(data, target) = ([], [])
for row in data_file:
target.append(row.pop(target_column))
data.append(np.asarray(... | ['def', 'load_csv_without_header(filename,', 'target_dtype,', 'features_dtype,', 'target_column=-1):', 'with', 'gfile.Open(filename)', 'as', 'csv_file:', 'data_file', '=', 'csv.reader(csv_file)', '(data,', 'target)', '=', '([],', '[])', 'for', 'row', 'in', 'data_file:', 'target.append(row.pop(target_column))', 'data.ap... | 181,623 |
awslabs/mxnet-lambda | pildriver.py | PILDriver.do_size | do_size | usage: size <image:pic1> Push the image size on the stack as (y, x). | [
"usage:",
"size",
"<image:pic1>",
"Push",
"the",
"image",
"size",
"on",
"the",
"stack",
"as",
"(y,",
"x)."
] | def do_size(self):
size = self.do_pop().size
self.push(size[0])
self.push(size[1]) | ['def', 'do_size(self):', 'size', '=', 'self.do_pop().size', 'self.push(size[0])', 'self.push(size[1])'] | 266,914 |
arshpreetsingh/quantopian-machinelearning | _in_process.py | prepare_metadata_for_build_wheel | prepare_metadata_for_build_wheel | Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined. | [
"Invoke",
"optional",
"prepare_metadata_for_build_wheel",
"Implements",
"a",
"fallback",
"by",
"building",
"a",
"wheel",
"if",
"the",
"hook",
"isn't",
"defined."
] | def prepare_metadata_for_build_wheel(metadata_directory, config_settings):
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
return _get_wheel_metadata_from_wheel(backend, metadata_directory, config_settings)
else:
return hook(... | ['def', 'prepare_metadata_for_build_wheel(metadata_directory,', 'config_settings):', 'backend', '=', '_build_backend()', 'try:', 'hook', '=', 'backend.prepare_metadata_for_build_wheel', 'except', 'AttributeError:', 'return', '_get_wheel_metadata_from_wheel(backend,', 'metadata_directory,', 'config_settings)', 'else:', ... | 891,646 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | check.py | Same | Same | Raises an error if the list of |values| are not all equal. | [
"Raises",
"an",
"error",
"if",
"the",
"list",
"of",
"|values|",
"are",
"not",
"all",
"equal."
] | def Same(values, message='', error=ValueError):
if not all([value == values[0] for value in values]):
raise error('Expected %s to equal each other: %s' % (values, message)) | ['def', 'Same(values,', "message='',", 'error=ValueError):', 'if', 'not', 'all([value', '==', 'values[0]', 'for', 'value', 'in', 'values]):', 'raise', "error('Expected", '%s', 'to', 'equal', 'each', 'other:', "%s'", '%', '(values,', 'message))'] | 29,036 |
myothida/Supervised-Machine-Learning | kernels.py | StationaryKernelMixin.is_stationary | is_stationary | Returns whether the kernel is stationary. | [
"Returns",
"whether",
"the",
"kernel",
"is",
"stationary."
] | def is_stationary(self):
return True | ['def', 'is_stationary(self):', 'return', 'True'] | 363,956 |
deepmind/dm_control | core.py | save_last_parsed_model_to_xml | save_last_parsed_model_to_xml | Writes a description of the most recently loaded model to an MJCF XML file. | [
"Writes",
"a",
"description",
"of",
"the",
"most",
"recently",
"loaded",
"model",
"to",
"an",
"MJCF",
"XML",
"file."
] | def save_last_parsed_model_to_xml(xml_path, check_model=None):
if check_model and check_model.ptr is not _LAST_PARSED_MODEL_PTR:
raise ValueError(_NOT_LAST_PARSED_ERROR)
mujoco.mj_saveLastXML(xml_path, _LAST_PARSED_MODEL_PTR) | ['def', 'save_last_parsed_model_to_xml(xml_path,', 'check_model=None):', 'if', 'check_model', 'and', 'check_model.ptr', 'is', 'not', '_LAST_PARSED_MODEL_PTR:', 'raise', 'ValueError(_NOT_LAST_PARSED_ERROR)', 'mujoco.mj_saveLastXML(xml_path,', '_LAST_PARSED_MODEL_PTR)'] | 165,315 |
piggyandy/artificial-intelligence | test_numerictypes.py | normalize_descr | normalize_descr | Normalize a description adding the platform byteorder. | [
"Normalize",
"a",
"description",
"adding",
"the",
"platform",
"byteorder."
] | def normalize_descr(descr):
out = []
for item in descr:
dtype = item[1]
if isinstance(dtype, str):
if dtype[0] not in ['|', '<', '>']:
onebyte = dtype[1:] == '1'
if onebyte or dtype[0] in ['S', 'V', 'b']:
dtype = '|' + dtype
... | ['def', 'normalize_descr(descr):', 'out', '=', '[]', 'for', 'item', 'in', 'descr:', 'dtype', '=', 'item[1]', 'if', 'isinstance(dtype,', 'str):', 'if', 'dtype[0]', 'not', 'in', "['|',", "'<',", "'>']:", 'onebyte', '=', 'dtype[1:]', '==', "'1'", 'if', 'onebyte', 'or', 'dtype[0]', 'in', "['S',", "'V',", "'b']:", 'dtype', ... | 61,613 |
rudranil723/mini-main | common.py | CommonMiddleware.process_response | process_response | When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. | [
"When",
"the",
"status",
"code",
"of",
"the",
"response",
"is",
"404,",
"it",
"may",
"redirect",
"to",
"a",
"path",
"with",
"an",
"appended",
"slash",
"if",
"should_redirect_with_slash()",
"returns",
"True."
] | def process_response(self, request, response):
if response.status_code == 404:
if self.should_redirect_with_slash(request):
return self.response_redirect_class(self.get_full_path_with_slash(request))
if not response.streaming and (not response.has_header('Content-Length')):
response[... | ['def', 'process_response(self,', 'request,', 'response):', 'if', 'response.status_code', '==', '404:', 'if', 'self.should_redirect_with_slash(request):', 'return', 'self.response_redirect_class(self.get_full_path_with_slash(request))', 'if', 'not', 'response.streaming', 'and', '(not', "response.has_header('Content-Len... | 316,354 |
ADLab3Ds/TiG-BEV | h3d_bbox_head.py | H3DBboxHead.get_targets | get_targets | Generate targets of proposal module. | [
"Generate",
"targets",
"of",
"proposal",
"module."
] | def get_targets(self, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask=None, pts_instance_mask=None, bbox_preds=None):
valid_gt_masks = list()
gt_num = list()
for index in range(len(gt_labels_3d)):
if len(gt_labels_3d[index]) == 0:
fake_box = gt_bboxes_3d[index].tensor.new_zeros(1, ... | ['def', 'get_targets(self,', 'points,', 'gt_bboxes_3d,', 'gt_labels_3d,', 'pts_semantic_mask=None,', 'pts_instance_mask=None,', 'bbox_preds=None):', 'valid_gt_masks', '=', 'list()', 'gt_num', '=', 'list()', 'for', 'index', 'in', 'range(len(gt_labels_3d)):', 'if', 'len(gt_labels_3d[index])', '==', '0:', 'fake_box', '=',... | 917,109 |
michellesri/cs188 | capture.py | GameState.getScore | getScore | Returns a number corresponding to the current score. | [
"Returns",
"a",
"number",
"corresponding",
"to",
"the",
"current",
"score."
] | def getScore(self):
return self.data.score | ['def', 'getScore(self):', 'return', 'self.data.score'] | 224,020 |
RasaHQ/rasa | test_importer.py | test_subintent_response_matches_with_action | test_subintent_response_matches_with_action | Tests retrieval intent responses are matched correctly to actions. | [
"Tests",
"retrieval",
"intent",
"responses",
"are",
"matched",
"correctly",
"to",
"actions."
] | def test_subintent_response_matches_with_action(project: Text):
config_path = os.path.join(project, DEFAULT_CONFIG_PATH)
domain_path = 'data/test_domains/simple_retrieval_intent.yml'
data_path = 'data/test/simple_retrieval_intent_nlu.yml'
importer = TrainingDataImporter.load_from_dict({}, config_path, d... | ['def', 'test_subintent_response_matches_with_action(project:', 'Text):', 'config_path', '=', 'os.path.join(project,', 'DEFAULT_CONFIG_PATH)', 'domain_path', '=', "'data/test_domains/simple_retrieval_intent.yml'", 'data_path', '=', "'data/test/simple_retrieval_intent_nlu.yml'", 'importer', '=', 'TrainingDataImporter.lo... | 838,097 |
caiiiac/Machine-Learning-with-Python | backend_pdf.py | PdfFile.writeTrailer | writeTrailer | Write out the PDF trailer. | [
"Write",
"out",
"the",
"PDF",
"trailer."
] | def writeTrailer(self):
self.write(b'trailer\n')
self.write(pdfRepr({'Size': self.nextObject, 'Root': self.rootObject, 'Info': self.infoObject}))
self.write(('\nstartxref\n%d\n%%%%EOF\n' % self.startxref).encode('ascii')) | ['def', 'writeTrailer(self):', "self.write(b'trailer\\n')", "self.write(pdfRepr({'Size':", 'self.nextObject,', "'Root':", 'self.rootObject,', "'Info':", 'self.infoObject}))', "self.write(('\\nstartxref\\n%d\\n%%%%EOF\\n'", '%', "self.startxref).encode('ascii'))"] | 716,425 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.