Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
SVD.predict | (self) |
This method computes a final rating for unknown pairs (user, item)
|
This method computes a final rating for unknown pairs (user, item) | def predict(self):
"""
This method computes a final rating for unknown pairs (user, item)
"""
if self.test_file is not None:
for user in self.test_set['users']:
for item in self.test_set['feedback'][user]:
self.predictions.append((user, item, self.predict_score(self.user_to_user_id[user],
self.item_to_item_id[item], True)))
else:
raise NotImplemented | [
"def",
"predict",
"(",
"self",
")",
":",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"for",
"user",
"in",
"self",
".",
"test_set",
"[",
"'users'",
"]",
":",
"for",
"item",
"in",
"self",
".",
"test_set",
"[",
"'feedback'",
"]",
"[",
"user",
"]",
":",
"self",
".",
"predictions",
".",
"append",
"(",
"(",
"user",
",",
"item",
",",
"self",
".",
"predict_score",
"(",
"self",
".",
"user_to_user_id",
"[",
"user",
"]",
",",
"self",
".",
"item_to_item_id",
"[",
"item",
"]",
",",
"True",
")",
")",
")",
"else",
":",
"raise",
"NotImplemented"
] | [
128,
4
] | [
140,
32
] | python | en | ['en', 'error', 'th'] | False |
SVD.compute | (self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t') |
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
|
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm | def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'):
"""
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
"""
super(SVD, self).compute(verbose=verbose)
if verbose:
self.init_model()
print("training_time:: %4f sec" % timed(self.fit))
if self.extra_info_header is not None:
print(self.extra_info_header)
print("prediction_time:: %4f sec" % timed(self.predict))
print('\n')
else:
# Execute all in silence without prints
self.init_model()
self.fit()
self.predict()
self.write_predictions()
if self.test_file is not None:
self.evaluate(metrics, verbose_evaluation, as_table=as_table, table_sep=table_sep) | [
"def",
"compute",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"metrics",
"=",
"None",
",",
"verbose_evaluation",
"=",
"True",
",",
"as_table",
"=",
"False",
",",
"table_sep",
"=",
"'\\t'",
")",
":",
"super",
"(",
"SVD",
",",
"self",
")",
".",
"compute",
"(",
"verbose",
"=",
"verbose",
")",
"if",
"verbose",
":",
"self",
".",
"init_model",
"(",
")",
"print",
"(",
"\"training_time:: %4f sec\"",
"%",
"timed",
"(",
"self",
".",
"fit",
")",
")",
"if",
"self",
".",
"extra_info_header",
"is",
"not",
"None",
":",
"print",
"(",
"self",
".",
"extra_info_header",
")",
"print",
"(",
"\"prediction_time:: %4f sec\"",
"%",
"timed",
"(",
"self",
".",
"predict",
")",
")",
"print",
"(",
"'\\n'",
")",
"else",
":",
"# Execute all in silence without prints",
"self",
".",
"init_model",
"(",
")",
"self",
".",
"fit",
"(",
")",
"self",
".",
"predict",
"(",
")",
"self",
".",
"write_predictions",
"(",
")",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"self",
".",
"evaluate",
"(",
"metrics",
",",
"verbose_evaluation",
",",
"as_table",
"=",
"as_table",
",",
"table_sep",
"=",
"table_sep",
")"
] | [
142,
4
] | [
184,
94
] | python | en | ['en', 'error', 'th'] | False |
OpenLayersWidget.map_options | (self) | Build the map options hash for the OpenLayers template. | Build the map options hash for the OpenLayers template. | def map_options(self):
"""Build the map options hash for the OpenLayers template."""
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % extent
def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % srid
# An array of the parameter name, the name of their OpenLayers
# counterpart, and the type of variable they are.
map_types = [('srid', 'projection', 'srid'),
('display_srid', 'displayProjection', 'srid'),
('units', 'units', str),
('max_resolution', 'maxResolution', float),
('max_extent', 'maxExtent', 'bounds'),
('num_zoom', 'numZoomLevels', int),
('max_zoom', 'maxZoomLevels', int),
('min_zoom', 'minZoomLevel', int),
]
# Building the map options hash.
map_options = {}
for param_name, js_name, option_type in map_types:
if self.params.get(param_name, False):
if option_type == 'srid':
value = ol_projection(self.params[param_name])
elif option_type == 'bounds':
value = ol_bounds(self.params[param_name])
elif option_type in (float, int):
value = self.params[param_name]
elif option_type in (str,):
value = '"%s"' % self.params[param_name]
else:
raise TypeError
map_options[js_name] = value
return map_options | [
"def",
"map_options",
"(",
"self",
")",
":",
"# JavaScript construction utilities for the Bounds and Projection.",
"def",
"ol_bounds",
"(",
"extent",
")",
":",
"return",
"'new OpenLayers.Bounds(%s)'",
"%",
"extent",
"def",
"ol_projection",
"(",
"srid",
")",
":",
"return",
"'new OpenLayers.Projection(\"EPSG:%s\")'",
"%",
"srid",
"# An array of the parameter name, the name of their OpenLayers",
"# counterpart, and the type of variable they are.",
"map_types",
"=",
"[",
"(",
"'srid'",
",",
"'projection'",
",",
"'srid'",
")",
",",
"(",
"'display_srid'",
",",
"'displayProjection'",
",",
"'srid'",
")",
",",
"(",
"'units'",
",",
"'units'",
",",
"str",
")",
",",
"(",
"'max_resolution'",
",",
"'maxResolution'",
",",
"float",
")",
",",
"(",
"'max_extent'",
",",
"'maxExtent'",
",",
"'bounds'",
")",
",",
"(",
"'num_zoom'",
",",
"'numZoomLevels'",
",",
"int",
")",
",",
"(",
"'max_zoom'",
",",
"'maxZoomLevels'",
",",
"int",
")",
",",
"(",
"'min_zoom'",
",",
"'minZoomLevel'",
",",
"int",
")",
",",
"]",
"# Building the map options hash.",
"map_options",
"=",
"{",
"}",
"for",
"param_name",
",",
"js_name",
",",
"option_type",
"in",
"map_types",
":",
"if",
"self",
".",
"params",
".",
"get",
"(",
"param_name",
",",
"False",
")",
":",
"if",
"option_type",
"==",
"'srid'",
":",
"value",
"=",
"ol_projection",
"(",
"self",
".",
"params",
"[",
"param_name",
"]",
")",
"elif",
"option_type",
"==",
"'bounds'",
":",
"value",
"=",
"ol_bounds",
"(",
"self",
".",
"params",
"[",
"param_name",
"]",
")",
"elif",
"option_type",
"in",
"(",
"float",
",",
"int",
")",
":",
"value",
"=",
"self",
".",
"params",
"[",
"param_name",
"]",
"elif",
"option_type",
"in",
"(",
"str",
",",
")",
":",
"value",
"=",
"'\"%s\"'",
"%",
"self",
".",
"params",
"[",
"param_name",
"]",
"else",
":",
"raise",
"TypeError",
"map_options",
"[",
"js_name",
"]",
"=",
"value",
"return",
"map_options"
] | [
80,
4
] | [
116,
26
] | python | en | ['en', 'en', 'en'] | True |
validate_options | (options) | Validates options. | Validates options. | def validate_options(options):
"""Validates options."""
kwcase = options.get('keyword_case')
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for keyword_case: '
'{!r}'.format(kwcase))
idcase = options.get('identifier_case')
if idcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for identifier_case: '
'{!r}'.format(idcase))
ofrmt = options.get('output_format')
if ofrmt not in [None, 'sql', 'python', 'php']:
raise SQLParseError('Unknown output format: '
'{!r}'.format(ofrmt))
strip_comments = options.get('strip_comments', False)
if strip_comments not in [True, False]:
raise SQLParseError('Invalid value for strip_comments: '
'{!r}'.format(strip_comments))
space_around_operators = options.get('use_space_around_operators', False)
if space_around_operators not in [True, False]:
raise SQLParseError('Invalid value for use_space_around_operators: '
'{!r}'.format(space_around_operators))
strip_ws = options.get('strip_whitespace', False)
if strip_ws not in [True, False]:
raise SQLParseError('Invalid value for strip_whitespace: '
'{!r}'.format(strip_ws))
truncate_strings = options.get('truncate_strings')
if truncate_strings is not None:
try:
truncate_strings = int(truncate_strings)
except (ValueError, TypeError):
raise SQLParseError('Invalid value for truncate_strings: '
'{!r}'.format(truncate_strings))
if truncate_strings <= 1:
raise SQLParseError('Invalid value for truncate_strings: '
'{!r}'.format(truncate_strings))
options['truncate_strings'] = truncate_strings
options['truncate_char'] = options.get('truncate_char', '[...]')
indent_columns = options.get('indent_columns', False)
if indent_columns not in [True, False]:
raise SQLParseError('Invalid value for indent_columns: '
'{!r}'.format(indent_columns))
elif indent_columns:
options['reindent'] = True # enforce reindent
options['indent_columns'] = indent_columns
reindent = options.get('reindent', False)
if reindent not in [True, False]:
raise SQLParseError('Invalid value for reindent: '
'{!r}'.format(reindent))
elif reindent:
options['strip_whitespace'] = True
reindent_aligned = options.get('reindent_aligned', False)
if reindent_aligned not in [True, False]:
raise SQLParseError('Invalid value for reindent_aligned: '
'{!r}'.format(reindent))
elif reindent_aligned:
options['strip_whitespace'] = True
indent_after_first = options.get('indent_after_first', False)
if indent_after_first not in [True, False]:
raise SQLParseError('Invalid value for indent_after_first: '
'{!r}'.format(indent_after_first))
options['indent_after_first'] = indent_after_first
indent_tabs = options.get('indent_tabs', False)
if indent_tabs not in [True, False]:
raise SQLParseError('Invalid value for indent_tabs: '
'{!r}'.format(indent_tabs))
elif indent_tabs:
options['indent_char'] = '\t'
else:
options['indent_char'] = ' '
indent_width = options.get('indent_width', 2)
try:
indent_width = int(indent_width)
except (TypeError, ValueError):
raise SQLParseError('indent_width requires an integer')
if indent_width < 1:
raise SQLParseError('indent_width requires a positive integer')
options['indent_width'] = indent_width
wrap_after = options.get('wrap_after', 0)
try:
wrap_after = int(wrap_after)
except (TypeError, ValueError):
raise SQLParseError('wrap_after requires an integer')
if wrap_after < 0:
raise SQLParseError('wrap_after requires a positive integer')
options['wrap_after'] = wrap_after
comma_first = options.get('comma_first', False)
if comma_first not in [True, False]:
raise SQLParseError('comma_first requires a boolean value')
options['comma_first'] = comma_first
right_margin = options.get('right_margin')
if right_margin is not None:
try:
right_margin = int(right_margin)
except (TypeError, ValueError):
raise SQLParseError('right_margin requires an integer')
if right_margin < 10:
raise SQLParseError('right_margin requires an integer > 10')
options['right_margin'] = right_margin
return options | [
"def",
"validate_options",
"(",
"options",
")",
":",
"kwcase",
"=",
"options",
".",
"get",
"(",
"'keyword_case'",
")",
"if",
"kwcase",
"not",
"in",
"[",
"None",
",",
"'upper'",
",",
"'lower'",
",",
"'capitalize'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for keyword_case: '",
"'{!r}'",
".",
"format",
"(",
"kwcase",
")",
")",
"idcase",
"=",
"options",
".",
"get",
"(",
"'identifier_case'",
")",
"if",
"idcase",
"not",
"in",
"[",
"None",
",",
"'upper'",
",",
"'lower'",
",",
"'capitalize'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for identifier_case: '",
"'{!r}'",
".",
"format",
"(",
"idcase",
")",
")",
"ofrmt",
"=",
"options",
".",
"get",
"(",
"'output_format'",
")",
"if",
"ofrmt",
"not",
"in",
"[",
"None",
",",
"'sql'",
",",
"'python'",
",",
"'php'",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Unknown output format: '",
"'{!r}'",
".",
"format",
"(",
"ofrmt",
")",
")",
"strip_comments",
"=",
"options",
".",
"get",
"(",
"'strip_comments'",
",",
"False",
")",
"if",
"strip_comments",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for strip_comments: '",
"'{!r}'",
".",
"format",
"(",
"strip_comments",
")",
")",
"space_around_operators",
"=",
"options",
".",
"get",
"(",
"'use_space_around_operators'",
",",
"False",
")",
"if",
"space_around_operators",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for use_space_around_operators: '",
"'{!r}'",
".",
"format",
"(",
"space_around_operators",
")",
")",
"strip_ws",
"=",
"options",
".",
"get",
"(",
"'strip_whitespace'",
",",
"False",
")",
"if",
"strip_ws",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for strip_whitespace: '",
"'{!r}'",
".",
"format",
"(",
"strip_ws",
")",
")",
"truncate_strings",
"=",
"options",
".",
"get",
"(",
"'truncate_strings'",
")",
"if",
"truncate_strings",
"is",
"not",
"None",
":",
"try",
":",
"truncate_strings",
"=",
"int",
"(",
"truncate_strings",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for truncate_strings: '",
"'{!r}'",
".",
"format",
"(",
"truncate_strings",
")",
")",
"if",
"truncate_strings",
"<=",
"1",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for truncate_strings: '",
"'{!r}'",
".",
"format",
"(",
"truncate_strings",
")",
")",
"options",
"[",
"'truncate_strings'",
"]",
"=",
"truncate_strings",
"options",
"[",
"'truncate_char'",
"]",
"=",
"options",
".",
"get",
"(",
"'truncate_char'",
",",
"'[...]'",
")",
"indent_columns",
"=",
"options",
".",
"get",
"(",
"'indent_columns'",
",",
"False",
")",
"if",
"indent_columns",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_columns: '",
"'{!r}'",
".",
"format",
"(",
"indent_columns",
")",
")",
"elif",
"indent_columns",
":",
"options",
"[",
"'reindent'",
"]",
"=",
"True",
"# enforce reindent",
"options",
"[",
"'indent_columns'",
"]",
"=",
"indent_columns",
"reindent",
"=",
"options",
".",
"get",
"(",
"'reindent'",
",",
"False",
")",
"if",
"reindent",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for reindent: '",
"'{!r}'",
".",
"format",
"(",
"reindent",
")",
")",
"elif",
"reindent",
":",
"options",
"[",
"'strip_whitespace'",
"]",
"=",
"True",
"reindent_aligned",
"=",
"options",
".",
"get",
"(",
"'reindent_aligned'",
",",
"False",
")",
"if",
"reindent_aligned",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for reindent_aligned: '",
"'{!r}'",
".",
"format",
"(",
"reindent",
")",
")",
"elif",
"reindent_aligned",
":",
"options",
"[",
"'strip_whitespace'",
"]",
"=",
"True",
"indent_after_first",
"=",
"options",
".",
"get",
"(",
"'indent_after_first'",
",",
"False",
")",
"if",
"indent_after_first",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_after_first: '",
"'{!r}'",
".",
"format",
"(",
"indent_after_first",
")",
")",
"options",
"[",
"'indent_after_first'",
"]",
"=",
"indent_after_first",
"indent_tabs",
"=",
"options",
".",
"get",
"(",
"'indent_tabs'",
",",
"False",
")",
"if",
"indent_tabs",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'Invalid value for indent_tabs: '",
"'{!r}'",
".",
"format",
"(",
"indent_tabs",
")",
")",
"elif",
"indent_tabs",
":",
"options",
"[",
"'indent_char'",
"]",
"=",
"'\\t'",
"else",
":",
"options",
"[",
"'indent_char'",
"]",
"=",
"' '",
"indent_width",
"=",
"options",
".",
"get",
"(",
"'indent_width'",
",",
"2",
")",
"try",
":",
"indent_width",
"=",
"int",
"(",
"indent_width",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'indent_width requires an integer'",
")",
"if",
"indent_width",
"<",
"1",
":",
"raise",
"SQLParseError",
"(",
"'indent_width requires a positive integer'",
")",
"options",
"[",
"'indent_width'",
"]",
"=",
"indent_width",
"wrap_after",
"=",
"options",
".",
"get",
"(",
"'wrap_after'",
",",
"0",
")",
"try",
":",
"wrap_after",
"=",
"int",
"(",
"wrap_after",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'wrap_after requires an integer'",
")",
"if",
"wrap_after",
"<",
"0",
":",
"raise",
"SQLParseError",
"(",
"'wrap_after requires a positive integer'",
")",
"options",
"[",
"'wrap_after'",
"]",
"=",
"wrap_after",
"comma_first",
"=",
"options",
".",
"get",
"(",
"'comma_first'",
",",
"False",
")",
"if",
"comma_first",
"not",
"in",
"[",
"True",
",",
"False",
"]",
":",
"raise",
"SQLParseError",
"(",
"'comma_first requires a boolean value'",
")",
"options",
"[",
"'comma_first'",
"]",
"=",
"comma_first",
"right_margin",
"=",
"options",
".",
"get",
"(",
"'right_margin'",
")",
"if",
"right_margin",
"is",
"not",
"None",
":",
"try",
":",
"right_margin",
"=",
"int",
"(",
"right_margin",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"SQLParseError",
"(",
"'right_margin requires an integer'",
")",
"if",
"right_margin",
"<",
"10",
":",
"raise",
"SQLParseError",
"(",
"'right_margin requires an integer > 10'",
")",
"options",
"[",
"'right_margin'",
"]",
"=",
"right_margin",
"return",
"options"
] | [
13,
0
] | [
128,
18
] | python | en | ['en', 'et', 'en'] | False |
build_filter_stack | (stack, options) | Setup and return a filter stack.
Args:
stack: :class:`~sqlparse.filters.FilterStack` instance
options: Dictionary with options validated by validate_options.
| Setup and return a filter stack. | def build_filter_stack(stack, options):
"""Setup and return a filter stack.
Args:
stack: :class:`~sqlparse.filters.FilterStack` instance
options: Dictionary with options validated by validate_options.
"""
# Token filter
if options.get('keyword_case'):
stack.preprocess.append(
filters.KeywordCaseFilter(options['keyword_case']))
if options.get('identifier_case'):
stack.preprocess.append(
filters.IdentifierCaseFilter(options['identifier_case']))
if options.get('truncate_strings'):
stack.preprocess.append(filters.TruncateStringFilter(
width=options['truncate_strings'], char=options['truncate_char']))
if options.get('use_space_around_operators', False):
stack.enable_grouping()
stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter())
# After grouping
if options.get('strip_comments'):
stack.enable_grouping()
stack.stmtprocess.append(filters.StripCommentsFilter())
if options.get('strip_whitespace') or options.get('reindent'):
stack.enable_grouping()
stack.stmtprocess.append(filters.StripWhitespaceFilter())
if options.get('reindent'):
stack.enable_grouping()
stack.stmtprocess.append(
filters.ReindentFilter(
char=options['indent_char'],
width=options['indent_width'],
indent_after_first=options['indent_after_first'],
indent_columns=options['indent_columns'],
wrap_after=options['wrap_after'],
comma_first=options['comma_first']))
if options.get('reindent_aligned', False):
stack.enable_grouping()
stack.stmtprocess.append(
filters.AlignedIndentFilter(char=options['indent_char']))
if options.get('right_margin'):
stack.enable_grouping()
stack.stmtprocess.append(
filters.RightMarginFilter(width=options['right_margin']))
# Serializer
if options.get('output_format'):
frmt = options['output_format']
if frmt.lower() == 'php':
fltr = filters.OutputPHPFilter()
elif frmt.lower() == 'python':
fltr = filters.OutputPythonFilter()
else:
fltr = None
if fltr is not None:
stack.postprocess.append(fltr)
return stack | [
"def",
"build_filter_stack",
"(",
"stack",
",",
"options",
")",
":",
"# Token filter",
"if",
"options",
".",
"get",
"(",
"'keyword_case'",
")",
":",
"stack",
".",
"preprocess",
".",
"append",
"(",
"filters",
".",
"KeywordCaseFilter",
"(",
"options",
"[",
"'keyword_case'",
"]",
")",
")",
"if",
"options",
".",
"get",
"(",
"'identifier_case'",
")",
":",
"stack",
".",
"preprocess",
".",
"append",
"(",
"filters",
".",
"IdentifierCaseFilter",
"(",
"options",
"[",
"'identifier_case'",
"]",
")",
")",
"if",
"options",
".",
"get",
"(",
"'truncate_strings'",
")",
":",
"stack",
".",
"preprocess",
".",
"append",
"(",
"filters",
".",
"TruncateStringFilter",
"(",
"width",
"=",
"options",
"[",
"'truncate_strings'",
"]",
",",
"char",
"=",
"options",
"[",
"'truncate_char'",
"]",
")",
")",
"if",
"options",
".",
"get",
"(",
"'use_space_around_operators'",
",",
"False",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"SpacesAroundOperatorsFilter",
"(",
")",
")",
"# After grouping",
"if",
"options",
".",
"get",
"(",
"'strip_comments'",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"StripCommentsFilter",
"(",
")",
")",
"if",
"options",
".",
"get",
"(",
"'strip_whitespace'",
")",
"or",
"options",
".",
"get",
"(",
"'reindent'",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"StripWhitespaceFilter",
"(",
")",
")",
"if",
"options",
".",
"get",
"(",
"'reindent'",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"ReindentFilter",
"(",
"char",
"=",
"options",
"[",
"'indent_char'",
"]",
",",
"width",
"=",
"options",
"[",
"'indent_width'",
"]",
",",
"indent_after_first",
"=",
"options",
"[",
"'indent_after_first'",
"]",
",",
"indent_columns",
"=",
"options",
"[",
"'indent_columns'",
"]",
",",
"wrap_after",
"=",
"options",
"[",
"'wrap_after'",
"]",
",",
"comma_first",
"=",
"options",
"[",
"'comma_first'",
"]",
")",
")",
"if",
"options",
".",
"get",
"(",
"'reindent_aligned'",
",",
"False",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"AlignedIndentFilter",
"(",
"char",
"=",
"options",
"[",
"'indent_char'",
"]",
")",
")",
"if",
"options",
".",
"get",
"(",
"'right_margin'",
")",
":",
"stack",
".",
"enable_grouping",
"(",
")",
"stack",
".",
"stmtprocess",
".",
"append",
"(",
"filters",
".",
"RightMarginFilter",
"(",
"width",
"=",
"options",
"[",
"'right_margin'",
"]",
")",
")",
"# Serializer",
"if",
"options",
".",
"get",
"(",
"'output_format'",
")",
":",
"frmt",
"=",
"options",
"[",
"'output_format'",
"]",
"if",
"frmt",
".",
"lower",
"(",
")",
"==",
"'php'",
":",
"fltr",
"=",
"filters",
".",
"OutputPHPFilter",
"(",
")",
"elif",
"frmt",
".",
"lower",
"(",
")",
"==",
"'python'",
":",
"fltr",
"=",
"filters",
".",
"OutputPythonFilter",
"(",
")",
"else",
":",
"fltr",
"=",
"None",
"if",
"fltr",
"is",
"not",
"None",
":",
"stack",
".",
"postprocess",
".",
"append",
"(",
"fltr",
")",
"return",
"stack"
] | [
131,
0
] | [
197,
16
] | python | en | ['en', 'da', 'en'] | True |
serve | (request, path, document_root=None, show_indexes=False) |
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
path('<path:path>', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
|
Serve static files below a given point in the directory structure. | def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
path('<path:path>', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(path).lstrip('/')
fullpath = Path(safe_join(document_root, path))
if fullpath.is_dir():
if show_indexes:
return directory_index(path, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not fullpath.exists():
raise Http404(_('“%(path)s” does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = fullpath.stat()
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
content_type, encoding = mimetypes.guess_type(str(fullpath))
content_type = content_type or 'application/octet-stream'
response = FileResponse(fullpath.open('rb'), content_type=content_type)
response.headers["Last-Modified"] = http_date(statobj.st_mtime)
if encoding:
response.headers["Content-Encoding"] = encoding
return response | [
"def",
"serve",
"(",
"request",
",",
"path",
",",
"document_root",
"=",
"None",
",",
"show_indexes",
"=",
"False",
")",
":",
"path",
"=",
"posixpath",
".",
"normpath",
"(",
"path",
")",
".",
"lstrip",
"(",
"'/'",
")",
"fullpath",
"=",
"Path",
"(",
"safe_join",
"(",
"document_root",
",",
"path",
")",
")",
"if",
"fullpath",
".",
"is_dir",
"(",
")",
":",
"if",
"show_indexes",
":",
"return",
"directory_index",
"(",
"path",
",",
"fullpath",
")",
"raise",
"Http404",
"(",
"_",
"(",
"\"Directory indexes are not allowed here.\"",
")",
")",
"if",
"not",
"fullpath",
".",
"exists",
"(",
")",
":",
"raise",
"Http404",
"(",
"_",
"(",
"'“%(path)s” does not exist') % ",
"{",
"p",
"t",
"h': fu",
"l",
"path})",
"",
"",
"# Respect the If-Modified-Since header.",
"statobj",
"=",
"fullpath",
".",
"stat",
"(",
")",
"if",
"not",
"was_modified_since",
"(",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_IF_MODIFIED_SINCE'",
")",
",",
"statobj",
".",
"st_mtime",
",",
"statobj",
".",
"st_size",
")",
":",
"return",
"HttpResponseNotModified",
"(",
")",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"str",
"(",
"fullpath",
")",
")",
"content_type",
"=",
"content_type",
"or",
"'application/octet-stream'",
"response",
"=",
"FileResponse",
"(",
"fullpath",
".",
"open",
"(",
"'rb'",
")",
",",
"content_type",
"=",
"content_type",
")",
"response",
".",
"headers",
"[",
"\"Last-Modified\"",
"]",
"=",
"http_date",
"(",
"statobj",
".",
"st_mtime",
")",
"if",
"encoding",
":",
"response",
".",
"headers",
"[",
"\"Content-Encoding\"",
"]",
"=",
"encoding",
"return",
"response"
] | [
18,
0
] | [
53,
19
] | python | en | ['en', 'error', 'th'] | False |
was_modified_since | (header=None, mtime=0, size=0) |
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
size
This is the size of the item we're talking about.
|
Was something modified since the user last downloaded it? | def was_modified_since(header=None, mtime=0, size=0):
"""
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
size
This is the size of the item we're talking about.
"""
try:
if header is None:
raise ValueError
matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
re.IGNORECASE)
header_mtime = parse_http_date(matches[1])
header_len = matches[3]
if header_len and int(header_len) != size:
raise ValueError
if int(mtime) > header_mtime:
raise ValueError
except (AttributeError, ValueError, OverflowError):
return True
return False | [
"def",
"was_modified_since",
"(",
"header",
"=",
"None",
",",
"mtime",
"=",
"0",
",",
"size",
"=",
"0",
")",
":",
"try",
":",
"if",
"header",
"is",
"None",
":",
"raise",
"ValueError",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"^([^;]+)(; length=([0-9]+))?$\"",
",",
"header",
",",
"re",
".",
"IGNORECASE",
")",
"header_mtime",
"=",
"parse_http_date",
"(",
"matches",
"[",
"1",
"]",
")",
"header_len",
"=",
"matches",
"[",
"3",
"]",
"if",
"header_len",
"and",
"int",
"(",
"header_len",
")",
"!=",
"size",
":",
"raise",
"ValueError",
"if",
"int",
"(",
"mtime",
")",
">",
"header_mtime",
":",
"raise",
"ValueError",
"except",
"(",
"AttributeError",
",",
"ValueError",
",",
"OverflowError",
")",
":",
"return",
"True",
"return",
"False"
] | [
107,
0
] | [
134,
16
] | python | en | ['en', 'error', 'th'] | False |
image2float_array | (image, scale_factor=None) |
source: https://github.com/ahundt/robotics_setup/blob/master/datasets/google_brain_robot_data/depth_image_encoding.py
Recovers the depth values from an image.
Reverses the depth to image conversion performed by FloatArrayToRgbImage or
FloatArrayToGrayImage.
The image is treated as an array of fixed point depth values. Each
value is converted to float and scaled by the inverse of the factor
that was used to generate the Image object from depth values. If
scale_factor is specified, it should be the same value that was
specified in the original conversion.
The result of this function should be equal to the original input
within the precision of the conversion.
Args:
image: Depth image output of FloatArrayTo[Format]Image.
scale_factor: Fixed point scale factor.
Returns:
A 2D floating point numpy array representing a depth image.
|
source: https://github.com/ahundt/robotics_setup/blob/master/datasets/google_brain_robot_data/depth_image_encoding.py
Recovers the depth values from an image.
Reverses the depth to image conversion performed by FloatArrayToRgbImage or
FloatArrayToGrayImage.
The image is treated as an array of fixed point depth values. Each
value is converted to float and scaled by the inverse of the factor
that was used to generate the Image object from depth values. If
scale_factor is specified, it should be the same value that was
specified in the original conversion. | def image2float_array(image, scale_factor=None):
'''
source: https://github.com/ahundt/robotics_setup/blob/master/datasets/google_brain_robot_data/depth_image_encoding.py
Recovers the depth values from an image.
Reverses the depth to image conversion performed by FloatArrayToRgbImage or
FloatArrayToGrayImage.
The image is treated as an array of fixed point depth values. Each
value is converted to float and scaled by the inverse of the factor
that was used to generate the Image object from depth values. If
scale_factor is specified, it should be the same value that was
specified in the original conversion.
The result of this function should be equal to the original input
within the precision of the conversion.
Args:
image: Depth image output of FloatArrayTo[Format]Image.
scale_factor: Fixed point scale factor.
Returns:
A 2D floating point numpy array representing a depth image.
'''
image_array = np.array(image)
image_dtype = image_array.dtype
image_shape = image_array.shape
channels = image_shape[2] if len(image_shape) > 2 else 1
assert 2 <= len(image_shape) <= 3
if channels == 3:
# RGB image needs to be converted to 24 bit integer.
float_array = np.sum(image_array * [65536, 256, 1], axis=2)
if scale_factor is None:
scale_factor = DEFAULT_RGB_SCALE_FACTOR
else:
if scale_factor is None:
scale_factor = DEFAULT_GRAY_SCALE_FACTOR[image_dtype.type]
float_array = image_array.astype(np.float32)
scaled_array = float_array / scale_factor
return scaled_array | [
"def",
"image2float_array",
"(",
"image",
",",
"scale_factor",
"=",
"None",
")",
":",
"image_array",
"=",
"np",
".",
"array",
"(",
"image",
")",
"image_dtype",
"=",
"image_array",
".",
"dtype",
"image_shape",
"=",
"image_array",
".",
"shape",
"channels",
"=",
"image_shape",
"[",
"2",
"]",
"if",
"len",
"(",
"image_shape",
")",
">",
"2",
"else",
"1",
"assert",
"2",
"<=",
"len",
"(",
"image_shape",
")",
"<=",
"3",
"if",
"channels",
"==",
"3",
":",
"# RGB image needs to be converted to 24 bit integer.",
"float_array",
"=",
"np",
".",
"sum",
"(",
"image_array",
"*",
"[",
"65536",
",",
"256",
",",
"1",
"]",
",",
"axis",
"=",
"2",
")",
"if",
"scale_factor",
"is",
"None",
":",
"scale_factor",
"=",
"DEFAULT_RGB_SCALE_FACTOR",
"else",
":",
"if",
"scale_factor",
"is",
"None",
":",
"scale_factor",
"=",
"DEFAULT_GRAY_SCALE_FACTOR",
"[",
"image_dtype",
".",
"type",
"]",
"float_array",
"=",
"image_array",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"scaled_array",
"=",
"float_array",
"/",
"scale_factor",
"return",
"scaled_array"
] | [
105,
0
] | [
149,
23
] | python | en | ['en', 'error', 'th'] | False |
image_resize2square | (image, desired_size=None) |
Transform image to a square image with desired size(resolution)
Padding image with black color which defined as MASK_BACKGROUND
|
Transform image to a square image with desired size(resolution)
Padding image with black color which defined as MASK_BACKGROUND
| def image_resize2square(image, desired_size=None):
'''
Transform image to a square image with desired size(resolution)
Padding image with black color which defined as MASK_BACKGROUND
'''
# initialize dimensions of the image to be resized and
# grab the image size
old_size = image.shape[:2]
# if both the width and height are None, then return the
# original image
if desired_size is None or (old_size[0] == desired_size and old_size[1] == desired_size):
return image
# calculate the ratio of the height and construct the
# dimensions
ratio = float(desired_size) / max(old_size)
new_size = tuple([int(x * ratio) for x in old_size])
# new_size should be in (width, height) format
resized = cv2.resize(image, (new_size[1], new_size[0]))
delta_w = desired_size - new_size[1]
delta_h = desired_size - new_size[0]
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
left, right = delta_w // 2, delta_w - (delta_w // 2)
new_image = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=MASK_BACKGROUND)
# return the resized image
return new_image | [
"def",
"image_resize2square",
"(",
"image",
",",
"desired_size",
"=",
"None",
")",
":",
"# initialize dimensions of the image to be resized and",
"# grab the image size",
"old_size",
"=",
"image",
".",
"shape",
"[",
":",
"2",
"]",
"# if both the width and height are None, then return the",
"# original image",
"if",
"desired_size",
"is",
"None",
"or",
"(",
"old_size",
"[",
"0",
"]",
"==",
"desired_size",
"and",
"old_size",
"[",
"1",
"]",
"==",
"desired_size",
")",
":",
"return",
"image",
"# calculate the ratio of the height and construct the",
"# dimensions",
"ratio",
"=",
"float",
"(",
"desired_size",
")",
"/",
"max",
"(",
"old_size",
")",
"new_size",
"=",
"tuple",
"(",
"[",
"int",
"(",
"x",
"*",
"ratio",
")",
"for",
"x",
"in",
"old_size",
"]",
")",
"# new_size should be in (width, height) format",
"resized",
"=",
"cv2",
".",
"resize",
"(",
"image",
",",
"(",
"new_size",
"[",
"1",
"]",
",",
"new_size",
"[",
"0",
"]",
")",
")",
"delta_w",
"=",
"desired_size",
"-",
"new_size",
"[",
"1",
"]",
"delta_h",
"=",
"desired_size",
"-",
"new_size",
"[",
"0",
"]",
"top",
",",
"bottom",
"=",
"delta_h",
"//",
"2",
",",
"delta_h",
"-",
"(",
"delta_h",
"//",
"2",
")",
"left",
",",
"right",
"=",
"delta_w",
"//",
"2",
",",
"delta_w",
"-",
"(",
"delta_w",
"//",
"2",
")",
"new_image",
"=",
"cv2",
".",
"copyMakeBorder",
"(",
"resized",
",",
"top",
",",
"bottom",
",",
"left",
",",
"right",
",",
"cv2",
".",
"BORDER_CONSTANT",
",",
"value",
"=",
"MASK_BACKGROUND",
")",
"# return the resized image",
"return",
"new_image"
] | [
152,
0
] | [
183,
20
] | python | en | ['en', 'error', 'th'] | False |
image_enhance | (image, shift) |
Input image is a numpy array with unit8 grayscale.
This function will enhance the bright by adding num to each pixel.
perform normalization
|
Input image is a numpy array with unit8 grayscale.
This function will enhance the bright by adding num to each pixel.
perform normalization
| def image_enhance(image, shift):
'''
Input image is a numpy array with unit8 grayscale.
This function will enhance the bright by adding num to each pixel.
perform normalization
'''
if shift > 0:
for i in range(shift):
image += 1
# If pixel value == 0 which means the value = 256 but overflow to 0
# shift the overflow pix values to 255.
image[image == 0] = 255
return image | [
"def",
"image_enhance",
"(",
"image",
",",
"shift",
")",
":",
"if",
"shift",
">",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"shift",
")",
":",
"image",
"+=",
"1",
"# If pixel value == 0 which means the value = 256 but overflow to 0",
"# shift the overflow pix values to 255. ",
"image",
"[",
"image",
"==",
"0",
"]",
"=",
"255",
"return",
"image"
] | [
186,
0
] | [
199,
16
] | python | en | ['en', 'error', 'th'] | False |
process_image | (img, shift, resolution) |
Pre-process image before store in numpy file.
shift: shift all pixels a distance with the shift value to avoid black color in image.
resolution: change image resolution to fit model.
|
Pre-process image before store in numpy file.
shift: shift all pixels a distance with the shift value to avoid black color in image.
resolution: change image resolution to fit model.
| def process_image(img, shift, resolution):
'''
Pre-process image before store in numpy file.
shift: shift all pixels a distance with the shift value to avoid black color in image.
resolution: change image resolution to fit model.
'''
# Add 5 for each pixel on the grayscale image.
if MODE != "L":
img = image_enhance(img, shift=shift)
# The source image should be 512X512 resolution.
img = image_resize2square(img, resolution)
return img | [
"def",
"process_image",
"(",
"img",
",",
"shift",
",",
"resolution",
")",
":",
"# Add 5 for each pixel on the grayscale image.",
"if",
"MODE",
"!=",
"\"L\"",
":",
"img",
"=",
"image_enhance",
"(",
"img",
",",
"shift",
"=",
"shift",
")",
"# The source image should be 512X512 resolution.",
"img",
"=",
"image_resize2square",
"(",
"img",
",",
"resolution",
")",
"return",
"img"
] | [
202,
0
] | [
215,
14
] | python | en | ['en', 'error', 'th'] | False |
change_background_color | (img, original_color, new_color) |
Convert mask color of 4 channels png image to new color
|
Convert mask color of 4 channels png image to new color
| def change_background_color(img, original_color, new_color):
'''
Convert mask color of 4 channels png image to new color
'''
r1, g1, b1, a1 = original_color[0], original_color[1], original_color[2], original_color[3] # Original value
# mask background color (0,0,0,0)
r2, g2, b2, a2 = new_color[0], new_color[1], new_color[2], new_color[3] # Value that we want to replace it with
red, green, blue, alpha = img[:, :, 0], img[:, :, 1], img[:, :, 2], img[:, :, 3]
mask = (red == r1) & (green == g1) & (blue == b1) & (alpha == a1)
img[:, :, :4][mask] = [r2, g2, b2, a2]
return img | [
"def",
"change_background_color",
"(",
"img",
",",
"original_color",
",",
"new_color",
")",
":",
"r1",
",",
"g1",
",",
"b1",
",",
"a1",
"=",
"original_color",
"[",
"0",
"]",
",",
"original_color",
"[",
"1",
"]",
",",
"original_color",
"[",
"2",
"]",
",",
"original_color",
"[",
"3",
"]",
"# Original value",
"# mask background color (0,0,0,0)",
"r2",
",",
"g2",
",",
"b2",
",",
"a2",
"=",
"new_color",
"[",
"0",
"]",
",",
"new_color",
"[",
"1",
"]",
",",
"new_color",
"[",
"2",
"]",
",",
"new_color",
"[",
"3",
"]",
"# Value that we want to replace it with",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"=",
"img",
"[",
":",
",",
":",
",",
"0",
"]",
",",
"img",
"[",
":",
",",
":",
",",
"1",
"]",
",",
"img",
"[",
":",
",",
":",
",",
"2",
"]",
",",
"img",
"[",
":",
",",
":",
",",
"3",
"]",
"mask",
"=",
"(",
"red",
"==",
"r1",
")",
"&",
"(",
"green",
"==",
"g1",
")",
"&",
"(",
"blue",
"==",
"b1",
")",
"&",
"(",
"alpha",
"==",
"a1",
")",
"img",
"[",
":",
",",
":",
",",
":",
"4",
"]",
"[",
"mask",
"]",
"=",
"[",
"r2",
",",
"g2",
",",
"b2",
",",
"a2",
"]",
"return",
"img"
] | [
218,
0
] | [
230,
14
] | python | en | ['en', 'error', 'th'] | False |
convert_mask_data | (mask, resolution=RESOLUTION, from_background_color=COCO_BACKGROUND,
to_background_color=MASK_BACKGROUND) |
1. Resize mask to square with size of resolution.
2. Change back ground color to black
3. Change pixel value to 1 for masking
4. Change pixel value to 0 for non-masking area
5. Reduce data type to uint8 to reduce the file size of mask.
|
1. Resize mask to square with size of resolution.
2. Change back ground color to black
3. Change pixel value to 1 for masking
4. Change pixel value to 0 for non-masking area
5. Reduce data type to uint8 to reduce the file size of mask.
| def convert_mask_data(mask, resolution=RESOLUTION, from_background_color=COCO_BACKGROUND,
to_background_color=MASK_BACKGROUND):
'''
1. Resize mask to square with size of resolution.
2. Change back ground color to black
3. Change pixel value to 1 for masking
4. Change pixel value to 0 for non-masking area
5. Reduce data type to uint8 to reduce the file size of mask.
'''
mask = image_resize2square(mask, resolution)
mask = change_background_color(mask, from_background_color, to_background_color)
if GRAYSCALE == True:
# Only need one channel for black and white
mask = mask[:, :, :1]
else:
mask = mask[:, :, :1] # keep 3 channels for RGB. Remove alpha channel.
mask[mask >= 1] = 1 # The mask. ie. class of Person
mask[mask != 1] = 0 # Non Person / Background
mask = mask.astype(np.uint8)
return mask | [
"def",
"convert_mask_data",
"(",
"mask",
",",
"resolution",
"=",
"RESOLUTION",
",",
"from_background_color",
"=",
"COCO_BACKGROUND",
",",
"to_background_color",
"=",
"MASK_BACKGROUND",
")",
":",
"mask",
"=",
"image_resize2square",
"(",
"mask",
",",
"resolution",
")",
"mask",
"=",
"change_background_color",
"(",
"mask",
",",
"from_background_color",
",",
"to_background_color",
")",
"if",
"GRAYSCALE",
"==",
"True",
":",
"# Only need one channel for black and white ",
"mask",
"=",
"mask",
"[",
":",
",",
":",
",",
":",
"1",
"]",
"else",
":",
"mask",
"=",
"mask",
"[",
":",
",",
":",
",",
":",
"1",
"]",
"# keep 3 channels for RGB. Remove alpha channel.",
"mask",
"[",
"mask",
">=",
"1",
"]",
"=",
"1",
"# The mask. ie. class of Person",
"mask",
"[",
"mask",
"!=",
"1",
"]",
"=",
"0",
"# Non Person / Background",
"mask",
"=",
"mask",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"return",
"mask"
] | [
233,
0
] | [
254,
15
] | python | en | ['en', 'error', 'th'] | False |
convert_img_data | (img, dims=4, resolution=RESOLUTION) |
Convert image data by
1. Shift RGB channel with value 1 to avoid pure black color.
2. Resize image to square
3. Normalized data
4. reshape to require dimension 3 or 4
|
Convert image data by
1. Shift RGB channel with value 1 to avoid pure black color.
2. Resize image to square
3. Normalized data
4. reshape to require dimension 3 or 4
| def convert_img_data(img, dims=4, resolution=RESOLUTION):
'''
Convert image data by
1. Shift RGB channel with value 1 to avoid pure black color.
2. Resize image to square
3. Normalized data
4. reshape to require dimension 3 or 4
'''
# img = img[:, :, :3]
if GRAYSCALE == True:
# Add 1 for each pixel and change resolution on the image.
img = process_image(img, shift=1, resolution=resolution)
if MODE != "L":
# Translate the image to 24bits grayscale by PILLOW package
img = image2float_array(img, 16777216 - 1) # 2^24=16777216
if dims == 3:
# Reshape numpy from 2 to 3 dimensions
img = img.reshape([img.shape[0], img.shape[1], 1])
else: # dimension = 4
img = img.reshape([1, img.shape[0], img.shape[1], 1])
else: # Color image with 3 channels
# Add 1 for each pixel and change resolution on the image.
img = process_image(img, shift=1, resolution=resolution)
if dims == 3:
# Keep RGB channel, remove alpha channel
img = img[:, :, :3]
else: # dimensions = 4
img = img[:, :, :, :3]
return img | [
"def",
"convert_img_data",
"(",
"img",
",",
"dims",
"=",
"4",
",",
"resolution",
"=",
"RESOLUTION",
")",
":",
"# img = img[:, :, :3]",
"if",
"GRAYSCALE",
"==",
"True",
":",
"# Add 1 for each pixel and change resolution on the image.",
"img",
"=",
"process_image",
"(",
"img",
",",
"shift",
"=",
"1",
",",
"resolution",
"=",
"resolution",
")",
"if",
"MODE",
"!=",
"\"L\"",
":",
"# Translate the image to 24bits grayscale by PILLOW package",
"img",
"=",
"image2float_array",
"(",
"img",
",",
"16777216",
"-",
"1",
")",
"# 2^24=16777216",
"if",
"dims",
"==",
"3",
":",
"# Reshape numpy from 2 to 3 dimensions",
"img",
"=",
"img",
".",
"reshape",
"(",
"[",
"img",
".",
"shape",
"[",
"0",
"]",
",",
"img",
".",
"shape",
"[",
"1",
"]",
",",
"1",
"]",
")",
"else",
":",
"# dimension = 4",
"img",
"=",
"img",
".",
"reshape",
"(",
"[",
"1",
",",
"img",
".",
"shape",
"[",
"0",
"]",
",",
"img",
".",
"shape",
"[",
"1",
"]",
",",
"1",
"]",
")",
"else",
":",
"# Color image with 3 channels",
"# Add 1 for each pixel and change resolution on the image.",
"img",
"=",
"process_image",
"(",
"img",
",",
"shift",
"=",
"1",
",",
"resolution",
"=",
"resolution",
")",
"if",
"dims",
"==",
"3",
":",
"# Keep RGB channel, remove alpha channel",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"else",
":",
"# dimensions = 4",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
":",
",",
":",
"3",
"]",
"return",
"img"
] | [
257,
0
] | [
286,
14
] | python | en | ['en', 'error', 'th'] | False |
BaseSessionManager.encode | (self, session_dict) |
Return the given session dictionary serialized and encoded as a string.
|
Return the given session dictionary serialized and encoded as a string.
| def encode(self, session_dict):
"""
Return the given session dictionary serialized and encoded as a string.
"""
session_store_class = self.model.get_session_store_class()
return session_store_class().encode(session_dict) | [
"def",
"encode",
"(",
"self",
",",
"session_dict",
")",
":",
"session_store_class",
"=",
"self",
".",
"model",
".",
"get_session_store_class",
"(",
")",
"return",
"session_store_class",
"(",
")",
".",
"encode",
"(",
"session_dict",
")"
] | [
9,
4
] | [
14,
57
] | python | en | ['en', 'error', 'th'] | False |
AddDiskResourcesIfNeeded | (context) | Checks context if disk resources need to be added. | Checks context if disk resources need to be added. | def AddDiskResourcesIfNeeded(context):
"""Checks context if disk resources need to be added."""
if default.DISK_RESOURCES in context.properties:
return context.properties[default.DISK_RESOURCES]
else:
return [] | [
"def",
"AddDiskResourcesIfNeeded",
"(",
"context",
")",
":",
"if",
"default",
".",
"DISK_RESOURCES",
"in",
"context",
".",
"properties",
":",
"return",
"context",
".",
"properties",
"[",
"default",
".",
"DISK_RESOURCES",
"]",
"else",
":",
"return",
"[",
"]"
] | [
30,
0
] | [
35,
13
] | python | en | ['en', 'en', 'en'] | True |
AutoName | (base, resource, *args) | Helper method to generate names automatically based on default. | Helper method to generate names automatically based on default. | def AutoName(base, resource, *args):
"""Helper method to generate names automatically based on default."""
auto_name = '%s-%s' % (base, '-'.join(list(args) + [default.AKA[resource]]))
if not RFC1035_RE.match(auto_name):
raise Error('"%s" name for type %s does not match RFC1035 regex (%s)' %
(auto_name, resource, RFC1035_RE.pattern))
return auto_name | [
"def",
"AutoName",
"(",
"base",
",",
"resource",
",",
"*",
"args",
")",
":",
"auto_name",
"=",
"'%s-%s'",
"%",
"(",
"base",
",",
"'-'",
".",
"join",
"(",
"list",
"(",
"args",
")",
"+",
"[",
"default",
".",
"AKA",
"[",
"resource",
"]",
"]",
")",
")",
"if",
"not",
"RFC1035_RE",
".",
"match",
"(",
"auto_name",
")",
":",
"raise",
"Error",
"(",
"'\"%s\" name for type %s does not match RFC1035 regex (%s)'",
"%",
"(",
"auto_name",
",",
"resource",
",",
"RFC1035_RE",
".",
"pattern",
")",
")",
"return",
"auto_name"
] | [
38,
0
] | [
44,
18
] | python | en | ['en', 'en', 'en'] | True |
AutoRef | (base, resource, *args) | Helper method that builds a reference for an auto-named resource. | Helper method that builds a reference for an auto-named resource. | def AutoRef(base, resource, *args):
"""Helper method that builds a reference for an auto-named resource."""
return Ref(AutoName(base, resource, *args)) | [
"def",
"AutoRef",
"(",
"base",
",",
"resource",
",",
"*",
"args",
")",
":",
"return",
"Ref",
"(",
"AutoName",
"(",
"base",
",",
"resource",
",",
"*",
"args",
")",
")"
] | [
47,
0
] | [
49,
45
] | python | en | ['en', 'en', 'en'] | True |
OrderedItems | (dict_obj) | Convenient method to yield sorted iteritems of a dictionary. | Convenient method to yield sorted iteritems of a dictionary. | def OrderedItems(dict_obj):
"""Convenient method to yield sorted iteritems of a dictionary."""
keys = list(dict_obj.keys())
keys.sort()
for k in keys:
yield (k, dict_obj[k]) | [
"def",
"OrderedItems",
"(",
"dict_obj",
")",
":",
"keys",
"=",
"list",
"(",
"dict_obj",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"yield",
"(",
"k",
",",
"dict_obj",
"[",
"k",
"]",
")"
] | [
52,
0
] | [
57,
26
] | python | en | ['en', 'en', 'en'] | True |
ShortenZoneName | (zone) | Given a string that looks like a zone name, creates a shorter version. | Given a string that looks like a zone name, creates a shorter version. | def ShortenZoneName(zone):
"""Given a string that looks like a zone name, creates a shorter version."""
geo, coord, number, letter = re.findall(r'(\w+)-(\w+)(\d)-(\w)', zone)[0]
geo = geo.lower() if len(geo) == 2 else default.LOC[geo.lower()]
coord = default.LOC[coord.lower()]
number = str(number)
letter = letter.lower()
return geo + '-' + coord + number + letter | [
"def",
"ShortenZoneName",
"(",
"zone",
")",
":",
"geo",
",",
"coord",
",",
"number",
",",
"letter",
"=",
"re",
".",
"findall",
"(",
"r'(\\w+)-(\\w+)(\\d)-(\\w)'",
",",
"zone",
")",
"[",
"0",
"]",
"geo",
"=",
"geo",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"geo",
")",
"==",
"2",
"else",
"default",
".",
"LOC",
"[",
"geo",
".",
"lower",
"(",
")",
"]",
"coord",
"=",
"default",
".",
"LOC",
"[",
"coord",
".",
"lower",
"(",
")",
"]",
"number",
"=",
"str",
"(",
"number",
")",
"letter",
"=",
"letter",
".",
"lower",
"(",
")",
"return",
"geo",
"+",
"'-'",
"+",
"coord",
"+",
"number",
"+",
"letter"
] | [
60,
0
] | [
67,
44
] | python | en | ['en', 'en', 'en'] | True |
ZoneToRegion | (zone) | Derives the region from a zone name. | Derives the region from a zone name. | def ZoneToRegion(zone):
"""Derives the region from a zone name."""
parts = zone.split('-')
if len(parts) != 3:
raise Error('Cannot derive region from zone "%s"' % zone)
return '-'.join(parts[:2]) | [
"def",
"ZoneToRegion",
"(",
"zone",
")",
":",
"parts",
"=",
"zone",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"3",
":",
"raise",
"Error",
"(",
"'Cannot derive region from zone \"%s\"'",
"%",
"zone",
")",
"return",
"'-'",
".",
"join",
"(",
"parts",
"[",
":",
"2",
"]",
")"
] | [
70,
0
] | [
75,
28
] | python | en | ['en', 'en', 'en'] | True |
FormatException | (message) | Adds more information to the exception. | Adds more information to the exception. | def FormatException(message):
"""Adds more information to the exception."""
message = ('Exception Type: %s\n'
'Details: %s\n'
'Message: %s\n') % (sys.exc_info()[0], traceback.format_exc(), message)
return message | [
"def",
"FormatException",
"(",
"message",
")",
":",
"message",
"=",
"(",
"'Exception Type: %s\\n'",
"'Details: %s\\n'",
"'Message: %s\\n'",
")",
"%",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"traceback",
".",
"format_exc",
"(",
")",
",",
"message",
")",
"return",
"message"
] | [
78,
0
] | [
83,
16
] | python | en | ['en', 'en', 'en'] | True |
SummarizeResources | (res_dict) | Summarizes the name of resources per resource type. | Summarizes the name of resources per resource type. | def SummarizeResources(res_dict):
"""Summarizes the name of resources per resource type."""
result = {}
for res in res_dict:
result.setdefault(res['type'], []).append(res['name'])
return result | [
"def",
"SummarizeResources",
"(",
"res_dict",
")",
":",
"result",
"=",
"{",
"}",
"for",
"res",
"in",
"res_dict",
":",
"result",
".",
"setdefault",
"(",
"res",
"[",
"'type'",
"]",
",",
"[",
"]",
")",
".",
"append",
"(",
"res",
"[",
"'name'",
"]",
")",
"return",
"result"
] | [
160,
0
] | [
165,
15
] | python | en | ['en', 'en', 'en'] | True |
ListPropertyValuesOfType | (res_dict, prop, res_type) | Lists all the values for a property of a certain type. | Lists all the values for a property of a certain type. | def ListPropertyValuesOfType(res_dict, prop, res_type):
"""Lists all the values for a property of a certain type."""
return [r['properties'][prop] for r in res_dict if r['type'] == res_type] | [
"def",
"ListPropertyValuesOfType",
"(",
"res_dict",
",",
"prop",
",",
"res_type",
")",
":",
"return",
"[",
"r",
"[",
"'properties'",
"]",
"[",
"prop",
"]",
"for",
"r",
"in",
"res_dict",
"if",
"r",
"[",
"'type'",
"]",
"==",
"res_type",
"]"
] | [
168,
0
] | [
170,
75
] | python | en | ['en', 'en', 'en'] | True |
MakeResource | (resource_list, output_list=None) | Wrapper for a DM template basic spec. | Wrapper for a DM template basic spec. | def MakeResource(resource_list, output_list=None):
"""Wrapper for a DM template basic spec."""
content = {'resources': resource_list}
if output_list:
content['outputs'] = output_list
return yaml.dump(content) | [
"def",
"MakeResource",
"(",
"resource_list",
",",
"output_list",
"=",
"None",
")",
":",
"content",
"=",
"{",
"'resources'",
":",
"resource_list",
"}",
"if",
"output_list",
":",
"content",
"[",
"'outputs'",
"]",
"=",
"output_list",
"return",
"yaml",
".",
"dump",
"(",
"content",
")"
] | [
173,
0
] | [
178,
27
] | python | en | ['en', 'en', 'en'] | True |
TakeZoneOut | (properties) | Given a properties dictionary, removes the zone specific information. | Given a properties dictionary, removes the zone specific information. | def TakeZoneOut(properties):
"""Given a properties dictionary, removes the zone specific information."""
def _CleanZoneUrl(value):
value = value.split('/')[-1] if IsComputeLink(value) else value
return value
for name in default.VM_ZONE_PROPERTIES:
if name in properties:
properties[name] = _CleanZoneUrl(properties[name])
if default.ZONE in properties:
properties.pop(default.ZONE)
if default.BOOTDISK in properties:
properties[default.BOOTDISK] = _CleanZoneUrl(properties[default.BOOTDISK])
if default.DISKS in properties:
for disk in properties[default.DISKS]:
# Don't touch references to other disks
if default.DISK_SOURCE in disk:
continue
if default.INITIALIZEP in disk:
disk_init = disk[default.INITIALIZEP]
if default.DISKTYPE in disk_init:
disk_init[default.DISKTYPE] = _CleanZoneUrl(disk_init[default.DISKTYPE]) | [
"def",
"TakeZoneOut",
"(",
"properties",
")",
":",
"def",
"_CleanZoneUrl",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"IsComputeLink",
"(",
"value",
")",
"else",
"value",
"return",
"value",
"for",
"name",
"in",
"default",
".",
"VM_ZONE_PROPERTIES",
":",
"if",
"name",
"in",
"properties",
":",
"properties",
"[",
"name",
"]",
"=",
"_CleanZoneUrl",
"(",
"properties",
"[",
"name",
"]",
")",
"if",
"default",
".",
"ZONE",
"in",
"properties",
":",
"properties",
".",
"pop",
"(",
"default",
".",
"ZONE",
")",
"if",
"default",
".",
"BOOTDISK",
"in",
"properties",
":",
"properties",
"[",
"default",
".",
"BOOTDISK",
"]",
"=",
"_CleanZoneUrl",
"(",
"properties",
"[",
"default",
".",
"BOOTDISK",
"]",
")",
"if",
"default",
".",
"DISKS",
"in",
"properties",
":",
"for",
"disk",
"in",
"properties",
"[",
"default",
".",
"DISKS",
"]",
":",
"# Don't touch references to other disks",
"if",
"default",
".",
"DISK_SOURCE",
"in",
"disk",
":",
"continue",
"if",
"default",
".",
"INITIALIZEP",
"in",
"disk",
":",
"disk_init",
"=",
"disk",
"[",
"default",
".",
"INITIALIZEP",
"]",
"if",
"default",
".",
"DISKTYPE",
"in",
"disk_init",
":",
"disk_init",
"[",
"default",
".",
"DISKTYPE",
"]",
"=",
"_CleanZoneUrl",
"(",
"disk_init",
"[",
"default",
".",
"DISKTYPE",
"]",
")"
] | [
181,
0
] | [
203,
80
] | python | en | ['en', 'en', 'en'] | True |
FormatErrorsDec | (func) | Decorator to format exceptions if they get raised. | Decorator to format exceptions if they get raised. | def FormatErrorsDec(func):
"""Decorator to format exceptions if they get raised."""
def FormatErrorsWrap(context):
try:
return func(context)
except Exception as e:
raise Error(FormatException(e.message))
return FormatErrorsWrap | [
"def",
"FormatErrorsDec",
"(",
"func",
")",
":",
"def",
"FormatErrorsWrap",
"(",
"context",
")",
":",
"try",
":",
"return",
"func",
"(",
"context",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Error",
"(",
"FormatException",
"(",
"e",
".",
"message",
")",
")",
"return",
"FormatErrorsWrap"
] | [
218,
0
] | [
227,
25
] | python | en | ['en', 'en', 'en'] | True |
get_flatpages | (parser, token) |
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``for`` clause controls the user whose permissions are used in
determining which flatpages are visible.
An optional argument, ``starts_with``, limits the returned flatpages to
those beginning with a particular base URL. This argument can be a variable
or a string, as it resolves from the template context.
Syntax::
{% get_flatpages ['url_starts_with'] [for user] as context_name %}
Example usage::
{% get_flatpages as flatpages %}
{% get_flatpages for someuser as flatpages %}
{% get_flatpages '/about/' as about_pages %}
{% get_flatpages prefix as about_pages %}
{% get_flatpages '/about/' for someuser as about_pages %}
|
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause. | def get_flatpages(parser, token):
"""
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``for`` clause controls the user whose permissions are used in
determining which flatpages are visible.
An optional argument, ``starts_with``, limits the returned flatpages to
those beginning with a particular base URL. This argument can be a variable
or a string, as it resolves from the template context.
Syntax::
{% get_flatpages ['url_starts_with'] [for user] as context_name %}
Example usage::
{% get_flatpages as flatpages %}
{% get_flatpages for someuser as flatpages %}
{% get_flatpages '/about/' as about_pages %}
{% get_flatpages prefix as about_pages %}
{% get_flatpages '/about/' for someuser as about_pages %}
"""
bits = token.split_contents()
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
"['url_starts_with'] [for user] as context_name" %
{'tag_name': bits[0]})
# Must have at 3-6 bits in the tag
if 3 <= len(bits) <= 6:
# If there's an even number of bits, there's no prefix
if len(bits) % 2 == 0:
prefix = bits[1]
else:
prefix = None
# The very last bit must be the context name
if bits[-2] != 'as':
raise template.TemplateSyntaxError(syntax_message)
context_name = bits[-1]
# If there are 5 or 6 bits, there is a user defined
if len(bits) >= 5:
if bits[-4] != 'for':
raise template.TemplateSyntaxError(syntax_message)
user = bits[-3]
else:
user = None
return FlatpageNode(context_name, starts_with=prefix, user=user)
else:
raise template.TemplateSyntaxError(syntax_message) | [
"def",
"get_flatpages",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"syntax_message",
"=",
"(",
"\"%(tag_name)s expects a syntax of %(tag_name)s \"",
"\"['url_starts_with'] [for user] as context_name\"",
"%",
"{",
"'tag_name'",
":",
"bits",
"[",
"0",
"]",
"}",
")",
"# Must have at 3-6 bits in the tag",
"if",
"3",
"<=",
"len",
"(",
"bits",
")",
"<=",
"6",
":",
"# If there's an even number of bits, there's no prefix",
"if",
"len",
"(",
"bits",
")",
"%",
"2",
"==",
"0",
":",
"prefix",
"=",
"bits",
"[",
"1",
"]",
"else",
":",
"prefix",
"=",
"None",
"# The very last bit must be the context name",
"if",
"bits",
"[",
"-",
"2",
"]",
"!=",
"'as'",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"syntax_message",
")",
"context_name",
"=",
"bits",
"[",
"-",
"1",
"]",
"# If there are 5 or 6 bits, there is a user defined",
"if",
"len",
"(",
"bits",
")",
">=",
"5",
":",
"if",
"bits",
"[",
"-",
"4",
"]",
"!=",
"'for'",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"syntax_message",
")",
"user",
"=",
"bits",
"[",
"-",
"3",
"]",
"else",
":",
"user",
"=",
"None",
"return",
"FlatpageNode",
"(",
"context_name",
",",
"starts_with",
"=",
"prefix",
",",
"user",
"=",
"user",
")",
"else",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"syntax_message",
")"
] | [
45,
0
] | [
98,
58
] | python | en | ['en', 'error', 'th'] | False |
base64_encode | (string) | Base64 encode a string of bytes or text. The resulting bytes are
safe to use in URLs.
| Base64 encode a string of bytes or text. The resulting bytes are
safe to use in URLs.
| def base64_encode(string):
"""Base64 encode a string of bytes or text. The resulting bytes are
safe to use in URLs.
"""
string = want_bytes(string)
return base64.urlsafe_b64encode(string).rstrip(b"=") | [
"def",
"base64_encode",
"(",
"string",
")",
":",
"string",
"=",
"want_bytes",
"(",
"string",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"string",
")",
".",
"rstrip",
"(",
"b\"=\"",
")"
] | [
14,
0
] | [
19,
56
] | python | en | ['en', 'en', 'en'] | True |
base64_decode | (string) | Base64 decode a URL-safe string of bytes or text. The result is
bytes.
| Base64 decode a URL-safe string of bytes or text. The result is
bytes.
| def base64_decode(string):
"""Base64 decode a URL-safe string of bytes or text. The result is
bytes.
"""
string = want_bytes(string, encoding="ascii", errors="ignore")
string += b"=" * (-len(string) % 4)
try:
return base64.urlsafe_b64decode(string)
except (TypeError, ValueError):
raise BadData("Invalid base64-encoded data") | [
"def",
"base64_decode",
"(",
"string",
")",
":",
"string",
"=",
"want_bytes",
"(",
"string",
",",
"encoding",
"=",
"\"ascii\"",
",",
"errors",
"=",
"\"ignore\"",
")",
"string",
"+=",
"b\"=\"",
"*",
"(",
"-",
"len",
"(",
"string",
")",
"%",
"4",
")",
"try",
":",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"string",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"BadData",
"(",
"\"Invalid base64-encoded data\"",
")"
] | [
22,
0
] | [
32,
52
] | python | en | ['en', 'en', 'en'] | True |
default_key_func | (key, key_prefix, version) |
Default function to generate keys.
Construct the key used by all other methods. By default, prepend
the `key_prefix`. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
|
Default function to generate keys. | def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Construct the key used by all other methods. By default, prepend
the `key_prefix`. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
return '%s:%s:%s' % (key_prefix, version, key) | [
"def",
"default_key_func",
"(",
"key",
",",
"key_prefix",
",",
"version",
")",
":",
"return",
"'%s:%s:%s'",
"%",
"(",
"key_prefix",
",",
"version",
",",
"key",
")"
] | [
28,
0
] | [
36,
50
] | python | en | ['en', 'error', 'th'] | False |
get_key_func | (key_func) |
Function to decide which key function to use.
Default to ``default_key_func``.
|
Function to decide which key function to use. | def get_key_func(key_func):
"""
Function to decide which key function to use.
Default to ``default_key_func``.
"""
if key_func is not None:
if callable(key_func):
return key_func
else:
return import_string(key_func)
return default_key_func | [
"def",
"get_key_func",
"(",
"key_func",
")",
":",
"if",
"key_func",
"is",
"not",
"None",
":",
"if",
"callable",
"(",
"key_func",
")",
":",
"return",
"key_func",
"else",
":",
"return",
"import_string",
"(",
"key_func",
")",
"return",
"default_key_func"
] | [
39,
0
] | [
50,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.get_backend_timeout | (self, timeout=DEFAULT_TIMEOUT) |
Return the timeout value usable by this backend based upon the provided
timeout.
|
Return the timeout value usable by this backend based upon the provided
timeout.
| def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
"""
Return the timeout value usable by this backend based upon the provided
timeout.
"""
if timeout == DEFAULT_TIMEOUT:
timeout = self.default_timeout
elif timeout == 0:
# ticket 21147 - avoid time.time() related precision issues
timeout = -1
return None if timeout is None else time.time() + timeout | [
"def",
"get_backend_timeout",
"(",
"self",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"timeout",
"==",
"DEFAULT_TIMEOUT",
":",
"timeout",
"=",
"self",
".",
"default_timeout",
"elif",
"timeout",
"==",
"0",
":",
"# ticket 21147 - avoid time.time() related precision issues",
"timeout",
"=",
"-",
"1",
"return",
"None",
"if",
"timeout",
"is",
"None",
"else",
"time",
".",
"time",
"(",
")",
"+",
"timeout"
] | [
82,
4
] | [
92,
65
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.make_key | (self, key, version=None) |
Construct the key used by all other methods. By default, use the
key_func to generate a key (which, by default, prepends the
`key_prefix' and 'version'). A different key function can be provided
at the time of cache construction; alternatively, you can subclass the
cache backend to provide custom key making behavior.
|
Construct the key used by all other methods. By default, use the
key_func to generate a key (which, by default, prepends the
`key_prefix' and 'version'). A different key function can be provided
at the time of cache construction; alternatively, you can subclass the
cache backend to provide custom key making behavior.
| def make_key(self, key, version=None):
"""
Construct the key used by all other methods. By default, use the
key_func to generate a key (which, by default, prepends the
`key_prefix' and 'version'). A different key function can be provided
at the time of cache construction; alternatively, you can subclass the
cache backend to provide custom key making behavior.
"""
if version is None:
version = self.version
return self.key_func(key, self.key_prefix, version) | [
"def",
"make_key",
"(",
"self",
",",
"key",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"self",
".",
"version",
"return",
"self",
".",
"key_func",
"(",
"key",
",",
"self",
".",
"key_prefix",
",",
"version",
")"
] | [
94,
4
] | [
105,
59
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.add | (self, key, value, timeout=DEFAULT_TIMEOUT, version=None) |
Set a value in the cache if the key does not already exist. If
timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
Return True if the value was stored, False otherwise.
|
Set a value in the cache if the key does not already exist. If
timeout is given, use that timeout for the key; otherwise use the
default cache timeout. | def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
"""
Set a value in the cache if the key does not already exist. If
timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
Return True if the value was stored, False otherwise.
"""
raise NotImplementedError('subclasses of BaseCache must provide an add() method') | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"version",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide an add() method'",
")"
] | [
107,
4
] | [
115,
89
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.get | (self, key, default=None, version=None) |
Fetch a given key from the cache. If the key does not exist, return
default, which itself defaults to None.
|
Fetch a given key from the cache. If the key does not exist, return
default, which itself defaults to None.
| def get(self, key, default=None, version=None):
"""
Fetch a given key from the cache. If the key does not exist, return
default, which itself defaults to None.
"""
raise NotImplementedError('subclasses of BaseCache must provide a get() method') | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide a get() method'",
")"
] | [
117,
4
] | [
122,
88
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.set | (self, key, value, timeout=DEFAULT_TIMEOUT, version=None) |
Set a value in the cache. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
|
Set a value in the cache. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
| def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
"""
Set a value in the cache. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
"""
raise NotImplementedError('subclasses of BaseCache must provide a set() method') | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"version",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide a set() method'",
")"
] | [
124,
4
] | [
129,
88
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.touch | (self, key, timeout=DEFAULT_TIMEOUT, version=None) |
Update the key's expiry time using timeout. Return True if successful
or False if the key does not exist.
|
Update the key's expiry time using timeout. Return True if successful
or False if the key does not exist.
| def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):
"""
Update the key's expiry time using timeout. Return True if successful
or False if the key does not exist.
"""
raise NotImplementedError('subclasses of BaseCache must provide a touch() method') | [
"def",
"touch",
"(",
"self",
",",
"key",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"version",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide a touch() method'",
")"
] | [
131,
4
] | [
136,
90
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.delete | (self, key, version=None) |
Delete a key from the cache and return whether it succeeded, failing
silently.
|
Delete a key from the cache and return whether it succeeded, failing
silently.
| def delete(self, key, version=None):
"""
Delete a key from the cache and return whether it succeeded, failing
silently.
"""
raise NotImplementedError('subclasses of BaseCache must provide a delete() method') | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"version",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide a delete() method'",
")"
] | [
138,
4
] | [
143,
91
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.get_many | (self, keys, version=None) |
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Return a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.
|
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values. | def get_many(self, keys, version=None):
"""
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Return a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.
"""
d = {}
for k in keys:
val = self.get(k, self._missing_key, version=version)
if val is not self._missing_key:
d[k] = val
return d | [
"def",
"get_many",
"(",
"self",
",",
"keys",
",",
"version",
"=",
"None",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"val",
"=",
"self",
".",
"get",
"(",
"k",
",",
"self",
".",
"_missing_key",
",",
"version",
"=",
"version",
")",
"if",
"val",
"is",
"not",
"self",
".",
"_missing_key",
":",
"d",
"[",
"k",
"]",
"=",
"val",
"return",
"d"
] | [
145,
4
] | [
158,
16
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.get_or_set | (self, key, default, timeout=DEFAULT_TIMEOUT, version=None) |
Fetch a given key from the cache. If the key does not exist,
add the key and set it to the default value. The default value can
also be any callable. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
Return the value of the key stored or retrieved.
|
Fetch a given key from the cache. If the key does not exist,
add the key and set it to the default value. The default value can
also be any callable. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout. | def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None):
"""
Fetch a given key from the cache. If the key does not exist,
add the key and set it to the default value. The default value can
also be any callable. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
Return the value of the key stored or retrieved.
"""
val = self.get(key, self._missing_key, version=version)
if val is self._missing_key:
if callable(default):
default = default()
self.add(key, default, timeout=timeout, version=version)
# Fetch the value again to avoid a race condition if another caller
# added a value between the first get() and the add() above.
return self.get(key, default, version=version)
return val | [
"def",
"get_or_set",
"(",
"self",
",",
"key",
",",
"default",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"version",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"get",
"(",
"key",
",",
"self",
".",
"_missing_key",
",",
"version",
"=",
"version",
")",
"if",
"val",
"is",
"self",
".",
"_missing_key",
":",
"if",
"callable",
"(",
"default",
")",
":",
"default",
"=",
"default",
"(",
")",
"self",
".",
"add",
"(",
"key",
",",
"default",
",",
"timeout",
"=",
"timeout",
",",
"version",
"=",
"version",
")",
"# Fetch the value again to avoid a race condition if another caller",
"# added a value between the first get() and the add() above.",
"return",
"self",
".",
"get",
"(",
"key",
",",
"default",
",",
"version",
"=",
"version",
")",
"return",
"val"
] | [
160,
4
] | [
177,
18
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.has_key | (self, key, version=None) |
Return True if the key is in the cache and has not expired.
|
Return True if the key is in the cache and has not expired.
| def has_key(self, key, version=None):
"""
Return True if the key is in the cache and has not expired.
"""
return self.get(key, self._missing_key, version=version) is not self._missing_key | [
"def",
"has_key",
"(",
"self",
",",
"key",
",",
"version",
"=",
"None",
")",
":",
"return",
"self",
".",
"get",
"(",
"key",
",",
"self",
".",
"_missing_key",
",",
"version",
"=",
"version",
")",
"is",
"not",
"self",
".",
"_missing_key"
] | [
179,
4
] | [
183,
89
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.incr | (self, key, delta=1, version=None) |
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
|
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
| def incr(self, key, delta=1, version=None):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key, self._missing_key, version=version)
if value is self._missing_key:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.set(key, new_value, version=version)
return new_value | [
"def",
"incr",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
",",
"version",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"self",
".",
"_missing_key",
",",
"version",
"=",
"version",
")",
"if",
"value",
"is",
"self",
".",
"_missing_key",
":",
"raise",
"ValueError",
"(",
"\"Key '%s' not found\"",
"%",
"key",
")",
"new_value",
"=",
"value",
"+",
"delta",
"self",
".",
"set",
"(",
"key",
",",
"new_value",
",",
"version",
"=",
"version",
")",
"return",
"new_value"
] | [
185,
4
] | [
195,
24
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.decr | (self, key, delta=1, version=None) |
Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.
|
Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.
| def decr(self, key, delta=1, version=None):
"""
Subtract delta from value in the cache. If the key does not exist, raise
a ValueError exception.
"""
return self.incr(key, -delta, version=version) | [
"def",
"decr",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
",",
"version",
"=",
"None",
")",
":",
"return",
"self",
".",
"incr",
"(",
"key",
",",
"-",
"delta",
",",
"version",
"=",
"version",
")"
] | [
197,
4
] | [
202,
54
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.__contains__ | (self, key) |
Return True if the key is in the cache and has not expired.
|
Return True if the key is in the cache and has not expired.
| def __contains__(self, key):
"""
Return True if the key is in the cache and has not expired.
"""
# This is a separate method, rather than just a copy of has_key(),
# so that it always has the same functionality as has_key(), even
# if a subclass overrides it.
return self.has_key(key) | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"# This is a separate method, rather than just a copy of has_key(),",
"# so that it always has the same functionality as has_key(), even",
"# if a subclass overrides it.",
"return",
"self",
".",
"has_key",
"(",
"key",
")"
] | [
204,
4
] | [
211,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.set_many | (self, data, timeout=DEFAULT_TIMEOUT, version=None) |
Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
On backends that support it, return a list of keys that failed
insertion, or an empty list if all keys were inserted successfully.
|
Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times. | def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None):
"""
Set a bunch of values in the cache at once from a dict of key/value
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
On backends that support it, return a list of keys that failed
insertion, or an empty list if all keys were inserted successfully.
"""
for key, value in data.items():
self.set(key, value, timeout=timeout, version=version)
return [] | [
"def",
"set_many",
"(",
"self",
",",
"data",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"version",
"=",
"None",
")",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"timeout",
"=",
"timeout",
",",
"version",
"=",
"version",
")",
"return",
"[",
"]"
] | [
213,
4
] | [
227,
17
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.delete_many | (self, keys, version=None) |
Delete a bunch of values in the cache at once. For certain backends
(memcached), this is much more efficient than calling delete() multiple
times.
|
Delete a bunch of values in the cache at once. For certain backends
(memcached), this is much more efficient than calling delete() multiple
times.
| def delete_many(self, keys, version=None):
"""
Delete a bunch of values in the cache at once. For certain backends
(memcached), this is much more efficient than calling delete() multiple
times.
"""
for key in keys:
self.delete(key, version=version) | [
"def",
"delete_many",
"(",
"self",
",",
"keys",
",",
"version",
"=",
"None",
")",
":",
"for",
"key",
"in",
"keys",
":",
"self",
".",
"delete",
"(",
"key",
",",
"version",
"=",
"version",
")"
] | [
229,
4
] | [
236,
45
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.clear | (self) | Remove *all* values from the cache at once. | Remove *all* values from the cache at once. | def clear(self):
"""Remove *all* values from the cache at once."""
raise NotImplementedError('subclasses of BaseCache must provide a clear() method') | [
"def",
"clear",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCache must provide a clear() method'",
")"
] | [
238,
4
] | [
240,
90
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.validate_key | (self, key) |
Warn about keys that would not be portable to the memcached
backend. This encourages (but does not force) writing backend-portable
cache code.
|
Warn about keys that would not be portable to the memcached
backend. This encourages (but does not force) writing backend-portable
cache code.
| def validate_key(self, key):
"""
Warn about keys that would not be portable to the memcached
backend. This encourages (but does not force) writing backend-portable
cache code.
"""
for warning in memcache_key_warnings(key):
warnings.warn(warning, CacheKeyWarning) | [
"def",
"validate_key",
"(",
"self",
",",
"key",
")",
":",
"for",
"warning",
"in",
"memcache_key_warnings",
"(",
"key",
")",
":",
"warnings",
".",
"warn",
"(",
"warning",
",",
"CacheKeyWarning",
")"
] | [
242,
4
] | [
249,
51
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.incr_version | (self, key, delta=1, version=None) |
Add delta to the cache version for the supplied key. Return the new
version.
|
Add delta to the cache version for the supplied key. Return the new
version.
| def incr_version(self, key, delta=1, version=None):
"""
Add delta to the cache version for the supplied key. Return the new
version.
"""
if version is None:
version = self.version
value = self.get(key, self._missing_key, version=version)
if value is self._missing_key:
raise ValueError("Key '%s' not found" % key)
self.set(key, value, version=version + delta)
self.delete(key, version=version)
return version + delta | [
"def",
"incr_version",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"self",
".",
"version",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"self",
".",
"_missing_key",
",",
"version",
"=",
"version",
")",
"if",
"value",
"is",
"self",
".",
"_missing_key",
":",
"raise",
"ValueError",
"(",
"\"Key '%s' not found\"",
"%",
"key",
")",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"version",
"=",
"version",
"+",
"delta",
")",
"self",
".",
"delete",
"(",
"key",
",",
"version",
"=",
"version",
")",
"return",
"version",
"+",
"delta"
] | [
251,
4
] | [
265,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.decr_version | (self, key, delta=1, version=None) |
Subtract delta from the cache version for the supplied key. Return the
new version.
|
Subtract delta from the cache version for the supplied key. Return the
new version.
| def decr_version(self, key, delta=1, version=None):
"""
Subtract delta from the cache version for the supplied key. Return the
new version.
"""
return self.incr_version(key, -delta, version) | [
"def",
"decr_version",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
",",
"version",
"=",
"None",
")",
":",
"return",
"self",
".",
"incr_version",
"(",
"key",
",",
"-",
"delta",
",",
"version",
")"
] | [
267,
4
] | [
272,
54
] | python | en | ['en', 'error', 'th'] | False |
BaseCache.close | (self, **kwargs) | Close the cache connection | Close the cache connection | def close(self, **kwargs):
"""Close the cache connection"""
pass | [
"def",
"close",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | [
274,
4
] | [
276,
12
] | python | en | ['en', 'en', 'en'] | True |
literals | (choices, prefix="", suffix="") |
Create a regex from a space-separated list of literal `choices`.
If provided, `prefix` and `suffix` will be attached to each choice
individually.
|
Create a regex from a space-separated list of literal `choices`. | def literals(choices, prefix="", suffix=""):
"""
Create a regex from a space-separated list of literal `choices`.
If provided, `prefix` and `suffix` will be attached to each choice
individually.
"""
return "|".join(prefix + re.escape(c) + suffix for c in choices.split()) | [
"def",
"literals",
"(",
"choices",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"return",
"\"|\"",
".",
"join",
"(",
"prefix",
"+",
"re",
".",
"escape",
"(",
"c",
")",
"+",
"suffix",
"for",
"c",
"in",
"choices",
".",
"split",
"(",
")",
")"
] | [
19,
0
] | [
26,
76
] | python | en | ['en', 'error', 'th'] | False |
prepare_js_for_gettext | (js) |
Convert the Javascript source `js` into something resembling C for
xgettext.
What actually happens is that all the regex literals are replaced with
"REGEX".
|
Convert the Javascript source `js` into something resembling C for
xgettext. | def prepare_js_for_gettext(js):
"""
Convert the Javascript source `js` into something resembling C for
xgettext.
What actually happens is that all the regex literals are replaced with
"REGEX".
"""
def escape_quotes(m):
"""Used in a regex to properly escape double quotes."""
s = m[0]
if s == '"':
return r'\"'
else:
return s
lexer = JsLexer()
c = []
for name, tok in lexer.lex(js):
if name == 'regex':
# C doesn't grok regexes, and they aren't needed for gettext,
# so just output a string instead.
tok = '"REGEX"'
elif name == 'string':
# C doesn't have single-quoted strings, so make all strings
# double-quoted.
if tok.startswith("'"):
guts = re.sub(r"\\.|.", escape_quotes, tok[1:-1])
tok = '"' + guts + '"'
elif name == 'id':
# C can't deal with Unicode escapes in identifiers. We don't
# need them for gettext anyway, so replace them with something
# innocuous
tok = tok.replace("\\", "U")
c.append(tok)
return ''.join(c) | [
"def",
"prepare_js_for_gettext",
"(",
"js",
")",
":",
"def",
"escape_quotes",
"(",
"m",
")",
":",
"\"\"\"Used in a regex to properly escape double quotes.\"\"\"",
"s",
"=",
"m",
"[",
"0",
"]",
"if",
"s",
"==",
"'\"'",
":",
"return",
"r'\\\"'",
"else",
":",
"return",
"s",
"lexer",
"=",
"JsLexer",
"(",
")",
"c",
"=",
"[",
"]",
"for",
"name",
",",
"tok",
"in",
"lexer",
".",
"lex",
"(",
"js",
")",
":",
"if",
"name",
"==",
"'regex'",
":",
"# C doesn't grok regexes, and they aren't needed for gettext,",
"# so just output a string instead.",
"tok",
"=",
"'\"REGEX\"'",
"elif",
"name",
"==",
"'string'",
":",
"# C doesn't have single-quoted strings, so make all strings",
"# double-quoted.",
"if",
"tok",
".",
"startswith",
"(",
"\"'\"",
")",
":",
"guts",
"=",
"re",
".",
"sub",
"(",
"r\"\\\\.|.\"",
",",
"escape_quotes",
",",
"tok",
"[",
"1",
":",
"-",
"1",
"]",
")",
"tok",
"=",
"'\"'",
"+",
"guts",
"+",
"'\"'",
"elif",
"name",
"==",
"'id'",
":",
"# C can't deal with Unicode escapes in identifiers. We don't",
"# need them for gettext anyway, so replace them with something",
"# innocuous",
"tok",
"=",
"tok",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"U\"",
")",
"c",
".",
"append",
"(",
"tok",
")",
"return",
"''",
".",
"join",
"(",
"c",
")"
] | [
184,
0
] | [
219,
21
] | python | en | ['en', 'error', 'th'] | False |
Lexer.lex | (self, text) |
Lexically analyze `text`.
Yield pairs (`name`, `tokentext`).
|
Lexically analyze `text`. | def lex(self, text):
"""
Lexically analyze `text`.
Yield pairs (`name`, `tokentext`).
"""
end = len(text)
state = self.state
regexes = self.regexes
toks = self.toks
start = 0
while start < end:
for match in regexes[state].finditer(text, start):
name = match.lastgroup
tok = toks[name]
toktext = match[name]
start += len(toktext)
yield (tok.name, toktext)
if tok.next:
state = tok.next
break
self.state = state | [
"def",
"lex",
"(",
"self",
",",
"text",
")",
":",
"end",
"=",
"len",
"(",
"text",
")",
"state",
"=",
"self",
".",
"state",
"regexes",
"=",
"self",
".",
"regexes",
"toks",
"=",
"self",
".",
"toks",
"start",
"=",
"0",
"while",
"start",
"<",
"end",
":",
"for",
"match",
"in",
"regexes",
"[",
"state",
"]",
".",
"finditer",
"(",
"text",
",",
"start",
")",
":",
"name",
"=",
"match",
".",
"lastgroup",
"tok",
"=",
"toks",
"[",
"name",
"]",
"toktext",
"=",
"match",
"[",
"name",
"]",
"start",
"+=",
"len",
"(",
"toktext",
")",
"yield",
"(",
"tok",
".",
"name",
",",
"toktext",
")",
"if",
"tok",
".",
"next",
":",
"state",
"=",
"tok",
".",
"next",
"break",
"self",
".",
"state",
"=",
"state"
] | [
48,
4
] | [
72,
26
] | python | en | ['en', 'error', 'th'] | False |
sql_flush | (style, connection, reset_sequences=True, allow_cascade=False) |
Return a list of the SQL statements used to flush the database.
|
Return a list of the SQL statements used to flush the database.
| def sql_flush(style, connection, reset_sequences=True, allow_cascade=False):
"""
Return a list of the SQL statements used to flush the database.
"""
tables = connection.introspection.django_table_names(only_existing=True, include_views=False)
return connection.ops.sql_flush(
style,
tables,
reset_sequences=reset_sequences,
allow_cascade=allow_cascade,
) | [
"def",
"sql_flush",
"(",
"style",
",",
"connection",
",",
"reset_sequences",
"=",
"True",
",",
"allow_cascade",
"=",
"False",
")",
":",
"tables",
"=",
"connection",
".",
"introspection",
".",
"django_table_names",
"(",
"only_existing",
"=",
"True",
",",
"include_views",
"=",
"False",
")",
"return",
"connection",
".",
"ops",
".",
"sql_flush",
"(",
"style",
",",
"tables",
",",
"reset_sequences",
"=",
"reset_sequences",
",",
"allow_cascade",
"=",
"allow_cascade",
",",
")"
] | [
4,
0
] | [
14,
5
] | python | en | ['en', 'error', 'th'] | False |
_get_project_id | () | Get project ID from default GCP connection. | Get project ID from default GCP connection. | def _get_project_id():
"""Get project ID from default GCP connection."""
extras = BaseHook.get_connection("google_cloud_default").extra_dejson
key = "extra__google_cloud_platform__project"
if key in extras:
project_id = extras[key]
else:
raise ("Must configure project_id in google_cloud_default "
"connection from Airflow Console")
return project_id | [
"def",
"_get_project_id",
"(",
")",
":",
"extras",
"=",
"BaseHook",
".",
"get_connection",
"(",
"\"google_cloud_default\"",
")",
".",
"extra_dejson",
"key",
"=",
"\"extra__google_cloud_platform__project\"",
"if",
"key",
"in",
"extras",
":",
"project_id",
"=",
"extras",
"[",
"key",
"]",
"else",
":",
"raise",
"(",
"\"Must configure project_id in google_cloud_default \"",
"\"connection from Airflow Console\"",
")",
"return",
"project_id"
] | [
33,
0
] | [
43,
19
] | python | en | ['en', 'en', 'en'] | True |
filter_detections | (detections, score_threshold=0.3, nms_iou_threshold=0.5, max_size=None) |
Remove detections with a low probability, run Non-maximum Suppression. If set, apply max size to all boxes.
:param detections: Tensor with detections in form [ymin, xmin, ymax, xmax, label, probability].
:param score_threshold: Minimal probability of a detection to be included in the result.
:param nms_iou_threshold: Threshold for deciding whether boxes overlap too much with respect to IOU.
:param max_size: Max size to strip the given bounding boxes, default: None = no stripping.
:return: Filtered bounding boxes.
|
Remove detections with a low probability, run Non-maximum Suppression. If set, apply max size to all boxes. | def filter_detections(detections, score_threshold=0.3, nms_iou_threshold=0.5, max_size=None):
"""
Remove detections with a low probability, run Non-maximum Suppression. If set, apply max size to all boxes.
:param detections: Tensor with detections in form [ymin, xmin, ymax, xmax, label, probability].
:param score_threshold: Minimal probability of a detection to be included in the result.
:param nms_iou_threshold: Threshold for deciding whether boxes overlap too much with respect to IOU.
:param max_size: Max size to strip the given bounding boxes, default: None = no stripping.
:return: Filtered bounding boxes.
"""
mask = detections[:, 4] >= score_threshold
result = tf.boolean_mask(detections, mask)
bboxes, labels, scores = result[:, 0:4], result[:, 5], result[:, 4]
if max_size is not None:
bboxes = tf.clip_by_value(tf.cast(bboxes, tf.float32), 0.0, max_size)
if tf.shape(bboxes)[0] == 0:
return tf.constant([], shape=(0, 6))
max_objects = tf.shape(result)[0]
selected_indices = tf.image.non_max_suppression(bboxes, scores, max_objects, iou_threshold=nms_iou_threshold)
selected_boxes = tf.gather(bboxes, selected_indices)
selected_labels = tf.gather(labels, selected_indices)
selected_scores = tf.gather(scores, selected_indices)
detections = tf.concat(
[selected_boxes, tf.expand_dims(selected_scores, axis=1), tf.expand_dims(selected_labels, axis=1)], axis=1
)
return detections | [
"def",
"filter_detections",
"(",
"detections",
",",
"score_threshold",
"=",
"0.3",
",",
"nms_iou_threshold",
"=",
"0.5",
",",
"max_size",
"=",
"None",
")",
":",
"mask",
"=",
"detections",
"[",
":",
",",
"4",
"]",
">=",
"score_threshold",
"result",
"=",
"tf",
".",
"boolean_mask",
"(",
"detections",
",",
"mask",
")",
"bboxes",
",",
"labels",
",",
"scores",
"=",
"result",
"[",
":",
",",
"0",
":",
"4",
"]",
",",
"result",
"[",
":",
",",
"5",
"]",
",",
"result",
"[",
":",
",",
"4",
"]",
"if",
"max_size",
"is",
"not",
"None",
":",
"bboxes",
"=",
"tf",
".",
"clip_by_value",
"(",
"tf",
".",
"cast",
"(",
"bboxes",
",",
"tf",
".",
"float32",
")",
",",
"0.0",
",",
"max_size",
")",
"if",
"tf",
".",
"shape",
"(",
"bboxes",
")",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"tf",
".",
"constant",
"(",
"[",
"]",
",",
"shape",
"=",
"(",
"0",
",",
"6",
")",
")",
"max_objects",
"=",
"tf",
".",
"shape",
"(",
"result",
")",
"[",
"0",
"]",
"selected_indices",
"=",
"tf",
".",
"image",
".",
"non_max_suppression",
"(",
"bboxes",
",",
"scores",
",",
"max_objects",
",",
"iou_threshold",
"=",
"nms_iou_threshold",
")",
"selected_boxes",
"=",
"tf",
".",
"gather",
"(",
"bboxes",
",",
"selected_indices",
")",
"selected_labels",
"=",
"tf",
".",
"gather",
"(",
"labels",
",",
"selected_indices",
")",
"selected_scores",
"=",
"tf",
".",
"gather",
"(",
"scores",
",",
"selected_indices",
")",
"detections",
"=",
"tf",
".",
"concat",
"(",
"[",
"selected_boxes",
",",
"tf",
".",
"expand_dims",
"(",
"selected_scores",
",",
"axis",
"=",
"1",
")",
",",
"tf",
".",
"expand_dims",
"(",
"selected_labels",
",",
"axis",
"=",
"1",
")",
"]",
",",
"axis",
"=",
"1",
")",
"return",
"detections"
] | [
67,
0
] | [
96,
21
] | python | en | ['en', 'error', 'th'] | False |
Draw.settransform | (self, offset) | Sets a transformation offset. | Sets a transformation offset. | def settransform(self, offset):
"""Sets a transformation offset."""
(xoffset, yoffset) = offset
self.transform = (1, 0, xoffset, 0, 1, yoffset) | [
"def",
"settransform",
"(",
"self",
",",
"offset",
")",
":",
"(",
"xoffset",
",",
"yoffset",
")",
"=",
"offset",
"self",
".",
"transform",
"=",
"(",
"1",
",",
"0",
",",
"xoffset",
",",
"0",
",",
"1",
",",
"yoffset",
")"
] | [
92,
4
] | [
95,
55
] | python | en | ['en', 'en', 'en'] | True |
Draw.arc | (self, xy, start, end, *options) |
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box. | def arc(self, xy, start, end, *options):
"""
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
"""
self.render("arc", xy, start, end, *options) | [
"def",
"arc",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"arc\"",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")"
] | [
97,
4
] | [
104,
52
] | python | en | ['en', 'error', 'th'] | False |
Draw.chord | (self, xy, start, end, *options) |
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line. | def chord(self, xy, start, end, *options):
"""
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
"""
self.render("chord", xy, start, end, *options) | [
"def",
"chord",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"chord\"",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")"
] | [
106,
4
] | [
113,
54
] | python | en | ['en', 'error', 'th'] | False |
Draw.ellipse | (self, xy, *options) |
Draws an ellipse inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
Draws an ellipse inside the given bounding box. | def ellipse(self, xy, *options):
"""
Draws an ellipse inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
"""
self.render("ellipse", xy, *options) | [
"def",
"ellipse",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"ellipse\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
115,
4
] | [
121,
44
] | python | en | ['en', 'error', 'th'] | False |
Draw.line | (self, xy, *options) |
Draws a line between the coordinates in the ``xy`` list.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
Draws a line between the coordinates in the ``xy`` list. | def line(self, xy, *options):
"""
Draws a line between the coordinates in the ``xy`` list.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
"""
self.render("line", xy, *options) | [
"def",
"line",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"line\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
123,
4
] | [
129,
41
] | python | en | ['en', 'error', 'th'] | False |
Draw.pieslice | (self, xy, start, end, *options) |
Same as arc, but also draws straight lines between the end points and the
center of the bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
Same as arc, but also draws straight lines between the end points and the
center of the bounding box. | def pieslice(self, xy, start, end, *options):
"""
Same as arc, but also draws straight lines between the end points and the
center of the bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
"""
self.render("pieslice", xy, start, end, *options) | [
"def",
"pieslice",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"pieslice\"",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")"
] | [
131,
4
] | [
138,
57
] | python | en | ['en', 'error', 'th'] | False |
Draw.polygon | (self, xy, *options) |
Draws a polygon.
The polygon outline consists of straight lines between the given
coordinates, plus a straight line between the last and the first
coordinate.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
Draws a polygon. | def polygon(self, xy, *options):
"""
Draws a polygon.
The polygon outline consists of straight lines between the given
coordinates, plus a straight line between the last and the first
coordinate.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
"""
self.render("polygon", xy, *options) | [
"def",
"polygon",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"polygon\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
140,
4
] | [
151,
44
] | python | en | ['en', 'error', 'th'] | False |
Draw.rectangle | (self, xy, *options) |
Draws a rectangle.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
Draws a rectangle. | def rectangle(self, xy, *options):
"""
Draws a rectangle.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
"""
self.render("rectangle", xy, *options) | [
"def",
"rectangle",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"rectangle\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
153,
4
] | [
159,
46
] | python | en | ['en', 'error', 'th'] | False |
Draw.text | (self, xy, text, font) |
Draws the string at the given position.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
Draws the string at the given position. | def text(self, xy, text, font):
"""
Draws the string at the given position.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
"""
if self.transform:
xy = ImagePath.Path(xy)
xy.transform(self.transform)
self.draw.text(xy, text, font=font.font, fill=font.color) | [
"def",
"text",
"(",
"self",
",",
"xy",
",",
"text",
",",
"font",
")",
":",
"if",
"self",
".",
"transform",
":",
"xy",
"=",
"ImagePath",
".",
"Path",
"(",
"xy",
")",
"xy",
".",
"transform",
"(",
"self",
".",
"transform",
")",
"self",
".",
"draw",
".",
"text",
"(",
"xy",
",",
"text",
",",
"font",
"=",
"font",
".",
"font",
",",
"fill",
"=",
"font",
".",
"color",
")"
] | [
161,
4
] | [
170,
65
] | python | en | ['en', 'error', 'th'] | False |
Draw.textsize | (self, text, font) |
Return the size of the given string, in pixels.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize`
|
Return the size of the given string, in pixels. | def textsize(self, text, font):
"""
Return the size of the given string, in pixels.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize`
"""
return self.draw.textsize(text, font=font.font) | [
"def",
"textsize",
"(",
"self",
",",
"text",
",",
"font",
")",
":",
"return",
"self",
".",
"draw",
".",
"textsize",
"(",
"text",
",",
"font",
"=",
"font",
".",
"font",
")"
] | [
172,
4
] | [
178,
55
] | python | en | ['en', 'error', 'th'] | False |
MostPopular.__init__ | (self, train_file=None, test_file=None, output_file=None, as_binary=False, rank_length=10, sep='\t',
output_sep='\t') |
Most Popular for Item Recommendation
This algorithm predicts a rank for each user using the count of number of feedback of users and items
Usage::
>> MostPopular(train, test).compute()
>> MostPopular(train, test, as_binary=True).compute()
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_value).
:type train_file: str
:param test_file: File which contains the test set. This file needs to have at least 3 columns
(user item feedback_value).
:type test_file: str, default None
:param output_file: File with dir to write the final predictions
:type output_file: str, default None
:param rank_length: Size of the rank that must be generated by the predictions of the recommender algorithm
:type rank_length: int, default 10
:param as_binary: If True, the explicit feedback will be transform to binary
:type as_binary: bool, default False
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param output_sep: Delimiter for output file
:type output_sep: str, default '\t'
|
Most Popular for Item Recommendation | def __init__(self, train_file=None, test_file=None, output_file=None, as_binary=False, rank_length=10, sep='\t',
output_sep='\t'):
"""
Most Popular for Item Recommendation
This algorithm predicts a rank for each user using the count of number of feedback of users and items
Usage::
>> MostPopular(train, test).compute()
>> MostPopular(train, test, as_binary=True).compute()
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_value).
:type train_file: str
:param test_file: File which contains the test set. This file needs to have at least 3 columns
(user item feedback_value).
:type test_file: str, default None
:param output_file: File with dir to write the final predictions
:type output_file: str, default None
:param rank_length: Size of the rank that must be generated by the predictions of the recommender algorithm
:type rank_length: int, default 10
:param as_binary: If True, the explicit feedback will be transform to binary
:type as_binary: bool, default False
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param output_sep: Delimiter for output file
:type output_sep: str, default '\t'
"""
super(MostPopular, self).__init__(train_file=train_file, test_file=test_file, output_file=output_file,
as_binary=as_binary, rank_length=rank_length, sep=sep, output_sep=output_sep)
self.recommender_name = 'Most Popular' | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
"=",
"None",
",",
"test_file",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"as_binary",
"=",
"False",
",",
"rank_length",
"=",
"10",
",",
"sep",
"=",
"'\\t'",
",",
"output_sep",
"=",
"'\\t'",
")",
":",
"super",
"(",
"MostPopular",
",",
"self",
")",
".",
"__init__",
"(",
"train_file",
"=",
"train_file",
",",
"test_file",
"=",
"test_file",
",",
"output_file",
"=",
"output_file",
",",
"as_binary",
"=",
"as_binary",
",",
"rank_length",
"=",
"rank_length",
",",
"sep",
"=",
"sep",
",",
"output_sep",
"=",
"output_sep",
")",
"self",
".",
"recommender_name",
"=",
"'Most Popular'"
] | [
18,
4
] | [
58,
46
] | python | en | ['en', 'error', 'th'] | False |
MostPopular.predict | (self) |
This method predict final result, building an rank of each user of the train set.
|
This method predict final result, building an rank of each user of the train set. | def predict(self):
"""
This method predict final result, building an rank of each user of the train set.
"""
for user in set(self.users):
predictions = list()
for item in self.train_set['items_unobserved'].get(user, []):
if self.as_binary:
predictions.append((user, item, len(self.train_set['users_viewed_item'][item])))
else:
count_value = 0
for user_v in self.train_set['users_viewed_item'][item]:
count_value += self.train_set['feedback'][user_v][item]
predictions.append((user, item, count_value))
predictions = sorted(predictions, key=lambda x: -x[2])
self.ranking += predictions[:self.rank_length] | [
"def",
"predict",
"(",
"self",
")",
":",
"for",
"user",
"in",
"set",
"(",
"self",
".",
"users",
")",
":",
"predictions",
"=",
"list",
"(",
")",
"for",
"item",
"in",
"self",
".",
"train_set",
"[",
"'items_unobserved'",
"]",
".",
"get",
"(",
"user",
",",
"[",
"]",
")",
":",
"if",
"self",
".",
"as_binary",
":",
"predictions",
".",
"append",
"(",
"(",
"user",
",",
"item",
",",
"len",
"(",
"self",
".",
"train_set",
"[",
"'users_viewed_item'",
"]",
"[",
"item",
"]",
")",
")",
")",
"else",
":",
"count_value",
"=",
"0",
"for",
"user_v",
"in",
"self",
".",
"train_set",
"[",
"'users_viewed_item'",
"]",
"[",
"item",
"]",
":",
"count_value",
"+=",
"self",
".",
"train_set",
"[",
"'feedback'",
"]",
"[",
"user_v",
"]",
"[",
"item",
"]",
"predictions",
".",
"append",
"(",
"(",
"user",
",",
"item",
",",
"count_value",
")",
")",
"predictions",
"=",
"sorted",
"(",
"predictions",
",",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
"[",
"2",
"]",
")",
"self",
".",
"ranking",
"+=",
"predictions",
"[",
":",
"self",
".",
"rank_length",
"]"
] | [
60,
4
] | [
80,
58
] | python | en | ['en', 'error', 'th'] | False |
MostPopular.compute | (self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t') |
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
|
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm | def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'):
"""
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
"""
super(MostPopular, self).compute(verbose=verbose)
if verbose:
print("prediction_time:: %4f sec" % timed(self.predict))
print('\n')
else:
self.predict()
self.write_ranking()
if self.test_file is not None:
self.evaluate(metrics, verbose_evaluation, as_table=as_table, table_sep=table_sep) | [
"def",
"compute",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"metrics",
"=",
"None",
",",
"verbose_evaluation",
"=",
"True",
",",
"as_table",
"=",
"False",
",",
"table_sep",
"=",
"'\\t'",
")",
":",
"super",
"(",
"MostPopular",
",",
"self",
")",
".",
"compute",
"(",
"verbose",
"=",
"verbose",
")",
"if",
"verbose",
":",
"print",
"(",
"\"prediction_time:: %4f sec\"",
"%",
"timed",
"(",
"self",
".",
"predict",
")",
")",
"print",
"(",
"'\\n'",
")",
"else",
":",
"self",
".",
"predict",
"(",
")",
"self",
".",
"write_ranking",
"(",
")",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"self",
".",
"evaluate",
"(",
"metrics",
",",
"verbose_evaluation",
",",
"as_table",
"=",
"as_table",
",",
"table_sep",
"=",
"table_sep",
")"
] | [
82,
4
] | [
115,
94
] | python | en | ['en', 'error', 'th'] | False |
convert_type | (ty, default=None) | Converts a callable or python ty into the most appropriate param
ty.
| Converts a callable or python ty into the most appropriate param
ty.
| def convert_type(ty, default=None):
"""Converts a callable or python ty into the most appropriate param
ty.
"""
guessed_type = False
if ty is None and default is not None:
if isinstance(default, tuple):
ty = tuple(map(type, default))
else:
ty = type(default)
guessed_type = True
if isinstance(ty, tuple):
return Tuple(ty)
if isinstance(ty, ParamType):
return ty
if ty is text_type or ty is str or ty is None:
return STRING
if ty is int:
return INT
# Booleans are only okay if not guessed. This is done because for
# flags the default value is actually a bit of a lie in that it
# indicates which of the flags is the one we want. See get_default()
# for more information.
if ty is bool and not guessed_type:
return BOOL
if ty is float:
return FLOAT
if guessed_type:
return STRING
# Catch a common mistake
if __debug__:
try:
if issubclass(ty, ParamType):
raise AssertionError('Attempted to use an uninstantiated '
'parameter type (%s).' % ty)
except TypeError:
pass
return FuncParamType(ty) | [
"def",
"convert_type",
"(",
"ty",
",",
"default",
"=",
"None",
")",
":",
"guessed_type",
"=",
"False",
"if",
"ty",
"is",
"None",
"and",
"default",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"default",
",",
"tuple",
")",
":",
"ty",
"=",
"tuple",
"(",
"map",
"(",
"type",
",",
"default",
")",
")",
"else",
":",
"ty",
"=",
"type",
"(",
"default",
")",
"guessed_type",
"=",
"True",
"if",
"isinstance",
"(",
"ty",
",",
"tuple",
")",
":",
"return",
"Tuple",
"(",
"ty",
")",
"if",
"isinstance",
"(",
"ty",
",",
"ParamType",
")",
":",
"return",
"ty",
"if",
"ty",
"is",
"text_type",
"or",
"ty",
"is",
"str",
"or",
"ty",
"is",
"None",
":",
"return",
"STRING",
"if",
"ty",
"is",
"int",
":",
"return",
"INT",
"# Booleans are only okay if not guessed. This is done because for",
"# flags the default value is actually a bit of a lie in that it",
"# indicates which of the flags is the one we want. See get_default()",
"# for more information.",
"if",
"ty",
"is",
"bool",
"and",
"not",
"guessed_type",
":",
"return",
"BOOL",
"if",
"ty",
"is",
"float",
":",
"return",
"FLOAT",
"if",
"guessed_type",
":",
"return",
"STRING",
"# Catch a common mistake",
"if",
"__debug__",
":",
"try",
":",
"if",
"issubclass",
"(",
"ty",
",",
"ParamType",
")",
":",
"raise",
"AssertionError",
"(",
"'Attempted to use an uninstantiated '",
"'parameter type (%s).'",
"%",
"ty",
")",
"except",
"TypeError",
":",
"pass",
"return",
"FuncParamType",
"(",
"ty",
")"
] | [
594,
0
] | [
633,
28
] | python | en | ['en', 'en', 'en'] | True |
ParamType.get_metavar | (self, param) | Returns the metavar default for this param if it provides one. | Returns the metavar default for this param if it provides one. | def get_metavar(self, param):
"""Returns the metavar default for this param if it provides one.""" | [
"def",
"get_metavar",
"(",
"self",
",",
"param",
")",
":"
] | [
40,
4
] | [
41,
76
] | python | en | ['en', 'en', 'en'] | True |
ParamType.get_missing_message | (self, param) | Optionally might return extra information about a missing
parameter.
.. versionadded:: 2.0
| Optionally might return extra information about a missing
parameter. | def get_missing_message(self, param):
"""Optionally might return extra information about a missing
parameter.
.. versionadded:: 2.0
""" | [
"def",
"get_missing_message",
"(",
"self",
",",
"param",
")",
":"
] | [
43,
4
] | [
48,
11
] | python | en | ['en', 'en', 'en'] | True |
ParamType.convert | (self, value, param, ctx) | Converts the value. This is not invoked for values that are
`None` (the missing value).
| Converts the value. This is not invoked for values that are
`None` (the missing value).
| def convert(self, value, param, ctx):
"""Converts the value. This is not invoked for values that are
`None` (the missing value).
"""
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
",",
"param",
",",
"ctx",
")",
":",
"return",
"value"
] | [
50,
4
] | [
54,
20
] | python | en | ['en', 'en', 'en'] | True |
ParamType.split_envvar_value | (self, rv) | Given a value from an environment variable this splits it up
into small chunks depending on the defined envvar list splitter.
If the splitter is set to `None`, which means that whitespace splits,
then leading and trailing whitespace is ignored. Otherwise, leading
and trailing splitters usually lead to empty items being included.
| Given a value from an environment variable this splits it up
into small chunks depending on the defined envvar list splitter. | def split_envvar_value(self, rv):
"""Given a value from an environment variable this splits it up
into small chunks depending on the defined envvar list splitter.
If the splitter is set to `None`, which means that whitespace splits,
then leading and trailing whitespace is ignored. Otherwise, leading
and trailing splitters usually lead to empty items being included.
"""
return (rv or '').split(self.envvar_list_splitter) | [
"def",
"split_envvar_value",
"(",
"self",
",",
"rv",
")",
":",
"return",
"(",
"rv",
"or",
"''",
")",
".",
"split",
"(",
"self",
".",
"envvar_list_splitter",
")"
] | [
56,
4
] | [
64,
58
] | python | en | ['en', 'en', 'en'] | True |
ParamType.fail | (self, message, param=None, ctx=None) | Helper method to fail with an invalid value message. | Helper method to fail with an invalid value message. | def fail(self, message, param=None, ctx=None):
"""Helper method to fail with an invalid value message."""
raise BadParameter(message, ctx=ctx, param=param) | [
"def",
"fail",
"(",
"self",
",",
"message",
",",
"param",
"=",
"None",
",",
"ctx",
"=",
"None",
")",
":",
"raise",
"BadParameter",
"(",
"message",
",",
"ctx",
"=",
"ctx",
",",
"param",
"=",
"param",
")"
] | [
66,
4
] | [
68,
57
] | python | en | ['en', 'en', 'en'] | True |
from_datastore | (entity) | Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
{id: id, prop: val, ...}
| Translates Datastore results into the format expected by the
application. | def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
{id: id, prop: val, ...}
"""
if not entity:
return None
if isinstance(entity, builtin_list):
entity = entity.pop()
entity['id'] = entity.key.id
return entity | [
"def",
"from_datastore",
"(",
"entity",
")",
":",
"if",
"not",
"entity",
":",
"return",
"None",
"if",
"isinstance",
"(",
"entity",
",",
"builtin_list",
")",
":",
"entity",
"=",
"entity",
".",
"pop",
"(",
")",
"entity",
"[",
"'id'",
"]",
"=",
"entity",
".",
"key",
".",
"id",
"return",
"entity"
] | [
29,
0
] | [
45,
17
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.spatial_version | (self) | Determine the version of the SpatiaLite library. | Determine the version of the SpatiaLite library. | def spatial_version(self):
"""Determine the version of the SpatiaLite library."""
try:
version = self.spatialite_version_tuple()[1:]
except Exception as exc:
raise ImproperlyConfigured(
'Cannot determine the SpatiaLite version for the "%s" database. '
'Was the SpatiaLite initialization SQL loaded on this database?' % (
self.connection.settings_dict['NAME'],
)
) from exc
if version < (4, 3, 0):
raise ImproperlyConfigured('GeoDjango supports SpatiaLite 4.3.0 and above.')
return version | [
"def",
"spatial_version",
"(",
"self",
")",
":",
"try",
":",
"version",
"=",
"self",
".",
"spatialite_version_tuple",
"(",
")",
"[",
"1",
":",
"]",
"except",
"Exception",
"as",
"exc",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Cannot determine the SpatiaLite version for the \"%s\" database. '",
"'Was the SpatiaLite initialization SQL loaded on this database?'",
"%",
"(",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'NAME'",
"]",
",",
")",
")",
"from",
"exc",
"if",
"version",
"<",
"(",
"4",
",",
"3",
",",
"0",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'GeoDjango supports SpatiaLite 4.3.0 and above.'",
")",
"return",
"version"
] | [
88,
4
] | [
101,
22
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.convert_extent | (self, box) |
Convert the polygon data received from SpatiaLite to min/max values.
|
Convert the polygon data received from SpatiaLite to min/max values.
| def convert_extent(self, box):
"""
Convert the polygon data received from SpatiaLite to min/max values.
"""
if box is None:
return None
shell = GEOSGeometry(box).shell
xmin, ymin = shell[0][:2]
xmax, ymax = shell[2][:2]
return (xmin, ymin, xmax, ymax) | [
"def",
"convert_extent",
"(",
"self",
",",
"box",
")",
":",
"if",
"box",
"is",
"None",
":",
"return",
"None",
"shell",
"=",
"GEOSGeometry",
"(",
"box",
")",
".",
"shell",
"xmin",
",",
"ymin",
"=",
"shell",
"[",
"0",
"]",
"[",
":",
"2",
"]",
"xmax",
",",
"ymax",
"=",
"shell",
"[",
"2",
"]",
"[",
":",
"2",
"]",
"return",
"(",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
")"
] | [
103,
4
] | [
112,
39
] | python | en | ['en', 'error', 'th'] | False |
SpatiaLiteOperations.geo_db_type | (self, f) |
Return None because geometry columns are added via the
`AddGeometryColumn` stored procedure on SpatiaLite.
|
Return None because geometry columns are added via the
`AddGeometryColumn` stored procedure on SpatiaLite.
| def geo_db_type(self, f):
"""
Return None because geometry columns are added via the
`AddGeometryColumn` stored procedure on SpatiaLite.
"""
return None | [
"def",
"geo_db_type",
"(",
"self",
",",
"f",
")",
":",
"return",
"None"
] | [
114,
4
] | [
119,
19
] | python | en | ['en', 'error', 'th'] | False |
SpatiaLiteOperations.get_distance | (self, f, value, lookup_type) |
Return the distance parameters for the given geometry field,
lookup value, and lookup type.
|
Return the distance parameters for the given geometry field,
lookup value, and lookup type.
| def get_distance(self, f, value, lookup_type):
"""
Return the distance parameters for the given geometry field,
lookup value, and lookup type.
"""
if not value:
return []
value = value[0]
if isinstance(value, Distance):
if f.geodetic(self.connection):
if lookup_type == 'dwithin':
raise ValueError(
'Only numeric values of degree units are allowed on '
'geographic DWithin queries.'
)
dist_param = value.m
else:
dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
else:
dist_param = value
return [dist_param] | [
"def",
"get_distance",
"(",
"self",
",",
"f",
",",
"value",
",",
"lookup_type",
")",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"value",
"=",
"value",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"value",
",",
"Distance",
")",
":",
"if",
"f",
".",
"geodetic",
"(",
"self",
".",
"connection",
")",
":",
"if",
"lookup_type",
"==",
"'dwithin'",
":",
"raise",
"ValueError",
"(",
"'Only numeric values of degree units are allowed on '",
"'geographic DWithin queries.'",
")",
"dist_param",
"=",
"value",
".",
"m",
"else",
":",
"dist_param",
"=",
"getattr",
"(",
"value",
",",
"Distance",
".",
"unit_attname",
"(",
"f",
".",
"units_name",
"(",
"self",
".",
"connection",
")",
")",
")",
"else",
":",
"dist_param",
"=",
"value",
"return",
"[",
"dist_param",
"]"
] | [
121,
4
] | [
141,
27
] | python | en | ['en', 'error', 'th'] | False |
SpatiaLiteOperations._get_spatialite_func | (self, func) |
Helper routine for calling SpatiaLite functions and returning
their result.
Any error occurring in this method should be handled by the caller.
|
Helper routine for calling SpatiaLite functions and returning
their result.
Any error occurring in this method should be handled by the caller.
| def _get_spatialite_func(self, func):
"""
Helper routine for calling SpatiaLite functions and returning
their result.
Any error occurring in this method should be handled by the caller.
"""
cursor = self.connection._cursor()
try:
cursor.execute('SELECT %s' % func)
row = cursor.fetchone()
finally:
cursor.close()
return row[0] | [
"def",
"_get_spatialite_func",
"(",
"self",
",",
"func",
")",
":",
"cursor",
"=",
"self",
".",
"connection",
".",
"_cursor",
"(",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"'SELECT %s'",
"%",
"func",
")",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")",
"return",
"row",
"[",
"0",
"]"
] | [
143,
4
] | [
155,
21
] | python | en | ['en', 'error', 'th'] | False |
SpatiaLiteOperations.geos_version | (self) | Return the version of GEOS used by SpatiaLite as a string. | Return the version of GEOS used by SpatiaLite as a string. | def geos_version(self):
"Return the version of GEOS used by SpatiaLite as a string."
return self._get_spatialite_func('geos_version()') | [
"def",
"geos_version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_spatialite_func",
"(",
"'geos_version()'",
")"
] | [
157,
4
] | [
159,
58
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.proj_version | (self) | Return the version of the PROJ library used by SpatiaLite. | Return the version of the PROJ library used by SpatiaLite. | def proj_version(self):
"""Return the version of the PROJ library used by SpatiaLite."""
return self._get_spatialite_func('proj4_version()') | [
"def",
"proj_version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_spatialite_func",
"(",
"'proj4_version()'",
")"
] | [
161,
4
] | [
163,
59
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.lwgeom_version | (self) | Return the version of LWGEOM library used by SpatiaLite. | Return the version of LWGEOM library used by SpatiaLite. | def lwgeom_version(self):
"""Return the version of LWGEOM library used by SpatiaLite."""
return self._get_spatialite_func('lwgeom_version()') | [
"def",
"lwgeom_version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_spatialite_func",
"(",
"'lwgeom_version()'",
")"
] | [
165,
4
] | [
167,
60
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.spatialite_version | (self) | Return the SpatiaLite library version as a string. | Return the SpatiaLite library version as a string. | def spatialite_version(self):
"Return the SpatiaLite library version as a string."
return self._get_spatialite_func('spatialite_version()') | [
"def",
"spatialite_version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_spatialite_func",
"(",
"'spatialite_version()'",
")"
] | [
169,
4
] | [
171,
64
] | python | en | ['en', 'en', 'en'] | True |
SpatiaLiteOperations.spatialite_version_tuple | (self) |
Return the SpatiaLite version as a tuple (version string, major,
minor, subminor).
|
Return the SpatiaLite version as a tuple (version string, major,
minor, subminor).
| def spatialite_version_tuple(self):
"""
Return the SpatiaLite version as a tuple (version string, major,
minor, subminor).
"""
version = self.spatialite_version()
return (version,) + get_version_tuple(version) | [
"def",
"spatialite_version_tuple",
"(",
"self",
")",
":",
"version",
"=",
"self",
".",
"spatialite_version",
"(",
")",
"return",
"(",
"version",
",",
")",
"+",
"get_version_tuple",
"(",
"version",
")"
] | [
173,
4
] | [
179,
54
] | python | en | ['en', 'error', 'th'] | False |
SpatiaLiteOperations.spatial_aggregate_name | (self, agg_name) |
Return the spatial aggregate SQL template and function for the
given Aggregate instance.
|
Return the spatial aggregate SQL template and function for the
given Aggregate instance.
| def spatial_aggregate_name(self, agg_name):
"""
Return the spatial aggregate SQL template and function for the
given Aggregate instance.
"""
agg_name = 'unionagg' if agg_name.lower() == 'union' else agg_name.lower()
return getattr(self, agg_name) | [
"def",
"spatial_aggregate_name",
"(",
"self",
",",
"agg_name",
")",
":",
"agg_name",
"=",
"'unionagg'",
"if",
"agg_name",
".",
"lower",
"(",
")",
"==",
"'union'",
"else",
"agg_name",
".",
"lower",
"(",
")",
"return",
"getattr",
"(",
"self",
",",
"agg_name",
")"
] | [
181,
4
] | [
187,
38
] | python | en | ['en', 'error', 'th'] | False |
handle_photo_save | (sender: ModelBase, instance: Photo, **kwargs) | log photo changes in audit | log photo changes in audit | def handle_photo_save(sender: ModelBase, instance: Photo, **kwargs):
""" log photo changes in audit """
label = instance._meta.app_label
model = instance._meta.model_name
verb = AuditVerbEnum.CREATED.value if kwargs.get('created') else AuditVerbEnum.UPDATED.value
# since images and album are created by users it is safe to
# assume the user created and updated them
user_id = instance.user_id
task_log_audit.apply_async(args=(user_id, verb, label, model, instance.id)) | [
"def",
"handle_photo_save",
"(",
"sender",
":",
"ModelBase",
",",
"instance",
":",
"Photo",
",",
"*",
"*",
"kwargs",
")",
":",
"label",
"=",
"instance",
".",
"_meta",
".",
"app_label",
"model",
"=",
"instance",
".",
"_meta",
".",
"model_name",
"verb",
"=",
"AuditVerbEnum",
".",
"CREATED",
".",
"value",
"if",
"kwargs",
".",
"get",
"(",
"'created'",
")",
"else",
"AuditVerbEnum",
".",
"UPDATED",
".",
"value",
"# since images and album are created by users it is safe to",
"# assume the user created and updated them",
"user_id",
"=",
"instance",
".",
"user_id",
"task_log_audit",
".",
"apply_async",
"(",
"args",
"=",
"(",
"user_id",
",",
"verb",
",",
"label",
",",
"model",
",",
"instance",
".",
"id",
")",
")"
] | [
11,
0
] | [
22,
79
] | python | en | ['en', 'en', 'en'] | True |
handle_album_save | (sender, instance: Album, **kwargs) | log album changes in audit | log album changes in audit | def handle_album_save(sender, instance: Album, **kwargs):
""" log album changes in audit """
label = instance._meta.app_label
model = instance._meta.model_name
verb = AuditVerbEnum.CREATED.value if kwargs.get('created') else AuditVerbEnum.UPDATED.value
# since images and album are created by users it is safe to
# assume the user created and updated them
user_id = instance.user_id
task_log_audit.apply_async(args=(user_id, verb, label, model, instance.id)) | [
"def",
"handle_album_save",
"(",
"sender",
",",
"instance",
":",
"Album",
",",
"*",
"*",
"kwargs",
")",
":",
"label",
"=",
"instance",
".",
"_meta",
".",
"app_label",
"model",
"=",
"instance",
".",
"_meta",
".",
"model_name",
"verb",
"=",
"AuditVerbEnum",
".",
"CREATED",
".",
"value",
"if",
"kwargs",
".",
"get",
"(",
"'created'",
")",
"else",
"AuditVerbEnum",
".",
"UPDATED",
".",
"value",
"# since images and album are created by users it is safe to",
"# assume the user created and updated them",
"user_id",
"=",
"instance",
".",
"user_id",
"task_log_audit",
".",
"apply_async",
"(",
"args",
"=",
"(",
"user_id",
",",
"verb",
",",
"label",
",",
"model",
",",
"instance",
".",
"id",
")",
")"
] | [
26,
0
] | [
37,
79
] | python | en | ['en', 'da', 'en'] | True |
_create_structure | (C, ball_x, ball_y, left=True) | Creates entire Goldberg machine structure. | Creates entire Goldberg machine structure. | def _create_structure(C, ball_x, ball_y, left=True):
"""Creates entire Goldberg machine structure."""
# Add ball.
ball = C.add('dynamic ball', scale=0.1) \
.set_center_x(ball_x * C.scene.width) \
.set_center_y(ball_y * C.scene.height)
# Add alley in which ball is located.
bottom_bar = C.add('static bar', scale=0.2) \
.set_top(ball.bottom)
top_bar = C.add('static bar', scale=0.1) \
.set_bottom(ball.top + 0.01 * C.scene.height)
if left:
bottom_bar.set_right(ball.right)
top_bar.set_right(ball.right)
else:
bottom_bar.set_left(ball.left)
top_bar.set_left(bottom_bar.left)
# Add stick that can be toppled over.
stick = C.add('dynamic bar', scale=0.12) \
.set_angle(90.) \
.set_bottom(bottom_bar.top)
if left:
stick.set_left(bottom_bar.left)
else:
stick.set_right(bottom_bar.right)
# Add downward facing bars.
vertical_bar = C.add('static bar', scale=1.0) \
.set_angle(90.) \
.set_top(bottom_bar.top)
if left:
vertical_bar.set_right(bottom_bar.right)
else:
vertical_bar.set_left(bottom_bar.left)
# Add downward facing bars.
if left:
vertical_bar_2 = C.add('static bar', scale=0.1) \
.set_bottom(stick.top + 0.2*C.scene.height) \
.set_left(stick.left)
else:
vertical_bar_2 = C.add('static bar', scale=0.1) \
.set_bottom(stick.top + 0.2*C.scene.height) \
.set_right(stick.right)
return ball, vertical_bar | [
"def",
"_create_structure",
"(",
"C",
",",
"ball_x",
",",
"ball_y",
",",
"left",
"=",
"True",
")",
":",
"# Add ball.",
"ball",
"=",
"C",
".",
"add",
"(",
"'dynamic ball'",
",",
"scale",
"=",
"0.1",
")",
".",
"set_center_x",
"(",
"ball_x",
"*",
"C",
".",
"scene",
".",
"width",
")",
".",
"set_center_y",
"(",
"ball_y",
"*",
"C",
".",
"scene",
".",
"height",
")",
"# Add alley in which ball is located.",
"bottom_bar",
"=",
"C",
".",
"add",
"(",
"'static bar'",
",",
"scale",
"=",
"0.2",
")",
".",
"set_top",
"(",
"ball",
".",
"bottom",
")",
"top_bar",
"=",
"C",
".",
"add",
"(",
"'static bar'",
",",
"scale",
"=",
"0.1",
")",
".",
"set_bottom",
"(",
"ball",
".",
"top",
"+",
"0.01",
"*",
"C",
".",
"scene",
".",
"height",
")",
"if",
"left",
":",
"bottom_bar",
".",
"set_right",
"(",
"ball",
".",
"right",
")",
"top_bar",
".",
"set_right",
"(",
"ball",
".",
"right",
")",
"else",
":",
"bottom_bar",
".",
"set_left",
"(",
"ball",
".",
"left",
")",
"top_bar",
".",
"set_left",
"(",
"bottom_bar",
".",
"left",
")",
"# Add stick that can be toppled over.",
"stick",
"=",
"C",
".",
"add",
"(",
"'dynamic bar'",
",",
"scale",
"=",
"0.12",
")",
".",
"set_angle",
"(",
"90.",
")",
".",
"set_bottom",
"(",
"bottom_bar",
".",
"top",
")",
"if",
"left",
":",
"stick",
".",
"set_left",
"(",
"bottom_bar",
".",
"left",
")",
"else",
":",
"stick",
".",
"set_right",
"(",
"bottom_bar",
".",
"right",
")",
"# Add downward facing bars.",
"vertical_bar",
"=",
"C",
".",
"add",
"(",
"'static bar'",
",",
"scale",
"=",
"1.0",
")",
".",
"set_angle",
"(",
"90.",
")",
".",
"set_top",
"(",
"bottom_bar",
".",
"top",
")",
"if",
"left",
":",
"vertical_bar",
".",
"set_right",
"(",
"bottom_bar",
".",
"right",
")",
"else",
":",
"vertical_bar",
".",
"set_left",
"(",
"bottom_bar",
".",
"left",
")",
"# Add downward facing bars.",
"if",
"left",
":",
"vertical_bar_2",
"=",
"C",
".",
"add",
"(",
"'static bar'",
",",
"scale",
"=",
"0.1",
")",
".",
"set_bottom",
"(",
"stick",
".",
"top",
"+",
"0.2",
"*",
"C",
".",
"scene",
".",
"height",
")",
".",
"set_left",
"(",
"stick",
".",
"left",
")",
"else",
":",
"vertical_bar_2",
"=",
"C",
".",
"add",
"(",
"'static bar'",
",",
"scale",
"=",
"0.1",
")",
".",
"set_bottom",
"(",
"stick",
".",
"top",
"+",
"0.2",
"*",
"C",
".",
"scene",
".",
"height",
")",
".",
"set_right",
"(",
"stick",
".",
"right",
")",
"return",
"ball",
",",
"vertical_bar"
] | [
61,
0
] | [
109,
29
] | python | en | ['fr', 'it', 'en'] | False |
_unicode_ci_compare | (s1, s2) |
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
|
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
| def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return unicodedata.normalize('NFKC', s1).casefold() == unicodedata.normalize('NFKC', s2).casefold() | [
"def",
"_unicode_ci_compare",
"(",
"s1",
",",
"s2",
")",
":",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"s1",
")",
".",
"casefold",
"(",
")",
"==",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"s2",
")",
".",
"casefold",
"(",
")"
] | [
23,
0
] | [
29,
103
] | python | en | ['en', 'error', 'th'] | False |
AuthenticationForm.__init__ | (self, request=None, *args, **kwargs) |
The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.
|
The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.
| def __init__(self, request=None, *args, **kwargs):
"""
The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.
"""
self.request = request
self.user_cache = None
super().__init__(*args, **kwargs)
# Set the max length and label for the "username" field.
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
username_max_length = self.username_field.max_length or 254
self.fields['username'].max_length = username_max_length
self.fields['username'].widget.attrs['maxlength'] = username_max_length
if self.fields['username'].label is None:
self.fields['username'].label = capfirst(self.username_field.verbose_name) | [
"def",
"__init__",
"(",
"self",
",",
"request",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"user_cache",
"=",
"None",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Set the max length and label for the \"username\" field.",
"self",
".",
"username_field",
"=",
"UserModel",
".",
"_meta",
".",
"get_field",
"(",
"UserModel",
".",
"USERNAME_FIELD",
")",
"username_max_length",
"=",
"self",
".",
"username_field",
".",
"max_length",
"or",
"254",
"self",
".",
"fields",
"[",
"'username'",
"]",
".",
"max_length",
"=",
"username_max_length",
"self",
".",
"fields",
"[",
"'username'",
"]",
".",
"widget",
".",
"attrs",
"[",
"'maxlength'",
"]",
"=",
"username_max_length",
"if",
"self",
".",
"fields",
"[",
"'username'",
"]",
".",
"label",
"is",
"None",
":",
"self",
".",
"fields",
"[",
"'username'",
"]",
".",
"label",
"=",
"capfirst",
"(",
"self",
".",
"username_field",
".",
"verbose_name",
")"
] | [
179,
4
] | [
194,
86
] | python | en | ['en', 'error', 'th'] | False |
AuthenticationForm.confirm_login_allowed | (self, user) |
Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users.
If the given user cannot log in, this method should raise a
``ValidationError``.
If the given user may log in, this method should return None.
|
Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users. | def confirm_login_allowed(self, user):
"""
Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users.
If the given user cannot log in, this method should raise a
``ValidationError``.
If the given user may log in, this method should return None.
"""
if not user.is_active:
raise ValidationError(
self.error_messages['inactive'],
code='inactive',
) | [
"def",
"confirm_login_allowed",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"is_active",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'inactive'",
"]",
",",
"code",
"=",
"'inactive'",
",",
")"
] | [
209,
4
] | [
224,
13
] | python | en | ['en', 'error', 'th'] | False |
PasswordResetForm.send_mail | (self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None) |
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
|
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
| def send_mail(self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
"""
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, 'text/html')
email_message.send() | [
"def",
"send_mail",
"(",
"self",
",",
"subject_template_name",
",",
"email_template_name",
",",
"context",
",",
"from_email",
",",
"to_email",
",",
"html_email_template_name",
"=",
"None",
")",
":",
"subject",
"=",
"loader",
".",
"render_to_string",
"(",
"subject_template_name",
",",
"context",
")",
"# Email subject *must not* contain newlines",
"subject",
"=",
"''",
".",
"join",
"(",
"subject",
".",
"splitlines",
"(",
")",
")",
"body",
"=",
"loader",
".",
"render_to_string",
"(",
"email_template_name",
",",
"context",
")",
"email_message",
"=",
"EmailMultiAlternatives",
"(",
"subject",
",",
"body",
",",
"from_email",
",",
"[",
"to_email",
"]",
")",
"if",
"html_email_template_name",
"is",
"not",
"None",
":",
"html_email",
"=",
"loader",
".",
"render_to_string",
"(",
"html_email_template_name",
",",
"context",
")",
"email_message",
".",
"attach_alternative",
"(",
"html_email",
",",
"'text/html'",
")",
"email_message",
".",
"send",
"(",
")"
] | [
244,
4
] | [
259,
28
] | python | en | ['en', 'error', 'th'] | False |
PasswordResetForm.get_users | (self, email) | Given an email, return matching user(s) who should receive a reset.
This allows subclasses to more easily customize the default policies
that prevent inactive users and users with unusable passwords from
resetting their password.
| Given an email, return matching user(s) who should receive a reset. | def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This allows subclasses to more easily customize the default policies
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % email_field_name: email,
'is_active': True,
})
return (
u for u in active_users
if u.has_usable_password() and
_unicode_ci_compare(email, getattr(u, email_field_name))
) | [
"def",
"get_users",
"(",
"self",
",",
"email",
")",
":",
"email_field_name",
"=",
"UserModel",
".",
"get_email_field_name",
"(",
")",
"active_users",
"=",
"UserModel",
".",
"_default_manager",
".",
"filter",
"(",
"*",
"*",
"{",
"'%s__iexact'",
"%",
"email_field_name",
":",
"email",
",",
"'is_active'",
":",
"True",
",",
"}",
")",
"return",
"(",
"u",
"for",
"u",
"in",
"active_users",
"if",
"u",
".",
"has_usable_password",
"(",
")",
"and",
"_unicode_ci_compare",
"(",
"email",
",",
"getattr",
"(",
"u",
",",
"email_field_name",
")",
")",
")"
] | [
261,
4
] | [
277,
9
] | python | en | ['en', 'en', 'en'] | True |
PasswordResetForm.save | (self, domain_override=None,
subject_template_name='registration/password_reset_subject.txt',
email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator,
from_email=None, request=None, html_email_template_name=None,
extra_email_context=None) |
Generate a one-use only link for resetting password and send it to the
user.
|
Generate a one-use only link for resetting password and send it to the
user.
| def save(self, domain_override=None,
subject_template_name='registration/password_reset_subject.txt',
email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator,
from_email=None, request=None, html_email_template_name=None,
extra_email_context=None):
"""
Generate a one-use only link for resetting password and send it to the
user.
"""
email = self.cleaned_data["email"]
if not domain_override:
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
else:
site_name = domain = domain_override
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
user_email = getattr(user, email_field_name)
context = {
'email': user_email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': token_generator.make_token(user),
'protocol': 'https' if use_https else 'http',
**(extra_email_context or {}),
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
user_email, html_email_template_name=html_email_template_name,
) | [
"def",
"save",
"(",
"self",
",",
"domain_override",
"=",
"None",
",",
"subject_template_name",
"=",
"'registration/password_reset_subject.txt'",
",",
"email_template_name",
"=",
"'registration/password_reset_email.html'",
",",
"use_https",
"=",
"False",
",",
"token_generator",
"=",
"default_token_generator",
",",
"from_email",
"=",
"None",
",",
"request",
"=",
"None",
",",
"html_email_template_name",
"=",
"None",
",",
"extra_email_context",
"=",
"None",
")",
":",
"email",
"=",
"self",
".",
"cleaned_data",
"[",
"\"email\"",
"]",
"if",
"not",
"domain_override",
":",
"current_site",
"=",
"get_current_site",
"(",
"request",
")",
"site_name",
"=",
"current_site",
".",
"name",
"domain",
"=",
"current_site",
".",
"domain",
"else",
":",
"site_name",
"=",
"domain",
"=",
"domain_override",
"email_field_name",
"=",
"UserModel",
".",
"get_email_field_name",
"(",
")",
"for",
"user",
"in",
"self",
".",
"get_users",
"(",
"email",
")",
":",
"user_email",
"=",
"getattr",
"(",
"user",
",",
"email_field_name",
")",
"context",
"=",
"{",
"'email'",
":",
"user_email",
",",
"'domain'",
":",
"domain",
",",
"'site_name'",
":",
"site_name",
",",
"'uid'",
":",
"urlsafe_base64_encode",
"(",
"force_bytes",
"(",
"user",
".",
"pk",
")",
")",
",",
"'user'",
":",
"user",
",",
"'token'",
":",
"token_generator",
".",
"make_token",
"(",
"user",
")",
",",
"'protocol'",
":",
"'https'",
"if",
"use_https",
"else",
"'http'",
",",
"*",
"*",
"(",
"extra_email_context",
"or",
"{",
"}",
")",
",",
"}",
"self",
".",
"send_mail",
"(",
"subject_template_name",
",",
"email_template_name",
",",
"context",
",",
"from_email",
",",
"user_email",
",",
"html_email_template_name",
"=",
"html_email_template_name",
",",
")"
] | [
279,
4
] | [
312,
13
] | python | en | ['en', 'error', 'th'] | False |
PasswordChangeForm.clean_old_password | (self) |
Validate that the old_password field is correct.
|
Validate that the old_password field is correct.
| def clean_old_password(self):
"""
Validate that the old_password field is correct.
"""
old_password = self.cleaned_data["old_password"]
if not self.user.check_password(old_password):
raise ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
return old_password | [
"def",
"clean_old_password",
"(",
"self",
")",
":",
"old_password",
"=",
"self",
".",
"cleaned_data",
"[",
"\"old_password\"",
"]",
"if",
"not",
"self",
".",
"user",
".",
"check_password",
"(",
"old_password",
")",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'password_incorrect'",
"]",
",",
"code",
"=",
"'password_incorrect'",
",",
")",
"return",
"old_password"
] | [
376,
4
] | [
386,
27
] | python | en | ['en', 'error', 'th'] | False |
AdminPasswordChangeForm.save | (self, commit=True) | Save the new password. | Save the new password. | def save(self, commit=True):
"""Save the new password."""
password = self.cleaned_data["password1"]
self.user.set_password(password)
if commit:
self.user.save()
return self.user | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"password",
"=",
"self",
".",
"cleaned_data",
"[",
"\"password1\"",
"]",
"self",
".",
"user",
".",
"set_password",
"(",
"password",
")",
"if",
"commit",
":",
"self",
".",
"user",
".",
"save",
"(",
")",
"return",
"self",
".",
"user"
] | [
425,
4
] | [
431,
24
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.