code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later ''' cls._to_compose.setdefault(module_name, []) cls._to_compose[module_name].append( (list(fsts), comp...
def add(cls, module_name, fsts, composer)
add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later
11.551203
3.182471
3.629633
''' Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified ...
def add(cls, module_name, msg='')
Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the paramet...
7.183042
2.162766
3.32123
module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries -= 1 if cls._num_entries < 1: if cls._num_entries < 0: raise Exception( 'Bug: ImportGuardHoo...
def remove(cls, module_name)
drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op.
5.591874
4.861578
1.150218
"Random selection from itertools.product(*args, **kwds)" pools = [tuple(pool) for pool in args] * repeat return tuple(random.choice(pool) for pool in pools)
def random_product(*args, repeat=1)
Random selection from itertools.product(*args, **kwds)
4.127604
2.790582
1.47912
f = Feature( extractor or self.extractor, needs=needs, store=self.store if store is None else store, encoder=self.encoder, decoder=self.decoder, key=self.key, data_writer=data_writer, persistence=persistence...
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None)
Use self as a template to build a new feature, replacing values in kwargs
3.089385
3.068958
1.006656
if self.store and self._stored(_id, persistence): return True if self.is_root: return False return all( [n._can_compute(_id, persistence) for n in self.dependencies])
def _can_compute(self, _id, persistence)
Return true if this feature stored, or is unstored, but can be computed from stored dependencies
5.813993
4.809985
1.208734
root = features is None stored = self._stored(_id, persistence) is_cached = self.store and stored if self.store and not stored: data_writer = None elif root: data_writer = BytesIODataWriter else: data_writer = None ...
def _partial(self, _id, features=None, persistence=None)
TODO: _partial is a shit name for this, kind of. I'm building a graph such that I can only do work necessary to compute self, and no more
5.697243
5.726696
0.994857
# http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break for result in results: yield result
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]
Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row
3.460873
4.059325
0.852573
return (row[0] for row in genrows(cursor, arraysize))
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]
Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row
4.813417
12.807305
0.375834
columns = get_fieldnames_from_cursor(cursor) return ( OrderedDict(zip(columns, row)) for row in genrows(cursor, arraysize) )
def gendicts(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Dict[str, Any], None, None]
Generate all rows from a cursor as :class:`OrderedDict` objects. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row, as an :class:`OrderedDict` whose key are column names and whose values are the row values
4.613371
6.729873
0.685506
columns = get_fieldnames_from_cursor(cursor) return [ OrderedDict(zip(columns, row)) for row in cursor.fetchall() ]
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]
Return all rows from a cursor as a list of :class:`OrderedDict` objects. Args: cursor: the cursor Returns: a list (one item per row) of :class:`OrderedDict` objects whose key are column names and whose values are the row values
4.193262
4.71839
0.888706
columns = get_fieldnames_from_cursor(cursor) row = cursor.fetchone() if not row: return None return OrderedDict(zip(columns, row))
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
3.631681
3.17873
1.142494
permissible_values = list(x[0] for x in values) # ... does not include the None value; those do not go to the validator if add_none: none_tuple = (SERIALIZED_NONE, none_description) values = [none_tuple] + list(values) return values, permissible_values
def get_values_and_permissible(values: Iterable[Tuple[Any, str]], add_none: bool = False, none_description: str = "[None]") \ -> Tuple[List[Tuple[Any, str]], List[Any]]
Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` ...
5.799984
6.452374
0.898891
if not appstruct: return colander.null try: appstruct = coerce_to_pendulum(appstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid( node, ...
def serialize(self, node: SchemaNode, appstruct: Union[PotentialDatetimeType, ColanderNullType]) \ -> Union[str, ColanderNullType]
Serializes Python object to string representation.
4.105922
4.094035
1.002904
if not cstruct: return colander.null try: result = coerce_to_pendulum(cstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid(node, "Invalid date/time: value={!r}, error=" ...
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]
Deserializes string representation to Python object.
4.122876
4.092513
1.007419
if value is None: retval = '' else: # noinspection PyUnresolvedReferences retval = self.type_.serialize(node, value) # log.debug("AllowNoneType.serialize: {!r} -> {!r}", value, retval) return retval
def serialize(self, node: SchemaNode, value: Any) -> Union[str, ColanderNullType]
Serializes Python object to string representation.
4.702799
4.608344
1.020496
features = [] for line in open(filename): line = line.split('#')[0].strip() if line: features.append(line) return features
def get_features_from_equation_file(filename)
returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return:
2.44114
2.793415
0.873891
# first step: extract the original special_refinement_type=None instance_refinement = _is_class_instance(base) if instance_refinement: dictelem = base.__class__.__dict__.get(target_attrname, None) else: dictelem = base.__dict__.get(target_attrnam...
def _create_refinement_wrapper(transformation, baseattr, base, target_attrname)
applies refinement ``transformation`` to ``baseattr`` attribute of ``base``. ``baseattr`` can be any type of callable (function, method, functor) this method handles the differences. docstrings are also rescued from the original if the refinement has no docstring set.
3.572841
3.339954
1.069727
''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
def _compose_pair(self, role, base)
composes onto base by applying the role
7.812371
5.397718
1.447347
''' compose applies multiple fsts onto a base implementation. Pass the base implementation as last parameter. fsts are merged from RIGHT TO LEFT (like function application) e.g.: class MyFST(object): #place introductions and refinements here intro...
def compose(self, *things)
compose applies multiple fsts onto a base implementation. Pass the base implementation as last parameter. fsts are merged from RIGHT TO LEFT (like function application) e.g.: class MyFST(object): #place introductions and refinements here introduce_foo = 'bar' ...
11.847572
3.191563
3.712153
if len(things) == 1: return things[0] module_name = things[-1] if module_name in sys.modules: raise CompositionError( 'compose_later call after module has been imported: ' + module_name ) LazyComposerHook.add(m...
def compose_later(self, *things)
register list of things for composition using compose() compose_later takes a list of fsts. The last element specifies the base module as string things are composed directly after the base module is imported by application code
6.265468
5.857646
1.069622
for feature_name in features: feature_module = importlib.import_module(feature_name) # if available, import feature.py and select the feature try: feature_spec_module = importlib.import_module( feature_name + '.feature' ...
def select(self, *features)
selects the features given as string e.g passing 'hello' and 'world' will result in imports of 'hello' and 'world'. Then, if possible 'hello.feature' and 'world.feature' are imported and select is called in each feature module.
4.956466
4.70277
1.053946
# OSM POI record if 'tags' in data: type_tag = 1 lonlat = data['coordinates'] payload = data['tags'] # Tweet with coordinates from Streaming API elif 'user_id' in data: type_tag = 2 # only allow tweets from the listed d...
def mapper_metro(self, _, data)
map each osm POI and geotweets based on spatial lookup of metro area
8.900345
8.162523
1.090391
lookup = CachedLookup(precision=POI_GEOHASH_PRECISION) for i, value in enumerate(values): type_tag, lonlat, data = value if type_tag == 1: # OSM POI node, construct geojson and add to Rtree index lookup.insert(i, dict( ...
def reducer_metro(self, metro, values)
Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags.
6.908532
5.532306
1.248762
total = sum(values) metro, poi = key # group data by metro areas for final output yield metro, (total, poi)
def reducer_count(self, key, values)
count occurences for each (metro, POI) record
15.831276
10.03788
1.577153
records = [] # build up list of data for each metro area and submit as one network # call instead of individually for value in values: total, poi = value records.append(dict( metro_area=metro, poi=poi, coun...
def reducer_output(self, metro, values)
store each record in MongoDB and output tab delimited lines
5.898533
5.474249
1.077505
raise NotImplementedError( "Don't know how to {task} on dialect {dialect!r}. " "(Check also: if you printed the SQL before it was bound to an " "engine, you will be trying to use a dialect like StrSQLCompiler, " "which could be a reason for failure.)".format( task=ta...
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None
Raise :exc:`NotImplementedError` in relation to a dialect for which a function hasn't been implemented (with a helpful error message).
10.364592
9.597084
1.079973
if len(element.clauses) != 1: raise TypeError("Only one argument supported; {} were passed".format( len(element.clauses))) clauselist = element.clauses # type: ClauseList first = clauselist.get_children()[0] return compiler.process(first)
def fetch_processed_single_clause(element: "ClauseElement", compiler: "SQLCompiler") -> str
Takes a clause element that must have a single clause, and converts it to raw SQL text.
5.203988
4.709674
1.104957
try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
def clean_int(x) -> int
Returns its parameter as an integer, or raises ``django.forms.ValidationError``.
5.528437
3.784847
1.460676
try: x = int(x) if not is_valid_nhs_number(x): raise ValueError return x except ValueError: raise forms.ValidationError( "Not a valid NHS number: {}".format(repr(x)))
def clean_nhs_number(x) -> int
Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``.
3.408913
2.79414
1.220022
if isinstance(coltype, TypeEngine): return coltype return coltype()
def coltype_as_typeengine(coltype: Union[VisitableType, TypeEngine]) -> TypeEngine
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python ...
6.46721
7.942671
0.814236
# http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects skip_relationships_always = skip_relationships_always or [] # type: List[str] # noqa skip_relationships_by_tablename = skip_relationships_by_tablename or {} # type: Dict[str, List[str]] # noqa skip_all_relationships_for_t...
def walk_orm_tree(obj, debug: bool = False, seen: Set = None, skip_relationships_always: List[str] = None, skip_relationships_by_tablename: Dict[str, List[str]] = None, skip_all_relationships_for_tablenames: List[str] = None, ...
Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'somet...
1.992631
2.113103
0.942988
omit_attrs = omit_attrs or [] # type: List[str] cls = type(obj) mapper = class_mapper(cls) newobj = cls() # not: cls.__new__(cls) rel_keys = set([c.key for c in mapper.relationships]) prohibited = rel_keys if omit_pk: pk_keys = set([c.key for c in mapper.primary_key]) ...
def copy_sqla_object(obj: object, omit_fk: bool = True, omit_pk: bool = True, omit_attrs: List[str] = None, debug: bool = False) -> object
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies across all attributes, omitting PKs (by default), FKs (by default), and relationship attributes (always omitted). Args: obj: the object to copy ...
2.432229
2.540189
0.9575
skip_table_names = skip_table_names or [] # type: List[str] insp = inspect(oldobj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname_rel in insp.mapper.relationships.items...
def rewrite_relationships(oldobj: object, newobj: object, objmap: Dict[object, object], debug: bool = False, skip_table_names: List[str] = None) -> None
A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. ...
3.851238
3.986433
0.966086
if objmap is None: objmap = {} # keys = old objects, values = new objects if debug: log.debug("deepcopy_sqla_objects: pass 1: create new objects") # Pass 1: iterate through all objects. (Can't guarantee to get # relationships correct until we've done this, since we don't know whet...
def deepcopy_sqla_objects( startobjs: List[object], session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = True, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> None
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), an...
4.301152
4.029194
1.067497
if objmap is None: objmap = {} # keys = old objects, values = new objects deepcopy_sqla_objects( startobjs=[startobj], session=session, flush=flush, debug=debug, debug_walk=debug_walk, debug_rewrite_rel=debug_rewrite_rel, objmap=objmap ) ...
def deepcopy_sqla_object(startobj: object, session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = False, debug_rewrite_rel: bool = False, objmap: D...
Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly t...
2.309403
2.334675
0.989175
mapper = obj.__mapper__ # type: Mapper assert mapper, "gen_columns called on {!r} which is not an " \ "SQLAlchemy ORM object".format(obj) colmap = mapper.columns # type: OrderedProperties if not colmap: return for attrname, column in colmap.items(): # NB: co...
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?" Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object instance. Also works with the corresponding SQLAlchemy ORM class. Examples: .. code-block:: python from sqlalchemy.ext.declarative import declarative_base ...
4.594499
5.508339
0.834099
return [attrname for attrname, column in gen_columns(obj) if column.primary_key]
def get_pk_attrnames(obj) -> List[str]
Asks an SQLAlchemy ORM object: "what are your primary key(s)?" Args: obj: SQLAlchemy ORM object Returns: list of attribute names of primary-key columns
6.145099
9.701726
0.633403
# noqa for attrname in dir(cls): potential_column = getattr(cls, attrname) if isinstance(potential_column, Column): yield attrname, potential_column
def gen_columns_for_uninstrumented_class(cls: Type) \ -> Generator[Tuple[str, Column], None, None]
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e. one that does not inherit from ``declarative_base()``. Use this for mixins of that kind. SUBOPTIMAL. May produce warnings like: .. code-block:: none SAWarning: Unmanaged access of declarative attribute id from ...
2.729617
5.094753
0.53577
attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
def attrname_to_colname_dict(cls) -> Dict[str, str]
Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names
3.514736
5.001441
0.702745
insp = inspect(obj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname, rel_prop in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa ...
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type], None, None]
Yields tuples of ``(attrname, RelationshipProperty, related_class)`` for all relationships of an ORM object. The object 'obj' can be EITHER an instance OR a class.
3.569863
3.418764
1.044197
mapper = inspect(cls) # type: Mapper # ... returns InstanceState if called with an ORM object # http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#session-object-states # noqa # ... returns Mapper if called with an ORM class # http://docs.sqlalchemy.org/en/latest/o...
def get_orm_columns(cls: Type) -> List[Column]
Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names.
4.591262
4.566484
1.005426
colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
3.241068
3.336575
0.971376
return [table.name for table in metadata.tables.values()]
def get_table_names_from_metadata(metadata: MetaData) -> List[str]
Returns all database table names found in an SQLAlchemy :class:`MetaData` object.
3.711096
4.009804
0.925506
for cls in gen_all_subclasses(base): if _get_immediate_cls_attr(cls, '__abstract__', strict=True): # This is SQLAlchemy's own way of detecting abstract classes; see # sqlalchemy.ext.declarative.base continue # NOT an ORM class yield cls
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]
From an SQLAlchemy ORM base class, yield all the subclasses (except those that are abstract). If you begin with the proper :class`Base` class, then this should give all ORM classes in use.
8.359922
7.979745
1.047643
# noinspection PyUnresolvedReferences return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use.
3.932061
4.881609
0.805485
# noinspection PyUnresolvedReferences columns = self.__table__.columns.keys() values = (getattr(self, x) for x in columns) zipped = zip(columns, values) return OrderedNamespace(zipped)
def get_attrdict(self) -> OrderedNamespace
Returns what looks like a plain object with the values of the SQLAlchemy ORM object.
4.090048
3.394294
1.204978
dictionary = attrdict.__dict__ # noinspection PyArgumentList return cls(**dictionary)
def from_attrdict(cls, attrdict: OrderedNamespace) -> object
Builds a new instance of the ORM object from values in an attrdict.
8.643148
6.421505
1.345969
derived_method = getattr(derived, method_name, None) if derived_method is None: return False base_method = getattr(base, method_name, None) # if six.PY2: # return derived_method.__func__ != base_method.__func__ # else: # return derived_method is not base_method retur...
def derived_class_implements_method(derived: Type[T1], base: Type[T2], method_name: str) -> bool
Does a derived class implement a method (and not just inherit a base class's version)? Args: derived: a derived class base: a base class method_name: the name of a method Returns: whether the derived class method is (a) present, and (b) different to the base class's...
2.121955
2.184391
0.971417
for s1 in cls.__subclasses__(): yield s1 for s2 in gen_all_subclasses(s1): yield s2
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]
Generates all subclasses of a class. Args: cls: a class Yields: all subclasses
2.3152
3.079145
0.751897
s = matrix.shape if ndim is None: ndim = s[0]+1 arr = N.identity(ndim) arr[:s[0],:s[1]] = matrix return arr
def augment_tensor(matrix, ndim=None)
Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices.
3.731532
3.350019
1.113884
n = (norm(v1)*norm(v2)) _ = dot(v1,v2)/n return _ if cos else N.arccos(_)
def angle(v1,v2, cos=False)
Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default.
5.03818
6.184045
0.814706
dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vectors perpendicular to higher- # index axes first. This may or may not be worth # doing. ...
def perpendicular_vector(n)
Get a random vector perpendicular to the given vector
7.060138
7.256006
0.973006
# noqa signal.signal(signal.SIGINT, ctrl_c_trapper) signal.signal(signal.SIGTERM, sigterm_trapper) if platform.system() == 'Windows': # SIGBREAK isn't in the Linux signal module # noinspection PyUnresolvedReferences signal.signal(signal.SIGBREAK, ctrl_break_trapper)
def trap_ctrl_c_ctrl_break() -> None
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing anything. See - https://docs.python.org/3/library/signal.html#signal.SIG_IGN - https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx Un...
3.766976
4.17057
0.903228
try: log.debug("Trying: {}", filename) with ZipFile(filename, 'r') as zip_ref: namelist = zip_ref.namelist() # type: List[str] # log.critical("\n{}", pformat(namelist)) # ----------------------------------------------------------------- # Contain...
def is_openxml_good(filename: str) -> bool
Determines whether an OpenXML file appears to be good (not corrupted).
4.997724
4.928475
1.014051
print_bad = not print_good try: file_good = is_openxml_good(filename) file_bad = not file_good if (print_good and file_good) or (print_bad and file_bad): print(filename) if delete_if_bad and file_bad: log.warning("Deleting: {}", filename) ...
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None
Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file ...
4.552696
4.673479
0.974156
if self.connection: # Nothing to do if the connection is already open. return False connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout try: self.con...
def open(self) -> bool
Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False).
2.796558
2.650482
1.055113
u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) assert all(s1.sum(axis=1) > 0) assert all(s2.sum(axis=1) > 0) _ = 1/8*dot((u1-u2).T, N.linalg.inv(sigma),u1-u2) ...
def bhattacharyya_distance(pca1,pca2)
A measure of the distance between two probability distributions
2.685822
2.705076
0.992882
output_csv(filehandle, fields) for row in values: output_csv(filehandle, row)
def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None
Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values
4.522909
8.300101
0.544922
line = ",".join(values) filehandle.write(line + "\n")
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None
Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values
5.116553
6.16665
0.829714
prefixstart = s.find(prefix) if ((prefixstart == 0 and onlyatstart) or (prefixstart != -1 and not onlyatstart)): # substring found resultstart = prefixstart + len(prefix) result = s[resultstart:] if stripwhitespace: result = result.strip() ret...
def get_what_follows_raw(s: str, prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True) -> Tuple[bool, str]
Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)``
2.7195
3.018074
0.901071
if not precedingline: for s in strings: (found, result) = get_what_follows_raw(s, prefix, onlyatstart, stripwhitespace) if found: return result return "" else: for i in range(1, len(strings)):...
def get_what_follows(strings: Sequence[str], prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True, precedingline: str = "") -> str
Find a string in ``strings`` that begins with ``prefix``; return the part that's after ``prefix``. Optionally, require that the preceding string (line) is ``precedingline``. Args: strings: strings to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right a...
3.077435
3.050822
1.008723
s = get_what_follows(strings, prefix, precedingline=precedingline) if ignoreleadingcolon: f = s.find(":") if f != -1: s = s[f+1:].strip() if len(s) == 0: return None return s
def get_string(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[str]
Find a string as per :func:`get_what_follows`. Args: strings: see :func:`get_what_follows` prefix: see :func:`get_what_follows` ignoreleadingcolon: if ``True``, restrict the result to what comes after its first colon (and whitespace-strip that) precedingline: see :func:`...
2.953132
3.285372
0.898873
for firstline in range(0, len(strings)): if strings[firstline].find(prefix1) == 0: # if found... secondline = firstline + delta if secondline < 0 or secondline >= len(strings): continue if strings[secondline].find(prefix2) == 0: s = s...
def get_string_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False, stripwhitespace: bool = True) -> Optional[str]
Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves ``delta`` lines (strings) further. Returns the end of the line that begins with ``prefix2``, if found. Args: strings: as above prefix1: as above delta: as above prefix2: as above ignoreleadingcolo...
2.236136
2.406682
0.929137
return get_int_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
def get_int(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[int]
Fetches an integer parameter via :func:`get_string`.
3.534791
3.335827
1.059645
return get_float_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
def get_float(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[float]
Fetches a float parameter via :func:`get_string`.
3.342979
3.214213
1.040061
if s == "Y" or s == "y": return True elif s == "N" or s == "n": return False return None
def get_bool_raw(s: str) -> Optional[bool]
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
2.208333
1.871218
1.180158
return get_bool_raw(get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline))
def get_bool(strings: Sequence[str], prefix: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[bool]
Fetches a boolean parameter via :func:`get_string`.
3.534569
3.395933
1.040824
return get_bool_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
def get_bool_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[bool]
Fetches a boolean parameter via :func:`get_string_relative`.
3.964216
3.519652
1.126309
return get_float_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
def get_float_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[float]
Fetches a float parameter via :func:`get_string_relative`.
4.16392
3.592258
1.159137
return get_int_raw(get_string_relative( strings, prefix1, delta, prefix2, ignoreleadingcolon=ignoreleadingcolon))
def get_int_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[int]
Fetches an int parameter via :func:`get_string_relative`.
4.189417
3.538962
1.183798
x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon, precedingline=precedingline) if len(x) == 0: return None # For the format strings you can pass to datetime.datetime.strptime, see # http://docs.python.org/library/datetime.html # A typical one is "...
def get_datetime(strings: Sequence[str], prefix: str, datetime_format_string: str, ignoreleadingcolon: bool = False, precedingline: str = "") -> Optional[datetime.datetime]
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
3.271256
3.304436
0.989959
if linestart is None: # match an empty line for i in range(len(strings)): if is_empty_string(strings[i]): return i return -1 for i in range(len(strings)): if strings[i].find(linestart) == 0: return i return -1
def find_line_beginning(strings: Sequence[str], linestart: Optional[str]) -> int
Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line.
2.629215
2.639987
0.99592
for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
def find_line_containing(strings: Sequence[str], contents: str) -> int
Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found.
2.9756
2.402671
1.238455
start_index = find_line_beginning(strings, firstlinestart) # log.debug("start_index: {}", start_index) if start_index == -1: return [] end_offset = None # itself a valid slice index for lls in list_of_lastline_starts: possible_end_offset = find_line_beginning(strings[start_inde...
def get_lines_from_to(strings: List[str], firstlinestart: str, list_of_lastline_starts: Iterable[Optional[str]]) \ -> List[str]
Takes a list of ``strings``. Returns a list of strings FROM ``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts`` (exclusive). To search to the end of the list, use ``list_of_lastline_starts = []``. To search to a blank line, use ``list_of_lastline_starts = [None]``
2.529567
2.702063
0.936162
# noqa data = [] # type: List[str] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: data.append(fields) return data
def csv_to_list_of_fields(lines: List[str], csvheader: str, quotechar: str = '"') -> List[str]
Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Used for processing e.g. MonkeyCantab rescue text output. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parame...
4.816227
5.912913
0.814527
data = [] # type: List[Dict[str, str]] # an empty line marks the end of the block csvlines = get_lines_from_to(lines, csvheader, [None])[1:] # ... remove the CSV header headerfields = csvheader.split(",") reader = csv.reader(csvlines, quotechar=quotechar) for fields in reader: ...
def csv_to_list_of_dicts(lines: List[str], csvheader: str, quotechar: str = '"') -> List[Dict[str, str]]
Extracts data from a list of CSV lines (starting with a defined header line) embedded in a longer text block but ending with a blank line. Args: lines: CSV lines csvheader: CSV header line quotechar: ``quotechar`` parameter passed to :func:`csv.reader` Returns: list of dict...
3.436683
3.502118
0.981315
for d in dict_list: d[key] = str(d[key]) if d[key] == "": d[key] = None
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``.
2.933228
2.060369
1.423642
for d in dict_list: d[key] = datetime.datetime.strptime(d[key], datetime_format_string)
def dictlist_convert_to_datetime(dict_list: Iterable[Dict], key: str, datetime_format_string: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a ``datetime.datetime`` form, using ``datetime_format_string`` as the format parameter to :func:`datetime.datetime.strptime`.
2.686899
2.187697
1.228186
for d in dict_list: try: d[key] = int(d[key]) except ValueError: d[key] = None
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to an integer. If that fails, convert it to ``None``.
2.605772
1.921448
1.35615
for d in dict_list: try: d[key] = float(d[key]) except ValueError: d[key] = None
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
2.613923
1.953182
1.33829
for d in dict_list: # d[key] = True if d[key] == "Y" else False d[key] = 1 if d[key] == "Y" else 0
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
2.800565
2.614596
1.071127
for d in dict_list: d[key] = value
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None
Process an iterable of dictionaries. For each dictionary ``d``, change (in place) ``d[key]`` to ``value``.
5.168135
3.503592
1.475096
for d in dict_list: d.pop(key, None)
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None
Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists.
4.467864
3.38205
1.321052
# Note that the function won't have the __self__ argument (as in # fn.__self__), at this point, even if it's a member function. try: call_sig = json_encode((fn.__qualname__, args, kwargs)) except TypeError: log.critical( "\nTo decorate using @django_cache_function withou...
def get_call_signature(fn: FunctionType, args: ArgsType, kwargs: KwargsType, debug_cache: bool = False) -> str
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable actual cache key.
8.290699
7.671997
1.080644
key = hashlib.md5(call_signature.encode("utf-8")).hexdigest() if debug_cache: log.debug("Making cache key {} from call_signature {!r}", key, call_signature) return key
def make_cache_key(call_signature: str, debug_cache: bool = False) -> str
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signature. The logic behind these decisions is as follows: - We have a bunch of components of arbitrary t...
3.449087
3.542315
0.973682
cache_key = cache_key or None def decorator(fn): def wrapper(*args, **kwargs): # - NOTE that Django returns None from cache.get() for "not in # cache", so can't cache a None value; # https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage # noqa ...
def django_cache_function(timeout: int = 5 * 60, cache_key: str = '', debug_cache: bool = False)
Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses?
3.904929
3.892325
1.003238
theta = angle(v1,v2) x = N.cross(v1,v2) x = x / N.linalg.norm(x) A = N.array([ [0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]) R = N.exp(A*theta) return R
def transform(v1, v2)
Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
2.537078
2.756438
0.920419
return N.array([ N.cos(lat)*N.cos(lon), N.cos(lat)*N.sin(lon), N.sin(lat) ])
def cartesian(lon, lat)
Converts spherical positions in (lon, lat) to cartesian coordiantes [x,y,z]. For the purposes of this library's focus on orientations, this operates in a *north = vertical* framework. That is, positions around the equator are in the [x,y] plane, and dipping planes occur with higher latitudes. This is i...
2.323282
2.920192
0.795592
utc = utc or context.headers[X_11PATHS_DATE_HEADER_NAME] url_path = ensure_url_path_starts_with_slash(context.url_path) url_path_query = url_path if context.query_params: url_path_query += "?%s" % (url_encode(context.query_params, sort=True)) string_to_sign = (context.method.upper().s...
def x_11paths_authorization(app_id, secret, context, utc=None)
Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API request
3.347353
3.585232
0.93365
sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash.digest())[:-1].decode('utf8')
def _sign_data(secret, data)
Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
2.769161
3.117513
0.888259
if x_headers: headers = to_key_val_list(x_headers, sort=True, insensitive=True) serialized_headers = "" for key, value in headers: if key.lower().startswith(X_11PATHS_HEADER_PREFIX.lower()) and \ key.lower() != X_11PATHS_DATE_HEADER_NAME.lower(): ...
def _get_11paths_serialized_headers(x_headers)
Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a...
3.423329
3.154783
1.085123
return N.array([[N.cos(angle),-N.sin(angle)], [N.sin(angle),N.cos(angle)]])
def rotate_2D(angle)
Returns a 2x2 transformation matrix to rotate by an angle in two dimensions
2.481094
2.913234
0.851663
a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0: sina *= -1 # Construct rotation matrix R= N.array([[cosa,sina],[-sina,cosa]]) else: # Small angle, don't bother ...
def apparent_dip_correction(axes)
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
4.854608
4.857858
0.999331
if means is None: means = N.array([0,0]) arr = augment_tensor(N.diag(hyp_axes)) # Transform ellipsoid to dual hyperboloid hyp = conic(arr).dual() if len(hyp_axes) == 3: # Three_dimensional case if transformation is None: transformation = N.identity(3) ...
def hyperbolic_errors(hyp_axes, xvals, transformation=None, axes=None, means=None, correct_apparent_dip=True, reverse=False)
Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. This creates a hyperbolic quadric and slices it to form a conic on a 2d cartesian plane aligned with the requested direction. A function is returned that takes x values (distance along nomin...
6.530196
6.689228
0.976226
A = N.sqrt(hyp_axes) return A[1]*N.cosh(N.arcsinh(xvals/A[0]))
def hyperbola_values(hyp_axes, xvals)
kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data
6.716705
9.608491
0.699039
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'): if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def sizeof_fmt(num: float, suffix: str = 'B') -> str
Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
1.447407
1.324999
1.092383
# noqa n = int(n) if n < 0: raise ValueError("n < 0") symbols = SYMBOLS[symbols] prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in reversed(symbols[1:]): if n >= prefix[symbol]: value = float(n) / prefix[symbol] ...
def bytes2human(n: Union[int, float], format: str = '%(value).1f %(symbol)s', symbols: str = 'customary') -> str
Converts a number of bytes into a human-readable format. From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Args: n: number of bytes format: a format specification string symbols: can be one of ``"customary"``, ``"customary_ext"``, ``"iec"`` ...
1.5074
1.67124
0.901965
# noqa if not s: raise ValueError("Can't interpret {!r} as integer".format(s)) try: return int(s) except ValueError: pass init = s num = "" while s and s[0:1].isdigit() or s[0:1] == '.': num += s[0] s = s[1:] num = float(num) letter = s.strip...
def human2bytes(s: str) -> int
Modified from http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/. Attempts to guess the string format based on default symbols set and return the corresponding bytes as an integer. When unable to recognize the format, :exc:`ValueError` is raised. >>> human2by...
2.769729
2.756714
1.004721
extra_dependencies = extra_dependencies or [] # type: List[TableDependency] # noqa for td in extra_dependencies: td.set_metadata_if_none(metadata) dependencies = set([td.sqla_tuple() for td in extra_dependencies]) tables = list(metadata.tables.values()) # type: List[Table] for tabl...
def get_all_dependencies(metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependency]
Describes how the tables found in the metadata depend on each other. (If table B contains a foreign key to table A, for example, then B depends on A.) Args: metadata: the metadata to inspect extra_dependencies: additional table dependencies to specify manually sort: sort into alphab...
3.021739
3.155943
0.957476