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 |
|---|---|---|---|---|---|---|---|---|
dgseten/bad-cv-tfm | inputs_test.py | InputsTest.test_error_with_bad_eval_config | test_error_with_bad_eval_config | Tests that a TypeError is raised with improper eval config. | [
"Tests",
"that",
"a",
"TypeError",
"is",
"raised",
"with",
"improper",
"eval",
"config."
] | def test_error_with_bad_eval_config(self):
configs = _get_configs_for_model('ssd_inception_v2_pets')
configs['model'].ssd.num_classes = 37
eval_input_fn = inputs.create_eval_input_fn(eval_config=configs['train_config'], eval_input_config=configs['eval_input_configs'][0], model_config=configs['model'])
w... | ['def', 'test_error_with_bad_eval_config(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['model'].ssd.num_classes", '=', '37', 'eval_input_fn', '=', "inputs.create_eval_input_fn(eval_config=configs['train_config'],", "eval_input_config=configs['eval_input_configs'][0],", "model_conf... | 421,348 |
kornia/kornia | kernels.py | get_box_kernel1d | get_box_kernel1d | Utility function that returns a 1-D box filter. | [
"Utility",
"function",
"that",
"returns",
"a",
"1-D",
"box",
"filter."
] | def get_box_kernel1d(kernel_size: int, *, device: Optional[Device]=None, dtype: Optional[Dtype]=None) -> Tensor:
scale = tensor(1.0 / kernel_size, device=device, dtype=dtype)
return scale.expand(1, kernel_size) | ['def', 'get_box_kernel1d(kernel_size:', 'int,', '*,', 'device:', 'Optional[Device]=None,', 'dtype:', 'Optional[Dtype]=None)', '->', 'Tensor:', 'scale', '=', 'tensor(1.0', '/', 'kernel_size,', 'device=device,', 'dtype=dtype)', 'return', 'scale.expand(1,', 'kernel_size)'] | 621,796 |
ivanmontero/autobot | retrieval_rag.py | RagRetriever.retrieve | retrieve | Retrieves documents for specified ``question_hidden_states``. | [
"Retrieves",
"documents",
"for",
"specified",
"``question_hidden_states``."
] | def retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> Tuple[np.ndarray, List[dict]]:
(doc_ids, retrieved_doc_embeds) = self._main_retrieve(question_hidden_states, n_docs)
return (retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(doc_ids)) | ['def', 'retrieve(self,', 'question_hidden_states:', 'np.ndarray,', 'n_docs:', 'int)', '->', 'Tuple[np.ndarray,', 'List[dict]]:', '(doc_ids,', 'retrieved_doc_embeds)', '=', 'self._main_retrieve(question_hidden_states,', 'n_docs)', 'return', '(retrieved_doc_embeds,', 'doc_ids,', 'self.index.get_doc_dicts(doc_ids))'] | 418,241 |
rudranil723/mini-main | testutils.py | assert_equal | assert_equal | Asserts that two items are equal. | [
"Asserts",
"that",
"two",
"items",
"are",
"equal."
] | def assert_equal(actual, desired, err_msg=''):
if isinstance(desired, dict):
if not isinstance(actual, dict):
raise AssertionError(repr(type(actual)))
assert_equal(len(actual), len(desired), err_msg)
for (k, i) in desired.items():
if k not in actual:
r... | ['def', 'assert_equal(actual,', 'desired,', "err_msg=''):", 'if', 'isinstance(desired,', 'dict):', 'if', 'not', 'isinstance(actual,', 'dict):', 'raise', 'AssertionError(repr(type(actual)))', 'assert_equal(len(actual),', 'len(desired),', 'err_msg)', 'for', '(k,', 'i)', 'in', 'desired.items():', 'if', 'k', 'not', 'in', '... | 322,950 |
wonheeML/mtl-ssl | per_image_evaluation.py | PerImageEvaluation.compute_object_detection_metrics | compute_object_detection_metrics | Compute Object Detection related metrics from a single image. | [
"Compute",
"Object",
"Detection",
"related",
"metrics",
"from",
"a",
"single",
"image."
] | def compute_object_detection_metrics(self, detected_boxes, detected_scores, detected_class_labels, groundtruth_boxes, groundtruth_class_labels, groundtruth_is_difficult_lists):
(detected_boxes, detected_scores, detected_class_labels) = self._remove_invalid_boxes(detected_boxes, detected_scores, detected_class_label... | ['def', 'compute_object_detection_metrics(self,', 'detected_boxes,', 'detected_scores,', 'detected_class_labels,', 'groundtruth_boxes,', 'groundtruth_class_labels,', 'groundtruth_is_difficult_lists):', '(detected_boxes,', 'detected_scores,', 'detected_class_labels)', '=', 'self._remove_invalid_boxes(detected_boxes,', '... | 643,186 |
enuguru/artificial_intelligence_and_machine_learning | itsdangerous.py | TimestampSigner.sign | sign | Signs the given string and also attaches a time information. | [
"Signs",
"the",
"given",
"string",
"and",
"also",
"attaches",
"a",
"time",
"information."
] | def sign(self, value):
value = want_bytes(value)
timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
sep = want_bytes(self.sep)
value = value + sep + timestamp
return value + sep + self.get_signature(value) | ['def', 'sign(self,', 'value):', 'value', '=', 'want_bytes(value)', 'timestamp', '=', 'base64_encode(int_to_bytes(self.get_timestamp()))', 'sep', '=', 'want_bytes(self.sep)', 'value', '=', 'value', '+', 'sep', '+', 'timestamp', 'return', 'value', '+', 'sep', '+', 'self.get_signature(value)'] | 146,941 |
arshpreetsingh/quantopian-machinelearning | testing.py | HTMLTreeBuilderSmokeTest.test_worst_case | test_worst_case | Test the worst case (currently) for linking issues. | [
"Test",
"the",
"worst",
"case",
"(currently)",
"for",
"linking",
"issues."
] | def test_worst_case(self):
soup = self.soup(BAD_DOCUMENT)
self.linkage_validator(soup) | ['def', 'test_worst_case(self):', 'soup', '=', 'self.soup(BAD_DOCUMENT)', 'self.linkage_validator(soup)'] | 816,538 |
open-mmlab/mmtracking | test_single_level_roi_extractor.py | test_single_roi_extractor | test_single_roi_extractor | Tests single roi extractor. | [
"Tests",
"single",
"roi",
"extractor."
] | def test_single_roi_extractor():
single_roi_extractor_config = dict(roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32])
self = SingleRoIExtractor(**single_roi_extractor_config)
feats = (torch.rand((1, 256, 200, 336)), torch.rand((1, 256, 100, 1... | ['def', 'test_single_roi_extractor():', 'single_roi_extractor_config', '=', "dict(roi_layer=dict(type='RoIAlign',", 'output_size=7,', 'sampling_ratio=0),', 'out_channels=256,', 'featmap_strides=[4,', '8,', '16,', '32])', 'self', '=', 'SingleRoIExtractor(**single_roi_extractor_config)', 'feats', '=', '(torch.rand((1,', ... | 625,932 |
muhanzhang/D-VAE | basic_ops.py | GpuCAReduce.supports_c_code | supports_c_code | Returns True if the current op and reduce pattern has functioning C code. | [
"Returns",
"True",
"if",
"the",
"current",
"op",
"and",
"reduce",
"pattern",
"has",
"functioning",
"C",
"code."
] | def supports_c_code(self, inputs):
pattern = ''.join((str(i) for i in self.reduce_mask))
if not hasattr(self, 'c_code_reduce_%s' % pattern):
return False
node = self.make_node(*inputs)
name = 'fake_name'
inp = ['fake_input_name_%d' % i for i in xrange(len(inputs))]
out = ['fake_output_na... | ['def', 'supports_c_code(self,', 'inputs):', 'pattern', '=', "''.join((str(i)", 'for', 'i', 'in', 'self.reduce_mask))', 'if', 'not', 'hasattr(self,', "'c_code_reduce_%s'", '%', 'pattern):', 'return', 'False', 'node', '=', 'self.make_node(*inputs)', 'name', '=', "'fake_name'", 'inp', '=', "['fake_input_name_%d'", '%', '... | 525,087 |
Hadishh/cs188 | inference.py | InferenceModule.initializeUniformly | initializeUniformly | Set the belief state to a uniform prior belief over all positions. | [
"Set",
"the",
"belief",
"state",
"to",
"a",
"uniform",
"prior",
"belief",
"over",
"all",
"positions."
] | def initializeUniformly(self, gameState):
raise NotImplementedError | ['def', 'initializeUniformly(self,', 'gameState):', 'raise', 'NotImplementedError'] | 225,818 |
facebookresearch/minihack | base.py | MiniHack.key_in_inventory | key_in_inventory | Returns key of the given object in the inventory. | [
"Returns",
"key",
"of",
"the",
"given",
"object",
"in",
"the",
"inventory."
] | def key_in_inventory(self, name):
assert 'inv_strs' in self._observation_keys
assert 'inv_letters' in self._observation_keys
inv_strs_index = self._observation_keys.index('inv_strs')
inv_letters_index = self._observation_keys.index('inv_letters')
inv_strs = self.last_observation[inv_strs_index]
... | ['def', 'key_in_inventory(self,', 'name):', 'assert', "'inv_strs'", 'in', 'self._observation_keys', 'assert', "'inv_letters'", 'in', 'self._observation_keys', 'inv_strs_index', '=', "self._observation_keys.index('inv_strs')", 'inv_letters_index', '=', "self._observation_keys.index('inv_letters')", 'inv_strs', '=', 'sel... | 670,693 |
43Carrig/recurrent_neural_networks_practice | window_ops.py | hann_window | hann_window | Generate a [Hann window][hann]. | [
"Generate",
"a",
"[Hann",
"window][hann]."
] | def hann_window(window_length, periodic=True, dtype=dtypes.float32, name=None):
return _raised_cosine_window(name, 'hann_window', window_length, periodic, dtype, 0.5, 0.5) | ['def', 'hann_window(window_length,', 'periodic=True,', 'dtype=dtypes.float32,', 'name=None):', 'return', '_raised_cosine_window(name,', "'hann_window',", 'window_length,', 'periodic,', 'dtype,', '0.5,', '0.5)'] | 335,188 |
marysia/thesis | model_building_pca.py | hyperparameter_randomiser_svm | hyperparameter_randomiser_svm | Returns the best hyperparameters from given ranges using a random search algorithm: c_range: Upper and lower bounds of the c distribution range as a list gamma_range: Upper and lower bounds of the gamma distribution range as a list c_dist: An argument specifying whether the distribution is drawn from a uniform or log u... | [
"Returns",
"the",
"best",
"hyperparameters",
"from",
"given",
"ranges",
"using",
"a",
"random",
"search",
"algorithm:",
"c_range:",
"Upper",
"and",
"lower",
"bounds",
"of",
"the",
"c",
"distribution",
"range",
"as",
"a",
"list",
"gamma_range:",
"Upper",
"and",
... | def hyperparameter_randomiser_svm(c_range, gamma_range, c_dist='log_uniform', gamma_dist='log_uniform', prints=False):
if c_dist == 'log_uniform':
c = loguniform(c_range[0], c_range[1]).rvs(1).item()
elif c_dist == 'uniform':
c = uniform(c_range[0], c_range[1]).rvs(1).item()
else:
ra... | ['def', 'hyperparameter_randomiser_svm(c_range,', 'gamma_range,', "c_dist='log_uniform',", "gamma_dist='log_uniform',", 'prints=False):', 'if', 'c_dist', '==', "'log_uniform':", 'c', '=', 'loguniform(c_range[0],', 'c_range[1]).rvs(1).item()', 'elif', 'c_dist', '==', "'uniform':", 'c', '=', 'uniform(c_range[0],', 'c_ran... | 354,964 |
matsu0228/nlp-jp | setup_common.py | check_api_version | check_api_version | Emits a MismacthCAPIWarning if the C API version needs updating. | [
"Emits",
"a",
"MismacthCAPIWarning",
"if",
"the",
"C",
"API",
"version",
"needs",
"updating."
] | def check_api_version(apiversion, codegen_dir):
(curapi_hash, api_hash) = get_api_versions(apiversion, codegen_dir)
if not curapi_hash == api_hash:
msg = 'API mismatch detected, the C API version numbers have to be updated. Current C api version is %d, with checksum %s, but recorded checksum for C API v... | ['def', 'check_api_version(apiversion,', 'codegen_dir):', '(curapi_hash,', 'api_hash)', '=', 'get_api_versions(apiversion,', 'codegen_dir)', 'if', 'not', 'curapi_hash', '==', 'api_hash:', 'msg', '=', "'API", 'mismatch', 'detected,', 'the', 'C', 'API', 'version', 'numbers', 'have', 'to', 'be', 'updated.', 'Current', 'C'... | 790,875 |
matsu0228/nlp-jp | test_exceptions.py | TestBestMatch.test_oneOf_and_anyOf_are_weak_matches | test_oneOf_and_anyOf_are_weak_matches | A property you *must* match is probably better than one you have to match a part of. | [
"A",
"property",
"you",
"*must*",
"match",
"is",
"probably",
"better",
"than",
"one",
"you",
"have",
"to",
"match",
"a",
"part",
"of."
] | def test_oneOf_and_anyOf_are_weak_matches(self):
validator = Draft4Validator({'minProperties': 2, 'anyOf': [{'type': 'string'}, {'type': 'number'}], 'oneOf': [{'type': 'string'}, {'type': 'number'}]})
best = self.best_match(validator.iter_errors({}))
self.assertEqual(best.validator, 'minProperties') | ['def', 'test_oneOf_and_anyOf_are_weak_matches(self):', 'validator', '=', "Draft4Validator({'minProperties':", '2,', "'anyOf':", "[{'type':", "'string'},", "{'type':", "'number'}],", "'oneOf':", "[{'type':", "'string'},", "{'type':", "'number'}]})", 'best', '=', 'self.best_match(validator.iter_errors({}))', 'self.asser... | 788,032 |
caikit/caikit-computer-vision | __init__.py | detector_transformer_dummy_model | detector_transformer_dummy_model | Bootstrap a detector transformer dummy model [yolos]. | [
"Bootstrap",
"a",
"detector",
"transformer",
"dummy",
"model",
"[yolos]."
] | def detector_transformer_dummy_model():
return TransformersObjectDetector.bootstrap(TRANSFORMER_OBJ_DETECT_MODEL) | ['def', 'detector_transformer_dummy_model():', 'return', 'TransformersObjectDetector.bootstrap(TRANSFORMER_OBJ_DETECT_MODEL)'] | 410,961 |
greydanus/pythonic_ocr | bccache.py | BytecodeCache.get_cache_key | get_cache_key | Returns the unique hash key for this template name. | [
"Returns",
"the",
"unique",
"hash",
"key",
"for",
"this",
"template",
"name."
] | def get_cache_key(self, name, filename=None):
hash = sha1(name.encode('utf-8'))
if filename is not None:
filename = '|' + filename
if isinstance(filename, text_type):
filename = filename.encode('utf-8')
hash.update(filename)
return hash.hexdigest() | ['def', 'get_cache_key(self,', 'name,', 'filename=None):', 'hash', '=', "sha1(name.encode('utf-8'))", 'if', 'filename', 'is', 'not', 'None:', 'filename', '=', "'|'", '+', 'filename', 'if', 'isinstance(filename,', 'text_type):', 'filename', '=', "filename.encode('utf-8')", 'hash.update(filename)', 'return', 'hash.hexdig... | 299,168 |
RasaHQ/rasa | duckling_entity_extractor.py | DucklingEntityExtractor.create | create | Creates component (see parent class for full docstring). | [
"Creates",
"component",
"(see",
"parent",
"class",
"for",
"full",
"docstring)."
] | def create(cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> DucklingEntityExtractor:
return cls(config) | ['def', 'create(cls,', 'config:', 'Dict[Text,', 'Any],', 'model_storage:', 'ModelStorage,', 'resource:', 'Resource,', 'execution_context:', 'ExecutionContext)', '->', 'DucklingEntityExtractor:', 'return', 'cls(config)'] | 837,202 |
ryu-ed/SpaceInvaders_Ros | cdrom_test.py | CDROMModuleTest.test_quit | test_quit | Ensure module not initialized after quit() called. | [
"Ensure",
"module",
"not",
"initialized",
"after",
"quit()",
"called."
] | def test_quit(self):
pygame.cdrom.quit()
self.assertFalse(pygame.cdrom.get_init()) | ['def', 'test_quit(self):', 'pygame.cdrom.quit()', 'self.assertFalse(pygame.cdrom.get_init())'] | 368,899 |
usmancheema89/computer_vision | inputs_test.py | InputsTest.test_error_with_bad_train_input_config | test_error_with_bad_train_input_config | Tests that a TypeError is raised with improper train input config. | [
"Tests",
"that",
"a",
"TypeError",
"is",
"raised",
"with",
"improper",
"train",
"input",
"config."
] | def test_error_with_bad_train_input_config(self):
configs = _get_configs_for_model('ssd_inception_v2_pets')
configs['model'].ssd.num_classes = 37
train_input_fn = inputs.create_train_input_fn(train_config=configs['train_config'], train_input_config=configs['model'], model_config=configs['model'])
with s... | ['def', 'test_error_with_bad_train_input_config(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['model'].ssd.num_classes", '=', '37', 'train_input_fn', '=', "inputs.create_train_input_fn(train_config=configs['train_config'],", "train_input_config=configs['model'],", "model_config=co... | 503,491 |
TheCurryMan/MedicAI | core.py | Context.find_root | find_root | Finds the outermost context. | [
"Finds",
"the",
"outermost",
"context."
] | def find_root(self):
node = self
while node.parent is not None:
node = node.parent
return node | ['def', 'find_root(self):', 'node', '=', 'self', 'while', 'node.parent', 'is', 'not', 'None:', 'node', '=', 'node.parent', 'return', 'node'] | 648,026 |
LLNL/DJINN | djinn_fns.py | tf_continue_training | tf_continue_training | Reloads and continues training an existing DJINN model. | [
"Reloads",
"and",
"continues",
"training",
"an",
"existing",
"DJINN",
"model."
] | def tf_continue_training(regression, xscale, yscale, x1, y1, ntrees, learnrate, training_epochs, batch_size, dropout_keep_prob, nhl, display_step, modelname, modelpath, random_state):
nhl = int(nhl)
model_path = modelpath
model_name = modelname
if y1.size > y1.shape[0]:
n_classes = y1.shape[1]
... | ['def', 'tf_continue_training(regression,', 'xscale,', 'yscale,', 'x1,', 'y1,', 'ntrees,', 'learnrate,', 'training_epochs,', 'batch_size,', 'dropout_keep_prob,', 'nhl,', 'display_step,', 'modelname,', 'modelpath,', 'random_state):', 'nhl', '=', 'int(nhl)', 'model_path', '=', 'modelpath', 'model_name', '=', 'modelname',... | 521,650 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | dtypes.py | DatetimeTZDtype.name | name | A string representation of the dtype. | [
"A",
"string",
"representation",
"of",
"the",
"dtype."
] | def name(self):
return str(self) | ['def', 'name(self):', 'return', 'str(self)'] | 967,566 |
zihuitang/medical_AI_platform | _header_value_parser.py | get_display_name | get_display_name | display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with the content of the phrase. | [
"display-name",
"=",
"phrase",
"Because",
"this",
"is",
"simply",
"a",
"name-rule,",
"we",
"don't",
"return",
"a",
"display-name",
"token",
"containing",
"a",
"phrase,",
"but",
"rather",
"a",
"display-name",
"token",
"with",
"the",
"content",
"of",
"the",
"phr... | def get_display_name(value):
display_name = DisplayName()
(token, value) = get_phrase(value)
display_name.extend(token[:])
display_name.defects = token.defects[:]
return (display_name, value) | ['def', 'get_display_name(value):', 'display_name', '=', 'DisplayName()', '(token,', 'value)', '=', 'get_phrase(value)', 'display_name.extend(token[:])', 'display_name.defects', '=', 'token.defects[:]', 'return', '(display_name,', 'value)'] | 282,504 |
devashish-patel/webcam-motion-detector | displayhook.py | ZMQShellDisplayHook.write_output_prompt | write_output_prompt | Write the output prompt. | [
"Write",
"the",
"output",
"prompt."
] | def write_output_prompt(self):
self.msg['content']['execution_count'] = self.prompt_count | ['def', 'write_output_prompt(self):', "self.msg['content']['execution_count']", '=', 'self.prompt_count'] | 978,317 |
facebookresearch/CompilerGym | env_without_bazel_test.py | test_default_autophase_observation | test_default_autophase_observation | Test default autophase observation space. | [
"Test",
"default",
"autophase",
"observation",
"space."
] | def test_default_autophase_observation(env: CompilerEnv):
env.observation_space = 'Autophase'
observation = env.reset()
assert isinstance(observation, np.ndarray)
assert observation.shape == (len(AUTOPHASE_FEATURE_NAMES),)
assert observation.dtype == np.int64
assert all((obs >= 0 for obs in obse... | ['def', 'test_default_autophase_observation(env:', 'CompilerEnv):', 'env.observation_space', '=', "'Autophase'", 'observation', '=', 'env.reset()', 'assert', 'isinstance(observation,', 'np.ndarray)', 'assert', 'observation.shape', '==', '(len(AUTOPHASE_FEATURE_NAMES),)', 'assert', 'observation.dtype', '==', 'np.int64',... | 125,812 |
AgnostiqHQ/covalent | data.py | get_mock_result_2 | get_mock_result_2 | Construct and return a result object corresponding to a lattice. | [
"Construct",
"and",
"return",
"a",
"result",
"object",
"corresponding",
"to",
"a",
"lattice."
] | def get_mock_result_2() -> Result:
@ct.electron
def identity(x):
return x
@ct.electron
def product(x, y):
return x * y
@ct.lattice
def pipeline(x, y):
res = product(x=x, y=y)
return identity(x=res)
pipeline.build_graph(x=1, y=1)
return Result(lattice=pi... | ['def', 'get_mock_result_2()', '->', 'Result:', '@ct.electron', 'def', 'identity(x):', 'return', 'x', '@ct.electron', 'def', 'product(x,', 'y):', 'return', 'x', '*', 'y', '@ct.lattice', 'def', 'pipeline(x,', 'y):', 'res', '=', 'product(x=x,', 'y=y)', 'return', 'identity(x=res)', 'pipeline.build_graph(x=1,', 'y=1)', 're... | 490,027 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | image.py | _ImageBase.get_resample | get_resample | Return whether image resampling is used. | [
"Return",
"whether",
"image",
"resampling",
"is",
"used."
] | def get_resample(self):
return self._resample | ['def', 'get_resample(self):', 'return', 'self._resample'] | 306,788 |
deep-learning-indaba/Baobab | tests.py | OutcomeApiTest.test_get_outcome_non_event_admin | test_get_outcome_non_event_admin | Test that a forbidden status is given when the logged in user is not an event admin and tries to get outcome. | [
"Test",
"that",
"a",
"forbidden",
"status",
"is",
"given",
"when",
"the",
"logged",
"in",
"user",
"is",
"not",
"an",
"event",
"admin",
"and",
"tries",
"to",
"get",
"outcome."
] | def test_get_outcome_non_event_admin(self):
self.seed_static_data()
response = self.app.get('/api/v1/outcome', data={'event_id': self.event2.id, 'user_id': self.test_user2.id}, headers=self.get_auth_header_for('something@email.com'))
self.assertEqual(response.status_code, 403) | ['def', 'test_get_outcome_non_event_admin(self):', 'self.seed_static_data()', 'response', '=', "self.app.get('/api/v1/outcome',", "data={'event_id':", 'self.event2.id,', "'user_id':", 'self.test_user2.id},', "headers=self.get_auth_header_for('something@email.com'))", 'self.assertEqual(response.status_code,', '403)'] | 94,172 |
dandingbudanding/DRSNet | build.py | mkdir_p | mkdir_p | Like `mkdir`, but does not raise an exception if the directory already exists. | [
"Like",
"`mkdir`,",
"but",
"does",
"not",
"raise",
"an",
"exception",
"if",
"the",
"directory",
"already",
"exists."
] | def mkdir_p(*args, **kwargs):
try:
return os.mkdir(*args, **kwargs)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise | ['def', 'mkdir_p(*args,', '**kwargs):', 'try:', 'return', 'os.mkdir(*args,', '**kwargs)', 'except', 'OSError', 'as', 'exc:', 'if', 'exc.errno', '!=', 'errno.EEXIST:', 'raise'] | 554,100 |
myothida/Supervised-Machine-Learning | _nonlin.py | LowRankMatrix.restart_reduce | restart_reduce | Reduce the rank of the matrix by dropping all vectors. | [
"Reduce",
"the",
"rank",
"of",
"the",
"matrix",
"by",
"dropping",
"all",
"vectors."
] | def restart_reduce(self, rank):
if self.collapsed is not None:
return
assert rank > 0
if len(self.cs) > rank:
del self.cs[:]
del self.ds[:] | ['def', 'restart_reduce(self,', 'rank):', 'if', 'self.collapsed', 'is', 'not', 'None:', 'return', 'assert', 'rank', '>', '0', 'if', 'len(self.cs)', '>', 'rank:', 'del', 'self.cs[:]', 'del', 'self.ds[:]'] | 445,908 |
intel/neural-compressor | main.py | eval_classifier_optimized_graph.run | run | This is neural_compressor function include tuning, export and benchmark option. | [
"This",
"is",
"neural_compressor",
"function",
"include",
"tuning,",
"export",
"and",
"benchmark",
"option."
] | def run(self):
from neural_compressor import set_random_seed
set_random_seed(9527)
if args.tune:
from neural_compressor import mix_precision
from neural_compressor.config import MixedPrecisionConfig
from neural_compressor.utils.create_obj_from_config import create_dataloader
... | ['def', 'run(self):', 'from', 'neural_compressor', 'import', 'set_random_seed', 'set_random_seed(9527)', 'if', 'args.tune:', 'from', 'neural_compressor', 'import', 'mix_precision', 'from', 'neural_compressor.config', 'import', 'MixedPrecisionConfig', 'from', 'neural_compressor.utils.create_obj_from_config', 'import', '... | 736,976 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | ModifiersAcceptor.nodesToAnnos | nodesToAnnos | Convert the annotations in the given branch to a decorator. | [
"Convert",
"the",
"annotations",
"in",
"the",
"given",
"branch",
"to",
"a",
"decorator."
] | def nodesToAnnos(self, branch, memo):
name = branch.firstChildOfType(tokens.IDENT).text
init = branch.firstChildOfType(tokens.ANNOTATION_INIT_BLOCK)
if not init:
deco = self.factory.expr(left=name, fs='@{left}()')
else:
defKey = init.firstChildOfType(tokens.ANNOTATION_INIT_DEFAULT_KEY)
... | ['def', 'nodesToAnnos(self,', 'branch,', 'memo):', 'name', '=', 'branch.firstChildOfType(tokens.IDENT).text', 'init', '=', 'branch.firstChildOfType(tokens.ANNOTATION_INIT_BLOCK)', 'if', 'not', 'init:', 'deco', '=', 'self.factory.expr(left=name,', "fs='@{left}()')", 'else:', 'defKey', '=', 'init.firstChildOfType(tokens.... | 17,197 |
intel/neural-compressor | quantize.py | LayerWiseQuant.quantize | quantize | The main entry of layer wise quantization. | [
"The",
"main",
"entry",
"of",
"layer",
"wise",
"quantization."
] | def quantize(self, clean_weight=True):
mk_tmp_dir()
self._layer_wise_quantize(self.calib_data)
if self.output_dir:
self._save(self.output_dir, clean_weight=clean_weight)
else:
self._convert(clean_weight=clean_weight)
del_tmp_dir()
return self.q_model | ['def', 'quantize(self,', 'clean_weight=True):', 'mk_tmp_dir()', 'self._layer_wise_quantize(self.calib_data)', 'if', 'self.output_dir:', 'self._save(self.output_dir,', 'clean_weight=clean_weight)', 'else:', 'self._convert(clean_weight=clean_weight)', 'del_tmp_dir()', 'return', 'self.q_model'] | 737,940 |
open-mmlab/mmrotate | test_forward.py | test_two_stage_forward_gpu | test_two_stage_forward_gpu | Test two stage forward (GPU). | [
"Test",
"two",
"stage",
"forward",
"(GPU)."
] | def test_two_stage_forward_gpu(cfg_file):
model = _get_detector_cfg(cfg_file)
model = _replace_r50_with_r18(model)
model.backbone.init_cfg = None
from mmdet.models import build_detector
detector = build_detector(model)
detector = detector.cuda()
input_shape = (1, 3, 128, 128)
mm_inputs =... | ['def', 'test_two_stage_forward_gpu(cfg_file):', 'model', '=', '_get_detector_cfg(cfg_file)', 'model', '=', '_replace_r50_with_r18(model)', 'model.backbone.init_cfg', '=', 'None', 'from', 'mmdet.models', 'import', 'build_detector', 'detector', '=', 'build_detector(model)', 'detector', '=', 'detector.cuda()', 'input_sha... | 625,256 |
zzxslp/WCL | extract.py | Extractor.extract | extract | Extract the observations in each report. | [
"Extract",
"the",
"observations",
"in",
"each",
"report."
] | def extract(self, collection):
documents = collection.documents
if self.verbose:
print('Extracting mentions...')
documents = tqdm(documents)
for document in documents:
impression = document.passages[0]
annotation_index = itertools.count(len(impression.annotations))
fo... | ['def', 'extract(self,', 'collection):', 'documents', '=', 'collection.documents', 'if', 'self.verbose:', "print('Extracting", "mentions...')", 'documents', '=', 'tqdm(documents)', 'for', 'document', 'in', 'documents:', 'impression', '=', 'document.passages[0]', 'annotation_index', '=', 'itertools.count(len(impression.... | 373,037 |
facebookresearch/Detectron | FPN.py | add_fpn | add_fpn | Add FPN connections based on the model described in the FPN paper. | [
"Add",
"FPN",
"connections",
"based",
"on",
"the",
"model",
"described",
"in",
"the",
"FPN",
"paper."
] | def add_fpn(model, fpn_level_info):
fpn_dim = cfg.FPN.DIM
(min_level, max_level) = get_min_max_levels()
num_backbone_stages = len(fpn_level_info.blobs) - (min_level - LOWEST_BACKBONE_LVL)
lateral_input_blobs = fpn_level_info.blobs[:num_backbone_stages]
output_blobs = ['fpn_inner_{}'.format(s) for s ... | ['def', 'add_fpn(model,', 'fpn_level_info):', 'fpn_dim', '=', 'cfg.FPN.DIM', '(min_level,', 'max_level)', '=', 'get_min_max_levels()', 'num_backbone_stages', '=', 'len(fpn_level_info.blobs)', '-', '(min_level', '-', 'LOWEST_BACKBONE_LVL)', 'lateral_input_blobs', '=', 'fpn_level_info.blobs[:num_backbone_stages]', 'outpu... | 548,898 |
usmancheema89/computer_vision | image_iter.py | FaceImageIter.postprocess_data | postprocess_data | Final postprocessing step before image is loaded into the batch. | [
"Final",
"postprocessing",
"step",
"before",
"image",
"is",
"loaded",
"into",
"the",
"batch."
] | def postprocess_data(self, datum):
return nd.transpose(datum, axes=(2, 0, 1)) | ['def', 'postprocess_data(self,', 'datum):', 'return', 'nd.transpose(datum,', 'axes=(2,', '0,', '1))'] | 500,130 |
ChenhongyiYang/PPAL | lad.py | LAD.extract_teacher_feat | extract_teacher_feat | Directly extract teacher features from the backbone+neck. | [
"Directly",
"extract",
"teacher",
"features",
"from",
"the",
"backbone+neck."
] | def extract_teacher_feat(self, img):
x = self.teacher_model.backbone(img)
if self.with_teacher_neck:
x = self.teacher_model.neck(x)
return x | ['def', 'extract_teacher_feat(self,', 'img):', 'x', '=', 'self.teacher_model.backbone(img)', 'if', 'self.with_teacher_neck:', 'x', '=', 'self.teacher_model.neck(x)', 'return', 'x'] | 821,667 |
google/ml-compiler-opt | feature_ops.py | get_normalize_fn | get_normalize_fn | Return a normalization function to normalize the input feature. | [
"Return",
"a",
"normalization",
"function",
"to",
"normalize",
"the",
"input",
"feature."
] | def get_normalize_fn(quantile: List[float], with_sqrt: bool, with_z_score_normalization: bool, eps: float=1e-08, preprocessing_fn: Optional[Callable[[types.Tensor], types.Float]]=None):
if not preprocessing_fn:
preprocessing_fn = lambda x: x
processed_quantile = [preprocessing_fn(x) for x in quantile]
... | ['def', 'get_normalize_fn(quantile:', 'List[float],', 'with_sqrt:', 'bool,', 'with_z_score_normalization:', 'bool,', 'eps:', 'float=1e-08,', 'preprocessing_fn:', 'Optional[Callable[[types.Tensor],', 'types.Float]]=None):', 'if', 'not', 'preprocessing_fn:', 'preprocessing_fn', '=', 'lambda', 'x:', 'x', 'processed_quanti... | 671,202 |
boostcampaitech3/level2-semantic-segmentation-level2-cv-16 | enc_head.py | EncHead.forward_test | forward_test | Forward function for testing, ignore se_loss. | [
"Forward",
"function",
"for",
"testing,",
"ignore",
"se_loss."
] | def forward_test(self, inputs, img_metas, test_cfg):
if self.use_se_loss:
return self.forward(inputs)[0]
else:
return self.forward(inputs) | ['def', 'forward_test(self,', 'inputs,', 'img_metas,', 'test_cfg):', 'if', 'self.use_se_loss:', 'return', 'self.forward(inputs)[0]', 'else:', 'return', 'self.forward(inputs)'] | 588,817 |
triaquae/triaquae | geometry.py | GEOSGeometry.union | union | Returns a Geometry representing all the points in this Geometry and other. | [
"Returns",
"a",
"Geometry",
"representing",
"all",
"the",
"points",
"in",
"this",
"Geometry",
"and",
"other."
] | def union(self, other):
return self._topology(capi.geos_union(self.ptr, other.ptr)) | ['def', 'union(self,', 'other):', 'return', 'self._topology(capi.geos_union(self.ptr,', 'other.ptr))'] | 357,810 |
joaquimcampos/DeepSplines | datasets.py | S_shape.get_labels | get_labels | Generate dataset labels for a set of inputs. | [
"Generate",
"dataset",
"labels",
"for",
"a",
"set",
"of",
"inputs."
] | def get_labels(self, inputs):
(x, y) = (inputs[:, 0].numpy(), inputs[:, 1].numpy())
in_sin = np.logical_and(x > self.sin_func(y, 'lower'), x < self.sin_func(y, 'upper'))
in_boundaries = np.abs(y) < self.y_cutoff
np_labels = np.logical_and(in_sin, in_boundaries).astype(np.float32)
return torch.from_n... | ['def', 'get_labels(self,', 'inputs):', '(x,', 'y)', '=', '(inputs[:,', '0].numpy(),', 'inputs[:,', '1].numpy())', 'in_sin', '=', 'np.logical_and(x', '>', 'self.sin_func(y,', "'lower'),", 'x', '<', 'self.sin_func(y,', "'upper'))", 'in_boundaries', '=', 'np.abs(y)', '<', 'self.y_cutoff', 'np_labels', '=', 'np.logical_an... | 540,039 |
rudranil723/mini-main | mace.py | test_model_found | test_model_found | Try some proofs and exhibit the results. | [
"Try",
"some",
"proofs",
"and",
"exhibit",
"the",
"results."
] | def test_model_found(arguments):
for (goal, assumptions) in arguments:
g = Expression.fromstring(goal)
alist = [lp.parse(a) for a in assumptions]
m = MaceCommand(g, assumptions=alist, max_models=50)
found = m.build_model()
for a in alist:
print(' %s' % a)
... | ['def', 'test_model_found(arguments):', 'for', '(goal,', 'assumptions)', 'in', 'arguments:', 'g', '=', 'Expression.fromstring(goal)', 'alist', '=', '[lp.parse(a)', 'for', 'a', 'in', 'assumptions]', 'm', '=', 'MaceCommand(g,', 'assumptions=alist,', 'max_models=50)', 'found', '=', 'm.build_model()', 'for', 'a', 'in', 'al... | 321,289 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | saving_images.py | save_image_as_hdf5 | save_image_as_hdf5 | Saves image as hdf5 files to preserve the floating point values. | [
"Saves",
"image",
"as",
"hdf5",
"files",
"to",
"preserve",
"the",
"floating",
"point",
"values."
] | def save_image_as_hdf5(image, filename):
h5f = h5py.File(filename, 'w')
h5f.create_dataset('image', data=image.transpose(), compression='lzf')
h5f.close() | ['def', 'save_image_as_hdf5(image,', 'filename):', 'h5f', '=', 'h5py.File(filename,', "'w')", "h5f.create_dataset('image',", 'data=image.transpose(),', "compression='lzf')", 'h5f.close()'] | 11,873 |
UBCDingXin/improved_CcGAN | eval_metrics.py | FID | FID | The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). | [
"The",
"Frechet",
"distance",
"between",
"two",
"multivariate",
"Gaussians",
"X_1",
"~",
"N(mu_1,",
"C_1)",
"and",
"X_2",
"~",
"N(mu_2,",
"C_2)",
"is",
"d^2",
"=",
"||mu_1",
"-",
"mu_2||^2",
"+",
"Tr(C_1",
"+",
"C_2",
"-",
"2*sqrt(C_1*C_2))."
] | def FID(Xr, Xg, eps=1e-10):
MUr = np.mean(Xr, axis=0)
MUg = np.mean(Xg, axis=0)
mean_diff = MUr - MUg
SIGMAr = np.cov(Xr.transpose())
SIGMAg = np.cov(Xg.transpose())
(covmean, _) = linalg.sqrtm(SIGMAr.dot(SIGMAg), disp=False)
covmean = covmean.real
if not np.isfinite(covmean).all():
... | ['def', 'FID(Xr,', 'Xg,', 'eps=1e-10):', 'MUr', '=', 'np.mean(Xr,', 'axis=0)', 'MUg', '=', 'np.mean(Xg,', 'axis=0)', 'mean_diff', '=', 'MUr', '-', 'MUg', 'SIGMAr', '=', 'np.cov(Xr.transpose())', 'SIGMAg', '=', 'np.cov(Xg.transpose())', '(covmean,', '_)', '=', 'linalg.sqrtm(SIGMAr.dot(SIGMAg),', 'disp=False)', 'covmean'... | 611,262 |
sktime/sktime | test_pipeline.py | test_missing_unequal_tag_inference | test_missing_unequal_tag_inference | Test that ClustererPipeline infers missing/unequal tags correctly. | [
"Test",
"that",
"ClustererPipeline",
"infers",
"missing/unequal",
"tags",
"correctly."
] | def test_missing_unequal_tag_inference():
c = TimeSeriesDBSCAN(FlatDist.create_test_instance())
c1 = ExponentTransformer() * PaddingTransformer() * ExponentTransformer() * c
c2 = ExponentTransformer() * ExponentTransformer() * c
c3 = Imputer() * ExponentTransformer() * c
c4 = ExponentTransformer() *... | ['def', 'test_missing_unequal_tag_inference():', 'c', '=', 'TimeSeriesDBSCAN(FlatDist.create_test_instance())', 'c1', '=', 'ExponentTransformer()', '*', 'PaddingTransformer()', '*', 'ExponentTransformer()', '*', 'c', 'c2', '=', 'ExponentTransformer()', '*', 'ExponentTransformer()', '*', 'c', 'c3', '=', 'Imputer()', '*'... | 886,073 |
thu-ml/ares | attacker.py | UniversalAttacker.train | train | Set self to training mode. | [
"Set",
"self",
"to",
"training",
"mode."
] | def train(self, mode: bool=True):
self.training = mode
for module in self.children():
module.train(mode)
self.detector.eval()
self.detector.training = True
return self | ['def', 'train(self,', 'mode:', 'bool=True):', 'self.training', '=', 'mode', 'for', 'module', 'in', 'self.children():', 'module.train(mode)', 'self.detector.eval()', 'self.detector.training', '=', 'True', 'return', 'self'] | 402,062 |
microsoft/nni | space.py | ExecutableModelSpace.metric | metric | Training result of the model, or ``None`` if it's not yet trained or has failed to train. | [
"Training",
"result",
"of",
"the",
"model,",
"or",
"``None``",
"if",
"it's",
"not",
"yet",
"trained",
"or",
"has",
"failed",
"to",
"train."
] | def metric(self) -> TrialMetric | None:
return self.metrics.final | ['def', 'metric(self)', '->', 'TrialMetric', '|', 'None:', 'return', 'self.metrics.final'] | 728,942 |
mo-cv/pycv | managers.py | CaptureManager.startWritingVideo | startWritingVideo | Start writing exited frames to a video file. | [
"Start",
"writing",
"exited",
"frames",
"to",
"a",
"video",
"file."
] | def startWritingVideo(self, filename, encoding=cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')):
self._videoFilename = filename
self._videoEncoding = encoding | ['def', 'startWritingVideo(self,', 'filename,', "encoding=cv2.VideoWriter_fourcc('M',", "'J',", "'P',", "'G')):", 'self._videoFilename', '=', 'filename', 'self._videoEncoding', '=', 'encoding'] | 819,492 |
neuroailab/unsup_vvs | depth_pbr_zip_input.py | PBRNetZipDepthInput.dataset_parser_depth | dataset_parser_depth | Parse an ImageNet record from a serialized string Tensor. | [
"Parse",
"an",
"ImageNet",
"record",
"from",
"a",
"serialized",
"string",
"Tensor."
] | def dataset_parser_depth(self, value):
keys_to_features = {'depth': tf.FixedLenFeature((), tf.string, '')}
parsed = tf.parse_single_example(value, keys_to_features)
print('parsed example', parsed)
depth_image = tf.reshape(parsed['depth'], shape=[])
depth_image = tf.image.decode_png(depth_image, dtyp... | ['def', 'dataset_parser_depth(self,', 'value):', 'keys_to_features', '=', "{'depth':", 'tf.FixedLenFeature((),', 'tf.string,', "'')}", 'parsed', '=', 'tf.parse_single_example(value,', 'keys_to_features)', "print('parsed", "example',", 'parsed)', 'depth_image', '=', "tf.reshape(parsed['depth'],", 'shape=[])', 'depth_ima... | 438,510 |
myothida/Supervised-Machine-Learning | test_gcs.py | gcs_buffer | gcs_buffer | Emulate GCS using a binary buffer. | [
"Emulate",
"GCS",
"using",
"a",
"binary",
"buffer."
] | def gcs_buffer(monkeypatch):
import fsspec
gcs_buffer = BytesIO()
gcs_buffer.close = lambda : True
class MockGCSFileSystem(fsspec.AbstractFileSystem):
@staticmethod
def open(*args, **kwargs):
gcs_buffer.seek(0)
return gcs_buffer
def ls(self, path, **kwa... | ['def', 'gcs_buffer(monkeypatch):', 'import', 'fsspec', 'gcs_buffer', '=', 'BytesIO()', 'gcs_buffer.close', '=', 'lambda', ':', 'True', 'class', 'MockGCSFileSystem(fsspec.AbstractFileSystem):', '@staticmethod', 'def', 'open(*args,', '**kwargs):', 'gcs_buffer.seek(0)', 'return', 'gcs_buffer', 'def', 'ls(self,', 'path,',... | 443,723 |
xycforgithub/MultiTask-MRC | bleu_scorer.py | BleuScorer.rescore | rescore | replace test(s) with new test(s), and returns the new score. | [
"replace",
"test(s)",
"with",
"new",
"test(s),",
"and",
"returns",
"the",
"new",
"score."
] | def rescore(self, new_test):
return self.retest(new_test).compute_score() | ['def', 'rescore(self,', 'new_test):', 'return', 'self.retest(new_test).compute_score()'] | 644,437 |
devashish-patel/webcam-motion-detector | filemanager.py | FileContentsManager.save | save | Save the file model and return the model with no content. | [
"Save",
"the",
"file",
"model",
"and",
"return",
"the",
"model",
"with",
"no",
"content."
] | def save(self, model, path=''):
path = path.strip('/')
if 'type' not in model:
raise web.HTTPError(400, u'No file type provided')
if 'content' not in model and model['type'] != 'directory':
raise web.HTTPError(400, u'No file content provided')
os_path = self._get_os_path(path)
self.l... | ['def', 'save(self,', 'model,', "path=''):", 'path', '=', "path.strip('/')", 'if', "'type'", 'not', 'in', 'model:', 'raise', 'web.HTTPError(400,', "u'No", 'file', 'type', "provided')", 'if', "'content'", 'not', 'in', 'model', 'and', "model['type']", '!=', "'directory':", 'raise', 'web.HTTPError(400,', "u'No", 'file', '... | 980,743 |
43Carrig/recurrent_neural_networks_practice | mvn_linear_operator.py | MultivariateNormalLinearOperator.scale | scale | The `scale` `LinearOperator` in `Y = scale @ X + loc`. | [
"The",
"`scale`",
"`LinearOperator`",
"in",
"`Y",
"=",
"scale",
"@",
"X",
"+",
"loc`."
] | def scale(self):
return self.bijector.scale | ['def', 'scale(self):', 'return', 'self.bijector.scale'] | 312,838 |
enuguru/artificial_intelligence_and_machine_ | util.py | provide_metadata | provide_metadata | Provide bound MetaData for a single test, dropping afterwards. | [
"Provide",
"bound",
"MetaData",
"for",
"a",
"single",
"test,",
"dropping",
"afterwards."
] | def provide_metadata(fn, *args, **kw):
from . import config
from . import engines
from sqlalchemy import schema
metadata = schema.MetaData(config.db)
self = args[0]
prev_meta = getattr(self, 'metadata', None)
self.metadata = metadata
try:
return fn(*args, **kw)
finally:
... | ['def', 'provide_metadata(fn,', '*args,', '**kw):', 'from', '.', 'import', 'config', 'from', '.', 'import', 'engines', 'from', 'sqlalchemy', 'import', 'schema', 'metadata', '=', 'schema.MetaData(config.db)', 'self', '=', 'args[0]', 'prev_meta', '=', 'getattr(self,', "'metadata',", 'None)', 'self.metadata', '=', 'metada... | 160,959 |
MACderRu/HyperDomainNet | model_irse.py | IR_50 | IR_50 | Constructs a ir-50 model. | [
"Constructs",
"a",
"ir-50",
"model."
] | def IR_50(input_size):
model = Backbone(input_size, num_layers=50, mode='ir', drop_ratio=0.4, affine=False)
return model | ['def', 'IR_50(input_size):', 'model', '=', 'Backbone(input_size,', 'num_layers=50,', "mode='ir',", 'drop_ratio=0.4,', 'affine=False)', 'return', 'model'] | 571,390 |
greydanus/mr_london | test_umath.py | test_reduceat | test_reduceat | Test bug in reduceat when structured arrays are not copied. | [
"Test",
"bug",
"in",
"reduceat",
"when",
"structured",
"arrays",
"are",
"not",
"copied."
] | def test_reduceat():
db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
a = np.empty([100], dtype=db)
a['name'] = 'Simple'
a['time'] = 10
a['value'] = 100
indx = [0, 7, 15, 25]
h2 = []
val1 = indx[0]
for val2 in indx[1:]:
h2.append(np.add.reduce(a['va... | ['def', 'test_reduceat():', 'db', '=', "np.dtype([('name',", "'S11'),", "('time',", 'np.int64),', "('value',", 'np.float32)])', 'a', '=', 'np.empty([100],', 'dtype=db)', "a['name']", '=', "'Simple'", "a['time']", '=', '10', "a['value']", '=', '100', 'indx', '=', '[0,', '7,', '15,', '25]', 'h2', '=', '[]', 'val1', '=', ... | 262,681 |
rudranil723/mini-main | introspection.py | DatabaseIntrospection.get_constraints | get_constraints | Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. | [
"Retrieve",
"any",
"constraints",
"or",
"keys",
"(unique,",
"pk,",
"fk,",
"check,",
"index)",
"across",
"one",
"or",
"more",
"columns."
] | def get_constraints(self, cursor, table_name):
constraints = {}
cursor.execute('PRAGMA index_list(%s)' % self.connection.ops.quote_name(table_name))
for row in cursor.fetchall():
(number, index, unique) = row[:3]
cursor.execute('PRAGMA index_info(%s)' % self.connection.ops.quote_name(index))... | ['def', 'get_constraints(self,', 'cursor,', 'table_name):', 'constraints', '=', '{}', "cursor.execute('PRAGMA", "index_list(%s)'", '%', 'self.connection.ops.quote_name(table_name))', 'for', 'row', 'in', 'cursor.fetchall():', '(number,', 'index,', 'unique)', '=', 'row[:3]', "cursor.execute('PRAGMA", "index_info(%s)'", '... | 315,887 |
wanggrun/Kalman-Normalization | symbolic_functions.py | rms | rms | Returns: root mean square of tensor x. | [
"Returns:",
"root",
"mean",
"square",
"of",
"tensor",
"x."
] | def rms(x, name=None):
if name is None:
name = x.op.name + '/rms'
with tf.name_scope(None):
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) | ['def', 'rms(x,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', 'x.op.name', '+', "'/rms'", 'with', 'tf.name_scope(None):', 'return', 'tf.sqrt(tf.reduce_mean(tf.square(x)),', 'name=name)', 'return', 'tf.sqrt(tf.reduce_mean(tf.square(x)),', 'name=name)'] | 594,835 |
kubeflow/pipelines | remote_runner.py | launch_flex_template | launch_flex_template | Main function for launching a Dataflow Flex Template. | [
"Main",
"function",
"for",
"launching",
"a",
"Dataflow",
"Flex",
"Template."
] | def launch_flex_template(type: str, project: str, location: str, payload: str, gcp_resources: str) -> None:
try:
job_spec = json_util.recursive_remove_empty(json.loads(insert_system_labels_into_payload(payload), strict=False))
except json.decoder.JSONDecodeError as err:
raise RuntimeError('Faile... | ['def', 'launch_flex_template(type:', 'str,', 'project:', 'str,', 'location:', 'str,', 'payload:', 'str,', 'gcp_resources:', 'str)', '->', 'None:', 'try:', 'job_spec', '=', 'json_util.recursive_remove_empty(json.loads(insert_system_labels_into_payload(payload),', 'strict=False))', 'except', 'json.decoder.JSONDecodeErro... | 770,730 |
Ruturaj123/Flowchart-Detection | summaries.py | add_image_summaries | add_image_summaries | Adds an image summary for each of the given tensors. | [
"Adds",
"an",
"image",
"summary",
"for",
"each",
"of",
"the",
"given",
"tensors."
] | def add_image_summaries(tensors, prefix=None):
summary_ops = []
for tensor in tensors:
summary_ops.append(add_image_summary(tensor, prefix=prefix))
return summary_ops | ['def', 'add_image_summaries(tensors,', 'prefix=None):', 'summary_ops', '=', '[]', 'for', 'tensor', 'in', 'tensors:', 'summary_ops.append(add_image_summary(tensor,', 'prefix=prefix))', 'return', 'summary_ops'] | 604,471 |
dbash/zerowaste | config.py | add_panoptic_deeplab_config | add_panoptic_deeplab_config | Add config for Panoptic-DeepLab. | [
"Add",
"config",
"for",
"Panoptic-DeepLab."
] | def add_panoptic_deeplab_config(cfg):
add_deeplab_config(cfg)
cfg.INPUT.GAUSSIAN_SIGMA = 10
cfg.INPUT.IGNORE_STUFF_IN_OFFSET = True
cfg.INPUT.SMALL_INSTANCE_AREA = 4096
cfg.INPUT.SMALL_INSTANCE_WEIGHT = 3
cfg.INPUT.IGNORE_CROWD_IN_SEMANTIC = False
cfg.SOLVER.OPTIMIZER = 'ADAM'
cfg.MODEL.... | ['def', 'add_panoptic_deeplab_config(cfg):', 'add_deeplab_config(cfg)', 'cfg.INPUT.GAUSSIAN_SIGMA', '=', '10', 'cfg.INPUT.IGNORE_STUFF_IN_OFFSET', '=', 'True', 'cfg.INPUT.SMALL_INSTANCE_AREA', '=', '4096', 'cfg.INPUT.SMALL_INSTANCE_WEIGHT', '=', '3', 'cfg.INPUT.IGNORE_CROWD_IN_SEMANTIC', '=', 'False', 'cfg.SOLVER.OPTIM... | 971,704 |
tgisaturday/image-text-recognition | resnet_model.py | resnet_v2 | resnet_v2 | Returns the ResNet model for a given size and number of output classes. | [
"Returns",
"the",
"ResNet",
"model",
"for",
"a",
"given",
"size",
"and",
"number",
"of",
"output",
"classes."
] | def resnet_v2(resnet_size, num_classes, data_format=None):
model_params = {18: {'block': building_block, 'layers': [2, 2, 2, 2]}, 34: {'block': building_block, 'layers': [3, 4, 6, 3]}, 50: {'block': bottleneck_block, 'layers': [3, 4, 6, 3]}, 101: {'block': bottleneck_block, 'layers': [3, 4, 23, 3]}, 152: {'block': ... | ['def', 'resnet_v2(resnet_size,', 'num_classes,', 'data_format=None):', 'model_params', '=', '{18:', "{'block':", 'building_block,', "'layers':", '[2,', '2,', '2,', '2]},', '34:', "{'block':", 'building_block,', "'layers':", '[3,', '4,', '6,', '3]},', '50:', "{'block':", 'bottleneck_block,', "'layers':", '[3,', '4,', '... | 229,302 |
louisthai/cpsc5910-su20 | ipythonblocks.py | BlockGrid.show_image | show_image | Embed grid in the notebook as a PNG image. | [
"Embed",
"grid",
"in",
"the",
"notebook",
"as",
"a",
"PNG",
"image."
] | def show_image(self):
if sys.version_info[0] == 2:
from StringIO import StringIO as BytesIO
elif sys.version_info[0] == 3:
from io import BytesIO
im = BytesIO()
self._write_image(im)
display(ipyImage(data=im.getvalue(), format='png')) | ['def', 'show_image(self):', 'if', 'sys.version_info[0]', '==', '2:', 'from', 'StringIO', 'import', 'StringIO', 'as', 'BytesIO', 'elif', 'sys.version_info[0]', '==', '3:', 'from', 'io', 'import', 'BytesIO', 'im', '=', 'BytesIO()', 'self._write_image(im)', 'display(ipyImage(data=im.getvalue(),', "format='png'))"] | 137,988 |
sunishsheth2009/ChatterBot | trainers.py | ListTrainer.train | train | Train the chat bot based on the provided list of statements that represents a single conversation. | [
"Train",
"the",
"chat",
"bot",
"based",
"on",
"the",
"provided",
"list",
"of",
"statements",
"that",
"represents",
"a",
"single",
"conversation."
] | def train(self, conversation):
previous_statement_text = None
previous_statement_search_text = ''
statements_to_create = []
for (conversation_count, text) in enumerate(conversation):
if self.show_training_progress:
utils.print_progress_bar('List Trainer', conversation_count + 1, len(... | ['def', 'train(self,', 'conversation):', 'previous_statement_text', '=', 'None', 'previous_statement_search_text', '=', "''", 'statements_to_create', '=', '[]', 'for', '(conversation_count,', 'text)', 'in', 'enumerate(conversation):', 'if', 'self.show_training_progress:', "utils.print_progress_bar('List", "Trainer',", ... | 478,072 |
thomasbinish/Computer-Vision | thread_demo.py | putIterationsPerSec | putIterationsPerSec | Add iterations per second text to lower-left corner of a frame. | [
"Add",
"iterations",
"per",
"second",
"text",
"to",
"lower-left",
"corner",
"of",
"a",
"frame."
] | def putIterationsPerSec(frame, iterations_per_sec):
cv2.putText(frame, '{:.0f} iterations/sec'.format(iterations_per_sec), (10, 450), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255))
return frame | ['def', 'putIterationsPerSec(frame,', 'iterations_per_sec):', 'cv2.putText(frame,', "'{:.0f}", "iterations/sec'.format(iterations_per_sec),", '(10,', '450),', 'cv2.FONT_HERSHEY_SIMPLEX,', '1.0,', '(255,', '255,', '255))', 'return', 'frame'] | 459,913 |
bryanvriel/pgan | structures.py | Data.test_batch | test_batch | Get a random batch of testing data as a dictionary. | [
"Get",
"a",
"random",
"batch",
"of",
"testing",
"data",
"as",
"a",
"dictionary."
] | def test_batch(self, batch_size=None):
batch_size = batch_size or self.batch_size
ind = self.rng.choice(self.n_test, size=batch_size)
return {key: self._test[key][ind] for key in self.keys} | ['def', 'test_batch(self,', 'batch_size=None):', 'batch_size', '=', 'batch_size', 'or', 'self.batch_size', 'ind', '=', 'self.rng.choice(self.n_test,', 'size=batch_size)', 'return', '{key:', 'self._test[key][ind]', 'for', 'key', 'in', 'self.keys}'] | 767,638 |
facebookresearch/CompilerGym | minimize_trajectory_test.py | test_random_minimization | test_random_minimization | Test that random minimization reduces trajectory. | [
"Test",
"that",
"random",
"minimization",
"reduces",
"trajectory."
] | def test_random_minimization():
env = MockEnv(actions=list(range(10)))
minimized = [0, 1, 4]
def hypothesis(env):
return all((x in env.actions for x in minimized))
list(mt.random_minimization(env, hypothesis))
assert len(env.actions) <= 10
assert len(env.actions) >= len(minimized)
a... | ['def', 'test_random_minimization():', 'env', '=', 'MockEnv(actions=list(range(10)))', 'minimized', '=', '[0,', '1,', '4]', 'def', 'hypothesis(env):', 'return', 'all((x', 'in', 'env.actions', 'for', 'x', 'in', 'minimized))', 'list(mt.random_minimization(env,', 'hypothesis))', 'assert', 'len(env.actions)', '<=', '10', '... | 126,005 |
rifqind/Agent-Programs-3KS1 | utils.py | num_or_str | num_or_str | The argument is a string; convert to a number if possible, or strip it. | [
"The",
"argument",
"is",
"a",
"string;",
"convert",
"to",
"a",
"number",
"if",
"possible,",
"or",
"strip",
"it."
] | def num_or_str(x):
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return str(x).strip() | ['def', 'num_or_str(x):', 'try:', 'return', 'int(x)', 'except', 'ValueError:', 'try:', 'return', 'float(x)', 'except', 'ValueError:', 'return', 'str(x).strip()'] | 22,205 |
gunthercox/ChatterBot | times.py | adatetime.tuple | tuple | Returns the attributes of the ``adatetime`` object as a tuple of ``(year, month, day, hour, minute, second, microsecond)``. | [
"Returns",
"the",
"attributes",
"of",
"the",
"``adatetime``",
"object",
"as",
"a",
"tuple",
"of",
"``(year,",
"month,",
"day,",
"hour,",
"minute,",
"second,",
"microsecond)``."
] | def tuple(self):
return (self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond) | ['def', 'tuple(self):', 'return', '(self.year,', 'self.month,', 'self.day,', 'self.hour,', 'self.minute,', 'self.second,', 'self.microsecond)'] | 484,817 |
enuguru/artificial_intelligence_and_machine_learning | numeric.py | max_value | max_value | Returns the maximum (unsigned) integer representable in the given number of bits. | [
"Returns",
"the",
"maximum",
"(unsigned)",
"integer",
"representable",
"in",
"the",
"given",
"number",
"of",
"bits."
] | def max_value(bitcount):
return ~(~0 << bitcount) | ['def', 'max_value(bitcount):', 'return', '~(~0', '<<', 'bitcount)'] | 162,782 |
sw-gong/coma | graph.py | rescale_L | rescale_L | Rescale the Laplacian eigenvalues in [-1,1]. | [
"Rescale",
"the",
"Laplacian",
"eigenvalues",
"in",
"[-1,1]."
] | def rescale_L(L, lmax=2):
(M, M) = L.shape
I = scipy.sparse.identity(M, format='csr', dtype=L.dtype)
L /= lmax / 2
L -= I
return L | ['def', 'rescale_L(L,', 'lmax=2):', '(M,', 'M)', '=', 'L.shape', 'I', '=', 'scipy.sparse.identity(M,', "format='csr',", 'dtype=L.dtype)', 'L', '/=', 'lmax', '/', '2', 'L', '-=', 'I', 'return', 'L'] | 467,121 |
nhsx/SynthVAE | module_inspection.py | has_no_param | has_no_param | Checks if a module does not have any parameters. | [
"Checks",
"if",
"a",
"module",
"does",
"not",
"have",
"any",
"parameters."
] | def has_no_param(module: nn.Module) -> bool:
has_params = any((p is not None for p in module.parameters(recurse=False)))
return not has_params | ['def', 'has_no_param(module:', 'nn.Module)', '->', 'bool:', 'has_params', '=', 'any((p', 'is', 'not', 'None', 'for', 'p', 'in', 'module.parameters(recurse=False)))', 'return', 'not', 'has_params'] | 906,247 |
yd8534976/cs224n | q1_window.py | WindowModel.consolidate_predictions | consolidate_predictions | Batch the predictions into groups of sentence length. | [
"Batch",
"the",
"predictions",
"into",
"groups",
"of",
"sentence",
"length."
] | def consolidate_predictions(self, examples_raw, examples, preds):
ret = []
i = 0
for (sentence, labels) in examples_raw:
labels_ = preds[i:i + len(sentence)]
i += len(sentence)
ret.append([sentence, labels, labels_])
return ret | ['def', 'consolidate_predictions(self,', 'examples_raw,', 'examples,', 'preds):', 'ret', '=', '[]', 'i', '=', '0', 'for', '(sentence,', 'labels)', 'in', 'examples_raw:', 'labels_', '=', 'preds[i:i', '+', 'len(sentence)]', 'i', '+=', 'len(sentence)', 'ret.append([sentence,', 'labels,', 'labels_])', 'return', 'ret'] | 506,663 |
jason718/game-feature-learning | test_coord_map.py | TestCoordMap.test_conv_pool_deconv | test_conv_pool_deconv | Map through conv, pool, and deconv. | [
"Map",
"through",
"conv,",
"pool,",
"and",
"deconv."
] | def test_conv_pool_deconv(self):
n = coord_net_spec()
(ax, a, b) = coord_map_from_to(n.deconv, n.data)
self.assertEquals(ax, 1)
self.assertEquals(a, 1)
self.assertEquals(b, 0)
n = coord_net_spec(pool=4, dstride=4)
(ax, a, b) = coord_map_from_to(n.deconv, n.data)
self.assertEquals(ax, 1)
... | ['def', 'test_conv_pool_deconv(self):', 'n', '=', 'coord_net_spec()', '(ax,', 'a,', 'b)', '=', 'coord_map_from_to(n.deconv,', 'n.data)', 'self.assertEquals(ax,', '1)', 'self.assertEquals(a,', '1)', 'self.assertEquals(b,', '0)', 'n', '=', 'coord_net_spec(pool=4,', 'dstride=4)', '(ax,', 'a,', 'b)', '=', 'coord_map_from_t... | 199,487 |
zihuitang/medical_AI_platform | _pydecimal.py | Decimal.logical_or | logical_or | Applies an 'or' operation between self and other's digits. | [
"Applies",
"an",
"'or'",
"operation",
"between",
"self",
"and",
"other's",
"digits."
] | def logical_or(self, other, context=None):
if context is None:
context = getcontext()
other = _convert_other(other, raiseit=True)
if not self._islogical() or not other._islogical():
return context._raise_error(InvalidOperation)
(opa, opb) = self._fill_logical(context, self._int, other._i... | ['def', 'logical_or(self,', 'other,', 'context=None):', 'if', 'context', 'is', 'None:', 'context', '=', 'getcontext()', 'other', '=', '_convert_other(other,', 'raiseit=True)', 'if', 'not', 'self._islogical()', 'or', 'not', 'other._islogical():', 'return', 'context._raise_error(InvalidOperation)', '(opa,', 'opb)', '=', ... | 281,915 |
intra2net/guibot | test_finder.py | CVParameterTest.test_parameter_parsing | test_parameter_parsing | Check that basic parameter parsing works. | [
"Check",
"that",
"basic",
"parameter",
"parsing",
"works."
] | def test_parameter_parsing(self):
expected = CVParameter(3, min_val=0.003, max_val=150, delta=1030.25, tolerance=10.2, fixed=True, enumerated=False)
parsed = CVParameter.from_string("<value='3' min='0.003' max='150' delta='1030.25' tolerance='10.2' fixed='True' enumerated='False'>")
self.assertEqual(parsed,... | ['def', 'test_parameter_parsing(self):', 'expected', '=', 'CVParameter(3,', 'min_val=0.003,', 'max_val=150,', 'delta=1030.25,', 'tolerance=10.2,', 'fixed=True,', 'enumerated=False)', 'parsed', '=', 'CVParameter.from_string("<value=\'3\'', "min='0.003'", "max='150'", "delta='1030.25'", "tolerance='10.2'", "fixed='True'"... | 572,668 |
matsu0228/nlp-jp | arffread.py | get_ndata | get_ndata | Read the whole file to get number of data attributes. | [
"Read",
"the",
"whole",
"file",
"to",
"get",
"number",
"of",
"data",
"attributes."
] | def get_ndata(ofile):
data = [next(ofile)]
loc = 1
if data[0].strip()[0] == '{':
raise ValueError('This looks like a sparse ARFF: not supported yet')
for i in ofile:
loc += 1
return loc | ['def', 'get_ndata(ofile):', 'data', '=', '[next(ofile)]', 'loc', '=', '1', 'if', 'data[0].strip()[0]', '==', "'{':", 'raise', "ValueError('This", 'looks', 'like', 'a', 'sparse', 'ARFF:', 'not', 'supported', "yet')", 'for', 'i', 'in', 'ofile:', 'loc', '+=', '1', 'return', 'loc'] | 805,455 |
nicknochnack/RealTimeSignLanguageTFJS | center_net_meta_arch_tf2_test.py | get_fake_groundtruth_dict | get_fake_groundtruth_dict | Prepares the fake groundtruth dictionary. | [
"Prepares",
"the",
"fake",
"groundtruth",
"dictionary."
] | def get_fake_groundtruth_dict(input_height, input_width, stride):
boxes = [tf.constant([[0.54, 0.54, 0.56, 0.56]]), tf.constant([[0.0, 0.0, 0.5, 0.5]])]
classes = [tf.one_hot([1], depth=_NUM_CLASSES), tf.one_hot([0], depth=_NUM_CLASSES)]
weights = [tf.constant([1.0]), tf.constant([0.0])]
keypoints = [tf... | ['def', 'get_fake_groundtruth_dict(input_height,', 'input_width,', 'stride):', 'boxes', '=', '[tf.constant([[0.54,', '0.54,', '0.56,', '0.56]]),', 'tf.constant([[0.0,', '0.0,', '0.5,', '0.5]])]', 'classes', '=', '[tf.one_hot([1],', 'depth=_NUM_CLASSES),', 'tf.one_hot([0],', 'depth=_NUM_CLASSES)]', 'weights', '=', '[tf.... | 852,398 |
opendilab/DI-star | sc2_env.py | SC2Env.observation_spec | observation_spec | Look at Features for full specs. | [
"Look",
"at",
"Features",
"for",
"full",
"specs."
] | def observation_spec(self):
return tuple((f.observation_spec() for f in self._features)) | ['def', 'observation_spec(self):', 'return', 'tuple((f.observation_spec()', 'for', 'f', 'in', 'self._features))'] | 184,636 |
Eric3911/OpenAGI | data_pipeline.py | DataPipeline.get_selected_node_ids | get_selected_node_ids | Translates selected keys to dependency graph keys. | [
"Translates",
"selected",
"keys",
"to",
"dependency",
"graph",
"keys."
] | def get_selected_node_ids(self, selected_keys):
return [self.key_to_node[key] for key in selected_keys] | ['def', 'get_selected_node_ids(self,', 'selected_keys):', 'return', '[self.key_to_node[key]', 'for', 'key', 'in', 'selected_keys]'] | 251,362 |
huawei-noah/xingtian | hw_cloud_helper.py | mox_makedir_if_not_existed | mox_makedir_if_not_existed | Make direction if not existed within s3. | [
"Make",
"direction",
"if",
"not",
"existed",
"within",
"s3."
] | def mox_makedir_if_not_existed(s3_path):
check_dir = s3_path if mox.file.is_directory(s3_path) else os.path.dirname(s3_path)
if not mox.file.is_directory(check_dir):
mox.file.make_dirs(check_dir) | ['def', 'mox_makedir_if_not_existed(s3_path):', 'check_dir', '=', 's3_path', 'if', 'mox.file.is_directory(s3_path)', 'else', 'os.path.dirname(s3_path)', 'if', 'not', 'mox.file.is_directory(check_dir):', 'mox.file.make_dirs(check_dir)'] | 962,422 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | classifier_base.py | ClassifierBase.default_hparams | default_hparams | Returns a dictionary of hyperparameters with default values. | [
"Returns",
"a",
"dictionary",
"of",
"hyperparameters",
"with",
"default",
"values."
] | def default_hparams():
return {'name': 'classifier'} | ['def', 'default_hparams():', 'return', "{'name':", "'classifier'}"] | 406,171 |
THUNLP-MT/THUCC | networks.py | SimpleVLblNce.update_learning_rate | update_learning_rate | Update the learning rate depending on a given method. | [
"Update",
"the",
"learning",
"rate",
"depending",
"on",
"a",
"given",
"method."
] | def update_learning_rate(self, remaining):
new_value = self.global_lr
if self.lr_adaptation_method == 'linear':
new_value = {k: v * remaining for (k, v) in new_value.iteritems()}
for (k, v) in new_value.iteritems():
self.lr[k].set_value(v)
log.debug("Param %s's learning rate is %s" % (se... | ['def', 'update_learning_rate(self,', 'remaining):', 'new_value', '=', 'self.global_lr', 'if', 'self.lr_adaptation_method', '==', "'linear':", 'new_value', '=', '{k:', 'v', '*', 'remaining', 'for', '(k,', 'v)', 'in', 'new_value.iteritems()}', 'for', '(k,', 'v)', 'in', 'new_value.iteritems():', 'self.lr[k].set_value(v)'... | 916,255 |
open-mmlab/mmtracking | test_selsa_bbox_head.py | test_selsa_bbox_head_loss | test_selsa_bbox_head_loss | Tests selsa_bbox_head loss when truth is empty and non-empty. | [
"Tests",
"selsa_bbox_head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_selsa_bbox_head_loss():
selsa_bbox_head_config = dict(num_shared_fcs=2, in_channels=8, fc_out_channels=16, roi_feat_size=3, aggregator=dict(type='SelsaAggregator', in_channels=16, num_attention_blocks=4))
self = SelsaBBoxHead(**selsa_bbox_head_config)
proposal_list = [torch.Tensor([[23.6667, 23.875... | ['def', 'test_selsa_bbox_head_loss():', 'selsa_bbox_head_config', '=', 'dict(num_shared_fcs=2,', 'in_channels=8,', 'fc_out_channels=16,', 'roi_feat_size=3,', "aggregator=dict(type='SelsaAggregator',", 'in_channels=16,', 'num_attention_blocks=4))', 'self', '=', 'SelsaBBoxHead(**selsa_bbox_head_config)', 'proposal_list',... | 625,931 |
Speedwagon13/CS-3600-Introduction-to-- | pytree.py | Base.replace | replace | Replace this node with a new one in the parent. | [
"Replace",
"this",
"node",
"with",
"a",
"new",
"one",
"in",
"the",
"parent."
] | def replace(self, new):
assert self.parent is not None, str(self)
assert new is not None
if not isinstance(new, list):
new = [new]
l_children = []
found = False
for ch in self.parent.children:
if ch is self:
assert not found, (self.parent.children, self, new)
... | ['def', 'replace(self,', 'new):', 'assert', 'self.parent', 'is', 'not', 'None,', 'str(self)', 'assert', 'new', 'is', 'not', 'None', 'if', 'not', 'isinstance(new,', 'list):', 'new', '=', '[new]', 'l_children', '=', '[]', 'found', '=', 'False', 'for', 'ch', 'in', 'self.parent.children:', 'if', 'ch', 'is', 'self:', 'asser... | 219,400 |
weimin17/Object-Detection_HelmetDetection | decoder.py | DeepSpeechDecoder.decode | decode | Decode the best guess from logits using greedy algorithm. | [
"Decode",
"the",
"best",
"guess",
"from",
"logits",
"using",
"greedy",
"algorithm."
] | def decode(self, logits):
best = list(np.argmax(logits, axis=1))
merge = [k for (k, _) in itertools.groupby(best)]
merge_remove_blank = []
for k in merge:
if k != self.blank_index:
merge_remove_blank.append(k)
return self.convert_to_string(merge_remove_blank) | ['def', 'decode(self,', 'logits):', 'best', '=', 'list(np.argmax(logits,', 'axis=1))', 'merge', '=', '[k', 'for', '(k,', '_)', 'in', 'itertools.groupby(best)]', 'merge_remove_blank', '=', '[]', 'for', 'k', 'in', 'merge:', 'if', 'k', '!=', 'self.blank_index:', 'merge_remove_blank.append(k)', 'return', 'self.convert_to_s... | 762,382 |
matsu0228/nlp-jp | storage_uri.py | BucketStorageUri.set_def_canned_acl | set_def_canned_acl | Sets or updates a bucket's default object acl to a predefined (canned) value. | [
"Sets",
"or",
"updates",
"a",
"bucket's",
"default",
"object",
"acl",
"to",
"a",
"predefined",
"(canned)",
"value."
] | def set_def_canned_acl(self, acl_str, validate=False, headers=None, version_id=None):
self._check_bucket_uri('set_def_canned_acl ')
key = self.get_key(validate, headers)
self.check_response(key, 'key', self.uri)
key.set_def_canned_acl(acl_str, headers, version_id) | ['def', 'set_def_canned_acl(self,', 'acl_str,', 'validate=False,', 'headers=None,', 'version_id=None):', "self._check_bucket_uri('set_def_canned_acl", "')", 'key', '=', 'self.get_key(validate,', 'headers)', 'self.check_response(key,', "'key',", 'self.uri)', 'key.set_def_canned_acl(acl_str,', 'headers,', 'version_id)'] | 783,893 |
YannDubs/Invariant-Self-Supervised-Learning | base.py | ISSLDataset.get_x_target_Mx | get_x_target_Mx | Return the correct example, target, and maximal invariant. | [
"Return",
"the",
"correct",
"example,",
"target,",
"and",
"maximal",
"invariant."
] | def get_x_target_Mx(self, index: int) -> tuple[Any, Any, Any]:
... | ['def', 'get_x_target_Mx(self,', 'index:', 'int)', '->', 'tuple[Any,', 'Any,', 'Any]:', '...'] | 245,954 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | skip_thoughts_model.py | random_orthonormal_initializer | random_orthonormal_initializer | Variable initializer that produces a random orthonormal matrix. | [
"Variable",
"initializer",
"that",
"produces",
"a",
"random",
"orthonormal",
"matrix."
] | def random_orthonormal_initializer(shape, dtype=tf.float32, partition_info=None):
if len(shape) != 2 or shape[0] != shape[1]:
raise ValueError('Expecting square shape, got %s' % shape)
(_, u, _) = tf.svd(tf.random_normal(shape, dtype=dtype), full_matrices=True)
return u | ['def', 'random_orthonormal_initializer(shape,', 'dtype=tf.float32,', 'partition_info=None):', 'if', 'len(shape)', '!=', '2', 'or', 'shape[0]', '!=', 'shape[1]:', 'raise', "ValueError('Expecting", 'square', 'shape,', 'got', "%s'", '%', 'shape)', '(_,', 'u,', '_)', '=', 'tf.svd(tf.random_normal(shape,', 'dtype=dtype),',... | 109,653 |
facebookresearch/deep_bisim4control | stacker.py | Physics.bounded_joint_pos | bounded_joint_pos | Returns joint positions as (sin, cos) values. | [
"Returns",
"joint",
"positions",
"as",
"(sin,",
"cos)",
"values."
] | def bounded_joint_pos(self, joint_names):
joint_pos = self.named.data.qpos[joint_names]
return np.vstack([np.sin(joint_pos), np.cos(joint_pos)]).T | ['def', 'bounded_joint_pos(self,', 'joint_names):', 'joint_pos', '=', 'self.named.data.qpos[joint_names]', 'return', 'np.vstack([np.sin(joint_pos),', 'np.cos(joint_pos)]).T'] | 536,466 |
enuguru/artificial_intelligence_and_machine_learning | utils.py | LRUCache.copy | copy | Return a shallow copy of the instance. | [
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"instance."
] | def copy(self):
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv | ['def', 'copy(self):', 'rv', '=', 'self.__class__(self.capacity)', 'rv._mapping.update(self._mapping)', 'rv._queue', '=', 'deque(self._queue)', 'return', 'rv'] | 129,478 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tiles.py | pixel_to_location | pixel_to_location | Converts a pixel in a tile to a coordinate. | [
"Converts",
"a",
"pixel",
"in",
"a",
"tile",
"to",
"a",
"coordinate."
] | def pixel_to_location(tile, dx, dy):
assert 0 <= dx <= 1, 'x offset is in [0, 1]'
assert 0 <= dy <= 1, 'y offset is in [0, 1]'
(west, south, east, north) = mercantile.bounds(tile)
def lerp(a, b, c):
return a + c * (b - a)
lon = lerp(west, east, dx)
lat = lerp(south, north, dy)
retur... | ['def', 'pixel_to_location(tile,', 'dx,', 'dy):', 'assert', '0', '<=', 'dx', '<=', '1,', "'x", 'offset', 'is', 'in', '[0,', "1]'", 'assert', '0', '<=', 'dy', '<=', '1,', "'y", 'offset', 'is', 'in', '[0,', "1]'", '(west,', 'south,', 'east,', 'north)', '=', 'mercantile.bounds(tile)', 'def', 'lerp(a,', 'b,', 'c):', 'retur... | 18,093 |
Kvatsx/Artificial-Intelligence-Assignments | utils.py | set_title | set_title | Set the terminal title. | [
"Set",
"the",
"terminal",
"title."
] | def set_title(text):
assert isinstance(text, six.text_type)
output = get_default_output()
output.set_title(text) | ['def', 'set_title(text):', 'assert', 'isinstance(text,', 'six.text_type)', 'output', '=', 'get_default_output()', 'output.set_title(text)'] | 76,130 |
palmettos/neat-autoencoders | statistics.py | StatisticsReporter.best_genome | best_genome | Returns the most fit genome ever seen. | [
"Returns",
"the",
"most",
"fit",
"genome",
"ever",
"seen."
] | def best_genome(self):
return self.best_genomes(1)[0] | ['def', 'best_genome(self):', 'return', 'self.best_genomes(1)[0]'] | 735,207 |
rlberry-py/rlberry | replay.py | ReplayBuffer.tags | tags | Tags identifying the entries in the replay buffer. | [
"Tags",
"identifying",
"the",
"entries",
"in",
"the",
"replay",
"buffer."
] | def tags(self):
return self._tags | ['def', 'tags(self):', 'return', 'self._tags'] | 862,112 |
LiWentomng/OrientedRepPoints | coco.py | CocoDataset.format_results | format_results | Format the results to json (standard format for COCO evaluation). | [
"Format",
"the",
"results",
"to",
"json",
"(standard",
"format",
"for",
"COCO",
"evaluation)."
] | def format_results(self, results, jsonfile_prefix=None, **kwargs):
assert isinstance(results, list), 'results must be a list'
assert len(results) == len(self), 'The length of results is not equal to the dataset len: {} != {}'.format(len(results), len(self))
if jsonfile_prefix is None:
tmp_dir = temp... | ['def', 'format_results(self,', 'results,', 'jsonfile_prefix=None,', '**kwargs):', 'assert', 'isinstance(results,', 'list),', "'results", 'must', 'be', 'a', "list'", 'assert', 'len(results)', '==', 'len(self),', "'The", 'length', 'of', 'results', 'is', 'not', 'equal', 'to', 'the', 'dataset', 'len:', '{}', '!=', "{}'.fo... | 776,557 |
rudranil723/mini-main | base.py | BaseDatabaseWrapper.ensure_connection | ensure_connection | Guarantee that a connection to the database is established. | [
"Guarantee",
"that",
"a",
"connection",
"to",
"the",
"database",
"is",
"established."
] | def ensure_connection(self):
if self.connection is None:
with self.wrap_database_errors:
self.connect() | ['def', 'ensure_connection(self):', 'if', 'self.connection', 'is', 'None:', 'with', 'self.wrap_database_errors:', 'self.connect()'] | 315,712 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | synthetic.py | lorentz | lorentz | This function generates a Lorentz time series of length sample_len, with standard parameters sigma, rho and beta. | [
"This",
"function",
"generates",
"a",
"Lorentz",
"time",
"series",
"of",
"length",
"sample_len,",
"with",
"standard",
"parameters",
"sigma,",
"rho",
"and",
"beta."
] | def lorentz(sample_len=1000, sigma=10, rho=28, beta=8 / 3, step=0.01):
x = np.zeros([sample_len])
y = np.zeros([sample_len])
z = np.zeros([sample_len])
x[0] = 0
y[0] = -0.01
z[0] = 9
for t in range(sample_len - 1):
x[t + 1] = x[t] + sigma * (y[t] - x[t]) * step
y[t + 1] = y[t... | ['def', 'lorentz(sample_len=1000,', 'sigma=10,', 'rho=28,', 'beta=8', '/', '3,', 'step=0.01):', 'x', '=', 'np.zeros([sample_len])', 'y', '=', 'np.zeros([sample_len])', 'z', '=', 'np.zeros([sample_len])', 'x[0]', '=', '0', 'y[0]', '=', '-0.01', 'z[0]', '=', '9', 'for', 't', 'in', 'range(sample_len', '-', '1):', 'x[t', '... | 15,206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.