code
stringlengths
64
7.01k
docstring
stringlengths
2
15.8k
text
stringlengths
144
19.2k
#vtb def count(self, object_class=None, params=None, **kwargs): path = "/directory-sync-service/v1/{}/count".format( object_class ) r = self._httpclient.request( method="GET", path=path, url=self.url, params=params, ...
Retrieve the attribute configuration object. Retrieve a count of all directory entries that belong to the identified objectClass. The count is limited to a single domain. Args: params (dict): Payload/request dictionary. object_class (str): Directory object class. ...
### Input: Retrieve the attribute configuration object. Retrieve a count of all directory entries that belong to the identified objectClass. The count is limited to a single domain. Args: params (dict): Payload/request dictionary. object_class (str): Directory object c...
#vtb def add_fields(self, field_dict): for key, field in field_dict.items(): self.add_field(key, field)
Add a mapping of field names to PayloadField instances. :API: public
### Input: Add a mapping of field names to PayloadField instances. :API: public ### Response: #vtb def add_fields(self, field_dict): for key, field in field_dict.items(): self.add_field(key, field)
#vtb def get_info(handle): csbi = _WindowsCSBI.CSBI() try: if not _WindowsCSBI.WINDLL.kernel32.GetConsoleScreenBufferInfo(handle, ctypes.byref(csbi)): raise IOError() except ctypes.ArgumentError: raise IOError() result =...
Get information about this current console window (for Microsoft Windows only). Raises IOError if attempt to get information fails (if there is no console window). Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method. Positional arguments: ...
### Input: Get information about this current console window (for Microsoft Windows only). Raises IOError if attempt to get information fails (if there is no console window). Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method. Positional argume...
#vtb def usernames(urls): usernames = StringCounter() for url, count in urls.items(): uparse = urlparse(url) path = uparse.path hostname = uparse.hostname m = username_re.match(path) if m: usernames[m.group()] += count elif hostname in [, ]: ...
Take an iterable of `urls` of normalized URL or file paths and attempt to extract usernames. Returns a list.
### Input: Take an iterable of `urls` of normalized URL or file paths and attempt to extract usernames. Returns a list. ### Response: #vtb def usernames(urls): usernames = StringCounter() for url, count in urls.items(): uparse = urlparse(url) path = uparse.path hostname = upa...
#vtb def _load_properties(self): method = data = _doget(method, user_id=self.__id) self.__loaded = True person = data.rsp.person self.__isadmin = person.isadmin self.__ispro = person.ispro self.__icon_server = person.iconserver if int(...
Load User properties from Flickr.
### Input: Load User properties from Flickr. ### Response: #vtb def _load_properties(self): method = data = _doget(method, user_id=self.__id) self.__loaded = True person = data.rsp.person self.__isadmin = person.isadmin self.__ispro = person.ispro ...
#vtb def build(self, words): words = [self._normalize(tokens) for tokens in words] self._dawg = dawg.CompletionDAWG(words) self._loaded_model = True
Construct dictionary DAWG from tokenized words.
### Input: Construct dictionary DAWG from tokenized words. ### Response: #vtb def build(self, words): words = [self._normalize(tokens) for tokens in words] self._dawg = dawg.CompletionDAWG(words) self._loaded_model = True
#vtb def make_processor(func, arg=None): def helper(instance, *args, **kwargs): value = kwargs.get() if value is None: value = instance if arg is not None: extra_arg = [arg] else: extra_arg = [] return func(value, *extra_arg) retur...
A pre-called processor that wraps the execution of the target callable ``func``. This is useful for when ``func`` is a third party mapping function that can take your column's value and return an expected result, but doesn't understand all of the extra kwargs that get sent to processor callbacks. Because ...
### Input: A pre-called processor that wraps the execution of the target callable ``func``. This is useful for when ``func`` is a third party mapping function that can take your column's value and return an expected result, but doesn't understand all of the extra kwargs that get sent to processor callback...
#vtb def get_api( profile=None, config_file=None, requirements=None): s default datafs application directory. Examples -------- The following specifies a simple API with a MongoDB manager and a temporary storage service: .. code-block:: python >>> try:...
Generate a datafs.DataAPI object from a config profile ``get_api`` generates a DataAPI object based on a pre-configured datafs profile specified in your datafs config file. To create a datafs config file, use the command line tool ``datafs configure --helper`` or export an existing DataAPI obj...
### Input: Generate a datafs.DataAPI object from a config profile ``get_api`` generates a DataAPI object based on a pre-configured datafs profile specified in your datafs config file. To create a datafs config file, use the command line tool ``datafs configure --helper`` or export an existing ...
#vtb def scale_and_crop(im, crop_spec): im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2)) if crop_spec.width and crop_spec.height: im = im.resize((crop_spec.width, crop_spec.height), resample=Image.ANTIALIAS) return im
Scale and Crop.
### Input: Scale and Crop. ### Response: #vtb def scale_and_crop(im, crop_spec): im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2)) if crop_spec.width and crop_spec.height: im = im.resize((crop_spec.width, crop_spec.height), resample=Image.ANTIALIAS) ret...
#vtb def listFigures(self,walkTrace=tuple(),case=None,element=None): if case == : print(walkTrace,self.title) if case == : caption,fig = element try: print(walkTrace,fig._leopardref,caption) except AttributeError: fig._leopardr...
List section figures.
### Input: List section figures. ### Response: #vtb def listFigures(self,walkTrace=tuple(),case=None,element=None): if case == : print(walkTrace,self.title) if case == : caption,fig = element try: print(walkTrace,fig._leopardref,caption) exc...
#vtb def pformat(self): lines = [] lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-")) lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size)) cap = self.consumed_capacity.get("__table__", {}) read = "Read: " + format_throughput(sel...
Pretty string format
### Input: Pretty string format ### Response: #vtb def pformat(self): lines = [] lines.append(("%s (%s)" % (self.name, self.status)).center(50, "-")) lines.append("items: {0:,} ({1:,} bytes)".format(self.item_count, self.size)) cap = self.consumed_capacity.get("__table__", {})...
#vtb def validate_scopes(self, request): if not request.scopes: request.scopes = utils.scope_to_list(request.scope) or utils.scope_to_list( self.request_validator.get_default_scopes(request.client_id, request)) log.debug(, request.scopes, request.cl...
:param request: OAuthlib request. :type request: oauthlib.common.Request
### Input: :param request: OAuthlib request. :type request: oauthlib.common.Request ### Response: #vtb def validate_scopes(self, request): if not request.scopes: request.scopes = utils.scope_to_list(request.scope) or utils.scope_to_list( self.request_validator.get_...
#vtb def transform(self, X, **kwargs): self.ranks_ = self.rank(X) self.draw(**kwargs) return X
The transform method is the primary drawing hook for ranking classes. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features kwargs : dict Pass generic arguments to the drawing method Returns ------...
### Input: The transform method is the primary drawing hook for ranking classes. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features kwargs : dict Pass generic arguments to the drawing method Returns ...
#vtb def spell_checker( self, text, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, action_type=None, app_name=None, country_code=None, client_machine_name=None, doc_id=None, market=None, session_id=None, set_lang=None, user_id=None, mode=None, pre_context_...
The Bing Spell Check API lets you perform contextual grammar and spell checking. Bing has developed a web-based spell-checker that leverages machine learning and statistical machine translation to dynamically train a constantly evolving and highly contextual algorithm. The spell-checker ...
### Input: The Bing Spell Check API lets you perform contextual grammar and spell checking. Bing has developed a web-based spell-checker that leverages machine learning and statistical machine translation to dynamically train a constantly evolving and highly contextual algorithm. The sp...
#vtb def _sign_payload(self, payload): app_key = self._app_key t = int(time.time() * 1000) requestStr = { : self._req_header, : payload } data = json.dumps({: json.dumps(requestStr)}) data_str = .format(self._req_token, t, app_key, data) ...
使用 appkey 对 payload 进行签名,返回新的请求参数
### Input: 使用 appkey 对 payload 进行签名,返回新的请求参数 ### Response: #vtb def _sign_payload(self, payload): app_key = self._app_key t = int(time.time() * 1000) requestStr = { : self._req_header, : payload } data = json.dumps({: json.dumps(requestStr)}) ...
#vtb def from_pycbc(cls, fs, copy=True): return cls(fs.data, f0=0, df=fs.delta_f, epoch=fs.epoch, copy=copy)
Convert a `pycbc.types.frequencyseries.FrequencySeries` into a `FrequencySeries` Parameters ---------- fs : `pycbc.types.frequencyseries.FrequencySeries` the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries` array copy : `bool`, optional, defaul...
### Input: Convert a `pycbc.types.frequencyseries.FrequencySeries` into a `FrequencySeries` Parameters ---------- fs : `pycbc.types.frequencyseries.FrequencySeries` the input PyCBC `~pycbc.types.frequencyseries.FrequencySeries` array copy : `bool`, opti...
#vtb def attachviewers(self, profiles): if self.metadata: template = None for profile in profiles: if isinstance(self, CLAMInputFile): for t in profile.input: if self.metadata.inputtemplate == t.id: ...
Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate
### Input: Attach viewers *and converters* to file, automatically scan all profiles for outputtemplate or inputtemplate ### Response: #vtb def attachviewers(self, profiles): if self.metadata: template = None for profile in profiles: if isinstance(self, CLAMInpu...
#vtb def mono_FM(x,fs=2.4e6,file_name=): b = signal.firwin(64,2*200e3/float(fs)) y = signal.lfilter(b,1,x) z = ss.downsample(y,10) z_bb = discrim(z) bb = signal.firwin(64,2*12e3/(float(fs)/10)) zz_bb = signal.lfilter(bb,1,z_bb) z_out = ss.downsample(zz_b...
Decimate complex baseband input by 10 Design 1st decimation lowpass filter (f_c = 200 KHz)
### Input: Decimate complex baseband input by 10 Design 1st decimation lowpass filter (f_c = 200 KHz) ### Response: #vtb def mono_FM(x,fs=2.4e6,file_name=): b = signal.firwin(64,2*200e3/float(fs)) y = signal.lfilter(b,1,x) z = ss.downsample(y,10) z_bb = discrim(z) bb...
#vtb def _get_deps(self, tree, include_punct, representation, universal): if universal: converter = self.universal_converter if self.universal_converter == self.converter: import warnings warnings.warn("This jar doesnbasiccollapsedCCprocessedt fa...
Get a list of dependencies from a Stanford Tree for a specific Stanford Dependencies representation.
### Input: Get a list of dependencies from a Stanford Tree for a specific Stanford Dependencies representation. ### Response: #vtb def _get_deps(self, tree, include_punct, representation, universal): if universal: converter = self.universal_converter if self.universal...
#vtb def get_core(self): if self.minicard and self.status == False: return pysolvers.minicard_core(self.minicard)
Get an unsatisfiable core if the formula was previously unsatisfied.
### Input: Get an unsatisfiable core if the formula was previously unsatisfied. ### Response: #vtb def get_core(self): if self.minicard and self.status == False: return pysolvers.minicard_core(self.minicard)
#vtb def wrap_iterable(obj): was_scalar = not isiterable(obj) wrapped_obj = [obj] if was_scalar else obj return wrapped_obj, was_scalar
Returns: wrapped_obj, was_scalar
### Input: Returns: wrapped_obj, was_scalar ### Response: #vtb def wrap_iterable(obj): was_scalar = not isiterable(obj) wrapped_obj = [obj] if was_scalar else obj return wrapped_obj, was_scalar
#vtb def send_text(self, sender, receiver_type, receiver_id, content): data = { : { : receiver_type, : receiver_id, }, : sender, : , : { : content, } } return self._po...
发送文本消息 详情请参考 https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明 :param sender: 发送人 :param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊 :param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id :param content: 消息内容 :return: 返回的 JSON 数据包
### Input: 发送文本消息 详情请参考 https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明 :param sender: 发送人 :param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊 :param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id :param content: 消息内容 :return: 返回的 JSON 数据包 ### Respo...
#vtb def user_token(scopes, client_id=None, client_secret=None, redirect_uri=None): webbrowser.open_new(authorize_url(client_id=client_id, redirect_uri=redirect_uri, scopes=scopes)) code = parse_code(raw_input()) return User(code, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_...
Generate a user access token :param List[str] scopes: Scopes to get :param str client_id: Spotify Client ID :param str client_secret: Spotify Client secret :param str redirect_uri: Spotify redirect URI :return: Generated access token :rtype: User
### Input: Generate a user access token :param List[str] scopes: Scopes to get :param str client_id: Spotify Client ID :param str client_secret: Spotify Client secret :param str redirect_uri: Spotify redirect URI :return: Generated access token :rtype: User ### Response: #vtb def user_token(s...
#vtb def probably_wkt(text): valid = False valid_types = set([ , , , , , , , ]) matched = re.match(r, text.strip()) if matched: valid = matched.group(1).upper() in valid_types return valid
Quick check to determine if the provided text looks like WKT
### Input: Quick check to determine if the provided text looks like WKT ### Response: #vtb def probably_wkt(text): valid = False valid_types = set([ , , , , , , , ]) matched = re.match(r, text.strip()) if matched: valid = matched.group(1).upper() in valid_types ret...
#vtb def mask_catalog(regionfile, infile, outfile, negate=False, racol=, deccol=): logging.info("Loading region from {0}".format(regionfile)) region = Region.load(regionfile) logging.info("Loading catalog from {0}".format(infile)) table = load_table(infile) masked_table = mask_table(region, tab...
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The catalogue...
### Input: Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region If negate=False then remove the rows with ra/dec outside the region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. T...
#vtb def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward)
Follow Figure 1 (left) for connections.
### Input: Follow Figure 1 (left) for connections. ### Response: #vtb def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward)
#vtb def admin_startWS(self, host=, port=8546, cors=None, apis=None): if cors is None: cors = [] if apis is None: apis = [, , ] return (yield from self.rpc_call(, [host, port, .jo...
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws :param host: Network interface to open the listener socket (optional) :type host: str :param port: Network port to open the listener socket (optional) :type port: int :param cors: Cross-origin resource ...
### Input: https://github.com/ethereum/go-ethereum/wiki/Management-APIs#admin_startws :param host: Network interface to open the listener socket (optional) :type host: str :param port: Network port to open the listener socket (optional) :type port: int :param cors: Cross-orig...
#vtb def compute_ratio(x): sum_ = sum(x) ratios = [] for i in x: ratio = i / sum_ ratios.append(ratio) return ratios
计算每一类数据的占比
### Input: 计算每一类数据的占比 ### Response: #vtb def compute_ratio(x): sum_ = sum(x) ratios = [] for i in x: ratio = i / sum_ ratios.append(ratio) return ratios
#vtb def _parse_game_date_and_location(self, boxscore): scheme = BOXSCORE_SCHEME["game_info"] items = [i.text() for i in boxscore(scheme).items()] game_info = items[0].split() attendance = None date = None duration = None stadium = None time = Non...
Retrieve the game's date and location. The games' meta information, such as date, location, attendance, and duration, follow a complex parsing scheme that changes based on the layout of the page. The information should be able to be parsed and set regardless of the order and how much in...
### Input: Retrieve the game's date and location. The games' meta information, such as date, location, attendance, and duration, follow a complex parsing scheme that changes based on the layout of the page. The information should be able to be parsed and set regardless of the order and...
#vtb def _parse_pages(self, unicode=False): if self.pageRange: pages = .format(self.pageRange) elif self.startingPage: pages = .format(self.startingPage, self.endingPage) else: pages = if unicode: pages = u.format(pages) return pages
Auxiliary function to parse and format page range of a document.
### Input: Auxiliary function to parse and format page range of a document. ### Response: #vtb def _parse_pages(self, unicode=False): if self.pageRange: pages = .format(self.pageRange) elif self.startingPage: pages = .format(self.startingPage, self.endingPage) else: pages = ...
#vtb def command(self, cluster_id, command, *args): cluster = self._storage[cluster_id] try: return getattr(cluster, command)(*args) except AttributeError: raise ValueError("Cannot issue the command %r to ShardedCluster %s" % (command...
Call a ShardedCluster method.
### Input: Call a ShardedCluster method. ### Response: #vtb def command(self, cluster_id, command, *args): cluster = self._storage[cluster_id] try: return getattr(cluster, command)(*args) except AttributeError: raise ValueError("Cannot issue the command %r to S...
#vtb def getParticleInfos(self, swarmId=None, genIdx=None, completed=None, matured=None, lastDescendent=False): if swarmId is not None: entryIdxs = self._swarmIdToIndexes.get(swarmId, []) else: entryIdxs = range(len(self._allResults)) if len(entryIdxs) == 0:...
Return a list of particleStates for all particles we know about in the given swarm, their model Ids, and metric results. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For...
### Input: Return a list of particleStates for all particles we know about in the given swarm, their model Ids, and metric results. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this ...
#vtb def update(self, data_set): now = time.time() for d in data_set: self.timed_data[d] = now self._expire_data()
Refresh the time of all specified elements in the supplied data set.
### Input: Refresh the time of all specified elements in the supplied data set. ### Response: #vtb def update(self, data_set): now = time.time() for d in data_set: self.timed_data[d] = now self._expire_data()
#vtb def _get_esxi_proxy_details(): s proxy details esxi.get_detailshostvcentervcenteresxi_hostesxi_hostusernamepasswordprotocolportmechanismprincipaldomain'), esxi_hosts
Returns the running esxi's proxy details
### Input: Returns the running esxi's proxy details ### Response: #vtb def _get_esxi_proxy_details(): s proxy details esxi.get_detailshostvcentervcenteresxi_hostesxi_hostusernamepasswordprotocolportmechanismprincipaldomain'), esxi_hosts
#vtb def _construct_body_s3_dict(self): if isinstance(self.definition_uri, dict): if not self.definition_uri.get("Bucket", None) or not self.definition_uri.get("Key", None): raise InvalidResourceException(self.logical_id, ...
Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property. :returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition :rtype: dict
### Input: Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property. :returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition :rtype: dict ### Response: #vtb def _construct_body_s3_dict(self): if isins...
#vtb def keep_types_s(s, types): patt = .join( + s + for s in types) return .join(re.findall(patt, + s.strip() + )).rstrip()
Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to keep Returns ...
### Input: Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str The type identifiers to keep ...
#vtb def safe_pdist(arr, *args, **kwargs): if arr is None or len(arr) < 2: return None else: import vtool as vt arr_ = vt.atleast_nd(arr, 2) return spdist.pdist(arr_, *args, **kwargs)
Kwargs: metric = ut.absdiff SeeAlso: scipy.spatial.distance.pdist TODO: move to vtool
### Input: Kwargs: metric = ut.absdiff SeeAlso: scipy.spatial.distance.pdist TODO: move to vtool ### Response: #vtb def safe_pdist(arr, *args, **kwargs): if arr is None or len(arr) < 2: return None else: import vtool as vt arr_ = vt.atleast_nd(arr, 2) ...
#vtb def on_setup_ssh(self, b): with self._setup_ssh_out: clear_output() self._ssh_keygen() password = self.__password proxy_password = self.__proxy_password if self.hostname is None: print("Please ...
ATTENTION: modifying the order of operations in this function can lead to unexpected problems
### Input: ATTENTION: modifying the order of operations in this function can lead to unexpected problems ### Response: #vtb def on_setup_ssh(self, b): with self._setup_ssh_out: clear_output() self._ssh_keygen() password = self.__password p...
#vtb def _Open(self, path_spec, mode=): if not path_spec.HasParent(): raise errors.PathSpecError( ) range_offset = getattr(path_spec, , None) if range_offset is None: raise errors.PathSpecError( ) range_size = getattr(path_spec, , None) if range_size is None: ...
Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: if th...
### Input: Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IO...
#vtb def xml_to_namespace(xmlstr): xmldoc = minidom.parseString(xmlstr) namespace = ServiceBusNamespace() mappings = ( (, , None), (, , None), (, , None), (, , None), (, , None), (, , None), (, , None),...
Converts xml response to service bus namespace The xml format for namespace: <entry> <id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id> <title type="text">myunittests</title> <updated>2012-08-22T16:48:10Z</updated> <content type="application/xml"> <NamespaceDescription xmlns="http://sche...
### Input: Converts xml response to service bus namespace The xml format for namespace: <entry> <id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id> <title type="text">myunittests</title> <updated>2012-08-22T16:48:10Z</updated> <content type="application/xml"> <NamespaceDescription xmlns=...
#vtb def delete(self, using=None, **kwargs): return self._get_connection(using).indices.delete(index=self._name, **kwargs)
Deletes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete`` unchanged.
### Input: Deletes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete`` unchanged. ### Response: #vtb def delete(self, using=None, **kwargs): return self._get_connection(using).indices.delete(index=self._name, **kwargs)
#vtb def workon(ctx, issue_id, new, base_branch): lancet = ctx.obj if not issue_id and not new: raise click.UsageError("Provide either an issue ID or the --new flag.") elif issue_id and new: raise click.UsageError( "Provide either an issue ID or the --new flag, but not both...
Start work on a given issue. This command retrieves the issue from the issue tracker, creates and checks out a new aptly-named branch, puts the issue in the configured active, status, assigns it to you and starts a correctly linked Harvest timer. If a branch with the same name as the one to be created...
### Input: Start work on a given issue. This command retrieves the issue from the issue tracker, creates and checks out a new aptly-named branch, puts the issue in the configured active, status, assigns it to you and starts a correctly linked Harvest timer. If a branch with the same name as the one t...
#vtb def delete(name, root=None): * cmd = [] if root is not None: cmd.extend((, root)) cmd.append(name) ret = __salt__[](cmd, python_shell=False) return not ret[]
Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo
### Input: Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo ### Response: #vtb def delete(name, root=None): * cmd = [] if root is not None: cmd.extend((, root)) ...
#vtb def process_pulls(self, testpulls=None, testarchive=None, expected=None): from datetime import datetime pulls = self.find_pulls(None if testpulls is None else testpulls.values()) for reponame in pulls: for pull in pulls[reponame]: try: ...
Runs self.find_pulls() *and* processes the pull requests unit tests, status updates and wiki page creations. :arg expected: for unit testing the output results that would be returned from running the tests in real time.
### Input: Runs self.find_pulls() *and* processes the pull requests unit tests, status updates and wiki page creations. :arg expected: for unit testing the output results that would be returned from running the tests in real time. ### Response: #vtb def process_pulls(self, testpulls=None, t...
#vtb def load_case(adapter, case_obj, update=False): existing_case = adapter.case(case_obj) if existing_case: if not update: raise CaseError("Case {0} already exists in database".format(case_obj[])) case_obj = update_case(case_obj, existing_case) try: adap...
Load a case to the database Args: adapter: Connection to database case_obj: dict update(bool): If existing case should be updated Returns: case_obj(models.Case)
### Input: Load a case to the database Args: adapter: Connection to database case_obj: dict update(bool): If existing case should be updated Returns: case_obj(models.Case) ### Response: #vtb def load_case(adapter, case_obj, update=False): existing_case = adapter...
#vtb def AppendFlagsIntoFile(self, filename): with open(filename, ) as out_file: out_file.write(self.FlagsIntoString())
Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags Args: filename: string, name of the file.
### Input: Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags Args: filename: string, name of the file. ### Response: #vtb def ...
#vtb def reshape(self, input_shapes): indptr = [0] sdata = [] keys = [] for k, v in input_shapes.items(): if not isinstance(v, tuple): raise ValueError("Expect input_shapes to be dict str->tuple") keys.append(c_str(k)) sdata.e...
Change the input shape of the predictor. Parameters ---------- input_shapes : dict of str to tuple The new shape of input data. Examples -------- >>> predictor.reshape({'data':data_shape_tuple})
### Input: Change the input shape of the predictor. Parameters ---------- input_shapes : dict of str to tuple The new shape of input data. Examples -------- >>> predictor.reshape({'data':data_shape_tuple}) ### Response: #vtb def reshape(self, input_shapes)...
#vtb def pix2vec(nside, ipix, nest=False): lon, lat = healpix_to_lonlat(ipix, nside, order= if nest else ) return ang2vec(*_lonlat_to_healpy(lon, lat))
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
### Input: Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`. ### Response: #vtb def pix2vec(nside, ipix, nest=False): lon, lat = healpix_to_lonlat(ipix, nside, order= if nest else ) return ang2vec(*_lonlat_to_healpy(lon, lat))
#vtb def free(self, connection): LOGGER.debug(, self.id, id(connection)) try: self.connection_handle(connection).free() except KeyError: raise ConnectionNotFoundError(self.id, id(connection)) if self.idle_connections == list(self.connections.values()): ...
Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError
### Input: Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError ### Response: #vtb def free(self, connection): LOGGER.debug(, self.id, id(conn...
#vtb def to_key_val_list(value): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError() if isinstance(value, collections.Mapping): value = value.items() return list(value)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Val...
### Input: Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string')...
#vtb def logjacobian(self, **params): r return numpy.log(abs(transforms.compute_jacobian( params, self.sampling_transforms, inverse=True)))
r"""Returns the log of the jacobian needed to transform pdfs in the ``variable_params`` parameter space to the ``sampling_params`` parameter space. Let :math:`\mathbf{x}` be the set of variable parameters, :math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and :m...
### Input: r"""Returns the log of the jacobian needed to transform pdfs in the ``variable_params`` parameter space to the ``sampling_params`` parameter space. Let :math:`\mathbf{x}` be the set of variable parameters, :math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, an...
#vtb def set_xticks(self, row, column, ticks): subplot = self.get_subplot_at(row, column) subplot.set_xticks(ticks)
Manually specify the x-axis tick values. :param row,column: specify the subplot. :param ticks: list of tick values.
### Input: Manually specify the x-axis tick values. :param row,column: specify the subplot. :param ticks: list of tick values. ### Response: #vtb def set_xticks(self, row, column, ticks): subplot = self.get_subplot_at(row, column) subplot.set_xticks(ticks)
#vtb def verifyZeroInteractions(*objs): for obj in objs: theMock = _get_mock_or_raise(obj) if len(theMock.invocations) > 0: raise VerificationError( "\nUnwanted interaction: %s" % theMock.invocations[0])
Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets recorded. So thi...
### Input: Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets reco...
#vtb def is_supported(value, check_all=False, filters=None, iterate=False): assert filters is not None if value is None: return True if not is_editable_type(value): return False elif not isinstance(value, filters): return False elif iterate: if isinstance(value, ...
Return True if the value is supported, False otherwise
### Input: Return True if the value is supported, False otherwise ### Response: #vtb def is_supported(value, check_all=False, filters=None, iterate=False): assert filters is not None if value is None: return True if not is_editable_type(value): return False elif not isinstance(val...
#vtb def assert_script_in_current_directory(): script = sys.argv[0] assert os.path.abspath(os.path.dirname(script)) == os.path.abspath( ), f"Change into directory of script {script} and run again."
Assert fail if current directory is different from location of the script
### Input: Assert fail if current directory is different from location of the script ### Response: #vtb def assert_script_in_current_directory(): script = sys.argv[0] assert os.path.abspath(os.path.dirname(script)) == os.path.abspath( ), f"Change into directory of script {script} and run again."
#vtb def _does_require_deprecation(self): for index, version_number in enumerate(self.current_version[0][:2]): if version_number > self.version_yaml[index]: return True return False
Check if we have to put the previous version into the deprecated list.
### Input: Check if we have to put the previous version into the deprecated list. ### Response: #vtb def _does_require_deprecation(self): for index, version_number in enumerate(self.current_version[0][:2]): if version_number > self.version_yaml[index]: ...
#vtb def id(self, obj): vid = self.obj2id[obj] if vid not in self.id2obj: self.id2obj[vid] = obj return vid
The method is to be used to assign an integer variable ID for a given new object. If the object already has an ID, no new ID is created and the old one is returned instead. An object can be anything. In some cases it is convenient to use string variable names. ...
### Input: The method is to be used to assign an integer variable ID for a given new object. If the object already has an ID, no new ID is created and the old one is returned instead. An object can be anything. In some cases it is convenient to use string variable names...
#vtb def scan_resource(self, pkg, path): r for fname in resource_listdir(pkg, path): if fname.endswith(TABLE_EXT): table_path = posixpath.join(path, fname) with contextlib.closing(resource_stream(pkg, table_path)) as stream: self.add_colort...
r"""Scan a resource directory for colortable files and add them to the registry. Parameters ---------- pkg : str The package containing the resource directory path : str The path to the directory with the color tables
### Input: r"""Scan a resource directory for colortable files and add them to the registry. Parameters ---------- pkg : str The package containing the resource directory path : str The path to the directory with the color tables ### Response: #vtb def scan_reso...
#vtb def __prepare_domain(data): if not data: raise JIDError("Domain must be given") data = unicode(data) if not data: raise JIDError("Domain must be given") if u in data: if data[0] == u and data[-1] == u: try: ...
Prepare domainpart of the JID. :Parameters: - `data`: Domain part of the JID :Types: - `data`: `unicode` :raise JIDError: if the domain name is too long.
### Input: Prepare domainpart of the JID. :Parameters: - `data`: Domain part of the JID :Types: - `data`: `unicode` :raise JIDError: if the domain name is too long. ### Response: #vtb def __prepare_domain(data): if not data: raise...
#vtb def get_profile(): argument_parser = ThrowingArgumentParser(add_help=False) argument_parser.add_argument() try: args, _ = argument_parser.parse_known_args() except ArgumentParserError: return Profile() imported = get_module(args.profile) profile = get_module_profile(imported) if not p...
Prefetch the profile module, to fill some holes in the help text.
### Input: Prefetch the profile module, to fill some holes in the help text. ### Response: #vtb def get_profile(): argument_parser = ThrowingArgumentParser(add_help=False) argument_parser.add_argument() try: args, _ = argument_parser.parse_known_args() except ArgumentParserError: return Profil...
#vtb def _dump_cnt(self): self._cnt[].dump(os.path.join(self.data_path, )) self._cnt[].dump(os.path.join(self.data_path, )) self._cnt[].dump(os.path.join(self.data_path, ))
Dump counters to file
### Input: Dump counters to file ### Response: #vtb def _dump_cnt(self): self._cnt[].dump(os.path.join(self.data_path, )) self._cnt[].dump(os.path.join(self.data_path, )) self._cnt[].dump(os.path.join(self.data_path, ))
#vtb def check_arguments(cls, conf): try: f = open(conf[], "r") f.close() except IOError as e: raise ArgsError("Cannot open config file : %s" % (conf[], e))
Sanity checks for options needed for configfile mode.
### Input: Sanity checks for options needed for configfile mode. ### Response: #vtb def check_arguments(cls, conf): try: f = open(conf[], "r") f.close() except IOError as e: raise ArgsError("Cannot open config file : %s" % ...
#vtb def delete(cls, object_version, key=None): with db.session.begin_nested(): q = cls.query.filter_by( version_id=as_object_version_id(object_version)) if key: q = q.filter_by(key=key) q.delete()
Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags.
### Input: Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags. ### Response: #vtb def delete(cls, object_version, key=None): with db.session.begin_nested(): q = cls.query.filter...
#vtb def run_jar(self, mem=None): cmd = config.get_command() if mem: cmd.append( % mem) cmd.append() cmd += self.cmd self.run(cmd)
Special case of run() when the executable is a JAR file.
### Input: Special case of run() when the executable is a JAR file. ### Response: #vtb def run_jar(self, mem=None): cmd = config.get_command() if mem: cmd.append( % mem) cmd.append() cmd += self.cmd self.run(cmd)
#vtb def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool: return not node_predicate(graph, node) return inverse_predicate
Build a node predicate that is the inverse of the given node predicate.
### Input: Build a node predicate that is the inverse of the given node predicate. ### Response: #vtb def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool: return not node_predicate(graph, node) re...
#vtb def get_file(original_file): import cStringIO import boto3 s3 = boto3.resource() bucket_name, object_key = _parse_s3_file(original_file) logger.debug("Downloading {0} from {1}".format(object_key, bucket_name)) bucket = s3.Bucket(bucket_name) output = cStringIO.StringIO() bucket...
original file should be s3://bucketname/path/to/file.txt returns a Buffer with the file in it
### Input: original file should be s3://bucketname/path/to/file.txt returns a Buffer with the file in it ### Response: #vtb def get_file(original_file): import cStringIO import boto3 s3 = boto3.resource() bucket_name, object_key = _parse_s3_file(original_file) logger.debug("Downloading {...
#vtb def serve(): logging.getLogger().setLevel(logging.DEBUG) logging.info() tracer = Tracer( service_name=, reporter=NullReporter(), sampler=ConstSampler(decision=True)) opentracing.tracer = tracer tchannel = TChannel(name=, hostport= % DEFAULT_SERVER_PORT, ...
main entry point
### Input: main entry point ### Response: #vtb def serve(): logging.getLogger().setLevel(logging.DEBUG) logging.info() tracer = Tracer( service_name=, reporter=NullReporter(), sampler=ConstSampler(decision=True)) opentracing.tracer = tracer tchannel = TChannel(name=,...
#vtb def filter_factory(global_conf, **local_conf): conf = global_conf.copy() conf.update(local_conf) def blacklist(app): return BlacklistFilter(app, conf) return blacklist
Returns a WSGI filter app for use with paste.deploy.
### Input: Returns a WSGI filter app for use with paste.deploy. ### Response: #vtb def filter_factory(global_conf, **local_conf): conf = global_conf.copy() conf.update(local_conf) def blacklist(app): return BlacklistFilter(app, conf) return blacklist
#vtb def _save_image(self, name, format=): dialog = QtGui.QFileDialog(self._control, ) dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilter( % (format, format.lower())) if dialog.exec_(): filename = d...
Shows a save dialog for the ImageResource with 'name'.
### Input: Shows a save dialog for the ImageResource with 'name'. ### Response: #vtb def _save_image(self, name, format=): dialog = QtGui.QFileDialog(self._control, ) dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilte...
#vtb def wait_actions_on_objects(self, objects, wait_interval=None, wait_time=None): acts = [] for o in objects: a = o.fetch_last_action() if a is None: yield o else: acts.append(a...
.. versionadded:: 0.2.0 Poll the server periodically until the most recent action on each resource in ``objects`` has finished, yielding each resource's final state when the corresponding action is done. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any remaini...
### Input: .. versionadded:: 0.2.0 Poll the server periodically until the most recent action on each resource in ``objects`` has finished, yielding each resource's final state when the corresponding action is done. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any ...
#vtb def overload(fn): if not isfunction(fn): raise TypeError() spec = getargspec(fn) args = spec.args if not spec.varargs and (len(args) < 2 or args[1] != ): raise ValueError() @functools.wraps(fn) def decorator(*args, **kw): if len(args) < 2: ...
Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is no...
### Input: Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine fu...
#vtb def _bind(self): main_window = self.main_window handlers = self.handlers c_handlers = self.cell_handlers self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel) self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey) self.GetGridWindow().Bind(wx.EVT_M...
Bind events to handlers
### Input: Bind events to handlers ### Response: #vtb def _bind(self): main_window = self.main_window handlers = self.handlers c_handlers = self.cell_handlers self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel) self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey) ...
#vtb def dmlc_opts(opts): args = [, str(opts.num_workers), , str(opts.num_servers), , opts.launcher, , opts.hostfile, , opts.sync_dst_dir] dopts = vars(opts) for key in [, , ]: for v in dopts[key]: args.append( + key.replace("_",...
convert from mxnet's opts to dmlc's opts
### Input: convert from mxnet's opts to dmlc's opts ### Response: #vtb def dmlc_opts(opts): args = [, str(opts.num_workers), , str(opts.num_servers), , opts.launcher, , opts.hostfile, , opts.sync_dst_dir] dopts = vars(opts) for key in [, , ]: ...
#vtb def complementTab(seq=[]): complement = {: , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : } seq_tmp = [] for bps in seq: if len(bps) == 0: seq_tm...
returns a list of complementary sequence without inversing it
### Input: returns a list of complementary sequence without inversing it ### Response: #vtb def complementTab(seq=[]): complement = {: , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : } ...
#vtb def kill(timeout=15): ret = { : None, : 1, } comment = [] pid = __grains__.get() if not pid: comment.append() ret[] = salt.defaults.exitcodes.EX_SOFTWARE else: if not in __salt__: comment.append() ret[] = salt.defaults.e...
Kill the salt minion. timeout int seconds to wait for the minion to die. If you have a monitor that restarts ``salt-minion`` when it dies then this is a great way to restart after a minion upgrade. CLI example:: >$ salt minion[12] minion.kill minion1: ---------- ...
### Input: Kill the salt minion. timeout int seconds to wait for the minion to die. If you have a monitor that restarts ``salt-minion`` when it dies then this is a great way to restart after a minion upgrade. CLI example:: >$ salt minion[12] minion.kill minion1: ...
#vtb def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str: r = 8 p = 8 dk_len = 64 scrypt = Scrypt(n, r, p, dk_len) derived_key = scrypt.generate_kd(password, salt) iv = derived_key[0:12] key = derived_key[32:64] ...
This interface is used to export an AES algorithm encrypted private key with the mode of GCM. :param password: the secret pass phrase to generate the keys from. :param salt: A string to use for better protection from dictionary attacks. This value does not need to be kept secret, ...
### Input: This interface is used to export an AES algorithm encrypted private key with the mode of GCM. :param password: the secret pass phrase to generate the keys from. :param salt: A string to use for better protection from dictionary attacks. This value does not need to be k...
#vtb def CreateTaskStorage(self, task): if task.identifier in self._task_storage_writers: raise IOError(.format( task.identifier)) storage_writer = FakeStorageWriter( self._session, storage_type=definitions.STORAGE_TYPE_TASK, task=task) self._task_storage_writers[task.identifie...
Creates a task storage. Args: task (Task): task. Returns: FakeStorageWriter: storage writer. Raises: IOError: if the task storage already exists. OSError: if the task storage already exists.
### Input: Creates a task storage. Args: task (Task): task. Returns: FakeStorageWriter: storage writer. Raises: IOError: if the task storage already exists. OSError: if the task storage already exists. ### Response: #vtb def CreateTaskStorage(self, task): if task.identi...
#vtb def adjacent(self, node_a, node_b): neighbors = self.neighbors(node_a) return node_b in neighbors
Determines whether there is an edge from node_a to node_b. Returns True if such an edge exists, otherwise returns False.
### Input: Determines whether there is an edge from node_a to node_b. Returns True if such an edge exists, otherwise returns False. ### Response: #vtb def adjacent(self, node_a, node_b): neighbors = self.neighbors(node_a) return node_b in neighbors
#vtb def create_user(self, instance, name, password, database_names, host=None): return instance.create_user(name=name, password=password, database_names=database_names, host=host)
Creates a user with the specified name and password, and gives that user access to the specified database(s).
### Input: Creates a user with the specified name and password, and gives that user access to the specified database(s). ### Response: #vtb def create_user(self, instance, name, password, database_names, host=None): return instance.create_user(name=name, password=password, dat...
#vtb def getDescription(self): description = {:self.name, :[f.name for f in self.fields], \ :[f.numRecords for f in self.fields]} return description
Returns a description of the dataset
### Input: Returns a description of the dataset ### Response: #vtb def getDescription(self): description = {:self.name, :[f.name for f in self.fields], \ :[f.numRecords for f in self.fields]} return description
#vtb def update(self): _LOGGER.debug("Querying the device..") time = datetime.now() value = struct.pack(, PROP_INFO_QUERY, time.year % 100, time.month, time.day, time.hour, time.minute, time.second) self._conn.make_request...
Update the data from the thermostat. Always sets the current time.
### Input: Update the data from the thermostat. Always sets the current time. ### Response: #vtb def update(self): _LOGGER.debug("Querying the device..") time = datetime.now() value = struct.pack(, PROP_INFO_QUERY, time.year % 100, time.month, time.day, ...
#vtb def date_in_past(self): now = datetime.datetime.now() return (now.date() > self.date)
Is the block's date in the past? (Has it not yet happened?)
### Input: Is the block's date in the past? (Has it not yet happened?) ### Response: #vtb def date_in_past(self): now = datetime.datetime.now() return (now.date() > self.date)
#vtb def series_lstrip(series, startswith=, ignorecase=True): return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase)
Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str
### Input: Strip a suffix str (`endswith` str) from a `df` columns or pd.Series of type str ### Response: #vtb def series_lstrip(series, startswith=, ignorecase=True): return series_strip(series, startswith=startswith, endswith=None, startsorendswith=None, ignorecase=ignorecase)
#vtb def get_cf_distribution_class(): if LooseVersion(troposphere.__version__) == LooseVersion(): cf_dist = cloudfront.Distribution cf_dist.props[] = (DistributionConfig, True) return cf_dist return cloudfront.Distribution
Return the correct troposphere CF distribution class.
### Input: Return the correct troposphere CF distribution class. ### Response: #vtb def get_cf_distribution_class(): if LooseVersion(troposphere.__version__) == LooseVersion(): cf_dist = cloudfront.Distribution cf_dist.props[] = (DistributionConfig, True) return cf_dist return clo...
#vtb def _iso_name_and_parent_from_path(self, iso_path): splitpath = utils.split_path(iso_path) name = splitpath.pop() parent = self._find_iso_record(b + b.join(splitpath)) return (name.decode().encode(), parent)
An internal method to find the parent directory record and name given an ISO path. If the parent is found, return a tuple containing the basename of the path and the parent directory record object. Parameters: iso_path - The absolute ISO path to the entry on the ISO. Returns: ...
### Input: An internal method to find the parent directory record and name given an ISO path. If the parent is found, return a tuple containing the basename of the path and the parent directory record object. Parameters: iso_path - The absolute ISO path to the entry on the ISO. ...
#vtb def thread_exception(self, raised_exception): print( % str(raised_exception)) print() print(traceback.format_exc())
Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started` :param raised_exception: raised exception :return: None
### Input: Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started` :param raised_exception: raised exception :return: None ### Response: #vtb def thread_exception(self, raised_exception): print( % str(raised_exception)) print() print(traceback.format_exc())
#vtb def source_sum_err(self): if self._error is not None: if self._is_completely_masked: return np.nan * self._error_unit else: return np.sqrt(np.sum(self._error_values ** 2)) else: return None
The uncertainty of `~photutils.SourceProperties.source_sum`, propagated from the input ``error`` array. ``source_sum_err`` is the quadrature sum of the total errors over the non-masked pixels within the source segment: .. math:: \\Delta F = \\sqrt{\\sum_{i \\in S} \\s...
### Input: The uncertainty of `~photutils.SourceProperties.source_sum`, propagated from the input ``error`` array. ``source_sum_err`` is the quadrature sum of the total errors over the non-masked pixels within the source segment: .. math:: \\Delta F = \\sqrt{\\sum_{i \\in S} ...
#vtb def job_not_running(self, jid, tgt, tgt_type, minions, is_finished): ping_pub_data = yield self.saltclients[](tgt, , [jid], tgt_ty...
Return a future which will complete once jid (passed in) is no longer running on tgt
### Input: Return a future which will complete once jid (passed in) is no longer running on tgt ### Response: #vtb def job_not_running(self, jid, tgt, tgt_type, minions, is_finished): ping_pub_data = yield self.saltclients[](tgt, , ...
#vtb def get_levels_of_description(self): if not hasattr(self, "levels_of_description"): self.levels_of_description = [ item["name"] for item in self._get(urljoin(self.base_url, "taxonomies/34")).json() ] return self.levels_of_description
Returns an array of all levels of description defined in this AtoM instance.
### Input: Returns an array of all levels of description defined in this AtoM instance. ### Response: #vtb def get_levels_of_description(self): if not hasattr(self, "levels_of_description"): self.levels_of_description = [ item["name"] for item in self._get(...
#vtb def set_resolving(self, **kw): if in kw and not in kw: kw.update(time_show_zone=True) self.data[].update(**kw)
Certain log fields can be individually resolved. Use this method to set these fields. Valid keyword arguments: :param str timezone: string value to set timezone for audits :param bool time_show_zone: show the time zone in the audit. :param bool time_show_millis: show timezone in...
### Input: Certain log fields can be individually resolved. Use this method to set these fields. Valid keyword arguments: :param str timezone: string value to set timezone for audits :param bool time_show_zone: show the time zone in the audit. :param bool time_show_millis: show...
#vtb def chunks(seq, size=None, dfmt="f", byte_order=None, padval=0.): if size is None: size = chunks.size chunk = array.array(dfmt, xrange(size)) idx = 0 for el in seq: chunk[idx] = el idx += 1 if idx == size: yield chunk.tostring() idx = 0 if idx != 0: for idx in xrange(...
Chunk generator based on the array module (Python standard library). See chunk.struct for more help. This strategy uses array.array (random access by indexing management) instead of struct.Struct and blocks/deque (circular queue appending) from the chunks.struct strategy. Hint ---- Try each one to find th...
### Input: Chunk generator based on the array module (Python standard library). See chunk.struct for more help. This strategy uses array.array (random access by indexing management) instead of struct.Struct and blocks/deque (circular queue appending) from the chunks.struct strategy. Hint ---- Try each on...
#vtb def __encryptKeyTransportMessage( self, bare_jids, encryption_callback, bundles = None, expect_problems = None, ignore_trust = False ): yield self.runInactiveDeviceCleanup() if isinstance(bare_jids, string_ty...
bare_jids: iterable<string> encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything. bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBu...
### Input: bare_jids: iterable<string> encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything. bundles: { [bare_jid: string] => { [device_id: int] => Exte...
#vtb def unwrap_aliases(data_type): unwrapped_alias = False while is_alias(data_type): unwrapped_alias = True data_type = data_type.data_type return data_type, unwrapped_alias
Convenience method to unwrap all Alias(es) from around a DataType. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool]: The underlying data type and a bool indicating whether the input type had at least one alias layer.
### Input: Convenience method to unwrap all Alias(es) from around a DataType. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool]: The underlying data type and a bool indicating whether the input type had at least one alias layer. ### Response: #vtb de...
#vtb def run_sim(morphology=, cell_rotation=dict(x=4.99, y=-4.33, z=3.14), closest_idx=dict(x=-200., y=0., z=800.)): cell = LFPy.Cell(morphology=morphology, **cell_parameters) cell.set_rotation(**cell_rotation) synapse_parameters = { : cell.get_clos...
set up simple cell simulation with LFPs in the plane
### Input: set up simple cell simulation with LFPs in the plane ### Response: #vtb def run_sim(morphology=, cell_rotation=dict(x=4.99, y=-4.33, z=3.14), closest_idx=dict(x=-200., y=0., z=800.)): cell = LFPy.Cell(morphology=morphology, **cell_parameters) cell.set_rotatio...
#vtb def get_parent_info(brain_or_object, endpoint=None): if is_root(brain_or_object): return {} parent = get_parent(brain_or_object) portal_type = get_portal_type(parent) resource = portal_type_to_resource(portal_type) if endpoint is None: endpoint = get_endpo...
Generate url information for the parent object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :returns: URL informat...
### Input: Generate url information for the parent object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :returns: ...
#vtb def get_comments(self): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find(self._view_filter()).sort(, DESCENDING) return object...
Gets all comments. return: (osid.commenting.CommentList) - a list of comments raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
### Input: Gets all comments. return: (osid.commenting.CommentList) - a list of comments raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* ### Response: #vtb def get_comment...
#vtb def _parseExpression(self, src, returnList=False): src, term = self._parseExpressionTerm(src) operator = None while src[:1] not in (, , , , , , ): for operator in self.ExpressionOperators: if src.startswith(operator): src = src[len(op...
expr : term [ operator term ]* ;
### Input: expr : term [ operator term ]* ; ### Response: #vtb def _parseExpression(self, src, returnList=False): src, term = self._parseExpressionTerm(src) operator = None while src[:1] not in (, , , , , , ): for operator in self.ExpressionOperators: ...
#vtb def deployment_check_existence(name, resource_group, **kwargs): result = False resconn = __utils__[](, **kwargs) try: result = resconn.deployments.check_existence( deployment_name=name, resource_group_name=resource_group ) except CloudError as exc: ...
.. versionadded:: 2019.2.0 Check the existence of a deployment. :param name: The name of the deployment to query. :param resource_group: The resource group name assigned to the deployment. CLI Example: .. code-block:: bash salt-call azurearm_resource.deployment_check_existence ...
### Input: .. versionadded:: 2019.2.0 Check the existence of a deployment. :param name: The name of the deployment to query. :param resource_group: The resource group name assigned to the deployment. CLI Example: .. code-block:: bash salt-call azurearm_resource.deployment_chec...
#vtb def tags( self): tags = [] regex = re.compile(r, re.S) if self.meta["tagString"]: matchList = regex.findall(self.meta["tagString"]) for m in matchList: tags.append(m.strip().replace("@", "")) return tags
*The list of tags associated with this taskpaper object* **Usage:** .. project and task objects can have associated tags. To get a list of tags assigned to an object use: .. code-block:: python projectTag = aProject.tags taskTags = aTasks.ta...
### Input: *The list of tags associated with this taskpaper object* **Usage:** .. project and task objects can have associated tags. To get a list of tags assigned to an object use: .. code-block:: python projectTag = aProject.tags taskTags...
#vtb def dcm(self, dcm): assert(isinstance(dcm, Matrix3)) self._dcm = dcm.copy() self._q = None self._euler = None
Set the DCM :param dcm: Matrix3
### Input: Set the DCM :param dcm: Matrix3 ### Response: #vtb def dcm(self, dcm): assert(isinstance(dcm, Matrix3)) self._dcm = dcm.copy() self._q = None self._euler = None