code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def remove(self, point, node=None): """ Removes the node with the given point from the tree Returns the new root node of the (sub)tree. If there are multiple points matching "point", only one is removed. The optional "node" parameter is used for checking the identity, once the ...
Removes the node with the given point from the tree Returns the new root node of the (sub)tree. If there are multiple points matching "point", only one is removed. The optional "node" parameter is used for checking the identity, once the removeal candidate is decided.
def _limit_call_handler(self): """ Ensure we don't exceed the N requests a minute limit by leveraging a thread lock """ # acquire a lock on our threading.Lock() object with self.limit_lock: # if we have no configured limit, exit. the lock releases based on scope ...
Ensure we don't exceed the N requests a minute limit by leveraging a thread lock
def output_sizes(self): """Returns a tuple of all output sizes of all the layers.""" return tuple([l() if callable(l) else l for l in self._output_sizes])
Returns a tuple of all output sizes of all the layers.
def resend_invitations(self): """ Resends invites for an event. :: event = service.calendar().get_event(id='KEY HERE') event.resend_invitations() Anybody who has not declined this meeting will get a new invite. """ if not self.id: raise TypeError(u"You can't send invites fo...
Resends invites for an event. :: event = service.calendar().get_event(id='KEY HERE') event.resend_invitations() Anybody who has not declined this meeting will get a new invite.
def _find_blob_start(self): """Find first blob from selection. """ # Convert input frequencies into what their corresponding channel number would be. self._setup_chans() # Check which is the blob time offset blob_time_start = self.t_start # Check which is the b...
Find first blob from selection.
def _is_cif(string): """Test if input string is in CIF format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in CIF format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False` """ if (s...
Test if input string is in CIF format. :param string: Input string. :type string: :py:class:`str` or :py:class:`bytes` :return: Input string if in CIF format or False otherwise. :rtype: :py:class:`str` or :py:obj:`False`
def watchlist(self, tubes): """Set the watchlist to the given tubes :param tubes: A list of tubes to watch Automatically un-watches any tubes that are not on the target list """ tubes = set(tubes) for tube in tubes - self._watchlist: self.watch(tube) ...
Set the watchlist to the given tubes :param tubes: A list of tubes to watch Automatically un-watches any tubes that are not on the target list
def lasts(iterable, items=1, default=None): # type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the last x items from this iterable or default. """ last_items = deque(iterable, maxlen=items) for _ in range(items - len(last_items)): yield default for y in last_items: yie...
Lazily return the last x items from this iterable or default.
def median2D(const, bin1, label1, bin2, label2, data_label, returnData=False): """Return a 2D average of data_label over a season and label1, label2. Parameters ---------- const: Constellation or Instrument bin#: [min, max, number of bins] label#: string i...
Return a 2D average of data_label over a season and label1, label2. Parameters ---------- const: Constellation or Instrument bin#: [min, max, number of bins] label#: string identifies data product for bin# data_label: list-like contains strings identify...
def diag_post_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") diag = ET.SubElement(config, "diag", xmlns="urn:brocade.com:mgmt:brocade-diagnostics") post = ET.SubElement(diag, "post") enable = ET.SubElement(post, "enable") callbac...
Auto Generated Code
def close(self): """ Close log stream and stream_lock. """ try: self._close() if hasattr(self.stream_lock, 'closed') and \ not self.stream_lock.closed: self.stream_lock.close() finally: self.stream_lock = None ...
Close log stream and stream_lock.
def post_relationship(self, session, json_data, api_type, obj_id, rel_key): """ Append to a relationship. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource :param rel_key...
Append to a relationship. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource :param rel_key: Key of the relationship to fetch
def min_scalar_prod(x, y): """Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n) """ x = sorted(x) # make copies y = sorted(y) # to save arguments retu...
Permute vector to minimize scalar product :param x: :param y: x, y are vectors of same size :returns: min sum x[i] * y[sigma[i]] over all permutations sigma :complexity: O(n log n)
def appendRecord(self, record): """ Saves the record in the underlying csv file. :param record: a list of Python objects that will be string-ified """ assert self._file is not None assert self._mode == self._FILE_WRITE_MODE assert isinstance(record, (list, tuple)), \ "unexpected reco...
Saves the record in the underlying csv file. :param record: a list of Python objects that will be string-ified
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
Return default mdata map for Grade
async def kickban(self, channel, target, reason=None, range=0): """ Kick and ban user from channel. """ await self.ban(channel, target, range) await self.kick(channel, target, reason)
Kick and ban user from channel.
def update_object(self, url, container, container_object, object_headers, container_headers): """Update an existing object in a swift container. This method will place new headers on an existing object or container. :param url: :param container: :param con...
Update an existing object in a swift container. This method will place new headers on an existing object or container. :param url: :param container: :param container_object:
def __doDownloadPage(self, *args, **kwargs): """Works like client.downloadPage(), but handle incoming headers """ logger.debug("download page: %r, %r", args, kwargs) return self.__clientDefer(downloadPage(*args, **kwargs))
Works like client.downloadPage(), but handle incoming headers
def encode(string): """ Encode the given string as an OID. >>> import snmp_passpersist as snmp >>> snmp.PassPersist.encode("hello") '5.104.101.108.108.111' >>> """ result=".".join([ str(ord(s)) for s in string ]) return "%s." % (len(string)) + result
Encode the given string as an OID. >>> import snmp_passpersist as snmp >>> snmp.PassPersist.encode("hello") '5.104.101.108.108.111' >>>
def _make_ipmi_payload(self, netfn, command, bridge_request=None, data=()): """This function generates the core ipmi payload that would be applicable for any channel (including KCS) """ bridge_msg = [] self.expectedcmd = command # in ipmi, the response netfn is always one...
This function generates the core ipmi payload that would be applicable for any channel (including KCS)
def sync(self, hooks=True, async_hooks=True): """Synchronize user repositories. :param bool hooks: True for syncing hooks. :param bool async_hooks: True for sending of an asynchronous task to sync hooks. .. note:: Syncing happens from GitHu...
Synchronize user repositories. :param bool hooks: True for syncing hooks. :param bool async_hooks: True for sending of an asynchronous task to sync hooks. .. note:: Syncing happens from GitHub's direction only. This means that we consid...
def install_board(board_id, board_options, hwpack='arduino', replace_existing=False): """install board in boards.txt. :param board_id: string identifier :param board_options: dict like :param replace_existing: bool :rtype: None """ doaction = 0 if board_id in boards(hwpack).keys(): ...
install board in boards.txt. :param board_id: string identifier :param board_options: dict like :param replace_existing: bool :rtype: None
def _gettables(self): """Return a list of hdf5 tables name PyMCsamples. """ groups = self._h5file.list_nodes("/") if len(groups) == 0: return [] else: return [ gr.PyMCsamples for gr in groups if gr._v_name[:5] == 'chain']
Return a list of hdf5 tables name PyMCsamples.
def remove_jobs(self, mask): """Mark all jobs that match a mask as 'removed' """ jobnames = self.table[mask]['jobname'] jobkey = self.table[mask]['jobkey'] self.table[mask]['status'] = JobStatus.removed for jobname, jobkey in zip(jobnames, jobkey): fullkey = JobDetail...
Mark all jobs that match a mask as 'removed'
def _should_send(self, rebuild, success, auto_canceled, manual_canceled): """Return True if any state in `self.send_on` meets given conditions, thus meaning that a notification mail should be sent. """ should_send = False should_send_mapping = { self.MANUAL_SUCCESS: ...
Return True if any state in `self.send_on` meets given conditions, thus meaning that a notification mail should be sent.
def add_securitygroup_rule(self, group_id, remote_ip=None, remote_group=None, direction=None, ethertype=None, port_max=None, port_min=None, protocol=None): """Add a rule to a security group :param int group_id:...
Add a rule to a security group :param int group_id: The ID of the security group to add this rule to :param str remote_ip: The remote IP or CIDR to enforce the rule on :param int remote_group: The remote security group ID to enforce the rule on :param st...
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffe...
Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. ...
def createEditor(self, parent, column, operator, value): """ Creates a new editor for the system. """ editor = super(EnumPlugin, self).createEditor(parent, column, operator, ...
Creates a new editor for the system.
def fetch(self): """ Fetch & return a new `Action` object representing the action's current state :rtype: Action :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return api._action(api.request(self.url)["action"])
Fetch & return a new `Action` object representing the action's current state :rtype: Action :raises DOAPIError: if the API endpoint replies with an error
def _identifier_filtered_iterator(graph): """Iterate over names in the given namespace.""" for data in graph: for pair in _get_node_names(data): yield pair for member in data.get(MEMBERS, []): for pair in _get_node_names(member): yield pair for ((_, ...
Iterate over names in the given namespace.
def check(self, state, when): """ Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or after the event. :return: A boolean representing whether the checkpoint should fire. ""...
Checks state `state` to see if the breakpoint should fire. :param state: The state. :param when: Whether the check is happening before or after the event. :return: A boolean representing whether the checkpoint should fire.
def calibrate(self, dataset_id, pre_launch_coeffs=False, calib_coeffs=None): """Calibrate the data """ tic = datetime.now() if calib_coeffs is None: calib_coeffs = {} units = {'reflectance': '%', ...
Calibrate the data
def check(self, F): """Rough sanity checks on the input function. """ assert F.ndim == 1, "checker only supports 1D" f = self.xfac * F fabs = np.abs(f) iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum()) assert 0 != iQ1 != iQ3 != self...
Rough sanity checks on the input function.
def get_builds(self, project, definitions=None, queues=None, build_number=None, min_time=None, max_time=None, requested_for=None, reason_filter=None, status_filter=None, result_filter=None, tag_filters=None, properties=None, top=None, continuation_token=None, max_builds_per_definition=None, deleted_filter=None, query_o...
GetBuilds. Gets a list of builds. :param str project: Project ID or project name :param [int] definitions: A comma-delimited list of definition IDs. If specified, filters to builds for these definitions. :param [int] queues: A comma-delimited list of queue IDs. If specified, filters to b...
def _cursor(self, *args, **kwargs): """A "tough" version of the method cursor().""" # The args and kwargs are not part of the standard, # but some database modules seem to use these. transaction = self._transaction if not transaction: self._ping_check(2) try: ...
A "tough" version of the method cursor().
def add_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Adds a role for a user on a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: manager.add_user_role(user, role, project) else: ...
Adds a role for a user on a tenant.
def import_module(mod_str): """ inspired by post on stackoverflow :param name: import path string like 'netshowlib.linux.provider_discovery' :return: module matching the import statement """ _module = __import__(mod_str) _mod_parts = mod_str.split('.') for _mod_part in _mod_parts[1:]: ...
inspired by post on stackoverflow :param name: import path string like 'netshowlib.linux.provider_discovery' :return: module matching the import statement
def _debug_linter_status(linter, filename, show_lint_files): """Indicate that we are running this linter if required.""" if show_lint_files: print("{linter}: {filename}".format(linter=linter, filename=filename))
Indicate that we are running this linter if required.
def add_params(param_list_left, param_list_right): """Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res....
Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays
def add_to_bashrc(self, line, match_regexp=None, note=None, loglevel=logging.DEBUG): """Takes care of adding a line to everyone's bashrc (/etc/bash.bashrc). @param line: Line to add. @param match_regexp: See add_line_to_file(...
Takes care of adding a line to everyone's bashrc (/etc/bash.bashrc). @param line: Line to add. @param match_regexp: See add_line_to_file() @param note: See send() @return: See add_line_to_file()
def configure_logger(self): """Configure the test batch runner logger """ logger_name = 'brome_runner' self.logger = logging.getLogger(logger_name) format_ = BROME_CONFIG['logger_runner']['format'] # Stream logger if BROME_CONFIG['logger_runner']['streamlogger...
Configure the test batch runner logger
def or_has(self, relation, operator='>=', count=1): """ Add a relationship count condition to the query with an "or". :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :t...
Add a relationship count condition to the query with an "or". :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder
def to_dot(self, name='BDD'): # pragma: no cover """Convert to DOT language representation. See the `DOT language reference <http://www.graphviz.org/content/dot-language>`_ for details. """ parts = ['graph', name, '{'] for node in self.dfs_postorder(): ...
Convert to DOT language representation. See the `DOT language reference <http://www.graphviz.org/content/dot-language>`_ for details.
def create(*args, **kwargs): """ Create a SDR classifier factory. The implementation of the SDR Classifier can be specified with the "implementation" keyword argument. The SDRClassifierFactory uses the implementation as specified in `Default NuPIC Configuration <default-config.html>`_. """...
Create a SDR classifier factory. The implementation of the SDR Classifier can be specified with the "implementation" keyword argument. The SDRClassifierFactory uses the implementation as specified in `Default NuPIC Configuration <default-config.html>`_.
def draw(self, **kwargs): """ Draws the heatmap of the ranking matrix of variables. """ # Set the axes aspect to be equal self.ax.set_aspect("equal") # Generate a mask for the upper triangle mask = np.zeros_like(self.ranks_, dtype=np.bool) mask[np.triu_in...
Draws the heatmap of the ranking matrix of variables.
def parse_timestamp(x): """Parse ISO8601 formatted timestamp.""" dt = dateutil.parser.parse(x) if dt.tzinfo is None: dt = dt.replace(tzinfo=pytz.utc) return dt
Parse ISO8601 formatted timestamp.
def create_global_secondary_index(table_name, global_index, region=None, key=None, keyid=None, profile=None): ''' Creates a single global secondary index on a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.create_global_secondary...
Creates a single global secondary index on a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.create_global_secondary_index table_name / index_name
def reassign_label(cls, destination_cluster, label): """ Reassign a label from one cluster to another. Args: `destination_cluster`: id/label of the cluster to move the label to `label`: label to be moved from the source cluster """ conn = Qubole.agent(ve...
Reassign a label from one cluster to another. Args: `destination_cluster`: id/label of the cluster to move the label to `label`: label to be moved from the source cluster
def import_wikipage(self, slug, content, **attrs): """ Import a Wiki page and return a :class:`WikiPage` object. :param slug: slug of the :class:`WikiPage` :param content: content of the :class:`WikiPage` :param attrs: optional attributes for :class:`Task` """ re...
Import a Wiki page and return a :class:`WikiPage` object. :param slug: slug of the :class:`WikiPage` :param content: content of the :class:`WikiPage` :param attrs: optional attributes for :class:`Task`
def upload(self, docs_base, release): """Upload docs in ``docs_base`` to the target of this uploader.""" return getattr(self, '_to_' + self.target)(docs_base, release)
Upload docs in ``docs_base`` to the target of this uploader.
def ws_db996(self, value=None): """ Corresponds to IDD Field `ws_db996` Mean wind speed coincident with 99.6% dry-bulb temperature Args: value (float): value for IDD Field `ws_db996` Unit: m/s if `value` is None it will not be checked against the ...
Corresponds to IDD Field `ws_db996` Mean wind speed coincident with 99.6% dry-bulb temperature Args: value (float): value for IDD Field `ws_db996` Unit: m/s if `value` is None it will not be checked against the specification and is assumed to ...
def random(self, namespace=0): """ Returns query string for random page """ query = self.LIST.substitute( WIKI=self.uri, ENDPOINT=self.endpoint, LIST='random') query += "&rnlimit=1&rnnamespace=%d" % namespace emoji = [ u'\U...
Returns query string for random page
def _compare_variables_function_generator( method_string, aggregation_func): """Return a function usable as a comparison method for class |Variable|. Pass the specific method (e.g. `__eq__`) and the corresponding operator (e.g. `==`) as strings. Also pass either |numpy.all| or |numpy.any| for...
Return a function usable as a comparison method for class |Variable|. Pass the specific method (e.g. `__eq__`) and the corresponding operator (e.g. `==`) as strings. Also pass either |numpy.all| or |numpy.any| for aggregating multiple boolean values.
def atype_view_asset(self, ): """View the project of the current assettype :returns: None :rtype: None :raises: None """ if not self.cur_atype: return i = self.atype_asset_treev.currentIndex() item = i.internalPointer() if item: ...
View the project of the current assettype :returns: None :rtype: None :raises: None
def add_peddy_information(config_data): """Add information from peddy outfiles to the individuals""" ped_info = {} ped_check = {} sex_check = {} relations = [] if config_data.get('peddy_ped'): file_handle = open(config_data['peddy_ped'], 'r') for ind_info in parse_peddy_ped(file...
Add information from peddy outfiles to the individuals
def as_list(callable): """Convert a scalar validator in a list validator""" @wraps(callable) def wrapper(value_iter): return [callable(value) for value in value_iter] return wrapper
Convert a scalar validator in a list validator
def createContactItem(self, person, notes): """ Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The...
Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly cr...
def mass1_from_tau0_tau3(tau0, tau3, f_lower): r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`.""" mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower) eta = eta_from_tau0_tau3(tau0, tau3, f_lower) return mass1_from_mtotal_eta(mtotal, eta)
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`.
def download(self, files=None, destination=None, overwrite=False, callback=None): """Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) ...
Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments ...
def _gradient(self, diff, d, coords): """Compute the gradient. Args: diff (`array-like`): [`m`, `m`] matrix. `D` - `d` d (`array-like`): [`m`, `m`] matrix. coords (`array-like`): [`m`, `n`] matrix. Returns: `np.array`: Gradient, shape [`m`, `n`]....
Compute the gradient. Args: diff (`array-like`): [`m`, `m`] matrix. `D` - `d` d (`array-like`): [`m`, `m`] matrix. coords (`array-like`): [`m`, `n`] matrix. Returns: `np.array`: Gradient, shape [`m`, `n`].
def get_site_packages(venv): ''' Return the path to the site-packages directory of a virtualenv venv Path to the virtualenv. CLI Example: .. code-block:: bash salt '*' virtualenv.get_site_packages /path/to/my/venv ''' bin_path = _verify_virtualenv(venv) ret = __salt_...
Return the path to the site-packages directory of a virtualenv venv Path to the virtualenv. CLI Example: .. code-block:: bash salt '*' virtualenv.get_site_packages /path/to/my/venv
def append(self, new: Statement) -> None: """Append a HistoryItem to end of the History list :param new: command line to convert to HistoryItem and add to the end of the History list """ new = HistoryItem(new) list.append(self, new) new.idx = len(self)
Append a HistoryItem to end of the History list :param new: command line to convert to HistoryItem and add to the end of the History list
def _compute_centers(self, X, sparse, rs): """Generate RBF centers""" # use supplied centers if present centers = self._get_user_components('centers') # use points taken uniformly from the bounding # hyperrectangle if (centers is None): n_features = X.shape[...
Generate RBF centers
def command_packet(cmd): """ Build a command message. """ return message('Command', Container(string_length=len(cmd), string=bytes(cmd, ENCODING)), len(cmd) + 2)
Build a command message.
def results(self, **query_params): """Returns a streaming handle to this job's search results. To get a nice, Pythonic iterator, pass the handle to :class:`splunklib.results.ResultsReader`, as in:: import splunklib.client as client import splunklib.results as results ...
Returns a streaming handle to this job's search results. To get a nice, Pythonic iterator, pass the handle to :class:`splunklib.results.ResultsReader`, as in:: import splunklib.client as client import splunklib.results as results from time import sleep se...
def reindex(self, comments=True, change_history=True, worklogs=True): """ Reindex the Jira instance Kicks off a reindex. Need Admin permissions to perform this reindex. :param comments: Indicates that comments should also be reindexed. Not relevant for foreground reindex, where c...
Reindex the Jira instance Kicks off a reindex. Need Admin permissions to perform this reindex. :param comments: Indicates that comments should also be reindexed. Not relevant for foreground reindex, where comments are always reindexed. :param change_history: Indicates that changeHistory ...
def approvewitness(ctx, witnesses, account): """ Approve witness(es) """ pprint(ctx.peerplays.approvewitness(witnesses, account=account))
Approve witness(es)
def parse_content(self, content): """ Parses the output of the ``date`` and ``date --utc`` command. Sample: Fri Jun 24 09:13:34 CST 2016 Sample: Fri Jun 24 09:13:34 UTC 2016 Attributes ---------- datetime: datetime.datetime A native datetime.datetime...
Parses the output of the ``date`` and ``date --utc`` command. Sample: Fri Jun 24 09:13:34 CST 2016 Sample: Fri Jun 24 09:13:34 UTC 2016 Attributes ---------- datetime: datetime.datetime A native datetime.datetime of the parsed date string timezone: str ...
def coffee(input, output, **kw): """Process CoffeeScript files""" subprocess.call([current_app.config.get('COFFEE_BIN'), '-c', '-o', output, input])
Process CoffeeScript files
def wrap_http_for_jwt_access(credentials, http): """Prepares an HTTP object's request method for JWT access. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. ...
Prepares an HTTP object's request method for JWT access. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: _JWTAccessCredentials, t...
def PrimaryHDU(model): ''' Construct the primary HDU file containing basic header info. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=0) if 'KEPMAG' not in [c[0] for c in cards]: cards.append(('KEPMAG', model.mag, 'Kepler magnitude')) # Add EVEREST info ...
Construct the primary HDU file containing basic header info.
def resolve_method(state, method_name, class_name, params=(), ret_type=None, include_superclasses=True, init_class=True, raise_exception_if_not_found=False): """ Resolves the method based on the given characteristics (name, class and params) The method may be defined in...
Resolves the method based on the given characteristics (name, class and params) The method may be defined in one of the superclasses of the given class (TODO: support interfaces). :rtype: archinfo.arch_soot.SootMethodDescriptor
def write_brackets(docgraph, output_file, layer='mmax'): """ converts a document graph into a plain text file with brackets. Parameters ---------- layer : str or None The layer from which the pointing chains/relations (i.e. coreference relations) should be extracted. If no l...
converts a document graph into a plain text file with brackets. Parameters ---------- layer : str or None The layer from which the pointing chains/relations (i.e. coreference relations) should be extracted. If no layer is selected, all pointing relations will be considered. ...
def request(endpoint, verb='GET', session_options=None, **options): """Performs a synchronous request. Uses a dedicated event loop and aiohttp.ClientSession object. Options: - endpoint: the endpoint to call - verb: the HTTP verb to use (defaults: GET) - session_options: a dict containing opti...
Performs a synchronous request. Uses a dedicated event loop and aiohttp.ClientSession object. Options: - endpoint: the endpoint to call - verb: the HTTP verb to use (defaults: GET) - session_options: a dict containing options to initialize the session (defaults: None) - options: extra o...
async def put(self, cid): """Update description for content Accepts: Query string args: - "cid" - int Request body parameters: - message (signed dict): - "description" - str - "coinid" - str Returns: dict with following fields: - "confirmed": None - "txid" - str - "descrip...
Update description for content Accepts: Query string args: - "cid" - int Request body parameters: - message (signed dict): - "description" - str - "coinid" - str Returns: dict with following fields: - "confirmed": None - "txid" - str - "description" - str - "content" - s...
def reset_sequence(self, topic): """Reset the expected sequence number for a topic If the topic is unknown, this does nothing. This behaviour is useful when you have wildcard topics that only create queues once they receive the first message matching the topic. Args: ...
Reset the expected sequence number for a topic If the topic is unknown, this does nothing. This behaviour is useful when you have wildcard topics that only create queues once they receive the first message matching the topic. Args: topic (string): The topic to reset the pa...
def set_Y(self, Y): """ Set the output data of the model :param Y: output observations :type Y: np.ndarray or ObsArray """ assert isinstance(Y, (np.ndarray, ObsAr)) state = self.update_model() self.update_model(False) if self.normalizer is not Non...
Set the output data of the model :param Y: output observations :type Y: np.ndarray or ObsArray
def self_inventory(self): """ Inventory output will only contain the server name and the session ID when a key is provided. Provide the same format as with the full inventory instead for consistency. """ if self.api_key is None: return {} if self._sel...
Inventory output will only contain the server name and the session ID when a key is provided. Provide the same format as with the full inventory instead for consistency.
def applyslicer(array, slicer, pmask, cval = 0): r""" Apply a slicer returned by the iterator to a new array of the same dimensionality as the one used to initialize the iterator. Notes ----- If ``array`` has more dimensions than ``slicer`` and ``pmask``, the fir...
r""" Apply a slicer returned by the iterator to a new array of the same dimensionality as the one used to initialize the iterator. Notes ----- If ``array`` has more dimensions than ``slicer`` and ``pmask``, the first ones are sliced. Parameters ...
def get_data_frame_transform(self, transform_id=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform.html>`_ :arg transform_id: The id or comma delimited list of id expressions of the transforms to get, '_all' or '*' impl...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform.html>`_ :arg transform_id: The id or comma delimited list of id expressions of the transforms to get, '_all' or '*' implies get all transforms :arg from_: skips a number of transform configs, defaults...
async def reload_modules(self, pathlist): """ Reload modules with a full path in the pathlist """ loadedModules = [] failures = [] for path in pathlist: p, module = findModule(path, False) if module is not None and hasattr(module, '_instance') and ...
Reload modules with a full path in the pathlist
def get_category_by_id(cls, category_id, **kwargs): """Find Category Return single instance of Category by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_category_by_id(category_i...
Find Category Return single instance of Category by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_category_by_id(category_id, async=True) >>> result = thread.get() :para...
def _set_value(self, target, value, bitarray): ''' set given numeric value to target field in bitarray ''' # derive raw value rng = target.find('range') rng_min = float(rng.find('min').text) rng_max = float(rng.find('max').text) scl = target.find('scale') scl_min ...
set given numeric value to target field in bitarray
def stop(self): """ Stops the backend process. """ if self._process is None: return if self._shared: BackendManager.SHARE_COUNT -= 1 if BackendManager.SHARE_COUNT: return comm('stopping backend process') # close ...
Stops the backend process.
async def acquire_async(self): """Acquire the :attr:`lock` asynchronously """ r = self.acquire(blocking=False) while not r: await asyncio.sleep(.01) r = self.acquire(blocking=False)
Acquire the :attr:`lock` asynchronously
def now(format_string): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ from datetime import datetime from dj...
Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %}
def build(ctx, builder="html", options=""): """Build docs with sphinx-build""" sourcedir = ctx.config.sphinx.sourcedir destdir = Path(ctx.config.sphinx.destdir or "build")/builder destdir = destdir.abspath() with cd(sourcedir): destdir_relative = Path(".").relpathto(destdir) command ...
Build docs with sphinx-build
def get_provider_token(self, provider_secret): """ 获取服务商凭证 https://work.weixin.qq.com/api/doc#90001/90143/91200 :param provider_secret: 服务商的secret,在服务商管理后台可见 :return: 返回的 JSON 数据包 """ return self._post( 'service/get_provider_token', data=...
获取服务商凭证 https://work.weixin.qq.com/api/doc#90001/90143/91200 :param provider_secret: 服务商的secret,在服务商管理后台可见 :return: 返回的 JSON 数据包
async def list_vms(self, preset_name): ''' List VMs by preset name :arg present_name: string ''' response = await self.nova.servers.list(name=f'^{preset_name}$') result = [] for server in response['servers']: result.append(self._map_vm_structure(serve...
List VMs by preset name :arg present_name: string
def new(self, vd, ino, orig_len, csum): # type: (headervd.PrimaryOrSupplementaryVD, inode.Inode, int, int) -> None ''' A method to create a new boot info table. Parameters: vd - The volume descriptor to associate with this boot info table. ino - The Inode associated wi...
A method to create a new boot info table. Parameters: vd - The volume descriptor to associate with this boot info table. ino - The Inode associated with this Boot Info Table. orig_len - The original length of the file before the boot info table was patched into it. csum - Th...
def relabel(self, catalogue): """Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping ...
Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type cat...
def patch_lines(x): """ Draw lines between groups """ for idx in range(len(x)-1): x[idx] = np.vstack([x[idx], x[idx+1][0,:]]) return x
Draw lines between groups
def delete_dashboard(self, team_context, dashboard_id): """DeleteDashboard. [Preview API] Delete a dashboard given its ID. This also deletes the widgets associated with this dashboard. :param :class:`<TeamContext> <azure.devops.v5_0.dashboard.models.TeamContext>` team_context: The team context f...
DeleteDashboard. [Preview API] Delete a dashboard given its ID. This also deletes the widgets associated with this dashboard. :param :class:`<TeamContext> <azure.devops.v5_0.dashboard.models.TeamContext>` team_context: The team context for the operation :param str dashboard_id: ID of the dashboa...
def divsin_fc(fdata): """Apply divide by sine in the Fourier domain.""" nrows = fdata.shape[0] ncols = fdata.shape[1] L = int(nrows / 2) # Assuming nrows is even, which it should be. L2 = L - 2 # This is the last index in the recursion for division by sine. g = np.zeros([nrows, ncol...
Apply divide by sine in the Fourier domain.
def get_asset_by_name(self, publisher_name, extension_name, version, asset_type, account_token=None, accept_default=None, account_token_header=None, **kwargs): """GetAssetByName. [Preview API] :param str publisher_name: :param str extension_name: :param str version: :para...
GetAssetByName. [Preview API] :param str publisher_name: :param str extension_name: :param str version: :param str asset_type: :param str account_token: :param bool accept_default: :param String account_token_header: Header to pass the account token ...
def _certifi_where_for_ssl_version(): """Gets the right location for certifi certifications for the current SSL version. Older versions of SSL don't support the stronger set of root certificates. """ if not ssl: return if ssl.OPENSSL_VERSION_INFO < (1, 0, 2): warnings.warn( ...
Gets the right location for certifi certifications for the current SSL version. Older versions of SSL don't support the stronger set of root certificates.
def update_ethernet_settings(self, configuration, force=False, timeout=-1): """ Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any probl...
Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is f...
def is_installed(self, pkgname): """Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool """ return any(d for d in self.get_d...
Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool
def search_article(self, keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None, unlock_callback=None, identify_image_callback=None, decode_u...
搜索 文章 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Para...
async def on_raw_433(self, message): """ Nickname in use. """ if not self.registered: self._registration_attempts += 1 # Attempt to set new nickname. if self._attempt_nicknames: await self.set_nickname(self._attempt_nicknames.pop(0)) else: ...
Nickname in use.