code stringlengths 1 18.2k |
|---|
def simhash(self, content): """ Select policies for simhash on the different types of content. """ if content is None: self.hash = -1 return if isinstance(content, str): features = self.tokenizer_func(content, self.keyword_weight_pari) self.hash = self.build_from_features(features) elif isinstance(content, collections.... |
def build_from_features(self, features): """ :param features: a list of (token,weight) tuples or a token -> weight dict, if is a string so it need compute weight (a weight of 1 will be assumed). :return: a decimal digit for the accumulative result of each after handled features-weight pair. """ v = [0] * self.hash_bit_... |
# Just record weight of the non-negative fingerprint = 0 for i in range(self.hash_bit_number): if v[i] >= 0: fingerprint += 1 << i return fingerprint |
def is_equal(self, another, limit=0.8): """ Determine two simhash are similar or not similar. :param another: another simhash. :param limit: a limit of the similarity. :return: if similarity greater than limit return true and else return false. """ if another is None: raise Exception("Parameter another is null") if isi... |
def hamming_distance(self, another): """ Compute hamming distance,hamming distance is a total number of different bits of two binary numbers. :param another: another simhash value. :return: a hamming distance that current simhash and another simhash. """ x = (self.hash ^ another) & ((1 << self.hash_bit_number) - 1) res... |
def _validate_date_str(str_): """Validate str as a date and return string version of date""" if not str_: return None # Convert to datetime so we can validate it's a real date that exists then # convert it back to the string. try: date = datetime.strptime(str_, DATE_FMT) except ValueError: msg = 'Invalid date format, s... |
def _parse_args(): """Parse sys.argv arguments""" token_file = os.path.expanduser('~/.nikeplus_access_token') parser = argparse.ArgumentParser(description='Export NikePlus data to CSV') parser.add_argument('-t', '--token', required=False, default=None, help=('Access token for API, can also store in file %s' ' to avoid ... |
def similarity(self, d, d_): """ Compute a similarity score for two documents. Optionally pass in a `term_sim_ref` dict-like, which should be able to take `term1, term2` as args and return their similarity. """ es = set([e.name for e in d.entities]) es_ = set([e.name for e in d_.entities]) e_weight = (len(es) + len(es_... |
b/c we are # comparing bidirectional term pairs here t_score *= 2 for toks1, toks2 in [(toks, toks_), (toks_, toks)]: for t in toks1 - shared_toks: best_match = max(toks2, key=lambda t_: self.term_sim_ref[t, t_]) sim = self.term_sim_ref[t, best_match] t_score += sim * ((self.idf[t] + self.idf[best_match])/2) if sim > 0... |
+ e_score) return t_score + e_score |
def get_match_info(template, match, state): """ Given a template and a regex match within said template, return a dictionary of information about the match to be used to help parse the template. """ info = match.groupdict() # Put special delimiter cases in terms of normal ones if info['change']: info.update({ 'tag_type... |
if standalone: template_length = len(template) # Standalone tags strip exactly one occurence of '\r', '\n', or '\r\n' # from the end of the line. if tag_end < len(template) and template[tag_end] == '\r': tag_end += 1 if tag_end < len(template) and template[tag_end] == '\n': tag_end += 1 elif lead_wsp: tag_start += len(... |
def get_tag_context(name, state): """ Given a tag name, return its associated value as defined in the current context stack. """ new_contexts = 0 ctm = None while True: try: ctx_key, name = name.split('.', 1) ctm = state.context.get(ctx_key) except ValueError: break if not ctm: break else: state.context.push(ctm) new_c... |
def section_end_info(template, tag_key, state, index): """ Given the tag key of an opening section tag, find the corresponding closing tag (if it exists) and return information about that match. """ state.section.push(tag_key) match = None matchinfo = None search_index = index while state.section: match = state.tag_re.... |
return matchinfo |
def render(template, context, partials={}, state=None): """ Renders a given mustache template, with sane defaults. """ # Create a new state by default state = state or State() # Add context to the state dict if isinstance(context, Context): state.context = context else: state.context = Context(context) # Add any partia... |
def __render(template, state, index=0): """ Given a /template/ string, a parser /state/, and a starting offset (/index/), return the rendered version of the template. """ # Find a Match match = state.tag_re.search(template, index) if not match: return template[index:] info = get_match_info(template, match, state) _pre ... |
state) # Raw tag (should not be escaped) elif info['tag_type'] == '&': state.escape.push(False) repl = __render_tag(info, state) state.escape.pop() # Partial elif info['tag_type'] == '>': partial_name = info['tag_key'] partial_template = None new_dir = None lead_wsp = re.compile(r'^(.)', re.M) repl = '' try: # Cached p... |
template_to_inner does # not need to be constructed with [:] indexing, which is extremely # expensive. elif info['tag_type'] in ('#', '^'): otag_info = info ctag_info = section_end_info(template, info['tag_key'], state, _continue) # Don't want to parse beyond the end of the inner section, but # must include information... |
the ctm if not hasattr(ctm, '__iter__') or isinstance(ctm, dict): ctx_list = [ctm] else: ctx_list = ctm # If there's no match, there are no new contexts else: ctx_list = [False] # If there are new contexts and the section is truthy, or if # there are no new contexts and the section is falsy, render # the contents repl_... |
def __render_tag(info, state): """ Render an individual tag by making the appropriate replacement within the current context (if any). """ new_contexts, context_match = get_tag_context(info['tag_key'], state) replacement = '' if context_match or context_match == 0: replacement = context_match elif info['tag_key'] == '.... |
def format_dict_to_str(dict, format): """ Format a dictionary to the string, param format is a specified format rule such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-' so result is 'name-Sylvanas, gender-Boy'. >>> dict = {'name': 'Sylvanas', 'gender': 'Boy'} >>> format_dict_to_str(dict, format='-') 'name... |
def list_to_str(list, separator=','): """ >>> list = [0, 0, 7] >>> list_to_str(list) '0,0,7' """ list = [str(x) for x in list] return separator.join(list) |
def unite_dict(a, b): """ >>> a = {'name': 'Sylvanas'} >>> b = {'gender': 'Man'} >>> unite_dict(a, b) {'name': 'Sylvanas', 'gender': 'Man'} """ c = {} c.update(a) c.update(b) return c |
def check_validity_for_dict(keys, dict): """ >>> dict = {'a': 0, 'b': 1, 'c': 2} >>> keys = ['a', 'd', 'e'] >>> check_validity_for_dict(keys, dict) == False True >>> keys = ['a', 'b', 'c'] >>> check_validity_for_dict(keys, dict) == False False """ for key in keys: if key not in dict or dict[key] is '' or dict[key] is N... |
def parallel(func, inputs, n_jobs, expand_args=False): """ Convenience wrapper around joblib's parallelization. """ if expand_args: return Parallel(n_jobs=n_jobs)(delayed(func)(*args) for args in inputs) else: return Parallel(n_jobs=n_jobs)(delayed(func)(arg) for arg in inputs) |
def breeding_plugevent(request, breeding_id): """This view defines a form for adding new plug events from a breeding cage. This form requires a breeding_id from a breeding set and restricts the PlugFemale and PlugMale to animals that are defined in that breeding cage.""" breeding = get_object_or_404(Breeding, pk=breedi... |
def get_queryset(self): """The queryset is over-ridden to show only plug events in which the strain matches the breeding strain.""" self.strain = get_object_or_404(Strain, Strain_slug__iexact=self.kwargs['slug']) return PlugEvents.objects.filter(Breeding__Strain=self.strain) |
def command(state, args): """Fix cache issues caused by schema pre-v4.""" if len(args) > 1: print(f'Usage: {args[0]}') return db = state.db _refresh_incomplete_anime(db) _fix_cached_completed(db) |
def read(self): """Parse content and metadata of markdown files""" self.convertRSTmetaToMD() self._md = Markdown(extensions=['meta', 'codehilite(linenums=True)']) content = self._md.convert(self.source) metadata = self._parse_metadata(self._md.Meta) return content, metadata |
def backup_db(release=None, limit=5): """ Backup database and associate it with current release """ assert "psql_user" in env, "Missing psql_user in env" assert "psql_db" in env, "Missing psql_db in env" assert "psql_password" in env, "Missing psql_password in env" if not release: release = paths.get_current_release_na... |
def restore_db(release=None): """ Restores backup back to version, uses current version by default. """ if not release: release = paths.get_current_release_name() if not release: raise Exception("Release %s was not found" % release) backup_file = "postgresql/%s.sql.gz" % release backup_path = paths.get_backup_path(back... |
def sync_local_to_remote(force="no"): """ Sync your local postgres database with remote Example: fabrik prod sync_local_to_remote:force=yes """ _check_requirements() if force != "yes": message = "This will replace the remote database '%s' with your "\ "local '%s', are you sure [y/n]" % (env.psql_db, env.local_psql_db) ... |
) # Cleanup env.run("rm %s" % remote_path) elocal("rm %s" % local_path) # Trigger hook run_hook("postgres.after_sync_local_to_remote") logger.info("Sync complete") |
def sync_remote_to_local(force="no"): """ Sync your remote postgres database with local Example: fabrik prod sync_remote_to_local """ _check_requirements() if force != "yes": message = "This will replace your local database '%s' with the "\ "remote '%s', are you sure [y/n]" % (env.local_psql_db, env.psql_db) answer = p... |
env.local_psql_db, env.local_psql_user, local_path) ) # Cleanup env.run("rm %s" % remote_path) elocal("rm %s" % local_path) # Trigger hook run_hook("postgres.after_sync_remote_to_local") logger.info("Sync complete") |
def get_user_model(): """ Returns the user model to use at runtime. :return: User or custom user """ if DJANGO_VERSION >= (1, 5): from django.contrib.auth import get_user_model return get_user_model() # NOQA else: from django.contrib.auth.models import User # NOQA return User |
def has_app(app_name): """ Determines whether an app is listed in INSTALLED_APPS or the app registry. :param app_name: string :return: bool """ if DJANGO_VERSION >= (1, 7): from django.apps import apps return apps.is_installed(app_name) else: from django.conf import settings return app_name in settings.INSTALLED_APPS |
def apply_check_config(self, config): """ Takes the `query` and `response` fields from a validated config dictionary and sets the proper instance attributes. """ self.query = config.get("query") self.expected_response = config.get("response") |
def perform(self): """ Performs a straightforward TCP request and response. Sends the TCP `query` to the proper host and port, and loops over the socket, gathering response chunks until a full line is acquired. If the response line matches the expected value, the check passes. If not, the check fails. The check will al... |
self.expected_response ) sock.close() return False sock.close() return True |
def _get_section_values(self, config, section): """ extract src and dst values from a section """ src_host = self._get_hosts_from_names(config.get(section, 'src.host')) \ if config.has_option(section, 'src.host') else None src_file = [self._get_abs_filepath(config.get(section, 'src.file'))] \ if config.has_option(secti... |
def _assemble_flowtable(self, values): """ generate a flowtable from a tuple of descriptors. """ values = map(lambda x: [] if x is None else x, values) src = values[0] + values[1] dst = values[2] + values[3] thistable = dict() for s in src: thistable[s] = dst return thistable |
def _detect_loop(self): """ detect loops in flow table, raise error if being present """ for source, dests in self.flowtable.items(): if source in dests: raise conferr('Loops detected: %s --> %s' % (source, source)) |
def _get_hosts_from_ports(self, ports): """ validate hostnames from a list of ports """ hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(',')) return list(set(hosts)) |
def _get_hosts_from_names(self, names): """ validate hostnames from a list of names """ result = set() hosts = map(lambda x: x.strip(), names.split(',')) for h in hosts: if valid_hostname(h.split(':')[0]): result.add(h if ':' in h else '%s:%d' % (h, self.PORT)) else: raise conferr('Invalid hostname: %s' % h.split(':')[... |
def _get_abs_filepath(self, ifile): """ validate src or dst file path with self.config_file """ assert ifile is not None ifile = ifile[7:] if ifile.startswith('file://') else ifile if ifile[0] != '/': basedir = os.path.abspath(os.path.dirname(self.config_file)) ifile = os.path.join(basedir, ifile) return 'file://' + if... |
def flowtable(self): """ get a flat flow table globally """ ftable = dict() for table in self.flow_table: for k, v in table.items(): if k not in ftable: ftable[k] = set(v) else: [ftable[k].add(i) for i in v] # convert set to list for k in ftable: ftable[k] = list(ftable[k]) return ftable |
def _set_last_aid(func): """Decorator for setting last_aid.""" @functools.wraps(func) def new_func(self, *args, **kwargs): # pylint: disable=missing-docstring aid = func(self, *args, **kwargs) self.last_aid = aid return aid return new_func |
def parse_aid(self, text, default_key): """Parse argument text for aid. May retrieve the aid from search result tables as necessary. aresults determines which search results to use by default; True means aresults is the default. The last aid when no aid has been parsed yet is undefined. The accepted formats, in order: ... |
def template(relative_path, *args, **kwargs): """ A decorator for easily rendering templates. Use as follows: main.py: from mustache import (template) @template('../tests/static/say_hello.html') def index(): context = {'name' : 'world'} partials = {} return context, partials if __name__=="__main__": print index() stati... |
partials, state) return render_template return wrapper |
def _connect(dbfile: 'PathLike') -> apsw.Connection: """Connect to SQLite database file.""" conn = apsw.Connection(os.fspath(dbfile)) _set_foreign_keys(conn, 1) assert _get_foreign_keys(conn) == 1 return conn |
def cmdloop(self): """Start CLI REPL.""" while True: cmdline = input(self.prompt) tokens = shlex.split(cmdline) if not tokens: if self.last_cmd: tokens = self.last_cmd else: print('No previous command.') continue if tokens[0] not in self.commands: print('Invalid command') continue command = self.commands[tokens[0]] sel... |
def to_array(self, channels=2): """Generate the array of multipliers for the dynamic""" return np.linspace(self.volume, self.volume, self.duration * channels).reshape(self.duration, channels) |
def add_measurement(request, experiment_id): """This is a view to display a form to add single measurements to an experiment. It calls the object MeasurementForm, which has an autocomplete field for animal.""" experiment = get_object_or_404(Experiment, pk=experiment_id) if request.method == 'POST': form = MeasurementFo... |
def experiment_details_csv(request, pk): """This view generates a csv output file of an experiment. The view writes to a csv table the animal, genotype, age (in days), assay and values.""" experiment = get_object_or_404(Experiment, pk=pk) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] ... |
def aging_csv(request): """This view generates a csv output file of all animal data for use in aging analysis. The view writes to a csv table the animal, strain, genotype, age (in days), and cause of death.""" animal_list = Animal.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposit... |
def litters_csv(request): """This view generates a csv output file of all animal data for use in litter analysis. The view writes to a csv table the birthdate, breeding cage and strain.""" animal_list = Animal.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; ... |
def data_csv(request, measurement_list): """This view generates a csv output of all data for a strain. For this function to work, you have to provide the filtered set of measurements.""" response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.write... |
def get_queryset(self): '''The queryset is filtered by measurements of animals which are part of that strain.''' cohort = get_object_or_404(Cohort, slug=self.kwargs['slug']) animals = cohort.animals.all() return Measurement.objects.filter(animal=animals) |
def get(self, request, *args, **kwargs): '''The queryset is filtered by measurements of animals which are part of that strain.''' cohort = get_object_or_404(Cohort, slug=self.kwargs['slug']) animals = cohort.animals.all() measurements = Measurement.objects.filter(animal=animals) return data_csv(self.request, measuremen... |
def get(self, request, *args, **kwargs): '''The queryset returns all measurement objects''' measurements = Measurement.objects.all() return data_csv(self.request, measurements) |
def get_queryset(self): '''The queryset is filtered by measurements of animals which are part of that strain.''' strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug']) animals = Animal.objects.filter(Strain=strain) return Measurement.objects.filter(animal=animals) |
def get(self, request, *args, **kwargs): '''The queryset is filtered by measurements of animals which are part of that strain.''' strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug']) animals = Animal.objects.filter(Strain=strain) measurements = Measurement.objects.filter(animal=animals) return dat... |
def vectorize( self, docs ): ''' Returns the feature vectors for a set of docs. If model is not already be trained, then self.train() is called. Args: docs (dict or list of tuples): asset_id, body_text of documents you wish to featurize. ''' if type(docs) == dict: docs = docs.items() if self.model == None: self.train(d... |
train=self.stream_train) asset_id2vector.update({item[0]: self.model['DOC_' + str(item[0])] for item in unfound}) return asset_id2vector |
def train(self, docs, retrain=False): ''' Train Doc2Vec on a series of docs. Train from scratch or update. Args: docs: list of tuples (assetid, body_text) or dictionary {assetid : body_text} retrain: boolean, retrain from scratch or update model saves model in class to self.model Returns: 0 if successful ''' if type(do... |
def update_model(self, sentences, update_labels_bool): ''' takes a list of sentenes and updates an existing model. Vectors will be callable through self.model[label] update_labels_bool: boolean that says whether to train the model (self.model.train_words = True) or simply to get vectors for the documents (self.model.tr... |
def _process(self, input): ''' Takes in html-mixed body text as a string and returns a list of strings, lower case and with punctuation given spacing. Called by self._gen_sentence() Args: inpnut (string): body text ''' input = re.sub("<[^>]*>", " ", input) punct = list(string.punctuation) for symbol in punct: input = i... |
def _gen_sentence(self, assetid_body_tuple): ''' Takes an assetid_body_tuple and returns a Doc2Vec LabeledSentence Args: assetid_body_tuple (tuple): (assetid, bodytext) pair ''' asset_id, body = assetid_body_tuple text = self._process(body) sentence = LabeledSentence(text, labels=['DOC_%s' % str(asset_id)]) return sent... |
def _add_new_labels(self, sentences): ''' Adds new sentences to the internal indexing of the model. Args: sentences (list): LabeledSentences for each doc to be added Returns: int: number of sentences added to the model ''' sentence_no = -1 total_words = 0 vocab = self.model.vocab model_sentence_n = len([l for l in voca... |
def run(targets, config_dir='.', check_licenses=False): # type: (List[str], str, bool) -> None """Runs `pylint` and `flake8` commands and exits based off the evaluation of both command results. :param targets: List[str] :param config_dir: str :param check_licenses: bool :return: """ pylint_return_state = False flake8_r... |
def _run_command(command, targets, options): # type: (str, List[str], List[str]) -> bool """Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result True :param command: str :param... |
def ynnm(n, m): """Initial value for recursion formula""" a = 1.0 / np.sqrt(4.0 * np.pi) pm = np.abs(m) out = 0.0 if(n < pm): out = 0.0 elif(n == 0): out = a else: out = a for k in xrange(1, n + 1): out *= np.sqrt((2.0 * k + 1.0) / 8.0 / k) if(n != pm): for k in xrange(n - 1, pm - 1, -1): out *= np.sqrt((n + k + 1.0) /... |
def ynunm(n, m, L): """Fourier coefficients for spherical harmonics""" out = np.zeros(L, dtype=np.float64) tmp1 = 0 tmp2 = 0 tmp3 = 0 tmp4 = 0 if(np.abs(m) <= n): out[n] = ynnm(n, m) k = n - 2 if(k >= 0): tmp1 = (n - k - 1.0) * (n + k + 2.0) tmp2 = (n - k - 2.0) * (n + k + 3.0) - 4.0 * m ** 2 tmp4 = ((n - k) * (n + k +... |
- 4.0 * m ** 2 tmp3 = (n - k - 3.0) * (n + k + 4.0); tmp4 = ((n - k) * (n + k + 1.0)) out[k] = ((tmp1 + tmp2) * out[k + 2] - tmp3 * out[k + 4]) / tmp4 return out |
def smallest_prime_factor(Q): """Find the smallest number factorable by the small primes 2, 3, 4, and 7 that is larger than the argument Q""" A = Q; while(A != 1): if(np.mod(A, 2) == 0): A = A / 2 elif(np.mod(A, 3) == 0): A = A / 3 elif(np.mod(A, 5) == 0): A = A / 5 elif(np.mod(A, 7) == 0): A = A / 7; else: A = Q + 1; ... |
def s_data(nrows_fdata, Nmax, Q): """ I am going to assume we will always have even data. This is pretty safe because it means that we have measured both poles of the sphere and have data that has been continued. nrows_fdata: Number of rows in fdata. Nmax: The largest number of n values desired. Q: A value greater than... |
/ nu return s |
def hkm_fc(fdata, Nmax, m, s): """ Assume fdata has even rows""" f = fdata[:, m] L1 = f.size MM = int(L1 / 2) Q = s.size ff = np.zeros(Q, dtype=np.complex128) for n in xrange(MM, L1): ff[n] = f[n - MM] for n in xrange(0, MM): ff[n] = f[n + MM] # For larger problems, this speeds things up pretty good. F = np.fft.fft(ff)... |
def mindx(m, nmax, mmax): """index to the first n value for a give m within the spherical coefficients vector. Used by sc_to_fc""" ind = 0 NN = nmax + 1 if np.abs(m) > mmax: raise Exception("|m| cannot be larger than mmax") if (m != 0): ind = NN ii = 1 for i in xrange(1, np.abs(m)): ind = ind + 2 * (NN - i) ii = i + 1 ... |
def sc_to_fc(spvec, nmax, mmax, nrows, ncols): """assume Ncols is even""" fdata = np.zeros([int(nrows), ncols], dtype=np.complex128) for k in xrange(0, int(ncols / 2)): if k < mmax: kk = k ind = mindx(kk, nmax, mmax) vec = spvec[ind:ind + nmax - np.abs(kk) + 1] fdata[:, kk] = fcvec_m_sc(vec, kk, nmax, nrows) kk = -(k +... |
def _use_methods(cls): """ Add use_* methods for calculations. Code below enables the usage my_calculation.use_parameters(my_parameters) """ use_dict = JobCalculation._use_methods use_dict.update({ "parameters": { 'valid_types': RipsDistanceMatrixParameters, 'additional_parameter': None, 'linkname': 'parameters', 'docs... |
def _validate_inputs(self, inputdict): """ Validate input links. """ # Check inputdict try: parameters = inputdict.pop(self.get_linkname('parameters')) except KeyError: raise InputValidationError("No parameters specified for this " "calculation") if not isinstance(parameters, RipsDistanceMatrixParameters): raise InputV... |
inputdict: raise ValidationError("Unrecognized inputs: {}".format(inputdict)) return parameters, code, distance_matrix, symlink |
def _prepare_for_submission(self, tempfolder, inputdict): """ Create input files. :param tempfolder: aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: dictionary of the input nodes as they would be returned by get_inputs_dict """ parameters, code, distance_matrix, symlink... |
def cache_status(db, aid, force=False): """Calculate and cache status for given anime. Don't do anything if status already exists and force is False. """ with db: cur = db.cursor() if not force: # We don't do anything if we already have this aid in our # cache. cur.execute('SELECT 1 FROM cache_anime WHERE aid=?', (aid,... |
= 0 for number, watched in cur: # Once we find the first unwatched episode, we set the last # consecutive watched episode to the previous episode (or 0). if watched == 0: number -= 1 break # We store this in the cache. set_status(db, aid, enddate and episodecount <= number, number) |
def set_status( db, aid: int, complete: Any, watched_episodes: int, ) -> None: """Set anime status.""" upsert(db, 'cache_anime', ['aid'], { 'aid': aid, 'complete': 1 if complete else 0, 'watched_episodes': watched_episodes, }) |
def get_complete(db) -> Iterator[int]: """Return AID of complete anime.""" cur = db.cursor() cur.execute( """SELECT aid FROM cache_anime WHERE complete=?""", (1,)) for row in cur: yield row[0] |
def create_component(self, module_name): '''Create a component out of a loaded module. Turns a previously-loaded shared module into a component in the manager. This will invalidate any objects that are children of this node. The @ref module_name argument can contain options that set various properties of the new compon... |
def delete_component(self, instance_name): '''Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises FailedToDeleteComponentError ''' with self... |
def load_module(self, path, init_func): '''Load a shared library. Call this function to load a shared library (DLL file under Windows, shared object under UNIX) into the manager. @param path The path to the shared library. @param init_func The name entry function in the library. @raises FailedToLoadModuleError ''' try:... |
def unload_module(self, path): '''Unload a loaded shared library. Call this function to remove a shared library (e.g. a component) that was previously loaded. @param path The path to the shared library. @raises FailedToUnloadModuleError ''' with self._mutex: if self._obj.unload_module(path) != RTC.RTC_OK: raise FailedT... |
def components(self): '''The list of components in this manager, if any. This information can also be found by listing the children of this node that are of type @ref Component. That method is more useful as it returns the tree entries for the components. ''' with self._mutex: if not self._components: self._components ... |
def factory_profiles(self): '''The factory profiles of all loaded modules.''' with self._mutex: if not self._factory_profiles: self._factory_profiles = [] for fp in self._obj.get_factory_profiles(): self._factory_profiles.append(utils.nvlist_to_dict(fp.properties)) return self._factory_profiles |
def set_config_parameter(self, param, value): '''Set a configuration parameter of the manager. @param The parameter to set. @value The new value for the parameter. @raises FailedToSetConfigurationError ''' with self._mutex: if self._obj.set_configuration(param, value) != RTC.RTC_OK: raise exceptions.FailedToSetConfigur... |
def configuration(self): '''The configuration dictionary of the manager.''' with self._mutex: if not self._configuration: self._configuration = utils.nvlist_to_dict(self._obj.get_configuration()) return self._configuration |
def profile(self): '''The manager's profile.''' with self._mutex: if not self._profile: profile = self._obj.get_profile() self._profile = utils.nvlist_to_dict(profile.properties) return self._profile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.