code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def info(self): if self._info_manager is None: self._info_manager = InfoManager(session=self._session) return self._info_manager
Property for accessing :class:`InfoManager` instance, which is used to general server info. :rtype: yagocd.resources.info.InfoManager
def wildcard_allowed_actions(self, pattern=None): wildcard_allowed = [] for statement in self.statements: if statement.wildcard_actions(pattern) and statement.effect == "Allow": wildcard_allowed.append(statement) return wildcard_allowed
Find statements which allow wildcard actions. A pattern can be specified for the wildcard action
def omnigraffle(self): temp = self.rdf_source("dot") try: from os.path import expanduser home = expanduser("~") filename = home + "/tmp/turtle_sketch.dot" f = open(filename, "w") except: filename = "turtle_sketch.dot" f = open(filename, "w") f.write(temp) f.close() try: os.system(...
tries to open an export directly in omnigraffle
def Nu_plate_Kumar(Re, Pr, chevron_angle, mu=None, mu_wall=None): r beta_list_len = len(Kumar_beta_list) for i in range(beta_list_len): if chevron_angle <= Kumar_beta_list[i]: C1_options, m_options, Re_ranges = Kumar_C1s[i], Kumar_ms[i], Kumar_Nu_Res[i] break ...
r'''Calculates Nusselt number for single-phase flow in a **well-designed** Chevron-style plate heat exchanger according to [1]_. The data is believed to have been developed by APV International Limited, since acquired by SPX Corporation. This uses a curve fit of that data published in [2]_. .....
def step_it_should_fail_with(context): assert context.text is not None, "ENSURE: multiline text is provided." step_command_output_should_contain(context) assert_that(context.command_result.returncode, is_not(equal_to(0)))
EXAMPLE: ... when I run "behave ..." then it should fail with: """ TEXT """
def _dot_product(self, imgs_to_decode): return np.dot(imgs_to_decode.T, self.feature_images).T
Decoding using the dot product.
def decode_sent_msg(pref, message, pretty=False): newline = "\n" if pretty else " " indent = " " if pretty else "" start = newline + indent out = [] out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ])) out.append("%sCOMPRESSION: %d," % (start, message[Const.W_...
decode_sent_msg: Return a string of the decoded message
def privateparts(self, domain): s = self.privatesuffix(domain) if s is None: return None else: pre = domain[0:-(len(s)+1)] if pre == "": return (s,) else: return tuple(pre.split(".") + [s])
Return tuple of labels and the private suffix.
def download(input, filename, representation, overwrite=False, resolvers=None, get3d=False, **kwargs): result = resolve(input, representation, resolvers, get3d, **kwargs) if not result: log.debug() return if not overwrite and os.path.isfile(filename): raise IOError("%s...
Convenience function to save a CIR response as a file. This is just a simple wrapper around the resolve function. :param string input: Chemical identifier to resolve :param string filename: File path to save to :param string representation: Desired output representation :param bool overwrite: (Opt...
def cwd_decorator(func): def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith(".rst"): found = arg break if found: directory = os.path.dirname(found) if directory:...
decorator to change cwd to directory containing rst for this function
def create_top_schema(self): self.execute() self.execute() self.execute() self.execute() self.execute() self.execute() self.commit()
(Category --->) Item <---> Module <---> LogEntry <---> is a many-to-many relationship ---> is a foreign key relationship (- Category: represents a group of Items which form a top list) - Item: something that can be played multiple times and is grouped by to build a top list ...
def __groupchat_message(self,stanza): fr=stanza.get_from() key=fr.bare().as_unicode() rs=self.rooms.get(key) if not rs: self.__logger.debug("groupchat message from unknown source") return False rs.process_groupchat_message(stanza) return T...
Process a groupchat message from a MUC room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `Message` :return: `True` if the message was properly recognized as directed to one of the managed rooms, `False` otherwise. :returntype: `...
def put(self, key, value): for store in self._stores: store.put(key, value)
Stores the object in all underlying datastores.
def send_rpc(self, service, routing_id, method, args=None, kwargs=None, broadcast=False): t have a connection to a hub ' if not self._peer.up: raise errors.Unroutable() return self._dispatcher.send_proxied_rpc(service, routing_id, method, args or ...
Send out an RPC request :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the registered handlers of the service. :type routing_id: int :param method: the method na...
def to_cfn_resource_name(name): if not name: raise ValueError("Invalid name: %r" % name) word_separators = [, ] for word_separator in word_separators: word_parts = [p for p in name.split(word_separator) if p] name = .join([w[0].upper() + w[1:] for w in word_parts]) retu...
Transform a name to a valid cfn name. This will convert the provided name to a CamelCase name. It's possible that the conversion to a CFN resource name can result in name collisions. It's up to the caller to handle name collisions appropriately.
def process(self, filename, encoding, **kwargs): byte_string = self.extract(filename, **kwargs) unicode_string = self.decode(byte_string) return self.encode(unicode_string, encoding)
Process ``filename`` and encode byte-string with ``encoding``. This method is called by :func:`textract.parsers.process` and wraps the :meth:`.BaseParser.extract` method in `a delicious unicode sandwich <http://nedbatchelder.com/text/unipain.html>`_.
def get_slot_value(payload, slot_name): if not in payload: return [] slots = [] for candidate in payload[]: if in candidate and candidate[] == slot_name: slots.append(candidate) result = [] for slot in slots: kind ...
Return the parsed value of a slot. An intent has the form: { "text": "brew me a cappuccino with 3 sugars tomorrow", "slots": [ {"value": {"slotName": "coffee_type", "value": "cappuccino"}}, ... ] } ...
def send_event(self, action, properties, event_severity=EVENT_SEVERITY): event_properties = dict() if (properties is None) else properties if type(event_properties) is not dict: raise TypeError() event_bunch = Bunch( Product=self.product_name, ...
send css_event and if fails send custom_event instead Args: action (ACTIONS): the action causing the event properties (dict): the action additional properties event_severity (string): the event severity Raises: XCLIError: if the xcli.cmd.custom_event faile...
def values(self): tmp = self while tmp is not None: yield tmp.data tmp = tmp.next
in order
def _get_url(cls, name, message_model, dispatch_model): global APP_URLS_ATTACHED url = if dispatch_model is None: return url if APP_URLS_ATTACHED != False: hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id) try: ...
Returns a common pattern sitemessage URL. :param str name: URL name :param Message message_model: :param Dispatch|None dispatch_model: :return:
def mark_running(self): with self._lock: self._set_state(self._RUNNING, self._PAUSED)
Moves the service to the Running state. Raises if the service is not currently in the Paused state.
def _persist(self): for command in self.commands: try: process = Popen( [command], stdout=PIPE, stderr=PIPE, universal_newlines=True, env=self.env, ...
Run the command inside a thread so that we can catch output for each line as it comes in and display it.
def create_article(tree, template, title, language, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, created_by=None, image=None, publication_date=None, publication_end_date=None, published=False, login_required=False, creatio...
Create a CMS Article and it's title for the given language
def from_chords(self, chords, duration=1): tun = self.get_tuning() def add_chord(chord, duration): if type(chord) == list: for c in chord: add_chord(c, duration * 2) else: chord = NoteContainer().from_chord(chord) ...
Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc. Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper fingering. Example: >>> t = Track(...
def cree_widgets(self): for t in self.FIELDS: if type(t) is str: attr, kwargs = t, {} else: attr, kwargs = t[0], t[1].copy() self.champs.append(attr) is_editable = kwargs.pop("is_editable", self.is_editable) arg...
Create widgets and store them in self.widgets
def init_app(self, app): state = self.init_mail(app.config, app.debug, app.testing) app.extensions = getattr(app, , {}) app.extensions[] = state return state
Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance
def _textOutput(self, gaObjects): for variant in gaObjects: print( variant.id, variant.variant_set_id, variant.names, variant.reference_name, variant.start, variant.end, variant.reference_bases, variant.alternate_bases, sep="\t...
Prints out the specified Variant objects in a VCF-like form.
def requires(self): value = self._schema.get("requires", {}) if not isinstance(value, (basestring, dict)): raise SchemaError( "requires value {0!r} is neither a string nor an" " object".format(value)) return value
Additional object or objects required by this object.
def Deserialize(self, reader): self.name = reader.ReadVarString().decode() self.symbol = reader.ReadVarString().decode() self.decimals = reader.ReadUInt8()
Read serialized data from byte stream Args: reader (neocore.IO.BinaryReader): reader to read byte data from
def _extract_error(): error_num = errno() try: error_string = os.strerror(error_num) except (ValueError): return str_cls(error_num) if isinstance(error_string, str_cls): return error_string return _try_decode(error_string)
Extracts the last OS error message into a python unicode string :return: A unicode string error message
def getColData(self, attri, fname, numtype=): fname=self.findFile(fname,numtype) f=open(fname,) for i in range(self.index+1): f.readline() lines=f.readlines() for i in range(len(lines)): lines[i]=lines[i].strip() lines[i]=lines[i].spli...
In this method a column of data for the associated column attribute is returned. Parameters ---------- attri : string The name of the attribute we are looking for. fname : string The name of the file we are getting the data from or the cycle n...
def _handle_get_cfn_template_response(self, response, application_id, template_id): status = response[] if status != "ACTIVE": if status == : message = ("Template for {} with id {} returned status: {}. Cannot access an expired " ...
Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application
def digit(uni_char, default_value=None): uni_char = unicod(uni_char) if default_value is not None: return unicodedata.digit(uni_char, default_value) else: return unicodedata.digit(uni_char)
Returns the digit value assigned to the Unicode character uni_char as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.
def setRecord( self, record ): super(XBasicCardWidget, self).setRecord(record) browser = self.browserWidget() if ( not browser ): return factory = browser.factory() if ( not factory ): return self._th...
Sets the record that is linked with this widget. :param record | <orb.Table>
def log(self,phrase): pass t = datetime.now() if phrase in self.items.keys(): s = str(t) + + str(phrase) + " took: " + \ str(t - self.items[phrase]) + if self.echo: print(s,end=) if self.filename: self...
log something that happened. The first time phrase is passed the start time is saved. The second time the phrase is logged, the elapsed time is written Parameters ---------- phrase : str the thing that happened
def _expand_pattern_lists(pattern, **mappings): expanded_patterns = [] f = string.Formatter() for (_, field_name, _, _) in f.parse(pattern): if field_name is None: continue (value, _) = f.get_field(field_name, None, mappings) if isinstance(value, list): ...
Expands the pattern for any list-valued mappings, such that for any list of length N in the mappings present in the pattern, N copies of the pattern are returned, each with an element of the list substituted. pattern: A pattern to expand, for example ``by-role/{grains[roles]}`` mappings: ...
def add_file(self, path, yaml): if is_job_config(yaml): name = self.get_job_name(yaml) file_data = FileData(path=path, yaml=yaml) self.files[path] = file_data self.jobs[name] = file_data else: self.files[path] = FileData(path=path, y...
Adds given file to the file index
def read_nonblocking(self, size=1, timeout=None): try: s = os.read(self.child_fd, size) except OSError as err: if err.args[0] == errno.EIO: self.flag_eof = True raise EOF() raise if s == b: ...
This reads data from the file descriptor. This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it. The timeout parameter is ignored.
def get_dependency_walker(): for dirname in os.getenv(, ).split(os.pathsep): filename = os.path.join(dirname, ) if os.path.isfile(filename): logger.info(.format(filename)) return filename temp_exe = os.path.join(tempfile.gettempdir(), ) temp_dll = os.path.join(tempfile.gettempdir(), ) i...
Checks if `depends.exe` is in the system PATH. If not, it will be downloaded and extracted to a temporary directory. Note that the file will not be deleted afterwards. Returns the path to the Dependency Walker executable.
def list_tags(self, pattern=None): request_url = "{}tags".format(self.create_basic_url()) params = None if pattern: params = {: pattern} return_value = self._call_api(request_url, params=params) return return_value[]
List all tags made on this project. :param pattern: filters the starting letters of the return value :return:
def get_labs(format): techshops_soup = data_from_techshop_ws(techshop_us_url) techshops = {} data = techshops_soup.findAll(, attrs={: }) for element in data: links = element.findAll() hrefs = {} for k, a in enumerate(links): if "contact" not in a[]: ...
Gets Techshop data from techshop.ws.
def to_affine(aff, dims=None): if aff is None: return None if isinstance(aff, _tuple_type): if (len(aff) != 2 or not pimms.is_matrix(aff[0], ) or not pimms.is_vector(aff[1], )): raise ValueError() mtx = np.asarray(aff[0]) ...
to_affine(None) yields None. to_affine(data) yields an affine transformation matrix equivalent to that given in data. Such a matrix may be specified either as (matrix, offset_vector), as an (n+1)x(n+1) matrix, or, as an n x (n+1) matrix. to_affine(data, dims) additionally requires that the dimension...
def find_ge(self, item): k = self._key(item) i = bisect_left(self._keys, k) if i != len(self): return self._items[i] raise ValueError( % (k,))
Return first item with a key >= equal to item. Raise ValueError if not found
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): local_stream = utils.BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) self.length = lo...
Write the data encoding the Archive response payload to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining ...
def _Cobject(cls, ctype): o = object.__new__(cls) o._as_parameter_ = ctype return o
(INTERNAL) New instance from ctypes.
def radiation_values(self, location, timestep=1): sp = Sunpath.from_location(location) altitudes = [] dates = self._get_datetimes(timestep) for t_date in dates: sun = sp.calculate_sun_from_date_time(t_date) altitudes.append(sun.altitude) ...
Lists of driect normal, diffuse horiz, and global horiz rad at each timestep.
def node_indent(elt_name, node_id, fact_term, attribute, highlight_node=None): color_dict = {0: {0: , 1: , 2: , 3: , 4: , 5: , 6: , 7: , ...
This tag uses a table structure to display indentation of fact terms based on the information contained in the node identifier. This tag and the closing 'node_indent_end' tag must enclose the value to be displayed after the display of the fact term.
def jsonHook(encoded): if in encoded: return Ci._fromJSON(encoded[]) elif in encoded: return MzmlProduct._fromJSON(encoded[]) elif in encoded: return MzmlPrecursor._fromJSON(encoded[]) else: return encoded
Custom JSON decoder that allows construction of a new ``Ci`` instance from a decoded JSON object. :param encoded: a JSON decoded object literal (a dict) :returns: "encoded" or one of the these objects: :class:`Ci`, :class:`MzmlProduct`, :class:`MzmlPrecursor`
def _initialize_context(self, trace_header): sampled = None if not global_sdk_config.sdk_enabled(): sampled = False elif trace_header.sampled == 0: sampled = False elif trace_header.sampled == 1: sampled = True segment = ...
Create a facade segment based on environment variables set by AWS Lambda and initialize storage for subsegments.
def revealjs(basedir=None, title=None, subtitle=None, description=None, github_user=None, github_repo=None): basedir = basedir or query_input(, default=) revealjs_repo_name = revealjs_dir = flo() _lazy_dict[] = title _lazy_dict[] = subtitle ...
Set up or update a reveals.js presentation with slides written in markdown. Several reveal.js plugins will be set up, too. More info: Demo: https://theno.github.io/revealjs_template http://lab.hakim.se/reveal-js/ https://github.com/hakimel/reveal.js plugins: https://github.com/...
def reverse(self): colors = ColorList.copy(self) _list.reverse(colors) return colors
Returns a reversed copy of the list.
def dc(result, reference): r result = numpy.atleast_1d(result.astype(numpy.bool)) reference = numpy.atleast_1d(reference.astype(numpy.bool)) intersection = numpy.count_nonzero(result & reference) size_i1 = numpy.count_nonzero(result) size_i2 = numpy.count_nonzero(reference) tr...
r""" Dice coefficient Computes the Dice coefficient (also known as Sorensen index) between the binary objects in two images. The metric is defined as .. math:: DC=\frac{2|A\cap B|}{|A|+|B|} , where :math:`A` is the first and :math:`B` the second set of sa...
def stop(name, kill=False, path=None, use_vt=None): _ensure_exists(name, path=path) orig_state = state(name, path=path) if orig_state == and not kill: return ret
Stop the named container path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 kill: False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespec...
def destroy(self, blocking=False): if self._jbroadcast is None: raise Exception("Broadcast can only be destroyed in driver") self._jbroadcast.destroy(blocking) os.unlink(self._path)
Destroy all data and metadata related to this broadcast variable. Use this with caution; once a broadcast variable has been destroyed, it cannot be used again. .. versionchanged:: 3.0.0 Added optional argument `blocking` to specify whether to block until all blocks are del...
def get_gafvals(self, line): flds = line.split() flds[3] = self._get_qualifier(flds[3]) flds[5] = self._get_set(flds[5]) flds[7] = self._get_set(flds[7]) flds[8] = self.aspect2ns[flds[8]] flds[9] = self._get_set(flds[9]) flds[10] = s...
Convert fields from string to preferred format for GAF ver 2.1 and 2.0.
def get_or_create_exh_obj(full_cname=False, exclude=None, callables_fname=None): r if not hasattr(__builtin__, "_EXH"): set_exh_obj( ExHandle( full_cname=full_cname, exclude=exclude, callables_fname=callables_fname ) ) return get_exh_obj()
r""" Return global exception handler if set, otherwise create a new one and return it. :param full_cname: Flag that indicates whether fully qualified function/method/class property names are obtained for functions/methods/class properties that use the ...
def _init_template(self, cls, base_init_template): if self.__class__ is not cls: raise TypeError("Inheritance from classes with @GtkTemplate decorators " "is not allowed at this time") connected_signals = set() self.__connected_template_signals__ = connected_...
This would be better as an override for Gtk.Widget
def to_bytes(s, encoding="utf-8"): if isinstance(s, six.binary_type): return s else: return six.text_type(s).encode(encoding)
Converts the string to a bytes type, if not already. :s: the string to convert to bytes :returns: `str` on Python2 and `bytes` on Python3.
def get_vmpolicy_macaddr_input_datacenter(self, **kwargs): config = ET.Element("config") get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr") config = get_vmpolicy_macaddr input = ET.SubElement(get_vmpolicy_macaddr, "input") datacenter = ET.SubElement(input, "datace...
Auto Generated Code
def find(default=, whole_words=0, case_sensitive=0, parent=None): "Shows a find text dialog" result = dialogs.findDialog(parent, default, whole_words, case_sensitive) return {: result.searchText, : result.wholeWordsOnly, : result.caseSensitive}
Shows a find text dialog
def offset_overlays(self, text, offset=0, **kw): if not isinstance(text, OverlayedText): text = OverlayedText(text) for m in self.regex.finditer(unicode(text)[offset:]): yield Overlay(text, (offset + m.start(), offset + m.end()), ...
Generate overlays after offset. :param text: The text to be searched. :param offset: Match starting that index. If none just search. :returns: An overlay or None
def random_boggle(n=4): cubes = [cubes16[i % 16] for i in range(n*n)] random.shuffle(cubes) return map(random.choice, cubes)
Return a random Boggle board of size n x n. We represent a board as a linear list of letters.
def readQuotes(self, start, end): rows = self.__hbase.scanTable(self.tableName(HBaseDAM.QUOTE), [HBaseDAM.QUOTE], start, end) return [self.__rowResultToQuote(row) for row in rows]
read quotes
def _fetch(self, request): client = self.client call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) request.call = call
Fetch using the OkHttpClient
def revoke_token(self, token, callback): yield Task(self.data_store.remove, , token=token) callback()
revoke_token removes the access token from the data_store
def _get_domain_id(self, domain): api = self.api[self.account][] qdomain = dns.name.from_text(domain).to_unicode(True) domains, last_count, page = {}, -1, 0 while last_count != len(domains): last_count = len(domains) page += 1 url = (api[].cop...
Pulls all domains managed by authenticated Hetzner account, extracts their IDs and returns the ID for the current domain, if exists. Otherwise raises error.
def choose_plural(amount, variants): if isinstance(variants, six.text_type): variants = split_values(variants) check_length(variants, 3) amount = abs(amount) if amount % 10 == 1 and amount % 100 != 11: variant = 0 elif amount % 10 >= 2 and amount % 10 <= 4 and \ ...
Choose proper case depending on amount @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with deli...
def ow_search(self, vid=0xBC, pid=None, name=None): for m in self.get_mems(MemoryElement.TYPE_1W): if pid and m.pid == pid or name and m.name == name: return m return None
Search for specific memory id/name and return it
def compile_fund(workbook, sheet, row, col): logger_excel.info("enter compile_fund") l = [] temp_sheet = workbook.sheet_by_name(sheet) while col < temp_sheet.ncols: col += 1 try: _curr = { : temp_sheet.cell_value(row, col), : ...
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty. :param obj workbook: :param str sheet: :param int row: :param int col: :return list of dict: l
def get(self, key, default=None, type=None): try: value = self[key] if type is not None: return type(value) return value except (KeyError, ValueError): return default
Returns the first value for a key. If `type` is not None, the value will be converted by calling `type` with the value as argument. If type() raises `ValueError`, it will be treated as if the value didn't exist, and `default` will be returned instead.
def get_info(self, full=False): " Return printable information about current site. " if full: context = self.as_dict() return "".join("{0:<25} = {1}\n".format( key, context[key]) for key in sorted(context.iterkeys())) return "%s [%s]" % (self.g...
Return printable information about current site.
def is_indexed(self, partition): query = text() result = self.execute(query, vid=partition.vid) return bool(result.fetchall())
Returns True if partition is already indexed. Otherwise returns False.
def write_collection_data(self, path, data): flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC fd = os.open(path, flags, 0o600) with os.fdopen(fd, ) as dyn_conf_file: dyn_conf_file.write(data)
Write collections rules to disk
def _prop_name(self): if in self._nsptagname: start = self._nsptagname.index() + 1 else: start = 0 return self._nsptagname[start:]
Calculate property name from tag name, e.g. a:schemeClr -> schemeClr.
def set_entries(self, entries, user_scope): route_values = {} if user_scope is not None: route_values[] = self._serialize.url(, user_scope, ) content = self._serialize.body(entries, ) self._send(http_method=, location_id=, versio...
SetEntries. [Preview API] Set the specified setting entry values for the given user/all-users scope :param {object} entries: The entries to set :param str user_scope: User-Scope at which to set the values. Should be "me" for the current user or "host" for all users.
def gen_key(minion_id, dns_name=None, zone=, password=None): qdata = __utils__[]( .format(_base_url(), zone), method=, decode=True, decode_type=, header_dict={ : _api_key(), : , }, ) zone_id = qdata[][] ...
Generate and return an private_key. If a ``dns_name`` is passed in, the private_key will be cached under that name. The type of key and the parameters used to generate the key are based on the default certificate use policy associated with the specified zone. CLI Example: .. code-block:: bash ...
def _set_port_security(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=port_security.port_security, is_container=, presence=True, yang_name="port-security", rest_name="port-security", parent=self, path_helper=self._path_helper, extmethods=self._extmet...
Setter method for port_security, mapped from YANG variable /interface/ethernet/switchport/port_security (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_security is considered as a private method. Backends looking to populate this variable should do so vi...
def key_rule(self, regex, verifier): if regex is not None: regex = re.compile(regex) self._additional_key_rules.append((regex, verifier))
Add a rule with a pattern that should apply to all keys. Any key not explicitly listed in an add_required or add_optional rule must match ONE OF the rules given in a call to key_rule(). So these rules are all OR'ed together. In this case you should pass a raw string specifying a regex ...
def cudnnCreateConvolutionDescriptor(): convDesc = ctypes.c_void_p() status = _libcudnn.cudnnCreateConvolutionDescriptor(ctypes.byref(convDesc)) cudnnCheckStatus(status) return convDesc.value
Create a convolution descriptor. This function creates a convolution descriptor object by allocating the memory needed to hold its opaque structure. Returns ------- convDesc : cudnnConvolutionDescriptor Handle to newly allocated convolution descriptor.
def git_list_refs(repo_dir): command = [, , , ] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = [l.strip() for l in raw if l.strip()] return {ref: commit_hash for commit_hash, ref in [l.split(None, 1) for l in output]}
List references available in the local repo with commit ids. This is similar to ls-remote, but shows the *local* refs. Return format: .. code-block:: python {<ref1>: <commit_hash1>, <ref2>: <commit_hash2>, ..., <refN>: <commit_hashN>, }
def distortion_score(X, labels, metric=): le = LabelEncoder() labels = le.fit_transform(labels) unique_labels = le.classes_ distortion = 0 for current_label in unique_labels: mask = labels == current_label instances = X[mask] center = ...
Compute the mean distortion of all samples. The distortion is computed as the the sum of the squared distances between each observation and its closest centroid. Logically, this is the metric that K-Means attempts to minimize as it is fitting the model. .. seealso:: http://kldavenport.com/the-cost-fun...
def is_virtual_host(endpoint_url, bucket_name): is_valid_bucket_name(bucket_name) parsed_url = urlsplit(endpoint_url) if in parsed_url.scheme and in bucket_name: return False for host in [, ]: if host in parsed_url.netloc: return True return False
Check to see if the ``bucket_name`` can be part of virtual host style. :param endpoint_url: Endpoint url which will be used for virtual host. :param bucket_name: Bucket name to be validated against.
def import_lane_element(lane_element, plane_element): lane_id = lane_element.getAttribute(consts.Consts.id) lane_name = lane_element.getAttribute(consts.Consts.name) child_lane_set_attr = {} flow_node_refs = [] for element in utils.BpmnImportUtils.iterate_elements(lane_e...
Method for importing 'laneSet' element from diagram file. :param lane_element: XML document element, :param plane_element: object representing a BPMN XML 'plane' element.
def get_ancestors(self, obj): def _get_ancestors(code, needle): for node in code.nodes: if node is needle: return [] for code in node.__children__(): ancestors = _get_ancestors(code, needle) if ances...
Return a list of all ancestor nodes of the :class:`.Node` *obj*. The list is ordered from the most shallow ancestor (greatest great- grandparent) to the direct parent. The node itself is not included in the list. For example:: >>> text = "{{a|{{b|{{c|{{d}}}}}}}}" >>> co...
def get_etree_layout_as_dict(layout_tree): layout_dict = dict() for item in layout_tree.findall(): name = item.find().text val_element = item.find() value = val_element.text.strip() if value == : children = val_element.getchildren() value = etree.to...
Convert something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> <value>blah.shp</value> </item> </layout> Into something that looks like this: { 'co...
def guessFormat(self, name): name = name.lower() generator = self.generator if re.findall(r, name): return lambda x:generator.boolean() if re.findall(r, name): return lambda x:generator.dateTime() if name in (,): return lambda x: generator.firstName() if name in...
:param name: :type name: str
def _CreateConfig(self, project_id): project_id = project_id or self._GetNumericProjectId() config.WriteConfig(config_file=self.boto_config)
Create the boto config to support standalone GSUtil. Args: project_id: string, the project ID to use in the config file.
def rewind(self, position=0): if position < 0 or position > len(self._data): raise Exception("Invalid position to rewind cursor to: %s." % position) self._position = position
Set the position of the data buffer cursor to 'position'.
def calc_path_and_create_folders(folder, import_path): file_path = abspath(path_join(folder, import_path[:import_path.rfind(".")].replace(".", folder_seperator) + ".py")) mkdir_p(dirname(file_path)) return file_path
calculate the path and create the needed folders
def _ExtractPathSpecsFromDirectory(self, file_entry, depth=0): if depth >= self._MAXIMUM_DEPTH: raise errors.MaximumRecursionDepth()
Extracts path specification from a directory. Args: file_entry (dfvfs.FileEntry): file entry that refers to the directory. depth (Optional[int]): current depth where 0 represents the file system root. Yields: dfvfs.PathSpec: path specification of a file entry found in the directory...
def service_endpoint_policy_definitions(self): api_version = self._get_api_version() if api_version == : from .v2018_07_01.operations import ServiceEndpointPolicyDefinitionsOperations as OperationClass elif api_version == : from .v2018_08_01.operations import Ser...
Instance depends on the API version: * 2018-07-01: :class:`ServiceEndpointPolicyDefinitionsOperations<azure.mgmt.network.v2018_07_01.operations.ServiceEndpointPolicyDefinitionsOperations>` * 2018-08-01: :class:`ServiceEndpointPolicyDefinitionsOperations<azure.mgmt.network.v2018_08_01.operations.S...
def poke_8(library, session, address, data): return library.viPoke8(session, address, data)
Write an 8-bit value from the specified address. Corresponds to viPoke8 function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the value. :param data: value to be written to th...
def pop_value(instance, path, ref=None): head, tail = os.path.split(abspath(path, ref)) instance = get_value(instance, head) if isinstance(instance, list): tail = int(tail) return instance.pop(tail)
Pop the value from `instance` at the given `path`. Parameters ---------- instance : dict or list instance from which to retrieve a value path : str path to retrieve a value from ref : str or None reference path if `path` is relative Returns ------- value : ...
def get_monitor_physical_size(monitor): width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return width_value.value, height_value.value
Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);
def build(subparsers): parser = subparsers.add_parser( , help=, description=build.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=) parser.set_defaults(run_command=run_metapack) parser.add_argument(, nargs=, help=...
Build source packages. The mp build program runs all of the resources listed in a Metatab file and produces one or more Metapack packages with those resources localized. It will always try to produce a Filesystem package, and may optionally produce Excel, Zip and CSV packages. Typical usage is to ...
def update(self): self.stats = datetime.now().strftime() if in localtime(): self.stats += .format(localtime().tm_zone) elif len(tzname) > 0: self.stats += .format(tzname[1]) return self.stats
Update current date/time.
def _iter_year_month(year_info): leap_month, leap_days = _parse_leap(year_info) months = [(i, 0) for i in range(1, 13)] if leap_month > 0: months.insert(leap_month, (leap_month, 1)) for month, leap in months: if leap: days = leap_days else: days...
Iter the month days in a lunar year.
def _prnt_min_max_val(var, text, verb): r if var.size > 3: print(text, _strvar(var.min()), "-", _strvar(var.max()), ":", _strvar(var.size), " [min-max; if verb > 3: print(" : ", _strvar(var)) else: print(text, _strvar(np.atleast_1d(var)))
r"""Print variable; if more than three, just min/max, unless verb > 3.
def results_tc(self, key, value): if os.access(self.default_args.tc_out_path, os.W_OK): results_file = .format(self.default_args.tc_out_path) else: results_file = new = True open(results_file, ).close() with open(results_file, ) as fh: ...
Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (strin...
def ge(self, value): self.op = self.negate_op = self.value = self._value(value) return self
Construct a greater than or equal to (``>=``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field