code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def firsts(properties): """ Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by ...
Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by names. :rtype: dict
def position_pnl(self): """ [float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分 """ last_price = self._data_proxy.get_last_price(self._order_book_id) if self._direction == POSITION_DIRECTION.LONG: price_spread = last_price - self._last_price else: price_spread = s...
[float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分
def check_apps_permission(self, apps): """ Checks if one of apps is listed in apps_dict Since apps_dict is derived from the app_list given by django admin, it lists only the apps the user can view """ for app in apps: if app in self.apps_dict: ...
Checks if one of apps is listed in apps_dict Since apps_dict is derived from the app_list given by django admin, it lists only the apps the user can view
def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4, debug=False): """See: pyqrcode.QRCode.png() This function was abstracted away from QRCode to allow for the output of QR codes during the build process, i.e. for debugging. It works ...
See: pyqrcode.QRCode.png() This function was abstracted away from QRCode to allow for the output of QR codes during the build process, i.e. for debugging. It works just the same except you must specify the code's version. This is needed to calculate the PNG's size. This method will write the given...
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ try: oauth_request = oauth_provider.utils.get_oauth_request(request) except oauth.Error as err: raise exceptions.Authenticati...
Returns two-tuple of (user, token) if authentication succeeds, or None otherwise.
def stonith_show(stonith_id, extra_args=None, cibfile=None): ''' Show the value of a cluster stonith stonith_id name for the stonith resource extra_args additional options for the pcs stonith command cibfile use cibfile instead of the live CIB CLI Example: .. code-...
Show the value of a cluster stonith stonith_id name for the stonith resource extra_args additional options for the pcs stonith command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.stonith_show stonith_id='eps_fence' ci...
def as_view(cls, action_map=None, **initkwargs): """ Allows custom request to method routing based on given ``action_map`` kwarg. """ # Needs to re-implement the method but contains all the things the parent does. if not action_map: # actions must not be empty raise...
Allows custom request to method routing based on given ``action_map`` kwarg.
def find_lexer_class_by_name(_alias): """Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2 """ if not _alias: raise ClassNotFound('no lexer for alias %r found' % _alias) # lookup builtin lexers for module_name, name, ...
Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2
async def release_lease_async(self, lease): """ Give up a lease currently held by this host. If the lease has been stolen, or expired, releasing it is unnecessary, and will fail if attempted. :param lease: The stored lease to be released. :type lease: ~azure.eventprocessorhost.l...
Give up a lease currently held by this host. If the lease has been stolen, or expired, releasing it is unnecessary, and will fail if attempted. :param lease: The stored lease to be released. :type lease: ~azure.eventprocessorhost.lease.Lease :return: `True` if the lease was released suc...
def get_customs_properties_by_inheritance(self, obj): """ Get custom properties from the templates defined in this object :param obj: the oject to search the property :type obj: alignak.objects.item.Item :return: list of custom properties :rtype: list """ ...
Get custom properties from the templates defined in this object :param obj: the oject to search the property :type obj: alignak.objects.item.Item :return: list of custom properties :rtype: list
def key_bytes(self): """Returns the raw signing key. :rtype: bytes """ return self.key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), )
Returns the raw signing key. :rtype: bytes
def add(self, host=None, f_community=None, f_access=None, f_version=None): """ Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 ...
Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr :param f_community: Community string to add :param f_access: READ or WRITE :param f_version: v1, v2c or v3 :return: (True/False, t_snmp.id/Error string)
def cwd (self): """ Change to URL parent directory. Return filename of last path component. """ path = self.urlparts[2].encode(self.filename_encoding, 'replace') dirname = path.strip('/') dirs = dirname.split('/') filename = dirs.pop() self.url_con...
Change to URL parent directory. Return filename of last path component.
def get_func(name, argtypes=None, restype=c_int, lib=libNLPIR): """Retrieves the corresponding NLPIR function. :param str name: The name of the NLPIR function to get. :param list argtypes: A list of :mod:`ctypes` data types that correspond to the function's argument types. :param restype: A :mo...
Retrieves the corresponding NLPIR function. :param str name: The name of the NLPIR function to get. :param list argtypes: A list of :mod:`ctypes` data types that correspond to the function's argument types. :param restype: A :mod:`ctypes` data type that corresponds to the function's return ...
def rot1(theta): """ Args: theta (float): Angle in radians Return: Rotation matrix of angle theta around the X-axis """ return np.array([ [1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)] ])
Args: theta (float): Angle in radians Return: Rotation matrix of angle theta around the X-axis
def _emit(self, s): """Append content to the main report file.""" if os.path.exists(self._html_dir): # Make sure we're not immediately after a clean-all. self._report_file.write(s) self._report_file.flush()
Append content to the main report file.
def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e %= L P = IDENT for i in range(253): if e & 1: P = edwards_add(P=P, Q=Bpow[i]) e //= 2 assert e == 0, e return P
Implements scalarmult(B, e) more efficiently.
def _setup(self): """ Prepare the system for using ``ansible-galaxy`` and returns None. :return: None """ role_directory = os.path.join(self._config.scenario.directory, self.options['roles-path']) if not os.path.isdir(role_directory)...
Prepare the system for using ``ansible-galaxy`` and returns None. :return: None
def bkg_calc_interp1d(self, analytes=None, kind=1, n_min=10, n_max=None, cstep=None, bkg_filter=False, f_win=7, f_n_lim=3, focus_stage='despiked'): """ Background calculation using a 1D interpolation. scipy.interpolate.interp1D is used for interpolation. Param...
Background calculation using a 1D interpolation. scipy.interpolate.interp1D is used for interpolation. Parameters ---------- analytes : str or iterable Which analyte or analytes to calculate. kind : str or int Integer specifying the order of the spline i...
def configure_delete(self, ns, definition): """ Register a delete endpoint. The definition's func should be a delete function, which must: - accept kwargs for path data - return truthy/falsey :param ns: the namespace :param definition: the endpoint definition ...
Register a delete endpoint. The definition's func should be a delete function, which must: - accept kwargs for path data - return truthy/falsey :param ns: the namespace :param definition: the endpoint definition
def visitObjectDef(self, ctx: jsgParser.ObjectDefContext): """ objectDef: ID objectExpr """ name = as_token(ctx) self._context.grammarelts[name] = JSGObjectExpr(self._context, ctx.objectExpr(), name)
objectDef: ID objectExpr
def select_sample(in_file, sample, out_file, config, filters=None): """Select a single sample from the supplied multisample VCF file. """ if not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: if len(get_samples(in_file)) == 1: shutil....
Select a single sample from the supplied multisample VCF file.
def find_external_urls(self, entry): """ Find external URLs in an entry. """ soup = BeautifulSoup(entry.html_content, 'html.parser') external_urls = [a['href'] for a in soup.find_all('a') if self.is_external_url( a['href'], se...
Find external URLs in an entry.
def _getCharWidths(self, xref, bfname, ext, ordering, limit, idx=0): """Return list of glyphs and glyph widths of a font.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document__getCharWidths(self, xref, bfname...
Return list of glyphs and glyph widths of a font.
def parsedeglat (latstr): """Parse a latitude formatted as sexagesimal degrees into an angle. This function converts a textual representation of a latitude, measured in degrees, into a floating point value measured in radians. The format of *latstr* is very limited: it may not have leading or trailing ...
Parse a latitude formatted as sexagesimal degrees into an angle. This function converts a textual representation of a latitude, measured in degrees, into a floating point value measured in radians. The format of *latstr* is very limited: it may not have leading or trailing whitespace, and the component...
def apply_config(self, config): """ Constructs HAProxyConfig and HAProxyControl instances based on the contents of the config. This is mostly a matter of constructing the configuration stanzas. """ self.haproxy_config_path = config["config_file"] global_stanza =...
Constructs HAProxyConfig and HAProxyControl instances based on the contents of the config. This is mostly a matter of constructing the configuration stanzas.
def rename_feature(self, old_feature, new_feature): """ Change the label of a feature attached to the Bundle :parameter str old_feature: the current name of the feature (must exist) :parameter str new_feature: the desired new name of the feature (must not exist) ...
Change the label of a feature attached to the Bundle :parameter str old_feature: the current name of the feature (must exist) :parameter str new_feature: the desired new name of the feature (must not exist) :return: None :raises ValueError: if the new_feature is ...
def _compute_scale(self, instruction_id, svg_dict): """Compute the scale of an instruction svg. Compute the scale using the bounding box stored in the :paramref:`svg_dict`. The scale is saved in a dictionary using :paramref:`instruction_id` as key. :param str instruction_id: id...
Compute the scale of an instruction svg. Compute the scale using the bounding box stored in the :paramref:`svg_dict`. The scale is saved in a dictionary using :paramref:`instruction_id` as key. :param str instruction_id: id identifying a symbol in the defs :param dict svg_dict:...
def write(self, writer): """ Writes an XML representation of this node (including descendants) to the specified file-like object. :param writer: An :class:`XmlWriter` instance to write this node to """ multiline = bool(self._children) newline_start = multiline and not bo...
Writes an XML representation of this node (including descendants) to the specified file-like object. :param writer: An :class:`XmlWriter` instance to write this node to
def get_install_names(filename): """ Return install names from library named in `filename` Returns tuple of install names tuple will be empty if no install names, or if this is not an object file. Parameters ---------- filename : str filename of library Returns ------- in...
Return install names from library named in `filename` Returns tuple of install names tuple will be empty if no install names, or if this is not an object file. Parameters ---------- filename : str filename of library Returns ------- install_names : tuple tuple of inst...
def add_access_list(self, loadbalancer, access_list): """ Adds the access list provided to the load balancer. The 'access_list' should be a list of dicts in the following format: [{"address": "192.0.43.10", "type": "DENY"}, {"address": "192.0.43.11", "type": "ALLOW"}, ...
Adds the access list provided to the load balancer. The 'access_list' should be a list of dicts in the following format: [{"address": "192.0.43.10", "type": "DENY"}, {"address": "192.0.43.11", "type": "ALLOW"}, ... {"address": "192.0.43.99", "type": "DENY"}, ...
def make(parser): """DEPRECATED prepare OpenStack basic environment""" s = parser.add_subparsers( title='commands', metavar='COMMAND', help='description', ) def gen_pass_f(args): gen_pass() gen_pass_parser = s.add_parser('gen-pass', help='generate the passwor...
DEPRECATED prepare OpenStack basic environment
def ReadSerializedDict(cls, json_dict): """Reads an attribute container from serialized dictionary form. Args: json_dict (dict[str, object]): JSON serialized objects. Returns: AttributeContainer: attribute container or None. Raises: TypeError: if the serialized dictionary does not c...
Reads an attribute container from serialized dictionary form. Args: json_dict (dict[str, object]): JSON serialized objects. Returns: AttributeContainer: attribute container or None. Raises: TypeError: if the serialized dictionary does not contain an AttributeContainer.
def get_context_data(self, **kwargs): """ Returns the context data to provide to the template. """ context = super().get_context_data(**kwargs) context['poster'] = self.poster return context
Returns the context data to provide to the template.
def _needed_markup_bot(self): """ Returns the input peer of the bot that's needed for the reply markup. This is necessary for :tl:`KeyboardButtonSwitchInline` since we need to know what bot we want to start. Raises ``ValueError`` if the bot cannot be found but is needed. Returns...
Returns the input peer of the bot that's needed for the reply markup. This is necessary for :tl:`KeyboardButtonSwitchInline` since we need to know what bot we want to start. Raises ``ValueError`` if the bot cannot be found but is needed. Returns ``None`` if it's not needed.
def more_like_this(self, query, fields, columns=None, start=0, rows=30): """ Retrieves "more like this" results for a passed query document query - query for a document on which to base similar documents fields - fields on which to base similarity estimation (either comma delimited stri...
Retrieves "more like this" results for a passed query document query - query for a document on which to base similar documents fields - fields on which to base similarity estimation (either comma delimited string or a list) columns - columns to return (list of strings) start - start num...
def update_device(name, **kwargs): ''' .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash...
.. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash salt myminion netbox.update_device ed...
def solubility_eutectic(T, Tm, Hm, Cpl=0, Cps=0, gamma=1): r'''Returns the maximum solubility of a solute in a solvent. .. math:: \ln x_i^L \gamma_i^L = \frac{\Delta H_{m,i}}{RT}\left( 1 - \frac{T}{T_{m,i}}\right) - \frac{\Delta C_{p,i}(T_{m,i}-T)}{RT} + \frac{\Delta C_{p,i}}{R}\ln\frac...
r'''Returns the maximum solubility of a solute in a solvent. .. math:: \ln x_i^L \gamma_i^L = \frac{\Delta H_{m,i}}{RT}\left( 1 - \frac{T}{T_{m,i}}\right) - \frac{\Delta C_{p,i}(T_{m,i}-T)}{RT} + \frac{\Delta C_{p,i}}{R}\ln\frac{T_m}{T} \Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S P...
def rotate_x(self, deg): """Rotate mesh around x-axis :param float deg: Rotation angle (degree) :return: """ rad = math.radians(deg) mat = numpy.array([ [1, 0, 0, 0], [0, math.cos(rad), math.sin(rad), 0], [0, -math.sin(rad), math.cos(r...
Rotate mesh around x-axis :param float deg: Rotation angle (degree) :return:
def remove_account(self, name): """ Remove an account from the account's sub accounts. :param name: The name of the account to remove. """ acc_to_remove = None for a in self.accounts: if a.name == name: acc_to_remove = a if acc_to_rem...
Remove an account from the account's sub accounts. :param name: The name of the account to remove.
def build(self, builder): """Build XML by appending to builder""" params = dict(MetaDataVersionOID=str(self.metadata_version_oid), StudyOID="%s (%s)" % (self.projectname, self.environment,), ) # mixins self.mixin_params(params) builde...
Build XML by appending to builder
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
Create database tables from sqlalchemy models
def _parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = parts.next() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() ...
Parse a Content-type like header. Return the main content-type and a dictionary of options.
def _write_section(self, fp, section_name, section_items, delimiter): """Write a single section to the specified `fp'.""" fp.write("[{0}]\n".format(section_name)) for key, value in section_items: value = self._interpolation.before_write(self, section_name, key, ...
Write a single section to the specified `fp'.
def coupling_efficiency(mode_solver, fibre_mfd, fibre_offset_x=0, fibre_offset_y=0, n_eff_fibre=1.441): ''' Finds the coupling efficiency between a solved fundamental mode and a fibre of given MFD. Args: mode_solver (_ModeSolver): Mode solver that...
Finds the coupling efficiency between a solved fundamental mode and a fibre of given MFD. Args: mode_solver (_ModeSolver): Mode solver that has found a fundamental mode. fibre_mfd (float): The mode-field diameter (MFD) of the fibre. fibre_offset_x (float): Offset...
def get_default_config(self): """ Returns default configuration options. """ config = super(NetfilterAccountingCollector, self).get_default_config() config.update({ 'path': 'nfacct', 'bin': 'nfacct', 'use_sudo': False, 'reset': True...
Returns default configuration options.
def fingerprint(dirnames, prefix=None, previous=[]): #pylint:disable=dangerous-default-value """ Returns a list of paths available from *dirname*. When previous is specified, returns a list of additional files only. Example: [{ "Key": "abc.txt", "LastModified": "Mon, 05 Jan 2015 12:00:00...
Returns a list of paths available from *dirname*. When previous is specified, returns a list of additional files only. Example: [{ "Key": "abc.txt", "LastModified": "Mon, 05 Jan 2015 12:00:00 UTC"}, { "Key": "def.txt", "LastModified": "Mon, 05 Jan 2015 12:00:001 UTC"}, ]
def using(self, client): """ Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. :arg client: an instance of ``elasticsearch.Elasticsearch`` to use or an alias to look up in ``elasticsearch_dsl.c...
Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged. :arg client: an instance of ``elasticsearch.Elasticsearch`` to use or an alias to look up in ``elasticsearch_dsl.connections``
def getWorkDirs(): """get input/output dirs (same input/output layout as for package)""" # get caller module caller_fullurl = inspect.stack()[1][1] caller_relurl = os.path.relpath(caller_fullurl) caller_modurl = os.path.splitext(caller_relurl)[0] # split caller_url & append 'Dir' to package name dirs = ca...
get input/output dirs (same input/output layout as for package)
def get_name_history( self, name, offset=None, count=None, reverse=False): """ Get the historic states for a name, grouped by block height. """ cur = self.db.cursor() name_hist = namedb_get_history( cur, name, offset=offset, count=count, reverse=reverse ) return name_hist
Get the historic states for a name, grouped by block height.
def remove_root_bank(self, bank_id): """Removes a root bank from this hierarchy. arg: bank_id (osid.id.Id): the ``Id`` of a bank raise: NotFound - ``bank_id`` not a parent of ``child_id`` raise: NullArgument - ``bank_id`` or ``child_id`` is ``null`` raise: OperationFailed ...
Removes a root bank from this hierarchy. arg: bank_id (osid.id.Id): the ``Id`` of a bank raise: NotFound - ``bank_id`` not a parent of ``child_id`` raise: NullArgument - ``bank_id`` or ``child_id`` is ``null`` raise: OperationFailed - unable to complete request raise: Per...
async def minizinc( mzn, *dzn_files, args=None, data=None, include=None, stdlib_dir=None, globals_dir=None, declare_enums=True, allow_multiple_assignments=False, keep=False, output_vars=None, output_base=None, output_mode='dict', solver=None, timeout=None, two_pass=None, pre_passes=None, output_obje...
Coroutine version of the ``pymzn.minizinc`` function. Parameters ---------- max_queue_size : int Maximum number of solutions in the queue between the solution parser and the returned solution stream. When the queue is full, the solver execution will halt untill an item of the queue ...
def single_run_arrays(spanning_cluster=True, **kwargs): r''' Generate statistics for a single run This is a stand-alone helper function to evolve a single sample state (realization) and return the cluster statistics. Parameters ---------- spanning_cluster : bool, optional Whether t...
r''' Generate statistics for a single run This is a stand-alone helper function to evolve a single sample state (realization) and return the cluster statistics. Parameters ---------- spanning_cluster : bool, optional Whether to detect a spanning cluster or not. Defaults to ``Tr...
def get_transcript(self, gene_pk, refseq_id): "Get a transcript from the cache or add a new record." if not refseq_id: return transcript_pk = self.transcripts.get(refseq_id) if transcript_pk: return transcript_pk gene = Gene(pk=gene_pk) transcript ...
Get a transcript from the cache or add a new record.
def get_partstudio_tessellatededges(self, did, wid, eid): ''' Gets the tessellation of the edges of all parts in a part studio. Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response:...
Gets the tessellation of the edges of all parts in a part studio. Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape response data
def defer(self, func, *args, **kwargs): """ Arrange for `func()` to execute on the broker thread. This function returns immediately without waiting the result of `func()`. Use :meth:`defer_sync` to block until a result is available. :raises mitogen.core.Error: :meth:...
Arrange for `func()` to execute on the broker thread. This function returns immediately without waiting the result of `func()`. Use :meth:`defer_sync` to block until a result is available. :raises mitogen.core.Error: :meth:`defer` was called after :class:`Broker` has begun shutdown.
def from_data(room, conn, data): """Construct a ChatMessage instance from raw protocol data""" files = list() rooms = dict() msg = str() for part in data["message"]: ptype = part["type"] if ptype == "text": val = part["value"] ...
Construct a ChatMessage instance from raw protocol data
def create_record_sets(self, record_set_dicts): """Accept list of record_set dicts. Return list of record_set objects.""" record_set_objects = [] for record_set_dict in record_set_dicts: # pop removes the 'Enabled' key and tests if True. if record_set_dict.pop('En...
Accept list of record_set dicts. Return list of record_set objects.
def create_route(self, item, routes): """Stores a new item in routing map""" for route in routes: self._routes.setdefault(route, set()).add(item) return item
Stores a new item in routing map
def parse_conditional_derived_variable(self, node): """ Parses <ConditionalDerivedVariable> @param node: Node containing the <ConditionalDerivedVariable> element @type node: xml.etree.Element @raise ParseError: Raised when no name or value is specified for the conditional deriv...
Parses <ConditionalDerivedVariable> @param node: Node containing the <ConditionalDerivedVariable> element @type node: xml.etree.Element @raise ParseError: Raised when no name or value is specified for the conditional derived variable.
def _groupby_consecutive(txn, max_delta=pd.Timedelta('8h')): """Merge transactions of the same direction separated by less than max_delta time duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed round_trips. One row per trade. - See full explan...
Merge transactions of the same direction separated by less than max_delta time duration. Parameters ---------- transactions : pd.DataFrame Prices and amounts of executed round_trips. One row per trade. - See full explanation in tears.create_full_tear_sheet max_delta : pandas.Timede...
async def plonks(self, ctx): """Shows members banned from the bot.""" plonks = self.config.get('plonks', {}) guild = ctx.message.server db = plonks.get(guild.id, []) members = '\n'.join(map(str, filter(None, map(guild.get_member, db)))) if members: await self....
Shows members banned from the bot.
def get_schema(self, dataset_id, table_id): """ Get the schema for a given datset.table. see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource :param dataset_id: the dataset ID of the requested table :param table_id: the table ID of the requested table ...
Get the schema for a given datset.table. see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource :param dataset_id: the dataset ID of the requested table :param table_id: the table ID of the requested table :return: a table schema
def remove(self, interval): """ Returns self after removing the interval and balancing. If interval is not present, raise ValueError. """ # since this is a list, called methods can set this to [1], # making it true done = [] return self.remove_interval_he...
Returns self after removing the interval and balancing. If interval is not present, raise ValueError.
def getFixedStars(self): """ Returns a list with all fixed stars. """ IDs = const.LIST_FIXED_STARS return ephem.getFixedStarList(IDs, self.date)
Returns a list with all fixed stars.
def _set_target_root_count_in_runtracker(self): """Sets the target root count in the run tracker's daemon stats object.""" # N.B. `self._target_roots` is always an expanded list of `Target` objects as # provided by `GoalRunner`. target_count = len(self._target_roots) self.run_tracker.pantsd_stats.se...
Sets the target root count in the run tracker's daemon stats object.
def addSuccess(self, test: unittest.case.TestCase) -> None: """ Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save """ # noinspection PyTypeChecker self.add_result(TestState.success, test)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save
def register_work(self, work, deps=None, manager=None, workdir=None): """ Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies. Args: work: :class:`Work` object. deps: List of :class:`Dependency` objects specifying the d...
Register a new :class:`Work` and add it to the internal list, taking into account possible dependencies. Args: work: :class:`Work` object. deps: List of :class:`Dependency` objects specifying the dependency of this node. An empy list of deps implies that this node has ...
def restore_app_connection(self, port=None): """Restores the app after device got reconnected. Instead of creating new instance of the client: - Uses the given port (or find a new available host_port if none is given). - Tries to connect to remote server with selected po...
Restores the app after device got reconnected. Instead of creating new instance of the client: - Uses the given port (or find a new available host_port if none is given). - Tries to connect to remote server with selected port. Args: port: If given, this is the...
def export_account_state(self, account_state): """ Make an account state presentable to external consumers """ return { 'address': account_state['address'], 'type': account_state['type'], 'credit_value': '{}'.format(account_state['credit_value']), ...
Make an account state presentable to external consumers
def grantSystemPermission(self, login, user, perm): """ Parameters: - login - user - perm """ self.send_grantSystemPermission(login, user, perm) self.recv_grantSystemPermission()
Parameters: - login - user - perm
def survey_loader(sur_dir=SUR_DIR, sur_file=SUR_FILE): """Loads up the given survey in the given dir.""" survey_path = os.path.join(sur_dir, sur_file) survey = None with open(survey_path) as survey_file: survey = Survey(survey_file.read()) return survey
Loads up the given survey in the given dir.
def list_settings(self): """ Get list of all appropriate settings and their default values. The returned list is then used in setup() and get_setup() methods to setup the widget internal settings. """ return [ (self.SETTING_FLAG_PLAIN, False), (se...
Get list of all appropriate settings and their default values. The returned list is then used in setup() and get_setup() methods to setup the widget internal settings.
def stdout(self): """ Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT. Если есть любое значение в CROSSPM_STDOUT - оно понимается как True :return: """ # --stdout stdout = self._args['--stdout'] if stdout: return True ...
Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT. Если есть любое значение в CROSSPM_STDOUT - оно понимается как True :return:
def _actionsFreqsAngles(self,*args,**kwargs): """ NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,vz[,...
NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single obj...
def mask_by_linear_ind(self, linear_inds): """Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Im...
Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Image` A new Image of the same type, with da...
def add_comes_from(self, basic_block): """ This simulates a set. Adds the basic_block to the comes_from list if not done already. """ if basic_block is None: return if self.lock: return # Return if already added if basic_block in self.com...
This simulates a set. Adds the basic_block to the comes_from list if not done already.
def libvlc_video_set_key_input(p_mi, on): '''Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse ...
Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse click events per window. If your application ...
def extract(self, doc): """From the defined JSONPath(s), pull out the values and insert them into a document with renamed field(s) then apply the Extractor and return the doc with the extracted values """ if isinstance(self.jsonpaths, JSONPath): input_field = self.extractor....
From the defined JSONPath(s), pull out the values and insert them into a document with renamed field(s) then apply the Extractor and return the doc with the extracted values
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternat...
Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`.
def set_copy_mode(self, use_copy: bool): """ Set all protocols in copy mode. They will return a copy of their protocol. This is used for writable mode in CFC. :param use_copy: :return: """ for group in self.rootItem.children: for proto in group.childr...
Set all protocols in copy mode. They will return a copy of their protocol. This is used for writable mode in CFC. :param use_copy: :return:
def stop(self): """ Try to gracefully stop the greenlet synchronously Stop isn't expected to re-raise greenlet _run exception (use self.greenlet.get() for that), but it should raise any stop-time exception """ if self._stop_event.ready(): return self._stop_ev...
Try to gracefully stop the greenlet synchronously Stop isn't expected to re-raise greenlet _run exception (use self.greenlet.get() for that), but it should raise any stop-time exception
def parse_args(args=None): """ Parse arguments provided as a list of strings, and return a namespace with parameter names matching the arguments :param args: List of strings to be parsed as command-line arguments. If none, reads in sys.argv as the values. :return: a namespace containing arg...
Parse arguments provided as a list of strings, and return a namespace with parameter names matching the arguments :param args: List of strings to be parsed as command-line arguments. If none, reads in sys.argv as the values. :return: a namespace containing arguments values
def emit(self, record): """Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return: """ try: # Shorten the source name of the record ...
Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return:
def setaty(self, content): """ Grab the (aty) soap-enc:arrayType and attach it to the content for proper array processing later in end(). @param content: The current content being unmarshalled. @type content: L{Content} @return: self @rtype: L{Encoded} """...
Grab the (aty) soap-enc:arrayType and attach it to the content for proper array processing later in end(). @param content: The current content being unmarshalled. @type content: L{Content} @return: self @rtype: L{Encoded}
def Main(url, similarity_mode="TfIdfCosine", similarity_limit=0.75): ''' Entry Point. Args: url: PDF url. ''' # The object of Web-scraping. web_scrape = WebScraping() # Set the object of reading PDF files. web_scrape.readable_web_pdf = WebPDFReading() # Execute Web-sc...
Entry Point. Args: url: PDF url.
def predraw(self): """ Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ . """ self.cam = self.view.cam super(LayerWorld,self).predraw()
Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ .
def ratelimit_remaining(self): """Number of requests before GitHub imposes a ratelimit. :returns: int """ json = self._json(self._get(self._github_url + '/rate_limit'), 200) core = json.get('resources', {}).get('core', {}) self._remaining = core.get('remaining', 0) ...
Number of requests before GitHub imposes a ratelimit. :returns: int
def hlen(key, host=None, port=None, db=None, password=None): ''' Returns number of fields of a hash. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hlen foo_hash ''' server = _connect(host, port, db, password) return server.hlen(key)
Returns number of fields of a hash. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hlen foo_hash
def addLineWidget( self, query = None ): """ Adds a new line widget to the system with the given values. :param query | (<str> term, <str> operator, <str> vlaue) || None """ widget = XQueryLineWidget(self) widget.setTerms(sorted(self._rules.keys())) ...
Adds a new line widget to the system with the given values. :param query | (<str> term, <str> operator, <str> vlaue) || None
def _merge_defaults(self, config): """The config object loads its values from two sources, with the following precedence: 1. data/default_config.yaml 2. The config file itself, passed in to this object in the constructor as `path`. in case of conflict, th...
The config object loads its values from two sources, with the following precedence: 1. data/default_config.yaml 2. The config file itself, passed in to this object in the constructor as `path`. in case of conflict, the config file dominates.
def create_vlan(self, id_vlan): """ Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None """ vlan_map = dict() vlan_map['vlan_id'] = id_vlan code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/') return self.response(c...
Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None
def fetch_chunk_data(self): """If period of time between start end end is bigger then one year We have to create and fetch chunks dates (6 months chunks).""" data = [] counter = (relativedelta(self.end_date, self.start_date).months / 6) + 1 months = 0 for month in range...
If period of time between start end end is bigger then one year We have to create and fetch chunks dates (6 months chunks).
def _setup_serializers(self): """ Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats """...
Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.blob.bucket prefix = self.blob.name if not prefix.endswith('/'): prefix += '/' for blob in bucket.list_blobs(prefi...
Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency.
def pack(header, s): """Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s ...
Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s : str The packed str...
def clear_learning_objectives(self): """Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.lea...
Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def edges_unique(self): """ The unique edges of the mesh. Returns ---------- edges_unique : (n, 2) int Vertex indices for unique edges """ unique, inverse = grouping.unique_rows(self.edges_sorted) edges_unique = self.edges_sorted[unique] ...
The unique edges of the mesh. Returns ---------- edges_unique : (n, 2) int Vertex indices for unique edges
def get_changes(self, extracted_name, similar=False, global_=False): """Get the changes this refactoring makes :parameters: - `similar`: if `True`, similar expressions/statements are also replaced. - `global_`: if `True`, the extracted method/variable will ...
Get the changes this refactoring makes :parameters: - `similar`: if `True`, similar expressions/statements are also replaced. - `global_`: if `True`, the extracted method/variable will be global.
def schedule(self, task: Schedulable, *args, **kwargs): """Add a job to be executed ASAP to the batch. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function """ ...
Add a job to be executed ASAP to the batch. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function