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 |
---|---|---|---|---|---|---|---|---|---|---|---|
DataLakeToDataMartCGBK.add_account_details | (self, account_info) | This function performs the join of the two datasets. | This function performs the join of the two datasets. | def add_account_details(self, account_info):
"""This function performs the join of the two datasets."""
(acct_number, data) = account_info
result = list(data['orders'])
if not data['account_details']:
logging.info('account details are empty')
return
if not data['orders']:
logging.info('orders are empty')
return
account_details = {}
try:
account_details = data['account_details'][0]
except KeyError as err:
traceback.print_exc()
logging.error("Account Not Found error: %s", err)
for order in result:
order.update(account_details)
return result | [
"def",
"add_account_details",
"(",
"self",
",",
"account_info",
")",
":",
"(",
"acct_number",
",",
"data",
")",
"=",
"account_info",
"result",
"=",
"list",
"(",
"data",
"[",
"'orders'",
"]",
")",
"if",
"not",
"data",
"[",
"'account_details'",
"]",
":",
"logging",
".",
"info",
"(",
"'account details are empty'",
")",
"return",
"if",
"not",
"data",
"[",
"'orders'",
"]",
":",
"logging",
".",
"info",
"(",
"'orders are empty'",
")",
"return",
"account_details",
"=",
"{",
"}",
"try",
":",
"account_details",
"=",
"data",
"[",
"'account_details'",
"]",
"[",
"0",
"]",
"except",
"KeyError",
"as",
"err",
":",
"traceback",
".",
"print_exc",
"(",
")",
"logging",
".",
"error",
"(",
"\"Account Not Found error: %s\"",
",",
"err",
")",
"for",
"order",
"in",
"result",
":",
"order",
".",
"update",
"(",
"account_details",
")",
"return",
"result"
] | [
208,
4
] | [
229,
21
] | python | en | ['en', 'en', 'en'] | True |
HttpError._get_reason | (self) | Calculate the reason for the error from the response content. | Calculate the reason for the error from the response content. | def _get_reason(self):
"""Calculate the reason for the error from the response content."""
reason = self.resp.reason
try:
data = json.loads(self.content.decode('utf-8'))
if isinstance(data, dict):
reason = data['error']['message']
elif isinstance(data, list) and len(data) > 0:
first_error = data[0]
reason = first_error['error']['message']
except (ValueError, KeyError, TypeError):
pass
if reason is None:
reason = ''
return reason | [
"def",
"_get_reason",
"(",
"self",
")",
":",
"reason",
"=",
"self",
".",
"resp",
".",
"reason",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"reason",
"=",
"data",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
"and",
"len",
"(",
"data",
")",
">",
"0",
":",
"first_error",
"=",
"data",
"[",
"0",
"]",
"reason",
"=",
"first_error",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"except",
"(",
"ValueError",
",",
"KeyError",
",",
"TypeError",
")",
":",
"pass",
"if",
"reason",
"is",
"None",
":",
"reason",
"=",
"''",
"return",
"reason"
] | [
49,
2
] | [
63,
17
] | python | en | ['en', 'en', 'en'] | True |
UnexpectedMethodError.__init__ | (self, methodId=None) | Constructor for an UnexpectedMethodError. | Constructor for an UnexpectedMethodError. | def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId) | [
"def",
"__init__",
"(",
"self",
",",
"methodId",
"=",
"None",
")",
":",
"super",
"(",
"UnexpectedMethodError",
",",
"self",
")",
".",
"__init__",
"(",
"'Received unexpected call %s'",
"%",
"methodId",
")"
] | [
140,
2
] | [
143,
49
] | python | en | ['en', 'gl', 'en'] | True |
UnexpectedBodyError.__init__ | (self, expected, provided) | Constructor for an UnexpectedMethodError. | Constructor for an UnexpectedMethodError. | def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided)) | [
"def",
"__init__",
"(",
"self",
",",
"expected",
",",
"provided",
")",
":",
"super",
"(",
"UnexpectedBodyError",
",",
"self",
")",
".",
"__init__",
"(",
"'Expected: [%s] - Provided: [%s]'",
"%",
"(",
"expected",
",",
"provided",
")",
")"
] | [
149,
2
] | [
152,
65
] | python | en | ['en', 'gl', 'en'] | True |
main | (args: (Optional[List[str]]) = None) | This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
| This is preserved for old console scripts that may still be referencing
it. | def main(args: (Optional[List[str]]) = None) -> int:
"""This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args) | [
"def",
"main",
"(",
"args",
":",
"(",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"=",
"None",
")",
"->",
"int",
":",
"from",
"pip",
".",
"_internal",
".",
"utils",
".",
"entrypoints",
"import",
"_wrapper",
"return",
"_wrapper",
"(",
"args",
")"
] | [
10,
0
] | [
18,
25
] | python | en | ['en', 'en', 'en'] | True |
was_installed_by_pip | (pkg) | Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora.
| Checks whether pkg was installed by pip | def was_installed_by_pip(pkg):
# type: (str) -> bool
"""Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora.
"""
dist = get_default_environment().get_distribution(pkg)
return dist is not None and "pip" == dist.installer | [
"def",
"was_installed_by_pip",
"(",
"pkg",
")",
":",
"# type: (str) -> bool",
"dist",
"=",
"get_default_environment",
"(",
")",
".",
"get_distribution",
"(",
"pkg",
")",
"return",
"dist",
"is",
"not",
"None",
"and",
"\"pip\"",
"==",
"dist",
".",
"installer"
] | [
92,
0
] | [
100,
55
] | python | en | ['en', 'en', 'en'] | True |
pip_self_version_check | (session, options) | Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
| Check for an update for pip. | def pip_self_version_check(session, options):
# type: (PipSession, optparse.Values) -> None
"""Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
"""
installed_dist = get_default_environment().get_distribution("pip")
if not installed_dist:
return
pip_version = installed_dist.version
pypi_version = None
try:
state = SelfCheckState(cache_dir=options.cache_dir)
current_time = datetime.datetime.utcnow()
# Determine if we need to refresh the state
if "last_check" in state.state and "pypi_version" in state.state:
last_check = datetime.datetime.strptime(
state.state["last_check"],
SELFCHECK_DATE_FMT
)
if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60:
pypi_version = state.state["pypi_version"]
# Refresh the version if we need to or just see if we need to warn
if pypi_version is None:
# Lets use PackageFinder to see what the latest pip version is
link_collector = LinkCollector.create(
session,
options=options,
suppress_no_index=True,
)
# Pass allow_yanked=False so we don't suggest upgrading to a
# yanked version.
selection_prefs = SelectionPreferences(
allow_yanked=False,
allow_all_prereleases=False, # Explicitly set to False
)
finder = PackageFinder.create(
link_collector=link_collector,
selection_prefs=selection_prefs,
)
best_candidate = finder.find_best_candidate("pip").best_candidate
if best_candidate is None:
return
pypi_version = str(best_candidate.version)
# save that we've performed a check
state.save(pypi_version, current_time)
remote_version = parse_version(pypi_version)
local_version_is_older = (
pip_version < remote_version and
pip_version.base_version != remote_version.base_version and
was_installed_by_pip('pip')
)
# Determine if our pypi_version is older
if not local_version_is_older:
return
# We cannot tell how the current pip is available in the current
# command context, so be pragmatic here and suggest the command
# that's always available. This does not accommodate spaces in
# `sys.executable`.
pip_cmd = f"{sys.executable} -m pip"
logger.warning(
"You are using pip version %s; however, version %s is "
"available.\nYou should consider upgrading via the "
"'%s install --upgrade pip' command.",
pip_version, pypi_version, pip_cmd
)
except Exception:
logger.debug(
"There was an error checking the latest version of pip",
exc_info=True,
) | [
"def",
"pip_self_version_check",
"(",
"session",
",",
"options",
")",
":",
"# type: (PipSession, optparse.Values) -> None",
"installed_dist",
"=",
"get_default_environment",
"(",
")",
".",
"get_distribution",
"(",
"\"pip\"",
")",
"if",
"not",
"installed_dist",
":",
"return",
"pip_version",
"=",
"installed_dist",
".",
"version",
"pypi_version",
"=",
"None",
"try",
":",
"state",
"=",
"SelfCheckState",
"(",
"cache_dir",
"=",
"options",
".",
"cache_dir",
")",
"current_time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"# Determine if we need to refresh the state",
"if",
"\"last_check\"",
"in",
"state",
".",
"state",
"and",
"\"pypi_version\"",
"in",
"state",
".",
"state",
":",
"last_check",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"state",
".",
"state",
"[",
"\"last_check\"",
"]",
",",
"SELFCHECK_DATE_FMT",
")",
"if",
"(",
"current_time",
"-",
"last_check",
")",
".",
"total_seconds",
"(",
")",
"<",
"7",
"*",
"24",
"*",
"60",
"*",
"60",
":",
"pypi_version",
"=",
"state",
".",
"state",
"[",
"\"pypi_version\"",
"]",
"# Refresh the version if we need to or just see if we need to warn",
"if",
"pypi_version",
"is",
"None",
":",
"# Lets use PackageFinder to see what the latest pip version is",
"link_collector",
"=",
"LinkCollector",
".",
"create",
"(",
"session",
",",
"options",
"=",
"options",
",",
"suppress_no_index",
"=",
"True",
",",
")",
"# Pass allow_yanked=False so we don't suggest upgrading to a",
"# yanked version.",
"selection_prefs",
"=",
"SelectionPreferences",
"(",
"allow_yanked",
"=",
"False",
",",
"allow_all_prereleases",
"=",
"False",
",",
"# Explicitly set to False",
")",
"finder",
"=",
"PackageFinder",
".",
"create",
"(",
"link_collector",
"=",
"link_collector",
",",
"selection_prefs",
"=",
"selection_prefs",
",",
")",
"best_candidate",
"=",
"finder",
".",
"find_best_candidate",
"(",
"\"pip\"",
")",
".",
"best_candidate",
"if",
"best_candidate",
"is",
"None",
":",
"return",
"pypi_version",
"=",
"str",
"(",
"best_candidate",
".",
"version",
")",
"# save that we've performed a check",
"state",
".",
"save",
"(",
"pypi_version",
",",
"current_time",
")",
"remote_version",
"=",
"parse_version",
"(",
"pypi_version",
")",
"local_version_is_older",
"=",
"(",
"pip_version",
"<",
"remote_version",
"and",
"pip_version",
".",
"base_version",
"!=",
"remote_version",
".",
"base_version",
"and",
"was_installed_by_pip",
"(",
"'pip'",
")",
")",
"# Determine if our pypi_version is older",
"if",
"not",
"local_version_is_older",
":",
"return",
"# We cannot tell how the current pip is available in the current",
"# command context, so be pragmatic here and suggest the command",
"# that's always available. This does not accommodate spaces in",
"# `sys.executable`.",
"pip_cmd",
"=",
"f\"{sys.executable} -m pip\"",
"logger",
".",
"warning",
"(",
"\"You are using pip version %s; however, version %s is \"",
"\"available.\\nYou should consider upgrading via the \"",
"\"'%s install --upgrade pip' command.\"",
",",
"pip_version",
",",
"pypi_version",
",",
"pip_cmd",
")",
"except",
"Exception",
":",
"logger",
".",
"debug",
"(",
"\"There was an error checking the latest version of pip\"",
",",
"exc_info",
"=",
"True",
",",
")"
] | [
103,
0
] | [
186,
9
] | python | en | ['en', 'en', 'en'] | True |
main | () | Main entry point for demimove-ui. | Main entry point for demimove-ui. | def main():
"Main entry point for demimove-ui."
startdir = os.getcwd()
try:
args = docopt(__doc__, version="0.2")
# args["-v"] = 3 # Force debug logging
fileop = fileops.FileOps(verbosity=args["-v"],
quiet=args["--quiet"])
if args["<path>"]:
startdir = args["<path>"]
except NameError:
fileop = fileops.FileOps()
log.error("Please install docopt to use the CLI.")
app = QtGui.QApplication(sys.argv)
app.setApplicationName("demimove-ui")
gui = DemiMoveGUI(startdir, fileop)
gui.show()
sys.exit(app.exec_()) | [
"def",
"main",
"(",
")",
":",
"startdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"0.2\"",
")",
"# args[\"-v\"] = 3 # Force debug logging",
"fileop",
"=",
"fileops",
".",
"FileOps",
"(",
"verbosity",
"=",
"args",
"[",
"\"-v\"",
"]",
",",
"quiet",
"=",
"args",
"[",
"\"--quiet\"",
"]",
")",
"if",
"args",
"[",
"\"<path>\"",
"]",
":",
"startdir",
"=",
"args",
"[",
"\"<path>\"",
"]",
"except",
"NameError",
":",
"fileop",
"=",
"fileops",
".",
"FileOps",
"(",
")",
"log",
".",
"error",
"(",
"\"Please install docopt to use the CLI.\"",
")",
"app",
"=",
"QtGui",
".",
"QApplication",
"(",
"sys",
".",
"argv",
")",
"app",
".",
"setApplicationName",
"(",
"\"demimove-ui\"",
")",
"gui",
"=",
"DemiMoveGUI",
"(",
"startdir",
",",
"fileop",
")",
"gui",
".",
"show",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"exec_",
"(",
")",
")"
] | [
829,
0
] | [
847,
25
] | python | en | ['es', 'en', 'en'] | True |
DemiMoveGUI.set_cwd | (self, index=None, force=False) | Set the current working directory for renaming actions. | Set the current working directory for renaming actions. | def set_cwd(self, index=None, force=False):
"Set the current working directory for renaming actions."
if not index:
index = self.get_index()
path = self.get_path(index)
if force or path != self.cwd and os.path.isdir(path):
self.cwd = path
self.cwdidx = index
self.dirview.setExpanded(self.cwdidx, True)
elif self.cwd and path == self.cwd:
self.dirview.setExpanded(self.cwdidx, False)
self.cwd = ""
self.cwdidx = None
self.update(2) | [
"def",
"set_cwd",
"(",
"self",
",",
"index",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"index",
":",
"index",
"=",
"self",
".",
"get_index",
"(",
")",
"path",
"=",
"self",
".",
"get_path",
"(",
"index",
")",
"if",
"force",
"or",
"path",
"!=",
"self",
".",
"cwd",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"cwd",
"=",
"path",
"self",
".",
"cwdidx",
"=",
"index",
"self",
".",
"dirview",
".",
"setExpanded",
"(",
"self",
".",
"cwdidx",
",",
"True",
")",
"elif",
"self",
".",
"cwd",
"and",
"path",
"==",
"self",
".",
"cwd",
":",
"self",
".",
"dirview",
".",
"setExpanded",
"(",
"self",
".",
"cwdidx",
",",
"False",
")",
"self",
".",
"cwd",
"=",
"\"\"",
"self",
".",
"cwdidx",
"=",
"None",
"self",
".",
"update",
"(",
"2",
")"
] | [
250,
4
] | [
263,
22
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.keyPressEvent | (self, e) | Overloaded to connect return key to self.set_cwd(). | Overloaded to connect return key to self.set_cwd(). | def keyPressEvent(self, e):
"Overloaded to connect return key to self.set_cwd()."
# TODO: Move this to TreeView only.
if e.key() == QtCore.Qt.Key_Return:
self.set_cwd()
if e.key() == QtCore.Qt.Key_Delete:
self.delete_index() | [
"def",
"keyPressEvent",
"(",
"self",
",",
"e",
")",
":",
"# TODO: Move this to TreeView only.",
"if",
"e",
".",
"key",
"(",
")",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Return",
":",
"self",
".",
"set_cwd",
"(",
")",
"if",
"e",
".",
"key",
"(",
")",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Delete",
":",
"self",
".",
"delete_index",
"(",
")"
] | [
350,
4
] | [
356,
31
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.update | (self, mode=1) | Main update routine using threading to get targets and/or previews | Main update routine using threading to get targets and/or previews | def update(self, mode=1):
"""Main update routine using threading to get targets and/or previews"""
# Modes: 0 = targets, 1 = previews, 2 = both.
self.fileops.stopupdate = False
if not self.autopreview or not self.cwd:
self.update_view()
return
self.updatethread.mode = mode
self.updatethread.start() | [
"def",
"update",
"(",
"self",
",",
"mode",
"=",
"1",
")",
":",
"# Modes: 0 = targets, 1 = previews, 2 = both.",
"self",
".",
"fileops",
".",
"stopupdate",
"=",
"False",
"if",
"not",
"self",
".",
"autopreview",
"or",
"not",
"self",
".",
"cwd",
":",
"self",
".",
"update_view",
"(",
")",
"return",
"self",
".",
"updatethread",
".",
"mode",
"=",
"mode",
"self",
".",
"updatethread",
".",
"start",
"(",
")"
] | [
358,
4
] | [
366,
33
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_saveoptionsbutton | (self) | Save current options to configfile. | Save current options to configfile. | def on_saveoptionsbutton(self):
"""Save current options to configfile."""
log.info("Saving options.")
helpers.save_configfile(self.fileops.configdir, self.get_options())
self.statusbar.showMessage("Configuration file saved.") | [
"def",
"on_saveoptionsbutton",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Saving options.\"",
")",
"helpers",
".",
"save_configfile",
"(",
"self",
".",
"fileops",
".",
"configdir",
",",
"self",
".",
"get_options",
"(",
")",
")",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Configuration file saved.\"",
")"
] | [
491,
4
] | [
495,
63
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_restoreoptionsbutton | (self) | Restore options to start point. | Restore options to start point. | def on_restoreoptionsbutton(self):
"""Restore options to start point."""
log.info("Restoring options.")
self.set_options(self.startoptions) | [
"def",
"on_restoreoptionsbutton",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Restoring options.\"",
")",
"self",
".",
"set_options",
"(",
"self",
".",
"startoptions",
")"
] | [
497,
4
] | [
500,
43
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_clearoptionsbutton | (self) | Reset/Clear all options. | Reset/Clear all options. | def on_clearoptionsbutton(self):
"""Reset/Clear all options."""
log.info("Clearing options.")
self.set_options(sanitize=True) | [
"def",
"on_clearoptionsbutton",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Clearing options.\"",
")",
"self",
".",
"set_options",
"(",
"sanitize",
"=",
"True",
")"
] | [
502,
4
] | [
505,
39
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_commitbutton | (self) | Perform the currently previewed rename actions. | Perform the currently previewed rename actions. | def on_commitbutton(self):
"""Perform the currently previewed rename actions."""
log.info("Committing previewed changes.")
if self.committhread.isRunning():
self.fileops.stopcommit = True
else:
self.fileops.stopcommit = False
self.committhread.start() | [
"def",
"on_commitbutton",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Committing previewed changes.\"",
")",
"if",
"self",
".",
"committhread",
".",
"isRunning",
"(",
")",
":",
"self",
".",
"fileops",
".",
"stopcommit",
"=",
"True",
"else",
":",
"self",
".",
"fileops",
".",
"stopcommit",
"=",
"False",
"self",
".",
"committhread",
".",
"start",
"(",
")"
] | [
507,
4
] | [
514,
37
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_undobutton | (self) | Pops the history stack of commits, reverting the one on top. | Pops the history stack of commits, reverting the one on top. | def on_undobutton(self):
"""Pops the history stack of commits, reverting the one on top."""
log.info("Reverting last commit.")
self.fileops.undo()
self.update(2) | [
"def",
"on_undobutton",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Reverting last commit.\"",
")",
"self",
".",
"fileops",
".",
"undo",
"(",
")",
"self",
".",
"update",
"(",
"2",
")"
] | [
516,
4
] | [
520,
22
] | python | en | ['en', 'en', 'en'] | True |
DemiMoveGUI.on_refreshbutton | (self) | Force a refresh of browser view and model. | Force a refresh of browser view and model. | def on_refreshbutton(self):
"""Force a refresh of browser view and model."""
if self.updatethread.isRunning():
self.fileops.stopupdate = True
else:
self.update(2) | [
"def",
"on_refreshbutton",
"(",
"self",
")",
":",
"if",
"self",
".",
"updatethread",
".",
"isRunning",
"(",
")",
":",
"self",
".",
"fileops",
".",
"stopupdate",
"=",
"True",
"else",
":",
"self",
".",
"update",
"(",
"2",
")"
] | [
522,
4
] | [
527,
26
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.__init__ | (self, path=None, cache=0, country=None, city=None) |
Initialize the GeoIP object. No parameters are required to use default
settings. Keyword arguments may be passed in to customize the locations
of the GeoIP datasets.
* path: Base directory to where GeoIP data is located or the full path
to where the city or country data files (*.mmdb) are located.
Assumes that both the city and country data sets are located in
this directory; overrides the GEOIP_PATH setting.
* cache: The cache settings when opening up the GeoIP datasets. May be
an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO,
MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY,
`GeoIPOptions` C API settings, respectively. Defaults to 0,
meaning MODE_AUTO.
* country: The name of the GeoIP country data file. Defaults to
'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting.
* city: The name of the GeoIP city data file. Defaults to
'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting.
|
Initialize the GeoIP object. No parameters are required to use default
settings. Keyword arguments may be passed in to customize the locations
of the GeoIP datasets. | def __init__(self, path=None, cache=0, country=None, city=None):
"""
Initialize the GeoIP object. No parameters are required to use default
settings. Keyword arguments may be passed in to customize the locations
of the GeoIP datasets.
* path: Base directory to where GeoIP data is located or the full path
to where the city or country data files (*.mmdb) are located.
Assumes that both the city and country data sets are located in
this directory; overrides the GEOIP_PATH setting.
* cache: The cache settings when opening up the GeoIP datasets. May be
an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO,
MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY,
`GeoIPOptions` C API settings, respectively. Defaults to 0,
meaning MODE_AUTO.
* country: The name of the GeoIP country data file. Defaults to
'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting.
* city: The name of the GeoIP city data file. Defaults to
'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting.
"""
# Checking the given cache option.
if cache in self.cache_options:
self._cache = cache
else:
raise GeoIP2Exception('Invalid GeoIP caching option: %s' % cache)
# Getting the GeoIP data path.
path = path or GEOIP_SETTINGS['GEOIP_PATH']
if not path:
raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
path = to_path(path)
if path.is_dir():
# Constructing the GeoIP database filenames using the settings
# dictionary. If the database files for the GeoLite country
# and/or city datasets exist, then try to open them.
country_db = path / (country or GEOIP_SETTINGS['GEOIP_COUNTRY'])
if country_db.is_file():
self._country = geoip2.database.Reader(str(country_db), mode=cache)
self._country_file = country_db
city_db = path / (city or GEOIP_SETTINGS['GEOIP_CITY'])
if city_db.is_file():
self._city = geoip2.database.Reader(str(city_db), mode=cache)
self._city_file = city_db
if not self._reader:
raise GeoIP2Exception('Could not load a database from %s.' % path)
elif path.is_file():
# Otherwise, some detective work will be needed to figure out
# whether the given database path is for the GeoIP country or city
# databases.
reader = geoip2.database.Reader(str(path), mode=cache)
db_type = reader.metadata().database_type
if db_type.endswith('City'):
# GeoLite City database detected.
self._city = reader
self._city_file = path
elif db_type.endswith('Country'):
# GeoIP Country database detected.
self._country = reader
self._country_file = path
else:
raise GeoIP2Exception('Unable to recognize database edition: %s' % db_type)
else:
raise GeoIP2Exception('GeoIP path must be a valid file or directory.') | [
"def",
"__init__",
"(",
"self",
",",
"path",
"=",
"None",
",",
"cache",
"=",
"0",
",",
"country",
"=",
"None",
",",
"city",
"=",
"None",
")",
":",
"# Checking the given cache option.",
"if",
"cache",
"in",
"self",
".",
"cache_options",
":",
"self",
".",
"_cache",
"=",
"cache",
"else",
":",
"raise",
"GeoIP2Exception",
"(",
"'Invalid GeoIP caching option: %s'",
"%",
"cache",
")",
"# Getting the GeoIP data path.",
"path",
"=",
"path",
"or",
"GEOIP_SETTINGS",
"[",
"'GEOIP_PATH'",
"]",
"if",
"not",
"path",
":",
"raise",
"GeoIP2Exception",
"(",
"'GeoIP path must be provided via parameter or the GEOIP_PATH setting.'",
")",
"path",
"=",
"to_path",
"(",
"path",
")",
"if",
"path",
".",
"is_dir",
"(",
")",
":",
"# Constructing the GeoIP database filenames using the settings",
"# dictionary. If the database files for the GeoLite country",
"# and/or city datasets exist, then try to open them.",
"country_db",
"=",
"path",
"/",
"(",
"country",
"or",
"GEOIP_SETTINGS",
"[",
"'GEOIP_COUNTRY'",
"]",
")",
"if",
"country_db",
".",
"is_file",
"(",
")",
":",
"self",
".",
"_country",
"=",
"geoip2",
".",
"database",
".",
"Reader",
"(",
"str",
"(",
"country_db",
")",
",",
"mode",
"=",
"cache",
")",
"self",
".",
"_country_file",
"=",
"country_db",
"city_db",
"=",
"path",
"/",
"(",
"city",
"or",
"GEOIP_SETTINGS",
"[",
"'GEOIP_CITY'",
"]",
")",
"if",
"city_db",
".",
"is_file",
"(",
")",
":",
"self",
".",
"_city",
"=",
"geoip2",
".",
"database",
".",
"Reader",
"(",
"str",
"(",
"city_db",
")",
",",
"mode",
"=",
"cache",
")",
"self",
".",
"_city_file",
"=",
"city_db",
"if",
"not",
"self",
".",
"_reader",
":",
"raise",
"GeoIP2Exception",
"(",
"'Could not load a database from %s.'",
"%",
"path",
")",
"elif",
"path",
".",
"is_file",
"(",
")",
":",
"# Otherwise, some detective work will be needed to figure out",
"# whether the given database path is for the GeoIP country or city",
"# databases.",
"reader",
"=",
"geoip2",
".",
"database",
".",
"Reader",
"(",
"str",
"(",
"path",
")",
",",
"mode",
"=",
"cache",
")",
"db_type",
"=",
"reader",
".",
"metadata",
"(",
")",
".",
"database_type",
"if",
"db_type",
".",
"endswith",
"(",
"'City'",
")",
":",
"# GeoLite City database detected.",
"self",
".",
"_city",
"=",
"reader",
"self",
".",
"_city_file",
"=",
"path",
"elif",
"db_type",
".",
"endswith",
"(",
"'Country'",
")",
":",
"# GeoIP Country database detected.",
"self",
".",
"_country",
"=",
"reader",
"self",
".",
"_country_file",
"=",
"path",
"else",
":",
"raise",
"GeoIP2Exception",
"(",
"'Unable to recognize database edition: %s'",
"%",
"db_type",
")",
"else",
":",
"raise",
"GeoIP2Exception",
"(",
"'GeoIP path must be a valid file or directory.'",
")"
] | [
45,
4
] | [
113,
82
] | python | en | ['en', 'error', 'th'] | False |
GeoIP2._check_query | (self, query, country=False, city=False, city_or_country=False) | Check the query and database availability. | Check the query and database availability. | def _check_query(self, query, country=False, city=False, city_or_country=False):
"Check the query and database availability."
# Making sure a string was passed in for the query.
if not isinstance(query, str):
raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)
# Extra checks for the existence of country and city databases.
if city_or_country and not (self._country or self._city):
raise GeoIP2Exception('Invalid GeoIP country and city data files.')
elif country and not self._country:
raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file)
elif city and not self._city:
raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file)
# Return the query string back to the caller. GeoIP2 only takes IP addresses.
try:
validate_ipv46_address(query)
except ValidationError:
query = socket.gethostbyname(query)
return query | [
"def",
"_check_query",
"(",
"self",
",",
"query",
",",
"country",
"=",
"False",
",",
"city",
"=",
"False",
",",
"city_or_country",
"=",
"False",
")",
":",
"# Making sure a string was passed in for the query.",
"if",
"not",
"isinstance",
"(",
"query",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'GeoIP query must be a string, not type %s'",
"%",
"type",
"(",
"query",
")",
".",
"__name__",
")",
"# Extra checks for the existence of country and city databases.",
"if",
"city_or_country",
"and",
"not",
"(",
"self",
".",
"_country",
"or",
"self",
".",
"_city",
")",
":",
"raise",
"GeoIP2Exception",
"(",
"'Invalid GeoIP country and city data files.'",
")",
"elif",
"country",
"and",
"not",
"self",
".",
"_country",
":",
"raise",
"GeoIP2Exception",
"(",
"'Invalid GeoIP country data file: %s'",
"%",
"self",
".",
"_country_file",
")",
"elif",
"city",
"and",
"not",
"self",
".",
"_city",
":",
"raise",
"GeoIP2Exception",
"(",
"'Invalid GeoIP city data file: %s'",
"%",
"self",
".",
"_city_file",
")",
"# Return the query string back to the caller. GeoIP2 only takes IP addresses.",
"try",
":",
"validate_ipv46_address",
"(",
"query",
")",
"except",
"ValidationError",
":",
"query",
"=",
"socket",
".",
"gethostbyname",
"(",
"query",
")",
"return",
"query"
] | [
141,
4
] | [
161,
20
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.city | (self, query) |
Return a dictionary of city information for the given IP address or
Fully Qualified Domain Name (FQDN). Some information in the dictionary
may be undefined (None).
|
Return a dictionary of city information for the given IP address or
Fully Qualified Domain Name (FQDN). Some information in the dictionary
may be undefined (None).
| def city(self, query):
"""
Return a dictionary of city information for the given IP address or
Fully Qualified Domain Name (FQDN). Some information in the dictionary
may be undefined (None).
"""
enc_query = self._check_query(query, city=True)
return City(self._city.city(enc_query)) | [
"def",
"city",
"(",
"self",
",",
"query",
")",
":",
"enc_query",
"=",
"self",
".",
"_check_query",
"(",
"query",
",",
"city",
"=",
"True",
")",
"return",
"City",
"(",
"self",
".",
"_city",
".",
"city",
"(",
"enc_query",
")",
")"
] | [
163,
4
] | [
170,
47
] | python | en | ['en', 'error', 'th'] | False |
GeoIP2.country_code | (self, query) | Return the country code for the given IP Address or FQDN. | Return the country code for the given IP Address or FQDN. | def country_code(self, query):
"Return the country code for the given IP Address or FQDN."
enc_query = self._check_query(query, city_or_country=True)
return self.country(enc_query)['country_code'] | [
"def",
"country_code",
"(",
"self",
",",
"query",
")",
":",
"enc_query",
"=",
"self",
".",
"_check_query",
"(",
"query",
",",
"city_or_country",
"=",
"True",
")",
"return",
"self",
".",
"country",
"(",
"enc_query",
")",
"[",
"'country_code'",
"]"
] | [
172,
4
] | [
175,
54
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.country_name | (self, query) | Return the country name for the given IP Address or FQDN. | Return the country name for the given IP Address or FQDN. | def country_name(self, query):
"Return the country name for the given IP Address or FQDN."
enc_query = self._check_query(query, city_or_country=True)
return self.country(enc_query)['country_name'] | [
"def",
"country_name",
"(",
"self",
",",
"query",
")",
":",
"enc_query",
"=",
"self",
".",
"_check_query",
"(",
"query",
",",
"city_or_country",
"=",
"True",
")",
"return",
"self",
".",
"country",
"(",
"enc_query",
")",
"[",
"'country_name'",
"]"
] | [
177,
4
] | [
180,
54
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.country | (self, query) |
Return a dictionary with the country code and name when given an
IP address or a Fully Qualified Domain Name (FQDN). For example, both
'24.124.1.80' and 'djangoproject.com' are valid parameters.
|
Return a dictionary with the country code and name when given an
IP address or a Fully Qualified Domain Name (FQDN). For example, both
'24.124.1.80' and 'djangoproject.com' are valid parameters.
| def country(self, query):
"""
Return a dictionary with the country code and name when given an
IP address or a Fully Qualified Domain Name (FQDN). For example, both
'24.124.1.80' and 'djangoproject.com' are valid parameters.
"""
# Returning the country code and name
enc_query = self._check_query(query, city_or_country=True)
return Country(self._country_or_city(enc_query)) | [
"def",
"country",
"(",
"self",
",",
"query",
")",
":",
"# Returning the country code and name",
"enc_query",
"=",
"self",
".",
"_check_query",
"(",
"query",
",",
"city_or_country",
"=",
"True",
")",
"return",
"Country",
"(",
"self",
".",
"_country_or_city",
"(",
"enc_query",
")",
")"
] | [
182,
4
] | [
190,
56
] | python | en | ['en', 'error', 'th'] | False |
GeoIP2.lon_lat | (self, query) | Return a tuple of the (longitude, latitude) for the given query. | Return a tuple of the (longitude, latitude) for the given query. | def lon_lat(self, query):
"Return a tuple of the (longitude, latitude) for the given query."
return self.coords(query) | [
"def",
"lon_lat",
"(",
"self",
",",
"query",
")",
":",
"return",
"self",
".",
"coords",
"(",
"query",
")"
] | [
200,
4
] | [
202,
33
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.lat_lon | (self, query) | Return a tuple of the (latitude, longitude) for the given query. | Return a tuple of the (latitude, longitude) for the given query. | def lat_lon(self, query):
"Return a tuple of the (latitude, longitude) for the given query."
return self.coords(query, ('latitude', 'longitude')) | [
"def",
"lat_lon",
"(",
"self",
",",
"query",
")",
":",
"return",
"self",
".",
"coords",
"(",
"query",
",",
"(",
"'latitude'",
",",
"'longitude'",
")",
")"
] | [
204,
4
] | [
206,
60
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.geos | (self, query) | Return a GEOS Point object for the given query. | Return a GEOS Point object for the given query. | def geos(self, query):
"Return a GEOS Point object for the given query."
ll = self.lon_lat(query)
if ll:
from django.contrib.gis.geos import Point
return Point(ll, srid=4326)
else:
return None | [
"def",
"geos",
"(",
"self",
",",
"query",
")",
":",
"ll",
"=",
"self",
".",
"lon_lat",
"(",
"query",
")",
"if",
"ll",
":",
"from",
"django",
".",
"contrib",
".",
"gis",
".",
"geos",
"import",
"Point",
"return",
"Point",
"(",
"ll",
",",
"srid",
"=",
"4326",
")",
"else",
":",
"return",
"None"
] | [
208,
4
] | [
215,
23
] | python | en | ['en', 'en', 'en'] | True |
GeoIP2.info | (self) | Return information about the GeoIP library and databases in use. | Return information about the GeoIP library and databases in use. | def info(self):
"Return information about the GeoIP library and databases in use."
meta = self._reader.metadata()
return 'GeoIP Library:\n\t%s.%s\n' % (meta.binary_format_major_version, meta.binary_format_minor_version) | [
"def",
"info",
"(",
"self",
")",
":",
"meta",
"=",
"self",
".",
"_reader",
".",
"metadata",
"(",
")",
"return",
"'GeoIP Library:\\n\\t%s.%s\\n'",
"%",
"(",
"meta",
".",
"binary_format_major_version",
",",
"meta",
".",
"binary_format_minor_version",
")"
] | [
219,
4
] | [
222,
113
] | python | en | ['en', 'en', 'en'] | True |
run_tests | (session, dir=None) | Run all tests for all directories (slow!) | Run all tests for all directories (slow!) | def run_tests(session, dir=None):
"""Run all tests for all directories (slow!)"""
run_test(session, dir) | [
"def",
"run_tests",
"(",
"session",
",",
"dir",
"=",
"None",
")",
":",
"run_test",
"(",
"session",
",",
"dir",
")"
] | [
59,
0
] | [
61,
26
] | python | en | ['en', 'en', 'en'] | True |
SigningAlgorithm.get_signature | (self, key, value) | Returns the signature for the given key and value. | Returns the signature for the given key and value. | def get_signature(self, key, value):
"""Returns the signature for the given key and value."""
raise NotImplementedError() | [
"def",
"get_signature",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
16,
4
] | [
18,
35
] | python | en | ['en', 'en', 'en'] | True |
SigningAlgorithm.verify_signature | (self, key, value, sig) | Verifies the given signature matches the expected
signature.
| Verifies the given signature matches the expected
signature.
| def verify_signature(self, key, value, sig):
"""Verifies the given signature matches the expected
signature.
"""
return constant_time_compare(sig, self.get_signature(key, value)) | [
"def",
"verify_signature",
"(",
"self",
",",
"key",
",",
"value",
",",
"sig",
")",
":",
"return",
"constant_time_compare",
"(",
"sig",
",",
"self",
".",
"get_signature",
"(",
"key",
",",
"value",
")",
")"
] | [
20,
4
] | [
24,
73
] | python | en | ['en', 'en', 'en'] | True |
Signer.derive_key | (self) | This method is called to derive the key. The default key
derivation choices can be overridden here. Key derivation is not
intended to be used as a security method to make a complex key
out of a short password. Instead you should use large random
secret keys.
| This method is called to derive the key. The default key
derivation choices can be overridden here. Key derivation is not
intended to be used as a security method to make a complex key
out of a short password. Instead you should use large random
secret keys.
| def derive_key(self):
"""This method is called to derive the key. The default key
derivation choices can be overridden here. Key derivation is not
intended to be used as a security method to make a complex key
out of a short password. Instead you should use large random
secret keys.
"""
salt = want_bytes(self.salt)
if self.key_derivation == "concat":
return self.digest_method(salt + self.secret_key).digest()
elif self.key_derivation == "django-concat":
return self.digest_method(salt + b"signer" + self.secret_key).digest()
elif self.key_derivation == "hmac":
mac = hmac.new(self.secret_key, digestmod=self.digest_method)
mac.update(salt)
return mac.digest()
elif self.key_derivation == "none":
return self.secret_key
else:
raise TypeError("Unknown key derivation method") | [
"def",
"derive_key",
"(",
"self",
")",
":",
"salt",
"=",
"want_bytes",
"(",
"self",
".",
"salt",
")",
"if",
"self",
".",
"key_derivation",
"==",
"\"concat\"",
":",
"return",
"self",
".",
"digest_method",
"(",
"salt",
"+",
"self",
".",
"secret_key",
")",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"\"django-concat\"",
":",
"return",
"self",
".",
"digest_method",
"(",
"salt",
"+",
"b\"signer\"",
"+",
"self",
".",
"secret_key",
")",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"\"hmac\"",
":",
"mac",
"=",
"hmac",
".",
"new",
"(",
"self",
".",
"secret_key",
",",
"digestmod",
"=",
"self",
".",
"digest_method",
")",
"mac",
".",
"update",
"(",
"salt",
")",
"return",
"mac",
".",
"digest",
"(",
")",
"elif",
"self",
".",
"key_derivation",
"==",
"\"none\"",
":",
"return",
"self",
".",
"secret_key",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unknown key derivation method\"",
")"
] | [
118,
4
] | [
137,
60
] | python | en | ['en', 'en', 'en'] | True |
Signer.get_signature | (self, value) | Returns the signature for the given value. | Returns the signature for the given value. | def get_signature(self, value):
"""Returns the signature for the given value."""
value = want_bytes(value)
key = self.derive_key()
sig = self.algorithm.get_signature(key, value)
return base64_encode(sig) | [
"def",
"get_signature",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"want_bytes",
"(",
"value",
")",
"key",
"=",
"self",
".",
"derive_key",
"(",
")",
"sig",
"=",
"self",
".",
"algorithm",
".",
"get_signature",
"(",
"key",
",",
"value",
")",
"return",
"base64_encode",
"(",
"sig",
")"
] | [
139,
4
] | [
144,
33
] | python | en | ['en', 'en', 'en'] | True |
Signer.sign | (self, value) | Signs the given string. | Signs the given string. | def sign(self, value):
"""Signs the given string."""
return want_bytes(value) + want_bytes(self.sep) + self.get_signature(value) | [
"def",
"sign",
"(",
"self",
",",
"value",
")",
":",
"return",
"want_bytes",
"(",
"value",
")",
"+",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"+",
"self",
".",
"get_signature",
"(",
"value",
")"
] | [
146,
4
] | [
148,
83
] | python | en | ['en', 'en', 'en'] | True |
Signer.verify_signature | (self, value, sig) | Verifies the signature for the given value. | Verifies the signature for the given value. | def verify_signature(self, value, sig):
"""Verifies the signature for the given value."""
key = self.derive_key()
try:
sig = base64_decode(sig)
except Exception:
return False
return self.algorithm.verify_signature(key, value, sig) | [
"def",
"verify_signature",
"(",
"self",
",",
"value",
",",
"sig",
")",
":",
"key",
"=",
"self",
".",
"derive_key",
"(",
")",
"try",
":",
"sig",
"=",
"base64_decode",
"(",
"sig",
")",
"except",
"Exception",
":",
"return",
"False",
"return",
"self",
".",
"algorithm",
".",
"verify_signature",
"(",
"key",
",",
"value",
",",
"sig",
")"
] | [
150,
4
] | [
157,
63
] | python | en | ['en', 'en', 'en'] | True |
Signer.unsign | (self, signed_value) | Unsigns the given string. | Unsigns the given string. | def unsign(self, signed_value):
"""Unsigns the given string."""
signed_value = want_bytes(signed_value)
sep = want_bytes(self.sep)
if sep not in signed_value:
raise BadSignature("No %r found in value" % self.sep)
value, sig = signed_value.rsplit(sep, 1)
if self.verify_signature(value, sig):
return value
raise BadSignature("Signature %r does not match" % sig, payload=value) | [
"def",
"unsign",
"(",
"self",
",",
"signed_value",
")",
":",
"signed_value",
"=",
"want_bytes",
"(",
"signed_value",
")",
"sep",
"=",
"want_bytes",
"(",
"self",
".",
"sep",
")",
"if",
"sep",
"not",
"in",
"signed_value",
":",
"raise",
"BadSignature",
"(",
"\"No %r found in value\"",
"%",
"self",
".",
"sep",
")",
"value",
",",
"sig",
"=",
"signed_value",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"if",
"self",
".",
"verify_signature",
"(",
"value",
",",
"sig",
")",
":",
"return",
"value",
"raise",
"BadSignature",
"(",
"\"Signature %r does not match\"",
"%",
"sig",
",",
"payload",
"=",
"value",
")"
] | [
159,
4
] | [
168,
78
] | python | en | ['en', 'en', 'en'] | True |
Signer.validate | (self, signed_value) | Only validates the given signed value. Returns ``True`` if
the signature exists and is valid.
| Only validates the given signed value. Returns ``True`` if
the signature exists and is valid.
| def validate(self, signed_value):
"""Only validates the given signed value. Returns ``True`` if
the signature exists and is valid.
"""
try:
self.unsign(signed_value)
return True
except BadSignature:
return False | [
"def",
"validate",
"(",
"self",
",",
"signed_value",
")",
":",
"try",
":",
"self",
".",
"unsign",
"(",
"signed_value",
")",
"return",
"True",
"except",
"BadSignature",
":",
"return",
"False"
] | [
170,
4
] | [
178,
24
] | python | en | ['en', 'en', 'en'] | True |
BaseHeuristic.warning | (self, response) |
Return a valid 1xx warning header value describing the cache
adjustments.
The response is provided too allow warnings like 113
http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
to explicitly say response is over 24 hours old.
|
Return a valid 1xx warning header value describing the cache
adjustments. | def warning(self, response):
"""
Return a valid 1xx warning header value describing the cache
adjustments.
The response is provided too allow warnings like 113
http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
to explicitly say response is over 24 hours old.
"""
return '110 - "Response is Stale"' | [
"def",
"warning",
"(",
"self",
",",
"response",
")",
":",
"return",
"'110 - \"Response is Stale\"'"
] | [
21,
4
] | [
30,
42
] | python | en | ['en', 'error', 'th'] | False |
BaseHeuristic.update_headers | (self, response) | Update the response headers with any new headers.
NOTE: This SHOULD always include some Warning header to
signify that the response was cached by the client, not
by way of the provided headers.
| Update the response headers with any new headers. | def update_headers(self, response):
"""Update the response headers with any new headers.
NOTE: This SHOULD always include some Warning header to
signify that the response was cached by the client, not
by way of the provided headers.
"""
return {} | [
"def",
"update_headers",
"(",
"self",
",",
"response",
")",
":",
"return",
"{",
"}"
] | [
32,
4
] | [
39,
17
] | python | en | ['en', 'en', 'en'] | True |
CloudinaryJsFileField.to_python | (self, value) | Convert to CloudinaryResource | Convert to CloudinaryResource | def to_python(self, value):
"""Convert to CloudinaryResource"""
if not value:
return None
m = re.search(r'^([^/]+)/([^/]+)/v(\d+)/([^#]+)#([^/]+)$', value)
if not m:
raise forms.ValidationError("Invalid format")
resource_type = m.group(1)
upload_type = m.group(2)
version = m.group(3)
filename = m.group(4)
signature = m.group(5)
m = re.search(r'(.*)\.(.*)', filename)
if not m:
raise forms.ValidationError("Invalid file name")
public_id = m.group(1)
image_format = m.group(2)
return CloudinaryResource(public_id,
format=image_format,
version=version,
signature=signature,
type=upload_type,
resource_type=resource_type) | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"m",
"=",
"re",
".",
"search",
"(",
"r'^([^/]+)/([^/]+)/v(\\d+)/([^#]+)#([^/]+)$'",
",",
"value",
")",
"if",
"not",
"m",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Invalid format\"",
")",
"resource_type",
"=",
"m",
".",
"group",
"(",
"1",
")",
"upload_type",
"=",
"m",
".",
"group",
"(",
"2",
")",
"version",
"=",
"m",
".",
"group",
"(",
"3",
")",
"filename",
"=",
"m",
".",
"group",
"(",
"4",
")",
"signature",
"=",
"m",
".",
"group",
"(",
"5",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r'(.*)\\.(.*)'",
",",
"filename",
")",
"if",
"not",
"m",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Invalid file name\"",
")",
"public_id",
"=",
"m",
".",
"group",
"(",
"1",
")",
"image_format",
"=",
"m",
".",
"group",
"(",
"2",
")",
"return",
"CloudinaryResource",
"(",
"public_id",
",",
"format",
"=",
"image_format",
",",
"version",
"=",
"version",
",",
"signature",
"=",
"signature",
",",
"type",
"=",
"upload_type",
",",
"resource_type",
"=",
"resource_type",
")"
] | [
75,
4
] | [
97,
62
] | python | en | ['en', 'su', 'en'] | True |
CloudinaryJsFileField.validate | (self, value) | Validate the signature | Validate the signature | def validate(self, value):
"""Validate the signature"""
# Use the parent's handling of required fields, etc.
super(CloudinaryJsFileField, self).validate(value)
if not value:
return
if not value.validate():
raise forms.ValidationError("Signature mismatch") | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"# Use the parent's handling of required fields, etc.",
"super",
"(",
"CloudinaryJsFileField",
",",
"self",
")",
".",
"validate",
"(",
"value",
")",
"if",
"not",
"value",
":",
"return",
"if",
"not",
"value",
".",
"validate",
"(",
")",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Signature mismatch\"",
")"
] | [
99,
4
] | [
106,
61
] | python | en | ['en', 'la', 'en'] | True |
CloudinaryFileField.to_python | (self, value) | Upload and convert to CloudinaryResource | Upload and convert to CloudinaryResource | def to_python(self, value):
"""Upload and convert to CloudinaryResource"""
value = super(CloudinaryFileField, self).to_python(value)
if not value:
return None
if self.autosave:
return cloudinary.uploader.upload_image(value, **self.options)
else:
return value | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"CloudinaryFileField",
",",
"self",
")",
".",
"to_python",
"(",
"value",
")",
"if",
"not",
"value",
":",
"return",
"None",
"if",
"self",
".",
"autosave",
":",
"return",
"cloudinary",
".",
"uploader",
".",
"upload_image",
"(",
"value",
",",
"*",
"*",
"self",
".",
"options",
")",
"else",
":",
"return",
"value"
] | [
133,
4
] | [
141,
24
] | python | en | ['en', 'en', 'en'] | True |
serve | (request, path, insecure=False, **kwargs) |
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
path('<path:path>', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
|
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders. | def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
path('<path:path>', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(path).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs) | [
"def",
"serve",
"(",
"request",
",",
"path",
",",
"insecure",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"settings",
".",
"DEBUG",
"and",
"not",
"insecure",
":",
"raise",
"Http404",
"normalized_path",
"=",
"posixpath",
".",
"normpath",
"(",
"path",
")",
".",
"lstrip",
"(",
"'/'",
")",
"absolute_path",
"=",
"finders",
".",
"find",
"(",
"normalized_path",
")",
"if",
"not",
"absolute_path",
":",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
"or",
"path",
"==",
"''",
":",
"raise",
"Http404",
"(",
"\"Directory indexes are not allowed here.\"",
")",
"raise",
"Http404",
"(",
"\"'%s' could not be found\"",
"%",
"path",
")",
"document_root",
",",
"path",
"=",
"os",
".",
"path",
".",
"split",
"(",
"absolute_path",
")",
"return",
"static",
".",
"serve",
"(",
"request",
",",
"path",
",",
"document_root",
"=",
"document_root",
",",
"*",
"*",
"kwargs",
")"
] | [
14,
0
] | [
38,
77
] | python | en | ['en', 'error', 'th'] | False |
glob | (pathname, recursive=False) | Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
| Return a list of paths matching a pathname pattern. | def glob(pathname, recursive=False):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
return list(iglob(pathname, recursive=recursive)) | [
"def",
"glob",
"(",
"pathname",
",",
"recursive",
"=",
"False",
")",
":",
"return",
"list",
"(",
"iglob",
"(",
"pathname",
",",
"recursive",
"=",
"recursive",
")",
")"
] | [
17,
0
] | [
28,
53
] | python | en | ['en', 'en', 'en'] | True |
iglob | (pathname, recursive=False) | Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
| Return an iterator which yields the paths matching a pathname pattern. | def iglob(pathname, recursive=False):
"""Return an iterator which yields the paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.
If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
it = _iglob(pathname, recursive)
if recursive and _isrecursive(pathname):
s = next(it) # skip empty string
assert not s
return it | [
"def",
"iglob",
"(",
"pathname",
",",
"recursive",
"=",
"False",
")",
":",
"it",
"=",
"_iglob",
"(",
"pathname",
",",
"recursive",
")",
"if",
"recursive",
"and",
"_isrecursive",
"(",
"pathname",
")",
":",
"s",
"=",
"next",
"(",
"it",
")",
"# skip empty string",
"assert",
"not",
"s",
"return",
"it"
] | [
31,
0
] | [
46,
13
] | python | en | ['en', 'en', 'en'] | True |
escape | (pathname) | Escape all special characters.
| Escape all special characters.
| def escape(pathname):
"""Escape all special characters.
"""
# Escaping is done by wrapping any of "*?[" between square brackets.
# Metacharacters do not work in the drive part and shouldn't be escaped.
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, binary_type):
pathname = magic_check_bytes.sub(br'[\1]', pathname)
else:
pathname = magic_check.sub(r'[\1]', pathname)
return drive + pathname | [
"def",
"escape",
"(",
"pathname",
")",
":",
"# Escaping is done by wrapping any of \"*?[\" between square brackets.",
"# Metacharacters do not work in the drive part and shouldn't be escaped.",
"drive",
",",
"pathname",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"pathname",
")",
"if",
"isinstance",
"(",
"pathname",
",",
"binary_type",
")",
":",
"pathname",
"=",
"magic_check_bytes",
".",
"sub",
"(",
"br'[\\1]'",
",",
"pathname",
")",
"else",
":",
"pathname",
"=",
"magic_check",
".",
"sub",
"(",
"r'[\\1]'",
",",
"pathname",
")",
"return",
"drive",
"+",
"pathname"
] | [
165,
0
] | [
175,
27
] | python | en | ['en', 'en', 'en'] | True |
cria_cardapios | (cardapios_por_data) |
Recebe objetos de Refeicao agrupados por data em um dicionario e retorna uma lista de objetos Cardapios a partir desse dicionario.
:param cardapios_por_data: dicionario do tipo {String: [Refeicao]}, onde a string eh uma data.
:return: lista com os objetos Cardapio instanciados.
|
Recebe objetos de Refeicao agrupados por data em um dicionario e retorna uma lista de objetos Cardapios a partir desse dicionario. | def cria_cardapios(cardapios_por_data):
"""
Recebe objetos de Refeicao agrupados por data em um dicionario e retorna uma lista de objetos Cardapios a partir desse dicionario.
:param cardapios_por_data: dicionario do tipo {String: [Refeicao]}, onde a string eh uma data.
:return: lista com os objetos Cardapio instanciados.
"""
cardapios = []
chaves_para_tipos = {
'Almoço':'almoco',
'Almoço vegetariano': 'almoco_vegetariano',
'Jantar': 'jantar',
'Jantar vegetariano': 'jantar_vegetariano'
}
for data in list(cardapios_por_data.keys()):
refeicoes = {chaves_para_tipos[r.tipo] : r for r in cardapios_por_data[data]}
cardapios.append(Cardapio(data=data, **refeicoes))
# cardapios = [limpa_nao_informado(c) for c in cardapios]
return cardapios | [
"def",
"cria_cardapios",
"(",
"cardapios_por_data",
")",
":",
"cardapios",
"=",
"[",
"]",
"chaves_para_tipos",
"=",
"{",
"'Almoço':",
"'",
"almoco',",
"",
"'Almoço vegetariano':",
" ",
"almoco_vegetariano',",
"",
"'Jantar'",
":",
"'jantar'",
",",
"'Jantar vegetariano'",
":",
"'jantar_vegetariano'",
"}",
"for",
"data",
"in",
"list",
"(",
"cardapios_por_data",
".",
"keys",
"(",
")",
")",
":",
"refeicoes",
"=",
"{",
"chaves_para_tipos",
"[",
"r",
".",
"tipo",
"]",
":",
"r",
"for",
"r",
"in",
"cardapios_por_data",
"[",
"data",
"]",
"}",
"cardapios",
".",
"append",
"(",
"Cardapio",
"(",
"data",
"=",
"data",
",",
"*",
"*",
"refeicoes",
")",
")",
"# cardapios = [limpa_nao_informado(c) for c in cardapios]",
"return",
"cardapios"
] | [
19,
0
] | [
41,
20
] | python | en | ['en', 'error', 'th'] | False |
cria_refeicoes | (refeicoes_list) |
Cria um dicionario que agrupas objetos da classe Refeicao por data a partir de uma lista de dicionarios contendo informacoes das refeicoes.
:param refeicoes_list: Lista com refeicoes em dicionarios.
:return: Dicionario que mapeia datas a uma lista com objetos Refeicao contendo o cardapios daquela data.
|
Cria um dicionario que agrupas objetos da classe Refeicao por data a partir de uma lista de dicionarios contendo informacoes das refeicoes. | def cria_refeicoes(refeicoes_list):
"""
Cria um dicionario que agrupas objetos da classe Refeicao por data a partir de uma lista de dicionarios contendo informacoes das refeicoes.
:param refeicoes_list: Lista com refeicoes em dicionarios.
:return: Dicionario que mapeia datas a uma lista com objetos Refeicao contendo o cardapios daquela data.
"""
cardapios_por_data = {}
for ref in refeicoes_list:
try:
d = ref['data']
except KeyError as e:
print("KeyError nas datas.")
print(e, end="\n\n")
break
except TypeError as e:
print("TypeError nas datas.")
print(e, end="\n\n")
break
try:
cardapios_por_data[d].append(Refeicao(**ref))
except KeyError as e: # cria lista para aquela data e armazena a primeira refeicao.
# print("criando list para data: {}".format(d))
# print(e)
cardapios_por_data[d] = [Refeicao(**ref)]
except TypeError as e:
print(e)
print("provavelmente argumento a mais no construtor de Refeicao")
return cardapios_por_data | [
"def",
"cria_refeicoes",
"(",
"refeicoes_list",
")",
":",
"cardapios_por_data",
"=",
"{",
"}",
"for",
"ref",
"in",
"refeicoes_list",
":",
"try",
":",
"d",
"=",
"ref",
"[",
"'data'",
"]",
"except",
"KeyError",
"as",
"e",
":",
"print",
"(",
"\"KeyError nas datas.\"",
")",
"print",
"(",
"e",
",",
"end",
"=",
"\"\\n\\n\"",
")",
"break",
"except",
"TypeError",
"as",
"e",
":",
"print",
"(",
"\"TypeError nas datas.\"",
")",
"print",
"(",
"e",
",",
"end",
"=",
"\"\\n\\n\"",
")",
"break",
"try",
":",
"cardapios_por_data",
"[",
"d",
"]",
".",
"append",
"(",
"Refeicao",
"(",
"*",
"*",
"ref",
")",
")",
"except",
"KeyError",
"as",
"e",
":",
"# cria lista para aquela data e armazena a primeira refeicao.",
"# print(\"criando list para data: {}\".format(d))",
"# print(e)",
"cardapios_por_data",
"[",
"d",
"]",
"=",
"[",
"Refeicao",
"(",
"*",
"*",
"ref",
")",
"]",
"except",
"TypeError",
"as",
"e",
":",
"print",
"(",
"e",
")",
"print",
"(",
"\"provavelmente argumento a mais no construtor de Refeicao\"",
")",
"return",
"cardapios_por_data"
] | [
47,
0
] | [
81,
29
] | python | en | ['en', 'error', 'th'] | False |
request_data_from_unicamp | () |
Responsavel por fazer o request ao webservices da UNICAMP e armazenar a resposta no firebase.
Esse metodo configura o add-on do Heroku que garante que todos os outbounds requests utilizando esse proxy sao feitos a partir de um IP fixo.
|
Responsavel por fazer o request ao webservices da UNICAMP e armazenar a resposta no firebase. | def request_data_from_unicamp():
""""
Responsavel por fazer o request ao webservices da UNICAMP e armazenar a resposta no firebase.
Esse metodo configura o add-on do Heroku que garante que todos os outbounds requests utilizando esse proxy sao feitos a partir de um IP fixo.
"""
proxyDict = {
"http": environment_vars.FIXIE_URL,
"https": environment_vars.FIXIE_URL
}
try:
print("Opcao 1: Executando request para o API da UNICAMP utilizando o proxy.")
r = requests.get("https://webservices.prefeitura.unicamp.br/cardapio_json.php", proxies=proxyDict)
raw_json = r.content
except:
print("Erro no primeiro request para UNICAMP.")
raw_json = b''
else:
print("Request para API da UNICAMP terminou com sucesso.")
# usar o backup server se o limite do add-on fixie foi atingido
if raw_json == b'' or len(raw_json) == 0:
try:
print("Opcao 2: Request para servidor backup...")
r = requests.get("https://backup-unicamp-server.herokuapp.com")
raw_json = r.content
except Exception as e:
print("Exception no request para o PRIMEIRO servidor backup: ", e)
raw_json = b''
else:
print("Request para o primeiro servidor backup terminou com sucesso.")
# usar o SEGUNDO backup server se o limite do fixie do primeiro foi atingido
if raw_json == b'' or len(raw_json) == 0:
try:
print("Opcao 3: Request para o SEGUNDO servidor backup...")
r = requests.get("https://backup-unicamp-server2.herokuapp.com")
raw_json = r.content
except Exception as e:
print("Exception no request para o SEGUNDO servidor backup: ", e)
raw_json = b''
else:
print("Request para o segundo servidor backup terminou com sucesso.")
# # Decode UTF-8 bytes to Unicode, and convert single quotes
# # to double quotes to make it valid JSON
raw_json = raw_json.decode('utf8').replace("'", '"')
#
# print("raw_json = ", raw_json)
if raw_json == b'' or len(raw_json) == 0:
print("Erro ao tentar armazenar JSON original no Firebase.")
return None
else:
db = setup_firebase()
db.child("cardapio_raw_json").set(raw_json)
print("Firebase atualizado com o JSON original da UNICAMP.")
return raw_json | [
"def",
"request_data_from_unicamp",
"(",
")",
":",
"proxyDict",
"=",
"{",
"\"http\"",
":",
"environment_vars",
".",
"FIXIE_URL",
",",
"\"https\"",
":",
"environment_vars",
".",
"FIXIE_URL",
"}",
"try",
":",
"print",
"(",
"\"Opcao 1: Executando request para o API da UNICAMP utilizando o proxy.\"",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"\"https://webservices.prefeitura.unicamp.br/cardapio_json.php\"",
",",
"proxies",
"=",
"proxyDict",
")",
"raw_json",
"=",
"r",
".",
"content",
"except",
":",
"print",
"(",
"\"Erro no primeiro request para UNICAMP.\"",
")",
"raw_json",
"=",
"b''",
"else",
":",
"print",
"(",
"\"Request para API da UNICAMP terminou com sucesso.\"",
")",
"# usar o backup server se o limite do add-on fixie foi atingido",
"if",
"raw_json",
"==",
"b''",
"or",
"len",
"(",
"raw_json",
")",
"==",
"0",
":",
"try",
":",
"print",
"(",
"\"Opcao 2: Request para servidor backup...\"",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"\"https://backup-unicamp-server.herokuapp.com\"",
")",
"raw_json",
"=",
"r",
".",
"content",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Exception no request para o PRIMEIRO servidor backup: \"",
",",
"e",
")",
"raw_json",
"=",
"b''",
"else",
":",
"print",
"(",
"\"Request para o primeiro servidor backup terminou com sucesso.\"",
")",
"# usar o SEGUNDO backup server se o limite do fixie do primeiro foi atingido",
"if",
"raw_json",
"==",
"b''",
"or",
"len",
"(",
"raw_json",
")",
"==",
"0",
":",
"try",
":",
"print",
"(",
"\"Opcao 3: Request para o SEGUNDO servidor backup...\"",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"\"https://backup-unicamp-server2.herokuapp.com\"",
")",
"raw_json",
"=",
"r",
".",
"content",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Exception no request para o SEGUNDO servidor backup: \"",
",",
"e",
")",
"raw_json",
"=",
"b''",
"else",
":",
"print",
"(",
"\"Request para o segundo servidor backup terminou com sucesso.\"",
")",
"# # Decode UTF-8 bytes to Unicode, and convert single quotes",
"# # to double quotes to make it valid JSON",
"raw_json",
"=",
"raw_json",
".",
"decode",
"(",
"'utf8'",
")",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
"#",
"# print(\"raw_json = \", raw_json)",
"if",
"raw_json",
"==",
"b''",
"or",
"len",
"(",
"raw_json",
")",
"==",
"0",
":",
"print",
"(",
"\"Erro ao tentar armazenar JSON original no Firebase.\"",
")",
"return",
"None",
"else",
":",
"db",
"=",
"setup_firebase",
"(",
")",
"db",
".",
"child",
"(",
"\"cardapio_raw_json\"",
")",
".",
"set",
"(",
"raw_json",
")",
"print",
"(",
"\"Firebase atualizado com o JSON original da UNICAMP.\"",
")",
"return",
"raw_json"
] | [
84,
0
] | [
145,
23
] | python | en | ['en', 'error', 'th'] | False |
request_cardapio | (raw_json) |
Obtem o JSON original contendo todas as informacoes dos proximos cardapios e retorna uma lista com as refeicoes em dicionarios, para comecar o processo de criacao dos objetos de tipo Refeicao e Cardapio.
:param raw_json: parametro opcional que contem as informacoes obtidas com o API da Unicamp em formato de JSON. Caso nao seja passado (acontece no envio das push notifications), essas informacoes sao obtidas pelo firebase.
:return: lista contendo as refeicoes em dicionarios.
|
Obtem o JSON original contendo todas as informacoes dos proximos cardapios e retorna uma lista com as refeicoes em dicionarios, para comecar o processo de criacao dos objetos de tipo Refeicao e Cardapio. | def request_cardapio(raw_json):
"""
Obtem o JSON original contendo todas as informacoes dos proximos cardapios e retorna uma lista com as refeicoes em dicionarios, para comecar o processo de criacao dos objetos de tipo Refeicao e Cardapio.
:param raw_json: parametro opcional que contem as informacoes obtidas com o API da Unicamp em formato de JSON. Caso nao seja passado (acontece no envio das push notifications), essas informacoes sao obtidas pelo firebase.
:return: lista contendo as refeicoes em dicionarios.
"""
# so faz request pro firebase se nao tiver o json.
if raw_json == None:
db = setup_firebase()
raw_json = db.child("cardapio_raw_json").get().val()
try:
cardapios = json.loads(raw_json)
refeicoes_list = cardapios['CARDAPIO']
except KeyError as e:
print('KeyError tentando pegar array de refeicoes.')
refeicoes_list = []
except:
print("erro deserializando conteudo do JSON.")
refeicoes_list = []
else:
print("Unloading do JSON feito com sucesso.")
return refeicoes_list | [
"def",
"request_cardapio",
"(",
"raw_json",
")",
":",
"# so faz request pro firebase se nao tiver o json.",
"if",
"raw_json",
"==",
"None",
":",
"db",
"=",
"setup_firebase",
"(",
")",
"raw_json",
"=",
"db",
".",
"child",
"(",
"\"cardapio_raw_json\"",
")",
".",
"get",
"(",
")",
".",
"val",
"(",
")",
"try",
":",
"cardapios",
"=",
"json",
".",
"loads",
"(",
"raw_json",
")",
"refeicoes_list",
"=",
"cardapios",
"[",
"'CARDAPIO'",
"]",
"except",
"KeyError",
"as",
"e",
":",
"print",
"(",
"'KeyError tentando pegar array de refeicoes.'",
")",
"refeicoes_list",
"=",
"[",
"]",
"except",
":",
"print",
"(",
"\"erro deserializando conteudo do JSON.\"",
")",
"refeicoes_list",
"=",
"[",
"]",
"else",
":",
"print",
"(",
"\"Unloading do JSON feito com sucesso.\"",
")",
"return",
"refeicoes_list"
] | [
151,
0
] | [
179,
25
] | python | en | ['en', 'error', 'th'] | False |
get_all_cardapios | (raw_json=None) |
Fornece uma lista de objetos Cardapio (contendo todos os cardapios disponiveis). O JSON com as informacoes e obtido pelo firebase e passa por um processo de "limpeza". Esse JSON e obtido pelo API da Unicamp e salvo no firebase utilizando a funcao `request_data_from_unicamp` (mais informacoes la).
Como o modulo `heroku_cache.py` faz o request pra Unicamp e serializa os objetos logo depois, eu coloquei um parametro opcional `raw_json` que pode ser passado para que um request para o firebase nao precise ser feito desnecessariamente.
:param raw_json:
:return: lista com os cardapios disponiveis ja em objetos da classe Cardapio.
|
Fornece uma lista de objetos Cardapio (contendo todos os cardapios disponiveis). O JSON com as informacoes e obtido pelo firebase e passa por um processo de "limpeza". Esse JSON e obtido pelo API da Unicamp e salvo no firebase utilizando a funcao `request_data_from_unicamp` (mais informacoes la).
Como o modulo `heroku_cache.py` faz o request pra Unicamp e serializa os objetos logo depois, eu coloquei um parametro opcional `raw_json` que pode ser passado para que um request para o firebase nao precise ser feito desnecessariamente. | def get_all_cardapios(raw_json=None):
"""
Fornece uma lista de objetos Cardapio (contendo todos os cardapios disponiveis). O JSON com as informacoes e obtido pelo firebase e passa por um processo de "limpeza". Esse JSON e obtido pelo API da Unicamp e salvo no firebase utilizando a funcao `request_data_from_unicamp` (mais informacoes la).
Como o modulo `heroku_cache.py` faz o request pra Unicamp e serializa os objetos logo depois, eu coloquei um parametro opcional `raw_json` que pode ser passado para que um request para o firebase nao precise ser feito desnecessariamente.
:param raw_json:
:return: lista com os cardapios disponiveis ja em objetos da classe Cardapio.
"""
refeicoes_list = request_cardapio(raw_json) # faz o request e recebe uma lista contendo as refeicoes em dicionarios.
limpa_chaves(refeicoes_list) # faz a limpeza das informacoes.
cardapios_por_data = cria_refeicoes(refeicoes_list)
cardapios = cria_cardapios(cardapios_por_data)
if len(cardapios) > 0:
print("Cardápios obtidos com sucesso.")
return cardapios
else: # usar o parser se os requests para os APIs todos falharam.
print("ERRO: não foi possível obter os cardápios com nenhum dos requests!")
return use_parser() | [
"def",
"get_all_cardapios",
"(",
"raw_json",
"=",
"None",
")",
":",
"refeicoes_list",
"=",
"request_cardapio",
"(",
"raw_json",
")",
"# faz o request e recebe uma lista contendo as refeicoes em dicionarios.",
"limpa_chaves",
"(",
"refeicoes_list",
")",
"# faz a limpeza das informacoes.",
"cardapios_por_data",
"=",
"cria_refeicoes",
"(",
"refeicoes_list",
")",
"cardapios",
"=",
"cria_cardapios",
"(",
"cardapios_por_data",
")",
"if",
"len",
"(",
"cardapios",
")",
">",
"0",
":",
"print",
"(",
"\"Cardápios obtidos com sucesso.\")",
"",
"return",
"cardapios",
"else",
":",
"# usar o parser se os requests para os APIs todos falharam.",
"print",
"(",
"\"ERRO: não foi possível obter os cardápios com nenhum dos requests!\")",
"",
"return",
"use_parser",
"(",
")"
] | [
203,
0
] | [
225,
27
] | python | en | ['en', 'error', 'th'] | False |
features_and_labels | (row_data) | Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
| Splits features and labels from feature dictionary. | def features_and_labels(row_data):
"""Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
"""
label = row_data.pop(LABEL_COLUMN)
return row_data, label | [
"def",
"features_and_labels",
"(",
"row_data",
")",
":",
"label",
"=",
"row_data",
".",
"pop",
"(",
"LABEL_COLUMN",
")",
"return",
"row_data",
",",
"label"
] | [
19,
0
] | [
29,
26
] | python | en | ['en', 'en', 'en'] | True |
load_dataset | (pattern, batch_size=1, mode='eval') | Loads dataset using the tf.data API from CSV files.
Args:
pattern: str, file pattern to glob into list of files.
batch_size: int, the number of examples per batch.
mode: 'eval' | 'train' to determine if training or evaluating.
Returns:
`Dataset` object.
| Loads dataset using the tf.data API from CSV files. | def load_dataset(pattern, batch_size=1, mode='eval'):
"""Loads dataset using the tf.data API from CSV files.
Args:
pattern: str, file pattern to glob into list of files.
batch_size: int, the number of examples per batch.
mode: 'eval' | 'train' to determine if training or evaluating.
Returns:
`Dataset` object.
"""
print("mode = {}".format(mode))
# Make a CSV dataset
dataset = tf.data.experimental.make_csv_dataset(
file_pattern=pattern,
batch_size=batch_size,
column_names=CSV_COLUMNS,
column_defaults=DEFAULTS)
# Map dataset to features and label
dataset = dataset.map(map_func=features_and_labels) # features, label
# Shuffle and repeat for training
if mode == 'train':
dataset = dataset.shuffle(buffer_size=1000).repeat()
# Take advantage of multi-threading; 1=AUTOTUNE
dataset = dataset.prefetch(buffer_size=1)
return dataset | [
"def",
"load_dataset",
"(",
"pattern",
",",
"batch_size",
"=",
"1",
",",
"mode",
"=",
"'eval'",
")",
":",
"print",
"(",
"\"mode = {}\"",
".",
"format",
"(",
"mode",
")",
")",
"# Make a CSV dataset",
"dataset",
"=",
"tf",
".",
"data",
".",
"experimental",
".",
"make_csv_dataset",
"(",
"file_pattern",
"=",
"pattern",
",",
"batch_size",
"=",
"batch_size",
",",
"column_names",
"=",
"CSV_COLUMNS",
",",
"column_defaults",
"=",
"DEFAULTS",
")",
"# Map dataset to features and label",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"map_func",
"=",
"features_and_labels",
")",
"# features, label",
"# Shuffle and repeat for training",
"if",
"mode",
"==",
"'train'",
":",
"dataset",
"=",
"dataset",
".",
"shuffle",
"(",
"buffer_size",
"=",
"1000",
")",
".",
"repeat",
"(",
")",
"# Take advantage of multi-threading; 1=AUTOTUNE",
"dataset",
"=",
"dataset",
".",
"prefetch",
"(",
"buffer_size",
"=",
"1",
")",
"return",
"dataset"
] | [
32,
0
] | [
60,
18
] | python | en | ['en', 'en', 'en'] | True |
create_input_layers | () | Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
| Creates dictionary of input layers for each feature. | def create_input_layers():
"""Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
"""
deep_inputs = {
colname: tf.keras.layers.Input(
name=colname, shape=(), dtype="float32")
for colname in ["mother_age", "gestation_weeks"]
}
wide_inputs = {
colname: tf.keras.layers.Input(
name=colname, shape=(), dtype="string")
for colname in ["is_male", "plurality"]
}
inputs = {**wide_inputs, **deep_inputs}
return inputs | [
"def",
"create_input_layers",
"(",
")",
":",
"deep_inputs",
"=",
"{",
"colname",
":",
"tf",
".",
"keras",
".",
"layers",
".",
"Input",
"(",
"name",
"=",
"colname",
",",
"shape",
"=",
"(",
")",
",",
"dtype",
"=",
"\"float32\"",
")",
"for",
"colname",
"in",
"[",
"\"mother_age\"",
",",
"\"gestation_weeks\"",
"]",
"}",
"wide_inputs",
"=",
"{",
"colname",
":",
"tf",
".",
"keras",
".",
"layers",
".",
"Input",
"(",
"name",
"=",
"colname",
",",
"shape",
"=",
"(",
")",
",",
"dtype",
"=",
"\"string\"",
")",
"for",
"colname",
"in",
"[",
"\"is_male\"",
",",
"\"plurality\"",
"]",
"}",
"inputs",
"=",
"{",
"*",
"*",
"wide_inputs",
",",
"*",
"*",
"deep_inputs",
"}",
"return",
"inputs"
] | [
63,
0
] | [
83,
17
] | python | en | ['en', 'en', 'en'] | True |
categorical_fc | (name, values) | Helper function to wrap categorical feature by indicator column.
Args:
name: str, name of feature.
values: list, list of strings of categorical values.
Returns:
Categorical and indicator column of categorical feature.
| Helper function to wrap categorical feature by indicator column. | def categorical_fc(name, values):
"""Helper function to wrap categorical feature by indicator column.
Args:
name: str, name of feature.
values: list, list of strings of categorical values.
Returns:
Categorical and indicator column of categorical feature.
"""
cat_column = tf.feature_column.categorical_column_with_vocabulary_list(
key=name, vocabulary_list=values)
ind_column = tf.feature_column.indicator_column(
categorical_column=cat_column)
return cat_column, ind_column | [
"def",
"categorical_fc",
"(",
"name",
",",
"values",
")",
":",
"cat_column",
"=",
"tf",
".",
"feature_column",
".",
"categorical_column_with_vocabulary_list",
"(",
"key",
"=",
"name",
",",
"vocabulary_list",
"=",
"values",
")",
"ind_column",
"=",
"tf",
".",
"feature_column",
".",
"indicator_column",
"(",
"categorical_column",
"=",
"cat_column",
")",
"return",
"cat_column",
",",
"ind_column"
] | [
86,
0
] | [
100,
33
] | python | en | ['en', 'en', 'en'] | True |
create_feature_columns | (nembeds) | Creates wide and deep dictionaries of feature columns from inputs.
Args:
nembeds: int, number of dimensions to embed categorical column down to.
Returns:
Wide and deep dictionaries of feature columns.
| Creates wide and deep dictionaries of feature columns from inputs. | def create_feature_columns(nembeds):
"""Creates wide and deep dictionaries of feature columns from inputs.
Args:
nembeds: int, number of dimensions to embed categorical column down to.
Returns:
Wide and deep dictionaries of feature columns.
"""
deep_fc = {
colname: tf.feature_column.numeric_column(key=colname)
for colname in ["mother_age", "gestation_weeks"]
}
wide_fc = {}
is_male, wide_fc["is_male"] = categorical_fc(
"is_male", ["True", "False", "Unknown"])
plurality, wide_fc["plurality"] = categorical_fc(
"plurality", ["Single(1)", "Twins(2)", "Triplets(3)",
"Quadruplets(4)", "Quintuplets(5)", "Multiple(2+)"])
# Bucketize the float fields. This makes them wide
age_buckets = tf.feature_column.bucketized_column(
source_column=deep_fc["mother_age"],
boundaries=np.arange(15, 45, 1).tolist())
wide_fc["age_buckets"] = tf.feature_column.indicator_column(
categorical_column=age_buckets)
gestation_buckets = tf.feature_column.bucketized_column(
source_column=deep_fc["gestation_weeks"],
boundaries=np.arange(17, 47, 1).tolist())
wide_fc["gestation_buckets"] = tf.feature_column.indicator_column(
categorical_column=gestation_buckets)
# Cross all the wide columns, have to do the crossing before we one-hot
crossed = tf.feature_column.crossed_column(
keys=[age_buckets, gestation_buckets],
hash_bucket_size=1000)
deep_fc["crossed_embeds"] = tf.feature_column.embedding_column(
categorical_column=crossed, dimension=nembeds)
return wide_fc, deep_fc | [
"def",
"create_feature_columns",
"(",
"nembeds",
")",
":",
"deep_fc",
"=",
"{",
"colname",
":",
"tf",
".",
"feature_column",
".",
"numeric_column",
"(",
"key",
"=",
"colname",
")",
"for",
"colname",
"in",
"[",
"\"mother_age\"",
",",
"\"gestation_weeks\"",
"]",
"}",
"wide_fc",
"=",
"{",
"}",
"is_male",
",",
"wide_fc",
"[",
"\"is_male\"",
"]",
"=",
"categorical_fc",
"(",
"\"is_male\"",
",",
"[",
"\"True\"",
",",
"\"False\"",
",",
"\"Unknown\"",
"]",
")",
"plurality",
",",
"wide_fc",
"[",
"\"plurality\"",
"]",
"=",
"categorical_fc",
"(",
"\"plurality\"",
",",
"[",
"\"Single(1)\"",
",",
"\"Twins(2)\"",
",",
"\"Triplets(3)\"",
",",
"\"Quadruplets(4)\"",
",",
"\"Quintuplets(5)\"",
",",
"\"Multiple(2+)\"",
"]",
")",
"# Bucketize the float fields. This makes them wide",
"age_buckets",
"=",
"tf",
".",
"feature_column",
".",
"bucketized_column",
"(",
"source_column",
"=",
"deep_fc",
"[",
"\"mother_age\"",
"]",
",",
"boundaries",
"=",
"np",
".",
"arange",
"(",
"15",
",",
"45",
",",
"1",
")",
".",
"tolist",
"(",
")",
")",
"wide_fc",
"[",
"\"age_buckets\"",
"]",
"=",
"tf",
".",
"feature_column",
".",
"indicator_column",
"(",
"categorical_column",
"=",
"age_buckets",
")",
"gestation_buckets",
"=",
"tf",
".",
"feature_column",
".",
"bucketized_column",
"(",
"source_column",
"=",
"deep_fc",
"[",
"\"gestation_weeks\"",
"]",
",",
"boundaries",
"=",
"np",
".",
"arange",
"(",
"17",
",",
"47",
",",
"1",
")",
".",
"tolist",
"(",
")",
")",
"wide_fc",
"[",
"\"gestation_buckets\"",
"]",
"=",
"tf",
".",
"feature_column",
".",
"indicator_column",
"(",
"categorical_column",
"=",
"gestation_buckets",
")",
"# Cross all the wide columns, have to do the crossing before we one-hot",
"crossed",
"=",
"tf",
".",
"feature_column",
".",
"crossed_column",
"(",
"keys",
"=",
"[",
"age_buckets",
",",
"gestation_buckets",
"]",
",",
"hash_bucket_size",
"=",
"1000",
")",
"deep_fc",
"[",
"\"crossed_embeds\"",
"]",
"=",
"tf",
".",
"feature_column",
".",
"embedding_column",
"(",
"categorical_column",
"=",
"crossed",
",",
"dimension",
"=",
"nembeds",
")",
"return",
"wide_fc",
",",
"deep_fc"
] | [
103,
0
] | [
142,
27
] | python | en | ['en', 'en', 'en'] | True |
get_model_outputs | (wide_inputs, deep_inputs, dnn_hidden_units) | Creates model architecture and returns outputs.
Args:
wide_inputs: Dense tensor used as inputs to wide side of model.
deep_inputs: Dense tensor used as inputs to deep side of model.
dnn_hidden_units: List of integers where length is number of hidden
layers and ith element is the number of neurons at ith layer.
Returns:
Dense tensor output from the model.
| Creates model architecture and returns outputs. | def get_model_outputs(wide_inputs, deep_inputs, dnn_hidden_units):
"""Creates model architecture and returns outputs.
Args:
wide_inputs: Dense tensor used as inputs to wide side of model.
deep_inputs: Dense tensor used as inputs to deep side of model.
dnn_hidden_units: List of integers where length is number of hidden
layers and ith element is the number of neurons at ith layer.
Returns:
Dense tensor output from the model.
"""
# Hidden layers for the deep side
layers = [int(x) for x in dnn_hidden_units]
deep = deep_inputs
for layerno, numnodes in enumerate(layers):
deep = tf.keras.layers.Dense(
units=numnodes,
activation="relu",
name="dnn_{}".format(layerno+1))(deep)
deep_out = deep
# Linear model for the wide side
wide_out = tf.keras.layers.Dense(
units=10, activation="relu", name="linear")(wide_inputs)
# Concatenate the two sides
both = tf.keras.layers.concatenate(
inputs=[deep_out, wide_out], name="both")
# Final output is a linear activation because this is regression
output = tf.keras.layers.Dense(
units=1, activation="linear", name="weight")(both)
return output | [
"def",
"get_model_outputs",
"(",
"wide_inputs",
",",
"deep_inputs",
",",
"dnn_hidden_units",
")",
":",
"# Hidden layers for the deep side",
"layers",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"dnn_hidden_units",
"]",
"deep",
"=",
"deep_inputs",
"for",
"layerno",
",",
"numnodes",
"in",
"enumerate",
"(",
"layers",
")",
":",
"deep",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"Dense",
"(",
"units",
"=",
"numnodes",
",",
"activation",
"=",
"\"relu\"",
",",
"name",
"=",
"\"dnn_{}\"",
".",
"format",
"(",
"layerno",
"+",
"1",
")",
")",
"(",
"deep",
")",
"deep_out",
"=",
"deep",
"# Linear model for the wide side",
"wide_out",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"Dense",
"(",
"units",
"=",
"10",
",",
"activation",
"=",
"\"relu\"",
",",
"name",
"=",
"\"linear\"",
")",
"(",
"wide_inputs",
")",
"# Concatenate the two sides",
"both",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"concatenate",
"(",
"inputs",
"=",
"[",
"deep_out",
",",
"wide_out",
"]",
",",
"name",
"=",
"\"both\"",
")",
"# Final output is a linear activation because this is regression",
"output",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"Dense",
"(",
"units",
"=",
"1",
",",
"activation",
"=",
"\"linear\"",
",",
"name",
"=",
"\"weight\"",
")",
"(",
"both",
")",
"return",
"output"
] | [
145,
0
] | [
178,
17
] | python | en | ['en', 'en', 'en'] | True |
rmse | (y_true, y_pred) | Calculates RMSE evaluation metric.
Args:
y_true: tensor, true labels.
y_pred: tensor, predicted labels.
Returns:
Tensor with value of RMSE between true and predicted labels.
| Calculates RMSE evaluation metric. | def rmse(y_true, y_pred):
"""Calculates RMSE evaluation metric.
Args:
y_true: tensor, true labels.
y_pred: tensor, predicted labels.
Returns:
Tensor with value of RMSE between true and predicted labels.
"""
return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) | [
"def",
"rmse",
"(",
"y_true",
",",
"y_pred",
")",
":",
"return",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_mean",
"(",
"tf",
".",
"square",
"(",
"y_pred",
"-",
"y_true",
")",
")",
")"
] | [
181,
0
] | [
190,
62
] | python | en | ['en', 'en', 'en'] | True |
build_wide_deep_model | (dnn_hidden_units=[64, 32], nembeds=3) | Builds wide and deep model using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
| Builds wide and deep model using Keras Functional API. | def build_wide_deep_model(dnn_hidden_units=[64, 32], nembeds=3):
"""Builds wide and deep model using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
"""
# Create input layers
inputs = create_input_layers()
# Create feature columns for both wide and deep
wide_fc, deep_fc = create_feature_columns(nembeds)
# The constructor for DenseFeatures takes a list of numeric columns
# The Functional API in Keras requires: LayerConstructor()(inputs)
wide_inputs = tf.keras.layers.DenseFeatures(
feature_columns=wide_fc.values(), name="wide_inputs")(inputs)
deep_inputs = tf.keras.layers.DenseFeatures(
feature_columns=deep_fc.values(), name="deep_inputs")(inputs)
# Get output of model given inputs
output = get_model_outputs(wide_inputs, deep_inputs, dnn_hidden_units)
# Build model and compile it all together
model = tf.keras.models.Model(inputs=inputs, outputs=output)
model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"])
return model | [
"def",
"build_wide_deep_model",
"(",
"dnn_hidden_units",
"=",
"[",
"64",
",",
"32",
"]",
",",
"nembeds",
"=",
"3",
")",
":",
"# Create input layers",
"inputs",
"=",
"create_input_layers",
"(",
")",
"# Create feature columns for both wide and deep",
"wide_fc",
",",
"deep_fc",
"=",
"create_feature_columns",
"(",
"nembeds",
")",
"# The constructor for DenseFeatures takes a list of numeric columns",
"# The Functional API in Keras requires: LayerConstructor()(inputs)",
"wide_inputs",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"DenseFeatures",
"(",
"feature_columns",
"=",
"wide_fc",
".",
"values",
"(",
")",
",",
"name",
"=",
"\"wide_inputs\"",
")",
"(",
"inputs",
")",
"deep_inputs",
"=",
"tf",
".",
"keras",
".",
"layers",
".",
"DenseFeatures",
"(",
"feature_columns",
"=",
"deep_fc",
".",
"values",
"(",
")",
",",
"name",
"=",
"\"deep_inputs\"",
")",
"(",
"inputs",
")",
"# Get output of model given inputs",
"output",
"=",
"get_model_outputs",
"(",
"wide_inputs",
",",
"deep_inputs",
",",
"dnn_hidden_units",
")",
"# Build model and compile it all together",
"model",
"=",
"tf",
".",
"keras",
".",
"models",
".",
"Model",
"(",
"inputs",
"=",
"inputs",
",",
"outputs",
"=",
"output",
")",
"model",
".",
"compile",
"(",
"optimizer",
"=",
"\"adam\"",
",",
"loss",
"=",
"\"mse\"",
",",
"metrics",
"=",
"[",
"rmse",
",",
"\"mse\"",
"]",
")",
"return",
"model"
] | [
193,
0
] | [
219,
16
] | python | en | ['en', 'en', 'en'] | True |
get_connection | (using=None) |
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
|
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
| def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
"""
if using is None:
using = DEFAULT_DB_ALIAS
return connections[using] | [
"def",
"get_connection",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"using",
"=",
"DEFAULT_DB_ALIAS",
"return",
"connections",
"[",
"using",
"]"
] | [
12,
0
] | [
19,
29
] | python | en | ['en', 'error', 'th'] | False |
get_autocommit | (using=None) | Get the autocommit status of the connection. | Get the autocommit status of the connection. | def get_autocommit(using=None):
"""Get the autocommit status of the connection."""
return get_connection(using).get_autocommit() | [
"def",
"get_autocommit",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_autocommit",
"(",
")"
] | [
22,
0
] | [
24,
49
] | python | en | ['en', 'en', 'en'] | True |
set_autocommit | (autocommit, using=None) | Set the autocommit status of the connection. | Set the autocommit status of the connection. | def set_autocommit(autocommit, using=None):
"""Set the autocommit status of the connection."""
return get_connection(using).set_autocommit(autocommit) | [
"def",
"set_autocommit",
"(",
"autocommit",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_autocommit",
"(",
"autocommit",
")"
] | [
27,
0
] | [
29,
59
] | python | en | ['en', 'en', 'en'] | True |
commit | (using=None) | Commit a transaction. | Commit a transaction. | def commit(using=None):
"""Commit a transaction."""
get_connection(using).commit() | [
"def",
"commit",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"commit",
"(",
")"
] | [
32,
0
] | [
34,
34
] | python | en | ['en', 'en', 'en'] | True |
rollback | (using=None) | Roll back a transaction. | Roll back a transaction. | def rollback(using=None):
"""Roll back a transaction."""
get_connection(using).rollback() | [
"def",
"rollback",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"rollback",
"(",
")"
] | [
37,
0
] | [
39,
36
] | python | en | ['en', 'en', 'en'] | True |
savepoint | (using=None) |
Create a savepoint (if supported and required by the backend) inside the
current transaction. Return an identifier for the savepoint that will be
used for the subsequent rollback or commit.
|
Create a savepoint (if supported and required by the backend) inside the
current transaction. Return an identifier for the savepoint that will be
used for the subsequent rollback or commit.
| def savepoint(using=None):
"""
Create a savepoint (if supported and required by the backend) inside the
current transaction. Return an identifier for the savepoint that will be
used for the subsequent rollback or commit.
"""
return get_connection(using).savepoint() | [
"def",
"savepoint",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"savepoint",
"(",
")"
] | [
42,
0
] | [
48,
44
] | python | en | ['en', 'error', 'th'] | False |
savepoint_rollback | (sid, using=None) |
Roll back the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
|
Roll back the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
| def savepoint_rollback(sid, using=None):
"""
Roll back the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_rollback(sid) | [
"def",
"savepoint_rollback",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_rollback",
"(",
"sid",
")"
] | [
51,
0
] | [
56,
49
] | python | en | ['en', 'error', 'th'] | False |
savepoint_commit | (sid, using=None) |
Commit the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
|
Commit the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
| def savepoint_commit(sid, using=None):
"""
Commit the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_commit(sid) | [
"def",
"savepoint_commit",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_commit",
"(",
"sid",
")"
] | [
59,
0
] | [
64,
47
] | python | en | ['en', 'error', 'th'] | False |
clean_savepoints | (using=None) |
Reset the counter used to generate unique savepoint ids in this thread.
|
Reset the counter used to generate unique savepoint ids in this thread.
| def clean_savepoints(using=None):
"""
Reset the counter used to generate unique savepoint ids in this thread.
"""
get_connection(using).clean_savepoints() | [
"def",
"clean_savepoints",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"clean_savepoints",
"(",
")"
] | [
67,
0
] | [
71,
44
] | python | en | ['en', 'error', 'th'] | False |
get_rollback | (using=None) | Get the "needs rollback" flag -- for *advanced use* only. | Get the "needs rollback" flag -- for *advanced use* only. | def get_rollback(using=None):
"""Get the "needs rollback" flag -- for *advanced use* only."""
return get_connection(using).get_rollback() | [
"def",
"get_rollback",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_rollback",
"(",
")"
] | [
74,
0
] | [
76,
47
] | python | en | ['en', 'en', 'en'] | True |
set_rollback | (rollback, using=None) |
Set or unset the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, trigger a rollback when exiting the innermost
enclosing atomic block that has `savepoint=True` (that's the default). Use
this to force a rollback without raising an exception.
When `rollback` is `False`, prevent such a rollback. Use this only after
rolling back to a known-good state! Otherwise, you break the atomic block
and data corruption may occur.
|
Set or unset the "needs rollback" flag -- for *advanced use* only. | def set_rollback(rollback, using=None):
"""
Set or unset the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, trigger a rollback when exiting the innermost
enclosing atomic block that has `savepoint=True` (that's the default). Use
this to force a rollback without raising an exception.
When `rollback` is `False`, prevent such a rollback. Use this only after
rolling back to a known-good state! Otherwise, you break the atomic block
and data corruption may occur.
"""
return get_connection(using).set_rollback(rollback) | [
"def",
"set_rollback",
"(",
"rollback",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_rollback",
"(",
"rollback",
")"
] | [
79,
0
] | [
91,
55
] | python | en | ['en', 'error', 'th'] | False |
mark_for_rollback_on_error | (using=None) |
Internal low-level utility to mark a transaction as "needs rollback" when
an exception is raised while not enforcing the enclosed block to be in a
transaction. This is needed by Model.save() and friends to avoid starting a
transaction when in autocommit mode and a single query is executed.
It's equivalent to:
connection = get_connection(using)
if connection.get_autocommit():
yield
else:
with transaction.atomic(using=using, savepoint=False):
yield
but it uses low-level utilities to avoid performance overhead.
|
Internal low-level utility to mark a transaction as "needs rollback" when
an exception is raised while not enforcing the enclosed block to be in a
transaction. This is needed by Model.save() and friends to avoid starting a
transaction when in autocommit mode and a single query is executed. | def mark_for_rollback_on_error(using=None):
"""
Internal low-level utility to mark a transaction as "needs rollback" when
an exception is raised while not enforcing the enclosed block to be in a
transaction. This is needed by Model.save() and friends to avoid starting a
transaction when in autocommit mode and a single query is executed.
It's equivalent to:
connection = get_connection(using)
if connection.get_autocommit():
yield
else:
with transaction.atomic(using=using, savepoint=False):
yield
but it uses low-level utilities to avoid performance overhead.
"""
try:
yield
except Exception:
connection = get_connection(using)
if connection.in_atomic_block:
connection.needs_rollback = True
raise | [
"def",
"mark_for_rollback_on_error",
"(",
"using",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"connection",
"=",
"get_connection",
"(",
"using",
")",
"if",
"connection",
".",
"in_atomic_block",
":",
"connection",
".",
"needs_rollback",
"=",
"True",
"raise"
] | [
95,
0
] | [
119,
13
] | python | en | ['en', 'error', 'th'] | False |
on_commit | (func, using=None) |
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
|
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
| def on_commit(func, using=None):
"""
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
"""
get_connection(using).on_commit(func) | [
"def",
"on_commit",
"(",
"func",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"on_commit",
"(",
"func",
")"
] | [
122,
0
] | [
127,
41
] | python | en | ['en', 'error', 'th'] | False |
Feed.feed_extra_kwargs | (self, obj) |
Return an extra keyword arguments dictionary that is used when
initializing the feed generator.
|
Return an extra keyword arguments dictionary that is used when
initializing the feed generator.
| def feed_extra_kwargs(self, obj):
"""
Return an extra keyword arguments dictionary that is used when
initializing the feed generator.
"""
return {} | [
"def",
"feed_extra_kwargs",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"}"
] | [
95,
4
] | [
100,
17
] | python | en | ['en', 'error', 'th'] | False |
Feed.item_extra_kwargs | (self, item) |
Return an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
|
Return an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
| def item_extra_kwargs(self, item):
"""
Return an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
"""
return {} | [
"def",
"item_extra_kwargs",
"(",
"self",
",",
"item",
")",
":",
"return",
"{",
"}"
] | [
102,
4
] | [
107,
17
] | python | en | ['en', 'error', 'th'] | False |
Feed.get_context_data | (self, **kwargs) |
Return a dictionary to use as extra context if either
``self.description_template`` or ``self.item_template`` are used.
Default implementation preserves the old behavior
of using {'obj': item, 'site': current_site} as the context.
|
Return a dictionary to use as extra context if either
``self.description_template`` or ``self.item_template`` are used. | def get_context_data(self, **kwargs):
"""
Return a dictionary to use as extra context if either
``self.description_template`` or ``self.item_template`` are used.
Default implementation preserves the old behavior
of using {'obj': item, 'site': current_site} as the context.
"""
return {'obj': kwargs.get('item'), 'site': kwargs.get('site')} | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"'obj'",
":",
"kwargs",
".",
"get",
"(",
"'item'",
")",
",",
"'site'",
":",
"kwargs",
".",
"get",
"(",
"'site'",
")",
"}"
] | [
112,
4
] | [
120,
70
] | python | en | ['en', 'error', 'th'] | False |
Feed.get_feed | (self, obj, request) |
Return a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raise FeedDoesNotExist for invalid parameters.
|
Return a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raise FeedDoesNotExist for invalid parameters.
| def get_feed(self, obj, request):
"""
Return a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raise FeedDoesNotExist for invalid parameters.
"""
current_site = get_current_site(request)
link = self._get_dynamic_attr('link', obj)
link = add_domain(current_site.domain, link, request.is_secure())
feed = self.feed_type(
title=self._get_dynamic_attr('title', obj),
subtitle=self._get_dynamic_attr('subtitle', obj),
link=link,
description=self._get_dynamic_attr('description', obj),
language=self.language or get_language(),
feed_url=add_domain(
current_site.domain,
self._get_dynamic_attr('feed_url', obj) or request.path,
request.is_secure(),
),
author_name=self._get_dynamic_attr('author_name', obj),
author_link=self._get_dynamic_attr('author_link', obj),
author_email=self._get_dynamic_attr('author_email', obj),
categories=self._get_dynamic_attr('categories', obj),
feed_copyright=self._get_dynamic_attr('feed_copyright', obj),
feed_guid=self._get_dynamic_attr('feed_guid', obj),
ttl=self._get_dynamic_attr('ttl', obj),
**self.feed_extra_kwargs(obj)
)
title_tmp = None
if self.title_template is not None:
try:
title_tmp = loader.get_template(self.title_template)
except TemplateDoesNotExist:
pass
description_tmp = None
if self.description_template is not None:
try:
description_tmp = loader.get_template(self.description_template)
except TemplateDoesNotExist:
pass
for item in self._get_dynamic_attr('items', obj):
context = self.get_context_data(item=item, site=current_site,
obj=obj, request=request)
if title_tmp is not None:
title = title_tmp.render(context, request)
else:
title = self._get_dynamic_attr('item_title', item)
if description_tmp is not None:
description = description_tmp.render(context, request)
else:
description = self._get_dynamic_attr('item_description', item)
link = add_domain(
current_site.domain,
self._get_dynamic_attr('item_link', item),
request.is_secure(),
)
enclosures = self._get_dynamic_attr('item_enclosures', item)
author_name = self._get_dynamic_attr('item_author_name', item)
if author_name is not None:
author_email = self._get_dynamic_attr('item_author_email', item)
author_link = self._get_dynamic_attr('item_author_link', item)
else:
author_email = author_link = None
tz = get_default_timezone()
pubdate = self._get_dynamic_attr('item_pubdate', item)
if pubdate and is_naive(pubdate):
pubdate = make_aware(pubdate, tz)
updateddate = self._get_dynamic_attr('item_updateddate', item)
if updateddate and is_naive(updateddate):
updateddate = make_aware(updateddate, tz)
feed.add_item(
title=title,
link=link,
description=description,
unique_id=self._get_dynamic_attr('item_guid', item, link),
unique_id_is_permalink=self._get_dynamic_attr(
'item_guid_is_permalink', item),
enclosures=enclosures,
pubdate=pubdate,
updateddate=updateddate,
author_name=author_name,
author_email=author_email,
author_link=author_link,
comments=self._get_dynamic_attr('item_comments', item),
categories=self._get_dynamic_attr('item_categories', item),
item_copyright=self._get_dynamic_attr('item_copyright', item),
**self.item_extra_kwargs(item)
)
return feed | [
"def",
"get_feed",
"(",
"self",
",",
"obj",
",",
"request",
")",
":",
"current_site",
"=",
"get_current_site",
"(",
"request",
")",
"link",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'link'",
",",
"obj",
")",
"link",
"=",
"add_domain",
"(",
"current_site",
".",
"domain",
",",
"link",
",",
"request",
".",
"is_secure",
"(",
")",
")",
"feed",
"=",
"self",
".",
"feed_type",
"(",
"title",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'title'",
",",
"obj",
")",
",",
"subtitle",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'subtitle'",
",",
"obj",
")",
",",
"link",
"=",
"link",
",",
"description",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'description'",
",",
"obj",
")",
",",
"language",
"=",
"self",
".",
"language",
"or",
"get_language",
"(",
")",
",",
"feed_url",
"=",
"add_domain",
"(",
"current_site",
".",
"domain",
",",
"self",
".",
"_get_dynamic_attr",
"(",
"'feed_url'",
",",
"obj",
")",
"or",
"request",
".",
"path",
",",
"request",
".",
"is_secure",
"(",
")",
",",
")",
",",
"author_name",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'author_name'",
",",
"obj",
")",
",",
"author_link",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'author_link'",
",",
"obj",
")",
",",
"author_email",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'author_email'",
",",
"obj",
")",
",",
"categories",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'categories'",
",",
"obj",
")",
",",
"feed_copyright",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'feed_copyright'",
",",
"obj",
")",
",",
"feed_guid",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'feed_guid'",
",",
"obj",
")",
",",
"ttl",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'ttl'",
",",
"obj",
")",
",",
"*",
"*",
"self",
".",
"feed_extra_kwargs",
"(",
"obj",
")",
")",
"title_tmp",
"=",
"None",
"if",
"self",
".",
"title_template",
"is",
"not",
"None",
":",
"try",
":",
"title_tmp",
"=",
"loader",
".",
"get_template",
"(",
"self",
".",
"title_template",
")",
"except",
"TemplateDoesNotExist",
":",
"pass",
"description_tmp",
"=",
"None",
"if",
"self",
".",
"description_template",
"is",
"not",
"None",
":",
"try",
":",
"description_tmp",
"=",
"loader",
".",
"get_template",
"(",
"self",
".",
"description_template",
")",
"except",
"TemplateDoesNotExist",
":",
"pass",
"for",
"item",
"in",
"self",
".",
"_get_dynamic_attr",
"(",
"'items'",
",",
"obj",
")",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"item",
"=",
"item",
",",
"site",
"=",
"current_site",
",",
"obj",
"=",
"obj",
",",
"request",
"=",
"request",
")",
"if",
"title_tmp",
"is",
"not",
"None",
":",
"title",
"=",
"title_tmp",
".",
"render",
"(",
"context",
",",
"request",
")",
"else",
":",
"title",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_title'",
",",
"item",
")",
"if",
"description_tmp",
"is",
"not",
"None",
":",
"description",
"=",
"description_tmp",
".",
"render",
"(",
"context",
",",
"request",
")",
"else",
":",
"description",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_description'",
",",
"item",
")",
"link",
"=",
"add_domain",
"(",
"current_site",
".",
"domain",
",",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_link'",
",",
"item",
")",
",",
"request",
".",
"is_secure",
"(",
")",
",",
")",
"enclosures",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_enclosures'",
",",
"item",
")",
"author_name",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_author_name'",
",",
"item",
")",
"if",
"author_name",
"is",
"not",
"None",
":",
"author_email",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_author_email'",
",",
"item",
")",
"author_link",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_author_link'",
",",
"item",
")",
"else",
":",
"author_email",
"=",
"author_link",
"=",
"None",
"tz",
"=",
"get_default_timezone",
"(",
")",
"pubdate",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_pubdate'",
",",
"item",
")",
"if",
"pubdate",
"and",
"is_naive",
"(",
"pubdate",
")",
":",
"pubdate",
"=",
"make_aware",
"(",
"pubdate",
",",
"tz",
")",
"updateddate",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_updateddate'",
",",
"item",
")",
"if",
"updateddate",
"and",
"is_naive",
"(",
"updateddate",
")",
":",
"updateddate",
"=",
"make_aware",
"(",
"updateddate",
",",
"tz",
")",
"feed",
".",
"add_item",
"(",
"title",
"=",
"title",
",",
"link",
"=",
"link",
",",
"description",
"=",
"description",
",",
"unique_id",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_guid'",
",",
"item",
",",
"link",
")",
",",
"unique_id_is_permalink",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_guid_is_permalink'",
",",
"item",
")",
",",
"enclosures",
"=",
"enclosures",
",",
"pubdate",
"=",
"pubdate",
",",
"updateddate",
"=",
"updateddate",
",",
"author_name",
"=",
"author_name",
",",
"author_email",
"=",
"author_email",
",",
"author_link",
"=",
"author_link",
",",
"comments",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_comments'",
",",
"item",
")",
",",
"categories",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_categories'",
",",
"item",
")",
",",
"item_copyright",
"=",
"self",
".",
"_get_dynamic_attr",
"(",
"'item_copyright'",
",",
"item",
")",
",",
"*",
"*",
"self",
".",
"item_extra_kwargs",
"(",
"item",
")",
")",
"return",
"feed"
] | [
122,
4
] | [
219,
19
] | python | en | ['en', 'error', 'th'] | False |
JSONMixin.json | (self) | The parsed JSON data if :attr:`mimetype` indicates JSON
(:mimetype:`application/json`, see :meth:`is_json`).
Calls :meth:`get_json` with default arguments.
| The parsed JSON data if :attr:`mimetype` indicates JSON
(:mimetype:`application/json`, see :meth:`is_json`). | def json(self):
"""The parsed JSON data if :attr:`mimetype` indicates JSON
(:mimetype:`application/json`, see :meth:`is_json`).
Calls :meth:`get_json` with default arguments.
"""
return self.get_json() | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_json",
"(",
")"
] | [
62,
4
] | [
68,
30
] | python | en | ['en', 'en', 'en'] | True |
JSONMixin.is_json | (self) | Check if the mimetype indicates JSON data, either
:mimetype:`application/json` or :mimetype:`application/*+json`.
| Check if the mimetype indicates JSON data, either
:mimetype:`application/json` or :mimetype:`application/*+json`.
| def is_json(self):
"""Check if the mimetype indicates JSON data, either
:mimetype:`application/json` or :mimetype:`application/*+json`.
"""
mt = self.mimetype
return (
mt == "application/json"
or mt.startswith("application/")
and mt.endswith("+json")
) | [
"def",
"is_json",
"(",
"self",
")",
":",
"mt",
"=",
"self",
".",
"mimetype",
"return",
"(",
"mt",
"==",
"\"application/json\"",
"or",
"mt",
".",
"startswith",
"(",
"\"application/\"",
")",
"and",
"mt",
".",
"endswith",
"(",
"\"+json\"",
")",
")"
] | [
71,
4
] | [
80,
9
] | python | en | ['en', 'en', 'en'] | True |
JSONMixin.get_json | (self, force=False, silent=False, cache=True) | Parse :attr:`data` as JSON.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :meth:`is_json`), this
returns ``None``.
If parsing fails, :meth:`on_json_loading_failed` is called and
its return value is used as the return value.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
:param cache: Store the parsed JSON to return for subsequent
calls.
| Parse :attr:`data` as JSON. | def get_json(self, force=False, silent=False, cache=True):
"""Parse :attr:`data` as JSON.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :meth:`is_json`), this
returns ``None``.
If parsing fails, :meth:`on_json_loading_failed` is called and
its return value is used as the return value.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
:param cache: Store the parsed JSON to return for subsequent
calls.
"""
if cache and self._cached_json[silent] is not Ellipsis:
return self._cached_json[silent]
if not (force or self.is_json):
return None
data = self._get_data_for_json(cache=cache)
try:
rv = self.json_module.loads(data)
except ValueError as e:
if silent:
rv = None
if cache:
normal_rv, _ = self._cached_json
self._cached_json = (normal_rv, rv)
else:
rv = self.on_json_loading_failed(e)
if cache:
_, silent_rv = self._cached_json
self._cached_json = (rv, silent_rv)
else:
if cache:
self._cached_json = (rv, rv)
return rv | [
"def",
"get_json",
"(",
"self",
",",
"force",
"=",
"False",
",",
"silent",
"=",
"False",
",",
"cache",
"=",
"True",
")",
":",
"if",
"cache",
"and",
"self",
".",
"_cached_json",
"[",
"silent",
"]",
"is",
"not",
"Ellipsis",
":",
"return",
"self",
".",
"_cached_json",
"[",
"silent",
"]",
"if",
"not",
"(",
"force",
"or",
"self",
".",
"is_json",
")",
":",
"return",
"None",
"data",
"=",
"self",
".",
"_get_data_for_json",
"(",
"cache",
"=",
"cache",
")",
"try",
":",
"rv",
"=",
"self",
".",
"json_module",
".",
"loads",
"(",
"data",
")",
"except",
"ValueError",
"as",
"e",
":",
"if",
"silent",
":",
"rv",
"=",
"None",
"if",
"cache",
":",
"normal_rv",
",",
"_",
"=",
"self",
".",
"_cached_json",
"self",
".",
"_cached_json",
"=",
"(",
"normal_rv",
",",
"rv",
")",
"else",
":",
"rv",
"=",
"self",
".",
"on_json_loading_failed",
"(",
"e",
")",
"if",
"cache",
":",
"_",
",",
"silent_rv",
"=",
"self",
".",
"_cached_json",
"self",
".",
"_cached_json",
"=",
"(",
"rv",
",",
"silent_rv",
")",
"else",
":",
"if",
"cache",
":",
"self",
".",
"_cached_json",
"=",
"(",
"rv",
",",
"rv",
")",
"return",
"rv"
] | [
93,
4
] | [
136,
17
] | python | de | ['en', 'de', 'ur'] | False |
JSONMixin.on_json_loading_failed | (self, e) | Called if :meth:`get_json` parsing fails and isn't silenced.
If this method returns a value, it is used as the return value
for :meth:`get_json`. The default implementation raises
:exc:`~werkzeug.exceptions.BadRequest`.
| Called if :meth:`get_json` parsing fails and isn't silenced.
If this method returns a value, it is used as the return value
for :meth:`get_json`. The default implementation raises
:exc:`~werkzeug.exceptions.BadRequest`.
| def on_json_loading_failed(self, e):
"""Called if :meth:`get_json` parsing fails and isn't silenced.
If this method returns a value, it is used as the return value
for :meth:`get_json`. The default implementation raises
:exc:`~werkzeug.exceptions.BadRequest`.
"""
raise BadRequest("Failed to decode JSON object: {0}".format(e)) | [
"def",
"on_json_loading_failed",
"(",
"self",
",",
"e",
")",
":",
"raise",
"BadRequest",
"(",
"\"Failed to decode JSON object: {0}\"",
".",
"format",
"(",
"e",
")",
")"
] | [
138,
4
] | [
144,
71
] | python | en | ['en', 'en', 'en'] | True |
description_of | (lines, name='stdin') |
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
|
Return a string describing the probable encoding of a file or
list of strings. | def description_of(lines, name='stdin'):
"""
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
"""
u = UniversalDetector()
for line in lines:
line = bytearray(line)
u.feed(line)
# shortcut out of the loop to save reading further - particularly useful if we read a BOM.
if u.done:
break
u.close()
result = u.result
if PY2:
name = name.decode(sys.getfilesystemencoding(), 'ignore')
if result['encoding']:
return '{}: {} with confidence {}'.format(name, result['encoding'],
result['confidence'])
else:
return '{}: no result'.format(name) | [
"def",
"description_of",
"(",
"lines",
",",
"name",
"=",
"'stdin'",
")",
":",
"u",
"=",
"UniversalDetector",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"bytearray",
"(",
"line",
")",
"u",
".",
"feed",
"(",
"line",
")",
"# shortcut out of the loop to save reading further - particularly useful if we read a BOM.",
"if",
"u",
".",
"done",
":",
"break",
"u",
".",
"close",
"(",
")",
"result",
"=",
"u",
".",
"result",
"if",
"PY2",
":",
"name",
"=",
"name",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
",",
"'ignore'",
")",
"if",
"result",
"[",
"'encoding'",
"]",
":",
"return",
"'{}: {} with confidence {}'",
".",
"format",
"(",
"name",
",",
"result",
"[",
"'encoding'",
"]",
",",
"result",
"[",
"'confidence'",
"]",
")",
"else",
":",
"return",
"'{}: no result'",
".",
"format",
"(",
"name",
")"
] | [
24,
0
] | [
49,
43
] | python | en | ['en', 'error', 'th'] | False |
main | (argv=None) |
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
|
Handles command line arguments and gets things started. | def main(argv=None):
"""
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
"""
# Get command line arguments
parser = argparse.ArgumentParser(
description="Takes one or more file paths and reports their detected \
encodings")
parser.add_argument('input',
help='File whose encoding we would like to determine. \
(default: stdin)',
type=argparse.FileType('rb'), nargs='*',
default=[sys.stdin if PY2 else sys.stdin.buffer])
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__))
args = parser.parse_args(argv)
for f in args.input:
if f.isatty():
print("You are running chardetect interactively. Press " +
"CTRL-D twice at the start of a blank line to signal the " +
"end of your input. If you want help, run chardetect " +
"--help\n", file=sys.stderr)
print(description_of(f, f.name)) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"# Get command line arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Takes one or more file paths and reports their detected \\\n encodings\"",
")",
"parser",
".",
"add_argument",
"(",
"'input'",
",",
"help",
"=",
"'File whose encoding we would like to determine. \\\n (default: stdin)'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'rb'",
")",
",",
"nargs",
"=",
"'*'",
",",
"default",
"=",
"[",
"sys",
".",
"stdin",
"if",
"PY2",
"else",
"sys",
".",
"stdin",
".",
"buffer",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s {}'",
".",
"format",
"(",
"__version__",
")",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"for",
"f",
"in",
"args",
".",
"input",
":",
"if",
"f",
".",
"isatty",
"(",
")",
":",
"print",
"(",
"\"You are running chardetect interactively. Press \"",
"+",
"\"CTRL-D twice at the start of a blank line to signal the \"",
"+",
"\"end of your input. If you want help, run chardetect \"",
"+",
"\"--help\\n\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"description_of",
"(",
"f",
",",
"f",
".",
"name",
")",
")"
] | [
52,
0
] | [
79,
40
] | python | en | ['en', 'error', 'th'] | False |
get_session_data | (transaction, session_id) | Looks up (or creates) the session with the given session_id.
Creates a random session_id if none is provided. Increments
the number of views in this session. Updates are done in a
transaction to make sure no saved increments are overwritten.
| Looks up (or creates) the session with the given session_id.
Creates a random session_id if none is provided. Increments
the number of views in this session. Updates are done in a
transaction to make sure no saved increments are overwritten.
| def get_session_data(transaction, session_id):
""" Looks up (or creates) the session with the given session_id.
Creates a random session_id if none is provided. Increments
the number of views in this session. Updates are done in a
transaction to make sure no saved increments are overwritten.
"""
if session_id is None:
session_id = str(uuid4()) # Random, unique identifier
doc_ref = sessions.document(document_id=session_id)
doc = doc_ref.get(transaction=transaction)
if doc.exists:
session = doc.to_dict()
else:
session = {
'greeting': random.choice(greetings),
'views': 0
}
session['views'] += 1 # This counts as a view
transaction.set(doc_ref, session)
session['session_id'] = session_id
return session | [
"def",
"get_session_data",
"(",
"transaction",
",",
"session_id",
")",
":",
"if",
"session_id",
"is",
"None",
":",
"session_id",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"# Random, unique identifier",
"doc_ref",
"=",
"sessions",
".",
"document",
"(",
"document_id",
"=",
"session_id",
")",
"doc",
"=",
"doc_ref",
".",
"get",
"(",
"transaction",
"=",
"transaction",
")",
"if",
"doc",
".",
"exists",
":",
"session",
"=",
"doc",
".",
"to_dict",
"(",
")",
"else",
":",
"session",
"=",
"{",
"'greeting'",
":",
"random",
".",
"choice",
"(",
"greetings",
")",
",",
"'views'",
":",
"0",
"}",
"session",
"[",
"'views'",
"]",
"+=",
"1",
"# This counts as a view",
"transaction",
".",
"set",
"(",
"doc_ref",
",",
"session",
")",
"session",
"[",
"'session_id'",
"]",
"=",
"session_id",
"return",
"session"
] | [
34,
0
] | [
57,
18
] | python | en | ['en', 'en', 'en'] | True |
generate_a_pyrex_source | (self, base, ext_name, source, extension) | Monkey patch for numpy build_src.build_src method
Uses Cython instead of Pyrex.
Assumes Cython is present
| Monkey patch for numpy build_src.build_src method
Uses Cython instead of Pyrex.
Assumes Cython is present
| def generate_a_pyrex_source(self, base, ext_name, source, extension):
''' Monkey patch for numpy build_src.build_src method
Uses Cython instead of Pyrex.
Assumes Cython is present
'''
if self.inplace:
target_dir = dirname(base)
else:
target_dir = appendpath(self.build_src, dirname(base))
target_file = pjoin(target_dir, ext_name + '.c')
depends = [source] + extension.depends
if self.force or newer_group(depends, target_file, 'newer'):
import Cython.Compiler.Main
log.info("cythonc:> %s" % (target_file))
self.mkpath(target_dir)
options = Cython.Compiler.Main.CompilationOptions(
defaults=Cython.Compiler.Main.default_options,
include_path=extension.include_dirs,
output_file=target_file)
cython_result = Cython.Compiler.Main.compile(source, options=options)
if cython_result.num_errors != 0:
raise DistutilsError("%d errors while compiling %r with Cython" % (cython_result.num_errors, source))
return target_file | [
"def",
"generate_a_pyrex_source",
"(",
"self",
",",
"base",
",",
"ext_name",
",",
"source",
",",
"extension",
")",
":",
"if",
"self",
".",
"inplace",
":",
"target_dir",
"=",
"dirname",
"(",
"base",
")",
"else",
":",
"target_dir",
"=",
"appendpath",
"(",
"self",
".",
"build_src",
",",
"dirname",
"(",
"base",
")",
")",
"target_file",
"=",
"pjoin",
"(",
"target_dir",
",",
"ext_name",
"+",
"'.c'",
")",
"depends",
"=",
"[",
"source",
"]",
"+",
"extension",
".",
"depends",
"if",
"self",
".",
"force",
"or",
"newer_group",
"(",
"depends",
",",
"target_file",
",",
"'newer'",
")",
":",
"import",
"Cython",
".",
"Compiler",
".",
"Main",
"log",
".",
"info",
"(",
"\"cythonc:> %s\"",
"%",
"(",
"target_file",
")",
")",
"self",
".",
"mkpath",
"(",
"target_dir",
")",
"options",
"=",
"Cython",
".",
"Compiler",
".",
"Main",
".",
"CompilationOptions",
"(",
"defaults",
"=",
"Cython",
".",
"Compiler",
".",
"Main",
".",
"default_options",
",",
"include_path",
"=",
"extension",
".",
"include_dirs",
",",
"output_file",
"=",
"target_file",
")",
"cython_result",
"=",
"Cython",
".",
"Compiler",
".",
"Main",
".",
"compile",
"(",
"source",
",",
"options",
"=",
"options",
")",
"if",
"cython_result",
".",
"num_errors",
"!=",
"0",
":",
"raise",
"DistutilsError",
"(",
"\"%d errors while compiling %r with Cython\"",
"%",
"(",
"cython_result",
".",
"num_errors",
",",
"source",
")",
")",
"return",
"target_file"
] | [
40,
0
] | [
62,
22
] | python | en | ['en', 'fr', 'en'] | True |
ConfigurationCommand.list_config_values | (self, options: Values, args: List[str]) | List config key-value pairs across different config files | List config key-value pairs across different config files | def list_config_values(self, options: Values, args: List[str]) -> None:
"""List config key-value pairs across different config files"""
self._get_n_args(args, "debug", n=0)
self.print_env_var_values()
# Iterate over config files and print if they exist, and the
# key-value pairs present in them if they do
for variant, files in sorted(self.configuration.iter_config_files()):
write_output("%s:", variant)
for fname in files:
with indent_log():
file_exists = os.path.exists(fname)
write_output("%s, exists: %r",
fname, file_exists)
if file_exists:
self.print_config_file_values(variant) | [
"def",
"list_config_values",
"(",
"self",
",",
"options",
":",
"Values",
",",
"args",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"self",
".",
"_get_n_args",
"(",
"args",
",",
"\"debug\"",
",",
"n",
"=",
"0",
")",
"self",
".",
"print_env_var_values",
"(",
")",
"# Iterate over config files and print if they exist, and the",
"# key-value pairs present in them if they do",
"for",
"variant",
",",
"files",
"in",
"sorted",
"(",
"self",
".",
"configuration",
".",
"iter_config_files",
"(",
")",
")",
":",
"write_output",
"(",
"\"%s:\"",
",",
"variant",
")",
"for",
"fname",
"in",
"files",
":",
"with",
"indent_log",
"(",
")",
":",
"file_exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
"write_output",
"(",
"\"%s, exists: %r\"",
",",
"fname",
",",
"file_exists",
")",
"if",
"file_exists",
":",
"self",
".",
"print_config_file_values",
"(",
"variant",
")"
] | [
184,
4
] | [
199,
62
] | python | en | ['fr', 'en', 'en'] | True |
ConfigurationCommand.print_config_file_values | (self, variant: Kind) | Get key-value pairs from the file of a variant | Get key-value pairs from the file of a variant | def print_config_file_values(self, variant: Kind) -> None:
"""Get key-value pairs from the file of a variant"""
for name, value in self.configuration.\
get_values_in_config(variant).items():
with indent_log():
write_output("%s: %s", name, value) | [
"def",
"print_config_file_values",
"(",
"self",
",",
"variant",
":",
"Kind",
")",
"->",
"None",
":",
"for",
"name",
",",
"value",
"in",
"self",
".",
"configuration",
".",
"get_values_in_config",
"(",
"variant",
")",
".",
"items",
"(",
")",
":",
"with",
"indent_log",
"(",
")",
":",
"write_output",
"(",
"\"%s: %s\"",
",",
"name",
",",
"value",
")"
] | [
201,
4
] | [
206,
51
] | python | en | ['en', 'en', 'en'] | True |
ConfigurationCommand.print_env_var_values | (self) | Get key-values pairs present as environment variables | Get key-values pairs present as environment variables | def print_env_var_values(self) -> None:
"""Get key-values pairs present as environment variables"""
write_output("%s:", 'env_var')
with indent_log():
for key, value in sorted(self.configuration.get_environ_vars()):
env_var = f'PIP_{key.upper()}'
write_output("%s=%r", env_var, value) | [
"def",
"print_env_var_values",
"(",
"self",
")",
"->",
"None",
":",
"write_output",
"(",
"\"%s:\"",
",",
"'env_var'",
")",
"with",
"indent_log",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"configuration",
".",
"get_environ_vars",
"(",
")",
")",
":",
"env_var",
"=",
"f'PIP_{key.upper()}'",
"write_output",
"(",
"\"%s=%r\"",
",",
"env_var",
",",
"value",
")"
] | [
208,
4
] | [
214,
53
] | python | en | ['fr', 'en', 'en'] | True |
ConfigurationCommand._get_n_args | (self, args: List[str], example: str, n: int) | Helper to make sure the command got the right number of arguments
| Helper to make sure the command got the right number of arguments
| def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
"""Helper to make sure the command got the right number of arguments
"""
if len(args) != n:
msg = (
'Got unexpected number of arguments, expected {}. '
'(example: "{} config {}")'
).format(n, get_prog(), example)
raise PipError(msg)
if n == 1:
return args[0]
else:
return args | [
"def",
"_get_n_args",
"(",
"self",
",",
"args",
":",
"List",
"[",
"str",
"]",
",",
"example",
":",
"str",
",",
"n",
":",
"int",
")",
"->",
"Any",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"n",
":",
"msg",
"=",
"(",
"'Got unexpected number of arguments, expected {}. '",
"'(example: \"{} config {}\")'",
")",
".",
"format",
"(",
"n",
",",
"get_prog",
"(",
")",
",",
"example",
")",
"raise",
"PipError",
"(",
"msg",
")",
"if",
"n",
"==",
"1",
":",
"return",
"args",
"[",
"0",
"]",
"else",
":",
"return",
"args"
] | [
231,
4
] | [
244,
23
] | python | en | ['en', 'en', 'en'] | True |
incoming_call | (request) | Twilio Voice URL - receives incoming calls from Twilio | Twilio Voice URL - receives incoming calls from Twilio | def incoming_call(request):
"""Twilio Voice URL - receives incoming calls from Twilio"""
# Create a new TwiML response
resp = VoiceResponse()
# <Say> a message to the caller
from_number = request.POST['From']
body = """
Thanks for calling!
Your phone number is {0}. I got your call because of Twilio's webhook.
Goodbye!""".format(' '.join(from_number))
resp.say(body)
# Return the TwiML
return HttpResponse(resp) | [
"def",
"incoming_call",
"(",
"request",
")",
":",
"# Create a new TwiML response",
"resp",
"=",
"VoiceResponse",
"(",
")",
"# <Say> a message to the caller",
"from_number",
"=",
"request",
".",
"POST",
"[",
"'From'",
"]",
"body",
"=",
"\"\"\"\n Thanks for calling!\n\n Your phone number is {0}. I got your call because of Twilio's webhook.\n\n Goodbye!\"\"\"",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"from_number",
")",
")",
"resp",
".",
"say",
"(",
"body",
")",
"# Return the TwiML",
"return",
"HttpResponse",
"(",
"resp",
")"
] | [
9,
0
] | [
25,
29
] | python | en | ['en', 'la', 'en'] | True |
incoming_message | (request) | Twilio Messaging URL - receives incoming messages from Twilio | Twilio Messaging URL - receives incoming messages from Twilio | def incoming_message(request):
"""Twilio Messaging URL - receives incoming messages from Twilio"""
# Create a new TwiML response
resp = MessagingResponse()
# <Message> a text back to the person who texted us
body = "Your text to me was {0} characters long. Webhooks are neat :)" \
.format(len(request.POST['Body']))
resp.message(body)
# Return the TwiML
return HttpResponse(resp) | [
"def",
"incoming_message",
"(",
"request",
")",
":",
"# Create a new TwiML response",
"resp",
"=",
"MessagingResponse",
"(",
")",
"# <Message> a text back to the person who texted us",
"body",
"=",
"\"Your text to me was {0} characters long. Webhooks are neat :)\"",
".",
"format",
"(",
"len",
"(",
"request",
".",
"POST",
"[",
"'Body'",
"]",
")",
")",
"resp",
".",
"message",
"(",
"body",
")",
"# Return the TwiML",
"return",
"HttpResponse",
"(",
"resp",
")"
] | [
31,
0
] | [
42,
29
] | python | en | ['en', 'en', 'en'] | True |
BaseModelAdmin.formfield_for_dbfield | (self, db_field, request, **kwargs) |
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
|
Hook for specifying the form Field instance for a given database Field
instance. | def formfield_for_dbfield(self, db_field, request, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
# ForeignKey or ManyToManyFields
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
# Combine the field kwargs with any options for formfield_overrides.
# Make sure the passed in **kwargs override anything in
# formfield_overrides because **kwargs is more specific, and should
# always win.
if db_field.__class__ in self.formfield_overrides:
kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs}
# Get the correct formfield.
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(db_field.remote_field.model)
wrapper_kwargs = {}
if related_modeladmin:
wrapper_kwargs.update(
can_add_related=related_modeladmin.has_add_permission(request),
can_change_related=related_modeladmin.has_change_permission(request),
can_delete_related=related_modeladmin.has_delete_permission(request),
can_view_related=related_modeladmin.has_view_permission(request),
)
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs
)
return formfield
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs}
return db_field.formfield(**kwargs)
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs) | [
"def",
"formfield_for_dbfield",
"(",
"self",
",",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# If the field specifies choices, we don't need to look for special",
"# admin widgets - we just need to use a select widget of some kind.",
"if",
"db_field",
".",
"choices",
":",
"return",
"self",
".",
"formfield_for_choice_field",
"(",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
"# ForeignKey or ManyToManyFields",
"if",
"isinstance",
"(",
"db_field",
",",
"(",
"models",
".",
"ForeignKey",
",",
"models",
".",
"ManyToManyField",
")",
")",
":",
"# Combine the field kwargs with any options for formfield_overrides.",
"# Make sure the passed in **kwargs override anything in",
"# formfield_overrides because **kwargs is more specific, and should",
"# always win.",
"if",
"db_field",
".",
"__class__",
"in",
"self",
".",
"formfield_overrides",
":",
"kwargs",
"=",
"{",
"*",
"*",
"self",
".",
"formfield_overrides",
"[",
"db_field",
".",
"__class__",
"]",
",",
"*",
"*",
"kwargs",
"}",
"# Get the correct formfield.",
"if",
"isinstance",
"(",
"db_field",
",",
"models",
".",
"ForeignKey",
")",
":",
"formfield",
"=",
"self",
".",
"formfield_for_foreignkey",
"(",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
"elif",
"isinstance",
"(",
"db_field",
",",
"models",
".",
"ManyToManyField",
")",
":",
"formfield",
"=",
"self",
".",
"formfield_for_manytomany",
"(",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
"# For non-raw_id fields, wrap the widget with a wrapper that adds",
"# extra HTML -- the \"add other\" interface -- to the end of the",
"# rendered output. formfield can be None if it came from a",
"# OneToOneField with parent_link=True or a M2M intermediary.",
"if",
"formfield",
"and",
"db_field",
".",
"name",
"not",
"in",
"self",
".",
"raw_id_fields",
":",
"related_modeladmin",
"=",
"self",
".",
"admin_site",
".",
"_registry",
".",
"get",
"(",
"db_field",
".",
"remote_field",
".",
"model",
")",
"wrapper_kwargs",
"=",
"{",
"}",
"if",
"related_modeladmin",
":",
"wrapper_kwargs",
".",
"update",
"(",
"can_add_related",
"=",
"related_modeladmin",
".",
"has_add_permission",
"(",
"request",
")",
",",
"can_change_related",
"=",
"related_modeladmin",
".",
"has_change_permission",
"(",
"request",
")",
",",
"can_delete_related",
"=",
"related_modeladmin",
".",
"has_delete_permission",
"(",
"request",
")",
",",
"can_view_related",
"=",
"related_modeladmin",
".",
"has_view_permission",
"(",
"request",
")",
",",
")",
"formfield",
".",
"widget",
"=",
"widgets",
".",
"RelatedFieldWidgetWrapper",
"(",
"formfield",
".",
"widget",
",",
"db_field",
".",
"remote_field",
",",
"self",
".",
"admin_site",
",",
"*",
"*",
"wrapper_kwargs",
")",
"return",
"formfield",
"# If we've got overrides for the formfield defined, use 'em. **kwargs",
"# passed to formfield_for_dbfield override the defaults.",
"for",
"klass",
"in",
"db_field",
".",
"__class__",
".",
"mro",
"(",
")",
":",
"if",
"klass",
"in",
"self",
".",
"formfield_overrides",
":",
"kwargs",
"=",
"{",
"*",
"*",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"formfield_overrides",
"[",
"klass",
"]",
")",
",",
"*",
"*",
"kwargs",
"}",
"return",
"db_field",
".",
"formfield",
"(",
"*",
"*",
"kwargs",
")",
"# For any other type of field, just call its formfield() method.",
"return",
"db_field",
".",
"formfield",
"(",
"*",
"*",
"kwargs",
")"
] | [
131,
4
] | [
186,
43
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.formfield_for_choice_field | (self, db_field, request, **kwargs) |
Get a form Field for a database Field that has declared choices.
|
Get a form Field for a database Field that has declared choices.
| def formfield_for_choice_field(self, db_field, request, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank=db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs) | [
"def",
"formfield_for_choice_field",
"(",
"self",
",",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# If the field is named as a radio_field, use a RadioSelect",
"if",
"db_field",
".",
"name",
"in",
"self",
".",
"radio_fields",
":",
"# Avoid stomping on custom widget/choices arguments.",
"if",
"'widget'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"widgets",
".",
"AdminRadioSelect",
"(",
"attrs",
"=",
"{",
"'class'",
":",
"get_ul_class",
"(",
"self",
".",
"radio_fields",
"[",
"db_field",
".",
"name",
"]",
")",
",",
"}",
")",
"if",
"'choices'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'choices'",
"]",
"=",
"db_field",
".",
"get_choices",
"(",
"include_blank",
"=",
"db_field",
".",
"blank",
",",
"blank_choice",
"=",
"[",
"(",
"''",
",",
"_",
"(",
"'None'",
")",
")",
"]",
")",
"return",
"db_field",
".",
"formfield",
"(",
"*",
"*",
"kwargs",
")"
] | [
188,
4
] | [
204,
43
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_field_queryset | (self, db, db_field, request) |
If the ModelAdmin specifies ordering, the queryset should respect that
ordering. Otherwise don't specify the queryset, let the field decide
(return None in that case).
|
If the ModelAdmin specifies ordering, the queryset should respect that
ordering. Otherwise don't specify the queryset, let the field decide
(return None in that case).
| def get_field_queryset(self, db, db_field, request):
"""
If the ModelAdmin specifies ordering, the queryset should respect that
ordering. Otherwise don't specify the queryset, let the field decide
(return None in that case).
"""
related_admin = self.admin_site._registry.get(db_field.remote_field.model)
if related_admin is not None:
ordering = related_admin.get_ordering(request)
if ordering is not None and ordering != ():
return db_field.remote_field.model._default_manager.using(db).order_by(*ordering)
return None | [
"def",
"get_field_queryset",
"(",
"self",
",",
"db",
",",
"db_field",
",",
"request",
")",
":",
"related_admin",
"=",
"self",
".",
"admin_site",
".",
"_registry",
".",
"get",
"(",
"db_field",
".",
"remote_field",
".",
"model",
")",
"if",
"related_admin",
"is",
"not",
"None",
":",
"ordering",
"=",
"related_admin",
".",
"get_ordering",
"(",
"request",
")",
"if",
"ordering",
"is",
"not",
"None",
"and",
"ordering",
"!=",
"(",
")",
":",
"return",
"db_field",
".",
"remote_field",
".",
"model",
".",
"_default_manager",
".",
"using",
"(",
"db",
")",
".",
"order_by",
"(",
"*",
"ordering",
")",
"return",
"None"
] | [
206,
4
] | [
217,
19
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.formfield_for_foreignkey | (self, db_field, request, **kwargs) |
Get a form Field for a ForeignKey.
|
Get a form Field for a ForeignKey.
| def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""
Get a form Field for a ForeignKey.
"""
db = kwargs.get('using')
if 'widget' not in kwargs:
if db_field.name in self.get_autocomplete_fields(request):
kwargs['widget'] = AutocompleteSelect(db_field, self.admin_site, using=db)
elif db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db)
elif db_field.name in self.radio_fields:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
kwargs['empty_label'] = _('None') if db_field.blank else None
if 'queryset' not in kwargs:
queryset = self.get_field_queryset(db, db_field, request)
if queryset is not None:
kwargs['queryset'] = queryset
return db_field.formfield(**kwargs) | [
"def",
"formfield_for_foreignkey",
"(",
"self",
",",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"db",
"=",
"kwargs",
".",
"get",
"(",
"'using'",
")",
"if",
"'widget'",
"not",
"in",
"kwargs",
":",
"if",
"db_field",
".",
"name",
"in",
"self",
".",
"get_autocomplete_fields",
"(",
"request",
")",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"AutocompleteSelect",
"(",
"db_field",
",",
"self",
".",
"admin_site",
",",
"using",
"=",
"db",
")",
"elif",
"db_field",
".",
"name",
"in",
"self",
".",
"raw_id_fields",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"widgets",
".",
"ForeignKeyRawIdWidget",
"(",
"db_field",
".",
"remote_field",
",",
"self",
".",
"admin_site",
",",
"using",
"=",
"db",
")",
"elif",
"db_field",
".",
"name",
"in",
"self",
".",
"radio_fields",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"widgets",
".",
"AdminRadioSelect",
"(",
"attrs",
"=",
"{",
"'class'",
":",
"get_ul_class",
"(",
"self",
".",
"radio_fields",
"[",
"db_field",
".",
"name",
"]",
")",
",",
"}",
")",
"kwargs",
"[",
"'empty_label'",
"]",
"=",
"_",
"(",
"'None'",
")",
"if",
"db_field",
".",
"blank",
"else",
"None",
"if",
"'queryset'",
"not",
"in",
"kwargs",
":",
"queryset",
"=",
"self",
".",
"get_field_queryset",
"(",
"db",
",",
"db_field",
",",
"request",
")",
"if",
"queryset",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'queryset'",
"]",
"=",
"queryset",
"return",
"db_field",
".",
"formfield",
"(",
"*",
"*",
"kwargs",
")"
] | [
219,
4
] | [
241,
43
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.formfield_for_manytomany | (self, db_field, request, **kwargs) |
Get a form Field for a ManyToManyField.
|
Get a form Field for a ManyToManyField.
| def formfield_for_manytomany(self, db_field, request, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.remote_field.through._meta.auto_created:
return None
db = kwargs.get('using')
if 'widget' not in kwargs:
autocomplete_fields = self.get_autocomplete_fields(request)
if db_field.name in autocomplete_fields:
kwargs['widget'] = AutocompleteSelectMultiple(
db_field,
self.admin_site,
using=db,
)
elif db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(
db_field.remote_field,
self.admin_site,
using=db,
)
elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]:
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
db_field.name in self.filter_vertical
)
if 'queryset' not in kwargs:
queryset = self.get_field_queryset(db, db_field, request)
if queryset is not None:
kwargs['queryset'] = queryset
form_field = db_field.formfield(**kwargs)
if (isinstance(form_field.widget, SelectMultiple) and
not isinstance(form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple))):
msg = _('Hold down “Control”, or “Command” on a Mac, to select more than one.')
help_text = form_field.help_text
form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg
return form_field | [
"def",
"formfield_for_manytomany",
"(",
"self",
",",
"db_field",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# If it uses an intermediary model that isn't auto created, don't show",
"# a field in admin.",
"if",
"not",
"db_field",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"auto_created",
":",
"return",
"None",
"db",
"=",
"kwargs",
".",
"get",
"(",
"'using'",
")",
"if",
"'widget'",
"not",
"in",
"kwargs",
":",
"autocomplete_fields",
"=",
"self",
".",
"get_autocomplete_fields",
"(",
"request",
")",
"if",
"db_field",
".",
"name",
"in",
"autocomplete_fields",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"AutocompleteSelectMultiple",
"(",
"db_field",
",",
"self",
".",
"admin_site",
",",
"using",
"=",
"db",
",",
")",
"elif",
"db_field",
".",
"name",
"in",
"self",
".",
"raw_id_fields",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"widgets",
".",
"ManyToManyRawIdWidget",
"(",
"db_field",
".",
"remote_field",
",",
"self",
".",
"admin_site",
",",
"using",
"=",
"db",
",",
")",
"elif",
"db_field",
".",
"name",
"in",
"[",
"*",
"self",
".",
"filter_vertical",
",",
"*",
"self",
".",
"filter_horizontal",
"]",
":",
"kwargs",
"[",
"'widget'",
"]",
"=",
"widgets",
".",
"FilteredSelectMultiple",
"(",
"db_field",
".",
"verbose_name",
",",
"db_field",
".",
"name",
"in",
"self",
".",
"filter_vertical",
")",
"if",
"'queryset'",
"not",
"in",
"kwargs",
":",
"queryset",
"=",
"self",
".",
"get_field_queryset",
"(",
"db",
",",
"db_field",
",",
"request",
")",
"if",
"queryset",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'queryset'",
"]",
"=",
"queryset",
"form_field",
"=",
"db_field",
".",
"formfield",
"(",
"*",
"*",
"kwargs",
")",
"if",
"(",
"isinstance",
"(",
"form_field",
".",
"widget",
",",
"SelectMultiple",
")",
"and",
"not",
"isinstance",
"(",
"form_field",
".",
"widget",
",",
"(",
"CheckboxSelectMultiple",
",",
"AutocompleteSelectMultiple",
")",
")",
")",
":",
"msg",
"=",
"_",
"(",
"'Hold down “Control”, or “Command” on a Mac, to select more than one.')",
"",
"help_text",
"=",
"form_field",
".",
"help_text",
"form_field",
".",
"help_text",
"=",
"format_lazy",
"(",
"'{} {}'",
",",
"help_text",
",",
"msg",
")",
"if",
"help_text",
"else",
"msg",
"return",
"form_field"
] | [
243,
4
] | [
283,
25
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_autocomplete_fields | (self, request) |
Return a list of ForeignKey and/or ManyToMany fields which should use
an autocomplete widget.
|
Return a list of ForeignKey and/or ManyToMany fields which should use
an autocomplete widget.
| def get_autocomplete_fields(self, request):
"""
Return a list of ForeignKey and/or ManyToMany fields which should use
an autocomplete widget.
"""
return self.autocomplete_fields | [
"def",
"get_autocomplete_fields",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"autocomplete_fields"
] | [
285,
4
] | [
290,
39
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_empty_value_display | (self) |
Return the empty_value_display set on ModelAdmin or AdminSite.
|
Return the empty_value_display set on ModelAdmin or AdminSite.
| def get_empty_value_display(self):
"""
Return the empty_value_display set on ModelAdmin or AdminSite.
"""
try:
return mark_safe(self.empty_value_display)
except AttributeError:
return mark_safe(self.admin_site.empty_value_display) | [
"def",
"get_empty_value_display",
"(",
"self",
")",
":",
"try",
":",
"return",
"mark_safe",
"(",
"self",
".",
"empty_value_display",
")",
"except",
"AttributeError",
":",
"return",
"mark_safe",
"(",
"self",
".",
"admin_site",
".",
"empty_value_display",
")"
] | [
305,
4
] | [
312,
65
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_exclude | (self, request, obj=None) |
Hook for specifying exclude.
|
Hook for specifying exclude.
| def get_exclude(self, request, obj=None):
"""
Hook for specifying exclude.
"""
return self.exclude | [
"def",
"get_exclude",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"self",
".",
"exclude"
] | [
314,
4
] | [
318,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_fields | (self, request, obj=None) |
Hook for specifying fields.
|
Hook for specifying fields.
| def get_fields(self, request, obj=None):
"""
Hook for specifying fields.
"""
if self.fields:
return self.fields
# _get_form_for_get_fields() is implemented in subclasses.
form = self._get_form_for_get_fields(request, obj)
return [*form.base_fields, *self.get_readonly_fields(request, obj)] | [
"def",
"get_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"if",
"self",
".",
"fields",
":",
"return",
"self",
".",
"fields",
"# _get_form_for_get_fields() is implemented in subclasses.",
"form",
"=",
"self",
".",
"_get_form_for_get_fields",
"(",
"request",
",",
"obj",
")",
"return",
"[",
"*",
"form",
".",
"base_fields",
",",
"*",
"self",
".",
"get_readonly_fields",
"(",
"request",
",",
"obj",
")",
"]"
] | [
320,
4
] | [
328,
75
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_fieldsets | (self, request, obj=None) |
Hook for specifying fieldsets.
|
Hook for specifying fieldsets.
| def get_fieldsets(self, request, obj=None):
"""
Hook for specifying fieldsets.
"""
if self.fieldsets:
return self.fieldsets
return [(None, {'fields': self.get_fields(request, obj)})] | [
"def",
"get_fieldsets",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"if",
"self",
".",
"fieldsets",
":",
"return",
"self",
".",
"fieldsets",
"return",
"[",
"(",
"None",
",",
"{",
"'fields'",
":",
"self",
".",
"get_fields",
"(",
"request",
",",
"obj",
")",
"}",
")",
"]"
] | [
330,
4
] | [
336,
66
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_inlines | (self, request, obj) | Hook for specifying custom inlines. | Hook for specifying custom inlines. | def get_inlines(self, request, obj):
"""Hook for specifying custom inlines."""
return self.inlines | [
"def",
"get_inlines",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"return",
"self",
".",
"inlines"
] | [
338,
4
] | [
340,
27
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.