repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
davenquinn/Attitude | docs/scripts/generate-json.py | serialize | def serialize(pca, **kwargs):
"""
Serialize an orientation object to a dict suitable
for JSON
"""
strike, dip, rake = pca.strike_dip_rake()
hyp_axes = sampling_axes(pca)
return dict(
**kwargs,
principal_axes = pca.axes.tolist(),
hyperbolic_axes = hyp_axes.tolist(),
... | python | def serialize(pca, **kwargs):
"""
Serialize an orientation object to a dict suitable
for JSON
"""
strike, dip, rake = pca.strike_dip_rake()
hyp_axes = sampling_axes(pca)
return dict(
**kwargs,
principal_axes = pca.axes.tolist(),
hyperbolic_axes = hyp_axes.tolist(),
... | [
"def",
"serialize",
"(",
"pca",
",",
"*",
"*",
"kwargs",
")",
":",
"strike",
",",
"dip",
",",
"rake",
"=",
"pca",
".",
"strike_dip_rake",
"(",
")",
"hyp_axes",
"=",
"sampling_axes",
"(",
"pca",
")",
"return",
"dict",
"(",
"*",
"*",
"kwargs",
",",
"... | Serialize an orientation object to a dict suitable
for JSON | [
"Serialize",
"an",
"orientation",
"object",
"to",
"a",
"dict",
"suitable",
"for",
"JSON"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/docs/scripts/generate-json.py#L11-L26 |
RudolfCardinal/pythonlib | cardinal_pythonlib/getch.py | _kbhit_unix | def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] | python | def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] | [
"def",
"_kbhit_unix",
"(",
")",
"->",
"bool",
":",
"dr",
",",
"dw",
",",
"de",
"=",
"select",
".",
"select",
"(",
"[",
"sys",
".",
"stdin",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
")",
"return",
"dr",
"!=",
"[",
"]"
] | Under UNIX: is a keystroke available? | [
"Under",
"UNIX",
":",
"is",
"a",
"keystroke",
"available?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/getch.py#L82-L87 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/insert_on_duplicate.py | insert_on_duplicate | def insert_on_duplicate(tablename: str,
values: Any = None,
inline: bool = False,
**kwargs):
"""
Command to produce an :class:`InsertOnDuplicate` object.
Args:
tablename: name of the table
values: values to ``INSERT``
... | python | def insert_on_duplicate(tablename: str,
values: Any = None,
inline: bool = False,
**kwargs):
"""
Command to produce an :class:`InsertOnDuplicate` object.
Args:
tablename: name of the table
values: values to ``INSERT``
... | [
"def",
"insert_on_duplicate",
"(",
"tablename",
":",
"str",
",",
"values",
":",
"Any",
"=",
"None",
",",
"inline",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"return",
"InsertOnDuplicate",
"(",
"tablename",
",",
"values",
","... | Command to produce an :class:`InsertOnDuplicate` object.
Args:
tablename: name of the table
values: values to ``INSERT``
inline: as per
http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert
kwargs: additional parameters
Returns:
... | [
"Command",
"to",
"produce",
"an",
":",
"class",
":",
"InsertOnDuplicate",
"object",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/insert_on_duplicate.py#L70-L88 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/insert_on_duplicate.py | compile_insert_on_duplicate_key_update | def compile_insert_on_duplicate_key_update(insert: Insert,
compiler: SQLCompiler,
**kw) -> str:
"""
Hooks into the use of the :class:`InsertOnDuplicate` class
for the MySQL dialect. Compiles the relevant SQL for an ``INSER... | python | def compile_insert_on_duplicate_key_update(insert: Insert,
compiler: SQLCompiler,
**kw) -> str:
"""
Hooks into the use of the :class:`InsertOnDuplicate` class
for the MySQL dialect. Compiles the relevant SQL for an ``INSER... | [
"def",
"compile_insert_on_duplicate_key_update",
"(",
"insert",
":",
"Insert",
",",
"compiler",
":",
"SQLCompiler",
",",
"*",
"*",
"kw",
")",
"->",
"str",
":",
"# noqa",
"# log.critical(compiler.__dict__)",
"# log.critical(compiler.dialect.__dict__)",
"# log.critical(insert... | Hooks into the use of the :class:`InsertOnDuplicate` class
for the MySQL dialect. Compiles the relevant SQL for an ``INSERT...
ON DUPLICATE KEY UPDATE`` statement.
Notes:
- We can't get the fieldnames directly from ``insert`` or ``compiler``.
- We could rewrite the innards of the visit_insert sta... | [
"Hooks",
"into",
"the",
"use",
"of",
"the",
":",
"class",
":",
"InsertOnDuplicate",
"class",
"for",
"the",
"MySQL",
"dialect",
".",
"Compiles",
"the",
"relevant",
"SQL",
"for",
"an",
"INSERT",
"...",
"ON",
"DUPLICATE",
"KEY",
"UPDATE",
"statement",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/insert_on_duplicate.py#L123-L157 |
davenquinn/Attitude | attitude/orientation/grouped.py | create_groups | def create_groups(orientations, *groups, **kwargs):
"""
Create groups of an orientation measurement dataset
"""
grouped = []
# Copy all datasets to be safe (this could be bad for
# memory usage, so can be disabled).
if kwargs.pop('copy', True):
orientations = [copy(o) for o in orient... | python | def create_groups(orientations, *groups, **kwargs):
"""
Create groups of an orientation measurement dataset
"""
grouped = []
# Copy all datasets to be safe (this could be bad for
# memory usage, so can be disabled).
if kwargs.pop('copy', True):
orientations = [copy(o) for o in orient... | [
"def",
"create_groups",
"(",
"orientations",
",",
"*",
"groups",
",",
"*",
"*",
"kwargs",
")",
":",
"grouped",
"=",
"[",
"]",
"# Copy all datasets to be safe (this could be bad for",
"# memory usage, so can be disabled).",
"if",
"kwargs",
".",
"pop",
"(",
"'copy'",
... | Create groups of an orientation measurement dataset | [
"Create",
"groups",
"of",
"an",
"orientation",
"measurement",
"dataset"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/grouped.py#L35-L71 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/merge_csv.py | merge_csv | def merge_csv(filenames: List[str],
outfile: TextIO = sys.stdout,
input_dialect: str = 'excel',
output_dialect: str = 'excel',
debug: bool = False,
headers: bool = True) -> None:
"""
Amalgamate multiple CSV/TSV/similar files into one.
Ar... | python | def merge_csv(filenames: List[str],
outfile: TextIO = sys.stdout,
input_dialect: str = 'excel',
output_dialect: str = 'excel',
debug: bool = False,
headers: bool = True) -> None:
"""
Amalgamate multiple CSV/TSV/similar files into one.
Ar... | [
"def",
"merge_csv",
"(",
"filenames",
":",
"List",
"[",
"str",
"]",
",",
"outfile",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
",",
"input_dialect",
":",
"str",
"=",
"'excel'",
",",
"output_dialect",
":",
"str",
"=",
"'excel'",
",",
"debug",
":",
"bool"... | Amalgamate multiple CSV/TSV/similar files into one.
Args:
filenames: list of filenames to process
outfile: file-like object to write output to
input_dialect: dialect of input files, as passed to ``csv.reader``
output_dialect: dialect to write, as passed to ``csv.writer``
deb... | [
"Amalgamate",
"multiple",
"CSV",
"/",
"TSV",
"/",
"similar",
"files",
"into",
"one",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/merge_csv.py#L45-L94 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/merge_csv.py | main | def main():
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
parser = argparse.ArgumentParser()
parser.add_argument(
"filenames",
nargs="+",
help="Names of CSV/TSV files to merge"
)
parser.add_argument(
"--outf... | python | def main():
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
parser = argparse.ArgumentParser()
parser.add_argument(
"filenames",
nargs="+",
help="Names of CSV/TSV files to merge"
)
parser.add_argument(
"--outf... | [
"def",
"main",
"(",
")",
":",
"main_only_quicksetup_rootlogger",
"(",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"filenames\"",
",",
"nargs",
"=",
"\"+\"",
",",
"help",
"=",
"\"Names of CSV/TSV files to... | Command-line processor. See ``--help`` for details. | [
"Command",
"-",
"line",
"processor",
".",
"See",
"--",
"help",
"for",
"details",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/merge_csv.py#L97-L153 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_numpy.py | softmax | def softmax(x: np.ndarray,
b: float = 1.0) -> np.ndarray:
r"""
Standard softmax function:
.. math::
P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} }
Args:
x: vector (``numpy.array``) of values
b: exploration parameter :math:`\beta`, or inverse temp... | python | def softmax(x: np.ndarray,
b: float = 1.0) -> np.ndarray:
r"""
Standard softmax function:
.. math::
P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} }
Args:
x: vector (``numpy.array``) of values
b: exploration parameter :math:`\beta`, or inverse temp... | [
"def",
"softmax",
"(",
"x",
":",
"np",
".",
"ndarray",
",",
"b",
":",
"float",
"=",
"1.0",
")",
"->",
"np",
".",
"ndarray",
":",
"constant",
"=",
"np",
".",
"mean",
"(",
"x",
")",
"products",
"=",
"x",
"*",
"b",
"-",
"constant",
"# ... softmax is... | r"""
Standard softmax function:
.. math::
P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} }
Args:
x: vector (``numpy.array``) of values
b: exploration parameter :math:`\beta`, or inverse temperature
[Daw2009], or :math:`1/t`; see below
Returns:
... | [
"r",
"Standard",
"softmax",
"function",
":"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_numpy.py#L48-L95 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_numpy.py | logistic | def logistic(x: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Standard logistic function.
.. math::
y = \frac {1} {1 + e^{-k (x - \theta)}}
Args:
x: :math:`x`
k: :math:`k`
theta: :math:`\theta`
Returns:
... | python | def logistic(x: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Standard logistic function.
.. math::
y = \frac {1} {1 + e^{-k (x - \theta)}}
Args:
x: :math:`x`
k: :math:`k`
theta: :math:`\theta`
Returns:
... | [
"def",
"logistic",
"(",
"x",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"k",
":",
"float",
",",
"theta",
":",
"float",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"# https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbo... | r"""
Standard logistic function.
.. math::
y = \frac {1} {1 + e^{-k (x - \theta)}}
Args:
x: :math:`x`
k: :math:`k`
theta: :math:`\theta`
Returns:
:math:`y` | [
"r",
"Standard",
"logistic",
"function",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_numpy.py#L102-L125 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_numpy.py | inv_logistic | def inv_logistic(y: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\t... | python | def inv_logistic(y: Union[float, np.ndarray],
k: float,
theta: float) -> Optional[float]:
r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\t... | [
"def",
"inv_logistic",
"(",
"y",
":",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
",",
"k",
":",
"float",
",",
"theta",
":",
"float",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"if",
"y",
"is",
"None",
"or",
"k",
"is",
"None",
"o... | r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\theta`
Returns:
:math:`x` | [
"r",
"Inverse",
"standard",
"logistic",
"function",
":"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_numpy.py#L128-L150 |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | SpatialLookup.get_object | def get_object(self, point, buffer_size=0, multiple=False):
""" lookup object based on point as [longitude, latitude] """
# first search bounding boxes
# idx.intersection method modifies input if it is a list
try:
tmp = tuple(point)
except TypeError:
retur... | python | def get_object(self, point, buffer_size=0, multiple=False):
""" lookup object based on point as [longitude, latitude] """
# first search bounding boxes
# idx.intersection method modifies input if it is a list
try:
tmp = tuple(point)
except TypeError:
retur... | [
"def",
"get_object",
"(",
"self",
",",
"point",
",",
"buffer_size",
"=",
"0",
",",
"multiple",
"=",
"False",
")",
":",
"# first search bounding boxes",
"# idx.intersection method modifies input if it is a list",
"try",
":",
"tmp",
"=",
"tuple",
"(",
"point",
")",
... | lookup object based on point as [longitude, latitude] | [
"lookup",
"object",
"based",
"on",
"point",
"as",
"[",
"longitude",
"latitude",
"]"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L83-L101 |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | SpatialLookup._build_from_geojson | def _build_from_geojson(self, src):
""" Build a RTree index to disk using bounding box of each feature """
geojson = json.loads(self.read(src))
idx = index.Index()
data_store = {}
for i, feature in enumerate(geojson['features']):
feature = self._build_obj(feature)
... | python | def _build_from_geojson(self, src):
""" Build a RTree index to disk using bounding box of each feature """
geojson = json.loads(self.read(src))
idx = index.Index()
data_store = {}
for i, feature in enumerate(geojson['features']):
feature = self._build_obj(feature)
... | [
"def",
"_build_from_geojson",
"(",
"self",
",",
"src",
")",
":",
"geojson",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"read",
"(",
"src",
")",
")",
"idx",
"=",
"index",
".",
"Index",
"(",
")",
"data_store",
"=",
"{",
"}",
"for",
"i",
",",
"fea... | Build a RTree index to disk using bounding box of each feature | [
"Build",
"a",
"RTree",
"index",
"to",
"disk",
"using",
"bounding",
"box",
"of",
"each",
"feature"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L107-L116 |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | CachedLookup.get | def get(self, point, buffer_size=0, multiple=False):
""" lookup state and county based on geohash of coordinates from tweet """
lon, lat = point
geohash = Geohash.encode(lat, lon, precision=self.precision)
key = (geohash, buffer_size, multiple)
if key in self.geohash_cache:
... | python | def get(self, point, buffer_size=0, multiple=False):
""" lookup state and county based on geohash of coordinates from tweet """
lon, lat = point
geohash = Geohash.encode(lat, lon, precision=self.precision)
key = (geohash, buffer_size, multiple)
if key in self.geohash_cache:
... | [
"def",
"get",
"(",
"self",
",",
"point",
",",
"buffer_size",
"=",
"0",
",",
"multiple",
"=",
"False",
")",
":",
"lon",
",",
"lat",
"=",
"point",
"geohash",
"=",
"Geohash",
".",
"encode",
"(",
"lat",
",",
"lon",
",",
"precision",
"=",
"self",
".",
... | lookup state and county based on geohash of coordinates from tweet | [
"lookup",
"state",
"and",
"county",
"based",
"on",
"geohash",
"of",
"coordinates",
"from",
"tweet"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L139-L157 |
KarrLab/nose2unitth | nose2unitth/core.py | Converter.run | def run(in_file_nose, out_dir_unitth):
""" Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files
Args:
in_file_nose (:obj:`str`): path to nose-style test report
out_file_unitth (:obj:`str`): path to save UnitTH-style test repor... | python | def run(in_file_nose, out_dir_unitth):
""" Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files
Args:
in_file_nose (:obj:`str`): path to nose-style test report
out_file_unitth (:obj:`str`): path to save UnitTH-style test repor... | [
"def",
"run",
"(",
"in_file_nose",
",",
"out_dir_unitth",
")",
":",
"suites",
"=",
"Converter",
".",
"read_nose",
"(",
"in_file_nose",
")",
"Converter",
".",
"write_unitth",
"(",
"suites",
",",
"out_dir_unitth",
")"
] | Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files
Args:
in_file_nose (:obj:`str`): path to nose-style test report
out_file_unitth (:obj:`str`): path to save UnitTH-style test reports | [
"Convert",
"nose",
"-",
"style",
"test",
"reports",
"to",
"UnitTH",
"-",
"style",
"test",
"reports",
"by",
"splitting",
"modules",
"into",
"separate",
"XML",
"files"
] | train | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L18-L26 |
KarrLab/nose2unitth | nose2unitth/core.py | Converter.read_nose | def read_nose(in_file):
""" Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`): path to nose-style test report
Returns:
:obj:`dict`: dictionary of test suites
"""
suites = {}
doc_xml = minidom.parse(in_file)
suite_xml ... | python | def read_nose(in_file):
""" Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`): path to nose-style test report
Returns:
:obj:`dict`: dictionary of test suites
"""
suites = {}
doc_xml = minidom.parse(in_file)
suite_xml ... | [
"def",
"read_nose",
"(",
"in_file",
")",
":",
"suites",
"=",
"{",
"}",
"doc_xml",
"=",
"minidom",
".",
"parse",
"(",
"in_file",
")",
"suite_xml",
"=",
"doc_xml",
".",
"getElementsByTagName",
"(",
"\"testsuite\"",
")",
"[",
"0",
"]",
"for",
"case_xml",
"i... | Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`): path to nose-style test report
Returns:
:obj:`dict`: dictionary of test suites | [
"Parse",
"nose",
"-",
"style",
"test",
"reports",
"into",
"a",
"dict"
] | train | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L29-L88 |
KarrLab/nose2unitth | nose2unitth/core.py | Converter.write_unitth | def write_unitth(suites, out_dir):
""" Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
"""
if not os.path.isdir(out_dir):
os.mkdir(out_dir)
fo... | python | def write_unitth(suites, out_dir):
""" Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
"""
if not os.path.isdir(out_dir):
os.mkdir(out_dir)
fo... | [
"def",
"write_unitth",
"(",
"suites",
",",
"out_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"out_dir",
")",
":",
"os",
".",
"mkdir",
"(",
"out_dir",
")",
"for",
"classname",
",",
"cases",
"in",
"suites",
".",
"items",
"(",
")... | Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports | [
"Write",
"UnitTH",
"-",
"style",
"test",
"reports"
] | train | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L91-L149 |
davenquinn/Attitude | attitude/display/plot/__init__.py | error_asymptotes | def error_asymptotes(pca,**kwargs):
"""
Plots asymptotic error bounds for
hyperbola on a stereonet.
"""
ax = kwargs.pop("ax",current_axes())
lon,lat = pca.plane_errors('upper', n=1000)
ax.plot(lon,lat,'-')
lon,lat = pca.plane_errors('lower', n=1000)
ax.plot(lon,lat,'-')
ax.pla... | python | def error_asymptotes(pca,**kwargs):
"""
Plots asymptotic error bounds for
hyperbola on a stereonet.
"""
ax = kwargs.pop("ax",current_axes())
lon,lat = pca.plane_errors('upper', n=1000)
ax.plot(lon,lat,'-')
lon,lat = pca.plane_errors('lower', n=1000)
ax.plot(lon,lat,'-')
ax.pla... | [
"def",
"error_asymptotes",
"(",
"pca",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"kwargs",
".",
"pop",
"(",
"\"ax\"",
",",
"current_axes",
"(",
")",
")",
"lon",
",",
"lat",
"=",
"pca",
".",
"plane_errors",
"(",
"'upper'",
",",
"n",
"=",
"1000",... | Plots asymptotic error bounds for
hyperbola on a stereonet. | [
"Plots",
"asymptotic",
"error",
"bounds",
"for",
"hyperbola",
"on",
"a",
"stereonet",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/__init__.py#L150-L163 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/core_query.py | get_rows_fieldnames_from_raw_sql | def get_rows_fieldnames_from_raw_sql(
session: Union[Session, Engine, Connection],
sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""
Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Conne... | python | def get_rows_fieldnames_from_raw_sql(
session: Union[Session, Engine, Connection],
sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""
Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Conne... | [
"def",
"get_rows_fieldnames_from_raw_sql",
"(",
"session",
":",
"Union",
"[",
"Session",
",",
"Engine",
",",
"Connection",
"]",
",",
"sql",
":",
"str",
")",
"->",
"Tuple",
"[",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
",",
"Sequence",
"[",
"str... | Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
sql: raw SQL to execure
Returns:
``(rows, fieldnames)`` where ``rows`` is the usual set of results and
``fieldnames`` are the na... | [
"Returns",
"results",
"and",
"column",
"names",
"from",
"a",
"query",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L51-L70 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/core_query.py | count_star | def count_star(session: Union[Session, Engine, Connection],
tablename: str,
*criteria: Any) -> int:
"""
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`... | python | def count_star(session: Union[Session, Engine, Connection],
tablename: str,
*criteria: Any) -> int:
"""
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`... | [
"def",
"count_star",
"(",
"session",
":",
"Union",
"[",
"Session",
",",
"Engine",
",",
"Connection",
"]",
",",
"tablename",
":",
"str",
",",
"*",
"criteria",
":",
"Any",
")",
"->",
"int",
":",
"# works if you pass a connection or a session or an engine; all have",... | Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy "where" criteria... | [
"Returns",
"the",
"result",
"of",
"COUNT",
"(",
"*",
")",
"from",
"the",
"specified",
"table",
"(",
"with",
"additional",
"WHERE",
"criteria",
"if",
"desired",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L78-L99 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/core_query.py | exists_in_table | def exists_in_table(session: Session, table_: Table, *criteria: Any) -> bool:
"""
Implements an efficient way of detecting if a record or records exist;
should be faster than ``COUNT(*)`` in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`... | python | def exists_in_table(session: Session, table_: Table, *criteria: Any) -> bool:
"""
Implements an efficient way of detecting if a record or records exist;
should be faster than ``COUNT(*)`` in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`... | [
"def",
"exists_in_table",
"(",
"session",
":",
"Session",
",",
"table_",
":",
"Table",
",",
"*",
"criteria",
":",
"Any",
")",
"->",
"bool",
":",
"exists_clause",
"=",
"exists",
"(",
")",
".",
"select_from",
"(",
"table_",
")",
"# ... EXISTS (SELECT * FROM ta... | Implements an efficient way of detecting if a record or records exist;
should be faster than ``COUNT(*)`` in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
table_: SQLAlchemy :class:`Table` object
criteria: opti... | [
"Implements",
"an",
"efficient",
"way",
"of",
"detecting",
"if",
"a",
"record",
"or",
"records",
"exist",
";",
"should",
"be",
"faster",
"than",
"COUNT",
"(",
"*",
")",
"in",
"some",
"circumstances",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L139-L176 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/core_query.py | exists_plain | def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool:
"""
Implements an efficient way of detecting if a record or records exist;
should be faster than COUNT(*) in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connec... | python | def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool:
"""
Implements an efficient way of detecting if a record or records exist;
should be faster than COUNT(*) in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connec... | [
"def",
"exists_plain",
"(",
"session",
":",
"Session",
",",
"tablename",
":",
"str",
",",
"*",
"criteria",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"exists_in_table",
"(",
"session",
",",
"table",
"(",
"tablename",
")",
",",
"*",
"criteria",
")"
] | Implements an efficient way of detecting if a record or records exist;
should be faster than COUNT(*) in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy ... | [
"Implements",
"an",
"efficient",
"way",
"of",
"detecting",
"if",
"a",
"record",
"or",
"records",
"exist",
";",
"should",
"be",
"faster",
"than",
"COUNT",
"(",
"*",
")",
"in",
"some",
"circumstances",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L179-L202 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/core_query.py | fetch_all_first_values | def fetch_all_first_values(session: Session,
select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
... | python | def fetch_all_first_values(session: Session,
select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
... | [
"def",
"fetch_all_first_values",
"(",
"session",
":",
"Session",
",",
"select_statement",
":",
"Select",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"rows",
"=",
"session",
".",
"execute",
"(",
"select_statement",
")",
"# type: ResultProxy",
"try",
":",
"return",... | Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
session: SQLAlchemy :class:`Session` object
select_statement: SQLAlchemy :class:`Select` object
Returns:... | [
"Returns",
"a",
"list",
"of",
"the",
"first",
"values",
"in",
"each",
"row",
"returned",
"by",
"a",
"SELECT",
"query",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L209-L230 |
davenquinn/Attitude | attitude/display/parametric.py | hyperbola | def hyperbola(axes, **kwargs):
"""
Plots a hyperbola that opens along y axis
"""
opens_up = kwargs.pop('opens_up', True)
center = kwargs.pop('center', defaults['center'])
th = N.linspace(0,2*N.pi,kwargs.pop('n', 500))
vals = [N.tan(th),1/N.cos(th)]
if not opens_up:
vals = vals[:... | python | def hyperbola(axes, **kwargs):
"""
Plots a hyperbola that opens along y axis
"""
opens_up = kwargs.pop('opens_up', True)
center = kwargs.pop('center', defaults['center'])
th = N.linspace(0,2*N.pi,kwargs.pop('n', 500))
vals = [N.tan(th),1/N.cos(th)]
if not opens_up:
vals = vals[:... | [
"def",
"hyperbola",
"(",
"axes",
",",
"*",
"*",
"kwargs",
")",
":",
"opens_up",
"=",
"kwargs",
".",
"pop",
"(",
"'opens_up'",
",",
"True",
")",
"center",
"=",
"kwargs",
".",
"pop",
"(",
"'center'",
",",
"defaults",
"[",
"'center'",
"]",
")",
"th",
... | Plots a hyperbola that opens along y axis | [
"Plots",
"a",
"hyperbola",
"that",
"opens",
"along",
"y",
"axis"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/parametric.py#L18-L41 |
davenquinn/Attitude | attitude/display/parametric.py | __reverse_ellipse | def __reverse_ellipse(axes, scalar=1):
"""
This method doesn't work as well
"""
ax1 = axes.copy()[::-1]*scalar
center = ax1[1]*N.sqrt(2)*scalar
return ax1, center | python | def __reverse_ellipse(axes, scalar=1):
"""
This method doesn't work as well
"""
ax1 = axes.copy()[::-1]*scalar
center = ax1[1]*N.sqrt(2)*scalar
return ax1, center | [
"def",
"__reverse_ellipse",
"(",
"axes",
",",
"scalar",
"=",
"1",
")",
":",
"ax1",
"=",
"axes",
".",
"copy",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
"*",
"scalar",
"center",
"=",
"ax1",
"[",
"1",
"]",
"*",
"N",
".",
"sqrt",
"(",
"2",
")",
"... | This method doesn't work as well | [
"This",
"method",
"doesn",
"t",
"work",
"as",
"well"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/parametric.py#L63-L69 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/sqlserver.py | if_sqlserver_disable_constraints | def if_sqlserver_disable_constraints(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable constraint checking for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tabl... | python | def if_sqlserver_disable_constraints(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable constraint checking for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tabl... | [
"def",
"if_sqlserver_disable_constraints",
"(",
"session",
":",
"SqlASession",
",",
"tablename",
":",
"str",
")",
"->",
"None",
":",
"# noqa",
"engine",
"=",
"get_engine_from_session",
"(",
"session",
")",
"if",
"is_sqlserver",
"(",
"engine",
")",
":",
"quoted_t... | If we're running under SQL Server, disable constraint checking for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tablename: table name
See
https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger | [
"If",
"we",
"re",
"running",
"under",
"SQL",
"Server",
"disable",
"constraint",
"checking",
"for",
"the",
"specified",
"table",
"while",
"the",
"resource",
"is",
"held",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlserver.py#L43-L67 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/sqlserver.py | if_sqlserver_disable_constraints_triggers | def if_sqlserver_disable_constraints_triggers(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable triggers AND constraints for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class... | python | def if_sqlserver_disable_constraints_triggers(session: SqlASession,
tablename: str) -> None:
"""
If we're running under SQL Server, disable triggers AND constraints for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class... | [
"def",
"if_sqlserver_disable_constraints_triggers",
"(",
"session",
":",
"SqlASession",
",",
"tablename",
":",
"str",
")",
"->",
"None",
":",
"with",
"if_sqlserver_disable_constraints",
"(",
"session",
",",
"tablename",
")",
":",
"with",
"if_sqlserver_disable_triggers",... | If we're running under SQL Server, disable triggers AND constraints for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tablename: table name | [
"If",
"we",
"re",
"running",
"under",
"SQL",
"Server",
"disable",
"triggers",
"AND",
"constraints",
"for",
"the",
"specified",
"table",
"while",
"the",
"resource",
"is",
"held",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlserver.py#L97-L109 |
avihad/twistes | twistes/bulk_utils.py | ActionParser.expand_action | def expand_action(data):
"""
From one document or action definition passed in by the user extract the
action/data lines needed for elasticsearch's
:meth:`~elasticsearch.Elasticsearch.bulk` api.
:return es format to bulk doc
"""
# when given a string, assume user w... | python | def expand_action(data):
"""
From one document or action definition passed in by the user extract the
action/data lines needed for elasticsearch's
:meth:`~elasticsearch.Elasticsearch.bulk` api.
:return es format to bulk doc
"""
# when given a string, assume user w... | [
"def",
"expand_action",
"(",
"data",
")",
":",
"# when given a string, assume user wants to index raw json",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"return",
"'{\"index\": {}}'",
",",
"data",
"# make sure we don't alter the action",
"data",
"=",
"... | From one document or action definition passed in by the user extract the
action/data lines needed for elasticsearch's
:meth:`~elasticsearch.Elasticsearch.bulk` api.
:return es format to bulk doc | [
"From",
"one",
"document",
"or",
"action",
"definition",
"passed",
"in",
"by",
"the",
"user",
"extract",
"the",
"action",
"/",
"data",
"lines",
"needed",
"for",
"elasticsearch",
"s",
":",
"meth",
":",
"~elasticsearch",
".",
"Elasticsearch",
".",
"bulk",
"api... | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/bulk_utils.py#L17-L38 |
avihad/twistes | twistes/bulk_utils.py | BulkUtility.bulk | def bulk(self, actions, stats_only=False, verbose=False, **kwargs):
"""
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides
a more human friendly interface - it consumes an iterator of actions and
sends them to elasticsearch in chunks. It returns a tuple with summa... | python | def bulk(self, actions, stats_only=False, verbose=False, **kwargs):
"""
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides
a more human friendly interface - it consumes an iterator of actions and
sends them to elasticsearch in chunks. It returns a tuple with summa... | [
"def",
"bulk",
"(",
"self",
",",
"actions",
",",
"stats_only",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"inserted",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"all",
"=",
"[",
"]",
"for",
"deferred_bulk",
"in",
... | Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides
a more human friendly interface - it consumes an iterator of actions and
sends them to elasticsearch in chunks. It returns a tuple with summary
information - number of successfully executed actions and either list of
... | [
"Helper",
"for",
"the",
":",
"meth",
":",
"~elasticsearch",
".",
"Elasticsearch",
".",
"bulk",
"api",
"that",
"provides",
"a",
"more",
"human",
"friendly",
"interface",
"-",
"it",
"consumes",
"an",
"iterator",
"of",
"actions",
"and",
"sends",
"them",
"to",
... | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/bulk_utils.py#L56-L92 |
avihad/twistes | twistes/bulk_utils.py | BulkUtility.streaming_bulk | def streaming_bulk(self, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024,
raise_on_error=True, expand_action_callback=ActionParser.expand_action,
raise_on_exception=True, **kwargs):
"""
Streaming bulk consumes actions from the iterable passed in a... | python | def streaming_bulk(self, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024,
raise_on_error=True, expand_action_callback=ActionParser.expand_action,
raise_on_exception=True, **kwargs):
"""
Streaming bulk consumes actions from the iterable passed in a... | [
"def",
"streaming_bulk",
"(",
"self",
",",
"actions",
",",
"chunk_size",
"=",
"500",
",",
"max_chunk_bytes",
"=",
"100",
"*",
"1024",
"*",
"1024",
",",
"raise_on_error",
"=",
"True",
",",
"expand_action_callback",
"=",
"ActionParser",
".",
"expand_action",
","... | Streaming bulk consumes actions from the iterable passed in and return the results of all bulk data
:func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming
bulk that returns summary information about the bulk operation once the
entire input is consumed and sent.
:arg acti... | [
"Streaming",
"bulk",
"consumes",
"actions",
"from",
"the",
"iterable",
"passed",
"in",
"and",
"return",
"the",
"results",
"of",
"all",
"bulk",
"data",
":",
"func",
":",
"~elasticsearch",
".",
"helpers",
".",
"bulk",
"which",
"is",
"a",
"wrapper",
"around",
... | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/bulk_utils.py#L94-L116 |
avihad/twistes | twistes/bulk_utils.py | BulkUtility._process_bulk_chunk | def _process_bulk_chunk(self, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors per chunk before
# raising them
resp = None
... | python | def _process_bulk_chunk(self, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors per chunk before
# raising them
resp = None
... | [
"def",
"_process_bulk_chunk",
"(",
"self",
",",
"bulk_actions",
",",
"raise_on_exception",
"=",
"True",
",",
"raise_on_error",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# if raise on error is set, we need to collect errors per chunk before",
"# raising them",
"resp... | Send a bulk request to elasticsearch and process the output. | [
"Send",
"a",
"bulk",
"request",
"to",
"elasticsearch",
"and",
"process",
"the",
"output",
"."
] | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/bulk_utils.py#L151-L188 |
oursky/norecaptcha | norecaptcha/captcha.py | displayhtml | def displayhtml(site_key,
language='',
theme='light',
fallback=False,
d_type='image',
size='normal'):
"""
Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
the... | python | def displayhtml(site_key,
language='',
theme='light',
fallback=False,
d_type='image',
size='normal'):
"""
Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
the... | [
"def",
"displayhtml",
"(",
"site_key",
",",
"language",
"=",
"''",
",",
"theme",
"=",
"'light'",
",",
"fallback",
"=",
"False",
",",
"d_type",
"=",
"'image'",
",",
"size",
"=",
"'normal'",
")",
":",
"return",
"\"\"\"\n<script\n src=\"https://www.google.com/reca... | Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
theme -- The color theme of the widget. `light` or `dark`
fallback -- Old version recaptcha.
d_type -- The type of CAPTCHA to serve. `image` or `audio`
size -- The size of the dispalyed... | [
"Gets",
"the",
"HTML",
"to",
"display",
"for",
"reCAPTCHA"
] | train | https://github.com/oursky/norecaptcha/blob/6323054bf42c1bf35c5d7a7def4729cb32518860/norecaptcha/captcha.py#L33-L95 |
oursky/norecaptcha | norecaptcha/captcha.py | submit | def submit(recaptcha_response_field,
secret_key,
remoteip,
verify_server=VERIFY_SERVER):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value from the form
secret_key -- your reCAPTCHA secr... | python | def submit(recaptcha_response_field,
secret_key,
remoteip,
verify_server=VERIFY_SERVER):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value from the form
secret_key -- your reCAPTCHA secr... | [
"def",
"submit",
"(",
"recaptcha_response_field",
",",
"secret_key",
",",
"remoteip",
",",
"verify_server",
"=",
"VERIFY_SERVER",
")",
":",
"if",
"not",
"(",
"recaptcha_response_field",
"and",
"len",
"(",
"recaptcha_response_field",
")",
")",
":",
"return",
"Recap... | Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value from the form
secret_key -- your reCAPTCHA secret key
remoteip -- the user's ip address | [
"Submits",
"a",
"reCAPTCHA",
"request",
"for",
"verification",
".",
"Returns",
"RecaptchaResponse",
"for",
"the",
"request"
] | train | https://github.com/oursky/norecaptcha/blob/6323054bf42c1bf35c5d7a7def4729cb32518860/norecaptcha/captcha.py#L98-L151 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | get_head_revision_from_alembic | def get_head_revision_from_alembic(
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
... | python | def get_head_revision_from_alembic(
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
... | [
"def",
"get_head_revision_from_alembic",
"(",
"alembic_config_filename",
":",
"str",
",",
"alembic_base_dir",
":",
"str",
"=",
"None",
",",
"version_table",
":",
"str",
"=",
"DEFAULT_ALEMBIC_VERSION_TABLE",
")",
"->",
"str",
":",
"if",
"alembic_base_dir",
"is",
"Non... | Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative paths in the
config file work.
version_table: table name for Alembic ... | [
"Ask",
"Alembic",
"what",
"its",
"head",
"revision",
"is",
"(",
"i",
".",
"e",
".",
"where",
"the",
"Python",
"code",
"would",
"like",
"the",
"database",
"to",
"be",
"at",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L71-L93 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | get_current_revision | def get_current_revision(
database_url: str,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions
"""
eng... | python | def get_current_revision(
database_url: str,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions
"""
eng... | [
"def",
"get_current_revision",
"(",
"database_url",
":",
"str",
",",
"version_table",
":",
"str",
"=",
"DEFAULT_ALEMBIC_VERSION_TABLE",
")",
"->",
"str",
":",
"engine",
"=",
"create_engine",
"(",
"database_url",
")",
"conn",
"=",
"engine",
".",
"connect",
"(",
... | Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions | [
"Ask",
"the",
"database",
"what",
"its",
"current",
"revision",
"is",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L96-L110 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | get_current_and_head_revision | def get_current_and_head_revision(
database_url: str,
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:
"""
Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revis... | python | def get_current_and_head_revision(
database_url: str,
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:
"""
Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revis... | [
"def",
"get_current_and_head_revision",
"(",
"database_url",
":",
"str",
",",
"alembic_config_filename",
":",
"str",
",",
"alembic_base_dir",
":",
"str",
"=",
"None",
",",
"version_table",
":",
"str",
"=",
"DEFAULT_ALEMBIC_VERSION_TABLE",
")",
"->",
"Tuple",
"[",
... | Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revision` and :func:`get_head_revision_from_alembic`.
Arguments:
database_url: SQLAlchemy URL for the database
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative p... | [
"Returns",
"a",
"tuple",
"of",
"(",
"current_revision",
"head_revision",
")",
";",
"see",
":",
"func",
":",
"get_current_revision",
"and",
":",
"func",
":",
"get_head_revision_from_alembic",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L113-L145 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | upgrade_database | def upgrade_database(
alembic_config_filename: str,
alembic_base_dir: str = None,
starting_revision: str = None,
destination_revision: str = "head",
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,
as_sql: bool = False) -> None:
"""
Use Alembic to upgrade our d... | python | def upgrade_database(
alembic_config_filename: str,
alembic_base_dir: str = None,
starting_revision: str = None,
destination_revision: str = "head",
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,
as_sql: bool = False) -> None:
"""
Use Alembic to upgrade our d... | [
"def",
"upgrade_database",
"(",
"alembic_config_filename",
":",
"str",
",",
"alembic_base_dir",
":",
"str",
"=",
"None",
",",
"starting_revision",
":",
"str",
"=",
"None",
",",
"destination_revision",
":",
"str",
"=",
"\"head\"",
",",
"version_table",
":",
"str"... | Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
alembic_base_dir:
directory to start in, so relative... | [
"Use",
"Alembic",
"to",
"upgrade",
"our",
"database",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L149-L208 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | create_database_migration_numbered_style | def create_database_migration_numbered_style(
alembic_ini_file: str,
alembic_versions_dir: str,
message: str,
n_sequence_chars: int = 4) -> None:
"""
Create a new Alembic migration script.
Alembic compares the **state of the database** to the **state of the
metadata*... | python | def create_database_migration_numbered_style(
alembic_ini_file: str,
alembic_versions_dir: str,
message: str,
n_sequence_chars: int = 4) -> None:
"""
Create a new Alembic migration script.
Alembic compares the **state of the database** to the **state of the
metadata*... | [
"def",
"create_database_migration_numbered_style",
"(",
"alembic_ini_file",
":",
"str",
",",
"alembic_versions_dir",
":",
"str",
",",
"message",
":",
"str",
",",
"n_sequence_chars",
":",
"int",
"=",
"4",
")",
"->",
"None",
":",
"# noqa",
"_",
",",
"_",
",",
... | Create a new Alembic migration script.
Alembic compares the **state of the database** to the **state of the
metadata**, and generates a migration that brings the former up to the
latter. (It does **not** compare the most recent revision to the current
metadata, so make sure your database is up to d... | [
"Create",
"a",
"new",
"Alembic",
"migration",
"script",
".",
"Alembic",
"compares",
"the",
"**",
"state",
"of",
"the",
"database",
"**",
"to",
"the",
"**",
"state",
"of",
"the",
"metadata",
"**",
"and",
"generates",
"a",
"migration",
"that",
"brings",
"the... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L275-L366 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | stamp_allowing_unusual_version_table | def stamp_allowing_unusual_version_table(
config: Config,
revision: str,
sql: bool = False,
tag: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
"""
Stamps the Alembic version table with the given revision; don't run any
migrations.
This ... | python | def stamp_allowing_unusual_version_table(
config: Config,
revision: str,
sql: bool = False,
tag: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None:
"""
Stamps the Alembic version table with the given revision; don't run any
migrations.
This ... | [
"def",
"stamp_allowing_unusual_version_table",
"(",
"config",
":",
"Config",
",",
"revision",
":",
"str",
",",
"sql",
":",
"bool",
"=",
"False",
",",
"tag",
":",
"str",
"=",
"None",
",",
"version_table",
":",
"str",
"=",
"DEFAULT_ALEMBIC_VERSION_TABLE",
")",
... | Stamps the Alembic version table with the given revision; don't run any
migrations.
This function is a clone of ``alembic.command.stamp()``, but allowing
``version_table`` to change. See
http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp | [
"Stamps",
"the",
"Alembic",
"version",
"table",
"with",
"the",
"given",
"revision",
";",
"don",
"t",
"run",
"any",
"migrations",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L369-L405 |
ivanprjcts/sdklib | sdklib/behave/requests.py | set_url_path_with_params | def set_url_path_with_params(context, url_path_str_format):
"""
Parameters:
+------+--------+
| key | value |
+======+========+
| key1 | value1 |
+------+--------+
| key2 | value2 |
+------+--------+
"""
safe_add_http_request_context_to_behave_c... | python | def set_url_path_with_params(context, url_path_str_format):
"""
Parameters:
+------+--------+
| key | value |
+======+========+
| key1 | value1 |
+------+--------+
| key2 | value2 |
+------+--------+
"""
safe_add_http_request_context_to_behave_c... | [
"def",
"set_url_path_with_params",
"(",
"context",
",",
"url_path_str_format",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"table_as_json",
"=",
"dict",
"(",
"context",
".",
"table",
")",
"url_path",
"=",
"url_path_str_format",
"%",... | Parameters:
+------+--------+
| key | value |
+======+========+
| key1 | value1 |
+------+--------+
| key2 | value2 |
+------+--------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L46-L61 |
ivanprjcts/sdklib | sdklib/behave/requests.py | set_headers | def set_headers(context):
"""
Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------... | python | def set_headers(context):
"""
Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------... | [
"def",
"set_headers",
"(",
"context",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"headers",
"=",
"dict",
"(",
")",
"for",
"row",
"in",
"context",
".",
"table",
":",
"headers",
"[",
"row",
"[",
"\"header_name\"",
"]",
"]",... | Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------+---------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L77-L93 |
ivanprjcts/sdklib | sdklib/behave/requests.py | set_form_parameters | def set_form_parameters(context):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+----... | python | def set_form_parameters(context):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+----... | [
"def",
"set_form_parameters",
"(",
"context",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"context",
".",
"http_request_context",
".",
"body_params",
"=",
"get_parameters",
"(",
"context",
")",
"context",
".",
"http_request_context",
... | Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L131-L145 |
ivanprjcts/sdklib | sdklib/behave/requests.py | set_body_files | def set_body_files(context):
"""
Parameters:
+-------------+--------------+
| param_name | path_to_file |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+---------... | python | def set_body_files(context):
"""
Parameters:
+-------------+--------------+
| param_name | path_to_file |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+---------... | [
"def",
"set_body_files",
"(",
"context",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"files",
"=",
"dict",
"(",
")",
"for",
"row",
"in",
"context",
".",
"table",
":",
"files",
"[",
"row",
"[",
"\"param_name\"",
"]",
"]",
... | Parameters:
+-------------+--------------+
| param_name | path_to_file |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L159-L175 |
ivanprjcts/sdklib | sdklib/behave/requests.py | send_http_request_with_query_parameters | def send_http_request_with_query_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |... | python | def send_http_request_with_query_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |... | [
"def",
"send_http_request_with_query_parameters",
"(",
"context",
",",
"method",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"set_query_parameters",
"(",
"context",
")",
"send_http_request",
"(",
"context",
",",
"method",
")"
] | Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L197-L211 |
ivanprjcts/sdklib | sdklib/behave/requests.py | send_http_request_with_body_parameters | def send_http_request_with_body_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | python | def send_http_request_with_body_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | [
"def",
"send_http_request_with_body_parameters",
"(",
"context",
",",
"method",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"set_body_parameters",
"(",
"context",
")",
"send_http_request",
"(",
"context",
",",
"method",
")"
] | Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L215-L229 |
ivanprjcts/sdklib | sdklib/behave/requests.py | send_http_request_with_form_parameters | def send_http_request_with_form_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | python | def send_http_request_with_form_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | [
"def",
"send_http_request_with_form_parameters",
"(",
"context",
",",
"method",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"set_form_parameters",
"(",
"context",
")",
"send_http_request",
"(",
"context",
",",
"method",
")"
] | Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+ | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L233-L247 |
ivanprjcts/sdklib | sdklib/behave/requests.py | send_http_request_with_json | def send_http_request_with_json(context, method):
"""
Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
}
"""
safe_add_http_re... | python | def send_http_request_with_json(context, method):
"""
Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
}
"""
safe_add_http_re... | [
"def",
"send_http_request_with_json",
"(",
"context",
",",
"method",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"context",
".",
"http_request_context",
".",
"body_params",
"=",
"json",
".",
"loads",
"(",
"context",
".",
"text",
... | Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
} | [
"Parameters",
":"
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/behave/requests.py#L261-L278 |
RudolfCardinal/pythonlib | cardinal_pythonlib/process.py | get_external_command_output | def get_external_command_output(command: str) -> bytes:
"""
Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes``
"""
args = shlex.split(command)
ret = subprocess.check_... | python | def get_external_command_output(command: str) -> bytes:
"""
Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes``
"""
args = shlex.split(command)
ret = subprocess.check_... | [
"def",
"get_external_command_output",
"(",
"command",
":",
"str",
")",
"->",
"bytes",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"ret",
"=",
"subprocess",
".",
"check_output",
"(",
"args",
")",
"# this needs Python 2.7 or higher",
"return",
... | Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes`` | [
"Takes",
"a",
"command",
"-",
"line",
"command",
"executes",
"it",
"and",
"returns",
"its",
"stdout",
"output",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L46-L60 |
RudolfCardinal/pythonlib | cardinal_pythonlib/process.py | get_pipe_series_output | def get_pipe_series_output(commands: Sequence[str],
stdinput: BinaryIO = None) -> bytes:
"""
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Retur... | python | def get_pipe_series_output(commands: Sequence[str],
stdinput: BinaryIO = None) -> bytes:
"""
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Retur... | [
"def",
"get_pipe_series_output",
"(",
"commands",
":",
"Sequence",
"[",
"str",
"]",
",",
"stdinput",
":",
"BinaryIO",
"=",
"None",
")",
"->",
"bytes",
":",
"# Python arrays indexes are zero-based, i.e. an array is indexed from",
"# 0 to len(array)-1.",
"# The range/xrange c... | Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Returns:
``stdout`` from the end of the pipe | [
"Get",
"the",
"output",
"from",
"a",
"piped",
"series",
"of",
"commands",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L63-L100 |
RudolfCardinal/pythonlib | cardinal_pythonlib/process.py | launch_external_file | def launch_external_file(filename: str, raise_if_fails: bool = False) -> None:
"""
Launches a file using the operating system's standard launcher.
Args:
filename: file to launch
raise_if_fails: raise any exceptions from
``subprocess.call(["xdg-open", filename])`` (Linux)
... | python | def launch_external_file(filename: str, raise_if_fails: bool = False) -> None:
"""
Launches a file using the operating system's standard launcher.
Args:
filename: file to launch
raise_if_fails: raise any exceptions from
``subprocess.call(["xdg-open", filename])`` (Linux)
... | [
"def",
"launch_external_file",
"(",
"filename",
":",
"str",
",",
"raise_if_fails",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"\"Launching external file: {!r}\"",
",",
"filename",
")",
"try",
":",
"if",
"sys",
".",
"platform"... | Launches a file using the operating system's standard launcher.
Args:
filename: file to launch
raise_if_fails: raise any exceptions from
``subprocess.call(["xdg-open", filename])`` (Linux)
or ``os.startfile(filename)`` (otherwise)? If not, exceptions
are suppress... | [
"Launches",
"a",
"file",
"using",
"the",
"operating",
"system",
"s",
"standard",
"launcher",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L110-L136 |
RudolfCardinal/pythonlib | cardinal_pythonlib/process.py | kill_proc_tree | def kill_proc_tree(pid: int,
including_parent: bool = True,
timeout_s: float = 5) \
-> Tuple[Set[psutil.Process], Set[psutil.Process]]:
"""
Kills a tree of processes, starting with the parent. Slightly modified from
https://stackoverflow.com/questions/1230669/su... | python | def kill_proc_tree(pid: int,
including_parent: bool = True,
timeout_s: float = 5) \
-> Tuple[Set[psutil.Process], Set[psutil.Process]]:
"""
Kills a tree of processes, starting with the parent. Slightly modified from
https://stackoverflow.com/questions/1230669/su... | [
"def",
"kill_proc_tree",
"(",
"pid",
":",
"int",
",",
"including_parent",
":",
"bool",
"=",
"True",
",",
"timeout_s",
":",
"float",
"=",
"5",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"psutil",
".",
"Process",
"]",
",",
"Set",
"[",
"psutil",
".",
"Process... | Kills a tree of processes, starting with the parent. Slightly modified from
https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows.
Args:
pid: process ID of the parent
including_parent: kill the parent too?
timeout_s: timeout to wait for processes... | [
"Kills",
"a",
"tree",
"of",
"processes",
"starting",
"with",
"the",
"parent",
".",
"Slightly",
"modified",
"from",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"1230669",
"/",
"subprocess",
"-",
"deleting",
"-",
"child",
"-",
"pr... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L144-L169 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/session.py | make_mysql_url | def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
"""
Makes an SQLAlchemy URL for a MySQL database.
"""
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}... | python | def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
"""
Makes an SQLAlchemy URL for a MySQL database.
"""
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}... | [
"def",
"make_mysql_url",
"(",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"dbname",
":",
"str",
",",
"driver",
":",
"str",
"=",
"\"mysqldb\"",
",",
"host",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"ch... | Makes an SQLAlchemy URL for a MySQL database. | [
"Makes",
"an",
"SQLAlchemy",
"URL",
"for",
"a",
"MySQL",
"database",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L52-L66 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/session.py | make_sqlite_url | def make_sqlite_url(filename: str) -> str:
"""
Makes an SQLAlchemy URL for a SQLite database.
"""
absfile = os.path.abspath(filename)
return "sqlite://{host}/{path}".format(host="", path=absfile) | python | def make_sqlite_url(filename: str) -> str:
"""
Makes an SQLAlchemy URL for a SQLite database.
"""
absfile = os.path.abspath(filename)
return "sqlite://{host}/{path}".format(host="", path=absfile) | [
"def",
"make_sqlite_url",
"(",
"filename",
":",
"str",
")",
"->",
"str",
":",
"absfile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"return",
"\"sqlite://{host}/{path}\"",
".",
"format",
"(",
"host",
"=",
"\"\"",
",",
"path",
"=",
"abs... | Makes an SQLAlchemy URL for a SQLite database. | [
"Makes",
"an",
"SQLAlchemy",
"URL",
"for",
"a",
"SQLite",
"database",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L69-L74 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/session.py | get_engine_from_session | def get_engine_from_session(dbsession: Session) -> Engine:
"""
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
"""
engine = dbsession.bind
assert isinstance(engine, Engine)
return engine | python | def get_engine_from_session(dbsession: Session) -> Engine:
"""
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
"""
engine = dbsession.bind
assert isinstance(engine, Engine)
return engine | [
"def",
"get_engine_from_session",
"(",
"dbsession",
":",
"Session",
")",
"->",
"Engine",
":",
"engine",
"=",
"dbsession",
".",
"bind",
"assert",
"isinstance",
"(",
"engine",
",",
"Engine",
")",
"return",
"engine"
] | Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`. | [
"Gets",
"the",
"SQLAlchemy",
":",
"class",
":",
"Engine",
"from",
"a",
"SQLAlchemy",
":",
"class",
":",
"Session",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L84-L90 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/session.py | get_safe_url_from_engine | def get_safe_url_from_engine(engine: Engine) -> str:
"""
Gets a URL from an :class:`Engine`, obscuring the password.
"""
raw_url = engine.url # type: str
url_obj = make_url(raw_url) # type: URL
return repr(url_obj) | python | def get_safe_url_from_engine(engine: Engine) -> str:
"""
Gets a URL from an :class:`Engine`, obscuring the password.
"""
raw_url = engine.url # type: str
url_obj = make_url(raw_url) # type: URL
return repr(url_obj) | [
"def",
"get_safe_url_from_engine",
"(",
"engine",
":",
"Engine",
")",
"->",
"str",
":",
"raw_url",
"=",
"engine",
".",
"url",
"# type: str",
"url_obj",
"=",
"make_url",
"(",
"raw_url",
")",
"# type: URL",
"return",
"repr",
"(",
"url_obj",
")"
] | Gets a URL from an :class:`Engine`, obscuring the password. | [
"Gets",
"a",
"URL",
"from",
"an",
":",
"class",
":",
"Engine",
"obscuring",
"the",
"password",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L93-L99 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sort.py | atoi | def atoi(text: str) -> Union[int, str]:
"""
Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``.
"""
return int(text) if text.isdigit() else text | python | def atoi(text: str) -> Union[int, str]:
"""
Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``.
"""
return int(text) if text.isdigit() else text | [
"def",
"atoi",
"(",
"text",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"str",
"]",
":",
"return",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text"
] | Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``. | [
"Converts",
"strings",
"to",
"integers",
"if",
"they",
"re",
"composed",
"of",
"digits",
";",
"otherwise",
"returns",
"the",
"strings",
"unchanged",
".",
"One",
"way",
"of",
"sorting",
"strings",
"with",
"numbers",
";",
"it",
"will",
"mean",
"that",
"11",
... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sort.py#L39-L45 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sort.py | natural_keys | def natural_keys(text: str) -> List[Union[int, str]]:
"""
Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
..... | python | def natural_keys(text: str) -> List[Union[int, str]]:
"""
Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
..... | [
"def",
"natural_keys",
"(",
"text",
":",
"str",
")",
"->",
"List",
"[",
"Union",
"[",
"int",
",",
"str",
"]",
"]",
":",
"# noqa",
"return",
"[",
"atoi",
"(",
"c",
")",
"for",
"c",
"in",
"re",
".",
"split",
"(",
"r'(\\d+)'",
",",
"text",
")",
"]... | Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
.. code-block:: python
>>> from cardinal_pythonlib.sort... | [
"Sort",
"key",
"function",
".",
"Returns",
"text",
"split",
"into",
"string",
"/",
"number",
"parts",
"for",
"natural",
"sorting",
";",
"as",
"per",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"5967500",
"/",
"how",
"-",
"to",
... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sort.py#L48-L72 |
ivanprjcts/sdklib | sdklib/util/logger.py | _get_pretty_body | def _get_pretty_body(headers, body):
"""
Return a pretty printed body using the Content-Type header information.
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string)
"""
try:
if CONTENT_TYPE_HEADER_N... | python | def _get_pretty_body(headers, body):
"""
Return a pretty printed body using the Content-Type header information.
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string)
"""
try:
if CONTENT_TYPE_HEADER_N... | [
"def",
"_get_pretty_body",
"(",
"headers",
",",
"body",
")",
":",
"try",
":",
"if",
"CONTENT_TYPE_HEADER_NAME",
"in",
"headers",
":",
"if",
"XMLRenderer",
".",
"DEFAULT_CONTENT_TYPE",
"==",
"headers",
"[",
"CONTENT_TYPE_HEADER_NAME",
"]",
":",
"xml_parsed",
"=",
... | Return a pretty printed body using the Content-Type header information.
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string) | [
"Return",
"a",
"pretty",
"printed",
"body",
"using",
"the",
"Content",
"-",
"Type",
"header",
"information",
"."
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L14-L35 |
ivanprjcts/sdklib | sdklib/util/logger.py | log_print_request | def log_print_request(method, url, query_params=None, headers=None, body=None):
"""
Log an HTTP request data in a user-friendly representation.
:param method: HTTP method
:param url: URL
:param query_params: Query parameters in the URL
:param headers: Headers (dict)
:param body: Body (raw b... | python | def log_print_request(method, url, query_params=None, headers=None, body=None):
"""
Log an HTTP request data in a user-friendly representation.
:param method: HTTP method
:param url: URL
:param query_params: Query parameters in the URL
:param headers: Headers (dict)
:param body: Body (raw b... | [
"def",
"log_print_request",
"(",
"method",
",",
"url",
",",
"query_params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"log_msg",
"=",
"'\\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \\n'",
"log_msg",
"+=",
"'\\t> Method: %s... | Log an HTTP request data in a user-friendly representation.
:param method: HTTP method
:param url: URL
:param query_params: Query parameters in the URL
:param headers: Headers (dict)
:param body: Body (raw body, string)
:return: None | [
"Log",
"an",
"HTTP",
"request",
"data",
"in",
"a",
"user",
"-",
"friendly",
"representation",
"."
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L38-L63 |
ivanprjcts/sdklib | sdklib/util/logger.py | log_print_response | def log_print_response(status_code, response, headers=None):
"""
Log an HTTP response data in a user-friendly representation.
:param status_code: HTTP Status Code
:param response: Raw response content (string)
:param headers: Headers in the response (dict)
:return: None
"""
log_msg = '... | python | def log_print_response(status_code, response, headers=None):
"""
Log an HTTP response data in a user-friendly representation.
:param status_code: HTTP Status Code
:param response: Raw response content (string)
:param headers: Headers in the response (dict)
:return: None
"""
log_msg = '... | [
"def",
"log_print_response",
"(",
"status_code",
",",
"response",
",",
"headers",
"=",
"None",
")",
":",
"log_msg",
"=",
"'\\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\\n'",
"log_msg",
"+=",
"'\\t< Response code: {}\\n'",
".",
"format",
"(",
"str",
"(",
"status... | Log an HTTP response data in a user-friendly representation.
:param status_code: HTTP Status Code
:param response: Raw response content (string)
:param headers: Headers in the response (dict)
:return: None | [
"Log",
"an",
"HTTP",
"response",
"data",
"in",
"a",
"user",
"-",
"friendly",
"representation",
"."
] | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L66-L84 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | args_kwargs_to_initdict | def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict:
"""
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
"""
return {ARGS_LABEL: args,
KWARGS_LABEL: kwargs} | python | def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict:
"""
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
"""
return {ARGS_LABEL: args,
KWARGS_LABEL: kwargs} | [
"def",
"args_kwargs_to_initdict",
"(",
"args",
":",
"ArgsList",
",",
"kwargs",
":",
"KwargsDict",
")",
"->",
"InitDict",
":",
"return",
"{",
"ARGS_LABEL",
":",
"args",
",",
"KWARGS_LABEL",
":",
"kwargs",
"}"
] | Converts a set of ``args`` and ``kwargs`` to an ``InitDict``. | [
"Converts",
"a",
"set",
"of",
"args",
"and",
"kwargs",
"to",
"an",
"InitDict",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L122-L127 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | strip_leading_underscores_from_keys | def strip_leading_underscores_from_keys(d: Dict) -> Dict:
"""
Clones a dictionary, removing leading underscores from key names.
Raises ``ValueError`` if this causes an attribute conflict.
"""
newdict = {}
for k, v in d.items():
if k.startswith('_'):
k = k[1:]
if k... | python | def strip_leading_underscores_from_keys(d: Dict) -> Dict:
"""
Clones a dictionary, removing leading underscores from key names.
Raises ``ValueError`` if this causes an attribute conflict.
"""
newdict = {}
for k, v in d.items():
if k.startswith('_'):
k = k[1:]
if k... | [
"def",
"strip_leading_underscores_from_keys",
"(",
"d",
":",
"Dict",
")",
"->",
"Dict",
":",
"newdict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'_'",
")",
":",
"k",
"=",
"k"... | Clones a dictionary, removing leading underscores from key names.
Raises ``ValueError`` if this causes an attribute conflict. | [
"Clones",
"a",
"dictionary",
"removing",
"leading",
"underscores",
"from",
"key",
"names",
".",
"Raises",
"ValueError",
"if",
"this",
"causes",
"an",
"attribute",
"conflict",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L149-L161 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | verify_initdict | def verify_initdict(initdict: InitDict) -> None:
"""
Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``.
"""
if (not isinstance(initdict, dict) or
ARGS_LABEL not in initdict or
KWARGS_LABEL not in initdict):
raise ValueError("Not an InitDict... | python | def verify_initdict(initdict: InitDict) -> None:
"""
Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``.
"""
if (not isinstance(initdict, dict) or
ARGS_LABEL not in initdict or
KWARGS_LABEL not in initdict):
raise ValueError("Not an InitDict... | [
"def",
"verify_initdict",
"(",
"initdict",
":",
"InitDict",
")",
"->",
"None",
":",
"if",
"(",
"not",
"isinstance",
"(",
"initdict",
",",
"dict",
")",
"or",
"ARGS_LABEL",
"not",
"in",
"initdict",
"or",
"KWARGS_LABEL",
"not",
"in",
"initdict",
")",
":",
"... | Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``. | [
"Ensures",
"that",
"its",
"parameter",
"is",
"a",
"proper",
"InitDict",
"or",
"raises",
"ValueError",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L164-L172 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | initdict_to_instance | def initdict_to_instance(d: InitDict, cls: ClassType) -> Any:
"""
Converse of simple_to_dict().
Given that JSON dictionary, we will end up re-instantiating the class with
.. code-block:: python
d = {'a': 1, 'b': 2, 'c': 3}
new_x = SimpleClass(**d)
We'll also support arbitrary crea... | python | def initdict_to_instance(d: InitDict, cls: ClassType) -> Any:
"""
Converse of simple_to_dict().
Given that JSON dictionary, we will end up re-instantiating the class with
.. code-block:: python
d = {'a': 1, 'b': 2, 'c': 3}
new_x = SimpleClass(**d)
We'll also support arbitrary crea... | [
"def",
"initdict_to_instance",
"(",
"d",
":",
"InitDict",
",",
"cls",
":",
"ClassType",
")",
"->",
"Any",
":",
"args",
"=",
"d",
".",
"get",
"(",
"ARGS_LABEL",
",",
"[",
"]",
")",
"kwargs",
"=",
"d",
".",
"get",
"(",
"KWARGS_LABEL",
",",
"{",
"}",
... | Converse of simple_to_dict().
Given that JSON dictionary, we will end up re-instantiating the class with
.. code-block:: python
d = {'a': 1, 'b': 2, 'c': 3}
new_x = SimpleClass(**d)
We'll also support arbitrary creation, by using both ``*args`` and
``**kwargs``. | [
"Converse",
"of",
"simple_to_dict",
"()",
".",
"Given",
"that",
"JSON",
"dictionary",
"we",
"will",
"end",
"up",
"re",
"-",
"instantiating",
"the",
"class",
"with"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L179-L195 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | wrap_kwargs_to_initdict | def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFnType:
"""
Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``.
"""... | python | def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFnType:
"""
Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``.
"""... | [
"def",
"wrap_kwargs_to_initdict",
"(",
"init_kwargs_fn",
":",
"InitKwargsFnType",
",",
"typename",
":",
"str",
",",
"check_result",
":",
"bool",
"=",
"True",
")",
"->",
"InstanceToInitDictFnType",
":",
"def",
"wrapper",
"(",
"obj",
":",
"Instance",
")",
"->",
... | Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``. | [
"Wraps",
"a",
"function",
"producing",
"a",
"KwargsDict",
"making",
"it",
"into",
"a",
"function",
"producing",
"an",
"InitDict",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L270-L287 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | wrap_args_kwargs_to_initdict | def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFnType:
"""
Wraps a function producing a ``KwargsDict``, making it into a function
producing ... | python | def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFnType:
"""
Wraps a function producing a ``KwargsDict``, making it into a function
producing ... | [
"def",
"wrap_args_kwargs_to_initdict",
"(",
"init_args_kwargs_fn",
":",
"InitArgsKwargsFnType",
",",
"typename",
":",
"str",
",",
"check_result",
":",
"bool",
"=",
"True",
")",
"->",
"InstanceToInitDictFnType",
":",
"def",
"wrapper",
"(",
"obj",
":",
"Instance",
"... | Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``. | [
"Wraps",
"a",
"function",
"producing",
"a",
"KwargsDict",
"making",
"it",
"into",
"a",
"function",
"producing",
"an",
"InitDict",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L290-L310 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | make_instance_to_initdict | def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType:
"""
Returns a function that takes an object (instance) and produces an
``InitDict`` enabling its re-creation.
"""
def custom_instance_to_initdict(x: Instance) -> InitDict:
kwargs = {}
for a in attributes:
... | python | def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType:
"""
Returns a function that takes an object (instance) and produces an
``InitDict`` enabling its re-creation.
"""
def custom_instance_to_initdict(x: Instance) -> InitDict:
kwargs = {}
for a in attributes:
... | [
"def",
"make_instance_to_initdict",
"(",
"attributes",
":",
"List",
"[",
"str",
"]",
")",
"->",
"InstanceToDictFnType",
":",
"def",
"custom_instance_to_initdict",
"(",
"x",
":",
"Instance",
")",
"->",
"InitDict",
":",
"kwargs",
"=",
"{",
"}",
"for",
"a",
"in... | Returns a function that takes an object (instance) and produces an
``InitDict`` enabling its re-creation. | [
"Returns",
"a",
"function",
"that",
"takes",
"an",
"object",
"(",
"instance",
")",
"and",
"produces",
"an",
"InitDict",
"enabling",
"its",
"re",
"-",
"creation",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L317-L328 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | register_class_for_json | def register_class_for_json(
cls: ClassType,
method: str = METHOD_SIMPLE,
obj_to_dict_fn: InstanceToDictFnType = None,
dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance,
default_factory: DefaultFactoryFnType = None) -> None:
"""
Registers the class cls for JSON ... | python | def register_class_for_json(
cls: ClassType,
method: str = METHOD_SIMPLE,
obj_to_dict_fn: InstanceToDictFnType = None,
dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance,
default_factory: DefaultFactoryFnType = None) -> None:
"""
Registers the class cls for JSON ... | [
"def",
"register_class_for_json",
"(",
"cls",
":",
"ClassType",
",",
"method",
":",
"str",
"=",
"METHOD_SIMPLE",
",",
"obj_to_dict_fn",
":",
"InstanceToDictFnType",
"=",
"None",
",",
"dict_to_obj_fn",
":",
"DictToInstanceFnType",
"=",
"initdict_to_instance",
",",
"d... | Registers the class cls for JSON serialization.
- If both ``obj_to_dict_fn`` and dict_to_obj_fn are registered, the
framework uses these to convert instances of the class to/from Python
dictionaries, which are in turn serialized to JSON.
- Otherwise:
.. code-block:: python
if metho... | [
"Registers",
"the",
"class",
"cls",
"for",
"JSON",
"serialization",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L395-L445 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | register_for_json | def register_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that ... | python | def register_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that ... | [
"def",
"register_for_json",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"if",
"DEBUG",
":",
"print",
"(",
"\"register_for_json: args = {}\"",
".",
"format",
"(",
"repr",
"(",
"args",
")",
")",
")",
"print",
"(",
"\"register_for_json: ... | Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that returns an ``(args, kwargs)`` tuple, suitable for passing t... | [
"Class",
"decorator",
"to",
"register",
"classes",
"with",
"our",
"JSON",
"system",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L448-L567 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | dump_map | def dump_map(file: TextIO = sys.stdout) -> None:
"""
Prints the JSON "registered types" map to the specified file.
"""
pp = pprint.PrettyPrinter(indent=4, stream=file)
print("Type map: ", file=file)
pp.pprint(TYPE_MAP) | python | def dump_map(file: TextIO = sys.stdout) -> None:
"""
Prints the JSON "registered types" map to the specified file.
"""
pp = pprint.PrettyPrinter(indent=4, stream=file)
print("Type map: ", file=file)
pp.pprint(TYPE_MAP) | [
"def",
"dump_map",
"(",
"file",
":",
"TextIO",
"=",
"sys",
".",
"stdout",
")",
"->",
"None",
":",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"4",
",",
"stream",
"=",
"file",
")",
"print",
"(",
"\"Type map: \"",
",",
"file",
"=",
... | Prints the JSON "registered types" map to the specified file. | [
"Prints",
"the",
"JSON",
"registered",
"types",
"map",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L570-L576 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | json_class_decoder_hook | def json_class_decoder_hook(d: Dict) -> Any:
"""
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``.
"""
if TYPE_LABEL in d:
typename = d.get(TYPE_LABEL)
if typename in TYPE_MAP:
if DEBUG:
... | python | def json_class_decoder_hook(d: Dict) -> Any:
"""
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``.
"""
if TYPE_LABEL in d:
typename = d.get(TYPE_LABEL)
if typename in TYPE_MAP:
if DEBUG:
... | [
"def",
"json_class_decoder_hook",
"(",
"d",
":",
"Dict",
")",
"->",
"Any",
":",
"if",
"TYPE_LABEL",
"in",
"d",
":",
"typename",
"=",
"d",
".",
"get",
"(",
"TYPE_LABEL",
")",
"if",
"typename",
"in",
"TYPE_MAP",
":",
"if",
"DEBUG",
":",
"log",
".",
"de... | Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``. | [
"Provides",
"a",
"JSON",
"decoder",
"that",
"converts",
"dictionaries",
"to",
"Python",
"objects",
"if",
"suitable",
"methods",
"are",
"found",
"in",
"our",
"TYPE_MAP",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L603-L619 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | json_encode | def json_encode(obj: Instance, **kwargs) -> str:
"""
Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``, for
formatting.
"""
return json.dumps(obj, cls=JsonClassEncoder, **kwargs) | python | def json_encode(obj: Instance, **kwargs) -> str:
"""
Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``, for
formatting.
"""
return json.dumps(obj, cls=JsonClassEncoder, **kwargs) | [
"def",
"json_encode",
"(",
"obj",
":",
"Instance",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"cls",
"=",
"JsonClassEncoder",
",",
"*",
"*",
"kwargs",
")"
] | Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``, for
formatting. | [
"Encodes",
"an",
"object",
"to",
"JSON",
"using",
"our",
"custom",
"encoder",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L626-L633 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | json_decode | def json_decode(s: str) -> Any:
"""
Decodes an object from JSON using our custom decoder.
"""
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)
except json.JSONDecodeError:
log.warning("Failed to decode JSON (returning None): {!r}", s)
return None | python | def json_decode(s: str) -> Any:
"""
Decodes an object from JSON using our custom decoder.
"""
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)
except json.JSONDecodeError:
log.warning("Failed to decode JSON (returning None): {!r}", s)
return None | [
"def",
"json_decode",
"(",
"s",
":",
"str",
")",
"->",
"Any",
":",
"try",
":",
"return",
"json",
".",
"JSONDecoder",
"(",
"object_hook",
"=",
"json_class_decoder_hook",
")",
".",
"decode",
"(",
"s",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"lo... | Decodes an object from JSON using our custom decoder. | [
"Decodes",
"an",
"object",
"from",
"JSON",
"using",
"our",
"custom",
"decoder",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L636-L644 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | dict_to_enum_fn | def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
"""
Converts an ``dict`` to a ``Enum``.
"""
return enum_class[d['name']] | python | def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
"""
Converts an ``dict`` to a ``Enum``.
"""
return enum_class[d['name']] | [
"def",
"dict_to_enum_fn",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"enum_class",
":",
"Type",
"[",
"Enum",
"]",
")",
"->",
"Enum",
":",
"return",
"enum_class",
"[",
"d",
"[",
"'name'",
"]",
"]"
] | Converts an ``dict`` to a ``Enum``. | [
"Converts",
"an",
"dict",
"to",
"a",
"Enum",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L702-L706 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | register_enum_for_json | def register_enum_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register ``Enum``-derived classes with our JSON system.
See comments/help for ``@register_for_json``, above.
"""
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# called as @register_enum_for_json
... | python | def register_enum_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register ``Enum``-derived classes with our JSON system.
See comments/help for ``@register_for_json``, above.
"""
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# called as @register_enum_for_json
... | [
"def",
"register_enum_for_json",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwargs",
")",
"==",
"0",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"... | Class decorator to register ``Enum``-derived classes with our JSON system.
See comments/help for ``@register_for_json``, above. | [
"Class",
"decorator",
"to",
"register",
"Enum",
"-",
"derived",
"classes",
"with",
"our",
"JSON",
"system",
".",
"See",
"comments",
"/",
"help",
"for"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L709-L726 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | dict_to_pendulum | def dict_to_pendulum(d: Dict[str, Any],
pendulum_class: ClassType) -> DateTime:
"""
Converts a ``dict`` object back to a ``Pendulum``.
"""
return pendulum.parse(d['iso']) | python | def dict_to_pendulum(d: Dict[str, Any],
pendulum_class: ClassType) -> DateTime:
"""
Converts a ``dict`` object back to a ``Pendulum``.
"""
return pendulum.parse(d['iso']) | [
"def",
"dict_to_pendulum",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"pendulum_class",
":",
"ClassType",
")",
"->",
"DateTime",
":",
"return",
"pendulum",
".",
"parse",
"(",
"d",
"[",
"'iso'",
"]",
")"
] | Converts a ``dict`` object back to a ``Pendulum``. | [
"Converts",
"a",
"dict",
"object",
"back",
"to",
"a",
"Pendulum",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L743-L748 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | dict_to_pendulumdate | def dict_to_pendulumdate(d: Dict[str, Any],
pendulumdate_class: ClassType) -> Date:
"""
Converts a ``dict`` object back to a ``pendulum.Date``.
"""
# noinspection PyTypeChecker
return pendulum.parse(d['iso']).date() | python | def dict_to_pendulumdate(d: Dict[str, Any],
pendulumdate_class: ClassType) -> Date:
"""
Converts a ``dict`` object back to a ``pendulum.Date``.
"""
# noinspection PyTypeChecker
return pendulum.parse(d['iso']).date() | [
"def",
"dict_to_pendulumdate",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"pendulumdate_class",
":",
"ClassType",
")",
"->",
"Date",
":",
"# noinspection PyTypeChecker",
"return",
"pendulum",
".",
"parse",
"(",
"d",
"[",
"'iso'",
"]",
")",
".... | Converts a ``dict`` object back to a ``pendulum.Date``. | [
"Converts",
"a",
"dict",
"object",
"back",
"to",
"a",
"pendulum",
".",
"Date",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L772-L778 |
RudolfCardinal/pythonlib | cardinal_pythonlib/json/serialize.py | simple_eq | def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == getattr(two, a) for a in attrs) | python | def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == getattr(two, a) for a in attrs) | [
"def",
"simple_eq",
"(",
"one",
":",
"Instance",
",",
"two",
":",
"Instance",
",",
"attrs",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"return",
"all",
"(",
"getattr",
"(",
"one",
",",
"a",
")",
"==",
"getattr",
"(",
"two",
",",
"a",
... | Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``. | [
"Test",
"if",
"two",
"objects",
"are",
"equal",
"based",
"on",
"a",
"comparison",
"of",
"the",
"specified",
"attributes",
"attrs",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L832-L837 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | smart_open | def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1,
encoding: str = None, errors: str = None, newline: str = None,
closefd: bool = True) -> IO:
"""
Context manager (for use with ``with``) that opens a filename and provides
a :class:`IO` object. If the filename ... | python | def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1,
encoding: str = None, errors: str = None, newline: str = None,
closefd: bool = True) -> IO:
"""
Context manager (for use with ``with``) that opens a filename and provides
a :class:`IO` object. If the filename ... | [
"def",
"smart_open",
"(",
"filename",
":",
"str",
",",
"mode",
":",
"str",
"=",
"'Ur'",
",",
"buffering",
":",
"int",
"=",
"-",
"1",
",",
"encoding",
":",
"str",
"=",
"None",
",",
"errors",
":",
"str",
"=",
"None",
",",
"newline",
":",
"str",
"="... | Context manager (for use with ``with``) that opens a filename and provides
a :class:`IO` object. If the filename is ``'-'``, however, then
``sys.stdin`` is used for reading and ``sys.stdout`` is used for writing. | [
"Context",
"manager",
"(",
"for",
"use",
"with",
"with",
")",
"that",
"opens",
"a",
"filename",
"and",
"provides",
"a",
":",
"class",
":",
"IO",
"object",
".",
"If",
"the",
"filename",
"is",
"-",
"however",
"then",
"sys",
".",
"stdin",
"is",
"used",
... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L57-L80 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | writelines_nl | def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None:
"""
Writes lines, plus terminating newline characters, to the file.
(Since :func:`fileobj.writelines` doesn't add newlines...
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file)
""... | python | def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None:
"""
Writes lines, plus terminating newline characters, to the file.
(Since :func:`fileobj.writelines` doesn't add newlines...
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file)
""... | [
"def",
"writelines_nl",
"(",
"fileobj",
":",
"TextIO",
",",
"lines",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"# noqa",
"fileobj",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"+",
"'\\n'",
")"
] | Writes lines, plus terminating newline characters, to the file.
(Since :func:`fileobj.writelines` doesn't add newlines...
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file) | [
"Writes",
"lines",
"plus",
"terminating",
"newline",
"characters",
"to",
"the",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L94-L101 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | write_text | def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) | python | def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) | [
"def",
"write_text",
"(",
"filename",
":",
"str",
",",
"text",
":",
"str",
")",
"->",
"None",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"# type: TextIO",
"print",
"(",
"text",
",",
"file",
"=",
"f",
")"
] | Writes text to a file. | [
"Writes",
"text",
"to",
"a",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L104-L109 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | write_gzipped_text | def write_gzipped_text(basefilename: str, text: str) -> None:
"""
Writes text to a file compressed with ``gzip`` (a ``.gz`` file).
The filename is used directly for the "inner" file and the extension
``.gz`` is appended to the "outer" (zipped) file's name.
This function exists primarily because... | python | def write_gzipped_text(basefilename: str, text: str) -> None:
"""
Writes text to a file compressed with ``gzip`` (a ``.gz`` file).
The filename is used directly for the "inner" file and the extension
``.gz`` is appended to the "outer" (zipped) file's name.
This function exists primarily because... | [
"def",
"write_gzipped_text",
"(",
"basefilename",
":",
"str",
",",
"text",
":",
"str",
")",
"->",
"None",
":",
"# noqa",
"zipfilename",
"=",
"basefilename",
"+",
"'.gz'",
"compresslevel",
"=",
"9",
"mtime",
"=",
"0",
"with",
"open",
"(",
"zipfilename",
","... | Writes text to a file compressed with ``gzip`` (a ``.gz`` file).
The filename is used directly for the "inner" file and the extension
``.gz`` is appended to the "outer" (zipped) file's name.
This function exists primarily because Lintian wants non-timestamped gzip
files, or it complains:
- http... | [
"Writes",
"text",
"to",
"a",
"file",
"compressed",
"with",
"gzip",
"(",
"a",
".",
"gz",
"file",
")",
".",
"The",
"filename",
"is",
"used",
"directly",
"for",
"the",
"inner",
"file",
"and",
"the",
"extension",
".",
"gz",
"is",
"appended",
"to",
"the",
... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L112-L129 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | get_lines_without_comments | def get_lines_without_comments(filename: str) -> List[str]:
"""
Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols!
"""
lines = []
with open(filename) a... | python | def get_lines_without_comments(filename: str) -> List[str]:
"""
Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols!
"""
lines = []
with open(filename) a... | [
"def",
"get_lines_without_comments",
"(",
"filename",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"parti... | Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols! | [
"Reads",
"a",
"file",
"and",
"returns",
"all",
"lines",
"as",
"a",
"list",
"left",
"-",
"and",
"right",
"-",
"stripping",
"the",
"lines",
"and",
"removing",
"everything",
"on",
"a",
"line",
"after",
"the",
"first",
"#",
".",
"NOTE",
":",
"does",
"not",... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L136-L150 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_textfiles_from_filenames | def gen_textfiles_from_filenames(
filenames: Iterable[str]) -> Generator[TextIO, None, None]:
"""
Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object
"""
for filename in filenames:
... | python | def gen_textfiles_from_filenames(
filenames: Iterable[str]) -> Generator[TextIO, None, None]:
"""
Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object
"""
for filename in filenames:
... | [
"def",
"gen_textfiles_from_filenames",
"(",
"filenames",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"Generator",
"[",
"TextIO",
",",
"None",
",",
"None",
"]",
":",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"... | Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object | [
"Generates",
"file",
"-",
"like",
"objects",
"from",
"a",
"list",
"of",
"filenames",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L157-L171 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_lines_from_textfiles | def gen_lines_from_textfiles(
files: Iterable[TextIO]) -> Generator[str, None, None]:
"""
Generates lines from file-like objects.
Args:
files: iterable of :class:`TextIO` objects
Yields:
each line of all the files
"""
for file in files:
for line in file:
... | python | def gen_lines_from_textfiles(
files: Iterable[TextIO]) -> Generator[str, None, None]:
"""
Generates lines from file-like objects.
Args:
files: iterable of :class:`TextIO` objects
Yields:
each line of all the files
"""
for file in files:
for line in file:
... | [
"def",
"gen_lines_from_textfiles",
"(",
"files",
":",
"Iterable",
"[",
"TextIO",
"]",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"for",
"file",
"in",
"files",
":",
"for",
"line",
"in",
"file",
":",
"yield",
"line"
] | Generates lines from file-like objects.
Args:
files: iterable of :class:`TextIO` objects
Yields:
each line of all the files | [
"Generates",
"lines",
"from",
"file",
"-",
"like",
"objects",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L174-L188 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_lower | def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:
"""
Args:
x: iterable of strings
Yields:
each string in lower case
"""
for string in x:
yield string.lower() | python | def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:
"""
Args:
x: iterable of strings
Yields:
each string in lower case
"""
for string in x:
yield string.lower() | [
"def",
"gen_lower",
"(",
"x",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"for",
"string",
"in",
"x",
":",
"yield",
"string",
".",
"lower",
"(",
")"
] | Args:
x: iterable of strings
Yields:
each string in lower case | [
"Args",
":",
"x",
":",
"iterable",
"of",
"strings"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L191-L200 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_lines_from_binary_files | def gen_lines_from_binary_files(
files: Iterable[BinaryIO],
encoding: str = UTF8) -> Generator[str, None, None]:
"""
Generates lines from binary files.
Strips out newlines.
Args:
files: iterable of :class:`BinaryIO` file-like objects
encoding: encoding to use
Yields... | python | def gen_lines_from_binary_files(
files: Iterable[BinaryIO],
encoding: str = UTF8) -> Generator[str, None, None]:
"""
Generates lines from binary files.
Strips out newlines.
Args:
files: iterable of :class:`BinaryIO` file-like objects
encoding: encoding to use
Yields... | [
"def",
"gen_lines_from_binary_files",
"(",
"files",
":",
"Iterable",
"[",
"BinaryIO",
"]",
",",
"encoding",
":",
"str",
"=",
"UTF8",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"for",
"file",
"in",
"files",
":",
"for",
"byte... | Generates lines from binary files.
Strips out newlines.
Args:
files: iterable of :class:`BinaryIO` file-like objects
encoding: encoding to use
Yields:
each line of all the files | [
"Generates",
"lines",
"from",
"binary",
"files",
".",
"Strips",
"out",
"newlines",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L203-L221 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_part_from_line | def gen_part_from_line(lines: Iterable[str],
part_index: int,
splitter: str = None) -> Generator[str, None, None]:
"""
Splits lines with ``splitter`` and yields a specified part by index.
Args:
lines: iterable of strings
part_index: index of par... | python | def gen_part_from_line(lines: Iterable[str],
part_index: int,
splitter: str = None) -> Generator[str, None, None]:
"""
Splits lines with ``splitter`` and yields a specified part by index.
Args:
lines: iterable of strings
part_index: index of par... | [
"def",
"gen_part_from_line",
"(",
"lines",
":",
"Iterable",
"[",
"str",
"]",
",",
"part_index",
":",
"int",
",",
"splitter",
":",
"str",
"=",
"None",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"for",
"line",
"in",
"lines"... | Splits lines with ``splitter`` and yields a specified part by index.
Args:
lines: iterable of strings
part_index: index of part to yield
splitter: string to split the lines on
Yields:
the specified part for each line | [
"Splits",
"lines",
"with",
"splitter",
"and",
"yields",
"a",
"specified",
"part",
"by",
"index",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L266-L283 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_part_from_iterables | def gen_part_from_iterables(iterables: Iterable[Any],
part_index: int) -> Generator[Any, None, None]:
r"""
Yields the *n*\ th part of each thing in ``iterables``.
Args:
iterables: iterable of anything
part_index: part index
Yields:
``item[part_index]... | python | def gen_part_from_iterables(iterables: Iterable[Any],
part_index: int) -> Generator[Any, None, None]:
r"""
Yields the *n*\ th part of each thing in ``iterables``.
Args:
iterables: iterable of anything
part_index: part index
Yields:
``item[part_index]... | [
"def",
"gen_part_from_iterables",
"(",
"iterables",
":",
"Iterable",
"[",
"Any",
"]",
",",
"part_index",
":",
"int",
")",
"->",
"Generator",
"[",
"Any",
",",
"None",
",",
"None",
"]",
":",
"# RST: make part of word bold/italic:",
"# https://stackoverflow.com/questio... | r"""
Yields the *n*\ th part of each thing in ``iterables``.
Args:
iterables: iterable of anything
part_index: part index
Yields:
``item[part_index] for item in iterable`` | [
"r",
"Yields",
"the",
"*",
"n",
"*",
"\\",
"th",
"part",
"of",
"each",
"thing",
"in",
"iterables",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L286-L302 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | gen_rows_from_csv_binfiles | def gen_rows_from_csv_binfiles(
csv_files: Iterable[BinaryIO],
encoding: str = UTF8,
skip_header: bool = False,
**csv_reader_kwargs) -> Generator[Iterable[str], None, None]:
"""
Iterate through binary file-like objects that are CSV files in a specified
encoding. Yield each ro... | python | def gen_rows_from_csv_binfiles(
csv_files: Iterable[BinaryIO],
encoding: str = UTF8,
skip_header: bool = False,
**csv_reader_kwargs) -> Generator[Iterable[str], None, None]:
"""
Iterate through binary file-like objects that are CSV files in a specified
encoding. Yield each ro... | [
"def",
"gen_rows_from_csv_binfiles",
"(",
"csv_files",
":",
"Iterable",
"[",
"BinaryIO",
"]",
",",
"encoding",
":",
"str",
"=",
"UTF8",
",",
"skip_header",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"csv_reader_kwargs",
")",
"->",
"Generator",
"[",
"Iterable"... | Iterate through binary file-like objects that are CSV files in a specified
encoding. Yield each row.
Args:
csv_files: iterable of :class:`BinaryIO` objects
encoding: encoding to use
skip_header: skip the header (first) row of each file?
csv_reader_kwargs: arguments to pass to :f... | [
"Iterate",
"through",
"binary",
"file",
"-",
"like",
"objects",
"that",
"are",
"CSV",
"files",
"in",
"a",
"specified",
"encoding",
".",
"Yield",
"each",
"row",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L305-L340 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | webify_file | def webify_file(srcfilename: str, destfilename: str) -> None:
"""
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process.
"""
with open(srcfilename) as infile, open(destfilename, 'w') as ofile:
for line_ in infile:
ofile.write(escape(line_)) | python | def webify_file(srcfilename: str, destfilename: str) -> None:
"""
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process.
"""
with open(srcfilename) as infile, open(destfilename, 'w') as ofile:
for line_ in infile:
ofile.write(escape(line_)) | [
"def",
"webify_file",
"(",
"srcfilename",
":",
"str",
",",
"destfilename",
":",
"str",
")",
"->",
"None",
":",
"with",
"open",
"(",
"srcfilename",
")",
"as",
"infile",
",",
"open",
"(",
"destfilename",
",",
"'w'",
")",
"as",
"ofile",
":",
"for",
"line_... | Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process. | [
"Rewrites",
"a",
"file",
"from",
"srcfilename",
"to",
"destfilename",
"HTML",
"-",
"escaping",
"it",
"in",
"the",
"process",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L347-L354 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | remove_gzip_timestamp | def remove_gzip_timestamp(filename: str,
gunzip_executable: str = "gunzip",
gzip_executable: str = "gzip",
gzip_args: List[str] = None) -> None:
"""
Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp.
Necessary... | python | def remove_gzip_timestamp(filename: str,
gunzip_executable: str = "gunzip",
gzip_executable: str = "gzip",
gzip_args: List[str] = None) -> None:
"""
Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp.
Necessary... | [
"def",
"remove_gzip_timestamp",
"(",
"filename",
":",
"str",
",",
"gunzip_executable",
":",
"str",
"=",
"\"gunzip\"",
",",
"gzip_executable",
":",
"str",
"=",
"\"gzip\"",
",",
"gzip_args",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
... | Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp.
Necessary for Lintian. | [
"Uses",
"external",
"gunzip",
"/",
"gzip",
"tools",
"to",
"remove",
"a",
"gzip",
"timestamp",
".",
"Necessary",
"for",
"Lintian",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L357-L383 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | replace_in_file | def replace_in_file(filename: str, text_from: str, text_to: str) -> None:
"""
Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text
"""
log.info("Amending {}: {} -> {}",
... | python | def replace_in_file(filename: str, text_from: str, text_to: str) -> None:
"""
Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text
"""
log.info("Amending {}: {} -> {}",
... | [
"def",
"replace_in_file",
"(",
"filename",
":",
"str",
",",
"text_from",
":",
"str",
",",
"text_to",
":",
"str",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"\"Amending {}: {} -> {}\"",
",",
"filename",
",",
"repr",
"(",
"text_from",
")",
",",
"repr... | Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text | [
"Replaces",
"text",
"in",
"a",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L390-L405 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | replace_multiple_in_file | def replace_multiple_in_file(filename: str,
replacements: List[Tuple[str, str]]) -> None:
"""
Replaces multiple from/to string pairs within a single file.
Args:
filename: filename to process (modifying it in place)
replacements: list of ``(from_text, to_text)`` ... | python | def replace_multiple_in_file(filename: str,
replacements: List[Tuple[str, str]]) -> None:
"""
Replaces multiple from/to string pairs within a single file.
Args:
filename: filename to process (modifying it in place)
replacements: list of ``(from_text, to_text)`` ... | [
"def",
"replace_multiple_in_file",
"(",
"filename",
":",
"str",
",",
"replacements",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
")",
"->",
"None",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"infile",
":",
"contents",
"=",
"infil... | Replaces multiple from/to string pairs within a single file.
Args:
filename: filename to process (modifying it in place)
replacements: list of ``(from_text, to_text)`` tuples | [
"Replaces",
"multiple",
"from",
"/",
"to",
"string",
"pairs",
"within",
"a",
"single",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L408-L424 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | convert_line_endings | def convert_line_endings(filename: str, to_unix: bool = False,
to_windows: bool = False) -> None:
"""
Converts a file (in place) from UNIX to Windows line endings, or the
reverse.
Args:
filename: filename to modify (in place)
to_unix: convert Windows (CR LF) to ... | python | def convert_line_endings(filename: str, to_unix: bool = False,
to_windows: bool = False) -> None:
"""
Converts a file (in place) from UNIX to Windows line endings, or the
reverse.
Args:
filename: filename to modify (in place)
to_unix: convert Windows (CR LF) to ... | [
"def",
"convert_line_endings",
"(",
"filename",
":",
"str",
",",
"to_unix",
":",
"bool",
"=",
"False",
",",
"to_windows",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"assert",
"to_unix",
"!=",
"to_windows",
"with",
"open",
"(",
"filename",
",",
"\... | Converts a file (in place) from UNIX to Windows line endings, or the
reverse.
Args:
filename: filename to modify (in place)
to_unix: convert Windows (CR LF) to UNIX (LF)
to_windows: convert UNIX (LF) to Windows (CR LF) | [
"Converts",
"a",
"file",
"(",
"in",
"place",
")",
"from",
"UNIX",
"to",
"Windows",
"line",
"endings",
"or",
"the",
"reverse",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L427-L459 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | is_line_in_file | def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
... | python | def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
... | [
"def",
"is_line_in_file",
"(",
"filename",
":",
"str",
",",
"line",
":",
"str",
")",
"->",
"bool",
":",
"assert",
"\"\\n\"",
"not",
"in",
"line",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"file",
":",
"for",
"fileline",
"in",
"file",
... | Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match) | [
"Detects",
"whether",
"a",
"line",
"is",
"present",
"within",
"a",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L462-L475 |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | add_line_if_absent | def add_line_if_absent(filename: str, line: str) -> None:
"""
Adds a line (at the end) if it's not already in the file somewhere.
Args:
filename: filename to modify (in place)
line: line to append (which must not have a newline in)
"""
assert "\n" not in line
if not is_line_in_f... | python | def add_line_if_absent(filename: str, line: str) -> None:
"""
Adds a line (at the end) if it's not already in the file somewhere.
Args:
filename: filename to modify (in place)
line: line to append (which must not have a newline in)
"""
assert "\n" not in line
if not is_line_in_f... | [
"def",
"add_line_if_absent",
"(",
"filename",
":",
"str",
",",
"line",
":",
"str",
")",
"->",
"None",
":",
"assert",
"\"\\n\"",
"not",
"in",
"line",
"if",
"not",
"is_line_in_file",
"(",
"filename",
",",
"line",
")",
":",
"log",
".",
"info",
"(",
"\"App... | Adds a line (at the end) if it's not already in the file somewhere.
Args:
filename: filename to modify (in place)
line: line to append (which must not have a newline in) | [
"Adds",
"a",
"line",
"(",
"at",
"the",
"end",
")",
"if",
"it",
"s",
"not",
"already",
"in",
"the",
"file",
"somewhere",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L478-L490 |
avihad/twistes | twistes/utilities.py | EsUtils.is_get_query_with_results | def is_get_query_with_results(results):
"""
:param results: the response from Elasticsearch
:return: true if the get query returned a result, false otherwise
"""
return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results | python | def is_get_query_with_results(results):
"""
:param results: the response from Elasticsearch
:return: true if the get query returned a result, false otherwise
"""
return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results | [
"def",
"is_get_query_with_results",
"(",
"results",
")",
":",
"return",
"results",
"and",
"EsConst",
".",
"FOUND",
"in",
"results",
"and",
"results",
"[",
"EsConst",
".",
"FOUND",
"]",
"and",
"EsConst",
".",
"FIELDS",
"in",
"results"
] | :param results: the response from Elasticsearch
:return: true if the get query returned a result, false otherwise | [
":",
"param",
"results",
":",
"the",
"response",
"from",
"Elasticsearch",
":",
"return",
":",
"true",
"if",
"the",
"get",
"query",
"returned",
"a",
"result",
"false",
"otherwise"
] | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/utilities.py#L39-L44 |
avihad/twistes | twistes/utilities.py | EsUtils.validate_scan_result | def validate_scan_result(results):
""" Check if there's a failed shard in the scan query"""
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0:
raise ScanError(
'Scroll request has failed on %d shards out of %d.' %
(resu... | python | def validate_scan_result(results):
""" Check if there's a failed shard in the scan query"""
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0:
raise ScanError(
'Scroll request has failed on %d shards out of %d.' %
(resu... | [
"def",
"validate_scan_result",
"(",
"results",
")",
":",
"if",
"results",
"[",
"EsConst",
".",
"SHARDS",
"]",
"[",
"EsConst",
".",
"FAILED",
"]",
"and",
"results",
"[",
"EsConst",
".",
"SHARDS",
"]",
"[",
"EsConst",
".",
"FAILED",
"]",
">",
"0",
":",
... | Check if there's a failed shard in the scan query | [
"Check",
"if",
"there",
"s",
"a",
"failed",
"shard",
"in",
"the",
"scan",
"query"
] | train | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/utilities.py#L47-L53 |
ivanprjcts/sdklib | sdklib/util/structures.py | to_key_val_list | def to_key_val_list(value, sort=False, insensitive=False):
"""
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
... | python | def to_key_val_list(value, sort=False, insensitive=False):
"""
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
... | [
"def",
"to_key_val_list",
"(",
"value",
",",
"sort",
"=",
"False",
",",
"insensitive",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int... | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list({'key': 'val'}, sort=Tr... | [
"Take",
"an",
"object",
"and",
"test",
"to",
"see",
"if",
"it",
"can",
"be",
"represented",
"as",
"a",
"dictionary",
".",
"If",
"it",
"can",
"be",
"return",
"a",
"list",
"of",
"tuples",
"e",
".",
"g",
".",
"::",
">>>",
"to_key_val_list",
"(",
"[",
... | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/structures.py#L19-L48 |
ivanprjcts/sdklib | sdklib/util/structures.py | to_key_val_dict | def to_key_val_dict(values):
"""
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_dict([('key', 'val')])
{'key': 'val'}
>>> to_key_val_dict({'key': 'val'})
{'key': 'val'}
>>> to... | python | def to_key_val_dict(values):
"""
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_dict([('key', 'val')])
{'key': 'val'}
>>> to_key_val_dict({'key': 'val'})
{'key': 'val'}
>>> to... | [
"def",
"to_key_val_dict",
"(",
"values",
")",
":",
"if",
"values",
"is",
"None",
":",
"return",
"{",
"}",
"if",
"isinstance",
"(",
"values",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int",
")",
")",
":",
"raise",
"ValueError",
"(",
"'cannot e... | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_dict([('key', 'val')])
{'key': 'val'}
>>> to_key_val_dict({'key': 'val'})
{'key': 'val'}
>>> to_key_val_dict('string')
ValueErro... | [
"Take",
"an",
"object",
"and",
"test",
"to",
"see",
"if",
"it",
"can",
"be",
"represented",
"as",
"a",
"dictionary",
".",
"If",
"it",
"can",
"be",
"return",
"a",
"list",
"of",
"tuples",
"e",
".",
"g",
".",
"::",
">>>",
"to_key_val_dict",
"(",
"[",
... | train | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/structures.py#L51-L83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.