code
stringlengths
1
18.2k
def validate(self, request, data): """ Validate response from OpenID server. Set identity in case of successfull validation. """ client = consumer.Consumer(request.session, None) try: resp = client.complete(data, request.session['openid_return_to']) except KeyError: messages.error(request, lang.INVALID_RESPONSE_FROM_OP...
def use(self, plugin, arguments={}): """Add plugin to use during compilation. plugin: Plugin to include. arguments: Dictionary of arguments to pass to the import. """ self.plugins[plugin] = dict(arguments) return self.plugins
def compile(self, source, options={}): """Compile stylus into css source: A string containing the stylus code options: A dictionary of arguments to pass to the compiler Returns a string of css resulting from the compilation """ options = dict(options) if "paths" in options: options["paths"] += self.paths else: options[...
def context(self): "Internal property that returns the stylus compiler" if self._context is None: with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file: compiler_source = compiler_file.read() self._context = self.backend.compile(compiler_source) return self._context
def backend(self): "Internal property that returns the Node script running harness" if self._backend is None: with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file: runner_source = runner_file.read() self._backend = execjs.ExternalRuntime(name="Node.js (V8)", command=["node"], runner...
def request_generic(self, act, coro, perform, complete): """ Performs an overlapped request (via `perform` callable) and saves the token and the (`overlapped`, `perform`, `complete`) trio. """ overlapped = OVERLAPPED() overlapped.object = act self.add_token(act, coro, (overlapped, perform, complete)) rc, nbytes = perfo...
def run(self, timeout = 0): """ Calls GetQueuedCompletionStatus and handles completion via process_op. """ # same resolution as epoll ptimeout = int( timeout.days * 86400000 + timeout.microseconds / 1000 + timeout.seconds * 1000 if timeout else (self.m_resolution if timeout is None else 0) ) if self.tokens: scheduler =...
# HANDLE CompletionPort byref(nbytes), # LPDWORD lpNumberOfBytes byref(completion_key), # PULONG_PTR lpCompletionKey byref(poverlapped), 0 if urgent else ptimeout ) overlap = poverlapped and poverlapped.contents nbytes = nbytes.value except RuntimeError, e: import warnings warnings.warn("RuntimeError(%s) on GetQueuedCo...
& priority.OP: # imediately run the asociated coroutine step op, coro = scheduler.process_op( coro.run_op(op, scheduler), coro ) if coro: #TODO, what "op and " if op and (op.prio & priority.CORO): scheduler.active.appendleft( (op, coro) ) else: scheduler.active.append( (op, coro) ) if overlap.object: assert overlap.obj...
def header(self): ''' This returns the first header in the data file ''' if self._header is None: self._header = self._read_half_frame_header(self.data) return self._header
def headers(self): ''' This returns all headers in the data file. There should be one for each half_frame in the file (typically 129). ''' first_header = self.header() single_compamp_data = np.frombuffer(self.data, dtype=np.int8)\ .reshape((first_header['number_of_half_frames'], first_header['half_frame_bytes'])) retur...
def _packed_data(self): ''' Returns the bit-packed data extracted from the data file. This is not so useful to analyze. Use the complex_data method instead. ''' header = self.header() packed_data = np.frombuffer(self.data, dtype=np.int8)\ .reshape((header['number_of_half_frames'], header['half_frame_bytes'])) # create ...
def complex_data(self): ''' This will cast each byte to an int8 and interpret each byte as 4 bits real values and 4 bits imag values (RRRRIIII). The data are then used to create a 3D numpy array of dtype=complex, which is returned. The shape of the numpy array is N half frames, M subbands, K data points per half frame,...
when that value is represented as an 8-bit signed integer. packed_data = self._packed_data() header = self.header() real_val = np.bitwise_and(packed_data, 0xf0).astype(np.int8) # coef's are: RRRRIIII (4 bits real, imag_val = np.left_shift(np.bitwise_and(packed_data, 0x0f), 4).astype(np.int8) # 4 bits imaginary in 2's c...
def complex_data(self): ''' This unpacks the data into a time-series data, of complex values. Also, any DC offset from the time-series is removed. This is a 1D complex-valued numpy array. ''' cp = np.frombuffer(self.data, dtype='i1').astype(np.float32).view(np.complex64) cp = cp - cp.mean() return cp
def _spec_fft(self, complex_data): ''' Calculates the DFT of the complex_data along axis = 1. This assumes complex_data is a 2D array. This uses numpy and the code is straight forward np.fft.fftshift( np.fft.fft(complex_data), 1) Note that we automatically shift the FFT frequency bins so that along the frequency axis, ...
def get_spectrogram(self): ''' Transforms the input simulated data and computes a standard-sized spectrogram. If self.sigProc function is not None, the 2D complex-valued time-series data will be processed with that function before the FFT and spectrogram are calculated. ''' return self._spec_power(self._spec_fft( self....
def riak_http_search_query(self, solr_core, solr_params, count_deleted=False): """ This method is for advanced SOLR queries. Riak HTTP search query endpoint, sends solr_params and query string as a proxy and returns solr reponse. Args: solr_core (str): solr core on which query will be executed solr_params (str): solr s...
def distinct_values_of(self, field, count_deleted=False): """ Uses riak http search query endpoint for advanced SOLR queries. Args: field (str): facet field count_deleted (bool): ignore deleted or not Returns: (dict): pairs of field values and number of counts """ solr_params = "facet=true&facet.field=%s&rows=0" % fiel...
def _clear(self, wait): """ clear outs the all content of current bucket only for development purposes """ i = 0 t1 = time.time() for k in self.bucket.get_keys(): i += 1 self.bucket.get(k).delete() print("\nDELETION TOOK: %s" % round(time.time() - t1, 2)) if wait: while self._model_class.objects.count(): time.sleep(0.3...
def get_from_solr(clone, number, row_size): """ If not start parameter is given, with the given number(0,1,2..) multiplies default row size and determines start parameter. Takes results from solr according to this parameter. For example, if number is 2 and default row size is 1000, takes results from solr between 2000 ...
riak_multi_get method input list. Example return = (0, [('models','personel','McAPchPZzB6RVJ8QI2XSVQk4mUR'), ('models','personel','XyZZrsadVJ8QI2XSVQk4mUR'), ('models','personel','SkFl3RPZzB6RVJ8QI2XSVQk4mUR'), ('models','personel','PxCdytPZzB6RVJ8QI2XSVQk4mUR')]) """ start = number * clone._cfg['row_size'] + clone._cf...
def riak_multi_get(self, key_list_tuple): """ Sends given tuples of list to multiget method and took riak objs' keys and data. For each multiget call, separate pools are used and after execution, pools are stopped. Args: key_list_tuple(list of tuples): [('bucket_type','bucket','riak_key')] Example: [('models','personel...
def _set_bucket(self, type, name): """ prepares bucket, sets index name :param str type: bucket type :param str name: bucket name :return: """ if type: self._cfg['bucket_type'] = type if name: self._cfg['bucket_name'] = name self.bucket = self._client.bucket_type(self._cfg['bucket_type'] ).bucket(self._cfg['bucket_name...
def _write_version(self, data, model): """ Writes a copy of the objects current state to write-once mirror bucket. Args: data (dict): Model instance's all data for versioning. model (instance): Model instance. Returns: Key of version record. key (str): Version_bucket key. """ vdata = {'data': data, 'key': model.key, 'm...
def _write_log(self, version_key, meta_data, index_fields): """ Creates a log entry for current object, Args: version_key(str): Version_bucket key from _write_version(). meta_data (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for second...
def save_model(self, model, meta_data=None, index_fields=None): """ model (instance): Model instance. meta (dict): JSON serializable meta data for logging of save operation. {'lorem': 'ipsum', 'dolar': 5} index_fields (list): Tuple list for indexing keys in riak (with 'bin' or 'int'). [('lorem','bin'),('dolar','int')] ...
else: sys.PYOKO_LOGS[self._model_class.__name__].append(obj.key) sys.PYOKO_STAT_COUNTER['update'] += 1 # sys._debug_db_queries.append({ # 'TIMESTAMP': t1, # 'KEY': obj.key, # 'BUCKET': self.index_name, # 'SAVE_IS_NEW': new_obj, # 'SERIALIZATION_TIME': round(t2 - t1, 5), # 'TIME': round(time.time() - t2, 5) # }) return ...
def set_to_cache(vk): """ Args: vk (tuple): obj data (dict), obj key(str) Return: tuple: value (dict), key (string) """ v, k = vk try: cache.set(k, json.dumps(v), settings.CACHE_EXPIRE_DURATION) except Exception as e: pass # todo should add log.error() return v, k
def get_from_cache(key): """ Args: key (str): Return: (dict): from json string """ try: value = cache.get(key) return json.loads(value), key if value else None except Exception as e: # todo should add log.error() return None
def _get_from_riak(self, key): """ Args: key (str): riak key Returns: (tuple): riak obj json data and riak key """ obj = self.bucket.get(key) if obj.exists: return obj.data, obj.key raise ObjectDoesNotExist("%s %s" % (key, self.compiled_query))
def count(self): """Counts the number of results that could be accessed with the current parameters. :return: number of objects matches to the query :rtype: int """ # Save the existing rows and start parameters to see how many results were actually expected _rows = self._solr_params.get('rows', None) _start = self._sol...
specified, then all results are accessible # (minus the ones skipped with 'start') if _rows is None: return number # If 'rows' is specified, then this many results at most will be accessible. If we have # more than this many results found, then we can say that this many results are # accessible. If there are less resul...
def search_on(self, *fields, **query): """ Search for query on given fields. Query modifier can be one of these: * exact * contains * startswith * endswith * range * lte * gte Args: \*fields (str): Field list to be searched on \*\*query: Search query. While it's implemented as \*\*kwargs we only support one (first) key...
def order_by(self, *args): """ Applies query ordering. New parameters are appended to current ones, overwriting existing ones. Args: **args: Order by fields names. Defaults to ascending, prepend with hypen (-) for desecending ordering. """ if self._solr_locked: raise Exception("Query already executed, no changes can be...
def set_params(self, **params): """ add/update solr query parameters """ if self._solr_locked: raise Exception("Query already executed, no changes can be made." "%s %s" % (self._solr_query, self._solr_params) ) self._solr_params.update(params)
def _escape_query(self, query, escaped=False): """ Escapes query if it's not already escaped. Args: query: Query value. escaped (bool): expresses if query already escaped or not. Returns: Escaped query value. """ if escaped: return query query = six.text_type(query) for e in ['+', '-', '&&', '||', '!', '(', ')', '{', '...
def _parse_query_modifier(self, modifier, qval, is_escaped): """ Parses query_value according to query_type Args: modifier (str): Type of query. Exact, contains, lte etc. qval: Value partition of the query. Returns: Parsed query_value. """ if modifier == 'range': if not qval[0]: start = '*' elif isinstance(qval[0], dat...
qval elif modifier == 'startswith': qval = "%s*" % qval elif modifier == 'endswith': qval = "%s*" % qval elif modifier == 'lte': qval = '[* TO %s]' % qval elif modifier == 'gte': qval = '[%s TO *]' % qval elif modifier == 'lt': if isinstance(qval, int): qval -= 1 qval = '[* TO %s]' % qval elif modifier == 'gt': if isin...
def _parse_query_key(self, key, val, is_escaped): """ Strips query modifier from key and call's the appropriate value modifier. Args: key (str): Query key val: Query value Returns: Parsed query key and value. """ if key.endswith('__contains'): key = key[:-10] val = self._parse_query_modifier('contains', val, is_escaped...
elif key != 'NOKEY' and not is_escaped: val = self._escape_query(val) return key, val
def _compile_query(self): """ Builds SOLR query and stores it into self.compiled_query """ # https://wiki.apache.org/solr/SolrQuerySyntax # http://lucene.apache.org/core/2_9_4/queryparsersyntax.html query = [] # filtered_query = self._model_class.row_level_access(self._current_context, self) # if filtered_query is not ...
then join them with "OR" after escaping & parsing if key == 'OR_QRY': key = 'NOKEY' val = ' OR '.join( ['%s:%s' % self._parse_query_key(*self._process_query_val(k, v, is_escaped)) for k, v in val.items()]) is_escaped = True # __in query is same as OR_QRY but key stays same for all values elif key.endswith('__in'): if n...
out records with deleted flag if key == 'deleted': self.want_deleted = True # convert two underscores to dot notation key = key.replace('__', '.') # NOKEY means we already combined key partition in to "val" if key == 'NOKEY': query.append("(%s)" % val) else: query.append("%s:%s" % (key, val)) # need to add *:* for nega...
not self.want_deleted: if joined_query: joined_query = "(%s) AND -deleted:True" % joined_query else: joined_query = '-deleted:True' elif not joined_query: joined_query = '*:*' self.compiled_query = joined_query
def _sort_to_str(self): """ Before exec query, this method transforms sort dict string from {"name": "asc", "timestamp":"desc"} to "name asc, timestamp desc" """ params_list = [] timestamp = "" for k, v in self._solr_params['sort'].items(): if k != "timestamp": params_list.append(" ".join([k, v])) else: timestamp = v p...
def _process_params(self): """ Adds default row size if it's not given in the query. Converts param values into unicode strings. Returns: Processed self._solr_params dict. """ # transform sort dict into str self._sort_to_str() if 'rows' not in self._solr_params: self._solr_params['rows'] = self._cfg['row_size'] for key...
def _exec_query(self): """ Executes solr query if it hasn't already executed. Returns: Self. """ if not self._solr_locked: if not self.compiled_query: self._compile_query() try: solr_params = self._process_params() if settings.DEBUG: t1 = time.time() self._solr_cache = self.bucket.search(self.compiled_query, self.index...
def parse_arguments(args=sys.argv[1:]): """Parse arguments of script.""" cmd_description = "Download tracklistings for BBC radio shows.\n\n" \ "Saves to a text file, tags audio file or does both.\n" \ "To select output file, filename " \ "must both be specified.\n" \ "If directory is not specified, directory is assumed...
"text: write tracklisting to text file (default)\n" \ "both: tag audio file and write to text file" parser.add_argument('action', choices=('tag', 'text', 'both'), default='text', help=action_help) parser.add_argument('pid', help="BBC programme id, e.g. b03fnc82") parser.add_argument('--directory', help="output director...
def main(): """Check arguments are retrieved.""" args = parse_arguments() print(args) print("action" + args.action) print("pid" + args.pid) print("directory" + args.directory) print("fileprefix" + args.fileprefix)
def begin(self, request, data): """ Try to get Request Token from OAuth Provider and redirect user to provider's site for approval. """ request = self.get_request( http_url = self.REQUEST_TOKEN_URL, parameters = dict(oauth_callback = self.get_callback(request))) content = self.load_request(request) if not content: retu...
def run(self, *args, **kwargs): """This runs in a greenlet""" return_value = self.coro(*args, **kwargs) # i don't like this but greenlets are so dodgy i have no other choice raise StopIteration(return_value)
def run_op(self, op, sched): """ Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever the function returned. * if StopIteration is raised, set STATE...
self._state_names[self.state], self._state_names[self.STATE_COMPLETED] ) coroutines.ident = self try: if self.state == self.STATE_RUNNING: if self.debug: traceback.print_stack(self.coro.gr_frame) if isinstance(op, CoroutineException): rop = self.coro.throw(*op.args) else: rop = self.coro.switch(op and op.finalize(sched...
def me(cls): """ Returns information about the currently authenticated user. :return: :rtype: User """ return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decode( cls.element_from_string( cls._get_request(endpoint=cls.ENDPOINT + '/me').text ) )
def ckm_standard(t12, t13, t23, delta): r"""CKM matrix in the standard parametrization and standard phase convention. Parameters ---------- - `t12`: CKM angle $\theta_{12}$ in radians - `t13`: CKM angle $\theta_{13}$ in radians - `t23`: CKM angle $\theta_{23}$ in radians - `delta`: CKM phase $\delta=\gamma$ in radians ...
def ckm_wolfenstein(laC, A, rhobar, etabar): r"""CKM matrix in the Wolfenstein parametrization and standard phase convention. This function does not rely on an expansion in the Cabibbo angle but defines, to all orders in $\lambda$, - $\lambda = \sin\theta_{12}$ - $A\lambda^2 = \sin\theta_{23}$ - $A\lambda^3(\rho-i \eta...
- A**2*laC**4) - A**2*laC**6*((1j)*eta + rho), A*laC**2*sqrt(1 - A**2*laC**6*((-1j)*eta + rho)*((1j)*eta + rho))], [A*laC**3 - A*laC**3*sqrt(1 - laC**2)*sqrt(1 - A**2*laC**4)*((1j)*eta + rho), -(A*laC**2*sqrt(1 - laC**2)) - A*laC**4*sqrt(1 - A**2*laC**4)*((1j)*eta + rho), sqrt(1 - A**2*laC**4)*sqrt(1 - A**2*laC**6*((-1...
def ckm_tree(Vus, Vub, Vcb, gamma): r"""CKM matrix in the tree parametrization and standard phase convention. In this parametrization, the parameters are directly measured from tree-level $B$ decays. It is thus particularly suited for new physics analyses because the tree-level decays should be dominated by the Standar...
(Vub*exp(1j*gamma)*Vcb*sqrt(1 - Vus**2/(1 - Vub**2)))/sqrt(1 - Vub**2), -((Vub*exp(1j*gamma)*Vcb*Vus)/(1 - Vub**2)) + sqrt(1 - Vcb**2/(1 - Vub**2))*sqrt(1 - Vus**2/(1 - Vub**2)), Vcb], [(Vcb*Vus)/(1 - Vub**2) - Vub*exp(1j*gamma)*sqrt(1 - Vcb**2/(1 - Vub**2))*sqrt(1 - Vus**2/(1 - Vub**2)), -((Vub*exp(1j*gamma)*sqrt(1 - ...
def debug(trace=True, backtrace=1, other=None, output=sys.stderr): """A decorator for debugging purposes. Shows the call arguments, result and instructions as they are runned.""" from pprint import pprint import traceback def debugdeco(func): def tracer(frame, event, arg): print>>output, '--- Tracer: %s, %r' % (event, ...
and ret or "ARG%s"%a.index(ret) ret ) return ret return wrapped return debugdeco
def bind_context(context_filename): """ loads context from file and binds to it :param: context_filename absolute path of the context file called by featuredjango.startup.select_product prior to selecting the individual features """ global PRODUCT_CONTEXT if PRODUCT_CONTEXT is None: with open(context_filename) as conte...
def get_chromosome_priority(chrom, chrom_dict={}): """ Return the chromosome priority Arguments: chrom (str): The cromosome name from the vcf chrom_dict (dict): A map of chromosome names and theis priority Return: priority (str): The priority for this chromosom """ priority = 0 chrom = str(chrom).lstrip('chr') if chrom...
def sort_variants(vcf_handle): """Sort the variants of a vcf file Args: vcf_handle mode (str): position or rank score Returns: sorted_variants (Iterable): An iterable with sorted variants """ logger.debug("Creating temp file") temp_file = NamedTemporaryFile(delete=False) temp_file.close() logger.debug("Opening temp fil...
def sort_variant_file(infile): """ Sort a modified variant file. Sorting is based on the first column and the POS. Uses unix sort to sort the variants and overwrites the infile. Args: infile : A string that is the path to a file mode : 'chromosome' or 'rank' outfile : The path to an outfile where the variants should be...
sorted since genmod can not find"\ "unix sort") raise e logger.info("Sorting done. Time to sort: {0}".format(datetime.now()-sort_start)) return
def include_feed(feed_url, *args): """ Parse an RSS or Atom feed and render a given number of its items into HTML. It is **highly** recommended that you use `Django's template fragment caching`_ to cache the output of this tag for a reasonable amount of time (e.g., one hour); polling a feed too often is impolite, waste...
of dictionaries representing feed items, each with 'title', 'summary', 'link' and 'date' members. ``feed`` The feed itself, for pulling out arbitrary attributes. Requires the Universal Feed Parser, which can be obtained at http://feedparser.org/. See `its documentation`_ for details of the parsed feed object. .. _its d...
template_name, { 'items': items, 'feed': feed }
def make_app(global_conf, full_stack=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether or not this application provides a full WSGI stack (by default, me...
exceptions #~ app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 500]) # Establish the Registry f...
def connectionMade(self): """Keep a reference to the protocol on the factory, and uses the factory's store to find multiplexed connection factories. Unfortunately, we can't add the protocol by TLS certificate fingerprint, because the TLS handshake won't have completed yet, so ``self.transport.getPeerCertificate()`` is ...
def connectionLost(self, reason): """Lose the reference to the protocol on the factory. """ self.factory.protocols.remove(self) super(AMP, self).connectionLost(reason)
def do_map(func_name, *sequence): """ Return a list of the results of applying the function to the items of the argument sequence(s). Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module If more than one sequence is given, the function is called with an argument list c...
False), sequence)
def do_reduce(func_name, *sequence): """ Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. Functions may be registered with ``native_tags`` or can be ``builtins`` or from the ``operator`` module Syntax:: {% reduce [function] [s...
def _write_field(self, value): """ Write a single field to the destination file. :param T value: The value of the field. """ class_name = str(value.__class__) if class_name not in self.handlers: raise ValueError('No handler has been registered for class: {0!s}'.format(class_name)) handler = self.handlers[class_name] ha...
def list_notes(self, page=0, since=None): """ Get the notes of current object :param page: the page starting at 0 :type since: int :param since: get all notes since a datetime :type since: datetime.datetime :return: the notes :rtype: list """ from highton.models.note import Note params = {'n': int(page) * self.NOTES_OF...
def _login(session): """Login.""" _LOGGER.info("logging in (no valid cookie found)") session.cookies.clear() resp = session.post(SSO_URL, { 'USER': session.auth.username, 'PASSWORD': session.auth.password, 'TARGET': TARGET_URL }) parsed = BeautifulSoup(resp.text, HTML_PARSER) relay_state = parsed.find('input', {'name':...
def authenticated(function): """Re-authenticate if session expired.""" def wrapped(*args): """Wrap function.""" try: return function(*args) except MoparError: _LOGGER.info("attempted to access page before login") _login(args[0]) return function(*args) return wrapped
def token(function): """Attach a CSRF token for POST requests.""" def wrapped(session, *args): """Wrap function.""" resp = session.get(TOKEN_URL).json() session.headers.update({'mopar-csrf-salt': resp['token']}) return function(session, *args) return wrapped
def get_profile(session): """Get complete profile.""" try: profile = session.get(PROFILE_URL).json() if 'errorCode' in profile and profile['errorCode'] == '403': raise MoparError("not logged in") return profile except JSONDecodeError: raise MoparError("not logged in")
def get_report(session, vehicle_index): """Get vehicle health report summary.""" vhr = get_vehicle_health_report(session, vehicle_index) if 'reportCard' not in vhr: raise MoparError("no vhr found") return _traverse_report(vhr['reportCard'])
def get_vehicle_health_report(session, vehicle_index): """Get complete vehicle health report.""" profile = get_profile(session) _validate_vehicle(vehicle_index, profile) return session.get(VHR_URL, params={ 'uuid': profile['vehicles'][vehicle_index]['uuid'] }).json()
def _traverse_report(data): """Recursively traverse vehicle health report.""" if 'items' not in data: return {} out = {} for item in data['items']: skip = (item['severity'] == 'NonDisplay' or item['itemKey'] == 'categoryDesc' or item['value'] in [None, 'Null', 'N/A', 'NULL']) if skip: continue value = 'Ok' if item['val...
def get_tow_guide(session, vehicle_index): """Get tow guide information.""" profile = get_profile(session) _validate_vehicle(vehicle_index, profile) return session.post(TOW_URL, { 'vin': profile['vehicles'][vehicle_index]['vin'] }).json()
def _get_model(vehicle): """Clean the model field. Best guess.""" model = vehicle['model'] model = model.replace(vehicle['year'], '') model = model.replace(vehicle['make'], '') return model.strip().split(' ')[0]
def get_summary(session): """Get vehicle summary.""" profile = get_profile(session) return { 'user': { 'email': profile['userProfile']['eMail'], 'name': '{} {}'.format(profile['userProfile']['firstName'], profile['userProfile']['lastName']) }, 'vehicles': [ { 'vin': vehicle['vin'], 'year': vehicle['year'], 'make': vehi...
def _remote_status(session, service_id, uuid, url, interval=3): """Poll for remote command status.""" _LOGGER.info('polling for status') resp = session.get(url, params={ 'remoteServiceRequestID':service_id, 'uuid':uuid }).json() if resp['status'] == 'SUCCESS': return 'completed' time.sleep(interval) return _remote_stat...
def remote_command(session, command, vehicle_index, poll=True): """Send a remote command.""" if command not in SUPPORTED_COMMANDS: raise MoparError("unsupported command: " + command) profile = get_profile(session) _validate_vehicle(vehicle_index, profile) if command in [COMMAND_LOCK, COMMAND_UNLOCK]: url = REMOTE_LOCK_...
def get_session(username, password, pin, cookie_path=COOKIE_PATH): """Get a new session.""" class MoparAuth(AuthBase): # pylint: disable=too-few-public-methods """Authentication wrapper.""" def __init__(self, username, password, pin, cookie_path): """Init.""" self.username = username self.password = password self.pin =...
def get_usage_from_mdoc(self): """ get_usage_from_mdoc """ usage = self.m_doc.strip().split("Usage:") if len(usage) > 1: usage = "\033[34mUsage:\033[34m" + usage[1] return "\n".join(usage.strip().split("\n")[:2]) + "\033[0m"
def print_commandless_help(self): """ print_commandless_help """ doc_help = self.m_doc.strip().split("\n") if len(doc_help) > 0: print("\033[33m--\033[0m") print("\033[34m" + doc_help[0] + "\033[0m") asp = "author :" doc_help_rest = "\n".join(doc_help[1:]) if asp in doc_help_rest: doc_help_rest = doc_help_rest.split("a...
def get_command_path(self): """ get_command_path """ name = "" if self.m_parents is not None: for parent in self.m_parents: name += parent.snake_case_class_name() name += " " name += self.snake_case_class_name() return name
def for_print(self): """ for_print """ s = "\033[34m" + self.get_object_info() + "\033[0m" s += "\n" s += self.as_string() return s
def get_subclass(self): """ get_subclass """ strbldr = """ class IArguments(Arguments): \"\"\" IArguments \"\"\" def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yamlfile=None, parse_arguments=True, persistoption=False, alwaysfullhelp=False, version=None, parent=None): \"\"\" @type doc: st...
def write_members(self): """ write_members """ s = "" objattributes = list(self.m_reprdict["positional"].keys()) objattributes.extend(list(self.m_reprdict["options"].keys())) objattributes.sort() for objattr in objattributes: s += 8 * " " + "self." + objattr + "=" if objattr in self.m_reprdict["positional"]: td = self....
def get_object_info(self): """ Returns object info in following form <module.class object at address> """ objectinfo = str(self.__class__).replace(">", "") objectinfo = objectinfo.replace("class ", "") objectinfo = objectinfo.replace("'", "") objectinfo += " object at 0x%x>" % id(self) return objectinfo