code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# 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#sqlal...
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
3.669546
3.702261
0.991163
lines = [] if dialect_name == SqlaDialectName.MYSQL: if start: lines = [ "SET autocommit=0;", "SET unique_checks=0;", "SET foreign_key_checks=0;", ] else: lines = [ "SET foreign_key_checks=1;...
def bulk_insert_extras(dialect_name: str, fileobj: TextIO, start: bool) -> None
Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-enables them at the end and commits. Args: dialect_name: SQLAlchemy dialect name (see :class:`SqlaDialectName`) fileobj: ...
3.322698
2.775508
1.19715
# noqa writeline_nl( fileobj, sql_comment("Data for all objects related to the first below:")) bulk_insert_extras(engine.dialect.name, fileobj, start=True) for part in walk_orm_tree(baseobj): dump_orm_object_as_insert_sql(engine, part, fileobj) bulk_insert_extras(engine.dia...
def dump_orm_tree_as_insert_sql(engine: Engine, baseobj: object, fileobj: TextIO) -> None
Sends an object, and all its relations (discovered via "relationship" links) as ``INSERT`` commands in SQL, to ``fileobj``. Args: engine: SQLAlchemy :class:`Engine` baseobj: starting SQLAlchemy ORM object fileobj: file-like object to write to Problem: foreign key constraints. ...
6.709296
7.515489
0.892729
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)
Fetch next page from scroll API.
5.179638
4.534
1.142399
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: #...
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 ...
2.445463
2.53117
0.966139
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...
def _read_source(self) -> None
Reads the source file.
3.428233
3.264767
1.05007
log.critical("{}Line {}: {!r}", extramsg, linenum, line)
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None
Writes a debugging report on a line.
25.265413
12.507474
2.020025
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
Rewrites the source file.
5.204747
4.235834
1.228742
for line in self.dest_lines: destination.write(line + NL)
def _write(self, destination: TextIO) -> None
Writes the converted output to a destination.
13.74785
8.432759
1.630291
for v in Counter(values).values(): if v > 1: return True return False
def contains_duplicates(values: Iterable[Any]) -> bool
Does the iterable contain any duplicate values?
4.676956
2.909843
1.607288
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) mean...
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 so...
4.738296
5.386828
0.879608
x[:] = [x[i] for i in indexes]
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"]
7.473196
21.398357
0.349242
# noqa return [item for sublist in x for item in sublist]
def flatten_list(x: List[Any]) -> List[Any]
Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
2.983396
5.109079
0.58394
# 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]
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
2.085737
2.393745
0.871328
for i in range(0, len(l), n): yield l[i:i + n]
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]
Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n``
1.988744
3.796245
0.523871
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
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).
2.899262
2.950011
0.982797
# See also http://stackoverflow.com/questions/4020539 if not s: return s d = "" # the destination string in_escape = False for i in range(len(s)): c = s[i] # the character being processed if in_escape: if c == "r": d += "\r" elif...
def unescape_newlines(s: str) -> str
Reverses :func:`escape_newlines`.
2.57162
2.375575
1.082525
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
Escapes CR, LF, tab, and backslashes. Its counterpart is :func:`unescape_tabs_newlines`.
2.287669
2.223763
1.028738
charlist = [] # type: List[str] for src in srclist: if isinstance(src, int): charlist.append(chr(src)) else: # Range like "0041-005A" first, last = [int(x, 16) for x in src.split("-")] charlist += [chr(x) for x in range(first, last + 1)] ...
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str
Used to create :data:`UNICODE_CATEGORY_STRINGS`. Args: srclist: list of integers or hex range strings like ``"0061-007A"`` Returns: a string with all characters described by ``srclist``: either the character corresponding to the integer Unicode character number, or all characte...
2.423585
2.271785
1.06682
name = kwargs.pop("name",None) grouped = len(arrays) > 1 if grouped: arr = N.concatenate(arrays) components = [PCAOrientation(a) for a in arrays] else: arr = arrays[0] components = [] #r = LinearOrientation(arr) pca = PCAOrientation(arr) di...
def report(*arrays, **kwargs)
Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information.
6.019484
6.173414
0.975066
if record and self._validate('user', record) \ and self._validate('coordinates', record): return True return False
def validate_geotweet(self, record)
check that stream record is actual tweet with coordinates
7.916946
6.1894
1.279114
return_tangent = kwargs.pop('tangent',False) con, transform, offset = ell.projection(**kwargs) v = N.linalg.norm(N.array(con.major_axes()),axis=1) A = N.sort(v)[::-1] # Sort highest values first A = N.squeeze(A) B = N.linalg.norm(offset) if return_tangent: return A/B return N.arcta...
def angle_subtended(ell, **kwargs)
Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin
6.52036
6.817555
0.956407
ax = list(axes) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) return arr.view(cls)
def from_axes(cls,axes)
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic
10.685214
10.288743
1.038534
ax = list(1/N.array(axes)**2) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) return arr.view(cls)
def from_semiaxes(cls,axes)
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic
10.400349
10.710397
0.971052
v = augment(p) _ = ell.solve(v) return N.allclose(_,0) if shell_only else _ <= 0
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).
17.806631
23.544224
0.756306
_ = ell[:-1,:-1] U,s,V = N.linalg.svd(_) scalar = -(ell.sum()-_.sum()) return N.sqrt(s*scalar)*V
def major_axes(ell)
Gets major axes of ellipsoids
13.498894
13.137895
1.027478
# Translation matrix T = N.identity(len(conic)) T[:-1,-1] = -vector return conic.transform(T)
def translate(conic, vector)
Translates a conic by a vector
7.147454
8.105335
0.881821
pole = augment(vector) return dot(conic,pole).view(Plane)
def polar_plane(conic, vector)
Calculates the polar plane to a vector (a 'pole') for a given conic section. For poles outside the conic, the polar plane contains all vectors of tangency to the pole.
37.193123
34.791786
1.06902
v = dot(N.linalg.inv(conic),plane) return v[:-1]/v[-1]
def pole(conic, plane)
Calculates the pole of a polar plane for a given conic section.
10.73233
14.620638
0.734053
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)
The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin.
5.054461
4.766212
1.060478
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_fil...
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
2.267087
2.02458
1.119781
if isinstance(data, basestring): raise ValueError("Data must not be a string.") # optional args boundary = kwargs.get("boundary", None) output_str = kwargs.get("output_str", self.output_str) new_fields = [] fields = to_key_val_list(data or {}) ...
def encode_params(self, data=None, files=None, **kwargs)
Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be string (filepath), 2-tuples (filename, fileobj),...
3.089383
3.025726
1.021039
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)): ...
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.
2.382971
2.382649
1.000135
charset = kwargs.get("charset", self.charset) collection_format = kwargs.get("collection_format", self.collection_format) output_str = kwargs.get("output_str", self.output_str) if data is None: return "", self.get_content_type(charset) elif isinstance(data, ...
def encode_params(self, data=None, **kwargs)
Build the body for a text/plain request. 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.
1.987197
1.980049
1.00361
if isinstance(data, basestring): raise ValueError("Data must not be a string.") if data is None: return b"", self.content_type fields = to_key_val_dict(data or "") try: body = json.dumps(fields) except: body = json.dumps(f...
def encode_params(self, data=None, **kwargs)
Build the body for a application/json request.
4.754189
4.56136
1.042274
# noqa if platform == 'this': platform = (sys.platform != 'win32') # RNC: includes 64-bit Windows if platform == 1: # POSIX re_cmd_lex = r'''"((?:\\["\\]|[^"])*)"|'([^']*)'|(\\.)|(&&?|\|\|?|\d?\>|[<])|([^\s'"\\&|<>]+)|(\s+)|(.)''' # noqa elif platform == 0: # Windows/CMD re...
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]
As per https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex. Multi-platform variant of ``shlex.split()`` for command-line splitting. For use with ``subprocess``, for ``argv`` injection etc. Using fast REGEX. Args: s: string to split ...
3.626677
3.56436
1.017483
scores = [] try: n = len(pcts) except TypeError: pcts = [pcts] n = 0 for i, p in enumerate(pcts): if axis is None: score = stats.scoreatpercentile(a.ravel(), p) else: score = N.apply_along_axis(stats.scoreatpercentile, axis, a, p) ...
def percentiles(a, pcts, axis=None)
Like scoreatpercentile but can take and return array of percentiles. Parameters ---------- a : array data pcts : sequence of percentile values percentile or percentiles to find score at axis : int or None if not None, computes scores over this axis Returns ------- ...
2.334849
2.271861
1.027725
p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
def ci(a, which=95, axis=None)
Return a percentile range from an array of values.
4.666241
3.61545
1.290639
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
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: Va...
4.145379
3.884899
1.067049
# 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
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 ...
11.729074
16.002361
0.732959
default = default or [] if not parser.has_section(section): raise ValueError("config missing section: " + section) try: multiline = parser.get(section, option) values = [x.strip() for x in multiline.splitlines() if x.strip()] return values except NoOptionError: ...
def get_config_multiline_option(parser: ConfigParser, section: str, option: str, default: List[str] = None) -> List[str]
Retrieves a multi-line string value from a parser as a list of strings (one per line, ignoring blank lines). Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if op...
2.781163
3.626407
0.76692
for o in options: setattr(obj, o, get_config_multiline_option(parser, section, o))
def read_config_multiline_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str]) -> None
This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is to :func:`get_config_string_option`.
4.899495
3.381163
1.449056
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
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: V...
4.159765
3.814943
1.090387
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...
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: ...
4.353445
4.38949
0.991788
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
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
4.944579
5.037821
0.981492
try: value = config.get(section, param).lower() if value == "debug": return logging.DEBUG # 10 elif value == "info": return logging.INFO elif value in ["warn", "warning"]: return logging.WARN elif value == "error": return ...
def get_config_parameter_loglevel(config: ConfigParser, section: str, param: str, default: int) -> int
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logging.DEBUG``. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: ...
2.938179
3.011979
0.975498
try: multiline = config.get(section, param) lines = [x.strip() for x in multiline.splitlines()] return [line for line in lines if line] except (TypeError, ValueError, NoOptionError): log.warning( "Configuration variable {} not found or improper in section [{}]; "...
def get_config_parameter_multiline(config: ConfigParser, section: str, param: str, default: List[str]) -> List[str]
Get multi-line string parameter from ``configparser`` ``.INI`` file, as a list of strings (one per line, ignoring blank lines). Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value ...
3.899535
4.414214
0.883404
defn = cursor.get_definition() return (defn is not None) and (cursor.location == defn.location)
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
6.408134
4.107038
1.560281
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)
Gets a cone of asymptotes for hyperbola
5.601129
5.266463
1.063547
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)
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)
7.565443
6.42941
1.176693
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 ...
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 debu...
3.444696
3.425857
1.005499
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
Description of the process.
6.007298
4.911376
1.223139
if self.debugging: s = "{}: {}".format(self.fullname, msg) log.debug(s)
def debug(self, msg: str) -> None
If we are being verbose, write a debug message to the Python disk log.
7.595897
5.207303
1.458701
# noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogInfoMsg(s) if self.debugging: log.info(s)
def info(self, msg: str) -> None
Write an info message to the Windows Application log (± to the Python disk log).
6.804647
5.757149
1.181947
# Log messages go to the Windows APPLICATION log. # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogWarningMsg(s) if self.debugging: log.warning(s)
def warning(self, msg: str) -> None
Write a warning message to the Windows Application log (± to the Python disk log).
10.951094
7.547932
1.450873
# noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogErrorMsg(s) if self.debugging: log.warning(s)
def error(self, msg: str) -> None
Write an error message to the Windows Application log (± to the Python disk log).
8.124304
6.803956
1.194056
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 e...
def open_logs(self) -> None
Open Python disk logs.
2.212278
2.045896
1.081325
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
Close Python disk logs.
2.552229
2.217902
1.15074
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 WIND...
def start(self) -> None
Starts a subprocess. Optionally routes its output to our disk logs.
4.327475
3.848153
1.124559
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...
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
6.535662
6.65182
0.982537
if not self.running: return True # Already closed by itself? try: self.wait(0) return True except subprocess.TimeoutExpired: # failed to close pass # SEE NOTES ABOVE. This is tricky under Windows. suffix = " [to...
def _terminate(self, level: int) -> bool
Returns: succeeded in *attempting* a kill?
3.641747
3.482593
1.0457
# noqa self.warning("Using a recursive hard kill; will assume it worked") pid = self.process.pid gone, still_alive = kill_proc_tree(pid, including_parent=True, timeout_s=self.kill_timeout_sec) self.debug("Killed: {!r}".format(gone)) ...
def _kill(self) -> None
Hard kill. - PROBLEM: originally, via ``self.process.kill()``, could leave orphans under Windows. - SOLUTION: see https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows, which uses ``psutil``.
6.511418
5.828215
1.117223
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 ...
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: ...
4.358134
4.478862
0.973045
# noinspection PyUnresolvedReferences servicemanager.LogInfoMsg(str(msg)) if self.debugging: log.info(msg)
def info(self, msg: str) -> None
Write an info message to the Windows Application log (± to the Python disk log).
7.74444
6.08668
1.272359
# noinspection PyUnresolvedReferences servicemanager.LogErrorMsg(str(msg)) if self.debugging: log.error(msg)
def error(self, msg: str) -> None
Write an error message to the Windows Application log (± to the Python disk log).
9.187806
6.596813
1.392764
# 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
Called when the service is being shut down.
5.804288
5.252904
1.104967
# 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 me...
def SvcDoRun(self) -> None
Called when the service is started.
3.119916
2.93414
1.063315
# Actual main service code. try: self.service() except Exception as e: self.error("Unexpected exception: {e}\n{t}".format( e=e, t=traceback.format_exc()))
def main(self) -> None
Main entry point. Runs :func:`service`.
5.875107
4.436688
1.32421
# 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_manager...
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``) sto...
3.143019
3.12397
1.006098
# noqa if not err.args: err.args = ('', ) err.args += (info, )
def add_info_to_exception(err: Exception, info: Dict) -> None
Adds an information dictionary to an exception. See http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python Args: err: the exception to be modified info: the information to add
4.061319
6.78895
0.598225
if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return info
def recover_info_from_exception(err: Exception) -> Dict
Retrives the information added to an exception by :func:`add_info_to_exception`.
3.282173
3.446525
0.952314
# noqa if exc: lines = traceback.format_exception( None, # etype: ignored exc, exc.__traceback__) # https://www.python.org/dev/peps/pep-3134/ msg = "".join(lines) # Method 1: # print("".join(lines), file=sys.stderr, flush=True) # Me...
def die(exc: Exception = None, exit_code: int = 1) -> None
It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python...
3.290626
3.717112
0.885264
try: obj = inspect.getsource(obj) except (TypeError, IOError): try: obj = marshal.dumps(obj) except ValueError: if hasattr(obj, '__dict__'): obj = _serialize_dict(obj.__dict__) return obj
def _serialize_function(obj)
Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return:
3.152769
3.168651
0.994988
obj = dict(obj.__dict__) if '__builtins__' in obj.keys(): obj.pop('__builtins__') for k, v in obj.items(): if callable(v): obj[k] = serialize_obj(v) else: obj[k] = repr(v) return obj
def _serialize_module(obj)
Tries to serialize a module by its __dict__ attr. Remove the builtins attr as this one is not relevant and extremely large. If its value is a callable, serialize it using serialize_obj, else, use its repr, because in this case we most likely run into max recursion depth errors. :param obj: :return:
2.811234
2.045454
1.374382
if isinstance(obj, (tuple, set)): # make a tuple assignable by casting it to list obj = list(obj) for item in obj: obj[obj.index(item)] = serialize_obj(item) return obj
def _serialize_iterable(obj)
Only for serializing list and tuples and stuff. Dicts and Strings/Unicode is treated differently. String/Unicode normally don't need further serialization and it would cause a max recursion error trying to do so. :param obj: :return:
5.480478
6.106567
0.897473
# 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...
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``
2.930657
2.98604
0.981453
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) ret...
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.
2.078863
1.857726
1.119036
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...
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.
2.475603
2.408832
1.027719
if not hasattr(obj, reverse_fk_set_field): return missing linked_objs = getattr(obj, reverse_fk_set_field).all() if not linked_objs: return missing first = linked_objs[0] app_name = first._meta.app_label.lower() model_name = first._meta.object_name.lower() viewname = "ad...
def admin_view_reverse_fk_links(modeladmin: ModelAdmin, obj, reverse_fk_set_field: str, missing: str = "(None)", use_str: bool = True, separator: str = "<br>", ...
Get multiple Django admin site URL for multiple objects linked to our object of interest (where the other objects have foreign keys to our object).
1.953653
1.914478
1.020463
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
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 ta...
4.206847
4.50442
0.933938
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
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 ...
2.216511
2.455735
0.902586
b, a = iirnotch( w0=normalized_frequency(notch_freq_hz, sampling_freq_hz), Q=quality_factor ) filtered_data = lfilter(b=b, a=a, x=data) return filtered_data
def notch_filter(data: FLOATS_TYPE, sampling_freq_hz: float, notch_freq_hz: float, quality_factor: float) -> FLOATS_TYPE
Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) notch_freq_hz: notch frequency, in Hz (or other consistent units) quality_f...
3.285309
4.027535
0.815712
return N.array([[N.cos(angle),-N.sin(angle),0], [N.sin(angle), N.cos(angle),0], [0 , 0 ,1]])
def rotation(angle)
Rotation about the Z axis (in the XY plane)
2.540572
2.607365
0.974383
# 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 =...
def ellipse(center,covariance_matrix,level=1, n=1000)
Returns error ellipse in slope-azimuth space
6.326252
6.518132
0.970562
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(), hyperbo...
def to_mapping(self,**values)
Create a JSON-serializable representation of the plane that is usable with the javascript frontend
4.398373
4.18525
1.050922
timeout_sec = 5 for p in processes: try: p.wait(timeout_sec) except TimeoutExpired: # failed to close p.kill()
def kill_child_processes() -> None
Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``.
6.377582
6.132726
1.039926
log.debug("{!r}", args) global processes global proc_args_list proc = Popen(args, stdin=stdin, stdout=stdout, stderr=stderr) # proc = Popen(args, stdin=None, stdout=PIPE, stderr=STDOUT) # proc = Popen(args, stdin=None, stdout=PIPE, stderr=PIPE) # Can't preserve colour: http://stackoverf...
def start_process(args: List[str], stdin: Any = None, stdout: Any = None, stderr: Any = None) -> Popen
Launch a child process and record it in our :data:`processes` variable. Args: args: program and its arguments, as a list stdin: typically None stdout: use None to perform no routing, which preserves console colour! Otherwise, specify somewhere to route stdout. See subprocess ...
3.930428
3.658657
1.074282
global processes global proc_args_list n = len(processes) Pool(n).map(print_lines, processes) # in case of PIPE something_running = True while something_running: something_running = False for i, p in enumerate(processes): try: retcode = p.wait(ti...
def wait_for_processes(die_on_failure: bool = True, timeout_sec: float = 1) -> None
Wait for child processes (catalogued in :data:`processes`) to finish. If ``die_on_failure`` is ``True``, then whenever a subprocess returns failure, all are killed. If ``timeout_sec`` is None, the function waits for its first process to complete, then waits for the second, etc. So a subprocess dying d...
4.63354
4.552021
1.017908
out, err = process.communicate() if out: for line in out.decode("utf-8").splitlines(): print(line) if err: for line in err.decode("utf-8").splitlines(): print(line)
def print_lines(process: Popen) -> None
Let a subprocess :func:`communicate`, then write both its ``stdout`` and its ``stderr`` to our ``stdout``.
1.974481
1.857086
1.063214
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
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`
4.893244
4.138063
1.182496
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("De...
def run(self) -> None
Read lines and put them on the queue.
3.527429
3.323512
1.061356
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 ...
def create_nation_fixtures(self)
Create national US and State Map
3.084691
3.048749
1.011789
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) ...
def serialize(pca, **kwargs)
Serialize an orientation object to a dict suitable for JSON
7.151212
6.723644
1.063592
dr, dw, de = select.select([sys.stdin], [], [], 0) return dr != []
def _kbhit_unix() -> bool
Under UNIX: is a keystroke available?
5.48219
3.555558
1.541865
# noqa return InsertOnDuplicate(tablename, values, inline=inline, **kwargs)
def insert_on_duplicate(tablename: str, values: Any = None, inline: bool = False, **kwargs)
Command to produce an :class:`InsertOnDuplicate` object. Args: tablename: name of the table values: values to ``INSERT`` inline: as per http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert kwargs: additional parameters Returns: ...
6.113868
10.343781
0.591067
# noqa # log.critical(compiler.__dict__) # log.critical(compiler.dialect.__dict__) # log.critical(insert.__dict__) s = compiler.visit_insert(insert, **kw) # log.critical(s) m = RE_INSERT_FIELDNAMES.match(s) if m is None: raise ValueError("compile_insert_on_duplicate_key_update:...
def compile_insert_on_duplicate_key_update(insert: Insert, compiler: SQLCompiler, **kw) -> str
Hooks into the use of the :class:`InsertOnDuplicate` class for the MySQL dialect. Compiles the relevant SQL for an ``INSERT... ON DUPLICATE KEY UPDATE`` statement. Notes: - We can't get the fieldnames directly from ``insert`` or ``compiler``. - We could rewrite the innards of the visit_insert sta...
2.581145
2.572734
1.003269
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 ...
def create_groups(orientations, *groups, **kwargs)
Create groups of an orientation measurement dataset
5.412897
5.241654
1.03267
writer = csv.writer(outfile, dialect=output_dialect) written_header = False header_items = [] # type: List[str] for filename in filenames: log.info("Processing file " + repr(filename)) with open(filename, 'r') as f: reader = csv.reader(f, dialect=input_dialect) ...
def merge_csv(filenames: List[str], outfile: TextIO = sys.stdout, input_dialect: str = 'excel', output_dialect: str = 'excel', debug: bool = False, headers: bool = True) -> None
Amalgamate multiple CSV/TSV/similar files into one. Args: filenames: list of filenames to process outfile: file-like object to write output to input_dialect: dialect of input files, as passed to ``csv.reader`` output_dialect: dialect to write, as passed to ``csv.writer`` deb...
2.317365
2.305984
1.004935
main_only_quicksetup_rootlogger() parser = argparse.ArgumentParser() parser.add_argument( "filenames", nargs="+", help="Names of CSV/TSV files to merge" ) parser.add_argument( "--outfile", default="-", help="Specify an output filename. If omitted...
def main()
Command-line processor. See ``--help`` for details.
2.345396
2.372471
0.988588
r constant = np.mean(x) products = x * b - constant # ... softmax is invariant to addition of a constant: Daw article and # http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-12.html#b # noinspection PyUnresolvedReferences if products.max() > sys.float_info.max_exp: # ... max_...
def softmax(x: np.ndarray, b: float = 1.0) -> np.ndarray
r""" Standard softmax function: .. math:: P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} } Args: x: vector (``numpy.array``) of values b: exploration parameter :math:`\beta`, or inverse temperature [Daw2009], or :math:`1/t`; see below Returns: ...
6.243594
5.749855
1.08587