Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _Roessler2010_SRK2(f, G, y0, tspan, IJmethod, dW=None, IJ=None): (d, m, f, G, y0, tspan, dW, IJ) = _check_args(f, G, y0, tspan, dW, IJ) have_separate_g = (not callable(G)) # if G is given as m separate functions N = len(tspan) h = (tspan[N-1] - tspan...
[ "Implements the Roessler2010 order 1.0 strong Stochastic Runge-Kutta\n algorithms SRI2 (for Ito equations) and SRS2 (for Stratonovich equations). \n\n Algorithms SRI2 and SRS2 are almost identical and have the same extended\n Butcher tableaus. The difference is that Ito repeateded integrals I_ij are\n r...
Please provide a description of the function:def stratKP2iS(f, G, y0, tspan, Jmethod=Jkpw, gam=None, al1=None, al2=None, rtol=1e-4, dW=None, J=None): try: from scipy.optimize import fsolve except ImportError: raise Error('stratKP2iS() requires package ``scipy`` to be installe...
[ "Use the Kloeden and Platen two-step implicit order 1.0 strong algorithm\n to integrate a Stratonovich equation dy = f(y,t)dt + G(y,t)\\circ dW(t)\n\n This semi-implicit algorithm may be useful for stiff systems. The noise\n does not need to be scalar, diagonal, or commutative.\n\n This algorithm is def...
Please provide a description of the function:def actively_watch_logs_for_error(self, on_error_call, interval=1): class LogWatchingThread(threading.Thread): def __init__(self, cluster): super(LogWatchingThread, self).__init__() self.cluster = clu...
[ "\n Begins a thread that repeatedly scans system.log for new errors, every interval seconds.\n (The first pass covers the entire log contents written at that point,\n subsequent scans cover newly appended log messages).\n\n Reports new errors, by calling the provided callback with an Ord...
Please provide a description of the function:def wait_for_compactions(self, timeout=600): for node in list(self.nodes.values()): if node.is_running(): node.wait_for_compactions(timeout) return self
[ "\n Wait for all compactions to finish on all nodes.\n " ]
Please provide a description of the function:def timed_grep_nodes_for_patterns(self, versions_to_patterns, timeout_seconds, filename="system.log"): end_time = time.time() + timeout_seconds while True: if time.time() > end_time: raise TimeoutError(time.strftime("%d %b...
[ "\n Searches all nodes in the cluster for a specific regular expression based on the node's version.\n Params:\n @versions_to_patterns : an instance of LogPatternToVersionMap, specifying the different log patterns based on a node's version.\n @version : the earliest version the new patte...
Please provide a description of the function:def show_logs(self, selected_nodes_names=None): if selected_nodes_names is None: selected_nodes_names = [] if len(self.nodes) == 0: print_("There are no nodes in this cluster yet.") return nodes = sorted...
[ "\n Shows logs of nodes in this cluster, by default, with multitail.\n If you need to alter the command or options, change CCM_MULTITAIL_CMD .\n Params:\n @selected_nodes_names : a list-like object that contains names of nodes to be shown. If empty, this will show all nodes in the cluste...
Please provide a description of the function:def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'): super(DseNode, self).watch_log_for_alive(nodes, from_mark=from_mark, timeout=timeout, filename=filename)
[ "\n Watch the log of this node until it detects that the provided other\n nodes are marked UP. This method works similarly to watch_log_for_death.\n\n We want to provide a higher default timeout when this is called on DSE.\n " ]
Please provide a description of the function:def export_dse_home_in_dse_env_sh(self): ''' Due to the way CCM lays out files, separating the repository from the node(s) confs, the `dse-env.sh` script of each node needs to have its DSE_HOME var set and exported. Since DSE 4.5.x, th...
[]
Please provide a description of the function:def load(path, name, cluster): node_path = os.path.join(path, name) filename = os.path.join(node_path, 'node.conf') with open(filename, 'r') as f: data = yaml.safe_load(f) try: itf = data['interfaces'] ...
[ "\n Load a node from from the path on disk to the config files, the node name and the\n cluster the node is part of.\n " ]
Please provide a description of the function:def get_path(self): return os.path.join(self.cluster.get_path(), self.name)
[ "\n Returns the path to this node top level directory (where config/data is stored)\n " ]
Please provide a description of the function:def get_install_dir(self): if self.__install_dir is None: return self.cluster.get_install_dir() else: common.validate_install_dir(self.__install_dir) return self.__install_dir
[ "\n Returns the path to the cassandra source directory used by this node.\n " ]
Please provide a description of the function:def set_install_dir(self, install_dir=None, version=None, verbose=False): if version is None: self.__install_dir = install_dir if install_dir is not None: common.validate_install_dir(install_dir) else: ...
[ "\n Sets the path to the cassandra source directory for use by this node.\n " ]
Please provide a description of the function:def set_configuration_options(self, values=None): if not hasattr(self,'_config_options') or self.__config_options is None: self.__config_options = {} if values is not None: self.__config_options = common.merge_configuration(s...
[ "\n Set Cassandra configuration options.\n ex:\n node.set_configuration_options(values={\n 'hinted_handoff_enabled' : True,\n 'concurrent_writes' : 64,\n })\n " ]
Please provide a description of the function:def set_batch_commitlog(self, enabled=False): if enabled: values = { "commitlog_sync": "batch", "commitlog_sync_batch_window_in_ms": 5, "commitlog_sync_period_in_ms": None } else...
[ "\n The batch_commitlog option gives an easier way to switch to batch\n commitlog (since it requires setting 2 options and unsetting one).\n " ]
Please provide a description of the function:def show(self, only_status=False, show_cluster=True): self.__update_status() indent = ''.join([" " for i in xrange(0, len(self.name) + 2)]) print_("{}: {}".format(self.name, self.__get_status_string())) if not only_status: ...
[ "\n Print infos on this node configuration.\n " ]
Please provide a description of the function:def is_running(self): self.__update_status() return self.status == Status.UP or self.status == Status.DECOMMISSIONED
[ "\n Return true if the node is running\n " ]
Please provide a description of the function:def grep_log(self, expr, filename='system.log', from_mark=None): matchings = [] pattern = re.compile(expr) with open(os.path.join(self.get_path(), 'logs', filename)) as f: if from_mark: f.seek(from_mark) ...
[ "\n Returns a list of lines matching the regular expression in parameter\n in the Cassandra log of this node\n " ]
Please provide a description of the function:def mark_log(self, filename='system.log'): log_file = os.path.join(self.get_path(), 'logs', filename) if not os.path.exists(log_file): return 0 with open(log_file) as f: f.seek(0, os.SEEK_END) return f.tell...
[ "\n Returns \"a mark\" to the current position of this node Cassandra log.\n This is for use with the from_mark parameter of watch_log_for_* methods,\n allowing to watch the log from the position when this method was called.\n " ]
Please provide a description of the function:def watch_log_for(self, exprs, from_mark=None, timeout=600, process=None, verbose=False, filename='system.log'): start = time.time() tofind = [exprs] if isinstance(exprs, string_types) else exprs tofind = [re.compile(e) for e in tofind] ...
[ "\n Watch the log until one or more (regular) expression are found.\n This methods when all the expressions have been found or the method\n timeouts (a TimeoutError is then raised). On successful completion,\n a list of pair (line matched, match object) is returned.\n " ]
Please provide a description of the function:def watch_log_for_death(self, nodes, from_mark=None, timeout=600, filename='system.log'): tofind = nodes if isinstance(nodes, list) else [nodes] tofind = ["%s is now [dead|DOWN]" % node.address() for node in tofind] self.watch_log_for(tofind,...
[ "\n Watch the log of this node until it detects that the provided other\n nodes are marked dead. This method returns nothing but throw a\n TimeoutError if all the requested node have not been found to be\n marked dead before timeout sec.\n A mark as returned by mark_log() can be u...
Please provide a description of the function:def wait_for_binary_interface(self, **kwargs): if self.cluster.version() >= '1.2': self.watch_log_for("Starting listening for CQL clients", **kwargs) binary_itf = self.network_interfaces['binary'] if not common.check_socket_liste...
[ "\n Waits for the Binary CQL interface to be listening. If > 1.2 will check\n log for 'Starting listening for CQL clients' before checking for the\n interface to be listening.\n\n Emits a warning if not listening after 30 seconds.\n " ]
Please provide a description of the function:def wait_for_thrift_interface(self, **kwargs): if self.cluster.version() >= '4': return; self.watch_log_for("Listening for thrift clients...", **kwargs) thrift_itf = self.network_interfaces['thrift'] if not common.check_...
[ "\n Waits for the Thrift interface to be listening.\n\n Emits a warning if not listening after 30 seconds.\n " ]
Please provide a description of the function:def start(self, join_ring=True, no_wait=False, verbose=False, update_pid=True, wait_other_notice=True, replace_token=None, replace_address=None, jvm_args=None, ...
[ "\n Start the node. Options includes:\n - join_ring: if false, start the node with -Dcassandra.join_ring=False\n - no_wait: by default, this method returns when the node is started and listening to clients.\n If no_wait=True, the method returns sooner.\n - wait_other_not...
Please provide a description of the function:def stop(self, wait=True, wait_other_notice=False, signal_event=signal.SIGTERM, **kwargs): if self.is_running(): if wait_other_notice: marks = [(node, node.mark_log()) for node in list(self.cluster.nodes.values()) if node.is_live(...
[ "\n Stop the node.\n - wait: if True (the default), wait for the Cassandra process to be\n really dead. Otherwise return after having sent the kill signal.\n - wait_other_notice: return only when the other live nodes of the\n cluster have marked this node has dead.\n ...
Please provide a description of the function:def wait_for_compactions(self, timeout=120): pattern = re.compile("pending tasks: 0") start = time.time() while time.time() - start < timeout: output, err, rc = self.nodetool("compactionstats") if pattern.search(output...
[ "\n Wait for all compactions to finish on this node.\n " ]
Please provide a description of the function:def update_startup_byteman_script(self, byteman_startup_script): if self.byteman_port == '0': raise common.LoadError('Byteman is not installed') self.byteman_startup_script = byteman_startup_script self.import_config_files()
[ "\n Update the byteman startup script, i.e., rule injected before the node starts.\n\n :param byteman_startup_script: the relative path to the script\n :raise common.LoadError: if the node does not have byteman installed\n " ]
Please provide a description of the function:def _find_cmd(self, cmd): cdir = self.get_install_cassandra_root() if self.get_base_cassandra_version() >= 2.1: fcmd = common.join_bin(cdir, os.path.join('tools', 'bin'), cmd) else: fcmd = common.join_bin(cdir, 'bin', ...
[ "\n Locates command under cassandra root and fixes permissions if needed\n " ]
Please provide a description of the function:def data_size(self, live_data=None): if live_data is not None: warnings.warn("The 'live_data' keyword argument is deprecated.", DeprecationWarning) output = self.nodetool('info')[0] return _get_load_from_...
[ "Uses `nodetool info` to get the size of a node's data in KB." ]
Please provide a description of the function:def get_sstable_data_files(self, ks, table): p = self.get_sstable_data_files_process(ks=ks, table=table) out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table]) return sorted(filter(lambda s: s.endswith('-...
[ "\n Read sstable data files by using sstableutil, so we ignore temporary files\n " ]
Please provide a description of the function:def is_modern_windows_install(version): version = LooseVersion(str(version)) if is_win() and version >= LooseVersion('2.1'): return True else: return False
[ "\n The 2.1 release line was when Cassandra received beta windows support.\n Many features are gated based on that added compatibility.\n\n Handles floats, strings, and LooseVersions by first converting all three types to a string, then to a LooseVersion.\n " ]
Please provide a description of the function:def get_jdk_version(): try: version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT) except OSError: print_("ERROR: Could not find java. Is it in your path?") exit(1) return _get_jdk_version(version)
[ "\n Retrieve the Java version as reported in the quoted string returned\n by invoking 'java -version'.\n\n Works for Java 1.8, Java 9 and should also be fine for Java 10.\n " ]
Please provide a description of the function:def wait_for_any_log(nodes, pattern, timeout, filename='system.log', marks=None): if marks is None: marks = {} for _ in range(timeout): for node in nodes: found = node.grep_log(pattern, filename=filename, from_mark=marks.get(node, Non...
[ "\n Look for a pattern in the system.log of any in a given list\n of nodes.\n @param nodes The list of nodes whose logs to scan\n @param pattern The target pattern\n @param timeout How long to wait for the pattern. Note that\n strictly speaking, timeout is not really a timeout,\n ...
Please provide a description of the function:def download_version(version, url=None, verbose=False, binary=False): assert_jdk_valid_for_cassandra_version(version) archive_url = ARCHIVE if CCM_CONFIG.has_option('repositories', 'cassandra'): archive_url = CCM_CONFIG.get('repositories', 'cassandr...
[ "Download, extract, and build Cassandra tarball.\n\n if binary == True, download precompiled tarball, otherwise build from source tarball.\n " ]
Please provide a description of the function:def get_tagged_version_numbers(series='stable'): releases = [] if series == 'testing': # Testing releases always have a hyphen after the version number: tag_regex = re.compile('^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+-.*$)') else: ...
[ "Retrieve git tags and find version numbers for a release series\n\n series - 'stable', 'oldstable', or 'testing'" ]
Please provide a description of the function:def execute_ccm_remotely(remote_options, ccm_args): if not PARAMIKO_IS_AVAILABLE: logging.warn("Paramiko is not Availble: Skipping remote execution of CCM command") return None, None # Create the SSH client ssh_client = SSHClient(remote_opti...
[ "\n Execute CCM operation(s) remotely\n\n :return A tuple defining the execution of the command\n * output - The output of the execution if the output was not displayed\n * exit_status - The exit status of remotely executed script\n :raises Exception if invalid options are pa...
Please provide a description of the function:def __connect(host, port, username, password, private_key): # Initialize the SSH connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if private_key is not None and password is not None: ...
[ "\n Establish remote connection\n\n :param host: Hostname or IP address to connect to\n :param port: Port number to use for SSH\n :param username: Username credentials for SSH access\n :param password: Password credentials for SSH access (or private key passphrase)\n :param...
Please provide a description of the function:def execute(self, command, is_displayed=True, profile=None): # Modify the command for remote execution command = " ".join("'{0}'".format(argument) for argument in command) # Execute the command and initialize for reading (close stdin/writes)...
[ "\n Execute a command on the remote server\n\n :param command: Command to execute remotely\n :param is_displayed: True if information should be display; false to return output\n (default: true)\n :param profile: Profile to source (unix like system only should ...
Please provide a description of the function:def execute_ccm_command(self, ccm_args, is_displayed=True): return self.execute(["ccm"] + ccm_args, profile=self.profile)
[ "\n Execute a CCM command on the remote server\n\n :param ccm_args: CCM arguments to execute remotely\n :param is_displayed: True if information should be display; false to return output\n (default: true)\n :return: A tuple defining the execution of the comman...
Please provide a description of the function:def execute_python_script(self, script): # Create the local file to copy to remote file_handle, filename = tempfile.mkstemp() temp_file = os.fdopen(file_handle, "wt") temp_file.write(script) temp_file.close() # Put th...
[ "\n Execute a python script of the remote server\n\n :param script: Inline script to convert to a file and execute remotely\n :return: The output of the script execution\n " ]
Please provide a description of the function:def put(self, local_path, remote_path=None): # Determine if local_path should be put into remote user directory if remote_path is None: remote_path = os.path.basename(local_path) ftp = self.ssh.open_sftp() if os.path.isdi...
[ "\n Copy a file (or directory recursively) to a location on the remote server\n\n :param local_path: Local path to copy to; can be file or directory\n :param remote_path: Remote path to copy to (default: None - Copies file or directory to\n home directory directory on...
Please provide a description of the function:def __put_dir(self, ftp, local_path, remote_path=None): # Determine if local_path should be put into remote user directory if remote_path is None: remote_path = os.path.basename(local_path) remote_path += self.separator #...
[ "\n Helper function to perform copy operation to remote server\n\n :param ftp: SFTP handle to perform copy operation(s)\n :param local_path: Local path to copy to; can be file or directory\n :param remote_path: Remote path to copy to (default: None - Copies file or directory to\n ...
Please provide a description of the function:def remove(self, remote_path): # Based on the remote file stats; remove a file or directory recursively ftp = self.ssh.open_sftp() if stat.S_ISDIR(ftp.stat(remote_path).st_mode): self.__remove_dir(ftp, remote_path) else: ...
[ "\n Delete a file or directory recursively on the remote server\n\n :param remote_path: Remote path to remove\n " ]
Please provide a description of the function:def __remove_dir(self, ftp, remote_path): # Iterate over the remote path and perform remove operations files = ftp.listdir(remote_path) for filename in files: # Attempt to remove the file (if exception then path is directory) ...
[ "\n Helper function to perform delete operation on the remote server\n\n :param ftp: SFTP handle to perform delete operation(s)\n :param remote_path: Remote path to remove\n " ]
Please provide a description of the function:def ssh_key(key): value = str(key) # Ensure the file exists locally if not os.path.isfile(value): raise Exception("File Does not Exist: %s" % key) return value
[ "\n SSH key parser validator (ensure file exists)\n\n :param key: Filename/Key to validate (ensure exists)\n :return: The filename/key passed in (if valid)\n :raises Exception if filename/key is not a valid file\n " ]
Please provide a description of the function:def port(port): value = int(port) if value <= 0 or value > 65535: raise argparse.ArgumentTypeError("%s must be between [1 - 65535]" % port) return value
[ "\n Port validator\n\n :param port: Port to validate (1 - 65535)\n :return: Port passed in (if valid)\n :raises ArgumentTypeError if port is not valid\n " ]
Please provide a description of the function:def usage(self): # Retrieve the text for just the arguments usage = self.parser.format_help().split("optional arguments:")[1] # Remove any blank lines and return return "Remote Options:" + os.linesep + \ os.linesep.joi...
[ "\n Get the usage for the remote exectuion options\n\n :return Usage for the remote execution options\n " ]
Please provide a description of the function:def _jwt_required(realm): token = _jwt.request_callback() if token is None: raise JWTError('Authorization Required', 'Request does not contain an access token', headers={'WWW-Authenticate': 'JWT realm="%s"' % realm}) try: ...
[ "Does the actual work of verifying the JWT data in the current request.\n This is done automatically for you by `jwt_required()` but you could call it manually.\n Doing so would be useful in the context of optional JWT access in your APIs.\n\n :param realm: an optional realm\n " ]
Please provide a description of the function:def jwt_required(realm=None): def wrapper(fn): @wraps(fn) def decorator(*args, **kwargs): _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM']) return fn(*args, **kwargs) return decorator return wrapper
[ "View decorator that requires a valid JWT token to be present in the request\n\n :param realm: an optional realm\n " ]
Please provide a description of the function:def auth_request_handler(self, callback): warnings.warn("This handler is deprecated. The recommended approach to have control over " "the authentication resource is to disable the built-in resource by " "setting J...
[ "Specifies the authentication response handler function.\n\n :param callable callback: the auth request handler function\n\n .. deprecated\n " ]
Please provide a description of the function:def iterencode(self, o, _one_shot=False): c_make_encoder_original = json.encoder.c_make_encoder json.encoder.c_make_encoder = None if self.check_circular: markers = {} else: markers = None if self.ensu...
[ "Encode the given object and yield each string\n representation as available.\n For example::\n for chunk in JSONEncoder().iterencode(bigobject):\n mysocket.write(chunk)\n " ]
Please provide a description of the function:def _svg_path(self, pathcodes, data): def gen_path_elements(pathcodes, data): counts = {'M': 1, 'L': 1, 'C': 3, 'Z': 0} it = iter(data) for code in pathcodes: yield code for _ in range(count...
[ "\n Return the SVG path's 'd' element.\n\n " ]
Please provide a description of the function:def fig_to_html(fig=None, template='base.html', tiles=None, crs=None, epsg=None, embed_links=False, float_precision=6): if tiles is None: tiles = maptiles.osm elif isinstance(tiles, six.string_types): if tiles not in maptiles.tile...
[ "\n Convert a Matplotlib Figure to a Leaflet map\n\n Parameters\n ----------\n fig : figure, default gcf()\n Figure used to convert to map\n template : string, default 'base.html'\n The Jinja2 template to use\n tiles : string or tuple\n The tiles argument is used to control th...
Please provide a description of the function:def fig_to_geojson(fig=None, **kwargs): if fig is None: fig = plt.gcf() renderer = LeafletRenderer(**kwargs) exporter = Exporter(renderer) exporter.run(fig) return renderer.geojson()
[ "\n Returns a figure's GeoJSON representation as a dictionary\n\n All arguments passed to fig_to_html()\n\n Returns\n -------\n GeoJSON dictionary\n\n " ]
Please provide a description of the function:def display(fig=None, closefig=True, **kwargs): from IPython.display import HTML if fig is None: fig = plt.gcf() if closefig: plt.close(fig) html = fig_to_html(fig, **kwargs) # We embed everything in an iframe. iframe_html = '<i...
[ "\n Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.\n\n Parameters\n ----------\n fig : figure, default gcf()\n Figure used to convert to map\n closefig : boolean, default True\n Close the current Figure\n " ]
Please provide a description of the function:def show(fig=None, path='_map.html', **kwargs): import webbrowser fullpath = os.path.abspath(path) with open(fullpath, 'w') as f: save_html(fig, fileobj=f, **kwargs) webbrowser.open('file://' + fullpath)
[ "\n Convert a Matplotlib Figure to a Leaflet map. Open in a browser\n\n Parameters\n ----------\n fig : figure, default gcf()\n Figure used to convert to map\n path : string, default '_map.html'\n Filename where output html will be saved\n\n See fig_to_html() for description of keywo...
Please provide a description of the function:def render(self, embedded=False): if embedded: if self.code is None: self.code = urllib.request.urlopen(self.url).read() return '<script>{}</script>'.format(self.code) else: return '<script src="{}"...
[ "Renders the object.\n \n Parameters\n ----------\n embedded : bool, default False\n Whether the code shall be embedded explicitely in the render.\n " ]
Please provide a description of the function:def create_incident(**kwargs): incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN) if 'component_id' in kwargs: return incidents.post(name=kwargs['name'], message=kwargs['message'], ...
[ "\n Creates an incident\n " ]
Please provide a description of the function:def incident_exists(name, message, status): incidents = cachet.Incidents(endpoint=ENDPOINT) all_incidents = json.loads(incidents.get()) for incident in all_incidents['data']: if name == incident['name'] and \ status == incident['status'] a...
[ "\n Check if an incident with these attributes already exists\n " ]
Please provide a description of the function:def get_component(id): components = cachet.Components(endpoint=ENDPOINT) component = json.loads(components.get(id=id)) return component['data']
[ "\n Gets a Cachet component by id\n " ]
Please provide a description of the function:def api_token_required(f, *args, **kwargs): try: if args[0].api_token is None: raise AttributeError('Parameter api_token is required.') except AttributeError: raise AttributeError('Parameter api_token is required.') return f(*arg...
[ "\n Decorator helper function to ensure some methods aren't needlessly called\n without an api_token configured.\n " ]
Please provide a description of the function:def check_required_args(required_args, args): for arg in required_args: if arg not in args: raise KeyError('Required argument: %s' % arg) return True
[ "\n Checks if all required_args have a value.\n :param required_args: list of required args\n :param args: kwargs\n :return: True (if an exception isn't raised)\n " ]
Please provide a description of the function:def get(self, id=None, **kwargs): if id is not None: return self._get('components/%s' % id, data=kwargs) elif 'params' in kwargs: data = dict(kwargs) params = data.pop('params') return self._get('compon...
[ "\n https://docs.cachethq.io/docs/get-components\n https://docs.cachethq.io/docs/get-a-component\n " ]
Please provide a description of the function:def put(self, **kwargs): required_args = ['id'] check_required_args(required_args, kwargs) return self._put('components/groups/%s' % kwargs['id'], data=kwargs)
[ "\n https://docs.cachethq.io/docs/put-component-group\n " ]
Please provide a description of the function:def get(self, id=None, **kwargs): if id is not None: return self._get('metrics/%s' % id, data=kwargs) else: return self._get('metrics', data=kwargs)
[ "\n https://docs.cachethq.io/docs/get-metrics\n https://docs.cachethq.io/docs/get-a-metric\n " ]
Please provide a description of the function:def post(self, **kwargs): # default values kwargs.setdefault('default_value', kwargs.get('default_value', 0)) required_args = ['name', 'suffix', 'description', 'default_value'] check_required_args(required_args, kwargs) retu...
[ "\n https://docs.cachethq.io/docs/metrics\n " ]
Please provide a description of the function:def get(self, metric_id=None, **kwargs): if metric_id is None: raise AttributeError('metric_id is required to get metric points.') return self._get('metrics/%s/points' % metric_id, data=kwargs)
[ "\n https://docs.cachethq.io/docs/get-metric-points\n " ]
Please provide a description of the function:def post(self, **kwargs): required_args = ['email'] check_required_args(required_args, kwargs) return self._post('subscribers', data=kwargs)
[ "\n https://docs.cachethq.io/docs/subscribers\n " ]
Please provide a description of the function:def synchronized(wrapped): _lock = threading.RLock() @functools.wraps(wrapped) def _wrapper(*args, **kwargs): with _lock: return wrapped(*args, **kwargs) return _wrapper
[ "The missing @synchronized decorator\n\n https://git.io/vydTA" ]
Please provide a description of the function:def get_version(): file_dir = os.path.realpath(os.path.dirname(__file__)) with open( os.path.join(file_dir, '..', 'behold', 'version.py')) as f: txt = f.read() version_match = re.search( r, txt, re.M) if version_match: ...
[ "Obtain the packge version from a python file e.g. pkg/__init__.py\n See <https://packaging.python.org/en/latest/single_source_version.html>.\n ", "^__version__ = ['\"]([^'\"]*)['\"]" ]
Please provide a description of the function:def when(self, *bools): self.passes = self.passes and all(bools) return self
[ "\n :type bools: bool\n :param bools: Boolean arguments\n\n All boolean arguments passed to this method must evaluate to `True` for\n printing to be enabled.\n\n So for example, the following code would print ``x: 1``\n\n .. code-block:: python\n\n for x in range(...
Please provide a description of the function:def when_values(self, **criteria): criteria = {k: str(v) for k, v in criteria.items()} self._add_value_filters(**criteria) return self
[ "\n By default, ``Behold`` objects call ``str()`` on all variables before\n sending them to the output stream. This method enables you to filter on\n those extracted string representations. The syntax is exactly like that\n of the ``when_context()`` method. Here is an example.\n\n ...
Please provide a description of the function:def stash(self, *values, **data): if not self.tag: raise ValueError( 'You must instantiate Behold with a tag name if you want to ' 'use stashing' ) item, att_names = self._get_item_and_att_name...
[ "\n The stash method allows you to stash values for later analysis. The\n arguments are identical to the ``show()`` method. Instead of writing\n outpout, however, the ``stash()`` method populates a global list with\n the values that would have been printed. This allows them to be\n ...
Please provide a description of the function:def is_true(self, item=None): if item: values = [item] else: values = [] self._get_item_and_att_names(*values) return self._passes_all
[ "\n If you are filtering on object values, you need to pass that object here.\n " ]
Please provide a description of the function:def show(self, *values, **data): item, att_names = self._get_item_and_att_names(*values, **data) if not item: self.reset() return False self._strict_checker(att_names, item=item) # set the string value ...
[ "\n :type values: str arguments\n :param values: A list of variable or attribute names you want to print.\n At most one argument can be something other than a\n string. Strings are interpreted as the\n variable/attribute names you want...
Please provide a description of the function:def extract(self, item, name): val = '' if hasattr(item, name): val = getattr(item, name) return str(val)
[ "\n You should never need to call this method when you are debugging. It is\n an internal method that is nevertheless exposed to allow you to\n implement custom extraction logic for variables/attributes.\n\n This method is responsible for turning attributes into strings for\n pri...
Please provide a description of the function:def _parse_html(self): self.parsed_html = soup = BeautifulSoup(self.html, 'html.parser') self.scripts = [script['src'] for script in soup.findAll('script', src=True)] self.meta = { meta['name'].lower(): ...
[ "\n Parse the HTML with BeautifulSoup to find <script> and <meta> tags.\n " ]
Please provide a description of the function:def new_from_url(cls, url, verify=True): response = requests.get(url, verify=verify, timeout=2.5) return cls.new_from_response(response)
[ "\n Constructs a new WebPage object for the URL,\n using the `requests` module to fetch the HTML.\n\n Parameters\n ----------\n\n url : str\n verify: bool\n " ]
Please provide a description of the function:def new_from_response(cls, response): return cls(response.url, html=response.text, headers=response.headers)
[ "\n Constructs a new WebPage object for the response,\n using the `BeautifulSoup` module to parse the HTML.\n\n Parameters\n ----------\n\n response : requests.Response object\n " ]
Please provide a description of the function:def _prepare_app(self, app): # Ensure these keys' values are lists for key in ['url', 'html', 'script', 'implies']: try: value = app[key] except KeyError: app[key] = [] else: ...
[ "\n Normalize app data, preparing it for the detection phase.\n " ]
Please provide a description of the function:def _prepare_pattern(self, pattern): regex, _, rest = pattern.partition('\\;') try: return re.compile(regex, re.I) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" ...
[ "\n Strip out key:value pairs from the pattern and compile the regular\n expression.\n " ]
Please provide a description of the function:def _has_app(self, app, webpage): # Search the easiest things first and save the full-text search of the # HTML for last for regex in app['url']: if regex.search(webpage.url): return True for name, regex ...
[ "\n Determine whether the web page matches the app signature.\n " ]
Please provide a description of the function:def _get_implied_apps(self, detected_apps): def __get_implied_apps(apps): _implied_apps = set() for app in apps: try: _implied_apps.update(set(self.apps[app]['implies'])) except KeyE...
[ "\n Get the set of apps implied by `detected_apps`.\n " ]
Please provide a description of the function:def get_categories(self, app_name): cat_nums = self.apps.get(app_name, {}).get("cats", []) cat_names = [self.categories.get("%s" % cat_num, "") for cat_num in cat_nums] return cat_names
[ "\n Returns a list of the categories for an app name.\n " ]
Please provide a description of the function:def analyze(self, webpage): detected_apps = set() for app_name, app in self.apps.items(): if self._has_app(app, webpage): detected_apps.add(app_name) detected_apps |= self._get_implied_apps(detected_apps) ...
[ "\n Return a list of applications that can be detected on the web page.\n " ]
Please provide a description of the function:def analyze_with_categories(self, webpage): detected_apps = self.analyze(webpage) categorised_apps = {} for app_name in detected_apps: cat_names = self.get_categories(app_name) categorised_apps[app_name] = {"categorie...
[ "\n Return a list of applications and categories that can be detected on the web page.\n " ]
Please provide a description of the function:def clean(self): if self._initialized: logger.info("brace yourselves, removing %r", self.path) shutil.rmtree(self.path)
[ "\n remove the directory we operated on\n\n :return: None\n " ]
Please provide a description of the function:def initialize(self): if not self._initialized: logger.info("initializing %r", self) if not os.path.exists(self.path): if self.mode is not None: os.makedirs(self.path, mode=self.mode) ...
[ "\n create the directory if needed and configure it\n\n :return: None\n " ]
Please provide a description of the function:def _set_selinux_context(self): chcon_command_exists() # FIXME: do this using python API if possible if self.selinux_context: logger.debug("setting SELinux context of %s to %s", self.path, self.selinux_context) run_cmd...
[ "\n Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException\n if the command is not present on the system.\n\n :return: None\n " ]
Please provide a description of the function:def _set_ownership(self): if self.owner or self.group: args = ( self.path, self.owner if self.owner else -1, self.group if self.group else -1, ) logger.debug("changing owners...
[ "\n set ownership of the directory: user and group\n\n :return: None\n " ]
Please provide a description of the function:def _set_mode(self): if self.mode is not None: logger.debug("changing permission bits of %s to %s", self.path, oct(self.mode)) os.chmod(self.path, self.mode)
[ "\n set permission bits if needed using python API os.chmod\n\n :return: None\n " ]
Please provide a description of the function:def _add_facl_rules(self): setfacl_command_exists() # we are not using pylibacl b/c it's only for python 2 if self.facl_rules: logger.debug("adding ACLs %s to %s", self.facl_rules, self.path) r = ",".join(self.facl_rul...
[ "\n Apply ACL rules on the directory using setfacl program. Raises CommandDoesNotExistException\n if the command is not present on the system.\n\n :return: None\n " ]
Please provide a description of the function:def create_from_tuple(cls, volume): if isinstance(volume, six.string_types): return Volume(target=volume) elif len(volume) == 2: return Volume(source=volume[0], target=volume[1]) elif len(volu...
[ "\n Create instance from tuple.\n :param volume: tuple in one one of the following forms: target | source,target | source,target,mode\n :return: instance of Volume\n " ]
Please provide a description of the function:def tag_image(self, repository=None, tag=None): if not (repository or tag): raise ValueError("You need to specify either repository or tag.") r = repository or self.name t = tag or "latest" identifier = self._id or self.ge...
[ "\n Apply additional tags to the image or a new name\n >> podman tag image[:tag] target-name[:tag]\n\n :param repository: str, see constructor\n :param tag: str, see constructor\n :return: instance of PodmanImage\n " ]
Please provide a description of the function:def rmi(self, force=False, via_name=False): identifier = self.get_full_name() if via_name else (self._id or self.get_id()) cmdline = ["podman", "rmi", identifier, "--force" if force else ""] run_cmd(cmdline)
[ "\n remove this image\n\n :param force: bool, force removal of the image\n :param via_name: bool, refer to the image via name, if false, refer via ID\n :return: None\n " ]
Please provide a description of the function:def _run_container(self, run_command_instance, callback): tmpfile = os.path.join(get_backend_tmpdir(), random_tmp_filename()) # the cid file must not exist run_command_instance.options += ["--cidfile=%s" % tmpfile] logger.debug("podma...
[ " this is internal method " ]
Please provide a description of the function:def _file_not_empty(tmpfile): if os.path.exists(tmpfile): return os.stat(tmpfile).st_size != 0 else: return False
[ "\n Returns True if file exists and it is not empty\n to check if it is time to read container ID from cidfile\n :param tmpfile: str, path to file\n :return: bool, True if container id is written to the file\n " ]
Please provide a description of the function:def run_via_binary(self, run_command_instance=None, command=None, volumes=None, additional_opts=None, **kwargs): logger.info("run container via binary in background") if (command is not None or additional_opts is not None) \ ...
[ "\n create a container using this image and run it in background;\n this method is useful to test real user scenarios when users invoke containers using\n binary\n\n :param run_command_instance: instance of PodmanRunBuilder\n :param command: list of str, command to run in the cont...
Please provide a description of the function:def run_via_binary_in_foreground( self, run_command_instance=None, command=None, volumes=None, additional_opts=None, popen_params=None, container_name=None): logger.info("run container via binary in foreground") if (command i...
[ "\n Create a container using this image and run it in foreground;\n this method is useful to test real user scenarios when users invoke containers using\n binary and pass input into the container via STDIN. You are also responsible for:\n\n * redirecting STDIN when intending to use cont...
Please provide a description of the function:def get_volume_options(volumes): if not isinstance(volumes, list): volumes = [volumes] volumes = [Volume.create_from_tuple(v) for v in volumes] result = [] for v in volumes: result += ["-v", str(v)] ret...
[ "\n Generates volume options to run methods.\n\n :param volumes: tuple or list of tuples in form target x source,target x source,target,mode.\n :return: list of the form [\"-v\", \"/source:/target\", \"-v\", \"/other/source:/destination:z\", ...]\n " ]
Please provide a description of the function:def get_layer_ids(self, rev=True): cmdline = ["podman", "history", "--format", "{{.ID}}", self._id or self.get_id()] layers = [layer for layer in run_cmd(cmdline, return_output=True)] if not rev: layers = layers.reverse() ...
[ "\n Get IDs of image layers\n\n :param rev: get layers reversed\n :return: list of strings\n " ]