code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_arg_param(self, param_name, layer_index, blob_index): """Add an arg param to .params file. Example: weights of a fully connected layer.""" self.add_param('arg:%s' % param_name, layer_index, blob_index)
Add an arg param to .params file. Example: weights of a fully connected layer.
def plot_prof_1(self, species, keystring, xlim1, xlim2, ylim1, ylim2, symbol=None, show=False): ''' Plot one species for cycle between xlim1 and xlim2 Only works with instances of se and mesa _profile. Parameters ---------- species : list ...
Plot one species for cycle between xlim1 and xlim2 Only works with instances of se and mesa _profile. Parameters ---------- species : list Which species to plot. keystring : string or integer Label that appears in the plot or in the case of se, a ...
def start(info): """Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port` """ c...
Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port`
def writefile(filename, content): """ writes the content into the file :param filename: the filename :param content: teh content :return: """ with open(path_expand(filename), 'w') as outfile: outfile.write(content)
writes the content into the file :param filename: the filename :param content: teh content :return:
def crypto_validator(func): """ This a decorator to be used for any method relying on the cryptography library. # noqa: E501 Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'. """ def func_in(*args, **kwargs): if not conf.crypto_valid: raise ImportError(...
This a decorator to be used for any method relying on the cryptography library. # noqa: E501 Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'.
def get_matrix(self): """Return a copy of the current transformation matrix (CTM).""" matrix = Matrix() cairo.cairo_get_matrix(self._pointer, matrix._pointer) self._check_status() return matrix
Return a copy of the current transformation matrix (CTM).
def set_config(self, **config): """Shadow all the current config.""" reinit = False if 'stdopt' in config: stdopt = config.pop('stdopt') reinit = (stdopt != self.stdopt) self.stdopt = stdopt if 'attachopt' in config: attachopt = config.pop(...
Shadow all the current config.
def active(self): """ Returns if task is active. """ if not os.path.isfile(self._paths['active_file']): return False return self._loaded
Returns if task is active.
def schema(self): """The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema` """ if not self.__schema: # Inherit context from parent. context = getattr(self.parent, 'context', {}) if isinstance(self.nested...
The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema`
def QA_fetch_get_option_50etf_contract_time_to_market(): ''' #🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series ''' result = QA_fetch_get_option_list('tdx') # pprint.pprint(result) # category market code name desc code ''' fix here : See the caveats in the documenta...
#🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series
def _resolve_file(file_name): """ Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None """ if not file_name: return None path = os.path....
Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None
def run_mutation_aggregator(job, mutation_results, univ_options): """ Aggregate all the called mutations. :param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome format :param dict univ_options: Dict of universal options used by almost all tools :r...
Aggregate all the called mutations. :param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome format :param dict univ_options: Dict of universal options used by almost all tools :returns: fsID for the merged mutations file :rtype: toil.fileStore.FileID
def _log(self, name, element): # pylint: disable=no-self-use """ Log Response and Tag elements. Do nothing if elements is none of them. """ from bs4 import BeautifulSoup, Tag if isinstance(element, Response): LOGGER.debug('%s response: URL=%s Code=%s', name, element....
Log Response and Tag elements. Do nothing if elements is none of them.
def compute_difficulty( bomb_delay: int, parent_header: BlockHeader, timestamp: int) -> int: """ https://github.com/ethereum/EIPs/issues/100 """ parent_timestamp = parent_header.timestamp validate_gt(timestamp, parent_timestamp, title="Header.timestamp") parent_difficult...
https://github.com/ethereum/EIPs/issues/100
def _tcpdump_callback(self, line, kill_switch): """Callback function to handle tcpdump""" line = line.lower() if ("listening" in line) or ("reading" in line): self.started = True if ("no suitable device" in line): self.error = True self.kill_switch() if "by kernel" in line: ...
Callback function to handle tcpdump
def write_stats_as_csv(gtfs, path_to_csv, re_write=False): """ Writes data from get_stats to csv file Parameters ---------- gtfs: GTFS path_to_csv: str filepath to the csv file to be generated re_write: insted of appending, create a new one. """ stats_dict = get_stat...
Writes data from get_stats to csv file Parameters ---------- gtfs: GTFS path_to_csv: str filepath to the csv file to be generated re_write: insted of appending, create a new one.
def unattach_rconfiguration(context, id, rconfiguration_id): """unattach_rconfiguration(context, id, rconfiguration_id): Unattach a rconfiguration from a remoteci. >>> dcictl remoteci-unattach-rconfiguration id [OPTIONS] :param string id: ID of the remoteci to unattach the rconfiguration from ...
unattach_rconfiguration(context, id, rconfiguration_id): Unattach a rconfiguration from a remoteci. >>> dcictl remoteci-unattach-rconfiguration id [OPTIONS] :param string id: ID of the remoteci to unattach the rconfiguration from [required] :param string rconfiguration_id: ID of...
def get_site_type_dummy_variables(self, sites): """ Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201). """ is_rock = np.array(sites.vs30 > self.NEHRP_BC_BOUNDARY) return is_rock
Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201).
def cast_to_seq_record(obj, alphabet=IUPAC.extended_protein, id="<unknown id>", name="<unknown name>", description="<unknown description>", dbxrefs=None, features=None, annotations=None, letter_annotations=None): """Return a SeqRecord representati...
Return a SeqRecord representation of a string or Seq object. Args: obj (str, Seq, SeqRecord): Sequence string or Biopython Seq object alphabet: See Biopython SeqRecord docs id: See Biopython SeqRecord docs name: See Biopython SeqRecord docs description: See Biopython SeqReco...
def _write_box_information(xml_file, structure, ref_distance): """Write box information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 R...
Write box information. Parameters ---------- xml_file : file object The file object of the hoomdxml file being written structure : parmed.Structure Parmed structure object ref_energy : float, default=1.0 Reference energy for conversion to reduced units
def sizeof(self, context=None) -> int: """ Return the size of the construct in bytes. :param context: Optional context dictionary. """ if context is None: context = Context() if not isinstance(context, Context): context = Context(context) ...
Return the size of the construct in bytes. :param context: Optional context dictionary.
def get_feature_flag_by_name(self, name, check_feature_exists=None): """GetFeatureFlagByName. [Preview API] Retrieve information on a single feature flag and its current states :param str name: The name of the feature to retrieve :param bool check_feature_exists: Check if feature exists ...
GetFeatureFlagByName. [Preview API] Retrieve information on a single feature flag and its current states :param str name: The name of the feature to retrieve :param bool check_feature_exists: Check if feature exists :rtype: :class:`<FeatureFlag> <azure.devops.v5_0.feature_availability.mo...
def _get_nws_feed(self): """get nws alert feed, and cache it""" url = '''http://alerts.weather.gov/cap/%s.php?x=0''' % (str(self._state).lower()) # pylint: disable=E1103 xml = requests.get(url).content return xml
get nws alert feed, and cache it
def push(self, metric_name=None, metric_value=None, volume=None): """ Ship that shit off to graphite broski """ graphite_path = self.path_prefix graphite_path += '.' + self.device + '.' + 'volume' graphite_path += '.' + volume + '.' + metric_name metric = Metric(graphit...
Ship that shit off to graphite broski
def _set_sip_ipv4_address(self, v, load=False): """ Setter method for sip_ipv4_address, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/sip_ipv4_address (sip-ipv4-address) If this variable is read-only (config: false) in the ...
Setter method for sip_ipv4_address, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/sip_ipv4_address (sip-ipv4-address) If this variable is read-only (config: false) in the source YANG file, then _set_sip_ipv4_address is considered ...
def _from_dict(cls, _dict): """Initialize a ToneCategory object from a json dictionary.""" args = {} if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) ] else: raise ValueError( ...
Initialize a ToneCategory object from a json dictionary.
def create_bookmark_action(parent, url, title, icon=None, shortcut=None): """Create bookmark action""" @Slot() def open_url(): return programs.start_file(url) return create_action( parent, title, shortcut=shortcut, icon=icon, triggered=open_url)
Create bookmark action
def min_volatility(self): """Get the minimum variance solution""" if not self.w: self.solve() var = [] for w in self.w: a = np.dot(np.dot(w.T, self.cov_matrix), w) var.append(a) # return min(var)**.5, self.w[var.index(min(var))] self.we...
Get the minimum variance solution
def readXML(self): """ Read XML. """ data = self.readLongString() root = xml.fromstring(data) self.context.addObject(root) return root
Read XML.
def load_modules(self, filepaths): """ Loads the modules from their `filepaths`. A filepath may be a directory filepath if there is an `__init__.py` file in the directory. If a filepath errors, the exception will be caught and logged in the logger. Returns a lis...
Loads the modules from their `filepaths`. A filepath may be a directory filepath if there is an `__init__.py` file in the directory. If a filepath errors, the exception will be caught and logged in the logger. Returns a list of modules.
def pretty_objname(self, obj=None, maxlen=50, color="boldcyan"): """ Pretty prints object name @obj: the object whose name you want to pretty print @maxlen: #int maximum length of an object name to print @color: your choice of :mod:colors or |None| -> #str prett...
Pretty prints object name @obj: the object whose name you want to pretty print @maxlen: #int maximum length of an object name to print @color: your choice of :mod:colors or |None| -> #str pretty object name .. from vital.debug import Look ...
def zonalstats(features, raster, all_touched, band, categorical, indent, info, nodata, prefix, stats, sequence, use_rs): '''zonalstats generates summary statistics of geospatial raster datasets based on vector features. The input arguments to zonalstats should be valid GeoJSON Features. (see...
zonalstats generates summary statistics of geospatial raster datasets based on vector features. The input arguments to zonalstats should be valid GeoJSON Features. (see cligj) The output GeoJSON will be mostly unchanged but have additional properties per feature describing the summary statistics (min,...
def ipop_range(self, start=0, stop=-1, callback=None, withscores=True): '''pop a range from the :class:`OrderedMixin`''' backend = self.backend res = backend.structure(self).ipop_range(start, stop, withscores=withscores) if not callba...
pop a range from the :class:`OrderedMixin`
def fromFile(cls, filepath): """ Creates a proxy instance from the inputted registry file. :param filepath | <str> :return <PluginProxy> || None """ xdata = ElementTree.parse(nstr(filepath)) xroot = xdata.getroot() # collect var...
Creates a proxy instance from the inputted registry file. :param filepath | <str> :return <PluginProxy> || None
def get_features(self, mapobject_type_name): '''Gets features for a given object type. Parameters ---------- mapobject_type_name: str type of the segmented objects Returns ------- List[Dict[str, str]] information about each feature ...
Gets features for a given object type. Parameters ---------- mapobject_type_name: str type of the segmented objects Returns ------- List[Dict[str, str]] information about each feature See also -------- :func:`tmserver.api...
def banlist(self, channel): """ Get the channel banlist. Required arguments: * channel - Channel of which to get the banlist for. """ with self.lock: self.is_in_channel(channel) self.send('MODE %s b' % channel) bans = [] w...
Get the channel banlist. Required arguments: * channel - Channel of which to get the banlist for.
def describe_event_source_mapping(UUID=None, EventSourceArn=None, FunctionName=None, region=None, key=None, keyid=None, profile=None): ''' Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings...
Given an event source mapping ID or an event source ARN and FunctionName, obtain the current settings of that mapping. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_event_source_mapping uuid
def get_grade_entry_form_for_update(self, grade_entry_id): """Gets the grade entry form for updating an existing entry. A new grade entry form should be requested for each update transaction. arg: grade_entry_id (osid.id.Id): the ``Id`` of the ``GradeEntry`` ...
Gets the grade entry form for updating an existing entry. A new grade entry form should be requested for each update transaction. arg: grade_entry_id (osid.id.Id): the ``Id`` of the ``GradeEntry`` return: (osid.grading.GradeEntryForm) - the grade entry form r...
def strainer(self): """ Determine whether it is required to run the MLST analyses """ # Initialise a variable to store whether the analyses need to be performed analyse = list() for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != 'NA'...
Determine whether it is required to run the MLST analyses
def wait_for_task_property(service, task, prop, timeout_sec=120): """Waits for a task to have the specified property""" return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec)
Waits for a task to have the specified property
def as_dict(self): """ Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object. """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__} ...
Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object.
def imagetransformer_ae_cifar(): """Hyperparameters for CIFAR-10 experiments.""" hparams = transformer_ae_small() hparams.filter_size = 512 hparams.num_compress_steps = 3 hparams.startup_steps = 10000 hparams.is_2d = 0 hparams.learning_rate_warmup_steps = 8000 hparams.learning_rate = 0.2 hparams.hidde...
Hyperparameters for CIFAR-10 experiments.
def clear_trash(cookie, tokens): '''清空回收站, 将里面的所有文件都删除.''' url = ''.join([ const.PAN_API_URL, 'recycle/clear?channel=chunlei&clienttype=0&web=1', '&t=', util.timestamp(), '&bdstoken=', tokens['bdstoken'], ]) # 使用POST方式发送命令, 但data为空. req = net.urlopen(url, headers={ ...
清空回收站, 将里面的所有文件都删除.
def _get_all_styles(self): """ return a dictionary of {(row, col) -> CellStyle} for all cells that use a non-default style. """ _styles = {} def _get_style(bold=False, bg_col=None, border=None): if (bold, bg_col, border) not in _styles: _styles...
return a dictionary of {(row, col) -> CellStyle} for all cells that use a non-default style.
def string_length(ctx, s=None): ''' Yields one number ''' if s is None: s = ctx.node elif callable(s): s = next(s.compute(ctx), '') yield len(s)
Yields one number
def get_message_definitions(self, msgid_or_symbol: str) -> list: """Returns the Message object for this message. :param str msgid_or_symbol: msgid_or_symbol may be either a numeric or symbolic id. :raises UnknownMessageError: if the message id is not defined. :rtype: List of MessageDefi...
Returns the Message object for this message. :param str msgid_or_symbol: msgid_or_symbol may be either a numeric or symbolic id. :raises UnknownMessageError: if the message id is not defined. :rtype: List of MessageDefinition :return: A message definition corresponding to msgid_or_symbo...
def ret(eqdata, **kwargs): """ Generate a DataFrame where the sole column, 'Return', is the return for the equity over the given number of sessions. For example, if 'XYZ' has 'Adj Close' of `100.0` on 2014-12-15 and `90.0` 4 *sessions* later on 2014-12-19, then the 'Return' value for 2014-...
Generate a DataFrame where the sole column, 'Return', is the return for the equity over the given number of sessions. For example, if 'XYZ' has 'Adj Close' of `100.0` on 2014-12-15 and `90.0` 4 *sessions* later on 2014-12-19, then the 'Return' value for 2014-12-19 will be `-0.1`. Parameters ...
def scaled_pressure_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. ...
The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute ...
def file_or_stderr(filename, *, mode="a", encoding="utf-8"): """Returns a context object wrapping either the given file or stderr (if filename is None). This makes dealing with log files more convenient. """ if filename is not None: return open(filename, mode, encoding=encoding) @conte...
Returns a context object wrapping either the given file or stderr (if filename is None). This makes dealing with log files more convenient.
def get_requirements(): """ Returns the content of 'requirements.txt' in a list. :return: The content of 'requirements.txt'. :rtype: list(str) """ requirements = [] with open( os.path.join(BASE_DIRECTORY, 'requirements.txt'), 'r', encoding='utf-8' ) as requireme...
Returns the content of 'requirements.txt' in a list. :return: The content of 'requirements.txt'. :rtype: list(str)
def validate(self, sources): """Validate the format of sources """ if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: logging.getLogger().warn...
Validate the format of sources
def _update_param(self): r"""Update parameters This method updates the values of the algorthm parameters with the methods provided """ # Update the gamma parameter. if not isinstance(self._gamma_update, type(None)): self._gamma = self._gamma_update(self._ga...
r"""Update parameters This method updates the values of the algorthm parameters with the methods provided
def _evaluate(self,x,y): ''' Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc). ''' if _isscalar(x): x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1) y_pos = max(m...
Returns the level of the interpolated function at each value in x,y. Only called internally by HARKinterpolator2D.__call__ (etc).
def map_forecast_estimate(self): """ get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values """ assert self.forecasts is not None ...
get the prior and posterior forecast (prediction) expectations. Returns ------- pandas.DataFrame : pandas.DataFrame dataframe with prior and posterior forecast expected values
def resources(ctx, gpu): """Get job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job -j 2 resources ``` For GPU resources \b ```bash $ polyaxon job -j 2 resources --gpu ``` """ user, project_name, _job = get_job...
Get job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job -j 2 resources ``` For GPU resources \b ```bash $ polyaxon job -j 2 resources --gpu ```
def cov(self, other, min_periods=None): """ Compute covariance with Series, excluding missing values. Parameters ---------- other : Series Series with which to compute the covariance. min_periods : int, optional Minimum number of observations need...
Compute covariance with Series, excluding missing values. Parameters ---------- other : Series Series with which to compute the covariance. min_periods : int, optional Minimum number of observations needed to have a valid result. Returns ------- ...
def string(prompt=None, empty=False): """Prompt a string. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a non-empty string. No...
Prompt a string. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a non-empty string. None if the user pressed only Enter and ``empty...
def getDependents(self, retracted=False): """ Returns a list of siblings who depend on us to calculate their result. :param retracted: If false, retracted/rejected dependents are dismissed :type retracted: bool :return: Analyses the current analysis depends on :rtype: lis...
Returns a list of siblings who depend on us to calculate their result. :param retracted: If false, retracted/rejected dependents are dismissed :type retracted: bool :return: Analyses the current analysis depends on :rtype: list of IAnalysis
def add_on_channel_close_callback(self): """ Tell pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ self._logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed)
Tell pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel.
def ra_indices_for_traj(self, traj): """ Gives the indices for a trajectory file index (without changing the order within the trajectory itself). :param traj: a trajectory file index :return: a Nx1 - np.array of the indices corresponding to the trajectory index """ assert...
Gives the indices for a trajectory file index (without changing the order within the trajectory itself). :param traj: a trajectory file index :return: a Nx1 - np.array of the indices corresponding to the trajectory index
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4...
Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5
def with_optimizer_tensor(self, tensor: Union[tf.Tensor, tf.Operation]) -> 'Optimization': """ Replace optimizer tensor. :param model: Tensorflow tensor. :return: Optimization instance self reference. """ self._optimizer_tensor = tensor return self
Replace optimizer tensor. :param model: Tensorflow tensor. :return: Optimization instance self reference.
def local_outgoing_hook(handler=None, coro=None): """add a callback to run every time a greenlet is switched away from :param handler: the callback function, must be a function taking 2 arguments: - an integer indicating whether it is being called as an incoming (1) hook or as an out...
add a callback to run every time a greenlet is switched away from :param handler: the callback function, must be a function taking 2 arguments: - an integer indicating whether it is being called as an incoming (1) hook or as an outgoing (2) hook (in this case it will always be 2). ...
def _mark_html_fields_as_safe(self, page): """ Mark the html content as safe so we don't have to use the safe template tag in all cms templates: """ page.title = mark_safe(page.title) page.content = mark_safe(page.content) return page
Mark the html content as safe so we don't have to use the safe template tag in all cms templates:
def marshal(self, v): """ Turn this value into API format. Do a reverse dictionary lookup on choices to find the original value. If there are no keys or too many keys for now we raise a NotImplementedError as marshal is not used anywhere currently. In the future we will want to ...
Turn this value into API format. Do a reverse dictionary lookup on choices to find the original value. If there are no keys or too many keys for now we raise a NotImplementedError as marshal is not used anywhere currently. In the future we will want to fail gracefully.
def format_table(table, column_names=None, column_specs=None, max_col_width=32, auto_col_width=False): """ Table pretty printer. Expects tables to be given as arrays of arrays:: print(format_table([[1, "2"], [3, "456"]], column_names=['A', 'B'])) """ orig_col_args = dict(column_names=column_nam...
Table pretty printer. Expects tables to be given as arrays of arrays:: print(format_table([[1, "2"], [3, "456"]], column_names=['A', 'B']))
def to_filelink(self): """ Checks is the status of the conversion is complete and, if so, converts to a Filelink *returns* [Filestack.Filelink] ```python filelink = av_convert.to_filelink() ``` """ if self.status != 'completed': return 'Audio...
Checks is the status of the conversion is complete and, if so, converts to a Filelink *returns* [Filestack.Filelink] ```python filelink = av_convert.to_filelink() ```
def add_command_hooks(commands, srcdir='.'): """ Look through setup_package.py modules for functions with names like ``pre_<command_name>_hook`` and ``post_<command_name>_hook`` where ``<command_name>`` is the name of a ``setup.py`` command (e.g. build_ext). If either hook is present this adds a wr...
Look through setup_package.py modules for functions with names like ``pre_<command_name>_hook`` and ``post_<command_name>_hook`` where ``<command_name>`` is the name of a ``setup.py`` command (e.g. build_ext). If either hook is present this adds a wrapped version of that command to the passed in ``comm...
def random_sample(self, elements=('a', 'b', 'c'), length=None): """ Returns a list of random unique elements for the specified length. Multiple occurrences of the same value increase its probability to be in the output. """ return self.random_elements(elements, length, unique=Tru...
Returns a list of random unique elements for the specified length. Multiple occurrences of the same value increase its probability to be in the output.
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features ...
def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusiv...
Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.padding instead] ...
def clear_to_enc_filename(fname): """ Converts the filename of a cleartext file and convert it to an encrypted filename :param fname: :return: filename of encrypted secret file if found, else None """ if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') ...
Converts the filename of a cleartext file and convert it to an encrypted filename :param fname: :return: filename of encrypted secret file if found, else None
def confirm_email(self): """ Confirm email """ if self._email and self.email_new: self._email = self.email_new self.email_confirmed = True self.email_link = None self.email_new = None self.email_link_expires = None
Confirm email
def set_digital_line_state(line_name, state): """Set the state of a single digital line. line_name (str) - The physical name of the line. e.g line_name="Dev1/port0/line3" This should be a single digital line. Specifying more than one would result in unexpected behaviour. For example "De...
Set the state of a single digital line. line_name (str) - The physical name of the line. e.g line_name="Dev1/port0/line3" This should be a single digital line. Specifying more than one would result in unexpected behaviour. For example "Dev1/port0/line0:5" is not allowed. see...
def json_datetime_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): serial = obj.isoformat() return serial if ObjectId is not None and isinstance(obj, ObjectId): # TODO: try to use bson.json_util instead ...
JSON serializer for objects not serializable by default json code
def update(self, id, data): """ Replaces document with _id = id with data. :param id: _id of document to update :type id: ``string`` :param data: the new document to insert :type data: ``string`` :return: id of replaced document :rtype: ``dict`` ...
Replaces document with _id = id with data. :param id: _id of document to update :type id: ``string`` :param data: the new document to insert :type data: ``string`` :return: id of replaced document :rtype: ``dict``
def set_in(self, que_in, num_senders): """Set the queue in input and the number of parallel tasks that send inputs""" for p in self.processes: p.set_in(que_in, num_senders)
Set the queue in input and the number of parallel tasks that send inputs
def write(self, offset, data): """ Write C{data} into this file at position C{offset}. Extending the file past its original end is expected. Unlike python's normal C{write()} methods, this method cannot do a partial write: it must write all of C{data} or else return an error. ...
Write C{data} into this file at position C{offset}. Extending the file past its original end is expected. Unlike python's normal C{write()} methods, this method cannot do a partial write: it must write all of C{data} or else return an error. The default implementation checks for an at...
def _from_api_repr(cls, resource): """Returns a job reference for an API resource representation.""" job_id = resource.get("jobId") project = resource.get("projectId") location = resource.get("location") job_ref = cls(job_id, project, location) return job_ref
Returns a job reference for an API resource representation.
def metric_get(self, project, metric_name): """API call: retrieve a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The metric...
API call: retrieve a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The metric object returned from the API (converted from a ...
def ph_supconj(b, orbit, solve_for=None, **kwargs): """ TODO: add documentation """ orbit_ps = _get_system_ps(b, orbit) # metawargs = orbit_ps.meta #metawargs.pop('qualifier') # t0_ph0 and phshift both exist by default, so we don't have to worry about creating either # t0_ph0 = orbit_p...
TODO: add documentation
def validation_statuses(self, area_uuid): """ Get count of validation statuses for all files in upload_area :param str area_uuid: A RFC4122-compliant ID for the upload area :return: a dict with key for each state and value being the count of files in that state :rtype: dict ...
Get count of validation statuses for all files in upload_area :param str area_uuid: A RFC4122-compliant ID for the upload area :return: a dict with key for each state and value being the count of files in that state :rtype: dict :raises UploadApiException: if information could not be ob...
def commit(self): """Commit the transaction""" self.flush() if hasattr(self, 'transaction') and self.transaction.is_active: self.transaction.commit() elif hasattr(self, 'connection'): self.connection.commit()
Commit the transaction
def dump_table(self, table, drop_statement=True): """Export a table structure and data to SQL file for backup or later import.""" create_statement = self.get_table_definition(table) data = self.select_all(table) statements = ['\n', sql_file_comment(''), sql_file_com...
Export a table structure and data to SQL file for backup or later import.
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ``importlib.import_module`` and each object is ...
def stop(self): """Stops the worker threads and waits for them to finish""" self.working = False for w in self.workers: w.join() self.workers = []
Stops the worker threads and waits for them to finish
async def reportCompleted(self, *args, **kwargs): """ Report Run Completed Report a task completed, resolving the run as `completed`. This method gives output: ``v1/task-status-response.json#`` This method is ``stable`` """ return await self._makeApiCall(self....
Report Run Completed Report a task completed, resolving the run as `completed`. This method gives output: ``v1/task-status-response.json#`` This method is ``stable``
def rvs(self, *args, **kwargs): """Draw Random Variates. Parameters ---------- size: int, optional (default=1) random_state_: optional (default=None) """ # TODO REVERSE THIS FUCK PYTHON2 size = kwargs.pop('size', 1) random_state = kwargs.pop('size...
Draw Random Variates. Parameters ---------- size: int, optional (default=1) random_state_: optional (default=None)
def fixed_string(self, data=None): """ The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to...
The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to extend the length of a static password.
def load_tiff(file): """ Load a geotiff raster keeping ndv values using a masked array Usage: data = load_tiff(file) """ ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file) data = gdalnumeric.LoadFile(file) data = np.ma.masked_array(data, mask=data == ndv, fill_va...
Load a geotiff raster keeping ndv values using a masked array Usage: data = load_tiff(file)
def add_markdown(self, markdown): """stub""" if markdown is None: raise NullArgument('markdown cannot be None') if not self.my_osid_object_form._is_valid_string( markdown, self.get_markdown_metadata()): raise InvalidArgument('markdown') self.my_osi...
stub
def logToFile(path, level=logging.INFO): """ Create a log handler that logs to the given file. """ logger = logging.getLogger() logger.setLevel(level) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s') handler = logging.FileHandler(path) handler.setF...
Create a log handler that logs to the given file.
def read_mm_uic2(fd, byte_order, dtype, count): """Read MM_UIC2 tag from file and return as dictionary.""" result = {'number_planes': count} values = numpy.fromfile(fd, byte_order+'I', 6*count) result['z_distance'] = values[0::6] // values[1::6] #result['date_created'] = tuple(values[2::6]) #res...
Read MM_UIC2 tag from file and return as dictionary.
def printProfile(self, reset=False): """ Prints profiling information. Parameters: ---------------------------- @param reset (bool) If set to True, the profiling will be reset. """ print "Profiling information for {}".format(type(self).__name__) totalTime = 0.000001 ...
Prints profiling information. Parameters: ---------------------------- @param reset (bool) If set to True, the profiling will be reset.
def setup_sft_obs(sft_file,ins_file=None,start_datetime=None,times=None,ncomp=1): """writes an instruction file for a mt3d-usgs sft output file Parameters ---------- sft_file : str the sft output file (ASCII) ins_file : str the name of the instruction file to create....
writes an instruction file for a mt3d-usgs sft output file Parameters ---------- sft_file : str the sft output file (ASCII) ins_file : str the name of the instruction file to create. If None, the name is <sft_file>.ins. Default is None start_datetim...
def _init_map(self): """call these all manually because non-cooperative""" DecimalAnswerFormRecord._init_map(self) DecimalValuesFormRecord._init_map(self) TextAnswerFormRecord._init_map(self) TextsFormRecord._init_map(self) super(edXNumericResponseAnswerFormRecord, self)....
call these all manually because non-cooperative
def close(self): """Close and exit the connection.""" try: self.ssh.close() self.logger.debug("close connect succeed.") except paramiko.SSHException as e: self.unknown("close connect error: %s" % e)
Close and exit the connection.
def createBlocksFromHTML(cls, html, encoding='utf-8'): ''' createBlocksFromHTML - Returns the root level node (unless multiple nodes), and a list of "blocks" added (text and nodes). @return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or...
createBlocksFromHTML - Returns the root level node (unless multiple nodes), and a list of "blocks" added (text and nodes). @return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or AdvancedTag (tags) NOTE: Results may be checked b...
def _start(self, update_cmd): """Start the long running operation. On completion, runs any callbacks. :param callable update_cmd: The API reuqest to check the status of the operation. """ try: self._poll(update_cmd) except BadStatus: sel...
Start the long running operation. On completion, runs any callbacks. :param callable update_cmd: The API reuqest to check the status of the operation.
def close(self): """Closes the cursor. No further operations are allowed once the cursor is closed. If the cursor is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` block. """ if self._closed: raise Programmin...
Closes the cursor. No further operations are allowed once the cursor is closed. If the cursor is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` block.