repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Sean1708/HipPy | hippy/parser.py | Parser._parse_comma_list | def _parse_comma_list(self):
"""Parse a comma seperated list."""
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_comma_list was called on non-literal"
" {} on line {}.".format(
repr(self._cur_token[... | python | def _parse_comma_list(self):
"""Parse a comma seperated list."""
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_comma_list was called on non-literal"
" {} on line {}.".format(
repr(self._cur_token[... | [
"def",
"_parse_comma_list",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_token",
"[",
"'type'",
"]",
"not",
"in",
"self",
".",
"_literals",
":",
"raise",
"Exception",
"(",
"\"Parser failed, _parse_comma_list was called on non-literal\"",
"\" {} on line {}.\"",
".",... | Parse a comma seperated list. | [
"Parse",
"a",
"comma",
"seperated",
"list",
"."
] | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L239-L263 |
Sean1708/HipPy | hippy/parser.py | Parser._parse_newline_list | def _parse_newline_list(self, indent):
"""Parse a newline seperated list."""
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_newline_list was called on non-literal"
" {} on line {}.".format(
repr(se... | python | def _parse_newline_list(self, indent):
"""Parse a newline seperated list."""
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_newline_list was called on non-literal"
" {} on line {}.".format(
repr(se... | [
"def",
"_parse_newline_list",
"(",
"self",
",",
"indent",
")",
":",
"if",
"self",
".",
"_cur_token",
"[",
"'type'",
"]",
"not",
"in",
"self",
".",
"_literals",
":",
"raise",
"Exception",
"(",
"\"Parser failed, _parse_newline_list was called on non-literal\"",
"\" {}... | Parse a newline seperated list. | [
"Parse",
"a",
"newline",
"seperated",
"list",
"."
] | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L265-L330 |
xtrementl/focus | focus/environment/cli.py | FocusArgParser.exit | def exit(self, status=0, message=None):
""" Handle general message exits (e.g. version).
"""
if message:
raise HelpBanner(message.strip(), code=status) | python | def exit(self, status=0, message=None):
""" Handle general message exits (e.g. version).
"""
if message:
raise HelpBanner(message.strip(), code=status) | [
"def",
"exit",
"(",
"self",
",",
"status",
"=",
"0",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
":",
"raise",
"HelpBanner",
"(",
"message",
".",
"strip",
"(",
")",
",",
"code",
"=",
"status",
")"
] | Handle general message exits (e.g. version). | [
"Handle",
"general",
"message",
"exits",
"(",
"e",
".",
"g",
".",
"version",
")",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L31-L35 |
xtrementl/focus | focus/environment/cli.py | FocusArgParser.format_help | def format_help(self):
""" Strip out { } redundant subcommand section.
"""
help_msg = super(FocusArgParser, self).format_help()
return re.sub(r'\{.+\}', '', help_msg) | python | def format_help(self):
""" Strip out { } redundant subcommand section.
"""
help_msg = super(FocusArgParser, self).format_help()
return re.sub(r'\{.+\}', '', help_msg) | [
"def",
"format_help",
"(",
"self",
")",
":",
"help_msg",
"=",
"super",
"(",
"FocusArgParser",
",",
"self",
")",
".",
"format_help",
"(",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\{.+\\}'",
",",
"''",
",",
"help_msg",
")"
] | Strip out { } redundant subcommand section. | [
"Strip",
"out",
"{",
"}",
"redundant",
"subcommand",
"section",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L37-L41 |
xtrementl/focus | focus/environment/cli.py | CLI._handle_help | def _handle_help(self, env, args):
""" Handles showing help information for arguments provided.
`env`
Runtime ``Environment`` instance.
`args`
List of argument strings passed.
Returns ``False`` if nothing handled.
* Raises ``Help... | python | def _handle_help(self, env, args):
""" Handles showing help information for arguments provided.
`env`
Runtime ``Environment`` instance.
`args`
List of argument strings passed.
Returns ``False`` if nothing handled.
* Raises ``Help... | [
"def",
"_handle_help",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"if",
"args",
":",
"# command help (focus help [command])",
"# get command plugin registered for command",
"active",
"=",
"env",
".",
"task",
".",
"active",
"plugin_obj",
"=",
"registration",
"."... | Handles showing help information for arguments provided.
`env`
Runtime ``Environment`` instance.
`args`
List of argument strings passed.
Returns ``False`` if nothing handled.
* Raises ``HelpBanner`` exception if valid subcommand provided... | [
"Handles",
"showing",
"help",
"information",
"for",
"arguments",
"provided",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L59-L82 |
xtrementl/focus | focus/environment/cli.py | CLI._handle_command | def _handle_command(self, command, env, args):
""" Handles calling appropriate command plugin based on the arguments
provided.
`command`
Command string.
`env`
Runtime ``Environment`` instance.
`args`
List of argumen... | python | def _handle_command(self, command, env, args):
""" Handles calling appropriate command plugin based on the arguments
provided.
`command`
Command string.
`env`
Runtime ``Environment`` instance.
`args`
List of argumen... | [
"def",
"_handle_command",
"(",
"self",
",",
"command",
",",
"env",
",",
"args",
")",
":",
"# get command plugin registered for command",
"# note, we're guaranteed to have a command string by this point",
"plugin_obj",
"=",
"registration",
".",
"get_command_hook",
"(",
"comman... | Handles calling appropriate command plugin based on the arguments
provided.
`command`
Command string.
`env`
Runtime ``Environment`` instance.
`args`
List of argument strings passed.
Returns ``False`` if nothing... | [
"Handles",
"calling",
"appropriate",
"command",
"plugin",
"based",
"on",
"the",
"arguments",
"provided",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L84-L122 |
xtrementl/focus | focus/environment/cli.py | CLI._get_parser | def _get_parser(self, env):
""" Creates base argument parser.
`env`
Runtime ``Environment`` instance.
* Raises ``HelpBanner`` exception when certain conditions apply.
Returns ``FocusArgumentParser`` object.
"""
version_str = 'focus vers... | python | def _get_parser(self, env):
""" Creates base argument parser.
`env`
Runtime ``Environment`` instance.
* Raises ``HelpBanner`` exception when certain conditions apply.
Returns ``FocusArgumentParser`` object.
"""
version_str = 'focus vers... | [
"def",
"_get_parser",
"(",
"self",
",",
"env",
")",
":",
"version_str",
"=",
"'focus version '",
"+",
"__version__",
"usage_str",
"=",
"'focus [-h] [-v] [--no-color] <command> [<args>]'",
"# setup parser",
"parser",
"=",
"FocusArgParser",
"(",
"description",
"=",
"(",
... | Creates base argument parser.
`env`
Runtime ``Environment`` instance.
* Raises ``HelpBanner`` exception when certain conditions apply.
Returns ``FocusArgumentParser`` object. | [
"Creates",
"base",
"argument",
"parser",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L124-L192 |
xtrementl/focus | focus/environment/cli.py | CLI._get_plugin_parser | def _get_plugin_parser(self, plugin_obj):
""" Creates a plugin argument parser.
`plugin_obj`
``Plugin`` object.
Returns ``FocusArgParser`` object.
"""
prog_name = 'focus ' + plugin_obj.command
desc = (plugin_obj.__doc__ or '').strip()
... | python | def _get_plugin_parser(self, plugin_obj):
""" Creates a plugin argument parser.
`plugin_obj`
``Plugin`` object.
Returns ``FocusArgParser`` object.
"""
prog_name = 'focus ' + plugin_obj.command
desc = (plugin_obj.__doc__ or '').strip()
... | [
"def",
"_get_plugin_parser",
"(",
"self",
",",
"plugin_obj",
")",
":",
"prog_name",
"=",
"'focus '",
"+",
"plugin_obj",
".",
"command",
"desc",
"=",
"(",
"plugin_obj",
".",
"__doc__",
"or",
"''",
")",
".",
"strip",
"(",
")",
"parser",
"=",
"FocusArgParser"... | Creates a plugin argument parser.
`plugin_obj`
``Plugin`` object.
Returns ``FocusArgParser`` object. | [
"Creates",
"a",
"plugin",
"argument",
"parser",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L194-L209 |
xtrementl/focus | focus/environment/cli.py | CLI.execute | def execute(self, env):
""" Executes basic flags and command plugins.
`env`
Runtime ``Environment`` instance.
* Raises ``FocusError`` exception when certain conditions apply.
"""
# parse args
parser = self._get_parser(env)
parsed_arg... | python | def execute(self, env):
""" Executes basic flags and command plugins.
`env`
Runtime ``Environment`` instance.
* Raises ``FocusError`` exception when certain conditions apply.
"""
# parse args
parser = self._get_parser(env)
parsed_arg... | [
"def",
"execute",
"(",
"self",
",",
"env",
")",
":",
"# parse args",
"parser",
"=",
"self",
".",
"_get_parser",
"(",
"env",
")",
"parsed_args",
",",
"cmd_args",
"=",
"parser",
".",
"parse_known_args",
"(",
"env",
".",
"args",
")",
"# disable colors",
"if",... | Executes basic flags and command plugins.
`env`
Runtime ``Environment`` instance.
* Raises ``FocusError`` exception when certain conditions apply. | [
"Executes",
"basic",
"flags",
"and",
"command",
"plugins",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L211-L230 |
mbarakaja/braulio | braulio/files.py | _split_chglog | def _split_chglog(path, title):
"""Split a RST file text in two parts. The title argument determine the
split point. The given title goes in the bottom part. If the title is not
found everything goes in the top part.
Return a tuple with the top and bottom parts.
"""
with path.open() as f:
... | python | def _split_chglog(path, title):
"""Split a RST file text in two parts. The title argument determine the
split point. The given title goes in the bottom part. If the title is not
found everything goes in the top part.
Return a tuple with the top and bottom parts.
"""
with path.open() as f:
... | [
"def",
"_split_chglog",
"(",
"path",
",",
"title",
")",
":",
"with",
"path",
".",
"open",
"(",
")",
"as",
"f",
":",
"doc",
"=",
"f",
".",
"readlines",
"(",
")",
"has_title",
"=",
"False",
"for",
"idx",
",",
"curr_line",
"in",
"enumerate",
"(",
"doc... | Split a RST file text in two parts. The title argument determine the
split point. The given title goes in the bottom part. If the title is not
found everything goes in the top part.
Return a tuple with the top and bottom parts. | [
"Split",
"a",
"RST",
"file",
"text",
"in",
"two",
"parts",
".",
"The",
"title",
"argument",
"determine",
"the",
"split",
"point",
".",
"The",
"given",
"title",
"goes",
"in",
"the",
"bottom",
"part",
".",
"If",
"the",
"title",
"is",
"not",
"found",
"eve... | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/files.py#L151-L180 |
smartmob-project/procfile | procfile/__init__.py | loads | def loads(content):
"""Load a Procfile from a string."""
lines = _group_lines(line for line in content.split('\n'))
lines = [
(i, _parse_procfile_line(line))
for i, line in lines if line.strip()
]
errors = []
# Reject files with duplicate process types (no sane default).
dupl... | python | def loads(content):
"""Load a Procfile from a string."""
lines = _group_lines(line for line in content.split('\n'))
lines = [
(i, _parse_procfile_line(line))
for i, line in lines if line.strip()
]
errors = []
# Reject files with duplicate process types (no sane default).
dupl... | [
"def",
"loads",
"(",
"content",
")",
":",
"lines",
"=",
"_group_lines",
"(",
"line",
"for",
"line",
"in",
"content",
".",
"split",
"(",
"'\\n'",
")",
")",
"lines",
"=",
"[",
"(",
"i",
",",
"_parse_procfile_line",
"(",
"line",
")",
")",
"for",
"i",
... | Load a Procfile from a string. | [
"Load",
"a",
"Procfile",
"from",
"a",
"string",
"."
] | train | https://github.com/smartmob-project/procfile/blob/338756d5b645f17aa2366c34afa3b7a58d880796/procfile/__init__.py#L70-L99 |
fred49/linshare-api | linshareapi/user/authentication.py | Authentication.update | def update(self, data):
""" Update a list."""
# if self.debug >= 2:
# self.debug(data)
url = "{base}/change_password".format(
base=self.local_base_url
)
self._check(data)
res = self.core.create(url, data)
self.log.debug("result: %s", res)
... | python | def update(self, data):
""" Update a list."""
# if self.debug >= 2:
# self.debug(data)
url = "{base}/change_password".format(
base=self.local_base_url
)
self._check(data)
res = self.core.create(url, data)
self.log.debug("result: %s", res)
... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"# if self.debug >= 2:",
"# self.debug(data)",
"url",
"=",
"\"{base}/change_password\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"local_base_url",
")",
"self",
".",
"_check",
"(",
"data",
")",
"res... | Update a list. | [
"Update",
"a",
"list",
"."
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/authentication.py#L56-L66 |
OpenVolunteeringPlatform/django-ovp-core | ovp_core/helpers/__init__.py | is_email_enabled | def is_email_enabled(email):
""" Emails are activated by default. Returns false
if an email has been disabled in settings.py
"""
s = get_settings(string="OVP_EMAILS")
email_settings = s.get(email, {})
enabled = True
if email_settings.get("disabled", False):
enabled = False
return enabled | python | def is_email_enabled(email):
""" Emails are activated by default. Returns false
if an email has been disabled in settings.py
"""
s = get_settings(string="OVP_EMAILS")
email_settings = s.get(email, {})
enabled = True
if email_settings.get("disabled", False):
enabled = False
return enabled | [
"def",
"is_email_enabled",
"(",
"email",
")",
":",
"s",
"=",
"get_settings",
"(",
"string",
"=",
"\"OVP_EMAILS\"",
")",
"email_settings",
"=",
"s",
".",
"get",
"(",
"email",
",",
"{",
"}",
")",
"enabled",
"=",
"True",
"if",
"email_settings",
".",
"get",
... | Emails are activated by default. Returns false
if an email has been disabled in settings.py | [
"Emails",
"are",
"activated",
"by",
"default",
".",
"Returns",
"false",
"if",
"an",
"email",
"has",
"been",
"disabled",
"in",
"settings",
".",
"py"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-core/blob/c81b868a0a4b317f7b1ec0718cabc34f7794dd20/ovp_core/helpers/__init__.py#L21-L32 |
OpenVolunteeringPlatform/django-ovp-core | ovp_core/helpers/__init__.py | get_email_subject | def get_email_subject(email, default):
""" Allows for email subject overriding from settings.py """
s = get_settings(string="OVP_EMAILS")
email_settings = s.get(email, {})
title = email_settings.get("subject", default)
return _(title) | python | def get_email_subject(email, default):
""" Allows for email subject overriding from settings.py """
s = get_settings(string="OVP_EMAILS")
email_settings = s.get(email, {})
title = email_settings.get("subject", default)
return _(title) | [
"def",
"get_email_subject",
"(",
"email",
",",
"default",
")",
":",
"s",
"=",
"get_settings",
"(",
"string",
"=",
"\"OVP_EMAILS\"",
")",
"email_settings",
"=",
"s",
".",
"get",
"(",
"email",
",",
"{",
"}",
")",
"title",
"=",
"email_settings",
".",
"get",... | Allows for email subject overriding from settings.py | [
"Allows",
"for",
"email",
"subject",
"overriding",
"from",
"settings",
".",
"py"
] | train | https://github.com/OpenVolunteeringPlatform/django-ovp-core/blob/c81b868a0a4b317f7b1ec0718cabc34f7794dd20/ovp_core/helpers/__init__.py#L35-L42 |
AKSW/SemanticPingbackPy | semanticpingback.py | SemanticPingbackReceiver._load | def _load(self, graph, source):
"""from https://rdflib.readthedocs.io/en/stable/_modules/rdflib/plugins/sparql/sparql.html"""
try:
return graph.load(source)
except:
pass
try:
return graph.load(source, format='n3')
except:
pass
... | python | def _load(self, graph, source):
"""from https://rdflib.readthedocs.io/en/stable/_modules/rdflib/plugins/sparql/sparql.html"""
try:
return graph.load(source)
except:
pass
try:
return graph.load(source, format='n3')
except:
pass
... | [
"def",
"_load",
"(",
"self",
",",
"graph",
",",
"source",
")",
":",
"try",
":",
"return",
"graph",
".",
"load",
"(",
"source",
")",
"except",
":",
"pass",
"try",
":",
"return",
"graph",
".",
"load",
"(",
"source",
",",
"format",
"=",
"'n3'",
")",
... | from https://rdflib.readthedocs.io/en/stable/_modules/rdflib/plugins/sparql/sparql.html | [
"from",
"https",
":",
"//",
"rdflib",
".",
"readthedocs",
".",
"io",
"/",
"en",
"/",
"stable",
"/",
"_modules",
"/",
"rdflib",
"/",
"plugins",
"/",
"sparql",
"/",
"sparql",
".",
"html"
] | train | https://github.com/AKSW/SemanticPingbackPy/blob/7185ab45aa5cae417f90702b08ae06040ac9dae9/semanticpingback.py#L63-L76 |
AguaClara/aide_document-DEPRECATED | aide_document/convert.py | md_to_pdf | def md_to_pdf(input_name, output_name):
"""
Converts an input MarkDown file to a PDF of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the o... | python | def md_to_pdf(input_name, output_name):
"""
Converts an input MarkDown file to a PDF of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the o... | [
"def",
"md_to_pdf",
"(",
"input_name",
",",
"output_name",
")",
":",
"if",
"output_name",
"[",
"-",
"4",
":",
"]",
"==",
"'.pdf'",
":",
"os",
".",
"system",
"(",
"\"pandoc \"",
"+",
"input_name",
"+",
"\" -o \"",
"+",
"output_name",
")",
"else",
":",
"... | Converts an input MarkDown file to a PDF of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the output file to where this function is being called. N... | [
"Converts",
"an",
"input",
"MarkDown",
"file",
"to",
"a",
"PDF",
"of",
"the",
"given",
"output",
"name",
"."
] | train | https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/convert.py#L3-L31 |
AguaClara/aide_document-DEPRECATED | aide_document/convert.py | docx_to_md | def docx_to_md(input_name, output_name):
"""
Converts an input docx file to MarkDown file of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of ... | python | def docx_to_md(input_name, output_name):
"""
Converts an input docx file to MarkDown file of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of ... | [
"def",
"docx_to_md",
"(",
"input_name",
",",
"output_name",
")",
":",
"if",
"output_name",
"[",
"-",
"5",
":",
"]",
"==",
"'.docx'",
":",
"os",
".",
"system",
"(",
"\"pandoc \"",
"+",
"input_name",
"+",
"\" -o \"",
"+",
"output_name",
")",
"else",
":",
... | Converts an input docx file to MarkDown file of the given output name.
Parameters
==========
input_name : String
Relative file location of the input file to where this function is being called.
output_name : String
Relative file location of the output file to where this function is being calle... | [
"Converts",
"an",
"input",
"docx",
"file",
"to",
"MarkDown",
"file",
"of",
"the",
"given",
"output",
"name",
"."
] | train | https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/convert.py#L33-L61 |
MrKriss/vigilance | vigilance/vigilance.py | expect | def expect(*exprs):
"""Tests given sequence of conditions and stores results.
Parameters
----------
exprs: bool or tuple of (bool, str)
Variable number of expressions evaluated. If a tuple first element is
expression evaluated, second is the message displayed on failure in the repo... | python | def expect(*exprs):
"""Tests given sequence of conditions and stores results.
Parameters
----------
exprs: bool or tuple of (bool, str)
Variable number of expressions evaluated. If a tuple first element is
expression evaluated, second is the message displayed on failure in the repo... | [
"def",
"expect",
"(",
"*",
"exprs",
")",
":",
"# Catch case of only two arguments where one is expr and other is msg",
"if",
"len",
"(",
"exprs",
")",
"==",
"2",
"and",
"(",
"isinstance",
"(",
"exprs",
"[",
"0",
"]",
",",
"(",
"bool",
",",
"np",
".",
"bool_"... | Tests given sequence of conditions and stores results.
Parameters
----------
exprs: bool or tuple of (bool, str)
Variable number of expressions evaluated. If a tuple first element is
expression evaluated, second is the message displayed on failure in the report. | [
"Tests",
"given",
"sequence",
"of",
"conditions",
"and",
"stores",
"results",
".",
"Parameters",
"----------",
"exprs",
":",
"bool",
"or",
"tuple",
"of",
"(",
"bool",
"str",
")",
"Variable",
"number",
"of",
"expressions",
"evaluated",
".",
"If",
"a",
"tuple"... | train | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/vigilance.py#L61-L87 |
MrKriss/vigilance | vigilance/vigilance.py | report_failures | def report_failures(error=False, display=True, clear=True):
""" Print details of logged failures in expect function
If no failures are detected, None is returned by the function.
Parameters
----------
error:bool
If true, will raise an Expectation of type 'FaliedValidationError' instead of ... | python | def report_failures(error=False, display=True, clear=True):
""" Print details of logged failures in expect function
If no failures are detected, None is returned by the function.
Parameters
----------
error:bool
If true, will raise an Expectation of type 'FaliedValidationError' instead of ... | [
"def",
"report_failures",
"(",
"error",
"=",
"False",
",",
"display",
"=",
"True",
",",
"clear",
"=",
"True",
")",
":",
"global",
"_failed_expectations",
"output",
"=",
"[",
"]",
"# Copy as failures are returned ",
"all_failed_expectations",
"=",
"_failed_expectatio... | Print details of logged failures in expect function
If no failures are detected, None is returned by the function.
Parameters
----------
error:bool
If true, will raise an Expectation of type 'FaliedValidationError' instead of printing to console
display: bool
If True, will print th... | [
"Print",
"details",
"of",
"logged",
"failures",
"in",
"expect",
"function"
] | train | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/vigilance.py#L90-L155 |
MrKriss/vigilance | vigilance/vigilance.py | _log_failure | def _log_failure(arg_num, msg=None):
""" Retrace stack and log the failed expresion information """
# stack() returns a list of frame records
# 0 is the _log_failure() function
# 1 is the expect() function
# 2 is the function that called expect(), that's what we want
#
# a frame reco... | python | def _log_failure(arg_num, msg=None):
""" Retrace stack and log the failed expresion information """
# stack() returns a list of frame records
# 0 is the _log_failure() function
# 1 is the expect() function
# 2 is the function that called expect(), that's what we want
#
# a frame reco... | [
"def",
"_log_failure",
"(",
"arg_num",
",",
"msg",
"=",
"None",
")",
":",
"# stack() returns a list of frame records",
"# 0 is the _log_failure() function",
"# 1 is the expect() function ",
"# 2 is the function that called expect(), that's what we want",
"#",
"# a frame record is... | Retrace stack and log the failed expresion information | [
"Retrace",
"stack",
"and",
"log",
"the",
"failed",
"expresion",
"information"
] | train | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/vigilance.py#L158-L208 |
rinocloud/rinocloud-python | rinocloud/collection.py | Collection.set_name | def set_name(self, name, create_dir=False):
"""
Sets the name of the file to be saved.
@params
name - the name to the file
increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt
overwrite - whether or not to... | python | def set_name(self, name, create_dir=False):
"""
Sets the name of the file to be saved.
@params
name - the name to the file
increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt
overwrite - whether or not to... | [
"def",
"set_name",
"(",
"self",
",",
"name",
",",
"create_dir",
"=",
"False",
")",
":",
"# check if the file exists",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"name",
")",
"... | Sets the name of the file to be saved.
@params
name - the name to the file
increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt
overwrite - whether or not to overwrite existing local file, renders increment redundant | [
"Sets",
"the",
"name",
"of",
"the",
"file",
"to",
"be",
"saved",
"."
] | train | https://github.com/rinocloud/rinocloud-python/blob/7c4bf994a518f961cffedb7260fc1e4fa1838b38/rinocloud/collection.py#L14-L32 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModuleArgumentsBuilder.add_argument | def add_argument(self, name, value_type, item_help, default=None):
"""
:type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder
"""
if value_type and value_type not in self.__restricted_types:
raise ArgumentException("Named argument ... | python | def add_argument(self, name, value_type, item_help, default=None):
"""
:type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder
"""
if value_type and value_type not in self.__restricted_types:
raise ArgumentException("Named argument ... | [
"def",
"add_argument",
"(",
"self",
",",
"name",
",",
"value_type",
",",
"item_help",
",",
"default",
"=",
"None",
")",
":",
"if",
"value_type",
"and",
"value_type",
"not",
"in",
"self",
".",
"__restricted_types",
":",
"raise",
"ArgumentException",
"(",
"\"N... | :type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder | [
":",
"type",
"name",
"str",
":",
"type",
"value_type",
"Type",
":",
"type",
"item_help",
"str",
":",
"type",
"default",
"Type",
":",
"rtype",
"ModuleArgumentsBuilder"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L23-L43 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModuleArgumentsBuilder.default_arguments | def default_arguments(self):
"""
:rtype dict
:rtype dict
"""
d = OrderedDict()
for arg in self._default_args:
d.update({arg.name: arg})
return d | python | def default_arguments(self):
"""
:rtype dict
:rtype dict
"""
d = OrderedDict()
for arg in self._default_args:
d.update({arg.name: arg})
return d | [
"def",
"default_arguments",
"(",
"self",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"for",
"arg",
"in",
"self",
".",
"_default_args",
":",
"d",
".",
"update",
"(",
"{",
"arg",
".",
"name",
":",
"arg",
"}",
")",
"return",
"d"
] | :rtype dict
:rtype dict | [
":",
"rtype",
"dict",
":",
"rtype",
"dict"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L53-L63 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModuleArgumentsBuilder.add_default_argument | def add_default_argument(self, name, value_type, item_help, default=None):
"""
:type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder
"""
if value_type not in self.__restricted_default_types:
raise ArgumentException("Positional(def... | python | def add_default_argument(self, name, value_type, item_help, default=None):
"""
:type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder
"""
if value_type not in self.__restricted_default_types:
raise ArgumentException("Positional(def... | [
"def",
"add_default_argument",
"(",
"self",
",",
"name",
",",
"value_type",
",",
"item_help",
",",
"default",
"=",
"None",
")",
":",
"if",
"value_type",
"not",
"in",
"self",
".",
"__restricted_default_types",
":",
"raise",
"ArgumentException",
"(",
"\"Positional... | :type name str
:type value_type Type
:type item_help str
:type default Type
:rtype ModuleArgumentsBuilder | [
":",
"type",
"name",
"str",
":",
"type",
"value_type",
"Type",
":",
"type",
"item_help",
"str",
":",
"type",
"default",
"Type",
":",
"rtype",
"ModuleArgumentsBuilder"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L65-L85 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModuleMetaInfo.parse_default_arguments | def parse_default_arguments(self, default_args_sample):
"""
:type default_args_sample list
:rtype dict
"""
parsed_arguments_dict = {}
default_arguments = list(self._arguments.default_arguments.values())
expected_length = len(default_arguments)
real_length = len(default_args_sample)
... | python | def parse_default_arguments(self, default_args_sample):
"""
:type default_args_sample list
:rtype dict
"""
parsed_arguments_dict = {}
default_arguments = list(self._arguments.default_arguments.values())
expected_length = len(default_arguments)
real_length = len(default_args_sample)
... | [
"def",
"parse_default_arguments",
"(",
"self",
",",
"default_args_sample",
")",
":",
"parsed_arguments_dict",
"=",
"{",
"}",
"default_arguments",
"=",
"list",
"(",
"self",
".",
"_arguments",
".",
"default_arguments",
".",
"values",
"(",
")",
")",
"expected_length"... | :type default_args_sample list
:rtype dict | [
":",
"type",
"default_args_sample",
"list",
":",
"rtype",
"dict"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L137-L177 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModuleMetaInfo.parse_arguments | def parse_arguments(self, conf):
"""
:type conf apputils.settings.Configuration|dict
"""
parsed_arguments_dict = {}
arguments = self._arguments.arguments
for arg_name in arguments:
arg_meta = arguments[arg_name]
""":type arg_meta ModuleArgumentItem"""
try:
if arg_meta.... | python | def parse_arguments(self, conf):
"""
:type conf apputils.settings.Configuration|dict
"""
parsed_arguments_dict = {}
arguments = self._arguments.arguments
for arg_name in arguments:
arg_meta = arguments[arg_name]
""":type arg_meta ModuleArgumentItem"""
try:
if arg_meta.... | [
"def",
"parse_arguments",
"(",
"self",
",",
"conf",
")",
":",
"parsed_arguments_dict",
"=",
"{",
"}",
"arguments",
"=",
"self",
".",
"_arguments",
".",
"arguments",
"for",
"arg_name",
"in",
"arguments",
":",
"arg_meta",
"=",
"arguments",
"[",
"arg_name",
"]"... | :type conf apputils.settings.Configuration|dict | [
":",
"type",
"conf",
"apputils",
".",
"settings",
".",
"Configuration|dict"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L179-L202 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModulesDiscovery.generate_help | def generate_help(self, filename="", command=""):
"""
:type command str
"""
"{} [{}]\n\n".format(filename, "|".join(self.available_command_list))
help_str = """Available commands:
"""
command_list = self.available_command_list if command == "" else [command]
for command in command_lis... | python | def generate_help(self, filename="", command=""):
"""
:type command str
"""
"{} [{}]\n\n".format(filename, "|".join(self.available_command_list))
help_str = """Available commands:
"""
command_list = self.available_command_list if command == "" else [command]
for command in command_lis... | [
"def",
"generate_help",
"(",
"self",
",",
"filename",
"=",
"\"\"",
",",
"command",
"=",
"\"\"",
")",
":",
"\"{} [{}]\\n\\n\"",
".",
"format",
"(",
"filename",
",",
"\"|\"",
".",
"join",
"(",
"self",
".",
"available_command_list",
")",
")",
"help_str",
"=",... | :type command str | [
":",
"type",
"command",
"str"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L267-L313 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModulesDiscovery.execute_command | def execute_command(self, default_arg_list=None, **kwargs):
"""
:type default_arg_list list
:type kwargs dict
"""
_custom_func_arguments = set()
if default_arg_list is None or len(default_arg_list) == 0:
raise NoCommandException("No command passed, unable to continue")
command_name =... | python | def execute_command(self, default_arg_list=None, **kwargs):
"""
:type default_arg_list list
:type kwargs dict
"""
_custom_func_arguments = set()
if default_arg_list is None or len(default_arg_list) == 0:
raise NoCommandException("No command passed, unable to continue")
command_name =... | [
"def",
"execute_command",
"(",
"self",
",",
"default_arg_list",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_custom_func_arguments",
"=",
"set",
"(",
")",
"if",
"default_arg_list",
"is",
"None",
"or",
"len",
"(",
"default_arg_list",
")",
"==",
"0",
":... | :type default_arg_list list
:type kwargs dict | [
":",
"type",
"default_arg_list",
"list",
":",
"type",
"kwargs",
"dict"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L329-L362 |
hapylestat/apputils | apputils/utils/import_tools/import_tools.py | ModulesDiscovery.main | def main(self, configuration):
"""
:type configuration Configuration
"""
_custom_func_arguments = {"conf"}
filename = os.path.basename(os.path.abspath(sys.argv[0]))
default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0]
if len(default_arg_list) == 0:
... | python | def main(self, configuration):
"""
:type configuration Configuration
"""
_custom_func_arguments = {"conf"}
filename = os.path.basename(os.path.abspath(sys.argv[0]))
default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0]
if len(default_arg_list) == 0:
... | [
"def",
"main",
"(",
"self",
",",
"configuration",
")",
":",
"_custom_func_arguments",
"=",
"{",
"\"conf\"",
"}",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",... | :type configuration Configuration | [
":",
"type",
"configuration",
"Configuration"
] | train | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/import_tools/import_tools.py#L364-L404 |
hephs/dispatk | dispatk.py | dispatk | def dispatk(keyer):
"""This is the decorator for the generic function and it accepts
only one argument *keyer*, it'll be called with the same arguments
of the function call and it must return an hashable object
(int, tuple, etc.).
Rhe generic function has a *register* method used to decorate the
... | python | def dispatk(keyer):
"""This is the decorator for the generic function and it accepts
only one argument *keyer*, it'll be called with the same arguments
of the function call and it must return an hashable object
(int, tuple, etc.).
Rhe generic function has a *register* method used to decorate the
... | [
"def",
"dispatk",
"(",
"keyer",
")",
":",
"calls",
"=",
"{",
"}",
"def",
"_dispatk",
"(",
"main",
")",
":",
"def",
"register",
"(",
"*",
"keys",
")",
":",
"def",
"_register",
"(",
"spec",
")",
":",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
... | This is the decorator for the generic function and it accepts
only one argument *keyer*, it'll be called with the same arguments
of the function call and it must return an hashable object
(int, tuple, etc.).
Rhe generic function has a *register* method used to decorate the
function for some specifi... | [
"This",
"is",
"the",
"decorator",
"for",
"the",
"generic",
"function",
"and",
"it",
"accepts",
"only",
"one",
"argument",
"*",
"keyer",
"*",
"it",
"ll",
"be",
"called",
"with",
"the",
"same",
"arguments",
"of",
"the",
"function",
"call",
"and",
"it",
"mu... | train | https://github.com/hephs/dispatk/blob/81418934093eb1eb20862e7fb9f97d6bfbc3cf10/dispatk.py#L44-L80 |
opinkerfi/nago | nago/extensions/agent.py | start | def start(debug=False, host='127.0.0.1'):
""" starts a nago agent (daemon) process """
if debug:
debug = True
nago.protocols.httpserver.app.run(debug=debug, host=host) | python | def start(debug=False, host='127.0.0.1'):
""" starts a nago agent (daemon) process """
if debug:
debug = True
nago.protocols.httpserver.app.run(debug=debug, host=host) | [
"def",
"start",
"(",
"debug",
"=",
"False",
",",
"host",
"=",
"'127.0.0.1'",
")",
":",
"if",
"debug",
":",
"debug",
"=",
"True",
"nago",
".",
"protocols",
".",
"httpserver",
".",
"app",
".",
"run",
"(",
"debug",
"=",
"debug",
",",
"host",
"=",
"hos... | starts a nago agent (daemon) process | [
"starts",
"a",
"nago",
"agent",
"(",
"daemon",
")",
"process"
] | train | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/agent.py#L17-L21 |
ylogx/far | far/main.py | parse_known_args | def parse_known_args():
""" Parse command line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-V', '--version',
action='store_true',
dest='version',
help='Print the version number and exit')
mutually_exclu... | python | def parse_known_args():
""" Parse command line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-V', '--version',
action='store_true',
dest='version',
help='Print the version number and exit')
mutually_exclu... | [
"def",
"parse_known_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-V'",
",",
"'--version'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'version'",
",",
"help",
"=",
"'Pri... | Parse command line arguments | [
"Parse",
"command",
"line",
"arguments"
] | train | https://github.com/ylogx/far/blob/8d3b28edab10ada2edd7cb2b20c655e00fa3f8e4/far/main.py#L21-L42 |
ylogx/far | far/main.py | main | def main():
""" Main
"""
args, otherthings = parse_known_args()
if args.version:
print_version()
return 0
verbosity = 0
if args.verbose:
verbosity = 1
far = Far(verbosity=verbosity)
if args.dry_run:
far.dry_run(old=args.old)
else:
far.find_... | python | def main():
""" Main
"""
args, otherthings = parse_known_args()
if args.version:
print_version()
return 0
verbosity = 0
if args.verbose:
verbosity = 1
far = Far(verbosity=verbosity)
if args.dry_run:
far.dry_run(old=args.old)
else:
far.find_... | [
"def",
"main",
"(",
")",
":",
"args",
",",
"otherthings",
"=",
"parse_known_args",
"(",
")",
"if",
"args",
".",
"version",
":",
"print_version",
"(",
")",
"return",
"0",
"verbosity",
"=",
"0",
"if",
"args",
".",
"verbose",
":",
"verbosity",
"=",
"1",
... | Main | [
"Main"
] | train | https://github.com/ylogx/far/blob/8d3b28edab10ada2edd7cb2b20c655e00fa3f8e4/far/main.py#L45-L63 |
testing-cabal/systemfixtures | systemfixtures/filesystem.py | FakeFilesystem.add | def add(self, path):
"""Add a path to the overlay filesytem.
Any filesystem operation involving the this path or any sub-paths
of it will be transparently redirected to temporary root dir.
@path: An absolute path string.
"""
if not path.startswith(os.sep):
r... | python | def add(self, path):
"""Add a path to the overlay filesytem.
Any filesystem operation involving the this path or any sub-paths
of it will be transparently redirected to temporary root dir.
@path: An absolute path string.
"""
if not path.startswith(os.sep):
r... | [
"def",
"add",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"raise",
"ValueError",
"(",
"\"Non-absolute path '{}'\"",
".",
"format",
"(",
"path",
")",
")",
"path",
"=",
"path",
".",
"rstr... | Add a path to the overlay filesytem.
Any filesystem operation involving the this path or any sub-paths
of it will be transparently redirected to temporary root dir.
@path: An absolute path string. | [
"Add",
"a",
"path",
"to",
"the",
"overlay",
"filesytem",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/filesystem.py#L65-L80 |
testing-cabal/systemfixtures | systemfixtures/filesystem.py | FakeFilesystem._fchown | def _fchown(self, real, fileno, uid, gid):
"""Run fake fchown code if fileno points to a sub-path of our tree.
The ownership set with this fake fchown can be inspected by looking
at the self.uid/self.gid dictionaries.
"""
path = self._fake_path(self._path_from_fd(fileno))
... | python | def _fchown(self, real, fileno, uid, gid):
"""Run fake fchown code if fileno points to a sub-path of our tree.
The ownership set with this fake fchown can be inspected by looking
at the self.uid/self.gid dictionaries.
"""
path = self._fake_path(self._path_from_fd(fileno))
... | [
"def",
"_fchown",
"(",
"self",
",",
"real",
",",
"fileno",
",",
"uid",
",",
"gid",
")",
":",
"path",
"=",
"self",
".",
"_fake_path",
"(",
"self",
".",
"_path_from_fd",
"(",
"fileno",
")",
")",
"self",
".",
"_chown_common",
"(",
"path",
",",
"uid",
... | Run fake fchown code if fileno points to a sub-path of our tree.
The ownership set with this fake fchown can be inspected by looking
at the self.uid/self.gid dictionaries. | [
"Run",
"fake",
"fchown",
"code",
"if",
"fileno",
"points",
"to",
"a",
"sub",
"-",
"path",
"of",
"our",
"tree",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/filesystem.py#L82-L89 |
anovelmous-dev-squad/anovelmous-grammar | grammar/__init__.py | GrammarFilter.get_grammatically_correct_vocabulary_subset | def get_grammatically_correct_vocabulary_subset(self, text,
sent_filter='combined'):
"""
Returns a subset of a given vocabulary based on whether its
terms are "grammatically correct".
"""
tokens = word_tokenize(text)
sen... | python | def get_grammatically_correct_vocabulary_subset(self, text,
sent_filter='combined'):
"""
Returns a subset of a given vocabulary based on whether its
terms are "grammatically correct".
"""
tokens = word_tokenize(text)
sen... | [
"def",
"get_grammatically_correct_vocabulary_subset",
"(",
"self",
",",
"text",
",",
"sent_filter",
"=",
"'combined'",
")",
":",
"tokens",
"=",
"word_tokenize",
"(",
"text",
")",
"sent_tokens",
"=",
"get_partial_sentence",
"(",
"tokens",
")",
"if",
"not",
"sent_to... | Returns a subset of a given vocabulary based on whether its
terms are "grammatically correct". | [
"Returns",
"a",
"subset",
"of",
"a",
"given",
"vocabulary",
"based",
"on",
"whether",
"its",
"terms",
"are",
"grammatically",
"correct",
"."
] | train | https://github.com/anovelmous-dev-squad/anovelmous-grammar/blob/fbffbfa2c6546d8c74e1f582b941ba190c31c097/grammar/__init__.py#L226-L252 |
dlancer/django-pages-cms | pages/managers/pagemanager.py | PageManager.get_queryset | def get_queryset(self, *args, **kwargs):
"""
Ensures that this manager always returns nodes in tree order.
"""
qs = super(TreeManager, self).get_queryset(*args, **kwargs)
# Restrict operations to pages on the current site if needed
if settings.PAGES_HIDE_SITES and settin... | python | def get_queryset(self, *args, **kwargs):
"""
Ensures that this manager always returns nodes in tree order.
"""
qs = super(TreeManager, self).get_queryset(*args, **kwargs)
# Restrict operations to pages on the current site if needed
if settings.PAGES_HIDE_SITES and settin... | [
"def",
"get_queryset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"super",
"(",
"TreeManager",
",",
"self",
")",
".",
"get_queryset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Restrict operations to pages on the... | Ensures that this manager always returns nodes in tree order. | [
"Ensures",
"that",
"this",
"manager",
"always",
"returns",
"nodes",
"in",
"tree",
"order",
"."
] | train | https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/managers/pagemanager.py#L10-L20 |
dlancer/django-pages-cms | pages/managers/pagemanager.py | PageManager.on_site | def on_site(self, site_id=None):
"""Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with.
"""
if settings.PAGES_USE_SITE_ID:
if not site_id:
... | python | def on_site(self, site_id=None):
"""Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with.
"""
if settings.PAGES_USE_SITE_ID:
if not site_id:
... | [
"def",
"on_site",
"(",
"self",
",",
"site_id",
"=",
"None",
")",
":",
"if",
"settings",
".",
"PAGES_USE_SITE_ID",
":",
"if",
"not",
"site_id",
":",
"site_id",
"=",
"settings",
".",
"SITE_ID",
"return",
"self",
".",
"get_queryset",
"(",
")",
".",
"filter"... | Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with. | [
"Return",
"a",
":",
"class",
":",
"QuerySet",
"of",
"pages",
"that",
"are",
"published",
"on",
"the",
"site",
"defined",
"by",
"the",
"SITE_ID",
"setting",
"."
] | train | https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/managers/pagemanager.py#L22-L32 |
FujiMakoto/IPS-Vagrant | ips_vagrant/installer/__init__.py | installer | def installer(cv, ctx, site, force=False):
"""
Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@type site: ip... | python | def installer(cv, ctx, site, force=False):
"""
Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@type site: ip... | [
"def",
"installer",
"(",
"cv",
",",
"ctx",
",",
"site",
",",
"force",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'ipsv.installer'",
")",
"log",
".",
"info",
"(",
"'Loading installer for IPS %s'",
",",
"cv",
")",
"iv",
"=",
"... | Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@type site: ips_vagrant.models.sites.Site
@param force: Overwri... | [
"Installer",
"factory"
] | train | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/__init__.py#L17-L42 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | center_start | def center_start(r, window_size):
"""
Center a region on its start and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
res.end = res.start + window_size / 2
res.start = res.end - window_size
return res | python | def center_start(r, window_size):
"""
Center a region on its start and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
res.end = res.start + window_size / 2
res.start = res.end - window_size
return res | [
"def",
"center_start",
"(",
"r",
",",
"window_size",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"r",
")",
"res",
".",
"end",
"=",
"res",
".",
"start",
"+",
"window_size",
"/",
"2",
"res",
".",
"start",
"=",
"res",
".",
"end",
"-",
"window_si... | Center a region on its start and expand it to window_size bases.
:return: the new region. | [
"Center",
"a",
"region",
"on",
"its",
"start",
"and",
"expand",
"it",
"to",
"window_size",
"bases",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L84-L93 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | center_end | def center_end(r, window_size):
"""
Center a region on its end and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
res.start = res.end - window_size / 2
res.end = res.start + window_size
return res | python | def center_end(r, window_size):
"""
Center a region on its end and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
res.start = res.end - window_size / 2
res.end = res.start + window_size
return res | [
"def",
"center_end",
"(",
"r",
",",
"window_size",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"r",
")",
"res",
".",
"start",
"=",
"res",
".",
"end",
"-",
"window_size",
"/",
"2",
"res",
".",
"end",
"=",
"res",
".",
"start",
"+",
"window_size... | Center a region on its end and expand it to window_size bases.
:return: the new region. | [
"Center",
"a",
"region",
"on",
"its",
"end",
"and",
"expand",
"it",
"to",
"window_size",
"bases",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L96-L105 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | center_middle | def center_middle(r, window_size):
"""
Center a region on its middle and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
mid = res.start + (len(res) / 2)
res.start = mid - (window_size / 2)
res.end = res.start + window_size
return res | python | def center_middle(r, window_size):
"""
Center a region on its middle and expand it to window_size bases.
:return: the new region.
"""
res = copy.copy(r)
mid = res.start + (len(res) / 2)
res.start = mid - (window_size / 2)
res.end = res.start + window_size
return res | [
"def",
"center_middle",
"(",
"r",
",",
"window_size",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"r",
")",
"mid",
"=",
"res",
".",
"start",
"+",
"(",
"len",
"(",
"res",
")",
"/",
"2",
")",
"res",
".",
"start",
"=",
"mid",
"-",
"(",
"wind... | Center a region on its middle and expand it to window_size bases.
:return: the new region. | [
"Center",
"a",
"region",
"on",
"its",
"middle",
"and",
"expand",
"it",
"to",
"window_size",
"bases",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L108-L118 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | transform_locus | def transform_locus(region, window_center, window_size):
"""
transform an input genomic region into one suitable for the profile.
:param region: input region to transform.
:param window_center: which part of the input region to center on.
:param window_size: how large the resultant region should ... | python | def transform_locus(region, window_center, window_size):
"""
transform an input genomic region into one suitable for the profile.
:param region: input region to transform.
:param window_center: which part of the input region to center on.
:param window_size: how large the resultant region should ... | [
"def",
"transform_locus",
"(",
"region",
",",
"window_center",
",",
"window_size",
")",
":",
"if",
"window_center",
"==",
"CENTRE",
":",
"region",
".",
"transform_center",
"(",
"window_size",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Don't know how to do th... | transform an input genomic region into one suitable for the profile.
:param region: input region to transform.
:param window_center: which part of the input region to center on.
:param window_size: how large the resultant region should be.
:return: a new genomic interval on the same chromosome, cen... | [
"transform",
"an",
"input",
"genomic",
"region",
"into",
"one",
"suitable",
"for",
"the",
"profile",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L121-L136 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | pid | def pid(col, ignore_gaps=False):
"""
Compute the percent identity of a an alignment column.
Define PID as the frequency of the most frequent nucleotide in the column.
:param col: an alignment column; a dictionary where keys are seq.
names and values are the nucleotide in the colu... | python | def pid(col, ignore_gaps=False):
"""
Compute the percent identity of a an alignment column.
Define PID as the frequency of the most frequent nucleotide in the column.
:param col: an alignment column; a dictionary where keys are seq.
names and values are the nucleotide in the colu... | [
"def",
"pid",
"(",
"col",
",",
"ignore_gaps",
"=",
"False",
")",
":",
"hist",
"=",
"{",
"}",
"total",
"=",
"0",
"found_non_gap",
"=",
"False",
"for",
"v",
"in",
"col",
".",
"values",
"(",
")",
":",
"if",
"v",
"==",
"sequence",
".",
"GAP_CHAR",
":... | Compute the percent identity of a an alignment column.
Define PID as the frequency of the most frequent nucleotide in the column.
:param col: an alignment column; a dictionary where keys are seq.
names and values are the nucleotide in the column for
that sequenc... | [
"Compute",
"the",
"percent",
"identity",
"of",
"a",
"an",
"alignment",
"column",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L143-L174 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | conservtion_profile_pid | def conservtion_profile_pid(region, genome_alignment,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,
species=None):
"""
build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases i... | python | def conservtion_profile_pid(region, genome_alignment,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,
species=None):
"""
build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases i... | [
"def",
"conservtion_profile_pid",
"(",
"region",
",",
"genome_alignment",
",",
"mi_seqs",
"=",
"MissingSequenceHandler",
".",
"TREAT_AS_ALL_GAPS",
",",
"species",
"=",
"None",
")",
":",
"res",
"=",
"[",
"]",
"s",
"=",
"region",
".",
"start",
"if",
"region",
... | build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases identical to the
reference sequence.
:param miss_seqs: how to treat sequence with no actual sequence data for
the column.
:return: a list of the same length ... | [
"build",
"a",
"conservation",
"profile",
"for",
"the",
"given",
"region",
"using",
"the",
"genome",
"alignment",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L177-L204 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | merge_profile | def merge_profile(mean_profile, new_profile):
"""Add a new list of values to a list of rolling means."""
for i in range(0, len(mean_profile)):
if new_profile[i] is None:
continue
mean_profile[i].add(new_profile[i]) | python | def merge_profile(mean_profile, new_profile):
"""Add a new list of values to a list of rolling means."""
for i in range(0, len(mean_profile)):
if new_profile[i] is None:
continue
mean_profile[i].add(new_profile[i]) | [
"def",
"merge_profile",
"(",
"mean_profile",
",",
"new_profile",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"mean_profile",
")",
")",
":",
"if",
"new_profile",
"[",
"i",
"]",
"is",
"None",
":",
"continue",
"mean_profile",
"[",
"i",... | Add a new list of values to a list of rolling means. | [
"Add",
"a",
"new",
"list",
"of",
"values",
"to",
"a",
"list",
"of",
"rolling",
"means",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L207-L212 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | processBED | def processBED(fh, genome_alig, window_size, window_centre,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None,
verbose=False):
"""
Process BED file, produce profile of conservation using whole genome alig.
:param fh:
:param genome_alig: the whole-genome alignment to... | python | def processBED(fh, genome_alig, window_size, window_centre,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None,
verbose=False):
"""
Process BED file, produce profile of conservation using whole genome alig.
:param fh:
:param genome_alig: the whole-genome alignment to... | [
"def",
"processBED",
"(",
"fh",
",",
"genome_alig",
",",
"window_size",
",",
"window_centre",
",",
"mi_seqs",
"=",
"MissingSequenceHandler",
".",
"TREAT_AS_ALL_GAPS",
",",
"species",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"mean_profile",
"=",
"["... | Process BED file, produce profile of conservation using whole genome alig.
:param fh:
:param genome_alig: the whole-genome alignment to use to compute
conservation scores
:param window_size: length of the profile.
:param window_center: which part of each interval to place at the cen... | [
"Process",
"BED",
"file",
"produce",
"profile",
"of",
"conservation",
"using",
"whole",
"genome",
"alig",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L219-L248 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | getUI | def getUI(prog_name, args):
"""Build and return user interface object for this script."""
longDescription = "Given a set of BED intervals, compute a profile of " +\
"conservation by averaging over all intervals using a " +\
"whole genome alignment to a set of relevent species... | python | def getUI(prog_name, args):
"""Build and return user interface object for this script."""
longDescription = "Given a set of BED intervals, compute a profile of " +\
"conservation by averaging over all intervals using a " +\
"whole genome alignment to a set of relevent species... | [
"def",
"getUI",
"(",
"prog_name",
",",
"args",
")",
":",
"longDescription",
"=",
"\"Given a set of BED intervals, compute a profile of \"",
"+",
"\"conservation by averaging over all intervals using a \"",
"+",
"\"whole genome alignment to a set of relevent species.\"",
"+",
"\"\\n\\... | Build and return user interface object for this script. | [
"Build",
"and",
"return",
"user",
"interface",
"object",
"for",
"this",
"script",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L255-L322 |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | main | def main(args, prog_name):
"""Process the command line arguments of this script and dispatch."""
# get options and arguments
ui = getUI(prog_name, args)
if ui.optionIsSet("test"):
# just run unit tests
unittest.main(argv=[sys.argv[0]])
elif ui.optionIsSet("help"):
# just show help
ui.usage()
... | python | def main(args, prog_name):
"""Process the command line arguments of this script and dispatch."""
# get options and arguments
ui = getUI(prog_name, args)
if ui.optionIsSet("test"):
# just run unit tests
unittest.main(argv=[sys.argv[0]])
elif ui.optionIsSet("help"):
# just show help
ui.usage()
... | [
"def",
"main",
"(",
"args",
",",
"prog_name",
")",
":",
"# get options and arguments",
"ui",
"=",
"getUI",
"(",
"prog_name",
",",
"args",
")",
"if",
"ui",
".",
"optionIsSet",
"(",
"\"test\"",
")",
":",
"# just run unit tests",
"unittest",
".",
"main",
"(",
... | Process the command line arguments of this script and dispatch. | [
"Process",
"the",
"command",
"line",
"arguments",
"of",
"this",
"script",
"and",
"dispatch",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L329-L395 |
etcher-be/elib_run | elib_run/_run/_run.py | check_error | def check_error(context: RunContext) -> int:
"""
Runs after a sub-process exits
Checks the return code; if it is different than 0, then a few things happen:
- if the process was muted ("mute" is True), the process output is printed anyway
- if "failure_ok" is True (default), then a SystemE... | python | def check_error(context: RunContext) -> int:
"""
Runs after a sub-process exits
Checks the return code; if it is different than 0, then a few things happen:
- if the process was muted ("mute" is True), the process output is printed anyway
- if "failure_ok" is True (default), then a SystemE... | [
"def",
"check_error",
"(",
"context",
":",
"RunContext",
")",
"->",
"int",
":",
"if",
"context",
".",
"return_code",
"!=",
"0",
":",
"if",
"context",
".",
"mute",
":",
"context",
".",
"result_buffer",
"+=",
"f': command failed: {context.return_code}'",
"else",
... | Runs after a sub-process exits
Checks the return code; if it is different than 0, then a few things happen:
- if the process was muted ("mute" is True), the process output is printed anyway
- if "failure_ok" is True (default), then a SystemExist exception is raised
:param context: run context... | [
"Runs",
"after",
"a",
"sub",
"-",
"process",
"exits"
] | train | https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_run.py#L28-L61 |
etcher-be/elib_run | elib_run/_run/_run.py | run | def run(cmd: str,
*paths: str,
cwd: str = '.',
mute: bool = False,
filters: typing.Optional[typing.Union[typing.Iterable[str], str]] = None,
failure_ok: bool = False,
timeout: float = _DEFAULT_PROCESS_TIMEOUT,
) -> typing.Tuple[str, int]:
"""
Executes a co... | python | def run(cmd: str,
*paths: str,
cwd: str = '.',
mute: bool = False,
filters: typing.Optional[typing.Union[typing.Iterable[str], str]] = None,
failure_ok: bool = False,
timeout: float = _DEFAULT_PROCESS_TIMEOUT,
) -> typing.Tuple[str, int]:
"""
Executes a co... | [
"def",
"run",
"(",
"cmd",
":",
"str",
",",
"*",
"paths",
":",
"str",
",",
"cwd",
":",
"str",
"=",
"'.'",
",",
"mute",
":",
"bool",
"=",
"False",
",",
"filters",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Union",
"[",
"typing",
".",
"I... | Executes a command and returns the result
Args:
cmd: command to execute
paths: paths to search executable in
cwd: working directory (defaults to ".")
mute: if true, output will not be printed
filters: gives a list of partial strings to filter out from the output (stdout or s... | [
"Executes",
"a",
"command",
"and",
"returns",
"the",
"result"
] | train | https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_run.py#L93-L141 |
fred49/linshare-api | linshareapi/admin/jwt.py | Jwt.list | def list(self, domain=None):
"""Workaround: data is automatically filtered by domain."""
# pylint: disable=arguments-differ
if domain:
return self._list(domain)
url = "{base}".format(
base="domains"
)
domains = self.core.get(url)
res = []
... | python | def list(self, domain=None):
"""Workaround: data is automatically filtered by domain."""
# pylint: disable=arguments-differ
if domain:
return self._list(domain)
url = "{base}".format(
base="domains"
)
domains = self.core.get(url)
res = []
... | [
"def",
"list",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"domain",
":",
"return",
"self",
".",
"_list",
"(",
"domain",
")",
"url",
"=",
"\"{base}\"",
".",
"format",
"(",
"base",
"=",
"\"domains\"",
")",
... | Workaround: data is automatically filtered by domain. | [
"Workaround",
":",
"data",
"is",
"automatically",
"filtered",
"by",
"domain",
"."
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/admin/jwt.py#L68-L91 |
sys-git/certifiable | certifiable/cli_impl/complex/certify_dict.py | cli_certify_complex_dict | def cli_certify_complex_dict(
config, schema, key_certifier, value_certifier, allow_extra,
include_collections, value,
):
"""Console script for certify_dict."""
schema = load_json_pickle(schema, config)
key_certifier = create_certifier(load_json_pickle(key_certifier, config))
value_certifier = c... | python | def cli_certify_complex_dict(
config, schema, key_certifier, value_certifier, allow_extra,
include_collections, value,
):
"""Console script for certify_dict."""
schema = load_json_pickle(schema, config)
key_certifier = create_certifier(load_json_pickle(key_certifier, config))
value_certifier = c... | [
"def",
"cli_certify_complex_dict",
"(",
"config",
",",
"schema",
",",
"key_certifier",
",",
"value_certifier",
",",
"allow_extra",
",",
"include_collections",
",",
"value",
",",
")",
":",
"schema",
"=",
"load_json_pickle",
"(",
"schema",
",",
"config",
")",
"key... | Console script for certify_dict. | [
"Console",
"script",
"for",
"certify_dict",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/complex/certify_dict.py#L29-L50 |
monkeython/scriba | scriba/schemes/scriba_https.py | write | def write(url, content, **args):
"""Put the object/collection into a file URL."""
with HTTPSResource(url, **args) as resource:
resource.write(content) | python | def write(url, content, **args):
"""Put the object/collection into a file URL."""
with HTTPSResource(url, **args) as resource:
resource.write(content) | [
"def",
"write",
"(",
"url",
",",
"content",
",",
"*",
"*",
"args",
")",
":",
"with",
"HTTPSResource",
"(",
"url",
",",
"*",
"*",
"args",
")",
"as",
"resource",
":",
"resource",
".",
"write",
"(",
"content",
")"
] | Put the object/collection into a file URL. | [
"Put",
"the",
"object",
"/",
"collection",
"into",
"a",
"file",
"URL",
"."
] | train | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_https.py#L32-L35 |
usc-isi-i2/dig-sparkutil | digSparkUtil/fileUtil.py | main | def main(argv=None):
'''TEST ONLY: this is called if run from command line'''
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input_file', required=True)
parser.add_argument('--input_file_format', default='sequence')
parser.add_argument('--input_data_type', default='json')
parser... | python | def main(argv=None):
'''TEST ONLY: this is called if run from command line'''
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input_file', required=True)
parser.add_argument('--input_file_format', default='sequence')
parser.add_argument('--input_data_type', default='json')
parser... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"'--input_file'",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--i... | TEST ONLY: this is called if run from command line | [
"TEST",
"ONLY",
":",
"this",
"is",
"called",
"if",
"run",
"from",
"command",
"line"
] | train | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/fileUtil.py#L260-L297 |
usc-isi-i2/dig-sparkutil | digSparkUtil/fileUtil.py | FileUtil._load_text_csv_file | def _load_text_csv_file(self, filename, separator=',', **kwargs):
"""Return a pair RDD where key is taken from first column, remaining columns are named after their column id as string"""
rdd_input = self.sc.textFile(filename)
def load_csv_record(line):
input_stream = StringIO.Strin... | python | def _load_text_csv_file(self, filename, separator=',', **kwargs):
"""Return a pair RDD where key is taken from first column, remaining columns are named after their column id as string"""
rdd_input = self.sc.textFile(filename)
def load_csv_record(line):
input_stream = StringIO.Strin... | [
"def",
"_load_text_csv_file",
"(",
"self",
",",
"filename",
",",
"separator",
"=",
"','",
",",
"*",
"*",
"kwargs",
")",
":",
"rdd_input",
"=",
"self",
".",
"sc",
".",
"textFile",
"(",
"filename",
")",
"def",
"load_csv_record",
"(",
"line",
")",
":",
"i... | Return a pair RDD where key is taken from first column, remaining columns are named after their column id as string | [
"Return",
"a",
"pair",
"RDD",
"where",
"key",
"is",
"taken",
"from",
"first",
"column",
"remaining",
"columns",
"are",
"named",
"after",
"their",
"column",
"id",
"as",
"string"
] | train | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/fileUtil.py#L131-L151 |
usc-isi-i2/dig-sparkutil | digSparkUtil/fileUtil.py | FileUtil.get_config | def get_config(config_spec):
"""Like get_json_config but does not parse result as JSON"""
config_file = None
if config_spec.startswith("http"):
# URL: fetch it
config_file = urllib.urlopen(config_spec)
else:
# string: open file with that name
... | python | def get_config(config_spec):
"""Like get_json_config but does not parse result as JSON"""
config_file = None
if config_spec.startswith("http"):
# URL: fetch it
config_file = urllib.urlopen(config_spec)
else:
# string: open file with that name
... | [
"def",
"get_config",
"(",
"config_spec",
")",
":",
"config_file",
"=",
"None",
"if",
"config_spec",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"# URL: fetch it",
"config_file",
"=",
"urllib",
".",
"urlopen",
"(",
"config_spec",
")",
"else",
":",
"# string: ... | Like get_json_config but does not parse result as JSON | [
"Like",
"get_json_config",
"but",
"does",
"not",
"parse",
"result",
"as",
"JSON"
] | train | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/fileUtil.py#L239-L254 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py | LookupModule.reset | def reset(self):
"""set sensible defaults"""
self.start = 1
self.count = None
self.end = None
self.stride = 1
self.format = "%d" | python | def reset(self):
"""set sensible defaults"""
self.start = 1
self.count = None
self.end = None
self.stride = 1
self.format = "%d" | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"start",
"=",
"1",
"self",
".",
"count",
"=",
"None",
"self",
".",
"end",
"=",
"None",
"self",
".",
"stride",
"=",
"1",
"self",
".",
"format",
"=",
"\"%d\""
] | set sensible defaults | [
"set",
"sensible",
"defaults"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py#L80-L86 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py | LookupModule.parse_kv_args | def parse_kv_args(self, args):
"""parse key-value style arguments"""
for arg in ["start", "end", "count", "stride"]:
try:
arg_raw = args.pop(arg, None)
if arg_raw is None:
continue
arg_cooked = int(arg_raw, 0)
... | python | def parse_kv_args(self, args):
"""parse key-value style arguments"""
for arg in ["start", "end", "count", "stride"]:
try:
arg_raw = args.pop(arg, None)
if arg_raw is None:
continue
arg_cooked = int(arg_raw, 0)
... | [
"def",
"parse_kv_args",
"(",
"self",
",",
"args",
")",
":",
"for",
"arg",
"in",
"[",
"\"start\"",
",",
"\"end\"",
",",
"\"count\"",
",",
"\"stride\"",
"]",
":",
"try",
":",
"arg_raw",
"=",
"args",
".",
"pop",
"(",
"arg",
",",
"None",
")",
"if",
"ar... | parse key-value style arguments | [
"parse",
"key",
"-",
"value",
"style",
"arguments"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py#L88-L108 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py | LookupModule.parse_simple_args | def parse_simple_args(self, term):
"""parse the shortcut forms, return True/False"""
match = SHORTCUT.match(term)
if not match:
return False
_, start, end, _, stride, _, format = match.groups()
if start is not None:
try:
start = int(start... | python | def parse_simple_args(self, term):
"""parse the shortcut forms, return True/False"""
match = SHORTCUT.match(term)
if not match:
return False
_, start, end, _, stride, _, format = match.groups()
if start is not None:
try:
start = int(start... | [
"def",
"parse_simple_args",
"(",
"self",
",",
"term",
")",
":",
"match",
"=",
"SHORTCUT",
".",
"match",
"(",
"term",
")",
"if",
"not",
"match",
":",
"return",
"False",
"_",
",",
"start",
",",
"end",
",",
"_",
",",
"stride",
",",
"_",
",",
"format",... | parse the shortcut forms, return True/False | [
"parse",
"the",
"shortcut",
"forms",
"return",
"True",
"/",
"False"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/lookup_plugins/sequence.py#L110-L141 |
coghost/izen | izen/crawler.py | ParseHeaderFromFile.parse_headers | def parse_headers(self, use_cookies, raw):
"""
analyze headers from file or raw messages
:return: (url, dat)
:rtype:
"""
if not raw:
packet = helper.to_str(helper.read_file(self.fpth))
else:
packet = raw
dat = {}
pks = [x ... | python | def parse_headers(self, use_cookies, raw):
"""
analyze headers from file or raw messages
:return: (url, dat)
:rtype:
"""
if not raw:
packet = helper.to_str(helper.read_file(self.fpth))
else:
packet = raw
dat = {}
pks = [x ... | [
"def",
"parse_headers",
"(",
"self",
",",
"use_cookies",
",",
"raw",
")",
":",
"if",
"not",
"raw",
":",
"packet",
"=",
"helper",
".",
"to_str",
"(",
"helper",
".",
"read_file",
"(",
"self",
".",
"fpth",
")",
")",
"else",
":",
"packet",
"=",
"raw",
... | analyze headers from file or raw messages
:return: (url, dat)
:rtype: | [
"analyze",
"headers",
"from",
"file",
"or",
"raw",
"messages"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L82-L113 |
coghost/izen | izen/crawler.py | ParseHeaderFromFile.fmt_cookies | def fmt_cookies(self, ck):
"""
:param ck:
:type ck:
:return:
:rtype:
"""
cks = {}
for c in ck.split(';'):
a = c.split('=')
if len(a) != 2:
continue
cks[a[0].replace(' ', '')] = a[1].replace(' ', '')
... | python | def fmt_cookies(self, ck):
"""
:param ck:
:type ck:
:return:
:rtype:
"""
cks = {}
for c in ck.split(';'):
a = c.split('=')
if len(a) != 2:
continue
cks[a[0].replace(' ', '')] = a[1].replace(' ', '')
... | [
"def",
"fmt_cookies",
"(",
"self",
",",
"ck",
")",
":",
"cks",
"=",
"{",
"}",
"for",
"c",
"in",
"ck",
".",
"split",
"(",
"';'",
")",
":",
"a",
"=",
"c",
".",
"split",
"(",
"'='",
")",
"if",
"len",
"(",
"a",
")",
"!=",
"2",
":",
"continue",
... | :param ck:
:type ck:
:return:
:rtype: | [
":",
"param",
"ck",
":",
":",
"type",
"ck",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L115-L128 |
coghost/izen | izen/crawler.py | Crawler.spawn | def spawn(self, url, force_spawn=False):
"""use the url for creation of domain and fetch cookies
- init cache dir by the url domain as ``<base>/domain``
- save the cookies to file ``<base>/domain/cookie.txt``
- init ``headers.get/post/json`` with response info
- init ``site_dir/... | python | def spawn(self, url, force_spawn=False):
"""use the url for creation of domain and fetch cookies
- init cache dir by the url domain as ``<base>/domain``
- save the cookies to file ``<base>/domain/cookie.txt``
- init ``headers.get/post/json`` with response info
- init ``site_dir/... | [
"def",
"spawn",
"(",
"self",
",",
"url",
",",
"force_spawn",
"=",
"False",
")",
":",
"_url",
",",
"domain",
"=",
"self",
".",
"get_domain_home_from_url",
"(",
"url",
")",
"if",
"not",
"_url",
":",
"return",
"False",
"self",
".",
"cache",
"[",
"'site_di... | use the url for creation of domain and fetch cookies
- init cache dir by the url domain as ``<base>/domain``
- save the cookies to file ``<base>/domain/cookie.txt``
- init ``headers.get/post/json`` with response info
- init ``site_dir/site_raw/site_media``
:param url:
:... | [
"use",
"the",
"url",
"for",
"creation",
"of",
"domain",
"and",
"fetch",
"cookies"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L179-L227 |
coghost/izen | izen/crawler.py | Crawler.get_domain_home_from_url | def get_domain_home_from_url(self, url):
""" parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype:
"""
p = parse.urlparse(url)
if p.netloc:
self.domain = p.netloc
self.homepage... | python | def get_domain_home_from_url(self, url):
""" parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype:
"""
p = parse.urlparse(url)
if p.netloc:
self.domain = p.netloc
self.homepage... | [
"def",
"get_domain_home_from_url",
"(",
"self",
",",
"url",
")",
":",
"p",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"if",
"p",
".",
"netloc",
":",
"self",
".",
"domain",
"=",
"p",
".",
"netloc",
"self",
".",
"homepage",
"=",
"'{}://{}'",
".",
... | parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype: | [
"parse",
"url",
"for",
"domain",
"and",
"homepage"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L229-L243 |
coghost/izen | izen/crawler.py | Crawler.map_url_to_cache_id | def map_url_to_cache_id(self, url):
"""use of the url resource location as cached id
e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html``
- map the url to local file
:param url:
:type url:
:return:
:rtype:
"""
base, _ = self.get_dom... | python | def map_url_to_cache_id(self, url):
"""use of the url resource location as cached id
e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html``
- map the url to local file
:param url:
:type url:
:return:
:rtype:
"""
base, _ = self.get_dom... | [
"def",
"map_url_to_cache_id",
"(",
"self",
",",
"url",
")",
":",
"base",
",",
"_",
"=",
"self",
".",
"get_domain_home_from_url",
"(",
"url",
")",
"if",
"base",
"==",
"''",
":",
"# invalid url",
"_sub_page",
"=",
"''",
"elif",
"base",
"==",
"url",
"or",
... | use of the url resource location as cached id
e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html``
- map the url to local file
:param url:
:type url:
:return:
:rtype: | [
"use",
"of",
"the",
"url",
"resource",
"location",
"as",
"cached",
"id"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L264-L293 |
coghost/izen | izen/crawler.py | Crawler.gen_tasks | def gen_tasks(self, urls):
""" according the urls gen {name:'', url:''} dict.
:param urls:
:type urls:
:return:
:rtype:
"""
tasks = []
if isinstance(urls, list):
for url in urls:
dat = {
'url': url,
... | python | def gen_tasks(self, urls):
""" according the urls gen {name:'', url:''} dict.
:param urls:
:type urls:
:return:
:rtype:
"""
tasks = []
if isinstance(urls, list):
for url in urls:
dat = {
'url': url,
... | [
"def",
"gen_tasks",
"(",
"self",
",",
"urls",
")",
":",
"tasks",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"urls",
",",
"list",
")",
":",
"for",
"url",
"in",
"urls",
":",
"dat",
"=",
"{",
"'url'",
":",
"url",
",",
"'name'",
":",
"url",
".",
"spli... | according the urls gen {name:'', url:''} dict.
:param urls:
:type urls:
:return:
:rtype: | [
"according",
"the",
"urls",
"gen",
"{",
"name",
":",
"url",
":",
"}",
"dict",
".",
":",
"param",
"urls",
":",
":",
"type",
"urls",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L301-L332 |
coghost/izen | izen/crawler.py | CommonCrawler.do_sess_get | def do_sess_get(self, url):
"""get url by requests synchronized
:param url:
:type url:
:return:
:rtype:
"""
try:
res = self.sess.get(url, headers=self.headers['get'], timeout=self.timeout)
if res.status_code == 200:
return ... | python | def do_sess_get(self, url):
"""get url by requests synchronized
:param url:
:type url:
:return:
:rtype:
"""
try:
res = self.sess.get(url, headers=self.headers['get'], timeout=self.timeout)
if res.status_code == 200:
return ... | [
"def",
"do_sess_get",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"sess",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
"[",
"'get'",
"]",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"if",
... | get url by requests synchronized
:param url:
:type url:
:return:
:rtype: | [
"get",
"url",
"by",
"requests",
"synchronized"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L347-L360 |
coghost/izen | izen/crawler.py | CommonCrawler.load | def load(self, url, use_cache=True, show_log=False):
"""fetch the url ``raw info``, use cache first, if no cache hit, try get from Internet
:param url:
:type url:
:param use_cache:
:type use_cache:
:param show_log:
:type show_log:
:return: the ``raw info`... | python | def load(self, url, use_cache=True, show_log=False):
"""fetch the url ``raw info``, use cache first, if no cache hit, try get from Internet
:param url:
:type url:
:param use_cache:
:type use_cache:
:param show_log:
:type show_log:
:return: the ``raw info`... | [
"def",
"load",
"(",
"self",
",",
"url",
",",
"use_cache",
"=",
"True",
",",
"show_log",
"=",
"False",
")",
":",
"_name",
"=",
"self",
".",
"map_url_to_cache_id",
"(",
"url",
")",
"raw",
"=",
"''",
"hit",
"=",
"False",
"if",
"use_cache",
":",
"hit",
... | fetch the url ``raw info``, use cache first, if no cache hit, try get from Internet
:param url:
:type url:
:param use_cache:
:type use_cache:
:param show_log:
:type show_log:
:return: the ``raw info`` of the url
:rtype: ``str`` | [
"fetch",
"the",
"url",
"raw",
"info",
"use",
"cache",
"first",
"if",
"no",
"cache",
"hit",
"try",
"get",
"from",
"Internet"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L362-L394 |
coghost/izen | izen/crawler.py | CommonCrawler.sync_save | def sync_save(self, res, overwrite=False):
""" save ``res`` to local synchronized
:param res: {'url': '', 'name': ''}
:type res: dict
:param overwrite:
:type overwrite:
:return:
:rtype: BeautifulSoup
"""
if not isinstance(res, dict):
r... | python | def sync_save(self, res, overwrite=False):
""" save ``res`` to local synchronized
:param res: {'url': '', 'name': ''}
:type res: dict
:param overwrite:
:type overwrite:
:return:
:rtype: BeautifulSoup
"""
if not isinstance(res, dict):
r... | [
"def",
"sync_save",
"(",
"self",
",",
"res",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"res",
",",
"dict",
")",
":",
"raise",
"CrawlerParamsError",
"(",
"'res must be dict'",
")",
"url_",
",",
"file_name",
"=",
"res",
".",... | save ``res`` to local synchronized
:param res: {'url': '', 'name': ''}
:type res: dict
:param overwrite:
:type overwrite:
:return:
:rtype: BeautifulSoup | [
"save",
"res",
"to",
"local",
"synchronized"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L448-L478 |
coghost/izen | izen/crawler.py | AsyncCrawler.crawl_raw | async def crawl_raw(self, res):
""" crawl the raw doc, and save it asynchronous.
:param res: {'url','', 'name': ''}
:type res: ``dict``
:return:
:rtype:
"""
cnt = await self.async_get(res)
if cnt:
loop_ = asyncio.get_event_loop()
a... | python | async def crawl_raw(self, res):
""" crawl the raw doc, and save it asynchronous.
:param res: {'url','', 'name': ''}
:type res: ``dict``
:return:
:rtype:
"""
cnt = await self.async_get(res)
if cnt:
loop_ = asyncio.get_event_loop()
a... | [
"async",
"def",
"crawl_raw",
"(",
"self",
",",
"res",
")",
":",
"cnt",
"=",
"await",
"self",
".",
"async_get",
"(",
"res",
")",
"if",
"cnt",
":",
"loop_",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"await",
"loop_",
".",
"run_in_executor",
"(",
... | crawl the raw doc, and save it asynchronous.
:param res: {'url','', 'name': ''}
:type res: ``dict``
:return:
:rtype: | [
"crawl",
"the",
"raw",
"doc",
"and",
"save",
"it",
"asynchronous",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L494-L508 |
coghost/izen | izen/crawler.py | AsyncCrawler._sem_crawl | async def _sem_crawl(self, sem, res):
""" use semaphore ``encapsulate`` the crawl_media \n
with async crawl, should avoid crawl too fast to become DDos attack to the crawled server
should set the ``semaphore size``, and take ``a little gap`` between each crawl behavior.
:param sem: the ... | python | async def _sem_crawl(self, sem, res):
""" use semaphore ``encapsulate`` the crawl_media \n
with async crawl, should avoid crawl too fast to become DDos attack to the crawled server
should set the ``semaphore size``, and take ``a little gap`` between each crawl behavior.
:param sem: the ... | [
"async",
"def",
"_sem_crawl",
"(",
"self",
",",
"sem",
",",
"res",
")",
":",
"async",
"with",
"sem",
":",
"st_",
"=",
"await",
"self",
".",
"crawl_raw",
"(",
"res",
")",
"if",
"st_",
":",
"self",
".",
"result",
"[",
"'ok'",
"]",
"+=",
"1",
"else"... | use semaphore ``encapsulate`` the crawl_media \n
with async crawl, should avoid crawl too fast to become DDos attack to the crawled server
should set the ``semaphore size``, and take ``a little gap`` between each crawl behavior.
:param sem: the size of semaphore
:type sem:
:para... | [
"use",
"semaphore",
"encapsulate",
"the",
"crawl_media",
"\\",
"n",
"with",
"async",
"crawl",
"should",
"avoid",
"crawl",
"too",
"fast",
"to",
"become",
"DDos",
"attack",
"to",
"the",
"crawled",
"server",
"should",
"set",
"the",
"semaphore",
"size",
"and",
"... | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L510-L530 |
coghost/izen | izen/crawler.py | AsyncCrawler.crawl | async def crawl(self, urls, sem):
"""
:param urls:
:type urls: list/dict
:param sem:
:type sem:
:return:
:rtype:
"""
tasks = [
self._sem_crawl(sem, x)
for x in urls
]
tasks_iter = asyncio.as_completed(tasks)... | python | async def crawl(self, urls, sem):
"""
:param urls:
:type urls: list/dict
:param sem:
:type sem:
:return:
:rtype:
"""
tasks = [
self._sem_crawl(sem, x)
for x in urls
]
tasks_iter = asyncio.as_completed(tasks)... | [
"async",
"def",
"crawl",
"(",
"self",
",",
"urls",
",",
"sem",
")",
":",
"tasks",
"=",
"[",
"self",
".",
"_sem_crawl",
"(",
"sem",
",",
"x",
")",
"for",
"x",
"in",
"urls",
"]",
"tasks_iter",
"=",
"asyncio",
".",
"as_completed",
"(",
"tasks",
")",
... | :param urls:
:type urls: list/dict
:param sem:
:type sem:
:return:
:rtype: | [
":",
"param",
"urls",
":",
":",
"type",
"urls",
":",
"list",
"/",
"dict",
":",
"param",
"sem",
":",
":",
"type",
"sem",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/crawler.py#L532-L555 |
emencia/emencia-django-forum | forum/utils/imports.py | safe_import_module | def safe_import_module(path, default=None):
"""
Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if import fails, it can be None, a callable or whatever you need.
Return a object ... | python | def safe_import_module(path, default=None):
"""
Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if import fails, it can be None, a callable or whatever you need.
Return a object ... | [
"def",
"safe_import_module",
"(",
"path",
",",
"default",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"default",
"dot",
"=",
"path",
".",
"rindex",
"(",
"'.'",
")",
"module_name",
"=",
"path",
"[",
":",
"dot",
"]",
"class_name",
... | Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if import fails, it can be None, a callable or whatever you need.
Return a object or None | [
"Try",
"to",
"import",
"the",
"specified",
"module",
"from",
"the",
"given",
"Python",
"path"
] | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/utils/imports.py#L6-L26 |
incuna/incuna-pagination | pagination/templatetags/querystrings.py | querystring_update | def querystring_update(request, **kwargs):
"""
Output a URL-encoded querystring, updated with key:values from `kwargs`.
From http://stackoverflow.com/a/24658162.
"""
updated = request.GET.copy()
for k, v in kwargs.items():
updated[k] = v
return updated.urlencode() | python | def querystring_update(request, **kwargs):
"""
Output a URL-encoded querystring, updated with key:values from `kwargs`.
From http://stackoverflow.com/a/24658162.
"""
updated = request.GET.copy()
for k, v in kwargs.items():
updated[k] = v
return updated.urlencode() | [
"def",
"querystring_update",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"updated",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"updated",
"[",
"k",
"]",
"=",
"v",
... | Output a URL-encoded querystring, updated with key:values from `kwargs`.
From http://stackoverflow.com/a/24658162. | [
"Output",
"a",
"URL",
"-",
"encoded",
"querystring",
"updated",
"with",
"key",
":",
"values",
"from",
"kwargs",
"."
] | train | https://github.com/incuna/incuna-pagination/blob/a80f923a313e69c9f0e2458f4eb65376b6544817/pagination/templatetags/querystrings.py#L8-L18 |
alfred82santa/aio-service-client | service_client/json.py | json_decoder | def json_decoder(content, *args, **kwargs):
"""
Json decoder parser to be used by service_client
"""
if not content:
return None
json_value = content.decode()
return json.loads(json_value) | python | def json_decoder(content, *args, **kwargs):
"""
Json decoder parser to be used by service_client
"""
if not content:
return None
json_value = content.decode()
return json.loads(json_value) | [
"def",
"json_decoder",
"(",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"content",
":",
"return",
"None",
"json_value",
"=",
"content",
".",
"decode",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"json_value",
")"
] | Json decoder parser to be used by service_client | [
"Json",
"decoder",
"parser",
"to",
"be",
"used",
"by",
"service_client"
] | train | https://github.com/alfred82santa/aio-service-client/blob/dd9ad49e23067b22178534915aa23ba24f6ff39b/service_client/json.py#L11-L18 |
mbarakaja/braulio | braulio/cli.py | init | def init(changelog_name):
"""Setup your project."""
changelog_path = find_chglog_file()
create_changelog_flag = True
mark = style("?", fg="blue", bold=True)
if not changelog_name:
if changelog_path:
filename = style(changelog_path.name, fg="blue", bold=True)
message... | python | def init(changelog_name):
"""Setup your project."""
changelog_path = find_chglog_file()
create_changelog_flag = True
mark = style("?", fg="blue", bold=True)
if not changelog_name:
if changelog_path:
filename = style(changelog_path.name, fg="blue", bold=True)
message... | [
"def",
"init",
"(",
"changelog_name",
")",
":",
"changelog_path",
"=",
"find_chglog_file",
"(",
")",
"create_changelog_flag",
"=",
"True",
"mark",
"=",
"style",
"(",
"\"?\"",
",",
"fg",
"=",
"\"blue\"",
",",
"bold",
"=",
"True",
")",
"if",
"not",
"changelo... | Setup your project. | [
"Setup",
"your",
"project",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L67-L91 |
mbarakaja/braulio | braulio/cli.py | bump_option_validator | def bump_option_validator(ctx, param, value):
"""In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**.
"""
if value:
try:
value = Version(value)
ex... | python | def bump_option_validator(ctx, param, value):
"""In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**.
"""
if value:
try:
value = Version(value)
ex... | [
"def",
"bump_option_validator",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
":",
"try",
":",
"value",
"=",
"Version",
"(",
"value",
")",
"except",
"ValueError",
":",
"ctx",
".",
"fail",
"(",
"f\"{x_mark} {value} is not a valid version stri... | In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**. | [
"In",
"case",
"a",
"value",
"is",
"provided",
"checks",
"that",
"it",
"is",
"a",
"valid",
"version",
"string",
".",
"If",
"is",
"not",
"thrown",
":",
"class",
":",
"click",
".",
"UsageError",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L94-L107 |
mbarakaja/braulio | braulio/cli.py | changelog_file_option_validator | def changelog_file_option_validator(ctx, param, value):
"""Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception.
"""
path = Path(value)
if not path.exists():
... | python | def changelog_file_option_validator(ctx, param, value):
"""Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception.
"""
path = Path(value)
if not path.exists():
... | [
"def",
"changelog_file_option_validator",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"path",
"=",
"Path",
"(",
"value",
")",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"filename",
"=",
"click",
".",
"style",
"(",
"path",
".",
"name",
"... | Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception. | [
"Checks",
"that",
"the",
"given",
"file",
"path",
"exists",
"in",
"the",
"current",
"working",
"directory",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L118-L135 |
mbarakaja/braulio | braulio/cli.py | message_option_validator | def message_option_validator(ctx, param, value):
"""A commit template must have the **{new_version}** placeholder."""
if not value or "{new_version}" not in value:
ctx.fail("Missing {new_version} placeholder in " f"{value}.")
return value | python | def message_option_validator(ctx, param, value):
"""A commit template must have the **{new_version}** placeholder."""
if not value or "{new_version}" not in value:
ctx.fail("Missing {new_version} placeholder in " f"{value}.")
return value | [
"def",
"message_option_validator",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"\"{new_version}\"",
"not",
"in",
"value",
":",
"ctx",
".",
"fail",
"(",
"\"Missing {new_version} placeholder in \"",
"f\"{value}.\"",
")",
"return",
... | A commit template must have the **{new_version}** placeholder. | [
"A",
"commit",
"template",
"must",
"have",
"the",
"**",
"{",
"new_version",
"}",
"**",
"placeholder",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L138-L144 |
mbarakaja/braulio | braulio/cli.py | current_version_option_validator | def current_version_option_validator(ctx, param, value):
"""If a version string is provided, validates it. Otherwise it tries
to determine the current version from the last Git tag that matches
``tag_pattern`` option.
Return a :class:`~braulio.version.Version` object or **None**.
"""
current_v... | python | def current_version_option_validator(ctx, param, value):
"""If a version string is provided, validates it. Otherwise it tries
to determine the current version from the last Git tag that matches
``tag_pattern`` option.
Return a :class:`~braulio.version.Version` object or **None**.
"""
current_v... | [
"def",
"current_version_option_validator",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"current_version",
"=",
"None",
"if",
"value",
":",
"try",
":",
"current_version",
"=",
"Version",
"(",
"value",
")",
"except",
"ValueError",
":",
"ctx",
".",
"fail"... | If a version string is provided, validates it. Otherwise it tries
to determine the current version from the last Git tag that matches
``tag_pattern`` option.
Return a :class:`~braulio.version.Version` object or **None**. | [
"If",
"a",
"version",
"string",
"is",
"provided",
"validates",
"it",
".",
"Otherwise",
"it",
"tries",
"to",
"determine",
"the",
"current",
"version",
"from",
"the",
"last",
"Git",
"tag",
"that",
"matches",
"tag_pattern",
"option",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L158-L191 |
mbarakaja/braulio | braulio/cli.py | label_pattern_option_validator | def label_pattern_option_validator(ctx, param, value):
"""Checks that a given string has all the required placeholders. The
possible placeholders are **{type}**, **{scope}** and **{subject}**.
``{type}`` are always required, ``{scope}`` is optional and
``{subject}`` are required only when ``label_posit... | python | def label_pattern_option_validator(ctx, param, value):
"""Checks that a given string has all the required placeholders. The
possible placeholders are **{type}**, **{scope}** and **{subject}**.
``{type}`` are always required, ``{scope}`` is optional and
``{subject}`` are required only when ``label_posit... | [
"def",
"label_pattern_option_validator",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"missings",
"=",
"[",
"]",
"label_position",
"=",
"ctx",
".",
"params",
"[",
"\"label_position\"",
"]",
"if",
"\"{type}\"",
"not",
"in",
"value",
":",
"missings",
".",... | Checks that a given string has all the required placeholders. The
possible placeholders are **{type}**, **{scope}** and **{subject}**.
``{type}`` are always required, ``{scope}`` is optional and
``{subject}`` are required only when ``label_position`` option is set to
``header``.
If the pattern is ... | [
"Checks",
"that",
"a",
"given",
"string",
"has",
"all",
"the",
"required",
"placeholders",
".",
"The",
"possible",
"placeholders",
"are",
"**",
"{",
"type",
"}",
"**",
"**",
"{",
"scope",
"}",
"**",
"and",
"**",
"{",
"subject",
"}",
"**",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L194-L222 |
mbarakaja/braulio | braulio/cli.py | release | def release(
ctx,
bump,
bump_type,
commit_flag,
message,
tag_flag,
confirm_flag,
changelog_file,
files,
label_pattern,
label_position,
tag_pattern,
current_version,
stage,
merge_pre,
current_tag=None,
versions=None,
):
"""Release a new version.
... | python | def release(
ctx,
bump,
bump_type,
commit_flag,
message,
tag_flag,
confirm_flag,
changelog_file,
files,
label_pattern,
label_position,
tag_pattern,
current_version,
stage,
merge_pre,
current_tag=None,
versions=None,
):
"""Release a new version.
... | [
"def",
"release",
"(",
"ctx",
",",
"bump",
",",
"bump_type",
",",
"commit_flag",
",",
"message",
",",
"tag_flag",
",",
"confirm_flag",
",",
"changelog_file",
",",
"files",
",",
"label_pattern",
",",
"label_position",
",",
"tag_pattern",
",",
"current_version",
... | Release a new version.
Determines the next version by inspecting commit messages, updates the
changelog, commit the changes and tag the repository with the new version. | [
"Release",
"a",
"new",
"version",
"."
] | train | https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/cli.py#L297-L434 |
lanhel/ftpysetup | ftpysetup/website/config/__init__.py | HTMLTranslator.layout | def layout(self, indent=' '):
"""This will indent each new tag in the body by given number of spaces."""
self.__indent(self.head, indent)
self.__indent(self.meta, indent)
self.__indent(self.stylesheet, indent)
self.__indent(self.header, indent)
self.__indent(self.body, indent, initial=3)
self.__inden... | python | def layout(self, indent=' '):
"""This will indent each new tag in the body by given number of spaces."""
self.__indent(self.head, indent)
self.__indent(self.meta, indent)
self.__indent(self.stylesheet, indent)
self.__indent(self.header, indent)
self.__indent(self.body, indent, initial=3)
self.__inden... | [
"def",
"layout",
"(",
"self",
",",
"indent",
"=",
"' '",
")",
":",
"self",
".",
"__indent",
"(",
"self",
".",
"head",
",",
"indent",
")",
"self",
".",
"__indent",
"(",
"self",
".",
"meta",
",",
"indent",
")",
"self",
".",
"__indent",
"(",
"self"... | This will indent each new tag in the body by given number of spaces. | [
"This",
"will",
"indent",
"each",
"new",
"tag",
"in",
"the",
"body",
"by",
"given",
"number",
"of",
"spaces",
"."
] | train | https://github.com/lanhel/ftpysetup/blob/9cdea6b82658fb4394b582d1fe5b05eaf5746fde/ftpysetup/website/config/__init__.py#L117-L128 |
lanhel/ftpysetup | ftpysetup/website/config/__init__.py | HTMLTranslator.__indent | def __indent(self, lines, indent, initial=2):
"""This will indent the given set of lines by normal HTML layout.
An initial indent of `2*indent` will be used to account for the
`<html><head>` or `<html><body>` levels."""
tagempty = re.compile(r"""<\w+(\s+[^>]*?)*/>""")
tagopen = re.compile(r"""<\w+(\s+[^>]*?)*... | python | def __indent(self, lines, indent, initial=2):
"""This will indent the given set of lines by normal HTML layout.
An initial indent of `2*indent` will be used to account for the
`<html><head>` or `<html><body>` levels."""
tagempty = re.compile(r"""<\w+(\s+[^>]*?)*/>""")
tagopen = re.compile(r"""<\w+(\s+[^>]*?)*... | [
"def",
"__indent",
"(",
"self",
",",
"lines",
",",
"indent",
",",
"initial",
"=",
"2",
")",
":",
"tagempty",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"<\\w+(\\s+[^>]*?)*/>\"\"\"",
")",
"tagopen",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"<\\w+(\\s+[^>]*?)*>\"\"\""... | This will indent the given set of lines by normal HTML layout.
An initial indent of `2*indent` will be used to account for the
`<html><head>` or `<html><body>` levels. | [
"This",
"will",
"indent",
"the",
"given",
"set",
"of",
"lines",
"by",
"normal",
"HTML",
"layout",
".",
"An",
"initial",
"indent",
"of",
"2",
"*",
"indent",
"will",
"be",
"used",
"to",
"account",
"for",
"the",
"<html",
">",
"<head",
">",
"or",
"<html",
... | train | https://github.com/lanhel/ftpysetup/blob/9cdea6b82658fb4394b582d1fe5b05eaf5746fde/ftpysetup/website/config/__init__.py#L130-L153 |
beaugunderson/intervention | intervention/launch.py | main | def main():
"""
Show the intervention screen.
"""
application = Application(sys.argv, ignore_close=not SKIP_FILTER)
platform.hide_cursor()
with open(resource_filename(__name__, 'intervention.css')) as css:
application.setStyleSheet(css.read())
# exec() is required for objc so we m... | python | def main():
"""
Show the intervention screen.
"""
application = Application(sys.argv, ignore_close=not SKIP_FILTER)
platform.hide_cursor()
with open(resource_filename(__name__, 'intervention.css')) as css:
application.setStyleSheet(css.read())
# exec() is required for objc so we m... | [
"def",
"main",
"(",
")",
":",
"application",
"=",
"Application",
"(",
"sys",
".",
"argv",
",",
"ignore_close",
"=",
"not",
"SKIP_FILTER",
")",
"platform",
".",
"hide_cursor",
"(",
")",
"with",
"open",
"(",
"resource_filename",
"(",
"__name__",
",",
"'inter... | Show the intervention screen. | [
"Show",
"the",
"intervention",
"screen",
"."
] | train | https://github.com/beaugunderson/intervention/blob/72ee436c38962006b30747e16ac0d20d298ec9d5/intervention/launch.py#L39-L98 |
dr4ke616/pinky | pinky/scripts/output.py | style_to_ansi_code | def style_to_ansi_code(style):
"""
:param style: A style name
:type style: string
:returns: A string containing one or more ansi escape codes that are
used to render the given style.
:type return: string
"""
ret = ''
for attr_name in _styles[style]:
# allow stuff th... | python | def style_to_ansi_code(style):
"""
:param style: A style name
:type style: string
:returns: A string containing one or more ansi escape codes that are
used to render the given style.
:type return: string
"""
ret = ''
for attr_name in _styles[style]:
# allow stuff th... | [
"def",
"style_to_ansi_code",
"(",
"style",
")",
":",
"ret",
"=",
"''",
"for",
"attr_name",
"in",
"_styles",
"[",
"style",
"]",
":",
"# allow stuff that has found it's way through ansi_code_pattern",
"ret",
"+=",
"codes",
".",
"get",
"(",
"attr_name",
",",
"attr_na... | :param style: A style name
:type style: string
:returns: A string containing one or more ansi escape codes that are
used to render the given style.
:type return: string | [
":",
"param",
"style",
":",
"A",
"style",
"name",
":",
"type",
"style",
":",
"string",
":",
"returns",
":",
"A",
"string",
"containing",
"one",
"or",
"more",
"ansi",
"escape",
"codes",
"that",
"are",
"used",
"to",
"render",
"the",
"given",
"style",
"."... | train | https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/pinky/scripts/output.py#L79-L92 |
ramrod-project/database-brain | schema/brain/binary/filesystem.py | start_filesystem | def start_filesystem(mountpoint,
config=None): # pragma: no cover
"""
prgramatically mount this filesystem to some mount point
:param mountpoint:
:param config:
:return:
"""
if has_fuse:
if not config:
config = BrainStoreConfig()
FUSE(BrainSt... | python | def start_filesystem(mountpoint,
config=None): # pragma: no cover
"""
prgramatically mount this filesystem to some mount point
:param mountpoint:
:param config:
:return:
"""
if has_fuse:
if not config:
config = BrainStoreConfig()
FUSE(BrainSt... | [
"def",
"start_filesystem",
"(",
"mountpoint",
",",
"config",
"=",
"None",
")",
":",
"# pragma: no cover",
"if",
"has_fuse",
":",
"if",
"not",
"config",
":",
"config",
"=",
"BrainStoreConfig",
"(",
")",
"FUSE",
"(",
"BrainStore",
"(",
"config",
")",
",",
"m... | prgramatically mount this filesystem to some mount point
:param mountpoint:
:param config:
:return: | [
"prgramatically",
"mount",
"this",
"filesystem",
"to",
"some",
"mount",
"point",
":",
"param",
"mountpoint",
":",
":",
"param",
"config",
":",
":",
"return",
":"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/filesystem.py#L232-L245 |
ramrod-project/database-brain | schema/brain/binary/filesystem.py | BrainStore.create | def create(self, path, mode): # pragma: no cover
"""
This is currently a read-only filessytem.
GetAttr will return a stat for everything
if getattr raises FuseOSError(ENOENT)
OS may call this function and the write function
"""
# print("create {}".format(path))
... | python | def create(self, path, mode): # pragma: no cover
"""
This is currently a read-only filessytem.
GetAttr will return a stat for everything
if getattr raises FuseOSError(ENOENT)
OS may call this function and the write function
"""
# print("create {}".format(path))
... | [
"def",
"create",
"(",
"self",
",",
"path",
",",
"mode",
")",
":",
"# pragma: no cover",
"# print(\"create {}\".format(path))",
"now_time",
"=",
"time",
"(",
")",
"with",
"self",
".",
"attr_lock",
":",
"base",
"=",
"NoStat",
"(",
")",
"base",
".",
"staged",
... | This is currently a read-only filessytem.
GetAttr will return a stat for everything
if getattr raises FuseOSError(ENOENT)
OS may call this function and the write function | [
"This",
"is",
"currently",
"a",
"read",
"-",
"only",
"filessytem",
".",
"GetAttr",
"will",
"return",
"a",
"stat",
"for",
"everything",
"if",
"getattr",
"raises",
"FuseOSError",
"(",
"ENOENT",
")",
"OS",
"may",
"call",
"this",
"function",
"and",
"the",
"wri... | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/filesystem.py#L149-L167 |
ramrod-project/database-brain | schema/brain/binary/filesystem.py | BrainStore.write | def write(self, path, data, offset, fh): # pragma: no cover
"""
This is a readonly filesystem right now
"""
# print("write {}".format(path))
with self.attr_lock:
base = self.attr[path][BASE_KEY]
staged = self.attr[path][STAGED_KEY]
if not stag... | python | def write(self, path, data, offset, fh): # pragma: no cover
"""
This is a readonly filesystem right now
"""
# print("write {}".format(path))
with self.attr_lock:
base = self.attr[path][BASE_KEY]
staged = self.attr[path][STAGED_KEY]
if not stag... | [
"def",
"write",
"(",
"self",
",",
"path",
",",
"data",
",",
"offset",
",",
"fh",
")",
":",
"# pragma: no cover",
"# print(\"write {}\".format(path))",
"with",
"self",
".",
"attr_lock",
":",
"base",
"=",
"self",
".",
"attr",
"[",
"path",
"]",
"[",
"BASE_KEY... | This is a readonly filesystem right now | [
"This",
"is",
"a",
"readonly",
"filesystem",
"right",
"now"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/filesystem.py#L169-L180 |
ramrod-project/database-brain | schema/brain/binary/filesystem.py | BrainStore._cleanup | def _cleanup(self): # pragma: no cover
"""
cleans up data that's been in the cache for a while
should be called from an async OS call like release? to not impact user
:return:
"""
need_to_delete = [] # can't delete from a dict while iterating
with self.attr_loc... | python | def _cleanup(self): # pragma: no cover
"""
cleans up data that's been in the cache for a while
should be called from an async OS call like release? to not impact user
:return:
"""
need_to_delete = [] # can't delete from a dict while iterating
with self.attr_loc... | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"# pragma: no cover",
"need_to_delete",
"=",
"[",
"]",
"# can't delete from a dict while iterating",
"with",
"self",
".",
"attr_lock",
":",
"now_time",
"=",
"time",
"(",
")",
"for",
"path",
"in",
"self",
".",
"cache",
... | cleans up data that's been in the cache for a while
should be called from an async OS call like release? to not impact user
:return: | [
"cleans",
"up",
"data",
"that",
"s",
"been",
"in",
"the",
"cache",
"for",
"a",
"while"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/filesystem.py#L214-L229 |
sci-bots/mpm | mpm/bin/__init__.py | validate_args | def validate_args(args):
'''
Apply custom validation and actions based on parsed arguments.
Parameters
----------
args : argparse.Namespace
Result from ``parse_args`` method of ``argparse.ArgumentParser``
instance.
Returns
-------
argparse.Namespace
Reference to... | python | def validate_args(args):
'''
Apply custom validation and actions based on parsed arguments.
Parameters
----------
args : argparse.Namespace
Result from ``parse_args`` method of ``argparse.ArgumentParser``
instance.
Returns
-------
argparse.Namespace
Reference to... | [
"def",
"validate_args",
"(",
"args",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"args",
".",
"log_level",
".",
"upper",
"(",
")",
")",
")",
"if",
"getattr",
"(",
"args",
",",
"'command'",
",",
"None",
... | Apply custom validation and actions based on parsed arguments.
Parameters
----------
args : argparse.Namespace
Result from ``parse_args`` method of ``argparse.ArgumentParser``
instance.
Returns
-------
argparse.Namespace
Reference to input ``args``, which have been vali... | [
"Apply",
"custom",
"validation",
"and",
"actions",
"based",
"on",
"parsed",
"arguments",
"."
] | train | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/bin/__init__.py#L88-L126 |
msuozzo/Aduro | aduro/manager.py | KindleProgressMgr.detect_events | def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
R... | python | def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
R... | [
"def",
"detect_events",
"(",
"self",
",",
"max_attempts",
"=",
"3",
")",
":",
"# Attempt to retrieve current state from KindleAPI",
"for",
"_",
"in",
"xrange",
"(",
"max_attempts",
")",
":",
"try",
":",
"with",
"KindleCloudReaderAPI",
".",
"get_instance",
"(",
"se... | Returns a list of `Event`s detected from differences in state
between the current snapshot and the Kindle Library.
`books` and `progress` attributes will be set with the latest API
results upon successful completion of the function.
Returns:
If failed to retrieve progress, ... | [
"Returns",
"a",
"list",
"of",
"Event",
"s",
"detected",
"from",
"differences",
"in",
"state",
"between",
"the",
"current",
"snapshot",
"and",
"the",
"Kindle",
"Library",
"."
] | train | https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/manager.py#L36-L70 |
msuozzo/Aduro | aduro/manager.py | KindleProgressMgr.commit_events | def commit_events(self):
"""Applies all outstanding `Event`s to the internal state
"""
# Events are sorted such that, when applied in order, each event
# represents a logical change in state. That is, an event never requires
# future events' data in order to be parsed.
# ... | python | def commit_events(self):
"""Applies all outstanding `Event`s to the internal state
"""
# Events are sorted such that, when applied in order, each event
# represents a logical change in state. That is, an event never requires
# future events' data in order to be parsed.
# ... | [
"def",
"commit_events",
"(",
"self",
")",
":",
"# Events are sorted such that, when applied in order, each event",
"# represents a logical change in state. That is, an event never requires",
"# future events' data in order to be parsed.",
"# e.g. All ADDs must go before START READINGs",
"# ... | Applies all outstanding `Event`s to the internal state | [
"Applies",
"all",
"outstanding",
"Event",
"s",
"to",
"the",
"internal",
"state"
] | train | https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/manager.py#L80-L91 |
florianpaquet/mease | mease/registry.py | Mease._get_registry_names | def _get_registry_names(self, registry):
"""
Returns functions names for a registry
"""
return ', '.join(
f.__name__ if not isinstance(f, tuple) else f[0].__name__
for f in getattr(self, registry, [])) | python | def _get_registry_names(self, registry):
"""
Returns functions names for a registry
"""
return ', '.join(
f.__name__ if not isinstance(f, tuple) else f[0].__name__
for f in getattr(self, registry, [])) | [
"def",
"_get_registry_names",
"(",
"self",
",",
"registry",
")",
":",
"return",
"', '",
".",
"join",
"(",
"f",
".",
"__name__",
"if",
"not",
"isinstance",
"(",
"f",
",",
"tuple",
")",
"else",
"f",
"[",
"0",
"]",
".",
"__name__",
"for",
"f",
"in",
"... | Returns functions names for a registry | [
"Returns",
"functions",
"names",
"for",
"a",
"registry"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L33-L39 |
florianpaquet/mease | mease/registry.py | Mease.receiver | def receiver(self, func=None, json=False):
"""
Registers a receiver function
"""
self.receivers.append((func, json)) | python | def receiver(self, func=None, json=False):
"""
Registers a receiver function
"""
self.receivers.append((func, json)) | [
"def",
"receiver",
"(",
"self",
",",
"func",
"=",
"None",
",",
"json",
"=",
"False",
")",
":",
"self",
".",
"receivers",
".",
"append",
"(",
"(",
"func",
",",
"json",
")",
")"
] | Registers a receiver function | [
"Registers",
"a",
"receiver",
"function"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L58-L62 |
florianpaquet/mease | mease/registry.py | Mease.sender | def sender(self, func, routing=None, routing_re=None):
"""
Registers a sender function
"""
if routing and not isinstance(routing, list):
routing = [routing]
if routing_re:
if not isinstance(routing_re, list):
routing_re = [routing_re]
... | python | def sender(self, func, routing=None, routing_re=None):
"""
Registers a sender function
"""
if routing and not isinstance(routing, list):
routing = [routing]
if routing_re:
if not isinstance(routing_re, list):
routing_re = [routing_re]
... | [
"def",
"sender",
"(",
"self",
",",
"func",
",",
"routing",
"=",
"None",
",",
"routing_re",
"=",
"None",
")",
":",
"if",
"routing",
"and",
"not",
"isinstance",
"(",
"routing",
",",
"list",
")",
":",
"routing",
"=",
"[",
"routing",
"]",
"if",
"routing_... | Registers a sender function | [
"Registers",
"a",
"sender",
"function"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L65-L77 |
florianpaquet/mease | mease/registry.py | Mease.call_openers | def call_openers(self, client, clients_list):
"""
Calls openers callbacks
"""
for func in self.openers:
func(client, clients_list) | python | def call_openers(self, client, clients_list):
"""
Calls openers callbacks
"""
for func in self.openers:
func(client, clients_list) | [
"def",
"call_openers",
"(",
"self",
",",
"client",
",",
"clients_list",
")",
":",
"for",
"func",
"in",
"self",
".",
"openers",
":",
"func",
"(",
"client",
",",
"clients_list",
")"
] | Calls openers callbacks | [
"Calls",
"openers",
"callbacks"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L81-L86 |
florianpaquet/mease | mease/registry.py | Mease.call_closers | def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list) | python | def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list) | [
"def",
"call_closers",
"(",
"self",
",",
"client",
",",
"clients_list",
")",
":",
"for",
"func",
"in",
"self",
".",
"closers",
":",
"func",
"(",
"client",
",",
"clients_list",
")"
] | Calls closers callbacks | [
"Calls",
"closers",
"callbacks"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L88-L93 |
florianpaquet/mease | mease/registry.py | Mease.call_receivers | def call_receivers(self, client, clients_list, message):
"""
Calls receivers callbacks
"""
# Try to parse JSON
try:
json_message = json.loads(message)
except ValueError:
json_message = None
for func, to_json in self.receivers:
... | python | def call_receivers(self, client, clients_list, message):
"""
Calls receivers callbacks
"""
# Try to parse JSON
try:
json_message = json.loads(message)
except ValueError:
json_message = None
for func, to_json in self.receivers:
... | [
"def",
"call_receivers",
"(",
"self",
",",
"client",
",",
"clients_list",
",",
"message",
")",
":",
"# Try to parse JSON",
"try",
":",
"json_message",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"ValueError",
":",
"json_message",
"=",
"None",
"... | Calls receivers callbacks | [
"Calls",
"receivers",
"callbacks"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L95-L116 |
florianpaquet/mease | mease/registry.py | Mease.call_senders | def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for func, routings, routings_re in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings... | python | def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for func, routings, routings_re in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings... | [
"def",
"call_senders",
"(",
"self",
",",
"routing",
",",
"clients_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"func",
",",
"routings",
",",
"routings_re",
"in",
"self",
".",
"senders",
":",
"call_callback",
"=",
"False",
"# Message... | Calls senders callbacks | [
"Calls",
"senders",
"callbacks"
] | train | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/registry.py#L118-L141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.