repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dump.py | dump_orm_object_as_insert_sql | def dump_orm_object_as_insert_sql(engine: Engine,
obj: object,
fileobj: TextIO) -> None:
"""
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it
to the output file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
obj: SQLAlchemy ORM object to write
fileobj: file-like object to write to
"""
# literal_query = make_literal_query_fn(engine.dialect)
insp = inspect(obj)
# insp: an InstanceState
# http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.InstanceState # noqa
# insp.mapper: a Mapper
# http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper # noqa
# Don't do this:
# table = insp.mapper.mapped_table
# Do this instead. The method above gives you fancy data types like list
# and Arrow on the Python side. We want the bog-standard datatypes drawn
# from the database itself.
meta = MetaData(bind=engine)
table_name = insp.mapper.mapped_table.name
# log.debug("table_name: {}", table_name)
table = Table(table_name, meta, autoload=True)
# log.debug("table: {}", table)
# NewRecord = quick_mapper(table)
# columns = table.columns.keys()
query = select(table.columns)
# log.debug("query: {}", query)
for orm_pkcol in insp.mapper.primary_key:
core_pkcol = table.columns.get(orm_pkcol.name)
pkval = getattr(obj, orm_pkcol.name)
query = query.where(core_pkcol == pkval)
# log.debug("query: {}", query)
cursor = engine.execute(query)
row = cursor.fetchone() # should only be one...
row_dict = dict(row)
# log.debug("obj: {}", obj)
# log.debug("row_dict: {}", row_dict)
statement = table.insert(values=row_dict)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
writeline_nl(fileobj, insert_str) | python | def dump_orm_object_as_insert_sql(engine: Engine,
obj: object,
fileobj: TextIO) -> None:
"""
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it
to the output file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
obj: SQLAlchemy ORM object to write
fileobj: file-like object to write to
"""
# literal_query = make_literal_query_fn(engine.dialect)
insp = inspect(obj)
# insp: an InstanceState
# http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.InstanceState # noqa
# insp.mapper: a Mapper
# http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper # noqa
# Don't do this:
# table = insp.mapper.mapped_table
# Do this instead. The method above gives you fancy data types like list
# and Arrow on the Python side. We want the bog-standard datatypes drawn
# from the database itself.
meta = MetaData(bind=engine)
table_name = insp.mapper.mapped_table.name
# log.debug("table_name: {}", table_name)
table = Table(table_name, meta, autoload=True)
# log.debug("table: {}", table)
# NewRecord = quick_mapper(table)
# columns = table.columns.keys()
query = select(table.columns)
# log.debug("query: {}", query)
for orm_pkcol in insp.mapper.primary_key:
core_pkcol = table.columns.get(orm_pkcol.name)
pkval = getattr(obj, orm_pkcol.name)
query = query.where(core_pkcol == pkval)
# log.debug("query: {}", query)
cursor = engine.execute(query)
row = cursor.fetchone() # should only be one...
row_dict = dict(row)
# log.debug("obj: {}", obj)
# log.debug("row_dict: {}", row_dict)
statement = table.insert(values=row_dict)
# insert_str = literal_query(statement)
insert_str = get_literal_query(statement, bind=engine)
writeline_nl(fileobj, insert_str) | [
"def",
"dump_orm_object_as_insert_sql",
"(",
"engine",
":",
"Engine",
",",
"obj",
":",
"object",
",",
"fileobj",
":",
"TextIO",
")",
"->",
"None",
":",
"# literal_query = make_literal_query_fn(engine.dialect)",
"insp",
"=",
"inspect",
"(",
"obj",
")",
"# insp: an In... | Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it
to the output file-like object.
Args:
engine: SQLAlchemy :class:`Engine`
obj: SQLAlchemy ORM object to write
fileobj: file-like object to write to | [
"Takes",
"a",
"SQLAlchemy",
"ORM",
"object",
"and",
"writes",
"INSERT",
"SQL",
"to",
"replicate",
"it",
"to",
"the",
"output",
"file",
"-",
"like",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L400-L447 | train | 52,900 |
avihad/twistes | twistes/scroller.py | Scroller.next | def next(self):
"""Fetch next page from scroll API."""
d = None
if self._first_results:
d = succeed(EsUtils.extract_hits(self._first_results))
self._first_results = None
elif self._scroll_id:
d = self._scroll_next_results()
else:
raise StopIteration()
return d | python | def next(self):
"""Fetch next page from scroll API."""
d = None
if self._first_results:
d = succeed(EsUtils.extract_hits(self._first_results))
self._first_results = None
elif self._scroll_id:
d = self._scroll_next_results()
else:
raise StopIteration()
return d | [
"def",
"next",
"(",
"self",
")",
":",
"d",
"=",
"None",
"if",
"self",
".",
"_first_results",
":",
"d",
"=",
"succeed",
"(",
"EsUtils",
".",
"extract_hits",
"(",
"self",
".",
"_first_results",
")",
")",
"self",
".",
"_first_results",
"=",
"None",
"elif"... | Fetch next page from scroll API. | [
"Fetch",
"next",
"page",
"from",
"scroll",
"API",
"."
] | 9ab8f5aa088b8886aefe3dec85a400e5035e034a | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/scroller.py#L31-L41 | train | 52,901 |
RudolfCardinal/pythonlib | cardinal_pythonlib/source_reformatting.py | reformat_python_docstrings | def reformat_python_docstrings(top_dirs: List[str],
correct_copyright_lines: List[str],
show_only: bool = True,
rewrite: bool = False,
process_only_filenum: int = None) -> None:
"""
Walk a directory, finding Python files and rewriting them.
Args:
top_dirs: list of directories to descend into
correct_copyright_lines:
list of lines (without newlines) representing the copyright
docstring block, including the transition lines of equals
symbols
show_only: show results (to stdout) only; don't rewrite
rewrite: write the changes
process_only_filenum: only process this file number (1-based index);
for debugging only
"""
filenum = 0
for top_dir in top_dirs:
for dirpath, dirnames, filenames in walk(top_dir):
for filename in filenames:
fullname = join(dirpath, filename)
extension = splitext(filename)[1]
if extension != PYTHON_EXTENSION:
# log.debug("Skipping non-Python file: {}", fullname)
continue
filenum += 1
if process_only_filenum and filenum != process_only_filenum:
continue
log.info("Processing file {}: {}", filenum, fullname)
proc = PythonProcessor(
full_path=fullname,
top_dir=top_dir,
correct_copyright_lines=correct_copyright_lines)
if show_only:
proc.show()
elif rewrite:
proc.rewrite_file() | python | def reformat_python_docstrings(top_dirs: List[str],
correct_copyright_lines: List[str],
show_only: bool = True,
rewrite: bool = False,
process_only_filenum: int = None) -> None:
"""
Walk a directory, finding Python files and rewriting them.
Args:
top_dirs: list of directories to descend into
correct_copyright_lines:
list of lines (without newlines) representing the copyright
docstring block, including the transition lines of equals
symbols
show_only: show results (to stdout) only; don't rewrite
rewrite: write the changes
process_only_filenum: only process this file number (1-based index);
for debugging only
"""
filenum = 0
for top_dir in top_dirs:
for dirpath, dirnames, filenames in walk(top_dir):
for filename in filenames:
fullname = join(dirpath, filename)
extension = splitext(filename)[1]
if extension != PYTHON_EXTENSION:
# log.debug("Skipping non-Python file: {}", fullname)
continue
filenum += 1
if process_only_filenum and filenum != process_only_filenum:
continue
log.info("Processing file {}: {}", filenum, fullname)
proc = PythonProcessor(
full_path=fullname,
top_dir=top_dir,
correct_copyright_lines=correct_copyright_lines)
if show_only:
proc.show()
elif rewrite:
proc.rewrite_file() | [
"def",
"reformat_python_docstrings",
"(",
"top_dirs",
":",
"List",
"[",
"str",
"]",
",",
"correct_copyright_lines",
":",
"List",
"[",
"str",
"]",
",",
"show_only",
":",
"bool",
"=",
"True",
",",
"rewrite",
":",
"bool",
"=",
"False",
",",
"process_only_filenu... | Walk a directory, finding Python files and rewriting them.
Args:
top_dirs: list of directories to descend into
correct_copyright_lines:
list of lines (without newlines) representing the copyright
docstring block, including the transition lines of equals
symbols
show_only: show results (to stdout) only; don't rewrite
rewrite: write the changes
process_only_filenum: only process this file number (1-based index);
for debugging only | [
"Walk",
"a",
"directory",
"finding",
"Python",
"files",
"and",
"rewriting",
"them",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L310-L352 | train | 52,902 |
RudolfCardinal/pythonlib | cardinal_pythonlib/source_reformatting.py | PythonProcessor._read_source | def _read_source(self) -> None:
"""
Reads the source file.
"""
with open(self.full_path, "rt") as f:
for linenum, line_with_nl in enumerate(f.readlines(), start=1):
line_without_newline = (
line_with_nl[:-1] if line_with_nl.endswith(NL)
else line_with_nl
)
if TAB in line_without_newline:
self._warn("Tab character at line {}".format(linenum))
if CR in line_without_newline:
self._warn("Carriage return character at line {} "
"(Windows CR+LF endings?)".format(linenum))
self.source_lines.append(line_without_newline) | python | def _read_source(self) -> None:
"""
Reads the source file.
"""
with open(self.full_path, "rt") as f:
for linenum, line_with_nl in enumerate(f.readlines(), start=1):
line_without_newline = (
line_with_nl[:-1] if line_with_nl.endswith(NL)
else line_with_nl
)
if TAB in line_without_newline:
self._warn("Tab character at line {}".format(linenum))
if CR in line_without_newline:
self._warn("Carriage return character at line {} "
"(Windows CR+LF endings?)".format(linenum))
self.source_lines.append(line_without_newline) | [
"def",
"_read_source",
"(",
"self",
")",
"->",
"None",
":",
"with",
"open",
"(",
"self",
".",
"full_path",
",",
"\"rt\"",
")",
"as",
"f",
":",
"for",
"linenum",
",",
"line_with_nl",
"in",
"enumerate",
"(",
"f",
".",
"readlines",
"(",
")",
",",
"start... | Reads the source file. | [
"Reads",
"the",
"source",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L95-L110 | train | 52,903 |
RudolfCardinal/pythonlib | cardinal_pythonlib/source_reformatting.py | PythonProcessor._debug_line | def _debug_line(linenum: int, line: str, extramsg: str = "") -> None:
"""
Writes a debugging report on a line.
"""
log.critical("{}Line {}: {!r}", extramsg, linenum, line) | python | def _debug_line(linenum: int, line: str, extramsg: str = "") -> None:
"""
Writes a debugging report on a line.
"""
log.critical("{}Line {}: {!r}", extramsg, linenum, line) | [
"def",
"_debug_line",
"(",
"linenum",
":",
"int",
",",
"line",
":",
"str",
",",
"extramsg",
":",
"str",
"=",
"\"\"",
")",
"->",
"None",
":",
"log",
".",
"critical",
"(",
"\"{}Line {}: {!r}\"",
",",
"extramsg",
",",
"linenum",
",",
"line",
")"
] | Writes a debugging report on a line. | [
"Writes",
"a",
"debugging",
"report",
"on",
"a",
"line",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L239-L243 | train | 52,904 |
RudolfCardinal/pythonlib | cardinal_pythonlib/source_reformatting.py | PythonProcessor.rewrite_file | def rewrite_file(self) -> None:
"""
Rewrites the source file.
"""
if not self.needs_rewriting:
return
self._info("Rewriting file")
with open(self.full_path, "w") as outfile:
self._write(outfile) | python | def rewrite_file(self) -> None:
"""
Rewrites the source file.
"""
if not self.needs_rewriting:
return
self._info("Rewriting file")
with open(self.full_path, "w") as outfile:
self._write(outfile) | [
"def",
"rewrite_file",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"needs_rewriting",
":",
"return",
"self",
".",
"_info",
"(",
"\"Rewriting file\"",
")",
"with",
"open",
"(",
"self",
".",
"full_path",
",",
"\"w\"",
")",
"as",
"outfile... | Rewrites the source file. | [
"Rewrites",
"the",
"source",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L288-L296 | train | 52,905 |
RudolfCardinal/pythonlib | cardinal_pythonlib/source_reformatting.py | PythonProcessor._write | def _write(self, destination: TextIO) -> None:
"""
Writes the converted output to a destination.
"""
for line in self.dest_lines:
destination.write(line + NL) | python | def _write(self, destination: TextIO) -> None:
"""
Writes the converted output to a destination.
"""
for line in self.dest_lines:
destination.write(line + NL) | [
"def",
"_write",
"(",
"self",
",",
"destination",
":",
"TextIO",
")",
"->",
"None",
":",
"for",
"line",
"in",
"self",
".",
"dest_lines",
":",
"destination",
".",
"write",
"(",
"line",
"+",
"NL",
")"
] | Writes the converted output to a destination. | [
"Writes",
"the",
"converted",
"output",
"to",
"a",
"destination",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L298-L303 | train | 52,906 |
RudolfCardinal/pythonlib | cardinal_pythonlib/lists.py | contains_duplicates | def contains_duplicates(values: Iterable[Any]) -> bool:
"""
Does the iterable contain any duplicate values?
"""
for v in Counter(values).values():
if v > 1:
return True
return False | python | def contains_duplicates(values: Iterable[Any]) -> bool:
"""
Does the iterable contain any duplicate values?
"""
for v in Counter(values).values():
if v > 1:
return True
return False | [
"def",
"contains_duplicates",
"(",
"values",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"bool",
":",
"for",
"v",
"in",
"Counter",
"(",
"values",
")",
".",
"values",
"(",
")",
":",
"if",
"v",
">",
"1",
":",
"return",
"True",
"return",
"False"
] | Does the iterable contain any duplicate values? | [
"Does",
"the",
"iterable",
"contain",
"any",
"duplicate",
"values?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L38-L45 | train | 52,907 |
RudolfCardinal/pythonlib | cardinal_pythonlib/lists.py | index_list_for_sort_order | def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,
reverse: bool = False) -> List[int]:
"""
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
the default is ``itemgetter(1)``
reverse: reverse the sort order?
Returns:
list of integer index values
Example:
.. code-block:: python
z = ["a", "c", "b"]
index_list_for_sort_order(z) # [0, 2, 1]
index_list_for_sort_order(z, reverse=True) # [1, 2, 0]
q = [("a", 9), ("b", 8), ("c", 7)]
index_list_for_sort_order(q, key=itemgetter(1))
"""
def key_with_user_func(idx_val: Tuple[int, Any]):
return key(idx_val[1])
if key:
sort_key = key_with_user_func
# see the simpler version below
else:
sort_key = itemgetter(1)
# enumerate, below, will return tuples of (index, value), so
# itemgetter(1) means sort by the value
index_value_list = sorted(enumerate(x), key=sort_key, reverse=reverse)
return [i for i, _ in index_value_list] | python | def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,
reverse: bool = False) -> List[int]:
"""
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
the default is ``itemgetter(1)``
reverse: reverse the sort order?
Returns:
list of integer index values
Example:
.. code-block:: python
z = ["a", "c", "b"]
index_list_for_sort_order(z) # [0, 2, 1]
index_list_for_sort_order(z, reverse=True) # [1, 2, 0]
q = [("a", 9), ("b", 8), ("c", 7)]
index_list_for_sort_order(q, key=itemgetter(1))
"""
def key_with_user_func(idx_val: Tuple[int, Any]):
return key(idx_val[1])
if key:
sort_key = key_with_user_func
# see the simpler version below
else:
sort_key = itemgetter(1)
# enumerate, below, will return tuples of (index, value), so
# itemgetter(1) means sort by the value
index_value_list = sorted(enumerate(x), key=sort_key, reverse=reverse)
return [i for i, _ in index_value_list] | [
"def",
"index_list_for_sort_order",
"(",
"x",
":",
"List",
"[",
"Any",
"]",
",",
"key",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"None",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"int",
"]",
":",
"def"... | Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
the default is ``itemgetter(1)``
reverse: reverse the sort order?
Returns:
list of integer index values
Example:
.. code-block:: python
z = ["a", "c", "b"]
index_list_for_sort_order(z) # [0, 2, 1]
index_list_for_sort_order(z, reverse=True) # [1, 2, 0]
q = [("a", 9), ("b", 8), ("c", 7)]
index_list_for_sort_order(q, key=itemgetter(1)) | [
"Returns",
"a",
"list",
"of",
"indexes",
"of",
"x",
"IF",
"x",
"WERE",
"TO",
"BE",
"SORTED",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L48-L84 | train | 52,908 |
RudolfCardinal/pythonlib | cardinal_pythonlib/lists.py | sort_list_by_index_list | def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None:
"""
Re-orders ``x`` by the list of ``indexes`` of ``x``, in place.
Example:
.. code-block:: python
from cardinal_pythonlib.lists import sort_list_by_index_list
z = ["a", "b", "c", "d", "e"]
sort_list_by_index_list(z, [4, 0, 1, 2, 3])
z # ["e", "a", "b", "c", "d"]
"""
x[:] = [x[i] for i in indexes] | python | def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None:
"""
Re-orders ``x`` by the list of ``indexes`` of ``x``, in place.
Example:
.. code-block:: python
from cardinal_pythonlib.lists import sort_list_by_index_list
z = ["a", "b", "c", "d", "e"]
sort_list_by_index_list(z, [4, 0, 1, 2, 3])
z # ["e", "a", "b", "c", "d"]
"""
x[:] = [x[i] for i in indexes] | [
"def",
"sort_list_by_index_list",
"(",
"x",
":",
"List",
"[",
"Any",
"]",
",",
"indexes",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"x",
"[",
":",
"]",
"=",
"[",
"x",
"[",
"i",
"]",
"for",
"i",
"in",
"indexes",
"]"
] | Re-orders ``x`` by the list of ``indexes`` of ``x``, in place.
Example:
.. code-block:: python
from cardinal_pythonlib.lists import sort_list_by_index_list
z = ["a", "b", "c", "d", "e"]
sort_list_by_index_list(z, [4, 0, 1, 2, 3])
z # ["e", "a", "b", "c", "d"] | [
"Re",
"-",
"orders",
"x",
"by",
"the",
"list",
"of",
"indexes",
"of",
"x",
"in",
"place",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L87-L101 | train | 52,909 |
RudolfCardinal/pythonlib | cardinal_pythonlib/lists.py | unique_list | def unique_list(seq: Iterable[Any]) -> List[Any]:
"""
Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
""" # noqa
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | def unique_list(seq: Iterable[Any]) -> List[Any]:
"""
Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
""" # noqa
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"unique_list",
"(",
"seq",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"# noqa",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
... | Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"unique",
"elements",
"in",
"the",
"input",
"list",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L121-L137 | train | 52,910 |
RudolfCardinal/pythonlib | cardinal_pythonlib/text.py | escape_newlines | def escape_newlines(s: str) -> str:
"""
Escapes CR, LF, and backslashes.
Its counterpart is :func:`unescape_newlines`.
``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are
alternatives, but they mess around with quotes, too (specifically,
backslash-escaping single quotes).
"""
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replace("\r", r"\r") # escape \r; note ord("\r") == 13
return s | python | def escape_newlines(s: str) -> str:
"""
Escapes CR, LF, and backslashes.
Its counterpart is :func:`unescape_newlines`.
``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are
alternatives, but they mess around with quotes, too (specifically,
backslash-escaping single quotes).
"""
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replace("\r", r"\r") # escape \r; note ord("\r") == 13
return s | [
"def",
"escape_newlines",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"s",
":",
"return",
"s",
"s",
"=",
"s",
".",
"replace",
"(",
"\"\\\\\"",
",",
"r\"\\\\\"",
")",
"# replace \\ with \\\\",
"s",
"=",
"s",
".",
"replace",
"(",
"\"\\n\"... | Escapes CR, LF, and backslashes.
Its counterpart is :func:`unescape_newlines`.
``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are
alternatives, but they mess around with quotes, too (specifically,
backslash-escaping single quotes). | [
"Escapes",
"CR",
"LF",
"and",
"backslashes",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L40-L55 | train | 52,911 |
RudolfCardinal/pythonlib | cardinal_pythonlib/text.py | escape_tabs_newlines | def escape_tabs_newlines(s: str) -> str:
"""
Escapes CR, LF, tab, and backslashes.
Its counterpart is :func:`unescape_tabs_newlines`.
"""
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replace("\r", r"\r") # escape \r; note ord("\r") == 13
s = s.replace("\t", r"\t") # escape \t; note ord("\t") == 9
return s | python | def escape_tabs_newlines(s: str) -> str:
"""
Escapes CR, LF, tab, and backslashes.
Its counterpart is :func:`unescape_tabs_newlines`.
"""
if not s:
return s
s = s.replace("\\", r"\\") # replace \ with \\
s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10
s = s.replace("\r", r"\r") # escape \r; note ord("\r") == 13
s = s.replace("\t", r"\t") # escape \t; note ord("\t") == 9
return s | [
"def",
"escape_tabs_newlines",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"s",
":",
"return",
"s",
"s",
"=",
"s",
".",
"replace",
"(",
"\"\\\\\"",
",",
"r\"\\\\\"",
")",
"# replace \\ with \\\\",
"s",
"=",
"s",
".",
"replace",
"(",
"\"... | Escapes CR, LF, tab, and backslashes.
Its counterpart is :func:`unescape_tabs_newlines`. | [
"Escapes",
"CR",
"LF",
"tab",
"and",
"backslashes",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L85-L97 | train | 52,912 |
meyersj/geotweet | geotweet/twitter/stream_steps.py | GeoFilterStep.validate_geotweet | def validate_geotweet(self, record):
""" check that stream record is actual tweet with coordinates """
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | python | def validate_geotweet(self, record):
""" check that stream record is actual tweet with coordinates """
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | [
"def",
"validate_geotweet",
"(",
"self",
",",
"record",
")",
":",
"if",
"record",
"and",
"self",
".",
"_validate",
"(",
"'user'",
",",
"record",
")",
"and",
"self",
".",
"_validate",
"(",
"'coordinates'",
",",
"record",
")",
":",
"return",
"True",
"retur... | check that stream record is actual tweet with coordinates | [
"check",
"that",
"stream",
"record",
"is",
"actual",
"tweet",
"with",
"coordinates"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/twitter/stream_steps.py#L53-L58 | train | 52,913 |
davenquinn/Attitude | attitude/geom/conics.py | Conic.contains | def contains(ell, p, shell_only=False):
"""
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
"""
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else _ <= 0 | python | def contains(ell, p, shell_only=False):
"""
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
"""
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else _ <= 0 | [
"def",
"contains",
"(",
"ell",
",",
"p",
",",
"shell_only",
"=",
"False",
")",
":",
"v",
"=",
"augment",
"(",
"p",
")",
"_",
"=",
"ell",
".",
"solve",
"(",
"v",
")",
"return",
"N",
".",
"allclose",
"(",
"_",
",",
"0",
")",
"if",
"shell_only",
... | Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False). | [
"Check",
"to",
"see",
"whether",
"point",
"is",
"inside",
"conic",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L57-L67 | train | 52,914 |
davenquinn/Attitude | attitude/geom/conics.py | Conic.major_axes | def major_axes(ell):
"""
Gets major axes of ellipsoids
"""
_ = ell[:-1,:-1]
U,s,V = N.linalg.svd(_)
scalar = -(ell.sum()-_.sum())
return N.sqrt(s*scalar)*V | python | def major_axes(ell):
"""
Gets major axes of ellipsoids
"""
_ = ell[:-1,:-1]
U,s,V = N.linalg.svd(_)
scalar = -(ell.sum()-_.sum())
return N.sqrt(s*scalar)*V | [
"def",
"major_axes",
"(",
"ell",
")",
":",
"_",
"=",
"ell",
"[",
":",
"-",
"1",
",",
":",
"-",
"1",
"]",
"U",
",",
"s",
",",
"V",
"=",
"N",
".",
"linalg",
".",
"svd",
"(",
"_",
")",
"scalar",
"=",
"-",
"(",
"ell",
".",
"sum",
"(",
")",
... | Gets major axes of ellipsoids | [
"Gets",
"major",
"axes",
"of",
"ellipsoids"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L80-L87 | train | 52,915 |
davenquinn/Attitude | attitude/geom/conics.py | Conic.translate | def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1,-1] = -vector
return conic.transform(T) | python | def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1,-1] = -vector
return conic.transform(T) | [
"def",
"translate",
"(",
"conic",
",",
"vector",
")",
":",
"# Translation matrix",
"T",
"=",
"N",
".",
"identity",
"(",
"len",
"(",
"conic",
")",
")",
"T",
"[",
":",
"-",
"1",
",",
"-",
"1",
"]",
"=",
"-",
"vector",
"return",
"conic",
".",
"trans... | Translates a conic by a vector | [
"Translates",
"a",
"conic",
"by",
"a",
"vector"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L120-L127 | train | 52,916 |
davenquinn/Attitude | attitude/geom/conics.py | Conic.pole | def pole(conic, plane):
"""
Calculates the pole of a polar plane for
a given conic section.
"""
v = dot(N.linalg.inv(conic),plane)
return v[:-1]/v[-1] | python | def pole(conic, plane):
"""
Calculates the pole of a polar plane for
a given conic section.
"""
v = dot(N.linalg.inv(conic),plane)
return v[:-1]/v[-1] | [
"def",
"pole",
"(",
"conic",
",",
"plane",
")",
":",
"v",
"=",
"dot",
"(",
"N",
".",
"linalg",
".",
"inv",
"(",
"conic",
")",
",",
"plane",
")",
"return",
"v",
"[",
":",
"-",
"1",
"]",
"/",
"v",
"[",
"-",
"1",
"]"
] | Calculates the pole of a polar plane for
a given conic section. | [
"Calculates",
"the",
"pole",
"of",
"a",
"polar",
"plane",
"for",
"a",
"given",
"conic",
"section",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L139-L145 | train | 52,917 |
davenquinn/Attitude | attitude/geom/conics.py | Conic.projection | def projection(self, **kwargs):
"""
The elliptical cut of an ellipsoidal
conic describing all points of tangency
to the conic as viewed from the origin.
"""
viewpoint = kwargs.pop('viewpoint', None)
if viewpoint is None:
ndim = self.shape[0]-1
viewpoint = N.zeros(ndim)
plane = self.polar_plane(viewpoint)
return self.slice(plane, **kwargs) | python | def projection(self, **kwargs):
"""
The elliptical cut of an ellipsoidal
conic describing all points of tangency
to the conic as viewed from the origin.
"""
viewpoint = kwargs.pop('viewpoint', None)
if viewpoint is None:
ndim = self.shape[0]-1
viewpoint = N.zeros(ndim)
plane = self.polar_plane(viewpoint)
return self.slice(plane, **kwargs) | [
"def",
"projection",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"viewpoint",
"=",
"kwargs",
".",
"pop",
"(",
"'viewpoint'",
",",
"None",
")",
"if",
"viewpoint",
"is",
"None",
":",
"ndim",
"=",
"self",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
"... | The elliptical cut of an ellipsoidal
conic describing all points of tangency
to the conic as viewed from the origin. | [
"The",
"elliptical",
"cut",
"of",
"an",
"ellipsoidal",
"conic",
"describing",
"all",
"points",
"of",
"tangency",
"to",
"the",
"conic",
"as",
"viewed",
"from",
"the",
"origin",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L181-L192 | train | 52,918 |
ivanprjcts/sdklib | sdklib/http/renderers.py | guess_file_name_stream_type_header | def guess_file_name_stream_type_header(args):
"""
Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filename, file stream, file type, file header
"""
ftype = None
fheader = None
if isinstance(args, (tuple, list)):
if len(args) == 2:
fname, fstream = args
elif len(args) == 3:
fname, fstream, ftype = args
else:
fname, fstream, ftype, fheader = args
else:
fname, fstream = guess_filename_stream(args)
ftype = guess_content_type(fname)
if isinstance(fstream, (str, bytes, bytearray)):
fdata = fstream
else:
fdata = fstream.read()
return fname, fdata, ftype, fheader | python | def guess_file_name_stream_type_header(args):
"""
Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filename, file stream, file type, file header
"""
ftype = None
fheader = None
if isinstance(args, (tuple, list)):
if len(args) == 2:
fname, fstream = args
elif len(args) == 3:
fname, fstream, ftype = args
else:
fname, fstream, ftype, fheader = args
else:
fname, fstream = guess_filename_stream(args)
ftype = guess_content_type(fname)
if isinstance(fstream, (str, bytes, bytearray)):
fdata = fstream
else:
fdata = fstream.read()
return fname, fdata, ftype, fheader | [
"def",
"guess_file_name_stream_type_header",
"(",
"args",
")",
":",
"ftype",
"=",
"None",
"fheader",
"=",
"None",
"if",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"fname",
... | Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filename, file stream, file type, file header | [
"Guess",
"filename",
"file",
"stream",
"file",
"type",
"file",
"header",
"from",
"args",
"."
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L52-L77 | train | 52,919 |
ivanprjcts/sdklib | sdklib/http/renderers.py | FormRenderer.encode_params | def encode_params(self, data=None, **kwargs):
"""
Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
collection_format = kwargs.get("collection_format", self.collection_format)
output_str = kwargs.get("output_str", self.output_str)
sort = kwargs.get("sort", self.sort)
if data is None:
return "", self.content_type
elif isinstance(data, (str, bytes)):
return data, self.content_type
elif hasattr(data, 'read'):
return data, self.content_type
elif collection_format == 'multi' and hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data, sort=sort):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else to_string(v, lang=output_str)))
return urlencode(result, doseq=True), self.content_type
elif collection_format == 'encoded' and hasattr(data, '__iter__'):
return urlencode(data, doseq=False), self.content_type
elif hasattr(data, '__iter__'):
results = []
for k, vs in to_key_val_dict(data).items():
if isinstance(vs, list):
v = self.COLLECTION_SEPARATORS[collection_format].join(quote_plus(e) for e in vs)
key = k + '[]'
else:
v = quote_plus(vs)
key = k
results.append("%s=%s" % (key, v))
return '&'.join(results), self.content_type
else:
return data, self.content_type | python | def encode_params(self, data=None, **kwargs):
"""
Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
collection_format = kwargs.get("collection_format", self.collection_format)
output_str = kwargs.get("output_str", self.output_str)
sort = kwargs.get("sort", self.sort)
if data is None:
return "", self.content_type
elif isinstance(data, (str, bytes)):
return data, self.content_type
elif hasattr(data, 'read'):
return data, self.content_type
elif collection_format == 'multi' and hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data, sort=sort):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else to_string(v, lang=output_str)))
return urlencode(result, doseq=True), self.content_type
elif collection_format == 'encoded' and hasattr(data, '__iter__'):
return urlencode(data, doseq=False), self.content_type
elif hasattr(data, '__iter__'):
results = []
for k, vs in to_key_val_dict(data).items():
if isinstance(vs, list):
v = self.COLLECTION_SEPARATORS[collection_format].join(quote_plus(e) for e in vs)
key = k + '[]'
else:
v = quote_plus(vs)
key = k
results.append("%s=%s" % (key, v))
return '&'.join(results), self.content_type
else:
return data, self.content_type | [
"def",
"encode_params",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"collection_format",
"=",
"kwargs",
".",
"get",
"(",
"\"collection_format\"",
",",
"self",
".",
"collection_format",
")",
"output_str",
"=",
"kwargs",
".",
"g... | Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict. | [
"Encode",
"parameters",
"in",
"a",
"piece",
"of",
"data",
".",
"Will",
"successfully",
"encode",
"parameters",
"when",
"passed",
"as",
"a",
"dict",
"or",
"a",
"list",
"of",
"2",
"-",
"tuples",
".",
"Order",
"is",
"retained",
"if",
"data",
"is",
"a",
"l... | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L161-L203 | train | 52,920 |
davenquinn/Attitude | attitude/display/plot/cov_types/misc.py | ci | def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis) | python | def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis) | [
"def",
"ci",
"(",
"a",
",",
"which",
"=",
"95",
",",
"axis",
"=",
"None",
")",
":",
"p",
"=",
"50",
"-",
"which",
"/",
"2",
",",
"50",
"+",
"which",
"/",
"2",
"return",
"percentiles",
"(",
"a",
",",
"p",
",",
"axis",
")"
] | Return a percentile range from an array of values. | [
"Return",
"a",
"percentile",
"range",
"from",
"an",
"array",
"of",
"values",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/cov_types/misc.py#L40-L43 | train | 52,921 |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | get_config_string_option | def get_config_string_option(parser: ConfigParser,
section: str,
option: str,
default: str = None) -> str:
"""
Retrieves a string value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent
"""
if not parser.has_section(section):
raise ValueError("config missing section: " + section)
return parser.get(section, option, fallback=default) | python | def get_config_string_option(parser: ConfigParser,
section: str,
option: str,
default: str = None) -> str:
"""
Retrieves a string value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent
"""
if not parser.has_section(section):
raise ValueError("config missing section: " + section)
return parser.get(section, option, fallback=default) | [
"def",
"get_config_string_option",
"(",
"parser",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"option",
":",
"str",
",",
"default",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"not",
"parser",
".",
"has_section",
"(",
"section",
")",
... | Retrieves a string value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent | [
"Retrieves",
"a",
"string",
"value",
"from",
"a",
"parser",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L42-L64 | train | 52,922 |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | read_config_string_options | def read_config_string_options(obj: Any,
parser: ConfigParser,
section: str,
options: Iterable[str],
default: str = None) -> None:
"""
Reads config options and writes them as attributes of ``obj``, with
attribute names as per ``options``.
Args:
obj: the object to modify
parser: instance of :class:`ConfigParser`
section: section name within config file
options: option (variable) names within that section
default: value to use for any missing options
Returns:
"""
# enforce_str removed; ConfigParser always returns strings unless asked
# specifically
for o in options:
setattr(obj, o, get_config_string_option(parser, section, o,
default=default)) | python | def read_config_string_options(obj: Any,
parser: ConfigParser,
section: str,
options: Iterable[str],
default: str = None) -> None:
"""
Reads config options and writes them as attributes of ``obj``, with
attribute names as per ``options``.
Args:
obj: the object to modify
parser: instance of :class:`ConfigParser`
section: section name within config file
options: option (variable) names within that section
default: value to use for any missing options
Returns:
"""
# enforce_str removed; ConfigParser always returns strings unless asked
# specifically
for o in options:
setattr(obj, o, get_config_string_option(parser, section, o,
default=default)) | [
"def",
"read_config_string_options",
"(",
"obj",
":",
"Any",
",",
"parser",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"options",
":",
"Iterable",
"[",
"str",
"]",
",",
"default",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"# enforce_str... | Reads config options and writes them as attributes of ``obj``, with
attribute names as per ``options``.
Args:
obj: the object to modify
parser: instance of :class:`ConfigParser`
section: section name within config file
options: option (variable) names within that section
default: value to use for any missing options
Returns: | [
"Reads",
"config",
"options",
"and",
"writes",
"them",
"as",
"attributes",
"of",
"obj",
"with",
"attribute",
"names",
"as",
"per",
"options",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L67-L90 | train | 52,923 |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | get_config_bool_option | def get_config_bool_option(parser: ConfigParser,
section: str,
option: str,
default: bool = None) -> bool:
"""
Retrieves a boolean value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent
"""
if not parser.has_section(section):
raise ValueError("config missing section: " + section)
return parser.getboolean(section, option, fallback=default) | python | def get_config_bool_option(parser: ConfigParser,
section: str,
option: str,
default: bool = None) -> bool:
"""
Retrieves a boolean value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent
"""
if not parser.has_section(section):
raise ValueError("config missing section: " + section)
return parser.getboolean(section, option, fallback=default) | [
"def",
"get_config_bool_option",
"(",
"parser",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"option",
":",
"str",
",",
"default",
":",
"bool",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"not",
"parser",
".",
"has_section",
"(",
"section",
")",
... | Retrieves a boolean value from a parser.
Args:
parser: instance of :class:`ConfigParser`
section: section name within config file
option: option (variable) name within that section
default: value to return if option is absent
Returns:
string value
Raises:
ValueError: if the section is absent | [
"Retrieves",
"a",
"boolean",
"value",
"from",
"a",
"parser",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L138-L160 | train | 52,924 |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | get_config_parameter | def get_config_parameter(config: ConfigParser,
section: str,
param: str,
fn: Callable[[Any], Any],
default: Any) -> Any:
"""
Fetch parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
fn: function to apply to string parameter (e.g. ``int``)
default: default value
Returns:
parameter value, or ``None`` if ``default is None``, or ``fn(default)``
"""
try:
value = fn(config.get(section, param))
except (TypeError, ValueError, NoOptionError):
log.warning(
"Configuration variable {} not found or improper in section [{}]; "
"using default of {!r}", param, section, default)
if default is None:
value = default
else:
value = fn(default)
return value | python | def get_config_parameter(config: ConfigParser,
section: str,
param: str,
fn: Callable[[Any], Any],
default: Any) -> Any:
"""
Fetch parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
fn: function to apply to string parameter (e.g. ``int``)
default: default value
Returns:
parameter value, or ``None`` if ``default is None``, or ``fn(default)``
"""
try:
value = fn(config.get(section, param))
except (TypeError, ValueError, NoOptionError):
log.warning(
"Configuration variable {} not found or improper in section [{}]; "
"using default of {!r}", param, section, default)
if default is None:
value = default
else:
value = fn(default)
return value | [
"def",
"get_config_parameter",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"fn",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
",",
"default",
":",
"Any",
")",
"->",
"Any",
":",
"try",
":... | Fetch parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
fn: function to apply to string parameter (e.g. ``int``)
default: default value
Returns:
parameter value, or ``None`` if ``default is None``, or ``fn(default)`` | [
"Fetch",
"parameter",
"from",
"configparser",
".",
"INI",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L171-L199 | train | 52,925 |
RudolfCardinal/pythonlib | cardinal_pythonlib/configfiles.py | get_config_parameter_boolean | def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
"""
Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default
"""
try:
value = config.getboolean(section, param)
except (TypeError, ValueError, NoOptionError):
log.warning(
"Configuration variable {} not found or improper in section [{}]; "
"using default of {!r}", param, section, default)
value = default
return value | python | def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
"""
Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default
"""
try:
value = config.getboolean(section, param)
except (TypeError, ValueError, NoOptionError):
log.warning(
"Configuration variable {} not found or improper in section [{}]; "
"using default of {!r}", param, section, default)
value = default
return value | [
"def",
"get_config_parameter_boolean",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"default",
":",
"bool",
")",
"->",
"bool",
":",
"try",
":",
"value",
"=",
"config",
".",
"getboolean",
"(",
"section",
"... | Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default | [
"Get",
"Boolean",
"parameter",
"from",
"configparser",
".",
"INI",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L202-L224 | train | 52,926 |
AndrewWalker/glud | glud/predicates.py | is_definition | def is_definition(cursor):
"""Test if a cursor refers to a definition
This occurs when the cursor has a definition, and shares the location of that definiton
"""
defn = cursor.get_definition()
return (defn is not None) and (cursor.location == defn.location) | python | def is_definition(cursor):
"""Test if a cursor refers to a definition
This occurs when the cursor has a definition, and shares the location of that definiton
"""
defn = cursor.get_definition()
return (defn is not None) and (cursor.location == defn.location) | [
"def",
"is_definition",
"(",
"cursor",
")",
":",
"defn",
"=",
"cursor",
".",
"get_definition",
"(",
")",
"return",
"(",
"defn",
"is",
"not",
"None",
")",
"and",
"(",
"cursor",
".",
"location",
"==",
"defn",
".",
"location",
")"
] | Test if a cursor refers to a definition
This occurs when the cursor has a definition, and shares the location of that definiton | [
"Test",
"if",
"a",
"cursor",
"refers",
"to",
"a",
"definition"
] | 57de000627fed13d0c383f131163795b09549257 | https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/predicates.py#L38-L44 | train | 52,927 |
davenquinn/Attitude | attitude/error/__init__.py | asymptotes | def asymptotes(hyp, n=1000):
"""
Gets a cone of asymptotes for hyperbola
"""
assert N.linalg.norm(hyp.center()) == 0
u = N.linspace(0,2*N.pi,n)
_ = N.ones(len(u))
angles = N.array([N.cos(u),N.sin(u),_]).T
return dot(angles,hyp[:-1,:-1]) | python | def asymptotes(hyp, n=1000):
"""
Gets a cone of asymptotes for hyperbola
"""
assert N.linalg.norm(hyp.center()) == 0
u = N.linspace(0,2*N.pi,n)
_ = N.ones(len(u))
angles = N.array([N.cos(u),N.sin(u),_]).T
return dot(angles,hyp[:-1,:-1]) | [
"def",
"asymptotes",
"(",
"hyp",
",",
"n",
"=",
"1000",
")",
":",
"assert",
"N",
".",
"linalg",
".",
"norm",
"(",
"hyp",
".",
"center",
"(",
")",
")",
"==",
"0",
"u",
"=",
"N",
".",
"linspace",
"(",
"0",
",",
"2",
"*",
"N",
".",
"pi",
",",
... | Gets a cone of asymptotes for hyperbola | [
"Gets",
"a",
"cone",
"of",
"asymptotes",
"for",
"hyperbola"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/__init__.py#L12-L21 | train | 52,928 |
davenquinn/Attitude | attitude/error/__init__.py | pca_to_mapping | def pca_to_mapping(pca,**extra_props):
"""
A helper to return a mapping of a PCA result set suitable for
reconstructing a planar error surface in other software packages
kwargs: method (defaults to sampling axes)
"""
from .axes import sampling_axes
method = extra_props.pop('method',sampling_axes)
return dict(
axes=pca.axes.tolist(),
covariance=method(pca).tolist(),
**extra_props) | python | def pca_to_mapping(pca,**extra_props):
"""
A helper to return a mapping of a PCA result set suitable for
reconstructing a planar error surface in other software packages
kwargs: method (defaults to sampling axes)
"""
from .axes import sampling_axes
method = extra_props.pop('method',sampling_axes)
return dict(
axes=pca.axes.tolist(),
covariance=method(pca).tolist(),
**extra_props) | [
"def",
"pca_to_mapping",
"(",
"pca",
",",
"*",
"*",
"extra_props",
")",
":",
"from",
".",
"axes",
"import",
"sampling_axes",
"method",
"=",
"extra_props",
".",
"pop",
"(",
"'method'",
",",
"sampling_axes",
")",
"return",
"dict",
"(",
"axes",
"=",
"pca",
... | A helper to return a mapping of a PCA result set suitable for
reconstructing a planar error surface in other software packages
kwargs: method (defaults to sampling axes) | [
"A",
"helper",
"to",
"return",
"a",
"mapping",
"of",
"a",
"PCA",
"result",
"set",
"suitable",
"for",
"reconstructing",
"a",
"planar",
"error",
"surface",
"in",
"other",
"software",
"packages"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/__init__.py#L23-L35 | train | 52,929 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | generic_service_main | def generic_service_main(cls: Type[WindowsService], name: str) -> None:
"""
Call this from your command-line entry point to manage a service.
- Via inherited functions, enables you to ``install``, ``update``,
``remove``, ``start``, ``stop``, and ``restart`` the service.
- Via our additional code, allows you to run the service function directly
from the command line in debug mode, using the ``debug`` command.
- Run with an invalid command like ``help`` to see help (!).
See
https://mail.python.org/pipermail/python-win32/2008-April/007299.html
Args:
cls: class deriving from :class:`WindowsService`
name: name of this service
"""
argc = len(sys.argv)
if argc == 1:
try:
print("Trying to start service directly...")
evtsrc_dll = os.path.abspath(servicemanager.__file__)
# noinspection PyUnresolvedReferences
servicemanager.PrepareToHostSingle(cls) # <-- sets up the service
# noinspection PyUnresolvedReferences
servicemanager.Initialize(name, evtsrc_dll)
# noinspection PyUnresolvedReferences
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
print("Failed: {}".format(details))
# print(repr(details.__dict__))
errnum = details.winerror
if errnum == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
elif argc == 2 and sys.argv[1] == 'debug':
s = cls()
s.run_debug()
else:
win32serviceutil.HandleCommandLine(cls) | python | def generic_service_main(cls: Type[WindowsService], name: str) -> None:
"""
Call this from your command-line entry point to manage a service.
- Via inherited functions, enables you to ``install``, ``update``,
``remove``, ``start``, ``stop``, and ``restart`` the service.
- Via our additional code, allows you to run the service function directly
from the command line in debug mode, using the ``debug`` command.
- Run with an invalid command like ``help`` to see help (!).
See
https://mail.python.org/pipermail/python-win32/2008-April/007299.html
Args:
cls: class deriving from :class:`WindowsService`
name: name of this service
"""
argc = len(sys.argv)
if argc == 1:
try:
print("Trying to start service directly...")
evtsrc_dll = os.path.abspath(servicemanager.__file__)
# noinspection PyUnresolvedReferences
servicemanager.PrepareToHostSingle(cls) # <-- sets up the service
# noinspection PyUnresolvedReferences
servicemanager.Initialize(name, evtsrc_dll)
# noinspection PyUnresolvedReferences
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
print("Failed: {}".format(details))
# print(repr(details.__dict__))
errnum = details.winerror
if errnum == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
elif argc == 2 and sys.argv[1] == 'debug':
s = cls()
s.run_debug()
else:
win32serviceutil.HandleCommandLine(cls) | [
"def",
"generic_service_main",
"(",
"cls",
":",
"Type",
"[",
"WindowsService",
"]",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"argc",
"=",
"len",
"(",
"sys",
".",
"argv",
")",
"if",
"argc",
"==",
"1",
":",
"try",
":",
"print",
"(",
"\"Trying... | Call this from your command-line entry point to manage a service.
- Via inherited functions, enables you to ``install``, ``update``,
``remove``, ``start``, ``stop``, and ``restart`` the service.
- Via our additional code, allows you to run the service function directly
from the command line in debug mode, using the ``debug`` command.
- Run with an invalid command like ``help`` to see help (!).
See
https://mail.python.org/pipermail/python-win32/2008-April/007299.html
Args:
cls: class deriving from :class:`WindowsService`
name: name of this service | [
"Call",
"this",
"from",
"your",
"command",
"-",
"line",
"entry",
"point",
"to",
"manage",
"a",
"service",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L1004-L1042 | train | 52,930 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.fullname | def fullname(self) -> str:
"""
Description of the process.
"""
fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs,
self.details.name)
if self.running:
fullname += " (PID={})".format(self.process.pid)
return fullname | python | def fullname(self) -> str:
"""
Description of the process.
"""
fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs,
self.details.name)
if self.running:
fullname += " (PID={})".format(self.process.pid)
return fullname | [
"def",
"fullname",
"(",
"self",
")",
"->",
"str",
":",
"fullname",
"=",
"\"Process {}/{} ({})\"",
".",
"format",
"(",
"self",
".",
"procnum",
",",
"self",
".",
"nprocs",
",",
"self",
".",
"details",
".",
"name",
")",
"if",
"self",
".",
"running",
":",
... | Description of the process. | [
"Description",
"of",
"the",
"process",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L375-L383 | train | 52,931 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.debug | def debug(self, msg: str) -> None:
"""
If we are being verbose, write a debug message to the Python disk log.
"""
if self.debugging:
s = "{}: {}".format(self.fullname, msg)
log.debug(s) | python | def debug(self, msg: str) -> None:
"""
If we are being verbose, write a debug message to the Python disk log.
"""
if self.debugging:
s = "{}: {}".format(self.fullname, msg)
log.debug(s) | [
"def",
"debug",
"(",
"self",
",",
"msg",
":",
"str",
")",
"->",
"None",
":",
"if",
"self",
".",
"debugging",
":",
"s",
"=",
"\"{}: {}\"",
".",
"format",
"(",
"self",
".",
"fullname",
",",
"msg",
")",
"log",
".",
"debug",
"(",
"s",
")"
] | If we are being verbose, write a debug message to the Python disk log. | [
"If",
"we",
"are",
"being",
"verbose",
"write",
"a",
"debug",
"message",
"to",
"the",
"Python",
"disk",
"log",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L389-L395 | train | 52,932 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.open_logs | def open_logs(self) -> None:
"""
Open Python disk logs.
"""
if self.details.logfile_out:
self.stdout = open(self.details.logfile_out, 'a')
else:
self.stdout = None
if self.details.logfile_err:
if self.details.logfile_err == self.details.logfile_out:
self.stderr = subprocess.STDOUT
else:
self.stderr = open(self.details.logfile_err, 'a')
else:
self.stderr = None | python | def open_logs(self) -> None:
"""
Open Python disk logs.
"""
if self.details.logfile_out:
self.stdout = open(self.details.logfile_out, 'a')
else:
self.stdout = None
if self.details.logfile_err:
if self.details.logfile_err == self.details.logfile_out:
self.stderr = subprocess.STDOUT
else:
self.stderr = open(self.details.logfile_err, 'a')
else:
self.stderr = None | [
"def",
"open_logs",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"details",
".",
"logfile_out",
":",
"self",
".",
"stdout",
"=",
"open",
"(",
"self",
".",
"details",
".",
"logfile_out",
",",
"'a'",
")",
"else",
":",
"self",
".",
"stdout",
... | Open Python disk logs. | [
"Open",
"Python",
"disk",
"logs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L431-L445 | train | 52,933 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.close_logs | def close_logs(self) -> None:
"""
Close Python disk logs.
"""
if self.stdout is not None:
self.stdout.close()
self.stdout = None
if self.stderr is not None and self.stderr != subprocess.STDOUT:
self.stderr.close()
self.stderr = None | python | def close_logs(self) -> None:
"""
Close Python disk logs.
"""
if self.stdout is not None:
self.stdout.close()
self.stdout = None
if self.stderr is not None and self.stderr != subprocess.STDOUT:
self.stderr.close()
self.stderr = None | [
"def",
"close_logs",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"stdout",
"is",
"not",
"None",
":",
"self",
".",
"stdout",
".",
"close",
"(",
")",
"self",
".",
"stdout",
"=",
"None",
"if",
"self",
".",
"stderr",
"is",
"not",
"None",
... | Close Python disk logs. | [
"Close",
"Python",
"disk",
"logs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L447-L456 | train | 52,934 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.start | def start(self) -> None:
"""
Starts a subprocess. Optionally routes its output to our disk logs.
"""
if self.running:
return
self.info("Starting: {} (with logs stdout={}, stderr={})".format(
self.details.procargs,
self.details.logfile_out,
self.details.logfile_err))
self.open_logs()
creationflags = CREATE_NEW_PROCESS_GROUP if WINDOWS else 0
# self.warning("creationflags: {}".format(creationflags))
self.process = subprocess.Popen(self.details.procargs, stdin=None,
stdout=self.stdout, stderr=self.stderr,
creationflags=creationflags)
self.running = True | python | def start(self) -> None:
"""
Starts a subprocess. Optionally routes its output to our disk logs.
"""
if self.running:
return
self.info("Starting: {} (with logs stdout={}, stderr={})".format(
self.details.procargs,
self.details.logfile_out,
self.details.logfile_err))
self.open_logs()
creationflags = CREATE_NEW_PROCESS_GROUP if WINDOWS else 0
# self.warning("creationflags: {}".format(creationflags))
self.process = subprocess.Popen(self.details.procargs, stdin=None,
stdout=self.stdout, stderr=self.stderr,
creationflags=creationflags)
self.running = True | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"running",
":",
"return",
"self",
".",
"info",
"(",
"\"Starting: {} (with logs stdout={}, stderr={})\"",
".",
"format",
"(",
"self",
".",
"details",
".",
"procargs",
",",
"self",
".",
... | Starts a subprocess. Optionally routes its output to our disk logs. | [
"Starts",
"a",
"subprocess",
".",
"Optionally",
"routes",
"its",
"output",
"to",
"our",
"disk",
"logs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L462-L478 | train | 52,935 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.stop | def stop(self) -> None:
"""
Stops a subprocess.
Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead.
.. todo::
cardinal_pythonlib.winservice.ProcessManager._kill: make
it reliable under Windows
"""
if not self.running:
return
try:
self.wait(timeout_s=0)
# If we get here: stopped already
except subprocess.TimeoutExpired: # still running
for kill_level in self.ALL_KILL_LEVELS:
tried_to_kill = self._terminate(level=kill_level) # please stop
if tried_to_kill:
try:
self.wait(timeout_s=self.kill_timeout_sec)
break
except subprocess.TimeoutExpired: # failed to close
self.warning("Subprocess didn't stop when asked")
pass # carry on escalating
self.close_logs()
self.running = False | python | def stop(self) -> None:
"""
Stops a subprocess.
Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead.
.. todo::
cardinal_pythonlib.winservice.ProcessManager._kill: make
it reliable under Windows
"""
if not self.running:
return
try:
self.wait(timeout_s=0)
# If we get here: stopped already
except subprocess.TimeoutExpired: # still running
for kill_level in self.ALL_KILL_LEVELS:
tried_to_kill = self._terminate(level=kill_level) # please stop
if tried_to_kill:
try:
self.wait(timeout_s=self.kill_timeout_sec)
break
except subprocess.TimeoutExpired: # failed to close
self.warning("Subprocess didn't stop when asked")
pass # carry on escalating
self.close_logs()
self.running = False | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"try",
":",
"self",
".",
"wait",
"(",
"timeout_s",
"=",
"0",
")",
"# If we get here: stopped already",
"except",
"subprocess",
".",
"TimeoutExpired",
":... | Stops a subprocess.
Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead.
.. todo::
cardinal_pythonlib.winservice.ProcessManager._kill: make
it reliable under Windows | [
"Stops",
"a",
"subprocess",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L480-L506 | train | 52,936 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | ProcessManager.wait | def wait(self, timeout_s: float = None) -> int:
"""
Wait for up to ``timeout_s`` for the child process to finish.
Args:
timeout_s: maximum time to wait or ``None`` to wait forever
Returns:
process return code; or ``0`` if it wasn't running, or ``1`` if
it managed to exit without a return code
Raises:
subprocess.TimeoutExpired: if the process continues to run
"""
if not self.running:
return 0
retcode = self.process.wait(timeout=timeout_s)
# We won't get further unless the process has stopped.
if retcode is None:
self.error("Subprocess finished, but return code was None")
retcode = 1 # we're promising to return an int
elif retcode == 0:
self.info("Subprocess finished cleanly (return code 0).")
else:
self.error(
"Subprocess finished, but FAILED (return code {}). "
"Logs were: {} (stdout), {} (stderr)".format(
retcode,
self.details.logfile_out,
self.details.logfile_err))
self.running = False
return retcode | python | def wait(self, timeout_s: float = None) -> int:
"""
Wait for up to ``timeout_s`` for the child process to finish.
Args:
timeout_s: maximum time to wait or ``None`` to wait forever
Returns:
process return code; or ``0`` if it wasn't running, or ``1`` if
it managed to exit without a return code
Raises:
subprocess.TimeoutExpired: if the process continues to run
"""
if not self.running:
return 0
retcode = self.process.wait(timeout=timeout_s)
# We won't get further unless the process has stopped.
if retcode is None:
self.error("Subprocess finished, but return code was None")
retcode = 1 # we're promising to return an int
elif retcode == 0:
self.info("Subprocess finished cleanly (return code 0).")
else:
self.error(
"Subprocess finished, but FAILED (return code {}). "
"Logs were: {} (stdout), {} (stderr)".format(
retcode,
self.details.logfile_out,
self.details.logfile_err))
self.running = False
return retcode | [
"def",
"wait",
"(",
"self",
",",
"timeout_s",
":",
"float",
"=",
"None",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"0",
"retcode",
"=",
"self",
".",
"process",
".",
"wait",
"(",
"timeout",
"=",
"timeout_s",
")",
"# ... | Wait for up to ``timeout_s`` for the child process to finish.
Args:
timeout_s: maximum time to wait or ``None`` to wait forever
Returns:
process return code; or ``0`` if it wasn't running, or ``1`` if
it managed to exit without a return code
Raises:
subprocess.TimeoutExpired: if the process continues to run | [
"Wait",
"for",
"up",
"to",
"timeout_s",
"for",
"the",
"child",
"process",
"to",
"finish",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L695-L727 | train | 52,937 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | WindowsService.SvcStop | def SvcStop(self) -> None:
"""
Called when the service is being shut down.
"""
# tell the SCM we're shutting down
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(self.h_stop_event) | python | def SvcStop(self) -> None:
"""
Called when the service is being shut down.
"""
# tell the SCM we're shutting down
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(self.h_stop_event) | [
"def",
"SvcStop",
"(",
"self",
")",
"->",
"None",
":",
"# tell the SCM we're shutting down",
"# noinspection PyUnresolvedReferences",
"self",
".",
"ReportServiceStatus",
"(",
"win32service",
".",
"SERVICE_STOP_PENDING",
")",
"# fire the stop event",
"win32event",
".",
"SetE... | Called when the service is being shut down. | [
"Called",
"when",
"the",
"service",
"is",
"being",
"shut",
"down",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L812-L820 | train | 52,938 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | WindowsService.SvcDoRun | def SvcDoRun(self) -> None:
"""
Called when the service is started.
"""
# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);
# that is done by the framework (see win32serviceutil.py).
# Similarly, no need to report a SERVICE_STOP_PENDING on exit.
# noinspection PyUnresolvedReferences
self.debug("Sending PYS_SERVICE_STARTED message")
# noinspection PyUnresolvedReferences
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# self.test_service() # test service
self.main() # real service
# noinspection PyUnresolvedReferences
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOPPED) | python | def SvcDoRun(self) -> None:
"""
Called when the service is started.
"""
# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);
# that is done by the framework (see win32serviceutil.py).
# Similarly, no need to report a SERVICE_STOP_PENDING on exit.
# noinspection PyUnresolvedReferences
self.debug("Sending PYS_SERVICE_STARTED message")
# noinspection PyUnresolvedReferences
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
# self.test_service() # test service
self.main() # real service
# noinspection PyUnresolvedReferences
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
# noinspection PyUnresolvedReferences
self.ReportServiceStatus(win32service.SERVICE_STOPPED) | [
"def",
"SvcDoRun",
"(",
"self",
")",
"->",
"None",
":",
"# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);",
"# that is done by the framework (see win32serviceutil.py).",
"# Similarly, no need to report a SERVICE_STOP_PENDING on exit.",
"# noinspection PyUnresolvedReferences... | Called when the service is started. | [
"Called",
"when",
"the",
"service",
"is",
"started",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L824-L846 | train | 52,939 |
RudolfCardinal/pythonlib | cardinal_pythonlib/winservice.py | WindowsService.run_processes | def run_processes(self,
procdetails: List[ProcessDetails],
subproc_run_timeout_sec: float = 1,
stop_event_timeout_ms: int = 1000,
kill_timeout_sec: float = 5) -> None:
"""
Run multiple child processes.
Args:
procdetails: list of :class:`ProcessDetails` objects (q.v.)
subproc_run_timeout_sec: time (in seconds) to wait for each process
when polling child processes to see how they're getting on
(default ``1``)
stop_event_timeout_ms: time to wait (in ms) while checking the
Windows stop event for this service (default ``1000``)
kill_timeout_sec: how long (in seconds) will we wait for the
subprocesses to end peacefully, before we try to kill them?
.. todo::
cardinal_pythonlib.winservice.WindowsService: NOT YET IMPLEMENTED:
Windows service autorestart
"""
# https://stackoverflow.com/questions/16333054
def cleanup():
self.debug("atexit function called: cleaning up")
for pmgr_ in self.process_managers:
pmgr_.stop()
atexit.register(cleanup)
# Set up process info
self.process_managers = [] # type: List[ProcessManager]
n = len(procdetails)
for i, details in enumerate(procdetails):
pmgr = ProcessManager(details, i + 1, n,
kill_timeout_sec=kill_timeout_sec,
debugging=self.debugging)
self.process_managers.append(pmgr)
# Start processes
for pmgr in self.process_managers:
pmgr.start()
self.info("All started")
# Run processes
something_running = True
stop_requested = False
subproc_failed = False
while something_running and not stop_requested and not subproc_failed:
if (win32event.WaitForSingleObject(
self.h_stop_event,
stop_event_timeout_ms) == win32event.WAIT_OBJECT_0):
stop_requested = True
self.info("Stop requested; stopping")
else:
something_running = False
for pmgr in self.process_managers:
if subproc_failed:
break
try:
retcode = pmgr.wait(timeout_s=subproc_run_timeout_sec)
if retcode != 0:
subproc_failed = True
except subprocess.TimeoutExpired:
something_running = True
# Kill any outstanding processes
#
# (a) Slow way
# for pmgr in self.process_managers:
# pmgr.stop()
#
# (b) Faster (slightly more parallel) way
# for pmgr in self.process_managers:
# pmgr.terminate()
# for pmgr in self.process_managers:
# pmgr.stop_having_terminated()
#
# ... No, it's bad if we leave things orphaned.
# Let's go for slow, clean code.
for pmgr in self.process_managers:
pmgr.stop()
self.info("All stopped") | python | def run_processes(self,
procdetails: List[ProcessDetails],
subproc_run_timeout_sec: float = 1,
stop_event_timeout_ms: int = 1000,
kill_timeout_sec: float = 5) -> None:
"""
Run multiple child processes.
Args:
procdetails: list of :class:`ProcessDetails` objects (q.v.)
subproc_run_timeout_sec: time (in seconds) to wait for each process
when polling child processes to see how they're getting on
(default ``1``)
stop_event_timeout_ms: time to wait (in ms) while checking the
Windows stop event for this service (default ``1000``)
kill_timeout_sec: how long (in seconds) will we wait for the
subprocesses to end peacefully, before we try to kill them?
.. todo::
cardinal_pythonlib.winservice.WindowsService: NOT YET IMPLEMENTED:
Windows service autorestart
"""
# https://stackoverflow.com/questions/16333054
def cleanup():
self.debug("atexit function called: cleaning up")
for pmgr_ in self.process_managers:
pmgr_.stop()
atexit.register(cleanup)
# Set up process info
self.process_managers = [] # type: List[ProcessManager]
n = len(procdetails)
for i, details in enumerate(procdetails):
pmgr = ProcessManager(details, i + 1, n,
kill_timeout_sec=kill_timeout_sec,
debugging=self.debugging)
self.process_managers.append(pmgr)
# Start processes
for pmgr in self.process_managers:
pmgr.start()
self.info("All started")
# Run processes
something_running = True
stop_requested = False
subproc_failed = False
while something_running and not stop_requested and not subproc_failed:
if (win32event.WaitForSingleObject(
self.h_stop_event,
stop_event_timeout_ms) == win32event.WAIT_OBJECT_0):
stop_requested = True
self.info("Stop requested; stopping")
else:
something_running = False
for pmgr in self.process_managers:
if subproc_failed:
break
try:
retcode = pmgr.wait(timeout_s=subproc_run_timeout_sec)
if retcode != 0:
subproc_failed = True
except subprocess.TimeoutExpired:
something_running = True
# Kill any outstanding processes
#
# (a) Slow way
# for pmgr in self.process_managers:
# pmgr.stop()
#
# (b) Faster (slightly more parallel) way
# for pmgr in self.process_managers:
# pmgr.terminate()
# for pmgr in self.process_managers:
# pmgr.stop_having_terminated()
#
# ... No, it's bad if we leave things orphaned.
# Let's go for slow, clean code.
for pmgr in self.process_managers:
pmgr.stop()
self.info("All stopped") | [
"def",
"run_processes",
"(",
"self",
",",
"procdetails",
":",
"List",
"[",
"ProcessDetails",
"]",
",",
"subproc_run_timeout_sec",
":",
"float",
"=",
"1",
",",
"stop_event_timeout_ms",
":",
"int",
"=",
"1000",
",",
"kill_timeout_sec",
":",
"float",
"=",
"5",
... | Run multiple child processes.
Args:
procdetails: list of :class:`ProcessDetails` objects (q.v.)
subproc_run_timeout_sec: time (in seconds) to wait for each process
when polling child processes to see how they're getting on
(default ``1``)
stop_event_timeout_ms: time to wait (in ms) while checking the
Windows stop event for this service (default ``1000``)
kill_timeout_sec: how long (in seconds) will we wait for the
subprocesses to end peacefully, before we try to kill them?
.. todo::
cardinal_pythonlib.winservice.WindowsService: NOT YET IMPLEMENTED:
Windows service autorestart | [
"Run",
"multiple",
"child",
"processes",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L912-L997 | train | 52,940 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/admin.py | disable_bool_icon | def disable_bool_icon(
fieldname: str,
model) -> Callable[[Any], bool]:
"""
Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is broken; see ``files.py``
"""
# noinspection PyUnusedLocal
def func(self, obj):
return getattr(obj, fieldname)
func.boolean = False
func.admin_order_field = fieldname
# func.short_description = \
# model._meta.get_field_by_name(fieldname)[0].verbose_name
# get_field_by_name() deprecated in Django 1.9 and will go in 1.10
# https://docs.djangoproject.com/en/1.8/ref/models/meta/
# noinspection PyProtectedMember, PyUnresolvedReferences
func.short_description = \
model._meta.get_field(fieldname).verbose_name
return func | python | def disable_bool_icon(
fieldname: str,
model) -> Callable[[Any], bool]:
"""
Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is broken; see ``files.py``
"""
# noinspection PyUnusedLocal
def func(self, obj):
return getattr(obj, fieldname)
func.boolean = False
func.admin_order_field = fieldname
# func.short_description = \
# model._meta.get_field_by_name(fieldname)[0].verbose_name
# get_field_by_name() deprecated in Django 1.9 and will go in 1.10
# https://docs.djangoproject.com/en/1.8/ref/models/meta/
# noinspection PyProtectedMember, PyUnresolvedReferences
func.short_description = \
model._meta.get_field(fieldname).verbose_name
return func | [
"def",
"disable_bool_icon",
"(",
"fieldname",
":",
"str",
",",
"model",
")",
"->",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
":",
"# noinspection PyUnusedLocal",
"def",
"func",
"(",
"self",
",",
"obj",
")",
":",
"return",
"getattr",
"(",
"obj",... | Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is broken; see ``files.py`` | [
"Disable",
"boolean",
"icons",
"for",
"a",
"Django",
"ModelAdmin",
"field",
".",
"The",
"_meta",
"attribute",
"is",
"present",
"on",
"Django",
"model",
"classes",
"and",
"instances",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L43-L67 | train | 52,941 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/admin.py | admin_view_url | def admin_view_url(admin_site: AdminSite,
obj,
view_type: str = "change",
current_app: str = None) -> str:
"""
Get a Django admin site URL for an object.
"""
app_name = obj._meta.app_label.lower()
model_name = obj._meta.object_name.lower()
pk = obj.pk
viewname = "admin:{}_{}_{}".format(app_name, model_name, view_type)
if current_app is None:
current_app = admin_site.name
url = reverse(viewname, args=[pk], current_app=current_app)
return url | python | def admin_view_url(admin_site: AdminSite,
obj,
view_type: str = "change",
current_app: str = None) -> str:
"""
Get a Django admin site URL for an object.
"""
app_name = obj._meta.app_label.lower()
model_name = obj._meta.object_name.lower()
pk = obj.pk
viewname = "admin:{}_{}_{}".format(app_name, model_name, view_type)
if current_app is None:
current_app = admin_site.name
url = reverse(viewname, args=[pk], current_app=current_app)
return url | [
"def",
"admin_view_url",
"(",
"admin_site",
":",
"AdminSite",
",",
"obj",
",",
"view_type",
":",
"str",
"=",
"\"change\"",
",",
"current_app",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"app_name",
"=",
"obj",
".",
"_meta",
".",
"app_label",
".",
... | Get a Django admin site URL for an object. | [
"Get",
"a",
"Django",
"admin",
"site",
"URL",
"for",
"an",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L75-L89 | train | 52,942 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/admin.py | admin_view_fk_link | def admin_view_fk_link(modeladmin: ModelAdmin,
obj,
fkfield: str,
missing: str = "(None)",
use_str: bool = True,
view_type: str = "change",
current_app: str = None) -> str:
"""
Get a Django admin site URL for an object that's found from a foreign
key in our object of interest.
"""
if not hasattr(obj, fkfield):
return missing
linked_obj = getattr(obj, fkfield)
app_name = linked_obj._meta.app_label.lower()
model_name = linked_obj._meta.object_name.lower()
viewname = "admin:{}_{}_{}".format(app_name, model_name, view_type)
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls # noqa
if current_app is None:
current_app = modeladmin.admin_site.name
# ... plus a bit of home-grown magic; see Django source
url = reverse(viewname, args=[linked_obj.pk], current_app=current_app)
if use_str:
label = escape(str(linked_obj))
else:
label = "{} {}".format(escape(linked_obj._meta.object_name),
linked_obj.pk)
return '<a href="{}">{}</a>'.format(url, label) | python | def admin_view_fk_link(modeladmin: ModelAdmin,
obj,
fkfield: str,
missing: str = "(None)",
use_str: bool = True,
view_type: str = "change",
current_app: str = None) -> str:
"""
Get a Django admin site URL for an object that's found from a foreign
key in our object of interest.
"""
if not hasattr(obj, fkfield):
return missing
linked_obj = getattr(obj, fkfield)
app_name = linked_obj._meta.app_label.lower()
model_name = linked_obj._meta.object_name.lower()
viewname = "admin:{}_{}_{}".format(app_name, model_name, view_type)
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls # noqa
if current_app is None:
current_app = modeladmin.admin_site.name
# ... plus a bit of home-grown magic; see Django source
url = reverse(viewname, args=[linked_obj.pk], current_app=current_app)
if use_str:
label = escape(str(linked_obj))
else:
label = "{} {}".format(escape(linked_obj._meta.object_name),
linked_obj.pk)
return '<a href="{}">{}</a>'.format(url, label) | [
"def",
"admin_view_fk_link",
"(",
"modeladmin",
":",
"ModelAdmin",
",",
"obj",
",",
"fkfield",
":",
"str",
",",
"missing",
":",
"str",
"=",
"\"(None)\"",
",",
"use_str",
":",
"bool",
"=",
"True",
",",
"view_type",
":",
"str",
"=",
"\"change\"",
",",
"cur... | Get a Django admin site URL for an object that's found from a foreign
key in our object of interest. | [
"Get",
"a",
"Django",
"admin",
"site",
"URL",
"for",
"an",
"object",
"that",
"s",
"found",
"from",
"a",
"foreign",
"key",
"in",
"our",
"object",
"of",
"interest",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L93-L120 | train | 52,943 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dsp.py | lowpass_filter | def lowpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
cutoff_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a low-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
cutoff_freq_hz: filter cutoff frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1
"""
coeffs = firwin(
numtaps=numtaps,
cutoff=normalized_frequency(cutoff_freq_hz, sampling_freq_hz),
pass_zero=True
) # coefficients of a finite impulse response (FIR) filter using window method # noqa
filtered_data = lfilter(b=coeffs, a=1.0, x=data)
return filtered_data | python | def lowpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
cutoff_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a low-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
cutoff_freq_hz: filter cutoff frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1
"""
coeffs = firwin(
numtaps=numtaps,
cutoff=normalized_frequency(cutoff_freq_hz, sampling_freq_hz),
pass_zero=True
) # coefficients of a finite impulse response (FIR) filter using window method # noqa
filtered_data = lfilter(b=coeffs, a=1.0, x=data)
return filtered_data | [
"def",
"lowpass_filter",
"(",
"data",
":",
"FLOATS_TYPE",
",",
"sampling_freq_hz",
":",
"float",
",",
"cutoff_freq_hz",
":",
"float",
",",
"numtaps",
":",
"int",
")",
"->",
"FLOATS_TYPE",
":",
"coeffs",
"=",
"firwin",
"(",
"numtaps",
"=",
"numtaps",
",",
"... | Apply a low-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
cutoff_freq_hz: filter cutoff frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1 | [
"Apply",
"a",
"low",
"-",
"pass",
"filter",
"to",
"the",
"data",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L71-L97 | train | 52,944 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dsp.py | bandpass_filter | def bandpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
lower_freq_hz: float,
upper_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a band-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
lower_freq_hz: filter cutoff lower frequency in Hz
(or other consistent units)
upper_freq_hz: filter cutoff upper frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1
"""
f1 = normalized_frequency(lower_freq_hz, sampling_freq_hz)
f2 = normalized_frequency(upper_freq_hz, sampling_freq_hz)
coeffs = firwin(
numtaps=numtaps,
cutoff=[f1, f2],
pass_zero=False
)
filtered_data = lfilter(b=coeffs, a=1.0, x=data)
return filtered_data | python | def bandpass_filter(data: FLOATS_TYPE,
sampling_freq_hz: float,
lower_freq_hz: float,
upper_freq_hz: float,
numtaps: int) -> FLOATS_TYPE:
"""
Apply a band-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
lower_freq_hz: filter cutoff lower frequency in Hz
(or other consistent units)
upper_freq_hz: filter cutoff upper frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1
"""
f1 = normalized_frequency(lower_freq_hz, sampling_freq_hz)
f2 = normalized_frequency(upper_freq_hz, sampling_freq_hz)
coeffs = firwin(
numtaps=numtaps,
cutoff=[f1, f2],
pass_zero=False
)
filtered_data = lfilter(b=coeffs, a=1.0, x=data)
return filtered_data | [
"def",
"bandpass_filter",
"(",
"data",
":",
"FLOATS_TYPE",
",",
"sampling_freq_hz",
":",
"float",
",",
"lower_freq_hz",
":",
"float",
",",
"upper_freq_hz",
":",
"float",
",",
"numtaps",
":",
"int",
")",
"->",
"FLOATS_TYPE",
":",
"f1",
"=",
"normalized_frequenc... | Apply a band-pass filter to the data.
Args:
data: time series of the data
sampling_freq_hz: sampling frequency :math:`f_s`, in Hz
(or other consistent units)
lower_freq_hz: filter cutoff lower frequency in Hz
(or other consistent units)
upper_freq_hz: filter cutoff upper frequency in Hz
(or other consistent units)
numtaps: number of filter taps
Returns:
filtered data
Note: number of filter taps = filter order + 1 | [
"Apply",
"a",
"band",
"-",
"pass",
"filter",
"to",
"the",
"data",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L129-L160 | train | 52,945 |
davenquinn/Attitude | attitude/orientation/base.py | ellipse | def ellipse(center,covariance_matrix,level=1, n=1000):
"""Returns error ellipse in slope-azimuth space"""
# singular value decomposition
U, s, rotation_matrix = N.linalg.svd(covariance_matrix)
# semi-axes (largest first)
saxes = N.sqrt(s)*level ## If the _area_ of a 2s ellipse is twice that of a 1s ellipse
# If the _axes_ are supposed to be twice as long, then it should be N.sqrt(s)*width
u = N.linspace(0, 2*N.pi, n)
data = N.column_stack((saxes[0]*N.cos(u), saxes[1]*N.sin(u)))
# rotate data
return N.dot(data, rotation_matrix)+ center | python | def ellipse(center,covariance_matrix,level=1, n=1000):
"""Returns error ellipse in slope-azimuth space"""
# singular value decomposition
U, s, rotation_matrix = N.linalg.svd(covariance_matrix)
# semi-axes (largest first)
saxes = N.sqrt(s)*level ## If the _area_ of a 2s ellipse is twice that of a 1s ellipse
# If the _axes_ are supposed to be twice as long, then it should be N.sqrt(s)*width
u = N.linspace(0, 2*N.pi, n)
data = N.column_stack((saxes[0]*N.cos(u), saxes[1]*N.sin(u)))
# rotate data
return N.dot(data, rotation_matrix)+ center | [
"def",
"ellipse",
"(",
"center",
",",
"covariance_matrix",
",",
"level",
"=",
"1",
",",
"n",
"=",
"1000",
")",
":",
"# singular value decomposition",
"U",
",",
"s",
",",
"rotation_matrix",
"=",
"N",
".",
"linalg",
".",
"svd",
"(",
"covariance_matrix",
")",... | Returns error ellipse in slope-azimuth space | [
"Returns",
"error",
"ellipse",
"in",
"slope",
"-",
"azimuth",
"space"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/base.py#L16-L28 | train | 52,946 |
davenquinn/Attitude | attitude/orientation/base.py | BaseOrientation.to_mapping | def to_mapping(self,**values):
"""
Create a JSON-serializable representation of the plane that is usable with the
javascript frontend
"""
strike, dip, rake = self.strike_dip_rake()
min, max = self.angular_errors()
try:
disabled = self.disabled
except AttributeError:
disabled = False
mapping = dict(
uid=self.hash,
axes=self.axes.tolist(),
hyperbolic_axes=self.hyperbolic_axes.tolist(),
max_angular_error=max,
min_angular_error=min,
strike=strike,
dip=dip,
rake=rake,
disabled=disabled)
# Add in user-provided-values, overwriting if
# necessary
for k,v in values.items():
mapping[k] = v
return mapping | python | def to_mapping(self,**values):
"""
Create a JSON-serializable representation of the plane that is usable with the
javascript frontend
"""
strike, dip, rake = self.strike_dip_rake()
min, max = self.angular_errors()
try:
disabled = self.disabled
except AttributeError:
disabled = False
mapping = dict(
uid=self.hash,
axes=self.axes.tolist(),
hyperbolic_axes=self.hyperbolic_axes.tolist(),
max_angular_error=max,
min_angular_error=min,
strike=strike,
dip=dip,
rake=rake,
disabled=disabled)
# Add in user-provided-values, overwriting if
# necessary
for k,v in values.items():
mapping[k] = v
return mapping | [
"def",
"to_mapping",
"(",
"self",
",",
"*",
"*",
"values",
")",
":",
"strike",
",",
"dip",
",",
"rake",
"=",
"self",
".",
"strike_dip_rake",
"(",
")",
"min",
",",
"max",
"=",
"self",
".",
"angular_errors",
"(",
")",
"try",
":",
"disabled",
"=",
"se... | Create a JSON-serializable representation of the plane that is usable with the
javascript frontend | [
"Create",
"a",
"JSON",
"-",
"serializable",
"representation",
"of",
"the",
"plane",
"that",
"is",
"usable",
"with",
"the",
"javascript",
"frontend"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/base.py#L91-L119 | train | 52,947 |
RudolfCardinal/pythonlib | cardinal_pythonlib/subproc.py | run_multiple_processes | def run_multiple_processes(args_list: List[List[str]],
die_on_failure: bool = True) -> None:
"""
Fire up multiple processes, and wait for them to finihs.
Args:
args_list: command arguments for each process
die_on_failure: see :func:`wait_for_processes`
"""
for procargs in args_list:
start_process(procargs)
# Wait for them all to finish
wait_for_processes(die_on_failure=die_on_failure) | python | def run_multiple_processes(args_list: List[List[str]],
die_on_failure: bool = True) -> None:
"""
Fire up multiple processes, and wait for them to finihs.
Args:
args_list: command arguments for each process
die_on_failure: see :func:`wait_for_processes`
"""
for procargs in args_list:
start_process(procargs)
# Wait for them all to finish
wait_for_processes(die_on_failure=die_on_failure) | [
"def",
"run_multiple_processes",
"(",
"args_list",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"die_on_failure",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"for",
"procargs",
"in",
"args_list",
":",
"start_process",
"(",
"procargs",
")",
... | Fire up multiple processes, and wait for them to finihs.
Args:
args_list: command arguments for each process
die_on_failure: see :func:`wait_for_processes` | [
"Fire",
"up",
"multiple",
"processes",
"and",
"wait",
"for",
"them",
"to",
"finihs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L208-L220 | train | 52,948 |
RudolfCardinal/pythonlib | cardinal_pythonlib/subproc.py | AsynchronousFileReader.run | def run(self) -> None:
"""
Read lines and put them on the queue.
"""
fd = self._fd
encoding = self._encoding
line_terminators = self._line_terminators
queue = self._queue
buf = ""
while True:
try:
c = fd.read(1).decode(encoding)
except UnicodeDecodeError as e:
log.warning("Decoding error from {!r}: {!r}", self._cmdargs, e)
if self._suppress_decoding_errors:
continue
else:
raise
# log.critical("c={!r}, returncode={!r}", c, p.returncode)
if not c:
# Subprocess has finished
return
buf += c
# log.critical("buf={!r}", buf)
# noinspection PyTypeChecker
for t in line_terminators:
try:
t_idx = buf.index(t) + len(t) # include terminator
fragment = buf[:t_idx]
buf = buf[t_idx:]
queue.put(fragment)
except ValueError:
pass | python | def run(self) -> None:
"""
Read lines and put them on the queue.
"""
fd = self._fd
encoding = self._encoding
line_terminators = self._line_terminators
queue = self._queue
buf = ""
while True:
try:
c = fd.read(1).decode(encoding)
except UnicodeDecodeError as e:
log.warning("Decoding error from {!r}: {!r}", self._cmdargs, e)
if self._suppress_decoding_errors:
continue
else:
raise
# log.critical("c={!r}, returncode={!r}", c, p.returncode)
if not c:
# Subprocess has finished
return
buf += c
# log.critical("buf={!r}", buf)
# noinspection PyTypeChecker
for t in line_terminators:
try:
t_idx = buf.index(t) + len(t) # include terminator
fragment = buf[:t_idx]
buf = buf[t_idx:]
queue.put(fragment)
except ValueError:
pass | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"fd",
"=",
"self",
".",
"_fd",
"encoding",
"=",
"self",
".",
"_encoding",
"line_terminators",
"=",
"self",
".",
"_line_terminators",
"queue",
"=",
"self",
".",
"_queue",
"buf",
"=",
"\"\"",
"while",
"T... | Read lines and put them on the queue. | [
"Read",
"lines",
"and",
"put",
"them",
"on",
"the",
"queue",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L260-L292 | train | 52,949 |
The-Politico/politico-civic-geography | geography/management/commands/bootstrap/fixtures/_nation.py | NationFixtures.create_nation_fixtures | def create_nation_fixtures(self):
"""
Create national US and State Map
"""
SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR)
DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG)
shape = shapefile.Reader(
os.path.join(DOWNLOAD_PATH, "{}.shp".format(SHP_SLUG))
)
fields = shape.fields[1:]
field_names = [f[0] for f in fields]
features = []
for shp in shape.shapeRecords():
state = dict(zip(field_names, shp.record))
geodata = {
"type": "Feature",
"geometry": shp.shape.__geo_interface__,
"properties": {
"state": state["STATEFP"],
"name": state["NAME"],
},
}
features.append(geodata)
Geometry.objects.update_or_create(
division=self.NATION,
subdivision_level=self.STATE_LEVEL,
simplification=self.THRESHOLDS["nation"],
source=os.path.join(
self.SHP_SOURCE_BASE.format(self.YEAR), SHP_SLUG
)
+ ".zip",
series=self.YEAR,
defaults={
"topojson": self.toposimplify(
geojson.FeatureCollection(features),
self.THRESHOLDS["nation"],
)
},
)
geo, created = Geometry.objects.update_or_create(
division=self.NATION,
subdivision_level=self.COUNTY_LEVEL,
simplification=self.THRESHOLDS["nation"],
source=os.path.join(
self.SHP_SOURCE_BASE.format(self.YEAR), SHP_SLUG
)
+ ".zip",
series=self.YEAR,
defaults={"topojson": self.get_state_county_shps("00")},
)
tqdm.write("Nation\n")
tqdm.write(
self.TQDM_PREFIX
+ "> FIPS {} @ ~{}kb ".format(
"00", round(len(json.dumps(geo.topojson)) / 1000)
)
)
tqdm.write(self.style.SUCCESS("Done.\n")) | python | def create_nation_fixtures(self):
"""
Create national US and State Map
"""
SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR)
DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG)
shape = shapefile.Reader(
os.path.join(DOWNLOAD_PATH, "{}.shp".format(SHP_SLUG))
)
fields = shape.fields[1:]
field_names = [f[0] for f in fields]
features = []
for shp in shape.shapeRecords():
state = dict(zip(field_names, shp.record))
geodata = {
"type": "Feature",
"geometry": shp.shape.__geo_interface__,
"properties": {
"state": state["STATEFP"],
"name": state["NAME"],
},
}
features.append(geodata)
Geometry.objects.update_or_create(
division=self.NATION,
subdivision_level=self.STATE_LEVEL,
simplification=self.THRESHOLDS["nation"],
source=os.path.join(
self.SHP_SOURCE_BASE.format(self.YEAR), SHP_SLUG
)
+ ".zip",
series=self.YEAR,
defaults={
"topojson": self.toposimplify(
geojson.FeatureCollection(features),
self.THRESHOLDS["nation"],
)
},
)
geo, created = Geometry.objects.update_or_create(
division=self.NATION,
subdivision_level=self.COUNTY_LEVEL,
simplification=self.THRESHOLDS["nation"],
source=os.path.join(
self.SHP_SOURCE_BASE.format(self.YEAR), SHP_SLUG
)
+ ".zip",
series=self.YEAR,
defaults={"topojson": self.get_state_county_shps("00")},
)
tqdm.write("Nation\n")
tqdm.write(
self.TQDM_PREFIX
+ "> FIPS {} @ ~{}kb ".format(
"00", round(len(json.dumps(geo.topojson)) / 1000)
)
)
tqdm.write(self.style.SUCCESS("Done.\n")) | [
"def",
"create_nation_fixtures",
"(",
"self",
")",
":",
"SHP_SLUG",
"=",
"\"cb_{}_us_state_500k\"",
".",
"format",
"(",
"self",
".",
"YEAR",
")",
"DOWNLOAD_PATH",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"DOWNLOAD_DIRECTORY",
",",
"SHP_SLUG",
"... | Create national US and State Map | [
"Create",
"national",
"US",
"and",
"State",
"Map"
] | 032b3ee773b50b65cfe672f230dda772df0f89e0 | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/management/commands/bootstrap/fixtures/_nation.py#L12-L71 | train | 52,950 |
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(),
n_samples = pca.n,
strike=strike, dip=dip, rake=rake,
angular_errors=[2*N.degrees(i)
for i in angular_errors(hyp_axes)]) | 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(),
n_samples = pca.n,
strike=strike, dip=dip, rake=rake,
angular_errors=[2*N.degrees(i)
for i in angular_errors(hyp_axes)]) | [
"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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/docs/scripts/generate-json.py#L11-L26 | train | 52,951 |
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 orientations]
for o in orientations:
# Get rid of and recreate group membership
o.member_of = None
try:
grouped += o.members
for a in o.members:
a.member_of = o
except AttributeError:
pass
def find(uid):
try:
val = next(x for x in orientations if x.hash == uid)
if val in grouped:
raise GroupedPlaneError("{} is already in a group."
.format(val.hash))
return val
except StopIteration:
raise KeyError("No measurement of with hash {} found"
.format(uid))
for uid_list in groups:
vals = [find(uid) for uid in uid_list]
o = GroupedOrientation(*vals, **kwargs)
orientations.append(o)
return orientations | 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 orientations]
for o in orientations:
# Get rid of and recreate group membership
o.member_of = None
try:
grouped += o.members
for a in o.members:
a.member_of = o
except AttributeError:
pass
def find(uid):
try:
val = next(x for x in orientations if x.hash == uid)
if val in grouped:
raise GroupedPlaneError("{} is already in a group."
.format(val.hash))
return val
except StopIteration:
raise KeyError("No measurement of with hash {} found"
.format(uid))
for uid_list in groups:
vals = [find(uid) for uid in uid_list]
o = GroupedOrientation(*vals, **kwargs)
orientations.append(o)
return orientations | [
"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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/grouped.py#L35-L71 | train | 52,952 |
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:
:math:`y`
"""
# https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbols
if x is None or k is None or theta is None:
return None
# noinspection PyUnresolvedReferences
return 1 / (1 + np.exp(-k * (x - theta))) | 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:
:math:`y`
"""
# https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbols
if x is None or k is None or theta is None:
return None
# noinspection PyUnresolvedReferences
return 1 / (1 + np.exp(-k * (x - theta))) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_numpy.py#L102-L125 | train | 52,953 |
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)
idx.insert(i, feature['geometry'].bounds)
data_store[i] = feature
return data_store, idx | 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)
idx.insert(i, feature['geometry'].bounds)
data_store[i] = feature
return data_store, idx | [
"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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L107-L116 | train | 52,954 |
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:
# cache hit on geohash
self.hit += 1
#print self.hit, self.miss
return self.geohash_cache[key]
self.miss += 1
# cache miss on geohash
# project point to ESRI:102005
lat, lon = Geohash.decode(geohash)
proj_point = project([float(lon), float(lat)])
args = dict(buffer_size=buffer_size, multiple=multiple)
payload = self.get_object(proj_point, **args)
self.geohash_cache[key] = payload
return payload | 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:
# cache hit on geohash
self.hit += 1
#print self.hit, self.miss
return self.geohash_cache[key]
self.miss += 1
# cache miss on geohash
# project point to ESRI:102005
lat, lon = Geohash.decode(geohash)
proj_point = project([float(lon), float(lat)])
args = dict(buffer_size=buffer_size, multiple=multiple)
payload = self.get_object(proj_point, **args)
self.geohash_cache[key] = payload
return payload | [
"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"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L139-L157 | train | 52,955 |
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 reports
"""
suites = Converter.read_nose(in_file_nose)
Converter.write_unitth(suites, out_dir_unitth) | 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 reports
"""
suites = Converter.read_nose(in_file_nose)
Converter.write_unitth(suites, out_dir_unitth) | [
"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"
] | c37f10a8b74b291b3a12669113f4404b01b97586 | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L18-L26 | train | 52,956 |
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 = doc_xml.getElementsByTagName("testsuite")[0]
for case_xml in suite_xml.getElementsByTagName('testcase'):
classname = case_xml.getAttribute('classname')
if classname not in suites:
suites[classname] = []
case = {
'name': case_xml.getAttribute('name'),
'time': float(case_xml.getAttribute('time')),
}
skipped_xml = case_xml.getElementsByTagName('skipped')
if skipped_xml:
if skipped_xml[0].hasAttribute('type'):
type = skipped_xml[0].getAttribute('type')
else:
type = ''
case['skipped'] = {
'type': type,
'message': skipped_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in skipped_xml[0].childNodes]),
}
failure_xml = case_xml.getElementsByTagName('failure')
if failure_xml:
if failure_xml[0].hasAttribute('type'):
type = failure_xml[0].getAttribute('type')
else:
type = ''
case['failure'] = {
'type': type,
'message': failure_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in failure_xml[0].childNodes]),
}
error_xml = case_xml.getElementsByTagName('error')
if error_xml:
if error_xml[0].hasAttribute('type'):
type = error_xml[0].getAttribute('type')
else:
type = ''
case['error'] = {
'type': type,
'message': error_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in error_xml[0].childNodes]),
}
suites[classname].append(case)
return suites | 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 = doc_xml.getElementsByTagName("testsuite")[0]
for case_xml in suite_xml.getElementsByTagName('testcase'):
classname = case_xml.getAttribute('classname')
if classname not in suites:
suites[classname] = []
case = {
'name': case_xml.getAttribute('name'),
'time': float(case_xml.getAttribute('time')),
}
skipped_xml = case_xml.getElementsByTagName('skipped')
if skipped_xml:
if skipped_xml[0].hasAttribute('type'):
type = skipped_xml[0].getAttribute('type')
else:
type = ''
case['skipped'] = {
'type': type,
'message': skipped_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in skipped_xml[0].childNodes]),
}
failure_xml = case_xml.getElementsByTagName('failure')
if failure_xml:
if failure_xml[0].hasAttribute('type'):
type = failure_xml[0].getAttribute('type')
else:
type = ''
case['failure'] = {
'type': type,
'message': failure_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in failure_xml[0].childNodes]),
}
error_xml = case_xml.getElementsByTagName('error')
if error_xml:
if error_xml[0].hasAttribute('type'):
type = error_xml[0].getAttribute('type')
else:
type = ''
case['error'] = {
'type': type,
'message': error_xml[0].getAttribute('message'),
'text': "".join([child.nodeValue for child in error_xml[0].childNodes]),
}
suites[classname].append(case)
return suites | [
"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"
] | c37f10a8b74b291b3a12669113f4404b01b97586 | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L29-L88 | train | 52,957 |
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)
for classname, cases in suites.items():
doc_xml = minidom.Document()
suite_xml = doc_xml.createElement('testsuite')
suite_xml.setAttribute('name', classname)
suite_xml.setAttribute('tests', str(len(cases)))
suite_xml.setAttribute('errors', str(sum('error' in case for case in cases)))
suite_xml.setAttribute('failures', str(sum('failure' in case for case in cases)))
suite_xml.setAttribute('skipped', str(sum('skipped' in case for case in cases)))
suite_xml.setAttribute('time', '{:.3f}'.format(sum(case['time'] for case in cases)))
doc_xml.appendChild(suite_xml)
for case in cases:
case_xml = doc_xml.createElement('testcase')
case_xml.setAttribute('classname', classname)
case_xml.setAttribute('name', case['name'])
case_xml.setAttribute('time', '{:.3f}'.format(case['time']))
suite_xml.appendChild(case_xml)
if 'skipped' in case:
skipped_xml = doc_xml.createElement('skipped')
skipped_xml.setAttribute('type', case['skipped']['type'])
skipped_xml.setAttribute('message', case['skipped']['message'])
case_xml.appendChild(skipped_xml)
skipped_text_xml = doc_xml.createCDATASection(case['skipped']['text'])
skipped_xml.appendChild(skipped_text_xml)
if 'failure' in case:
failure_xml = doc_xml.createElement('failure')
failure_xml.setAttribute('type', case['failure']['type'])
failure_xml.setAttribute('message', case['failure']['message'])
case_xml.appendChild(failure_xml)
failure_text_xml = doc_xml.createCDATASection(case['failure']['text'])
failure_xml.appendChild(failure_text_xml)
if 'error' in case:
error_xml = doc_xml.createElement('error')
error_xml.setAttribute('type', case['error']['type'])
error_xml.setAttribute('message', case['error']['message'])
case_xml.appendChild(error_xml)
error_text_xml = doc_xml.createCDATASection(case['error']['text'])
error_xml.appendChild(error_text_xml)
with open(os.path.join(out_dir, '{}.xml'.format(classname)), 'w') as output:
doc_xml.writexml(output, encoding='utf-8', addindent='', newl="")
doc_xml.unlink() | 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)
for classname, cases in suites.items():
doc_xml = minidom.Document()
suite_xml = doc_xml.createElement('testsuite')
suite_xml.setAttribute('name', classname)
suite_xml.setAttribute('tests', str(len(cases)))
suite_xml.setAttribute('errors', str(sum('error' in case for case in cases)))
suite_xml.setAttribute('failures', str(sum('failure' in case for case in cases)))
suite_xml.setAttribute('skipped', str(sum('skipped' in case for case in cases)))
suite_xml.setAttribute('time', '{:.3f}'.format(sum(case['time'] for case in cases)))
doc_xml.appendChild(suite_xml)
for case in cases:
case_xml = doc_xml.createElement('testcase')
case_xml.setAttribute('classname', classname)
case_xml.setAttribute('name', case['name'])
case_xml.setAttribute('time', '{:.3f}'.format(case['time']))
suite_xml.appendChild(case_xml)
if 'skipped' in case:
skipped_xml = doc_xml.createElement('skipped')
skipped_xml.setAttribute('type', case['skipped']['type'])
skipped_xml.setAttribute('message', case['skipped']['message'])
case_xml.appendChild(skipped_xml)
skipped_text_xml = doc_xml.createCDATASection(case['skipped']['text'])
skipped_xml.appendChild(skipped_text_xml)
if 'failure' in case:
failure_xml = doc_xml.createElement('failure')
failure_xml.setAttribute('type', case['failure']['type'])
failure_xml.setAttribute('message', case['failure']['message'])
case_xml.appendChild(failure_xml)
failure_text_xml = doc_xml.createCDATASection(case['failure']['text'])
failure_xml.appendChild(failure_text_xml)
if 'error' in case:
error_xml = doc_xml.createElement('error')
error_xml.setAttribute('type', case['error']['type'])
error_xml.setAttribute('message', case['error']['message'])
case_xml.appendChild(error_xml)
error_text_xml = doc_xml.createCDATASection(case['error']['text'])
error_xml.appendChild(error_text_xml)
with open(os.path.join(out_dir, '{}.xml'.format(classname)), 'w') as output:
doc_xml.writexml(output, encoding='utf-8', addindent='', newl="")
doc_xml.unlink() | [
"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"
] | c37f10a8b74b291b3a12669113f4404b01b97586 | https://github.com/KarrLab/nose2unitth/blob/c37f10a8b74b291b3a12669113f4404b01b97586/nose2unitth/core.py#L91-L149 | train | 52,958 |
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.plane(*pca.strike_dip()) | 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.plane(*pca.strike_dip()) | [
"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",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/__init__.py#L150-L163 | train | 52,959 |
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:
session: SQLAlchemy :class:`Session` object
select_statement: SQLAlchemy :class:`Select` object
Returns:
a list of the first value of each result row
"""
rows = session.execute(select_statement) # type: ResultProxy
try:
return [row[0] for row in rows]
except ValueError as e:
raise MultipleResultsFound(str(e)) | 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:
session: SQLAlchemy :class:`Session` object
select_statement: SQLAlchemy :class:`Select` object
Returns:
a list of the first value of each result row
"""
rows = session.execute(select_statement) # type: ResultProxy
try:
return [row[0] for row in rows]
except ValueError as e:
raise MultipleResultsFound(str(e)) | [
"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:
a list of the first value of each result row | [
"Returns",
"a",
"list",
"of",
"the",
"first",
"values",
"in",
"each",
"row",
"returned",
"by",
"a",
"SELECT",
"query",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/core_query.py#L209-L230 | train | 52,960 |
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[::-1]
x = axes[0]*vals[0]+center[0]
y = axes[1]*vals[1]+center[1]
extrema = [N.argmin(x),N.argmax(x)]
def remove_asymptotes(arr):
arr[extrema] = N.nan
return arr
xy = tuple(remove_asymptotes(i) for i in (x,y))
return xy | 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[::-1]
x = axes[0]*vals[0]+center[0]
y = axes[1]*vals[1]+center[1]
extrema = [N.argmin(x),N.argmax(x)]
def remove_asymptotes(arr):
arr[extrema] = N.nan
return arr
xy = tuple(remove_asymptotes(i) for i in (x,y))
return xy | [
"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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/parametric.py#L18-L41 | train | 52,961 |
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"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/parametric.py#L63-L69 | train | 52,962 |
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`
tablename: table name
See
https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
""" # noqa
engine = get_engine_from_session(session)
if is_sqlserver(engine):
quoted_tablename = quote_identifier(tablename, engine)
session.execute(
"ALTER TABLE {} NOCHECK CONSTRAINT all".format(
quoted_tablename))
yield
session.execute(
"ALTER TABLE {} WITH CHECK CHECK CONSTRAINT all".format(
quoted_tablename))
else:
yield | 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`
tablename: table name
See
https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
""" # noqa
engine = get_engine_from_session(session)
if is_sqlserver(engine):
quoted_tablename = quote_identifier(tablename, engine)
session.execute(
"ALTER TABLE {} NOCHECK CONSTRAINT all".format(
quoted_tablename))
yield
session.execute(
"ALTER TABLE {} WITH CHECK CHECK CONSTRAINT all".format(
quoted_tablename))
else:
yield | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlserver.py#L43-L67 | train | 52,963 |
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:`Session`
tablename: table name
"""
with if_sqlserver_disable_constraints(session, tablename):
with if_sqlserver_disable_triggers(session, tablename):
yield | 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:`Session`
tablename: table name
"""
with if_sqlserver_disable_constraints(session, tablename):
with if_sqlserver_disable_triggers(session, tablename):
yield | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlserver.py#L97-L109 | train | 52,964 |
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
"""
engine = create_engine(database_url)
conn = engine.connect()
opts = {'version_table': version_table}
mig_context = MigrationContext.configure(conn, opts=opts)
return mig_context.get_current_revision() | 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
"""
engine = create_engine(database_url)
conn = engine.connect()
opts = {'version_table': version_table}
mig_context = MigrationContext.configure(conn, opts=opts)
return mig_context.get_current_revision() | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L96-L110 | train | 52,965 |
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 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 paths in the config file work
starting_revision:
revision to start at (typically ``None`` to ask the database)
destination_revision:
revision to aim for (typically ``"head"`` to migrate to the latest
structure)
version_table: table name for Alembic versions
as_sql:
run in "offline" mode: print the migration SQL, rather than
modifying the database. See
http://alembic.zzzcomputing.com/en/latest/offline.html
"""
if alembic_base_dir is None:
alembic_base_dir = os.path.dirname(alembic_config_filename)
os.chdir(alembic_base_dir) # so the directory in the config file works
config = Config(alembic_config_filename)
script = ScriptDirectory.from_config(config)
# noinspection PyUnusedLocal,PyProtectedMember
def upgrade(rev, context):
return script._upgrade_revs(destination_revision, rev)
log.info("Upgrading database to revision {!r} using Alembic",
destination_revision)
with EnvironmentContext(config,
script,
fn=upgrade,
as_sql=as_sql,
starting_rev=starting_revision,
destination_rev=destination_revision,
tag=None,
version_table=version_table):
script.run_env()
log.info("Database upgrade completed") | 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 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 paths in the config file work
starting_revision:
revision to start at (typically ``None`` to ask the database)
destination_revision:
revision to aim for (typically ``"head"`` to migrate to the latest
structure)
version_table: table name for Alembic versions
as_sql:
run in "offline" mode: print the migration SQL, rather than
modifying the database. See
http://alembic.zzzcomputing.com/en/latest/offline.html
"""
if alembic_base_dir is None:
alembic_base_dir = os.path.dirname(alembic_config_filename)
os.chdir(alembic_base_dir) # so the directory in the config file works
config = Config(alembic_config_filename)
script = ScriptDirectory.from_config(config)
# noinspection PyUnusedLocal,PyProtectedMember
def upgrade(rev, context):
return script._upgrade_revs(destination_revision, rev)
log.info("Upgrading database to revision {!r} using Alembic",
destination_revision)
with EnvironmentContext(config,
script,
fn=upgrade,
as_sql=as_sql,
starting_rev=starting_revision,
destination_rev=destination_revision,
tag=None,
version_table=version_table):
script.run_env()
log.info("Database upgrade completed") | [
"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 paths in the config file work
starting_revision:
revision to start at (typically ``None`` to ask the database)
destination_revision:
revision to aim for (typically ``"head"`` to migrate to the latest
structure)
version_table: table name for Alembic versions
as_sql:
run in "offline" mode: print the migration SQL, rather than
modifying the database. See
http://alembic.zzzcomputing.com/en/latest/offline.html | [
"Use",
"Alembic",
"to",
"upgrade",
"our",
"database",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L149-L208 | train | 52,966 |
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 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
""" # noqa
script = ScriptDirectory.from_config(config)
starting_rev = None
if ":" in revision:
if not sql:
raise CommandError("Range revision not allowed")
starting_rev, revision = revision.split(':', 2)
# noinspection PyUnusedLocal
def do_stamp(rev: str, context):
# noinspection PyProtectedMember
return script._stamp_revs(revision, rev)
with EnvironmentContext(config,
script,
fn=do_stamp,
as_sql=sql,
destination_rev=revision,
starting_rev=starting_rev,
tag=tag,
version_table=version_table):
script.run_env() | 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 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
""" # noqa
script = ScriptDirectory.from_config(config)
starting_rev = None
if ":" in revision:
if not sql:
raise CommandError("Range revision not allowed")
starting_rev, revision = revision.split(':', 2)
# noinspection PyUnusedLocal
def do_stamp(rev: str, context):
# noinspection PyProtectedMember
return script._stamp_revs(revision, rev)
with EnvironmentContext(config,
script,
fn=do_stamp,
as_sql=sql,
destination_rev=revision,
starting_rev=starting_rev,
tag=tag,
version_table=version_table):
script.run_env() | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L369-L405 | train | 52,967 |
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_output(args) # this needs Python 2.7 or higher
return ret | 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_output(args) # this needs Python 2.7 or higher
return ret | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L46-L60 | train | 52,968 |
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
Returns:
``stdout`` from the end of the pipe
"""
# Python arrays indexes are zero-based, i.e. an array is indexed from
# 0 to len(array)-1.
# The range/xrange commands, by default, start at 0 and go to one less
# than the maximum specified.
# print commands
processes = [] # type: List[subprocess.Popen]
for i in range(len(commands)):
if i == 0: # first processes
processes.append(
subprocess.Popen(
shlex.split(commands[i]),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
)
else: # subsequent ones
processes.append(
subprocess.Popen(
shlex.split(commands[i]),
stdin=processes[i - 1].stdout,
stdout=subprocess.PIPE
)
)
return processes[len(processes) - 1].communicate(stdinput)[0] | 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
Returns:
``stdout`` from the end of the pipe
"""
# Python arrays indexes are zero-based, i.e. an array is indexed from
# 0 to len(array)-1.
# The range/xrange commands, by default, start at 0 and go to one less
# than the maximum specified.
# print commands
processes = [] # type: List[subprocess.Popen]
for i in range(len(commands)):
if i == 0: # first processes
processes.append(
subprocess.Popen(
shlex.split(commands[i]),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
)
else: # subsequent ones
processes.append(
subprocess.Popen(
shlex.split(commands[i]),
stdin=processes[i - 1].stdout,
stdout=subprocess.PIPE
)
)
return processes[len(processes) - 1].communicate(stdinput)[0] | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L63-L100 | train | 52,969 |
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)
or ``os.startfile(filename)`` (otherwise)? If not, exceptions
are suppressed.
"""
log.info("Launching external file: {!r}", filename)
try:
if sys.platform.startswith('linux'):
cmdargs = ["xdg-open", filename]
# log.debug("... command: {!r}", cmdargs)
subprocess.call(cmdargs)
else:
# log.debug("... with os.startfile()")
# noinspection PyUnresolvedReferences
os.startfile(filename)
except Exception as e:
log.critical("Error launching {!r}: error was {}.\n\n{}",
filename, str(e), traceback.format_exc())
if raise_if_fails:
raise | 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)
or ``os.startfile(filename)`` (otherwise)? If not, exceptions
are suppressed.
"""
log.info("Launching external file: {!r}", filename)
try:
if sys.platform.startswith('linux'):
cmdargs = ["xdg-open", filename]
# log.debug("... command: {!r}", cmdargs)
subprocess.call(cmdargs)
else:
# log.debug("... with os.startfile()")
# noinspection PyUnresolvedReferences
os.startfile(filename)
except Exception as e:
log.critical("Error launching {!r}: error was {}.\n\n{}",
filename, str(e), traceback.format_exc())
if raise_if_fails:
raise | [
"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 suppressed. | [
"Launches",
"a",
"file",
"using",
"the",
"operating",
"system",
"s",
"standard",
"launcher",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/process.py#L110-L136 | train | 52,970 |
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}?charset={cs}".format(
driver=driver,
host=host,
port=port,
db=dbname,
u=username,
p=password,
cs=charset,
) | 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}?charset={cs}".format(
driver=driver,
host=host,
port=port,
db=dbname,
u=username,
p=password,
cs=charset,
) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L52-L66 | train | 52,971 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/session.py#L69-L74 | train | 52,972 |
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",
... | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sort.py#L39-L45 | train | 52,973 |
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_NAME in headers:
if XMLRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
xml_parsed = parseString(body)
pretty_xml_as_string = xml_parsed.toprettyxml()
return pretty_xml_as_string
elif JSONRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
decoded_body = body.decode('utf-8')
parsed = json.loads(decoded_body)
return json.dumps(parsed, sort_keys=True, indent=4)
except:
pass
finally:
return body | 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_NAME in headers:
if XMLRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
xml_parsed = parseString(body)
pretty_xml_as_string = xml_parsed.toprettyxml()
return pretty_xml_as_string
elif JSONRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]:
decoded_body = body.decode('utf-8')
parsed = json.loads(decoded_body)
return json.dumps(parsed, sort_keys=True, indent=4)
except:
pass
finally:
return body | [
"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",
"."
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L14-L35 | train | 52,974 |
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 body, string)
:return: None
"""
log_msg = '\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \n'
log_msg += '\t> Method: %s\n' % method
log_msg += '\t> Url: %s\n' % url
if query_params is not None:
log_msg += '\t> Query params: {}\n'.format(str(query_params))
if headers is not None:
log_msg += '\t> Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))
if body is not None:
try:
log_msg += '\t> Payload sent:\n{}\n'.format(_get_pretty_body(headers, body))
except:
log_msg += "\t> Payload could't be formatted"
logger.debug(log_msg) | 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 body, string)
:return: None
"""
log_msg = '\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \n'
log_msg += '\t> Method: %s\n' % method
log_msg += '\t> Url: %s\n' % url
if query_params is not None:
log_msg += '\t> Query params: {}\n'.format(str(query_params))
if headers is not None:
log_msg += '\t> Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))
if body is not None:
try:
log_msg += '\t> Payload sent:\n{}\n'.format(_get_pretty_body(headers, body))
except:
log_msg += "\t> Payload could't be formatted"
logger.debug(log_msg) | [
"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",
"."
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L38-L63 | train | 52,975 |
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 = '\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n'
log_msg += '\t< Response code: {}\n'.format(str(status_code))
if headers is not None:
log_msg += '\t< Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))
try:
log_msg += '\t< Payload received:\n{}'.format(_get_pretty_body(headers, response))
except:
log_msg += '\t< Payload received:\n{}'.format(response)
logger.debug(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 = '\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n'
log_msg += '\t< Response code: {}\n'.format(str(status_code))
if headers is not None:
log_msg += '\t< Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))
try:
log_msg += '\t< Payload received:\n{}'.format(_get_pretty_body(headers, response))
except:
log_msg += '\t< Payload received:\n{}'.format(response)
logger.debug(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",
"."
] | 7ba4273a05c40e2e338f49f2dd564920ed98fcab | https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/logger.py#L66-L84 | train | 52,976 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L122-L127 | train | 52,977 |
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 in newdict:
raise ValueError("Attribute conflict: _{k}, {k}".format(k=k))
newdict[k] = v
return newdict | 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 in newdict:
raise ValueError("Attribute conflict: _{k}, {k}".format(k=k))
newdict[k] = v
return newdict | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L149-L161 | train | 52,978 |
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 dictionary") | 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 dictionary") | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L164-L172 | train | 52,979 |
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 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 method == 'simple':
# ... uses simple_to_dict and simple_from_dict (q.v.)
if method == 'strip_underscore':
# ... uses strip_underscore_to_dict and simple_from_dict (q.v.)
"""
typename = cls.__qualname__ # preferable to __name__
# ... __name__ looks like "Thing" and is ambiguous
# ... __qualname__ looks like "my.module.Thing" and is not
if obj_to_dict_fn and dict_to_obj_fn:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=obj_to_dict_fn,
dict_to_obj_fn=dict_to_obj_fn,
cls=cls,
default_factory=default_factory)
elif method == METHOD_SIMPLE:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=instance_to_initdict_simple,
dict_to_obj_fn=initdict_to_instance,
cls=cls,
default_factory=default_factory)
elif method == METHOD_STRIP_UNDERSCORE:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=instance_to_initdict_stripping_underscores,
dict_to_obj_fn=initdict_to_instance,
cls=cls,
default_factory=default_factory)
else:
raise ValueError("Unknown method, and functions not fully specified")
global TYPE_MAP
TYPE_MAP[typename] = descriptor | 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 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 method == 'simple':
# ... uses simple_to_dict and simple_from_dict (q.v.)
if method == 'strip_underscore':
# ... uses strip_underscore_to_dict and simple_from_dict (q.v.)
"""
typename = cls.__qualname__ # preferable to __name__
# ... __name__ looks like "Thing" and is ambiguous
# ... __qualname__ looks like "my.module.Thing" and is not
if obj_to_dict_fn and dict_to_obj_fn:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=obj_to_dict_fn,
dict_to_obj_fn=dict_to_obj_fn,
cls=cls,
default_factory=default_factory)
elif method == METHOD_SIMPLE:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=instance_to_initdict_simple,
dict_to_obj_fn=initdict_to_instance,
cls=cls,
default_factory=default_factory)
elif method == METHOD_STRIP_UNDERSCORE:
descriptor = JsonDescriptor(
typename=typename,
obj_to_dict_fn=instance_to_initdict_stripping_underscores,
dict_to_obj_fn=initdict_to_instance,
cls=cls,
default_factory=default_factory)
else:
raise ValueError("Unknown method, and functions not fully specified")
global TYPE_MAP
TYPE_MAP[typename] = descriptor | [
"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 method == 'simple':
# ... uses simple_to_dict and simple_from_dict (q.v.)
if method == 'strip_underscore':
# ... uses strip_underscore_to_dict and simple_from_dict (q.v.) | [
"Registers",
"the",
"class",
"cls",
"for",
"JSON",
"serialization",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L395-L445 | train | 52,980 |
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 returns an ``(args, kwargs)`` tuple, suitable for passing to its
``__init__()`` function as ``__init__(*args, **kwargs)``.
- If method is ``'provides_init_kwargs'``, the class provides a function
.. code-block:: python
def init_kwargs(self) -> Dict
that returns a dictionary ``kwargs`` suitable for passing to its
``__init__()`` function as ``__init__(**kwargs)``.
- Otherwise, the method argument is as for ``register_class_for_json()``.
Usage looks like:
.. code-block:: python
@register_for_json(method=METHOD_STRIP_UNDERSCORE)
class TableId(object):
def __init__(self, db: str = '', schema: str = '',
table: str = '') -> None:
self._db = db
self._schema = schema
self._table = table
"""
if DEBUG:
print("register_for_json: args = {}".format(repr(args)))
print("register_for_json: kwargs = {}".format(repr(kwargs)))
# http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator-that-can-be-used-either-with-or-without-paramet # noqa
# In brief,
# @decorator
# x
#
# means
# x = decorator(x)
#
# so
# @decorator(args)
# x
#
# means
# x = decorator(args)(x)
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
if DEBUG:
print("... called as @register_for_json")
# called as @decorator
# ... the single argument is the class itself, e.g. Thing in:
# @decorator
# class Thing(object):
# # ...
# ... e.g.:
# args = (<class '__main__.unit_tests.<locals>.SimpleThing'>,)
# kwargs = {}
cls = args[0] # type: ClassType
register_class_for_json(cls, method=METHOD_SIMPLE)
return cls
# Otherwise:
if DEBUG:
print("... called as @register_for_json(*args, **kwargs)")
# called as @decorator(*args, **kwargs)
# ... e.g.:
# args = ()
# kwargs = {'method': 'provides_to_init_args_kwargs_dict'}
method = kwargs.pop('method', METHOD_SIMPLE) # type: str
obj_to_dict_fn = kwargs.pop('obj_to_dict_fn', None) # type: InstanceToDictFnType # noqa
dict_to_obj_fn = kwargs.pop('dict_to_obj_fn', initdict_to_instance) # type: DictToInstanceFnType # noqa
default_factory = kwargs.pop('default_factory', None) # type: DefaultFactoryFnType # noqa
check_result = kwargs.pop('check_results', True) # type: bool
def register_json_class(cls_: ClassType) -> ClassType:
odf = obj_to_dict_fn
dof = dict_to_obj_fn
if method == METHOD_PROVIDES_INIT_ARGS_KWARGS:
if hasattr(cls_, INIT_ARGS_KWARGS_FN_NAME):
odf = wrap_args_kwargs_to_initdict(
getattr(cls_, INIT_ARGS_KWARGS_FN_NAME),
typename=cls_.__qualname__,
check_result=check_result
)
else:
raise ValueError(
"Class type {} does not provide function {}".format(
cls_, INIT_ARGS_KWARGS_FN_NAME))
elif method == METHOD_PROVIDES_INIT_KWARGS:
if hasattr(cls_, INIT_KWARGS_FN_NAME):
odf = wrap_kwargs_to_initdict(
getattr(cls_, INIT_KWARGS_FN_NAME),
typename=cls_.__qualname__,
check_result=check_result
)
else:
raise ValueError(
"Class type {} does not provide function {}".format(
cls_, INIT_KWARGS_FN_NAME))
elif method == METHOD_NO_ARGS:
odf = obj_with_no_args_to_init_dict
register_class_for_json(cls_,
method=method,
obj_to_dict_fn=odf,
dict_to_obj_fn=dof,
default_factory=default_factory)
return cls_
return register_json_class | 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 returns an ``(args, kwargs)`` tuple, suitable for passing to its
``__init__()`` function as ``__init__(*args, **kwargs)``.
- If method is ``'provides_init_kwargs'``, the class provides a function
.. code-block:: python
def init_kwargs(self) -> Dict
that returns a dictionary ``kwargs`` suitable for passing to its
``__init__()`` function as ``__init__(**kwargs)``.
- Otherwise, the method argument is as for ``register_class_for_json()``.
Usage looks like:
.. code-block:: python
@register_for_json(method=METHOD_STRIP_UNDERSCORE)
class TableId(object):
def __init__(self, db: str = '', schema: str = '',
table: str = '') -> None:
self._db = db
self._schema = schema
self._table = table
"""
if DEBUG:
print("register_for_json: args = {}".format(repr(args)))
print("register_for_json: kwargs = {}".format(repr(kwargs)))
# http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator-that-can-be-used-either-with-or-without-paramet # noqa
# In brief,
# @decorator
# x
#
# means
# x = decorator(x)
#
# so
# @decorator(args)
# x
#
# means
# x = decorator(args)(x)
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
if DEBUG:
print("... called as @register_for_json")
# called as @decorator
# ... the single argument is the class itself, e.g. Thing in:
# @decorator
# class Thing(object):
# # ...
# ... e.g.:
# args = (<class '__main__.unit_tests.<locals>.SimpleThing'>,)
# kwargs = {}
cls = args[0] # type: ClassType
register_class_for_json(cls, method=METHOD_SIMPLE)
return cls
# Otherwise:
if DEBUG:
print("... called as @register_for_json(*args, **kwargs)")
# called as @decorator(*args, **kwargs)
# ... e.g.:
# args = ()
# kwargs = {'method': 'provides_to_init_args_kwargs_dict'}
method = kwargs.pop('method', METHOD_SIMPLE) # type: str
obj_to_dict_fn = kwargs.pop('obj_to_dict_fn', None) # type: InstanceToDictFnType # noqa
dict_to_obj_fn = kwargs.pop('dict_to_obj_fn', initdict_to_instance) # type: DictToInstanceFnType # noqa
default_factory = kwargs.pop('default_factory', None) # type: DefaultFactoryFnType # noqa
check_result = kwargs.pop('check_results', True) # type: bool
def register_json_class(cls_: ClassType) -> ClassType:
odf = obj_to_dict_fn
dof = dict_to_obj_fn
if method == METHOD_PROVIDES_INIT_ARGS_KWARGS:
if hasattr(cls_, INIT_ARGS_KWARGS_FN_NAME):
odf = wrap_args_kwargs_to_initdict(
getattr(cls_, INIT_ARGS_KWARGS_FN_NAME),
typename=cls_.__qualname__,
check_result=check_result
)
else:
raise ValueError(
"Class type {} does not provide function {}".format(
cls_, INIT_ARGS_KWARGS_FN_NAME))
elif method == METHOD_PROVIDES_INIT_KWARGS:
if hasattr(cls_, INIT_KWARGS_FN_NAME):
odf = wrap_kwargs_to_initdict(
getattr(cls_, INIT_KWARGS_FN_NAME),
typename=cls_.__qualname__,
check_result=check_result
)
else:
raise ValueError(
"Class type {} does not provide function {}".format(
cls_, INIT_KWARGS_FN_NAME))
elif method == METHOD_NO_ARGS:
odf = obj_with_no_args_to_init_dict
register_class_for_json(cls_,
method=method,
obj_to_dict_fn=odf,
dict_to_obj_fn=dof,
default_factory=default_factory)
return cls_
return register_json_class | [
"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 to its
``__init__()`` function as ``__init__(*args, **kwargs)``.
- If method is ``'provides_init_kwargs'``, the class provides a function
.. code-block:: python
def init_kwargs(self) -> Dict
that returns a dictionary ``kwargs`` suitable for passing to its
``__init__()`` function as ``__init__(**kwargs)``.
- Otherwise, the method argument is as for ``register_class_for_json()``.
Usage looks like:
.. code-block:: python
@register_for_json(method=METHOD_STRIP_UNDERSCORE)
class TableId(object):
def __init__(self, db: str = '', schema: str = '',
table: str = '') -> None:
self._db = db
self._schema = schema
self._table = table | [
"Class",
"decorator",
"to",
"register",
"classes",
"with",
"our",
"JSON",
"system",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L448-L567 | train | 52,981 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L570-L576 | train | 52,982 |
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:
log.debug("Deserializing: {!r}", d)
d.pop(TYPE_LABEL)
descriptor = TYPE_MAP[typename]
obj = descriptor.to_obj(d)
if DEBUG:
log.debug("... to: {!r}", obj)
return obj
return d | 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:
log.debug("Deserializing: {!r}", d)
d.pop(TYPE_LABEL)
descriptor = TYPE_MAP[typename]
obj = descriptor.to_obj(d)
if DEBUG:
log.debug("... to: {!r}", obj)
return obj
return d | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L603-L619 | train | 52,983 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L626-L633 | train | 52,984 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L636-L644 | train | 52,985 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L702-L706 | train | 52,986 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L743-L748 | train | 52,987 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L772-L778 | train | 52,988 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/json/serialize.py#L832-L837 | train | 52,989 |
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)
""" # noqa
fileobj.write('\n'.join(lines) + '\n') | 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)
""" # noqa
fileobj.write('\n'.join(lines) + '\n') | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L94-L101 | train | 52,990 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L104-L109 | train | 52,991 |
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:
with open(filename) as f:
yield f | 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:
with open(filename) as f:
yield f | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L157-L171 | train | 52,992 |
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:
yield line | 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:
yield line | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L174-L188 | train | 52,993 |
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:
each line of all the files
"""
for file in files:
for byteline in file:
line = byteline.decode(encoding).strip()
yield line | 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:
each line of all the files
"""
for file in files:
for byteline in file:
line = byteline.decode(encoding).strip()
yield line | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L203-L221 | train | 52,994 |
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 part to yield
splitter: string to split the lines on
Yields:
the specified part for each line
"""
for line in lines:
parts = line.split(splitter)
yield parts[part_index] | 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 part to yield
splitter: string to split the lines on
Yields:
the specified part for each line
"""
for line in lines:
parts = line.split(splitter)
yield parts[part_index] | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L266-L283 | train | 52,995 |
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 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 :func:`csv.reader`
Yields:
rows from the files
"""
dialect = csv_reader_kwargs.pop('dialect', None)
for csv_file_bin in csv_files:
# noinspection PyTypeChecker
csv_file = io.TextIOWrapper(csv_file_bin, encoding=encoding)
thisfile_dialect = dialect
if thisfile_dialect is None:
thisfile_dialect = csv.Sniffer().sniff(csv_file.read(1024))
csv_file.seek(0)
reader = csv.reader(csv_file, dialect=thisfile_dialect,
**csv_reader_kwargs)
first = True
for row in reader:
if first:
first = False
if skip_header:
continue
yield row | 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 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 :func:`csv.reader`
Yields:
rows from the files
"""
dialect = csv_reader_kwargs.pop('dialect', None)
for csv_file_bin in csv_files:
# noinspection PyTypeChecker
csv_file = io.TextIOWrapper(csv_file_bin, encoding=encoding)
thisfile_dialect = dialect
if thisfile_dialect is None:
thisfile_dialect = csv.Sniffer().sniff(csv_file.read(1024))
csv_file.seek(0)
reader = csv.reader(csv_file, dialect=thisfile_dialect,
**csv_reader_kwargs)
first = True
for row in reader:
if first:
first = False
if skip_header:
continue
yield row | [
"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 :func:`csv.reader`
Yields:
rows from the files | [
"Iterate",
"through",
"binary",
"file",
"-",
"like",
"objects",
"that",
"are",
"CSV",
"files",
"in",
"a",
"specified",
"encoding",
".",
"Yield",
"each",
"row",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L305-L340 | train | 52,996 |
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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L347-L354 | train | 52,997 |
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 {}: {} -> {}",
filename, repr(text_from), repr(text_to))
with open(filename) as infile:
contents = infile.read()
contents = contents.replace(text_from, text_to)
with open(filename, 'w') as outfile:
outfile.write(contents) | 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 {}: {} -> {}",
filename, repr(text_from), repr(text_to))
with open(filename) as infile:
contents = infile.read()
contents = contents.replace(text_from, text_to)
with open(filename, 'w') as outfile:
outfile.write(contents) | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L390-L405 | train | 52,998 |
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:
if fileline == line:
return True
return False | 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:
if fileline == line:
return True
return False | [
"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",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L462-L475 | train | 52,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.