text
stringlengths
81
112k
Return the list of available files in the coverage report. def files(self): """ Return the list of available files in the coverage report. """ # maybe replace with a trie at some point? see has_file FIXME already_seen = set() filenames = [] for el in self.xml.xp...
Return a list for source lines of file `filename`. def source_lines(self, filename): """ Return a list for source lines of file `filename`. """ with self.filesystem.open(filename) as f: return f.readlines()
Return `True` if coverage of has improved, `False` otherwise. This does not ensure that all changes have been covered. If this is what you want, use `CoberturaDiff.has_all_changes_covered()` instead. def has_better_coverage(self): """ Return `True` if coverage of has improved, `False` ...
Return `True` if all changes have been covered, `False` otherwise. def has_all_changes_covered(self): """ Return `True` if all changes have been covered, `False` otherwise. """ for filename in self.files(): for hunk in self.file_source_hunks(filename): for li...
Return the difference between `self.cobertura2.<attr_name>(filename)` and `self.cobertura1.<attr_name>(filename)`. This generic method is meant to diff the count of methods that return counts for a given file `filename`, e.g. `Cobertura.total_statements`, `Cobertura.total_misses...
Return a list of 2-element tuples `(lineno, is_new)` for the given file `filename` where `lineno` is a missed line number and `is_new` indicates whether the missed line was introduced (True) or removed (False). def diff_missed_lines(self, filename): """ Return a list of 2-elemen...
Return a list of namedtuple `Line` for each line of code found in the given file `filename`. def file_source(self, filename): """ Return a list of namedtuple `Line` for each line of code found in the given file `filename`. """ if self.cobertura1.has_file(filename) and \...
Like `CoberturaDiff.file_source`, but returns a list of line hunks of the lines that have changed for the given file `filename`. An empty list means that the file has no lines that have a change in coverage status. def file_source_hunks(self, filename): """ Like `CoberturaDiff.f...
Flushes the queue periodically. def monitor(self): """Flushes the queue periodically.""" while self.monitor_running.is_set(): if time.time() - self.last_flush > self.batch_time: if not self.queue.empty(): logger.info("Queue Flush: time without flush excee...
Add a list of data records to the record queue in the proper format. Convinience method that calls self.put_record for each element. Parameters ---------- records : list Lists of records to send. partition_key: str Hash that determines which shard a given...
Add data to the record queue in the proper format. Parameters ---------- data : str Data to send. partition_key: str Hash that determines which shard a given data record belongs to. def put_record(self, data, partition_key=None): """Add data to the recor...
Flushes the queue and waits for the executor to finish. def close(self): """Flushes the queue and waits for the executor to finish.""" logger.info('Closing producer') self.flush_queue() self.monitor_running.clear() self.pool.shutdown() logger.info('Producer closed')
Grab all the current records in the queue and send them. def flush_queue(self): """Grab all the current records in the queue and send them.""" records = [] while not self.queue.empty() and len(records) < self.batch_size: records.append(self.queue.get()) if records: ...
Send records to the Kinesis stream. Falied records are sent again with an exponential backoff decay. Parameters ---------- records : array Array of formated records to send. attempt: int Number of times the records have been sent without success. def se...
Assumes the list is sorted. def rangify(number_list): """Assumes the list is sorted.""" if not number_list: return number_list ranges = [] range_start = prev_num = number_list[0] for num in number_list[1:]: if num != (prev_num + 1): ranges.append((range_start, prev_num...
Given the following input: >>> lines_w_status = [ (1, True), (4, True), (7, False), (9, False), ] Return expanded lines with their extrapolated line status. >>> extrapolate_coverage(lines_w_status) == [ (1, True), (2, True), (3, True), (...
Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1` of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines that are common in both sets are present in the dict, lines unique to one of the sets are omitted. def reconcile_lines(lines1, lines2): """ Return a dic...
Return a list of line hunks given a list of lines `lines`. The number of context lines can be control with `context` which will return line hunks surrounded with `context` lines before and after the code change. def hunkify_lines(lines, context=3): """ Return a list of line hunks given a list of lines ...
show coverage summary of a Cobertura report def show(cobertura_file, format, output, source, source_prefix): """show coverage summary of a Cobertura report""" cobertura = Cobertura(cobertura_file, source=source) Reporter = reporters[format] reporter = Reporter(cobertura) report = reporter.generate(...
compare coverage of two Cobertura reports def diff( cobertura_file1, cobertura_file2, color, format, output, source1, source2, source_prefix1, source_prefix2, source): """compare coverage of two Cobertura reports""" cobertura1 = Cobertura( cobertura_file1, source=source1...
Yield a file-like object for file `filename`. This function is a context manager. def open(self, filename): """ Yield a file-like object for file `filename`. This function is a context manager. """ filename = self.real_filename(filename) if not os.path.exists(...
Injecting message into topic. if _msg_content, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _msg_content: optional message content :param kwargs: each extra kwarg will be put int he message is structure matches :return: def topic_inj...
Setting parameter. if _value, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _value: optional value :param kwargs: each extra kwarg will be put in the value if structure matches :return: def param_set(self, param_name, _value=None, **k...
runner def run(self): """runner""" # change version in code and changelog before running this subprocess.check_call("git commit CHANGELOG.rst pyros/_version.py CHANGELOG.rst -m 'v{0}'".format(__version__), shell=True) subprocess.check_call("git push", shell=True) print("You sh...
Start a pyros node. :param interface: the interface implementation (ROS, Mock, ZMP, etc.) :param config: the config file path, absolute, or relative to working directory :param logfile: the logfile path, absolute, or relative to working directory :param ros_args: the ros arguments (useful to absorb addi...
store nick, user, host in kwargs if prefix is correct format def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None: """ store nick, user, host in kwargs if prefix is correct format """ if "!" in prefix and "@" in prefix: # From a user kwargs["nick"], remainder = prefix.split("!", 1) ...
Parse message according to rfc 2812 for routing def split_line(msg: str) -> Tuple[str, str, List[str]]: """ Parse message according to rfc 2812 for routing """ match = RE_IRCLINE.match(msg) if not match: raise ValueError("Invalid line") prefix = match.group("prefix") or "" command = match....
Return `present` value (default to `field`) if `field` in `kwargs` and Truthy, otherwise return `missing` value def b(field: str, kwargs: Dict[str, Any], present: Optional[Any] = None, missing: Any = '') -> str: """ Return `present` value (default to `field`) if `field` in `kwargs` and Truthy, ot...
Alias for more readable command construction def f(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None) -> str: """ Alias for more readable command construction """ if default is not None: return str(kwargs.get(field, default)) return str(kwargs[field])
Util for joining multiple fields with commas def pack(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None, sep: str=',') -> str: """ Util for joining multiple fields with commas """ if default is not None: value = kwargs.get(field, default) else: value = kwargs[field]...
Pack a command to send to an IRC server def pack_command(command: str, **kwargs: Any) -> str: """ Pack a command to send to an IRC server """ if not command: raise ValueError("Must provide a command") if not isinstance(command, str): raise ValueError("Command must be a string") command ...
Open a connection to the defined server. async def connect(self) -> None: """Open a connection to the defined server.""" def protocol_factory() -> Protocol: return Protocol(client=self) _, protocol = await self.loop.create_connection( protocol_factory, host=...
Trigger all handlers for an event to (asynchronously) execute def trigger(self, event: str, **kwargs: Any) -> None: """Trigger all handlers for an event to (asynchronously) execute""" event = event.upper() for func in self._event_handlers[event]: self.loop.create_task(func(**kwargs)...
Decorate a function to be invoked when the given event occurs. The function may be a coroutine. Your function should accept **kwargs in case an event is triggered with unexpected kwargs. Example ------- import asyncio import bottom client = bottom.Client(...) ...
Send a message to the server. .. code-block:: python client.send("nick", nick="weatherbot") client.send("privmsg", target="#python", message="Hello, World!") def send(self, command: str, **kwargs: Any) -> None: """ Send a message to the server. .. code-block::...
client callback entrance def _handle(self, nick, target, message, **kwargs): """ client callback entrance """ for regex, (func, pattern) in self.routes.items(): match = regex.match(message) if match: self.client.loop.create_task( func(nick, ta...
parse commandline arguments and print result def main(): """parse commandline arguments and print result""" fcodes = collections.OrderedDict(( ('f.i', protocol.FLG_FORMAT_FDI), ('fi', protocol.FLG_FORMAT_FI), ('f.i.c', protocol.FLG_FORMAT_FDIDC), ('f.ic', protocol.FLG_FORMAT_FD...
parse commandline arguments and print result def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', ...
Constructs the url for a cheddar API resource def build_url(self, path, params=None): ''' Constructs the url for a cheddar API resource ''' url = u'%s/%s/productCode/%s' % ( self.endpoint, path, self.product_code, ) if params: ...
Makes a request to the cheddar api using the authentication and configuration settings available. def make_request(self, path, params=None, data=None, method=None): ''' Makes a request to the cheddar api using the authentication and configuration settings available. ''' ...
parse commandline arguments and print result def main(): """parse commandline arguments and print result""" # # setup command line parsing a la argpase # parser = argparse.ArgumentParser() # positional args parser.add_argument('uri', metavar='URI', nargs='?', default='/', ...
factory function that returns a proxy object for an owserver at host, port. def proxy(host='localhost', port=4304, flags=0, persistent=False, verbose=False, ): """factory function that returns a proxy object for an owserver at host, port. """ # resolve host name/port try: gai...
factory function for cloning a proxy object def clone(proxy, persistent=True): """factory function for cloning a proxy object""" if not isinstance(proxy, _Proxy): raise TypeError('argument is not a Proxy object') if persistent: pclass = _PersistentProxy else: pclass = _Proxy ...
shutdown connection def shutdown(self): """shutdown connection""" if self.verbose: print(self.socket.getsockname(), 'xx', self.peername) try: self.socket.shutdown(socket.SHUT_RDWR) except IOError as err: assert err.errno is _ENOTCONN, "unexpected IO...
send message to server and return response def req(self, msgtype, payload, flags, size=0, offset=0, timeout=0): """send message to server and return response""" if timeout < 0: raise ValueError("timeout cannot be negative!") tohead = _ToServerHeader(payload=len(payload), type=msgt...
send message to server def _send_msg(self, header, payload): """send message to server""" if self.verbose: print('->', repr(header)) print('..', repr(payload)) assert header.payload == len(payload) try: sent = self.socket.send(header + payload) ...
read message from server def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): ...
retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ flags |= self....
sends a NOP packet and waits response; returns None def ping(self): """sends a NOP packet and waits response; returns None""" ret, data = self.sendmess(MSG_NOP, bytes()) if data or ret > 0: raise ProtocolError('invalid reply to ping message') if ret < 0: raise O...
returns True if there is an entity at path def present(self, path, timeout=0): """returns True if there is an entity at path""" ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path), timeout=timeout) assert ret <= 0 and not data, (ret, data) if ret <...
list entities at path def dir(self, path='/', slash=True, bus=False, timeout=0): """list entities at path""" if slash: msg = MSG_DIRALLSLASH else: msg = MSG_DIRALL if bus: flags = self.flags | FLG_BUS_RET else: flags = self.flags ...
read data at path def read(self, path, size=MAX_PAYLOAD, offset=0, timeout=0): """read data at path""" if size > MAX_PAYLOAD: raise ValueError("size cannot exceed %d" % MAX_PAYLOAD) ret, data = self.sendmess(MSG_READ, str2bytez(path), size=size, o...
write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding. def write(self, path, data, offset=0, timeout=0): """write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding. ...
retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ # reus...
Returns all customers. Sometimes they are too much and cause internal server errors on CG. API call permits post parameters for filtering which tends to fix this https://cheddargetter.com/developers#all-customers filter_data Will be processed by urlencode and can be used f...
This method does exactly what you think it does. Calling this method deletes all customer data in your cheddar product and the configured gateway. This action cannot be undone. DO NOT RUN THIS UNLESS YOU REALLY, REALLY, REALLY MEAN TO! def delete_all_customers(self): ''' ...
An estimated initial bill date for an account created today, based on available plan info. def initial_bill_date(self): ''' An estimated initial bill date for an account created today, based on available plan info. ''' time_to_start = None if self.initia...
Add an arbitrary charge or credit to a customer's account. A positive number will create a charge. A negative number will create a credit. each_amount is normalized to a Decimal with a precision of 2 as that is the level of precision which the cheddar API supports. def charge(self, c...
Charges should be a list of charges to execute immediately. Each value in the charges diectionary should be a dictionary with the following keys: code Your code for this charge. This code will be displayed in the user's invoice and is limited to 36 characters. ...
Set the item's quantity to the passed in amount. If nothing is passed in, a quantity of 1 is assumed. If a decimal value is passsed in, it is rounded to the 4th decimal place as that is the level of precision which the Cheddar API accepts. def set(self, quantity): ''' Set the...
Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return bool: whether the two names are compatible def deep_compare(self, other, settings): """ Compares each ...
Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return int: sequence ratio match (out of 100) def ratio_deep_compare(self, other, settings): """ Compares eac...
Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes def _is_compatible_with(self, other): """ Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes """ ...
Return False if titles have different gender associations def _compare_title(self, other): """Return False if titles have different gender associations""" # If title is omitted, assume a match if not self.title or not other.title: return True titles = set(self.title_list +...
Return false if suffixes are mutually exclusive def _compare_suffix(self, other): """Return false if suffixes are mutually exclusive""" # If suffix is omitted, assume a match if not self.suffix or not other.suffix: return True # Check if more than one unique suffix ...
Return comparison of first, middle, and last components def _compare_components(self, other, settings, ratio=False): """Return comparison of first, middle, and last components""" first = compare_name_component( self.first_list, other.first_list, settings['first'], ...
Return weights of name components based on whether or not they were omitted def _determine_weights(self, other, settings): """ Return weights of name components based on whether or not they were omitted """ # TODO: Reduce weight for matches by prefix or initials ...
:param app: :class:`sanic.Sanic` instance to rate limit. def init_app(self, app): """ :param app: :class:`sanic.Sanic` instance to rate limit. """ self.enabled = app.config.setdefault(C.ENABLED, True) self._swallow_errors = app.config.setdefault( C.SWALLOW_ERRORS, se...
decorator to be used for rate limiting individual routes. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param function key_func: function/lambda to extract the unique identifier for the rate limit. defaults to rem...
decorator to be applied to multiple routes sharing the same rate limit. :param limit_value: rate limit string or a callable that returns a string. :ref:`ratelimit-string` for more details. :param scope: a string or callable that returns a string for defining the rate limiting scope. ...
resets the storage if it supports being reset def reset(self): """ resets the storage if it supports being reset """ try: self._storage.reset() self.logger.info("Storage has been reset and all limits cleared") except NotImplementedError: self....
Returns a bs4 object of the page requested def get_soup(page=''): """ Returns a bs4 object of the page requested """ content = requests.get('%s/%s' % (BASE_URL, page)).text return BeautifulSoup(content)
Takes two names and returns true if they describe the same person. :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict options: custom strictness settings updates :return bool: the names match def mat...
Takes two names and returns true if they describe the same person. Uses difflib's sequence matching on a per-field basis for names :param string fullname1: first human name :param string fullname2: second human name :param string strictness: strictness settings to use :param dict options: custom st...
Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. def _get_zipped_rows(self, soup): """ Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. """ # the table with all submissions table = soup.findCh...
Builds and returns a list of stories (dicts) from the passed source. def _build_story(self, all_rows): """ Builds and returns a list of stories (dicts) from the passed source. """ # list to hold all stories all_stories = [] for (info, detail) in all_rows: ...
Yields a list of stories from the passed page of HN. 'story_type' can be: \t'' = top stories (homepage) (default) \t'news2' = page 2 of top stories \t'newest' = most recent stories \t'best' = best stories 'limit' is the number of stories required from the...
Return the leaders of Hacker News def get_leaders(self, limit=10): """ Return the leaders of Hacker News """ if limit is None: limit = 10 soup = get_soup('leaders') table = soup.find('table') leaders_table = table.find_all('table')[1] listleaders = lea...
Get the relative url of the next page (The "More" link at the bottom of the page) def _get_next_page(self, soup, current_page): """ Get the relative url of the next page (The "More" link at the bottom of the page) """ # Get the table with all the comments: ...
For the story, builds and returns a list of Comment objects. def _build_comments(self, soup): """ For the story, builds and returns a list of Comment objects. """ comments = [] current_page = 1 while True: # Get the table holding all comments: ...
Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int. def fromid(self, item_id): """ Initializes an instance of Story for given item_id. It is assumed t...
Compare a list of names from a name component based on settings def compare_name_component(list1, list2, settings, use_ratio=False): """ Compare a list of names from a name component based on settings """ if not list1[0] or not list2[0]: not_required = not settings['required'] return no...
Evaluates whether names match, or one name is the initial of the other def equate_initial(name1, name2): """ Evaluates whether names match, or one name is the initial of the other """ if len(name1) == 0 or len(name2) == 0: return False if len(name1) == 1 or len(name2) == 1: return ...
Evaluates whether names match, or one name prefixes another def equate_prefix(name1, name2): """ Evaluates whether names match, or one name prefixes another """ if len(name1) == 0 or len(name2) == 0: return False return name1.startswith(name2) or name2.startswith(name1)
Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison def equate_nickname(name1, name2): """ Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison """ # Convert '-ie' and '-...
Converts unicode-specific characters to their equivalent ascii def make_ascii(word): """ Converts unicode-specific characters to their equivalent ascii """ if sys.version_info < (3, 0, 0): word = unicode(word) else: word = str(word) normalized = unicodedata.normalize('NFKD', wo...
Returns sequence match ratio for two words def seq_ratio(word1, word2): """ Returns sequence match ratio for two words """ raw_ratio = SequenceMatcher(None, word1, word2).ratio() return int(round(100 * raw_ratio))
Updates the values in a nested dict, while unspecified values will remain unchanged def deep_update_dict(default, options): """ Updates the values in a nested dict, while unspecified values will remain unchanged """ for key in options.keys(): default_setting = default.get(key) n...
Get base output path for a list of songs for download. def template_to_base_path(template, google_songs): """Get base output path for a list of songs for download.""" if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [temp...
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. def count(self): """Returns the number of bits set to True in the bit string. Usage...
Wait for an event on any channel. def drain_events(self, allowed_methods=None, timeout=None): """Wait for an event on any channel.""" return self.wait_multi(self.channels.values(), timeout=timeout)
Wait for an event on a channel. def wait_multi(self, channels, allowed_methods=None, timeout=None): """Wait for an event on a channel.""" chanmap = dict((chan.channel_id, chan) for chan in channels) chanid, method_sig, args, content = self._wait_multiple( chanmap.keys(), allowed...
Establish connection to the AMQP broker. def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise ...
Check if a queue has been declared. :rtype bool: def queue_exists(self, queue): """Check if a queue has been declared. :rtype bool: """ try: self.channel.queue_declare(queue=queue, passive=True) except AMQPChannelException, e: if e.amqp_reply_c...
Delete queue by name. def queue_delete(self, queue, if_unused=False, if_empty=False): """Delete queue by name.""" return self.channel.queue_delete(queue, if_unused, if_empty)
Declare a named queue. def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" if warn_if_exists and self.queue_exists(queue): warnings.warn(QueueAlreadyExistsWarning( QueueAlreadyExistsW...
Declare an named exchange. def exchange_declare(self, exchange, type, durable, auto_delete): """Declare an named exchange.""" return self.channel.exchange_declare(exchange=exchange, type=type, durable=durable, ...
Bind queue to an exchange using a routing key. def queue_bind(self, queue, exchange, routing_key, arguments=None): """Bind queue to an exchange using a routing key.""" return self.channel.queue_bind(queue=queue, exchange=exchange, ...