code
stringlengths
64
7.01k
docstring
stringlengths
2
15.8k
text
stringlengths
144
19.2k
#vtb def time_in_range(self): curr = datetime.datetime.now().time() if self.start_time <= self.end_time: return self.start_time <= curr <= self.end_time else: return self.start_time <= curr or curr <= self.end_time
Return true if current time is in the active range
### Input: Return true if current time is in the active range ### Response: #vtb def time_in_range(self): curr = datetime.datetime.now().time() if self.start_time <= self.end_time: return self.start_time <= curr <= self.end_time else: return self.start_time <= ...
#vtb def load_config(): filename = keyring_cfg = os.path.join(platform.config_root(), filename) if not os.path.exists(keyring_cfg): return config = configparser.RawConfigParser() config.read(keyring_cfg) _load_keyring_path(config) try: if config.has_section("b...
Load a keyring using the config file in the config root.
### Input: Load a keyring using the config file in the config root. ### Response: #vtb def load_config(): filename = keyring_cfg = os.path.join(platform.config_root(), filename) if not os.path.exists(keyring_cfg): return config = configparser.RawConfigParser() config.read(keyring...
#vtb def sayHello(self, name="Not given", message="nothing"): print( "Python.sayHello called by: {0} " "with message: ".format(name, message) ) return ( "PythonSync says: Howdy {0} " "that's a nice runtime you got there".format(name) ...
Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds.
### Input: Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds. ### Response: #vtb def sayHello(self, name="Not given", message="nothing"): print( "Python.sayHello called by: {0} " ...
#vtb def set_connection(host=None, database=None, user=None, password=None): c.CONNECTION[] = host c.CONNECTION[] = database c.CONNECTION[] = user c.CONNECTION[] = password
Set connection parameters. Call set_connection with no arguments to clear.
### Input: Set connection parameters. Call set_connection with no arguments to clear. ### Response: #vtb def set_connection(host=None, database=None, user=None, password=None): c.CONNECTION[] = host c.CONNECTION[] = database c.CONNECTION[] = user c.CONNECTION[] = password
#vtb def __build_author_name_expr(author_name, author_email_address): assert author_name or author_email_address, author_name_expr = author_name or author_email_address[:author_email_address.find()] if in author_name_expr: author_name_expr = % author_name_expr if a...
Build the name of the author of a message as described in the Internet Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2 @param author_name: complete name of the originator of the message. @param author_email_address: address of the mailbox to which the author of the...
### Input: Build the name of the author of a message as described in the Internet Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2 @param author_name: complete name of the originator of the message. @param author_email_address: address of the mailbox to which the author ...
#vtb def zip_entry_rollup(zipfile): files = dirs = 0 total_c = total_u = 0 for i in zipfile.infolist(): if i.filename[-1] == : dirs += 1 else: files += 1 total_c += i.compress_size total_u += i.file_size return files, d...
returns a tuple of (files, dirs, size_uncompressed, size_compressed). files+dirs will equal len(zipfile.infolist)
### Input: returns a tuple of (files, dirs, size_uncompressed, size_compressed). files+dirs will equal len(zipfile.infolist) ### Response: #vtb def zip_entry_rollup(zipfile): files = dirs = 0 total_c = total_u = 0 for i in zipfile.infolist(): if i.filename[-1] == : ...
#vtb def _get_reference(self): super()._get_reference() self.cubeA_body_id = self.sim.model.body_name2id("cubeA") self.cubeB_body_id = self.sim.model.body_name2id("cubeB") self.l_finger_geom_ids = [ self.sim.model.geom_name2id(x) for x in self.gripper.left_finger_geo...
Sets up references to important components. A reference is typically an index or a list of indices that point to the corresponding elements in a flatten array, which is how MuJoCo stores physical simulation data.
### Input: Sets up references to important components. A reference is typically an index or a list of indices that point to the corresponding elements in a flatten array, which is how MuJoCo stores physical simulation data. ### Response: #vtb def _get_reference(self): super()._get_ref...
#vtb def create_app(config=, override=None, init_logging=init_logging): app = UDataApp(APP_NAME) app.config.from_object(config) settings = os.environ.get(, join(os.getcwd(), )) if exists(settings): app.settings_file = settings app.config.from_pyfile(settings) ...
Factory for a minimal application
### Input: Factory for a minimal application ### Response: #vtb def create_app(config=, override=None, init_logging=init_logging): app = UDataApp(APP_NAME) app.config.from_object(config) settings = os.environ.get(, join(os.getcwd(), )) if exists(settings): app.settings_fil...
#vtb def validate_data(self): warnings = {} spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {} if self.specimens: spec_warnings = self.validate_items(self.specimens, ) if self.samples: samp_warnings = self.validate_items(self.sampl...
Validate specimen, sample, site, and location data.
### Input: Validate specimen, sample, site, and location data. ### Response: #vtb def validate_data(self): warnings = {} spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {} if self.specimens: spec_warnings = self.validate_items(self.specimens, ) ...
#vtb def get_locations(): arequest = requests.get(LOCATIONS_URL, headers=HEADERS) status_code = str(arequest.status_code) if status_code == : _LOGGER.error("Token expired.") return False return arequest.json()
Pull the accounts locations.
### Input: Pull the accounts locations. ### Response: #vtb def get_locations(): arequest = requests.get(LOCATIONS_URL, headers=HEADERS) status_code = str(arequest.status_code) if status_code == : _LOGGER.error("Token expired.") return False return arequ...
#vtb def guess_labels(self, doc): if doc.nb_pages <= 0: return set() self.label_guesser.total_nb_documents = len(self._docs_by_id.keys()) label_names = self.label_guesser.guess(doc) labels = set() for label_name in label_names: label = self.labels...
return a prediction of label names
### Input: return a prediction of label names ### Response: #vtb def guess_labels(self, doc): if doc.nb_pages <= 0: return set() self.label_guesser.total_nb_documents = len(self._docs_by_id.keys()) label_names = self.label_guesser.guess(doc) labels = set() ...
#vtb def _at_extend(self, calculator, rule, scope, block): from scss.selector import Selector selectors = calculator.apply_vars(block.argument) rule.extends_selectors.extend(Selector.parse_many(selectors))
Implements @extend
### Input: Implements @extend ### Response: #vtb def _at_extend(self, calculator, rule, scope, block): from scss.selector import Selector selectors = calculator.apply_vars(block.argument) rule.extends_selectors.extend(Selector.parse_many(selectors))
#vtb def wrap(x): if isinstance(x, G1Element): return _wrap(x, serializeG1) elif isinstance(x, G2Element): return _wrap(x, serializeG2) elif isinstance(x, GtElement): return _wrap(x, serializeGt) elif isinstance(x, str): return x elif isinstance(...
Wraps an element or integer type by serializing it and base64 encoding the resulting bytes.
### Input: Wraps an element or integer type by serializing it and base64 encoding the resulting bytes. ### Response: #vtb def wrap(x): if isinstance(x, G1Element): return _wrap(x, serializeG1) elif isinstance(x, G2Element): return _wrap(x, serializeG2) elif isinstance(x, G...
#vtb def set_event_data(self, data, read_attrs): if self.handle.mode == : raise Exception() read_number = read_attrs[] read_group = .format(self.group_name, read_number) read_info = self.handle.status.read_info read_number_map = self.handle.status.read_number...
Set event data with the specied attributes. :param data: Event data table. :param read_attrs: Attributes to put on the read group. This must include the read_number, which must refer to a read present in the object. The attributes should not include the standard read att...
### Input: Set event data with the specied attributes. :param data: Event data table. :param read_attrs: Attributes to put on the read group. This must include the read_number, which must refer to a read present in the object. The attributes should not include the stand...
#vtb def _construct_w(self, inputs): depthwise_weight_shape = self._kernel_shape + (self._input_channels, self._channel_multiplier) pointwise_input_size = self._channel_multiplier * self._input_channels pointwise_weight_shape = (1, 1, pointwise_input_s...
Connects the module into the graph, with input Tensor `inputs`. Args: inputs: A 4D Tensor of shape: [batch_size, input_height, input_width, input_channels] and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: A tuple of two 4D Tensors, each with the same dtype as `...
### Input: Connects the module into the graph, with input Tensor `inputs`. Args: inputs: A 4D Tensor of shape: [batch_size, input_height, input_width, input_channels] and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: A tuple of two 4D Tensors, each with the sam...
#vtb def _parse_geometry(geometry): if isinstance(geometry, str): geometry = shapely.wkt.loads(geometry) elif isinstance(geometry, dict): geometry = shapely.geometry.shape(geometry) elif not isinstance(geometry, shapely.geometry.base.BaseGeometry): ra...
Parses given geometry into shapely object :param geometry: :return: Shapely polygon or multipolygon :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon :raises TypeError
### Input: Parses given geometry into shapely object :param geometry: :return: Shapely polygon or multipolygon :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon :raises TypeError ### Response: #vtb def _parse_geometry(geometry): if isinstance(geometry,...
#vtb def _add_arg_python(self, key, value=None, mask=False): self._data[key] = value if not value: pass elif value is True: self._args.append(.format(key)) self._args_quoted.append(.format(key)) self._args_masked....
Add CLI Arg formatted specifically for Python. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
### Input: Add CLI Arg formatted specifically for Python. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value. ### Response: #vtb def _add_arg_python(self, key, ...
#vtb def _create_page_control(self): if self.custom_page_control: control = self.custom_page_control() elif self.kind == : control = QtGui.QPlainTextEdit() elif self.kind == : control = QtGui.QTextEdit() control.installEventFilter(self) ...
Creates and connects the underlying paging widget.
### Input: Creates and connects the underlying paging widget. ### Response: #vtb def _create_page_control(self): if self.custom_page_control: control = self.custom_page_control() elif self.kind == : control = QtGui.QPlainTextEdit() elif self.kind == : ...
#vtb def limit(self, limit_value, key_func=None, per_method=False, methods=None, error_message=None, exempt_when=None): return self.__limit_decorator(limit_value, key_func, per_method=per_method, methods=methods, error_message=error_message, ...
decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param function key_func: function/lambda to extract the unique identifier for the rate limit. defaults to rem...
### Input: decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param function key_func: function/lambda to extract the unique identifier for the rate limit. def...
#vtb def ruamel_structure(data, validator=None): if isinstance(data, dict): if len(data) == 0: raise exceptions.CannotBuildDocumentsFromEmptyDictOrList( "Document must be built with non-empty dicts and lists" ) return CommentedMap( [ ...
Take dicts and lists and return a ruamel.yaml style structure of CommentedMaps, CommentedSeqs and data. If a validator is presented and the type is unknown, it is checked against the validator to see if it will turn it back in to YAML.
### Input: Take dicts and lists and return a ruamel.yaml style structure of CommentedMaps, CommentedSeqs and data. If a validator is presented and the type is unknown, it is checked against the validator to see if it will turn it back in to YAML. ### Response: #vtb def ruamel_structure(data, vali...
#vtb def _copy_selection(self, *event): if react_to_event(self.view, self.view.editor, event): logger.debug("copy selection") global_clipboard.copy(self.model.selection) return True
Copies the current selection to the clipboard.
### Input: Copies the current selection to the clipboard. ### Response: #vtb def _copy_selection(self, *event): if react_to_event(self.view, self.view.editor, event): logger.debug("copy selection") global_clipboard.copy(self.model.selection) return True
#vtb def getquals(args): p = OptionParser(getquals.__doc__) p.add_option("--types", default="gene,mRNA,CDS", type="str", dest="quals_ftypes", help="Feature types from which to extract qualifiers") p.add_option("--ignore", default="locus_tag,product,codon_start,translatio...
%prog getquals [--options] gbkfile > qualsfile Read GenBank file and extract all qualifiers per feature type into a tab-delimited file
### Input: %prog getquals [--options] gbkfile > qualsfile Read GenBank file and extract all qualifiers per feature type into a tab-delimited file ### Response: #vtb def getquals(args): p = OptionParser(getquals.__doc__) p.add_option("--types", default="gene,mRNA,CDS", type="str",...
#vtb def SetPlatformArchContext(): _CONFIG.AddContext("Platform:%s" % platform.system().title()) machine = platform.uname()[4] if machine in ["x86_64", "AMD64", "i686"]: if platform.architecture()[0] == "32bit": arch = "i386" else: arch = "amd64" elif machine == "x86": arch ...
Add the running contexts to the config system.
### Input: Add the running contexts to the config system. ### Response: #vtb def SetPlatformArchContext(): _CONFIG.AddContext("Platform:%s" % platform.system().title()) machine = platform.uname()[4] if machine in ["x86_64", "AMD64", "i686"]: if platform.architecture()[0] == "32bit": arch ...
#vtb def logBranch(self, indent=0, level=logging.DEBUG): if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childItems: childItems.logBranch(indent + 1, level=level)
Logs the item and all descendants, one line per child
### Input: Logs the item and all descendants, one line per child ### Response: #vtb def logBranch(self, indent=0, level=logging.DEBUG): if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childIte...
#vtb def rev_comp(seq): rev_seq = seq[::-1] rev_comp_seq = .join([base_pairing[s] for s in rev_seq]) return rev_comp_seq
Get reverse complement of sequence. rev_comp will maintain the case of the sequence. Parameters ---------- seq : str nucleotide sequence. valid {a, c, t, g, n} Returns ------- rev_comp_seq : str reverse complement of sequence
### Input: Get reverse complement of sequence. rev_comp will maintain the case of the sequence. Parameters ---------- seq : str nucleotide sequence. valid {a, c, t, g, n} Returns ------- rev_comp_seq : str reverse complement of sequence ### Response: #vtb def rev_comp(se...
#vtb def local_open(url): scheme, server, path, param, query, frag = urllib.parse.urlparse(url) filename = urllib.request.url2pathname(path) if os.path.isfile(filename): return urllib.request.urlopen(url) elif path.endswith() and os.path.isdir(filename): files = [] for f in ...
Read a local path, with special support for directories
### Input: Read a local path, with special support for directories ### Response: #vtb def local_open(url): scheme, server, path, param, query, frag = urllib.parse.urlparse(url) filename = urllib.request.url2pathname(path) if os.path.isfile(filename): return urllib.request.urlopen(url) eli...
#vtb def cmd_tcpscan(ip, port, iface, flags, sleeptime, timeout, show_all, verbose): if verbose: logging.basicConfig(level=logging.INFO, format=) conf.verb = False if iface: conf.iface = iface port_regex = r if not re.match(port_regex, port): logging.critical("Inval...
TCP Port Scanner. Print the ports that generated a response with the SYN flag or (if show use -a) all the ports that generated a response. It's really basic compared with nmap, but who is comparing? Example: \b # habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133 22 S -> SA 80 S -> SA ...
### Input: TCP Port Scanner. Print the ports that generated a response with the SYN flag or (if show use -a) all the ports that generated a response. It's really basic compared with nmap, but who is comparing? Example: \b # habu.tcpscan -p 22,23,80,443 -s 1 45.77.113.133 22 S -> SA ...
#vtb def options(argv=[]): parser = HendrixOptionParser parsed_args = parser.parse_args(argv) return vars(parsed_args[0])
A helper function that returns a dictionary of the default key-values pairs
### Input: A helper function that returns a dictionary of the default key-values pairs ### Response: #vtb def options(argv=[]): parser = HendrixOptionParser parsed_args = parser.parse_args(argv) return vars(parsed_args[0])
#vtb def ber_code(self): try: alt_text = self._ad_page_content.find( , {: } ).find()[] if ( in alt_text): return else: alt_arr = alt_text.split() if in alt_arr[0].lower(): ...
This method gets ber code listed in Daft. :return:
### Input: This method gets ber code listed in Daft. :return: ### Response: #vtb def ber_code(self): try: alt_text = self._ad_page_content.find( , {: } ).find()[] if ( in alt_text): return else: ...
#vtb def is_img_id_valid(img_id): t = re.sub(r, , img_id, re.IGNORECASE) t = re.sub(r, , t) if img_id != t or img_id.count() != 1: return False profile, base_name = img_id.split(, 1) if not profile or not base_name: return False try: get_profile_configs(profile) ...
Checks if img_id is valid.
### Input: Checks if img_id is valid. ### Response: #vtb def is_img_id_valid(img_id): t = re.sub(r, , img_id, re.IGNORECASE) t = re.sub(r, , t) if img_id != t or img_id.count() != 1: return False profile, base_name = img_id.split(, 1) if not profile or not base_name: return Fa...
#vtb def mean_by_panel(self, length): self._check_panel(length) func = lambda v: v.reshape(-1, length).mean(axis=0) newindex = arange(length) return self.map(func, index=newindex)
Compute the mean across fixed sized panels of each record. Splits each record into panels of size `length`, and then computes the mean across panels. Panel length must subdivide record exactly. Parameters ---------- length : int Fixed length with which to su...
### Input: Compute the mean across fixed sized panels of each record. Splits each record into panels of size `length`, and then computes the mean across panels. Panel length must subdivide record exactly. Parameters ---------- length : int Fixed length with...
#vtb def check_str(obj): if isinstance(obj, str): return obj if isinstance(obj, float): return str(int(obj)) else: return str(obj)
Returns a string for various input types
### Input: Returns a string for various input types ### Response: #vtb def check_str(obj): if isinstance(obj, str): return obj if isinstance(obj, float): return str(int(obj)) else: return str(obj)
#vtb def _parse_wsgi_headers(wsgi_environ): prefix = p_len = len(prefix) headers = { key[p_len:].replace(, ).lower(): val for (key, val) in wsgi_environ.items() if key.startswith(prefix)} return headers
HTTP headers are presented in WSGI environment with 'HTTP_' prefix. This method finds those headers, removes the prefix, converts underscores to dashes, and converts to lower case. :param wsgi_environ: :return: returns a dictionary of headers
### Input: HTTP headers are presented in WSGI environment with 'HTTP_' prefix. This method finds those headers, removes the prefix, converts underscores to dashes, and converts to lower case. :param wsgi_environ: :return: returns a dictionary of headers ### Response: #vtb def _parse_w...
#vtb def consume_changes(self, start, end): left, right = self._get_changed(start, end) if left < right: del self.lines[left:right] return left < right
Clear the changed status of lines from start till end
### Input: Clear the changed status of lines from start till end ### Response: #vtb def consume_changes(self, start, end): left, right = self._get_changed(start, end) if left < right: del self.lines[left:right] return left < right
#vtb async def deregister(self, check): check_id = extract_attr(check, keys=["CheckID", "ID"]) response = await self._api.get("/v1/agent/check/deregister", check_id) return response.status == 200
Deregisters a local check Parameters: check (ObjectID): Check ID Returns: bool: ``True`` on success The agent will take care of deregistering the check from the Catalog.
### Input: Deregisters a local check Parameters: check (ObjectID): Check ID Returns: bool: ``True`` on success The agent will take care of deregistering the check from the Catalog. ### Response: #vtb async def deregister(self, check): check_id = extra...
#vtb def set(ctx, key, value): if key == "default_account" and value[0] == "@": value = value[1:] ctx.bitshares.config[key] = value
Set configuration parameters
### Input: Set configuration parameters ### Response: #vtb def set(ctx, key, value): if key == "default_account" and value[0] == "@": value = value[1:] ctx.bitshares.config[key] = value
#vtb def price_change(self): try: if self._data_from_search: return self._data_from_search.find(, {: }).text else: return self._ad_page_content.find(, {: }).text except Exception as e: if self._debug: logging.er...
This method returns any price change. :return:
### Input: This method returns any price change. :return: ### Response: #vtb def price_change(self): try: if self._data_from_search: return self._data_from_search.find(, {: }).text else: return self._ad_page_content.find(, {: }).text ...
#vtb def fromJSON(value): j = json.loads(value) v = GPString() if "defaultValue" in j: v.value = j[] else: v.value = j[] if in j: v.paramName = j[] elif in j: v.paramName = j[] return v
loads the GP object from a JSON string
### Input: loads the GP object from a JSON string ### Response: #vtb def fromJSON(value): j = json.loads(value) v = GPString() if "defaultValue" in j: v.value = j[] else: v.value = j[] if in j: v.paramName = j[] elif in j: ...
#vtb def delete_image(self, identifier): if isinstance(identifier, dict): identifier = identifier.get(, ) j, r = self.request(, + str(identifier)) r.raise_for_status() return j
:: DELETE /:login/images/:id :param identifier: match on the listed image identifier :type identifier: :py:class:`basestring` or :py:class:`dict` A string or a dictionary containing an ``id`` key may be passed in. Will raise an error if the response...
### Input: :: DELETE /:login/images/:id :param identifier: match on the listed image identifier :type identifier: :py:class:`basestring` or :py:class:`dict` A string or a dictionary containing an ``id`` key may be passed in. Will raise an error if ...
#vtb def remove_entry(self, entry): if not isinstance(entry, Entry): raise TypeError("entry param must be of type Entry.") if not entry in self.entries: raise ValueError("Entry doesn't exist / not bound to this datbase.") entry.group.entries.remove(entry...
Remove specified entry. :param entry: The Entry object to remove. :type entry: :class:`keepassdb.model.Entry`
### Input: Remove specified entry. :param entry: The Entry object to remove. :type entry: :class:`keepassdb.model.Entry` ### Response: #vtb def remove_entry(self, entry): if not isinstance(entry, Entry): raise TypeError("entry param must be of type Entry.") ...
#vtb def addText(self, text): self.moveCursor(QtGui.QTextCursor.End) self.setTextColor(self._currentColor) self.textCursor().insertText(text)
append text in the chosen color
### Input: append text in the chosen color ### Response: #vtb def addText(self, text): self.moveCursor(QtGui.QTextCursor.End) self.setTextColor(self._currentColor) self.textCursor().insertText(text)
#vtb def robot_files(self): result = [] for name in os.listdir(self.path): fullpath = os.path.join(self.path, name) if os.path.isdir(fullpath): result.append(RobotFactory(fullpath, parent=self)) else: if ((name.endswith(".txt")...
Return a list of all folders, and test suite files (.txt, .robot)
### Input: Return a list of all folders, and test suite files (.txt, .robot) ### Response: #vtb def robot_files(self): result = [] for name in os.listdir(self.path): fullpath = os.path.join(self.path, name) if os.path.isdir(fullpath): result.append(Robo...
#vtb def load_preferences(session, config, valid_paths, cull_disabled=False, openid=None, cull_backends=None): cull_backends = cull_backends or [] query = session.query(fmn.lib.models.Preference) if openid: query = query.filter(fmn.lib.models.Prefere...
Every rule for every filter for every context for every user. Any preferences in the DB that are for contexts that are disabled in the config are omitted here. If the `openid` argument is None, then this is an expensive query that loads, practically, the whole database. However, if an openid string i...
### Input: Every rule for every filter for every context for every user. Any preferences in the DB that are for contexts that are disabled in the config are omitted here. If the `openid` argument is None, then this is an expensive query that loads, practically, the whole database. However, if an ope...
#vtb def GetRowHeaders(self) -> list: eleArray = self.pattern.GetCurrentRowHeaders() if eleArray: controls = [] for i in range(eleArray.Length): ele = eleArray.GetElement(i) con = Control.CreateControlFromElement(element=ele) ...
Call IUIAutomationTablePattern::GetCurrentRowHeaders. Return list, a list of `Control` subclasses, representing all the row headers in a table. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern-getcurrentrowheaders
### Input: Call IUIAutomationTablePattern::GetCurrentRowHeaders. Return list, a list of `Control` subclasses, representing all the row headers in a table. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern-getcurrentrowheaders #...
#vtb def get_instance(self, payload): return MonthlyInstance(self._version, payload, account_sid=self._solution[], )
Build an instance of MonthlyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance
### Input: Build an instance of MonthlyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyInstance ### Response: #vtb def get_instance(self,...
#vtb def delete_collection_pod_security_policy(self, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_collection_pod_security_policy_with_http_info(**kwargs) else: (data) = self.delete_collection_pod_security_policy_with_http_info(**kwargs) ...
delete collection of PodSecurityPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_pod_security_policy(async_req=True) >>> result = thread.get() :param async_req bool...
### Input: delete collection of PodSecurityPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_pod_security_policy(async_req=True) >>> result = thread.get() :param as...
#vtb def contains_entry(self, key, value): check_not_none(key, "key cant be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_contains_entry_codec, key_data, key=key_data, ...
Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple.
### Input: Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple. ### Response: #vtb def contains_entry(self, key, value): ...
#vtb def parse_and_normalize_url_date(date_str): if date_str is None: return None try: return d1_common.date_time.dt_from_iso8601_str(date_str) except d1_common.date_time.iso8601.ParseError as e: raise d1_common.types.exceptions.InvalidRequest( 0, .format...
Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC.
### Input: Parse a ISO 8601 date-time with optional timezone. - Return as datetime with timezone adjusted to UTC. - Return naive date-time set to UTC. ### Response: #vtb def parse_and_normalize_url_date(date_str): if date_str is None: return None try: return d1_common.date_time.d...
#vtb def create_layout(self, size = None): if not self.context: raise Exception("Can not create layout without existing context!") layout = pangocairo.create_layout(self.context) font_desc = pango.FontDescription(_font_desc) if size: font_d...
utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout
### Input: utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout ### Response: #vtb def create_layout(self, size = None): if not self.context: raise Exceptio...
#vtb def merge_code(left_code, right_code): data = dict() code_lines = (left_code and left_code.iter_code_by_lines()) or tuple() for abs_line, rel_line, dis in code_lines: data[rel_line] = [(abs_line, dis), None] code_lines = (right_code and right_code.iter_code_by_lines()) or tuple() ...
{ relative_line: ((left_abs_line, ((offset, op, args), ...)), (right_abs_line, ((offset, op, args), ...))), ... }
### Input: { relative_line: ((left_abs_line, ((offset, op, args), ...)), (right_abs_line, ((offset, op, args), ...))), ... } ### Response: #vtb def merge_code(left_code, right_code): data = dict() code_lines = (left_code and left_code.iter_code_by_lines()) or tuple() for abs_line...
#vtb def light_to_gl(light, transform, lightN): gl_color = vector_to_gl(light.color.astype(np.float64) / 255.0) assert len(gl_color) == 4 gl_position = vector_to_gl(transform[:3, 3]) args = [(lightN, gl.GL_POSITION, gl_position), (lightN, gl.GL_SPECULAR, gl_color), ...
Convert trimesh.scene.lighting.Light objects into args for gl.glLightFv calls Parameters -------------- light : trimesh.scene.lighting.Light Light object to be converted to GL transform : (4, 4) float Transformation matrix of light lightN : int Result of gl.GL_LIGHT0, gl.GL_LI...
### Input: Convert trimesh.scene.lighting.Light objects into args for gl.glLightFv calls Parameters -------------- light : trimesh.scene.lighting.Light Light object to be converted to GL transform : (4, 4) float Transformation matrix of light lightN : int Result of gl.GL_LIGH...
#vtb async def pause(self, pause: bool = True): self._paused = pause await self.node.pause(self.channel.guild.id, pause)
Pauses the current song. Parameters ---------- pause : bool Set to ``False`` to resume.
### Input: Pauses the current song. Parameters ---------- pause : bool Set to ``False`` to resume. ### Response: #vtb async def pause(self, pause: bool = True): self._paused = pause await self.node.pause(self.channel.guild.id, pause)
#vtb def _rotate_tr(self): rot, x, y, z = self._quaternion.get_axis_angle() up, forward, right = self._get_dim_vectors() self.transform.rotate(180 * rot / np.pi, (x, z, y))
Rotate the transformation matrix based on camera parameters
### Input: Rotate the transformation matrix based on camera parameters ### Response: #vtb def _rotate_tr(self): rot, x, y, z = self._quaternion.get_axis_angle() up, forward, right = self._get_dim_vectors() self.transform.rotate(180 * rot / np.pi, (x, z, y))
#vtb def _cbc_decrypt(self, final_key, crypted_content): aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) decrypted_content = aes.decrypt(crypted_content) padding = decrypted_content[-1] if sys.version > : padding = decrypted_content[-1] else: ...
This method decrypts the database
### Input: This method decrypts the database ### Response: #vtb def _cbc_decrypt(self, final_key, crypted_content): aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) decrypted_content = aes.decrypt(crypted_content) padding = decrypted_content[-1] if sys.version > ...
#vtb def add_sent(self, sent_obj): if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: sent_obj.ID = next(self.__idgen) elif self.has_id(sent_obj.ID): raise Exception("Sentence ID {} exists".fo...
Add a ttl.Sentence object to this document
### Input: Add a ttl.Sentence object to this document ### Response: #vtb def add_sent(self, sent_obj): if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: sent_obj.ID = next(self.__idgen) elif self.has_i...
#vtb def save(self, set_cookie, **params): if set(self.store.items()) ^ set(self.items()): value = dict(self.items()) value = json.dumps(value) value = self.encrypt(value) if not isinstance(value, str): value = value.encode(self.encoding) ...
Update cookies if the session has been changed.
### Input: Update cookies if the session has been changed. ### Response: #vtb def save(self, set_cookie, **params): if set(self.store.items()) ^ set(self.items()): value = dict(self.items()) value = json.dumps(value) value = self.encrypt(value) if not i...
#vtb async def teardown_client(self, client_id): client_info = self._client_info(client_id) self.adapter.remove_monitor(client_info[]) conns = client_info[] for conn_string, conn_id in conns.items(): try: self._logger.debug("Disconnecting client %s...
Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: client_id (s...
### Input: Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: ...
#vtb def set_data_length(self, length): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() len_diff = length - self.info_len if len_diff > 0: new_len = self.alloc_descs[-1][0] + len_diff if new_...
A method to set the length of the data that this UDF File Entry points to. Parameters: length - The new length for the data. Returns: Nothing.
### Input: A method to set the length of the data that this UDF File Entry points to. Parameters: length - The new length for the data. Returns: Nothing. ### Response: #vtb def set_data_length(self, length): if not self._initialized: rai...
#vtb def rsi(self, n, array=False): result = talib.RSI(self.close, n) if array: return result return result[-1]
RSI指标
### Input: RSI指标 ### Response: #vtb def rsi(self, n, array=False): result = talib.RSI(self.close, n) if array: return result return result[-1]
#vtb def cidr_notation(ip_address, netmask): try: inet_aton(ip_address) except: raise Exception("Invalid ip address " % ip_address) try: inet_aton(netmask) except: raise Exception("Invalid netmask " % netmask) ip_address_split = ip_address.split() netmask_sp...
Retrieve the cidr notation given an ip address and netmask. For example: cidr_notation('12.34.56.78', '255.255.255.248') Would return: 12.34.56.72/29 @see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for-a-subne-given-an-ip-and-netmask/ @see http://ww...
### Input: Retrieve the cidr notation given an ip address and netmask. For example: cidr_notation('12.34.56.78', '255.255.255.248') Would return: 12.34.56.72/29 @see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for-a-subne-given-an-ip-and-netmask/ @s...
#vtb def subscribe_topics(self): base = self.topic subscribe = self.mqtt.subscribe subscribe(b"/".join((base, b"$stats/interval/set"))) subscribe(b"/".join((self.settings.MQTT_BASE_TOPIC, b"$broadcast/ nodes = self.nodes for node in nodes: ...
subscribe to all registered device and node topics
### Input: subscribe to all registered device and node topics ### Response: #vtb def subscribe_topics(self): base = self.topic subscribe = self.mqtt.subscribe subscribe(b"/".join((base, b"$stats/interval/set"))) subscribe(b"/".join((self.settings.MQTT_BASE_TOPIC, b"$...
#vtb def stop(cls, app_id): conn = Qubole.agent() return conn.put(cls.element_path(app_id) + "/stop")
Stops an app by issuing a PUT request to the /apps/ID/stop endpoint.
### Input: Stops an app by issuing a PUT request to the /apps/ID/stop endpoint. ### Response: #vtb def stop(cls, app_id): conn = Qubole.agent() return conn.put(cls.element_path(app_id) + "/stop")
#vtb def playlist_create( self, name, description=, *, make_public=False, songs=None ): share_state = if make_public else playlist = self._call( mc_calls.PlaylistsCreate, name, description, share_state ).body if songs: playlist = self.playlist_songs_add(songs, playlist) re...
Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` songs (list, Optional): A list of song dicts to add to the ...
### Input: Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` songs (list, Optional): A list of song dicts to...
#vtb def loadfn(fn, *args, **kwargs): if "mpk" in os.path.basename(fn).lower(): if msgpack is None: raise RuntimeError( "Loading of message pack files is not " "possible as msgpack-python is not installed.") if "object_hook" not in kwargs: ...
Loads json/yaml/msgpack directly from a filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed. Args: fn (str/Path): filena...
### Input: Loads json/yaml/msgpack directly from a filename instead of a File-like object. For YAML, ruamel.yaml must be installed. The file type is automatically detected. YAML is assumed if the filename contains "yaml" (lower or upper case). Otherwise, json is always assumed. Args: fn (str/P...
#vtb def Update(self, env, args=None): values = {} for option in self.options: if not option.default is None: values[option.key] = option.default for filename in self.files: if os.path.exists(filename): dir = o...
Update an environment with the option variables. env - the environment to update.
### Input: Update an environment with the option variables. env - the environment to update. ### Response: #vtb def Update(self, env, args=None): values = {} for option in self.options: if not option.default is None: values[option.key] = option....
#vtb def Sonnad_Goudar_2006(Re, eD): r S = 0.124*eD*Re + log(0.4587*Re) return (.8686*log(.4587*Re/S**(S/(S+1))))**-2
r'''Calculates Darcy friction factor using the method in Sonnad and Goudar (2006) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right) .. math:: S = 0.1240\times\frac{\epsilon}{D}\times Re + \ln(0.4587Re) Parameters ---------- ...
### Input: r'''Calculates Darcy friction factor using the method in Sonnad and Goudar (2006) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = 0.8686\ln\left(\frac{0.4587Re}{S^{S/(S+1)}}\right) .. math:: S = 0.1240\times\frac{\epsilon}{D}\times Re + \ln(0.4587Re) Parameters ...
#vtb def build_image_from_inherited_image(self, image_name: str, image_tag: str, repo_path: Path, requirements_option: RequirementsOptions): base_name, base_tag = self.get_inherit_image() if requirements_option ...
Builds a image with installed requirements from the inherited image. (Or just tags the image if there are no requirements.) See :meth:`build_image` for parameters descriptions. :rtype: docker.models.images.Image
### Input: Builds a image with installed requirements from the inherited image. (Or just tags the image if there are no requirements.) See :meth:`build_image` for parameters descriptions. :rtype: docker.models.images.Image ### Response: #vtb def build_image_from_inherited_image(self, image_n...
#vtb def save_aggregate_report_to_elasticsearch(aggregate_report, index_suffix=None, monthly_indexes=False): logger.debug("Saving aggregate report to Elasticsearch") aggregate_report = aggregate_report.copy() metadata...
Saves a parsed DMARC aggregate report to ElasticSearch Args: aggregate_report (OrderedDict): A parsed forensic report index_suffix (str): The suffix of the name of the index to save to monthly_indexes (bool): Use monthly indexes instead of daily indexes Raises: AlreadySaved
### Input: Saves a parsed DMARC aggregate report to ElasticSearch Args: aggregate_report (OrderedDict): A parsed forensic report index_suffix (str): The suffix of the name of the index to save to monthly_indexes (bool): Use monthly indexes instead of daily indexes Raises: ...
#vtb def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None: for d in dict_list: d[key] = 1 if d[key] == "Y" else 0
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
### Input: Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a bool. If that fails, convert it to ``None``. ### Response: #vtb def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None: for d in dict_list: d[key] = 1 if d[key...
#vtb def _get_new_connection(self, conn_params): self.__connection_string = conn_params.get(, ) conn = self.Database.connect(**conn_params) return conn
Opens a connection to the database.
### Input: Opens a connection to the database. ### Response: #vtb def _get_new_connection(self, conn_params): self.__connection_string = conn_params.get(, ) conn = self.Database.connect(**conn_params) return conn
#vtb def load(self): pg = self.usr.getPage("http://www.neopets.com/bank.phtml") if not "great to see you again" in pg.content: logging.getLogger("neolib.user").info("Could not load userpg': pg}) raise noBankAcct self.__loadDetails(p...
Loads the user's account details and Raises parseException
### Input: Loads the user's account details and Raises parseException ### Response: #vtb def load(self): pg = self.usr.getPage("http://www.neopets.com/bank.phtml") if not "great to see you again" in pg.content: logging.getLogger("n...
#vtb def get_arctic_version(self, symbol, as_of=None): return self._read_metadata(symbol, as_of=as_of).get(, 0)
Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was a...
### Input: Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data...
#vtb def space_cluster(catalog, d_thresh, show=True): dist_mat = dist_mat_km(catalog) dist_vec = squareform(dist_mat) Z = linkage(dist_vec, method=) indices = fcluster(Z, t=d_thresh, criterion=) group_ids = list(set(indices)) indices = [(indices[i], i) for i in range(len(indices)...
Cluster a catalog by distance only. Will compute the matrix of physical distances between events and utilize the :mod:`scipy.clustering.hierarchy` module to perform the clustering. :type catalog: obspy.core.event.Catalog :param catalog: Catalog of events to clustered :type d_thresh: float :par...
### Input: Cluster a catalog by distance only. Will compute the matrix of physical distances between events and utilize the :mod:`scipy.clustering.hierarchy` module to perform the clustering. :type catalog: obspy.core.event.Catalog :param catalog: Catalog of events to clustered :type d_thresh: fl...
#vtb def is_valid_number_for_region(numobj, region_code): country_code = numobj.country_code if region_code is None: return False metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper()) if (metadata is None or (region_code != REGION_CODE_FOR_N...
Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. ...
### Input: Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits ...
#vtb def result(self): if self._result.lower() == : return WIN if self._result.lower() == and \ self.overtime != 0: return OVERTIME_LOSS return LOSS
Returns a ``string`` constant to indicate whether the team lost in regulation, lost in overtime, or won.
### Input: Returns a ``string`` constant to indicate whether the team lost in regulation, lost in overtime, or won. ### Response: #vtb def result(self): if self._result.lower() == : return WIN if self._result.lower() == and \ self.overtime != 0: ret...
#vtb def _trunc(x, minval=None, maxval=None): x = np.copy(x) if minval is not None: x[x < minval] = minval if maxval is not None: x[x > maxval] = maxval return x
Truncate vector values to have values on range [minval, maxval]
### Input: Truncate vector values to have values on range [minval, maxval] ### Response: #vtb def _trunc(x, minval=None, maxval=None): x = np.copy(x) if minval is not None: x[x < minval] = minval if maxval is not None: x[x > maxval] = maxval return x
#vtb def _get_task_with_policy(queue_name, task_id, owner): now = datetime.datetime.utcnow() task = ( WorkQueue.query .filter_by(queue_name=queue_name, task_id=task_id) .with_lockmode() .first()) if not task: raise TaskDoesNotExistError( % task_id) leas...
Fetches the specified task and enforces ownership policy. Args: queue_name: Name of the queue the work item is on. task_id: ID of the task that is finished. owner: Who or what has the current lease on the task. Returns: The valid WorkQueue task that is currently owned. Rai...
### Input: Fetches the specified task and enforces ownership policy. Args: queue_name: Name of the queue the work item is on. task_id: ID of the task that is finished. owner: Who or what has the current lease on the task. Returns: The valid WorkQueue task that is currently own...
#vtb def register_entity_to_group(self, entity, group): if entity in self._entities: if group in self._groups: self._groups[group].append(entity) else: self._groups[group] = [entity] else: raise UnmanagedEntityError(entity)
Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group
### Input: Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group ### Response: #vtb def register_entity_to_group(self, entity, group): if entity in self._entities: ...
#vtb def get_gaf_format(self): sep = return sep.join( [self.gene, self.db_ref, self.term.id, self.evidence, .join(self.db_ref), .join(self.with_)])
Return a GAF 2.0-compatible string representation of the annotation. Parameters ---------- Returns ------- str The formatted string.
### Input: Return a GAF 2.0-compatible string representation of the annotation. Parameters ---------- Returns ------- str The formatted string. ### Response: #vtb def get_gaf_format(self): sep = return sep.join( [self.gene, se...
#vtb def _translate_segment_glob(pattern): escape = False regex = i, end = 0, len(pattern) while i < end: char = pattern[i] i += 1 if escape: escape = False regex += re.escape(char) elif char == : escape = True elif char == : regex += eli...
Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`).
### Input: Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`). ### Response: #vtb def _translate_seg...
#vtb def GET_names( self, path_info ): include_expired = False qs_values = path_info[] page = qs_values.get(, None) if page is None: log.error("Page required") return self._reply_json({: }, status_code=400) try: page = int(page) ...
Get all names in existence If `all=true` is set, then include expired names. Returns the list on success Returns 400 on invalid arguments Returns 502 on failure to get names
### Input: Get all names in existence If `all=true` is set, then include expired names. Returns the list on success Returns 400 on invalid arguments Returns 502 on failure to get names ### Response: #vtb def GET_names( self, path_info ): include_expired = False ...
#vtb def _has_population_germline(rec): for k in population_keys: if k in rec.header.info: return True return False
Check if header defines population annotated germline samples for tumor only.
### Input: Check if header defines population annotated germline samples for tumor only. ### Response: #vtb def _has_population_germline(rec): for k in population_keys: if k in rec.header.info: return True return False
#vtb def printSegmentForCell(tm, cell): print "Segments for cell", cell, ":" for seg in tm.basalConnections._cells[cell]._segments: print " ", synapses = seg._synapses for s in synapses: print "%d:%g" %(s.presynapticCell,s.permanence), print
Print segment information for this cell
### Input: Print segment information for this cell ### Response: #vtb def printSegmentForCell(tm, cell): print "Segments for cell", cell, ":" for seg in tm.basalConnections._cells[cell]._segments: print " ", synapses = seg._synapses for s in synapses: print "%d:%g" %(s.presynapticCell,s.pe...
#vtb def read(self, want=0): if self._finished: if self._finished == 1: self._finished += 1 return "" return EOFError("EOF reached") self._want = want self._add.set() self._result.wait() self._result.clear...
Read method, gets data from internal buffer while releasing :meth:`write` locks when needed. The lock usage means it must ran on a different thread than :meth:`fill`, ie. the main thread, otherwise will deadlock. The combination of both write and this method running on different ...
### Input: Read method, gets data from internal buffer while releasing :meth:`write` locks when needed. The lock usage means it must ran on a different thread than :meth:`fill`, ie. the main thread, otherwise will deadlock. The combination of both write and this method running on diff...
#vtb def get_serializer(name): try: log.debug(, name) return SERIALIZER_LOOKUP[name] except KeyError: msg = .format(name) log.error(msg, exc_info=True) raise InvalidSerializerException(msg)
Return the serialize function.
### Input: Return the serialize function. ### Response: #vtb def get_serializer(name): try: log.debug(, name) return SERIALIZER_LOOKUP[name] except KeyError: msg = .format(name) log.error(msg, exc_info=True) raise InvalidSerializerException(msg)
#vtb def _shrink_file(dicom_file_in, subsample_factor): dicom_file_out = dicom_file_in dicom_in = compressed_dicom.read_file(dicom_file_in) file_meta = pydicom.dataset.Dataset() for key, value in dicom_in.file_meta.items(): file_meta.add(value) dico...
Anonimize a single dicomfile :param dicom_file_in: filepath for input file :param dicom_file_out: filepath for output file :param fields_to_keep: dicom tags to keep
### Input: Anonimize a single dicomfile :param dicom_file_in: filepath for input file :param dicom_file_out: filepath for output file :param fields_to_keep: dicom tags to keep ### Response: #vtb def _shrink_file(dicom_file_in, subsample_factor): dicom_file_out = dicom_file_in ...
#vtb def _build_urlmapping(urls, strict_slashes=False, **kwargs): rules = _build_rules(urls) return Map(rules=list(rules), strict_slashes=strict_slashes, **kwargs)
Convers the anillo urlmappings list into werkzeug Map instance. :return: a werkzeug Map instance :rtype: Map
### Input: Convers the anillo urlmappings list into werkzeug Map instance. :return: a werkzeug Map instance :rtype: Map ### Response: #vtb def _build_urlmapping(urls, strict_slashes=False, **kwargs): rules = _build_rules(urls) return Map(rules=list(rules), strict_slashes=strict_slashes, **k...
#vtb def _deserialize_datetime(self, data): for key in data: if isinstance(data[key], dict): if data[key].get() == : data[key] = \ datetime.datetime.fromtimestamp(data[key][]) return data
Take any values coming in as a datetime and deserialize them
### Input: Take any values coming in as a datetime and deserialize them ### Response: #vtb def _deserialize_datetime(self, data): for key in data: if isinstance(data[key], dict): if data[key].get() == : data[key] = \ datetime.dat...
#vtb def login(self, token, use_token=True, mount_point=DEFAULT_MOUNT_POINT): params = { : token, } api_path = .format(mount_point=mount_point) return self._adapter.login( url=api_path, use_token=use_token, json=params, )
Login using GitHub access token. Supported methods: POST: /auth/{mount_point}/login. Produces: 200 application/json :param token: GitHub personal API token. :type token: str | unicode :param use_token: if True, uses the token in the response received from the auth request ...
### Input: Login using GitHub access token. Supported methods: POST: /auth/{mount_point}/login. Produces: 200 application/json :param token: GitHub personal API token. :type token: str | unicode :param use_token: if True, uses the token in the response received from the a...
#vtb def _on_changed(self): page = self._get_page() if not page.flag_autosave: page.flag_changed = True self._update_gui_text_tabs()
Slot for changed events
### Input: Slot for changed events ### Response: #vtb def _on_changed(self): page = self._get_page() if not page.flag_autosave: page.flag_changed = True self._update_gui_text_tabs()
#vtb def date_parser(items): try: dt = datetime.strptime(items,"%d/%m/%Y %H:%M:%S") except Exception as e: try: dt = datetime.strptime(items,"%m/%d/%Y %H:%M:%S") except Exception as ee: raise Exception("error parsing datetime string" +\ ...
datetime parser to help load smp files Parameters ---------- items : iterable something or somethings to try to parse into datetimes Returns ------- dt : iterable the cast datetime things
### Input: datetime parser to help load smp files Parameters ---------- items : iterable something or somethings to try to parse into datetimes Returns ------- dt : iterable the cast datetime things ### Response: #vtb def date_parser(items): try: dt = datetim...
#vtb def _send_content(self, content, connection): if connection: if connection.async: callback = connection.callbacks[] if callback: callback(self, self.parent_object, content) self.current_connection.reset() ...
Send a content array from the connection
### Input: Send a content array from the connection ### Response: #vtb def _send_content(self, content, connection): if connection: if connection.async: callback = connection.callbacks[] if callback: callback(self, self.parent_object,...
#vtb def p_new_expr(self, p): if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.NewExpr(p[2]) p[0].setpos(p)
new_expr : member_expr | NEW new_expr
### Input: new_expr : member_expr | NEW new_expr ### Response: #vtb def p_new_expr(self, p): if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.NewExpr(p[2]) p[0].setpos(p)
#vtb def map_nested(function, data_struct, dict_only=False, map_tuple=False): if isinstance(data_struct, dict): return { k: map_nested(function, v, dict_only, map_tuple) for k, v in data_struct.items() } elif not dict_only: types = [list] if map_tuple: types.append(tuple...
Apply a function recursively to each element of a nested data struct.
### Input: Apply a function recursively to each element of a nested data struct. ### Response: #vtb def map_nested(function, data_struct, dict_only=False, map_tuple=False): if isinstance(data_struct, dict): return { k: map_nested(function, v, dict_only, map_tuple) for k, v in data_struct....
#vtb def setup(self): self.devman.sort_device() self.call.setup() self.model_setup() self.xy_addr0() self.dae.setup() self.to_sysbase() return self
Set up the power system object by executing the following workflow: * Sort the loaded models to meet the initialization sequence * Create call strings for routines * Call the ``setup`` function of the loaded models * Assign addresses for the loaded models * Call ``dae.setup...
### Input: Set up the power system object by executing the following workflow: * Sort the loaded models to meet the initialization sequence * Create call strings for routines * Call the ``setup`` function of the loaded models * Assign addresses for the loaded models * Call...
#vtb def parse_reports(self): self.infer_exp = dict() regexes = { : r"\"1\+\+,1--,2\+-,2-\+\": (\d\.\d+)", : r"\"1\+-,1-\+,2\+\+,2--\": (\d\.\d+)", : r"\"\+\+,--\": (\d\.\d+)", : r"\+-,-\+\": (\d\.\d+)", : r"Fraction of reads failed to determine: (\d\.\d+)" ...
Find RSeQC infer_experiment reports and parse their data
### Input: Find RSeQC infer_experiment reports and parse their data ### Response: #vtb def parse_reports(self): self.infer_exp = dict() regexes = { : r"\"1\+\+,1--,2\+-,2-\+\": (\d\.\d+)", : r"\"1\+-,1-\+,2\+\+,2--\": (\d\.\d+)", : r"\"\+\+,--\": (\d\.\d+)", : r"\+-,...
#vtb def cert_from_instance(instance): if instance.signature: if instance.signature.key_info: return cert_from_key_info(instance.signature.key_info, ignore_age=True) return []
Find certificates that are part of an instance :param instance: An instance :return: possible empty list of certificates
### Input: Find certificates that are part of an instance :param instance: An instance :return: possible empty list of certificates ### Response: #vtb def cert_from_instance(instance): if instance.signature: if instance.signature.key_info: return cert_from_key_info(instance.signa...
#vtb def _decode_image(fobj, session, filename): buf = fobj.read() image = tfds.core.lazy_imports.cv2.imdecode( np.fromstring(buf, dtype=np.uint8), flags=3) if image is None: logging.warning( "Image %s could not be decoded by OpenCV, falling back to TF", filename) try: image = tf...
Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB) - GIF (1-frame RGB) Since TFDS assumes tha...
### Input: Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB) - GIF (1-frame RGB) Since TFDS...
#vtb def scopes(self): if not self.__scopes: self.__scopes = Scopes(self.__connection) return self.__scopes
Gets the Scopes API client. Returns: Scopes:
### Input: Gets the Scopes API client. Returns: Scopes: ### Response: #vtb def scopes(self): if not self.__scopes: self.__scopes = Scopes(self.__connection) return self.__scopes
#vtb def add_default_parameter_values(self, sam_template): parameter_definition = sam_template.get("Parameters", None) if not parameter_definition or not isinstance(parameter_definition, dict): return self.parameter_values for param_name, value in parameter_definition.item...
Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String Default: default_value Param2: ...
### Input: Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String Default: default_value Param2: ...