code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''normalize x to have mean 0 and unity standard deviation''' x = x.astype(float) x -= x.mean() return x / float(x.std())
def normalize(x)
normalize x to have mean 0 and unity standard deviation
5.015206
4.167917
1.203288
''' mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - e.g., the multichannel LFP ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title ''' zvec = np.r_[z_vec] zvec =...
def plot_correlation(z_vec, x0, x1, ax, lag=20., title='firing_rate vs LFP')
mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - e.g., the multichannel LFP ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title
4.058969
3.150008
1.288558
Pr = ((r0*z1 - z0*r1)*(r2 - r3) - (r0 - r1)*(r2*z3 - r3*z2)) / \ ((r0 - r1)*(z2 - z3) - (z0 - z1)*(r2-r3)) Pz = ((r0*z1 - z0*r1)*(z2 - z3) - (z0 - z1)*(r2*z3 - r3*z2)) / \ ((r0 - r1)*(z2 - z3) - (z0 - z1)*(r2-r3)) if Pr >= r0 and Pr <= r1 and Pz >= z...
def _PrPz(r0, z0, r1, z1, r2, z2, r3, z3)
Intersection point for infinite lines. Parameters ---------- r0 : float z0 : float r1 : float z1 : float r2 : float z2 : float r3 : float z3 : float Returns ---------- Pr : float Pz : float hit : bool
1.655588
1.548553
1.069119
from .config import ConfigStore from .database import DataBase from .query import expand_query, preprocess_kwds cfstore = ConfigStore() kwds = expand_query(cfstore.get_config(), kwds) format = get_formatter(**kwds) fmtkeys = formatter_keys(format) candidates = set([ 'comman...
def search_run(output, **kwds)
Search command history.
7.243109
7.026567
1.030818
self.logger.debug('Indexing record: %s', json_path) json_path = os.path.abspath(json_path) self.check_path(json_path, '`json_path`') with open(json_path) as fp: try: dct = json.load(fp) except ValueError: warnings.warn( ...
def index_record(self, json_path)
Import `json_path` and remove it if :attr:`keep_json` is false.
2.735094
2.504615
1.092022
for (root, _, files) in os.walk(self.record_path): for f in (f for f in files if f.endswith('.json')): yield os.path.join(root, f)
def find_record_files(self)
Yield paths to record files.
2.717856
2.414434
1.12567
self.logger.debug('Start indexing all records under: %s', self.record_path) with self.db.connection(): for json_path in sorted(self.find_record_files()): self.index_record(json_path)
def index_all(self)
Index all records under :attr:`record_path`.
6.199953
4.113718
1.507141
''' Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli codes to be executed verbosity : 'str', nest verbosity flag ''' # Load parameters from par...
def sli_run(parameters=object(), fname='microcircuit.sli', verbosity='M_ERROR')
Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli codes to be executed verbosity : 'str', nest verbosity flag
15.573458
4.966423
3.135749
try: value, length = struct.unpack_from(str(self.endianness or default_endianness) + self.struct_format, buffer, offset)[0], struct.calcsize(self.struct_format) if self._enum is not None: try: return self....
def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS)
Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of bytes consumed to create it. :param obj: The parent :class:`.PebblePacket` of this field :type obj: .PebblePacket :param buffer: The buffer from which to extract a value. ...
2.865909
2.62581
1.091438
return struct.pack(str(self.endianness or default_endianness) + self.struct_format, value)
def value_to_bytes(self, obj, value, default_endianness=DEFAULT_ENDIANNESS)
Converts the given value to an appropriately encoded string of bytes that represents it. :param obj: The parent :class:`.PebblePacket` of this field :type obj: .PebblePacket :param value: The python value to serialise. :param default_endianness: The default endianness of the value. Used...
4.384696
5.786803
0.757706
def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps.print_stats() print(s.getvalue()) return res retur...
def profile(func)
Decorator to profile functions with cProfile Args: func: python function Returns: profile report References: https://osf.io/upav8/
1.574514
1.879263
0.837836
func = getattr(self.client, cmd) try: if self.credentials is None: return func(kwargs) else: return func(self.credentials, kwargs) except socket.error as e: raise BackendConnectionError(e) except (xmlrpclib.Pro...
def rpc(self, cmd, **kwargs)
Generic helper function to call an RPC method.
4.020169
3.862818
1.040735
kwargs = { 'body': message, 'from': domain, 'to': '%s@%s' % (username, domain), } if self.api_version <= (14, 7): # TODO: it's unclear when send_message was introduced command = 'send_message_chat' else: c...
def message_user(self, username, domain, subject, message)
Currently use send_message_chat and discard subject, because headline messages are not stored by mod_offline.
4.913199
4.269611
1.150737
openssl_pkey = cert.get_pubkey() openssl_lib = _util.binding.lib ffi = _util.binding.ffi buf = ffi.new("unsigned char **") rsa = openssl_lib.EVP_PKEY_get1_RSA(openssl_pkey._pkey) length = openssl_lib.i2d_RSAPublicKey(rsa, buf) public_key = ffi.buffer(buf[...
def _get_rsa_public_key(cert)
PyOpenSSL does not provide a public method to export the public key from a certificate as a properly formatted ASN.1 RSAPublicKey structure. There are 'hacks' which use dump_privatekey(crypto.FILETYPE_ASN1, <public_key>), but this dumps the public key within a PrivateKeyInfo structure which is not suita...
3.481313
3.379231
1.030209
if not (force_install or self._bundle.should_permit_install()): raise AppInstallError("This pbw is not supported on this platform.") if self._pebble.firmware_version.major < 3: self._install_legacy2() else: self._install_modern()
def install(self, force_install=False)
Installs an app. Blocks until the installation is complete, or raises :exc:`AppInstallError` if it fails. While this method runs, "progress" events will be emitted regularly with the following signature: :: (sent_this_interval, sent_total, total_size) :param force_install: Install even if ...
10.734874
7.258927
1.478851
arrow = _pp.oneOf('-> <- <=>').setResultsName('arrow') species = _pp.Word(_pp.printables).setResultsName('species') coefficient = (_pp.Optional(_pp.Word(_pp.nums), default=1) .setParseAction(_pp.tokenMap(int)) .setResultsName('coefficient')) group_ = _pp.Group(...
def _parse_chemical_equation(value)
Parse the chemical equation mini-language. See the docstring of `ChemicalEquation` for more. Parameters ---------- value : `str` A string in chemical equation mini-language. Returns ------- mapping A mapping in the format specified by the mini-language (see notes on ...
3.017066
3.121469
0.966553
def _get_token(species, coefficient): if coefficient == 1: return '{}'.format(species) else: return '{:g} {}'.format(coefficient, species) bag = [] for species, coefficient in zip(species_list, coefficients): if coefficient < 0: coefficient =...
def _get_chemical_equation_piece(species_list, coefficients)
Produce a string from chemical species and their coefficients. Parameters ---------- species_list : iterable of `str` Iterable of chemical species. coefficients : iterable of `float` Nonzero stoichiometric coefficients. The length of `species_list` and `coefficients` must be the...
2.571825
2.630835
0.97757
if "vibfreqs" in data.columns: for species in data.index: vibfreqs = data.loc[species, "vibfreqs"] nimagvibfreqs = _np.sum(_np.array(vibfreqs) < 0) if species[-1] == '#' and nimagvibfreqs != 1: _warnings.warn("'{}' should have 1 imaginary vibfreqs but...
def _check_data(data)
Check a data object for inconsistencies. Parameters ---------- data : `pandas.DataFrame` A `data` object, i.e., a table whose rows store information about chemical species, indexed by chemical species. Warns ----- UserWarning Warned if a ground state species has one or ...
2.830315
2.333756
1.212773
pieces = _split_arrows(value) return [(pieces[i] + pieces[i + 1] + pieces[i + 2]).strip() for i in range(0, len(pieces) - 2, 2)]
def _split_chemical_equations(value)
Split a string with sequential chemical equations into separate strings. Each string in the returned iterable represents a single chemical equation of the input. See the docstrings of `ChemicalEquation` and `ChemicalSystem` for more. Parameters ---------- value : `str` A string with se...
4.22497
5.560454
0.759825
dataframe = _pd.DataFrame([equation.to_series(*args, **kwargs) for equation in self.equations]) dataframe.index.name = "chemical_equation" return dataframe
def to_dataframe(self, *args, **kwargs)
Produce a data table with records for all chemical equations. All possible differences for numeric attributes are computed and stored as columns in the returned `pandas.DataFrame` object (see examples below), whose rows represent chemical equations. In terms of behavior, this method ca...
6.066541
6.973443
0.869949
# TODO: make test for this digraph = _nx.DiGraph() for equation in self.equations: reactants, arrow, products = [value.strip() for value in _split_arrows(str(equation))] try: attr = equation.to_series("re...
def to_digraph(self, *args, **kwargs)
Compute a directed graph for the chemical system. Returns ------- digraph : `networkx.DiGraph` Graph nodes are reactants and/or products of chemical equations, while edges represent the equations themselves. Double ended edges are used to represent equilibria...
2.902367
2.613437
1.110556
if isinstance(value, _logfileparser.Logfile): # TODO: test this case. jobfilename = value.filename ccdata = value.parse() elif isinstance(value, _data.ccData): # TODO: test this case. jobfilename = None ccdata = value else: # TODO: test this case....
def read_cclib(value, name=None)
Create an `Atoms` object from data attributes parsed by cclib. `cclib <https://cclib.github.io/>`_ is an open source library, written in Python, for parsing and interpreting the results (logfiles) of computational chemistry packages. Parameters ---------- value : `str`, `cclib.parser.logfilepa...
3.53357
3.158865
1.11862
if isinstance(value, _pb.Molecule): # TODO: test this case. jobfilename = None charge, mult = value.charge, value.spin ccdata = _makecclib(value.OBMol) elif isinstance(value, _ob.OBMol): # TODO: test this case. jobfilename = None charge, mult = value....
def read_pybel(value, name=None)
Create an `Atoms` object from content parsed by Pybel. `Pybel <https://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html>`_ is a Python module that simplifies access to the OpenBabel API, a chemical toolbox designed to speak the many languages of chemical data. It’s an open, collaborative project ...
3.249606
3.350346
0.969932
def _prepare_data(data): if not isinstance(data, _pd.DataFrame): try: data = _pd.DataFrame([data.to_series()]) except AttributeError: data = _pd.DataFrame([Atoms(data).to_series()]) if data.index.name != "name": if "name" not i...
def create_data(*args)
Produce a single data object from an arbitrary number of different objects. This function returns a single `pandas.DataFrame` object from a collection of `Atoms` and `pandas.DataFrame` objects. The returned object, already indexed by `Atoms.name`, can be promptly used by e.g. `ChemicalSystem`. Paramet...
3.443173
3.385345
1.017082
r molecule_pybel = self.to_pybel() if pattern is None: fragments = [read_pybel(frag) for frag in molecule_pybel.OBMol.Separate()] else: fragments = [] for group in pattern: fragment_obmol = _pb.ob.OBMol() ...
def split(self, pattern=None)
r""" Break molecule up into constituent fragments. By default (i.e., if `pattern` is `None`), each disconnected fragment is returned as a separate new `Atoms` object. This uses OpenBabel (through `OBMol.Separate`) and might not preserve atom order, depending on your version of t...
4.513959
3.848027
1.173058
# TODO: This only exports last geometry by default. obmol = _makeopenbabel(self.atomcoords, self.atomnos, self.charge, self.mult) title = self.name or "" if 'scfenergies' in self.attributes: title += ", scfenergy={} eV".format(self.scf...
def to_pybel(self)
Produce a Pybel Molecule object. It is based on the capabilities of OpenBabel through Pybel. The present object must have at least `atomcoords`, `atomnos`, `charge` and `mult` defined. Returns ------- `pybel.Molecule` Examples -------- >>> from ...
9.372564
9.496804
0.986918
if type(macro) == list: macro = ' '.join(macro) if len(macro) == 0: print('fijibin.macro.run got empty macro, not starting fiji') return _exists(output_files) if force_close: # make sure fiji halts immediately when done # hack: use error code 42 to check if macro...
def run(macro, output_files=[], force_close=True)
Runs Fiji with the suplied macro. Output of Fiji can be viewed by setting environment variable `DEBUG=fijibin`. Parameters ---------- macro : string or list of strings IJM-macro(s) to run. If list of strings, it will be joined with a space, so all statements should end with ``;``. o...
4.70492
4.023379
1.169395
macro = [] macro.append('run("Grid/Collection stitching",') macro.append('"type=[Filename defined position]') macro.append('order=[Defined by filename ]') macro.append('grid_size_x={}'.format(x_size)) macro.append('grid_size_y={}'.format(y_size)) macro.append('tile_overlap={}'....
def stitch(folder, filenames, x_size, y_size, output_filename, x_start=0, y_start=0, overlap=10)
Creates a Fiji Grid/Collection stitching macro. Parameters are the same as in the plugin and are described in further detail here: http://fiji.sc/Image_Stitching#Grid.2FCollection_Stitching. **Default stitch parameters:** * Filename defined positions * Compute overlap * Subpixel accurancy ...
5.905464
3.740647
1.578728
exists = [] for filename in filenames: if os.path.isfile(filename): exists.append(filename) else: print('fijibin ERROR missing output file {}'.format(filename)) return exists
def _exists(filenames)
Check if every filename exists. If not, print an error message and remove the item from the list. Parameters ---------- filenames : list List of filenames to check for existence. Returns ------- list Filtered list of filenames that exists.
6.86404
9.328059
0.735849
''' Stop an audio streaming session ''' assert self._session_id != VoiceService.SESSION_ID_INVALID self._pebble.send_packet(AudioStream(session_id=self._session_id, data=StopTransfer()))
def send_stop_audio(self)
Stop an audio streaming session
13.516822
10.104067
1.337761
''' Send the result of setting up a dictation session requested by the watch :param result: result of setting up the session :type result: .SetupResult :param app_uuid: UUID of app that initiated the session :type app_uuid: uuid.UUID ''' assert self._ses...
def send_session_setup_result(self, result, app_uuid=None)
Send the result of setting up a dictation session requested by the watch :param result: result of setting up the session :type result: .SetupResult :param app_uuid: UUID of app that initiated the session :type app_uuid: uuid.UUID
4.56488
3.033973
1.504588
''' Send the result of a dictation session :param result: Result of the session :type result: DictationResult :param sentences: list of sentences, each of which is a list of words and punctuation :param app_uuid: UUID of app that initiated the session :type app_u...
def send_dictation_result(self, result, sentences=None, app_uuid=None)
Send the result of a dictation session :param result: Result of the session :type result: DictationResult :param sentences: list of sentences, each of which is a list of words and punctuation :param app_uuid: UUID of app that initiated the session :type app_uuid: uuid.UUID
3.186049
2.763155
1.153047
#ip = get_ipython() ip.register_magics(CustomMagics) # enable C# (CSHARP) highlight patch = ("IPython.config.cell_magic_highlight['clrmagic'] = " "{'reg':[/^%%CS/]};") js = display.Javascript(data=patch, lib=["https://github.com/codemirror/CodeMirror/blo...
def load_ipython_extension(ip)
register magics function, can be called from a notebook
10.016286
9.81523
1.020484
if self._module is None: if self.library is None: raise ValueError( "Backend '%s' doesn't specify a library attribute" % self.__class__) try: if '.' in self.library: mod_path, cls_name = self.library.rspli...
def module(self)
The module specified by the ``library`` attribute.
2.904328
2.601413
1.116443
if dt is None: return int(time.time()) if six.PY3: if not dt.tzinfo: dt = pytz.utc.localize(dt) return int(dt.timestamp()) else: if dt.tzinfo: dt = dt.replace(tzinfo=None) - dt.utcoffset() retur...
def datetime_to_timestamp(self, dt)
Helper function to convert a datetime object to a timestamp. If datetime instance ``dt`` is naive, it is assumed that it is in UTC. In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset and returns the difference since 1970-01-01 00:00:00. ...
2.065833
1.995498
1.035247
if chars is None: chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for x in range(length))
def get_random_password(self, length=32, chars=None)
Helper function that gets a random password. :param length: The length of the random password. :type length: int :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits. :type chars: str
1.93233
2.16751
0.891498
now = datetime.utcnow() if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now: return self.version_cache_value # we have a cached value self.version_cache_value = self.get_api_version() if self.minimum_version and se...
def api_version(self)
Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`.
3.111661
2.66842
1.166106
password = self.get_random_password() self.create(username=username, domain=domain, password=password, email=email)
def create_reservation(self, username, domain, email=None)
Reserve a new account. This method is called when a user account should be reserved, meaning that the account can no longer be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email confirmation is still pending. The default implementation cal...
3.34995
4.871447
0.68767
self.set_password(username=username, domain=domain, password=password) if email is not None: self.set_email(username=username, domain=domain, email=email)
def confirm_reservation(self, username, domain, password, email=None)
Confirm a reservation for a username. The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
2.135602
1.895467
1.126689
self.set_password(username, domain, self.get_random_password())
def block_user(self, username, domain)
Block the specified user. The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a random password. :param username: The username of the user. :type username: str :param domain: The domain of the user. :type domain: str
5.875925
4.507107
1.303702
# TODO: Websockets, HTTP Polling if connection == 'c2s_tls': return CONNECTION_XMPP, True, False elif connection == 'c2s_compressed_tls': return CONNECTION_XMPP, True, True elif connection == 'http_bind': return CONNECTION_HTTP_BINDING, None, ...
def parse_connection_string(self, connection)
Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls. >>> EjabberdBackendBase().parse_connection_string('c2s_tls') (0, True, False) >>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls') (0, True, True) >>> EjabberdBackend...
5.066591
3.06064
1.655402
if ip_address.startswith('::FFFF:'): ip_address = ip_address[7:] if six.PY2 and isinstance(ip_address, str): # ipaddress constructor does not eat str in py2 :-/ ip_address = ip_address.decode('utf-8') return ipaddress.ip_address(ip_address)
def parse_ip_address(self, ip_address)
Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls. Example:: >>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT IPv4Address('192.168.0.1') >>> EjabberdBackendBase().parse_ip_address('::FFFF:192.16...
3.910304
3.915169
0.998757
origin, message = self.transport.read_packet() if isinstance(origin, MessageTargetWatch): self._handle_watch_message(message) else: self._broadcast_transport_message(origin, message)
def pump_reader(self)
Synchronously reads one message from the watch, blocking until a message is available. All events caused by the message read will be processed before this method returns. .. note:: You usually don't need to invoke this method manually; instead, see :meth:`run_sync` and :meth:`run_async`.
9.480642
8.782968
1.079435
while self.connected: try: self.pump_reader() except PacketDecodeError as e: logger.warning("Packet decode failed: %s", e) except ConnectionError: break
def run_sync(self)
Runs the message loop until the Pebble disconnects. This method will block until the watch disconnects or a fatal error occurs. For alternatives that don't block forever, see :meth:`pump_reader` and :meth:`run_async`.
6.474588
4.475021
1.446829
thread = threading.Thread(target=self.run_sync) thread.daemon = True thread.name = "PebbleConnection" thread.start() self.fetch_watch_info()
def run_async(self)
Spawns a new thread that runs the message loop until the Pebble disconnects. ``run_async`` will call :meth:`fetch_watch_info` on your behalf, and block until it receives a response.
5.905529
3.139935
1.880781
if self.log_protocol_level is not None: logger.log(self.log_protocol_level, "<- %s", hexlify(message).decode()) message = self.pending_bytes + message while len(message) >= 4: try: packet, length = PebblePacket.parse_message(message) ...
def _handle_watch_message(self, message)
Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes
5.655601
5.445445
1.038593
self.event_handler.broadcast_event((_EventType.Transport, type(origin), type(message)), message)
def _broadcast_transport_message(self, origin, message)
Broadcasts an event originating from a transport that does not represent a message from the Pebble. :param origin: The type of transport responsible for the message. :type origin: .MessageTarget :param message: The message from the transport
16.186083
18.027489
0.897856
return self.event_handler.register_handler((_EventType.Transport, origin, message_type), handler)
def register_transport_endpoint(self, origin, message_type, handler)
Register a handler for a message received from a transport that does not indicate a message from the connected Pebble. :param origin: The type of :class:`.MessageTarget` that triggers the message :param message_type: The class of the message that is expected. :param handler: A callback ...
8.984063
12.940666
0.69425
return self.event_handler.register_handler((_EventType.Watch, endpoint), handler)
def register_endpoint(self, endpoint, handler)
Register a handler for a message received from the Pebble. :param endpoint: The type of :class:`.PebblePacket` that is being listened for. :type endpoint: .PacketType :param handler: A callback to be called when a message is received. :type handler: callable :return: A handle th...
19.547054
29.842987
0.654997
return self.event_handler.wait_for_event((_EventType.Watch, endpoint), timeout=timeout)
def read_from_endpoint(self, endpoint, timeout=15)
Blocking read from an endpoint. Will block until a message is received, or it times out. Also see :meth:`get_endpoint_queue` if you are considering calling this in a loop. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock. .. no...
14.864369
27.267839
0.545125
return self.event_handler.wait_for_event((_EventType.Transport, origin, message_type), timeout=timeout)
def read_transport_message(self, origin, message_type, timeout=15)
Blocking read of a transport message that does not indicate a message from the Pebble. Will block until a message is received, or it times out. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock. :param origin: The type of :class...
7.933492
11.247828
0.705335
if self.log_packet_level: logger.log(self.log_packet_level, "-> %s", packet) serialised = packet.serialise_packet() self.event_handler.broadcast_event("raw_outbound", serialised) self.send_raw(serialised)
def send_packet(self, packet)
Sends a message to the Pebble. :param packet: The message to send. :type packet: .PebblePacket
5.762733
6.443421
0.894359
queue = self.get_endpoint_queue(endpoint) self.send_packet(packet) try: return queue.get(timeout=timeout) finally: queue.close()
def send_and_read(self, packet, endpoint, timeout=15)
Sends a packet, then returns the next response received from that endpoint. This method sets up a listener before it actually sends the message, avoiding a potential race. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock. :para...
3.138228
3.548387
0.88441
if self.log_protocol_level: logger.log(self.log_protocol_level, "-> %s", hexlify(message).decode()) self.transport.send_packet(message)
def send_raw(self, message)
Sends a raw binary message to the Pebble. No processing will be applied, but any transport framing should be omitted. :param message: The message to send to the pebble. :type message: bytes
4.672655
4.867197
0.96003
self._watch_info = self.send_and_read(WatchVersion(data=WatchVersionRequest()), WatchVersion).data
def fetch_watch_info(self)
This method should be called before accessing :attr:`watch_info`, :attr:`firmware_version` or :attr:`watch_platform`. Blocks until it has fetched the required information.
21.281338
15.934727
1.335532
version = self.watch_info.running.version_tag[1:] parts = version.split('-', 1) points = [int(x) for x in parts[0].split('.')] while len(points) < 3: points.append(0) if len(parts) == 2: suffix = parts[1] else: suffix = '' ...
def firmware_version(self)
Provides information on the connected Pebble, including its firmware version, language, capabilities, etc. .. note: This is a blocking call if :meth:`fetch_watch_info` has not yet been called, which could lead to deadlock if called in an endpoint callback. :rtype: .WatchVersionRe...
3.849499
3.895042
0.988307
with open(fname, 'rb') as f: while True: a = [] for i in range(self.bsize): line = f.readline() if not line: break a.append(line.split()) if a == []: raise StopIteration ...
def _blockread(self, fname)
Generator yields bsize lines from gdf file. Hidden method. Parameters ---------- fname : str Name of gdf-file. Yields ------ list file contents
3.036597
2.854223
1.063896
self.cursor.execute('CREATE TABLE IF NOT EXISTS spikes (neuron INT UNSIGNED, time REAL)') tic = now() for f in glob.glob(re): print(f) while True: try: for data in self._blockread(f): self.cursor.execut...
def create(self, re='brunel-py-ex-*.gdf', index=True)
Create db from list of gdf file glob Parameters ---------- re : str File glob to load. index : bool Create index on neurons for speed. Returns ------- None See also -------- ...
3.762314
3.405071
1.104915
self.cursor.execute('CREATE TABLE IF NOT EXISTS spikes (neuron INT UNSIGNED, time REAL)') tic = now() i = 0 for x in re: data = list(zip([i] * len(x), x)) self.cursor.executemany('INSERT INTO spikes VALUES (?, ?)', data) i += 1 self.c...
def create_from_list(self, re=[], index=True)
Create db from list of arrays. Parameters ---------- re : list Index of element is cell index, and element `i` an array of spike times in ms. index : bool Create index on neurons for speed. Returns ------- None ...
3.370054
2.976259
1.132312
s = [] for neuron in neurons: self.cursor.execute('SELECT time FROM spikes where neuron = %d' % neuron) sel = self.cursor.fetchall() spikes = np.array(sel).flatten() s.append(spikes) return s
def select(self, neurons)
Select spike trains. Parameters ---------- neurons : numpy.ndarray or list Array of list of neurons. Returns ------- list List of numpy.ndarray objects containing spike times. See also -------- sqlite3.connect.cursor
3.607786
3.103693
1.162417
self.cursor.execute('SELECT * FROM spikes WHERE time BETWEEN %f AND %f' % tuple(T)) sel = self.cursor.fetchall() return sel
def interval(self, T=[0, 1000])
Get all spikes in a time interval T. Parameters ---------- T : list Time interval. Returns ------- s : list Nested list with spike times. See also -------- sqlite3.connect.cursor
5.334426
4.050808
1.316879
self.cursor.execute('SELECT DISTINCT neuron FROM spikes ORDER BY neuron') sel = self.cursor.fetchall() return np.array(sel).flatten()
def neurons(self)
Return list of neuron indices. Parameters ---------- None Returns ------- list list of neuron indices See also -------- sqlite3.connect.cursor
5.460954
4.321258
1.263742
self.cursor.execute('SELECT Count(*) from spikes') rows = self.cursor.fetchall()[0] # Check against 'wc -l *ex*.gdf' if self.debug: print('DB has %d spikes' % rows) return rows
def num_spikes(self)
Return total number of spikes. Parameters ---------- None Returns ------- list
11.435448
11.789087
0.970003
fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) neurons = self.neurons() i = 0 for x in self.select_neurons_interval(neurons, T): ax.plot(x, np.zeros(x.size) + neurons[i], 'o', markersize=1, markerfacecolor='k', markeredgeco...
def plotstuff(self, T=[0, 1000])
Create a scatter plot of the contents of the database, with entries on the interval T. Parameters ---------- T : list Time interval. Returns ------- None See also -------- GDF.select_neurons...
2.797113
2.327198
1.201923
def represent_as_tuple(string): keep = (".", "[", "]") return tuple(str_digit_to_int(c) if c not in keep else c for c in string)
Represent a number-string in the form of a tuple of digits. "868.0F" -> (8, 6, 8, '.', 0, 15) Args: string - Number represented as a string of digits. Returns: Number represented as an iterable container of digits >>> represent_as_tuple('868.0F') (8, 6, 8, '.', 0, 15)
null
null
null
def represent_as_string(iterable): keep = (".", "[", "]") return "".join(tuple(int_to_str_digit(i) if i not in keep else i for i in iterable))
Represent a number in the form of a string. (8, 6, 8, '.', 0, 15) -> "868.0F" Args: iterable - Number represented as an iterable container of digits. Returns: Number represented as a string of digits. >>> represent_as_string((8, 6, 8, '.', 0, 15)) '868.0F'
null
null
null
def digit(decimal, digit, input_base=10): if decimal == 0: return 0 if digit != 0: return (decimal // (input_base ** digit)) % input_base else: return decimal % input_base
Find the value of an integer at a specific digit when represented in a particular base. Args: decimal(int): A number represented in base 10 (positive integer). digit(int): The digit to find where zero is the first, lowest, digit. base(int): The base to use (default 10). Ret...
null
null
null
def digits(number, base=10): if number < 1: return 0 digits = 0 n = 1 while(number >= 1): number //= base digits += 1 return digits
Determines the number of digits of a number in a specific base. Args: number(int): An integer number represented in base 10. base(int): The base to find the number of digits. Returns: Number of digits when represented in a particular base (integer). Examples: >>>...
null
null
null
def integer_fractional_parts(number): radix_point = number.index(".") integer_part = number[:radix_point] fractional_part = number[radix_point:] return(integer_part, fractional_part)
Returns a tuple of the integer and fractional parts of a number. Args: number(iterable container): A number in the following form: (..., ".", int, int, int, ...) Returns: (integer_part, fractional_part): tuple. Example: >>> integer_fractional_parts((1,2,3,"."...
null
null
null
def from_base_10_int(decimal, output_base=10): if decimal <= 0: return (0,) if output_base == 1: return (1,) * decimal length = digits(decimal, output_base) converted = tuple(digit(decimal, i, output_base) for i in range(length)) return converted[::-1]
Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16...
null
null
null
def to_base_10_int(n, input_base): return sum(c * input_base ** i for i, c in enumerate(n[::-1]))
Converts an integer in any base into it's decimal representation. Args: n - An integer represented as a tuple of digits in the specified base. input_base - the base of the input number. Returns: integer converted into base 10. Example: >>> to_base_10_int((8,1), 1...
null
null
null
def fractional_base(fractional_part, input_base=10, output_base=10, max_depth=100): fractional_part = fractional_part[1:] fractional_digits = len(fractional_part) numerator = 0 for i, value in enumerate(fractional_part, 1): numerator += value * input_base ** (frac...
Convert the fractional part of a number from any base to any base. Args: fractional_part(iterable container): The fractional part of a number in the following form: ( ".", int, int, int, ...) input_base(int): The base to convert from (defualt 10). output_base(int): The ...
null
null
null
def truncate(n): count = 0 for digit in n[-1::-1]: if digit != 0: break count += 1 return n[:-count] if count > 0 else n
Removes trailing zeros. Args: n: The number to truncate. This number should be in the following form: (..., '.', int, int, int, ..., 0) Returns: n with all trailing zeros removed >>> truncate((9, 9, 9, '.', 9, 9, 9, 9, 0, 0, 0, 0)) (9, 9, 9, '.', 9, 9...
null
null
null
def str_digit_to_int(chr): # 0 - 9 if chr in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): n = int(chr) else: n = ord(chr) # A - Z if n < 91: n -= 55 # a - z or higher else: n -= 61 return n
Converts a string character to a decimal number. Where "A"->10, "B"->11, "C"->12, ...etc Args: chr(str): A single character in the form of a string. Returns: The integer value of the input string digit.
null
null
null
def int_to_str_digit(n): # 0 - 9 if n < 10: return str(n) # A - Z elif n < 36: return chr(n + 55) # a - z or higher else: return chr(n + 61)
Converts a positive integer, to a single string character. Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc Args: n(int): A positve integer number. Returns: The character representation of the input digit of value n (str).
null
null
null
def find_recurring(number, min_repeat=5): # Return number if it has no fractional part, or min_repeat value invalid. if "." not in number or min_repeat < 1: return number # Seperate the number into integer and fractional parts. integer_part, fractional_part = integer_fractional_parts(...
Attempts to find repeating digits in the fractional component of a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) min_repeat(int): the minimum number of times a pattern must occur to be defined as recurring. ...
null
null
null
def expand_recurring(number, repeat=5): if "[" in number: pattern_index = number.index("[") pattern = number[pattern_index + 1:-1] number = number[:pattern_index] number = number + pattern * (repeat + 1) return number
Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. E...
null
null
null
def check_valid(number, input_base=10): for n in number: if n in (".", "[", "]"): continue elif n >= input_base: if n == 1 and input_base == 1: continue else: return False return True
Checks if there is an invalid digit in the input number. Args: number: An number in the following form: (int, int, int, ... , '.' , int, int, int) (iterable container) containing positive integers of the input base input_base(int): The base of the input number. ...
null
null
null
def base(number, input_base=10, output_base=10, max_depth=10, string=False, recurring=True): # Convert number to tuple representation. if type(number) == int or type(number) == float: number = str(number) if type(number) == str: number = represent_as_tuple(number) #...
Converts a number from any base to any another. Args: number(tuple|str|int): The number to convert. input_base(int): The base to convert from (defualt 10). output_base(int): The base to convert to (default 10). max_depth(int): The maximum number of fractional digits (defult 10...
null
null
null
if platform.system().lower() == 'windows': path = os.path.join(os.getenv('APPDATA') or '~', appname, appname) elif platform.system().lower() == 'darwin': path = os.path.join('~', 'Library', 'Application Support', appname) else: path = os.path.join(os.getenv('XDG_CONFIG_HOME') or...
def get_config_directory(appname)
Get OS-specific configuration directory. :type appname: str :arg appname: capitalized name of the application
1.991942
2.067196
0.963596
email = message.EmailMessage( subject=obj.subject, body=obj.body, from_email=obj.from_email, to=[t.strip() for t in obj.to_emails.split(',')], bcc=[t.strip() for t in obj.bcc_emails.split(',')], cc=[t.strip() for t in obj.cc_emails...
def save_model(self, request, obj, form, change)
sends the email and does not save it
2.046878
1.909629
1.071872
gdf_file = open(fname, 'r') gdf = [] for l in gdf_file: data = l.split() gdf += [data] gdf = np.array(gdf, dtype=object) if gdf.size > 0: gdf[:, 0] = gdf[:, 0].astype(int) gdf[:, 1:] = gdf[:, 1:].astype(float) return np.array(gdf)
def read_gdf(fname)
Fast line-by-line gdf-file reader. Parameters ---------- fname : str Path to gdf-file. Returns ------- numpy.ndarray ([gid, val0, val1, **]), dtype=object) mixed datatype array
2.299811
2.242695
1.025468
gdf_file = open(fname, 'w') for line in gdf: for i in np.arange(len(line)): gdf_file.write(str(line[i]) + '\t') gdf_file.write('\n') return None
def write_gdf(gdf, fname)
Fast line-by-line gdf-file write function Parameters ---------- gdf : numpy.ndarray Column 0 is gids, columns 1: are values. fname : str Path to gdf-file. Returns ------- None
2.462605
2.399923
1.026118
assert y is not None or electrode is not None if y is not None: f = h5py.File(os.path.join(path, '%s_%ss.h5' %(y,data_type))) data = f['data'].value[:,:, warmup:] if scaling != 1.: np.random.shuffle(data) num_cells = int(len(data)*scaling) da...
def load_h5_data(path='', data_type='LFP', y=None, electrode=None, warmup=0., scaling=1.)
Function loading results from hdf5 file Parameters ---------- path : str Path to hdf5-file data_type : str Signal types in ['CSD' , 'LFP', 'CSDsum', 'LFPsum']. y : None or str Name of population. electrode : None or int TODO: update, electrode is NOT USE...
2.780175
2.921884
0.951501
# Open file print('writing to file: %s' % fname) f = h5py.File(fname) # Iterate over values for i, ivalue in list(data.items()): igrp = f.create_group(str(i)) for j, jvalue in enumerate(ivalue): jgrp = igrp.create_group(str(j)) for k, kvalue in enumerate(...
def dump_dict_of_nested_lists_to_h5(fname, data)
Take nested list structure and dump it in hdf5 file. Parameters ---------- fname : str Filename data : dict(list(numpy.ndarray)) Dict of nested lists with variable len arrays. Returns ------- None
2.349143
2.352017
0.998778
# Container: data = {} # Open file object f = h5py.File(fname, 'r') # Iterate over partial dataset if toplevelkeys is not None: for i in toplevelkeys: ivalue = f[str(i)] data[i] = [] for j, jvalue in enumerate(ivalue.values()): ...
def load_dict_of_nested_lists_from_h5(fname, toplevelkeys=None)
Load nested list structure from hdf5 file Parameters ---------- fname : str Filename toplevelkeys : None or iterable, Load a two(default) or three-layered structure. Returns ------- dict(list(numpy.ndarray)) dictionary of nested lists with variable length...
2.267263
2.390766
0.948342
if RANK == 0: if not os.path.isdir(params.savefolder): os.mkdir(params.savefolder) assert(os.path.isdir(params.savefolder)) else: if clearDestination: print('removing folder tree %s' % params.savefolder) while os.path.isdir(par...
def setup_file_dest(params, clearDestination=True)
Function to set up the file catalog structure for simulation output Parameters ---------- params : object e.g., `cellsim16popsParams.multicompartment_params()` clear_dest : bool Savefolder will be cleared if already existing. Returns ------- None
2.46433
2.282857
1.079494
if len(np.shape(data)) > 1: n = len(data[0]) return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data, axis=1) else: n = len(data) return np.fft.fftfreq(n, tbin * 1e-3), np.fft.fft(data)
def calculate_fft(data, tbin)
Function to calculate the Fourier transform of data. Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series. tbin : float Bin size of time series (in ms). Returns ------- freqs : numpy.ndarray Frequency axis of signal in F...
1.927647
2.007702
0.960126
assert(time is not False or units is not False) res = copy.copy(data) if time is True: res = np.array([x - np.mean(x) for x in res]) if units is True: res = np.array(res - np.mean(res, axis=0)) return res
def centralize(data, time=False, units=False)
Function to subtract the mean across time and/or across units from data Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series, 1st index: unit, 2nd index: time time : bool True: subtract mean across time. units : bool True: subtract mean...
2.782497
3.320112
0.838073
data = data.astype(float) data -= data.mean() return data / data.std()
def normalize(data)
Function to normalize data to have mean 0 and unity standard deviation (also called z-transform) Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray z-transform of input array
4.531834
8.60822
0.526454
if Dx <= dx: return y else: ly = len(y) r = np.zeros(ly) n = np.int(np.round((Dx / dx))) r[0:np.int(n / 2.)] = 1.0 / n r[-np.int(n / 2.)::] = 1.0 / n R = np.fft.fft(r) Y = np.fft.fft(y) yf = np.fft.ifft(Y * R) return yf
def movav(y, Dx, dx)
Moving average rectangular window filter: calculate average of signal y by using sliding rectangular window of size Dx using binsize dx Parameters ---------- y : numpy.ndarray Signal Dx : float Window length of filter. dx : float Bin size of signal sampling....
2.981463
3.052845
0.976618
if not isinstance(q, int): raise TypeError("q must be an integer") if n is None: n = 1 if filterfun == ss.butter: b, a = filterfun(n, k / q) elif filterfun == ss.cheby1: b, a = filterfun(n, 0.05, k / q) else: raise Exception('only ss.butter or ss.cheby1...
def decimate(x, q=10, n=4, k=0.8, filterfun=ss.cheby1)
scipy.signal.decimate like downsampling using filtfilt instead of lfilter, and filter coeffs from butterworth or chebyshev type 1. Parameters ---------- x : numpy.ndarray Array to be downsampled along last axis. q : int Downsampling factor. n : int Filter order. k ...
2.892422
2.896353
0.998643
assert(units is not False or time is not False) if units is True and time is False: return np.mean(data, axis=0) elif units is False and time is True: return np.mean(data, axis=1) elif units is True and time is True: return np.mean(data)
def mean(data, units=False, time=False)
Function to compute mean of data Parameters ---------- data : numpy.ndarray 1st axis unit, 2nd axis time units : bool Average over units time : bool Average over time Returns ------- if units=False and time=False: error if units=True: 1...
2.036888
2.412723
0.844228
freq, DATA = calculate_fft(data, tbin) df = freq[1] - freq[0] T = tbin * len(freq) POW = np.abs(DATA) ** 2 if Df is not None: POW = [movav(x, Df, df) for x in POW] cut = int(Df / df) freq = freq[cut:] POW = np.array([x[cut:] for x in POW]) POW = np.abs(P...
def powerspec(data, tbin, Df=None, units=False, pointProcess=False)
Calculate (smoothed) power spectra of all timeseries in data. If units=True, power spectra are averaged across units. Note that averaging is done on power spectra rather than data. If pointProcess is True, power spectra are normalized by the length T of the time series. Parameters ----------...
4.058245
4.186177
0.969439
return powerspec([np.sum(data, axis=0)], tbin, Df=Df, units=True, pointProcess=pointProcess)
def compound_powerspec(data, tbin, Df=None, pointProcess=False)
Calculate the power spectrum of the compound/sum signal. data is first summed across units, then the power spectrum is calculated. If pointProcess=True, power spectra are normalized by the length T of the time series. Parameters ---------- data : numpy.ndarray, 1st axis unit, 2nd...
6.547906
9.795803
0.66844
N = len(data) if units is True: # smoothing and normalization take place in powerspec # and compound_powerspec freq, POW = powerspec(data, tbin, Df=Df, units=True) freq_com, CPOW = compound_powerspec(data, tbin, Df=Df) assert(len(freq) == len(freq_com)) asse...
def crossspec(data, tbin, Df=None, units=False, pointProcess=False)
Calculate (smoothed) cross spectra of data. If `units`=True, cross spectra are averaged across units. Note that averaging is done on cross spectra rather than data. Cross spectra are normalized by the length T of the time series -> no scaling with T. If pointProcess=True, power spectra are normali...
3.1638
3.050104
1.037276
a_mdata = [] for data in a_data: a_mdata.append(np.sum(data, axis=0)) # calculate compound signals return crossspec(np.array(a_mdata), tbin, Df, units=False, pointProcess=pointProcess)
def compound_crossspec(a_data, tbin, Df=None, pointProcess=False)
Calculate cross spectra of compound signals. a_data is a list of datasets (a_data = [data1,data2,...]). For each dataset in a_data, the compound signal is calculated and the crossspectra between these compound signals is computed. If pointProcess=True, power spectra are normalized by the length T o...
4.742481
4.759728
0.996376
tbin = 1. / (2. * np.max(freq)) * 1e3 # tbin in ms time = np.arange(-len(freq) / 2. + 1, len(freq) / 2. + 1) * tbin # T = max(time) multidata = False if len(np.shape(power)) > 1: multidata = True if multidata: N = len(power) autof = np.zeros((N, len(freq))) ...
def autocorrfunc(freq, power)
Calculate autocorrelation function(s) for given power spectrum/spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. power : numpy.ndarray 2 dimensional power spectra, 1st axis units, 2nd axis frequencies. Returns ------- time : tuple ...
2.641698
2.518006
1.049123
tbin = 1. / (2. * np.max(freq)) * 1e3 # tbin in ms time = np.arange(-len(freq) / 2. + 1, len(freq) / 2. + 1) * tbin # T = max(time) multidata = False # check whether cross contains many cross spectra if len(np.shape(cross)) > 1: multidata = True if multidata: N = len(c...
def crosscorrfunc(freq, cross)
Calculate crosscorrelation function(s) for given cross spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. cross : numpy.ndarray 2 dimensional array of cross spectra, 1st axis units, 2nd axis units, 3rd axis frequencies. Returns --...
2.682681
2.579259
1.040098
N = len(crossf) cc = np.zeros(np.shape(crossf)[:-1]) tbin = abs(time[1] - time[0]) lim = int(integration_window / tbin) if len(time)%2 == 0: mid = len(time)/2-1 else: mid = np.floor(len(time)/2.) for i in range(N): ai = np.sum(crossf[i, i][mid - lim:mi...
def corrcoef(time, crossf, integration_window=0.)
Calculate the correlation coefficient for given auto- and crosscorrelation functions. Standard settings yield the zero lag correlation coefficient. Setting integration_window > 0 yields the correlation coefficient of integrated auto- and crosscorrelation functions. The correlation coefficient between a ...
2.463165
2.434471
1.011786