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
Katja-M/Python_NaturalLanguageProcessing
framenet.py
FramenetCorpusReader.lu_ids_and_names
lu_ids_and_names
Uses the LU index, which is much faster than looking up each LU definition if only the names and IDs are needed.
[ "Uses", "the", "LU", "index,", "which", "is", "much", "faster", "than", "looking", "up", "each", "LU", "definition", "if", "only", "the", "names", "and", "IDs", "are", "needed." ]
def lu_ids_and_names(self, name=None): if not self._lu_idx: self._buildluindex() return {luID: luinfo.name for (luID, luinfo) in self._lu_idx.items() if luinfo.status not in self._bad_statuses and (name is None or re.search(name, luinfo.name) is not None)}
['def', 'lu_ids_and_names(self,', 'name=None):', 'if', 'not', 'self._lu_idx:', 'self._buildluindex()', 'return', '{luID:', 'luinfo.name', 'for', '(luID,', 'luinfo)', 'in', 'self._lu_idx.items()', 'if', 'luinfo.status', 'not', 'in', 'self._bad_statuses', 'and', '(name', 'is', 'None', 'or', 're.search(name,', 'luinfo.nam...
866,199
loftylabs/django-hardcopy
views.py
BaseMixin.process_html_content
process_html_content
Called after the template rendering, this method can be used to change the HTML before converting it to PDF or PNG (for example to replace relative images, css, or js file pathes to absolute pathes).
[ "Called", "after", "the", "template", "rendering,", "this", "method", "can", "be", "used", "to", "change", "the", "HTML", "before", "converting", "it", "to", "PDF", "or", "PNG", "(for", "example", "to", "replace", "relative", "images,", "css,", "or", "js", ...
def process_html_content(self, content): return content
['def', 'process_html_content(self,', 'content):', 'return', 'content']
164,650
Farama-Foundation/Gymnasium
compatibility.py
LegacyEnv.reset
reset
Reset the environment and return the initial observation.
[ "Reset", "the", "environment", "and", "return", "the", "initial", "observation." ]
def reset(self) -> Any: ...
['def', 'reset(self)', '->', 'Any:', '...']
573,365
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
macosxSupport.py
isCarbonTk
isCarbonTk
Returns True if IDLE is using a Carbon Aqua Tk (instead of the newer Cocoa Aqua Tk).
[ "Returns", "True", "if", "IDLE", "is", "using", "a", "Carbon", "Aqua", "Tk", "(instead", "of", "the", "newer", "Cocoa", "Aqua", "Tk)." ]
def isCarbonTk(): assert _tk_type is not None return _tk_type == 'carbon'
['def', 'isCarbonTk():', 'assert', '_tk_type', 'is', 'not', 'None', 'return', '_tk_type', '==', "'carbon'"]
430,872
sek788432/Waymo-2D-Object-Detection
relu.py
relu6
relu6
Computes the Relu6 activation function.
[ "Computes", "the", "Relu6", "activation", "function." ]
def relu6(features): features = tf.convert_to_tensor(features) return tf.nn.relu6(features)
['def', 'relu6(features):', 'features', '=', 'tf.convert_to_tensor(features)', 'return', 'tf.nn.relu6(features)']
972,349
arshpreetsingh/quantopian-machinelearning
cache.py
memoize_method
memoize_method
A normal memoize function.
[ "A", "normal", "memoize", "function." ]
def memoize_method(method): @wraps(method) def wrapper(self, *args, **kwargs): cache_dict = self.__dict__.setdefault('_memoize_method_dct', {}) dct = cache_dict.setdefault(method, {}) key = (args, frozenset(kwargs.items())) try: return dct[key] except KeyErro...
['def', 'memoize_method(method):', '@wraps(method)', 'def', 'wrapper(self,', '*args,', '**kwargs):', 'cache_dict', '=', "self.__dict__.setdefault('_memoize_method_dct',", '{})', 'dct', '=', 'cache_dict.setdefault(method,', '{})', 'key', '=', '(args,', 'frozenset(kwargs.items()))', 'try:', 'return', 'dct[key]', 'except'...
887,286
43Carrig/recurrent_neural_networks_practice
__init__.py
Extension.getConfigInfo
getConfigInfo
Return all config descriptions as a list of tuples.
[ "Return", "all", "config", "descriptions", "as", "a", "list", "of", "tuples." ]
def getConfigInfo(self): return [(key, self.config[key][1]) for key in self.config.keys()]
['def', 'getConfigInfo(self):', 'return', '[(key,', 'self.config[key][1])', 'for', 'key', 'in', 'self.config.keys()]']
310,567
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjvOptionWrapper.jointgroup
jointgroup
joint visualization by group.
[ "joint", "visualization", "by", "group." ]
def jointgroup(self): return util.buf_to_npy(self._ptr.contents.jointgroup, (6,))
['def', 'jointgroup(self):', 'return', 'util.buf_to_npy(self._ptr.contents.jointgroup,', '(6,))']
440,742
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
progress.py
Progress.Update
Update
Replaces internal current_size with current_size.
[ "Replaces", "internal", "current_size", "with", "current_size." ]
def Update(self, current_size): self.current_size = current_size
['def', 'Update(self,', 'current_size):', 'self.current_size', '=', 'current_size']
112,583
weimin17/Object-Detection_HelmetDetection
loss_layers_test.py
CrossFunctionTest.testVectorAndMatrixLabelEquivalence
testVectorAndMatrixLabelEquivalence
Tests equivalence between label shape [batch_size] or [batch_size, 1].
[ "Tests", "equivalence", "between", "label", "shape", "[batch_size]", "or", "[batch_size,", "1]." ]
def testVectorAndMatrixLabelEquivalence(self, global_objective, objective_kwargs): vector_labels = tf.constant([1.0, 1.0, 0.0, 0.0], shape=[4]) vector_logits = tf.constant([1.0, 0.1, 0.1, -1.0], shape=[4]) vector_kwargs = objective_kwargs.copy() vector_kwargs['labels'] = vector_labels vector_kwargs[...
['def', 'testVectorAndMatrixLabelEquivalence(self,', 'global_objective,', 'objective_kwargs):', 'vector_labels', '=', 'tf.constant([1.0,', '1.0,', '0.0,', '0.0],', 'shape=[4])', 'vector_logits', '=', 'tf.constant([1.0,', '0.1,', '0.1,', '-1.0],', 'shape=[4])', 'vector_kwargs', '=', 'objective_kwargs.copy()', "vector_kw...
763,024
shenyunhang/PDSL
point_utils.py
get_point_coords_from_point_annotation
get_point_coords_from_point_annotation
Load point coords and their corresponding labels from point annotation.
[ "Load", "point", "coords", "and", "their", "corresponding", "labels", "from", "point", "annotation." ]
def get_point_coords_from_point_annotation(instances): point_coords_list = [] point_labels_list = [] for instances_per_image in instances: if len(instances_per_image) == 0: continue point_coords = instances_per_image.gt_point_coords.to(torch.float32) point_labels = instan...
['def', 'get_point_coords_from_point_annotation(instances):', 'point_coords_list', '=', '[]', 'point_labels_list', '=', '[]', 'for', 'instances_per_image', 'in', 'instances:', 'if', 'len(instances_per_image)', '==', '0:', 'continue', 'point_coords', '=', 'instances_per_image.gt_point_coords.to(torch.float32)', 'point_l...
279,415
myothida/Supervised-Machine-Learning
common.py
any_none
any_none
Returns a boolean indicating if any argument is None.
[ "Returns", "a", "boolean", "indicating", "if", "any", "argument", "is", "None." ]
def any_none(*args) -> bool: return any((arg is None for arg in args))
['def', 'any_none(*args)', '->', 'bool:', 'return', 'any((arg', 'is', 'None', 'for', 'arg', 'in', 'args))']
442,335
aeon-toolkit/aeon
test_all_estimators.py
TestAllObjects.test_valid_estimator_tags
test_valid_estimator_tags
Check that Estimator tags are in VALID_ESTIMATOR_TAGS.
[ "Check", "that", "Estimator", "tags", "are", "in", "VALID_ESTIMATOR_TAGS." ]
def test_valid_estimator_tags(self, estimator_instance): for tag in estimator_instance.get_tags().keys(): assert tag in VALID_ESTIMATOR_TAGS
['def', 'test_valid_estimator_tags(self,', 'estimator_instance):', 'for', 'tag', 'in', 'estimator_instance.get_tags().keys():', 'assert', 'tag', 'in', 'VALID_ESTIMATOR_TAGS']
399,861
PKU-Alignment/safe-rlhf
chatbot.py
Chatbot.generator
generator
Generate the response to the given text.
[ "Generate", "the", "response", "to", "the", "given", "text." ]
def generator(self, text: str, stream: bool=False) -> Generator[str, None, None]: self.last_input = text self.last_dialogue = self.dialogue self.inputs.append(text) dialogue = self.dialogue + PROMPT_USER.format(input=text) + PROMPT_ASSISTANT tokenized = to_device(self.tokenizer(dialogue, return_tens...
['def', 'generator(self,', 'text:', 'str,', 'stream:', 'bool=False)', '->', 'Generator[str,', 'None,', 'None]:', 'self.last_input', '=', 'text', 'self.last_dialogue', '=', 'self.dialogue', 'self.inputs.append(text)', 'dialogue', '=', 'self.dialogue', '+', 'PROMPT_USER.format(input=text)', '+', 'PROMPT_ASSISTANT', 'toke...
829,180
95616ARG/PRDNN
mnist_mft.py
MNISTMFT.run
run
Runs the corruption-fine-tuning experiment.
[ "Runs", "the", "corruption-fine-tuning", "experiment." ]
def run(self): network = self.load_network('mnist_relu_3_100') assert isinstance(network.layers[-1], ReluLayer) network = Network(network.layers[:-1]) self.record_artifact(network, 'original', 'network') self.which_params = int(input('Which fine-tuning params? (1 or 2): ')) assert self.which_par...
['def', 'run(self):', 'network', '=', "self.load_network('mnist_relu_3_100')", 'assert', 'isinstance(network.layers[-1],', 'ReluLayer)', 'network', '=', 'Network(network.layers[:-1])', 'self.record_artifact(network,', "'original',", "'network')", 'self.which_params', '=', "int(input('Which", 'fine-tuning', 'params?', '...
822,183
43Carrig/recurrent_neural_networks_practice
cross_tower_utils.py
group_device_names
group_device_names
Group device names into groups of group_size.
[ "Group", "device", "names", "into", "groups", "of", "group_size." ]
def group_device_names(devices, group_size): num_devices = len(devices) if group_size > num_devices: raise ValueError('only %d devices, but group_size=%d' % (num_devices, group_size)) num_groups = num_devices // group_size + (1 if num_devices % group_size != 0 else 0) groups = [[] for i in range...
['def', 'group_device_names(devices,', 'group_size):', 'num_devices', '=', 'len(devices)', 'if', 'group_size', '>', 'num_devices:', 'raise', "ValueError('only", '%d', 'devices,', 'but', "group_size=%d'", '%', '(num_devices,', 'group_size))', 'num_groups', '=', 'num_devices', '//', 'group_size', '+', '(1', 'if', 'num_de...
312,765
Kvatsx/Artificial-Intelligence-Assignments
mainwindow.py
MainWindow.get_available_syntax_styles
get_available_syntax_styles
Get a list with the syntax styles available.
[ "Get", "a", "list", "with", "the", "syntax", "styles", "available." ]
def get_available_syntax_styles(self): styles = list(get_all_styles()) return sorted(styles)
['def', 'get_available_syntax_styles(self):', 'styles', '=', 'list(get_all_styles())', 'return', 'sorted(styles)']
77,303
linkedin/lambda-learner
trainer_logistic_loss_with_l2_test.py
TrainerLogisticLossWithL2Test.test_lr_update_hessian
test_lr_update_hessian
Test the Hessian update.
[ "Test", "the", "Hessian", "update." ]
def test_lr_update_hessian(self): (indexed_data, model) = simple_mock_data() lr = TrainerLogisticLossWithL2(training_data=indexed_data, initial_model=model, penalty=10, hessian_type=HessianType.FULL) hessian = lr._update_full_hessian(model.theta) expected_hessian = np.array([[10.076006603, 0.00782668920...
['def', 'test_lr_update_hessian(self):', '(indexed_data,', 'model)', '=', 'simple_mock_data()', 'lr', '=', 'TrainerLogisticLossWithL2(training_data=indexed_data,', 'initial_model=model,', 'penalty=10,', 'hessian_type=HessianType.FULL)', 'hessian', '=', 'lr._update_full_hessian(model.theta)', 'expected_hessian', '=', 'n...
261,866
RasaHQ/rasa
get_version_from_toml.py
project_root
project_root
Root directory of the project.
[ "Root", "directory", "of", "the", "project." ]
def project_root() -> Path: return Path(os.path.dirname(__file__)).parent
['def', 'project_root()', '->', 'Path:', 'return', 'Path(os.path.dirname(__file__)).parent']
837,984
weimin17/Object-Detection_HelmetDetection
contextual_bandit.py
ContextualBandit.reward
reward
Returns the reward for the number-th context and action.
[ "Returns", "the", "reward", "for", "the", "number-th", "context", "and", "action." ]
def reward(self, number, action): return self.data[self.order[number]][self.context_dim + action]
['def', 'reward(self,', 'number,', 'action):', 'return', 'self.data[self.order[number]][self.context_dim', '+', 'action]']
762,335
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
parse_to_conll.py
get_segmenter_corpus
get_segmenter_corpus
Reads in a character corpus for segmenting.
[ "Reads", "in", "a", "character", "corpus", "for", "segmenting." ]
def get_segmenter_corpus(input_data_path, use_text_format): tf.logging.info('Reading documents...') if use_text_format: char_corpus = sentence_io.FormatSentenceReader(input_data_path, 'untokenized-text').corpus() else: input_corpus = sentence_io.ConllSentenceReader(input_data_path).corpus() ...
['def', 'get_segmenter_corpus(input_data_path,', 'use_text_format):', "tf.logging.info('Reading", "documents...')", 'if', 'use_text_format:', 'char_corpus', '=', 'sentence_io.FormatSentenceReader(input_data_path,', "'untokenized-text').corpus()", 'else:', 'input_corpus', '=', 'sentence_io.ConllSentenceReader(input_data...
111,651
flow-project/flow
multiagent_traffic_light_grid.py
policy_mapping_fn
policy_mapping_fn
Map a policy in RLlib.
[ "Map", "a", "policy", "in", "RLlib." ]
def policy_mapping_fn(_): return 'av'
['def', 'policy_mapping_fn(_):', 'return', "'av'"]
212,046
deep-learning-indaba/Baobab
tests.py
EventsAPITest.test_past_event_offer_accepted
test_past_event_offer_accepted
API should return past events that user had an accepted offer for.
[ "API", "should", "return", "past", "events", "that", "user", "had", "an", "accepted", "offer", "for." ]
def test_past_event_offer_accepted(self): self.seed_static_data() past_event = self.add_event(start_date=datetime.now() - timedelta(days=30), end_date=datetime.now() - timedelta(days=30), key='PAST12') self.add_offer(self.test_user.id, past_event.id, candidate_response=True) response = self.app.get('/ap...
['def', 'test_past_event_offer_accepted(self):', 'self.seed_static_data()', 'past_event', '=', 'self.add_event(start_date=datetime.now()', '-', 'timedelta(days=30),', 'end_date=datetime.now()', '-', 'timedelta(days=30),', "key='PAST12')", 'self.add_offer(self.test_user.id,', 'past_event.id,', 'candidate_response=True)'...
94,143
matsu0228/nlp-jp
test_exceptions.py
TestErrorTree.test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error
test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error
If a validator is dumb (like :validator:`required` in draft 3) and refers to a path that isn't in the instance, the tree still properly returns a subtree for that path.
[ "If", "a", "validator", "is", "dumb", "(like", ":validator:`required`", "in", "draft", "3)", "and", "refers", "to", "a", "path", "that", "isn't", "in", "the", "instance,", "the", "tree", "still", "properly", "returns", "a", "subtree", "for", "that", "path." ...
def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self): error = exceptions.ValidationError('a message', validator='foo', instance={}, path=['foo']) tree = exceptions.ErrorTree([error]) self.assertIsInstance(tree['foo'], exceptions.ErrorTree)
['def', 'test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):', 'error', '=', "exceptions.ValidationError('a", "message',", "validator='foo',", 'instance={},', "path=['foo'])", 'tree', '=', 'exceptions.ErrorTree([error])', "self.assertIsInstance(tree['foo'],", 'exceptions.ErrorTree)']
788,036
nicknochnack/RealTimeSignLanguageTFJS
instance_heads.py
DetectionHead.call
call
Box and class branches for the Mask-RCNN model.
[ "Box", "and", "class", "branches", "for", "the", "Mask-RCNN", "model." ]
def call(self, inputs, training=None): roi_features = inputs (_, num_rois, height, width, filters) = roi_features.get_shape().as_list() x = tf.reshape(roi_features, [-1, height, width, filters]) for (conv, bn) in zip(self._convs, self._conv_norms): x = conv(x) x = bn(x) x = self....
['def', 'call(self,', 'inputs,', 'training=None):', 'roi_features', '=', 'inputs', '(_,', 'num_rois,', 'height,', 'width,', 'filters)', '=', 'roi_features.get_shape().as_list()', 'x', '=', 'tf.reshape(roi_features,', '[-1,', 'height,', 'width,', 'filters])', 'for', '(conv,', 'bn)', 'in', 'zip(self._convs,', 'self._conv...
850,846
gatapia/py_ml_utils
ast_parser.py
StrNodeVisitor.visit_Tuple
visit_Tuple
return a string representation of tuple.
[ "return", "a", "string", "representation", "of", "tuple." ]
def visit_Tuple(self, node): return self._sequence(node, '(%s)')
['def', 'visit_Tuple(self,', 'node):', 'return', 'self._sequence(node,', "'(%s)')"]
302,645
myothida/Supervised-Machine-Learning
_base.py
_AxesBase.get_ylabel
get_ylabel
Get the ylabel text string.
[ "Get", "the", "ylabel", "text", "string." ]
def get_ylabel(self): label = self.yaxis.get_label() return label.get_text()
['def', 'get_ylabel(self):', 'label', '=', 'self.yaxis.get_label()', 'return', 'label.get_text()']
362,583
saymedia/remoteobjects
fields.py
Dict.encode
encode
Encodes a `DataObject` attribute (a dictionary with decoded `DataObject` attribute values for values) into a dictionary value (a dictionary with encoded dictionary values for values).
[ "Encodes", "a", "`DataObject`", "attribute", "(a", "dictionary", "with", "decoded", "`DataObject`", "attribute", "values", "for", "values)", "into", "a", "dictionary", "value", "(a", "dictionary", "with", "encoded", "dictionary", "values", "for", "values)." ]
def encode(self, value): return dict(((k, self.fld.encode(v)) for (k, v) in value.iteritems()))
['def', 'encode(self,', 'value):', 'return', 'dict(((k,', 'self.fld.encode(v))', 'for', '(k,', 'v)', 'in', 'value.iteritems()))']
346,026
ifwe/digsby
accounttray.py
should_grey
should_grey
If this returns True, the account's tray icon will be greyed out when its count is zero.
[ "If", "this", "returns", "True,", "the", "account's", "tray", "icon", "will", "be", "greyed", "out", "when", "its", "count", "is", "zero." ]
def should_grey(acct): return not isinstance(acct, social.network)
['def', 'should_grey(acct):', 'return', 'not', 'isinstance(acct,', 'social.network)']
185,359
lebrice/Sequoia
pnn_method.py
PnnMethod.on_task_switch
on_task_switch
Called when switching tasks in a CL setting.
[ "Called", "when", "switching", "tasks", "in", "a", "CL", "setting." ]
def on_task_switch(self, task_id: Optional[int]) -> None: self.model.freeze_columns(skip=[task_id]) if task_id not in self.added_tasks: if isinstance(self.model, PnnA2CAgent): self.model.new_task(device=self.device, num_inputs=self.num_inputs, num_actions=self.num_actions) else: ...
['def', 'on_task_switch(self,', 'task_id:', 'Optional[int])', '->', 'None:', 'self.model.freeze_columns(skip=[task_id])', 'if', 'task_id', 'not', 'in', 'self.added_tasks:', 'if', 'isinstance(self.model,', 'PnnA2CAgent):', 'self.model.new_task(device=self.device,', 'num_inputs=self.num_inputs,', 'num_actions=self.num_ac...
343,989
Kvatsx/Artificial-Intelligence-Assignments
newrange.py
newrange.count
count
Return the number of ocurrences of integer `value` in the sequence this range represents.
[ "Return", "the", "number", "of", "ocurrences", "of", "integer", "`value`", "in", "the", "sequence", "this", "range", "represents." ]
def count(self, value): return int(value in self)
['def', 'count(self,', 'value):', 'return', 'int(value', 'in', 'self)']
37,182
rtlee9/recipe-summarization
prep_data.py
get_complete_recipes
get_complete_recipes
Return intersection of recipe keys and image keys.
[ "Return", "intersection", "of", "recipe", "keys", "and", "image", "keys." ]
def get_complete_recipes(recipes, image_list): recipe_keys = [url_to_filename(k) for k in recipes.keys()] files = np.array([filename for filename in image_list.keys() if filename in recipe_keys]) print('{:,} complete recipes found'.format(len(files))) return files
['def', 'get_complete_recipes(recipes,', 'image_list):', 'recipe_keys', '=', '[url_to_filename(k)', 'for', 'k', 'in', 'recipes.keys()]', 'files', '=', 'np.array([filename', 'for', 'filename', 'in', 'image_list.keys()', 'if', 'filename', 'in', 'recipe_keys])', "print('{:,}", 'complete', 'recipes', "found'.format(len(fil...
309,068
xunhuang1995/SGAN
extract_features_for_classification.py
chunks
chunks
Yield n-sized chunks from list of pfd or ar2 files.
[ "Yield", "n-sized", "chunks", "from", "list", "of", "pfd", "or", "ar2", "files." ]
def chunks(pfd_files, n): for i in range(0, len(pfd_files), n): yield pfd_files[i:i + n]
['def', 'chunks(pfd_files,', 'n):', 'for', 'i', 'in', 'range(0,', 'len(pfd_files),', 'n):', 'yield', 'pfd_files[i:i', '+', 'n]']
898,662
aws/sagemaker-python-sdk
session.py
Session.wait_for_endpoint
wait_for_endpoint
Wait for an Amazon SageMaker endpoint deployment to complete.
[ "Wait", "for", "an", "Amazon", "SageMaker", "endpoint", "deployment", "to", "complete." ]
def wait_for_endpoint(self, endpoint, poll=30): desc = _wait_until(lambda : _deploy_done(self.sagemaker_client, endpoint), poll) status = desc['EndpointStatus'] if status != 'InService': reason = desc.get('FailureReason', None) message = 'Error hosting endpoint {endpoint}: {status}. Reason: ...
['def', 'wait_for_endpoint(self,', 'endpoint,', 'poll=30):', 'desc', '=', '_wait_until(lambda', ':', '_deploy_done(self.sagemaker_client,', 'endpoint),', 'poll)', 'status', '=', "desc['EndpointStatus']", 'if', 'status', '!=', "'InService':", 'reason', '=', "desc.get('FailureReason',", 'None)', 'message', '=', "'Error",...
829,650
rudranil723/mini-main
admin_list.py
pagination
pagination
Generate the series of links to the pages in a paginated list.
[ "Generate", "the", "series", "of", "links", "to", "the", "pages", "in", "a", "paginated", "list." ]
def pagination(cl): (paginator, page_num) = (cl.paginator, cl.page_num) pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page if not pagination_required: page_range = [] else: ON_EACH_SIDE = 3 ON_ENDS = 2 if paginator.num_pages <= 10: ...
['def', 'pagination(cl):', '(paginator,', 'page_num)', '=', '(cl.paginator,', 'cl.page_num)', 'pagination_required', '=', '(not', 'cl.show_all', 'or', 'not', 'cl.can_show_all)', 'and', 'cl.multi_page', 'if', 'not', 'pagination_required:', 'page_range', '=', '[]', 'else:', 'ON_EACH_SIDE', '=', '3', 'ON_ENDS', '=', '2', ...
314,844
NetManAIOps/OmniAnomaly
vae.py
VAE.x_group_ndims
x_group_ndims
Get the `group_ndims` for `x`.
[ "Get", "the", "`group_ndims`", "for", "`x`." ]
def x_group_ndims(self): return self._x_group_ndims
['def', 'x_group_ndims(self):', 'return', 'self._x_group_ndims']
250,274
mragungsetiaji/nlp
yesno.py
OpinionClassifier.infer
infer
Infers with the trained models.
[ "Infers", "with", "the", "trained", "models." ]
def infer(self): cls = self.network() return cls
['def', 'infer(self):', 'cls', '=', 'self.network()', 'return', 'cls']
808,669
caiiiac/Machine-Learning-with-Python
dates.py
hours
hours
Return hours as days.
[ "Return", "hours", "as", "days." ]
def hours(h): return h / HOURS_PER_DAY
['def', 'hours(h):', 'return', 'h', '/', 'HOURS_PER_DAY']
715,419
Ixiaohuihuihui/AO2-DETR
orconv.py
ORConv2d.reset_parameters
reset_parameters
Reset the parameters of ORConv2d.
[ "Reset", "the", "parameters", "of", "ORConv2d." ]
def reset_parameters(self): n = self.in_channels * self.nOrientation for k in self.kernel_size: n *= k self.weight.data.normal_(0, math.sqrt(2.0 / n)) if self.bias is not None: self.bias.data.zero_()
['def', 'reset_parameters(self):', 'n', '=', 'self.in_channels', '*', 'self.nOrientation', 'for', 'k', 'in', 'self.kernel_size:', 'n', '*=', 'k', 'self.weight.data.normal_(0,', 'math.sqrt(2.0', '/', 'n))', 'if', 'self.bias', 'is', 'not', 'None:', 'self.bias.data.zero_()']
401,607
neuroailab/unsup_vvs
optimizer.py
ClipOptimizerSelf.compute_gradients
compute_gradients
Compute gradients to model variables from loss.
[ "Compute", "gradients", "to", "model", "variables", "from", "loss." ]
def compute_gradients(self, loss, var_list=None, *args, **kwargs): if var_list is None: var_list = tf.trainable_variables() if self.trainable_scope is not None: new_var_list = [v for v in var_list if any([nm in v.name for nm in self.trainable_scope])] if len(new_var_list): va...
['def', 'compute_gradients(self,', 'loss,', 'var_list=None,', '*args,', '**kwargs):', 'if', 'var_list', 'is', 'None:', 'var_list', '=', 'tf.trainable_variables()', 'if', 'self.trainable_scope', 'is', 'not', 'None:', 'new_var_list', '=', '[v', 'for', 'v', 'in', 'var_list', 'if', 'any([nm', 'in', 'v.name', 'for', 'nm', '...
438,382
suarez12138/AI-Reversi_IMP_TextDichotomy
animation.py
MovieWriter.cleanup
cleanup
Clean-up and collect the process used to write the movie file.
[ "Clean-up", "and", "collect", "the", "process", "used", "to", "write", "the", "movie", "file." ]
def cleanup(self): (out, err) = self._proc.communicate() self._frame_sink().close() out = TextIOWrapper(BytesIO(out)).read() err = TextIOWrapper(BytesIO(err)).read() if out: _log.log(logging.WARNING if self._proc.returncode else logging.DEBUG, 'MovieWriter stdout:\n%s', out) if err: ...
['def', 'cleanup(self):', '(out,', 'err)', '=', 'self._proc.communicate()', 'self._frame_sink().close()', 'out', '=', 'TextIOWrapper(BytesIO(out)).read()', 'err', '=', 'TextIOWrapper(BytesIO(err)).read()', 'if', 'out:', '_log.log(logging.WARNING', 'if', 'self._proc.returncode', 'else', 'logging.DEBUG,', "'MovieWriter",...
96,039
matsu0228/nlp-jp
named_commands.py
beginning_of_history
beginning_of_history
Move to the first line in the history.
[ "Move", "to", "the", "first", "line", "in", "the", "history." ]
def beginning_of_history(event): event.current_buffer.go_to_history(0)
['def', 'beginning_of_history(event):', 'event.current_buffer.go_to_history(0)']
804,458
triaquae/triaquae
_winapi.py
format_system_message
format_system_message
Call FormatMessage with a system error number to retrieve the descriptive error message.
[ "Call", "FormatMessage", "with", "a", "system", "error", "number", "to", "retrieve", "the", "descriptive", "error", "message." ]
def format_system_message(errno): ALLOCATE_BUFFER = 256 ARGUMENT_ARRAY = 8192 FROM_HMODULE = 2048 FROM_STRING = 1024 FROM_SYSTEM = 4096 IGNORE_INSERTS = 512 flags = ALLOCATE_BUFFER | FROM_SYSTEM source = None message_id = errno language_id = 0 result_buffer = ctypes.wintypes....
['def', 'format_system_message(errno):', 'ALLOCATE_BUFFER', '=', '256', 'ARGUMENT_ARRAY', '=', '8192', 'FROM_HMODULE', '=', '2048', 'FROM_STRING', '=', '1024', 'FROM_SYSTEM', '=', '4096', 'IGNORE_INSERTS', '=', '512', 'flags', '=', 'ALLOCATE_BUFFER', '|', 'FROM_SYSTEM', 'source', '=', 'None', 'message_id', '=', 'errno'...
356,481
triaquae/triaquae
fallback.py
FallbackTest.stored_messages_count
stored_messages_count
Return the storage totals from both cookie and session backends.
[ "Return", "the", "storage", "totals", "from", "both", "cookie", "and", "session", "backends." ]
def stored_messages_count(self, storage, response): total = self.stored_cookie_messages_count(storage, response) + self.stored_session_messages_count(storage, response) return total
['def', 'stored_messages_count(self,', 'storage,', 'response):', 'total', '=', 'self.stored_cookie_messages_count(storage,', 'response)', '+', 'self.stored_session_messages_count(storage,', 'response)', 'return', 'total']
358,137
naver/oasis
main_adapt.py
SolverOps.load_model
load_model
Method to load a pre-trained model.
[ "Method", "to", "load", "a", "pre-trained", "model." ]
def load_model(self, vanilla_load=False): if 'pseudo-labels' not in self.args.adapt_mode: for param in self.model.parameters(): param.requires_grad = False if 'pseudo-labels' in self.args.adapt_mode and self.args.adapt_only_classifier: for child in self.model.children(): ...
['def', 'load_model(self,', 'vanilla_load=False):', 'if', "'pseudo-labels'", 'not', 'in', 'self.args.adapt_mode:', 'for', 'param', 'in', 'self.model.parameters():', 'param.requires_grad', '=', 'False', 'if', "'pseudo-labels'", 'in', 'self.args.adapt_mode', 'and', 'self.args.adapt_only_classifier:', 'for', 'child', 'in'...
725,141
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjrContextWrapper.shadowFBO
shadowFBO
shadow map framebuffer object.
[ "shadow", "map", "framebuffer", "object." ]
def shadowFBO(self): return self._ptr.contents.shadowFBO
['def', 'shadowFBO(self):', 'return', 'self._ptr.contents.shadowFBO']
440,639
intel/neural-compressor
tf2onnx_utils.py
get_tensorflow_node_attr
get_tensorflow_node_attr
Parse tensorflow node attribute.
[ "Parse", "tensorflow", "node", "attribute." ]
def get_tensorflow_node_attr(node, name): return node.get_attr(name)
['def', 'get_tensorflow_node_attr(node,', 'name):', 'return', 'node.get_attr(name)']
737,739
sktime/sktime
test_all_estimators.py
TestAllEstimators.test_dl_constructor_initializes_deeply
test_dl_constructor_initializes_deeply
Test DL estimators that they pass custom parameters to underlying Network.
[ "Test", "DL", "estimators", "that", "they", "pass", "custom", "parameters", "to", "underlying", "Network." ]
def test_dl_constructor_initializes_deeply(self, estimator_class): estimator = estimator_class if not issubclass(estimator, (BaseDeepClassifier, BaseDeepRegressor)): return None if not hasattr(estimator, 'get_test_params'): return None params = estimator.get_test_params() if isinstan...
['def', 'test_dl_constructor_initializes_deeply(self,', 'estimator_class):', 'estimator', '=', 'estimator_class', 'if', 'not', 'issubclass(estimator,', '(BaseDeepClassifier,', 'BaseDeepRegressor)):', 'return', 'None', 'if', 'not', 'hasattr(estimator,', "'get_test_params'):", 'return', 'None', 'params', '=', 'estimator....
877,626
boris-kz/CogAlg
utils.py
is_close
is_close
Recursively check equality of two objects containing floats.
[ "Recursively", "check", "equality", "of", "two", "objects", "containing", "floats." ]
def is_close(x1, x2): if isinstance(x1, numbers.Number) and isinstance(x2, numbers.Number): return np.isclose(x1, x2) elif isinstance(x1, np.ndarray) and isinstance(x2, np.ndarray): try: return np.allclose(x1, x2) except ValueError as error_message: print(f'\nWarn...
['def', 'is_close(x1,', 'x2):', 'if', 'isinstance(x1,', 'numbers.Number)', 'and', 'isinstance(x2,', 'numbers.Number):', 'return', 'np.isclose(x1,', 'x2)', 'elif', 'isinstance(x1,', 'np.ndarray)', 'and', 'isinstance(x2,', 'np.ndarray):', 'try:', 'return', 'np.allclose(x1,', 'x2)', 'except', 'ValueError', 'as', 'error_me...
495,892
myothida/Supervised-Machine-Learning
test_peak_finding.py
TestFindPeaks.test_constant
test_constant
Test behavior for signal without local maxima.
[ "Test", "behavior", "for", "signal", "without", "local", "maxima." ]
def test_constant(self): open_interval = (None, None) (peaks, props) = find_peaks(np.ones(10), height=open_interval, threshold=open_interval, prominence=open_interval, width=open_interval) assert_(peaks.size == 0) for key in self.property_keys: assert_(props[key].size == 0)
['def', 'test_constant(self):', 'open_interval', '=', '(None,', 'None)', '(peaks,', 'props)', '=', 'find_peaks(np.ones(10),', 'height=open_interval,', 'threshold=open_interval,', 'prominence=open_interval,', 'width=open_interval)', 'assert_(peaks.size', '==', '0)', 'for', 'key', 'in', 'self.property_keys:', 'assert_(pr...
446,236
tobegit3hub/deep_image_model
ops.py
IndexedSlices.values
values
A `Tensor` containing the values of the slices.
[ "A", "`Tensor`", "containing", "the", "values", "of", "the", "slices." ]
def values(self): return self._values
['def', 'values(self):', 'return', 'self._values']
182,561
airbus/scikit-decide
scheduling_domains.py
SchedulingDomain.update_progress_uncertain
update_progress_uncertain
In an uncertain scheduling environment, update the progress of all ongoing tasks in the state.
[ "In", "an", "uncertain", "scheduling", "environment,", "update", "the", "progress", "of", "all", "ongoing", "tasks", "in", "the", "state." ]
def update_progress_uncertain(self, states: DiscreteDistribution[State]): next_states = DiscreteDistribution([(state, prob) for (state, prob) in states.get_values()]) for (next_state, _) in next_states.get_values(): for task_id in next_state.tasks_ongoing: next_state.tasks_progress[task_id] ...
['def', 'update_progress_uncertain(self,', 'states:', 'DiscreteDistribution[State]):', 'next_states', '=', 'DiscreteDistribution([(state,', 'prob)', 'for', '(state,', 'prob)', 'in', 'states.get_values()])', 'for', '(next_state,', '_)', 'in', 'next_states.get_values():', 'for', 'task_id', 'in', 'next_state.tasks_ongoing...
847,858
enuguru/artificial_intelligence_and_machine_learning
mcore.py
Matcher.is_active
is_active
Returns True if this matcher is still "active", that is, it has not yet reached the end of the posting list.
[ "Returns", "True", "if", "this", "matcher", "is", "still", "\"active\",", "that", "is,", "it", "has", "not", "yet", "reached", "the", "end", "of", "the", "posting", "list." ]
def is_active(self): raise NotImplementedError
['def', 'is_active(self):', 'raise', 'NotImplementedError']
133,452
changdaeoh/BlackVIP
tools.py
read_json
read_json
Read json file from a path.
[ "Read", "json", "file", "from", "a", "path." ]
def read_json(fpath): with open(fpath, 'r') as f: obj = json.load(f) return obj
['def', 'read_json(fpath):', 'with', 'open(fpath,', "'r')", 'as', 'f:', 'obj', '=', 'json.load(f)', 'return', 'obj']
461,640
meidachen/STPLS3D
cindex.py
Cursor.hash
hash
Returns a hash of the cursor as an int.
[ "Returns", "a", "hash", "of", "the", "cursor", "as", "an", "int." ]
def hash(self): if not hasattr(self, '_hash'): self._hash = conf.lib.clang_hashCursor(self) return self._hash
['def', 'hash(self):', 'if', 'not', 'hasattr(self,', "'_hash'):", 'self._hash', '=', 'conf.lib.clang_hashCursor(self)', 'return', 'self._hash']
909,150
Ruturaj123/Flowchart-Detection
training_ops.py
Load
Load
Load training ops library and return the loaded module.
[ "Load", "training", "ops", "library", "and", "return", "the", "loaded", "module." ]
def Load(): with _ops_lock: global _training_ops if not _training_ops: ops_path = resource_loader.get_path_to_datafile(TRAINING_OPS_FILE) logging.info('data path: %s', ops_path) _training_ops = loader.load_op_library(ops_path) assert _training_ops, 'Co...
['def', 'Load():', 'with', '_ops_lock:', 'global', '_training_ops', 'if', 'not', '_training_ops:', 'ops_path', '=', 'resource_loader.get_path_to_datafile(TRAINING_OPS_FILE)', "logging.info('data", 'path:', "%s',", 'ops_path)', '_training_ops', '=', 'loader.load_op_library(ops_path)', 'assert', '_training_ops,', "'Could...
604,583
xudejing/video-clip-order-prediction
ucf101.py
gen_ucf101_vcop_splits
gen_ucf101_vcop_splits
Generate split files for different configs.
[ "Generate", "split", "files", "for", "different", "configs." ]
def gen_ucf101_vcop_splits(root_dir, clip_len, interval, tuple_len): vcop_train_split_name = 'vcop_train_{}_{}_{}.txt'.format(clip_len, interval, tuple_len) vcop_train_split_path = os.path.join(root_dir, 'split', vcop_train_split_name) vcop_test_split_name = 'vcop_test_{}_{}_{}.txt'.format(clip_len, interva...
['def', 'gen_ucf101_vcop_splits(root_dir,', 'clip_len,', 'interval,', 'tuple_len):', 'vcop_train_split_name', '=', "'vcop_train_{}_{}_{}.txt'.format(clip_len,", 'interval,', 'tuple_len)', 'vcop_train_split_path', '=', 'os.path.join(root_dir,', "'split',", 'vcop_train_split_name)', 'vcop_test_split_name', '=', "'vcop_te...
379,811
google-research/scenic
common.py
cpu_matcher
cpu_matcher
Wraps matching function to be usable within jitted functions.
[ "Wraps", "matching", "function", "to", "be", "usable", "within", "jitted", "functions." ]
def cpu_matcher(matching_fn): def slice_and_match(args): (cost, ncol) = args return slicer(cost, ncol, matching_fn) @jax.custom_vjp def matching_fn_hcb(cost, n_cols=None): (*b, n, m) = cost.shape return jax.pure_callback(slice_and_match, jax.ShapeDtypeStruct(b + [2, min(n, ...
['def', 'cpu_matcher(matching_fn):', 'def', 'slice_and_match(args):', '(cost,', 'ncol)', '=', 'args', 'return', 'slicer(cost,', 'ncol,', 'matching_fn)', '@jax.custom_vjp', 'def', 'matching_fn_hcb(cost,', 'n_cols=None):', '(*b,', 'n,', 'm)', '=', 'cost.shape', 'return', 'jax.pure_callback(slice_and_match,', 'jax.ShapeDt...
846,283
matthewearl/deep-anpr
model.py
convolutional_layers
convolutional_layers
Get the convolutional layers of the model.
[ "Get", "the", "convolutional", "layers", "of", "the", "model." ]
def convolutional_layers(): x = tf.placeholder(tf.float32, [None, None, None]) W_conv1 = weight_variable([5, 5, 1, 48]) b_conv1 = bias_variable([48]) x_expanded = tf.expand_dims(x, 3) h_conv1 = tf.nn.relu(conv2d(x_expanded, W_conv1) + b_conv1) h_pool1 = max_pool(h_conv1, ksize=(2, 2), stride=(2,...
['def', 'convolutional_layers():', 'x', '=', 'tf.placeholder(tf.float32,', '[None,', 'None,', 'None])', 'W_conv1', '=', 'weight_variable([5,', '5,', '1,', '48])', 'b_conv1', '=', 'bias_variable([48])', 'x_expanded', '=', 'tf.expand_dims(x,', '3)', 'h_conv1', '=', 'tf.nn.relu(conv2d(x_expanded,', 'W_conv1)', '+', 'b_con...
516,868
AboudyKreidieh/h-baselines
train.py
create_sac_parser
create_sac_parser
Add the SAC hyperparameters to the parser.
[ "Add", "the", "SAC", "hyperparameters", "to", "the", "parser." ]
def create_sac_parser(parser): parser.add_argument('--buffer_size', type=int, default=SAC_PARAMS['buffer_size'], help='the max number of transitions to store') parser.add_argument('--batch_size', type=int, default=SAC_PARAMS['batch_size'], help='the size of the batch for learning the policy') parser.add_arg...
['def', 'create_sac_parser(parser):', "parser.add_argument('--buffer_size',", 'type=int,', "default=SAC_PARAMS['buffer_size'],", "help='the", 'max', 'number', 'of', 'transitions', 'to', "store')", "parser.add_argument('--batch_size',", 'type=int,', "default=SAC_PARAMS['batch_size'],", "help='the", 'size', 'of', 'the', ...
574,016
YanZiQinKevin/object_detection
c2.py
CudaScope
CudaScope
Create a CUDA device scope for GPU device `gpu_id`.
[ "Create", "a", "CUDA", "device", "scope", "for", "GPU", "device", "`gpu_id`." ]
def CudaScope(gpu_id): gpu_dev = CudaDevice(gpu_id) with core.DeviceScope(gpu_dev): yield
['def', 'CudaScope(gpu_id):', 'gpu_dev', '=', 'CudaDevice(gpu_id)', 'with', 'core.DeviceScope(gpu_dev):', 'yield']
773,236
facebookresearch/CompilerGym
llvm_random_actions_fuzz_test.py
test_fuzz
test_fuzz
Run randomly selected actions on a benchmark until a minimum amount of time has elapsed.
[ "Run", "randomly", "selected", "actions", "on", "a", "benchmark", "until", "a", "minimum", "amount", "of", "time", "has", "elapsed." ]
def test_fuzz(observation_space: str, reward_space: str): with gym.make('llvm-v0', reward_space=reward_space, observation_space=observation_space) as env: benchmark = env.datasets['generator://llvm-stress-v0'].random_benchmark() print(benchmark.uri) env.reset(benchmark=benchmark) end...
['def', 'test_fuzz(observation_space:', 'str,', 'reward_space:', 'str):', 'with', "gym.make('llvm-v0',", 'reward_space=reward_space,', 'observation_space=observation_space)', 'as', 'env:', 'benchmark', '=', "env.datasets['generator://llvm-stress-v0'].random_benchmark()", 'print(benchmark.uri)', 'env.reset(benchmark=ben...
135,796
deepmind/acme
atari.py
DeepIMPALAAtariNetwork.unroll
unroll
Efficient unroll that applies embeddings, MLP, & convnet in one pass.
[ "Efficient", "unroll", "that", "applies", "embeddings,", "MLP,", "&", "convnet", "in", "one", "pass." ]
def unroll(self, inputs: observation_action_reward.OAR, state: hk.LSTMState) -> Any: embeddings = self._embed(inputs) (embeddings, new_states) = hk.static_unroll(self._core, embeddings, state) (logits, values) = self._head(embeddings) return ((logits, values), new_states)
['def', 'unroll(self,', 'inputs:', 'observation_action_reward.OAR,', 'state:', 'hk.LSTMState)', '->', 'Any:', 'embeddings', '=', 'self._embed(inputs)', '(embeddings,', 'new_states)', '=', 'hk.static_unroll(self._core,', 'embeddings,', 'state)', '(logits,', 'values)', '=', 'self._head(embeddings)', 'return', '((logits,'...
7,831
flyteorg/flytelab
workflow.py
encode_datetime
encode_datetime
One-hot encode datetime into features.
[ "One-hot", "encode", "datetime", "into", "features." ]
def encode_datetime(dt: datetime): dt = pd.Timestamp(dt) return np.array([*onehot_encode(dt.hour, 24), *onehot_encode(dt.day_of_week, 7), *onehot_encode(dt.day, 31), *onehot_encode(dt.day_of_year, 356), *onehot_encode(dt.month, 12), minmax_scaler(dt.year, 1900, 2500)])
['def', 'encode_datetime(dt:', 'datetime):', 'dt', '=', 'pd.Timestamp(dt)', 'return', 'np.array([*onehot_encode(dt.hour,', '24),', '*onehot_encode(dt.day_of_week,', '7),', '*onehot_encode(dt.day,', '31),', '*onehot_encode(dt.day_of_year,', '356),', '*onehot_encode(dt.month,', '12),', 'minmax_scaler(dt.year,', '1900,', ...
606,992
flavioschneider/rl-transfer-
test_ppo.py
TestPPOPendulumGRU.test_ppo_pendulum_gru
test_ppo_pendulum_gru
Test PPO with Pendulum environment and recurrent policy.
[ "Test", "PPO", "with", "Pendulum", "environment", "and", "recurrent", "policy." ]
def test_ppo_pendulum_gru(self): with TFTrainer(snapshot_config) as trainer: env = normalize(GymEnv('InvertedDoublePendulum-v2', max_episode_length=100)) gru_policy = GaussianGRUPolicy(env_spec=env.spec) baseline = GaussianMLPBaseline(env_spec=env.spec, hidden_sizes=(32, 32)) sampler...
['def', 'test_ppo_pendulum_gru(self):', 'with', 'TFTrainer(snapshot_config)', 'as', 'trainer:', 'env', '=', "normalize(GymEnv('InvertedDoublePendulum-v2',", 'max_episode_length=100))', 'gru_policy', '=', 'GaussianGRUPolicy(env_spec=env.spec)', 'baseline', '=', 'GaussianMLPBaseline(env_spec=env.spec,', 'hidden_sizes=(32...
861,758
danamyu/hedgehog_detector
utils.py
init_linear
init_linear
Linear (affine) transformation, y = x W + b, for a variety of configurations.
[ "Linear", "(affine)", "transformation,", "y", "=", "x", "W", "+", "b,", "for", "a", "variety", "of", "configurations." ]
def init_linear(in_size, out_size, do_bias=True, mat_init_value=None, bias_init_value=None, alpha=1.0, identity_if_possible=False, normalized=False, name=None, collections=None): if mat_init_value is not None and mat_init_value.shape != (in_size, out_size): raise ValueError('Provided mat_init_value must hav...
['def', 'init_linear(in_size,', 'out_size,', 'do_bias=True,', 'mat_init_value=None,', 'bias_init_value=None,', 'alpha=1.0,', 'identity_if_possible=False,', 'normalized=False,', 'name=None,', 'collections=None):', 'if', 'mat_init_value', 'is', 'not', 'None', 'and', 'mat_init_value.shape', '!=', '(in_size,', 'out_size):'...
589,838
TrellixVulnTeam/Unsupervised_Learning_HFI7
target_python.py
TargetPython.format_given
format_given
Format the given, non-None attributes for display.
[ "Format", "the", "given,", "non-None", "attributes", "for", "display." ]
def format_given(self): display_version = None if self._given_py_version_info is not None: display_version = '.'.join((str(part) for part in self._given_py_version_info)) key_values = [('platforms', self.platforms), ('version_info', display_version), ('abis', self.abis), ('implementation', self.impl...
['def', 'format_given(self):', 'display_version', '=', 'None', 'if', 'self._given_py_version_info', 'is', 'not', 'None:', 'display_version', '=', "'.'.join((str(part)", 'for', 'part', 'in', 'self._given_py_version_info))', 'key_values', '=', "[('platforms',", 'self.platforms),', "('version_info',", 'display_version),',...
454,236
matsu0228/nlp-jp
ticker.py
Locator.view_limits
view_limits
select a scale for the range from vmin to vmax Normally this method is overridden by subclasses to change locator behaviour.
[ "select", "a", "scale", "for", "the", "range", "from", "vmin", "to", "vmax", "Normally", "this", "method", "is", "overridden", "by", "subclasses", "to", "change", "locator", "behaviour." ]
def view_limits(self, vmin, vmax): return mtransforms.nonsingular(vmin, vmax)
['def', 'view_limits(self,', 'vmin,', 'vmax):', 'return', 'mtransforms.nonsingular(vmin,', 'vmax)']
789,347
AboudyKreidieh/h-baselines
test_envs.py
TestPendulum.test_reset
test_reset
Ensure the state initialization is within the expected range.
[ "Ensure", "the", "state", "initialization", "is", "within", "the", "expected", "range." ]
def test_reset(self): state = self.env.reset() num_obj = len(state) // 3 for i in range(num_obj): self.assertTrue(np.arccos(state[i]) >= self.env.initial_state_space[i][0]) self.assertTrue(np.arccos(state[i]) <= self.env.initial_state_space[i][1]) self.assertTrue(state[i + 2 * num_ob...
['def', 'test_reset(self):', 'state', '=', 'self.env.reset()', 'num_obj', '=', 'len(state)', '//', '3', 'for', 'i', 'in', 'range(num_obj):', 'self.assertTrue(np.arccos(state[i])', '>=', 'self.env.initial_state_space[i][0])', 'self.assertTrue(np.arccos(state[i])', '<=', 'self.env.initial_state_space[i][1])', 'self.asser...
574,056
tencent-ailab/TriNet
metrics.py
reset_meter
reset_meter
Reset Meter instance aggregated under a given *name* and *key*.
[ "Reset", "Meter", "instance", "aggregated", "under", "a", "given", "*name*", "and", "*key*." ]
def reset_meter(name: str, key: str) -> None: meter = get_meter(name, key) if meter is not None: meter.reset()
['def', 'reset_meter(name:', 'str,', 'key:', 'str)', '->', 'None:', 'meter', '=', 'get_meter(name,', 'key)', 'if', 'meter', 'is', 'not', 'None:', 'meter.reset()']
425,276
ilya16/MultINN
multinn_core.py
MultINNCore.encoders
encoders
The list of the MultINN Encoders.
[ "The", "list", "of", "the", "MultINN", "Encoders." ]
def encoders(self): return self._encoders
['def', 'encoders(self):', 'return', 'self._encoders']
644,325
zihuitang/medical_AI_platform
test_funcattrs.py
empty_cell
empty_cell
Create an empty cell.
[ "Create", "an", "empty", "cell." ]
def empty_cell(empty=True): def f(): print(a) if not empty: a = 1729 return f.__closure__[0]
['def', 'empty_cell(empty=True):', 'def', 'f():', 'print(a)', 'if', 'not', 'empty:', 'a', '=', '1729', 'return', 'f.__closure__[0]']
283,384
KalleHallden/InstaAutomator
ffmpeg_tools.py
ffmpeg_merge_video_audio
ffmpeg_merge_video_audio
merges video file ``video`` and audio file ``audio`` into one movie file ``output``.
[ "merges", "video", "file", "``video``", "and", "audio", "file", "``audio``", "into", "one", "movie", "file", "``output``." ]
def ffmpeg_merge_video_audio(video, audio, output, vcodec='copy', acodec='copy', ffmpeg_output=False, verbose=True): cmd = [get_setting('FFMPEG_BINARY'), '-y', '-i', audio, '-i', video, '-vcodec', vcodec, '-acodec', acodec, output] subprocess_call(cmd, verbose=verbose)
['def', 'ffmpeg_merge_video_audio(video,', 'audio,', 'output,', "vcodec='copy',", "acodec='copy',", 'ffmpeg_output=False,', 'verbose=True):', 'cmd', '=', "[get_setting('FFMPEG_BINARY'),", "'-y',", "'-i',", 'audio,', "'-i',", 'video,', "'-vcodec',", 'vcodec,', "'-acodec',", 'acodec,', 'output]', 'subprocess_call(cmd,', ...
230,437
melfm/avod-ssd
anchor_encoder.py
offset_to_anchor
offset_to_anchor
Decodes the anchor regression predictions with the anchor.
[ "Decodes", "the", "anchor", "regression", "predictions", "with", "the", "anchor." ]
def offset_to_anchor(anchors, offsets): fc.check_anchor_format(anchors) fc.check_anchor_format(offsets) x_pred = offsets[:, 0] * anchors[:, 3] + anchors[:, 0] y_pred = offsets[:, 1] * anchors[:, 4] + anchors[:, 1] z_pred = offsets[:, 2] * anchors[:, 5] + anchors[:, 2] tensor_format = isinstance(...
['def', 'offset_to_anchor(anchors,', 'offsets):', 'fc.check_anchor_format(anchors)', 'fc.check_anchor_format(offsets)', 'x_pred', '=', 'offsets[:,', '0]', '*', 'anchors[:,', '3]', '+', 'anchors[:,', '0]', 'y_pred', '=', 'offsets[:,', '1]', '*', 'anchors[:,', '4]', '+', 'anchors[:,', '1]', 'z_pred', '=', 'offsets[:,', '...
420,834
microsoft/nlp-recipes
extractive_summarization.py
get_pred
get_pred
Get the summarization prediction for the paragraph example based on the scores returned by the transformer summarization model.
[ "Get", "the", "summarization", "prediction", "for", "the", "paragraph", "example", "based", "on", "the", "scores", "returned", "by", "the", "transformer", "summarization", "model." ]
def get_pred(example, sent_scores, cal_lead=False, sentence_separator='<q>', block_trigram=True, top_n=3): def _get_ngrams(n, text): ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_start + 1): ngram_set.add...
['def', 'get_pred(example,', 'sent_scores,', 'cal_lead=False,', "sentence_separator='<q>',", 'block_trigram=True,', 'top_n=3):', 'def', '_get_ngrams(n,', 'text):', 'ngram_set', '=', 'set()', 'text_length', '=', 'len(text)', 'max_index_ngram_start', '=', 'text_length', '-', 'n', 'for', 'i', 'in', 'range(max_index_ngram_...
731,299
ldamewood/renormalization
graph.py
Graph.edgeWeights
edgeWeights
Edge generator (no repeats).
[ "Edge", "generator", "(no", "repeats)." ]
def edgeWeights(self): for (key, value) in self._edges: yield (key, value)
['def', 'edgeWeights(self):', 'for', '(key,', 'value)', 'in', 'self._edges:', 'yield', '(key,', 'value)']
840,213
SamuelScheit/carcassonne-ai
muzero.py
MuZero.logging_loop
logging_loop
Keep track of the training performance.
[ "Keep", "track", "of", "the", "training", "performance." ]
def logging_loop(self, num_gpus): self.test_worker = self_play.SelfPlay.options(num_cpus=0, num_gpus=num_gpus).remote(self.checkpoint, self.Game, self.config, self.config.seed + self.config.num_workers) self.test_worker.continuous_self_play.remote(self.shared_storage_worker, None, True) writer = SummaryWrit...
['def', 'logging_loop(self,', 'num_gpus):', 'self.test_worker', '=', 'self_play.SelfPlay.options(num_cpus=0,', 'num_gpus=num_gpus).remote(self.checkpoint,', 'self.Game,', 'self.config,', 'self.config.seed', '+', 'self.config.num_workers)', 'self.test_worker.continuous_self_play.remote(self.shared_storage_worker,', 'Non...
109,093
matsu0228/nlp-jp
egg_info.py
FileList.recursive_exclude
recursive_exclude
Exclude any file anywhere in 'dir/' that match the pattern.
[ "Exclude", "any", "file", "anywhere", "in", "'dir/'", "that", "match", "the", "pattern." ]
def recursive_exclude(self, dir, pattern): match = translate_pattern(os.path.join(dir, '**', pattern)) return self._remove_files(match.match)
['def', 'recursive_exclude(self,', 'dir,', 'pattern):', 'match', '=', 'translate_pattern(os.path.join(dir,', "'**',", 'pattern))', 'return', 'self._remove_files(match.match)']
806,246
facebookresearch/CompilerGym
env_without_bazel_test.py
test_observation_before_reset
test_observation_before_reset
Taking an observation before reset() is illegal.
[ "Taking", "an", "observation", "before", "reset()", "is", "illegal." ]
def test_observation_before_reset(env: CompilerEnv): with pytest.raises(SessionNotFound, match='Must call reset\\(\\) before step\\(\\)'): _ = env.observation['ir']
['def', 'test_observation_before_reset(env:', 'CompilerEnv):', 'with', 'pytest.raises(SessionNotFound,', "match='Must", 'call', 'reset\\\\(\\\\)', 'before', "step\\\\(\\\\)'):", '_', '=', "env.observation['ir']"]
135,726
bnpy/bnpy
TestHDPHMM_ParallelBenchmark.py
Test.shutdownWorkers
shutdownWorkers
Shut down all worker processes.
[ "Shut", "down", "all", "worker", "processes." ]
def shutdownWorkers(self): for workerID in range(self.nWorkers): self.JobQ.put(None)
['def', 'shutdownWorkers(self):', 'for', 'workerID', 'in', 'range(self.nWorkers):', 'self.JobQ.put(None)']
465,512
sek788432/Waymo-2D-Object-Detection
augment.py
ImageAugment.distort
distort
Given an image tensor, returns a distorted image with the same shape.
[ "Given", "an", "image", "tensor,", "returns", "a", "distorted", "image", "with", "the", "same", "shape." ]
def distort(self, image: tf.Tensor) -> tf.Tensor: raise NotImplementedError()
['def', 'distort(self,', 'image:', 'tf.Tensor)', '->', 'tf.Tensor:', 'raise', 'NotImplementedError()']
973,229
TerenceCYJ/S2HAND
utils.py
efficientnet_params
efficientnet_params
Map EfficientNet model name to parameter coefficients.
[ "Map", "EfficientNet", "model", "name", "to", "parameter", "coefficients." ]
def efficientnet_params(model_name): params_dict = {'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 'efficientnet-b6':...
['def', 'efficientnet_params(model_name):', 'params_dict', '=', "{'efficientnet-b0':", '(1.0,', '1.0,', '224,', '0.2),', "'efficientnet-b1':", '(1.0,', '1.1,', '240,', '0.2),', "'efficientnet-b2':", '(1.1,', '1.2,', '260,', '0.3),', "'efficientnet-b3':", '(1.2,', '1.4,', '300,', '0.3),', "'efficientnet-b4':", '(1.4,', ...
327,278
ibarrien/SemiSupervisedLearning
expectation_maximization.py
EM_SSL.only_labeled_test_acc
only_labeled_test_acc
Test accuracy using only labeled data.
[ "Test", "accuracy", "using", "only", "labeled", "data." ]
def only_labeled_test_acc(self) -> float: return self.test_accuracy_hist[0]
['def', 'only_labeled_test_acc(self)', '->', 'float:', 'return', 'self.test_accuracy_hist[0]']
343,759
microsoft/InnerEye-DeepLearning
test_dataloader_speed.py
test_dataloader_speed
test_dataloader_speed
Test how dataloaders work when using multiple processes.
[ "Test", "how", "dataloaders", "work", "when", "using", "multiple", "processes." ]
def test_dataloader_speed(test_output_dirs: OutputFolderForTests, num_dataload_workers: int, shuffle: bool) -> None: ml_util.set_random_seed(0) csv_string = StringIO('subject,channel,path,value,scalar1\nS1,image,4be9beed-5861-fdd2-72c2-8dd89aadc1ef\nS1,label,,True,1.0\nS2,image,6ceacaf8-abd2-ffec-2ade-d52afd6dd...
['def', 'test_dataloader_speed(test_output_dirs:', 'OutputFolderForTests,', 'num_dataload_workers:', 'int,', 'shuffle:', 'bool)', '->', 'None:', 'ml_util.set_random_seed(0)', 'csv_string', '=', "StringIO('subject,channel,path,value,scalar1\\nS1,image,4be9beed-5861-fdd2-72c2-8dd89aadc1ef\\nS1,label,,True,1.0\\nS2,image,...
613,652
RasaHQ/rasa_core
model.py
merge_model
merge_model
Merges two model directories.
[ "Merges", "two", "model", "directories." ]
def merge_model(source: Text, target: Text) -> bool: try: shutil.move(source, target) return True except Exception as e: logging.debug(e) return False
['def', 'merge_model(source:', 'Text,', 'target:', 'Text)', '->', 'bool:', 'try:', 'shutil.move(source,', 'target)', 'return', 'True', 'except', 'Exception', 'as', 'e:', 'logging.debug(e)', 'return', 'False']
838,138
0xangelo/raylab
policy.py
MBPolicyMixin.build_timers
build_timers
Create timers for model and policy training.
[ "Create", "timers", "for", "model", "and", "policy", "training." ]
def build_timers(self): self.timers = {'model': TimerStat(), 'policy': TimerStat()} self._info = {}
['def', 'build_timers(self):', 'self.timers', '=', "{'model':", 'TimerStat(),', "'policy':", 'TimerStat()}', 'self._info', '=', '{}']
848,358
FeliMe/feature-autoencoder
datasets.py
get_mood_val_test_files
get_mood_val_test_files
Get MOOD validation and test files.
[ "Get", "MOOD", "validation", "and", "test", "files." ]
def get_mood_val_test_files(path: str=MOODROOT, **kwargs) -> Tuple[List[str], List[str]]: test_files = glob(os.path.join(path, 'brain/test_raw/*.nii.gz')) assert len(test_files) > 0, 'No files found in MOOD' return (test_files, None)
['def', 'get_mood_val_test_files(path:', 'str=MOODROOT,', '**kwargs)', '->', 'Tuple[List[str],', 'List[str]]:', 'test_files', '=', 'glob(os.path.join(path,', "'brain/test_raw/*.nii.gz'))", 'assert', 'len(test_files)', '>', '0,', "'No", 'files', 'found', 'in', "MOOD'", 'return', '(test_files,', 'None)']
544,702
deepmind/dm_control
runtime.py
Runtime.restart
restart
Restarts the episode, resetting environment, model, and data.
[ "Restarts", "the", "episode,", "resetting", "environment,", "model,", "and", "data." ]
def restart(self): if self._state != State.STOPPED: self._state = State.RESTARTING else: self._state = State.START
['def', 'restart(self):', 'if', 'self._state', '!=', 'State.STOPPED:', 'self._state', '=', 'State.RESTARTING', 'else:', 'self._state', '=', 'State.START']
165,693
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
quantization.py
ParameterEncoding.decode
decode
Decode bfloat16 to float32.
[ "Decode", "bfloat16", "to", "float32." ]
def decode(self, x): raise NotImplementedError('decode not implemented')
['def', 'decode(self,', 'x):', 'raise', "NotImplementedError('decode", 'not', "implemented')"]
966,170
boris-kz/CogAlg
utils.py
draw_blob
draw_blob
Map a single blob into an image.
[ "Map", "a", "single", "blob", "into", "an", "image." ]
def draw_blob(blob, *args, blob_box=None, **kwargs): if blob_box is None: blob_box = blob.box blob_img = blank_image(blob_box) for stack in blob.stack_: sub_box = stack_box(stack) stack_map = draw_stack(stack, sub_box, blob.sign, *args, **kwargs) paint_over(blob_img, stack_ma...
['def', 'draw_blob(blob,', '*args,', 'blob_box=None,', '**kwargs):', 'if', 'blob_box', 'is', 'None:', 'blob_box', '=', 'blob.box', 'blob_img', '=', 'blank_image(blob_box)', 'for', 'stack', 'in', 'blob.stack_:', 'sub_box', '=', 'stack_box(stack)', 'stack_map', '=', 'draw_stack(stack,', 'sub_box,', 'blob.sign,', '*args,'...
495,905
asyml/texar
embedding.py
Embedding.vector_size
vector_size
The embedding dimention size.
[ "The", "embedding", "dimention", "size." ]
def vector_size(self): return self._hparams.dim
['def', 'vector_size(self):', 'return', 'self._hparams.dim']
924,487
Oneflow-Inc/vision
imagenet.py
parse_train_archive
parse_train_archive
Parse the train images archive of the ImageNet2012 classification dataset and prepare it for usage with the ImageNet dataset.
[ "Parse", "the", "train", "images", "archive", "of", "the", "ImageNet2012", "classification", "dataset", "and", "prepare", "it", "for", "usage", "with", "the", "ImageNet", "dataset." ]
def parse_train_archive(root: str, file: Optional[str]=None, folder: str='train') -> None: archive_meta = ARCHIVE_META['train'] if file is None: file = archive_meta[0] md5 = archive_meta[1] _verify_archive(root, file, md5) train_root = os.path.join(root, folder) extract_archive(os.path.j...
['def', 'parse_train_archive(root:', 'str,', 'file:', 'Optional[str]=None,', 'folder:', "str='train')", '->', 'None:', 'archive_meta', '=', "ARCHIVE_META['train']", 'if', 'file', 'is', 'None:', 'file', '=', 'archive_meta[0]', 'md5', '=', 'archive_meta[1]', '_verify_archive(root,', 'file,', 'md5)', 'train_root', '=', 'o...
958,196
rudranil723/mini-main
query.py
Query.get_count
get_count
Perform a COUNT() query using the current filter constraints.
[ "Perform", "a", "COUNT()", "query", "using", "the", "current", "filter", "constraints." ]
def get_count(self, using): obj = self.clone() obj.add_annotation(Count('*'), alias='__count', is_summary=True) number = obj.get_aggregation(using, ['__count'])['__count'] if number is None: number = 0 return number
['def', 'get_count(self,', 'using):', 'obj', '=', 'self.clone()', "obj.add_annotation(Count('*'),", "alias='__count',", 'is_summary=True)', 'number', '=', 'obj.get_aggregation(using,', "['__count'])['__count']", 'if', 'number', 'is', 'None:', 'number', '=', '0', 'return', 'number']
316,138
sarnsdev/social-alignment-data-mining
basic.py
upgrade_to_float
upgrade_to_float
Upgrade any int types to float32 or float64 to avoid losing precision.
[ "Upgrade", "any", "int", "types", "to", "float32", "or", "float64", "to", "avoid", "losing", "precision." ]
def upgrade_to_float(*types): conv = {bool: float32, int8: float32, int16: float32, int32: float64, int64: float64, uint8: float32, uint16: float32, uint32: float64, uint64: float64} return (get_scalar_type(Scalar.upcast(*[conv.get(type, type) for type in types])),)
['def', 'upgrade_to_float(*types):', 'conv', '=', '{bool:', 'float32,', 'int8:', 'float32,', 'int16:', 'float32,', 'int32:', 'float64,', 'int64:', 'float64,', 'uint8:', 'float32,', 'uint16:', 'float32,', 'uint32:', 'float64,', 'uint64:', 'float64}', 'return', '(get_scalar_type(Scalar.upcast(*[conv.get(type,', 'type)', ...
392,845
matsu0228/nlp-jp
styles.py
get_colors
get_colors
Construct the keys to be used building the base stylesheet from a templatee.
[ "Construct", "the", "keys", "to", "be", "used", "building", "the", "base", "stylesheet", "from", "a", "templatee." ]
def get_colors(stylename): style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3, 6): try: int(fgcolor, 16) except TypeError: pass else: fgcolor = '#' + fgcolor return dict(bgcolor...
['def', 'get_colors(stylename):', 'style', '=', 'get_style_by_name(stylename)', 'fgcolor', '=', "style.style_for_token(Token.Text)['color']", 'or', "''", 'if', 'len(fgcolor)', 'in', '(3,', '6):', 'try:', 'int(fgcolor,', '16)', 'except', 'TypeError:', 'pass', 'else:', 'fgcolor', '=', "'#'", '+', 'fgcolor', 'return', 'di...
805,265
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
blocks.py
ExtensionBlock.take_nd
take_nd
Take values according to indexer and return them as a block.
[ "Take", "values", "according", "to", "indexer", "and", "return", "them", "as", "a", "block." ]
def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None): if fill_tuple is None: fill_value = None else: fill_value = fill_tuple[0] new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True) assert not (self.ndim == 1 and new_mgr_locs is None) if new...
['def', 'take_nd(self,', 'indexer,', 'axis=0,', 'new_mgr_locs=None,', 'fill_tuple=None):', 'if', 'fill_tuple', 'is', 'None:', 'fill_value', '=', 'None', 'else:', 'fill_value', '=', 'fill_tuple[0]', 'new_values', '=', 'self.values.take(indexer,', 'fill_value=fill_value,', 'allow_fill=True)', 'assert', 'not', '(self.ndim...
83,029
JIA-HONG-CHU/Swin-Transformer-add-EncNet-DaNet-DraNet-for---on-Statelite-Dataset
test.py
collect_results_cpu
collect_results_cpu
Collect results with CPU.
[ "Collect", "results", "with", "CPU." ]
def collect_results_cpu(result_part, size, tmpdir=None): (rank, world_size) = get_dist_info() if tmpdir is None: MAX_LEN = 512 dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda') if rank == 0: tmpdir = tempfile.mkdtemp() tmpdir = torch.tensor...
['def', 'collect_results_cpu(result_part,', 'size,', 'tmpdir=None):', '(rank,', 'world_size)', '=', 'get_dist_info()', 'if', 'tmpdir', 'is', 'None:', 'MAX_LEN', '=', '512', 'dir_tensor', '=', 'torch.full((MAX_LEN,),', '32,', 'dtype=torch.uint8,', "device='cuda')", 'if', 'rank', '==', '0:', 'tmpdir', '=', 'tempfile.mkdt...
882,813
Media-Smart/volkscv
utils.py
get_pallete
get_pallete
Generate pallete for categories.
[ "Generate", "pallete", "for", "categories." ]
def get_pallete(categories): num_cls = len(categories) + 1 color_map = num_cls * [0, 0, 0] for i in range(0, num_cls): j = 0 lab = i while lab: color_map[i * 3] |= (lab >> 0 & 1) << 7 - j color_map[i * 3 + 1] |= (lab >> 1 & 1) << 7 - j color_map[i ...
['def', 'get_pallete(categories):', 'num_cls', '=', 'len(categories)', '+', '1', 'color_map', '=', 'num_cls', '*', '[0,', '0,', '0]', 'for', 'i', 'in', 'range(0,', 'num_cls):', 'j', '=', '0', 'lab', '=', 'i', 'while', 'lab:', 'color_map[i', '*', '3]', '|=', '(lab', '>>', '0', '&', '1)', '<<', '7', '-', 'j', 'color_map[...
946,432
tensorly/quantum
serializable_gate_set_test.py
SerializableGateSetTest.test_serialize_deserialize_op
test_serialize_deserialize_op
Simple serialize and deserialize back test.
[ "Simple", "serialize", "and", "deserialize", "back", "test." ]
def test_serialize_deserialize_op(self): q0 = cirq.GridQubit(1, 1) proto = op_proto({'gate': {'id': 'x_pow'}, 'args': {'half_turns': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_1'}]}) self.assertEqual(proto, MY_GATE_SET.serialize_op(cirq.XPowGate(exponent=0.125)(q0))) self.assertEqual(M...
['def', 'test_serialize_deserialize_op(self):', 'q0', '=', 'cirq.GridQubit(1,', '1)', 'proto', '=', "op_proto({'gate':", "{'id':", "'x_pow'},", "'args':", "{'half_turns':", "{'arg_value':", "{'float_value':", '0.125}}},', "'qubits':", "[{'id':", "'1_1'}]})", 'self.assertEqual(proto,', 'MY_GATE_SET.serialize_op(cirq.XPo...
834,954
gunthercox/ChatterBot
_native.py
escape_silent
escape_silent
Like :func:`escape` but converts `None` into an empty markup string.
[ "Like", ":func:`escape`", "but", "converts", "`None`", "into", "an", "empty", "markup", "string." ]
def escape_silent(s): if s is None: return Markup() return escape(s)
['def', 'escape_silent(s):', 'if', 's', 'is', 'None:', 'return', 'Markup()', 'return', 'escape(s)']
529,603