Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
359,600
def resize(self, logical_size): if not isinstance(logical_size, baseinteger): raise TypeError("logical_size can only be an instance of type baseinteger") progress = self._call("resize", in_p=[logical_size]) progress = IProgress(progress) return p...
Starts resizing this medium. This means that the nominal size of the medium is set to the new value. Both increasing and decreasing the size is possible, and there are no safety checks, since VirtualBox does not make any assumptions about the medium contents. Resizing usually ne...
359,601
def format_t_into_dhms_format(timestamp): mins, timestamp = divmod(timestamp, 60) hour, mins = divmod(mins, 60) day, hour = divmod(hour, 24) return % (day, hour, mins, timestamp)
Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s'
359,602
def configure_ckan(m): from ckanapi import RemoteCKAN try: doc = MetapackDoc(m.mt_file, cache=m.cache) except (IOError, MetatabError) as e: err("Failed to open metatab : {}".format(m.mt_file, e)) c = RemoteCKAN(m.ckan_url, apikey=m.api_key) groups = { g[]:g for g in c.action....
Load groups and organizations, from a file in Metatab format
359,603
def call_builder_init(cls, kb_app, sphinx_app: Sphinx): conf_dir = sphinx_app.confdir plugins_dir = sphinx_app.config.kaybee_settings.plugins_dir full_plugins_dir = os.path.join(conf_dir, plugins_dir) if os.path.exists(full_plugins_dir): sys.path.insert(0,...
On builder init event, commit registry and do callbacks
359,604
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): self.samples.append(Sample(name, labels, value, timestamp, exemplar))
Add a sample to the metric. Internal-only, do not use.
359,605
def load_yamlf(fpath, encoding): with codecs.open(fpath, encoding=encoding) as f: return yaml.safe_load(f)
:param unicode fpath: :param unicode encoding: :rtype: dict | list
359,606
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable: def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated(self, *args, **kwargs): if not hasattr(self, attr): raise tp(msg) return func(self, ...
decorator to assert an object has an attribute when run.
359,607
def temporary_file_path(root_dir=None, cleanup=True, suffix=, permissions=None): with temporary_file(root_dir, cleanup=cleanup, suffix=suffix, permissions=permissions) as fd: fd.close() yield fd.name
A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file.
359,608
def set_pwm(self, channel, on, off): self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(LED0_ON_H+4*channel, on >> 8) self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(LED0_OFF_H+4*channel, off >> 8)
Sets a single PWM channel.
359,609
def isRecord(self, db=None): if db is not None: same_db = db == self.context().db if db is None or same_db: col = self.schema().idColumn() with ReadLocker(self.__dataLock): return (col in self.__loaded) and (self.__values[col.name()][0] is no...
Returns whether or not this database table record exists in the database. :return <bool>
359,610
def conjugate_quat(quat): return Quat(-quat.x, -quat.y, -quat.z, quat.w)
Negate the vector part of the quaternion.
359,611
def _cleanlogs(silent=False, log_location="log"): try: print("cleaning up Icetea log directory.") shutil.rmtree(log_location, ignore_errors=silent, onerror=None if silent else _clean_onerror) except OSError as error: print(error)
Cleans up Mbed-test default log directory. :param silent: Defaults to False :param log_location: Location of log files, defaults to "log" :return: Nothing
359,612
def clone(self): new_node = self.__class__(self._name, self._demand) return new_node
Returns a deep copy of self Function clones: * allocation * nodes Returns ------- type Deep copy of self
359,613
def mapPriority(levelno): if levelno <= _logging.DEBUG: return LOG_DEBUG elif levelno <= _logging.INFO: return LOG_INFO elif levelno <= _logging.WARNING: return LOG_WARNING elif levelno <= _logging.ERROR: return LOG_ERR eli...
Map logging levels to journald priorities. Since Python log level numbers are "sparse", we have to map numbers in between the standard levels too.
359,614
def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0): return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
Compute the time-derivative of a Lorentz system.
359,615
def gaus_pdf(x, mean, std): s probability density function. See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_. :param x: point in x-axis :type x: float or numpy.ndarray :param float mean: mean or expectation :param float str: standard deviation :returns: pdf(s) in ...
Gaussian distribution's probability density function. See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_. :param x: point in x-axis :type x: float or numpy.ndarray :param float mean: mean or expectation :param float str: standard deviation :returns: pdf(s) in point **x*...
359,616
async def shutdown(self, force = False, connmark = -1): if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, force, connmark))
Can call without delegate
359,617
def report(self, min_confidence=0, sort_by_size=False, make_whitelist=False): for item in self.get_unused_code( min_confidence=min_confidence, sort_by_size=sort_by_size): print(item.get_whitelist_string() if make_whitelist else item.get_repor...
Print ordered list of Item objects to stdout.
359,618
def load(self, path=None, format=None, schema=None, **options): if format is not None: self.format(format) if schema is not None: self.schema(schema) self.options(**options) if path is not None: if type(path) != str or len(path.strip()) == 0: ...
Loads a data stream from a data source and returns it as a :class`DataFrame`. .. note:: Evolving. :param path: optional string for file-system backed data sources. :param format: optional string for format of the data source. Default to 'parquet'. :param schema: optional :class:`pyspar...
359,619
def messageid_match(self, messageid): if isinstance(messageid, _uuid.UUID): messageid = messageid.hex self.add_match(MESSAGE_ID=messageid)
Add match for log entries with specified `messageid`. `messageid` can be string of hexadicimal digits or a UUID instance. Standard message IDs can be found in systemd.id128. Equivalent to add_match(MESSAGE_ID=`messageid`).
359,620
def _svd(cls, matrix, num_concepts=5): u, s, v = svds(matrix, k=num_concepts) return u, s, v
Perform singular value decomposition for dimensionality reduction of the input matrix.
359,621
def _drawContents(self, currentRti=None): table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti ...
Draws the attributes of the currentRTI
359,622
def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger): cow = configuration.get(, False) try: volume = hypervisor.storageVolLookupByPath(image) except libvirt.libvirtError: if os.path.exists(image): pool_path = os.path.dirname(image) ...
Disk image cloning. Given an original disk image it clones it into a new one, the clone will be created within the storage pool. The following values are set into the disk XML configuration: * name * target/path * target/permission/label * backingStore/path if copy on write is enabled
359,623
def _set_instance_proxies(self): proxies = {} if self.tor_routing: proxies = { "http": "socks5://127.0.0.1:9050", "https": "socks5://127.0.0.1:9050" } elif self.proxy_list: try: with open(self.proxy_list...
Set the proxies to any of the following: Proxy List - a list of proxies to choose randomly from for each request. Read from file. TOR - a dict of socks5 and the TOR service default 9050 that will be used Else, No proxies - an empty dict will be used.
359,624
def oauth_client_create(self, name, redirect_uri, **kwargs): params = { "label": name, "redirect_uri": redirect_uri, } params.update(kwargs) result = self.client.post(, data=params) if not in result: raise UnexpectedResponseError(, ...
Make a new OAuth Client and return it
359,625
def t_ATOM(self, t): r t.type = LDLfLexer.reserved.get(t.value, ) return t
r'[a-zA-Z_][a-zA-Z_0-9]*
359,626
async def _process_auth_form(self, html: str) -> (str, str): p = AuthPageParser() p.feed(html) p.close() form_data = dict(p.inputs) form_url = p.url form_data[] = self.login form_data[] = self.password if p.message: ...
Parsing data from authorization page and filling the form and submitting the form :param html: html page :return: url and html from redirected page
359,627
def getMonitorById(self, monitorId): url = self.baseUrl url += "getMonitors?apiKey=%s&monitors=%s" % (self.apiKey, monitorId) url += "&noJsonCallback=1&format=json" success, response = self.requestApi(url) if success: status = response.get().get()[0].get() ...
Returns monitor status and alltimeuptimeratio for a MonitorId.
359,628
def add_version_tracking(self, info_id, version, date, command_line=): other_line = .format( info_id, version, date, command_line) self.other_dict[info_id] = other_line return
Add a line with information about which software that was run and when to the header. Arguments: info_id (str): The id of the info line version (str): The version of the software used date (str): Date when software was run command_line (str): The...
359,629
def _validate_doc_refs_helper(self, env, doc, loc, type_context=None): for match in doc_ref_re.finditer(doc): tag = match.group() val = match.group() if tag == : if in val: type_name, field_name = val.split(, 1) ...
Validates that all the documentation references in a docstring are formatted properly, have valid values, and make references to valid symbols. Args: env (dict): The environment of defined symbols. doc (str): The docstring to validate. lineno (int): The line ...
359,630
def raise_api_exceptions(function, *args, **kwargs): try: return_value = function(*args, **kwargs) except errors.HTTPException as exc: if exc._raw.status_code != 400: raise try: data = exc._raw.json() assert len(data) == 2 retu...
Raise client side exception(s) when present in the API response. Returned data is not modified.
359,631
def _list_records(self, rtype=None, name=None, content=None): opts = {: self._domain} if rtype is not None: opts[] = rtype.upper() if name is not None: opts[] = self._full_name(name) if content is not None: opts[] = content opts.update...
list all records :param str rtype: type of record :param str name: name of record :param mixed content: value of record :return list: list of found records :raises Exception: on error
359,632
def get_fault(fault_id=None): counts = __get_table_limits() result = None id_ = 0 try: if isinstance(fault_id, int): id_ = fault_id elif isinstance(fault_id, float): print() id_ = round(fault_id) else: id_ = random.randint(1,...
Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit with different keywords.
359,633
def start_site(name): *My Test Site ps_cmd = [, r"".format(name)] cmd_ret = _srvmgr(ps_cmd) return cmd_ret[] == 0
Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site'
359,634
def records(self): return [self._records[i] for i in range(len(self._records))]
Returns a list of records in SORT_KEY order
359,635
def groups_set_description(self, room_id, description, **kwargs): return self.__call_api_post(, roomId=room_id, description=description, kwargs=kwargs)
Sets the description for the private group.
359,636
def tree(self): from cmdtree.tree import CmdTree if self._tree is None: self._tree = CmdTree() return self._tree
:rtype: cmdtree.tree.CmdTree
359,637
def name(cls): if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column_type, nullable=False, unique=True) else: return Column(...
The URL name of this object, unique across all instances of this model
359,638
def coordination_geometry_symmetry_measures_sepplane_optim(self, coordination_geometry, points_perfect=None, nb_set=None, optimization=None): csms = [] permutations = []...
Returns the symmetry measures of a given coordination_geometry for a set of permutations depending on the permutation setup. Depending on the parameters of the LocalGeometryFinder and on the coordination geometry, different methods are called. :param coordination_geometry: Coordination geometry...
359,639
def decrypt_var(source, passphrase=None): cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(), passphrase_file(passphrase)] return stderr_with_input(flatten(cmd), source)
Attempts to decrypt a variable
359,640
def attach(self, name, data=None, maintype=None, subtype=None, inline=False, filename=None, filename_charset=, filename_language=, encoding=None): self._dirty = True if not maintype: maintype, guessed_encoding = guess_type(name) encoding = encoding or guessed_encoding if not maintype: maintype,...
Attach a file to this message. :param name: Path to the file to attach if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the file to attach, or None if the data is to be read from the file pointed to by the ``name`` argument :type data: bytes or a fil...
359,641
def element_should_exist(self, json_string, expr): value = self.select_elements(json_string, expr) if value is None: raise JsonValidatorError( % expr)
Check the existence of one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression. *DEPRECATED* JSON Select query language is outdated and not supported any more. Use other keywords of this library to query JSON. *Args:*\n _json_string_ - JSON string;\n _e...
359,642
def gregorian_to_julian(day): before_march = 1 if day.month < MARCH else 0 month_index = day.month + MONTHS_PER_YEAR * before_march - MARCH years_elapsed = day.year - JULIAN_START_YEAR - before_march total_days_in_previous_months = (153 * month_index + 2) // 5 t...
Convert a datetime.date object to its corresponding Julian day. :param day: The datetime.date to convert to a Julian day :returns: A Julian day, as an integer
359,643
def map_ontologies(): if request.method == : return {} response = request.body.read().decode() body = json.loads(response) stmts_json = body.get() stmts = stmts_from_json(stmts_json) om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False) om.map_statements() ret...
Run ontology mapping on a list of INDRA Statements.
359,644
def api_call(endpoint, args, payload): headers = {: } url = .format(args[], endpoint) attempt = 0 resp = None while True: try: attempt += 1 resp = requests.post( url, data=json.dumps(payload), headers=headers, verify=args[] ...
Generic function to call the RO API
359,645
def copyModel(mdl): copyNum = _modelCopyMap[mdl] _modelCopyMap[mdl] += 1 mdlCopy = type(mdl.__name__ + + str(copyNum), mdl.__bases__, copy.deepcopy(dict(mdl.__dict__))) mdlCopy.FIELDS = [field.copy() for field in mdl.FIELDS] mdlCopy.INDEXED_FIELDS = [str(idxField) for idxField in mdl.INDEXED_...
copyModel - Copy this model, and return that copy. The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members, and the INDEXED_FIELDS array. This is useful for converting, like changing field types or whatever, where you can load from one mod...
359,646
def raw(self, drop_collections = False): base_df = self._data if drop_collections is True: out_df = self._drop_collections(base_df) else: out_df = base_df return out_df
Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
359,647
def _set_bang_to_py_ast(ctx: GeneratorContext, node: SetBang) -> GeneratedPyAST: assert node.op == NodeOp.SET_BANG val_temp_name = genname("set_bang_val") val_ast = gen_py_ast(ctx, node.val) target = node.target assert isinstance( target, (HostField, Local, VarRef) ), f"invalid se...
Return a Python AST Node for a `set!` expression.
359,648
def list_streams(self): path = .format(self._instance) response = self._client.get_proto(path=path) message = rest_pb2.ListStreamsResponse() message.ParseFromString(response.content) streams = getattr(message, ) return iter([Stream(stream) for s...
Returns the existing streams. Streams are returned in lexicographical order. :rtype: ~collections.Iterable[.Stream]
359,649
def stop(self): with self.condition: self.running = False self.condition.notify_all()
Force the next() method to return while in another thread. The return value of next() will be None.
359,650
def to_dict(self, include_meta=False): result = super(JackalDoc, self).to_dict(include_meta=include_meta) if include_meta: source = result.pop() return {**result, **source} else: return result
Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.
359,651
def wait(self): try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: self.stop() raise
Wait for all running containers to stop.
359,652
async def process_activity(self, logic: Callable): while True: msg = input() if msg is None: pass else: self._next_id += 1 activity = Activity(text=msg, channel_id=, ...
Begins listening to console input. :param logic: :return:
359,653
def create_log2fc_bigwigs(matrix, outdir, args): call("mkdir -p {}".format(outdir), shell=True) genome_size_dict = args.chromosome_sizes outpaths = [] for bed_file in matrix[args.treatment]: outpath = join(outdir, splitext(basename(bed_file))[0] + "_log2fc.bw") outpaths.appen...
Create bigwigs from matrix.
359,654
def ellipticity2phi_q(e1, e2): phi = np.arctan2(e2, e1)/2 c = np.sqrt(e1**2+e2**2) if c > 0.999: c = 0.999 q = (1-c)/(1+c) return phi, q
:param e1: :param e2: :return:
359,655
def add_event(self, source, reference, event_title, event_type, method=, description=, bucket_list=[], campaign=, confidence=, date=None): ...
Adds an event. If the event name already exists, it will return that event instead. Args: source: Source of the information reference: A reference where more information can be found event_title: The title of the event event_type: The type of event. See y...
359,656
def add(self, text, checked=False, sort=None): if self.parent is None: raise exception.InvalidException() node = self.parent.add(text, checked, sort) self.indent(node) return node
Add a new sub item to the list. This item must already be attached to a list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting.
359,657
def find(self, name, resolved=True): qref = qualify(name, self.schema.root, self.schema.tns) query = BlindQuery(qref) result = query.execute(self.schema) if result is None: log.error(, name) return None if resolved: r...
Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} ...
359,658
async def get_json( self, force: bool=False, silent: bool=False, cache: bool=True, ) -> Any: if cache and self._cached_json is not sentinel: return self._cached_json if not (force or self.is_json): return None data = await self._load_json_data() ...
Parses the body data as JSON and returns it. Arguments: force: Force JSON parsing even if the mimetype is not JSON. silent: Do not trigger error handling if parsing fails, without this the :meth:`on_json_loading_failed` will be called on error. ...
359,659
def _call(self, x): result = 0 for i in range(0, self.domain.size - 1): result += (self.scale * (x[i + 1] - x[i] ** 2) ** 2 + (x[i] - 1) ** 2) return result
Return ``self(x)``.
359,660
def spatial_firing_rate(self,label_x=,label_y=,bins=None,resolution=1.0,geometry=None,weight_function=None,normalize_time=True,normalize_n=False,start_units_with_0=True): if bool(self): if type(bins) is tuple: if type(bins[0]) is int: bins_x = self.spike_...
`bins` can be either a number of bins (has to be int) or a list of edges. `bins` can be a tuple (for x and y respectively). imshow(s.spatial_firing_rate(weight_function=lambda x: (x[:,1]>0.5)*(x[:,1]<0.6)))
359,661
def _gather_buffer_space(): if HAS_PSUTIL and psutil.version_info >= (0, 6, 0): total_mem = psutil.virtual_memory().total else: import platform import salt.grains.core return max([total_mem * 0.05, 10 << 20])
Gather some system data and then calculate buffer space. Result is in bytes.
359,662
def parse(self): self._options, self._arguments = self._parse_args() self._arguments = self._arguments or [] if not self._validate_options(self._options): raise IllegalConfiguration() self._run_conf = self._create_run_config(self._options) config = self._c...
Parse the configuration. If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all error codes to check and disregards any error code related configurations from the configuration files.
359,663
def rename(self, req, parent, name, newparent, newname): self.reply_err(req, errno.EROFS)
Rename a file Valid replies: reply_err
359,664
def add_prefix(prefix, s): "Add `prefix` to all unprefixed names in `s`" toks = xpath_lexer.scan(s) toks2 = [_add_prefix(prefix, tok) for tok in toks] ls = [x.value for x in toks2] return .join(ls)
Add `prefix` to all unprefixed names in `s`
359,665
def write_file(path, data, format=True): if format: fs.write_file(path, format_json(data)) else: fs.write_file(path, json.dumps(data))
Write JSON data to file. Arguments: path (str): Destination. data (dict or list): JSON serializable data. format (bool, optional): Pretty-print JSON data.
359,666
def pip_cmd(env, cmd, ignore_activated=False, **kwargs): r cmd = tuple(cmd) dirname = safe_path(env) if not ignore_activated: activated_env = os.environ.get() if hasattr(sys, ): dirname = sys.prefix elif activated_env: dirname = activated_env pip_pa...
r"""Run pip command in given or activated virtual environment. :param env: Virtual environment name. :param cmd: Pip subcommand to run. :param ignore_activated: Ignore activated virtual environment and use given venv instead. By default: False :param \*\*kwargs: Additional keywo...
359,667
def create(cls, name, address, time_to_live=20, update_interval=10, secondary=None, comment=None): json = { : name, : address, : comment, : time_to_live, : update_interval, : secondary if secondary else []} ...
Create a DNS Server element. :param str name: Name of DNS Server :param str address: IP address for DNS Server element :param int time_to_live: Defines how long a DNS entry can be cached before querying the DNS server again (default: 20) :param int update_interval: D...
359,668
def _get_observation(self): di = super()._get_observation() if self.use_camera_obs: camera_obs = self.sim.render( camera_name=self.camera_name, width=self.camera_width, height=self.camera_height, depth=self.cam...
Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information. object-state: requires @self.use_object_obs to be True. contains object-centric information. image: requires @self....
359,669
def to_html(self): if self.align is : if self.style_class is None: self.style_class = else: self.style_class += elif self.align is : if self.style_class is None: self.style_class = else: ...
Render a Cell MessageElement as html :returns: The html representation of the Cell MessageElement :rtype: basestring
359,670
def committors(sources, sinks, msm): if hasattr(msm, ): commits = np.zeros(msm.all_transmats_.shape[:2]) for i, tprob in enumerate(msm.all_transmats_): commits[i, :] = _committors(sources, sinks, tprob) return np.median(commits, axis=0) return _committors(sources, sink...
Get the forward committors of the reaction sources -> sinks. Parameters ---------- sources : array_like, int The set of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder.MarkovStateModel MSM fit to the data. Returns ...
359,671
def plot(self, hist=False, show=False, **kwargs): import matplotlib.pyplot as plt if hist: vals = self._mcpts low = vals.min() high = vals.max() h = plt.hist( vals, bins=int(np.sqrt(len(vals)) + 0.5), ...
Plot the distribution of the UncertainVariable. Continuous distributions are plotted with a line plot and discrete distributions are plotted with discrete circles. Optional -------- hist : bool If true, a histogram is displayed show : bool ...
359,672
def multicolumn_map_expectation(cls, func): if PY3: argspec = inspect.getfullargspec(func)[0][1:] else: argspec = inspect.getargspec(func)[0][1:] @cls.expectation(argspec) @wraps(func) def inner_wrapper(self, column_list, mostly=None, ignore_row_...
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of evaluating truthiness of some condition on a per row basis across a set of columns.
359,673
def from_raw_message(cls, rawmessage): userdata_dict = Userdata(rawmessage[8:22]) return ExtendedSend(rawmessage[2:5], {: rawmessage[6], : rawmessage[7]}, userdata_dict, flags=rawmes...
Create a message from a raw byte stream.
359,674
def netconf_confirmed_commit_source_host(self, **kwargs): config = ET.Element("config") netconf_confirmed_commit = ET.SubElement(config, "netconf-confirmed-commit", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications") source_host = ET.SubElement(netconf_confirmed_commit, "sou...
Auto Generated Code
359,675
def get_lswitch_ids_for_network(self, context, network_id): lswitches = self._lswitches_for_network(context, network_id).results() return [s[] for s in lswitches["results"]]
Public interface for fetching lswitch ids for a given network. NOTE(morgabra) This is here because calling private methods from outside the class feels wrong, and we need to be able to fetch lswitch ids for use in other drivers.
359,676
def _ToString(x): if x is None: return if isinstance(x, six.string_types): return x return pprint.pformat(x)
The default default formatter!.
359,677
def groups_filter_from_query(query, field_map={}): f = None for group in query.get("groups", []): group_f = MatchAll() for condition in group.get("conditions", []): field_name = condition["field"] field_name = field_map.get(field_name, field_name) op...
Creates an F object for the groups of a search query.
359,678
def modify_karma(self, words): k = defaultdict(int) if words: for word_tuple in words: word = word_tuple[0] ending = word[-1] word = word[1:-1] word = word.s...
Given a regex object, look through the groups and modify karma as necessary
359,679
def detect_function_shadowing(contracts, direct_shadowing=True, indirect_shadowing=True): results = set() for contract in contracts: if direct_shadowing: shadows = detect_direct_function_shadowing(contract) for (overshadowing_function, overshadowed_base_contract, o...
Detects all overshadowing and overshadowed functions in the provided contracts. :param contracts: The contracts to detect shadowing within. :param direct_shadowing: Include results from direct inheritance/inheritance ancestry. :param indirect_shadowing: Include results from indirect inheritance collisions a...
359,680
def sample(self): acceptance = 1 finish = 0 while (acceptance < 0.234 or acceptance > 0.4) or finish == 0: if not (acceptance < 0.234 or acceptance > 0.4): finish = 1 if not self.quiet_progress: print("...
Sample from M-H algorithm Returns ---------- chain : np.array Chains for each parameter mean_est : np.array Mean values for each parameter median_est : np.array Median values for each parameter upper_95_est : np.array Up...
359,681
def is_varchar(self): dt = DATA_TYPES[] if type(self.data) is dt[] and len(self.data) < dt[]: self.type = self.len = len(self.data) return True
Determine if a data record is of the type VARCHAR.
359,682
def try_printout(data, out, opts, **kwargs): try: printout = get_printout(out, opts)(data, **kwargs) if printout is not None: return printout.rstrip() except (KeyError, AttributeError, TypeError): log.debug(traceback.format_exc()) try: printout = get_...
Safely get the string to print out, try the configured outputter, then fall back to nested and then to raw
359,683
def generate_complementary_strand(strand1): rise_adjust = ( strand1.rise_per_nucleotide * strand1.axis.unit_tangent) * 2 strand2 = NucleicAcidStrand.from_start_and_end( strand1.helix_end - rise_adjust, strand1.helix_start - rise_adjust, generate_antisense_seq...
Takes a SingleStrandHelix and creates the antisense strand.
359,684
def get(self, report_id): return Report( self._app, self._swimlane.request(, "reports/{0}".format(report_id)).json() )
Retrieve report by ID Args: report_id (str): Full report ID Returns: Report: Corresponding Report instance
359,685
def _init_params_default(self): Yimp = self.Y.copy() Inan = sp.isnan(Yimp) Yimp[Inan] = Yimp[~Inan].mean() if self.P==1: C = sp.array([[Yimp.var()]]) else: C = sp.cov(Yimp.T) C /= float(self.n_randEffs) for ti in range(self.n_randEffs...
Internal method for default parameter initialization
359,686
def iterfile(path, since=-1): surrogatepass with io.open(path, ) as fd: unpk = msgpack.Unpacker(fd, **unpacker_kwargs) for i, mesg in enumerate(unpk): if i <= since: continue yield mesg
Generator which yields msgpack objects from a file path. Args: path: File path to open and consume data from. Notes: String objects are decoded using utf8 encoding. In order to handle potentially malformed input, ``unicode_errors='surrogatepass'`` is set to allow decoding bad ...
359,687
def is_zero(pauli_object): if isinstance(pauli_object, PauliTerm): return np.isclose(pauli_object.coefficient, 0) elif isinstance(pauli_object, PauliSum): return len(pauli_object.terms) == 1 and np.isclose(pauli_object.terms[0].coefficient, 0) else: raise TypeError("is_zero only...
Tests to see if a PauliTerm or PauliSum is zero. :param pauli_object: Either a PauliTerm or PauliSum :returns: True if PauliTerm is zero, False otherwise :rtype: bool
359,688
def getPrimaryKeys(self, sortByAge=False): conn = self._get_connection() numFilters = len(self.filters) numNotFilters = len(self.notFilters) if numFilters + numNotFilters == 0: conn = self._get_connection() matchedKeys = conn.smembers(self._get_ids_key()) elif numNotFilters == 0: if n...
getPrimaryKeys - Returns all primary keys matching current filterset. @param sortByAge <bool> - If False, return will be a set and may not be ordered. If True, return will be a list and is guarenteed to represent objects oldest->newest @return <set> - A set of all primary keys associated with current filter...
359,689
def _entity_to_region_map(self): entity_to_region = {} for key in self.get_all_keys(): layer, rx, ry = struct.unpack(, key) if layer != 4: continue stream = io.BytesIO(self.get(layer, rx, ry)) num_entities = sbon.read_varint(stream...
A dict whose keys are the UUIDs (or just IDs, in some cases) of entities, and whose values are the `(rx, ry)` coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world.
359,690
def html(text, extensions=0, render_flags=0): extensions = args_to_int(extension_map, extensions) render_flags = args_to_int(html_flag_map, render_flags) ib = lib.hoedown_buffer_new(IUNIT) ob = lib.hoedown_buffer_new(OUNIT) renderer = lib.hoedown_html_renderer_new(render_flags, 0) document...
Convert markdown text to HTML. ``extensions`` can be a list or tuple of extensions (e.g. ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``). ``render_flags`` can be a list or tuple of flags (e.g. ``('skip-html', 'hard-wra...
359,691
def ngram_diff(args, parser): store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) tokenizer = utils.get_tokenizer(args) store.validate(corpus, catalogue) if args.asymmetric: store.diff_asymmetric(catalogue, args.asymmetric, tokeni...
Outputs the results of performing a diff query.
359,692
def album_primary_image_url(self): path = .format(self.album_id) return self.connector.get_url(path, attach_api_key=False)
The image of the album
359,693
def funding_info2marc(self, key, value): return { : value.get(), : value.get(), : value.get(), }
Populate the ``536`` MARC field.
359,694
def save_state_machine(delete_old_state_machine=False, recent_opened_notification=False, as_copy=False, copy_path=None): state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model states_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller() state_machine_m = s...
Save selected state machine The function checks if states of the state machine has not stored script data abd triggers dialog windows to take user input how to continue (ignoring or storing this script changes). If the state machine file_system_path is None function save_state_machine_as is used to coll...
359,695
def purge(self, connection): self._checkpid() if connection.pid == self.pid: idx = connection._pattern_idx if connection in self._in_use_connections[idx]: self._in_use_connections[idx].remove(connection) else: self._available_c...
Remove the connection from rotation
359,696
def _get_batch_representative(items, key): if isinstance(items, dict): return items, items else: vals = set([]) out = [] for data in items: if key in data: vals.add(data[key]) out.append(data) if len(vals) != 1: ...
Retrieve a representative data item from a batch. Handles standard bcbio cases (a single data item) and CWL cases with batches that have a consistent variant file.
359,697
def _from_dict(cls, _dict): args = {} if in _dict: args[] = _dict.get() if in _dict: args[] = SemanticRolesResultSubject._from_dict( _dict.get()) if in _dict: args[] = SemanticRolesResultAction._from_dict( _d...
Initialize a SemanticRolesResult object from a json dictionary.
359,698
def refresh(self, props, body): LOGGER.debug("InjectorCachedComponent.refresh") operation = props[] if operation == "REFRESH": if self.parent_actor_ref is not None: parent_actor = self.parent_actor_ref.proxy() parent_actor.sniff().get() ...
the refresh method called when on demand refresh service receive a message. then call the parent actor sniff method if message is compliant on what is attended :param props: the message properties :param body: the message body :return:
359,699
async def publish_changes(self, zone, changes): zone_id = self.get_managed_zone(zone) url = f resp = await self.request(, url, json=changes) return json.loads(resp)[]
Post changes to a zone. Args: zone (str): DNS zone of the change. changes (dict): JSON compatible dict of a `Change <https://cloud.google.com/dns/api/v1/changes>`_. Returns: string identifier of the change.