INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Lock thread.
def unlock(self): """Lock thread. Requires that the currently authenticated user has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server. """ url = self.reddit_session.config['unlock'] ...
Unsticky this post.
def unsticky(self): """Unsticky this post. :returns: The json response from the server """ url = self.reddit_session.config['sticky_submission'] data = {'id': self.fullname, 'state': False} return self.reddit_session.request_json(url, data=data)
Remove all user flair on this subreddit.
def clear_all_flair(self): """Remove all user flair on this subreddit. :returns: The json response from the server when there is flair to clear, otherwise returns None. """ csv = [{'user': x['user']} for x in self.get_flair_list(limit=None)] if csv: retu...
Return an instance of the appropriate class from the json dict.
def from_api_response(cls, reddit_session, json_dict): """Return an instance of the appropriate class from the json dict.""" # The Multireddit response contains the Subreddits attribute as a list # of dicts of the form {'name': 'subredditname'}. # We must convert each of these into a Sub...
Add a subreddit to the multireddit.
def add_subreddit(self, subreddit, _delete=False, *args, **kwargs): """Add a subreddit to the multireddit. :param subreddit: The subreddit name or Subreddit object to add The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json`. """ ...
Copy this multireddit.
def copy(self, to_name): """Copy this multireddit. Convenience function that utilizes :meth:`.MultiredditMixin.copy_multireddit` populating both the `from_redditor` and `from_name` parameters. """ return self.reddit_session.copy_multireddit(self._author, self.name, ...
Edit this multireddit.
def edit(self, *args, **kwargs): """Edit this multireddit. Convenience function that utilizes :meth:`.MultiredditMixin.edit_multireddit` populating the `name` parameter. """ return self.reddit_session.edit_multireddit(name=self.name, *args, ...
Remove a subreddit from the user s multireddit.
def remove_subreddit(self, subreddit, *args, **kwargs): """Remove a subreddit from the user's multireddit.""" return self.add_subreddit(subreddit, True, *args, **kwargs)
Rename this multireddit.
def rename(self, new_name, *args, **kwargs): """Rename this multireddit. This function is a handy shortcut to :meth:`rename_multireddit` of the reddit_session. """ new = self.reddit_session.rename_multireddit(self.name, new_name, ...
Return a Redditor object from the data.
def _convert(reddit_session, data): """Return a Redditor object from the data.""" retval = Redditor(reddit_session, data['name'], fetch=False) retval.id = data['id'].split('_')[1] # pylint: disable=C0103,W0201 return retval
Return an instance of the appropriate class from the json_dict.
def from_api_response(cls, reddit_session, json_dict): """Return an instance of the appropriate class from the json_dict.""" # The WikiPage response does not contain the necessary information # in the JSON response to determine the name of the page nor the # subreddit it belongs to. Thus...
Add an editor to this wiki page.
def add_editor(self, username, _delete=False, *args, **kwargs): """Add an editor to this wiki page. :param username: The name or Redditor object of the user to add. :param _delete: If True, remove the user as an editor instead. Please use :meth:`remove_editor` rather than setting it...
Return the settings for this wiki page.
def get_settings(self, *args, **kwargs): """Return the settings for this wiki page. Includes permission level, names of editors, and whether the page is listed on /wiki/pages. Additional parameters are passed into :meth:`~praw.__init__.BaseReddit.request_json` """ ...
Edit the wiki page.
def edit(self, *args, **kwargs): """Edit the wiki page. Convenience function that utilizes :meth:`.AuthenticatedReddit.edit_wiki_page` populating both the ``subreddit`` and ``page`` parameters. """ return self.subreddit.edit_wiki_page(self.page, *args, **kwargs)
Edit the settings for this individual wiki page.
def edit_settings(self, permlevel, listed, *args, **kwargs): """Edit the settings for this individual wiki page. :param permlevel: Who can edit this page? (0) use subreddit wiki permissions, (1) only approved wiki contributors for this page may edit (see :meth:`~praw...
Remove an editor from this wiki page.
def remove_editor(self, username, *args, **kwargs): """Remove an editor from this wiki page. :param username: The name or Redditor object of the user to remove. This method points to :meth:`add_editor` with _delete=True. Additional parameters are are passed to :meth:`add_editor` and ...
Return a WikiPage object from the data.
def _convert(reddit_session, data): """Return a WikiPage object from the data.""" # TODO: The _request_url hack shouldn't be necessary # pylint: disable=W0212 subreddit = reddit_session._request_url.rsplit('/', 4)[1] # pylint: enable=W0212 return WikiPage(reddit_session, ...
Indefinitely yield new comments from the provided subreddit.
def comment_stream(reddit_session, subreddit, limit=None, verbosity=1): """Indefinitely yield new comments from the provided subreddit. Comments are yielded from oldest to newest. :param reddit_session: The reddit_session to make requests from. In all the examples this is assigned to the variable ...
Indefinitely yield new submissions from the provided subreddit.
def submission_stream(reddit_session, subreddit, limit=None, verbosity=1): """Indefinitely yield new submissions from the provided subreddit. Submissions are yielded from oldest to newest. :param reddit_session: The reddit_session to make requests from. In all the examples this is assigned to the ...
Return a verified list of valid Redditor instances.
def valid_redditors(redditors, sub): """Return a verified list of valid Redditor instances. :param redditors: A list comprised of Redditor instances and/or strings that are to be verified as actual redditor accounts. :param sub: A Subreddit instance that the authenticated account has flair ...
Yield submissions between two timestamps.
def submissions_between(reddit_session, subreddit, lowest_timestamp=None, highest_timestamp=None, newest_first=True, extra_cloudsearch_fields=None, verbosity=1): """Yield s...
Given a sequence divide it into sequences of length chunk_length.
def chunk_sequence(sequence, chunk_length, allow_incomplete=True): """Given a sequence, divide it into sequences of length `chunk_length`. :param allow_incomplete: If True, allow final chunk to be shorter if the given sequence is not an exact multiple of `chunk_length`. If False, the incomplete...
Convert strings representing base36 numbers into an integer.
def convert_id36_to_numeric_id(id36): """Convert strings representing base36 numbers into an integer.""" if not isinstance(id36, six.string_types) or id36.count("_") > 0: raise ValueError("must supply base36 string, not fullname (e.g. use " "xxxxx, not t3_xxxxx)") return int...
Convert an integer into its base36 string representation.
def convert_numeric_id_to_id36(numeric_id): """Convert an integer into its base36 string representation. This method has been cleaned up slightly to improve readability. For more info see: https://github.com/reddit/reddit/blob/master/r2/r2/lib/utils/_utils.pyx https://www.reddit.com/r/redditdev/c...
Return a flattened version of the passed in tree.
def flatten_tree(tree, nested_attr='replies', depth_first=False): """Return a flattened version of the passed in tree. :param nested_attr: The attribute name that contains the nested items. Defaults to ``replies`` which is suitable for comments. :param depth_first: When true, add to the list in a d...
Return url after stripping trailing. json and trailing slashes.
def normalize_url(url): """Return url after stripping trailing .json and trailing slashes.""" if url.endswith('.json'): url = url[:-5] if url.endswith('/'): url = url[:-1] return url
Add an item to the set discarding the oldest item if necessary.
def add(self, item): """Add an item to the set discarding the oldest item if necessary.""" if item in self._set: self._fifo.remove(item) elif len(self._set) == self.max_items: self._set.remove(self._fifo.pop(0)) self._fifo.append(item) self._set.add(item)
Downloads an entire table as a zip file.: param str datatable_code: The datatable code to download such as MER/ F1: param str filename: The filename for the download. \ If not specified will download to the current working directory: param str api_key: Most databases require api_key for bulk download
def export_table(datatable_code, **kwargs): """Downloads an entire table as a zip file. :param str datatable_code: The datatable code to download, such as MER/F1 :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key:...
Return dataframe of requested dataset from Quandl.: param dataset: str or list depending on single dataset usage or multiset usage Dataset codes are available on the Quandl website: param str api_key: Downloads are limited to 50 unless api_key is specified: param str start_date end_date: Optional datefilers otherwise e...
def get(dataset, **kwargs): """Return dataframe of requested dataset from Quandl. :param dataset: str or list, depending on single dataset usage or multiset usage Dataset codes are available on the Quandl website :param str api_key: Downloads are limited to 50 unless api_key is specified :pa...
Downloads an entire database.: param str database: The database code to download: param str filename: The filename for the download. \ If not specified will download to the current working directory: param str api_key: Most databases require api_key for bulk download: param str download_type: partial or complete. \ See...
def bulkdownload(database, **kwargs): """Downloads an entire database. :param str database: The database code to download :param str filename: The filename for the download. \ If not specified, will download to the current working directory :param str api_key: Most databases require api_key for bulk...
Map of json - rpc available calls.
def jsonrpc_map(self): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return Response(resul...
通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块
def command(self, cmd, type=None): """ 通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令 gm指令相关功能请参考safaia GM指令扩展模块 :param cmd: 指令 :param type: 语言,默认text :return: None """ type = type or 'text' self.hunter.script(cmd, lang=type)
Add a method to the dispatcher.
def add_method(self, f, name=None): """ Add a method to the dispatcher. Parameters ---------- f : callable Callable to be added. name : str, optional Name to register (the default is function **f** name) Notes ----- When used as a...
Add prototype methods to the dispatcher.
def build_method_map(self, prototype, prefix=''): """ Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispa...
小数据片段拼接成完整数据包 如果内容足够则yield数据包
def input(self, data): """ 小数据片段拼接成完整数据包 如果内容足够则yield数据包 """ self.buf += data while len(self.buf) > HEADER_SIZE: data_len = struct.unpack('i', self.buf[0:HEADER_SIZE])[0] if len(self.buf) >= data_len + HEADER_SIZE: content = self.buf[HE...
content should be str
def pack(content): """ content should be str """ if isinstance(content, six.text_type): content = content.encode("utf-8") return struct.pack('i', len(content)) + content
return length content
def unpack(data): """ return length, content """ length = struct.unpack('i', data[0:HEADER_SIZE]) return length[0], data[HEADER_SIZE:]
Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment (). A fragment stream is completed when sendFragmentEnd () is called.
def sendFragmentStart(self, data): """ Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame...
Send websocket data frame to the client.
def sendMessage(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if _check_unicode(data): ...
将HRpcRemoteException. NodeHasBeenRemovedException转换成PocoTargetRemovedException
def transform_node_has_been_removed_exception(func): """ 将HRpcRemoteException.NodeHasBeenRemovedException转换成PocoTargetRemovedException :param func: 仅限getattr和setattr两个接口方法 :return: """ @wraps(func) def wrapped(self, nodes, name, *args, **kwargs): """ :param self: ...
Handle request data.
def handle_request(cls, request, dispatcher): """ Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 """ rs = reques...
Response to each single JSON - RPC Request.
def _get_responses(cls, requests, dispatcher): """ Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. """ for request in requests: def r...
JSON - RPC 2. 0 handler.
def jsonrpc(self, request): """ JSON-RPC 2.0 handler.""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) request_str = request.body.decode('utf8') try: jsonrpc_request = JSONRPCRequest.from_json(request_str) except (TypeError, ValueEr...
Map of json - rpc available calls.
def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return HttpR...
Sample this motion track into discretized motion events.
def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): """ Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference """ if not s...
Dump a hierarchy immediately from target runtime and store into a Node ( subclass of: py: class: AbstractNode <poco. sdk. AbstractNode > ) object.
def getRoot(self): """ Dump a hierarchy immediately from target runtime and store into a Node (subclass of :py:class:`AbstractNode <poco.sdk.AbstractNode>`) object. Returns: :py:class:`inherit from AbstractNode <Node>`: Each time a new node instance is created by latest hie...
Check whether function func accepts parameters args kwargs.
def is_invalid_params(func, *args, **kwargs): """ Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. ...
Get the top level element for the application with the specified bundle ID such as com. vmware. fusion.
def getAppRefByBundleId(cls, bundleId): """ Get the top level element for the application with the specified bundle ID, such as com.vmware.fusion. """ ra = AppKit.NSRunningApplication # return value (apps) is always an array. if there is a match it will # have an ...
Return the driver of this agent related to. None if the driver is not ready to bind.
def driver(self): """ Return the driver of this agent related to. None if the driver is not ready to bind. Returns: :py:class:`inherit from Poco <poco.pocofw.Poco>`: the driver of this agent related to. """ if not self._driver: raise AttributeError("`dri...
Crawl the hierarchy tree using the simple DFS algorithm. The dump procedure is the engine independent as the hierarchy structure is wrapped by: py: class: AbstractNode <poco. sdk. AbstractNode > and therefore the dump procedure can be algorithmized.
def dumpHierarchyImpl(self, node, onlyVisibleNode=True): """ Crawl the hierarchy tree using the simple DFS algorithm. The ``dump`` procedure is the engine independent as the hierarchy structure is wrapped by :py:class:`AbstractNode <poco.sdk.AbstractNode>` and therefore the ``dump`` proc...
Select the direct child ( ren ) from the UI element ( s ) given by the query expression see QueryCondition for more details about the selectors.
def child(self, name=None, **attrs): """ Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for more details about the selectors. Args: name: query expression of attribute "name", i.e. the UI elements with ``name`` name ...
Select the direct child ( ren ) from the UI element ( s ) given by the query expression see QueryCondition for more details about the selectors.
def parent(self): """ Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for more details about the selectors. Warnings: Experimental method, may not be available for all drivers. Returns: :py:class:...
Perform the click action on the UI element ( s ) represented by the UI proxy. If this UI proxy represents a set of UI elements the first one in the set is clicked and the anchor point of the UI element is used as the default one. It is also possible to click another point offset by providing focus argument.
def click(self, focus=None, sleep_interval=None): """ Perform the click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default one. It is ...
Perform the long click action on the UI element ( s ) represented by the UI proxy. If this UI proxy represents a set of UI elements the first one in the set is clicked and the anchor point of the UI element is used as the default one. Similar to click but press the screen for the given time interval and then release. A...
def long_click(self, duration=2.0): """ Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the default one. Similar to cl...
Perform a swipe action given by the direction from this UI element. For notices and limitations see: py: meth:. click () <poco. proxy. UIObjectProxy. click >.
def swipe(self, direction, focus=None, duration=0.5): """ Perform a swipe action given by the direction from this UI element. For notices and limitations see :py:meth:`.click() <poco.proxy.UIObjectProxy.click>`. Args: direction (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): co...
Similar to swipe action but the end point is provide by a UI proxy or by fixed coordinates.
def drag_to(self, target, duration=2.0): """ Similar to swipe action, but the end point is provide by a UI proxy or by fixed coordinates. Args: target (:py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`): a UI proxy or 2-list/2-tuple coordinates (x, y) in NormalizedCo...
Simply touch down from point A and move to point B then release up finally. This action is performed within specific motion range and duration.
def scroll(self, direction='vertical', percent=0.6, duration=2.0): """ Simply touch down from point A and move to point B then release up finally. This action is performed within specific motion range and duration. Args: direction (:py:obj:`str`): scrolling direction. "verti...
Squeezing or expanding 2 fingers on this UI with given motion range and duration.
def pinch(self, direction='in', percent=0.6, duration=2.0, dead_zone=0.1): """ Squeezing or expanding 2 fingers on this UI with given motion range and duration. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding ...
Get a new UI proxy copy with the given focus. Return a new UI proxy object as the UI proxy is immutable.
def focus(self, f): """ Get a new UI proxy copy with the given focus. Return a new UI proxy object as the UI proxy is immutable. Args: f (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): the focus point, it can be specified as 2-list/2-tuple coordinates (x, y) in NormalizedCoo...
Get the position of the UI elements.
def get_position(self, focus=None): """ Get the position of the UI elements. Args: focus: focus point of UI proxy, see :py:meth:`.focus() <poco.proxy.UIObjectProxy.focus>` for more details Returns: 2-list/2-tuple: coordinates (x, y) in NormalizedCoordinate syst...
Block and wait for max given time before the UI element appears.
def wait(self, timeout=3): """ Block and wait for max given time before the UI element appears. Args: timeout: maximum waiting time in seconds Returns: :py:class:`UIObjectProxy <poco.proxy.UIObjectProxy>`: self """ start = time.time() wh...
Block and wait until the UI element ** disappears ** within the given timeout.
def wait_for_disappearance(self, timeout=120): """ Block and wait until the UI element **disappears** within the given timeout. Args: timeout: maximum waiting time in seconds Raises: PocoTargetTimeout: when timeout """ start = time.time() ...
Retrieve the attribute of UI element by given attribute name. Return None if attribute does not exist. If attribute type is: obj: str it is encoded to utf - 8 as: obj: str in Python2. 7.
def attr(self, name): """ Retrieve the attribute of UI element by given attribute name. Return None if attribute does not exist. If attribute type is :obj:`str`, it is encoded to utf-8 as :obj:`str` in Python2.7. Args: name: attribute name, it can be one of ...
Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the immutable attributes or attributes which do not exist the InvalidOperationException exception is raised.
def setattr(self, name, val): """ Change the attribute value of the UI element. Not all attributes can be casted to text. If changing the immutable attributes or attributes which do not exist, the InvalidOperationException exception is raised. Args: name: attribute name ...
Get the parameters of bounding box of the UI element.
def get_bounds(self): """ Get the parameters of bounding box of the UI element. Returns: :obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in NormalizedCoordinate system """ size = self.get_size() ...
Args: origin (: obj: str ): original string pattern (: obj: str ): Regexp pattern string
def compare(self, origin, pattern): """ Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False. """ if origin is None or pattern is None: return False ...
See Also:: py: meth: IMatcher. match <poco. sdk. DefaultMatcher. IMatcher. match >
def match(self, cond, node): """ See Also: :py:meth:`IMatcher.match <poco.sdk.DefaultMatcher.IMatcher.match>` """ op, args = cond # 条件匹配 if op == 'and': for arg in args: if not self.match(arg, node): return False ...
Wait until any of given UI proxies show up before timeout and return the first appeared UI proxy. All UI proxies will be polled periodically. See options: py: class: poll_interval <poco. pocofw. Poco > in Poco s initialization for more details.
def wait_for_any(self, objects, timeout=120): """ Wait until any of given UI proxies show up before timeout and return the first appeared UI proxy. All UI proxies will be polled periodically. See options :py:class:`poll_interval <poco.pocofw.Poco>` in ``Poco``'s initialization for more d...
Wait until all of given UI proxies show up before timeout. All UI proxies will be polled periodically. See option: py: class: poll_interval <poco. pocofw. Poco > in Poco s initialization for more details.
def wait_for_all(self, objects, timeout=120): """ Wait until all of given UI proxies show up before timeout. All UI proxies will be polled periodically. See option :py:class:`poll_interval <poco.pocofw.Poco>` in ``Poco``'s initialization for more details. Args: obje...
Snapshot current ** hierarchy ** and cache it into a new poco instance. This new poco instance is a copy from current poco instance ( self ). The hierarchy of the new poco instance is fixed and immutable. It will be super fast when calling dump function from frozen poco. See the example below. Examples:::
def freeze(this): """ Snapshot current **hierarchy** and cache it into a new poco instance. This new poco instance is a copy from current poco instance (``self``). The hierarchy of the new poco instance is fixed and immutable. It will be super fast when calling ``dump`` function from fro...
Perform click ( touch tap etc. ) action on target device at given coordinates.
def click(self, pos): """ Perform click (touch, tap, etc.) action on target device at given coordinates. The coordinates (x, y) are either a 2-list or 2-tuple. The coordinates values for x and y must be in the interval between 0 ~ 1 to represent the percentage of the screen. For example...
Perform swipe action on target device from point to point given by start point and end point or by the direction vector. At least one of the end point or direction must be provided.
def swipe(self, p1, p2=None, direction=None, duration=2.0): """ Perform swipe action on target device from point to point given by start point and end point, or by the direction vector. At least one of the end point or direction must be provided. The coordinates (x, y) definition for po...
Similar to click but press the screen for the given time interval and then release
def long_click(self, pos, duration=2.0): """ Similar to click but press the screen for the given time interval and then release Args: pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1 duration: duration of press the screen """ try: ...
Scroll from the lower part to the upper part of the entire screen.
def scroll(self, direction='vertical', percent=0.6, duration=2.0): """ Scroll from the lower part to the upper part of the entire screen. Args: direction (:py:obj:`str`): scrolling direction. "vertical" or "horizontal" percent (:py:obj:`float`): scrolling distance percen...
Squeezing or expanding 2 fingers on the entire screen.
def pinch(self, direction='in', percent=0.6, duration=2.0, dead_zone=0.1): """ Squeezing or expanding 2 fingers on the entire screen. Args: direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding percent (:py:obj:`float`...
Similar to click but press the screen for the given time interval and then release
def apply_motion_tracks(self, tracks, accuracy=0.004): """ Similar to click but press the screen for the given time interval and then release Args: tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object accuracy (:py:obj:`float`): motion accuracy ...
This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the current device instance provided by airtest to get the AndroidUiautomationPoco instance. If no such AndroidUiautomationPoco instance a new instance will be created and stored.
def get_instance(cls, device): """ This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance. If no such AndroidUiautomatio...
Automatically dismiss the target objects
def dismiss(self, targets, exit_when=None, sleep_interval=0.5, appearance_timeout=20, timeout=120): """ Automatically dismiss the target objects Args: targets (:obj:`list`): list of poco objects to be dropped exit_when: termination condition, default is None which means ...
See Also:: py: meth: select <poco. sdk. Selector. ISelector. select > method in ISelector.
def select(self, cond, multiple=False): """ See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. """ return self.selectImpl(cond, multiple, self.getRoot(), 9999, True, True)
Selector internal implementation. TODO: add later.
def selectImpl(self, cond, multiple, root, maxDepth, onlyVisibleNode, includeRoot): """ Selector internal implementation. TODO: add later. .. note:: This doc shows only the outline of the algorithm. Do not call this method in your code as this is an internal method. A...
Get API key details.
def find_by_id(key: str, user: str=None) -> Optional['ApiKey']: """ Get API key details. """ return ApiKey.from_db(db.get_key(key, user))
List all API keys.
def find_all(query: Query=None) -> List['ApiKey']: """ List all API keys. """ return [ApiKey.from_db(key) for key in db.get_keys(query)]
List API keys for a user.
def find_by_user(user: str) -> List['ApiKey']: """ List API keys for a user. """ return [ApiKey.from_db(key) for key in db.get_keys(qb.from_dict({'user': user}))]
Create an admin API key.
def key(username, key, all): """Create an admin API key.""" if username and username not in current_app.config['ADMIN_USERS']: raise click.UsageError('User {} not an admin'.format(username)) def create_key(admin, key): key = ApiKey( user=admin, key=key, s...
List admin API keys.
def keys(): """List admin API keys.""" for admin in current_app.config['ADMIN_USERS']: try: db.get_db() # init db on global app context keys = ApiKey.find_by_user(admin) except Exception as e: click.echo('ERROR: {}'.format(e)) else: for ke...
Create admin users ( BasicAuth only ).
def user(username, password, all): """Create admin users (BasicAuth only).""" if current_app.config['AUTH_PROVIDER'] != 'basic': raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER'])) if username and username not in current_app.config['ADMIN_USERS']: ...
List admin users.
def users(): """List admin users.""" for admin in current_app.config['ADMIN_USERS']: try: db.get_db() # init db on global app context user = User.find_by_username(admin) except Exception as e: click.echo('ERROR: {}'.format(e)) else: if use...
Get severity of correlated alert. Used to determine previous severity.
def get_severity(self, alert): """ Get severity of correlated alert. Used to determine previous severity. """ query = { 'environment': alert.environment, 'resource': alert.resource, '$or': [ { 'event': alert.event, ...
Return true if alert severity has changed more than X times in Y seconds
def is_flapping(self, alert, window=1800, count=2): """ Return true if alert severity has changed more than X times in Y seconds """ pipeline = [ {'$match': { 'environment': alert.environment, 'resource': alert.resource, 'event'...
Update alert status service value text timeout and rawData increment duplicate count and set repeat = True and keep track of last receive id and time but don t append to history unless status changes.
def dedup_alert(self, alert, history): """ Update alert status, service, value, text, timeout and rawData, increment duplicate count and set repeat=True, and keep track of last receive id and time but don't append to history unless status changes. """ query = { 'envir...
Update alert key attributes reset duplicate count and set repeat = False keep track of last receive id and time appending all to history. Append to history again if status changes.
def correlate_alert(self, alert, history): """ Update alert key attributes, reset duplicate count and set repeat=False, keep track of last receive id and time, appending all to history. Append to history again if status changes. """ query = { 'environment': alert.envi...
Set status and update history.
def set_status(self, id, status, timeout, update_time, history=None): """ Set status and update history. """ query = {'_id': {'$regex': '^' + id}} update = { '$set': {'status': status, 'timeout': timeout, 'updateTime': update_time}, '$push': { ...
Append tags to tag list. Don t add same tag more than once.
def tag_alert(self, id, tags): """ Append tags to tag list. Don't add same tag more than once. """ response = self.get_db().alerts.update_one( {'_id': {'$regex': '^' + id}}, {'$addToSet': {'tags': {'$each': tags}}}) return response.matched_count > 0
Set all attributes and unset attributes by using a value of null.
def update_attributes(self, id, old_attrs, new_attrs): """ Set all attributes and unset attributes by using a value of 'null'. """ update = dict() set_value = {'attributes.' + k: v for k, v in new_attrs.items() if v is not None} if set_value: update['$set'] = ...
Return total number of alerts that meet the query filter.
def get_count(self, query=None): """ Return total number of alerts that meet the query filter. """ query = query or Query() return self.get_db().alerts.find(query.where).count()
Set all attributes and unset attributes by using a value of null.
def update_user_attributes(self, id, old_attrs, new_attrs): """ Set all attributes and unset attributes by using a value of 'null'. """ from alerta.utils.collections import merge merge(old_attrs, new_attrs) attrs = {k: v for k, v in old_attrs.items() if v is not None} ...
Does this alert match a blackout period?
def is_blackout(self) -> bool: """Does this alert match a blackout period?""" if not current_app.config['NOTIFICATION_BLACKOUT']: if self.severity in current_app.config['BLACKOUT_ACCEPT']: return False return db.is_blackout_period(self)
should return internal id of external system
def take_action(self, alert, action, text, **kwargs): """should return internal id of external system""" BASE_URL = '{}/projects/{}'.format(GITLAB_URL, quote(GITLAB_PROJECT_ID, safe='')) if action == 'createIssue': if 'issue_iid' not in alert.attributes: url = BASE_...
Wraps JSONified output for JSONP requests.
def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mim...
Return true if alert severity has changed more than X times in Y seconds
def is_flapping(self, alert, window=1800, count=2): """ Return true if alert severity has changed more than X times in Y seconds """ select = """ SELECT COUNT(*) FROM alerts, unnest(history) h WHERE environment=%(environment)s AND res...