Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
352,000
def dump_to_stream(self, cnf, stream, **kwargs): for key, val in anyconfig.compat.iteritems(cnf): stream.write("%s=%s" % (key, val, os.linesep))
Dump config 'cnf' to a file or file-like object 'stream'. :param cnf: Shell variables data to dump :param stream: Shell script file or file like object :param kwargs: backend-specific optional keyword parameters :: dict
352,001
def validate_arrangement_version(self): arrangement_version = self.build_kwargs[] if arrangement_version is None: return if arrangement_version <= 5: self.log.warning("arrangement_version <= 5 is deprecated and will be removed" ...
Validate if the arrangement_version is supported This is for autorebuilds to fail early otherwise they may failed on workers because of osbs-client validation checks. Method should be called after self.adjust_build_kwargs Shows a warning when version is deprecated :raises Val...
352,002
def _equals(v1_indices, v1_values, v2_indices, v2_values): v1_size = len(v1_values) v2_size = len(v2_values) k1 = 0 k2 = 0 all_equal = True while all_equal: while k1 < v1_size and v1_values[k1] == 0: k1 += 1 while k2 < v2_s...
Check equality between sparse/dense vectors, v1_indices and v2_indices assume to be strictly increasing.
352,003
def __patch_pipe_methods(tango_device_klass, pipe): __patch_pipe_read_method(tango_device_klass, pipe) if pipe.pipe_write == PipeWriteType.PIPE_READ_WRITE: __patch_pipe_write_method(tango_device_klass, pipe)
Checks if the read and write methods have the correct signature. If a read/write method doesn't have a parameter (the traditional Pipe), then the method is wrapped into another method to make this work. :param tango_device_klass: a DeviceImpl class :type tango_device_klass: class :param pipe: t...
352,004
def get_unique_name(self, prefix): ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1 return % (prefix, ident)
Returns an index-suffixed unique name for the given prefix. This is used for auto-generating layer names based on the type-prefix.
352,005
def post(self): self.reqparse.add_argument(, type=str, required=True) self.reqparse.add_argument(, type=str, required=True) args = self.reqparse.parse_args() template = db.Template.find_one(template_name=args[]) if template: return self.make_response(, HTTP....
Create a new template
352,006
def _make_temp_filename(prefix): temp_location = _get_temp_file_location() temp_file_name = .join([temp_location, str(prefix)+str(_uuid.uuid4())]) return temp_file_name
Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be cleaned up when unity_server restarts
352,007
def handle(self, pkt, raddress, rport): log.debug("In TftpStateServerStart.handle") if isinstance(pkt, TftpPacketRRQ): log.debug("Handling an RRQ packet") return TftpStateServerRecvRRQ(self.context).handle(pkt, ...
Handle a packet we just received.
352,008
def minimal_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]: models = self.all_models(alphabet) minimal_models = set() for m in models: min_m = m for m1 in models: if min_m.true_propositions.issuperset(m1.true_propositions): ...
Find models of min size (i.e. the less number of proposition to True). Very trivial (and inefficient) algorithm: BRUTE FORCE on all the possible interpretations.
352,009
def last_run(ext_source=None, outputter=None, metadata=None, function=None, target=None, display_progress=False): cmd.runfoobar if metadata: if not isinstance(metadata, dict): log.info() return False _all_jobs...
.. versionadded:: 2015.8.0 List all detectable jobs and associated functions CLI Example: .. code-block:: bash salt-run jobs.last_run salt-run jobs.last_run target=nodename salt-run jobs.last_run function='cmd.run' salt-run jobs.last_run metadata="{'foo': 'bar'}"
352,010
def community_neighbors(c_j, reverse_index_rows, unavailable_communities, unavailable_communities_counter): indices = list() extend = indices.extend for node in c_j: extend(reverse_index_rows[node]) indices = np.array(indices) indices = np.setdiff1d(indices, unavailable_communities[:un...
Finds communities with shared nodes to a seed community. Called by mroc. Inputs: - c_j: The seed community for which we want to find which communities overlap. - reverse_index_rows: A node to community indicator matrix. - unavailable_communities: A set of communities that have already ei...
352,011
def parse(self, fp, parser=None, context=None): if parser is None: parser = lxml.etree.HTMLParser() doc = lxml.etree.parse(fp, parser=parser).getroot() return self.extract(doc, context=context)
Parse an HTML or XML document and return the extacted object following the Parsley rules give at instantiation. :param fp: file-like object containing an HTML or XML document, or URL or filename :param parser: *lxml.etree._FeedParser* instance (optional); defaults to lxml.etree.HTMLParser() ...
352,012
def as_sql(self, return_id=False): queries = [ self._rewrite_insert(sql, params, return_id) for sql, params in super().as_sql() ] return queries
Builds the SQL INSERT statement.
352,013
def merge_sorted(lst, func=cmp, reversed=False): assert isinstance(lst, list) if len(lst) <= 1: return lst def merge(a, b): mlst = [] while a and b: mlst.append(a.pop(0) if func(a[0], b[0]) < 0 else b.pop(0)) return mlst + a + b m = int(len(lst) / 2) ...
>>> l = [2,3,1,0,6,4,7,8,5,9] >>> merge_sorted(l) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> merge_sorted(l, func=lambda a, b: cmp(b, a)) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> merge_sorted(l, reversed=True) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> merge_sorted(l, func=lambda a, b: cmp(b, a), reversed=True) ...
352,014
def index(in_cram, config): out_file = in_cram + ".crai" if not utils.file_uptodate(out_file, in_cram): with file_transaction(config, in_cram + ".crai") as tx_out_file: tx_in_file = os.path.splitext(tx_out_file)[0] utils.symlink_plus(in_cram, tx_in_file) cmd = "s...
Ensure CRAM file has a .crai index file.
352,015
def getClass(self, tryImport=True): if not self.triedImport and tryImport: self.tryImportClass() return self._cls
Gets the underlying class. Tries to import if tryImport is True (the default). Returns None if the import has failed (the exception property will contain the reason)
352,016
def get(self, instance_id): self.content_type = self.write(json.dumps(utils.chain([ [, ], [, instance_id], [, ], [, {print $2}\]])).strip()) self.finish()
get method
352,017
def _new_gnu_trans(self, localedir, use_null_fallback=True): use_null_fallback = False return gettext_module.translation( domain=self.domain, localedir=localedir, languages=[self.language], codeset=, fallback=use_null_fallback)
Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'.
352,018
def sdiffstore(self, destination, *keys): return self._execute([b, destination] + list(keys))
This command is equal to :meth:`~tredis.RedisClient.sdiff`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the total number of elements in a...
352,019
def utf8(value): if isinstance(value, _UTF8_TYPES): return value assert isinstance(value, unicode) return value.encode("utf-8")
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
352,020
def insert(self, docs, *args, **kwargs): if isinstance(docs, list): return self.insert_many(docs, *args, **kwargs) else: return self.insert_one(docs, *args, **kwargs)
Backwards compatibility with insert
352,021
def list_nodes_full(session=None): if session is None: session = _get_session() ret = {} vms = session.xenapi.VM.get_all() for vm in vms: record = session.xenapi.VM.get_record(vm) if not record[] and not record[]: return ret
List full virtual machines .. code-block:: bash salt-cloud -F
352,022
def uninstall(): ret, git_dir, _ = run("git rev-parse --show-toplevel") if ret != 0: click.echo( "ERROR: Please run from within a GIT repository.", file=sys.stderr) raise click.Abort git_dir = git_dir[0] hooks_dir = os.path.join(git_dir, HOOK_PATH) for ...
Uninstall git hooks.
352,023
def index(self, name, graph): nodes = graph.nodes() new_nodes = list(set(nodes) - set(self.node_index.values())) start = max(len(self.node_index) - 1, max(self.node_index.keys())) for i in xrange(start, start + len(new_nodes)): n = new_nodes.pop() ...
Index any new nodes in `graph`, and relabel the nodes in `graph` using the index. Parameters ---------- name : hashable Unique name used to identify the `graph`. graph : networkx.Graph Returns ------- indexed_graph : networkx.Graph
352,024
def remove_type_from_resource( type_id, resource_type, resource_id,**kwargs): node_id = resource_id if resource_type == else None link_id = resource_id if resource_type == else None group_id = resource_id if resource_type == else None resourcetype = db.DBSession.query(ResourceType).filter( ...
Remove a resource type trom a resource
352,025
def set_path(self, path, val): path = tuple(path.split()) if isinstance(path , str) else tuple(path) disallowed = [p for p in path if not type(self)._sanitizer.allowable(p)] if any(disallowed): raise Exception("Attribute strings in path elements cannot be " ...
Set the given value at the supplied path where path is either a tuple of strings or a string in A.B.C format.
352,026
def _merge_chains(chain_model_a, chain_model_b): _set_chain_sid( chain_model_a, d1_gmn.app.did.get_did_by_foreign_key(chain_model_b.sid) ) for member_model in _get_all_chain_member_queryset_by_chain(chain_model_b): member_model.chain = chain_model_a member_model.save() chain...
Merge two chains. For use when it becomes known that two chains that were created separately actually are separate sections of the same chain E.g.: - A obsoleted by X is created. A has no SID. X does not exist yet. A chain is created for A. - B obsoleting Y is created. B has SID. Y does not...
352,027
def set_recursion_limit(limit): if limit < minimum_recursion_limit: raise CoconutException("--recursion-limit must be at least " + str(minimum_recursion_limit)) sys.setrecursionlimit(limit)
Set the Python recursion limit.
352,028
def DEFINE_string(flag_name, default_value, docstring, required=False): _define_helper(flag_name, default_value, docstring, str, required)
Defines a flag of type 'string'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a string. docstring: A helpful message explaining the use of the flag.
352,029
def convert_enamldef_def_to_func(token_stream): in_enamldef = False depth = 0 for tok in token_stream: if tok.type == : in_enamldef = True elif tok.type == : depth += 1 elif in_enamldef and tok.type == : depth -= 1 ...
A token stream processor which processes all enaml declarative functions to allow using `def` instead of `func`. It does this by transforming DEF tokens to NAME within enamldef blocks and then changing the token value to `func`. Notes ------ Use this at your own risk! This was a feature...
352,030
def coalescence_times(self, backward=True): if not isinstance(backward, bool): raise TypeError("backward must be a bool") for dist in sorted((d for n,d in self.distances_from_root() if len(n.children) > 1), reverse=backward): yield dist
Generator over the times of successive coalescence events Args: ``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
352,031
def obj_to_csv(self, file_path=None, quote_everything=False, space_columns=True, quote_numbers=True): list_of_list, column_widths = self.get_data_and_shared_column_widths( data_kwargs=dict(quote_numbers=quote_numbers, quote_everything=quote_ev...
This will return a str of a csv text that is friendly to excel :param file_path: str to the path :param quote_everything: bool if True will quote everything if it needs it or not, this is so it looks pretty in excel. :param quote_numbers: bool if True w...
352,032
def proj_l2ball(b, s, r, axes=None): r d = np.sqrt(np.sum((b - s)**2, axis=axes, keepdims=True)) p = zdivide(b - s, d) return np.asarray((d <= r) * b + (d > r) * (s + r*p), b.dtype)
r""" Project :math:`\mathbf{b}` into the :math:`\ell_2` ball of radius :math:`r` about :math:`\mathbf{s}`, i.e. :math:`\{ \mathbf{x} : \|\mathbf{x} - \mathbf{s} \|_2 \leq r \}`. Note that ``proj_l2ball(b, s, r)`` is equivalent to :func:`.prox.proj_l2` ``(b - s, r) + s``. Parameters --------...
352,033
def add_attendees(self, attendees, required=True): new_attendees = self._build_resource_dictionary(attendees, required=required) for email in new_attendees: self._attendees[email] = new_attendees[email] self._dirty_attributes.add(u)
Adds new attendees to the event. *attendees* can be a list of email addresses or :class:`ExchangeEventAttendee` objects.
352,034
def _add_variable(self, variable): variable_data = self.data[][][variable] variable_element = etree.SubElement(self.variables, , attrib={: variable, : variable_data[], ...
Adds a node to the ProbModelXML.
352,035
def below(self, ref): if not self._valid_ordering_reference(ref): raise ValueError( "%r can only be moved below instances of %r which %s equals %r." % ( self, self.__class__, self.order_with_respect_to, self._get_order_with_respect_to(...
Move this object below the referenced object.
352,036
def replace_embedded(self,src_file,dst_file): with open(dst_file, ) as fh: crc = self.get_file_crc(src_file) self.crc_to_new_embedded[crc] = fh.read()
Replace one embdded object by another one into a docx This has been done mainly because it is not possible to add images in docx header/footer. With this function, put a dummy picture in your header/footer, then specify it with its replacement in this function Syntax: tpl.repla...
352,037
def pkt2uptime(pkt, HZ=100): if not isinstance(pkt, Packet): raise TypeError("Not a TCP packet") if isinstance(pkt, NoPayload): raise TypeError("Not a TCP packet") if not isinstance(pkt, TCP): return pkt2uptime(pkt.payload) for opt in pkt.options: if opt[0] == "Times...
Calculate the date the machine which emitted the packet booted using TCP timestamp # noqa: E501 pkt2uptime(pkt, [HZ=100])
352,038
def set_servo(self, gpio, pulse_width_us): _pulse_incr_us = _PWM.get_pulse_incr_us() if pulse_width_us % _pulse_incr_us: raise AttributeError(("Pulse width increment granularity %sus " "cannot divide a pulse-time of %sus") % (_pulse_incr_us,...
Sets a pulse-width on a gpio to repeat every subcycle (by default every 20ms).
352,039
def _convert_string_to_hhmmss(self, string): components = string.split() if len(components) != 3: raise InvalidArgument() return { : int(components[0]), : int(components[1]), : int(components[2]) }
stub
352,040
def validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg=, validatecert=False, debug=False): error_callback_method = None if debug: error_callback_method = print_xmlsec_errors xmlsec.set_error_callback(error_callback_method) xmlsec.ad...
Validates a signature node. :param signature_node: The signature node :type: Node :param xml: The element we should validate :type: Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string...
352,041
def BFS(G, start): if start not in G.vertices: raise GraphInsertError("Vertex %s doesnwhitewhitegreyblack' return pred
Algorithm for breadth-first searching the vertices of a graph.
352,042
def describe_supported(series, **kwargs): leng = len(series) count = series.count() n_infinite = count - series.count() value_counts, distinct_count = base.get_groupby_statistic(series) if count > distinct_count > 1: mode = series.mode().iloc[0] else: mode = series[0]...
Compute summary statistics of a supported variable (a Series). Parameters ---------- series : Series The variable to describe. Returns ------- Series The description of the variable as a Series with index being stats keys.
352,043
def update_path_labels(self): self.view[].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path)) self.view[].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path))
Update labels showing config paths
352,044
def mute_string(text): start = 1 end = len(text) - 1 if text.endswith(): start += text.index() elif text.endswith("") if text.endswith() or text.endswith("x' * (end - start) + text[end:]
Replace contents with 'xxx' to prevent syntax matching. >>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'"
352,045
async def open(self) -> : LOGGER.debug() await super().open() if self.config.get(, False): ArchivableCaches.parse(self.dir_cache) LOGGER.debug() return self
Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object
352,046
def list(self, date_created_from=values.unset, date_created_to=values.unset, limit=None, page_size=None): return list(self.stream( date_created_from=date_created_from, date_created_to=date_created_to, limit=limit, page_size=page_size, ...
Lists ExecutionInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param datetime date_created_from: Only show Executions that started on or after this ISO8601 date-time. :param datetime date_crea...
352,047
def ParseNotificationcenterRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = MacNotificationCenterEventData() event_data.bundle_name = self._GetRowValue(query_hash, row, ) event_data.presented = self._GetRowValue(query_hash, row, ) blob = se...
Parses a message row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
352,048
def match_all(self, pattern): pattern = self.pattern_open(pattern) search_img = pattern.image screen = self.region_screenshot() screen = imutils.from_pillow(screen) points = ac.find_all_template(screen, search_img, maxcnt=10) return points
Test method, not suggested to use
352,049
def fetch_and_execute_function_to_run(self, key): (driver_id, serialized_function, run_on_other_drivers) = self.redis_client.hmget( key, ["driver_id", "function", "run_on_other_drivers"]) if (utils.decode(run_on_other_drivers) == "False" and self.worker.mo...
Run on arbitrary function on the worker.
352,050
def branchScale(self): bs = -(self.prx * scipy.diagonal(self.Prxy, axis1=1, axis2=2) ).sum() * self.mu / float(self.nsites) assert bs > 0 return bs
See docs for `Model` abstract base class.
352,051
def getAllThemes(self): if self._getAllThemesCache is None: self._getAllThemesCache = self._realGetAllThemes() return self._getAllThemesCache
Collect themes from all available offerings, or (if called multiple times) return the previously collected list.
352,052
def configure(level, logfile=None): log_format = "%(asctime)s-%(levelname)s: %(message)s" date_format = logging.basicConfig(format=log_format, datefmt=date_format) Log.setLevel(level) if logfile is not None: fh = logging.FileHandler(logfile) fh.setFormatter(logging.Formatter(log_format)) Log...
configure logging
352,053
def from_dict(cls, dic): if not in dic: raise ValueError() data_version = int(dic[].replace(, )) this_version = int(cls._version.replace(, )) logger.debug(, this_version, data_version) if data_version < this_version: raise ValueError() ...
Convert dict generated by `convert_2_dict` into Docpie instance You can do this: pie = Docpie(__doc__) clone_pie = json.loads(pie.convert_2_docpie( json.dumps(pie.convert_2_dict()) )) Note if you changed `extra`, it will be lost. You can use `set_config(extr...
352,054
def writef(notebook, nb_file, fmt=None): if nb_file == : write(notebook, sys.stdout, fmt) return _, ext = os.path.splitext(nb_file) fmt = copy(fmt or {}) fmt = long_form_one_format(fmt, update={: ext}) create_prefix_dir(nb_file, fmt) with io.open(nb_file, , encoding=) as ...
Write a notebook to the file with given name
352,055
def include(context, bundle_name, version): store = Store(context.obj[], context.obj[]) if version: version_obj = store.Version.get(version) if version_obj is None: click.echo(click.style(, fg=)) else: bundle_obj = store.bundle(bundle_name) if bundle_obj is N...
Include a bundle of files into the internal space. Use bundle name if you simply want to inlcude the latest version.
352,056
def mark_done(task_id): task = Task.get_by_id(task_id) if task is None: raise ValueError( % task_id) task.done = True task.put()
Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist.
352,057
def __load_omitted_parcov(self): if self.omitted_parcov_arg is None and self.omitted_par_arg is None: raise Exception("ErrVar.__load_omitted_parcov: " + "both omitted args are None") if self.omitted_parcov_arg is None and self.omitted_par_arg is ...
private: set the omitted_parcov attribute
352,058
def get_upload_path(finfo, sample_info, config): try: storage_dir = _get_storage_dir(finfo, config) except ValueError: return None if finfo.get("type") == "directory": return _get_dir_upload_path(finfo, storage_dir) else: return _get_file_upload_path(finfo, stor...
Dry" update the file: only return the upload path
352,059
def parse_query(query, ilogger): p = urlparse(query) if p and p.scheme and p.netloc: if "youtube" in p.netloc and p.query and ytdiscoveryapi is not None: query_parts = p.query.split() yturl_parts = {} for q in query_parts: s = q.split() ...
Gets either a list of videos from a query, parsing links and search queries and playlists Args: query (str): The YouTube search query ilogger (logging.logger): The logger to log API calls to Returns: queue (list): The items obtained from the YouTube search
352,060
def log_to_history(logger, name): def log_to_history_decorator(method): def l2h_method(self, ri): history_header = fits.Header() fh = FITSHistoryHandler(history_header) fh.setLevel(logging.INFO) logger.addHandler(fh) try: r...
Decorate function, adding a logger handler stored in FITS.
352,061
def path_dispatch_rename(rename_like_method): def _wrapper_method(self, old_path, new_path): old_path, _old_path, old_sentinel = _split_path(old_path); new_path, _new_path, new_sentinel = _split_path(new_path); if old_sentinel != new_sentinel: rai...
decorator for rename-like function, that need dispatch on 2 arguments
352,062
def put(self, measurementId, deviceId): data = request.get_json() if data is not None: parsedData = json.loads(data) logger.debug( + measurementId + + deviceId + + str(len(parsedData)) + ) if self._measurementController.recordData(m...
Store a bunch of data for this measurement session. :param measurementId: :param deviceId: :return:
352,063
def _setup(self): agent_config = CONF.get("AGENT", {}) self._worker_count = agent_config.get() self._phys_net_map = agent_config.get( , []) self._local_network_vswitch = agent_config.get( ) self._load_physical_network_mappings(self._phys_net_map) ...
Setup the layer two agent.
352,064
def delete(self, force=False, client=None): client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project if force: blobs = list( self.list_blobs( ...
Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed, this will first attempt to delete all the objects / blobs in the bucket (i.e. try to empty the bucket). If the bucket doesn't exist, this will raise :class:`google...
352,065
def check_integrity(filename): if not os.path.exists(filename): raise ValueError("file {} does not exist".format(filename)) with loadfile(filename, ) as fp: parameters = fp[fp.samples_group].keys() if len(parameters) > 0: group = fp.sampl...
Checks the integrity of an InferenceFile. Checks done are: * can the file open? * do all of the datasets in the samples group have the same shape? * can the first and last sample in all of the datasets in the samples group be read? If any of these checks fail, an IOError is ...
352,066
def symm_op(g, ax, theta, do_refl): import numpy as np gx = geom_rotate(g, ax, theta) if do_refl: gx = geom_reflect(gx, ax) return gx
Perform general point symmetry operation on a geometry. .. todo:: Complete symm_op docstring
352,067
def _ParseJournalEntry(self, file_object, file_offset): entry_object = self._ParseEntryObject(file_object, file_offset) entry_item_map = self._GetDataTypeMap() file_offset += 64 data_end_offset = file_offset + entry_object.data_size - 64 fields = {: entry_object.real_time} while fi...
Parses a journal entry. This method will generate an event per ENTRY object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the entry object relative to the start of the file-like object. Returns: dict[str, objects]: entry items per key. ...
352,068
def _ParseStorageMediaImageOptions(self, options): self._partitions = getattr(options, , None) if self._partitions: try: self._ParseVolumeIdentifiersString(self._partitions, prefix=) except ValueError: raise errors.BadConfigOption() self._volumes = getattr(options, , None) ...
Parses the storage media image options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
352,069
def check_first_party_caveat(self, ctx, cav): try: cond, arg = parse_caveat(cav) except ValueError as ex: return .format(cav, ex.args[0]) checker = self._checkers.get(cond) if checker is None: return .format( ...
Checks the caveat against all registered caveat conditions. :return: error message string if any or None
352,070
def get_url(client, name, version, wheel=False, hashed_format=False): try: release_urls = client.release_urls(name, version) release_data = client.release_data(name, version) except BaseException: logger.debug(.format( client, name, version)) raise exceptions.M...
Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL of prefered archive and md5_digest.
352,071
def generate_catalogs_indicators(catalogs, central_catalog=None, identifier_search=False, validator=None): assert isinstance(catalogs, string_types + (dict, list)) if isinstance(catalogs, string_types + (dict,)): catalogs = [cat...
Genera una lista de diccionarios con varios indicadores sobre los catálogos provistos, tales como la cantidad de datasets válidos, días desde su última fecha actualizada, entre otros. Args: catalogs (str o list): uno o más catalogos sobre los que se quiera obtener indicadores ce...
352,072
def create(model_config, vec_env, model, algo, env_roller, parallel_envs: int, rollout_steps: int, training_steps: int, training_rounds: int=1): settings = BufferedOffPolicyIterationReinforcerSettings( rollout_steps=rollout_steps, training_steps=training_steps, training_round...
Vel factory function
352,073
def polish_model(model): onnx.checker.check_model(model) onnx.helper.strip_doc_string(model) model = onnx.shape_inference.infer_shapes(model) model = onnx.optimizer.optimize(model) onnx.checker.check_model(model) return model
This function combines several useful utility functions together.
352,074
def set_state(self, state): if REGION_MAPPING not in state.options: l.warning( ) state.options.add(REGION_MAPPING) SimMemory.set_state(self, state) for _,v in self._regions.items(): ...
Overriding the SimStatePlugin.set_state() method :param state: A SimState object :return: None
352,075
def plot(args): from jcvi.graphics.base import plt, savefig from jcvi.graphics.chromosome import ChromosomeMap p = OptionParser(plot.__doc__) p.add_option("--firstn", type="int", help="Only plot the first N genes") p.add_option("--ymax", type="int", help="Y-axis max value") p.add_option("-...
%prog plot tagged.new.bed chr1 Plot gene identifiers along a particular chromosome, often to illustrate the gene id assignment procedure.
352,076
def _remove(self, telegram): index = self._buffer.index(telegram) + len(telegram) self._buffer = self._buffer[index:]
Remove telegram from buffer and incomplete data preceding it. This is easier than validating the data before adding it to the buffer. :param str telegram: :return:
352,077
def set_intrusion_alert_through_smoke_detectors(self, activate: bool = True): data = {"intrusionAlertThroughSmokeDetectors": activate} return self._restCall( "home/security/setIntrusionAlertThroughSmokeDetectors", json.dumps(data) )
activate or deactivate if smoke detectors should "ring" during an alarm Args: activate(bool): True will let the smoke detectors "ring" during an alarm
352,078
def get_entries_for_scope(self, user_scope, scope_name, scope_value, key=None): route_values = {} if user_scope is not None: route_values[] = self._serialize.url(, user_scope, ) if scope_name is not None: route_values[] = self._serialize.url(, scope_name, ) ...
GetEntriesForScope. [Preview API] Get all setting entries for the given named scope :param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users. :param str scope_name: Scope at which to get the setting for (e.g. "project" or "team") ...
352,079
def setExpanded(self, index, expanded): if index.isValid(): item = self.getItem(index) item.expanded = expanded
Expands the model item specified by the index. Overridden from QTreeView to make it persistent (between inspector changes).
352,080
def limits(self, low, high): if self._high_limits is None: result = self.call({: , : , : }) self._high_limits = in \ result[][][] if self._high_limits: return high else: ...
Convenience function for determining appropriate limits in the API. If the (usually logged-in) client has the ``apihighlimits`` right, it will return *high*; otherwise it will return *low*. It's generally a good idea to use the highest limit possible; this reduces the amount of HTTP req...
352,081
def parse_embeddedObject(self, val): if type(val) == list: return [self.parse_embeddedObject(obj) for obj in val] if val is None: return None tup_tree = xml_to_tupletree_sax(val, "embedded object", self.conn_id) if name(tup_tree) ==...
Parse and embedded instance or class and return the CIMInstance or CIMClass. Parameters: val (string): The string value that contains the embedded object in CIM-XML format. One level of XML entity references have already been unescaped. Exampl...
352,082
def handle_has_components(self, _, __, tokens: ParseResults) -> ParseResults: return self._handle_list_helper(tokens, HAS_COMPONENT)
Handle list relations like ``p(X) hasComponents list(p(Y), p(Z), ...)``.
352,083
def main(self, configuration): _custom_func_arguments = {"conf"} filename = os.path.basename(os.path.abspath(sys.argv[0])) default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0] if len(default_arg_list) == 0: sys.stdout.write(self.generate_help(filename=...
:type configuration Configuration
352,084
def json_validate(schema, resp): try: json_validate_error(resp) except ValidationError: if json_is_exception(resp): if BLOCKSTACK_TEST: log.error(.format(resp[])) return {: , : resp[], : 500} if in resp and not in resp: ...
Validate an RPC response. The response must either take the form of the given schema, or it must take the form of {'error': ...} Returns the resp on success Returns {'error': ...} on validation error
352,085
def partitions_for_topic(self, topic): if topic not in self._partitions: return None return set(self._partitions[topic].keys())
Return set of all partitions for topic (whether available or not) Arguments: topic (str): topic to check for partitions Returns: set: {partition (int), ...}
352,086
def initial(self, request, *args, **kwargs): super(BaseInterfaceList, self).initial(request, *args, **kwargs) try: self.device = Device.objects.accessible_to(request.user)\ .get(pk=self.kwargs.get(, None)) except Device.DoesNotExist: ...
Custom initial method: * ensure device exists and store it in an instance attribute * change queryset to return only devices of current node
352,087
def tag_atoms_unique_ids(self, force=False): tagged = [ in x.tags.keys() for x in self.get_atoms()] if (not all(tagged)) or force: for m in self.get_monomers(): for atom_type, atom in m.atoms.items(): atom.tags[] = (m.unique_id, atom_type) ...
Tags each Atom in the Assembly with its unique_id. Notes ----- The unique_id for each atom is a tuple (a double). `unique_id[0]` is the unique_id for its parent `Monomer` (see `Monomer.unique_id` for more information). `unique_id[1]` is the atom_type in the `Assembly` as...
352,088
def get_scheduler_from_hostname(self, host_name): scheduler_uuid = self.hosts_schedulers.get(host_name, None) return self.schedulers.get(scheduler_uuid, None)
Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict
352,089
def register(self, pattern, view=None): if view is None: return partial(self.register, pattern) self.patterns.append(self._make_url((pattern, view))) return view
Allow decorator-style construction of URL pattern lists.
352,090
def complete(self, request, response): extra = self.get_extra_data(response) data = {} for form_field, backend_field in self.PROFILE_MAPPING.items(): data[form_field] = self.extract_data(extra, backend_field) request.session[] = data if settings.ACCEPT_EXTRA...
Complete net auth.
352,091
def handle_reply(self, msg): method = self.__class__.unhandled_reply if msg.name in self._reply_handlers: method = self._reply_handlers[msg.name] try: return method(self, msg) except Exception: e_type, e_value, trace = sys.exc_info() ...
Dispatch a reply message to the appropriate method. Parameters ---------- msg : Message object The reply message to dispatch.
352,092
def spkez(targ, et, ref, abcorr, obs): targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = ctypes.c_int(obs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkez_c(targ, et, ref, abcorr, ...
Return the state (position and velocity) of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html :param targ: Target body. :type targ: int :param et: ...
352,093
def get_tasks(current): allowed_workflows = [bpmn_wf.name for bpmn_wf in BPMNWorkflow.objects.all() if current.has_permission(bpmn_wf.name)] queryset = queryset.exclude(role_id=current.role_id).filter(wf_name__in=allowed_workflows) else: }
List task invitations of current user .. code-block:: python # request: { 'view': '_zops_get_tasks', 'state': string, # one of these: # "active", "future", "finished", "expired" 'inverted': boolean, ...
352,094
def gfevnt(udstep, udrefn, gquant, qnpars, lenvals, qpnams, qcpars, qdpars, qipars, qlpars, op, refval, tol, adjust, rpt, udrepi, udrepu, udrepf, nintvls, bail, udbail, cnfine, result=None): assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() if result...
Determine time intervals when a specified geometric quantity satisfies a specified mathematical condition. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfevnt_c.html :param udstep: Name of the routine that computes and returns a :type udstep: spiceypy.utils.callbacks.UDSTEP :param udref...
352,095
def load_plugins(self, raise_error=False): pm_env = os.getenv(, ).split() include_pms = [s[4:] for s in pm_env if s.startswith()] exclude_pms = [s[3:] for s in pm_env if s.startswith()] logger = logging.getLogger(__name__) plotters = self[] def_plots = {: list...
Load the plotters and defaultParams from the plugins This method loads the `plotters` attribute and `defaultParams` attribute from the plugins that use the entry point specified by `group`. Entry points must be objects (or modules) that have a `defaultParams` and a `plotters` attribute....
352,096
def gap_index_map(sequence, gap_chars=): return dict( (v, k) for k, v in list(ungap_index_map(sequence, gap_chars).items()))
Opposite of ungap_index_map: returns mapping from gapped index to ungapped index. >>> gap_index_map('AC-TG-') {0: 0, 1: 1, 3: 2, 4: 3}
352,097
def cee_map_remap_fabric_priority_fabric_remapped_priority(self, **kwargs): config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop() remap...
Auto Generated Code
352,098
def add_userid_for_address(self, address: Address, user_id: str): self._address_to_userids[address].add(user_id)
Add a ``user_id`` for the given ``address``. Implicitly adds the address if it was unknown before.
352,099
def show_closed_prs(self): all_prs = self.collect_prs_info() for pr_info in all_prs.get(, []): logger.info( .format(**pr_info) )
Log only closed PRs.