code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
skills_data_file = expanduser('~/.mycroft/skills.json') if isfile(skills_data_file): try: with open(skills_data_file) as f: return json.load(f) except json.JSONDecodeError: return {} else: return {}
def load_skills_data() -> dict
Contains info on how skills should be updated
2.520296
2.237414
1.126432
for e in skills_data.get('skills', []): if e.get('name') == name: return e return {}
def get_skill_entry(name, skills_data) -> dict
Find a skill entry in the skills_data and returns it.
3.970779
2.897253
1.370532
# if the sequence of the packet is smaller than the last received sequence, return false # therefore calculate the difference between the two values: try: # try, because self.lastSequence might not been initialized diff = packet.sequence - self.lastSequence[packet.universe]...
def is_legal_sequence(self, packet: DataPacket) -> bool
Check if the Sequence number of the DataPacket is legal. For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf. :param packet: the packet to check :return: true if the sequence is legal. False if the sequence number is bad
7.659259
7.347131
1.042483
# check if the packet's priority is high enough to get processed if packet.universe not in self.callbacks.keys() or \ packet.priority < self.priorities[packet.universe][0]: return False # return if the universe is not interesting else: return True
def is_legal_priority(self, packet: DataPacket)
Check if the given packet has high enough priority for the stored values for the packet's universe. :param packet: the packet to check :return: returns True if the priority is good. Otherwise False
7.787605
6.096089
1.277476
svc = Class(**kw) if name is None: name = Class.__name__ # Make it easier (possible) to find this service by name later on svc.setName(name) app = service.Application(name, uid=uid, gid=gid) app.addComponent(NotPersistable(app), ignoreClass=True) ...
def deploy(Class, name=None, uid=None, gid=None, **kw)
Create an application with the give name, uid, and gid. The application has one child service, an instance of Class configured based on the additional keyword arguments passed. The application is not persistable. @param Class: @param name: @param uid: @param gi...
7.690116
7.854132
0.979117
tcp = internet.TCPServer(normalPort, f) tcp.setName(name) self.servers.append(tcp) if sslPort is not None: ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac) ssl.setName(name+'s') self.servers.append(ssl)
def addServer(self, normalPort, sslPort, f, name)
Add a TCP and an SSL server. Name them `name` and `name`+'s'. @param normalPort: @param sslPort: @param f: @param name:
2.72334
3.011251
0.904388
ourPrivateCert = self.service.certificateStorage.getPrivateCertificate( str(subject) ) ourCA = Certificate(ourPrivateCert.original) return dict(certificate=ourCA)
def _identify(self, subject)
Implementation of L{Identify}.
16.364004
13.19787
1.239897
# The peer is coming from a client-side representation of the user # described by 'From', and talking *to* a server-side representation of # the user described by 'From'. self.verifyCertificateAllowed(From, From) theirCert = Certificate.peerFromTransport(self.transport) ...
def _listen(self, protocols, From, description)
Implementation of L{Listen}.
8.941204
8.78534
1.017741
# Verify stuff! self.verifyCertificateAllowed(to, From) return self.service.verifyHook(From, to, protocol ).addCallback(self._inboundimpl, From, ...
def _inbound(self, From, to, protocol, udp_source=None)
Implementation of L{Inbound}.
15.133089
13.868127
1.091214
if id not in self.connections: raise error.ConnectionDone() connection = self.connections[id] connection.dataReceived(body) return {}
def _write(self, body, id)
Respond to a WRITE command, sending some data over a virtual channel created by VIRTUAL. The answer is simply an acknowledgement, as it is simply meant to note that the write went through without errors. An occurrence of I{Write} on the wire, together with the response generated by thi...
7.376809
7.841739
0.940711
# The connection is removed from the mapping by connectionLost. connection = self.connections[id] connection.connectionLost(Failure(CONNECTION_DONE)) return {}
def _close(self, id)
Respond to a CLOSE command, dumping some data onto the stream. As with WRITE, this returns an empty acknowledgement. An occurrence of I{Close} on the wire, together with the response generated by this method, might have this apperance:: C: -Command: Close C: -Ask: 1 ...
13.046718
14.403809
0.905782
if self.service.portal is None: raise BadCertificateRequest("This agent cannot sign certificates.") subj = certificate_request.getSubject() sk = subj.keys() if 'commonName' not in sk: raise BadCertificateRequest( "Certificate requested w...
def _sign(self, certificate_request, password)
Respond to a request to sign a CSR for a user or agent located within our domain.
9.304661
9.034402
1.029914
if self.hostCertificate is not None: raise RuntimeError("Re-encrypting already encrypted connection") CS = self.service.certificateStorage ourCert = CS.getPrivateCertificate(str(to.domainAddress())) if authorize: D = CS.getSelfSignedCertificate(str(From.d...
def _secure(self, to, From, authorize)
Response to a SECURE command, starting TLS when necessary, and using a certificate identified by the I{To} header. An occurrence of I{Secure} on the wire, together with the response generated by this method, might have the following appearance:: C: -Command: Secure C: -...
7.486009
8.258938
0.906413
CS = self.service.certificateStorage host = str(From.domainAddress()) p = AMP() p.wrapper = self.wrapper f = protocol.ClientCreator(reactor, lambda: p) connD = f.connectTCP(host, port) def connected(proto): dhost = From.domainAddress() ...
def _retrieveRemoteCertificate(self, From, port=port)
The entire conversation, starting with TCP handshake and ending at disconnect, to retrieve a foreign domain's certificate for the first time.
5.31052
5.325552
0.997177
if self.hostCertificate is not None: raise RuntimeError("Re-securing already secured connection.") def _cbSecure(response): if foreignCertificateAuthority is not None: self.authorized = True return True extra = {'tls_localCertificate'...
def secure(self, fromAddress, toAddress, fromCertificate, foreignCertificateAuthority=None, authorize=True)
Return a Deferred which fires True when this connection has been secured as a channel between fromAddress (locally) and toAddress (remotely). Raises an error if this is not possible.
5.192276
4.516697
1.149573
publicIP = self._determinePublicIP() A = dict(From=From, to=to, protocol=protocolName) if self.service.dispatcher is not None: # Tell them exactly where they can shove it A['udp_source'] = (publicIP, ...
def connect(self, From, to, protocolName, clientFactory, chooser)
Issue an INBOUND command, creating a virtual connection to the peer, given identifying information about the endpoint to connect to, and a protocol factory. @param clientFactory: a *Client* ProtocolFactory instance which will generate a protocol upon connect. @return: a Deferre...
6.792125
6.726706
1.009725
def cbWhoAmI(result): return result['address'] return self.callRemote(WhoAmI).addCallback(cbWhoAmI)
def whoami(self)
Return a Deferred which fires with a 2-tuple of (dotted quad ip, port number).
7.756973
5.592804
1.386956
username, domain = credentials.username.split("@") key = self.users.key(domain, username) if key is None: return defer.fail(UnauthorizedLogin()) def _cbPasswordChecked(passwordIsCorrect): if passwordIsCorrect: return username + '@' + doma...
def requestAvatarId(self, credentials)
Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user ...
4.389384
4.384438
1.001128
if existingCertificate is None: assert '@' not in subjectName, "Don't self-sign user certs!" mainDN = DistinguishedName(commonName=subjectName) mainKey = KeyPair.generate() mainCertReq = mainKey.certificateRequest(mainDN) mainCertData = mainKe...
def addPrivateCertificate(self, subjectName, existingCertificate=None)
Add a PrivateCertificate object to this store for this subjectName. If existingCertificate is None, add a new self-signed certificate.
5.383545
5.366652
1.003148
return itertools.chain( self.secureConnectionCache.cachedConnections.itervalues(), iter(self.subConnections), (self.dispatcher or ()) and self.dispatcher.iterconnections())
def iterconnections(self)
Iterator of all connections associated with this service, whether cached or not. For testing purposes only.
17.732664
13.369692
1.326333
myDomain = fromAddress.domainAddress() D = self.getSecureConnection(fromAddress, myDomain) def _secured(proto): lfm = self.localFactoriesMapping def startup(listenResult): for protocol, factory in protocolsToFactories.iteritems(): ...
def listenQ2Q(self, fromAddress, protocolsToFactories, serverDescription)
Right now this is really only useful in the client implementation, since it is transient. protocolFactoryFactory is used for persistent listeners.
4.191679
4.150091
1.010021
kp = KeyPair.generate() subject = DistinguishedName(commonName=str(fromAddress)) reqobj = kp.requestObject(subject) # Create worthless, self-signed certificate for the moment, it will be # replaced later. # attemptAddress = q2q.Q2QAddress(fromAddress.domain, ...
def requestCertificateForAddress(self, fromAddress, sharedSecret)
Connect to the authoritative server for the domain part of the given address and obtain a certificate signed by the root certificate for that domain, then store that certificate in my local certificate storage. @param fromAddress: an address that this service is authorized to use, ...
7.265366
6.996497
1.038429
listenerID = self._nextConnectionID(From, to) call = reactor.callLater(120, self.unmapListener, listenerID) expires = datetime.datetime(*time.localtime(call.getTime())[:7]) self.inboundConnections[listenerID] = ( ...
def mapListener(self, to, From, protocolName, protocolFactory, isClient=False)
Returns 2-tuple of (expiryTime, listenerID)
6.773994
5.579524
1.214081
if listenID in self.inboundConnections: # Make the connection? cwait, call = self.inboundConnections.pop(listenID) # _ConnectionWaiter instance call.cancel() return cwait
def lookupListener(self, listenID)
(internal) Retrieve a waiting connection by its connection identifier, passing in the transport to be used to connect the waiting protocol factory to.
14.563801
14.732569
0.988545
result = [] x = self.localFactoriesMapping.get((to, protocolName), ()) result.extend(x) y = self.protocolFactoryFactory(From, to, protocolName) result.extend(y) return result
def getLocalFactories(self, From, to, protocolName)
Returns a list of 2-tuples of (protocolFactory, description) to handle this from/to/protocolName @param From: @param to: @param protocolName: @return:
5.01732
5.070233
0.989564
if chooser is None: chooser = lambda x: x and [x[0]] def onSecureConnection(protocol): if fakeFromDomain: connectFromAddress = Q2QAddress( fakeFromDomain, toAddress.resource ) else: ...
def connectQ2Q(self, fromAddress, toAddress, protocolName, protocolFactory, usePrivateCertificate=None, fakeFromDomain=None, chooser=None)
Connect a named protocol factory from a resource@domain to a resource@domain. This is analagous to something like connectTCP, in that it creates a connection-oriented transport for each connection, except instead of specifying your credentials with an application-level (username, ...
3.721686
3.490084
1.06636
@wraps(func) def wrapper(self, *args, **kwargs): self.old_path = None if self.is_local: self.old_path = join(gettempdir(), self.name) if exists(self.old_path): rmtree(self.old_path) shutil.copytree(self.path, self.old_path) try: ...
def _backup_previous_version(func: Callable = None)
Private decorator to back up previous skill folder
3.47021
3.176758
1.092375
self.name = remote_entry.name self.sha = remote_entry.sha self.url = remote_entry.url self.author = remote_entry.author return self
def attach(self, remote_entry)
Attach a remote entry to a local entry
3.020952
3.046783
0.991522
# Priority goes to the user's parsers. if isinstance(input, basestring): for func in current_acl_manager.permission_set_parsers: res = func(input) if res is not None: input = res break if isinstance(input, basestring): try: ...
def parse_permission_set(input)
Lookup a permission set name in the defined permissions. Requires a Flask app context.
4.224245
4.131877
1.022355
if isinstance(perm_set, basestring): return perm == perm_set elif isinstance(perm_set, Container): return perm in perm_set elif isinstance(perm_set, Callable): return perm_set(perm) else: raise TypeError('permission set must be a string, container, or callable')
def is_permission_in_set(perm, perm_set)
Test if a permission is in the given set. :param perm: The permission object to check for. :param perm_set: The set to check in. If a ``str``, the permission is checked for equality. If a container, the permission is looked for in the set. If a function, the permission is passed to the "set".
2.636422
2.184106
1.207095
if len(raw_data)%2 != 0: raise TypeError('The given data has not a length that is a multiple of 2!') rtrnList = [] for i in range(0, len(raw_data), 2): rtrnList.append(two_bytes_to_int(raw_data[i], raw_data[i+1])) return tuple(rtrnList)
def convert_raw_data_to_universes(raw_data) -> tuple
converts the raw data to a readable universes tuple. The raw_data is scanned from index 0 and has to have 16-bit numbers with high byte first. The data is converted from the start to the beginning! :param raw_data: the raw data to convert :return: tuple full with 16-bit numbers
3.331417
2.817377
1.182453
tmpList = [] if len(universes)%512 != 0: num_of_packets = int(len(universes)/512)+1 else: # just get how long the list has to be. Just read and think about the if statement. # Should be self-explaining num_of_packets = int(len(universes)/512) ...
def make_multiple_uni_disc_packets(cid: tuple, sourceName: str, universes: list) -> List['UniverseDiscoveryPacket']
Creates a list with universe discovery packets based on the given data. It creates automatically enough packets for the given universes list. :param cid: the cid to use in all packets :param sourceName: the source name to use in all packets :param universes: the universes. Can be longer ...
4.203211
3.970938
1.058493
result = super(MultipleModelLimitOffsetPagination, self).paginate_queryset(queryset, request, view) try: if self.max_count < self.count: self.max_count = self.count except AttributeError: self.max_count = self.count try: self...
def paginate_queryset(self, queryset, request, view=None)
adds `max_count` as a running tally of the largest table size. Used for calculating next/previous links later
2.70756
2.511768
1.07795
self.count = self.max_count return OrderedDict([ ('highest_count', self.max_count), ('overall_total', self.total), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])
def format_response(self, data)
replaces the `count` (the last queryset count) with the running `max_count` variable, to ensure accurate link calculation
4.422406
3.257139
1.357758
for key in self.required_keys: if key not in query_data: raise ValidationError( 'All items in the {} querylist attribute should contain a ' '`{}` key'.format(self.__class__.__name__, key) )
def check_query_data(self, query_data)
All items in a `querylist` must at least have `queryset` key and a `serializer_class` key. Any querylist item lacking both those keys will raise a ValidationError
5.115544
3.840643
1.33195
queryset = query_data.get('queryset', []) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() # run rest_framework filters queryset = self.filter_queryset(queryset) # run custom filter...
def load_queryset(self, query_data, request, *args, **kwargs)
Fetches the queryset and runs any necessary filtering, both built-in rest_framework filters and custom filters passed into the querylist
2.597665
2.368102
1.09694
assert self.result_type is not None, ( '{} must specify a `result_type` value or overwrite the ' '`get_empty_result` method.'.format(self.__class__.__name__) ) return self.result_type()
def get_empty_results(self)
Because the base result type is different depending on the return structure (e.g. list for flat, dict for object), `get_result_type` initials the `results` variable to the proper type
4.692456
4.279572
1.096478
raise NotImplementedError( '{} must specify how to add data to the running results tally ' 'by overriding the `add_to_results` method.'.format( self.__class__.__name__ ) )
def add_to_results(self, data, label, results)
responsible for updating the running `results` variable with the data from this queryset/serializer combo
6.009713
5.844774
1.02822
super(FlatMultipleModelMixin, self).initial(request, *args, **kwargs) assert not (self.sorting_field and self.sorting_fields), \ '{} should either define ``sorting_field`` or ``sorting_fields`` property, not both.' \ .format(self.__class__.__name__) if self.sorti...
def initial(self, request, *args, **kwargs)
Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has been ran in order to make sure that view has all its properties se...
3.744466
2.983315
1.255136
for datum in data: if label is not None: datum.update({'type': label}) results.append(datum) return results
def add_to_results(self, data, label, results)
Adds the label to the results, as needed, then appends the data to the running results tab
5.070309
5.825999
0.87029
self.prepare_sorting_fields() if self._sorting_fields: results = self.sort_results(results) if request.accepted_renderer.format == 'html': # Makes the the results available to the template context by transforming to a dict results = {'data': results}...
def format_results(self, results, request)
Prepares sorting parameters, and sorts results, if(as) necessary
7.588665
6.002713
1.264206
if not path: path = [] try: if '__' in param: root, new_param = param.split('__') path.append(root) return self._sort_by(datum[root], param=new_param, path=path) else: path.append(param) ...
def _sort_by(self, datum, param, path=None)
Key function that is used for results sorting. This is passed as argument to `sorted()`
2.95106
3.012557
0.979586
if self.sorting_parameter_name in self.request.query_params: # Extract sorting parameter from query string self._sorting_fields = [ _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',') ] if self._sorting_fi...
def prepare_sorting_fields(self)
Determine sorting direction and sorting field based on request query parameters and sorting options of self
3.201954
2.980039
1.074467
if query_data.get('label', False): return query_data['label'] try: return queryset.model.__name__ except AttributeError: return query_data['queryset'].model.__name__
def get_label(self, queryset, query_data)
Gets option label for each datum. Can be used for type identification of individual serialized objects
3.041718
3.067162
0.991705
return setuptools.Extension(modpath, [modpath.replace(".", "/") + ".py"])
def _extension(modpath: str) -> setuptools.Extension
Make setuptools.Extension.
6.123916
4.772074
1.283282
try: build_ext.build_ext.build_extension(self, ext) except ( distutils.errors.CCompilerError, distutils.errors.DistutilsExecError, distutils.errors.DistutilsPlatformError, ValueError, ): raise BuildFailed()
def build_extension(self, ext)
build_extension. :raises BuildFailed: cythonize impossible
2.51076
2.340326
1.072825
# retrieve the remote environment variables for the host try: result = conn.gateway.remote_exec("import os; channel.send(os.environ.copy())") env = result.receive() except Exception: conn.logger.exception('failed to retrieve the remote environment variables') env = {} ...
def extend_env(conn, arguments)
get the remote environment's env so we can explicitly add the path without wiping out everything
3.941939
3.774886
1.044254
stop_on_error = kw.pop('stop_on_error', True) if not kw.get('env'): # get the remote environment's env so we can explicitly add # the path without wiping out everything kw = extend_env(conn, kw) command = conn.cmd(command) timeout = timeout or conn.global_timeout conn....
def run(conn, command, exit=False, timeout=None, **kw)
A real-time-logging implementation of a remote subprocess.Popen call where a command is just executed on the remote end and no other handling is done. :param conn: A connection oject :param command: The command to pass in to the remote subprocess.Popen :param exit: If this call should close the connect...
4.570287
4.66026
0.980694
command = conn.cmd(command) stop_on_error = kw.pop('stop_on_error', True) timeout = timeout or conn.global_timeout if not kw.get('env'): # get the remote environment's env so we can explicitly add # the path without wiping out everything kw = extend_env(conn, kw) conn....
def check(conn, command, exit=False, timeout=None, **kw)
Execute a remote command with ``subprocess.Popen`` but report back the results in a tuple with three items: stdout, stderr, and exit status. This helper function *does not* provide any logging as it is the caller's responsibility to do so.
5.732038
5.787426
0.99043
local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monitor) _notify_sync_ready(len(lfile_set), local_dir, remote_dir) _notify_sync_ready(len(rfile...
def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR)
Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields bef...
2.124472
2.073756
1.024456
local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, new_arrivals # where new_arrivals is possibly empty if new_ar...
def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR)
Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.
3.968117
3.490699
1.136769
remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arrivals: _notify_sync(Direction.down, new_arrivals) ...
def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR)
Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.
3.848639
3.451966
1.114912
files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir)
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1)
Sync most recent file by date, time attribues
4.995249
4.408947
1.13298
files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=local_dir)
def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1)
Sync files whose filename attribute is highest in alphanumeric order
5.815984
4.868382
1.194644
try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) os.remove(local_path) raise e
def _write_file_safely(local_path, fileinfo, response)
attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error
3.958327
4.063001
0.974237
if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files)
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None)
Sync a given list of local files to `remote_dir` dir
3.667958
3.622156
1.012645
remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, rem...
def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1)
Sync most recent file by date, time attribues
4.958626
4.699389
1.055164
remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.up, to_sync) up_by_files(to_sync[::-1], remote_dir, remote_fi...
def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1)
Sync files whose filename attribute is highest in alphanumeric order
5.557179
4.965224
1.11922
try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fileinfo.path)) upload.delete_file(fi...
def _upload_file_safely(fileinfo, remote_dir)
attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error
4.649637
4.51288
1.030304
logger = logger or basic_remote_logger() sync = _RSync(source, logger=logger) # setup_targets if not isinstance(hosts, list): hosts = [hosts] for host in hosts: conn = Connection( host, logger, sudo, ) sync.add_target(conn.ga...
def rsync(hosts, source, destination, logger=None, sudo=False)
Grabs the hosts (or single host), creates the connection object for each and set the rsync execnet engine to push the files. It assumes that all of the destinations for the different hosts is the same. This deviates from what execnet does because it has the flexibility to push to different locations.
6.979359
8.339131
0.836941
value = float(raw_value) if low < high: if value < low: return 0 elif value > high: return 1.0 elif low > high: if value > low: return 0 elif value < high: return -1.0 return (value - low) / abs(high - low)
def map_into_range(low, high, raw_value)
Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0 :param low: The value in the input range corresponding to zero. :param high: The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the...
2.419453
2.703855
0.894816
input_range = high - low corrected_low = low + input_range * dead_zone corrected_high = high - input_range * hot_zone return map_into_range(corrected_low, corrected_high, value)
def map_single_axis(low, high, dead_zone, hot_zone, value)
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively, so for example setting dead zone to 0.2 means the first 20% of the range of the axis w...
3.046376
3.165008
0.962518
if value <= centre: return map_single_axis(centre, low, dead_zone, hot_zone, value) else: return map_single_axis(centre, high, dead_zone, hot_zone, value)
def map_dual_axis(low, high, centre, dead_zone, hot_zone, value)
Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in that call based on which side of the centre value the input value falls. This is ...
2.315284
2.318483
0.99862
return self.buttons.register_button_handler(button_handler, self.buttons[button_sname])
def register_button_handler(self, button_handler, button_sname: str)
Register a handler function which will be called when a button is pressed :param button_handler: A function which will be called when any of the specified buttons are pressed. The function is called with the Button that was pressed as the sole argument. :param button_sname: ...
6.254344
5.982989
1.045354
if prefix is not None: axis = self.axes_by_code.get(prefix + str(event.code)) else: axis = self.axes_by_code.get(event.code) if axis is not None: axis.receive_device_value(event.value) else: logger.debug('Unknown axis code {} ({}),...
def axis_updated(self, event: InputEvent, prefix=None)
Called to process an absolute axis event from evdev, this is called internally by the controller implementations :internal: :param event: The evdev event to process :param prefix: If present, a named prefix that should be applied to the event code when searching for the...
3.105083
2.952375
1.051724
for axis in self.axes_by_code.values(): if isinstance(axis, CentredAxis): axis.centre = axis.value
def set_axis_centres(self, *args)
Sets the centre points for each axis to the current value for that axis. This centre value is used when computing the value for the axis and is subtracted before applying any scaling. This will only be applied to CentredAxis instances
7.420729
5.104289
1.453822
return sorted([name for name in self.axes_by_sname.keys() if name is not ''])
def names(self) -> [str]
The snames of all axis objects
10.371758
6.922167
1.49834
return (float(value) - self.min_raw_value) / self.max_raw_value
def _input_to_raw_value(self, value: int) -> float
Convert the value read from evdev to a 0.0 to 1.0 range. :internal: :param value: a value ranging from the defined minimum to the defined maximum value. :return: 0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points.
4.827992
5.713181
0.845062
return map_single_axis(self.min, self.max, self.dead_zone, self.hot_zone, self.__value)
def value(self) -> float
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of the trigger or the edge of the hot zone, if defined as other than 1.0. :return: a float va...
15.381867
9.643425
1.595063
new_value = self._input_to_raw_value(raw_value) if self.button is not None: if new_value > (self.button_trigger_value + 0.05) > self.__value: self.buttons.button_pressed(self.button.key_code) elif new_value < (self.button_trigger_value - 0.05) < self.__va...
def receive_device_value(self, raw_value: int)
Set a new value, called from within the joystick implementation class when parsing the event queue. :param raw_value: the raw value from the joystick hardware :internal:
2.70088
2.641824
1.022354
mapped_value = map_dual_axis(self.min, self.max, self.centre, self.dead_zone, self.hot_zone, self.__value) if self.invert: return -mapped_value else: return mapped_value
def value(self) -> float
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will scale from 0.0 at the edge of the dead-zone to 1.0 (positive) or -1.0 (negative) at the extreme position of the controller or the edge of the hot zone, if defined as other than 1.0. The axis will auto...
6.533076
4.872062
1.340926
new_value = self._input_to_raw_value(raw_value) self.__value = new_value if new_value > self.max: self.max = new_value elif new_value < self.min: self.min = new_value
def receive_device_value(self, raw_value: int)
Set a new value, called from within the joystick implementation class when parsing the event queue. :param raw_value: the raw value from the joystick hardware :internal:
3.186219
2.729912
1.167151
if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: for handler in state.button_handlers: handler(state.button) state.is_pre...
def button_pressed(self, key_code, prefix=None)
Called from the controller classes to update the state of this button manager when a button is pressed. :internal: :param key_code: The code specified when populating Button instances :param prefix: Applied to key code if present
2.71767
2.929399
0.927723
if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: state.is_pressed = False state.last_pressed = None
def button_released(self, key_code, prefix=None)
Called from the controller classes to update the state of this button manager when a button is released. :internal: :param key_code: The code specified when populating Button instance :param prefix: Applied to key code if present
2.414443
2.667208
0.905232
pressed = [] for button, state in self.buttons.items(): if state.was_pressed_since_last_check: pressed.append(button) state.was_pressed_since_last_check = False self.__presses = ButtonPresses(pressed) return self.__presses
def check_presses(self)
Return the set of Buttons which have been pressed since this call was last made, clearing it as we do. :return: A ButtonPresses instance which contains buttons which were pressed since this call was last made.
3.421345
3.108425
1.100668
state = self.buttons_by_sname.get(sname) if state is not None: if state.is_pressed and state.last_pressed is not None: return time() - state.last_pressed return None
def held(self, sname)
Determines whether a button is currently held, identifying it by standard name :param sname: The standard name of the button :return: None if the button is not held down, or is not available, otherwise the number of seconds as a floating point value since it was pres...
4.032008
4.076389
0.989113
if not isinstance(buttons, list): buttons = [buttons] for button in buttons: state = self.buttons.get(button) if state is not None: state.button_handlers.append(button_handler) def remove(): for button_to_remove in buttons...
def register_button_handler(self, button_handler, buttons)
Register a handler function which will be called when a button is pressed :param button_handler: A function which will be called when any of the specified buttons are pressed. The function is called with the Button that was pressed as the sole argument. :param [Button] buttons: ...
2.112928
2.32899
0.907229
return self.__func
def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]
Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]]
36.854439
70.645851
0.521679
raise NotImplementedError()
def _get_function_wrapper( self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., typing.Any]
Here should be constructed and returned real decorator. :param func: Wrapped function :type func: typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]] :rtype: typing.Callable
216.747314
626.357849
0.346044
@functools.wraps(target) def wrapper(*args, **kwargs): # type: (typing.Any, typing.Any) -> typing.Any result = target(*args, **kwargs) if asyncio.iscoroutine(result): loop = asyncio.new_event_loop() result = loop.run_until_c...
def _await_if_required( target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]] ) -> typing.Callable[..., typing.Any]
Await result if coroutine was returned.
2.099133
2.066546
1.015769
if device.uniq: return device.uniq elif device.phys: return device.phys.split('/')[0] return '{}-{}-{}-{}'.format(device.info.vendor, device.info.product, device.info.version, device.path)
def unique_name(device: InputDevice) -> str
Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and finally a concatenation of vendor, product, version and filename. :param device: An InputDevice instance to query :return: A string containing as unique as possible a name for the physical e...
4.303463
3.388589
1.269987
requirements = list(requirements) if requirements is None or len(requirements) == 0: requirements = [ControllerRequirement()] def pop_controller(r: ControllerRequirement, discoveries: [ControllerDiscovery]) -> ControllerDiscovery: for index, d in enumerate(discoveries): ...
def find_matching_controllers(*requirements, **kwargs) -> [ControllerDiscovery]
Find a sequence of controllers which match the supplied requirements, or raise an error if no such controllers exist. :param requirements: Zero or more ControllerRequirement instances defining the requirements for controllers. If no item is passed it will be treated as a single requirement with...
3.801387
3.850495
0.987246
def get_controller_classes() -> [{}]: for controller_class in Controller.__subclasses__(): for vendor_id, product_id in controller_class.registration_ids(): yield {'constructor': controller_class, 'vendor_id': vendor_id, ...
def find_all_controllers(**kwargs) -> [ControllerDiscovery]
:return: A list of :class:`~approxeng.input.controllers.ControllerDiscovery` instances corresponding to controllers attached to this host, ordered by the ordering on ControllerDiscovery. Any controllers found will be constructed with kwargs passed to their constructor function, particularly usef...
2.98504
2.948416
1.012422
def device_verbose_info(device: InputDevice) -> {}: def axis_name(axis_code): try: return ecodes.ABS[axis_code] except KeyError: return 'EXTENDED_CODE_{}'.format(axis_code) def rel_axis_name(axis_code): try: ...
def print_devices()
Simple test function which prints out all devices found by evdev
2.557276
2.488302
1.027719
_check_import() pp = pprint.PrettyPrinter(indent=2) for discovery in find_all_controllers(): pp.pprint(discovery.controller)
def print_controllers()
Pretty-print all controllers found
7.686213
7.0322
1.093003
if self.require_class is not None and not isinstance(discovery.controller, self.require_class): return False if self.snames is not None: all_controls = discovery.controller.buttons.names + discovery.controller.axes.names for sname in self.snames: ...
def accept(self, discovery: ControllerDiscovery)
Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise
3.65129
3.263668
1.118769
pmap = {Config.mastercode: mastercode} pmap.update(param_map) processed_params = dict(_process_params(pmap)) return processed_params
def config(param_map, mastercode=DEFAULT_MASTERCODE)
Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi
5.018221
4.925375
1.018851
prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
def post(param_map, url=URL)
Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint
7.292999
7.597486
0.959923
val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
def _validate_timeout(seconds: float)
Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout
4.334248
2.681514
1.616344
date_els, time_els = _split_datetime(datetime_input) date_vals = _parse_date(date_els) time_vals = _parse_time(time_els) vals = tuple(date_vals) + tuple(time_vals) return arrow.get(*vals)
def parse_datetime(datetime_input)
The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.
2.850687
2.664388
1.069922
if 1 > led_number > 4: return write_led_value(hw_id=self.device_unique_name, led_name='sony{}'.format(led_number), value=led_value)
def set_led(self, led_number, led_value)
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can be either on or off. :param led_number: Integer between 1 and 4 :param led_value: Value, set to 0 to turn the LED off, 1 to turn it on
8.597839
10.392239
0.827333
left = throttle + yaw right = throttle - yaw scale = float(max_power) / max(1, abs(left), abs(right)) return int(left * scale), int(right * scale)
def mixer(yaw, throttle, max_power=100)
Mix a pair of joystick axes, returning a pair of wheel speeds. This is where the mapping from joystick positions to wheel powers is defined, so any changes to how the robot drives should be made here, everything else is really just plumbing. :param yaw: Yaw axis value, ranges from -1.0 to 1.0 ...
3.499403
3.80088
0.920682
if sudo: if not isinstance(command, list): command = [command] return ['sudo'] + [cmd for cmd in command] return command
def admin_command(sudo, command)
If sudo is needed, make sure the command is prepended correctly, otherwise return the command as it came. :param sudo: A boolean representing the intention of having a sudo command (or not) :param command: A list of the actual command to execute with Popen.
3.53148
4.435579
0.796171
def find_device_hardware_id(uevent_file_path): hid_uniq = None phys = None for line in open(uevent_file_path, 'r').read().split('\n'): parts = line.split('=') if len(parts) == 2: name, value = parts value = value.replace('"', '') ...
def scan_system()
Scans /sys/class/leds looking for entries, then examining their .../device/uevent file to obtain unique hardware IDs corresponding to the associated hardware. This then allows us to associate InputDevice based controllers with sets of zero or more LEDs. The result is a dict from hardware address to a dict of na...
2.300928
2.028729
1.134172
discoveries = list(discoveries) class SelectThread(Thread): def __init__(self): Thread.__init__(self, name='evdev select thread') self.daemon = True self.running = True self.device_to_controller_discovery = {} for discovery in discoveri...
def bind_controllers(*discoveries, print_events=False)
Bind a controller or controllers to a set of evdev InputDevice instances, starting a thread to keep those controllers in sync with the state of the hardware. :param discoveries: ControllerDiscovery instances specifying the controllers and their associated input devices :param print_events: ...
2.777576
2.73402
1.015931
dt = arrow.get(mtime) dt = dt.to("local") date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day secs = dt.second + dt.microsecond / 10**6 time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2) return (date_val << 16) | time_val
def _encode_time(mtime: float)
Encode a mtime float as a 32-bit FAT time
2.804633
2.505532
1.119376
def threadpooled( func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]], *, loop_getter: None = None, loop_getter_need_context: bool = False, ) -> typing.Callable[..., "concurrent.futures.Future[typing.Any]"]
Overload: function callable, no loop getter.
155,483.25
5,885.395508
26.418488
def threadpooled( func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]], *, loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop], loop_getter_need_context: bool = False, ) -> typing.Callable[..., "asyncio.Task[typing.Any]"]
Overload: function callable, loop getter available.
68,983.359375
6,134.661621
11.244852
def threadpooled( func: None = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None, loop_getter_need_context: bool = False, ) -> ThreadPooled
Overload: No function.
624,769.1875
10,923.291992
57.196053
if func is None: return ThreadPooled(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context) return ThreadPooled( # type: ignore func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context )(func)
def threadpooled( # noqa: F811 func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None, loop_getter_need_context: bool = False, ) -...
Post function to ThreadPoolExecutor. :param func: function to wrap :type func: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] :param loop_getter: Method to get event loop, if wrap in asyncio task :type loop_getter: typing.Union[ None, ...
1.740466
1.915219
0.908756