code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_umi_consensus(data): """Retrieve UMI for consensus based preparation. We specify this either as a separate fastq file or embedded in the read name as `fastq_name`.` """ consensus_choices = (["fastq_name"]) umi = tz.get_in(["config", "algorithm", "umi_type"], data) # don't run consen...
Retrieve UMI for consensus based preparation. We specify this either as a separate fastq file or embedded in the read name as `fastq_name`.`
def node_is_on_list(self, node): """Returns True if this node is on *some* list. A node is not on any list if it is linked to itself, or if it does not have the next and/prev attributes at all. """ next = self.node_next(node) if next == node or next is None: ...
Returns True if this node is on *some* list. A node is not on any list if it is linked to itself, or if it does not have the next and/prev attributes at all.
def precip(self, start, end, **kwargs): r""" Returns precipitation observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to o...
r""" Returns precipitation observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may als...
def console_init_root( w: int, h: int, title: Optional[str] = None, fullscreen: bool = False, renderer: Optional[int] = None, order: str = "C", ) -> tcod.console.Console: """Set up the primary display and return the root console. `w` and `h` are the columns and rows of the new window (i...
Set up the primary display and return the root console. `w` and `h` are the columns and rows of the new window (in tiles.) `title` is an optional string to display on the windows title bar. `fullscreen` determines if the window will start in fullscreen. Fullscreen mode is unreliable unless the rende...
def DeleteCronJob(self, cronjob_id): """Deletes a cronjob along with all its runs.""" if cronjob_id not in self.cronjobs: raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id) del self.cronjobs[cronjob_id] try: del self.cronjob_leases[cronjob_id] except KeyError: pass...
Deletes a cronjob along with all its runs.
def _sectors(self, ignore_chunk=None): """ Return a list of all sectors, each sector is a list of chunks occupying the block. """ sectorsize = self._bytes_to_sector(self.size) sectors = [[] for s in range(sectorsize)] sectors[0] = True # locations sectors[1] = Tru...
Return a list of all sectors, each sector is a list of chunks occupying the block.
def related_records2marc(self, key, value): """Populate the ``78708`` MARC field Also populates the ``78002``, ``78502`` MARC fields through side effects. """ if value.get('relation_freetext'): return { 'i': value.get('relation_freetext'), 'w': get_recid_from_ref(value.g...
Populate the ``78708`` MARC field Also populates the ``78002``, ``78502`` MARC fields through side effects.
def print_msg(contentlist): # type: (Union[AnyStr, List[AnyStr], Tuple[AnyStr]]) -> AnyStr """concatenate message list as single string with line feed.""" if isinstance(contentlist, list) or isinstance(contentlist, tuple): return '\n'.join(contentlist) else: # strings ...
concatenate message list as single string with line feed.
def count(self, axis='major'): """ Return number of observations over requested axis. Parameters ---------- axis : {'items', 'major', 'minor'} or {0, 1, 2} Returns ------- count : DataFrame """ i = self._get_axis_number(axis) val...
Return number of observations over requested axis. Parameters ---------- axis : {'items', 'major', 'minor'} or {0, 1, 2} Returns ------- count : DataFrame
def _get_stream_id(self, text): """Try to find a stream_id""" m = self._image_re.search(text) if m: return m.group("stream_id")
Try to find a stream_id
async def input(dev: Device, input, output): """Get and change outputs.""" inputs = await dev.get_inputs() if input: click.echo("Activating %s" % input) try: input = next((x for x in inputs if x.title == input)) except StopIteration: click.echo("Unable to find...
Get and change outputs.
def groupby_with_null(data, *args, **kwargs): """ Groupby on columns with NaN/None/Null values Pandas currently does have proper support for groupby on columns with null values. The nulls are discarded and so not grouped on. """ by = kwargs.get('by', args[0]) altered_columns = {} i...
Groupby on columns with NaN/None/Null values Pandas currently does have proper support for groupby on columns with null values. The nulls are discarded and so not grouped on.
def from_xml(cls, xml_val): """ Return the enumeration member corresponding to the XML value *xml_val*. """ if xml_val not in cls._xml_to_member: raise InvalidXmlError( "attribute value '%s' not valid for this type" % xml_val ) retu...
Return the enumeration member corresponding to the XML value *xml_val*.
def schema_to_command( p, name: str, callback: callable, add_message: bool ) -> click.Command: """ Generates a ``notify`` :class:`click.Command` for :class:`~notifiers.core.Provider` :param p: Relevant Provider :param name: Command name :return: A ``notify`` :class:`click.Command` """ p...
Generates a ``notify`` :class:`click.Command` for :class:`~notifiers.core.Provider` :param p: Relevant Provider :param name: Command name :return: A ``notify`` :class:`click.Command`
def _rm_udf_link(self, rec): # type: (udfmod.UDFFileEntry) -> int ''' An internal method to remove a UDF File Entry link. Parameters: rec - The UDF File Entry to remove. Returns: The number of bytes to remove from the ISO. ''' if not rec.is_file...
An internal method to remove a UDF File Entry link. Parameters: rec - The UDF File Entry to remove. Returns: The number of bytes to remove from the ISO.
def analisar(retorno): """Constrói uma :class:`RespostaExtrairLogs` a partir do retorno informado. :param unicode retorno: Retorno da função ``ExtrairLogs``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ExtrairLogs', classe_res...
Constrói uma :class:`RespostaExtrairLogs` a partir do retorno informado. :param unicode retorno: Retorno da função ``ExtrairLogs``.
def _setup_simplejson(self, responder): """ We support serving simplejson for Python 2.4 targets on Ansible 2.3, at least so the package's own CI Docker scripts can run without external help, however newer versions of simplejson no longer support Python 2.4. Therefore override an...
We support serving simplejson for Python 2.4 targets on Ansible 2.3, at least so the package's own CI Docker scripts can run without external help, however newer versions of simplejson no longer support Python 2.4. Therefore override any installed/loaded version with a 2.4-compatible ver...
def splitroot(self, path, sep=None): """Split path into drive, root and rest.""" if sep is None: sep = self.filesystem.path_separator if self.filesystem.is_windows_fs: return self._splitroot_with_drive(path, sep) return self._splitroot_posix(path, sep)
Split path into drive, root and rest.
def stop_tensorboard(args): '''stop tensorboard''' experiment_id = check_experiment_id(args) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() config_file_name = experiment_dict[experiment_id]['fileName'] nni_config = Config(config_file_name) tensorb...
stop tensorboard
def show_G_distribution(data): '''Show the distribution of the G function.''' Xs, t = fitting.preprocess_data(data) Theta, Phi = np.meshgrid(np.linspace(0, np.pi, 50), np.linspace(0, 2 * np.pi, 50)) G = [] for i in range(len(Theta)): G.append([]) for j in range(len(Theta[i])): ...
Show the distribution of the G function.
def smkdirs(dpath, mode=0o777): """Safely make a full directory path if it doesn't exist. Parameters ---------- dpath : str Path of directory/directories to create mode : int [default=0777] Permissions for the new directories See also -------- os.makedirs """ i...
Safely make a full directory path if it doesn't exist. Parameters ---------- dpath : str Path of directory/directories to create mode : int [default=0777] Permissions for the new directories See also -------- os.makedirs
async def renew_lease_async(self, lease): """ Renew a lease currently held by this host. If the lease has been stolen, or expired, or released, it is not possible to renew it. You will have to call getLease() and then acquireLease() again. :param lease: The stored lease to be re...
Renew a lease currently held by this host. If the lease has been stolen, or expired, or released, it is not possible to renew it. You will have to call getLease() and then acquireLease() again. :param lease: The stored lease to be renewed. :type lease: ~azure.eventprocessorhost.lease.Le...
def cli(ctx, amount, index, stage, stepresult, formattype, select, where, order, outputfile, showkeys, showvalues, showalways, position): """Export from memory to format supported by tablib""" if not ctx.bubb...
Export from memory to format supported by tablib
def setColor(self, personID, color): """setColor(string, (integer, integer, integer, integer)) sets color for person with the given ID. i.e. (255,0,0,0) for the color red. The fourth integer (alpha) is only used when drawing persons with raster images """ self._connection...
setColor(string, (integer, integer, integer, integer)) sets color for person with the given ID. i.e. (255,0,0,0) for the color red. The fourth integer (alpha) is only used when drawing persons with raster images
def check_type(self, type): """Check to see if the type is either in TYPES or fits type name Returns proper type """ if type in TYPES: return type tdict = dict(zip(TYPES,TYPES)) tdict.update({ 'line': 'lc', 'bar': 'bvs', 'p...
Check to see if the type is either in TYPES or fits type name Returns proper type
def accept_format(*, version: str = "v3", media: Optional[str] = None, json: bool = True) -> str: """Construct the specification of the format that a request should return. The version argument defaults to v3 of the GitHub API and is applicable to all requests. The media argument along wi...
Construct the specification of the format that a request should return. The version argument defaults to v3 of the GitHub API and is applicable to all requests. The media argument along with 'json' specifies what format the request should return, e.g. requesting the rendered HTML of a comment. Do note ...
def note_hz_to_midi(annotation): '''Convert a pitch_hz annotation to pitch_midi''' annotation.namespace = 'note_midi' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, ...
Convert a pitch_hz annotation to pitch_midi
def transaction_abort(self, transaction_id, **kwargs): """Abort a transaction and roll back all operations. :param transaction_id: ID of transaction to be aborted. :param **kwargs: Further parameters for the transport layer. """ if transaction_id not in self.__transactions: ...
Abort a transaction and roll back all operations. :param transaction_id: ID of transaction to be aborted. :param **kwargs: Further parameters for the transport layer.
def clone(self, opts): ''' Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance. ''' topt = self.opts.copy() topt.update(opts) return self.__class__(self.modl, self.name, self...
Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance.
def _parse_docline(self, line, container): """Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element.""" match = self.RE_DECOR.match(line) if match is not None: return "{...
Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element.
def cache_git_tag(): """ Try to read the current version from git and, if read successfully, cache it into the version cache file. If the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a pre-existing version cache file upon failure. :return: Project ver...
Try to read the current version from git and, if read successfully, cache it into the version cache file. If the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a pre-existing version cache file upon failure. :return: Project version string
def urls(self): """ A dictionary of the urls to be mocked with this service and the handlers that should be called in their place """ url_bases = self._url_module.url_bases unformatted_paths = self._url_module.url_paths urls = {} for url_base in url_bases...
A dictionary of the urls to be mocked with this service and the handlers that should be called in their place
def streamweigths_get(self, session): '''taobao.wangwang.eservice.streamweigths.get 获取分流权重接口 获取当前登录用户自己的店铺内的分流权重设置''' request = TOPRequest('taobao.wangwang.eservice.streamweigths.get') self.create(self.execute(request, session)) return self.staff_stream_weights
taobao.wangwang.eservice.streamweigths.get 获取分流权重接口 获取当前登录用户自己的店铺内的分流权重设置
def comp_srcmdl_xml(self, **kwargs): """ return the name of a source model file """ kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( '...
return the name of a source model file
def delete_container(container_name, profile, **libcloud_kwargs): ''' Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver...
Delete an object container in the cloud :param container_name: Container name :type container_name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` :return: ...
def from_pycode(cls, co): """Create a Code object from a python code object. Parameters ---------- co : CodeType The python code object. Returns ------- code : Code The codetransformer Code object. """ # Make it sparse to ...
Create a Code object from a python code object. Parameters ---------- co : CodeType The python code object. Returns ------- code : Code The codetransformer Code object.
def _get_class_repr(cls, type_, bound, keyfunc, keyfunc_name): # type: (Any, slice, Callable, str) -> str """Return a class representation using the slice parameters. Args: type_: The type the class was sliced with. bound: The boundaries specified for the values of type_...
Return a class representation using the slice parameters. Args: type_: The type the class was sliced with. bound: The boundaries specified for the values of type_. keyfunc: The comparison function used to check the value boundaries. keyfunc_name: ...
def simulate(self): """ Section 7 - uwg main section self.N # Total hours in simulation self.ph # per hour self.dayType # 3=Sun, 2=Sat, 1=Weekday self.ceil_time_step # simulation timestep (dt) fitted to weathe...
Section 7 - uwg main section self.N # Total hours in simulation self.ph # per hour self.dayType # 3=Sun, 2=Sat, 1=Weekday self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep # ...
def query(self): ''' The :attr:`query_string` parsed into a :class:`FormsDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`. ''' pairs = parse_qsl(self.q...
The :attr:`query_string` parsed into a :class:`FormsDict`. These values are sometimes called "URL arguments" or "GET parameters", but not to be confused with "URL wildcards" as they are provided by the :class:`Router`.
def parrep(self, parfile=None,enforce_bounds=True): """replicates the pest parrep util. replaces the parval1 field in the parameter data section dataframe Parameters ---------- parfile : str parameter file to use. If None, try to use a parameter file...
replicates the pest parrep util. replaces the parval1 field in the parameter data section dataframe Parameters ---------- parfile : str parameter file to use. If None, try to use a parameter file that corresponds to the case name. Default is None...
def _srm(self, data): """Expectation-Maximization algorithm for fitting the probabilistic SRM. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. Returns -...
Expectation-Maximization algorithm for fitting the probabilistic SRM. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. Returns ------- sigma_s : array, ...
def compute(self, write_to_tar=True): """Perform all desired calculations on the data and save externally.""" data = self._get_all_data(self.start_date, self.end_date) logging.info('Computing timeseries for {0} -- ' '{1}.'.format(self.start_date, self.end_date)) full...
Perform all desired calculations on the data and save externally.
def export(self, last_checkpoint, output_dir): """Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model. """ logging.info('Exporting prediction graph to %s', outp...
Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model.
def value_from_ast_untyped( value_node: ValueNode, variables: Dict[str, Any] = None ) -> Any: """Produce a Python value given a GraphQL Value AST. Unlike `value_from_ast()`, no type is provided. The resulting Python value will reflect the provided GraphQL value AST. | GraphQL Value | JSON V...
Produce a Python value given a GraphQL Value AST. Unlike `value_from_ast()`, no type is provided. The resulting Python value will reflect the provided GraphQL value AST. | GraphQL Value | JSON Value | Python Value | | -------------------- | ---------- | ------------ | | Input Object ...
def _pop(self): ''' Actual pop ''' if not self.canPop(): raise IndexError('pop from an empty or blocked queue') priority = self.prioritySet[-1] ret = self.queues[priority]._pop() self.outputStat = self.outputStat + 1 self.totalSize = self.total...
Actual pop
def browse_in_qt5_ui(self): """Browse and edit the SubjectInfo in a simple Qt5 based UI.""" self._render_type = "browse" self._tree.show(tree_style=self._get_tree_style())
Browse and edit the SubjectInfo in a simple Qt5 based UI.
def sys_call(cmd): """Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr) """ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) return p.stdout.readlines(), p.stderr.readlines()
Execute cmd and capture stdout and stderr :param cmd: command to be executed :return: (stdout, stderr)
def read_column(self, column, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """ # validate the version self.validate_version() # infer the data kind if not self.infer_axes(): r...
return a single column from the table, generally only indexables are interesting
def remove_by_rank(self, low, high=None): """ Remove elements from the ZSet by their rank (relative position). :param low: Lower bound. :param high: Upper bound. """ if high is None: high = low return self.database.zremrangebyrank(self.key, low, high)
Remove elements from the ZSet by their rank (relative position). :param low: Lower bound. :param high: Upper bound.
def get_priority_rules(db) -> Iterable[PriorityRule]: """Get file priority rules.""" cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield PriorityRule(*row)
Get file priority rules.
def execute(self, cacheable=False): """Returns the XML DOM response of the POST Request from the server""" if self.network.is_caching_enabled() and cacheable: response = self._get_cached_response() else: response = self._download_response() return minidom.parseS...
Returns the XML DOM response of the POST Request from the server
def _server_begin_response_callback(self, response: Response): '''Pre-response callback handler.''' self._item_session.response = response if self._cookie_jar: self._cookie_jar.extract_cookies(response, self._item_session.request) action = self._result_rule.handle_pre_respo...
Pre-response callback handler.
def qwe(rtol, atol, maxint, inp, intervals, lambd=None, off=None, factAng=None): r"""Quadrature-With-Extrapolation. This is the kernel of the QWE method, used for the Hankel (``hqwe``) and the Fourier (``fqwe``) Transforms. See ``hqwe`` for an extensive description. This function is based ...
r"""Quadrature-With-Extrapolation. This is the kernel of the QWE method, used for the Hankel (``hqwe``) and the Fourier (``fqwe``) Transforms. See ``hqwe`` for an extensive description. This function is based on ``qwe.m`` from the source code distributed with [Key12]_.
def get(self, subscription_id=None, stream=None, historics_id=None, page=None, per_page=None, order_by=None, order_dir=None, include_finished=None): """ Show details of the Subscriptions belonging to this user. Uses API documented at http://dev.datasift.com/docs/api/rest-api...
Show details of the Subscriptions belonging to this user. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget :param subscription_id: optional id of an existing Push Subscription :type subscription_id: str :param hash: optional hash of a l...
def regex(expression, flags=re.IGNORECASE): """ Convenient shortcut to ``re.compile()`` for fast, easy to use regular expression compilation without an extra import statement. Arguments: expression (str): regular expression value. flags (int): optional regular expression flags. ...
Convenient shortcut to ``re.compile()`` for fast, easy to use regular expression compilation without an extra import statement. Arguments: expression (str): regular expression value. flags (int): optional regular expression flags. Defaults to ``re.IGNORECASE`` Returns: ...
def use_args( self, argmap: ArgMap, req: typing.Optional[Request] = None, locations: typing.Iterable = None, as_kwargs: bool = False, validate: Validate = None, error_status_code: typing.Optional[int] = None, error_headers: typing.Union[typing.Mapping[str,...
Decorator that injects parsed arguments into a view function or method. Receives the same arguments as `webargs.core.Parser.use_args`.
def is_now(s, dt=None): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: s = cron-like string (minute, hour, day of month, month, day of week) dt = datetime to use as reference time, defaults to now @output: boolean of result...
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: s = cron-like string (minute, hour, day of month, month, day of week) dt = datetime to use as reference time, defaults to now @output: boolean of result
def determine_chan_detect_threshold(kal_out): """Return channel detect threshold from kal output.""" channel_detect_threshold = "" while channel_detect_threshold == "": for line in kal_out.splitlines(): if "channel detect threshold: " in line: channel_detect_threshold = s...
Return channel detect threshold from kal output.
def get_all(limit=''): ''' Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit '''...
Return all installed services. Use the ``limit`` param to restrict results to services of that type. CLI Example: .. code-block:: bash salt '*' service.get_all salt '*' service.get_all limit=upstart salt '*' service.get_all limit=sysvinit
def query(self): """Runs an fstat for this file and repopulates the data""" self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0] self._head = HeadRevision(self._p4dict) self._filename = self.depotFile
Runs an fstat for this file and repopulates the data
def paste_mashes(sketches, pasted_mash, force = False): """ Combine mash files into single sketch Input: sketches <list[str]> -- paths to sketch files pasted_mash <str> -- path to output mash file force <boolean> -- force overwrite of all mash file """ if os.path.isf...
Combine mash files into single sketch Input: sketches <list[str]> -- paths to sketch files pasted_mash <str> -- path to output mash file force <boolean> -- force overwrite of all mash file
async def destroy_models(self, *models, destroy_storage=False): """Destroy one or more models. :param str *models: Names or UUIDs of models to destroy :param bool destroy_storage: Whether or not to destroy storage when destroying the models. Defaults to false. """ u...
Destroy one or more models. :param str *models: Names or UUIDs of models to destroy :param bool destroy_storage: Whether or not to destroy storage when destroying the models. Defaults to false.
def askopenfilename(**kwargs): """Return file name(s) from Tkinter's file open dialog.""" try: from Tkinter import Tk import tkFileDialog as filedialog except ImportError: from tkinter import Tk, filedialog root = Tk() root.withdraw() root.update() filenames = filedia...
Return file name(s) from Tkinter's file open dialog.
def make_nylas_blueprint( client_id=None, client_secret=None, scope="email", redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with Nylas using OAuth 2. This requires an A...
Make a blueprint for authenticating with Nylas using OAuth 2. This requires an API ID and API secret from Nylas. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`NYLAS_OAUTH_CLIENT_ID` and :envvar:`NYLAS_OAUTH_CLI...
def _prune_hit(hit, model): """ Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine whether a 'hit' (search document) should be pruned from an index, and if so it returns the hit as a Django object(id=hit_id). Args: ...
Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine whether a 'hit' (search document) should be pruned from an index, and if so it returns the hit as a Django object(id=hit_id). Args: hit: dict object the represents ...
def _compute_error(self): """Compute unexplained error.""" sum_x = sum(self.x_transforms) err = sum((self.y_transform - sum_x) ** 2) / len(sum_x) return err
Compute unexplained error.
def transform(self, X): ''' :param X: features. ''' inverser_tranformer = self.dict_vectorizer_ if self.feature_selection: inverser_tranformer = self.clone_dict_vectorizer_ return inverser_tranformer.inverse_transform( self.transformer.transform( ...
:param X: features.
def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False): """Initializes parsing parameters.""" if target is None: target = "" else: target = str(target).replace(".", "") if target in pseudo_targets: ...
Initializes parsing parameters.
def use_sequestered_assessment_part_view(self): """Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view""" # Does this need to be re-implemented to match the other non-sub-package view setters? self._containable_views['assessment_part'] = SEQUESTERED ...
Pass through to provider AssessmentPartLookupSession.use_sequestered_assessment_part_view
def extend(self, item): """ Extend list from object, if object is list. """ if self.meta_type == 'dict': raise AssertionError('Cannot extend to object of `dict` base type!') if self.meta_type == 'list': self._list.extend(item) return
Extend list from object, if object is list.
def to_proper_radians(theta): """ Converts theta (radians) to be within -pi and +pi. """ if theta > pi or theta < -pi: theta = theta % pi return theta
Converts theta (radians) to be within -pi and +pi.
def GetSavename(default=None, **kwargs): """Prompt the user for a filename to save as. This will raise a Zenity Save As Dialog. It will return the name to save a file as or None if the user hit cancel. default - The default name that should appear in the save as dialog. kwargs - Optional...
Prompt the user for a filename to save as. This will raise a Zenity Save As Dialog. It will return the name to save a file as or None if the user hit cancel. default - The default name that should appear in the save as dialog. kwargs - Optional command line parameters for Zenity such as heig...
def move_saved_issue_data(self, issue, ns, other_ns): """Moves an issue_data from one namespace to another.""" if isinstance(issue, int): issue_number = str(issue) elif isinstance(issue, basestring): issue_number = issue else: issue_number = issue.num...
Moves an issue_data from one namespace to another.
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get("files") ...
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. .. versionadded:: 0.9
def generate_name_variations(name): """Generate name variations for a given name. Args: name (six.text_type): The name whose variations are to be generated. Returns: list: All the name variations for the given name. Notes: Uses `unidecode` for doing unicode characters translit...
Generate name variations for a given name. Args: name (six.text_type): The name whose variations are to be generated. Returns: list: All the name variations for the given name. Notes: Uses `unidecode` for doing unicode characters transliteration to ASCII ones. This was chosen so t...
def add_snippet_client(self, name, package): """Adds a snippet client to the management. Args: name: string, the attribute name to which to attach the snippet client. E.g. `name='maps'` attaches the snippet client to `ad.maps`. package: string, th...
Adds a snippet client to the management. Args: name: string, the attribute name to which to attach the snippet client. E.g. `name='maps'` attaches the snippet client to `ad.maps`. package: string, the package name of the snippet apk to connect to. ...
def parse_proposal_data(self, proposal_data, dossier_pk): """Get or Create a proposal model from raw data""" proposal_display = '{} ({})'.format(proposal_data['title'].encode( 'utf-8'), proposal_data.get('report', '').encode('utf-8')) if 'issue_type' not in proposal_data.keys(): ...
Get or Create a proposal model from raw data
def sync_sources(self): """ Syncs data sources between Elements, which draw data from the same object. """ get_sources = lambda x: (id(x.current_frame.data), x) filter_fn = lambda x: (x.shared_datasource and x.current_frame is not None and n...
Syncs data sources between Elements, which draw data from the same object.
def get_soup_response(self): """Get the response as a cached BeautifulSoup container. Returns: obj: The BeautifulSoup container. """ if self.response is not None: if self.__response_soup is None: result = BeautifulSoup(self.response.text, "lxml"...
Get the response as a cached BeautifulSoup container. Returns: obj: The BeautifulSoup container.
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
Compute the eigvals of mat and then find the center eigval difference.
def get_disk_cache(self, key=None): """Return result in disk cache for key 'key' or None if not found.""" key = self.model.hash if key is None else key if not getattr(self, 'disk_cache_location', False): self.init_disk_cache() disk_cache = shelve.open(self.disk_cache_location...
Return result in disk cache for key 'key' or None if not found.
def timethis(func): """A wrapper use for timeit.""" func_module, func_name = func.__module__, func.__name__ @functools.wraps(func) def wrapper(*args, **kwargs): start = _time_perf_counter() r = func(*args, **kwargs) end = _time_perf_counter() print('timethis : <{}.{}> : ...
A wrapper use for timeit.
def dsa_sign(private_key, data, hash_algorithm): """ Generates a DSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", ...
Generates a DSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when ...
def copy_from_dict(self, attributes): """Copies the attribute container from a dictionary. Args: attributes (dict[str, object]): attribute values per name. """ for attribute_name, attribute_value in attributes.items(): # Not using startswith to improve performance. if attribute_name[0]...
Copies the attribute container from a dictionary. Args: attributes (dict[str, object]): attribute values per name.
def ModifyInstance(self, ModifiedInstance, IncludeQualifiers=None, PropertyList=None, **extra): # pylint: disable=invalid-name,line-too-long """ Modify the property values of an instance. This method performs the ModifyInstance operation (see :term:`DSP020...
Modify the property values of an instance. This method performs the ModifyInstance operation (see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all methods performing such operations. The `PropertyList` parameter determines the set of properties that are designated...
def close(self, discard=False): '''Close this pool connection by releasing the underlying :attr:`connection` back to the :attr:`pool`. ''' if self.pool is not None: self.pool._put(self.connection, discard) self.pool = None conn, self.connection = self....
Close this pool connection by releasing the underlying :attr:`connection` back to the :attr:`pool`.
def setup_environment(config: Dict[str, Any], environment_type: Environment) -> None: """Sets the config depending on the environment type""" # interpret the provided string argument if environment_type == Environment.PRODUCTION: # Safe configuration: restrictions for mainnet apply and matrix rooms ...
Sets the config depending on the environment type
def do_drag_data_received(self, drag_context, x, y, data, info, time): '''从其它程序拖放目录/文件, 以便上传. 这里, 会直接把文件上传到当前目录(self.path). 拖放事件已经被处理, 所以不会触发self.app.window的拖放动作. ''' if not self.app.profile: return if info == TargetInfo.URI_LIST: uris = data.get_...
从其它程序拖放目录/文件, 以便上传. 这里, 会直接把文件上传到当前目录(self.path). 拖放事件已经被处理, 所以不会触发self.app.window的拖放动作.
def get_count_sql(self): """ Build a SELECT query which returns the count of items for an unlimited SELECT :return: A SQL SELECT query which returns the count of items for an unlimited query based on this SQLBuilder """ sql = 'SELECT COUNT(*) FROM ' + self.tables ...
Build a SELECT query which returns the count of items for an unlimited SELECT :return: A SQL SELECT query which returns the count of items for an unlimited query based on this SQLBuilder
def log_histogram(self, name, value, step=None): """Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be...
Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and ...
def login(self, user=None, password=None, restrict_login=None): """ Attempt to log in using the given username and password. Subsequent method calls will use this username and password. Returns False if login fails, otherwise returns some kind of login info - typically either a n...
Attempt to log in using the given username and password. Subsequent method calls will use this username and password. Returns False if login fails, otherwise returns some kind of login info - typically either a numeric userid, or a dict of user info. If user is not set, the value of Bug...
def plot_sens_center(self, frequency=2): """ plot sensitivity center distribution for all configurations in config.dat. The centers of mass are colored by the data given in volt_file. """ try: colors = np.loadtxt(self.volt_file, skiprows=1) except IOE...
plot sensitivity center distribution for all configurations in config.dat. The centers of mass are colored by the data given in volt_file.
def list_contains(list_of_strings, substring, return_true_false_array=False): """ Get strings in list which contains substring. """ key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings] if return_true_false_array: return key_tf keys_to_remove = list_of_strings[key_tf] return...
Get strings in list which contains substring.
def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2): """Return the MLIPNS distance between two strings. This is a wrapper for :py:meth:`MLIPNS.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison threshold : floa...
Return the MLIPNS distance between two strings. This is a wrapper for :py:meth:`MLIPNS.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison threshold : float A number [0, 1] indicating the maximum similarity score, b...
def ISBNValidator(raw_isbn): """ Check string is a valid ISBN number""" isbn_to_check = raw_isbn.replace('-', '').replace(' ', '') if not isinstance(isbn_to_check, string_types): raise ValidationError(_(u'Invalid ISBN: Not a string')) if len(isbn_to_check) != 10 and len(isbn_to_check) != 13: ...
Check string is a valid ISBN number
def _generate_AES_CBC_cipher(cek, iv): ''' Generates and returns an encryption cipher for AES CBC using the given cek and iv. :param bytes[] cek: The content encryption key for the cipher. :param bytes[] iv: The initialization vector for the cipher. :return: A cipher for encrypting in AES256 CBC. ...
Generates and returns an encryption cipher for AES CBC using the given cek and iv. :param bytes[] cek: The content encryption key for the cipher. :param bytes[] iv: The initialization vector for the cipher. :return: A cipher for encrypting in AES256 CBC. :rtype: ~cryptography.hazmat.primitives.ciphers....
def uri(host='localhost', port=5432, dbname='postgres', user='postgres', password=None): """Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to conn...
Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to connect as :param str password: The password to use, None for no password :return str: The PostgreSQ...
def __cache_point(self, index): """! @brief Store index points. @param[in] index (uint): Index point that should be stored. """ if self.__cache_points: if self.__points is None: self.__points = [] self.__points.append(index)
! @brief Store index points. @param[in] index (uint): Index point that should be stored.
def create(self, table_id, schema): """ Create a table in Google BigQuery given a table and schema Parameters ---------- table : str Name of table to be written schema : str Use the generate_bq_schema to generate your table schema from a dataf...
Create a table in Google BigQuery given a table and schema Parameters ---------- table : str Name of table to be written schema : str Use the generate_bq_schema to generate your table schema from a dataframe.
def ignore(mapping): """ Use ignore to prevent a mapping from being mapped to a namedtuple. """ if isinstance(mapping, Mapping): return AsDict(mapping) elif isinstance(mapping, list): return [ignore(item) for item in mapping] return mapping
Use ignore to prevent a mapping from being mapped to a namedtuple.