positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def recv_line(self, max_size=None, timeout='default', ending=None): """ Recieve until the next newline , default "\\n". The newline string can be changed by changing ``nc.LINE_ENDING``. The newline will be returned as part of the string. Aliases: recvline, readline, read_line, r...
Recieve until the next newline , default "\\n". The newline string can be changed by changing ``nc.LINE_ENDING``. The newline will be returned as part of the string. Aliases: recvline, readline, read_line, readln, recvln
def get_current_environment(self, note=None): """Returns the current environment id from the current shutit_pexpect_session """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) res = self.get_current_shutit_pexpect_session_environment().environment_id self.handle_note_after(note) ...
Returns the current environment id from the current shutit_pexpect_session
def return_markers(self): """Return all the markers (also called triggers or events). Returns ------- list of dict where each dict contains 'name' as str, 'start' and 'end' as float in seconds from the start of the recordings, and 'chan' as list of st...
Return all the markers (also called triggers or events). Returns ------- list of dict where each dict contains 'name' as str, 'start' and 'end' as float in seconds from the start of the recordings, and 'chan' as list of str with the channels involved (if not ...
def show_system_monitor_output_switch_status_rbridge_id_out(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "output")...
Auto Generated Code
def _get_filter_ids(cls, request): """Parses the `id` filter paramter from the url query. """ id_query = request.url.query.get('id', None) if id_query is None: return None filter_ids = id_query.split(',') for filter_id in filter_ids: cls._validat...
Parses the `id` filter paramter from the url query.
def collective_diffusion_coefficient( self ): """ Returns the collective or "jump" diffusion coefficient, D_J. Args: None Returns: (Float): The collective diffusion coefficient, D_J. """ if self.has_run: return self.atoms.collective_d...
Returns the collective or "jump" diffusion coefficient, D_J. Args: None Returns: (Float): The collective diffusion coefficient, D_J.
def set_volume(self, volume): """ Set receiver volume via HTTP get command. Volume is send in a format like -50.0. Minimum is -80.0, maximum at 18.0 """ if volume < -80 or volume > 18: raise ValueError("Invalid volume") try: return bool(s...
Set receiver volume via HTTP get command. Volume is send in a format like -50.0. Minimum is -80.0, maximum at 18.0
def delete(customer, card): """ Delete a card from its id. :param customer: The customer id or object :type customer: string|Customer :param card: The card id or object :type card: string|Card """ if isinstance(customer, resources.Customer): c...
Delete a card from its id. :param customer: The customer id or object :type customer: string|Customer :param card: The card id or object :type card: string|Card
def query_induction(self, nodes: List[Node]) -> List[Edge]: """Get all edges between any of the given nodes (minimum length of 2).""" if len(nodes) < 2: raise ValueError('not enough nodes given to induce over') return self.session.query(Edge).filter(self._edge_both_nodes(nodes)).all...
Get all edges between any of the given nodes (minimum length of 2).
def _typed_from_items(items): """ Construct strongly typed attributes (properties) from a dictionary of name and :class:`~exa.typed.Typed` object pairs. See Also: :func:`~exa.typed.typed` """ dct = {} for name, attr in items: if isinstance(attr, Typed): dct[name]...
Construct strongly typed attributes (properties) from a dictionary of name and :class:`~exa.typed.Typed` object pairs. See Also: :func:`~exa.typed.typed`
def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) ...
Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) u'parent|child' :param attribute: Attribute. :type attribute: unicode :param namesp...
def rule(self): """ Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used ------------------- _fd_matrix Member variables used --------------------...
Return finite differencing rule. The rule is for a nominal unit step size, and must be scaled later to reflect the local step size. Member methods used ------------------- _fd_matrix Member variables used --------------------- n order me...
def standardize_role(role): """Convert role text into standardized form.""" role = role.lower() if any(c in role for c in {'synthesis', 'give', 'yield', 'afford', 'product', 'preparation of'}): return 'product' return role
Convert role text into standardized form.
async def on_error(self, event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details. ...
|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`discord.on_error` for more details.
def grep(filename, tag, firstOccurrence=False): """Greps the line that starts with a specific `tag` string from inside a file.""" import re try: afile = open(filename, "r") except: print("Error in utils.grep(): cannot open file", filename) exit() content = None for line ...
Greps the line that starts with a specific `tag` string from inside a file.
def _compute_layer_name(is_defined_within_template, arn): """ Computes a unique name based on the LayerVersion Arn Format: <Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn> Parameters ---------- is_defined_within_template bool ...
Computes a unique name based on the LayerVersion Arn Format: <Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn> Parameters ---------- is_defined_within_template bool True if the resource is a Ref to a resource otherwise False arn st...
def center_of_mass(X, Y): """Get center of mass Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- res: number The position of the center of mass in X Notes ----- Uses least squares """ X = np.asarray(X) Y = ...
Get center of mass Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- res: number The position of the center of mass in X Notes ----- Uses least squares
def getNumberOfRegularSamples(self): """ Returns the number of regular samples. :returns: number of regular samples :rtype: integer """ analyses = self.getRegularAnalyses() samples = [a.getRequestUID() for a in analyses] # discarding any duplicate values ...
Returns the number of regular samples. :returns: number of regular samples :rtype: integer
def clear(self): """Clear the displayed image.""" self._imgobj = None try: # See if there is an image on the canvas self.canvas.delete_object_by_tag(self._canvas_img_tag) self.redraw() except KeyError: pass
Clear the displayed image.
def definition_name(cls): """Helper method for creating definition name. Names will be generated to include the classes package name, scope (if the class is nested in another definition) and class name. By default, the package name for a definition is derived from its m...
Helper method for creating definition name. Names will be generated to include the classes package name, scope (if the class is nested in another definition) and class name. By default, the package name for a definition is derived from its module name. However, this value can b...
def copy(self, invert=False): """Return a copy of the current instance Parameters ---------- invert: bool The copy will be inverted w.r.t. the original """ if invert: inverted = not self.inverted else: inverted = self.inverted ...
Return a copy of the current instance Parameters ---------- invert: bool The copy will be inverted w.r.t. the original
def view_portfolio_losses(token, dstore): """ The losses for the full portfolio, for each realization and loss type, extracted from the event loss table. """ oq = dstore['oqparam'] loss_dt = oq.loss_dt() data = portfolio_loss(dstore).view(loss_dt)[:, 0] rlzids = [str(r) for r in range(le...
The losses for the full portfolio, for each realization and loss type, extracted from the event loss table.
def rebuildtable(cls): """Regenerate the entire closuretree.""" cls._closure_model.objects.all().delete() cls._closure_model.objects.bulk_create([cls._closure_model( parent_id=x['pk'], child_id=x['pk'], depth=0 ) for x in cls.objects.values("pk")]) ...
Regenerate the entire closuretree.
def min_cvar(self, s=10000, beta=0.95, random_state=None): """ Find the portfolio weights that minimises the CVaR, via Monte Carlo sampling from the return distribution. :param s: number of bootstrap draws, defaults to 10000 :type s: int, optional :param beta: "significa...
Find the portfolio weights that minimises the CVaR, via Monte Carlo sampling from the return distribution. :param s: number of bootstrap draws, defaults to 10000 :type s: int, optional :param beta: "significance level" (i. 1 - q), defaults to 0.95 :type beta: float, optional ...
def maxId(self): """int: current max id of objects""" if len(self.model.db) == 0: return 0 return max(map(lambda obj: obj["id"], self.model.db))
int: current max id of objects
def __write_p4settings(self, config): """ write perforce settings """ self.logger.info("Writing p4settings...") root_dir = os.path.expanduser(config.get('root_path')) p4settings_path = os.path.join(root_dir, ".p4settings") if os.path.exists(p4settings_path): if self.t...
write perforce settings
async def unformat(self): """Unformat this partition.""" self._data = await self._handler.unformat( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id)
Unformat this partition.
def _product(*args, **kwds): """ Generates cartesian product of lists given as arguments From itertools.product documentation """ pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] return result
Generates cartesian product of lists given as arguments From itertools.product documentation
def default_spec(self, manager): """ Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">...
Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">=2")``. * When ``releases_always_forward...
def error_response(self, code, content=''): """Construct and send error response.""" self.send_response(code) self.send_header('Content-Type', 'text/xml') self.add_compliance_header() self.end_headers() self.wfile.write(content)
Construct and send error response.
def inflate(self, value): """ Handles the marshalling from Neo4J POINT to NeomodelPoint :param value: Value returned from the database :type value: Neo4J POINT :return: NeomodelPoint """ if not isinstance(value,neo4j.types.spatial.Point): raise TypeEr...
Handles the marshalling from Neo4J POINT to NeomodelPoint :param value: Value returned from the database :type value: Neo4J POINT :return: NeomodelPoint
def get_cert_types(self): """ Collect the certificate types that are available to the customer. :return: A list of dictionaries of certificate types :rtype: list """ result = self.client.service.getCustomerCertTypes(authData=self.auth) if result.statusCode == 0:...
Collect the certificate types that are available to the customer. :return: A list of dictionaries of certificate types :rtype: list
def bump_repos_version(module_name, new_version, local_only): """ Changes the pinned version number in the requirements files of all repos which have the specified Python module as a dependency. This script assumes that GITHUB_TOKEN is set for GitHub authentication. """ # Make the cloning direc...
Changes the pinned version number in the requirements files of all repos which have the specified Python module as a dependency. This script assumes that GITHUB_TOKEN is set for GitHub authentication.
def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty. """ # Don't poll shards when there are pending records. if self.buffer: return # 0) Collect ...
Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty.
def complete_automaton(self): """ Adds missing transition states such that δ(q, u) is defined for every state q and any u ∈ S """ self.term_state = object() self.Q.add(self.term_state) for tv in self.Q: for u in self.S: try: ...
Adds missing transition states such that δ(q, u) is defined for every state q and any u ∈ S
def connectionMade(self): """Send a HTTP POST command with the appropriate CIM over HTTP headers and payload.""" self.factory.request_xml = str(self.factory.payload) self.sendCommand('POST', '/cimom') self.sendHeader('Host', '%s:%d' % (self.transport.ad...
Send a HTTP POST command with the appropriate CIM over HTTP headers and payload.
def generate_network(user=None, reset=False): """ Assemble the network connections for a given user """ token = collect_token() try: gh = login(token=token) root_user = gh.user(user) except Exception, e: # Failed to login using the token, github3.models.GitHubError ...
Assemble the network connections for a given user
def _readXputMaps(self, mapCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None): """ GSSHA Project Read Map Files from File Method """ if self.mapType in self.MAP_TYPES_SUPPORTED: for card in self.projectCards: if (card.nam...
GSSHA Project Read Map Files from File Method
def get_class(schema_name): """ Retrieve the message class associated with the schema name. If no match is found, the default schema is returned and a warning is logged. Args: schema_name (six.text_type): The name of the :class:`Message` sub-class; this is typically the Python path...
Retrieve the message class associated with the schema name. If no match is found, the default schema is returned and a warning is logged. Args: schema_name (six.text_type): The name of the :class:`Message` sub-class; this is typically the Python path. Returns: Message: A sub-c...
def load(cls, fpath): """Loads a module and returns its object. :param str|unicode fpath: :rtype: module """ module_name = os.path.splitext(os.path.basename(fpath))[0] sys.path.insert(0, os.path.dirname(fpath)) try: module = import_module(module_name...
Loads a module and returns its object. :param str|unicode fpath: :rtype: module
def _decode_lines(geom): """ Decode a linear MVT geometry into a list of Lines. Each individual linestring in the MVT is extracted to a separate entry in the list of lines. """ lines = [] current_line = [] current_moveto = None # to keep track of the position. we'll adapt the move...
Decode a linear MVT geometry into a list of Lines. Each individual linestring in the MVT is extracted to a separate entry in the list of lines.
def _get_connection_state(self, conn_or_int_id): """Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal str...
Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id
def lookup(alias): """ Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one. """ if alias in matchers: return matchers[alias] else: norm = normalize(alias) ...
Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one.
def _cron_matched(cron, cmd, identifier=None): '''Check if: - we find a cron with same cmd, old state behavior - but also be smart enough to remove states changed crons where we do not removed priorly by a cron.absent by matching on the provided identifier. We assure retrocompati...
Check if: - we find a cron with same cmd, old state behavior - but also be smart enough to remove states changed crons where we do not removed priorly by a cron.absent by matching on the provided identifier. We assure retrocompatibility by only checking on identifier if and o...
def find_snapshots(network, carrier, maximum = True, minimum = True, n = 3): """ Function that returns snapshots with maximum and/or minimum feed-in of selected carrier. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA carrier: str Selec...
Function that returns snapshots with maximum and/or minimum feed-in of selected carrier. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA carrier: str Selected carrier of generators maximum: bool Choose if timestep of maximal feed-in is r...
def write_tables(target, tables, append=False, overwrite=False, **kwargs): """Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` ...
Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `T...
def double_prompt_for_plaintext_password(): """Get the desired password from the user through a double prompt.""" password = 1 password_repeat = 2 while password != password_repeat: password = getpass.getpass('Enter password: ') password_repeat = getpass.getpass('Repeat password: ') ...
Get the desired password from the user through a double prompt.
def DataProcessorsDelete(self, dataProcessorId): """ Delete a data processor in CommonSense. @param dataProcessorId - The id of the data processor that will be deleted. @return (bool) - Boolean indicating whether GroupsP...
Delete a data processor in CommonSense. @param dataProcessorId - The id of the data processor that will be deleted. @return (bool) - Boolean indicating whether GroupsPost was successful.
def update(self, instance, validated_data): """ change password """ instance.user.set_password(validated_data["password1"]) instance.user.full_clean() instance.user.save() # mark password reset object as reset instance.reset = True instance.full_clean() in...
change password
def train(ctx, output, corpus, clusters): """Train POS Tagger.""" click.echo('chemdataextractor.pos.train') click.echo('Output: %s' % output) click.echo('Corpus: %s' % corpus) click.echo('Clusters: %s' % clusters) wsj_sents = [] genia_sents = [] if corpus == 'wsj' or corpus == 'wsj+gen...
Train POS Tagger.
def _get_response(self, params): """ wrap the call to the requests package """ return self._session.get( self._api_url, params=params, timeout=self._timeout ).json(encoding="utf8")
wrap the call to the requests package
def dest_path(self): """ :return: The destination path. :rtype: str """ if os.path.isabs(self.config.local_path): return self.config.local_path else: return os.path.normpath(os.path.join( os.getcwd(), self.config.loc...
:return: The destination path. :rtype: str
def _create_put_request(self, resource, billomat_id, command=None, send_data=None): """ Creates a put request and return the response data """ assert (isinstance(resource, str)) if isinstance(billomat_id, int): billomat_id = str(billomat_id) if not command: ...
Creates a put request and return the response data
def extract_months(time, months): """Extract times within specified months of the year. Parameters ---------- time : xarray.DataArray Array of times that can be represented by numpy.datetime64 objects (i.e. the year is between 1678 and 2262). months : Desired months of the year to...
Extract times within specified months of the year. Parameters ---------- time : xarray.DataArray Array of times that can be represented by numpy.datetime64 objects (i.e. the year is between 1678 and 2262). months : Desired months of the year to include Returns ------- xar...
def _get_library_root_key_for_os_path(self, path): """Return library root key if path is within library root paths""" path = os.path.realpath(path) library_root_key = None for library_root_key, library_root_path in self._library_root_paths.items(): rel_path = os.path.relpath(...
Return library root key if path is within library root paths
def _parse_config(self, config): """ Parses a tensorflow configuration """ self._batch_size = config['batch_size'] self._im_height = config['im_height'] self._im_width = config['im_width'] self._num_channels = config['channels'] self._output_layer = config['out_layer'] ...
Parses a tensorflow configuration
def get_sys_info(): "Returns system information as a dict" blob = [] # commit = cc._git_hash # blob.append(('commit', commit)) try: (sysname, nodename, release, version, machine, processor) = platform.uname() blob.extend([ ("python", "%d.%d.%d.%s.%s" % sys.ver...
Returns system information as a dict
def remove_routes(self, item, routes): """Removes item from matching routes""" for route in routes: items = self._routes.get(route) try: items.remove(item) LOG.debug('removed item from route %s', route) except ValueError: ...
Removes item from matching routes
def _import(self, record_key, record_data, overwrite=True, encryption='', last_modified=0.0, **kwargs): ''' a helper method for other storage clients to import into s3 :param record_key: string with key for record :param record_data: byte data for body of record...
a helper method for other storage clients to import into s3 :param record_key: string with key for record :param record_data: byte data for body of record :param overwrite: [optional] boolean to overwrite existing records :param encryption: [optional] string with encryption ...
def memoize(func): """ Decorator to cause a function to cache it's results for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> @memoize ... def foo(x): ... print('running function wit...
Decorator to cause a function to cache it's results for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> @memoize ... def foo(x): ... print('running function with', x) ... return x+3 ...
def pool_create(self, name, description, is_public): """Function to create a pool (Require login) (UNTESTED). Parameters: name (str): The name. description (str): A description of the pool. is_public (int): 1 or 0, whether or not the pool is public. """ ...
Function to create a pool (Require login) (UNTESTED). Parameters: name (str): The name. description (str): A description of the pool. is_public (int): 1 or 0, whether or not the pool is public.
def render_field_description(field): """ Render a field description as HTML. """ if hasattr(field, 'description') and field.description != '': html = """<p class="help-block">{field.description}</p>""" html = html.format( field=field ) return HTMLString(html)...
Render a field description as HTML.
def check_runtime_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second """ a_minute_value = calc_minutes_from_ticks(the_s...
OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second
def _varx(ins): """ Defines a memory space with a default CONSTANT expression 1st parameter is the var name 2nd parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc) 3rd parameter is the list of expressions. All of them will be converted to the type required. """ outpu...
Defines a memory space with a default CONSTANT expression 1st parameter is the var name 2nd parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc) 3rd parameter is the list of expressions. All of them will be converted to the type required.
def read_data(self, variable_instance): """ read values from the device """ if self.inst is None: return if variable_instance.visavariable.device_property.upper() == 'vrms_chan1': return self.parse_value(self.inst.query(':MEAS:ITEM? VRMS,CHAN1')) r...
read values from the device
def get_visible_elements(self, locator, params=None, timeout=None): """ Get elements both present AND visible in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :p...
Get elements both present AND visible in the DOM. If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: locator tuple :param params: (optional) locator params :pa...
def mass1_from_mass2_eta(mass2, eta, force_real=True): """Returns the primary mass from the secondary mass and symmetric mass ratio. """ return mass_from_knownmass_eta(mass2, eta, known_is_secondary=True, force_real=force_real)
Returns the primary mass from the secondary mass and symmetric mass ratio.
def from_client_config(cls, client_config, scopes, **kwargs): """Creates a :class:`requests_oauthlib.OAuth2Session` from client configuration loaded from a Google-format client secrets file. Args: client_config (Mapping[str, Any]): The client configuration in the Goo...
Creates a :class:`requests_oauthlib.OAuth2Session` from client configuration loaded from a Google-format client secrets file. Args: client_config (Mapping[str, Any]): The client configuration in the Google `client secrets`_ format. scopes (Sequence[str]): The lis...
def load_models_in_model_repo(self, global_model_repo=None, encoding='utf-8'): """ load all registered models (called explicitly from the user and not as an automatic activity). Normally this is done automatically while reference resolution of on...
load all registered models (called explicitly from the user and not as an automatic activity). Normally this is done automatically while reference resolution of one loaded model. However, if you wish to load all models you can call this and get a model repository. The m...
def queryAll(self, queryString): ''' Retrieves data from specified objects, whether or not they have been deleted. ''' self._setHeaders('queryAll') return self._sforce.service.queryAll(queryString)
Retrieves data from specified objects, whether or not they have been deleted.
async def send_document(self, path, entity): """Sends the file located at path to the desired entity as a document""" await self.send_file( entity, path, force_document=True, progress_callback=self.upload_progress_callback ) print('Document sent!')
Sends the file located at path to the desired entity as a document
def list_directory(self, mdir, limit=None, marker=None): """ListDirectory https://apidocs.joyent.com/manta/api.html#ListDirectory @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @param limit {int} Limits the number of records to come back (default and max is 1000)....
ListDirectory https://apidocs.joyent.com/manta/api.html#ListDirectory @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @param limit {int} Limits the number of records to come back (default and max is 1000). @param marker {str} Key name at which to start the next lis...
def in_place( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, ): """ A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects,...
A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects, where `writable` replaces `readable`. If an exception occurs, the old file is restored, removing the written data. Mode *must not* us...
def update(self, *args, **kwargs): """d.update([E, ]**F) -> None. Update D from mapping/iterable E and F. Overwrite the values in `d` with the keys from `E` and `F`. If any key in `value` is invalid in `d`, ``KeyError`` is raised. This method is atomic - either all values in `value` a...
d.update([E, ]**F) -> None. Update D from mapping/iterable E and F. Overwrite the values in `d` with the keys from `E` and `F`. If any key in `value` is invalid in `d`, ``KeyError`` is raised. This method is atomic - either all values in `value` are set in `d`, or none are. ``update``...
def max_frequency (sig,FS): """Compute max frequency along the specified axes. Parameters ---------- sig: ndarray input from which max frequency is computed. FS: int sampling frequency Returns ------- f_max: int 0.95 of max_frequency using cumsum. """ ...
Compute max frequency along the specified axes. Parameters ---------- sig: ndarray input from which max frequency is computed. FS: int sampling frequency Returns ------- f_max: int 0.95 of max_frequency using cumsum.
def stdout_to_results(s): """Turns the multi-line output of a benchmark process into a sequence of BenchmarkResult instances.""" results = s.strip().split('\n') return [BenchmarkResult(*r.split()) for r in results]
Turns the multi-line output of a benchmark process into a sequence of BenchmarkResult instances.
def random_redshift_array( log, sampleNumber, lowerRedshiftLimit, upperRedshiftLimit, redshiftResolution, pathToOutputPlotDirectory, plot=False): """ *Generate a NumPy array of random distances given a sample number and distance limit* **Key Arguments...
*Generate a NumPy array of random distances given a sample number and distance limit* **Key Arguments:** - ``log`` -- logger - ``sampleNumber`` -- the sample number, i.e. array size - ``lowerRedshiftLimit`` -- the lower redshift limit of the volume to be included - ``upperRedshiftLi...
def rows(self): """Returns a numpy array of the rows name""" bf = self.copy() result = bf.query.executeQuery(format="soa") return result["_rowName"]
Returns a numpy array of the rows name
def create(dotted, shortname, longname): """ Creates new OID in the database @param dotted - dotted-decimal representation of new OID @param shortname - short name for new OID @param longname - long name for new OID @returns Oid object corresponding to new OID This function should be used...
Creates new OID in the database @param dotted - dotted-decimal representation of new OID @param shortname - short name for new OID @param longname - long name for new OID @returns Oid object corresponding to new OID This function should be used with exreme care. Whenever possible, it is bette...
def url(self): """ Returns the URL for the current transformation, which can be used to retrieve the file. If security is enabled, signature and policy parameters will be included *returns* [String] ```python transform = client.upload(filepath='/path/to/file') ...
Returns the URL for the current transformation, which can be used to retrieve the file. If security is enabled, signature and policy parameters will be included *returns* [String] ```python transform = client.upload(filepath='/path/to/file') transform.url() # ht...
def setFilepath( self, filepath ): """ Sets the filepath for this button to the inputed path. :param filepath | <str> """ self._filepath = nativestring(filepath) self.setIcon(QIcon(filepath)) if ( not self.signalsBlocked() ): self.filepat...
Sets the filepath for this button to the inputed path. :param filepath | <str>
def consistent_with_call(self, call): """ check to see if a new call would be consistent to add to this Axes instance checks include: * compatible units in all directions * compatible independent-variable (if applicable) """ if len(self.calls) == 0: r...
check to see if a new call would be consistent to add to this Axes instance checks include: * compatible units in all directions * compatible independent-variable (if applicable)
def __marshal_matches(matched): """Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format """ json_matches = [] for m in matched: identities = [i.uuid for i in m] if l...
Convert matches to JSON format. :param matched: a list of matched identities :returns json_matches: a list of matches in JSON format
def get_parser(): """Get parser for mpu.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('--version', action='version'...
Get parser for mpu.
def get_row_list(self, row_idx): """ get a feature vector for the nth row :param row_idx: which row :return: a list of feature values, ordered by column_names """ try: row = self._rows[row_idx] except TypeError: row = self._rows[self._row_name_id...
get a feature vector for the nth row :param row_idx: which row :return: a list of feature values, ordered by column_names
def clone(self, snapshot_name_or_id=None, mode=library.CloneMode.machine_state, options=None, name=None, uuid=None, groups=None, basefolder='', register=True): """Clone this Machine Options: snapshot_name_or_id - value can be either ISnapshot, name,...
Clone this Machine Options: snapshot_name_or_id - value can be either ISnapshot, name, or id mode - set the CloneMode value options - define the CloneOptions options name - define a name of the new VM uuid - set the uuid of the new VM grou...
def acquire_reader(self): """ Acquire a read lock, several threads can hold this type of lock. """ with self.mutex: while self.rwlock < 0 or self.rwlock == self.max_reader_concurrency or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1
Acquire a read lock, several threads can hold this type of lock.
def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): """Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the com...
Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) ...
def update_insight(self, project_key, insight_id, **kwargs): """Update an insight. **Note that only elements included in the request will be updated. All omitted elements will remain untouched. :param project_key: Projrct identifier, in the form of projectOwner/projectid ...
Update an insight. **Note that only elements included in the request will be updated. All omitted elements will remain untouched. :param project_key: Projrct identifier, in the form of projectOwner/projectid :type project_key: str :param insight_id: Insight unique identi...
def safe_listget(list_, index, default='?'): """ depricate """ if index >= len(list_): return default ret = list_[index] if ret is None: return default return ret
depricate
def walk_json_dict(coll): """ Flatten a parsed SBP object into a dicts and lists, which are compatible for JSON output. Parameters ---------- coll : dict """ if isinstance(coll, dict): return dict((k, walk_json_dict(v)) for (k, v) in iter(coll.items())) elif isinstance(coll, bytes): return c...
Flatten a parsed SBP object into a dicts and lists, which are compatible for JSON output. Parameters ---------- coll : dict
def setup_environment_from_config_file(): """ Imports the environmental configuration settings from the config file, if present, and sets the environment variables to test it. """ from os.path import exists config_file = get_config_file() if not exists(config_file): return ...
Imports the environmental configuration settings from the config file, if present, and sets the environment variables to test it.
def to_line(self): """ Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ if self.valid: return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(), ...
Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included.
def imf(m): ''' Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorization available via vimf() ''' m1 = 0.08; m2 = 0.50 a1 = 0.30; a2 = 1.30; a3 = 2.3 const2 = m1**-a1 -m1**-a2 const3 = m2**-a2 -m2**-a3 if m < 0.08: alpha = 0.3 ...
Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorization available via vimf()
def _get_assumptions(t): """ Given a constraint, _get_assumptions() returns a set of constraints that are implicitly assumed to be true. For example, `x <= 10` would return `x >= 0`. """ if t.op in ('__le__', '__lt__', 'ULE', 'ULT'): return [ t.args[0] >= 0 ] ...
Given a constraint, _get_assumptions() returns a set of constraints that are implicitly assumed to be true. For example, `x <= 10` would return `x >= 0`.
def on_msg(self, callback, remove=False): """(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool ...
(Un)Register a custom msg receive callback. Parameters ---------- callback: callable callback will be passed three arguments when a message arrives:: callback(widget, content, buffers) remove: bool True if the callback should be unregistered.
def find_kernel_specs_for_envs(self): """Returns a dict mapping kernel names to resource directories.""" data = self._get_env_data() return {name: data[name][0] for name in data}
Returns a dict mapping kernel names to resource directories.
def check_elasticsearch(record, *args, **kwargs): """Return permission that check if the record exists in ES index. :params record: A record object. :returns: A object instance with a ``can()`` method. """ def can(self): """Try to search for given record.""" search = request._method...
Return permission that check if the record exists in ES index. :params record: A record object. :returns: A object instance with a ``can()`` method.
def encode (self, s): """Encode string with output encoding.""" assert isinstance(s, unicode) return s.encode(self.output_encoding, self.codec_errors)
Encode string with output encoding.
def bulk_lookup_rdap(addresses=None, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, rate_limit_timeout=60, socket_timeout=10, asn_timeout=240, proxy_openers=None): """ The function for bulk retrieving and parsing whois information for a list of IP ad...
The function for bulk retrieving and parsing whois information for a list of IP addresses via HTTP (RDAP). This bulk lookup method uses bulk ASN Whois lookups first to retrieve the ASN for each IP. It then optimizes RDAP queries to achieve the fastest overall time, accounting for rate-limiting RIRs. ...