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 |
|---|---|---|---|---|---|---|---|---|
scikit-learn/scikit-learn | test_boundary_decision_display.py | test_multioutput_regressor_error | test_multioutput_regressor_error | Check that multioutput regressor raises correct error. | [
"Check",
"that",
"multioutput",
"regressor",
"raises",
"correct",
"error."
] | def test_multioutput_regressor_error(pyplot):
X = np.asarray([[0, 1], [1, 2]])
y = np.asarray([[0, 1], [4, 1]])
tree = DecisionTreeRegressor().fit(X, y)
with pytest.raises(ValueError, match='Multi-output regressors are not supported'):
DecisionBoundaryDisplay.from_estimator(tree, X) | ['def', 'test_multioutput_regressor_error(pyplot):', 'X', '=', 'np.asarray([[0,', '1],', '[1,', '2]])', 'y', '=', 'np.asarray([[0,', '1],', '[4,', '1]])', 'tree', '=', 'DecisionTreeRegressor().fit(X,', 'y)', 'with', 'pytest.raises(ValueError,', "match='Multi-output", 'regressors', 'are', 'not', "supported'):", 'Decisio... | 853,460 |
alex-petrenko/sample-factory | utils.py | numpy_all_the_way | numpy_all_the_way | Turn a list of numpy arrays into a 2D numpy array. | [
"Turn",
"a",
"list",
"of",
"numpy",
"arrays",
"into",
"a",
"2D",
"numpy",
"array."
] | def numpy_all_the_way(list_of_arrays):
shape = list(list_of_arrays[0].shape)
shape[:0] = [len(list_of_arrays)]
arr = np.concatenate(list_of_arrays).reshape(shape)
return arr | ['def', 'numpy_all_the_way(list_of_arrays):', 'shape', '=', 'list(list_of_arrays[0].shape)', 'shape[:0]', '=', '[len(list_of_arrays)]', 'arr', '=', 'np.concatenate(list_of_arrays).reshape(shape)', 'return', 'arr'] | 329,193 |
CLARIN-PL/embeddings | datamodule.py | TextClassificationDataModule.convert_to_features | convert_to_features | Encodes either single sentence or sentence pairs. | [
"Encodes",
"either",
"single",
"sentence",
"or",
"sentence",
"pairs."
] | def convert_to_features(self, example_batch: Dict[str, Any], indices: Optional[List[int]]=None) -> BatchEncoding:
if len(self.text_fields) == 2:
texts_or_text_pairs = list(zip(example_batch[self.text_fields[0]], example_batch[self.text_fields[1]]))
elif len(self.text_fields) == 1:
texts_or_text_... | ['def', 'convert_to_features(self,', 'example_batch:', 'Dict[str,', 'Any],', 'indices:', 'Optional[List[int]]=None)', '->', 'BatchEncoding:', 'if', 'len(self.text_fields)', '==', '2:', 'texts_or_text_pairs', '=', 'list(zip(example_batch[self.text_fields[0]],', 'example_batch[self.text_fields[1]]))', 'elif', 'len(self.t... | 561,523 |
zihuitang/medical_AI_platform | __init__.py | Text.tag_raise | tag_raise | Change the priority of tag TAGNAME such that it is higher than the priority of ABOVETHIS. | [
"Change",
"the",
"priority",
"of",
"tag",
"TAGNAME",
"such",
"that",
"it",
"is",
"higher",
"than",
"the",
"priority",
"of",
"ABOVETHIS."
] | def tag_raise(self, tagName, aboveThis=None):
self.tk.call(self._w, 'tag', 'raise', tagName, aboveThis) | ['def', 'tag_raise(self,', 'tagName,', 'aboveThis=None):', 'self.tk.call(self._w,', "'tag',", "'raise',", 'tagName,', 'aboveThis)'] | 284,361 |
OliverKillane/NuNet-Designer | NuNetLibrary.py | Output.getloss | getloss | getloss returns the loss of the output. | [
"getloss",
"returns",
"the",
"loss",
"of",
"the",
"output."
] | def getloss(self) -> float:
return self._activationValue | ['def', 'getloss(self)', '->', 'float:', 'return', 'self._activationValue'] | 730,525 |
hamza-murad/AALU | discovery_v2.py | QueryTableResult.from_dict | from_dict | Initialize a QueryTableResult object from a json dictionary. | [
"Initialize",
"a",
"QueryTableResult",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'QueryTableResult':
args = {}
valid_keys = ['table_id', 'source_document_id', 'collection_id', 'table_html', 'table_html_offset', 'table']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'QueryTableResult':", 'args', '=', '{}', 'valid_keys', '=', "['table_id',", "'source_document_id',", "'collection_id',", "'table_html',", "'table_html_offset',", "'table']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "Val... | 5,778 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | polar.py | PolarAxes.get_rmax | get_rmax | Returns ------- float Outer radial limit. | [
"Returns",
"-------",
"float",
"Outer",
"radial",
"limit."
] | def get_rmax(self):
return self.viewLim.ymax | ['def', 'get_rmax(self):', 'return', 'self.viewLim.ymax'] | 257,770 |
jimtin/Stock_Comparison | utils.py | iso_to_plotly_time_string | iso_to_plotly_time_string | Remove timezone info and replace 'T' delimeter with ' ' (ws). | [
"Remove",
"timezone",
"info",
"and",
"replace",
"'T'",
"delimeter",
"with",
"'",
"'",
"(ws)."
] | def iso_to_plotly_time_string(iso_string):
if iso_string.split('-')[:3] is '00:00' or iso_string.split('+')[0] is '00:00':
raise Exception("Plotly won't accept timestrings with timezone info.\nAll timestrings are assumed to be in UTC.")
iso_string = iso_string.replace('-00:00', '').replace('+00:00', '')... | ['def', 'iso_to_plotly_time_string(iso_string):', 'if', "iso_string.split('-')[:3]", 'is', "'00:00'", 'or', "iso_string.split('+')[0]", 'is', "'00:00':", 'raise', 'Exception("Plotly', "won't", 'accept', 'timestrings', 'with', 'timezone', 'info.\\nAll', 'timestrings', 'are', 'assumed', 'to', 'be', 'in', 'UTC.")', 'iso_s... | 389,203 |
briannemsick/barrage | io_utils.py | save_pickle | save_pickle | Save a pickled object. | [
"Save",
"a",
"pickled",
"object."
] | def save_pickle(obj, filename: str, path: str=''):
with open(os.path.join(path, filename), 'wb') as fn:
pickle.dump(obj, fn) | ['def', 'save_pickle(obj,', 'filename:', 'str,', 'path:', "str=''):", 'with', 'open(os.path.join(path,', 'filename),', "'wb')", 'as', 'fn:', 'pickle.dump(obj,', 'fn)'] | 94,319 |
voxel51/fiftyone | view.py | DatasetView.is_saved | is_saved | Whether the view is a saved view or not. | [
"Whether",
"the",
"view",
"is",
"a",
"saved",
"view",
"or",
"not."
] | def is_saved(self):
return self.__name is not None | ['def', 'is_saved(self):', 'return', 'self.__name', 'is', 'not', 'None'] | 583,489 |
calico/basenji | basenji_sat_plot2.py | subplot_params | subplot_params | Specify subplot layout parameters for various sequence lengths. | [
"Specify",
"subplot",
"layout",
"parameters",
"for",
"various",
"sequence",
"lengths."
] | def subplot_params(seq_len):
if seq_len < 500:
spp = {'heat_cols': 400, 'sad_start': 1, 'sad_span': 321, 'logo_start': 0, 'logo_span': 323}
else:
spp = {'heat_cols': 400, 'sad_start': 1, 'sad_span': 320, 'logo_start': 0, 'logo_span': 322}
return spp | ['def', 'subplot_params(seq_len):', 'if', 'seq_len', '<', '500:', 'spp', '=', "{'heat_cols':", '400,', "'sad_start':", '1,', "'sad_span':", '321,', "'logo_start':", '0,', "'logo_span':", '323}', 'else:', 'spp', '=', "{'heat_cols':", '400,', "'sad_start':", '1,', "'sad_span':", '320,', "'logo_start':", '0,', "'logo_span... | 94,810 |
flavioschneider/rl-transfer- | add_gaussian_noise.py | AddGaussianNoise.get_action | get_action | Get action from this policy for the input observation. | [
"Get",
"action",
"from",
"this",
"policy",
"for",
"the",
"input",
"observation."
] | def get_action(self, observation):
(action, agent_info) = self.policy.get_action(observation)
action = np.clip(action + np.random.normal(size=action.shape) * self._sigma(), self._action_space.low, self._action_space.high)
self._total_env_steps += 1
return (action, agent_info) | ['def', 'get_action(self,', 'observation):', '(action,', 'agent_info)', '=', 'self.policy.get_action(observation)', 'action', '=', 'np.clip(action', '+', 'np.random.normal(size=action.shape)', '*', 'self._sigma(),', 'self._action_space.low,', 'self._action_space.high)', 'self._total_env_steps', '+=', '1', 'return', '(a... | 861,206 |
kubeflow/pipelines | _components.py | load_component_from_file | load_component_from_file | Loads component from file and creates a task factory function. | [
"Loads",
"component",
"from",
"file",
"and",
"creates",
"a",
"task",
"factory",
"function."
] | def load_component_from_file(filename):
component_spec = _load_component_spec_from_file(path=filename)
return _create_task_factory_from_component_spec(component_spec=component_spec, component_filename=filename) | ['def', 'load_component_from_file(filename):', 'component_spec', '=', '_load_component_spec_from_file(path=filename)', 'return', '_create_task_factory_from_component_spec(component_spec=component_spec,', 'component_filename=filename)'] | 780,039 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | TrimmedMean | TrimmedMean | Computes the trimmed mean of a sequence of numbers. | [
"Computes",
"the",
"trimmed",
"mean",
"of",
"a",
"sequence",
"of",
"numbers."
] | def TrimmedMean(t, p=0.01):
t = Trim(t, p)
return Mean(t) | ['def', 'TrimmedMean(t,', 'p=0.01):', 't', '=', 'Trim(t,', 'p)', 'return', 'Mean(t)'] | 19,351 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | base.py | maybe_extract_name | maybe_extract_name | If no name is passed, then extract it from data, validating hashability. | [
"If",
"no",
"name",
"is",
"passed,",
"then",
"extract",
"it",
"from",
"data,",
"validating",
"hashability."
] | def maybe_extract_name(name, obj, cls) -> Label:
if name is None and isinstance(obj, (Index, ABCSeries)):
name = obj.name
if not is_hashable(name):
raise TypeError(f'{cls.__name__}.name must be a hashable type')
return name | ['def', 'maybe_extract_name(name,', 'obj,', 'cls)', '->', 'Label:', 'if', 'name', 'is', 'None', 'and', 'isinstance(obj,', '(Index,', 'ABCSeries)):', 'name', '=', 'obj.name', 'if', 'not', 'is_hashable(name):', 'raise', "TypeError(f'{cls.__name__}.name", 'must', 'be', 'a', 'hashable', "type')", 'return', 'name'] | 453,086 |
secretflow/secretflow | model.py | SSRegression.fit | fit | Fit the model according to the given training data. | [
"Fit",
"the",
"model",
"according",
"to",
"the",
"given",
"training",
"data."
] | def fit(self, x: Union[FedNdarray, VDataFrame], y: Union[FedNdarray, VDataFrame], epochs: int, learning_rate: float=0.1, batch_size: int=1024, sig_type: str='t1', reg_type: str='logistic', penalty: str='None', l2_norm: float=0.5, eps: float=0.001, decay_epoch: int=None, decay_rate: float=None, strategy: str='naive_sgd'... | ['def', 'fit(self,', 'x:', 'Union[FedNdarray,', 'VDataFrame],', 'y:', 'Union[FedNdarray,', 'VDataFrame],', 'epochs:', 'int,', 'learning_rate:', 'float=0.1,', 'batch_size:', 'int=1024,', 'sig_type:', "str='t1',", 'reg_type:', "str='logistic',", 'penalty:', "str='None',", 'l2_norm:', 'float=0.5,', 'eps:', 'float=0.001,',... | 856,532 |
TARGET-SIDE-DATA-AUG/TSDASG | sequence_generator.py | SequenceGenerator.is_finished | is_finished | Check whether decoding for a sentence is finished, which occurs when the list of finalized sentences has reached the beam size, or when we reach the maximum length. | [
"Check",
"whether",
"decoding",
"for",
"a",
"sentence",
"is",
"finished,",
"which",
"occurs",
"when",
"the",
"list",
"of",
"finalized",
"sentences",
"has",
"reached",
"the",
"beam",
"size,",
"or",
"when",
"we",
"reach",
"the",
"maximum",
"length."
] | def is_finished(self, step: int, unfin_idx: int, max_len: int, finalized_sent_len: int, beam_size: int):
assert finalized_sent_len <= beam_size
if finalized_sent_len == beam_size or step == max_len:
return True
return False | ['def', 'is_finished(self,', 'step:', 'int,', 'unfin_idx:', 'int,', 'max_len:', 'int,', 'finalized_sent_len:', 'int,', 'beam_size:', 'int):', 'assert', 'finalized_sent_len', '<=', 'beam_size', 'if', 'finalized_sent_len', '==', 'beam_size', 'or', 'step', '==', 'max_len:', 'return', 'True', 'return', 'False'] | 951,867 |
matsu0228/nlp-jp | test_nbconvertapp.py | TestNbConvertApp.test_pdf | test_pdf | Check to see if pdfs compile, even if strikethroughs are included. | [
"Check",
"to",
"see",
"if",
"pdfs",
"compile,",
"even",
"if",
"strikethroughs",
"are",
"included."
] | def test_pdf(self):
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--log-level 0 --to pdf "notebook2" --PDFExporter.latex_count=1 --PDFExporter.verbose=True')
assert os.path.isfile('notebook2.pdf') | ['def', 'test_pdf(self):', 'with', "self.create_temp_cwd(['notebook2.ipynb']):", "self.nbconvert('--log-level", '0', '--to', 'pdf', '"notebook2"', '--PDFExporter.latex_count=1', "--PDFExporter.verbose=True')", 'assert', "os.path.isfile('notebook2.pdf')"] | 790,307 |
Deeplite/deeplite-torch-zoo | augment.py | Mosaic.get_indexes | get_indexes | Return a list of random indexes from the dataset. | [
"Return",
"a",
"list",
"of",
"random",
"indexes",
"from",
"the",
"dataset."
] | def get_indexes(self, buffer=True):
if buffer:
return random.choices(list(self.dataset.buffer), k=self.n - 1)
else:
return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)] | ['def', 'get_indexes(self,', 'buffer=True):', 'if', 'buffer:', 'return', 'random.choices(list(self.dataset.buffer),', 'k=self.n', '-', '1)', 'else:', 'return', '[random.randint(0,', 'len(self.dataset)', '-', '1)', 'for', '_', 'in', 'range(self.n', '-', '1)]'] | 538,816 |
AgnostiqHQ/covalent | write_result_to_db.py | store_file | store_file | This function writes data corresponding to the filepaths in the DB. | [
"This",
"function",
"writes",
"data",
"corresponding",
"to",
"the",
"filepaths",
"in",
"the",
"DB."
] | def store_file(storage_path: str, filename: str, data: Any=None) -> None:
if filename.endswith('.pkl'):
with open(Path(storage_path) / filename, 'wb') as f:
cloudpickle.dump(data, f)
elif filename.endswith('.log') or filename.endswith('.txt'):
if data is None:
data = ''
... | ['def', 'store_file(storage_path:', 'str,', 'filename:', 'str,', 'data:', 'Any=None)', '->', 'None:', 'if', "filename.endswith('.pkl'):", 'with', 'open(Path(storage_path)', '/', 'filename,', "'wb')", 'as', 'f:', 'cloudpickle.dump(data,', 'f)', 'elif', "filename.endswith('.log')", 'or', "filename.endswith('.txt'):", 'if... | 489,623 |
aws/sagemaker-python-sdk | steps.py | Step.to_request | to_request | Gets the request structure for workflow service calls. | [
"Gets",
"the",
"request",
"structure",
"for",
"workflow",
"service",
"calls."
] | def to_request(self) -> RequestType:
request_dict = {'Name': self.name, 'Type': self.step_type.value, 'Arguments': self.arguments}
if self.depends_on:
request_dict['DependsOn'] = self._resolve_depends_on(self.depends_on)
if self.display_name:
request_dict['DisplayName'] = self.display_name
... | ['def', 'to_request(self)', '->', 'RequestType:', 'request_dict', '=', "{'Name':", 'self.name,', "'Type':", 'self.step_type.value,', "'Arguments':", 'self.arguments}', 'if', 'self.depends_on:', "request_dict['DependsOn']", '=', 'self._resolve_depends_on(self.depends_on)', 'if', 'self.display_name:', "request_dict['Disp... | 830,671 |
psychopa4/MMCNN | BasicConvLSTMCell.py | ConvRNNCell.state_size | state_size | size(s) of state(s) used by this cell. | [
"size(s)",
"of",
"state(s)",
"used",
"by",
"this",
"cell."
] | def state_size(self):
raise NotImplementedError('Abstract method') | ['def', 'state_size(self):', 'raise', "NotImplementedError('Abstract", "method')"] | 240,250 |
MushroomRL/mushroom-rl | viewer.py | MujocoGlfwViewer.read_pixels | read_pixels | Reads the pixels from the glfw viewer. | [
"Reads",
"the",
"pixels",
"from",
"the",
"glfw",
"viewer."
] | def read_pixels(self, depth=False):
shape = glfw.get_framebuffer_size(self._window)
if depth:
rgb_img = np.zeros((shape[1], shape[0], 3), dtype=np.uint8)
depth_img = np.zeros((shape[1], shape[0], 1), dtype=np.float32)
mujoco.mjr_readPixels(rgb_img, depth_img, self._viewport, self._contex... | ['def', 'read_pixels(self,', 'depth=False):', 'shape', '=', 'glfw.get_framebuffer_size(self._window)', 'if', 'depth:', 'rgb_img', '=', 'np.zeros((shape[1],', 'shape[0],', '3),', 'dtype=np.uint8)', 'depth_img', '=', 'np.zeros((shape[1],', 'shape[0],', '1),', 'dtype=np.float32)', 'mujoco.mjr_readPixels(rgb_img,', 'depth_... | 266,209 |
arshpreetsingh/quantopian-machinelearning | interface.py | Waker.write_fileno | write_fileno | Returns the write file descriptor for this waker. | [
"Returns",
"the",
"write",
"file",
"descriptor",
"for",
"this",
"waker."
] | def write_fileno(self):
raise NotImplementedError() | ['def', 'write_fileno(self):', 'raise', 'NotImplementedError()'] | 834,255 |
AndrewYinLi/lstm-neural-network-spam-filter | api.py | CorpusReader.readme | readme | Return the contents of the corpus README file, if it exists. | [
"Return",
"the",
"contents",
"of",
"the",
"corpus",
"README",
"file,",
"if",
"it",
"exists."
] | def readme(self):
return self.open('README').read() | ['def', 'readme(self):', 'return', "self.open('README').read()"] | 217,616 |
thaines/helit | smo.py | SMO.getIndices | getIndices | Returns an array of the indices of the vectors from the input dataset that form the support vectors of the current model, or None if solve has never been called. | [
"Returns",
"an",
"array",
"of",
"the",
"indices",
"of",
"the",
"vectors",
"from",
"the",
"input",
"dataset",
"that",
"form",
"the",
"support",
"vectors",
"of",
"the",
"current",
"model,",
"or",
"None",
"if",
"solve",
"has",
"never",
"been",
"called."
] | def getIndices(self):
return numpy.nonzero(self.alpha >= 0.001)[0] | ['def', 'getIndices(self):', 'return', 'numpy.nonzero(self.alpha', '>=', '0.001)[0]'] | 592,594 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | SpearmanCorr | SpearmanCorr | Computes Spearman's rank correlation. | [
"Computes",
"Spearman's",
"rank",
"correlation."
] | def SpearmanCorr(xs, ys):
xranks = pandas.Series(xs).rank()
yranks = pandas.Series(ys).rank()
return Corr(xranks, yranks) | ['def', 'SpearmanCorr(xs,', 'ys):', 'xranks', '=', 'pandas.Series(xs).rank()', 'yranks', '=', 'pandas.Series(ys).rank()', 'return', 'Corr(xranks,', 'yranks)'] | 19,536 |
SamsungLabs/fcaf3d | h3d_bbox_head.py | H3DBboxHead.get_targets_single | get_targets_single | Generate targets for primitive cues for single batch. | [
"Generate",
"targets",
"for",
"primitive",
"cues",
"for",
"single",
"batch."
] | def get_targets_single(self, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask=None, pts_instance_mask=None, aggregated_points=None, pred_surface_center=None, pred_line_center=None, pred_obj_surface_center=None, pred_obj_line_center=None, pred_surface_sem=None, pred_line_sem=None):
device = points.device
gt... | ['def', 'get_targets_single(self,', 'points,', 'gt_bboxes_3d,', 'gt_labels_3d,', 'pts_semantic_mask=None,', 'pts_instance_mask=None,', 'aggregated_points=None,', 'pred_surface_center=None,', 'pred_line_center=None,', 'pred_obj_surface_center=None,', 'pred_obj_line_center=None,', 'pred_surface_sem=None,', 'pred_line_sem... | 560,524 |
rudranil723/mini-main | exceptions.py | ParseBaseException.lineno | lineno | Return the 1-based line number of text where the exception occurred. | [
"Return",
"the",
"1-based",
"line",
"number",
"of",
"text",
"where",
"the",
"exception",
"occurred."
] | def lineno(self) -> int:
return lineno(self.loc, self.pstr) | ['def', 'lineno(self)', '->', 'int:', 'return', 'lineno(self.loc,', 'self.pstr)'] | 269,454 |
ilya16/MultINN | rnn_multinade.py | RnnMultiNADE.sample_single | sample_single | Computes a sample and its probability from a batch of states. | [
"Computes",
"a",
"sample",
"and",
"its",
"probability",
"from",
"a",
"batch",
"of",
"states."
] | def sample_single(self, inputs, state):
(sample, log_prob) = ([], [])
for i in range(self.num_tracks):
(b_enc, b_dec) = (state.b_enc[i], state.b_dec[i])
(sample_i, log_prob_i) = self._nades[i].sample(b_enc, b_dec, temperature=1.0)
sample.append(sample_i)
log_prob.append(log_prob_... | ['def', 'sample_single(self,', 'inputs,', 'state):', '(sample,', 'log_prob)', '=', '([],', '[])', 'for', 'i', 'in', 'range(self.num_tracks):', '(b_enc,', 'b_dec)', '=', '(state.b_enc[i],', 'state.b_dec[i])', '(sample_i,', 'log_prob_i)', '=', 'self._nades[i].sample(b_enc,', 'b_dec,', 'temperature=1.0)', 'sample.append(s... | 644,264 |
OpenMDAO/OpenMDAO-Framework | hasparameters.py | ParameterGroup.get_config | get_config | Return list of configuration argument tuples. | [
"Return",
"list",
"of",
"configuration",
"argument",
"tuples."
] | def get_config(self):
return [p.get_config() for p in self._params] | ['def', 'get_config(self):', 'return', '[p.get_config()', 'for', 'p', 'in', 'self._params]'] | 275,802 |
k2kobayashi/crank | sinc_conv.py | BarkScale.convert | convert | Convert Hz to Bark. | [
"Convert",
"Hz",
"to",
"Bark."
] | def convert(f):
b = torch.div(f, 1000.0)
b = torch.pow(b, 2.0) * 1.4
b = torch.pow(b + 1.0, 0.69)
return b * 75.0 + 25.0 | ['def', 'convert(f):', 'b', '=', 'torch.div(f,', '1000.0)', 'b', '=', 'torch.pow(b,', '2.0)', '*', '1.4', 'b', '=', 'torch.pow(b', '+', '1.0,', '0.69)', 'return', 'b', '*', '75.0', '+', '25.0'] | 490,667 |
jimtin/Stock_Comparison | testutils.py | skip_if_no_uuid | skip_if_no_uuid | Decorator to skip a test if uuid is not supported by Py/PG. | [
"Decorator",
"to",
"skip",
"a",
"test",
"if",
"uuid",
"is",
"not",
"supported",
"by",
"Py/PG."
] | def skip_if_no_uuid(f):
@wraps(f)
def skip_if_no_uuid_(self):
try:
import uuid
except ImportError:
return self.skipTest('uuid not available in this Python version')
try:
cur = self.conn.cursor()
cur.execute("select typname from pg_type whe... | ['def', 'skip_if_no_uuid(f):', '@wraps(f)', 'def', 'skip_if_no_uuid_(self):', 'try:', 'import', 'uuid', 'except', 'ImportError:', 'return', "self.skipTest('uuid", 'not', 'available', 'in', 'this', 'Python', "version')", 'try:', 'cur', '=', 'self.conn.cursor()', 'cur.execute("select', 'typname', 'from', 'pg_type', 'wher... | 389,345 |
rneilson/rngru | rn_rnn_char.py | ModelState.loadmodel | loadmodel | Attempts to load model parameters first from given file, then from current model file, then from current checkpoint (or file). | [
"Attempts",
"to",
"load",
"model",
"parameters",
"first",
"from",
"given",
"file,",
"then",
"from",
"current",
"model",
"file,",
"then",
"from",
"current",
"checkpoint",
"(or",
"file)."
] | def loadmodel(self, filename=None, fromdir=''):
if filename:
openfile = filename
elif self.modelfile:
openfile = self.modelfile
elif self.cp:
openfile = self.cp.modelfile
elif self.cpfile:
self.cp = Checkpoint.loadcheckpoint(self.cpfile, self.curdir)
if self.cp:
... | ['def', 'loadmodel(self,', 'filename=None,', "fromdir=''):", 'if', 'filename:', 'openfile', '=', 'filename', 'elif', 'self.modelfile:', 'openfile', '=', 'self.modelfile', 'elif', 'self.cp:', 'openfile', '=', 'self.cp.modelfile', 'elif', 'self.cpfile:', 'self.cp', '=', 'Checkpoint.loadcheckpoint(self.cpfile,', 'self.cur... | 324,926 |
ecobost/cnn4brca | train_with_val_split.py | val_split | val_split | Divides the data set into training and validation sets sampling patients at random. | [
"Divides",
"the",
"data",
"set",
"into",
"training",
"and",
"validation",
"sets",
"sampling",
"patients",
"at",
"random."
] | def val_split(csv_path, num_val_patients, model_dir):
with open(csv_path) as csv_file:
lines = csv_file.read().splitlines()
val_patients = set()
while len(val_patients) < num_val_patients:
patient_name = random.choice(lines).split('/')[0]
val_patients.add(patient_name)
val_lines ... | ['def', 'val_split(csv_path,', 'num_val_patients,', 'model_dir):', 'with', 'open(csv_path)', 'as', 'csv_file:', 'lines', '=', 'csv_file.read().splitlines()', 'val_patients', '=', 'set()', 'while', 'len(val_patients)', '<', 'num_val_patients:', 'patient_name', '=', "random.choice(lines).split('/')[0]", 'val_patients.add... | 123,892 |
AlbertPi-Git/Semantic-Recognized-Realtime-Camera-Style-Transfer | gen_efficientnet.py | mixnet_m | mixnet_m | Creates a MixNet Medium model. | [
"Creates",
"a",
"MixNet",
"Medium",
"model."
] | def mixnet_m(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['mixnet_m']
model = _gen_mixnet_m(channel_multiplier=1.0, num_classes=num_classes, in_chans=in_chans, **kwargs)
model.default_cfg = default_cfg
if pretrained:
load_pretrained(model, default_cfg, nu... | ['def', 'mixnet_m(pretrained=False,', 'num_classes=1000,', 'in_chans=3,', '**kwargs):', 'default_cfg', '=', "default_cfgs['mixnet_m']", 'model', '=', '_gen_mixnet_m(channel_multiplier=1.0,', 'num_classes=num_classes,', 'in_chans=in_chans,', '**kwargs)', 'model.default_cfg', '=', 'default_cfg', 'if', 'pretrained:', 'loa... | 844,376 |
clear-nus/MuMMI | dog.py | Stand.get_reward_factors | get_reward_factors | Returns the factorized reward. | [
"Returns",
"the",
"factorized",
"reward."
] | def get_reward_factors(self, physics):
torso = rewards.tolerance(physics.torso_pelvis_height()[0], bounds=(self._stand_height[0], float('inf')), margin=self._stand_height[0])
pelvis = rewards.tolerance(physics.torso_pelvis_height()[1], bounds=(self._stand_height[1], float('inf')), margin=self._stand_height[1])
... | ['def', 'get_reward_factors(self,', 'physics):', 'torso', '=', 'rewards.tolerance(physics.torso_pelvis_height()[0],', 'bounds=(self._stand_height[0],', "float('inf')),", 'margin=self._stand_height[0])', 'pelvis', '=', 'rewards.tolerance(physics.torso_pelvis_height()[1],', 'bounds=(self._stand_height[1],', "float('inf')... | 265,950 |
feast-dev/feast | rockset.py | RocksetOnlineStore.online_read | online_read | Retrieve feature values from the online Rockset store. | [
"Retrieve",
"feature",
"values",
"from",
"the",
"online",
"Rockset",
"store."
] | def online_read(self, config: RepoConfig, table: FeatureView, entity_keys: List[EntityKeyProto], requested_features: Optional[List[str]]=None) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]:
online_config = config.online_store
assert isinstance(online_config, RocksetOnlineStoreConfig)
r... | ['def', 'online_read(self,', 'config:', 'RepoConfig,', 'table:', 'FeatureView,', 'entity_keys:', 'List[EntityKeyProto],', 'requested_features:', 'Optional[List[str]]=None)', '->', 'List[Tuple[Optional[datetime],', 'Optional[Dict[str,', 'ValueProto]]]]:', 'online_config', '=', 'config.online_store', 'assert', 'isinstanc... | 544,484 |
ryu-ed/SpaceInvaders_Ros | player.py | PlayerGroup.play | play | Begin playing all players in the group simultaneously. | [
"Begin",
"playing",
"all",
"players",
"in",
"the",
"group",
"simultaneously."
] | def play(self):
audio_players = [p._audio_player for p in self.players if p._audio_player]
if audio_players:
audio_players[0]._play_group(audio_players)
for player in self.players:
player.play() | ['def', 'play(self):', 'audio_players', '=', '[p._audio_player', 'for', 'p', 'in', 'self.players', 'if', 'p._audio_player]', 'if', 'audio_players:', 'audio_players[0]._play_group(audio_players)', 'for', 'player', 'in', 'self.players:', 'player.play()'] | 369,656 |
intel/neural-compressor | utils.py | convert_PIL_to_numpy | convert_PIL_to_numpy | Convert PIL image to numpy array of target format. | [
"Convert",
"PIL",
"image",
"to",
"numpy",
"array",
"of",
"target",
"format."
] | def convert_PIL_to_numpy(image, format):
if format is not None:
conversion_format = format
if format in ['BGR', 'YUV-BT.601']:
conversion_format = 'RGB'
image = image.convert(conversion_format)
image = np.asarray(image)
if format == 'L':
image = np.expand_dims(ima... | ['def', 'convert_PIL_to_numpy(image,', 'format):', 'if', 'format', 'is', 'not', 'None:', 'conversion_format', '=', 'format', 'if', 'format', 'in', "['BGR',", "'YUV-BT.601']:", 'conversion_format', '=', "'RGB'", 'image', '=', 'image.convert(conversion_format)', 'image', '=', 'np.asarray(image)', 'if', 'format', '==', "'... | 736,492 |
RasaHQ/rasa | common.py | directory_size_in_mb | directory_size_in_mb | Calculates the size of a directory. | [
"Calculates",
"the",
"size",
"of",
"a",
"directory."
] | def directory_size_in_mb(path: Path, filenames_to_exclude: Optional[List[Text]]=None) -> float:
filenames_to_exclude = filenames_to_exclude or []
size = 0.0
for (root, _dirs, files) in os.walk(path):
for filename in files:
if filename in filenames_to_exclude:
continue
... | ['def', 'directory_size_in_mb(path:', 'Path,', 'filenames_to_exclude:', 'Optional[List[Text]]=None)', '->', 'float:', 'filenames_to_exclude', '=', 'filenames_to_exclude', 'or', '[]', 'size', '=', '0.0', 'for', '(root,', '_dirs,', 'files)', 'in', 'os.walk(path):', 'for', 'filename', 'in', 'files:', 'if', 'filename', 'in... | 837,841 |
Ruturaj123/Flowchart-Detection | metric_ops_test.py | StreamingSparseRecallTest.test_three_labels_at_k5_some_out_of_range | test_three_labels_at_k5_some_out_of_range | Tests that labels outside the [0, n_classes) count in denominator. | [
"Tests",
"that",
"labels",
"outside",
"the",
"[0,",
"n_classes)",
"count",
"in",
"denominator."
] | def test_three_labels_at_k5_some_out_of_range(self):
predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]]
top_k_predictions = [[9, 4, 6, 2, 0], [5, 7, 2, 9, 6]]
sp_labels = sparse_tensor.SparseTensorValue(indices=[[0, 0], [0, 1], [0, 2], [0, ... | ['def', 'test_three_labels_at_k5_some_out_of_range(self):', 'predictions', '=', '[[0.5,', '0.1,', '0.6,', '0.3,', '0.8,', '0.0,', '0.7,', '0.2,', '0.4,', '0.9],', '[0.3,', '0.0,', '0.7,', '0.2,', '0.4,', '0.9,', '0.5,', '0.8,', '0.1,', '0.6]]', 'top_k_predictions', '=', '[[9,', '4,', '6,', '2,', '0],', '[5,', '7,', '2,... | 604,336 |
bes-dev/mean_average_precision | metric_builder.py | MetricBuilder.get_metrics_list | get_metrics_list | Get evaluation metrics list. | [
"Get",
"evaluation",
"metrics",
"list."
] | def get_metrics_list():
return list(metrics_dict.keys()) | ['def', 'get_metrics_list():', 'return', 'list(metrics_dict.keys())'] | 647,937 |
instadeepai/jumanji | env.py | Sudoku.render | render | Renders the current state of the sudoku. | [
"Renders",
"the",
"current",
"state",
"of",
"the",
"sudoku."
] | def render(self, state: State) -> Any:
return self._viewer.render(state=state) | ['def', 'render(self,', 'state:', 'State)', '->', 'Any:', 'return', 'self._viewer.render(state=state)'] | 594,137 |
43Carrig/recurrent_neural_networks_practice | cross_tower_utils.py | extract_ranges | extract_ranges | Extract consecutive ranges and singles from index_list. | [
"Extract",
"consecutive",
"ranges",
"and",
"singles",
"from",
"index_list."
] | def extract_ranges(index_list, range_size_limit=32):
if not index_list:
return ([], [])
first = index_list[0]
last = first
ranges = []
singles = []
for i in index_list[1:]:
if i == last + 1 and last - first <= range_size_limit:
last = i
else:
if la... | ['def', 'extract_ranges(index_list,', 'range_size_limit=32):', 'if', 'not', 'index_list:', 'return', '([],', '[])', 'first', '=', 'index_list[0]', 'last', '=', 'first', 'ranges', '=', '[]', 'singles', '=', '[]', 'for', 'i', 'in', 'index_list[1:]:', 'if', 'i', '==', 'last', '+', '1', 'and', 'last', '-', 'first', '<=', '... | 312,770 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_deprecate.py | new_func_wrong_docstring | new_func_wrong_docstring | Summary should be in the next line. | [
"Summary",
"should",
"be",
"in",
"the",
"next",
"line."
] | def new_func_wrong_docstring():
return 'new_func_wrong_docstring called' | ['def', 'new_func_wrong_docstring():', 'return', "'new_func_wrong_docstring", "called'"] | 453,904 |
weimin17/Object-Detection_HelmetDetection | graph_builder_test.py | GraphBuilderTest.testSetTracingTrue | testSetTracingTrue | Checks that 'annotations' does call SetTracing if enabled. | [
"Checks",
"that",
"'annotations'",
"does",
"call",
"SetTracing",
"if",
"enabled."
] | def testSetTracingTrue(self):
test_name = 'set-tracing-true'
with tf.Graph().as_default():
(builder, _) = self.getBuilderAndTarget(test_name)
anno = builder.add_annotation(test_name, enable_tracing=True)
self.checkOpOrder('annotations', anno['annotations'], ['GetSession', 'SetTracing', '... | ['def', 'testSetTracingTrue(self):', 'test_name', '=', "'set-tracing-true'", 'with', 'tf.Graph().as_default():', '(builder,', '_)', '=', 'self.getBuilderAndTarget(test_name)', 'anno', '=', 'builder.add_annotation(test_name,', 'enable_tracing=True)', "self.checkOpOrder('annotations',", "anno['annotations'],", "['GetSess... | 760,176 |
Ruturaj123/Flowchart-Detection | ops.py | one_hot_encoding | one_hot_encoding | Transform numeric labels into onehot_labels. | [
"Transform",
"numeric",
"labels",
"into",
"onehot_labels."
] | def one_hot_encoding(labels, num_classes, scope=None):
with tf.name_scope(scope, 'OneHotEncoding', [labels]):
batch_size = labels.get_shape()[0]
indices = tf.expand_dims(tf.range(0, batch_size), 1)
labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype)
concated = tf.concat(axis=1... | ['def', 'one_hot_encoding(labels,', 'num_classes,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'OneHotEncoding',", '[labels]):', 'batch_size', '=', 'labels.get_shape()[0]', 'indices', '=', 'tf.expand_dims(tf.range(0,', 'batch_size),', '1)', 'labels', '=', 'tf.cast(tf.expand_dims(labels,', '1),', 'indices.dtype)',... | 585,729 |
MycroftAI/mycroft-core | tts.py | default_preprocess_utterance | default_preprocess_utterance | Default method for preprocessing Mycroft utterances for TTS. | [
"Default",
"method",
"for",
"preprocessing",
"Mycroft",
"utterances",
"for",
"TTS."
] | def default_preprocess_utterance(utterance):
utterance = WHITESPACE_AFTER_PERIOD.sub('\\g<1>', utterance)
chunks = SENTENCE_DELIMITERS.split(utterance)
return chunks | ['def', 'default_preprocess_utterance(utterance):', 'utterance', '=', "WHITESPACE_AFTER_PERIOD.sub('\\\\g<1>',", 'utterance)', 'chunks', '=', 'SENTENCE_DELIMITERS.split(utterance)', 'return', 'chunks'] | 290,690 |
matsu0228/nlp-jp | traitlets.py | repr_type | repr_type | Return a string representation of a value and its type for readable error messages. | [
"Return",
"a",
"string",
"representation",
"of",
"a",
"value",
"and",
"its",
"type",
"for",
"readable",
"error",
"messages."
] | def repr_type(obj):
the_type = type(obj)
if six.PY2 and the_type is InstanceType:
the_type = obj.__class__
msg = '%r %r' % (obj, the_type)
return msg | ['def', 'repr_type(obj):', 'the_type', '=', 'type(obj)', 'if', 'six.PY2', 'and', 'the_type', 'is', 'InstanceType:', 'the_type', '=', 'obj.__class__', 'msg', '=', "'%r", "%r'", '%', '(obj,', 'the_type)', 'return', 'msg'] | 807,538 |
zihuitang/medical_AI_platform | _pydecimal.py | Decimal.ln | ln | Returns the natural (base e) logarithm of self. | [
"Returns",
"the",
"natural",
"(base",
"e)",
"logarithm",
"of",
"self."
] | def ln(self, context=None):
if context is None:
context = getcontext()
ans = self._check_nans(context=context)
if ans:
return ans
if not self:
return _NegativeInfinity
if self._isinfinity() == 1:
return _Infinity
if self == _One:
return _Zero
if self._... | ['def', 'ln(self,', 'context=None):', 'if', 'context', 'is', 'None:', 'context', '=', 'getcontext()', 'ans', '=', 'self._check_nans(context=context)', 'if', 'ans:', 'return', 'ans', 'if', 'not', 'self:', 'return', '_NegativeInfinity', 'if', 'self._isinfinity()', '==', '1:', 'return', '_Infinity', 'if', 'self', '==', '_... | 281,910 |
43Carrig/recurrent_neural_networks_practice | experiment.py | Experiment.reset_export_strategies | reset_export_strategies | Resets the export strategies with the `new_export_strategies`. | [
"Resets",
"the",
"export",
"strategies",
"with",
"the",
"`new_export_strategies`."
] | def reset_export_strategies(self, new_export_strategies=None):
old_export_strategies = self._export_strategies
self._set_export_strategies(new_export_strategies)
return old_export_strategies | ['def', 'reset_export_strategies(self,', 'new_export_strategies=None):', 'old_export_strategies', '=', 'self._export_strategies', 'self._set_export_strategies(new_export_strategies)', 'return', 'old_export_strategies'] | 313,522 |
oarriaga/paz | render_keypoints.py | render_random_sample | render_random_sample | Renders an image with rotated objects and keypoints. | [
"Renders",
"an",
"image",
"with",
"rotated",
"objects",
"and",
"keypoints."
] | def render_random_sample(render, augment, keypoints, focal_length):
(image, alpha_mask, world_to_camera) = render()
input_image = augment(image, alpha_mask)
keypoints = project_keypoints(keypoints, world_to_camera, focal_length)
return (input_image, keypoints) | ['def', 'render_random_sample(render,', 'augment,', 'keypoints,', 'focal_length):', '(image,', 'alpha_mask,', 'world_to_camera)', '=', 'render()', 'input_image', '=', 'augment(image,', 'alpha_mask)', 'keypoints', '=', 'project_keypoints(keypoints,', 'world_to_camera,', 'focal_length)', 'return', '(input_image,', 'keypo... | 765,178 |
rudranil723/mini-main | test_time_grouper.py | test_aggregate_nth | test_aggregate_nth | Check TimeGrouper's aggregation is identical as normal groupby. | [
"Check",
"TimeGrouper's",
"aggregation",
"is",
"identical",
"as",
"normal",
"groupby."
] | def test_aggregate_nth():
data = np.random.randn(20, 4)
normal_df = DataFrame(data, columns=['A', 'B', 'C', 'D'])
normal_df['key'] = [1, 2, 3, 4, 5] * 4
dt_df = DataFrame(data, columns=['A', 'B', 'C', 'D'])
dt_df['key'] = [datetime(2013, 1, 1), datetime(2013, 1, 2), datetime(2013, 1, 3), datetime(20... | ['def', 'test_aggregate_nth():', 'data', '=', 'np.random.randn(20,', '4)', 'normal_df', '=', 'DataFrame(data,', "columns=['A',", "'B',", "'C',", "'D'])", "normal_df['key']", '=', '[1,', '2,', '3,', '4,', '5]', '*', '4', 'dt_df', '=', 'DataFrame(data,', "columns=['A',", "'B',", "'C',", "'D'])", "dt_df['key']", '=', '[da... | 267,681 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | datasets.py | create_speech_dataset | create_speech_dataset | Creates a speech dataset. | [
"Creates",
"a",
"speech",
"dataset."
] | def create_speech_dataset(path, batch_size, samples_per_timestep=200, num_parallel_calls=DEFAULT_PARALLELISM, prefetch_buffer_size=2048, shuffle=False, repeat=False):
filenames = [path]
def read_speech_example(value):
decoded = tf.decode_raw(value, out_type=tf.float32)
example = tf.reshape(deco... | ['def', 'create_speech_dataset(path,', 'batch_size,', 'samples_per_timestep=200,', 'num_parallel_calls=DEFAULT_PARALLELISM,', 'prefetch_buffer_size=2048,', 'shuffle=False,', 'repeat=False):', 'filenames', '=', '[path]', 'def', 'read_speech_example(value):', 'decoded', '=', 'tf.decode_raw(value,', 'out_type=tf.float32)'... | 48,457 |
BlueMirrors/cvu | general.py | load_json | load_json | Loads json file in a dict object. | [
"Loads",
"json",
"file",
"in",
"a",
"dict",
"object."
] | def load_json(fname: str) -> dict:
if not os.path.exists(fname):
raise FileNotFoundError(f'{fname} is not found.')
data = {}
with open(fname, 'r') as json_file:
data = json.load(json_file)
return data | ['def', 'load_json(fname:', 'str)', '->', 'dict:', 'if', 'not', 'os.path.exists(fname):', 'raise', "FileNotFoundError(f'{fname}", 'is', 'not', "found.')", 'data', '=', '{}', 'with', 'open(fname,', "'r')", 'as', 'json_file:', 'data', '=', 'json.load(json_file)', 'return', 'data'] | 524,145 |
nicknochnack/RealTimeSignLanguageTFJS | model_training_utils.py | steps_to_run | steps_to_run | Calculates steps to run on device. | [
"Calculates",
"steps",
"to",
"run",
"on",
"device."
] | def steps_to_run(current_step, steps_per_epoch, steps_per_loop):
if steps_per_loop <= 0:
raise ValueError('steps_per_loop should be positive integer.')
if steps_per_loop == 1:
return steps_per_loop
remainder_in_epoch = current_step % steps_per_epoch
if remainder_in_epoch != 0:
re... | ['def', 'steps_to_run(current_step,', 'steps_per_epoch,', 'steps_per_loop):', 'if', 'steps_per_loop', '<=', '0:', 'raise', "ValueError('steps_per_loop", 'should', 'be', 'positive', "integer.')", 'if', 'steps_per_loop', '==', '1:', 'return', 'steps_per_loop', 'remainder_in_epoch', '=', 'current_step', '%', 'steps_per_ep... | 850,284 |
unixpickle/anyrl-py | test_spaces.py | test_stacked_box_space_json | test_stacked_box_space_json | Test JSON conversions for StackedBoxSpace. | [
"Test",
"JSON",
"conversions",
"for",
"StackedBoxSpace."
] | def test_stacked_box_space_json():
box_space = Box(low=np.array([[1.0, 2.0], [3.0, 4.0]]), high=np.array([[1.3, 4.9], [3.5, 5.0]]))
space = StackedBoxSpace(box_space, 2)
samples = [box_space.sample() for _ in range(5)]
jsoned = space.to_jsonable(samples)
assert space.to_jsonable(space.from_jsonable(... | ['def', 'test_stacked_box_space_json():', 'box_space', '=', 'Box(low=np.array([[1.0,', '2.0],', '[3.0,', '4.0]]),', 'high=np.array([[1.3,', '4.9],', '[3.5,', '5.0]]))', 'space', '=', 'StackedBoxSpace(box_space,', '2)', 'samples', '=', '[box_space.sample()', 'for', '_', 'in', 'range(5)]', 'jsoned', '=', 'space.to_jsonab... | 33,954 |
proxypoke/quickswitch-for-i3 | quickswitch.py | next_used | next_used | Return the next used numbered workspace after the given number. | [
"Return",
"the",
"next",
"used",
"numbered",
"workspace",
"after",
"the",
"given",
"number."
] | def next_used(number):
workspaces = sorted([int(ws) for ws in get_workspaces().keys() if ws.isdecimal() and int(ws) > number])
return workspaces[0] if workspaces else None | ['def', 'next_used(number):', 'workspaces', '=', 'sorted([int(ws)', 'for', 'ws', 'in', 'get_workspaces().keys()', 'if', 'ws.isdecimal()', 'and', 'int(ws)', '>', 'number])', 'return', 'workspaces[0]', 'if', 'workspaces', 'else', 'None'] | 304,090 |
palVikram/Machine-Learning-using-Python | opt.py | local_inplace_setsubtensor | local_inplace_setsubtensor | Also work for GpuIncSubtensor. | [
"Also",
"work",
"for",
"GpuIncSubtensor."
] | def local_inplace_setsubtensor(node):
if isinstance(node.op, IncSubtensor) and (not node.op.inplace):
dta = node.op.destroyhandler_tolerate_aliased
new_op = node.op.__class__(node.op.idx_list, inplace=True, set_instead_of_inc=node.op.set_instead_of_inc, destroyhandler_tolerate_aliased=dta)
n... | ['def', 'local_inplace_setsubtensor(node):', 'if', 'isinstance(node.op,', 'IncSubtensor)', 'and', '(not', 'node.op.inplace):', 'dta', '=', 'node.op.destroyhandler_tolerate_aliased', 'new_op', '=', 'node.op.__class__(node.op.idx_list,', 'inplace=True,', 'set_instead_of_inc=node.op.set_instead_of_inc,', 'destroyhandler_t... | 714,449 |
AgnostiqHQ/covalent | write_result_to_db.py | transaction_update_lattices_data | transaction_update_lattices_data | This function updates the lattices record. | [
"This",
"function",
"updates",
"the",
"lattices",
"record."
] | def transaction_update_lattices_data(session: Session, dispatch_id: str, **kwargs) -> None:
valid_update = session.query(Lattice).where(Lattice.dispatch_id == dispatch_id).first()
if not valid_update:
raise MissingLatticeRecordError
for (attr, value) in kwargs.items():
if value:
... | ['def', 'transaction_update_lattices_data(session:', 'Session,', 'dispatch_id:', 'str,', '**kwargs)', '->', 'None:', 'valid_update', '=', 'session.query(Lattice).where(Lattice.dispatch_id', '==', 'dispatch_id).first()', 'if', 'not', 'valid_update:', 'raise', 'MissingLatticeRecordError', 'for', '(attr,', 'value)', 'in',... | 489,616 |
facebookresearch/CompilerGym | testing.py | Testing.benchmarks_iterator | benchmarks_iterator | Return an iterator over the test benchmarks. | [
"Return",
"an",
"iterator",
"over",
"the",
"test",
"benchmarks."
] | def benchmarks_iterator(self, env: CompilerEnv) -> Iterable[Benchmark]:
for _ in range(self.runs_per_benchmark):
for bm in self.benchmarks:
yield from bm.benchmarks_iterator(env) | ['def', 'benchmarks_iterator(self,', 'env:', 'CompilerEnv)', '->', 'Iterable[Benchmark]:', 'for', '_', 'in', 'range(self.runs_per_benchmark):', 'for', 'bm', 'in', 'self.benchmarks:', 'yield', 'from', 'bm.benchmarks_iterator(env)'] | 135,691 |
theSnehaThing/NaturalLanguageProcessing | tokenization.py | validate_case_matches_checkpoint | validate_case_matches_checkpoint | Checks whether the casing config is consistent with the checkpoint name. | [
"Checks",
"whether",
"the",
"casing",
"config",
"is",
"consistent",
"with",
"the",
"checkpoint",
"name."
] | def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
if not init_checkpoint:
return
m = re.match('^.*?([A-Za-z0-9_-]+)/bert_model.ckpt', init_checkpoint)
if m is None:
return
model_name = m.group(1)
lower_models = ['uncased_L-24_H-1024_A-16', 'uncased_L-12_H-768_A-12... | ['def', 'validate_case_matches_checkpoint(do_lower_case,', 'init_checkpoint):', 'if', 'not', 'init_checkpoint:', 'return', 'm', '=', "re.match('^.*?([A-Za-z0-9_-]+)/bert_model.ckpt',", 'init_checkpoint)', 'if', 'm', 'is', 'None:', 'return', 'model_name', '=', 'm.group(1)', 'lower_models', '=', "['uncased_L-24_H-1024_A-... | 800,549 |
LiyuanHsu/Master-Thesis | bebop_api_client.py | Bebop.land | land | Return the balance remaining after withdrawing *amount* dollars. | [
"Return",
"the",
"balance",
"remaining",
"after",
"withdrawing",
"*amount*",
"dollars."
] | def land(self):
print('**Landing**')
land_call = rospy.ServiceProxy('bebop1/land', EmptySrv)
land_call()
return True | ['def', 'land(self):', "print('**Landing**')", 'land_call', '=', "rospy.ServiceProxy('bebop1/land',", 'EmptySrv)', 'land_call()', 'return', 'True'] | 209,815 |
google-research/tensor2robot | tensorspec_utils.py | validate_and_flatten | validate_and_flatten | Validate that TensorSpecs (required) are fulfilled and flatten the result. | [
"Validate",
"that",
"TensorSpecs",
"(required)",
"are",
"fulfilled",
"and",
"flatten",
"the",
"result."
] | def validate_and_flatten(expected_spec, actual_tensors_or_spec, ignore_batch=False):
assert_valid_spec_structure(expected_spec)
assert_valid_spec_structure(actual_tensors_or_spec)
try:
assert_required(expected_spec, actual_tensors_or_spec, ignore_batch)
except ValueError as e:
logging.er... | ['def', 'validate_and_flatten(expected_spec,', 'actual_tensors_or_spec,', 'ignore_batch=False):', 'assert_valid_spec_structure(expected_spec)', 'assert_valid_spec_structure(actual_tensors_or_spec)', 'try:', 'assert_required(expected_spec,', 'actual_tensors_or_spec,', 'ignore_batch)', 'except', 'ValueError', 'as', 'e:',... | 908,471 |
unixpickle/anyrl-py | test_wrappers.py | test_stack_3_no_concat_strided | test_stack_3_no_concat_strided | Test FrameStackEnv for 3 frames with no concatenation and a stride of 2. | [
"Test",
"FrameStackEnv",
"for",
"3",
"frames",
"with",
"no",
"concatenation",
"and",
"a",
"stride",
"of",
"2."
] | def test_stack_3_no_concat_strided():
low = np.zeros((4, 5, 2))
high = np.zeros((4, 5, 2)) + 255
env = FrameStackEnv(ShapeEnv(low, high), 3, concat=False, stride=2)
assert env.observation_space.box.shape == (4, 5, 2)
assert env.observation_space.count == 3
obses = [env.reset()]
for _ in rang... | ['def', 'test_stack_3_no_concat_strided():', 'low', '=', 'np.zeros((4,', '5,', '2))', 'high', '=', 'np.zeros((4,', '5,', '2))', '+', '255', 'env', '=', 'FrameStackEnv(ShapeEnv(low,', 'high),', '3,', 'concat=False,', 'stride=2)', 'assert', 'env.observation_space.box.shape', '==', '(4,', '5,', '2)', 'assert', 'env.observ... | 33,964 |
marcsto/rl | test_distributed.py | DistributedCollectorBase.test_distributed_collector_sync | test_distributed_collector_sync | Testing sync and async. | [
"Testing",
"sync",
"and",
"async."
] | def test_distributed_collector_sync(self, sync):
queue = mp.Queue(1)
proc = mp.Process(target=TestDistributedCollector._test_distributed_collector_sync, args=(queue, sync))
proc.start()
try:
out = queue.get(timeout=TIMEOUT)
assert out == 'passed'
finally:
proc.join(10)
... | ['def', 'test_distributed_collector_sync(self,', 'sync):', 'queue', '=', 'mp.Queue(1)', 'proc', '=', 'mp.Process(target=TestDistributedCollector._test_distributed_collector_sync,', 'args=(queue,', 'sync))', 'proc.start()', 'try:', 'out', '=', 'queue.get(timeout=TIMEOUT)', 'assert', 'out', '==', "'passed'", 'finally:', ... | 858,390 |
Kvatsx/Artificial-Intelligence-Assignments | test_peak_finding.py | TestPeakWidths.test_basic | test_basic | Test a simple use case with easy to verify results at different relative heights. | [
"Test",
"a",
"simple",
"use",
"case",
"with",
"easy",
"to",
"verify",
"results",
"at",
"different",
"relative",
"heights."
] | def test_basic(self):
x = np.array([1, 0, 1, 2, 1, 0, -1])
prominence = 2
for (rel_height, width_true, lip_true, rip_true) in [(0.0, 0.0, 3.0, 3.0), (0.25, 1.0, 2.5, 3.5), (0.5, 2.0, 2.0, 4.0), (0.75, 3.0, 1.5, 4.5), (1.0, 4.0, 1.0, 5.0), (2.0, 5.0, 1.0, 6.0), (3.0, 5.0, 1.0, 6.0)]:
(width_calc, hei... | ['def', 'test_basic(self):', 'x', '=', 'np.array([1,', '0,', '1,', '2,', '1,', '0,', '-1])', 'prominence', '=', '2', 'for', '(rel_height,', 'width_true,', 'lip_true,', 'rip_true)', 'in', '[(0.0,', '0.0,', '3.0,', '3.0),', '(0.25,', '1.0,', '2.5,', '3.5),', '(0.5,', '2.0,', '2.0,', '4.0),', '(0.75,', '3.0,', '1.5,', '4.... | 77,921 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | deep_cnn.py | inference | inference | Build the CNN model. | [
"Build",
"the",
"CNN",
"model."
] | def inference(images, dropout=False):
if FLAGS.dataset == 'mnist':
first_conv_shape = [5, 5, 1, 64]
else:
first_conv_shape = [5, 5, 3, 64]
with tf.variable_scope('conv1') as scope:
kernel = _variable_with_weight_decay('weights', shape=first_conv_shape, stddev=0.0001, wd=0.0)
... | ['def', 'inference(images,', 'dropout=False):', 'if', 'FLAGS.dataset', '==', "'mnist':", 'first_conv_shape', '=', '[5,', '5,', '1,', '64]', 'else:', 'first_conv_shape', '=', '[5,', '5,', '3,', '64]', 'with', "tf.variable_scope('conv1')", 'as', 'scope:', 'kernel', '=', "_variable_with_weight_decay('weights',", 'shape=fi... | 47,728 |
xmed-lab/URN | class_names.py | cityscapes_classes | cityscapes_classes | Cityscapes class names for external use. | [
"Cityscapes",
"class",
"names",
"for",
"external",
"use."
] | def cityscapes_classes():
return ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle'] | ['def', 'cityscapes_classes():', 'return', "['road',", "'sidewalk',", "'building',", "'wall',", "'fence',", "'pole',", "'traffic", "light',", "'traffic", "sign',", "'vegetation',", "'terrain',", "'sky',", "'person',", "'rider',", "'car',", "'truck',", "'bus',", "'train',", "'motorcycle',", "'bicycle']"] | 930,313 |
LLNL/Abmarl | wrapper.py | Wrapper.unwrapped | unwrapped | Fall through all the wrappers and obtain the original, completely unwrapped simulation. | [
"Fall",
"through",
"all",
"the",
"wrappers",
"and",
"obtain",
"the",
"original,",
"completely",
"unwrapped",
"simulation."
] | def unwrapped(self):
try:
return self.sim.unwrapped
except AttributeError:
return self.sim | ['def', 'unwrapped(self):', 'try:', 'return', 'self.sim.unwrapped', 'except', 'AttributeError:', 'return', 'self.sim'] | 405,846 |
LukasHedegaard/co3d | transform.py | lighting_jitter | lighting_jitter | Perform AlexNet-style PCA jitter on the given images. | [
"Perform",
"AlexNet-style",
"PCA",
"jitter",
"on",
"the",
"given",
"images."
] | def lighting_jitter(images, alphastd, eigval, eigvec):
if alphastd == 0:
return images
alpha = np.random.normal(0, alphastd, size=(1, 3))
eig_vec = np.array(eigvec)
eig_val = np.reshape(eigval, (1, 3))
rgb = np.sum(eig_vec * np.repeat(alpha, 3, axis=0) * np.repeat(eig_val, 3, axis=0), axis=1... | ['def', 'lighting_jitter(images,', 'alphastd,', 'eigval,', 'eigvec):', 'if', 'alphastd', '==', '0:', 'return', 'images', 'alpha', '=', 'np.random.normal(0,', 'alphastd,', 'size=(1,', '3))', 'eig_vec', '=', 'np.array(eigvec)', 'eig_val', '=', 'np.reshape(eigval,', '(1,', '3))', 'rgb', '=', 'np.sum(eig_vec', '*', 'np.rep... | 124,092 |
chainer/chainerrl | replay_buffer.py | batch_recurrent_experiences | batch_recurrent_experiences | Batch experiences for recurrent model updates. | [
"Batch",
"experiences",
"for",
"recurrent",
"model",
"updates."
] | def batch_recurrent_experiences(experiences, model, xp, phi, gamma, batch_states=batch_states):
flat_transitions = list(itertools.chain.from_iterable(experiences))
batch_exp = {'state': [batch_states([transition['state'] for transition in ep], xp, phi) for ep in experiences], 'action': xp.array([transition['act... | ['def', 'batch_recurrent_experiences(experiences,', 'model,', 'xp,', 'phi,', 'gamma,', 'batch_states=batch_states):', 'flat_transitions', '=', 'list(itertools.chain.from_iterable(experiences))', 'batch_exp', '=', "{'state':", "[batch_states([transition['state']", 'for', 'transition', 'in', 'ep],', 'xp,', 'phi)', 'for',... | 104,397 |
tinazhouhui/computer_vision | cpp_lint.py | CheckCStyleCast | CheckCStyleCast | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C-style",
"cast",
"by",
"looking",
"for",
"the",
"pattern."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error):
match = Search(pattern, line)
if not match:
return False
sizeof_match = Match('.*sizeof\\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
if line[0:match.start(1) - 1].endswith(' operato... | ['def', 'CheckCStyleCast(filename,', 'linenum,', 'line,', 'raw_line,', 'cast_type,', 'pattern,', 'error):', 'match', '=', 'Search(pattern,', 'line)', 'if', 'not', 'match:', 'return', 'False', 'sizeof_match', '=', "Match('.*sizeof\\\\s*$',", 'line[0:match.start(1)', '-', '1])', 'if', 'sizeof_match:', 'return', 'False', ... | 473,073 |
asyml/texar | preprocess.py | make_array | make_array | generate id numpy array from plain text words. | [
"generate",
"id",
"numpy",
"array",
"from",
"plain",
"text",
"words."
] | def make_array(word_id, words):
ids = [word_id.get(word, unk_token_id) for word in words]
return np.array(ids, 'i') | ['def', 'make_array(word_id,', 'words):', 'ids', '=', '[word_id.get(word,', 'unk_token_id)', 'for', 'word', 'in', 'words]', 'return', 'np.array(ids,', "'i')"] | 924,310 |
pytorch/vision | __init__.py | set_image_backend | set_image_backend | Specifies the package used to load images. | [
"Specifies",
"the",
"package",
"used",
"to",
"load",
"images."
] | def set_image_backend(backend):
global _image_backend
if backend not in ['PIL', 'accimage']:
raise ValueError("Invalid backend '{}'. Options are 'PIL' and 'accimage'".format(backend))
_image_backend = backend | ['def', 'set_image_backend(backend):', 'global', '_image_backend', 'if', 'backend', 'not', 'in', "['PIL',", "'accimage']:", 'raise', 'ValueError("Invalid', 'backend', "'{}'.", 'Options', 'are', "'PIL'", 'and', '\'accimage\'".format(backend))', '_image_backend', '=', 'backend'] | 955,781 |
openvinotoolkit/training_extensions | progress.py | ProgressCallback.on_test_batch_end | on_test_batch_end | Adds testing completion percentage to the progress bar. | [
"Adds",
"testing",
"completion",
"percentage",
"to",
"the",
"progress",
"bar."
] | def on_test_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
super().on_test_batch_end(trainer, pl_module, outputs, batch, batch_idx, dataloader_idx)
self._update_progress(stage='test') | ['def', 'on_test_batch_end(self,', 'trainer,', 'pl_module,', 'outputs,', 'batch,', 'batch_idx,', 'dataloader_idx):', 'super().on_test_batch_end(trainer,', 'pl_module,', 'outputs,', 'batch,', 'batch_idx,', 'dataloader_idx)', "self._update_progress(stage='test')"] | 903,911 |
NREL/sup3r | test_out_conditional_moments.py | test_out_s_mom1_sf | test_out_s_mom1_sf | Test basic spatial model outputing. | [
"Test",
"basic",
"spatial",
"model",
"outputing."
] | def test_out_s_mom1_sf(FEATURES, TRAIN_FEATURES, plot=False, full_shape=(20, 20), sample_shape=(10, 10, 1), batch_size=4, n_batches=4, s_enhance=2, model_dir=None):
handler = DataHandlerH5(FP_WTK, FEATURES, target=TARGET_COORD, train_only_features=TRAIN_FEATURES, shape=full_shape, sample_shape=sample_shape, tempora... | ['def', 'test_out_s_mom1_sf(FEATURES,', 'TRAIN_FEATURES,', 'plot=False,', 'full_shape=(20,', '20),', 'sample_shape=(10,', '10,', '1),', 'batch_size=4,', 'n_batches=4,', 's_enhance=2,', 'model_dir=None):', 'handler', '=', 'DataHandlerH5(FP_WTK,', 'FEATURES,', 'target=TARGET_COORD,', 'train_only_features=TRAIN_FEATURES,'... | 912,802 |
intel/neural-compressor | sigopt.py | SigOptTuneStrategy.create_exp | create_exp | Set the config for the experiment. | [
"Set",
"the",
"config",
"for",
"the",
"experiment."
] | def create_exp(self, acc_target):
params = []
from copy import deepcopy
tuning_space = self.tuning_space
initial_op_tuning_cfg = {}
for item in tuning_space.root_item.options:
if item.item_type == 'op':
(op_name, op_type) = item.name
initial_op_tuning_cfg[item.name] =... | ['def', 'create_exp(self,', 'acc_target):', 'params', '=', '[]', 'from', 'copy', 'import', 'deepcopy', 'tuning_space', '=', 'self.tuning_space', 'initial_op_tuning_cfg', '=', '{}', 'for', 'item', 'in', 'tuning_space.root_item.options:', 'if', 'item.item_type', '==', "'op':", '(op_name,', 'op_type)', '=', 'item.name', '... | 738,241 |
facebookresearch/fvcore | test_focal_loss.py | TestFocalLoss.test_positives_ignored_focal_loss | test_positives_ignored_focal_loss | With alpha = 0 postive examples have focal loss of 0. | [
"With",
"alpha",
"=",
"0",
"postive",
"examples",
"have",
"focal",
"loss",
"of",
"0."
] | def test_positives_ignored_focal_loss(self) -> None:
inputs = logit(torch.tensor([[[0.05], [0.12], [0.89], [0.79]]], dtype=torch.float32))
targets = torch.tensor([[[1], [1], [0], [0]]], dtype=torch.float32)
focal_loss = sigmoid_focal_loss(inputs, targets, gamma=2, alpha=0).squeeze().numpy()
ce_loss = F.... | ['def', 'test_positives_ignored_focal_loss(self)', '->', 'None:', 'inputs', '=', 'logit(torch.tensor([[[0.05],', '[0.12],', '[0.89],', '[0.79]]],', 'dtype=torch.float32))', 'targets', '=', 'torch.tensor([[[1],', '[1],', '[0],', '[0]]],', 'dtype=torch.float32)', 'focal_loss', '=', 'sigmoid_focal_loss(inputs,', 'targets,... | 565,979 |
HighnessAtharva/VocabCLI | vocabCLI.py | favorite | favorite | Adds a word to the favorite list. | [
"Adds",
"a",
"word",
"to",
"the",
"favorite",
"list."
] | def favorite(words: List[str]=typer.Argument(..., help='ðÂ\x9fÂ\x92Â\x99 Word to add to [bold gold1]favorites[/bold gold1].')):
from modules.Utils import set_favorite
for word in words:
set_favorite(word) | ['def', 'favorite(words:', 'List[str]=typer.Argument(...,', "help='ðÂ\\x9fÂ\\x92Â\\x99", 'Word', 'to', 'add', 'to', '[bold', 'gold1]favorites[/bold', "gold1].')):", 'from', 'modules.Utils', 'import', 'set_favorite', 'for', 'word', 'in', 'words:', 'set_favorite(word)'] | 946,214 |
43Carrig/recurrent_neural_networks_practice | template.py | Template.name | name | Returns the name given to this Template. | [
"Returns",
"the",
"name",
"given",
"to",
"this",
"Template."
] | def name(self):
return self._name | ['def', 'name(self):', 'return', 'self._name'] | 339,027 |
Xianpeng919/MonoCon | test_coord_3d_mode.py | test_points_conversion | test_points_conversion | Test the conversion of points between different modes. | [
"Test",
"the",
"conversion",
"of",
"points",
"between",
"different",
"modes."
] | def test_points_conversion():
points_np = np.array([[-5.24223238, 40.0209696, 0.297570381, 0.6666, 0.1956, 0.4974, 0.9409], [-26.6751588, 5.59499564, -0.91434586, 0.1502, 0.3707, 0.1086, 0.6297], [-5.80979675, 35.4092357, 0.200889888, 0.6565, 0.6248, 0.6954, 0.2538], [-31.3086877, 1.09007628, -0.194612112, 0.2803, ... | ['def', 'test_points_conversion():', 'points_np', '=', 'np.array([[-5.24223238,', '40.0209696,', '0.297570381,', '0.6666,', '0.1956,', '0.4974,', '0.9409],', '[-26.6751588,', '5.59499564,', '-0.91434586,', '0.1502,', '0.3707,', '0.1086,', '0.6297],', '[-5.80979675,', '35.4092357,', '0.200889888,', '0.6565,', '0.6248,',... | 654,694 |
lishunyao97/Pun-GAN | misc_utils.py | load_hparams | load_hparams | Load hparams from an existing model directory. | [
"Load",
"hparams",
"from",
"an",
"existing",
"model",
"directory."
] | def load_hparams(model_dir):
hparams_file = os.path.join(model_dir, 'hparams')
if tf.gfile.Exists(hparams_file):
print_out('# Loading hparams from %s' % hparams_file)
with codecs.getreader('utf-8')(tf.gfile.GFile(hparams_file, 'rb')) as f:
try:
hparams_values = json.l... | ['def', 'load_hparams(model_dir):', 'hparams_file', '=', 'os.path.join(model_dir,', "'hparams')", 'if', 'tf.gfile.Exists(hparams_file):', "print_out('#", 'Loading', 'hparams', 'from', "%s'", '%', 'hparams_file)', 'with', "codecs.getreader('utf-8')(tf.gfile.GFile(hparams_file,", "'rb'))", 'as', 'f:', 'try:', 'hparams_va... | 818,768 |
ZumoLabs/zpy | jobs.py | fetch_jobs | fetch_jobs | fetch jobs Fetch job objects from ZumoLabs backend. | [
"fetch",
"jobs",
"Fetch",
"job",
"objects",
"from",
"ZumoLabs",
"backend."
] | def fetch_jobs(filters, url, auth_headers):
endpoint = f'{url}/api/v1/jobs/'
r = requests.get(endpoint, headers=auth_headers, params=filters)
if r.status_code != 200:
r.raise_for_status()
return json.loads(r.text)['results'] | ['def', 'fetch_jobs(filters,', 'url,', 'auth_headers):', 'endpoint', '=', "f'{url}/api/v1/jobs/'", 'r', '=', 'requests.get(endpoint,', 'headers=auth_headers,', 'params=filters)', 'if', 'r.status_code', '!=', '200:', 'r.raise_for_status()', 'return', "json.loads(r.text)['results']"] | 971,934 |
kemaloksuz/RankSortLoss | dataset_wrappers.py | RepeatDataset.get_cat_ids | get_cat_ids | Get category ids of repeat dataset by index. | [
"Get",
"category",
"ids",
"of",
"repeat",
"dataset",
"by",
"index."
] | def get_cat_ids(self, idx):
return self.dataset.get_cat_ids(idx % self._ori_len) | ['def', 'get_cat_ids(self,', 'idx):', 'return', 'self.dataset.get_cat_ids(idx', '%', 'self._ori_len)'] | 836,004 |
Eric3911/OpenAGI | neural_type.py | NeuralType.compare_and_raise_error | compare_and_raise_error | Method compares definition of one type with another and raises an error if not compatible. | [
"Method",
"compares",
"definition",
"of",
"one",
"type",
"with",
"another",
"and",
"raises",
"an",
"error",
"if",
"not",
"compatible."
] | def compare_and_raise_error(self, parent_type_name, port_name, second_object):
type_comatibility = self.compare(second_object)
if type_comatibility != NeuralTypeComparisonResult.SAME and type_comatibility != NeuralTypeComparisonResult.GREATER:
raise NeuralPortNmTensorMismatchError(parent_type_name, port... | ['def', 'compare_and_raise_error(self,', 'parent_type_name,', 'port_name,', 'second_object):', 'type_comatibility', '=', 'self.compare(second_object)', 'if', 'type_comatibility', '!=', 'NeuralTypeComparisonResult.SAME', 'and', 'type_comatibility', '!=', 'NeuralTypeComparisonResult.GREATER:', 'raise', 'NeuralPortNmTenso... | 274,080 |
enuguru/artificial_intelligence_and_machine_learning | numeric.py | bits_required | bits_required | Returns the number of bits required to represent the given (unsigned) integer. | [
"Returns",
"the",
"number",
"of",
"bits",
"required",
"to",
"represent",
"the",
"given",
"(unsigned)",
"integer."
] | def bits_required(maxnum):
return max(1, math.ceil(math.log(maxnum, 2))) | ['def', 'bits_required(maxnum):', 'return', 'max(1,', 'math.ceil(math.log(maxnum,', '2)))'] | 162,781 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MakeCdfFromPmf | MakeCdfFromPmf | Makes a CDF from a Pmf object. | [
"Makes",
"a",
"CDF",
"from",
"a",
"Pmf",
"object."
] | def MakeCdfFromPmf(pmf, label=None):
if label is None:
label = pmf.label
return Cdf(pmf, label=label) | ['def', 'MakeCdfFromPmf(pmf,', 'label=None):', 'if', 'label', 'is', 'None:', 'label', '=', 'pmf.label', 'return', 'Cdf(pmf,', 'label=label)'] | 18,953 |
open-mmlab/mmselfsup | cross_correlation_loss.py | CrossCorrelationLoss.forward | forward | Forward function of cross correlation loss. | [
"Forward",
"function",
"of",
"cross",
"correlation",
"loss."
] | def forward(self, cross_correlation_matrix: torch.Tensor) -> torch.Tensor:
on_diag = torch.diagonal(cross_correlation_matrix).add_(-1).pow_(2).sum()
off_diag = self.off_diagonal(cross_correlation_matrix).pow_(2).sum()
loss = on_diag + self.lambd * off_diag
return loss | ['def', 'forward(self,', 'cross_correlation_matrix:', 'torch.Tensor)', '->', 'torch.Tensor:', 'on_diag', '=', 'torch.diagonal(cross_correlation_matrix).add_(-1).pow_(2).sum()', 'off_diag', '=', 'self.off_diagonal(cross_correlation_matrix).pow_(2).sum()', 'loss', '=', 'on_diag', '+', 'self.lambd', '*', 'off_diag', 'retu... | 240,432 |
arshpreetsingh/quantopian-machinelearning | _pclass.py | PClass.evolver | evolver | Returns an evolver for this object. | [
"Returns",
"an",
"evolver",
"for",
"this",
"object."
] | def evolver(self):
return _PClassEvolver(self, self._to_dict()) | ['def', 'evolver(self):', 'return', '_PClassEvolver(self,', 'self._to_dict())'] | 892,711 |
googleapis/python-aiplatform | client.py | EndpointServiceClientMeta.get_transport_class | get_transport_class | Returns an appropriate transport class. | [
"Returns",
"an",
"appropriate",
"transport",
"class."
] | def get_transport_class(cls, label: Optional[str]=None) -> Type[EndpointServiceTransport]:
if label:
return cls._transport_registry[label]
return next(iter(cls._transport_registry.values())) | ['def', 'get_transport_class(cls,', 'label:', 'Optional[str]=None)', '->', 'Type[EndpointServiceTransport]:', 'if', 'label:', 'return', 'cls._transport_registry[label]', 'return', 'next(iter(cls._transport_registry.values()))'] | 812,341 |
noambassat/SpeechTrainer | wheel.py | get_console_script_specs | get_console_script_specs | Given the mapping from entrypoint name to callable, return the relevant console script specs. | [
"Given",
"the",
"mapping",
"from",
"entrypoint",
"name",
"to",
"callable,",
"return",
"the",
"relevant",
"console",
"script",
"specs."
] | def get_console_script_specs(console):
console = console.copy()
scripts_to_generate = []
pip_script = console.pop('pip', None)
if pip_script:
if 'ENSUREPIP_OPTIONS' not in os.environ:
scripts_to_generate.append('pip = ' + pip_script)
if os.environ.get('ENSUREPIP_OPTIONS', '')... | ['def', 'get_console_script_specs(console):', 'console', '=', 'console.copy()', 'scripts_to_generate', '=', '[]', 'pip_script', '=', "console.pop('pip',", 'None)', 'if', 'pip_script:', 'if', "'ENSUREPIP_OPTIONS'", 'not', 'in', 'os.environ:', "scripts_to_generate.append('pip", '=', "'", '+', 'pip_script)', 'if', "os.env... | 895,052 |
nosyndicate/pytorchrl | replay.py | SimpleReplayPool.advance | advance | Update the top pointer, bottom pointer, and size of the replay buffer. | [
"Update",
"the",
"top",
"pointer,",
"bottom",
"pointer,",
"and",
"size",
"of",
"the",
"replay",
"buffer."
] | def advance(self):
self._top = (self._top + 1) % self._max_pool_size
if self._size >= self._max_pool_size:
self._bottom = (self._bottom + 1) % self._max_pool_size
else:
self._size += 1 | ['def', 'advance(self):', 'self._top', '=', '(self._top', '+', '1)', '%', 'self._max_pool_size', 'if', 'self._size', '>=', 'self._max_pool_size:', 'self._bottom', '=', '(self._bottom', '+', '1)', '%', 'self._max_pool_size', 'else:', 'self._size', '+=', '1'] | 815,379 |
zihuitang/medical_AI_platform | ttk.py | Treeview.index | index | Returns the integer index of item within its parent's list of children. | [
"Returns",
"the",
"integer",
"index",
"of",
"item",
"within",
"its",
"parent's",
"list",
"of",
"children."
] | def index(self, item):
return self.tk.getint(self.tk.call(self._w, 'index', item)) | ['def', 'index(self,', 'item):', 'return', 'self.tk.getint(self.tk.call(self._w,', "'index',", 'item))'] | 283,993 |
dustin/twitty-twister | test_twitter.py | TwitterFeedTest.test_user | test_user | C{user} opens a Twitter User Stream. | [
"C{user}",
"opens",
"a",
"Twitter",
"User",
"Stream."
] | def test_user(self):
self.patch(self.feed, '_rtfeed', self._rtfeed)
self.feed.user(None)
self.assertEqual(1, len(self.calls))
(url, delegate, args) = self.calls[-1]
self.assertEqual('https://userstream.twitter.com/1.1/user.json', url)
self.assertIdentical(None, delegate)
self.assertIdentical... | ['def', 'test_user(self):', 'self.patch(self.feed,', "'_rtfeed',", 'self._rtfeed)', 'self.feed.user(None)', 'self.assertEqual(1,', 'len(self.calls))', '(url,', 'delegate,', 'args)', '=', 'self.calls[-1]', "self.assertEqual('https://userstream.twitter.com/1.1/user.json',", 'url)', 'self.assertIdentical(None,', 'delegate... | 426,499 |
PaddlePaddle/PaddleSpeech | standard_updater.py | StandardUpdater.read_batch | read_batch | Read a batch from the data loader, auto renew when data is exhausted. | [
"Read",
"a",
"batch",
"from",
"the",
"data",
"loader,",
"auto",
"renew",
"when",
"data",
"is",
"exhausted."
] | def read_batch(self):
with timer() as t:
try:
batch = next(self.train_iterator)
except StopIteration:
self.new_epoch()
batch = next(self.train_iterator)
logging.debug(f'Read a batch takes {t.elapse}s.')
return batch | ['def', 'read_batch(self):', 'with', 'timer()', 'as', 't:', 'try:', 'batch', '=', 'next(self.train_iterator)', 'except', 'StopIteration:', 'self.new_epoch()', 'batch', '=', 'next(self.train_iterator)', "logging.debug(f'Read", 'a', 'batch', 'takes', "{t.elapse}s.')", 'return', 'batch'] | 277,317 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | wrapped_units.py | BaseLSTMNetwork.get_logits | get_logits | Returns the logits for prediction. | [
"Returns",
"the",
"logits",
"for",
"prediction."
] | def get_logits(self, network_tensors):
return network_tensors[self.get_layer_index('logits')] | ['def', 'get_logits(self,', 'network_tensors):', 'return', "network_tensors[self.get_layer_index('logits')]"] | 28,784 |
intel/neural-compressor | test_saved_model.py | TestSavedModelModel.test_get_input_and_output_nodes | test_get_input_and_output_nodes | Test getting input nodes. | [
"Test",
"getting",
"input",
"nodes."
] | def test_get_input_and_output_nodes(self) -> None:
model = SavedModelModel('/path/to/saved_model')
self.assertEqual(['first input node', 'second input node'], model.get_input_nodes())
self.assertEqual(['first output node', 'second output node', 'custom'], model.get_output_nodes()) | ['def', 'test_get_input_and_output_nodes(self)', '->', 'None:', 'model', '=', "SavedModelModel('/path/to/saved_model')", "self.assertEqual(['first", 'input', "node',", "'second", 'input', "node'],", 'model.get_input_nodes())', "self.assertEqual(['first", 'output', "node',", "'second", 'output', "node',", "'custom'],", ... | 721,681 |
devashish-patel/webcam-motion-detector | document.py | Document.to_json | to_json | Convert this document to a JSON object. | [
"Convert",
"this",
"document",
"to",
"a",
"JSON",
"object."
] | def to_json(self):
doc_json = self.to_json_string()
return loads(doc_json) | ['def', 'to_json(self):', 'doc_json', '=', 'self.to_json_string()', 'return', 'loads(doc_json)'] | 977,314 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.