repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
hufman/flask_rdf | flask_rdf/common_decorators.py | ViewDecorator.output | def output(self, response, accepts):
""" Formats a response from a view to handle any RDF graphs
If a view function returns an RDF graph, serialize it based on Accept header
If it's not an RDF graph, return it without any special handling
"""
graph = self.get_graph(response)
if graph is not None:
... | python | def output(self, response, accepts):
""" Formats a response from a view to handle any RDF graphs
If a view function returns an RDF graph, serialize it based on Accept header
If it's not an RDF graph, return it without any special handling
"""
graph = self.get_graph(response)
if graph is not None:
... | [
"def",
"output",
"(",
"self",
",",
"response",
",",
"accepts",
")",
":",
"graph",
"=",
"self",
".",
"get_graph",
"(",
"response",
")",
"if",
"graph",
"is",
"not",
"None",
":",
"# decide the format",
"mimetype",
",",
"format",
"=",
"self",
".",
"format_se... | Formats a response from a view to handle any RDF graphs
If a view function returns an RDF graph, serialize it based on Accept header
If it's not an RDF graph, return it without any special handling | [
"Formats",
"a",
"response",
"from",
"a",
"view",
"to",
"handle",
"any",
"RDF",
"graphs",
"If",
"a",
"view",
"function",
"returns",
"an",
"RDF",
"graph",
"serialize",
"it",
"based",
"on",
"Accept",
"header",
"If",
"it",
"s",
"not",
"an",
"RDF",
"graph",
... | train | https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/common_decorators.py#L45-L68 |
hufman/flask_rdf | flask_rdf/common_decorators.py | ViewDecorator.decorate | def decorate(self, view):
""" Wraps a view function to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified
"""
from functools import wraps
@wraps(view)
def decorated(*args, **kwargs):
response = view... | python | def decorate(self, view):
""" Wraps a view function to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified
"""
from functools import wraps
@wraps(view)
def decorated(*args, **kwargs):
response = view... | [
"def",
"decorate",
"(",
"self",
",",
"view",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"view",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"view",
"(",
"*",
"args",
",",
... | Wraps a view function to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified | [
"Wraps",
"a",
"view",
"function",
"to",
"return",
"formatted",
"RDF",
"graphs",
"Uses",
"content",
"negotiation",
"to",
"serialize",
"the",
"graph",
"to",
"the",
"client",
"-",
"preferred",
"format",
"Passes",
"other",
"content",
"through",
"unmodified"
] | train | https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/common_decorators.py#L70-L82 |
Duke-QCD/hic | hic/initial.py | IC.ecc | def ecc(self, n):
r"""
Calculate eccentricity harmonic `\varepsilon_n`.
:param int n: Eccentricity order.
"""
ny, nx = self._profile.shape
xmax, ymax = self._xymax
xcm, ycm = self._cm
# create (X, Y) grids relative to CM
Y, X = np.mgrid[ymax:-ym... | python | def ecc(self, n):
r"""
Calculate eccentricity harmonic `\varepsilon_n`.
:param int n: Eccentricity order.
"""
ny, nx = self._profile.shape
xmax, ymax = self._xymax
xcm, ycm = self._cm
# create (X, Y) grids relative to CM
Y, X = np.mgrid[ymax:-ym... | [
"def",
"ecc",
"(",
"self",
",",
"n",
")",
":",
"ny",
",",
"nx",
"=",
"self",
".",
"_profile",
".",
"shape",
"xmax",
",",
"ymax",
"=",
"self",
".",
"_xymax",
"xcm",
",",
"ycm",
"=",
"self",
".",
"_cm",
"# create (X, Y) grids relative to CM",
"Y",
",",... | r"""
Calculate eccentricity harmonic `\varepsilon_n`.
:param int n: Eccentricity order. | [
"r",
"Calculate",
"eccentricity",
"harmonic",
"\\",
"varepsilon_n",
"."
] | train | https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/initial.py#L63-L102 |
alefnula/tea | tea/dsa/config.py | Config.get | def get(self, var, default=None):
"""Return a value from configuration.
Safe version which always returns a default value if the value is not
found.
"""
try:
return self.__get(var)
except (KeyError, IndexError):
return default | python | def get(self, var, default=None):
"""Return a value from configuration.
Safe version which always returns a default value if the value is not
found.
"""
try:
return self.__get(var)
except (KeyError, IndexError):
return default | [
"def",
"get",
"(",
"self",
",",
"var",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"__get",
"(",
"var",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
"default"
] | Return a value from configuration.
Safe version which always returns a default value if the value is not
found. | [
"Return",
"a",
"value",
"from",
"configuration",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L211-L220 |
alefnula/tea | tea/dsa/config.py | Config.insert | def insert(self, var, value, index=None):
"""Insert at the index.
If the index is not provided appends to the end of the list.
"""
current = self.__get(var)
if not isinstance(current, list):
raise KeyError("%s: is not a list" % var)
if index is None:
... | python | def insert(self, var, value, index=None):
"""Insert at the index.
If the index is not provided appends to the end of the list.
"""
current = self.__get(var)
if not isinstance(current, list):
raise KeyError("%s: is not a list" % var)
if index is None:
... | [
"def",
"insert",
"(",
"self",
",",
"var",
",",
"value",
",",
"index",
"=",
"None",
")",
":",
"current",
"=",
"self",
".",
"__get",
"(",
"var",
")",
"if",
"not",
"isinstance",
"(",
"current",
",",
"list",
")",
":",
"raise",
"KeyError",
"(",
"\"%s: i... | Insert at the index.
If the index is not provided appends to the end of the list. | [
"Insert",
"at",
"the",
"index",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L238-L251 |
alefnula/tea | tea/dsa/config.py | MultiConfig.keys | def keys(self):
"""Return a merged set of top level keys from all configurations."""
s = set()
for config in self.__configs:
s |= config.keys()
return s | python | def keys(self):
"""Return a merged set of top level keys from all configurations."""
s = set()
for config in self.__configs:
s |= config.keys()
return s | [
"def",
"keys",
"(",
"self",
")",
":",
"s",
"=",
"set",
"(",
")",
"for",
"config",
"in",
"self",
".",
"__configs",
":",
"s",
"|=",
"config",
".",
"keys",
"(",
")",
"return",
"s"
] | Return a merged set of top level keys from all configurations. | [
"Return",
"a",
"merged",
"set",
"of",
"top",
"level",
"keys",
"from",
"all",
"configurations",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L328-L333 |
alefnula/tea | tea/logger/win_handlers.py | FileHandler.close | def close(self):
"""Close the stream."""
self.flush()
self.stream.close()
logging.StreamHandler.close(self) | python | def close(self):
"""Close the stream."""
self.flush()
self.stream.close()
logging.StreamHandler.close(self) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"stream",
".",
"close",
"(",
")",
"logging",
".",
"StreamHandler",
".",
"close",
"(",
"self",
")"
] | Close the stream. | [
"Close",
"the",
"stream",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L22-L26 |
alefnula/tea | tea/logger/win_handlers.py | BaseRotatingHandler.emit | def emit(self, record):
"""Emit a record.
Output the record to the file, catering for rollover as described
in doRollover().
"""
try:
if self.shouldRollover(record):
self.doRollover()
FileHandler.emit(self, record)
except (Keyboard... | python | def emit(self, record):
"""Emit a record.
Output the record to the file, catering for rollover as described
in doRollover().
"""
try:
if self.shouldRollover(record):
self.doRollover()
FileHandler.emit(self, record)
except (Keyboard... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"if",
"self",
".",
"shouldRollover",
"(",
"record",
")",
":",
"self",
".",
"doRollover",
"(",
")",
"FileHandler",
".",
"emit",
"(",
"self",
",",
"record",
")",
"except",
"(",
"KeyboardI... | Emit a record.
Output the record to the file, catering for rollover as described
in doRollover(). | [
"Emit",
"a",
"record",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L42-L55 |
alefnula/tea | tea/logger/win_handlers.py | RotatingFileHandler.doRollover | def doRollover(self):
"""Do a rollover, as described in __init__()."""
self.stream.close()
try:
if self.backupCount > 0:
tmp_location = "%s.0" % self.baseFilename
os.rename(self.baseFilename, tmp_location)
for i in range(self.backupCoun... | python | def doRollover(self):
"""Do a rollover, as described in __init__()."""
self.stream.close()
try:
if self.backupCount > 0:
tmp_location = "%s.0" % self.baseFilename
os.rename(self.baseFilename, tmp_location)
for i in range(self.backupCoun... | [
"def",
"doRollover",
"(",
"self",
")",
":",
"self",
".",
"stream",
".",
"close",
"(",
")",
"try",
":",
"if",
"self",
".",
"backupCount",
">",
"0",
":",
"tmp_location",
"=",
"\"%s.0\"",
"%",
"self",
".",
"baseFilename",
"os",
".",
"rename",
"(",
"self... | Do a rollover, as described in __init__(). | [
"Do",
"a",
"rollover",
"as",
"described",
"in",
"__init__",
"()",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L93-L114 |
alefnula/tea | tea/logger/win_handlers.py | RotatingFileHandler.shouldRollover | def shouldRollover(self, record):
"""Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
"""
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self... | python | def shouldRollover(self, record):
"""Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
"""
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self... | [
"def",
"shouldRollover",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"maxBytes",
">",
"0",
":",
"# are we rolling over?",
"msg",
"=",
"\"%s\\n\"",
"%",
"self",
".",
"format",
"(",
"record",
")",
"self",
".",
"stream",
".",
"seek",
"(",
"0"... | Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have. | [
"Determine",
"if",
"rollover",
"should",
"occur",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L116-L127 |
alefnula/tea | tea/shell/__init__.py | split | def split(s, posix=True):
"""Split the string s using shell-like syntax.
Args:
s (str): String to split
posix (bool): Use posix split
Returns:
list of str: List of string parts
"""
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, po... | python | def split(s, posix=True):
"""Split the string s using shell-like syntax.
Args:
s (str): String to split
posix (bool): Use posix split
Returns:
list of str: List of string parts
"""
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, po... | [
"def",
"split",
"(",
"s",
",",
"posix",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"shlex",
".",
"split",
"(",
"s",
",",
"posix",
... | Split the string s using shell-like syntax.
Args:
s (str): String to split
posix (bool): Use posix split
Returns:
list of str: List of string parts | [
"Split",
"the",
"string",
"s",
"using",
"shell",
"-",
"like",
"syntax",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L25-L37 |
alefnula/tea | tea/shell/__init__.py | search | def search(path, matcher="*", dirs=False, files=True):
"""Recursive search function.
Args:
path (str): Path to search recursively
matcher (str or callable): String pattern to search for or function
that returns True/False for a file argument
dirs (bool): if True returns dire... | python | def search(path, matcher="*", dirs=False, files=True):
"""Recursive search function.
Args:
path (str): Path to search recursively
matcher (str or callable): String pattern to search for or function
that returns True/False for a file argument
dirs (bool): if True returns dire... | [
"def",
"search",
"(",
"path",
",",
"matcher",
"=",
"\"*\"",
",",
"dirs",
"=",
"False",
",",
"files",
"=",
"True",
")",
":",
"if",
"callable",
"(",
"matcher",
")",
":",
"def",
"fnmatcher",
"(",
"items",
")",
":",
"return",
"list",
"(",
"filter",
"("... | Recursive search function.
Args:
path (str): Path to search recursively
matcher (str or callable): String pattern to search for or function
that returns True/False for a file argument
dirs (bool): if True returns directories that match the pattern
files(bool): if True re... | [
"Recursive",
"search",
"function",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L40-L70 |
alefnula/tea | tea/shell/__init__.py | chdir | def chdir(directory):
"""Change the current working directory.
Args:
directory (str): Directory to go to.
"""
directory = os.path.abspath(directory)
logger.info("chdir -> %s" % directory)
try:
if not os.path.isdir(directory):
logger.error(
"chdir -> %... | python | def chdir(directory):
"""Change the current working directory.
Args:
directory (str): Directory to go to.
"""
directory = os.path.abspath(directory)
logger.info("chdir -> %s" % directory)
try:
if not os.path.isdir(directory):
logger.error(
"chdir -> %... | [
"def",
"chdir",
"(",
"directory",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"logger",
".",
"info",
"(",
"\"chdir -> %s\"",
"%",
"directory",
")",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(... | Change the current working directory.
Args:
directory (str): Directory to go to. | [
"Change",
"the",
"current",
"working",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L73-L91 |
alefnula/tea | tea/shell/__init__.py | goto | def goto(directory, create=False):
"""Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... | python | def goto(directory, create=False):
"""Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... | [
"def",
"goto",
"(",
"directory",
",",
"create",
"=",
"False",
")",
":",
"current",
"=",
"os",
".",
"getcwd",
"(",
")",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"director... | Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... else:
... print ... | [
"Context",
"object",
"for",
"changing",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L95-L127 |
alefnula/tea | tea/shell/__init__.py | mkdir | def mkdir(path, mode=0o755, delete=False):
"""Make a directory.
Create a leaf directory and all intermediate ones.
Works like ``mkdir``, except that any intermediate path segment (not just
the rightmost) will be created if it does not exist. This is recursive.
Args:
path (str): Directory t... | python | def mkdir(path, mode=0o755, delete=False):
"""Make a directory.
Create a leaf directory and all intermediate ones.
Works like ``mkdir``, except that any intermediate path segment (not just
the rightmost) will be created if it does not exist. This is recursive.
Args:
path (str): Directory t... | [
"def",
"mkdir",
"(",
"path",
",",
"mode",
"=",
"0o755",
",",
"delete",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"mkdir: %s\"",
"%",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"not",
"delete",
":"... | Make a directory.
Create a leaf directory and all intermediate ones.
Works like ``mkdir``, except that any intermediate path segment (not just
the rightmost) will be created if it does not exist. This is recursive.
Args:
path (str): Directory to create
mode (int): Directory mode
... | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L130-L156 |
alefnula/tea | tea/shell/__init__.py | __copyfile | def __copyfile(source, destination):
"""Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation... | python | def __copyfile(source, destination):
"""Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation... | [
"def",
"__copyfile",
"(",
"source",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"copyfile: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
"shutil",
".",
"copy",
"(",
"... | Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise. | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"source",
"destination",
")",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L166-L187 |
alefnula/tea | tea/shell/__init__.py | __copyfile2 | def __copyfile2(source, destination):
"""Copy data and all stat info ("cp -p source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the o... | python | def __copyfile2(source, destination):
"""Copy data and all stat info ("cp -p source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the o... | [
"def",
"__copyfile2",
"(",
"source",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"copyfile2: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
"shutil",
".",
"copy2",
"(",
... | Copy data and all stat info ("cp -p source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise. | [
"Copy",
"data",
"and",
"all",
"stat",
"info",
"(",
"cp",
"-",
"p",
"source",
"destination",
")",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L190-L211 |
alefnula/tea | tea/shell/__init__.py | __copytree | def __copytree(source, destination, symlinks=False):
"""Copy a directory tree recursively using copy2().
The destination directory must not already exist.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the ... | python | def __copytree(source, destination, symlinks=False):
"""Copy a directory tree recursively using copy2().
The destination directory must not already exist.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the ... | [
"def",
"__copytree",
"(",
"source",
",",
"destination",
",",
"symlinks",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"\"copytree: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
... | Copy a directory tree recursively using copy2().
The destination directory must not already exist.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are c... | [
"Copy",
"a",
"directory",
"tree",
"recursively",
"using",
"copy2",
"()",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L214-L241 |
alefnula/tea | tea/shell/__init__.py | copy | def copy(source, destination):
"""Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(source):
... | python | def copy(source, destination):
"""Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(source):
... | [
"def",
"copy",
"(",
"source",
",",
"destination",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"return",
"__copytree",
"(",
"source",
",",
"destination",
")",
"else",
":",
"return",
"__copyfile2",
"(",
"source",
",",
"desti... | Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise. | [
"Copy",
"file",
"or",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L244-L257 |
alefnula/tea | tea/shell/__init__.py | gcopy | def gcopy(pattern, destination):
"""Copy all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | python | def gcopy(pattern, destination):
"""Copy all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | [
"def",
"gcopy",
"(",
"pattern",
",",
"destination",
")",
":",
"for",
"item",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"if",
"not",
"copy",
"(",
"item",
",",
"destination",
")",
":",
"return",
"False",
"return",
"True"
] | Copy all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise. | [
"Copy",
"all",
"file",
"found",
"by",
"glob",
".",
"glob",
"(",
"pattern",
")",
"to",
"destination",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L260-L273 |
alefnula/tea | tea/shell/__init__.py | move | def move(source, destination):
"""Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or di... | python | def move(source, destination):
"""Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or di... | [
"def",
"move",
"(",
"source",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"Move: %s -> %s\"",
"%",
"(",
"source",
",",
"destination",
")",
")",
"try",
":",
"__create_destdir",
"(",
"destination",
")",
"shutil",
".",
"move",
"(",
"source",
... | Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or directory to move).
destination ... | [
"Move",
"a",
"file",
"or",
"directory",
"(",
"recursively",
")",
"to",
"another",
"location",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L276-L297 |
alefnula/tea | tea/shell/__init__.py | gmove | def gmove(pattern, destination):
"""Move all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | python | def gmove(pattern, destination):
"""Move all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | [
"def",
"gmove",
"(",
"pattern",
",",
"destination",
")",
":",
"for",
"item",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"if",
"not",
"move",
"(",
"item",
",",
"destination",
")",
":",
"return",
"False",
"return",
"True"
] | Move all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise. | [
"Move",
"all",
"file",
"found",
"by",
"glob",
".",
"glob",
"(",
"pattern",
")",
"to",
"destination",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L300-L313 |
alefnula/tea | tea/shell/__init__.py | __rmfile | def __rmfile(path):
"""Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmfile: %s" % path)
try:
os.remove(path)
return True
except Exception as ... | python | def __rmfile(path):
"""Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmfile: %s" % path)
try:
os.remove(path)
return True
except Exception as ... | [
"def",
"__rmfile",
"(",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"rmfile: %s\"",
"%",
"path",
")",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"rmfi... | Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | [
"Delete",
"a",
"file",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L316-L331 |
alefnula/tea | tea/shell/__init__.py | __rmtree | def __rmtree(path):
"""Recursively delete a directory tree.
Args:
path (str): Path to the directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmtree: %s" % path)
try:
shutil.rmtree(path)
retur... | python | def __rmtree(path):
"""Recursively delete a directory tree.
Args:
path (str): Path to the directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmtree: %s" % path)
try:
shutil.rmtree(path)
retur... | [
"def",
"__rmtree",
"(",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"rmtree: %s\"",
"%",
"path",
")",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"... | Recursively delete a directory tree.
Args:
path (str): Path to the directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | [
"Recursively",
"delete",
"a",
"directory",
"tree",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L334-L349 |
alefnula/tea | tea/shell/__init__.py | remove | def remove(path):
"""Delete a file or directory.
Args:
path (str): Path to the file or directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(path):
return __rmtree(path)
else:
return __rmfil... | python | def remove(path):
"""Delete a file or directory.
Args:
path (str): Path to the file or directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(path):
return __rmtree(path)
else:
return __rmfil... | [
"def",
"remove",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"__rmtree",
"(",
"path",
")",
"else",
":",
"return",
"__rmfile",
"(",
"path",
")"
] | Delete a file or directory.
Args:
path (str): Path to the file or directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | [
"Delete",
"a",
"file",
"or",
"directory",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L352-L364 |
alefnula/tea | tea/shell/__init__.py | gremove | def gremove(pattern):
"""Remove all file found by glob.glob(pattern).
Args:
pattern (str): Pattern of files to remove
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item in glob.glob(pattern):
if not remove(item):
return False
re... | python | def gremove(pattern):
"""Remove all file found by glob.glob(pattern).
Args:
pattern (str): Pattern of files to remove
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item in glob.glob(pattern):
if not remove(item):
return False
re... | [
"def",
"gremove",
"(",
"pattern",
")",
":",
"for",
"item",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"if",
"not",
"remove",
"(",
"item",
")",
":",
"return",
"False",
"return",
"True"
] | Remove all file found by glob.glob(pattern).
Args:
pattern (str): Pattern of files to remove
Returns:
bool: True if the operation is successful, False otherwise. | [
"Remove",
"all",
"file",
"found",
"by",
"glob",
".",
"glob",
"(",
"pattern",
")",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L367-L378 |
alefnula/tea | tea/shell/__init__.py | read | def read(path, encoding="utf-8"):
"""Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error
"""
try:
with io.open(path, encoding=encoding) as f:
... | python | def read(path, encoding="utf-8"):
"""Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error
"""
try:
with io.open(path, encoding=encoding) as f:
... | [
"def",
"read",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
"except",
"Exception",
"as",
... | Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error | [
"Read",
"the",
"content",
"of",
"the",
"file",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L381-L396 |
alefnula/tea | tea/shell/__init__.py | touch | def touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... | python | def touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... | [
"def",
"touch",
"(",
"path",
",",
"content",
"=",
"\"\"",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"overwrite",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"not",
"overwrite",
"and",
"os",
".",
"pa... | Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.
Default: ``utf-8``
overwrite (bool): Overwrite the... | [
"Create",
"a",
"file",
"at",
"the",
"given",
"path",
"if",
"it",
"does",
"not",
"already",
"exists",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L399-L425 |
alefnula/tea | tea/utils/__init__.py | get_object | def get_object(path="", obj=None):
"""Return an object from a dot path.
Path can either be a full path, in which case the `get_object` function
will try to import the modules in the path and follow it to the final
object. Or it can be a path relative to the object passed in as the second
argument.
... | python | def get_object(path="", obj=None):
"""Return an object from a dot path.
Path can either be a full path, in which case the `get_object` function
will try to import the modules in the path and follow it to the final
object. Or it can be a path relative to the object passed in as the second
argument.
... | [
"def",
"get_object",
"(",
"path",
"=",
"\"\"",
",",
"obj",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"obj",
"path",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"importlib",
".",
"impo... | Return an object from a dot path.
Path can either be a full path, in which case the `get_object` function
will try to import the modules in the path and follow it to the final
object. Or it can be a path relative to the object passed in as the second
argument.
Args:
path (str): Full or rel... | [
"Return",
"an",
"object",
"from",
"a",
"dot",
"path",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/__init__.py#L30-L102 |
alefnula/tea | tea/utils/__init__.py | load_subclasses | def load_subclasses(klass, modules=None):
"""Load recursively all all subclasses from a module.
Args:
klass (str or list of str): Class whose subclasses we want to load.
modules: List of additional modules or module names that should be
recursively imported in order to find all the ... | python | def load_subclasses(klass, modules=None):
"""Load recursively all all subclasses from a module.
Args:
klass (str or list of str): Class whose subclasses we want to load.
modules: List of additional modules or module names that should be
recursively imported in order to find all the ... | [
"def",
"load_subclasses",
"(",
"klass",
",",
"modules",
"=",
"None",
")",
":",
"if",
"modules",
":",
"if",
"isinstance",
"(",
"modules",
",",
"six",
".",
"string_types",
")",
":",
"modules",
"=",
"[",
"modules",
"]",
"loader",
"=",
"Loader",
"(",
")",
... | Load recursively all all subclasses from a module.
Args:
klass (str or list of str): Class whose subclasses we want to load.
modules: List of additional modules or module names that should be
recursively imported in order to find all the subclasses of the
desired class. Defa... | [
"Load",
"recursively",
"all",
"all",
"subclasses",
"from",
"a",
"module",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/__init__.py#L156-L174 |
alefnula/tea | tea/utils/__init__.py | get_exception | def get_exception():
"""Return full formatted traceback as a string."""
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
... | python | def get_exception():
"""Return full formatted traceback as a string."""
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
... | [
"def",
"get_exception",
"(",
")",
":",
"trace",
"=",
"\"\"",
"exception",
"=",
"\"\"",
"exc_list",
"=",
"traceback",
".",
"format_exception_only",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
... | Return full formatted traceback as a string. | [
"Return",
"full",
"formatted",
"traceback",
"as",
"a",
"string",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/__init__.py#L177-L189 |
alefnula/tea | tea/utils/__init__.py | Loader.load | def load(self, *modules):
"""Load one or more modules.
Args:
modules: Either a string full path to a module or an actual module
object.
"""
for module in modules:
if isinstance(module, six.string_types):
try:
mo... | python | def load(self, *modules):
"""Load one or more modules.
Args:
modules: Either a string full path to a module or an actual module
object.
"""
for module in modules:
if isinstance(module, six.string_types):
try:
mo... | [
"def",
"load",
"(",
"self",
",",
"*",
"modules",
")",
":",
"for",
"module",
"in",
"modules",
":",
"if",
"isinstance",
"(",
"module",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"module",
"=",
"get_object",
"(",
"module",
")",
"except",
"Ex... | Load one or more modules.
Args:
modules: Either a string full path to a module or an actual module
object. | [
"Load",
"one",
"or",
"more",
"modules",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/__init__.py#L129-L153 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | _product_filter | def _product_filter(products) -> str:
"""Calculate the product filter."""
_filter = 0
for product in {PRODUCTS[p] for p in products}:
_filter += product
return format(_filter, "b")[::-1] | python | def _product_filter(products) -> str:
"""Calculate the product filter."""
_filter = 0
for product in {PRODUCTS[p] for p in products}:
_filter += product
return format(_filter, "b")[::-1] | [
"def",
"_product_filter",
"(",
"products",
")",
"->",
"str",
":",
"_filter",
"=",
"0",
"for",
"product",
"in",
"{",
"PRODUCTS",
"[",
"p",
"]",
"for",
"p",
"in",
"products",
"}",
":",
"_filter",
"+=",
"product",
"return",
"format",
"(",
"_filter",
",",
... | Calculate the product filter. | [
"Calculate",
"the",
"product",
"filter",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L172-L177 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | _base_url | def _base_url() -> str:
"""Build base url."""
_lang: str = "d"
_type: str = "n"
_with_suggestions: str = "?"
return BASE_URI + STBOARD_PATH + _lang + _type + _with_suggestions | python | def _base_url() -> str:
"""Build base url."""
_lang: str = "d"
_type: str = "n"
_with_suggestions: str = "?"
return BASE_URI + STBOARD_PATH + _lang + _type + _with_suggestions | [
"def",
"_base_url",
"(",
")",
"->",
"str",
":",
"_lang",
":",
"str",
"=",
"\"d\"",
"_type",
":",
"str",
"=",
"\"n\"",
"_with_suggestions",
":",
"str",
"=",
"\"?\"",
"return",
"BASE_URI",
"+",
"STBOARD_PATH",
"+",
"_lang",
"+",
"_type",
"+",
"_with_sugges... | Build base url. | [
"Build",
"base",
"url",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L180-L185 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | RMVtransport.get_departures | async def get_departures(
self,
station_id: str,
direction_id: Optional[str] = None,
max_journeys: int = 20,
products: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Fetch data from rmv.de."""
self.station_id: str = station_id
self.direction_id: s... | python | async def get_departures(
self,
station_id: str,
direction_id: Optional[str] = None,
max_journeys: int = 20,
products: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Fetch data from rmv.de."""
self.station_id: str = station_id
self.direction_id: s... | [
"async",
"def",
"get_departures",
"(",
"self",
",",
"station_id",
":",
"str",
",",
"direction_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"max_journeys",
":",
"int",
"=",
"20",
",",
"products",
":",
"Optional",
"[",
"List",
"[",
"str",
"]"... | Fetch data from rmv.de. | [
"Fetch",
"data",
"from",
"rmv",
".",
"de",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L44-L111 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | RMVtransport.data | def data(self) -> Dict[str, Any]:
"""Return travel data."""
data: Dict[str, Any] = {}
data["station"] = self.station
data["stationId"] = self.station_id
data["filter"] = self.products_filter
journeys = []
for j in sorted(self.journeys, key=lambda k: k.real_depart... | python | def data(self) -> Dict[str, Any]:
"""Return travel data."""
data: Dict[str, Any] = {}
data["station"] = self.station
data["stationId"] = self.station_id
data["filter"] = self.products_filter
journeys = []
for j in sorted(self.journeys, key=lambda k: k.real_depart... | [
"def",
"data",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"data",
"[",
"\"station\"",
"]",
"=",
"self",
".",
"station",
"data",
"[",
"\"stationId\"",
"]",
"... | Return travel data. | [
"Return",
"travel",
"data",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L113-L140 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | RMVtransport._station | def _station(self) -> str:
"""Extract station name."""
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval) | python | def _station(self) -> str:
"""Extract station name."""
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval) | [
"def",
"_station",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"obj",
".",
"SBRes",
".",
"SBReq",
".",
"Start",
".",
"Station",
".",
"HafasName",
".",
"Text",
".",
"pyval",
")"
] | Extract station name. | [
"Extract",
"station",
"name",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L142-L144 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | RMVtransport.current_time | def current_time(self) -> datetime:
"""Extract current time."""
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d")
_time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M")
return datetime.combine(_date.date(), _time.time()) | python | def current_time(self) -> datetime:
"""Extract current time."""
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d")
_time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M")
return datetime.combine(_date.date(), _time.time()) | [
"def",
"current_time",
"(",
"self",
")",
"->",
"datetime",
":",
"_date",
"=",
"datetime",
".",
"strptime",
"(",
"self",
".",
"obj",
".",
"SBRes",
".",
"SBReq",
".",
"StartT",
".",
"get",
"(",
"\"date\"",
")",
",",
"\"%Y%m%d\"",
")",
"_time",
"=",
"da... | Extract current time. | [
"Extract",
"current",
"time",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L146-L150 |
cgtobi/PyRMVtransport | RMVtransport/rmvtransport.py | RMVtransport.output | def output(self) -> None:
"""Pretty print travel times."""
print("%s - %s" % (self.station, self.now))
print(self.products_filter)
for j in sorted(self.journeys, key=lambda k: k.real_departure)[
: self.max_journeys
]:
print("-------------")
pr... | python | def output(self) -> None:
"""Pretty print travel times."""
print("%s - %s" % (self.station, self.now))
print(self.products_filter)
for j in sorted(self.journeys, key=lambda k: k.real_departure)[
: self.max_journeys
]:
print("-------------")
pr... | [
"def",
"output",
"(",
"self",
")",
"->",
"None",
":",
"print",
"(",
"\"%s - %s\"",
"%",
"(",
"self",
".",
"station",
",",
"self",
".",
"now",
")",
")",
"print",
"(",
"self",
".",
"products_filter",
")",
"for",
"j",
"in",
"sorted",
"(",
"self",
".",... | Pretty print travel times. | [
"Pretty",
"print",
"travel",
"times",
"."
] | train | https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L152-L169 |
night-crawler/django-docker-helpers | django_docker_helpers/config/backends/mpt_redis_parser.py | MPTRedisParser.get | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-separated path to a nested value
:para... | python | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-separated path to a nested value
:para... | [
"def",
"get",
"(",
"self",
",",
"variable_path",
":",
"str",
",",
"default",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Any",
"]",
"=",
"None",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer"... | :param variable_path: a delimiter-separated path to a nested value
:param default: default value if there's no object by specified path
:param coerce_type: cast a type of a value to a specified one
:param coercer: perform a type casting with specified callback
:param kwargs: additional a... | [
":",
"param",
"variable_path",
":",
"a",
"delimiter",
"-",
"separated",
"path",
"to",
"a",
"nested",
"value",
":",
"param",
"default",
":",
"default",
"value",
"if",
"there",
"s",
"no",
"object",
"by",
"specified",
"path",
":",
"param",
"coerce_type",
":",... | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/mpt_redis_parser.py#L75-L112 |
letuananh/chirptext | chirptext/chio.py | process_file | def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
''' Process a text file's content. If the file name ends with .gz, read it as gzip file '''
if mode not in ('rU', 'rt', 'rb', 'r'):
raise Exception("Invalid file reading mode")
with open(path, encoding=encoding, mode=mo... | python | def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
''' Process a text file's content. If the file name ends with .gz, read it as gzip file '''
if mode not in ('rU', 'rt', 'rb', 'r'):
raise Exception("Invalid file reading mode")
with open(path, encoding=encoding, mode=mo... | [
"def",
"process_file",
"(",
"path",
",",
"processor",
",",
"encoding",
"=",
"'utf-8'",
",",
"mode",
"=",
"'rt'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"'rU'",
",",
"'rt'",
",",
"'rb'",
",",
"'r'",
")... | Process a text file's content. If the file name ends with .gz, read it as gzip file | [
"Process",
"a",
"text",
"file",
"s",
"content",
".",
"If",
"the",
"file",
"name",
"ends",
"with",
".",
"gz",
"read",
"it",
"as",
"gzip",
"file"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L75-L80 |
letuananh/chirptext | chirptext/chio.py | read_file | def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
'''
if 'mode' in kwargs and kwargs['mode'] == 'r... | python | def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
'''
if 'mode' in kwargs and kwargs['mode'] == 'r... | [
"def",
"read_file",
"(",
"path",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mode'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'mode'",
"]",
"==",
"'rb'",
":",
"return",
"process_file",
"(",
"path",
",",... | Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string. | [
"Read",
"text",
"file",
"content",
".",
"If",
"the",
"file",
"name",
"ends",
"with",
".",
"gz",
"read",
"it",
"as",
"gzip",
"file",
".",
"If",
"mode",
"argument",
"is",
"provided",
"as",
"rb",
"content",
"will",
"be",
"read",
"as",
"byte",
"stream",
... | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L83-L93 |
letuananh/chirptext | chirptext/chio.py | write_file | def write_file(path, content, mode=None, encoding='utf-8'):
''' Write content to a file. If the path ends with .gz, gzip will be used. '''
if not mode:
if isinstance(content, bytes):
mode = 'wb'
else:
mode = 'wt'
if not path:
raise ValueError("Output path is i... | python | def write_file(path, content, mode=None, encoding='utf-8'):
''' Write content to a file. If the path ends with .gz, gzip will be used. '''
if not mode:
if isinstance(content, bytes):
mode = 'wb'
else:
mode = 'wt'
if not path:
raise ValueError("Output path is i... | [
"def",
"write_file",
"(",
"path",
",",
"content",
",",
"mode",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"not",
"mode",
":",
"if",
"isinstance",
"(",
"content",
",",
"bytes",
")",
":",
"mode",
"=",
"'wb'",
"else",
":",
"mode",
"... | Write content to a file. If the path ends with .gz, gzip will be used. | [
"Write",
"content",
"to",
"a",
"file",
".",
"If",
"the",
"path",
"ends",
"with",
".",
"gz",
"gzip",
"will",
"be",
"used",
"."
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L96-L121 |
letuananh/chirptext | chirptext/chio.py | iter_csv_stream | def iter_csv_stream(input_stream, fieldnames=None, sniff=False, *args, **kwargs):
''' Read CSV content as a table (list of lists) from an input stream '''
if 'dialect' not in kwargs and sniff:
kwargs['dialect'] = csv.Sniffer().sniff(input_stream.read(1024))
input_stream.seek(0)
if 'quoting' ... | python | def iter_csv_stream(input_stream, fieldnames=None, sniff=False, *args, **kwargs):
''' Read CSV content as a table (list of lists) from an input stream '''
if 'dialect' not in kwargs and sniff:
kwargs['dialect'] = csv.Sniffer().sniff(input_stream.read(1024))
input_stream.seek(0)
if 'quoting' ... | [
"def",
"iter_csv_stream",
"(",
"input_stream",
",",
"fieldnames",
"=",
"None",
",",
"sniff",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'dialect'",
"not",
"in",
"kwargs",
"and",
"sniff",
":",
"kwargs",
"[",
"'dialect'",
"... | Read CSV content as a table (list of lists) from an input stream | [
"Read",
"CSV",
"content",
"as",
"a",
"table",
"(",
"list",
"of",
"lists",
")",
"from",
"an",
"input",
"stream"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L124-L142 |
letuananh/chirptext | chirptext/chio.py | read_csv_iter | def read_csv_iter(path, fieldnames=None, sniff=True, mode='rt', encoding='utf-8', *args, **kwargs):
''' Iterate through CSV rows in a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict inst... | python | def read_csv_iter(path, fieldnames=None, sniff=True, mode='rt', encoding='utf-8', *args, **kwargs):
''' Iterate through CSV rows in a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict inst... | [
"def",
"read_csv_iter",
"(",
"path",
",",
"fieldnames",
"=",
"None",
",",
"sniff",
"=",
"True",
",",
"mode",
"=",
"'rt'",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"path",
",",
"mode"... | Iterate through CSV rows in a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead.
CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off. | [
"Iterate",
"through",
"CSV",
"rows",
"in",
"a",
"file",
".",
"By",
"default",
"csv",
".",
"reader",
"()",
"will",
"be",
"used",
"any",
"output",
"will",
"be",
"a",
"list",
"of",
"lists",
".",
"If",
"fieldnames",
"is",
"provided",
"DictReader",
"will",
... | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L149-L157 |
letuananh/chirptext | chirptext/chio.py | read_csv | def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs):
''' Read CSV rows as table from a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead.
CSV sni... | python | def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs):
''' Read CSV rows as table from a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead.
CSV sni... | [
"def",
"read_csv",
"(",
"path",
",",
"fieldnames",
"=",
"None",
",",
"sniff",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"list",
"(",
"r",
"for",
"r",
"in",
"read_csv_iter",
"(",
"pa... | Read CSV rows as table from a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead.
CSV sniffing (dialect detection) is enabled by default, set sniff=False to switch it off. | [
"Read",
"CSV",
"rows",
"as",
"table",
"from",
"a",
"file",
".",
"By",
"default",
"csv",
".",
"reader",
"()",
"will",
"be",
"used",
"any",
"output",
"will",
"be",
"a",
"list",
"of",
"lists",
".",
"If",
"fieldnames",
"is",
"provided",
"DictReader",
"will... | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L164-L170 |
letuananh/chirptext | chirptext/chio.py | write_csv | def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
''' Write rows data to a CSV file (with or without fieldnames) '''
if not quoting:
quoting = csv.QUOTE_MINIMAL
if 'lineterminator' not in kwargs:
kw... | python | def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
''' Write rows data to a CSV file (with or without fieldnames) '''
if not quoting:
quoting = csv.QUOTE_MINIMAL
if 'lineterminator' not in kwargs:
kw... | [
"def",
"write_csv",
"(",
"path",
",",
"rows",
",",
"dialect",
"=",
"'excel'",
",",
"fieldnames",
"=",
"None",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_ALL",
",",
"extrasaction",
"=",
"'ignore'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if... | Write rows data to a CSV file (with or without fieldnames) | [
"Write",
"rows",
"data",
"to",
"a",
"CSV",
"file",
"(",
"with",
"or",
"without",
"fieldnames",
")"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L177-L192 |
letuananh/chirptext | chirptext/chio.py | CSV.write | def write(file_name, rows, header=None, *args, **kwargs):
''' Write rows data to a CSV file (with or without header) '''
warnings.warn("chirptext.io.CSV is deprecated and will be removed in near future.", DeprecationWarning)
write_csv(file_name, rows, fieldnames=header, *args, **kwargs) | python | def write(file_name, rows, header=None, *args, **kwargs):
''' Write rows data to a CSV file (with or without header) '''
warnings.warn("chirptext.io.CSV is deprecated and will be removed in near future.", DeprecationWarning)
write_csv(file_name, rows, fieldnames=header, *args, **kwargs) | [
"def",
"write",
"(",
"file_name",
",",
"rows",
",",
"header",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"chirptext.io.CSV is deprecated and will be removed in near future.\"",
",",
"DeprecationWarning",
")",
... | Write rows data to a CSV file (with or without header) | [
"Write",
"rows",
"data",
"to",
"a",
"CSV",
"file",
"(",
"with",
"or",
"without",
"header",
")"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chio.py#L216-L219 |
alefnula/tea | tea/msg/mail.py | make_msgid | def make_msgid(idstring=None, utc=False):
"""Return a string suitable for RFC 2822 compliant Message-ID.
E.g: <20020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
"""
if utc:
timesta... | python | def make_msgid(idstring=None, utc=False):
"""Return a string suitable for RFC 2822 compliant Message-ID.
E.g: <20020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
"""
if utc:
timesta... | [
"def",
"make_msgid",
"(",
"idstring",
"=",
"None",
",",
"utc",
"=",
"False",
")",
":",
"if",
"utc",
":",
"timestamp",
"=",
"time",
".",
"gmtime",
"(",
")",
"else",
":",
"timestamp",
"=",
"time",
".",
"localtime",
"(",
")",
"utcdate",
"=",
"time",
"... | Return a string suitable for RFC 2822 compliant Message-ID.
E.g: <20020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id. | [
"Return",
"a",
"string",
"suitable",
"for",
"RFC",
"2822",
"compliant",
"Message",
"-",
"ID",
".",
"E",
".",
"g",
":",
"<20020201195627",
".",
"33539",
".",
"96671"
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L75-L100 |
alefnula/tea | tea/msg/mail.py | forbid_multi_line_headers | def forbid_multi_line_headers(name, val):
"""Forbid multi-line headers, to prevent header injection."""
val = smart_text(val)
if "\n" in val or "\r" in val:
raise BadHeaderError(
"Header values can't contain newlines "
"(got %r for header %r)" % (val, name)
)
... | python | def forbid_multi_line_headers(name, val):
"""Forbid multi-line headers, to prevent header injection."""
val = smart_text(val)
if "\n" in val or "\r" in val:
raise BadHeaderError(
"Header values can't contain newlines "
"(got %r for header %r)" % (val, name)
)
... | [
"def",
"forbid_multi_line_headers",
"(",
"name",
",",
"val",
")",
":",
"val",
"=",
"smart_text",
"(",
"val",
")",
"if",
"\"\\n\"",
"in",
"val",
"or",
"\"\\r\"",
"in",
"val",
":",
"raise",
"BadHeaderError",
"(",
"\"Header values can't contain newlines \"",
"\"(go... | Forbid multi-line headers, to prevent header injection. | [
"Forbid",
"multi",
"-",
"line",
"headers",
"to",
"prevent",
"header",
"injection",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L107-L130 |
alefnula/tea | tea/msg/mail.py | send_mail | def send_mail(
subject,
sender,
to,
message,
html_message=None,
cc=None,
bcc=None,
attachments=None,
host=None,
port=None,
auth_user=None,
auth_password=None,
use_tls=False,
fail_silently=False,
):
"""Send a single email to a recipient list.
... | python | def send_mail(
subject,
sender,
to,
message,
html_message=None,
cc=None,
bcc=None,
attachments=None,
host=None,
port=None,
auth_user=None,
auth_password=None,
use_tls=False,
fail_silently=False,
):
"""Send a single email to a recipient list.
... | [
"def",
"send_mail",
"(",
"subject",
",",
"sender",
",",
"to",
",",
"message",
",",
"html_message",
"=",
"None",
",",
"cc",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",... | Send a single email to a recipient list.
All members of the recipient list will see the other recipients in the 'To'
field.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly. | [
"Send",
"a",
"single",
"email",
"to",
"a",
"recipient",
"list",
".",
"All",
"members",
"of",
"the",
"recipient",
"list",
"will",
"see",
"the",
"other",
"recipients",
"in",
"the",
"To",
"field",
".",
"Note",
":",
"The",
"API",
"for",
"this",
"method",
"... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L432-L494 |
alefnula/tea | tea/msg/mail.py | send_mass_mail | def send_mass_mail(
datatuple, fail_silently=False, auth_user=None, auth_password=None
):
"""Send multiple emails to multiple recipients.
Given a datatuple of (subject, message, sender, recipient_list), sends
each message to each recipient list. Returns the number of e-mails sent.
If auth_... | python | def send_mass_mail(
datatuple, fail_silently=False, auth_user=None, auth_password=None
):
"""Send multiple emails to multiple recipients.
Given a datatuple of (subject, message, sender, recipient_list), sends
each message to each recipient list. Returns the number of e-mails sent.
If auth_... | [
"def",
"send_mass_mail",
"(",
"datatuple",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
")",
":",
"connection",
"=",
"SMTPConnection",
"(",
"username",
"=",
"auth_user",
",",
"password",
"=",
"auth_passw... | Send multiple emails to multiple recipients.
Given a datatuple of (subject, message, sender, recipient_list), sends
each message to each recipient list. Returns the number of e-mails sent.
If auth_user and auth_password are set, they're used to log in.
Note: The API for this method is frozen. ... | [
"Send",
"multiple",
"emails",
"to",
"multiple",
"recipients",
".",
"Given",
"a",
"datatuple",
"of",
"(",
"subject",
"message",
"sender",
"recipient_list",
")",
"sends",
"each",
"message",
"to",
"each",
"recipient",
"list",
".",
"Returns",
"the",
"number",
"of"... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L497-L517 |
alefnula/tea | tea/msg/mail.py | SMTPConnection.open | def open(self):
"""Ensure we have a connection to the email server.
Returns whether or not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
# I... | python | def open(self):
"""Ensure we have a connection to the email server.
Returns whether or not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
# I... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
":",
"# Nothing to do if the connection is already open.\r",
"return",
"False",
"try",
":",
"# If local_hostname is not specified, socket.getfqdn() gets used.\r",
"# For performance, we use the cached FQDN for l... | Ensure we have a connection to the email server.
Returns whether or not a new connection was required (True or False). | [
"Ensure",
"we",
"have",
"a",
"connection",
"to",
"the",
"email",
"server",
".",
"Returns",
"whether",
"or",
"not",
"a",
"new",
"connection",
"was",
"required",
"(",
"True",
"or",
"False",
")",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L165-L194 |
alefnula/tea | tea/msg/mail.py | SMTPConnection.close | def close(self):
"""Close the connection to the email server."""
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.cl... | python | def close(self):
"""Close the connection to the email server."""
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.cl... | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"self",
".",
"connection",
".",
"quit",
"(",
")",
"except",
"socket",
".",
"sslerror",
":",
"# This happens when calling quit() on a TLS connection\r",
"# sometimes.\r",
"self",
".",
"connection",
".... | Close the connection to the email server. | [
"Close",
"the",
"connection",
"to",
"the",
"email",
"server",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L196-L216 |
alefnula/tea | tea/msg/mail.py | SMTPConnection.send_messages | def send_messages(self, messages):
"""Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent.
"""
if not messages:
return
new_conn_created = self.open()
if not self.connection:
# We failed silentl... | python | def send_messages(self, messages):
"""Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent.
"""
if not messages:
return
new_conn_created = self.open()
if not self.connection:
# We failed silentl... | [
"def",
"send_messages",
"(",
"self",
",",
"messages",
")",
":",
"if",
"not",
"messages",
":",
"return",
"new_conn_created",
"=",
"self",
".",
"open",
"(",
")",
"if",
"not",
"self",
".",
"connection",
":",
"# We failed silently on open(). Trying to send would be po... | Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent. | [
"Send",
"one",
"or",
"more",
"EmailMessage",
"objects",
".",
"Returns",
":",
"int",
":",
"Number",
"of",
"email",
"messages",
"sent",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L218-L237 |
alefnula/tea | tea/msg/mail.py | SMTPConnection._send | def _send(self, message):
"""Send an email.
Helper method that does the actual sending.
"""
if not message.recipients():
return False
try:
self.connection.sendmail(
message.sender,
message.recipients(),
... | python | def _send(self, message):
"""Send an email.
Helper method that does the actual sending.
"""
if not message.recipients():
return False
try:
self.connection.sendmail(
message.sender,
message.recipients(),
... | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"message",
".",
"recipients",
"(",
")",
":",
"return",
"False",
"try",
":",
"self",
".",
"connection",
".",
"sendmail",
"(",
"message",
".",
"sender",
",",
"message",
".",
"recipients"... | Send an email.
Helper method that does the actual sending. | [
"Send",
"an",
"email",
".",
"Helper",
"method",
"that",
"does",
"the",
"actual",
"sending",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L239-L262 |
alefnula/tea | tea/msg/mail.py | EmailMessage.attach | def attach(self, filename=None, content=None, mimetype=None):
"""Attache a file with the given filename and content.
The filename can be omitted (useful for multipart/alternative messages)
and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass... | python | def attach(self, filename=None, content=None, mimetype=None):
"""Attache a file with the given filename and content.
The filename can be omitted (useful for multipart/alternative messages)
and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass... | [
"def",
"attach",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"content",
"=",
"None",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"MIMEBase",
")",
":",
"assert",
"content",
"is",
"None",
"and",
"mimetype",
"is",... | Attache a file with the given filename and content.
The filename can be omitted (useful for multipart/alternative messages)
and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly
into the resulting message attachments. | [
"Attache",
"a",
"file",
"with",
"the",
"given",
"filename",
"and",
"content",
".",
"The",
"filename",
"can",
"be",
"omitted",
"(",
"useful",
"for",
"multipart",
"/",
"alternative",
"messages",
")",
"and",
"the",
"mimetype",
"is",
"guessed",
"if",
"not",
"p... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L370-L386 |
alefnula/tea | tea/msg/mail.py | EmailMessage.attach_file | def attach_file(self, path, mimetype=None):
"""Attache a file from the filesystem."""
filename = os.path.basename(path)
content = open(path, "rb").read()
self.attach(filename, content, mimetype) | python | def attach_file(self, path, mimetype=None):
"""Attache a file from the filesystem."""
filename = os.path.basename(path)
content = open(path, "rb").read()
self.attach(filename, content, mimetype) | [
"def",
"attach_file",
"(",
"self",
",",
"path",
",",
"mimetype",
"=",
"None",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"content",
"=",
"open",
"(",
"path",
",",
"\"rb\"",
")",
".",
"read",
"(",
")",
"self",
... | Attache a file from the filesystem. | [
"Attache",
"a",
"file",
"from",
"the",
"filesystem",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L388-L392 |
alefnula/tea | tea/msg/mail.py | EmailMessage._create_attachment | def _create_attachment(self, filename, content, mimetype=None):
"""Convert the filename, content, mimetype triple to attachment."""
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
... | python | def _create_attachment(self, filename, content, mimetype=None):
"""Convert the filename, content, mimetype triple to attachment."""
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
... | [
"def",
"_create_attachment",
"(",
"self",
",",
"filename",
",",
"content",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"mimetype",
"is",
"None",
":",
"mimetype",
",",
"_",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"if",
"mimetype",
"is... | Convert the filename, content, mimetype triple to attachment. | [
"Convert",
"the",
"filename",
"content",
"mimetype",
"triple",
"to",
"attachment",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L394-L414 |
alefnula/tea | tea/msg/mail.py | EmailMultiAlternatives.attach_alternative | def attach_alternative(self, content, mimetype=None):
"""Attach an alternative content representation."""
self.attach(content=content, mimetype=mimetype) | python | def attach_alternative(self, content, mimetype=None):
"""Attach an alternative content representation."""
self.attach(content=content, mimetype=mimetype) | [
"def",
"attach_alternative",
"(",
"self",
",",
"content",
",",
"mimetype",
"=",
"None",
")",
":",
"self",
".",
"attach",
"(",
"content",
"=",
"content",
",",
"mimetype",
"=",
"mimetype",
")"
] | Attach an alternative content representation. | [
"Attach",
"an",
"alternative",
"content",
"representation",
"."
] | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/msg/mail.py#L427-L429 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | setup_logging | def setup_logging(verbose=False, logger=None):
"""Setup console logging. Info and below go to stdout, others go to stderr.
:param bool verbose: Print debug statements.
:param str logger: Which logger to set handlers to. Used for testing.
"""
if not verbose:
logging.getLogger('requests').set... | python | def setup_logging(verbose=False, logger=None):
"""Setup console logging. Info and below go to stdout, others go to stderr.
:param bool verbose: Print debug statements.
:param str logger: Which logger to set handlers to. Used for testing.
"""
if not verbose:
logging.getLogger('requests').set... | [
"def",
"setup_logging",
"(",
"verbose",
"=",
"False",
",",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"verbose",
":",
"logging",
".",
"getLogger",
"(",
"'requests'",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"format_",
"=",
"'%(asctim... | Setup console logging. Info and below go to stdout, others go to stderr.
:param bool verbose: Print debug statements.
:param str logger: Which logger to set handlers to. Used for testing. | [
"Setup",
"console",
"logging",
".",
"Info",
"and",
"below",
"go",
"to",
"stdout",
"others",
"go",
"to",
"stderr",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L92-L116 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | with_log | def with_log(func):
"""Automatically adds a named logger to a function upon function call.
:param func: Function to decorate.
:return: Decorated function.
:rtype: function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Inject `log` argument into wrapped function.
... | python | def with_log(func):
"""Automatically adds a named logger to a function upon function call.
:param func: Function to decorate.
:return: Decorated function.
:rtype: function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Inject `log` argument into wrapped function.
... | [
"def",
"with_log",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Inject `log` argument into wrapped function.\n\n :param list args: Pass through all positio... | Automatically adds a named logger to a function upon function call.
:param func: Function to decorate.
:return: Decorated function.
:rtype: function | [
"Automatically",
"adds",
"a",
"named",
"logger",
"to",
"a",
"function",
"upon",
"function",
"call",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L119-L142 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | get_arguments | def get_arguments(argv=None, environ=None):
"""Get command line arguments or values from environment variables.
:param list argv: Command line argument list to process. For testing.
:param dict environ: Environment variables. For testing.
:return: Parsed options.
:rtype: dict
"""
name = 'a... | python | def get_arguments(argv=None, environ=None):
"""Get command line arguments or values from environment variables.
:param list argv: Command line argument list to process. For testing.
:param dict environ: Environment variables. For testing.
:return: Parsed options.
:rtype: dict
"""
name = 'a... | [
"def",
"get_arguments",
"(",
"argv",
"=",
"None",
",",
"environ",
"=",
"None",
")",
":",
"name",
"=",
"'appveyor-artifacts'",
"environ",
"=",
"environ",
"or",
"os",
".",
"environ",
"require",
"=",
"getattr",
"(",
"pkg_resources",
",",
"'require'",
")",
"# ... | Get command line arguments or values from environment variables.
:param list argv: Command line argument list to process. For testing.
:param dict environ: Environment variables. For testing.
:return: Parsed options.
:rtype: dict | [
"Get",
"command",
"line",
"arguments",
"or",
"values",
"from",
"environment",
"variables",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L145-L198 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | query_api | def query_api(endpoint, log):
"""Query the AppVeyor API.
:raise HandledError: On non HTTP200 responses or invalid JSON response.
:param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts').
:param logging.Logger log: Logger for this function. Populated by with_log() decor... | python | def query_api(endpoint, log):
"""Query the AppVeyor API.
:raise HandledError: On non HTTP200 responses or invalid JSON response.
:param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts').
:param logging.Logger log: Logger for this function. Populated by with_log() decor... | [
"def",
"query_api",
"(",
"endpoint",
",",
"log",
")",
":",
"url",
"=",
"API_PREFIX",
"+",
"endpoint",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
"response",
"=",
"None",
"log",
".",
"debug",
"(",
"'Querying %s with headers %s.'",
",... | Query the AppVeyor API.
:raise HandledError: On non HTTP200 responses or invalid JSON response.
:param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts').
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Parsed JSON respo... | [
"Query",
"the",
"AppVeyor",
"API",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L202-L250 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | validate | def validate(config, log):
"""Validate config values.
:raise HandledError: On invalid config values.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
if config['always_job_dirs'] and config['no_job_... | python | def validate(config, log):
"""Validate config values.
:raise HandledError: On invalid config values.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
if config['always_job_dirs'] and config['no_job_... | [
"def",
"validate",
"(",
"config",
",",
"log",
")",
":",
"if",
"config",
"[",
"'always_job_dirs'",
"]",
"and",
"config",
"[",
"'no_job_dirs'",
"]",
":",
"log",
".",
"error",
"(",
"'Contradiction: --always-job-dirs and --no-job-dirs used.'",
")",
"raise",
"HandledEr... | Validate config values.
:raise HandledError: On invalid config values.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator. | [
"Validate",
"config",
"values",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L254-L285 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | query_build_version | def query_build_version(config, log):
"""Find the build version we're looking for.
AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query,
only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status... | python | def query_build_version(config, log):
"""Find the build version we're looking for.
AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query,
only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status... | [
"def",
"query_build_version",
"(",
"config",
",",
"log",
")",
":",
"url",
"=",
"'/projects/{0}/{1}/history?recordsNumber=10'",
".",
"format",
"(",
"config",
"[",
"'owner'",
"]",
",",
"config",
"[",
"'repo'",
"]",
")",
"# Query history.",
"log",
".",
"debug",
"... | Find the build version we're looking for.
AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query,
only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status update.
Returns None if the job isn't q... | [
"Find",
"the",
"build",
"version",
"we",
"re",
"looking",
"for",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L289-L326 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | query_job_ids | def query_job_ids(build_version, config, log):
"""Get one or more job IDs and their status associated with a build version.
Filters jobs by name if --job-name is specified.
:raise HandledError: On invalid JSON data or bad job name.
:param str build_version: AppVeyor build version from query_build_ver... | python | def query_job_ids(build_version, config, log):
"""Get one or more job IDs and their status associated with a build version.
Filters jobs by name if --job-name is specified.
:raise HandledError: On invalid JSON data or bad job name.
:param str build_version: AppVeyor build version from query_build_ver... | [
"def",
"query_job_ids",
"(",
"build_version",
",",
"config",
",",
"log",
")",
":",
"url",
"=",
"'/projects/{0}/{1}/build/{2}'",
".",
"format",
"(",
"config",
"[",
"'owner'",
"]",
",",
"config",
"[",
"'repo'",
"]",
",",
"build_version",
")",
"# Query version.",... | Get one or more job IDs and their status associated with a build version.
Filters jobs by name if --job-name is specified.
:raise HandledError: On invalid JSON data or bad job name.
:param str build_version: AppVeyor build version from query_build_version().
:param dict config: Dictionary from get_ar... | [
"Get",
"one",
"or",
"more",
"job",
"IDs",
"and",
"their",
"status",
"associated",
"with",
"a",
"build",
"version",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L330-L366 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | query_artifacts | def query_artifacts(job_ids, log):
"""Query API again for artifacts.
:param iter job_ids: List of AppVeyor jobIDs.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: List of tuples: (job ID, artifact file name, artifact file size).
:rtype: list
"""... | python | def query_artifacts(job_ids, log):
"""Query API again for artifacts.
:param iter job_ids: List of AppVeyor jobIDs.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: List of tuples: (job ID, artifact file name, artifact file size).
:rtype: list
"""... | [
"def",
"query_artifacts",
"(",
"job_ids",
",",
"log",
")",
":",
"jobs_artifacts",
"=",
"list",
"(",
")",
"for",
"job",
"in",
"job_ids",
":",
"url",
"=",
"'/buildjobs/{0}/artifacts'",
".",
"format",
"(",
"job",
")",
"log",
".",
"debug",
"(",
"'Querying AppV... | Query API again for artifacts.
:param iter job_ids: List of AppVeyor jobIDs.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: List of tuples: (job ID, artifact file name, artifact file size).
:rtype: list | [
"Query",
"API",
"again",
"for",
"artifacts",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L370-L386 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | artifacts_urls | def artifacts_urls(config, jobs_artifacts, log):
"""Determine destination file paths for job artifacts.
:param dict config: Dictionary from get_arguments().
:param iter jobs_artifacts: List of job artifacts from query_artifacts().
:param logging.Logger log: Logger for this function. Populated by with_l... | python | def artifacts_urls(config, jobs_artifacts, log):
"""Determine destination file paths for job artifacts.
:param dict config: Dictionary from get_arguments().
:param iter jobs_artifacts: List of job artifacts from query_artifacts().
:param logging.Logger log: Logger for this function. Populated by with_l... | [
"def",
"artifacts_urls",
"(",
"config",
",",
"jobs_artifacts",
",",
"log",
")",
":",
"artifacts",
"=",
"dict",
"(",
")",
"# Determine if we should create job ID directories.",
"if",
"config",
"[",
"'always_job_dirs'",
"]",
":",
"job_dirs",
"=",
"True",
"elif",
"co... | Determine destination file paths for job artifacts.
:param dict config: Dictionary from get_arguments().
:param iter jobs_artifacts: List of job artifacts from query_artifacts().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Destination file paths (ke... | [
"Determine",
"destination",
"file",
"paths",
"for",
"job",
"artifacts",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L390-L440 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | get_urls | def get_urls(config, log):
"""Wait for AppVeyor job to finish and get all artifacts' URLs.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Paths and URLs from artifacts_urls.
:rtype: dict
"""
... | python | def get_urls(config, log):
"""Wait for AppVeyor job to finish and get all artifacts' URLs.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Paths and URLs from artifacts_urls.
:rtype: dict
"""
... | [
"def",
"get_urls",
"(",
"config",
",",
"log",
")",
":",
"# Wait for job to be queued. Once it is we'll have the \"version\".",
"build_version",
"=",
"None",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"build_version",
"=",
"query_build_version",
"(",
"config",
")... | Wait for AppVeyor job to finish and get all artifacts' URLs.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Paths and URLs from artifacts_urls.
:rtype: dict | [
"Wait",
"for",
"AppVeyor",
"job",
"to",
"finish",
"and",
"get",
"all",
"artifacts",
"URLs",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L444-L491 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | download_file | def download_file(config, local_path, url, expected_size, chunk_size, log):
"""Download a file.
:param dict config: Dictionary from get_arguments().
:param str local_path: Destination path to save file to.
:param str url: URL of the file to download.
:param int expected_size: Expected file size in ... | python | def download_file(config, local_path, url, expected_size, chunk_size, log):
"""Download a file.
:param dict config: Dictionary from get_arguments().
:param str local_path: Destination path to save file to.
:param str url: URL of the file to download.
:param int expected_size: Expected file size in ... | [
"def",
"download_file",
"(",
"config",
",",
"local_path",
",",
"url",
",",
"expected_size",
",",
"chunk_size",
",",
"log",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"local_path",
")",
")",
"... | Download a file.
:param dict config: Dictionary from get_arguments().
:param str local_path: Destination path to save file to.
:param str url: URL of the file to download.
:param int expected_size: Expected file size in bytes.
:param int chunk_size: Number of bytes to read in memory before writing ... | [
"Download",
"a",
"file",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L495-L526 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | mangle_coverage | def mangle_coverage(local_path, log):
"""Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
# Read the file, or return if not a .cove... | python | def mangle_coverage(local_path, log):
"""Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
# Read the file, or return if not a .cove... | [
"def",
"mangle_coverage",
"(",
"local_path",
",",
"log",
")",
":",
"# Read the file, or return if not a .coverage file.",
"with",
"open",
"(",
"local_path",
",",
"mode",
"=",
"'rb'",
")",
"as",
"handle",
":",
"if",
"handle",
".",
"read",
"(",
"13",
")",
"!=",
... | Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator. | [
"Edit",
".",
"coverage",
"file",
"substituting",
"Windows",
"file",
"paths",
"to",
"Linux",
"paths",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L530-L559 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | main | def main(config, log):
"""Main function. Runs the program.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
validate(config)
paths_and_urls = get_urls(config)
if not paths_and_urls:
log.w... | python | def main(config, log):
"""Main function. Runs the program.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
validate(config)
paths_and_urls = get_urls(config)
if not paths_and_urls:
log.w... | [
"def",
"main",
"(",
"config",
",",
"log",
")",
":",
"validate",
"(",
"config",
")",
"paths_and_urls",
"=",
"get_urls",
"(",
"config",
")",
"if",
"not",
"paths_and_urls",
":",
"log",
".",
"warning",
"(",
"'No artifacts; nothing to download.'",
")",
"return",
... | Main function. Runs the program.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator. | [
"Main",
"function",
".",
"Runs",
"the",
"program",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L563-L585 |
Robpol86/appveyor-artifacts | appveyor_artifacts.py | entry_point | def entry_point():
"""Entry-point from setuptools."""
signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C
config = get_arguments()
setup_logging(config['verbose'])
try:
main(config)
except HandledError:
if config['raise']:
rai... | python | def entry_point():
"""Entry-point from setuptools."""
signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C
config = get_arguments()
setup_logging(config['verbose'])
try:
main(config)
except HandledError:
if config['raise']:
rai... | [
"def",
"entry_point",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"lambda",
"*",
"_",
":",
"getattr",
"(",
"os",
",",
"'_exit'",
")",
"(",
"0",
")",
")",
"# Properly handle Control+C",
"config",
"=",
"get_arguments",
"(",
... | Entry-point from setuptools. | [
"Entry",
"-",
"point",
"from",
"setuptools",
"."
] | train | https://github.com/Robpol86/appveyor-artifacts/blob/20bc2963b09f4142fd4c0b1f5da04f1105379e36/appveyor_artifacts.py#L588-L599 |
mmEissen/airpixel | airpixel/client.py | ConnectionSupervisor.incoming_messages | def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]:
"""Consume the receive buffer and return the messages.
If there are new messages added to the queue while this funciton is being
processed, they will not be returned. This ensures that this terminates in
a timely manner.
... | python | def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]:
"""Consume the receive buffer and return the messages.
If there are new messages added to the queue while this funciton is being
processed, they will not be returned. This ensures that this terminates in
a timely manner.
... | [
"def",
"incoming_messages",
"(",
"self",
")",
"->",
"t",
".",
"List",
"[",
"t",
".",
"Tuple",
"[",
"float",
",",
"bytes",
"]",
"]",
":",
"approximate_messages",
"=",
"self",
".",
"_receive_buffer",
".",
"qsize",
"(",
")",
"messages",
"=",
"[",
"]",
"... | Consume the receive buffer and return the messages.
If there are new messages added to the queue while this funciton is being
processed, they will not be returned. This ensures that this terminates in
a timely manner. | [
"Consume",
"the",
"receive",
"buffer",
"and",
"return",
"the",
"messages",
"."
] | train | https://github.com/mmEissen/airpixel/blob/23385776eaa1a8a573fa94200eea051fa7c6c120/airpixel/client.py#L278-L292 |
pyout/pyout | pyout/common.py | _safe_get | def _safe_get(mapping, key, default=None):
"""Helper for accessing style values.
It exists to avoid checking whether `mapping` is indeed a mapping before
trying to get a key. In the context of style dicts, this eliminates "is
this a mapping" checks in two common situations: 1) a style argument is
... | python | def _safe_get(mapping, key, default=None):
"""Helper for accessing style values.
It exists to avoid checking whether `mapping` is indeed a mapping before
trying to get a key. In the context of style dicts, this eliminates "is
this a mapping" checks in two common situations: 1) a style argument is
... | [
"def",
"_safe_get",
"(",
"mapping",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"mapping",
".",
"get",
"(",
"key",
",",
"default",
")",
"except",
"AttributeError",
":",
"return",
"default"
] | Helper for accessing style values.
It exists to avoid checking whether `mapping` is indeed a mapping before
trying to get a key. In the context of style dicts, this eliminates "is
this a mapping" checks in two common situations: 1) a style argument is
None, and 2) a style key's value (e.g., width) can... | [
"Helper",
"for",
"accessing",
"style",
"values",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L214-L226 |
pyout/pyout | pyout/common.py | RowNormalizer.strip_callables | def strip_callables(row):
"""Extract callable values from `row`.
Replace the callable values with the initial value (if specified) or
an empty string.
Parameters
----------
row : mapping
A data row. The keys are either a single column name or a tuple of
... | python | def strip_callables(row):
"""Extract callable values from `row`.
Replace the callable values with the initial value (if specified) or
an empty string.
Parameters
----------
row : mapping
A data row. The keys are either a single column name or a tuple of
... | [
"def",
"strip_callables",
"(",
"row",
")",
":",
"callables",
"=",
"[",
"]",
"to_delete",
"=",
"[",
"]",
"to_add",
"=",
"[",
"]",
"for",
"columns",
",",
"value",
"in",
"row",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple... | Extract callable values from `row`.
Replace the callable values with the initial value (if specified) or
an empty string.
Parameters
----------
row : mapping
A data row. The keys are either a single column name or a tuple of
column names. The values ta... | [
"Extract",
"callable",
"values",
"from",
"row",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L150-L198 |
pyout/pyout | pyout/common.py | StyleFields.build | def build(self, columns):
"""Build the style and fields.
Parameters
----------
columns : list of str
Column names.
"""
self.columns = columns
default = dict(elements.default("default_"),
**_safe_get(self.init_style, "default_", ... | python | def build(self, columns):
"""Build the style and fields.
Parameters
----------
columns : list of str
Column names.
"""
self.columns = columns
default = dict(elements.default("default_"),
**_safe_get(self.init_style, "default_", ... | [
"def",
"build",
"(",
"self",
",",
"columns",
")",
":",
"self",
".",
"columns",
"=",
"columns",
"default",
"=",
"dict",
"(",
"elements",
".",
"default",
"(",
"\"default_\"",
")",
",",
"*",
"*",
"_safe_get",
"(",
"self",
".",
"init_style",
",",
"\"defaul... | Build the style and fields.
Parameters
----------
columns : list of str
Column names. | [
"Build",
"the",
"style",
"and",
"fields",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L252-L281 |
pyout/pyout | pyout/common.py | StyleFields._compose | def _compose(self, name, attributes):
"""Construct a style taking `attributes` from the column styles.
Parameters
----------
name : str
Name of main style (e.g., "header_").
attributes : set of str
Adopt these elements from the column styles.
Ret... | python | def _compose(self, name, attributes):
"""Construct a style taking `attributes` from the column styles.
Parameters
----------
name : str
Name of main style (e.g., "header_").
attributes : set of str
Adopt these elements from the column styles.
Ret... | [
"def",
"_compose",
"(",
"self",
",",
"name",
",",
"attributes",
")",
":",
"name_style",
"=",
"_safe_get",
"(",
"self",
".",
"init_style",
",",
"name",
",",
"elements",
".",
"default",
"(",
"name",
")",
")",
"if",
"self",
".",
"init_style",
"is",
"not",... | Construct a style taking `attributes` from the column styles.
Parameters
----------
name : str
Name of main style (e.g., "header_").
attributes : set of str
Adopt these elements from the column styles.
Returns
-------
The composite style ... | [
"Construct",
"a",
"style",
"taking",
"attributes",
"from",
"the",
"column",
"styles",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L283-L304 |
pyout/pyout | pyout/common.py | StyleFields._set_widths | def _set_widths(self, row, proc_group):
"""Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns... | python | def _set_widths(self, row, proc_group):
"""Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns... | [
"def",
"_set_widths",
"(",
"self",
",",
"row",
",",
"proc_group",
")",
":",
"width_free",
"=",
"self",
".",
"style",
"[",
"\"width_\"",
"]",
"-",
"sum",
"(",
"[",
"sum",
"(",
"self",
".",
"fields",
"[",
"c",
"]",
".",
"width",
"for",
"c",
"in",
"... | Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns
-------
True if any widths require... | [
"Update",
"auto",
"-",
"width",
"Fields",
"based",
"on",
"row",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L361-L434 |
pyout/pyout | pyout/common.py | StyleFields._proc_group | def _proc_group(self, style, adopt=True):
"""Return whether group is "default" or "override".
In the case of "override", the self.fields pre-format and post-format
processors will be set under the "override" key.
Parameters
----------
style : dict
A style th... | python | def _proc_group(self, style, adopt=True):
"""Return whether group is "default" or "override".
In the case of "override", the self.fields pre-format and post-format
processors will be set under the "override" key.
Parameters
----------
style : dict
A style th... | [
"def",
"_proc_group",
"(",
"self",
",",
"style",
",",
"adopt",
"=",
"True",
")",
":",
"fields",
"=",
"self",
".",
"fields",
"if",
"style",
"is",
"not",
"None",
":",
"if",
"adopt",
":",
"style",
"=",
"elements",
".",
"adopt",
"(",
"self",
".",
"styl... | Return whether group is "default" or "override".
In the case of "override", the self.fields pre-format and post-format
processors will be set under the "override" key.
Parameters
----------
style : dict
A style that follows the schema defined in pyout.elements.
... | [
"Return",
"whether",
"group",
"is",
"default",
"or",
"override",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L436-L466 |
pyout/pyout | pyout/common.py | StyleFields.render | def render(self, row, style=None, adopt=True):
"""Render fields with values from `row`.
Parameters
----------
row : dict
A normalized row.
style : dict, optional
A style that follows the schema defined in pyout.elements. If
None, `self.style`... | python | def render(self, row, style=None, adopt=True):
"""Render fields with values from `row`.
Parameters
----------
row : dict
A normalized row.
style : dict, optional
A style that follows the schema defined in pyout.elements. If
None, `self.style`... | [
"def",
"render",
"(",
"self",
",",
"row",
",",
"style",
"=",
"None",
",",
"adopt",
"=",
"True",
")",
":",
"group",
"=",
"self",
".",
"_proc_group",
"(",
"style",
",",
"adopt",
"=",
"adopt",
")",
"if",
"group",
"==",
"\"override\"",
":",
"# Override t... | Render fields with values from `row`.
Parameters
----------
row : dict
A normalized row.
style : dict, optional
A style that follows the schema defined in pyout.elements. If
None, `self.style` is used.
adopt : bool, optional
Merge... | [
"Render",
"fields",
"with",
"values",
"from",
"row",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/common.py#L468-L499 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafka.get_config | def get_config(self):
"""
Sets up the basic config from the variables passed in
all of these are from what Heroku gives you.
"""
self.create_ssl_certs()
config = {
"bootstrap_servers": self.get_brokers(),
"security_protocol": 'SSL',
"s... | python | def get_config(self):
"""
Sets up the basic config from the variables passed in
all of these are from what Heroku gives you.
"""
self.create_ssl_certs()
config = {
"bootstrap_servers": self.get_brokers(),
"security_protocol": 'SSL',
"s... | [
"def",
"get_config",
"(",
"self",
")",
":",
"self",
".",
"create_ssl_certs",
"(",
")",
"config",
"=",
"{",
"\"bootstrap_servers\"",
":",
"self",
".",
"get_brokers",
"(",
")",
",",
"\"security_protocol\"",
":",
"'SSL'",
",",
"\"ssl_cafile\"",
":",
"self",
"."... | Sets up the basic config from the variables passed in
all of these are from what Heroku gives you. | [
"Sets",
"up",
"the",
"basic",
"config",
"from",
"the",
"variables",
"passed",
"in",
"all",
"of",
"these",
"are",
"from",
"what",
"Heroku",
"gives",
"you",
"."
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L27-L43 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafka.get_brokers | def get_brokers(self):
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
return ['{}:{}'.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split(',')]] | python | def get_brokers(self):
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
return ['{}:{}'.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split(',')]] | [
"def",
"get_brokers",
"(",
"self",
")",
":",
"return",
"[",
"'{}:{}'",
".",
"format",
"(",
"parsedUrl",
".",
"hostname",
",",
"parsedUrl",
".",
"port",
")",
"for",
"parsedUrl",
"in",
"[",
"urlparse",
"(",
"url",
")",
"for",
"url",
"in",
"self",
".",
... | Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects. | [
"Parses",
"the",
"KAKFA_URL",
"and",
"returns",
"a",
"list",
"of",
"hostname",
":",
"port",
"pairs",
"in",
"the",
"format",
"that",
"kafka",
"-",
"python",
"expects",
"."
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L45-L51 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafka.create_ssl_certs | def create_ssl_certs(self):
"""
Creates SSL cert files
"""
for key, file in self.ssl.items():
file["file"] = self.create_temp_file(file["suffix"], file["content"]) | python | def create_ssl_certs(self):
"""
Creates SSL cert files
"""
for key, file in self.ssl.items():
file["file"] = self.create_temp_file(file["suffix"], file["content"]) | [
"def",
"create_ssl_certs",
"(",
"self",
")",
":",
"for",
"key",
",",
"file",
"in",
"self",
".",
"ssl",
".",
"items",
"(",
")",
":",
"file",
"[",
"\"file\"",
"]",
"=",
"self",
".",
"create_temp_file",
"(",
"file",
"[",
"\"suffix\"",
"]",
",",
"file",
... | Creates SSL cert files | [
"Creates",
"SSL",
"cert",
"files"
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L53-L58 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafka.create_temp_file | def create_temp_file(self, suffix, content):
"""
Creates file, because environment variables are by default escaped it
encodes and then decodes them before write so \n etc. work correctly.
"""
temp = tempfile.NamedTemporaryFile(suffix=suffix)
temp.write(content.encode('l... | python | def create_temp_file(self, suffix, content):
"""
Creates file, because environment variables are by default escaped it
encodes and then decodes them before write so \n etc. work correctly.
"""
temp = tempfile.NamedTemporaryFile(suffix=suffix)
temp.write(content.encode('l... | [
"def",
"create_temp_file",
"(",
"self",
",",
"suffix",
",",
"content",
")",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"suffix",
")",
"temp",
".",
"write",
"(",
"content",
".",
"encode",
"(",
"'latin1'",
")",
".",
"decod... | Creates file, because environment variables are by default escaped it
encodes and then decodes them before write so \n etc. work correctly. | [
"Creates",
"file",
"because",
"environment",
"variables",
"are",
"by",
"default",
"escaped",
"it",
"encodes",
"and",
"then",
"decodes",
"them",
"before",
"write",
"so",
"\\",
"n",
"etc",
".",
"work",
"correctly",
"."
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L61-L69 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafka.prefix_topic | def prefix_topic(self, topics):
"""
Adds the topic_prefix to topic(s) supplied
"""
if not self.topic_prefix or not topics:
return topics
if not isinstance(topics, str) and isinstance(topics, collections.Iterable):
return [self.topic_prefix + topic for top... | python | def prefix_topic(self, topics):
"""
Adds the topic_prefix to topic(s) supplied
"""
if not self.topic_prefix or not topics:
return topics
if not isinstance(topics, str) and isinstance(topics, collections.Iterable):
return [self.topic_prefix + topic for top... | [
"def",
"prefix_topic",
"(",
"self",
",",
"topics",
")",
":",
"if",
"not",
"self",
".",
"topic_prefix",
"or",
"not",
"topics",
":",
"return",
"topics",
"if",
"not",
"isinstance",
"(",
"topics",
",",
"str",
")",
"and",
"isinstance",
"(",
"topics",
",",
"... | Adds the topic_prefix to topic(s) supplied | [
"Adds",
"the",
"topic_prefix",
"to",
"topic",
"(",
"s",
")",
"supplied"
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L71-L81 |
HubbleHQ/heroku-kafka | heroku_kafka.py | HerokuKafkaProducer.send | def send(self, topic, *args, **kwargs):
"""
Appends the prefix to the topic before sendingf
"""
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs) | python | def send(self, topic, *args, **kwargs):
"""
Appends the prefix to the topic before sendingf
"""
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"topic",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"prefix_topic",
"=",
"self",
".",
"heroku_kafka",
".",
"prefix_topic",
"(",
"topic",
")",
"return",
"super",
"(",
"HerokuKafkaProducer",
",",
"self",
")",
".... | Appends the prefix to the topic before sendingf | [
"Appends",
"the",
"prefix",
"to",
"the",
"topic",
"before",
"sendingf"
] | train | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L98-L103 |
night-crawler/django-docker-helpers | django_docker_helpers/config/backends/base.py | BaseParser.get | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Inherited method should take all specified arguments.
:param variable_p... | python | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Inherited method should take all specified arguments.
:param variable_p... | [
"def",
"get",
"(",
"self",
",",
"variable_path",
":",
"str",
",",
"default",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Any",
"]",
"=",
"None",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer"... | Inherited method should take all specified arguments.
:param variable_path: a delimiter-separated path to a nested value
:param default: default value if there's no object by specified path
:param coerce_type: cast a type of a value to a specified one
:param coercer: perform a type cast... | [
"Inherited",
"method",
"should",
"take",
"all",
"specified",
"arguments",
"."
] | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/base.py#L47-L63 |
night-crawler/django-docker-helpers | django_docker_helpers/config/backends/base.py | BaseParser.coerce | def coerce(val: t.Any,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None) -> t.Any:
"""
Casts a type of ``val`` to ``coerce_type`` with ``coercer``.
If ``coerce_type`` is bool and no ``coercer`` specified it uses
:func:`~django_... | python | def coerce(val: t.Any,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None) -> t.Any:
"""
Casts a type of ``val`` to ``coerce_type`` with ``coercer``.
If ``coerce_type`` is bool and no ``coercer`` specified it uses
:func:`~django_... | [
"def",
"coerce",
"(",
"val",
":",
"t",
".",
"Any",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Callable",
"]",
"=",
"None",
")",
"->",
"t",
... | Casts a type of ``val`` to ``coerce_type`` with ``coercer``.
If ``coerce_type`` is bool and no ``coercer`` specified it uses
:func:`~django_docker_helpers.utils.coerce_str_to_bool` by default.
:param val: a value of any type
:param coerce_type: any type
:param coercer: provide ... | [
"Casts",
"a",
"type",
"of",
"val",
"to",
"coerce_type",
"with",
"coercer",
"."
] | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/base.py#L66-L92 |
night-crawler/django-docker-helpers | django_docker_helpers/config/backends/base.py | BaseParser.client | def client(self):
"""
Helper property to lazy initialize and cache client. Runs
:meth:`~django_docker_helpers.config.backends.base.BaseParser.get_client`.
:return: an instance of backend-specific client
"""
if self._client is not None:
return self._client
... | python | def client(self):
"""
Helper property to lazy initialize and cache client. Runs
:meth:`~django_docker_helpers.config.backends.base.BaseParser.get_client`.
:return: an instance of backend-specific client
"""
if self._client is not None:
return self._client
... | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_client",
"self",
".",
"_client",
"=",
"self",
".",
"get_client",
"(",
")",
"return",
"self",
".",
"_client"
] | Helper property to lazy initialize and cache client. Runs
:meth:`~django_docker_helpers.config.backends.base.BaseParser.get_client`.
:return: an instance of backend-specific client | [
"Helper",
"property",
"to",
"lazy",
"initialize",
"and",
"cache",
"client",
".",
"Runs",
":",
"meth",
":",
"~django_docker_helpers",
".",
"config",
".",
"backends",
".",
"base",
".",
"BaseParser",
".",
"get_client",
"."
] | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/base.py#L95-L106 |
pyout/pyout | pyout/truncate.py | _splice | def _splice(value, n):
"""Splice `value` at its center, retaining a total of `n` characters.
Parameters
----------
value : str
n : int
The total length of the returned ends will not be greater than this
value. Characters will be dropped from the center to reach this limit.
Ret... | python | def _splice(value, n):
"""Splice `value` at its center, retaining a total of `n` characters.
Parameters
----------
value : str
n : int
The total length of the returned ends will not be greater than this
value. Characters will be dropped from the center to reach this limit.
Ret... | [
"def",
"_splice",
"(",
"value",
",",
"n",
")",
":",
"if",
"n",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be positive\"",
")",
"value_len",
"=",
"len",
"(",
"value",
")",
"center",
"=",
"value_len",
"//",
"2",
"left",
",",
"right",
"=",
"v... | Splice `value` at its center, retaining a total of `n` characters.
Parameters
----------
value : str
n : int
The total length of the returned ends will not be greater than this
value. Characters will be dropped from the center to reach this limit.
Returns
-------
A tuple o... | [
"Splice",
"value",
"at",
"its",
"center",
"retaining",
"a",
"total",
"of",
"n",
"characters",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/truncate.py#L27-L54 |
night-crawler/django-docker-helpers | django_docker_helpers/cli/django/management/commands/run_configured_uwsgi.py | write_uwsgi_ini_cfg | def write_uwsgi_ini_cfg(fp: t.IO, cfg: dict):
"""
Writes into IO stream the uwsgi.ini file content (actually it does smth strange, just look below).
uWSGI configs are likely to break INI (YAML, etc) specification (double key definition)
so it writes `cfg` object (dict) in "uWSGI Style".
>>> import... | python | def write_uwsgi_ini_cfg(fp: t.IO, cfg: dict):
"""
Writes into IO stream the uwsgi.ini file content (actually it does smth strange, just look below).
uWSGI configs are likely to break INI (YAML, etc) specification (double key definition)
so it writes `cfg` object (dict) in "uWSGI Style".
>>> import... | [
"def",
"write_uwsgi_ini_cfg",
"(",
"fp",
":",
"t",
".",
"IO",
",",
"cfg",
":",
"dict",
")",
":",
"fp",
".",
"write",
"(",
"f'[uwsgi]\\n'",
")",
"for",
"key",
",",
"val",
"in",
"cfg",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",... | Writes into IO stream the uwsgi.ini file content (actually it does smth strange, just look below).
uWSGI configs are likely to break INI (YAML, etc) specification (double key definition)
so it writes `cfg` object (dict) in "uWSGI Style".
>>> import sys
>>> cfg = {
... 'static-map': [
... '/sta... | [
"Writes",
"into",
"IO",
"stream",
"the",
"uwsgi",
".",
"ini",
"file",
"content",
"(",
"actually",
"it",
"does",
"smth",
"strange",
"just",
"look",
"below",
")",
"."
] | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/cli/django/management/commands/run_configured_uwsgi.py#L9-L40 |
night-crawler/django-docker-helpers | django_docker_helpers/config/backends/mpt_consul_parser.py | MPTConsulParser.get | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-separated path to a nested value
:para... | python | def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-separated path to a nested value
:para... | [
"def",
"get",
"(",
"self",
",",
"variable_path",
":",
"str",
",",
"default",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Any",
"]",
"=",
"None",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer"... | :param variable_path: a delimiter-separated path to a nested value
:param default: default value if there's no object by specified path
:param coerce_type: cast a type of a value to a specified one
:param coercer: perform a type casting with specified callback
:param kwargs: additional a... | [
":",
"param",
"variable_path",
":",
"a",
"delimiter",
"-",
"separated",
"path",
"to",
"a",
"nested",
"value",
":",
"param",
"default",
":",
"default",
"value",
"if",
"there",
"s",
"no",
"object",
"by",
"specified",
"path",
":",
"param",
"coerce_type",
":",... | train | https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/mpt_consul_parser.py#L76-L119 |
meng89/ipodshuffle | ipodshuffle/db/itunessd.py | itunessd_to_dics | def itunessd_to_dics(itunessd):
"""
:param itunessd: the whole iTunesSD bytes data
:return: translate to tree object, see doc of dics_to_itunessd
"""
# header
header_size = get_table_size(header_table)
header_chunk = itunessd[0:header_size]
header_dic = chunk_to_dic(header_chunk, header... | python | def itunessd_to_dics(itunessd):
"""
:param itunessd: the whole iTunesSD bytes data
:return: translate to tree object, see doc of dics_to_itunessd
"""
# header
header_size = get_table_size(header_table)
header_chunk = itunessd[0:header_size]
header_dic = chunk_to_dic(header_chunk, header... | [
"def",
"itunessd_to_dics",
"(",
"itunessd",
")",
":",
"# header",
"header_size",
"=",
"get_table_size",
"(",
"header_table",
")",
"header_chunk",
"=",
"itunessd",
"[",
"0",
":",
"header_size",
"]",
"header_dic",
"=",
"chunk_to_dic",
"(",
"header_chunk",
",",
"he... | :param itunessd: the whole iTunesSD bytes data
:return: translate to tree object, see doc of dics_to_itunessd | [
":",
"param",
"itunessd",
":",
"the",
"whole",
"iTunesSD",
"bytes",
"data",
":",
"return",
":",
"translate",
"to",
"tree",
"object",
"see",
"doc",
"of",
"dics_to_itunessd"
] | train | https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/db/itunessd.py#L372-L402 |
meng89/ipodshuffle | ipodshuffle/db/itunessd.py | dics_to_itunessd | def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... | python | def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... | [
"def",
"dics_to_itunessd",
"(",
"header_dic",
",",
"tracks_dics",
",",
"playlists_dics_and_indexes",
")",
":",
"############################################",
"# header",
"######",
"header_dic",
"[",
"'length'",
"]",
"=",
"get_table_size",
"(",
"header_table",
")",
"heade... | :param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data | [
":",
"param",
"header_dic",
":",
"dic",
"of",
"header_table",
":",
"param",
"tracks_dics",
":",
"list",
"of",
"all",
"track_table",
"s",
"dics",
":",
"param",
"playlists_dics_and_indexes",
":",
"list",
"of",
"all",
"playlists",
"and",
"all",
"their",
"track",
... | train | https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/db/itunessd.py#L418-L516 |
pyout/pyout | pyout/field.py | Field.add | def add(self, kind, key, *values):
"""Add processor functions.
Any previous list of processors for `kind` and `key` will be
overwritten.
Parameters
----------
kind : {"pre", "post"}
key : str
A registered key. Add the functions (in order) to this ke... | python | def add(self, kind, key, *values):
"""Add processor functions.
Any previous list of processors for `kind` and `key` will be
overwritten.
Parameters
----------
kind : {"pre", "post"}
key : str
A registered key. Add the functions (in order) to this ke... | [
"def",
"add",
"(",
"self",
",",
"kind",
",",
"key",
",",
"*",
"values",
")",
":",
"if",
"kind",
"==",
"\"pre\"",
":",
"procs",
"=",
"self",
".",
"pre",
"elif",
"kind",
"==",
"\"post\"",
":",
"procs",
"=",
"self",
".",
"post",
"else",
":",
"raise"... | Add processor functions.
Any previous list of processors for `kind` and `key` will be
overwritten.
Parameters
----------
kind : {"pre", "post"}
key : str
A registered key. Add the functions (in order) to this key's list
of processors.
*v... | [
"Add",
"processor",
"functions",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/field.py#L84-L106 |
pyout/pyout | pyout/field.py | Field._format | def _format(self, _, result):
"""Wrap format call as a two-argument processor function.
"""
return self._fmt.format(six.text_type(result)) | python | def _format(self, _, result):
"""Wrap format call as a two-argument processor function.
"""
return self._fmt.format(six.text_type(result)) | [
"def",
"_format",
"(",
"self",
",",
"_",
",",
"result",
")",
":",
"return",
"self",
".",
"_fmt",
".",
"format",
"(",
"six",
".",
"text_type",
"(",
"result",
")",
")"
] | Wrap format call as a two-argument processor function. | [
"Wrap",
"format",
"call",
"as",
"a",
"two",
"-",
"argument",
"processor",
"function",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/field.py#L121-L124 |
pyout/pyout | pyout/field.py | StyleProcessors.transform | def transform(function):
"""Return a processor for a style's "transform" function.
"""
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
retur... | python | def transform(function):
"""Return a processor for a style's "transform" function.
"""
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
retur... | [
"def",
"transform",
"(",
"function",
")",
":",
"def",
"transform_fn",
"(",
"_",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"Nothing",
")",
":",
"return",
"result",
"lgr",
".",
"debug",
"(",
"\"Transforming %r with %r\"",
",",
"result"... | Return a processor for a style's "transform" function. | [
"Return",
"a",
"processor",
"for",
"a",
"style",
"s",
"transform",
"function",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/field.py#L240-L262 |
pyout/pyout | pyout/field.py | StyleProcessors.by_key | def by_key(self, style_key, style_value):
"""Return a processor for a "simple" style value.
Parameters
----------
style_key : str
A style key.
style_value : bool or str
A "simple" style value that is either a style attribute (str) and a
boolea... | python | def by_key(self, style_key, style_value):
"""Return a processor for a "simple" style value.
Parameters
----------
style_key : str
A style key.
style_value : bool or str
A "simple" style value that is either a style attribute (str) and a
boolea... | [
"def",
"by_key",
"(",
"self",
",",
"style_key",
",",
"style_value",
")",
":",
"if",
"self",
".",
"style_types",
"[",
"style_key",
"]",
"is",
"bool",
":",
"style_attr",
"=",
"style_key",
"else",
":",
"style_attr",
"=",
"style_value",
"def",
"proc",
"(",
"... | Return a processor for a "simple" style value.
Parameters
----------
style_key : str
A style key.
style_value : bool or str
A "simple" style value that is either a style attribute (str) and a
boolean flag indicating to use the style attribute named by... | [
"Return",
"a",
"processor",
"for",
"a",
"simple",
"style",
"value",
"."
] | train | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/field.py#L264-L287 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.