code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def run(self, cmd): """Similar to profile.Profile.run .""" import __main__ dict = __main__.__dict__ return self.runctx(cmd, dict, dict)
Similar to profile.Profile.run .
def verify(verified_entity, verification_key): """ Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return: """ verification = get_object_or_none(Verification, verified_entity=verified_entity) if verification is ...
Метод должен райзить ошибки :param verified_entity: сущность :param verification_key: ключ :return:
def jenkins(self): """Generate jenkins job details.""" job_name = self.format['jenkins_job_name'].format(**self.data) job = {'name': job_name} return job
Generate jenkins job details.
def base64_decode(nb): """Restore all bytes objects in the notebook from base64-encoded strings. Note: This is never used """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == 'code': for output in cell.outputs: if 'png' in o...
Restore all bytes objects in the notebook from base64-encoded strings. Note: This is never used
def set_weights(self, new_weights): """Sets the weights to new_weights. Note: Can set subsets of variables as well, by only passing in the variables you want to be set. Args: new_weights (Dict): Dictionary mapping variable names to their weig...
Sets the weights to new_weights. Note: Can set subsets of variables as well, by only passing in the variables you want to be set. Args: new_weights (Dict): Dictionary mapping variable names to their weights.
def handle_data_sending(self, source_file, source_len, info_cb=DEFAULT_MESSAGE_CALLBACK, progress_callback=None, timeout_ms=None): """Handles the protocol for sending data to the device. Arguments: source_file: File-object to read from for the device. ...
Handles the protocol for sending data to the device. Arguments: source_file: File-object to read from for the device. source_len: Amount of data, in bytes, to send to the device. info_cb: Optional callback for text sent from the bootloader. progress_callback: Callback that takes the current...
def save(self, block_id, consensus_hash, ops_hash, accepted_ops, virtualchain_ops_hints, backup=False): """ Write out all state to the working directory. Calls the implementation's 'db_save' method to store any state for this block. Calls the implementation's 'db_continue' method at the ...
Write out all state to the working directory. Calls the implementation's 'db_save' method to store any state for this block. Calls the implementation's 'db_continue' method at the very end, to signal to the implementation that all virtualchain state has been saved. This method can retur...
def initialize_aggregate_metric(section, aggr_hosts, aggr_metrics, metrics, outdir_default, resource_path, label, ts_start, ts_end, rule_strings, important_sub_metrics, anomaly_detection_metrics, other_options): """ Initialize aggregate metric :param: section: config section name ...
Initialize aggregate metric :param: section: config section name :param: aggr_hosts: list of hostnames to aggregate :param: aggr_metrics: list of metrics to aggregate :param: metrics: list of metric objects associated with the current naarad analysis :param: outdir_default: report location :param: resource_...
def Laliberte_heat_capacity_i(T, w_w, a1, a2, a3, a4, a5, a6): r'''Calculate the heat capacity of a solute using the form proposed by [1]_ Parameters are needed, and a temperature, and water fraction. .. math:: Cp_i = a_1 e^\alpha + a_5(1-w_w)^{a_6} \alpha = a_2 t + a_3 \exp(0.01t) + a_4(1-...
r'''Calculate the heat capacity of a solute using the form proposed by [1]_ Parameters are needed, and a temperature, and water fraction. .. math:: Cp_i = a_1 e^\alpha + a_5(1-w_w)^{a_6} \alpha = a_2 t + a_3 \exp(0.01t) + a_4(1-w_w) Parameters ---------- T : float Temperatu...
def register_plugin(self): """Register plugin in Spyder's main window""" self.main.add_dockwidget(self) self.findinfiles.result_browser.sig_edit_goto.connect( self.main.editor.load) self.findinfiles.find_options.redirect_stdio...
Register plugin in Spyder's main window
def import_image(image_path, os_version): """ Import the specific image. Input parameters: :image_path: Image file name :os_version: Operation System version. e.g. rhel7.4 """ image_name = os.path.basename(image_path) print("\nChecking if image %s exists ..." % image_name) image_...
Import the specific image. Input parameters: :image_path: Image file name :os_version: Operation System version. e.g. rhel7.4
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current ind...
def sent_tokenize(context): """ Cut the given context into sentences. Avoid a linebreak in between paried symbols, float numbers, and some abbrs. Nothing will be discard after sent_tokeinze, simply ''.join(sents) will get the original context. Evey whitespace, tab, linebreak will be kept. >>> c...
Cut the given context into sentences. Avoid a linebreak in between paried symbols, float numbers, and some abbrs. Nothing will be discard after sent_tokeinze, simply ''.join(sents) will get the original context. Evey whitespace, tab, linebreak will be kept. >>> context = "I love you. Please don't leave...
def convertSeqOntology(self, seqOntStr): """ Splits a string of sequence ontology effects and creates an ontology term record for each, which are built into an array of return soTerms. :param seqOntStr: :return: [protocol.OntologyTerm] """ return [ ...
Splits a string of sequence ontology effects and creates an ontology term record for each, which are built into an array of return soTerms. :param seqOntStr: :return: [protocol.OntologyTerm]
def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm, bytes): realm = realm.encode('ascii') self.start_response(401, [(b'WWW-Authenticate', b'Basic realm="' + realm + b'"')]) ...
Return 401 for authentication failure. This will end the handler.
def _algebraic_data(metaclass): """A class decorator to pull out `_list_fields` from a mixin class for use with a `datatype`.""" def wrapper(cls): cls.__bases__ += (metaclass,) cls._list_fields = metaclass._list_fields return cls return wrapper
A class decorator to pull out `_list_fields` from a mixin class for use with a `datatype`.
def contour(self, level): """Get contour lines at the given level. Parameters ---------- level : numbers.Number The data level to calculate the contour lines for. Returns ------- : The result of the :attr:`formatter` called on the contour...
Get contour lines at the given level. Parameters ---------- level : numbers.Number The data level to calculate the contour lines for. Returns ------- : The result of the :attr:`formatter` called on the contour at the given `level`.
def alter_add_column(self, table, column_name, field, **kwargs): """Fix fieldname for ForeignKeys.""" name = field.name op = super(SchemaMigrator, self).alter_add_column(table, column_name, field, **kwargs) if isinstance(field, pw.ForeignKeyField): field.name = name r...
Fix fieldname for ForeignKeys.
def check_data(self, ds, name, dims): """ A validation method for the data shape Parameters ---------- name: list of lists of strings The variable names (see the :meth:`~psyplot.plotter.Plotter.check_data` method of the :attr:`plotter_cls` att...
A validation method for the data shape Parameters ---------- name: list of lists of strings The variable names (see the :meth:`~psyplot.plotter.Plotter.check_data` method of the :attr:`plotter_cls` attribute for details) dims: list of dictionaries ...
def usergroup_delete(usergroupids, **kwargs): ''' .. versionadded:: 2016.3.0 :param usergroupids: IDs of the user groups to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (ca...
.. versionadded:: 2016.3.0 :param usergroupids: IDs of the user groups to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) ...
def _loadKSubcatRelations( inputFile ): ''' Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid. Iga muster peab olema failis eraldi real, kujul: (sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp) nt ees;_K_;post;g eest;_K_;post;g enn...
Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid. Iga muster peab olema failis eraldi real, kujul: (sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp) nt ees;_K_;post;g eest;_K_;post;g enne;_K_;pre;p Tagastab laetud andmed sõnas...
def resize_pane(pymux, variables): """ Resize/zoom the active pane. """ try: left = int(variables['<left>'] or 0) right = int(variables['<right>'] or 0) up = int(variables['<up>'] or 0) down = int(variables['<down>'] or 0) except ValueError: raise CommandExcep...
Resize/zoom the active pane.
def get_l2vpnfs_table(self): """Returns global L2VPN Flow Specification table. Creates the table if it does not exist. """ l2vpnfs_table = self._global_tables.get(RF_L2VPN_FLOWSPEC) # Lazy initialization of the table. if not l2vpnfs_table: l2vpnfs_table = L2V...
Returns global L2VPN Flow Specification table. Creates the table if it does not exist.
def create(self): """Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties. """ if self.bt_table.exists(): utils.dbg('Table already exists') return max_versions_rule = bigtable_column_fa...
Create the table underlying the queue. Create the 'metadata' and 'tfexample' column families and their properties.
def temporary_directory(): """ make a temporary directory, yeild its name, cleanup on exit """ dir_name = tempfile.mkdtemp() yield dir_name if os.path.exists(dir_name): shutil.rmtree(dir_name)
make a temporary directory, yeild its name, cleanup on exit
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_n...
Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet.
def getUpdates(self): """ Get the latest new or updated events from Event Registry NOTE: call this method exactly once per minute - calling it more frequently will return the same results multiple times, calling it less frequently will miss on some results. Results are computed once a mi...
Get the latest new or updated events from Event Registry NOTE: call this method exactly once per minute - calling it more frequently will return the same results multiple times, calling it less frequently will miss on some results. Results are computed once a minute.
def _lastColumn(self, block): """Returns the last non-whitespace column in the given line. If there are only whitespaces in the line, the return value is -1. """ text = block.text() index = len(block.text()) - 1 while index >= 0 and \ (text[index].isspace() ...
Returns the last non-whitespace column in the given line. If there are only whitespaces in the line, the return value is -1.
def from_file(cls, filename, beam=None): """ Create a new WCSHelper class from a given fits file. Parameters ---------- filename : string The file to be read beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplie...
Create a new WCSHelper class from a given fits file. Parameters ---------- filename : string The file to be read beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is None then one is constructed form the header. ...
def set_sensitivity(self, sensitivity=DEFAULT_SENSITIVITY): """Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69. """ if sensitivity < 31: self._mtreg = 31 elif sensitivity > 254: self._mtreg = 254 else: ...
Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69.
def get_command(self, ctx, cmd_name): """ Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found. :param ctx: Click context :param cmd_name: Top-level command name :return: Click object representing the command """ ...
Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found. :param ctx: Click context :param cmd_name: Top-level command name :return: Click object representing the command
def get_group_result(self, grp, **kwargs): """ Retrieve the results for a group. Needs this to already be calculated - errors out if result not available. """ id_ = self.get_id(grp) self.cache[grp] = id_ # Check if this file is already processed alignment...
Retrieve the results for a group. Needs this to already be calculated - errors out if result not available.
def disconnect(self, container, *args, **kwargs): """ Disconnect a container from this network. Args: container (str): Container to disconnect from this network, as either an ID, name, or :py:class:`~docker.models.containers.Container` object. ...
Disconnect a container from this network. Args: container (str): Container to disconnect from this network, as either an ID, name, or :py:class:`~docker.models.containers.Container` object. force (bool): Force the container to disconnect from a network. ...
def fit(self, linear_predictor, event, time): """Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contain...
Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, sh...
def get_jpp_env(jpp_dir): """Return the environment dict of a loaded Jpp env. The returned env can be passed to `subprocess.Popen("J...", env=env)` to execute Jpp commands. """ env = { v[0]: ''.join(v[1:]) for v in [ l.split('=') for l in os.popen( "sour...
Return the environment dict of a loaded Jpp env. The returned env can be passed to `subprocess.Popen("J...", env=env)` to execute Jpp commands.
def loads(s, parser_params=JSONParserParams(), object_builder_params=PythonObjectBuilderParams()): """ Loads a json string as a python object hierarchy just like the standard json.loads(). Unlike the standard json.loads() this function uses OrderedDict instances to represent json objects...
Loads a json string as a python object hierarchy just like the standard json.loads(). Unlike the standard json.loads() this function uses OrderedDict instances to represent json objects but the class of the dictionary to be used is configurable. :param s: The json string to load. :params parser_params: ...
def begin(self): """Start transaction Wait to get connection and returns `Transaction` object. :return: Future[Transaction] :rtype: Future """ conn = yield self._get_conn() try: yield conn.begin() except: self._close_conn(conn) ...
Start transaction Wait to get connection and returns `Transaction` object. :return: Future[Transaction] :rtype: Future
def pad_batch(features, batch_multiple): """Pad batch dim of features to nearest multiple of batch_multiple.""" feature = list(features.items())[0][1] batch_size = tf.shape(feature)[0] mod = batch_size % batch_multiple has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32) batch_padding = batch_multiple * has_m...
Pad batch dim of features to nearest multiple of batch_multiple.
def on_retry(self, exc, task_id, args, kwargs, einfo): """ Capture the exception that caused the task to be retried, if any. """ super(LoggedTask, self).on_retry(exc, task_id, args, kwargs, einfo) log.warning('[{}] retried due to {}'.format(task_id, getattr(einfo, 'traceback', No...
Capture the exception that caused the task to be retried, if any.
def resume(name, call=None, session=None): ''' Resume a vm from disk .. code-block:: bash salt-cloud -a resume xenvm01 ''' if call == 'function': raise SaltCloudException( 'The show_instnce function must be called with -a or --action.' ) if session is None:...
Resume a vm from disk .. code-block:: bash salt-cloud -a resume xenvm01
def initialize(g, app): """ If postgresql url is defined in configuration params a scoped session will be created """ if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']: # Database connection established for console commands for k, v in app.config['DATABASES']['...
If postgresql url is defined in configuration params a scoped session will be created
def perform_checks(template, do_redirect=False, context=None, next=None, quiet=False): '''return all checks for required variables before returning to desired view Parameters ========== template: the html temp...
return all checks for required variables before returning to desired view Parameters ========== template: the html template to render do_redirect: if True, perform a redirect and not render context: dictionary of context variables to pass to render_template next: a pre...
def file_follow_durable( path, min_dump_interval=10, xattr_name='user.collectd.logtail.pos', xattr_update=True, **follow_kwz ): '''Records log position into xattrs after reading line every min_dump_interval seconds. Checksum of the last line at the position is also recorded (so line itself don't have to ...
Records log position into xattrs after reading line every min_dump_interval seconds. Checksum of the last line at the position is also recorded (so line itself don't have to fit into xattr) to make sure file wasn't truncated between last xattr dump and re-open.
def hyphen_range(string): ''' Expands a string of numbers separated by commas and hyphens into a list of integers. For example: 2-3,5-7,20-21,23,100-200 ''' list_numbers = list() temporary_list = string.split(',') for element in temporary_list: sub_element = element.split('-') ...
Expands a string of numbers separated by commas and hyphens into a list of integers. For example: 2-3,5-7,20-21,23,100-200
def indexesof(coll, item): """Return all the indexes of the item in the collection :param coll: the collection :param item: a value :returns: a list of indexes >>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael'] >>> indexesof(monties, 'Terry') [2, 3] """ return [...
Return all the indexes of the item in the collection :param coll: the collection :param item: a value :returns: a list of indexes >>> monties = ['Eric', 'John', 'Terry', 'Terry', 'Graham', 'Mickael'] >>> indexesof(monties, 'Terry') [2, 3]
def _determine_base_url(document, page_url): """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the ...
Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :p...
def get_stops_in_polygon( feed: "Feed", polygon: Polygon, geo_stops=None ) -> DataFrame: """ Return the slice of ``feed.stops`` that contains all stops that lie within the given Shapely Polygon object that is specified in WGS84 coordinates. Parameters ---------- feed : Feed polygon ...
Return the slice of ``feed.stops`` that contains all stops that lie within the given Shapely Polygon object that is specified in WGS84 coordinates. Parameters ---------- feed : Feed polygon : Shapely Polygon Specified in WGS84 coordinates geo_stops : Geopandas GeoDataFrame A...
def _pack(self, content): """pack the content using serializer and compressor""" if self.serializer: content = self.serializer.serialize(content) if self.compressor: content = self.compressor.compress(content) return content
pack the content using serializer and compressor
def import_locations(self, gpsdata_file, checksum=True): r"""Import GPS NMEA-formatted data files. ``import_locations()`` returns a list of `Fix` objects representing the fix sentences found in the GPS data. It expects data files in NMEA 0183 format, as specified in `the offici...
r"""Import GPS NMEA-formatted data files. ``import_locations()`` returns a list of `Fix` objects representing the fix sentences found in the GPS data. It expects data files in NMEA 0183 format, as specified in `the official documentation`_, which is ASCII text such as:: $G...
def interruptible_sleep(t, event=None): """ Sleeps for a specified duration, optionally stopping early for event. Returns True if interrupted """ log.info("sleeping %s", t) if event is None: time.sleep(t) return False else: return not event.wait(t)
Sleeps for a specified duration, optionally stopping early for event. Returns True if interrupted
def getAdaptiveSVDDims(self, singularValues, fractionOfMax=0.001): """ Compute the number of eigenvectors (singularValues) to keep. :param singularValues: :param fractionOfMax: :return: """ v = singularValues/singularValues[0] idx = numpy.where(v<fractionOfMax)[0] if len(idx): ...
Compute the number of eigenvectors (singularValues) to keep. :param singularValues: :param fractionOfMax: :return:
def _getSmallestDifference(inputList, targetVal): ''' Returns the value in inputList that is closest to targetVal Iteratively splits the dataset in two, so it should be pretty fast ''' targetList = inputList[:] retVal = None while True: # If we're down to one value, stop iterati...
Returns the value in inputList that is closest to targetVal Iteratively splits the dataset in two, so it should be pretty fast
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
convert to datetime to UTC offset.
def _like_pattern(start, end, anywhere, index, length): """ Create a LIKE pattern to use as a search parameter for a WHERE clause. :param start: Value to be found at the start :param end: Value to be found at the end :param anywhere: Value to be found anywhere :param ind...
Create a LIKE pattern to use as a search parameter for a WHERE clause. :param start: Value to be found at the start :param end: Value to be found at the end :param anywhere: Value to be found anywhere :param index: Value to be found at a certain index :param length: Minimum char...
def iter_statuses(self, sha, number=-1, etag=None): """Iterates over the statuses for a specific SHA. :param str sha: SHA of the commit to list the statuses of :param int number: (optional), return up to number statuses. Default: -1 returns all available statuses. :param str...
Iterates over the statuses for a specific SHA. :param str sha: SHA of the commit to list the statuses of :param int number: (optional), return up to number statuses. Default: -1 returns all available statuses. :param str etag: (optional), ETag from a previous request to the same ...
def get_req(url): """simple get request""" request = urllib.request.Request(url) request.add_header('Authorization', 'token %s' % API_TOKEN) try: response = urllib.request.urlopen(request).read().decode('utf-8') return response except urllib.error.HTTPError: exception() ...
simple get request
def BooleanField(default=NOTHING, required=True, repr=True, cmp=True, key=None): """ Create new bool field on a model. :param default: any boolean value :param bool required: whether or not the object is invalid if not provided. :param bool repr: include this field should appear in...
Create new bool field on a model. :param default: any boolean value :param bool required: whether or not the object is invalid if not provided. :param bool repr: include this field should appear in object's repr. :param bool cmp: include this field in generated comparison. :param string key: overri...
def get_cond_latents(all_latents=None, hparams=None): """Get z^{cond}_{t} given z^{1..t-1}. Args: all_latents: list of list of tensors, outer-size equals no.of time_steps-1 inner-size equals hparams.n_levels. hparams: See next_frame_glow_hparams. Returns: cond_latent...
Get z^{cond}_{t} given z^{1..t-1}. Args: all_latents: list of list of tensors, outer-size equals no.of time_steps-1 inner-size equals hparams.n_levels. hparams: See next_frame_glow_hparams. Returns: cond_latents: conditional latents at time-step t.
def winter_rain_ratio(pr, prsn=None, tas=None): """Ratio of rainfall to total precipitation during winter The ratio of total liquid precipitation over the total precipitation over the winter months (DJF. If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below...
Ratio of rainfall to total precipitation during winter The ratio of total liquid precipitation over the total precipitation over the winter months (DJF. If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below 0°C. Parameters ---------- pr : xarray.Da...
def overlaps_point(self, p): """ Returns whether some interval in the tree overlaps p. Completes in O(log n) time. :rtype: bool """ if self.is_empty(): return False return bool(self.top_node.contains_point(p))
Returns whether some interval in the tree overlaps p. Completes in O(log n) time. :rtype: bool
def means_samples(self): r""" Samples of the Gaussian distribution means """ res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype) for i in range(self.nsamples): for j in range(self.nstates): res[i, j, :] = self._sampled_hmms[i].means[j] ...
r""" Samples of the Gaussian distribution means
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
Denormalize a list of bounding boxes.
def setgitlabciservice(self, project_id, token, project_url): """ Set GitLab CI service for project :param project_id: project id :param token: CI project token :param project_url: CI project url :return: true if success, false if not """ data = {'token':...
Set GitLab CI service for project :param project_id: project id :param token: CI project token :param project_url: CI project url :return: true if success, false if not
def identify_marker_genes_ratio(self, labels=None): """ Ranks marker genes for each cluster using a SAM-weighted expression-ratio approach (works quite well). Parameters ---------- labels - numpy.array or str, optional, default None Cluster labels to use fo...
Ranks marker genes for each cluster using a SAM-weighted expression-ratio approach (works quite well). Parameters ---------- labels - numpy.array or str, optional, default None Cluster labels to use for marker gene identification. If None, assumes that one of S...
def _check_command_response(response, msg=None, allowable_errors=None, parse_write_concern_error=False): """Check the response to a command for errors. """ if "ok" not in response: # Server didn't recognize our message as a command. raise OperationFailure(response...
Check the response to a command for errors.
def tuple_sealer(fields, defaults): """ This sealer returns an equivalent of a ``namedtuple``. """ baseclass_name = 'FieldsBase_for__{0}'.format('__'.join(fields)) global_namespace, local_namespace = make_init_func( fields, defaults, baseclass_name, header_name='__new__', hea...
This sealer returns an equivalent of a ``namedtuple``.
def get_authorization_form_for_create_for_agent(self, agent_id, function_id, qualifier_id, authorization_record_types): """Gets the authorization form for creating new authorizations. A new form should be requested for each create transaction. arg: agent_id (osid.id.Id): the agent ``Id`` ...
Gets the authorization form for creating new authorizations. A new form should be requested for each create transaction. arg: agent_id (osid.id.Id): the agent ``Id`` arg: function_id (osid.id.Id): the function ``Id`` arg: qualifier_id (osid.id.Id): the qualifier ``Id`` ...
def im_messages_others(self, room_id, **kwargs): """Retrieves the messages from any direct message in the server""" return self.__call_api_get('im.messages.others', roomId=room_id, kwargs=kwargs)
Retrieves the messages from any direct message in the server
def last_modified_time(path): """ Get the last modified time of path as a Timestamp. """ return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')
Get the last modified time of path as a Timestamp.
def _parse(self, init_info): """Initialize a FCP device object from several lines of string describing properties of the FCP device. Here is a sample: opnstk1: FCP device number: B83D opnstk1: Status: Free opnstk1: NPIV world wide port numbe...
Initialize a FCP device object from several lines of string describing properties of the FCP device. Here is a sample: opnstk1: FCP device number: B83D opnstk1: Status: Free opnstk1: NPIV world wide port number: NONE opnstk1: Channe...
def _cleanup(): ''' Make sure that any terminal processes still running when __del__ was called to the waited and cleaned up. ''' for inst in _ACTIVE[:]: res = inst.isalive() if res is not True: try: _ACTIVE.remove(inst) except ValueError: ...
Make sure that any terminal processes still running when __del__ was called to the waited and cleaned up.
def filter(self, info, releases): """ Remove files from `releases` that match any pattern. """ # Make a copy of releases keys # as we may delete packages during iteration removed = 0 versions = list(releases.keys()) for version in versions: ne...
Remove files from `releases` that match any pattern.
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") ...
Parse leaf-list value or list keys.
def _from_yaml_v0(cls, job): """Populate a JobDescriptor from the local provider's original meta.yaml. The local job provider had the first incarnation of a YAML file for each task. That idea was extended here in the JobDescriptor and the local provider adopted the JobDescriptor.to_yaml() call to write...
Populate a JobDescriptor from the local provider's original meta.yaml. The local job provider had the first incarnation of a YAML file for each task. That idea was extended here in the JobDescriptor and the local provider adopted the JobDescriptor.to_yaml() call to write its meta.yaml. The JobDescript...
def get_human_readable_time(time_ms): """ Convert given duration in milliseconds into a human-readable representation, i.e. hours, minutes, seconds, etc. More specifically, the returned string may look like following: 1 day 3 hours 12 mins 3 days 0 hours 0 mins 8 hours 12 mins ...
Convert given duration in milliseconds into a human-readable representation, i.e. hours, minutes, seconds, etc. More specifically, the returned string may look like following: 1 day 3 hours 12 mins 3 days 0 hours 0 mins 8 hours 12 mins 34 mins 02 secs 13 secs 541 ms ...
def AgregarFardo(self, cod_trazabilidad, clase_tabaco, peso, **kwargs): "Agrego un fardo al último romaneo agregado a la liq." fardo = dict(codTrazabilidad=cod_trazabilidad, claseTabaco=clase_tabaco, peso=peso) self.solicitud['romaneo'][-1]['fardo'].append(fardo) return True
Agrego un fardo al último romaneo agregado a la liq.
def _fetch_cdn_data(self): """Fetches the container's CDN data from the CDN service""" if self._cdn_enabled is FAULT: headers = self.manager.fetch_cdn_data(self) else: headers = {} # Set defaults in case not all headers are present. self._set_cdn_defaults(...
Fetches the container's CDN data from the CDN service
def find_upstream_changed(self, kind): """ Return list of files that have been changed upstream belonging to a particular kind of change """ output = subprocess.check_output([ 'git', 'log', '{}..origin/{}'.format(self.branch_name, self.branch_name), '--oneline', '...
Return list of files that have been changed upstream belonging to a particular kind of change
def legacy_write(self, request_id, msg, max_doc_size, acknowledged, docs): """A proxy for SocketInfo.legacy_write that handles event publishing. """ if self.publish: duration = datetime.datetime.now() - self.start_time cmd = self._start(request_id, docs) start...
A proxy for SocketInfo.legacy_write that handles event publishing.
def atleast_nd(n, u): """ If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int Minimum number of required dimensio...
If the input array has fewer than n dimensions, append singleton dimensions so that it is n dimensional. Note that the interface differs substantially from that of :func:`numpy.atleast_3d` etc. Parameters ---------- n : int Minimum number of required dimensions u : array_like Input ...
def tk(self, k, x): """ Evaluates an individual Chebyshev polynomial `k` in coordinate space with proper transformation given the window """ weights = np.diag(np.ones(k+1))[k] return np.polynomial.chebyshev.chebval(self._x2c(x), weights)
Evaluates an individual Chebyshev polynomial `k` in coordinate space with proper transformation given the window
def genargs() -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser() parser.add_argument("spec", help="JSG specification - can be file name, URI or string") parser.add_argument("-o", "--outfile", help="Output python file - if omitted, python is not...
Create a command line parser :return: parser
def DBSCAN(data, minPts, eps = None, quantile = 50, subsamples_matrix = None, samples_weights = None, metric = 'minkowski', p = 2, verbose = True): """Performs Density-Based Spatial Clustering of Applications with Noise, possibly on various subsamples or combinations of data-points extracted from the whole...
Performs Density-Based Spatial Clustering of Applications with Noise, possibly on various subsamples or combinations of data-points extracted from the whole dataset, 'data'. If the radius 'eps' is not provided by the user, it will be determined in an adaptive, data-dependent way by a c...
def output_stream(plugin, stream): """Open stream, create output and finally write the stream to output.""" global output success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True break e...
Open stream, create output and finally write the stream to output.
def privateparts(self, domain): """ Return tuple of labels and the private suffix. """ s = self.privatesuffix(domain) if s is None: return None else: # I know the domain is valid and ends with private suffix pre = domain[0:-(len(s)+1)] if p...
Return tuple of labels and the private suffix.
def set_attribute(self, aid, attrib, val, idx='*'): """ Set the value of an xml attribute marked with the matching aid attribute. """ if aid in self.__attrib_ids: elems = self.__attrib_ids[aid] if idx == '*': for elem in elems: ...
Set the value of an xml attribute marked with the matching aid attribute.
def from_table(self, table=None, fields='*', schema=None, **kwargs): """ Adds a ``Table`` and any optional fields to the list of tables this query is selecting from. :type table: str or dict or :class:`Table <querybuilder.tables.Table>` or :class:`Query <querybuilder.query.Q...
Adds a ``Table`` and any optional fields to the list of tables this query is selecting from. :type table: str or dict or :class:`Table <querybuilder.tables.Table>` or :class:`Query <querybuilder.query.Query>` or :class:`ModelBase <django:django.db.models.base.ModelBase>` ...
def cmd(self, value): """Command setter.""" self.bytearray[self._get_slicers(0)] = bytearray(c_uint8(value or 0))
Command setter.
def add_missing_particles(st, rad='calc', tries=50, **kwargs): """ Attempts to add missing particles to the state. Operates by: (1) featuring the difference image using feature_guess, (2) attempting to add the featured positions using check_add_particles. Parameters ---------- st : :cl...
Attempts to add missing particles to the state. Operates by: (1) featuring the difference image using feature_guess, (2) attempting to add the featured positions using check_add_particles. Parameters ---------- st : :class:`peri.states.State` The state to check adding particles to. ...
def unexpo(intpart, fraction, expo): """Remove the exponent by changing intpart and fraction.""" if expo > 0: # Move the point left f = len(fraction) intpart, fraction = intpart + fraction[:expo], fraction[expo:] if expo > f: intpart = intpart + '0'*(expo-f) elif expo < 0...
Remove the exponent by changing intpart and fraction.
def main(argv): """ Main program. @return: none """ global g_log_base_dir global g_airline_java global g_milsongs_java global g_airline_python global g_milsongs_python if len(argv) < 2: print "python grabGLRMrunLogs logsBaseDirectory\n" sys.exit(1) else: #...
Main program. @return: none
def __properties_update(self, properties): """ Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else ...
Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else False
def verify_param(self, param, must=[], r=None): '''return Code.ARGUMENT_MISSING if every key in must not found in param''' if APIKEY not in param: param[APIKEY] = self.apikey() r = Result() if r is None else r for p in must: if p not in param: r.c...
return Code.ARGUMENT_MISSING if every key in must not found in param
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding).
def edge_factory(**row_factory_kw): """ Give new edges a unique ID. """ if "__table_editor__" in row_factory_kw: table_editor = row_factory_kw["__table_editor__"] graph = table_editor.object ID = make_unique_name("node", [node.ID for node in graph.nodes]) n_nodes = len(graph.no...
Give new edges a unique ID.
def AddClientLabels(self, client_id, owner, labels, cursor=None): """Attaches a list of user labels to a client.""" cid = db_utils.ClientIDToInt(client_id) labels = set(labels) args = [(cid, mysql_utils.Hash(owner), owner, label) for label in labels] args = list(collection.Flatten(args)) query ...
Attaches a list of user labels to a client.
def files_type(fs0, fs1, files): """Inspects the file type of the given files.""" for file_meta in files['deleted_files']: file_meta['type'] = fs0.file(file_meta['path']) for file_meta in files['created_files'] + files['modified_files']: file_meta['type'] = fs1.file(file_meta['path']) r...
Inspects the file type of the given files.
def language(self, value=None): """No arguments: Get the document's language (ISO-639-3) from metadata Argument: Set the document's language (ISO-639-3) in metadata """ if not (value is None): if (self.metadatatype == "native"): self.metadata['language'] = ...
No arguments: Get the document's language (ISO-639-3) from metadata Argument: Set the document's language (ISO-639-3) in metadata
def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, bkg=True): """Orbit on the given path focusing on the focus point Parameters ---------- path : vtki.PolyData Path of orbital points. The order in the points is the order of travel focu...
Orbit on the given path focusing on the focus point Parameters ---------- path : vtki.PolyData Path of orbital points. The order in the points is the order of travel focus : list(float) of length 3, optional The point ot focus the camera. st...
def std_human_uid(kind=None): """Return a random generated human-friendly phrase as low-probability unique id""" kind_list = alphabet if kind == 'animal': kind_list = animals elif kind == 'place': kind_list = places name = "{color} {adjective} {kind} of {attribute}".format( ...
Return a random generated human-friendly phrase as low-probability unique id