Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,700
def networkMultiLevel(self, *modes, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None, nodeAttribute = None, _networkTypeString = ): stemCheck = False if stemmer is not None: if isinstance(stemmer, collections.abc.Callable): stemCheck = True ...
Creates a network of the objects found by any number of tags _modes_, with edges between all co-occurring values. IF you only want edges between co-occurring values from different tags use [networkMultiMode()](#metaknowledge.CollectionWithIDs.networkMultiMode). A **networkMultiLevel**() looks are each entry in...
355,701
def _finalize_run(self): self._run_information[self.v_crun][] = 1 while len(self._new_links): name_pair, child_parent_pair = self._new_links.popitem(last=False) parent_node, _ = child_parent_pair _, link = name_pair parent_node.f_remove_child(link...
Called by the environment after storing to perform some rollback operations. All results and derived parameters created in the current run are removed. Important for single processing to not blow up the parent trajectory with the results of all runs.
355,702
def parse(cls, spec, relative_to=, subproject_roots=None): spec_path, target_name = parse_spec(spec, relative_to=relative_to, subproject_roots=subproject_roots) return cls(spec_path, target_name)
Parses an address from its serialized form. :param string spec: An address in string form <path>:<name>. :param string relative_to: For sibling specs, ie: ':another_in_same_build_family', interprets the missing spec_path part as `relative_to`. :param list subproject_roots: Pa...
355,703
def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True): modes_directory = "./modes_semi_vec/" if not os.path.isdir(modes_directory): os.mkdir(modes_directory) filename = modes_directory + filename for i, mode in enumerate(self._ms.modes): ...
Writes the mode fields to a file and optionally plots them. Args: filename (str): The nominal filename to use for the saved data. The suffix will be automatically be changed to identifiy each mode number. Default is 'mode.dat' plot (bool): `True` if plo...
355,704
def main(): log = logging.getLogger(mod_logger + ) parser = argparse.ArgumentParser(description=) parser.add_argument(, , help=, required=False) parser.add_argument(, , help=, required=True) parser.add_argument(, , help=, required=True) parser.add_argument(, , help=, required=True) pars...
Handles calling this module as a script :return: None
355,705
def filter_data(d, x, model="lms", **kwargs): kwargs["n"] = x.shape[1] if model in ["LMS", "lms"]: f = FilterLMS(**kwargs) elif model in ["NLMS", "nlms"]: f = FilterNLMS(**kwargs) elif model in ["RLS", "rls"]: f = FilterRLS(**kwargs) elif model in ["GNGD", "gng...
Function that filter data with selected adaptive filter. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Kwargs:** * Any key argument that can be accepted with selected filter m...
355,706
def parse_readme(cls, readme_path: str = , encoding: str = ) -> str: with HERE.joinpath(readme_path).open(encoding=encoding) as readme_file: long_description = readme_file.read() if readme_path.endswith() and cls.download_url.startswith(): base_url = .format(cls.downl...
Parse readme and resolve relative links in it if it is feasible. Links are resolved if readme is in rst format and the package is hosted on GitHub.
355,707
def overlay(ctx): args = ctx.obj.get() filename = args.get() debug = args.get() _setup(filename) for c in config.config(filename): with fasteners.InterProcessLock(c.lock_file): util.print_info(.format(c.name)) if not os.path.exists(c.src): git....
Install gilt dependencies
355,708
def find_prime_polys(generator=2, c_exp=8, fast_primes=False, single=False): root_charac = 2 if not conflict: correct_primes.append(prim) if single: return prim return correct_primes
Compute the list of prime polynomials for the given generator and galois field characteristic exponent.
355,709
def __AddEntryType(self, entry_type_name, entry_schema, parent_name): entry_schema.pop(, None) description = % parent_name schema = { : entry_type_name, : , : description, : { : { : , ...
Add a type for a list entry.
355,710
def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None, spoiler_text=None, language=None, idempotency_key=None, content_type=None, scheduled_at=None, poll=None, untag=False): user_id = self.__get_logged_in_id() ...
Helper function - acts like status_post, but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden. Set `untag` to True if you want the reply to only go to the user you are replying to, removing...
355,711
def distance_between(self, string, start, end): count = 0 started = False for line in string.split("\n"): if self.scan_line(line, start) and not started: started = True if self.scan_line(line, end): return count if ...
Returns number of lines between start and end
355,712
def _parse_rnaseq_qualimap_metrics(report_file): from bs4 import BeautifulSoup out = {} parsers = ["Reads alignment", "Reads genomic origin", "Transcript coverage profile"] with open(report_file) as in_handle: root = BeautifulSoup(in_handle.read(), "html.parser") for table in root.find_...
Extract useful metrics from the qualimap HTML report file.
355,713
def newDocNodeEatName(self, doc, name, content): if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlNewDocNodeEatName(doc__o, self._o, name, content) if ret is None:raise treeError() __tmp = xmlNode(_obj=ret) return __tmp
Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by using xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNo...
355,714
def update(self): con = self.subpars.pars.control self(con.eqi2*con.tind)
Update |KI2| based on |EQI2| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqi2(1.0) >>> tind.value = 10.0 >>> derived.ki2.update() >>> derived.ki2 ki2(10.0)
355,715
def mmap_key(metric_name, name, labelnames, labelvalues): labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
Format a key for use in the mmap file.
355,716
def get_perm_model(): try: return django_apps.get_model(settings.PERM_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("PERM_MODEL must be of the form ") except LookupError: raise ImproperlyConfigured( "PERM_MODEL refers to model that has no...
Returns the Perm model that is active in this project.
355,717
def pre_save(self, model_instance, add): file = getattr(model_instance, self.attname) if file and not file._committed: image_file = file if self.resize_source_to: file.seek(0) image_file = processors.process(file, self.resize_source_to) ...
Process the source image through the defined processors.
355,718
def _write(self, content, mode, encoding=None, linesep=False): makedirs(self.path) try: encoding = encoding or ENCODING if "b" not in mode: try: content = str(content) except: pass if...
Handles file writes.
355,719
def asfactor(self): for colname in self.names: t = self.types[colname] if t not in {"bool", "int", "string", "enum"}: raise H2OValueError("Only or are allowed for " "asfactor(), got %s:%s " % (colname, t)) fr = H2OFra...
Convert columns in the current frame to categoricals. :returns: new H2OFrame with columns of the "enum" type.
355,720
def storage_factory(storage_service, trajectory=None, **kwargs): if in kwargs and storage_service is None: filename = kwargs[] _, ext = os.path.splitext(filename) if ext in (, , , , , , ): storage_service = HDF5StorageService else: raise ValueError( % ...
Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :param kwargs: Arguments passed to the storage service :retur...
355,721
def zero_extend(self, new_length): si = self.copy() si._bits = new_length return si
Unary operation: ZeroExtend :param new_length: New length after zero-extension :return: A new StridedInterval
355,722
def dict_merge(self, merge_to, merge_in): for key, value in merge_in.items(): if isinstance(value, dict): self.dict_merge(merge_to[key], value) continue merge_to[key] = copy.copy(value)
Recursively merges two dicts Overwrites any non-dictionary items merge_to <- merge_in Modifies merge_to dictionary @param merge_to: Base dictionary to merge into @param merge_in: Dictionary that may overwrite elements in merge_in
355,723
def configure_plugin(self, name, options): url = self._url(, name) data = options if isinstance(data, dict): data = [.format(k, v) for k, v in six.iteritems(data)] res = self._post_json(url, data=data) self._raise_for_status(res) return True
Configure a plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. options (dict): A key-value mapping of options Returns: ``True`` if successful
355,724
def make_outpoint(tx_id_le, index, tree=None): if in riemann.get_current_network_name(): return tx.DecredOutpoint(tx_id=tx_id_le, index=utils.i2le_padded(index, 4), tree=utils.i2le_padded(tree, 1)) return tx.Outpoint(tx_id=tx_id_le,...
byte-like, int, int -> Outpoint
355,725
def load_remote_trajectory(url, format=None): from urllib import urlretrieve filename, headers = urlretrieve(url) load_trajectory(filename, format)
Load a trajectory file from a remote location specified by *url*. .. seealso:: load_remote_system
355,726
def dfsmooth (window, df, ucol, k=None): import pandas as pd if k is None: k = window.size conv = lambda q, r: np.convolve (q, r, mode=) w = df[ucol] ** -2 invcw = 1. / conv (w, window) res = {} for col in df.columns: if col == ucol: res[col] = np.s...
Smooth a :class:`pandas.DataFrame` according to a window, weighting based on uncertainties. Arguments are: window The smoothing window. df The :class:`pandas.DataFrame`. ucol The name of the column in *df* that contains the uncertainties to weight by. k = None If ...
355,727
def get_service_details(self, service_id): content = self._fetch("/service/%s/details" % service_id) return FastlyService(self, content)
List detailed information on a specified service.
355,728
def getProcList(self, fields=(, , ,), threads=False, **kwargs): field_list = list(fields) for key in kwargs: col = re.sub(, , key) if not col in field_list: field_list.append(col) pinfo = self.parseProcCmd(field_list, threads) ...
Execute ps command with custom output format with columns columns from fields, select lines using the filters defined by kwargs and return result as a nested list. The Standard Format Specifiers from ps man page must be used for the fields parameter. @param fi...
355,729
def from_dict(cls, d): m = Molecule.from_dict(d[]) return cls(m, d[])
As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information.
355,730
def zip_dir(zip_name, source_dir,rename_source_dir=False): src_path = Path(source_dir).expanduser().resolve() with ZipFile(zip_name, , ZIP_DEFLATED) as zf: for file in src_path.rglob(): path_in_zip = str(file.relative_to(src_path.parent)) if rename_source_dir != False: ...
https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory
355,731
def get_farthest_entries(self, type_measurement): farthest_entity1 = None; farthest_entity2 = None; farthest_distance = 0; for i in range(0, len(self.entries)): candidate1 = self.entries[i]; for j in range(i + 1, l...
! @brief Find pair of farthest entries of the node. @param[in] type_measurement (measurement_type): Measurement type that is used for obtaining farthest entries. @return (list) Pair of farthest entries of the node that are represented by list.
355,732
def _guess_header(info): value = "group" if "metadata" in info: if info["metadata"]: return ",".join(map(str, info["metadata"].keys())) return value
Add the first group to get report with some factor
355,733
def to_html_(self) -> str: try: renderer = pytablewriter.HtmlTableWriter data = self._build_export(renderer) return data except Exception as e: self.err(e, "Can not convert data to html")
Convert the main dataframe to html :return: html data :rtype: str :example: ``ds.to_html_()``
355,734
def update(self): res = super(BipartiteGraph, self).update() max_v = None min_v = float("inf") for r in self.reviewers: max_v = max(max_v, r.anomalous_score) min_v = min(min_v, r.anomalous_score) width = max_v - min_v if width: ...
Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The weight is calculated by the manner in :class:`ria.biparti...
355,735
def decrypt_file(self, filename): if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return if self.vault_password is None: print "ENV Variable PYANSI_VAULT_PASSWORD not set" return if not self.is_fil...
Decrypt File Args: filename: Pass the filename to encrypt. Returns: No return.
355,736
def get_attrs_to_paths(schema, attrs_to_paths=None, path=None): attrs_to_paths = attrs_to_paths or {} tag = schema[0] if len(schema) == 1: _insert_attr_path(attrs_to_paths, tag, "/".join(path + [tag])) else: for elem in schema[1:]: if isinstance(elem, dict): ...
Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps attribute names to the simplified XPaths needed to retrieve them, e.g.,:: >>> {'object_identifier_type': 'object_identifier/object_identifier_type', 'object_identifier_value': 'object_identif...
355,737
def blast(args): task_choices = ("blastn", "blastn-short", "dc-megablast", \ "megablast", "vecscreen") p = OptionParser(blast.__doc__) p.set_align(pctid=0, evalue=.01) p.add_option("--wordsize", type="int", help="Word size [default: %default]") p.add_option("--best", default...
%prog blast ref.fasta query.fasta Calls blast and then filter the BLAST hits. Default is megablast.
355,738
def install(): from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer)
Install the import hook to load extensions from the app Lib folder. Like imports but leaves it in the meta_path, thus it is slower.
355,739
def transform_conf_module(cls): global CONF_NODE if cls.name == : cls._locals.update(cls.locals[][0].locals) CONF_NODE = cls CONF_LOCALS.update(cls.locals)
Transform usages of the conf module by updating locals.
355,740
def get_all_deferred_code_breakpoints(self): result = [] for pid, deferred in compat.iteritems(self.__deferredBP): for (label, (action, oneshot)) in compat.iteritems(deferred): result.add( (pid, label, action, oneshot) ) return result
Returns a list of deferred code breakpoints. @rtype: tuple of (int, str, callable, bool) @return: Tuple containing the following elements: - Process ID where to set the breakpoint. - Label pointing to the address where to set the breakpoint. - Action callback for...
355,741
def _create_json(self): data_json = { "rclass": "virtual", "key": self.name, "description": self.description, "packageType": self.packageType, "repositories": self._repositories, "notes": self.notes, } return data_...
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
355,742
def claim(self, ttl, grace, count=None): if count is None: qs = "" else: qs = "?limit=%s" % count uri = "/%s%s" % (self.uri_base, qs) body = {"ttl": ttl, "grace": grace, } resp, resp_body = self.api.method_post(uri,...
Claims up to `count` unclaimed messages from this queue. If count is not specified, the default is to claim 10 messages. The `ttl` parameter specifies how long the server should wait before releasing the claim. The ttl value MUST be between 60 and 43200 seconds. The `grace` parameter i...
355,743
def find_shows_by_related(self, show_id, count=20): url = params = { : self.client_id, : show_id, : count } r = requests.get(url, params=params) check_error(r) return r.json()
doc: http://open.youku.com/docs/doc?id=63
355,744
def update_company(self, company): if not isinstance(company, dict): raise AttributeError() method, url = get_URL() payload = { : self.config.get(), : self.session.cookies.get() } payload.update(company) res = getattr(...
Update company settings :param company: updated settings :type company: ``dict`` :rtype: ``bool``
355,745
def get_table_content(self, table): result = [[]] cols = table.cols for cell in self.compute_content(table): if cols == 0: result.append([]) cols = table.cols cols -= 1 result[-1].append(cell) while len...
trick to get table content without actually writing it return an aligned list of lists containing table cells values as string
355,746
def _get_pubkey_hash(cert): sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest() return _pretty_hex(sha_hash)
Returns the sha1 hash of the modulus of a public key in a cert Used for generating subject key identifiers
355,747
def get_properties_by_type(self, type, recursive=True, parent_path=""): if parent_path: parent_path += "." if isinstance(type, str): if type == "*": type = set(MAPPING_NAME_TYPE.keys()) - set(["nested", "multi_field", "multifield"]) else: ...
Returns a sorted list of fields that match the type. :param type the type of the field "string","integer" or a list of types :param recursive recurse to sub object :returns a sorted list of fields the match the type
355,748
def as_dict(self): return dict((f, self[i]) for f, i in self.__field_positions.items())
Returns this Record as a dictionary using the field names as keys :return: dict
355,749
def clean_source_files(self): self.build_source_files.file(File.BSFILE.SOURCESCHEMA).remove() self.build_source_files.file(File.BSFILE.SCHEMA).remove() self.commit()
Remove the schema.csv and source_schema.csv files
355,750
def remove_all_containers(self, stop_timeout=10, list_only=False): containers = [(container[], container[]) for container in self.containers(all=True)] running_containers = [c_id for c_id, status in containers if ...
First stops (if necessary) and them removes all containers present on the Docker instance. :param stop_timeout: Timeout to stopping each container. :type stop_timeout: int :param list_only: When set to ``True`` only lists containers, but does not actually stop or remove them. :type list...
355,751
def send_error_email(subject, message, additional_recipients=None): recipients = _email_recipients(additional_recipients) sender = email().sender send_email( subject=subject, message=message, sender=sender, recipients=recipients )
Sends an email to the configured error email, if it's configured.
355,752
def get_vlan_brief_output_unprovisioned_vlans_count(self, **kwargs): config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief output = ET.SubElement(get_vlan_brief, "output") unprovisioned_vlans_count = ET.SubElement(output, "un...
Auto Generated Code
355,753
def get_historical_output(self, assessment, options): responseFormat=None if options and in options and options[] is not None: responseFormat = options[] options[] = None url = + str(assessment) + + urllib.parse.urlencode(options) response = self.http...
To get output of a historical Assessment :param assessment: string :param options: dict
355,754
def load_object(self, value): if value is None: return None if value.startswith(b): try: return pickle.loads(value[1:]) except pickle.PickleError: return None try: return int(value) except ValueError...
The reversal of :meth:`dump_object`. This might be callde with None.
355,755
def full_url(url=, domain=None, protocol=): if domain is None: from django.contrib.sites.models import Site domain = Site.objects.get_current().domain return f
Prepend protocol (default to https) and domain name (default from the Site framework) to an url
355,756
def source_loader(self, source_paths, create_missing_tables=True): if not isinstance(source_paths, Iterable) or len(source_paths) < 3: raise TypeError( % source_paths) self.native_language = self.languages = [] self.templates = [] self.tables = {} s...
Load source from 3 csv files. First file should contain global settings: * ``native_lagnauge,languages`` header on first row * appropriate values on following rows Example:: native_lagnauge,languages ru,ru ,en Second file should contain ...
355,757
def raise_402(instance, msg=None): instance.response.status = 402 if msg: instance.response.body_raw = {: msg} raise ResponseException(instance.response)
Abort the current request with a 402 (Payment Required) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.R...
355,758
def save_state(self): settings = QtCore.QSettings() settings.setValue( , self.default_template_radio.isChecked()) settings.setValue( , self.template_combo.itemData(self.template_combo.currentIndex())) settings.setValue( ...
Store the options into the user's stored session info. .. versionadded: 4.3.0
355,759
def quadraticEval(a, b, c, x): return a*(x**2) + b*x + c
given all params return the result of quadratic equation a*x^2 + b*x + c
355,760
def start(self, input_data=None): if input_data: raise ValueError("Passing input through container's stdin is not supported") if not self.is_created(): raise RuntimeError("Container does not exist. Cannot start this container") real_container = self.d...
Calls Docker API to start the container. The container must be created at the first place to run. It waits for the container to complete, fetches both stdout and stderr logs and returns through the given streams. Parameters ---------- input_data Optional. Input data ...
355,761
def connect(self): if self.is_connected(): raise tornado.gen.Return(True) cb1 = self._read_callback cb2 = self._close_callback self.__callback_queue = collections.deque() self._reply_list = [] self.__reader = hiredis.Reader(replyError=ClientError) ...
Connects the client object to redis. It's safe to use this method even if you are already connected. Note: this method is useless with autoconnect mode (default). Returns: a Future object with True as result if the connection was ok.
355,762
def chunks(stream, size=None): t know why this isnlines if size == : for item in stream: yield item return if size is None: size = MAXBUF while True: buf = stream.read(size) if not buf: return yield buf
Returns a generator of chunks from the `stream` with a maximum size of `size`. I don't know why this isn't part of core Python. :Parameters: stream : file-like object The stream to fetch the chunks from. Note that the stream will not be repositioned in any way. size : int | 'lines'; default: null ...
355,763
def footer(self): return self.footer_left(on=False), self.footer_center(on=False), \ self.footer_right(on=False)
Returns the axis instance where the footer will be printed
355,764
def transferring_item(self, item, increment_amt=1): self.cnt += increment_amt percent_done = int(float(self.cnt) / float(self.total) * 100.0) if KindType.is_project(item): details = else: details = os.path.basename(item.path) self.progress_bar.up...
Update progress that item is about to be transferred. :param item: LocalFile, LocalFolder, or LocalContent(project) that is about to be sent. :param increment_amt: int amount to increase our count(how much progress have we made)
355,765
def create_lead(self, first_name, last_name, email=None, position=None, company=None, company_industry=None, company_size=None, confidence_score=None, website=None, country_code=None, postal_code=None, source=None, linkedin_url=None, phone_...
Create a lead on your account. :param first_name: The first name of the lead to create. Must be defined. :param last_name: The last name of the lead to create. Must be defined. :param email: The email of the lead to create. :param position: The professional position of the le...
355,766
def _reduce_opacity(self, watermark, opacity): if watermark.type() != ImageType.TrueColorMatteType: watermark.type(ImageType.TrueColorMatteType) depth = 255 - int(255 * opacity) watermark.quantumOperator(ChannelType.OpacityChannel, QuOp.MaxQuantumOp, depth)
Returns an image with reduced opacity. Converts image to RGBA if needs. Simple watermark.opacity(65535 - int(65535 * opacity) would not work for images with the Opacity channel (RGBA images). So we have to convert RGB or any other type to RGBA in this case
355,767
def _get_extra(self, attrs, exclude): result = {} for key in attrs.getNames(): if key not in exclude: result[str(key)] = str(attrs[key]) return result
Read the extra properties, taking into account an exclude list
355,768
def uncancel(self): if self.cancelled: logger.debug("Uncancelling {}".format(self)) self.cancelled = False self.save()
Uncancel an EighthScheduledActivity. This does nothing besides unset the cancelled flag and save the object.
355,769
def estimate_assignment_probs(q, trials, cxn, p0=None): from pyquil.quil import Program if p0 is None: p0 = Program() results_i = np.sum(cxn.run(p0 + Program(I(q), MEASURE(q, 0)), [0], trials)) results_x = np.sum(cxn.run(p0 + Program(X(q), MEASURE(q, 0)), [0], trials)) p00 = 1. - res...
Estimate the readout assignment probabilities for a given qubit ``q``. The returned matrix is of the form:: [[p00 p01] [p10 p11]] :param int q: The index of the qubit. :param int trials: The number of samples for each state preparation. :param Union[QVMConnection,QPUConnection...
355,770
def Gharagheizi_liquid(T, M, Tb, Pc, omega): r Pc = Pc/1E5 B = 16.0407*M + 2.*Tb - 27.9074 A = 3.8588*M**8*(1.0045*B + 6.5152*M - 8.9756) kl = 1E-4*(10.*omega + 2.*Pc - 2.*T + 4. + 1.908*(Tb + 1.009*B*B/(M*M)) + 3.9287*M**4*B**-4 + A*B**-8) return kl
r'''Estimates the thermal conductivity of a liquid as a function of temperature using the CSP method of Gharagheizi [1]_. A convoluted method claiming high-accuracy and using only statistically significant variable following analalysis. Requires temperature, molecular weight, boiling temperature and c...
355,771
def print_device_list(self, device_list=None): dev_list = device_list if device_list is not None else self.get_all_devices_in_portal() for dev in dev_list: print(.format( dev[][][], dev[], dev[]\ if...
Optional parameter is a list of device objects. If omitted, will just print all portal devices objects.
355,772
def render_to(self, path, template, **data): html = self.render(template, **data) with open(path, ) as f: f.write(html.encode(charset))
Render data with template and then write to path
355,773
def create_bootstrap_tour(self, name=None): if not name: name = "default" new_tour = ( ) self._tour_steps[name] = [] self._tour_steps[name].append(new_tour)
Creates a Bootstrap tour for a website. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to.
355,774
def move_drive_to_H(slh, which=None, expand_simplify=True): r = \Op{L}_i - \alpha_i \\ \Op{H} &\longrightarrow \Op{H} if which is None: which = [] scalarcs = [] for jj, L in enumerate(slh.Ls): if not which or jj in which: scalarcs.append(-get_coeffs...
r'''Move coherent drives from the Lindblad operators to the Hamiltonian. For the given SLH model, move inhomogeneities in the Lindblad operators (resulting from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the Hamiltonian. This exploits the invariance of the Lindblad master equat...
355,775
def angle(self, other): return math.acos(self.dot(other) / (self.magnitude() * other.magnitude()))
Return the angle to the vector other
355,776
def get_glyph(self, char): try: return self._glyphs[char] except KeyError: glyph = self._font_file.get_glyph(self._size, self._content_scale, char, self._flags) self._glyphs[char] = glyph return glyph
Retrieves a :class:`Glyph` that renders the given character. :param char: the character (a string)
355,777
def locally_linear_embedding(geom, n_components, reg=1e-3, eigen_solver=, random_state=None, solver_kwds=None): if geom.X is None: raise ValueError("Must pass data matrix X to Geometry") if geom.adjacency_matrix is None: geom.compute_...
Perform a Locally Linear Embedding analysis on the data. Parameters ---------- geom : a Geometry object from megaman.geometry.geometry n_components : integer number of coordinates for the manifold. reg : float regularization constant, multiplies the trace of the local covariance ...
355,778
def get_grade_systems_by_query(self, grade_system_query): and_list = list() or_list = list() for term in grade_system_query._query_terms: if in grade_system_query._query_terms[term] and in grade_system_query._query_terms[term]: and_list.ap...
Gets a list of ``GradeSystem`` objects matching the given grade system query. arg: grade_system_query (osid.grading.GradeSystemQuery): the grade system query return: (osid.grading.GradeSystemList) - the returned ``GradeSystemList`` raise: NullArgument - ``gra...
355,779
def get_sec2gos(sortobj): sec_gos = [] for section_name, nts in sortobj.get_desc2nts_fnc(hdrgo_prt=True)[]: sec_gos.append((section_name, set(nt.GO for nt in nts))) return cx.OrderedDict(sec_gos)
Initialize section_name2goids.
355,780
def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None): total_seconds = (x[-1] - x[0]).total_seconds() if total_seconds <= 86400 * 1 * 3: return plot_one_day(x, y, xlabel, ylabel, title, ylim) elif total_seconds <= 86400 * 7 * 2: return plot_one_week(x, y, xlabel, yla...
A universal function plot arbitrary time series data.
355,781
def to_file(self, path, precision=): table_info = self.get_table_info() def dump_rows(rows): if len(rows) > 1: for row in rows: csv_writer.writerow(row) csv_writer.writerow([]) with open(path, ) as _f: csv_wri...
Create a CSV report of the trackables :param path: path to file :param precision: numeric string formatter
355,782
def skus(self): api_version = self._get_api_version() if api_version == : from .v2017_06_01.operations import SkusOperations as OperationClass elif api_version == : from .v2017_10_01.operations import SkusOperations as OperationClass elif api_version == :...
Instance depends on the API version: * 2017-06-01: :class:`SkusOperations<azure.mgmt.storage.v2017_06_01.operations.SkusOperations>` * 2017-10-01: :class:`SkusOperations<azure.mgmt.storage.v2017_10_01.operations.SkusOperations>` * 2018-02-01: :class:`SkusOperations<azure.mgmt.storage.v...
355,783
def call(args, stdout=None, stderr=None, stdin=None, daemonize=False, preexec_fn=None, shell=False, cwd=None, env=None): stream = lambda s, m: s is None and os.open(os.devnull, m) or s stdout = stream(stdout, os.O_WRONLY) stderr = stream(stderr, os.O_WRONLY) stdin = stream(stdin, os.O_RDON...
Run an external command in a separate process and detach it from the current process. Excepting `stdout`, `stderr`, and `stdin` all file descriptors are closed after forking. If `daemonize` is True then the parent process exits. All stdio is redirected to `os.devnull` unless specified. The `preexec_fn`, `sh...
355,784
def check_bounds(self): if not (self.camera_bounds == None): if self.__pan.X < self.camera_bounds.Left: self.__pan[0] = self.camera_bounds.Left if self.__pan.X > self.camera_bounds.Right: self.__pan[0] = self.camera_bounds.Right if s...
Make sure the camera is not outside if its legal range.
355,785
def command_start(self, daemonize=False): if daemonize: safe_makedirs(self.logfile, self.pidfile) flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile, logfile=self.logfile, daemonize=daemonize, cwd=self.cwd, umask=self.umask, **self....
Start a server:: ./manage.py flup:start [--daemonize]
355,786
def compute(datetimes, to_np=None): if not isinstance(datetimes, (list, tuple, np.ndarray)): raise TypeError() if isinstance(datetimes[0], numbers.Number): items = len(datetimes) elif isinstance(datetimes[0], (list, tuple, np.ndarray)): items = le...
Computes the provided date/time components into CDF epoch value(s). For CDF_EPOCH: For computing into CDF_EPOCH value, each date/time elements should have exactly seven (7) components, as year, month, day, hour, minute, second and millisecond, in a list. For exam...
355,787
def from_raw_seed(cls, raw_seed): signing_key = ed25519.SigningKey(raw_seed) verifying_key = signing_key.get_verifying_key() return cls(verifying_key, signing_key)
Generate a :class:`Keypair` object via a sequence of bytes. Typically these bytes are random, such as the usage of :func:`os.urandom` in :meth:`Keypair.random`. However this class method allows you to use an arbitrary sequence of bytes, provided the sequence is 32 bytes long. :...
355,788
def save_as(self, new_filename): xfile._save_file( self._filename, self._workbookTree, new_filename)
Save our file with the name provided. Args: new_filename: New name for the workbook file. String. Returns: Nothing.
355,789
def _rsplit(expr, pat=None, n=-1): return _string_op(expr, RSplit, output_type=types.List(types.string), _pat=pat, _n=n)
Split each string in the Series/Index by the given delimiter string, starting at the end of the string and working to the front. Equivalent to str.rsplit(). :param expr: :param pat: Separator to split on. If None, splits on whitespace :param n: None, 0 and -1 will be interpreted as return all split...
355,790
def Client(api_version, *args, **kwargs): neutron_client = utils.get_client_class( API_NAME, api_version, API_VERSIONS, ) return neutron_client(*args, **kwargs)
Return an neutron client. @param api_version: only 2.0 is supported now
355,791
def is_image(f, types=(, , ), set_content_type=True): assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True
Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image'
355,792
def remove_all_gap_columns( components ): seqs = [ list( c.text ) for c in components ] i = 0 text_size = len( seqs[0] ) while i < text_size: all_gap = True for seq in seqs: if seq[i] != : all_gap = False if all_gap: for seq in seqs: del seq[i...
Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex.
355,793
async def iter_lines(self, chunk_size=1024): pending = b async for chunk in self.iter_chunks(chunk_size): lines = (pending + chunk).splitlines(True) for line in lines[:-1]: await yield_(line.splitlines()[0]) pending = lines[-1] if pend...
Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there.
355,794
def set_logging_config(log_level, handlers): logging.basicConfig( format=, datefmt=, level=log_level, handlers=handlers)
Set python logging library config. Run this ONCE at the start of your process. It formats the python logging module's output. Defaults logging level to INFO = 20)
355,795
def _create_min_max_boundaries( max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE): bucket_boundaries = [] x = min_boundary while x < max_length: bucket_boundaries.append(x) x = max(x + 1, int(x * boundary_scale)) buckets_min = [0] + bucket_boundaries buckets_max ...
Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_max = [4, 8, 16, 24, 25] Args: max_length: The maximum length of example in dataset. min_boundary: Minimu...
355,796
def glir(self): canvas = get_current_canvas() if canvas is None: msg = ("If you want to use gloo without vispy.app, " + "use a gloo.context.FakeCanvas.") raise RuntimeError( + msg) return canvas.context.glir
The GLIR queue corresponding to the current canvas
355,797
def base_url(klass, space_id, webhook_id, resource_id=None): return "spaces/{0}/webhooks/{1}/calls/{2}".format( space_id, webhook_id, resource_id if resource_id is not None else )
Returns the URI for the webhook call.
355,798
def create(self, max_wait=180, **kwargs): self.service.create(async=True, create_keys=False) while self._create_in_progress() and max_wait > 0: time.sleep(1) max_wait -= 1 cfg = self.service._get_service_config() self.service.s...
Create an instance of the Predix Cache Service with they typical starting settings. :param max_wait: service is created asynchronously, so will only wait this number of seconds before giving up.
355,799
def surface_area(self): r return [self.atomic_sa(i) for i in range(len(self.rads))]
r"""Calculate all atomic surface area. :rtype: [float]