text
stringlengths
81
112k
Add a message to the outgoing queue. :arg signature: the signature of the message :arg fields: the fields of the message as a tuple :arg response: a response object to handle callbacks def _append(self, signature, fields=(), response=None): """ Add a message to the outgoing queue. ...
Add a RESET message to the outgoing queue, send it and consume all remaining messages. def reset(self): """ Add a RESET message to the outgoing queue, send it and consume all remaining messages. """ def fail(metadata): raise ProtocolError("RESET failed %r" % metadat...
Send all queued messages to the server. def _send(self): """ Send all queued messages to the server. """ data = self.output_buffer.view() if not data: return if self.closed(): raise self.Error("Failed to write to closed connection {!r}".format(self.server...
Receive at least one message from the server, if available. :return: 2-tuple of number of detail messages and number of summary messages fetched def _fetch(self): """ Receive at least one message from the server, if available. :return: 2-tuple of number of detail messages and number of summar...
Send and fetch all outstanding messages. :return: 2-tuple of number of detail messages and number of summary messages fetched def sync(self): """ Send and fetch all outstanding messages. :return: 2-tuple of number of detail messages and number of summary messages fetched """ s...
Close the connection. def close(self): """ Close the connection. """ if not self._closed: if self.protocol_version >= 3: log_debug("[#%04X] C: GOODBYE", self.local_port) self._append(b"\x02", ()) try: self.send() ...
Acquire a connection to a given address from the pool. The address supplied should always be an IP address, not a host name. This method is thread safe. def acquire_direct(self, address): """ Acquire a connection to a given address from the pool. The address supplied should alw...
Release a connection back into the pool. This method is thread safe. def release(self, connection): """ Release a connection back into the pool. This method is thread safe. """ with self.lock: connection.in_use = False self.cond.notify_all()
Count the number of connections currently in use to a given address. def in_use_connection_count(self, address): """ Count the number of connections currently in use to a given address. """ try: connections = self.connections[address] except KeyError: ...
Deactivate an address from the connection pool, if present, closing all idle connection to that address def deactivate(self, address): """ Deactivate an address from the connection pool, if present, closing all idle connection to that address """ with self.lock: try:...
Remove an address from the connection pool, if present, closing all connections to that address. def remove(self, address): """ Remove an address from the connection pool, if present, closing all connections to that address. """ with self.lock: for connection in self...
Close all connections and empty the pool. This method is thread safe. def close(self): """ Close all connections and empty the pool. This method is thread safe. """ if self._closed: return try: with self.lock: if not self._closed: ...
Called when one or more RECORD messages have been received. def on_records(self, records): """ Called when one or more RECORD messages have been received. """ handler = self.handlers.get("on_records") if callable(handler): handler(records)
Called when a SUCCESS message has been received. def on_success(self, metadata): """ Called when a SUCCESS message has been received. """ handler = self.handlers.get("on_success") if callable(handler): handler(metadata) handler = self.handlers.get("on_summary") ...
Called when a FAILURE message has been received. def on_failure(self, metadata): """ Called when a FAILURE message has been received. """ self.connection.reset() handler = self.handlers.get("on_failure") if callable(handler): handler(metadata) handler = self....
Called when an IGNORED message has been received. def on_ignored(self, metadata=None): """ Called when an IGNORED message has been received. """ handler = self.handlers.get("on_ignored") if callable(handler): handler(metadata) handler = self.handlers.get("on_summary"...
A replacement for the property decorator that will only compute the attribute's value on the first call and serve a cached copy from then on. def cached_property(prop): """ A replacement for the property decorator that will only compute the attribute's value on the first call and serve a cached cop...
Converts pysnmp objects into native Python objects. def _convert_value_to_native(value): """ Converts pysnmp objects into native Python objects. """ if isinstance(value, Counter32): return int(value.prettyPrint()) if isinstance(value, Counter64): return int(value.prettyPrint()) ...
Get a single OID value. def get(self, oid): """ Get a single OID value. """ snmpsecurity = self._get_snmp_security() try: engine_error, pdu_error, pdu_error_index, objects = self._cmdgen.getCmd( snmpsecurity, cmdgen.UdpTransportTarget...
Sets a single OID value. If you do not pass value_type hnmp will try to guess the correct type. Autodetection is supported for: * int and float (as Integer, fractional part will be discarded) * IPv4 address (as IpAddress) * str (as OctetString) Unfortunately, pysnmp does not su...
Get a table of values with the given OID prefix. def table(self, oid, columns=None, column_value_mapping=None, non_repeaters=0, max_repetitions=20, fetch_all_columns=True): """ Get a table of values with the given OID prefix. """ snmpsecurity = self._get_snmp_security() ...
Load parser for command line arguments. It parses argv/input into args variable. def get_parser(): """Load parser for command line arguments. It parses argv/input into args variable. """ desc = Colors.LIGHTBLUE + textwrap.dedent( '''\ Welcome to _ ...
Insert args values into instance variables. def insert(args): """Insert args values into instance variables.""" string_search = args.str_search mode_search = MODES[args.mode] page = list(TORRENTS[args.torr_page].keys())[0] key_search = TORRENTS[args.torr_page][page]['key_search'] torrent_page =...
Search and download torrents until the user says it so. def run_it(): """Search and download torrents until the user says it so.""" initialize() parser = get_parser() args = None first_parse = True while(True): if first_parse is True: first_parse = False args = p...
Open magnet according to os. def open_magnet(self): """Open magnet according to os.""" if sys.platform.startswith('linux'): subprocess.Popen(['xdg-open', self.magnet], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif sys.platform.startswith('win32'):...
Get magnet from torrent page. Url already got domain. def get_magnet(self, url): """Get magnet from torrent page. Url already got domain.""" content_most_rated = requests.get(url) rated_soup = BeautifulSoup(content_most_rated.content, 'lxml') if self.page == 'torrent_project': ...
Download torrent. Rated implies download the unique best rated torrent found. Otherwise: get the magnet and download it. def download_torrent(self): """Download torrent. Rated implies download the unique best rated torrent found. Otherwise: get the magnet and download it. ...
Build table. def build_table(self): """Build table.""" headers = ['Title', 'Seeders', 'Leechers', 'Age', 'Size'] titles = [] seeders = [] leechers = [] ages = [] sizes = [] if self.page == 'torrent_project': titles = [list(span.find('a').stri...
Get proper torrent/magnet information. If search_mode is rated then get torrent/magnet. If not, get all the elements to build the table. There are different ways for each page. def soupify(self): """Get proper torrent/magnet information. If search_mode is rated then get torren...
Handle user's input in list mode. def handle_select(self): """Handle user's input in list mode.""" self.selected = input('>> ') if self.selected in ['Q', 'q']: sys.exit(1) elif self.selected in ['B', 'b']: self.back_to_menu = True return True ...
Select torrent. First check if specific element/info is obtained in content_page. Specify to user if it wants best rated torrent or select one from list. If the user wants best rated: Directly obtain magnet/torrent. Else: build table with all data and enable the user select the torrent....
Build appropiate encoded URL. This implies the same way of searching a torrent as in the page itself. def build_url(self): """Build appropiate encoded URL. This implies the same way of searching a torrent as in the page itself. """ url = requests.utils.requote_uri( ...
Get content of the page through url. def get_content(self): """Get content of the page through url.""" url = self.build_url() try: self.content_page = requests.get(url) if not(self.content_page.status_code == requests.codes.ok): self.content_page.raise_fo...
Reclaim buffer space before the origin. Note: modifies buffer size def _recycle(self): """ Reclaim buffer space before the origin. Note: modifies buffer size """ origin = self._origin if origin == 0: return False available = self._extent - origin ...
Construct a frame around the first complete message in the buffer. def frame_message(self): """ Construct a frame around the first complete message in the buffer. """ if self._frame is not None: self.discard_message() panes = [] p = origin = self._origin exte...
Rate limit the call to request_function. :param request_function: A function call that returns an HTTP response object. :param set_header_callback: A callback function used to set the request headers. This callback is called after any necessary sleep time occurs. ...
Sleep for an amount of time to remain under the rate limit. def delay(self): """Sleep for an amount of time to remain under the rate limit.""" if self.next_request_timestamp is None: return sleep_seconds = self.next_request_timestamp - time.time() if sleep_seconds <= 0: ...
Update the state of the rate limiter based on the response headers. This method should only be called following a HTTP request to reddit. Response headers that do not contain x-ratelimit fields will be treated as a single request. This behavior is to error on the safe-side as such resp...
If a custom resolver is defined, perform custom resolution on the contained addresses. :return: def custom_resolve(self): """ If a custom resolver is defined, perform custom resolution on the contained addresses. :return: """ if not callable(self.custom_resolve...
Perform DNS resolution on the contained addresses. :return: def dns_resolve(self): """ Perform DNS resolution on the contained addresses. :return: """ new_addresses = [] for address in self.addresses: try: info = getaddrinfo(address[0], addr...
Gets the quality of a network / cell. @param string cell A network / cell from iwlist scan. @return string The quality of the network. def get_quality(cell): """ Gets the quality of a network / cell. @param string cell A network / cell from iwlist scan. @return string ...
Gets the signal level of a network / cell. @param string cell A network / cell from iwlist scan. @return string The signal level of the network. def get_signal_level(cell): """ Gets the signal level of a network / cell. @param string cell A network / cell from iwlist scan. ...
Gets the noise level of a network / cell. @param string cell A network / cell from iwlist scan. @return string The noise level of the network. def get_noise_level(cell): """ Gets the noise level of a network / cell. @param string cell A network / cell from iwlist scan. @re...
Gets the channel of a network / cell. @param string cell A network / cell from iwlist scan. @return string The channel of the network. def get_channel(cell): """ Gets the channel of a network / cell. @param string cell A network / cell from iwlist scan. @return string ...
Gets the encryption type of a network / cell. @param string cell A network / cell from iwlist scan. @return string The encryption type of the network. def get_encryption(cell, emit_version=False): """ Gets the encryption type of a network / cell. @param string cell A network / ...
Returns the first matching line in a list of lines. @see match() def matching_line(lines, keyword): """ Returns the first matching line in a list of lines. @see match() """ for line in lines: matching = match(line,keyword) if matching != None: return matching return ...
If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise checks if keyword is anywhere in the line and returns that section, else returns None def match(line, keyword): """ If the first part of line (modulo blanks) matches keyword, returns the end of that line....
Applies the rules to the bunch of text describing a cell. @param string cell A network / cell from iwlist scan. @param dictionary rules A dictionary of parse rules. @return dictionary parsed networks. def parse_cell(cell, rules): """ Applies the rules to the bunch of text descr...
Parses iwlist output into a list of networks. @param list iw_data Output from iwlist scan. A list of strings. @return list properties: Name, Address, Quality, Channel, Frequency, Encryption, Signal Level, Noise Level, Bit Rates, Mode. def get_parsed_cells(iw_data, r...
Return the json content from the resource at ``path``. :param method: The request verb. E.g., get, post, put. :param path: The path of the request. This path will be combined with the ``oauth_url`` of the Requestor. :param data: Dictionary, bytes, or file-like object to send in the ...
Provide the program's entry point when directly executed. def main(): """Provide the program's entry point when directly executed.""" authenticator = prawcore.TrustedAuthenticator( prawcore.Requestor("prawcore_script_auth_example"), os.environ["PRAWCORE_CLIENT_ID"], os.environ["PRAWCORE...
Provide the program's entry point when directly executed. def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print("Usage: {} USERNAME".format(sys.argv[0])) return 1 caching_requestor = prawcore.Requestor( "prawcore_device_id_auth_exa...
Perform a request, or return a cached response if available. def request(self, method, url, params=None, **kwargs): """Perform a request, or return a cached response if available.""" params_key = tuple(params.items()) if params else () if method.upper() == "GET": if (url, params_key...
Parse the records returned from a getServers call and return a new RoutingTable instance. def parse_routing_info(cls, records): """ Parse the records returned from a getServers call and return a new RoutingTable instance. """ if len(records) != 1: raise RoutingProtoc...
Indicator for whether routing information is still usable. def is_fresh(self, access_mode): """ Indicator for whether routing information is still usable. """ log_debug("[#0000] C: <ROUTING> Checking table freshness for %r", access_mode) expired = self.last_updated_time + self.ttl <= s...
Update the current routing table with new routing information from a replacement table. def update(self, new_routing_table): """ Update the current routing table with new routing information from a replacement table. """ self.routers.replace(new_routing_table.routers) se...
Fetch raw routing info from a given router address. :param address: router address :return: list of routing records or None if no connection could be established :raise ServiceUnavailable: if the server does not support routing or if routing s...
Fetch a routing table from a given router address. :param address: router address :return: a new RoutingTable instance or None if the given router is currently unable to provide routing information :raise ServiceUnavailable: if no writers are available :raise ProtocolEr...
Try to update routing tables with the given routers. :return: True if the routing table is successfully updated, otherwise False def update_routing_table_from(self, *routers): """ Try to update routing tables with the given routers. :return: True if the routing table is successfully updated, ...
Update the routing table from the first router able to provide valid routing information. def update_routing_table(self): """ Update the routing table from the first router able to provide valid routing information. """ # copied because it can be modified existing_router...
Update the routing table if stale. This method performs two freshness checks, before and after acquiring the refresh lock. If the routing table is already fresh on entry, the method exits immediately; otherwise, the refresh lock is acquired and the second freshness check that follows de...
Deactivate an address from the connection pool, if present, remove from the routing table and also closing all idle connections to that address. def deactivate(self, address): """ Deactivate an address from the connection pool, if present, remove from the routing table and also closing ...
Remove a writer address from the routing table, if present. def remove_writer(self, address): """ Remove a writer address from the routing table, if present. """ log_debug("[#0000] C: <ROUTING> Removing writer %r", address) self.routing_table.writers.discard(address) log_debug(...
Handle any cleanup or similar activity related to an error occurring on a pooled connection. def handle(self, error, connection): """ Handle any cleanup or similar activity related to an error occurring on a pooled connection. """ error_class = error.__class__ if error_c...
Dynamically create a Point subclass. def point_type(name, fields, srid_map): """ Dynamically create a Point subclass. """ def srid(self): try: return srid_map[len(self)] except KeyError: return None attributes = {"srid": property(srid)} for index, subclass...
Provide the program's entry point when directly executed. def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print("Usage: {} USERNAME".format(sys.argv[0])) return 1 authenticator = prawcore.TrustedAuthenticator( prawcore.Requestor("p...
Read a directory containing json files for Kibana panels, beautify them and replace size value in aggregations as specified through corresponding params params. def main(): """Read a directory containing json files for Kibana panels, beautify them and replace size value in aggregations as specified ...
Parse arguments from the command line def parse_args(): """Parse arguments from the command line""" parser = argparse.ArgumentParser(description=TO_KIBANA5_DESC_MSG) parser.add_argument('-s', '--source', dest='src_path', \ required=True, help='source directory') parser.add_argument('-d', '--d...
Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode def configure_logging(debug=False): """Configure logging The function configures log messages. By default, ...
Quit signal handler. def signal_handler(signal_name, frame): """Quit signal handler.""" sys.stdout.flush() print("\nSIGINT in frame signal received. Quitting...") sys.stdout.flush() sys.exit(0)
Show changes graphically in memory consumption def graph_format(new_mem, old_mem, is_firstiteration=True): """Show changes graphically in memory consumption""" if is_firstiteration: output = " n/a " elif new_mem - old_mem > 50000000: output = " +++++" elif new_mem - old_mem > 20000...
return utilization of memory def get_cur_mem_use(): """return utilization of memory""" # http://lwn.net/Articles/28345/ lines = open("/proc/meminfo", 'r').readlines() emptySpace = re.compile('[ ]+') for line in lines: if "MemTotal" in line: memtotal = float(emptySpace.split(lin...
Check if a propper Python version is used. def check_py_version(): """Check if a propper Python version is used.""" try: if sys.version_info >= (2, 7): return except: pass print(" ") print(" ERROR - memtop needs python version at least 2.7") print(("Chances are that ...
Prompt a single character. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a single-character, non-empty string. None if the user pr...
Prompt an email address. This check is based on a simple regular expression and does not verify whether an email actually exists. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. mode : {'simple'}, optio...
Prompt an integer. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- int or None An int if the user entered a valid integer. None if the user pressed only Enter and ``empty...
Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter a...
Prompt a string that matches a regular expression. Parameters ---------- pattern : str A regular expression that must be matched. prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. flags : int, optional Flags that wi...
Prompt a string without echoing. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a non-empty string. None if the user pressed only E...
Prompt a string. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- str or None A str if the user entered a non-empty string. None if the user pressed only Enter and ``empty...
Return a cache region plus key. def _get_cache_plus_key(self): """Return a cache region plus key.""" key = getattr(self, '_cache_key', self.key_from_query()) return self._cache.cache, key
Return the value from the cache for this query. def get_value(self, merge=True, createfunc=None, expiration_time=None, ignore_expiration=False): """ Return the value from the cache for this query. """ cache, cache_key = self._get_cache_plus_key() # ignore_expi...
Set the value in the cache for this query. def set_value(self, value): """Set the value in the cache for this query.""" cache, cache_key = self._get_cache_plus_key() cache.set(cache_key, value)
Given a Query, create a cache key. There are many approaches to this; here we use the simplest, which is to create an md5 hash of the text of the SQL statement, combined with stringified versions of all the bound parameters within it. There's a bit of a performance hit with compiling o...
Process a Query that is used within a lazy loader. (the process_query_conditionally() method is a SQLAlchemy hook invoked only within lazyload.) def process_query_conditionally(self, query): """ Process a Query that is used within a lazy loader. (the process_query_conditionall...
Fit the smoother Parameters ---------- t : array_like time locations of the points to smooth y : array_like y locations of the points to smooth dy : array_like or float (default = 1) Errors in the y values presorted : bool (default = F...
Predict the smoothed function value at time t Parameters ---------- t : array_like Times at which to predict the result Returns ------- y : ndarray Smoothed values at time t def predict(self, t): """Predict the smoothed function value at...
Return the residuals of the cross-validation for the fit data def cv_residuals(self, cv=True): """Return the residuals of the cross-validation for the fit data""" vals = self.cv_values(cv) return (self.y - vals) / self.dy
Return the sum of cross-validation residuals for the input data def cv_error(self, cv=True, skip_endpoints=True): """Return the sum of cross-validation residuals for the input data""" resids = self.cv_residuals(cv) if skip_endpoints: resids = resids[1:-1] return np.mean(abs(...
Return a generator for the ARCFOUR/RC4 pseudorandom keystream for the key provided. Keys should be byte strings or sequences of ints. def arcfour(key, csbN=1): '''Return a generator for the ARCFOUR/RC4 pseudorandom keystream for the key provided. Keys should be byte strings or sequences of ints.''' if isin...
Return a generator for the RC4-drop pseudorandom keystream given by the key and number of bytes to drop passed as arguments. Dropped bytes default to the more conservative 3072, NOT the SCAN default of 768. def arcfour_drop(key, n=3072): '''Return a generator for the RC4-drop pseudorandom keystream given by ...
Look up an SSL protocol version by name. If *version* is not specified, then the strongest protocol available will be returned. :param str version: The name of the version to look up. :return: A protocol constant from the :py:mod:`ssl` module. :rtype: int def resolve_ssl_protocol_version(version=None): """ Look...
Build a server from command line arguments. If a ServerClass or HandlerClass is specified, then the object must inherit from the corresponding AdvancedHTTPServer base class. :param str description: Description string to be passed to the argument parser. :param server_klass: Alternative server class to use. :type ...
Build a server from a provided :py:class:`configparser.ConfigParser` instance. If a ServerClass or HandlerClass is specified, then the object must inherit from the corresponding AdvancedHTTPServer base class. :param config: Configuration to retrieve settings from. :type config: :py:class:`configparser.ConfigParse...
Configure the serializer to use for communication with the server. The serializer specified must be valid and in the :py:data:`.g_serializer_drivers` map. :param str serializer_name: The name of the serializer to use. :param str compression: The name of a compression library to use. def set_serializer(self, s...
Reconnect to the remote server. def reconnect(self): """Reconnect to the remote server.""" self.lock.acquire() if self.use_ssl: self.client = http.client.HTTPSConnection(self.host, self.port, context=self.ssl_context) else: self.client = http.client.HTTPConnection(self.host, self.port) self.lock.releas...
Issue a call to the remote end point to execute the specified procedure. :param str method: The name of the remote procedure to execute. :return: The return value from the remote function. def call(self, method, *args, **kwargs): """ Issue a call to the remote end point to execute the specified procedure....
Call a remote method and store the result locally. Subsequent calls to the same method with the same arguments will return the cached result without invoking the remote procedure. Cached results are kept indefinitely and must be manually refreshed with a call to :py:meth:`.cache_call_refresh`. :param str met...
Call a remote method and update the local cache with the result if it already existed. :param str method: The name of the remote procedure to execute. :return: The return value from the remote function. def cache_call_refresh(self, method, *options): """ Call a remote method and update the local cache with ...
Purge the local store of all cached function information. def cache_clear(self): """Purge the local store of all cached function information.""" with self.cache_lock: cursor = self.cache_db.cursor() cursor.execute('DELETE FROM cache') self.cache_db.commit() self.logger.info('the RPC cache has been purge...