code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def build_sourcemap(sources): """ Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files). """ sourcemap = {} for sfile in sources: inc = find_includes(sfile) sourcemap[sfile] = set(inc) return sourcemap
Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files).
def AddTrack(self, uri, after_track, set_as_current): """Adds a URI in the TrackList. :param str uri: The uri of the item to add. :param str after_track: The identifier of the track after which the new item should be inserted. :param bool set_as_current: ...
Adds a URI in the TrackList. :param str uri: The uri of the item to add. :param str after_track: The identifier of the track after which the new item should be inserted. :param bool set_as_current: Whether the newly inserted track ...
def get_components(self, uri): """ Get components from a component definition in order """ try: component_definition = self._components[uri] except KeyError: return False sorted_sequences = sorted(component_definition.sequence_annotations, ...
Get components from a component definition in order
def get_submodules(module): """ This function imports all sub-modules of the supplied module and returns a dictionary with module names as keys and the sub-module objects as values. If the supplied parameter is not a module object, a RuntimeError is raised. :param module: Module object from which t...
This function imports all sub-modules of the supplied module and returns a dictionary with module names as keys and the sub-module objects as values. If the supplied parameter is not a module object, a RuntimeError is raised. :param module: Module object from which to import sub-modules. :return: Dict ...
def search(self, query_string=None, field_dictionary=None, filter_dictionary=None, exclude_dictionary=None, facet_terms=None, exclude_ids=None, use_field_match=False, **kwargs): # pylint: disable=too...
Implements call to search the index for the desired content. Args: query_string (str): the string of values upon which to search within the content of the objects within the index field_dictionary (dict): dictionary of values which _must_ exist and _must_ match ...
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ # We can't use BGE during testing, since we don't have access to the #...
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
def open(self): """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. """ if self._f is not None: return self._f try: rv, self.should_close = open_str...
Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows.
def convert(profiling_data, outputfile): """convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can...
convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can either be: - a file() instance open in ...
def S4U2self(self, user_to_impersonate, supp_enc_methods = [EncryptionType.DES_CBC_CRC,EncryptionType.DES_CBC_MD4,EncryptionType.DES_CBC_MD5,EncryptionType.DES3_CBC_SHA1,EncryptionType.ARCFOUR_HMAC_MD5,EncryptionType.AES256_CTS_HMAC_SHA1_96,EncryptionType.AES128_CTS_HMAC_SHA1_96]): #def S4U2self(self, user_to_imperson...
user_to_impersonate : KerberosTarget class
def getAccountsFromPublicKey(self, pub): """ Obtain all accounts associated with a public key """ names = self.rpc.get_key_references([str(pub)])[0] for name in names: yield name
Obtain all accounts associated with a public key
def safe_call(func, *args, **kwargs): """ Call `func(*args, **kwargs)` but NEVER raise an exception. Useful in situations such as inside exception handlers where calls to `logging.error` try to send email, but the SMTP server isn't always availalbe and you don't want your exception handler blowing ...
Call `func(*args, **kwargs)` but NEVER raise an exception. Useful in situations such as inside exception handlers where calls to `logging.error` try to send email, but the SMTP server isn't always availalbe and you don't want your exception handler blowing up.
def _compute_imt1100(self, C, sites, rup, dists, get_pga_site=False): """ Computes the PGA on reference (Vs30 = 1100 m/s) rock. """ # Calculates simple site response term assuming all sites 1100 m/s fsite = (C['c10'] + (C['k2'] * C['n'])) * log(1100. / C['k1']) # Calculat...
Computes the PGA on reference (Vs30 = 1100 m/s) rock.
def get_neighbor_expression_vector(neighbors, gene_expression_dict): """Get an expression vector of neighboring genes. Attribute: neighbors (list): List of gene identifiers of neighboring genes. gene_expression_dict (dict): (Gene identifier)-(gene expression) dictionary. """ expres...
Get an expression vector of neighboring genes. Attribute: neighbors (list): List of gene identifiers of neighboring genes. gene_expression_dict (dict): (Gene identifier)-(gene expression) dictionary.
def if_modified_since(self) -> Optional[datetime.datetime]: """The value of If-Modified-Since HTTP header, or None. This header is represented as a `datetime` object. """ return self._http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE))
The value of If-Modified-Since HTTP header, or None. This header is represented as a `datetime` object.
def get_results(): """Parse all search result pages.""" # store info in a dictionary {name -> shortname} res = {} session = requests.Session() baseUrl = 'http://comicfury.com/search.php?search=1&webcomics=Search+for+webcomics&query=&worder=5&asc=1&incvi=1&incse=1&incnu=1&incla=1&all_ge=1&all_st=1&al...
Parse all search result pages.
def max(self, **kwargs): """Return `max_pt`. Parameters ---------- kwargs For duck-typing with `numpy.amax` See Also -------- min odl.set.domain.IntervalProd.max Examples -------- >>> g = RectGrid([1, 2, 5], [-2, 1.5,...
Return `max_pt`. Parameters ---------- kwargs For duck-typing with `numpy.amax` See Also -------- min odl.set.domain.IntervalProd.max Examples -------- >>> g = RectGrid([1, 2, 5], [-2, 1.5, 2]) >>> g.max() arr...
def dequeue_jobs(self, max_jobs=1, job_class=None, worker=None): """ Fetch a maximum of max_jobs from this queue """ if job_class is None: from .job import Job job_class = Job count = 0 # TODO: remove _id sort after full migration to datequeued sort_o...
Fetch a maximum of max_jobs from this queue
def as_list(x): '''Ensure `x` is of list type.''' if x is None: x = [] elif not isinstance(x, Sequence): x = [x] return list(x)
Ensure `x` is of list type.
async def get_pinstate_report(self, command): """ This method retrieves a Firmata pin_state report for a pin.. See: http://firmata.org/wiki/Protocol#Pin_State_Query :param command: {"method": "get_pin_state", "params": [PIN]} :returns: {"method": "get_pin_state_reply", "params"...
This method retrieves a Firmata pin_state report for a pin.. See: http://firmata.org/wiki/Protocol#Pin_State_Query :param command: {"method": "get_pin_state", "params": [PIN]} :returns: {"method": "get_pin_state_reply", "params": [PIN_NUMBER, PIN_MODE, PIN_STATE]}
def inspect(name): ''' .. versionchanged:: 2017.7.0 Volumes and networks are now checked, in addition to containers and images. This is a generic container/image/volume/network inspecton function. It will run the following functions in order: - :py:func:`docker.inspect_container ...
.. versionchanged:: 2017.7.0 Volumes and networks are now checked, in addition to containers and images. This is a generic container/image/volume/network inspecton function. It will run the following functions in order: - :py:func:`docker.inspect_container <salt.modules.dockermod.ins...
def walk(self): """Walk proposal kernel""" if self.verbose > 1: print_('\t' + self._id + ' Running Walk proposal kernel') # Mask for values to move phi = self.phi theta = self.walk_theta u = random(len(phi)) z = (theta / (1 + theta)) * (theta * u *...
Walk proposal kernel
def choropleth(): """ Returns """ path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv') df=pd.read_csv(path) del df['Unnamed: 0'] df['z']=[np.random.randint(0,100) for _ in range(len(df))] return df
Returns
def advpng(ext_args): """Run the external program advpng on the file.""" args = _ADVPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
Run the external program advpng on the file.
def init_db(): """ Populate a small db with some example entries. """ db.drop_all() db.create_all() # Create sample Post title = "de Finibus Bonorum et Malorum - Part I" text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \ incididunt ...
Populate a small db with some example entries.
def byte2bit_string(data): """ >>> byte2bit_string("H") '00010010' >>> byte2bit_string(0x55) '10101010' """ if isinstance(data, basestring): assert len(data) == 1 data = ord(data) bits = '{0:08b}'.format(data) bits = bits[::-1] return bits
>>> byte2bit_string("H") '00010010' >>> byte2bit_string(0x55) '10101010'
def route53_public_hosted_zone_id(self, lookup, default=None): """ Args: lookup: The zone name to look up. Must end with "." default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the public hosted zone for the 'lookup' domain, or default/None if...
Args: lookup: The zone name to look up. Must end with "." default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the public hosted zone for the 'lookup' domain, or default/None if no match found
def load_module(self, module, module_uri=None): """load_module Attempts to load module by name, if it is not available, loads it by url """ # Check to see that module isn't availble in python path try: import_module(module) except ImportError, e: ...
load_module Attempts to load module by name, if it is not available, loads it by url
def add_picture(self, image_file, left, top, width=None, height=None): """Add picture shape displaying image in *image_file*. *image_file* can be either a path to a file (a string) or a file-like object. The picture is positioned with its top-left corner at (*top*, *left*). If *width* a...
Add picture shape displaying image in *image_file*. *image_file* can be either a path to a file (a string) or a file-like object. The picture is positioned with its top-left corner at (*top*, *left*). If *width* and *height* are both |None|, the native size of the image is used. If only...
def unlink(self, parameter): """ Sets free one or more parameters which have been linked previously :param parameter: the parameter to be set free, can also be a list of parameters :return: (none) """ if not isinstance(parameter,list): # Make a list of one eleme...
Sets free one or more parameters which have been linked previously :param parameter: the parameter to be set free, can also be a list of parameters :return: (none)
def image_url(self, pixel_size=None): """ Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image. """ if "profile" not in self._raw: return profile = self._raw["profile"] if (...
Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image.
def main(): """Test the functionality of the rController object""" import time print('Testing controller in position 1:') print('Running 3 x 3 seconds tests') # Initialise Controller con = rController(1) # Loop printing controller state and buttons held for i in range(3): prin...
Test the functionality of the rController object
def apply_dataset_vfunc( func, *args, signature, join='inner', dataset_join='exact', fill_value=_NO_FILL_VALUE, exclude_dims=frozenset(), keep_attrs=False ): """Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects. """ ...
Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects.
def scroll_forward(event, half=False): """ Scroll window down. """ w = _current_window_for_event(event) b = event.cli.current_buffer if w and w.render_info: info = w.render_info ui_content = info.ui_content # Height to scroll. scroll_height = info.window_height ...
Scroll window down.
def read_fcs_data_segment(buf, begin, end, datatype, num_events, param_bit_widths, big_endian, param_ranges=None): """ Read DATA s...
Read DATA segment of FCS file. Parameters ---------- buf : file-like object Buffer containing data to interpret as DATA segment. begin : int Offset (in bytes) to first byte of DATA segment in `buf`. end : int Offset (in bytes) to last byte of DATA segment in `buf`. datat...
def get_usage(self): """Get fitness locations and their current usage.""" resp = requests.get(FITNESS_URL, timeout=30) resp.raise_for_status() soup = BeautifulSoup(resp.text, "html5lib") eastern = pytz.timezone('US/Eastern') output = [] for item in soup.findAll(...
Get fitness locations and their current usage.
async def down(self): """Press key down.""" await self._send_commands( self._move('Down', 0, 20, 250), self._move('Move', 1, 20, 255), self._move('Move', 2, 20, 260), self._move('Move', 3, 20, 265), self._move('Move', 4, 20, 270), s...
Press key down.
def hardware_version(self): """Get a hardware identification string.""" hardware_string = self.hardware_string if not isinstance(hardware_string, bytes): hardware_string = self.hardware_string.encode('utf-8') if len(hardware_string) > 10: self._logger.warn("Tru...
Get a hardware identification string.
def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=("qualitative", "Set1_9")): """ Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in ...
Provides a publication quality plot, with nice defaults for font sizes etc. Args: width (float): Width of plot in inches. Defaults to 8in. height (float): Height of plot in inches. Defaults to width * golden ratio. plt (matplotlib.pyplot): If plt is supplied, changes will be mad...
def run_dependent_peptides(allPeptides_file, rawFilesTable_file, outfile): """ transform a allPeptides.txt and experimentalDesign.txt table into the dependentPeptides.txt table written in outfile. :param allPeptides_file: MaxQuant 'allPeptides.txt' output table. :param rawFilesTable_file: MaxQuant 'Raw ...
transform a allPeptides.txt and experimentalDesign.txt table into the dependentPeptides.txt table written in outfile. :param allPeptides_file: MaxQuant 'allPeptides.txt' output table. :param rawFilesTable_file: MaxQuant 'Raw files'-tab table. :param outfile: Path to the output file.
def discover_details(self): ''' Enumerate the discovered nodes from discover() and update the nodes in the array with additional info. ''' if (self.root_node == None): return if (self.verbose > 0): print('\nCollecting node details...') ni...
Enumerate the discovered nodes from discover() and update the nodes in the array with additional info.
def save_host_keys(self, filename): """ Save the host keys back to a file. Only the host keys loaded with L{load_host_keys} (plus any added directly) will be saved -- not any host keys loaded with L{load_system_host_keys}. @param filename: the filename to save to @type ...
Save the host keys back to a file. Only the host keys loaded with L{load_host_keys} (plus any added directly) will be saved -- not any host keys loaded with L{load_system_host_keys}. @param filename: the filename to save to @type filename: str @raise IOError: if the file could...
def delete(ctx, opts, owner_repo_package, yes): """ Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your...
Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'.
def download_file_from_google_drive(file_id, root, filename=None, md5=None): """Download a Google Drive file from and place it in root. Args: file_id (str): id of file to be downloaded root (str): Directory to place downloaded file in filename (str, optional): Name to save the file und...
Download a Google Drive file from and place it in root. Args: file_id (str): id of file to be downloaded root (str): Directory to place downloaded file in filename (str, optional): Name to save the file under. If None, use the id of the file. md5 (str, optional): MD5 checksum of th...
def getState(self): """See comments in base class.""" return dict(_position = self._position, position = self.getPosition(), velocity = self._velocity, bestPosition = self._bestPosition, bestResult = self._bestResult)
See comments in base class.
def file_html(models, resources, title=None, template=FILE, template_variables={}, theme=FromCurdoc, suppress_callback_warning=False, _always_new=False): ''' Return an HTML document that embeds Bokeh Model or Document ...
Return an HTML document that embeds Bokeh Model or Document objects. The data for the plot is stored directly in the returned HTML, with support for customizing the JS/CSS resources independently and customizing the jinja2 template. Args: models (Model or Document or seq[Model]) : Bokeh object...
def parallel_newton (func, x0, fprime=None, par_args=(), simple_args=(), tol=1.48e-8, maxiter=50, parallel=True, **kwargs): """A parallelized version of :func:`scipy.optimize.newton`. Arguments: func The function to search for zeros, called as ``f(x, [*par_args...], [*simple_arg...
A parallelized version of :func:`scipy.optimize.newton`. Arguments: func The function to search for zeros, called as ``f(x, [*par_args...], [*simple_args...])``. x0 The initial point for the zero search. fprime (Optional) The first derivative of *func*, called the same way. par_a...
def _check_result(self): ''' Check and set the result of a zypper command. In case of an error, either raise a CommandExecutionError or extract the error. result The result of a zypper command called with cmd.run_all ''' if not self.__call_result: ...
Check and set the result of a zypper command. In case of an error, either raise a CommandExecutionError or extract the error. result The result of a zypper command called with cmd.run_all
def _get_table_names(statement): """ Returns table names found in the query. NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well. Args: statement (sqlparse.sql.Statement): parsed by sqlparse sql statement. Returns: list of str """ parts = st...
Returns table names found in the query. NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well. Args: statement (sqlparse.sql.Statement): parsed by sqlparse sql statement. Returns: list of str
def delete_user_by_email(self, email): """ This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request. """ call = "/api/users/"+ ...
This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request.
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: """ Args: x: iterable of strings Yields: each string in lower case """ for string in x: yield string.lower()
Args: x: iterable of strings Yields: each string in lower case
def update_fp(self, fp, length): # type: (BinaryIO, int) -> None ''' Update the Inode to use a different file object and length. Parameters: fp - A file object that contains the data for this Inode. length - The length of the data. Returns: Nothing. ...
Update the Inode to use a different file object and length. Parameters: fp - A file object that contains the data for this Inode. length - The length of the data. Returns: Nothing.
def sync_with(self, config, conflict_resolver): '''Synchronizes current set of key/values in this instance with those in the config.''' if not config.has_section(self._name): config.add_section(self._name) resolved = self._sync_and_resolve(config, conflict_resolver) self._add...
Synchronizes current set of key/values in this instance with those in the config.
def register(key=None, server=None, protocol=None, api=None, certificate_validation=None, bolt=None): """API key registration and server selection Changing the key effects all derived Plotter instances. :param key: API key. :type key: String. :param server: URL of the visualiza...
API key registration and server selection Changing the key effects all derived Plotter instances. :param key: API key. :type key: String. :param server: URL of the visualization server. :type server: Optional string. :param protocol: Protocol used to contact visualizati...
def safeunicode(arg, *args, **kwargs): """Coerce argument to unicode, if it's not already.""" return arg if isinstance(arg, unicode) else unicode(arg, *args, **kwargs)
Coerce argument to unicode, if it's not already.
def del_doc(self, doc): """ Delete a document """ if not self.index_writer: self.index_writer = self.index.writer() if not self.label_guesser_updater: self.label_guesser_updater = self.label_guesser.get_updater() logger.info("Removing doc from the ...
Delete a document
def directed_bipartition(seq, nontrivial=False): """Return a list of directed bipartitions for a sequence. Args: seq (Iterable): The sequence to partition. Returns: list[tuple[tuple]]: A list of tuples containing each of the two parts. Example: >>> directed_bipartition...
Return a list of directed bipartitions for a sequence. Args: seq (Iterable): The sequence to partition. Returns: list[tuple[tuple]]: A list of tuples containing each of the two parts. Example: >>> directed_bipartition((1, 2, 3)) # doctest: +NORMALIZE_WHITESPACE [(...
def create_job(batch_service_client, job_id, pool_id): """Creates a job with the specified ID, associated with the specified pool. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.batch.BatchServiceClient` :param str job_id: The ID for the job. :param str pool...
Creates a job with the specified ID, associated with the specified pool. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.batch.BatchServiceClient` :param str job_id: The ID for the job. :param str pool_id: The ID for the pool.
def prepare_bucket(self): """ Resets and creates the destination bucket ( only called if --create is true). :return: """ self.logger.info('Deleting old bucket first') del_url = '{0}/buckets/{1}'.format(self.cluster_prefix, self.bucket) r = self._htsess...
Resets and creates the destination bucket ( only called if --create is true). :return:
def drop(self, items): """Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop. """ self._manager.leaser.remove(items) self._manager.maybe_resume_consumer()
Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop.
def html_table_from_query(rows: Iterable[Iterable[Optional[str]]], descriptions: Iterable[Optional[str]]) -> str: """ Converts rows from an SQL query result to an HTML table. Suitable for processing output from the defunct function ``rnc_db.fetchall_with_fieldnames(sql)``. ...
Converts rows from an SQL query result to an HTML table. Suitable for processing output from the defunct function ``rnc_db.fetchall_with_fieldnames(sql)``.
def ast2expr(ast): """Convert an abstract syntax tree to an Expression.""" if ast[0] == 'const': return _CONSTS[ast[1]] elif ast[0] == 'var': return exprvar(ast[1], ast[2]) else: xs = [ast2expr(x) for x in ast[1:]] return ASTOPS[ast[0]](*xs, simplify=False)
Convert an abstract syntax tree to an Expression.
def _replaceParam(self, p, newP): """ Replace parameter on this interface (in configuration stage) :ivar pName: actual name of param on me :ivar newP: new Param instance by which should be old replaced """ i = self._params.index(p) pName = p._scopes[self][1] ...
Replace parameter on this interface (in configuration stage) :ivar pName: actual name of param on me :ivar newP: new Param instance by which should be old replaced
def skip_job(self, job_record): """ method transfers: - given job into STATE_SKIPPED if it is not not in finished state - UOW into STATE_CANCELED if it is not in finished state """ original_job_state = job_record.state if not job_record.is_finished: job_recor...
method transfers: - given job into STATE_SKIPPED if it is not not in finished state - UOW into STATE_CANCELED if it is not in finished state
def proxy(self) -> bool: """ 从 app 读取是否判断 proxy """ if self.app is None: return False return bool(cast(Any, self.app).proxy)
从 app 读取是否判断 proxy
def emit(self, batch): """Submits batches to Thrift HTTP Server through Binary Protocol. :type batch: :class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch` :param batch: Object to emit Jaeger spans. """ try: self.client.submitBatches([batch]) ...
Submits batches to Thrift HTTP Server through Binary Protocol. :type batch: :class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch` :param batch: Object to emit Jaeger spans.
def pips(f_fcn, x0, A=None, l=None, u=None, xmin=None, xmax=None, gh_fcn=None, hess_fcn=None, opt=None): """Primal-dual interior point method for NLP (non-linear programming). Minimize a function F(X) beginning from a starting point M{x0}, subject to optional linear and non-linear constraints and v...
Primal-dual interior point method for NLP (non-linear programming). Minimize a function F(X) beginning from a starting point M{x0}, subject to optional linear and non-linear constraints and variable bounds:: min f(x) x subject to:: g(x) = 0 (non-linear equa...
def setWorkingCollisionBoundsInfo(self, unQuadsCount): """Sets the Collision Bounds in the working copy.""" fn = self.function_table.setWorkingCollisionBoundsInfo pQuadsBuffer = HmdQuad_t() fn(byref(pQuadsBuffer), unQuadsCount) return pQuadsBuffer
Sets the Collision Bounds in the working copy.
def create_deployment_details(vcenter_resource_model, vm_cluster, vm_storage, vm_resource_pool, vm_location): """ :type vcenter_resource_model: VMwarevCenterResourceModel :type vm_cluster: str :type vm_storage: str :type vm_resource_pool: str :type vm_location: str ...
:type vcenter_resource_model: VMwarevCenterResourceModel :type vm_cluster: str :type vm_storage: str :type vm_resource_pool: str :type vm_location: str :rtype: DeploymentDetails
def join(self, timeout=None): """Joins the pool waiting until all workers exited. If *timeout* is set, it block until all workers are done or raises TimeoutError. """ if self._context.state == RUNNING: raise RuntimeError('The Pool is still running') if self._...
Joins the pool waiting until all workers exited. If *timeout* is set, it block until all workers are done or raises TimeoutError.
def free (self): """ Returns free properties which are not dependency properties. """ result = [p for p in self.lazy_properties if not p.feature.incidental and p.feature.free] result.extend(self.free_) return result
Returns free properties which are not dependency properties.
def get_version(fname): "grab __version__ variable from fname (assuming fname is a python file). parses without importing." assign_stmts = [s for s in ast.parse(open(fname).read()).body if isinstance(s,ast.Assign)] valid_targets = [s for s in assign_stmts if len(s.targets) == 1 and s.targets[0].id == '__versio...
grab __version__ variable from fname (assuming fname is a python file). parses without importing.
def parse_html(html, cleanup=True): """ Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags. """ if cl...
Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags.
def _redundancy_routers_for_floatingip( self, context, router_id, redundancy_router_ids=None, ha_settings_db=None): """To be called in update_floatingip() to get the redundant router ids. """ if ha_settings_db is None: ha_settings_db = self._get_ha...
To be called in update_floatingip() to get the redundant router ids.
def build_reverse_dictionary(word_to_id): """Given a dictionary that maps word to integer id. Returns a reverse dictionary that maps a id to word. Parameters ---------- word_to_id : dictionary that maps word to ID. Returns -------- dictionary A dictionary that maps IDs ...
Given a dictionary that maps word to integer id. Returns a reverse dictionary that maps a id to word. Parameters ---------- word_to_id : dictionary that maps word to ID. Returns -------- dictionary A dictionary that maps IDs to words.
def find_by_project(self, project, params={}, **options): """Returns the compact records for all sections in the specified project. Parameters ---------- project : {Id} The project to get sections from. [params] : {Object} Parameters for the request """ path = "...
Returns the compact records for all sections in the specified project. Parameters ---------- project : {Id} The project to get sections from. [params] : {Object} Parameters for the request
def create(self, model_obj): """Write a record to the dict repository""" # Update the value of the counters model_obj = self._set_auto_fields(model_obj) # Add the entity to the repository identifier = model_obj[self.entity_cls.meta_.id_field.field_name] with self.conn['l...
Write a record to the dict repository
def process_file(self, filepath, only_if_updated=True, safe_mode=True): """ Given a path to a python module or zip file, this method imports the module and look for dag objects within it. """ from airflow.models.dag import DAG # Avoid circular import found_dags = [] ...
Given a path to a python module or zip file, this method imports the module and look for dag objects within it.
def load_nifti(filename, to='auto'): ''' load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are underst...
load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are understood: * 'header' will yield just the image h...
def dar_nombre_campo_dbf(clave, claves): "Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir" # achico el nombre del campo para que quepa en la tabla: nombre = clave.replace("_","")[:10] # si el campo esta repetido, le agrego un número i = 0 while nombre in claves: i...
Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir
def show_zoning_enabled_configuration_output_enabled_configuration_enabled_zone_member_entry_entry_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration") config = show_zoni...
Auto Generated Code
def fetch(self, url, params): """Return the textual content associated to the Response object""" logger.debug("Kitsune client calls API: %s params: %s", url, str(params)) response = super().fetch(url, payload=params) return response.text
Return the textual content associated to the Response object
def build(self): """build the scripts and return a string""" if not self.embed: mkdir_recursive(self.output_directory) # get list of script files in build order self.build_order = remove_dups( reduce(lambda a, b: a + glob.glob(b), self.build_t...
build the scripts and return a string
def _check_field_value(field_value, pattern): """Check a song metadata field value for a pattern.""" if isinstance(field_value, list): return any(re.search(pattern, str(value), re.I) for value in field_value) else: return re.search(pattern, str(field_value), re.I)
Check a song metadata field value for a pattern.
def _login_snmp(self): """Login to a SNMP server""" logger.info("Trying to grab stats by SNMP...") from glances.stats_client_snmp import GlancesStatsClientSNMP # Init stats self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) if not self.stats.check_...
Login to a SNMP server
def ValidateYesNoUnknown(value, column_name=None, problems=None): """Validates a value "0" for uknown, "1" for yes, and "2" for no.""" if IsEmpty(value) or IsValidYesNoUnknown(value): return True else: if problems: problems.InvalidValue(column_name, value) return False
Validates a value "0" for uknown, "1" for yes, and "2" for no.
def add_channel_info(self, data, clear=False): """ Add channel info data to the channel_id group. :param data: A dictionary of key/value pairs. Keys must be strings. Values can be strings or numeric values. :param clear: If set, any existing channel info data will be removed...
Add channel info data to the channel_id group. :param data: A dictionary of key/value pairs. Keys must be strings. Values can be strings or numeric values. :param clear: If set, any existing channel info data will be removed.
def _do_relation(self): """ Attaches subjects, objects and verbs. If the previous chunk is a subject/object/verb, it is stored in Sentence.relations{}. """ if self.chunks: ch = self.chunks[-1] for relation, role in ch.relations: if role == "SBJ...
Attaches subjects, objects and verbs. If the previous chunk is a subject/object/verb, it is stored in Sentence.relations{}.
def save_pstat(self, path): """ Save the modified pstats file """ stats = {} for s in self.stats: if not s.exclude: stats.update(s.to_dict()) with open(path, 'wb') as f: marshal.dump(stats, f)
Save the modified pstats file
def eigenvalues_hadamard(matrix1, matrix2): """Computes the Hadamard product of 2 matrices. See https://www.johndcook.com/blog/2018/10/10/hadamard-product/ for details :param matrix1: first matrix :param matrix2: second matrix :return: lower and upper """ matrix1 = array(matrix1) # as arr...
Computes the Hadamard product of 2 matrices. See https://www.johndcook.com/blog/2018/10/10/hadamard-product/ for details :param matrix1: first matrix :param matrix2: second matrix :return: lower and upper
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'): "Get the version of the specified program" args_prog = [program, version_arg] try: proc = run( args_prog, close_fds=True, universal_newlines=True, stdout=PIPE, st...
Get the version of the specified program
def uninstall(plugin_package, plugins_directory): ''' Parameters ---------- plugin_package : str Name of plugin package hosted on MicroDrop plugin index. plugins_directory : str Path to MicroDrop user plugins directory. ''' # Check existing version (if any). plugin_path =...
Parameters ---------- plugin_package : str Name of plugin package hosted on MicroDrop plugin index. plugins_directory : str Path to MicroDrop user plugins directory.
def all(self): """ Return all registered users http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource """ return self._client.get( url=self._client.get_full_url( self.get_path('collection', realm=self._realm_name) ) ...
Return all registered users http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
def _get_scope_with_mangled(self, name): """Return a scope containing passed mangled name.""" scope = self while True: parent = scope.get_enclosing_scope() if parent is None: return if name in parent.rev_mangled: return parent ...
Return a scope containing passed mangled name.
def rest_add_filters(self, data): """ Adds list of dicts :param data: list of dicts :return: """ for _filter in data: filter_class = map_args_filter.get(_filter["opr"], None) if filter_class: self.add_filter(_filter["col"], fil...
Adds list of dicts :param data: list of dicts :return:
def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # c...
Compile given source code. Return object code, modified by given post treatment.
def relabel(image): """Given a labeled image, relabel each of the objects consecutively image - a labeled 2-d integer array returns - (labeled image, object count) """ # # Build a label table that converts an old label # into # labels using the new numbering scheme # unique_lab...
Given a labeled image, relabel each of the objects consecutively image - a labeled 2-d integer array returns - (labeled image, object count)
def compile(self, session=None): """ Before calling the standard compile function, check to see if the size of the data has changed and add variational parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data. """ ...
Before calling the standard compile function, check to see if the size of the data has changed and add variational parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data.
def print_diskinfo(diskinfo, widelayout, incolor): ''' Disk information output function. ''' sep = ' ' if opts.relative: import math base = max([ disk.ocap for disk in diskinfo ]) for disk in diskinfo: if disk.ismntd: ico = _diskico else: ico = _unmnico...
Disk information output function.
def drdcyl(r, lon, z): """ This routine computes the Jacobian of the transformation from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdcyl_c.html :param r: Distance of a point from the origin. :type r: float :param lon: Angle of the poin...
This routine computes the Jacobian of the transformation from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdcyl_c.html :param r: Distance of a point from the origin. :type r: float :param lon: Angle of the point from the xz plane in radians. ...
def read_mm_header(fd, byte_order, dtype, count): """Read MM_HEADER tag from file and return as numpy.rec.array.""" return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]
Read MM_HEADER tag from file and return as numpy.rec.array.