code
stringlengths
1
18.2k
: bool, optional Whether to treat the `med` parameter as the median or mode (default will be mode). return_distribution: bool, optional If `True`, then function will return a `DoubleGauss_Distribution` object. Otherwise, will return just the parameters. """ if median: q1 = 0.5 - (interval/2) q2 = 0.5 + (interval/2) tar...
def pctile(self,pct,res=1000): """Returns the desired percentile of the distribution. Will only work if properly normalized. Designed to mimic the `ppf` method of the `scipy.stats` random variate objects. Works by gridding the CDF at a given resolution and matching the nearest point. NB, this is of course not as precis...
def save_hdf(self,filename,path='',res=1000,logspace=False): """Saves distribution to an HDF5 file. Saves a pandas `dataframe` object containing tabulated pdf and cdf values at a specfied resolution. After saving to a particular path, a distribution may be regenerated using the `Distribution_FromH5` subclass. Parameter...
gridding. """ if logspace: vals = np.logspace(np.log10(self.minval), np.log10(self.maxval), res) else: vals = np.linspace(self.minval,self.maxval,res) d = {'vals':vals, 'pdf':self(vals), 'cdf':self.cdf(vals)} df = pd.DataFrame(d) df.to_hdf(filename,path+'/fns') if hasattr(self,'samples'): s = pd.Series(self.samples) s....
def plot(self,minval=None,maxval=None,fig=None,log=False, npts=500,**kwargs): """ Plots distribution. Parameters ---------- minval : float,optional minimum value to plot. Required if minval of Distribution is `-np.inf`. maxval : float, optional maximum value to plot. Required if maxval of Distribution is `np.inf`. fig ...
= self.minval if maxval is None: maxval = self.maxval if maxval==np.inf or minval==-np.inf: raise ValueError('must have finite upper and lower bounds to plot. (use minval, maxval kws)') if log: xs = np.logspace(np.log10(minval),np.log10(maxval),npts) else: xs = np.linspace(minval,maxval,npts) setfig(fig) plt.plot(xs,se...
def resample(self,N,minval=None,maxval=None,log=False,res=1e4): """Returns random samples generated according to the distribution Mirrors basic functionality of `rvs` method for `scipy.stats` random variates. Implemented by mapping uniform numbers onto the inverse CDF using a closest-matching grid approach. Parameters ...
hasattr(self,'maxval_cdf'): maxval = self.maxval_cdf else: maxval = self.maxval if maxval==np.inf or minval==-np.inf: raise ValueError('must have finite upper and lower bounds to resample. (set minval, maxval kws)') u = rand.random(size=N) if log: vals = np.logspace(log10(minval),log10(maxval),res) else: vals = np.lins...
def plothist(self,fig=None,**kwargs): """Plots a histogram of samples using provided bins. Parameters ---------- fig : None or int Parameter passed to `setfig`. kwargs Keyword arguments passed to `plt.hist`. """ setfig(fig) plt.hist(self.samples,bins=self.bins,**kwargs)
def resample(self,N): """Returns a bootstrap resampling of provided samples. Parameters ---------- N : int Number of samples. """ inds = rand.randint(len(self.samples),size=N) return self.samples[inds]
def resample(self,N): """Returns a random sampling. """ return rand.random(size=N)*(self.maxval - self.minval) + self.minval
def resample(self,N,**kwargs): """Random resampling of the doublegauss distribution """ lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo) hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi) u = rand.random(size=N) hi = (u < float(self.sighi)/(self.sighi + self.siglo)) lo = (u >= float(self.sighi...
def tzname_in_python2(myfunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ def inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func
def lookahead(iterable, *args, **kwargs): """Constructs a generator over the iterable yielding look-ahead (and/or “look-behind”) tuples. One tuple will be generated for each element value accessible from the iterator, containing that element and the number of elements specified just prior to and immediately after. When...
lookbehind, lookahead) Notice that lookahead is now the 3rd parameter! Example semantics: lookahead(iterable): yield (item, next) lookahead(iterable, 2): yield (item, next, next+1) lookahead(iterable, 1, 2): yield (prev, item, next, next+1) lookahead(iterable, p, n): yeild (prev, ..., prev+p-1, item, next, ..., next+n-...
the lookbehind positions to None and generate the first element. # This will immediately raise StopIteration in the trivial case: lst = [None]*num_prev + [iterator.next()] # Prime the needed lookahead values: for x in xrange(num_next): try: lst.append(iterator.next()) except StopIteration: lst.append(None) num_next -= ...
def ac3(space): """ AC-3 algorithm. This reduces the domains of the variables by propagating constraints to ensure arc consistency. :param Space space: The space to reduce """ #determine arcs arcs = {} for name in space.variables: arcs[name] = set([]) for const in space.constraints: for vname1,vname2 in product(const.v...
def _unary(space,const,name): """ Reduce the domain of variable name to be node-consistent with this constraint, i.e. remove those values for the variable that are not consistent with the constraint. returns True if the domain of name was modified """ if not name in const.vnames: return False if space.variables[name].d...
def _binary(space,const,name1,name2): """ reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint returns True if the domain of name1 was mod...
def solve(space,method='backtrack',ordering=None): """ Generator for all solutions. :param str method: the solution method to employ :param ordering: an optional parameter ordering :type ordering: sequence of parameter names Methods: :"backtrack": simple chronological backtracking :"ac-lookahead": full lookahead """ if...
def get_task_parser(task): """ Construct an ArgumentParser for the given task. This function returns a tuple (parser, proxy_args). If task accepts varargs only, proxy_args is True. If task accepts only positional and explicit keyword args, proxy args is False. """ args, varargs, keywords, defaults = inspect.getargspec(...
def invoke_task(task, args): """ Parse args and invoke task function. :param task: task function to invoke :param args: arguments to the task (list of str) :return: result of task function :rtype: object """ parser, proxy_args = get_task_parser(task) if proxy_args: return task(*args) else: pargs = parser.parse_args(arg...
def get_task_module(feature): """ Return imported task module of feature. This function first tries to import the feature and raises FeatureNotFound if that is not possible. Thereafter, it looks for a submodules called ``apetasks`` and ``tasks`` in that order. If such a submodule exists, it is imported and returned. :p...
feature ... try tasks pass try: tasks_module = importlib.import_module(feature + '.tasks') except ImportError: # No tasks module in feature ... skip it pass return tasks_module
def run(args, features=None): """ Run an ape task. Composes task modules out of the selected features and calls the task with arguments. :param args: list comprised of task name followed by arguments :param features: list of features to compose before invoking the task """ features = features or [] for feature in featu...
def main(): """ Entry point when used via command line. Features are given using the environment variable ``PRODUCT_EQUATION``. If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points to an existing equation file that selection is used. (if ``APE_PREPEND_FEATURES`` is given, those features are prepended)...
to be set!' ) # run ape with features selected run(sys.argv, features=features)
def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle_noargs() to facilitate testing. """ if self.symlink: if sys.platform == 'win32': raise CommandError("Symlinking is not supported by this " "platform (%s)." % sys.platform) if not self.local: raise CommandError("Can't symlink to ...
' to have been collected first. Try ' ' ecstatic.storage.CachedStaticFilesStorage' \ % e) raise ValueError(message) if not self.progressive_post_process and do_post_process: self._post_process(found_files, self.dry_run) return { 'modified': self.copied_files + self.symlinked_files, 'unmodified': self.unmodified_files, ...
def compare(self, path, prefixed_path, source_storage): """ Returns True if the file should be copied. """ # First try a method on the command named compare_<comparison_method> # If that doesn't exist, create a comparitor that calls methods on the # storage with the name <comparison_method>, passing them the name. comp...
def initiate_session(config): """ Initiate a session globally used in prof : + Retrive the cookie + Log to prof Returns an initiated session """ global baseurl baseurl = config['DEFAULT']['baseurl'] if 'session' in config['DEFAULT']: cookies = { 'PHPSESSID': config['DEFAULT']['session'] } prof_session.cookies = request...
def verify_session(session, baseurl): """ Check that this session is still valid on this baseurl, ie, we get a list of projects """ request = session.post(baseurl+"/select_projet.php") return VERIFY_SESSION_STRING in request.content.decode('iso-8859-1')
def get_session(session, baseurl, config): """ Try to get a valid session for this baseurl, using login found in config. This function invoques Firefox if necessary """ # Read proxy for firefox if environ.get("HTTP_PROXY"): myProxy = environ.get("HTTP_PROXY") proxy = Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': ...
def credentials(login=None): """ Find user credentials. We should have parsed the command line for a ``--login`` option. We will try to find credentials in environment variables. We will ask user if we cannot find any in arguments nor environment """ if not login: login = environ.get("PROF_LOGIN") password = environ.ge...
def display(self): ''' Displays statistics about our LM ''' voc_list = [] doc_ids = self.term_count_n.keys() doc_ids.sort() for doc_id in doc_ids: ngrams = len(self.term_count_n[doc_id]['ngrams']) print 'n-Grams (doc %s): %d' % (str(doc_id), ngrams) ngrams1 = len(self.term_count_n_1[doc_id]['ngrams']) print '(n-1)-Gram...
def get_ngram_counts(self): ''' Returns a list of n-gram counts Array of classes counts and last item is for corpus ''' ngram_counts = { 'classes': [], 'corpus': 0 } doc_ids = self.term_count_n.keys() doc_ids.sort() for doc_id in doc_ids: print self.term_count_n[doc_id] class_ngrams = len(self.term_count_n[doc_id]['ngr...
def to_ngrams(self, terms): ''' Converts terms to all possibe ngrams terms: list of terms ''' if len(terms) <= self.n: return terms if self.n == 1: n_grams = [[term] for term in terms] else: n_grams = [] for i in range(0,len(terms)-self.n+1): n_grams.append(terms[i:i+self.n]) return n_grams
def lr_padding(self, terms): ''' Pad doc from the left and right before adding, depending on what's in self.lpad and self.rpad If any of them is '', then don't pad there. ''' lpad = rpad = [] if self.lpad: lpad = [self.lpad] * (self.n - 1) if self.rpad: rpad = [self.rpad] * (self.n - 1) return lpad + terms + rpad
def add_doc(self, doc_id ='', doc_terms=[], doc_length=-1): ''' Add new document to our Language Model (training phase) doc_id is used here, so we build seperate LF for each doc_id I.e. if you call it more than once with same doc_id, then all terms given via doc_terms will contribute to same LM doc_terms: list of words...
def calculate(self, doc_terms=[], actual_id='', doc_length=-1): ''' Given a set of terms, doc_terms We find the doc in training data (calc_id), whose LM is more likely to produce those terms Then return the data structure calculated back doc_length is passed to pr_ngram() and pr_doc() it is up to them to use it or not....
unseen_count = 0 for ngram in ngrams: (ngram_pr, ngram_seen) = self.pr_ngram(doc_id, ngram, new_doc=new_doc, log=True, logbase=2, doc_length=doc_length) doc_pr += ngram_pr new_doc = False if ngram_seen: seen_count += 1 else: unseen_count += 1 doc_pr += self.pr_doc(doc_id, doc_length=doc_length) if self.verbose: print d...
def run(self): """ pop up a dialog box and return when the user has closed it """ response = None root = tkinter.Tk() root.withdraw() while response is not True: response = tkinter.messagebox.askokcancel(title=self.title, message=self.pre_message) if self.post_message: print(self.post_message) self.exit_time = time.tim...
def download(url, file=None): """ Pass file as a filename, open file object, or None to return the request bytes Args: url (str): URL of file to download file (Union[str, io, None]): One of the following: - Filename of output file - File opened in binary write mode - None: Return raw bytes instead Returns: Union[bytes,...
def download_extract_tar(tar_url, folder, tar_filename=''): """ Download and extract the tar at the url to the given folder Args: tar_url (str): URL of tar file to download folder (str): Location of parent directory to extract to. Doesn't have to exist tar_filename (str): Location to download tar. Default is to a temp ...
def install_package(tar_url, folder, md5_url='{tar_url}.md5', on_download=lambda: None, on_complete=lambda: None): """ Install or update a tar package that has an md5 Args: tar_url (str): URL of package to download folder (str): Location to extract tar. Will be created if doesn't exist md5_url (str): URL of md5 to use ...
pass download_extract_tar(tar_url, folder, data_file) on_complete() if remote_md5 != calc_md5(data_file): raise ValueError('MD5 url does not match tar: ' + md5_url) return True return False
def _process_cell(i, state, finite=False): """Process 3 cells and return a value from 0 to 7. """ op_1 = state[i - 1] op_2 = state[i] if i == len(state) - 1: if finite: op_3 = state[0] else: op_3 = 0 else: op_3 = state[i + 1] result = 0 for i, val in enumerate([op_3, op_2, op_1]): if val: result += 2**i return result
def _remove_lead_trail_false(bool_list): """Remove leading and trailing false's from a list""" # The internet can be a wonderful place... for i in (0, -1): while bool_list and not bool_list[i]: bool_list.pop(i) return bool_list
def _crop_list_to_size(l, size): """Make a list a certain size""" for x in range(size - len(l)): l.append(False) for x in range(len(l) - size): l.pop() return l
def process(self, state): """Process a state and return the next state Usage: out = rule_110.process([True, False, True]) len(out) # 5, because a False is added to either side out == [True, True, True, True, False] out = rule_110.process([False, True, False, True]) len(out) # still 5, because leading / trailing False's...
def iterate(self, state): """Process a starting state over and over again. Example: for x in rule_110.iterate(state): # Do something with the current state here # Note: You should break this yourself # This breaks automatically if the previous state was the same as the # current one, but that's not gonna happen on an i...
def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = None, dry_run = False, stop_on_failure = False, **kwargs): """Submits a job that will be executed on the local machine during a call to "run". All kwargs will simply be ignored.""" # remove duplicate dependencies dep...
def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, keep_logs=False, **kwargs): """Re-submit jobs automatically""" self.lock() # iterate over all jobs jobs = self.get_jobs(job_ids) if new_command is not None: if len(jobs) == 1: jobs[0].set_command_line(new_command) else: log...
def stop_jobs(self, job_ids=None): """Resets the status of the job to 'submitted' when they are labeled as 'executing'.""" self.lock() jobs = self.get_jobs(job_ids) for job in jobs: if job.status in ('executing', 'queued', 'waiting') and job.queue_name == 'local': logger.info("Reset job '%s' (%s) in the database", job....
def stop_job(self, job_id, array_id = None): """Resets the status of the given to 'submitted' when they are labeled as 'executing'.""" self.lock() job, array_job = self._job_and_array(job_id, array_id) if job is not None: if job.status in ('executing', 'queued', 'waiting'): logger.info("Reset job '%s' (%s) in the datab...
def _run_parallel_job(self, job_id, array_id = None, no_log = False, nice = None, verbosity = 0): """Executes the code for this job on the local machine.""" environ = copy.deepcopy(os.environ) environ['JOB_ID'] = str(job_id) if array_id: environ['SGE_TASK_ID'] = str(array_id) else: environ['SGE_TASK_ID'] = 'undefined' ...
open(array_job.std_out_file(), 'w', 1), open(array_job.std_err_file(), 'w', 1) else: out, err = open(job.std_out_file(), 'w', 1), open(job.std_err_file(), 'w', 1) # return the subprocess pipe to the process try: return subprocess.Popen(command, env=environ, stdout=out, stderr=err, bufsize=1) except OSError as e: logger...
def run_scheduler(self, parallel_jobs = 1, job_ids = None, sleep_time = 0.1, die_when_finished = False, no_log = False, nice = None, verbosity = 0): """Starts the scheduler, which is constantly checking for jobs that should be ran.""" running_tasks = [] finished_tasks = set() try: # keep the scheduler alive until every...
is not None: jj = array_job if array_job is not None else job result = "%s (%d)" % (jj.status, jj.result) if jj.result is not None else "%s (?)" % jj.status if jj.status not in ('success', 'failure'): logger.error("Job '%s' (%s) finished with status '%s' instead of 'success' or 'failure'. Usually this means an internal...
the queue for job in jobs: if job.status == 'submitted' and job.queue_name == 'local': job.queue() # get all unfinished jobs that are submitted to the local queue unfinished_jobs = [job for job in jobs if job.status in ('queued', 'executing') and job.queue_name == 'local'] for job in unfinished_jobs: if job.array: # fi...
jobs to be run twice # e.g., if the loop is executed while the asynchronous job did not start yet array_job.status = 'executing' job.status = 'executing' if len(running_tasks) == parallel_jobs: break else: if job.status == 'queued': # start a new job process = self._run_parallel_job(job.unique, no_log=no_log, nice=nice...
are no more jobs running.") break # THIRD: sleep the desired amount of time before re-checking time.sleep(sleep_time) # This is the only way to stop: you have to interrupt the scheduler except (KeyboardInterrupt, StopIteration): if hasattr(self, 'session'): self.unlock() logger.info("Stopping task scheduler due to user...
job.status != 'success'] self.unlock() return sorted(failures)
def makeDependencyMap(aMap): """ create a dependency data structure as follows: - Each key in aMap represents an item that depends on each item in the iterable which is that key's value - Each Node represents an item which is a precursor to its parents and depends on its children Returns a map whose keys are the items ...
to find the precursors for a given item by using BottomUpVisitor on the Node associated with that item """ index = {} for i in aMap.keys(): iNode = index.get(i,None) if not iNode: iNode = Node(i) index[i] = iNode for c in aMap[i]: cNode = index.get(c,None) if not cNode: cNode = Node(c) index[c] = cNode iNode.addChild(c...
def debugTreePrint(node,pfx="->"): """Purely a debugging aid: Ascii-art picture of a tree descended from node""" print pfx,node.item for c in node.children: debugTreePrint(c," "+pfx)
def dependencyOrder(aMap, aList = None): """ Given descriptions of dependencies in aMap and an optional list of items in aList if not aList, aList = aMap.keys() Returns a list containing each element of aList and all its precursors so that every precursor of any element in the returned list is seen before that dependen...
def addChild(self,item): """ When you add a child to a Node, you are adding yourself as a parent to the child You cannot have the same node as a child more than once. If you add a Node, it is used. If you add a non-node, a new child Node is created. Thus: You cannot add a child as an item which is a Node. (You can, how...
def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT): """ Convert a HTML mesasge to plain text. """ def _patched_handle_charref(c): self = h charref = self.charref(c) if self.code or self.pre: charref = cgi.escape(charref) self.o(charref, 1) def _patched_handle_entityref(c): self = h entityref = self.entityref...
def replace_fields(text, context, autoescape=None, errors='inline'): """ Allow simple field replacements, using the python str.format() syntax. When a string is passed that is tagged with :func:`~django.utils.safestring.mark_safe`, the context variables will be escaped before replacement. This function is used instead ...
when some fields are not provided. # Instead, simulate its' behavior to make sure all items that were found will be replaced. start = 0 new_text = [] for match in RE_FORMAT.finditer(text): new_text.append(text[start:match.start()]) start = match.end() # See if the element was found key = match.group('var') try: value =...
template.format(value) except ValueError: logger.debug("Invalid format %s in email template %s!", format, match.group(0)) if raise_errors: raise elif ignore_errors: new_text.append(match.group(0)) elif inline_errors: new_text.append(escape_error("!!invalid format {0}!!".format(format))) continue else: value = escape_fu...
def render_email_template(email_template, base_url, extra_context=None, user=None): """ Render the email template. :type email_template: fluentcms_emailtemplates.models.EmailTemplate :type base_url: str :type extra_context: dict | None :type user: django.contrib.auth.models.User :return: The subject, html and text cont...
language. with switch_language(email_template): # Get the body content context_data['body'] = _render_email_placeholder(dummy_request, email_template, base_url, context_data) context_data['subject'] = subject = replace_fields(email_template.subject, context_data, autoescape=False) # Merge that with the HTML templates. ...
def _get_dummy_request(base_url, user): """ Create a dummy request. Use the ``base_url``, so code can use ``request.build_absolute_uri()`` to create absolute URLs. """ split_url = urlsplit(base_url) is_secure = split_url[0] == 'https' dummy_request = RequestFactory(HTTP_HOST=split_url[1]).get('/', secure=is_secure) dum...
def _render_email_placeholder(request, email_template, base_url, context): """ Internal rendering of the placeholder/contentitems. This a simple variation of render_placeholder(), making is possible to render both a HTML and text item in a single call. Caching is currently not implemented. :rtype: fluentcms_emailtempla...
def _make_links_absolute(html, base_url): """ Make all links absolute. """ url_changes = [] soup = BeautifulSoup(html) for tag in soup.find_all('a', href=True): old = tag['href'] fixed = urljoin(base_url, old) if old != fixed: url_changes.append((old, fixed)) tag['href'] = fixed for tag in soup.find_all('img', src=True...
def string_to_datetime(date): """Return a datetime.datetime instance with tzinfo. I.e. a timezone aware datetime instance. Acceptable formats for input are: * 2012-01-10T12:13:14 * 2012-01-10T12:13:14.98765 * 2012-01-10T12:13:14.98765+03:00 * 2012-01-10T12:13:14.98765Z * 2012-01-10 12:13:14 * 2012-01-10 12:13:14.98765 ...
def date_to_string(date): """Transform a date or datetime object into a string and return it. Examples: >>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC)) '2012-01-03T12:23:34+00:00' >>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34)) '2012-01-03T12:23:34' >>> date_to_string(datetime.da...
def uuid_to_date(uuid, century='20'): """Return a date created from the last 6 digits of a uuid. Arguments: uuid The unique identifier to parse. century The first 2 digits to assume in the year. Default is '20'. Examples: >>> uuid_to_date('e8820616-1462-49b6-9784-e99a32120201') datetime.date(2012, 2, 1) >>> uuid_to_dat...
def add_to_gitignore(line: str): """ Adds a line to the .gitignore file of the repo Args: line: line to add """ if not line.endswith('\n'): line = f'{line}\n' if GIT_IGNORE.exists(): if line in GIT_IGNORE.read_text(encoding='utf8'): return previous_content = GIT_IGNORE.read_text(encoding='utf8') else: previous_content ...
def hardware_info(): """ Returns basic hardware information about the computer. Gives actual number of CPU's in the machine, even when hyperthreading is turned on. Returns ------- info : dict Dictionary containing cpu and memory information. """ try: if sys.platform == 'darwin': out = _mac_hardware_info() elif sys.plat...
def clear_i2b2_tables(tables: I2B2Tables, uploadid: int) -> None: """ Remove all entries in the i2b2 tables for uploadid. :param tables: :param uploadid: :return: """ # This is a static function to support the removefacts operation print("Deleted {} patient_dimension records" .format(PatientDimension.delete_upload_id(t...
def create_parser() -> FileAwareParser: """ Create a command line parser :return: parser """ parser = FileAwareParser(description="Clear data from FHIR observation fact table", prog="removefacts", use_defaults=False) parser.add_argument("-ss", "--sourcesystem", metavar="SOURCE SYSTEM CODE", help="Sourcesystem code") pa...
def remove_facts(argv: List[str]) -> bool: """ Convert a set of FHIR resources into their corresponding i2b2 counterparts. :param argv: Command line arguments. See: create_parser for details :return: """ parser = create_parser() local_opts = parser.parse_args(argv) # Pull everything from the actual command line if not ...
if opts.sourcesystem: print("---> Removing entries for sourcesystem_cd {}".format(opts.sourcesystem)) clear_i2b2_sourcesystems(I2B2Tables(opts), opts.sourcesystem) if opts.testlist: opts.testprefix = opts.testprefix if (opts and opts.testprefix) else default_test_prefix print(f"---> Listing orphan test elements for sou...
async def add(client: Client, identity_signed_raw: str) -> ClientResponse: """ POST identity raw document :param client: Client to connect to the api :param identity_signed_raw: Identity raw document :return: """ return await client.post(MODULE + '/add', {'identity': identity_signed_raw}, rtype=RESPONSE_AIOHTTP)
async def certify(client: Client, certification_signed_raw: str) -> ClientResponse: """ POST certification raw document :param client: Client to connect to the api :param certification_signed_raw: Certification raw document :return: """ return await client.post(MODULE + '/certify', {'cert': certification_signed_raw}, r...
async def revoke(client: Client, revocation_signed_raw: str) -> ClientResponse: """ POST revocation document :param client: Client to connect to the api :param revocation_signed_raw: Certification raw document :return: """ return await client.post(MODULE + '/revoke', {'revocation': revocation_signed_raw}, rtype=RESPONS...
async def lookup(client: Client, search: str) -> dict: """ GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/lookup/%s' % search, schema=LOOKUP_SCHEMA)
async def certifiers_of(client: Client, search: str) -> dict: """ GET UID/Public key certifiers :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/certifiers-of/%s' % search, schema=CERTIFICATIONS_SCHEMA)
async def requirements(client: Client, search: str) -> dict: """ GET list of requirements for a given UID/Public key :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/requirements/%s' % search, schema=REQUIREMENTS_SCHEMA)
async def identity_of(client: Client, search: str) -> dict: """ GET Identity data written in the blockchain :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA)
def shell_exec(command, **kwargs): # from gitapi.py """Excecutes the given command silently. """ proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs) out, err = [x.decode("utf-8") for x in proc.communicate()] return {'out': out, 'err': err, 'code': proc.returncode}
def run(command, **kwargs): """Excecutes the given command while transfering control, till the execution is complete. """ print command p = Popen(shlex.split(command), **kwargs) p.wait() return p.returncode
def data(tableid, variables=dict(), stream=False, descending=False, lang=DEFAULT_LANGUAGE): """Pulls data from a table and generates rows. Variables is a dictionary mapping variable codes to values. Streaming: Values must be chosen for all variables when streaming """ # bulk is also in csv format, but the response is s...
def subjects(subjects=None, recursive=False, include_tables=False, lang=DEFAULT_LANGUAGE): """List subjects from the subject hierarchy. If subjects is not given, the root subjects will be used. Returns a generator. """ request = Request('subjects', *subjects, recursive=recursive, includeTables=include_tables, lang=lang...
def tableinfo(tableid, lang=DEFAULT_LANGUAGE): """Fetch metadata for statbank table Metadata includes information about variables, which can be used when extracting data. """ request = Request('tableinfo', tableid, lang=lang) return Tableinfo(request.json, lang=lang)
def tables(subjects=None, pastDays=None, include_inactive=False, lang=DEFAULT_LANGUAGE): """Find tables placed under given subjects. """ request = Request('tables', subjects=subjects, pastDays=pastDays, includeInactive=include_inactive, lang=lang) return (Table(table, lang=lang) for table in request.json)
def request_method(self, method: str, **method_kwargs: Union[str, int]) -> dict: """ Process method request and return json with results :param method: str: specifies the method, example: "users.get" :param method_kwargs: dict: method parameters, example: "users_id=1", "fields='city, contacts'" """ response = self.sess...