Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''): content_id_from = self.get_post(duplicated_cid)["id"] content_id_to = self.get_post(master_cid)["id"] params = { "cid_dupe": content_id_from, "cid_to": c...
[ "Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid``\n\n :type duplicated_cid: int\n :param duplicated_cid: The numeric id of the duplicated post\n :type master_cid: int\n :param master_cid: The numeric id of an older post. This will be the\n post that gets ...
Please provide a description of the function:def resolve_post(self, post): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "resolved": "true" } return self._rpc.content_mark_resolved(params)
[ "Mark post as resolved\n\n :type post: dict|str|int\n :param post: Either the post dict returned by another API method, or\n the `cid` field of that post.\n :returns: True if it is successful. False otherwise\n " ]
Please provide a description of the function:def pin_post(self, post): try: cid = post['id'] except KeyError: cid = post params = { "cid": cid, } return self._rpc.content_pin(params)
[ "Pin post\n\n :type post: dict|str|int\n :param post: Either the post dict returned by another API method, or\n the `cid` field of that post.\n :returns: True if it is successful. False otherwise\n " ]
Please provide a description of the function:def delete_post(self, post): try: cid = post['id'] except KeyError: cid = post except TypeError: post = self.get_post(post) cid = post['id'] params = { "cid": cid, ...
[ " Deletes post by cid\n\n :type post: dict|str|int\n :param post: Either the post dict returned by another API method, the post ID, or\n the `cid` field of that post.\n :rtype: dict\n :returns: Dictionary with information about the post cid.\n " ]
Please provide a description of the function:def get_feed(self, limit=100, offset=0): return self._rpc.get_my_feed(limit=limit, offset=offset)
[ "Get your feed for this network\n\n Pagination for this can be achieved by using the ``limit`` and\n ``offset`` params\n\n :type limit: int\n :param limit: Number of posts from feed to get, starting from ``offset``\n :type offset: int\n :param offset: Offset starting from b...
Please provide a description of the function:def get_filtered_feed(self, feed_filter): assert isinstance(feed_filter, (UnreadFilter, FollowingFilter, FolderFilter)) return self._rpc.filter_feed(**feed_filter.to_kwargs())
[ "Get your feed containing only posts filtered by ``feed_filter``\n\n :type feed_filter: FeedFilter\n :param feed_filter: Must be an instance of either: UnreadFilter,\n FollowingFilter, or FolderFilter\n :rtype: dict\n " ]
Please provide a description of the function:def get_all_datasets(self): success = True for dataset in tqdm(self.datasets): individual_success = self.get_dataset(dataset) if not individual_success: success = False return success
[ "\n Make sure the datasets are present. If not, downloads and extracts them.\n Attempts the download five times because the file hosting is unreliable.\n :return: True if successful, false otherwise\n " ]
Please provide a description of the function:def get_dataset(self, dataset): # If the dataset is present, no need to download anything. success = True dataset_path = self.base_dataset_path + dataset if not isdir(dataset_path): # Try 5 times to download. The download...
[ "\n Checks to see if the dataset is present. If not, it downloads and unzips it.\n " ]
Please provide a description of the function:def get_raw(self, verbose=True): assert self.get_all_datasets() is True, "Datasets aren't properly downloaded, " \ "rerun to try again or download datasets manually." for dataset in self.datasets: ...
[ "\n Used to create easily introspectable image directories of all the data.\n :return:\n " ]
Please provide a description of the function:def load_character_images(self, verbose=True): for dataset in self.character_sets: assert self.get_dataset(dataset) is True, "Datasets aren't properly downloaded, " \ "rerun to try again or do...
[ "\n Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.\n :return: (Pillow.Image.Image, string) tuples\n " ]
Please provide a description of the function:def load_dataset(self, dataset, verbose=True): assert self.get_dataset(dataset) is True, "Datasets aren't properly downloaded, " \ "rerun to try again or download datasets manually." if verbose: ...
[ "\n Load a directory of gnt files. Yields the image and label in tuples.\n :param dataset: The directory to load.\n :return: Yields (Pillow.Image.Image, label) pairs.\n " ]
Please provide a description of the function:def load_gnt_file(filename): # Thanks to nhatch for the code to read the GNT file, available at https://github.com/nhatch/casia with open(filename, "rb") as f: while True: packed_length = f.read(4) if pack...
[ "\n Load characters and images from a given GNT file.\n :param filename: The file path to load.\n :return: (image: Pillow.Image.Image, character) tuples\n " ]
Please provide a description of the function:def middleware(self, *args, **kwargs): kwargs.setdefault('priority', 5) kwargs.setdefault('relative', None) kwargs.setdefault('attach_to', None) kwargs.setdefault('with_context', False) if len(args) == 1 and callable(args[0]):...
[ "Decorate and register middleware\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any)\n :return: The middleware function to use as the decorator\n :rty...
Please provide a description of the function:def exception(self, *args, **kwargs): if len(args) == 1 and callable(args[0]): if isinstance(args[0], type) and issubclass(args[0], Exception): pass else: # pragma: no cover raise RuntimeError("Cannot ...
[ "Decorate and register an exception handler\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any)\n :return: The exception function to use as the decorator\n ...
Please provide a description of the function:def listener(self, event, *args, **kwargs): if len(args) == 1 and callable(args[0]): # pragma: no cover raise RuntimeError("Cannot use the @listener decorator without " "arguments") def wrapper(listener_f)...
[ "Create a listener from a decorated function.\n :param event: Event to listen to.\n :type event: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any...
Please provide a description of the function:def route(self, uri, *args, **kwargs): if len(args) == 0 and callable(uri): # pragma: no cover raise RuntimeError("Cannot use the @route decorator without " "arguments.") kwargs.setdefault('methods', frozen...
[ "Create a plugin route from a decorated function.\n :param uri: endpoint at which the route will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n ...
Please provide a description of the function:def websocket(self, uri, *args, **kwargs): kwargs.setdefault('host', None) kwargs.setdefault('strict_slashes', None) kwargs.setdefault('subprotocols', None) kwargs.setdefault('name', None) def wrapper(handler_f): ...
[ "Create a websocket route from a decorated function\n :param uri: endpoint at which the socket endpoint will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments p...
Please provide a description of the function:def static(self, uri, file_or_directory, *args, **kwargs): kwargs.setdefault('pattern', r'/?.+') kwargs.setdefault('use_modified_since', True) kwargs.setdefault('use_content_range', False) kwargs.setdefault('stream_large_files', Fals...
[ "Create a websocket route from a decorated function\n :param uri: endpoint at which the socket endpoint will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments p...
Please provide a description of the function:def first_plugin_context(self): # Note, because registrations are stored in a set, its not _really_ # the first one, but whichever one it sees first in the set. first_spf_reg = next(iter(self.registrations)) return self.get_context_fr...
[ "Returns the context is associated with the first app this plugin was\n registered on" ]
Please provide a description of the function:def decorate(cls, app, *args, run_middleware=False, with_context=False, **kwargs): from spf.framework import SanicPluginsFramework spf = SanicPluginsFramework(app) # get the singleton from the app try: assoc = sp...
[ "\n This is a decorator that can be used to apply this plugin to a specific\n route/view on your app, rather than the whole app.\n :param app:\n :type app: Sanic | Blueprint\n :param args:\n :type args: tuple(Any)\n :param run_middleware:\n :type run_middlewar...
Please provide a description of the function:async def route_wrapper(self, route, request, context, request_args, request_kw, *decorator_args, with_context=None, **decorator_kw): # by default, do nothing, just run the wrapped function if w...
[ "This is the function that is called when a route is decorated with\n your plugin decorator. Context will normally be None, but the user\n can pass use_context=True so the route will get the plugin\n context\n " ]
Please provide a description of the function:def replace(self, key, value): if key in self._inner().keys(): return self.__setitem__(key, value) parents_searched = [self] parent = self._parent_context while parent: try: if key in parent.key...
[ "\n If this ContextDict doesn't already have this key, it sets\n the value on a parent ContextDict if that parent has the key,\n otherwise sets the value on this ContextDict.\n :param key:\n :param value:\n :return: Nothing\n :rtype: None\n " ]
Please provide a description of the function:def update(self, E=None, **F): if E is not None: if hasattr(E, 'keys'): for K in E: self.replace(K, E[K]) elif hasattr(E, 'items'): for K, V in E.items(): self.re...
[ "\n Update ContextDict from dict/iterable E and F\n :return: Nothing\n :rtype: None\n " ]
Please provide a description of the function:def middleware(self, *args, **kwargs): kwargs.setdefault('priority', 5) kwargs.setdefault('relative', None) kwargs.setdefault('attach_to', None) kwargs['with_context'] = True # This is the whole point of this plugin plugin = ...
[ "Decorate and register middleware\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any)\n :return: The middleware function to use as the decorator\n :rty...
Please provide a description of the function:def route(self, uri, *args, **kwargs): if len(args) == 0 and callable(uri): raise RuntimeError("Cannot use the @route decorator without " "arguments.") kwargs.setdefault('methods', frozenset({'GET'})) ...
[ "Create a plugin route from a decorated function.\n :param uri: endpoint at which the route will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n ...
Please provide a description of the function:def listener(self, event, *args, **kwargs): if len(args) == 1 and callable(args[0]): raise RuntimeError("Cannot use the @listener decorator without " "arguments") kwargs['with_context'] = True # This is the...
[ "Create a listener from a decorated function.\n :param event: Event to listen to.\n :type event: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any...
Please provide a description of the function:def websocket(self, uri, *args, **kwargs): kwargs.setdefault('host', None) kwargs.setdefault('strict_slashes', None) kwargs.setdefault('subprotocols', None) kwargs.setdefault('name', None) kwargs['with_context'] = True # Thi...
[ "Create a websocket route from a decorated function\n :param uri: endpoint at which the socket endpoint will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments p...
Please provide a description of the function:def middleware(self, *args, **kwargs): kwargs.setdefault('priority', 5) kwargs.setdefault('relative', None) kwargs.setdefault('attach_to', None) kwargs['with_context'] = True # This is the whole point of this plugin if len(ar...
[ "Decorate and register middleware\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any)\n :return: The middleware function to use as the decorator\n :rty...
Please provide a description of the function:def route(self, uri, *args, **kwargs): if len(args) == 0 and callable(uri): raise RuntimeError("Cannot use the @route decorator without " "arguments.") kwargs.setdefault('methods', frozenset({'GET'})) ...
[ "Create a plugin route from a decorated function.\n :param uri: endpoint at which the route will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n ...
Please provide a description of the function:def listener(self, event, *args, **kwargs): if len(args) == 1 and callable(args[0]): raise RuntimeError("Cannot use the @listener decorator without " "arguments") kwargs['with_context'] = True # This is the...
[ "Create a listener from a decorated function.\n :param event: Event to listen to.\n :type event: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments passed in\n :type kwargs: dict(Any...
Please provide a description of the function:def websocket(self, uri, *args, **kwargs): kwargs.setdefault('host', None) kwargs.setdefault('strict_slashes', None) kwargs.setdefault('subprotocols', None) kwargs.setdefault('name', None) kwargs['with_context'] = True # Thi...
[ "Create a websocket route from a decorated function\n :param uri: endpoint at which the socket endpoint will be accessible.\n :type uri: str\n :param args: captures all of the positional arguments passed in\n :type args: tuple(Any)\n :param kwargs: captures the keyword arguments p...
Please provide a description of the function:def get_peercred(sock): buf = sock.getsockopt(_PEERCRED_LEVEL, _PEERCRED_OPTION, struct.calcsize('3i')) return struct.unpack('3i', buf)
[ "Gets the (pid, uid, gid) for the client on the given *connected* socket." ]
Please provide a description of the function:def check_credentials(client): pid, uid, gid = get_peercred(client) euid = os.geteuid() client_name = "PID:%s UID:%s GID:%s" % (pid, uid, gid) if uid not in (0, euid): raise SuspiciousClient("Can't accept client with %s. It doesn't match the cur...
[ "\n Checks credentials for given socket.\n " ]
Please provide a description of the function:def handle_connection_exec(client): class ExitExecLoop(Exception): pass def exit(): raise ExitExecLoop() client.settimeout(None) fh = os.fdopen(client.detach() if hasattr(client, 'detach') else client.fileno()) with closing(client)...
[ "\n Alternate connection handler. No output redirection.\n " ]
Please provide a description of the function:def handle_connection_repl(client): client.settimeout(None) # # disable this till we have evidence that it's needed # client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 0) # # Note: setting SO_RCVBUF on UDS has no effect, see: http://man7.org/linux/m...
[ "\n Handles connection.\n " ]
Please provide a description of the function:def handle_repl(locals): dump_stacktraces() namespace = { 'dump_stacktraces': dump_stacktraces, 'sys': sys, 'os': os, 'socket': socket, 'traceback': traceback, } if locals: namespace.update(locals) Manh...
[ "\n Dumps stacktraces and runs an interactive prompt (REPL).\n " ]
Please provide a description of the function:def install(verbose=True, verbose_destination=sys.__stderr__.fileno() if hasattr(sys.__stderr__, 'fileno') else sys.__stderr__, strict=True, **kwargs): # pylint: disable=W0603 global _MANHOLE with _LOCK: if _MANHO...
[ "\n Installs the manhole.\n\n Args:\n verbose (bool): Set it to ``False`` to squelch the logging.\n verbose_destination (file descriptor or handle): Destination for verbose messages. Default is unbuffered stderr\n (stderr ``2`` file descriptor).\n patch_fork (bool): Set it to `...
Please provide a description of the function:def dump_stacktraces(): lines = [] for thread_id, stack in sys._current_frames().items(): # pylint: disable=W0212 lines.append("\n######### ProcessID=%s, ThreadID=%s #########" % ( os.getpid(), thread_id )) for filename, line...
[ "\n Dumps thread ids and tracebacks to stdout.\n " ]
Please provide a description of the function:def clone(self, **kwargs): return ManholeThread( self.get_socket, self.sigmask, self.start_timeout, connection_handler=self.connection_handler, daemon_connection=self.daemon_connection, **kwargs )
[ "\n Make a fresh thread with the same options. This is usually used on dead threads.\n " ]
Please provide a description of the function:def run(self): self.serious.set() if signalfd and self.sigmask: signalfd.sigprocmask(signalfd.SIG_BLOCK, self.sigmask) pthread_setname_np(self.ident, self.psname) if self.bind_delay: _LOG("Delaying UDS binding...
[ "\n Runs the manhole loop. Only accepts one connection at a time because:\n\n * This thread is a daemon thread (exits when main thread exists).\n * The connection need exclusive access to stdin, stderr and stdout so it can redirect inputs and outputs.\n " ]
Please provide a description of the function:def reinstall(self): with _LOCK: if not (self.thread.is_alive() and self.thread in _ORIGINAL__ACTIVE): self.thread = self.thread.clone(bind_delay=self.reinstall_delay) if self.should_restart: se...
[ "\n Reinstalls the manhole. Checks if the thread is running. If not, it starts it again.\n " ]
Please provide a description of the function:def patched_fork(self): pid = self.original_os_fork() if not pid: _LOG('Fork detected. Reinstalling Manhole.') self.reinstall() return pid
[ "Fork a child process." ]
Please provide a description of the function:def patched_forkpty(self): pid, master_fd = self.original_os_forkpty() if not pid: _LOG('Fork detected. Reinstalling Manhole.') self.reinstall() return pid, master_fd
[ "Fork a new process with a new pseudo-terminal as controlling tty." ]
Please provide a description of the function:def update( # noqa: C901 self, alert_condition_nrql_id, policy_id, name=None, threshold_type=None, query=None, since_value=None, terms=None, expected_groups=None, value_function=None, runbook_url=None, ignore_overlap=None, enabled=True): ...
[ "\n Updates any of the optional parameters of the alert condition nrql\n\n :type alert_condition_nrql_id: int\n :param alert_condition_nrql_id: Alerts condition NRQL id to update\n\n :type policy_id: int\n :param policy_id: Alert policy id where target alert condition belongs to\n...
Please provide a description of the function:def create( self, policy_id, name, threshold_type, query, since_value, terms, expected_groups=None, value_function=None, runbook_url=None, ignore_overlap=None, enabled=True): data = { 'nrql_condition': { ...
[ "\n Creates an alert condition nrql\n\n :type policy_id: int\n :param policy_id: Alert policy id where target alert condition nrql belongs to\n\n :type name: str\n :param name: The name of the alert\n\n :type threshold_type: str\n :param type: The threshold_type of t...
Please provide a description of the function:def delete(self, alert_condition_nrql_id): return self._delete( url='{0}alerts_nrql_conditions/{1}.json'.format(self.URL, alert_condition_nrql_id), headers=self.headers )
[ "\n This API endpoint allows you to delete an alert condition nrql\n\n :type alert_condition_nrql_id: integer\n :param alert_condition_nrql_id: Alert Condition ID\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n {\n \"nrql_condition\": {\n...
Please provide a description of the function:def list(self, filter_name=None, filter_ids=None, filter_labels=None, page=None): label_param = '' if filter_labels: label_param = ';'.join(['{}:{}'.format(label, value) for label, value in filter_labels.items()]) filters = [ ...
[ "\n This API endpoint returns a paginated list of the Servers\n associated with your New Relic account. Servers can be filtered\n by their name or by a list of server IDs.\n\n :type filter_name: str\n :param filter_name: Filter by server name\n\n :type filter_ids: list of i...
Please provide a description of the function:def update(self, id, name=None): nr_data = self.show(id)['server'] data = { 'server': { 'name': name or nr_data['name'], } } return self._put( url='{0}servers/{1}.json'.format(self...
[ "\n Updates any of the optional parameters of the server\n\n :type id: int\n :param id: Server ID\n\n :type name: str\n :param name: The name of the server\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {\n \"serv...
Please provide a description of the function:def metric_names(self, id, name=None, page=None): params = [ 'name={0}'.format(name) if name else None, 'page={0}'.format(page) if page else None ] return self._get( url='{0}servers/{1}/metrics.json'.forma...
[ "\n Return a list of known metrics and their value names for the given resource.\n\n :type id: int\n :param id: Server ID\n\n :type name: str\n :param name: Filter metrics by name\n\n :type page: int\n :param page: Pagination index\n\n :rtype: dict\n :r...
Please provide a description of the function:def create(self, name, incident_preference): data = { "policy": { "name": name, "incident_preference": incident_preference } } return self._post( url='{0}alerts_policies.js...
[ "\n This API endpoint allows you to create an alert policy\n\n :type name: str\n :param name: The name of the policy\n\n :type incident_preference: str\n :param incident_preference: Can be PER_POLICY, PER_CONDITION or\n PER_CONDITION_AND_TARGET\n\n :rtype: dict\n...
Please provide a description of the function:def update(self, id, name, incident_preference): data = { "policy": { "name": name, "incident_preference": incident_preference } } return self._put( url='{0}alerts_policies...
[ "\n This API endpoint allows you to update an alert policy\n\n :type id: integer\n :param id: The id of the policy\n\n :type name: str\n :param name: The name of the policy\n\n :type incident_preference: str\n :param incident_preference: Can be PER_POLICY, PER_CONDIT...
Please provide a description of the function:def delete(self, id): return self._delete( url='{0}alerts_policies/{1}.json'.format(self.URL, id), headers=self.headers )
[ "\n This API endpoint allows you to delete an alert policy\n\n :type id: integer\n :param id: The id of the policy\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {\n \"policy\": {\n \"created_at\": \"time\",\...
Please provide a description of the function:def associate_with_notification_channel(self, id, channel_id): return self._put( url='{0}alerts_policy_channels.json?policy_id={1}&channel_ids={2}'.format( self.URL, id, channel_id ), ...
[ "\n This API endpoint allows you to associate an alert policy with an\n notification channel\n\n :type id: integer\n :param id: The id of the policy\n\n :type channel_id: integer\n :param channel_id: The id of the notification channel\n\n :rtype: dict\n :r...
Please provide a description of the function:def dissociate_from_notification_channel(self, id, channel_id): return self._delete( url='{0}alerts_policy_channels.json?policy_id={1}&channel_id={2}'.format( self.URL, id, channel_id )...
[ "\n This API endpoint allows you to dissociate an alert policy from an\n notification channel\n\n :type id: integer\n :param id: The id of the policy\n\n :type channel_id: integer\n :param channel_id: The id of the notification channel\n\n :rtype: dict\n :...
Please provide a description of the function:def list(self, policy_id, page=None): filters = [ 'policy_id={0}'.format(policy_id), 'page={0}'.format(page) if page else None ] return self._get( url='{0}alerts_conditions.json'.format(self.URL), ...
[ "\n This API endpoint returns a paginated list of alert conditions associated with the\n given policy_id.\n\n This API endpoint returns a paginated list of the alert conditions\n associated with your New Relic account. Alert conditions can be filtered\n by their name, list of IDs,...
Please provide a description of the function:def update( self, alert_condition_id, policy_id, type=None, condition_scope=None, name=None, entities=None, metric=None, runbook_url=None, terms=None, user_defined=Non...
[ "\n Updates any of the optional parameters of the alert condition\n\n :type alert_condition_id: int\n :param alert_condition_id: Alerts condition id to update\n\n :type policy_id: int\n :param policy_id: Alert policy id where target alert condition belongs to\n\n :type type...
Please provide a description of the function:def create( self, policy_id, type, condition_scope, name, entities, metric, terms, runbook_url=None, user_defined=None, enabled=True): da...
[ "\n Creates an alert condition\n\n :type policy_id: int\n :param policy_id: Alert policy id where target alert condition belongs to\n\n :type type: str\n :param type: The type of the condition, can be apm_app_metric,\n apm_kt_metric, servers_metric, browser_metric, mobi...
Please provide a description of the function:def delete(self, alert_condition_id): return self._delete( url='{0}alerts_conditions/{1}.json'.format(self.URL, alert_condition_id), headers=self.headers )
[ "\n This API endpoint allows you to delete an alert condition\n\n :type alert_condition_id: integer\n :param alert_condition_id: Alert Condition ID\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {\n \"condition\": {\n ...
Please provide a description of the function:def show(self, id): return self._get( url='{root}key_transactions/{id}.json'.format( root=self.URL, id=id ), headers=self.headers, )
[ "\n This API endpoint returns a single Key transaction, identified its ID.\n\n :type id: int\n :param id: Key transaction ID\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {\n \"key_transaction\": {\n \"id\":...
Please provide a description of the function:def list(self, policy_id, limit=None, offset=None): filters = [ 'policy_id={0}'.format(policy_id), 'limit={0}'.format(limit) if limit else '50', 'offset={0}'.format(offset) if offset else '0' ] return sel...
[ "\n This API endpoint returns a paginated list of alert conditions for infrastucture\n metrics associated with the given policy_id.\n\n :type policy_id: int\n :param policy_id: Alert policy id\n\n :type limit: string\n :param limit: Max amount of results to return\n\n ...
Please provide a description of the function:def show(self, alert_condition_infra_id): return self._get( url='{0}alerts/conditions/{1}'.format(self.URL, alert_condition_infra_id), headers=self.headers, )
[ "\n This API endpoint returns an alert condition for infrastucture, identified by its\n ID.\n\n :type alert_condition_infra_id: int\n :param alert_condition_infra_id: Alert Condition Infra ID\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n ...
Please provide a description of the function:def create(self, policy_id, name, condition_type, alert_condition_configuration, enabled=True): data = { "data": alert_condition_configuration } data['data']['type'] = condition_type data['data']['policy_id'] = policy_id...
[ "\n This API endpoint allows you to create an alert condition for infrastucture\n\n :type policy_id: int\n :param policy_id: Alert policy id\n\n :type name: str\n :param name: The name of the alert condition\n\n :type condition_type: str\n :param condition_type: The ...
Please provide a description of the function:def update(self, alert_condition_infra_id, policy_id, name, condition_type, alert_condition_configuration, enabled=True): data = { "data": alert_condition_configuration } data['data']['type'] = condition_type ...
[ "\n This API endpoint allows you to update an alert condition for infrastucture\n\n :type alert_condition_infra_id: int\n :param alert_condition_infra_id: Alert Condition Infra ID\n\n :type policy_id: int\n :param policy_id: Alert policy id\n\n :type name: str\n :par...
Please provide a description of the function:def delete(self, alert_condition_infra_id): return self._delete( url='{0}alerts/conditions/{1}'.format(self.URL, alert_condition_infra_id), headers=self.headers )
[ "\n This API endpoint allows you to delete an alert condition for infrastucture\n\n :type alert_condition_infra_id: integer\n :param alert_condition_infra_id: Alert Condition Infra ID\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {}\n\n ...
Please provide a description of the function:def create(self, name, category, applications=None, servers=None): data = { "label": { "category": category, "name": name, "links": { "applications": applications or [], ...
[ "\n This API endpoint will create a new label with the provided name and\n category\n\n :type name: str\n :param name: The name of the label\n\n :type category: str\n :param category: The Category\n\n :type applications: list of int\n :param applications: An o...
Please provide a description of the function:def delete(self, key): return self._delete( url='{url}labels/labels/{key}.json'.format( url=self.URL, key=key), headers=self.headers, )
[ "\n When applications are provided, this endpoint will remove those\n applications from the label.\n\n When no applications are provided, this endpoint will remove the label.\n\n :type key: str\n :param key: Label key. Example: 'Language:Java'\n\n :rtype: dict\n :ret...
Please provide a description of the function:def list(self, filter_guid=None, filter_ids=None, detailed=None, page=None): filters = [ 'filter[guid]={0}'.format(filter_guid) if filter_guid else None, 'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if fi...
[ "\n This API endpoint returns a paginated list of the plugins associated\n with your New Relic account.\n\n Plugins can be filtered by their name or by a list of IDs.\n\n :type filter_guid: str\n :param filter_guid: Filter by name\n\n :type filter_ids: list of ints\n ...
Please provide a description of the function:def show(self, id, detailed=None): filters = [ 'detailed={0}'.format(detailed) if detailed is not None else None, ] return self._get( url='{root}plugins/{id}.json'.format( root=self.URL, ...
[ "\n This API endpoint returns a single Key transaction, identified its ID.\n\n :type id: int\n :param id: Key transaction ID\n\n :type detailed: bool\n :param detailed:\n\n :rtype: dict\n :return: The JSON response of the API\n\n ::\n\n {\n ...
Please provide a description of the function:def list( self, application_id, filter_hostname=None, filter_ids=None, page=None): filters = [ 'filter[hostname]={0}'.format(filter_hostname) if filter_hostname else None, 'filter[ids]={0}'.format(','.join([str...
[ "\n This API endpoint returns a paginated list of instances associated with the\n given application.\n\n Application instances can be filtered by hostname, or the list of\n application instance IDs.\n\n :type application_id: int\n :param application_id: Application ID\n\n ...
Please provide a description of the function:def show(self, application_id, host_id): return self._get( url='{root}applications/{application_id}/hosts/{host_id}.json'.format( root=self.URL, application_id=application_id, host_id=host_id ...
[ "\n This API endpoint returns a single application host, identified by its\n ID.\n\n :type application_id: int\n :param application_id: Application ID\n\n :type host_id: int\n :param host_id: Application host ID\n\n :rtype: dict\n :return: The JSON response of...
Please provide a description of the function:def metric_names(self, application_id, host_id, name=None, page=None): params = [ 'name={0}'.format(name) if name else None, 'page={0}'.format(page) if page else None ] return self._get( url='{root}applicat...
[ "\n Return a list of known metrics and their value names for the given resource.\n\n :type application_id: int\n :param application_id: Application ID\n\n :type host_id: int\n :param host_id: Application Host ID\n\n :type name: str\n :param name: Filter metrics by na...
Please provide a description of the function:def metric_data( self, id, names, values=None, from_dt=None, to_dt=None, summarize=False): params = [ 'from={0}'.format(from_dt) if from_dt else None, 'to={0}'.format(to_dt) if to_dt else None, 'sum...
[ "\n This API endpoint returns a list of values for each of the requested\n metrics. The list of available metrics can be returned using the Metric\n Name API endpoint.\n\n Metric data can be filtered by a number of parameters, including\n multiple names and values, and by time ran...
Please provide a description of the function:def _get(self, *args, **kwargs): response = requests.get(*args, **kwargs) if not response.ok: raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) json_response = response.json() if resp...
[ "\n A wrapper for getting things\n\n :returns: The response of your get\n :rtype: dict\n\n :raises: This will raise a\n :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>`\n if there is an error from New Relic\n " ]
Please provide a description of the function:def _put(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) response = requests.put(*args, **kwargs) if not response.ok: raise NewRelicAPIServerException('{}: {}'.format(response.s...
[ "\n A wrapper for putting things. It will also json encode your 'data' parameter\n\n :returns: The response of your put\n :rtype: dict\n\n :raises: This will raise a\n :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>`\n if there...
Please provide a description of the function:def _post(self, *args, **kwargs): if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) response = requests.post(*args, **kwargs) if not response.ok: raise NewRelicAPIServerException('{}: {}'.format(response...
[ "\n A wrapper for posting things. It will also json encode your 'data' parameter\n\n :returns: The response of your post\n :rtype: dict\n\n :raises: This will raise a\n :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>`\n if ther...
Please provide a description of the function:def _delete(self, *args, **kwargs): response = requests.delete(*args, **kwargs) if not response.ok: raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) if response.text: return respo...
[ "\n A wrapper for deleting things\n\n :returns: The response of your delete\n :rtype: dict\n\n :raises: This will raise a\n :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>`\n if there is an error from New Relic\n " ]
Please provide a description of the function:def list(self, filter_title=None, filter_ids=None, page=None): filters = [ 'filter[title]={0}'.format(filter_title) if filter_title else None, 'filter[ids]={0}'.format(','.join([str(dash_id) for dash_id in filter_ids])) if filter_ids ...
[ "\n :type filter_title: str\n :param filter_title: Filter by dashboard title\n\n :type filter_ids: list of ints\n :param filter_ids: Filter by dashboard ids\n\n :type page: int\n :param page: Pagination index\n\n :rtype: dict\n :return: The JSON response of th...
Please provide a description of the function:def create(self, dashboard_data): return self._post( url='{0}dashboards.json'.format(self.URL), headers=self.headers, data=dashboard_data, )
[ "\n This API endpoint creates a dashboard and all defined widgets.\n\n :type dashboard: dict\n :param dashboard: Dashboard Dictionary\n\n :rtype dict\n :return: The JSON response of the API\n\n ::\n {\n \"dashboard\": {\n \"id\":...
Please provide a description of the function:def update(self, id, dashboard_data): return self._put( url='{0}dashboards/{1}.json'.format(self.URL, id), headers=self.headers, data=dashboard_data, )
[ "\n This API endpoint updates a dashboard and all defined widgets.\n\n :type id: int\n :param id: Dashboard ID\n\n :type dashboard: dict\n :param dashboard: Dashboard Dictionary\n\n :rtype dict\n :return: The JSON response of the API\n\n ::\n {\n ...
Please provide a description of the function:def operatorPrecedence(base, operators): # The full expression, used to provide sub-expressions expression = Forward() # The initial expression last = base | Suppress('(') + expression + Suppress(')') def parse_operator(expr, arity, association, a...
[ "\n This re-implements pyparsing's operatorPrecedence function.\n\n It gets rid of a few annoying bugs, like always putting operators inside\n a Group, and matching the whole grammar with Forward first (there may\n actually be a reason for that, but I couldn't find it). It doesn't\n support trinary e...
Please provide a description of the function:def addevensubodd(operator, operand): try: for i, x in enumerate(operand): if x % 2: operand[i] = -x return operand except TypeError: if operand % 2: return -operand return operand
[ "Add even numbers, subtract odd ones. See http://1w6.org/w6 " ]
Please provide a description of the function:def main(argv=None): args = docopt.docopt(__doc__, argv=argv, version=__version__) verbose = bool(args['--verbose']) f_roll = dice.roll kwargs = {} if args['--min']: f_roll = dice.roll_min elif args['--max']: f_roll = dice.roll_...
[ "Run roll() from a command line interface" ]
Please provide a description of the function:def set_parse_attributes(self, string, location, tokens): "Fluent API for setting parsed location" self.string = string self.location = location self.tokens = tokens return self
[]
Please provide a description of the function:def evaluate_object(obj, cls=None, cache=False, **kwargs): old_obj = obj if isinstance(obj, Element): if cache: obj = obj.evaluate_cached(**kwargs) else: obj = obj.evaluate(cache=cache, **kwargs...
[ "Evaluates elements, and coerces objects to a class if needed" ]
Please provide a description of the function:def evaluate_cached(self, **kwargs): if not hasattr(self, 'result'): self.result = self.evaluate(cache=True, **kwargs) return self.result
[ "Wraps evaluate(), caching results" ]
Please provide a description of the function:def readGraph(edgeList, nodeList = None, directed = False, idKey = 'ID', eSource = 'From', eDest = 'To'): progArgs = (0, "Starting to reading graphs") if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' :...
[ "Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files.\n\n This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph()](#metaknowledge.graphHelpers.writeGraph), if this does not produce the desired results the networkx bui...
Please provide a description of the function:def writeGraph(grph, name, edgeInfo = True, typing = False, suffix = 'csv', overwrite = True, allSameAttribute = False): progArgs = (0, "Writing the graph to files starting with: {}".format(name)) if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : Fa...
[ "Writes both the edge list and the node attribute list of _grph_ to files starting with _name_.\n\n The output files start with _name_, the file type (edgeList, nodeAttributes) then if typing is True the type of graph (directed or undirected) then the suffix, the default is as follows:\n\n >> name_fileType.su...
Please provide a description of the function:def writeEdgeList(grph, name, extraInfo = True, allSameAttribute = False, _progBar = None): count = 0 eMax = len(grph.edges()) if metaknowledge.VERBOSE_MODE or isinstance(_progBar, _ProgressBar): if isinstance(_progBar, _ProgressBar): PBa...
[ "Writes an edge list of _grph_ at the destination _name_.\n\n The edge list has two columns for the source and destination of the edge, `'From'` and `'To'` respectively, then, if _edgeInfo_ is `True`, for each attribute of the node another column is created.\n\n **Note**: If any edges are missing an attribute...
Please provide a description of the function:def writeNodeAttributeFile(grph, name, allSameAttribute = False, _progBar = None): count = 0 nMax = len(grph.nodes()) if metaknowledge.VERBOSE_MODE or isinstance(_progBar, _ProgressBar): if isinstance(_progBar, _ProgressBar): PBar = _prog...
[ "Writes a node attribute list of _grph_ to the file given by the path _name_.\n\n The node list has one column call `'ID'` with the node ids used by networkx and all other columns are the node attributes.\n\n **Note**: If any nodes are missing an attribute it will be left blank by default, enable _allSameAttr...
Please provide a description of the function:def writeTnetFile(grph, name, modeNameString, weighted = False, sourceMode = None, timeString = None, nodeIndexString = 'tnet-ID', weightString = 'weight'): count = 0 eMax = len(grph.edges()) progArgs = (0, "Writing tnet edge list {}".format(name)) if me...
[ "Writes an edge list designed for reading by the _R_ package [tnet](https://toreopsahl.com/tnet/).\n\n The _networkx_ graph provided must be a pure two-mode network, the modes must be 2 different values for the node attribute accessed by _modeNameString_ and all edges must be between different node types. Each n...
Please provide a description of the function:def getWeight(grph, nd1, nd2, weightString = "weight", returnType = int): if not weightString: return returnType(1) else: return returnType(grph.edges[nd1, nd2][weightString])
[ "\n A way of getting the weight of an edge with or without weight as a parameter\n returns a the value of the weight parameter converted to returnType if it is given or 1 (also converted) if not\n " ]
Please provide a description of the function:def getNodeDegrees(grph, weightString = "weight", strictMode = False, returnType = int, edgeType = 'bi'): ndsDict = {} for nd in grph.nodes(): ndsDict[nd] = returnType(0) for e in grph.edges(data = True): if weightString: try: ...
[ "\n Retunrs a dictionary of nodes to their degrees, the degree is determined by adding the weight of edge with the weight being the string weightString that gives the name of the attribute of each edge containng thier weight. The Weights are then converted to the type returnType. If weightString is give as False...
Please provide a description of the function:def dropEdges(grph, minWeight = - float('inf'), maxWeight = float('inf'), parameterName = 'weight', ignoreUnweighted = False, dropSelfLoops = False): count = 0 total = len(grph.edges()) if metaknowledge.VERBOSE_MODE: progArgs = (0, "Dropping edges") ...
[ "Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges whose weights meet the following inequality: _minWeight_ <= edge's weight <= _maxWeight_. A `Keyerror` will be raised if the graph is unweighted unless _ig...
Please provide a description of the function:def dropNodesByDegree(grph, minDegree = -float('inf'), maxDegree = float('inf'), useWeight = True, parameterName = 'weight', includeUnweighted = True): count = 0 total = len(grph.nodes()) if metaknowledge.VERBOSE_MODE: progArgs = (0, "Dropping nodes ...
[ "Modifies _grph_ by dropping nodes that do not have a degree that is within inclusive bounds of _minDegree_ and _maxDegree_, i.e after running _grph_ will only have nodes whose degrees meet the following inequality: _minDegree_ <= node's degree <= _maxDegree_.\n\n Degree is determined in two ways, the default _u...
Please provide a description of the function:def dropNodesByCount(grph, minCount = -float('inf'), maxCount = float('inf'), parameterName = 'count', ignoreMissing = False): count = 0 total = len(grph.nodes()) if metaknowledge.VERBOSE_MODE: progArgs = (0, "Dropping nodes by count") progKw...
[ "Modifies _grph_ by dropping nodes that do not have a count that is within inclusive bounds of _minCount_ and _maxCount_, i.e after running _grph_ will only have nodes whose degrees meet the following inequality: _minCount_ <= node's degree <= _maxCount_.\n\n Count is determined by the count attribute, _paramete...
Please provide a description of the function:def mergeGraphs(targetGraph, addedGraph, incrementedNodeVal = 'count', incrementedEdgeVal = 'weight'): for addedNode, attribs in addedGraph.nodes(data = True): if incrementedNodeVal: try: targetGraph.node[addedNode][incrementedNo...
[ "A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and target were not generated by the same method.\n\n **mergeGraphs**() will **modify** _targetGraph_ in place ...
Please provide a description of the function:def graphStats(G, stats = ('nodes', 'edges', 'isolates', 'loops', 'density', 'transitivity'), makeString = True, sentenceString = False): for sts in stats: if sts not in ['nodes', 'edges', 'isolates', 'loops', 'density', 'transitivity']: raise R...
[ "Returns a string or list containing statistics about the graph _G_.\n\n **graphStats()** gives 6 different statistics: number of nodes, number of edges, number of isolates, number of loops, density and transitivity. The ones wanted can be given to _stats_. By default a string giving each stat on a different lin...
Please provide a description of the function:def AD(val): retDict = {} for v in val: split = v.split(' : ') retDict[split[0]] = [s for s in' : '.join(split[1:]).replace('\n', '').split(';') if s != ''] return retDict
[ "Affiliation\n Undoing what the parser does then splitting at the semicolons and dropping newlines extra fitlering is required beacuse some AD's end with a semicolon" ]
Please provide a description of the function:def AUID(val): retDict = {} for v in val: split = v.split(' : ') retDict[split[0]] = ' : '.join(split[1:]) return retDict
[ "AuthorIdentifier\n one line only just need to undo the parser's effects" ]
Please provide a description of the function:def isInteractive(): if sys.stdout.isatty() and os.name != 'nt': #Hopefully everything but ms supports '\r' try: import threading except ImportError: return False else: return True else: ...
[ "\n A basic check of if the program is running in interactive mode\n " ]