code
stringlengths
1
18.2k
def list(self): """ List all available data logging sessions """ # We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(DataLogging) self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[]))) sessions = [] while ...
def download(self, session_id): """ Download a specific session. Returns (session_info, data) """ # We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(DataLogging) # First, we need to open up all sessions self._pebble.send_packet(DataLogg...
break else: self._pebble.send_packet(DataLogging(data=DataLoggingEmptySession( session_id=session_id))) continue if isinstance(result, DataLoggingDespoolSendData): if result.session_id != session_id: self._pebble.send_packet(DataLogging( data=DataLoggingNACK(session_id=result.session_id))) else: logger.info("Received {...
def get_send_enable(self): """ Return true if sending of sessions is enabled on the watch """ # We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(DataLogging) self._pebble.send_packet(DataLogging(data=DataLoggingGetSendEnableRequest())) ...
def set_send_enable(self, setting): """ Set the send enable setting on the watch """ self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting)))
def loglevel(level): """ Convert any representation of `level` to an int appropriately. :type level: int or str :rtype: int >>> loglevel('DEBUG') == logging.DEBUG True >>> loglevel(10) 10 >>> loglevel(None) Traceback (most recent call last): ... ValueError: None is not a proper log level. """ if isinstance(level, str):...
def setup_daemon_log_file(cfstore): """ Attach file handler to RASH logger. :type cfstore: rash.config.ConfigStore """ level = loglevel(cfstore.daemon_log_level) handler = logging.FileHandler(filename=cfstore.daemon_log_path) handler.setLevel(level) logger.setLevel(level) logger.addHandler(handler)
def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=0, utf8_encoding='standard'): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following opt...
methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding, allow_none) data = m.dumps(params) if encoding != "utf-8": xmlheader ...
def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO() gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) gzf.write(data) gzf.close() encoded = f.getvalue() f.close() return encod...
def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO(data) gzf = gzip.GzipFile(mode="rb", fileobj=f) try: if max_decode < 0: # no limit decoded = gzf.read()...
def result_headers(context, cl): """ Generates the list column headers. """ for i, field_name in enumerate(cl.list_display): text, attr = label_for_field(field_name, cl.model, return_attr=True) if attr: # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'acti...
+ 1): is_sorted = True ascending = True th_classes.append('sorted ascending') if 'request' in context: url = context['request'].path else: url = "./" ### TODO: when start using action_checkbox use i instead of i + 1. This +1 is to correct enumerate index # builds url url += "?sort_by=" if ascending is False: url += "-"...
'', }
def sort_headers(context, cl): """ Displays the headers and data list together """ headers = list(result_headers(context, cl)) sorted_fields = False for h in headers: if h['sortable'] and h['sorted']: sorted_fields = True return {'cl': cl, 'result_headers': headers, 'sorted_fields': sorted_fields}
def sort_link(context, text, sort_field, visible_name=None): """Usage: {% sort_link "text" "field_name" %} Usage: {% sort_link "text" "field_name" "Visible name" %} """ sorted_fields = False ascending = None class_attrib = 'sortable' orig_sort_field = sort_field if context.get('current_sort_field') == sort_field: sort_...
else: if 'request' in context: request = context['request'] getvars = request.GET.copy() if 'sort_by' in getvars: del getvars['sort_by'] if len(getvars.keys()) > 0: context['getsortvars'] = "&%s" % getvars.urlencode() else: context['getsortvars'] = '' extra_vars = context['getsortvars'] # append other vars to url url +...
def auto_sort(parser, token): "usage: {% auto_sort queryset %}" try: tag_name, queryset = token.split_contents() except ValueError: raise template.TemplateSyntaxError("{0} tag requires a single argument".format(token.contents.split()[0])) return SortedQuerysetNode(queryset)
def from_str(cls, tagstring): """Create a tag by parsing the tag of a message :param tagstring: A tag string described in the irc protocol :type tagstring: :class:`str` :returns: A tag :rtype: :class:`Tag` :raises: None """ m = cls._parse_regexp.match(tagstring) return cls(name=m.group('name'), value=m.group('value'), ...
def from_str(cls, emotestr): """Create an emote from the emote tag key :param emotestr: the tag key, e.g. ``'123:0-4'`` :type emotestr: :class:`str` :returns: an emote :rtype: :class:`Emote` :raises: None """ emoteid, occstr = emotestr.split(':') occurences = [] for occ in occstr.split(','): start, end = occ.split('-')...
def from_event(cls, event): """Create a message from an event :param event: the event that was received of type ``pubmsg`` or ``privmsg`` :type event: :class:`Event3` :returns: a message that resembles the event :rtype: :class:`Message3` :raises: None """ source = Chatter(event.source) return cls(source, event.target, ...
def set_tags(self, tags): """For every known tag, set the appropriate attribute. Known tags are: :color: The user color :emotes: A list of emotes :subscriber: True, if subscriber :turbo: True, if turbo user :user_type: None, mod, staff, global_mod, admin :param tags: a list of tags :type tags: :class:`list` of :class:`...
def emotes(self, emotes): """Set the emotes :param emotes: the key of the emotes tag :type emotes: :class:`str` :returns: None :rtype: None :raises: None """ if emotes is None: self._emotes = [] return es = [] for estr in emotes.split('/'): es.append(Emote.from_str(estr)) self._emotes = es
def sum(data, start=0): """sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. """ n, d = exact_ratio(start) T = type(start) partials = {d: n} # map {denomina...
1 return T(total.numerator) if issubclass(T, Decimal): return T(total.numerator) / total.denominator return T(total)
def exact_ratio(x): """Convert Real number x exactly to (numerator, denominator) pair. x is expected to be an int, Fraction, Decimal or float. """ try: try: # int, Fraction return x.numerator, x.denominator except AttributeError: # float try: return x.as_integer_ratio() except AttributeError: # Decimal try: return deci...
def decimal_to_ratio(d): """Convert Decimal d to exact integer ratio (numerator, denominator). """ sign, digits, exp = d.as_tuple() if exp in ('F', 'n', 'N'): # INF, NAN, sNAN assert not d.is_finite() raise ValueError num = 0 for digit in digits: num = num * 10 + digit if sign: num = -num den = 10 ** -exp return (num, ...
def coerce_types(T1, T2): """Coerce types T1 and T2 to a common type. Coercion is performed according to this table, where "N/A" means that a TypeError exception is raised. +----------+-----------+-----------+-----------+----------+ | | int | Fraction | Decimal | float | +----------+-----------+-----------+-----------+...
T2 if T2 is int: return T1 # Subclasses trump their parent class. if issubclass(T2, T1): return T2 if issubclass(T1, T2): return T1 # Floats trump everything else. if issubclass(T2, float): return T2 if issubclass(T1, float): return T1 # Subclasses of the same base class give priority to the second. if T1.__base__ is T...
def counts(data): """ Generate a table of sorted (value, frequency) pairs. """ if data is None: raise TypeError('None is not iterable') table = collections.Counter(data).most_common() if not table: return table # Extract the values with the highest frequency. maxfreq = table[0][1] for i in range(1, len(table)): if tabl...
def mean(data): """Return the sample arithmetic mean of data. If ``data`` is empty, StatisticsError will be raised. """ if iter(data) is data: data = list(data) n = len(data) if n < 1: raise StatisticsError('mean requires at least one data point') return sum(data) / n
def median(data): """Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: """ data = sorted(data) n = len(data) if n == 0: raise Statistics...
def median_low(data): """Return the low median of numeric data. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned. """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") if n % 2 == 1: return...
def median_high(data): """Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") return data[n // 2]
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: If there is not exactly one most common value, ``mode`` will raise StatisticsError. """ # Generate a t...
def _ss(data, c=None): """Return sum of square deviations of sequence data. If ``c`` is None, the mean is calculated in one pass, and the deviations from the mean are calculated in a second pass. Otherwise, deviations are calculated from ``c`` as given. Use the second case with care, as it can lead to garbage results. ...
def variance(data, xbar=None): """Return the sample variance of data. data should be an iterable of Real-valued numbers, with at least two values. The optional argument xbar, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function when your data is a s...
= list(data) n = len(data) if n < 2: raise StatisticsError('variance requires at least two data points') ss = _ss(data, xbar) return ss / (n - 1)
def pvariance(data, mu=None): """Return the population variance of ``data``. data should be an iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function to calculate the ...
is data: data = list(data) n = len(data) if n < 1: raise StatisticsError('pvariance requires at least one data point') ss = _ss(data, mu) return ss / n
def stdev(data, xbar=None): """Return the square root of the sample variance. See ``variance`` for arguments and other details. """ var = variance(data, xbar) try: return var.sqrt() except AttributeError: return math.sqrt(var)
def pstdev(data, mu=None): """Return the square root of the population variance. See ``pvariance`` for arguments and other details. """ var = pvariance(data, mu) try: return var.sqrt() except AttributeError: return math.sqrt(var)
def geometric_mean(data): """Return the geometric mean of data """ if not data: raise StatisticsError('geometric_mean requires at least one data point') # in order to support negative or null values data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data] return math.pow(math.fabs(functools.reduce(operator.mul,...
def harmonic_mean(data): """Return the harmonic mean of data """ if not data: raise StatisticsError('harmonic_mean requires at least one data point') divisor = sum(map(lambda x: 1.0 / x if x else 0.0, data)) return len(data) / divisor if divisor else 0.0
def kurtosis(data): """Return the kurtosis of the data's distribution """ if not data: raise StatisticsError('kurtosis requires at least one data point') size = len(data) sd = stdev(data) ** 4 if not sd: return 0.0 mn = mean(data) return sum(map(lambda x: ((x - mn) ** 4 / sd), data)) / size - 3
def percentile(data, n): """Return the n-th percentile of the given data Assume that the data are already sorted """ size = len(data) idx = (n / 100.0) * size - 0.5 if idx < 0 or idx > size: raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n)) return data[int(idx)]
def get_histogram(data): """Return the histogram relative to the given data Assume that the data are already sorted """ count = len(data) if count < 2: raise StatisticsError('Too few data points ({}) for get_histogram'.format(count)) min_ = data[0] max_ = data[-1] std = stdev(data) bins = get_histogram_bins(min_, max_,...
def get_histogram_bins(min_, max_, std, count): """ Return optimal bins given the input parameters """ width = _get_bin_width(std, count) count = int(round((max_ - min_) / width) + 1) if count: bins = [i * width + min_ for i in xrange(1, count + 1)] else: bins = [min_] return bins
def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 """ w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
def _longest_common_subsequence(x, y): """ Return the longest common subsequence between two sequences. Parameters ---------- x, y : sequence Returns ------- sequence Longest common subsequence of x and y. Examples -------- >>> _longest_common_subsequence("AGGTAB", "GXTXAYB") ['G', 'T', 'A', 'B'] >>> _longest_common_su...
j - 1] + 1 else: L[i, j] = max(L[i - 1, j], L[i, j - 1]) ret = [] i, j = m, n while i > 0 and j > 0: # If current character in x and y are same, then current character is # part of the longest common subsequence. if x[i - 1] == y[j - 1]: ret.append(x[i - 1]) i, j = i - 1, j - 1 # If not same, then find the larger of tw...
def tower_layout(graph, height='freeenergy', scale=None, center=None, dim=2): """ Position all nodes of graph stacked on top of each other. Parameters ---------- graph : `networkx.Graph` or `list` of nodes A position will be assigned to every node in graph. height : `str` or `None`, optional The node attribute that hol...
>>> from pyrrole import ChemicalSystem >>> from pyrrole.atoms import create_data, read_cclib >>> from pyrrole.drawing import tower_layout >>> data = create_data( ... read_cclib("data/acetate/acetic_acid.out", "AcOH(g)"), ... read_cclib("data/acetate/acetic_acid@water.out", "AcOH(aq)")) >>> digraph = (ChemicalSystem("Ac...
if scale is not None: pos_arr = _nx.drawing.layout.rescale_layout(pos_arr, scale=scale) + center pos = dict(zip(graph, pos_arr)) # TODO: make test return pos
def diagram_layout(graph, height='freeenergy', sources=None, targets=None, pos=None, scale=None, center=None, dim=2): """ Position nodes such that paths are highlighted, from left to right. Parameters ---------- graph : `networkx.Graph` or `list` of nodes A position will be assigned to every node in graph. height : `st...
keys and values as a coordinate `list` or `tuple`. If not specified (default), initial positions are computed with `tower_layout`. scale : number, optional Scale factor for positions. center : array-like, optional Coordinate pair around which to center the layout. Default is the origin. dim : `int` Dimension of layout....
-19.8}, ... {"name": "mCARBX", "freeenergy": 20}]).set_index("name") >>> system = ChemicalSystem( ... ["Separated_Reactants -> mlC1 -> mTS1", ... "Separated_Reactants -> mlC2 -> mTS1", ... "mCARB2 <- mTS1 -> mCARB1", ... "Separated_Reactants -> mCARBX"], data) >>> digraph = system.to_digraph() >>> layout = diagram_layo...
in _nx.all_simple_paths(graph, source, target)] if pos is None: pos = tower_layout(graph, height=height, scale=None, center=center, dim=dim) for path in simple_paths: for n, step in enumerate(path): if pos[step][0] < n: pos[step][0] = n if scale is not None: pos_arr = _np.array([pos[node] for node in graph]) pos_arr = ...
def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7, node_color='k', style='solid', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, label=None): """ Draw nodes of graph. This draws only the nodes of graph as horizontal lines at each ``y = pos[1]`` from ``x - node_size/2`` to ``x + node_size/2``, wh...
as nodelist. node_color : color `str`, or array of `float` Node color. Can be a single color format `str` (default is ``'k'``), or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the `cmap` and `vmin`, `vmax` parameters. See `matplotlib.hlines` ...
alpha multiple times if necessary). cmap : Matplotlib colormap, optional Colormap name or Colormap instance for mapping intensities of nodes. vmin : `float`, optional Minimum for node colormap scaling. vmax : `float`, optional Maximum for node colormap scaling. ax : `matplotlib.axes.Axes`, optional Draw the graph in th...
{"name": "mCARB2", "freeenergy": -19.8}, ... {"name": "mCARBX", "freeenergy": 20}]).set_index("name") >>> system = ChemicalSystem( ... ["Separated_Reactants -> mlC1 -> mTS1", ... "Separated_Reactants -> mlC2 -> mTS1", ... "mCARB2 <- mTS1 -> mCARB1", ... "Separated_Reactants -> mCARBX"], data) >>> digraph = system.to_di...
xy[:, 0] + node_size/2., colors=node_color, linestyles=style, label=label, cmap=cmap) node_collection.set_zorder(2) return node_collection
def draw_diagram_edges(graph, pos=None, edgelist=None, width=1.0, edge_color='k', style='dashed', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, label=None, nodelist=None, node_size=.7): """ Draw edges of graph. This draws only the edges of a graph. Parameters ---------- graph : `networkx.Graph` A ...
of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the `edge_cmap` and `edge_vmin`, `edge_vmax` parameters. style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``) Edge line style (default is ``'dashed'``). See `matplotlib.hlines` for more deta...
specified it must be the same length as nodelist. Returns ------- `matplotlib.collections.LineCollection` `LineCollection` of the edges. Raises ------ networkx.NetworkXError Raised if a node has no position or one with bad value. ValueError Raised if `edge_color` contains something other than color names (one or a list...
mTS1 -> mCARB1", ... "Separated_Reactants -> mCARBX"], data) >>> digraph = system.to_digraph() >>> edges = draw_diagram_edges(digraph) """ if ax is None: ax = _plt.gca() if edgelist is None: edgelist = list(graph.edges()) if not edgelist or len(edgelist) == 0: # no edges! return None if nodelist is None: nodelist = lis...
of color letters such as ['k','r','k',...] edge_colors = tuple([_colorConverter.to_rgba(c, alpha) for c in edge_color]) elif _np.alltrue([not isinstance(c, str) for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if _np.alltrue([_cb.iterable(c) and len(c) in (3, 4) for c in edge_color]...
not None: assert(isinstance(edge_cmap, _Colormap)) edge_collection.set_array(_np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() ax.autoscale_view() return edge_collection
def draw_diagram_labels(graph, pos=None, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, bbox=None, ax=None, offset=None, **kwds): """ Draw node labels of graph. This draws only the node labels of a graph. Parameters ---------- graph : `networkx.Graph` A NetworkX gr...
`str`, optional Font weight (default is ``'normal'``). alpha : `float`, optional The text transparency (default is ``1.0``). ax : `matplotlib.axes.Axes`, optional Draw the graph in the specified Matplotlib axes. offset : array-like or `str`, optional Label positions are summed to this before drawing. Defaults to zero v...
"mCARBX", "freeenergy": 20}]).set_index("name") >>> system = ChemicalSystem( ... ["Separated_Reactants -> mlC1 -> mTS1", ... "Separated_Reactants -> mlC2 -> mTS1", ... "mCARB2 <- mTS1 -> mCARB1", ... "Separated_Reactants -> mCARBX"], data) >>> digraph = system.to_digraph() >>> edges = draw_diagram_labels(digraph, font_...
no text collection so we'll fake one for n, label in labels.items(): (x, y) = _np.asanyarray(pos[n]) + _np.asanyarray(offset) if not isinstance(label, str): label = str(label) # this makes "1" and 1 labeled the same t = ax.text(x, y, label, size=font_size, color=font_color, family=font_family, weight=font_weight, alpha...
def draw_diagram(graph, pos=None, with_labels=True, offset=None, **kwds): """ Draw a diagram for graph using Matplotlib. Draw graph as a simple energy diagram with Matplotlib with options for node positions, labeling, titles, and many other drawing features. See examples below. Parameters ---------- graph : `networkx.G...
passed to `draw_diagram_nodes` and `draw_diagram_edges`. If `pos` is `None`, `diagram_layout` is also called and have keywords passed as well. The same happens with `draw_diagram_labels` if `with_labels` is `True`. Examples -------- >>> import pandas as pd >>> from pyrrole import ChemicalSystem >>> from pyrrole.drawing...
v in digraph.nodes(data='freeenergy')} >>> edges = draw_diagram_labels(digraph, labels=labels, ... offset="above") """ if pos is None: pos = diagram_layout(graph, **kwds) # default to diagram layout node_collection = draw_diagram_nodes(graph, pos, **kwds) # noqa edge_collection = draw_diagram_edges(graph, pos, **kwds) ...
def serialise(self, default_endianness=None): """ Serialise a message, without including any framing. :param default_endianness: The default endianness, unless overridden by the fields or class metadata. Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and ``'>'`` for big endian. :type defau...
def serialise_packet(self): """ Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet. ``self.Meta.endpoint`` must be defined to call this method. :return: A serialised message, ready to be sent to the Pebble. """ if not hasattr(self, '_Meta'): raise ReferenceError("Can...
def parse_message(cls, message): """ Parses a message received from the Pebble. Uses Pebble Protocol framing to figure out what sort of packet it is. If the packet is registered (has been defined and imported), returns the deserialised packet, which will not necessarily be the same class as this. Otherwise returns ``No...
def parse(cls, message, default_endianness=DEFAULT_ENDIANNESS): """ Parses a message without any framing, returning the decoded result and length of message consumed. The result will always be of the same class as :meth:`parse` was called on. If the message is invalid, :exc:`.PacketDecodeError` will be raised. :param m...
value) return obj, offset
def expand_query(config, kwds): """ Expand `kwds` based on `config.search.query_expander`. :type config: .config.Configuration :type kwds: dict :rtype: dict :return: Return `kwds`, modified in place. """ pattern = [] for query in kwds.pop('pattern', []): expansion = config.search.alias.get(query) if expansion is None: ...
def preprocess_kwds(kwds): """ Preprocess keyword arguments for `DataBase.search_command_record`. """ from .utils.timeutils import parse_datetime, parse_duration for key in ['output', 'format', 'format_level', 'with_command_id', 'with_session_id']: kwds.pop(key, None) for key in ['time_after', 'time_before']: val = kwd...
def __fix_args(kwargs): """ Set all named arguments shortcuts and flags. """ kwargs.setdefault('fixed_strings', kwargs.get('F')) kwargs.setdefault('basic_regexp', kwargs.get('G')) kwargs.setdefault('extended_regexp', kwargs.get('E')) kwargs.setdefault('ignore_case', kwargs.get('i')) kwargs.setdefault('invert', kwargs.g...
def grep(target, pattern, **kwargs): """ Main grep function. :param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler. :param pattern: Grep pattern to search. :param kwargs: Optional flags (note: the docs below talk about matching 'lines', but this function also...
that form whole words. - x, line: Select only matches that exactly match the whole line. - c, count: Instead of the normal output, print a count of matching lines. - m NUM, max_count: Stop reading after NUM matching values. - A NUM, after_context: Return NUM lines of trailing context after matching lines. This will rep...
return just a single True / False if found matches. - b, byte_offset: Instead of a list of strings will return a list of (offset, string), where offset is the offset of the matched 'pattern' in line. - n, line_number: Instead of a list of strings will return a list of (index, string), where index is the line number. - ...
characters from every line processed. :return: A list with matching lines (even if provided target is a single string), unless flags state otherwise. """ # unify flags (convert shortcuts to full name) __fix_args(kwargs) # parse the params that are relevant to this function f_count = kwargs.get('count') f_max_count = kw...
match if f_quiet: return False # if requested count return results count if f_count: return len(ret) # return results list return ret
def grep_iter(target, pattern, **kwargs): """ Main grep function, as a memory efficient iterator. Note: this function does not support the 'quiet' or 'count' flags. :param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler. :param pattern: Grep pattern to search....
a list if isinstance(target, _basestring): target = [target] # calculate if need to trim end of lines need_to_trim_eol = not kwargs.get('keep_eol') and hasattr(target, 'readline') # list of previous lines, used only when f_before_context is set prev_lines = [] # iterate target and grep for line_index, line in enumerate...
after trailing context if f_after_context: # convert return string to list (unless f_before_context is set, in which case its already a list) if not f_before_context: ret_str = [ret_str] # iterate X lines to read after for i in range(f_after_context): # if target got next or readline, use next() # note: unfortunately d...
value = (offset, ret_str) # if requested line number, add offset + line to return list elif f_line_number: value = (line_index, ret_str) # default: add line to return list else: value = ret_str # maintain a list of previous lines, if the before-context option is provided if f_before_context: prev_lines.append(line) if ...
def __process_line(line, strip_eol, strip): """ process a single line value. """ if strip: line = line.strip() elif strip_eol and line.endswith('\n'): line = line[:-1] return line
def __do_grep(curr_line, pattern, **kwargs): """ Do grep on a single string. See 'grep' docs for info about kwargs. :param curr_line: a single line to test. :param pattern: pattern to search. :return: (matched, position, end_position). """ # currently found position position = -1 end_pos = -1 # check if fixed strings m...
if need to match whole words if kwargs.get('words') and position != -1: foundpart = (' ' + curr_line + ' ')[position:position+len(pattern)+2] if _is_part_of_word(foundpart[0]): position = -1 elif _is_part_of_word(foundpart[-1]): position = -1 # if not fixed string, it means its a regex else: # set regex flags flags = k...
invert value if kwargs.get('invert'): matched = not matched # if position is -1 reset end pos as well if not matched: end_pos = -1 # return result return matched, position, end_pos
def get_parser(commands): """ Generate argument parser given a list of subcommand specifications. :type commands: list of (str, function, function) :arg commands: Each element must be a tuple ``(name, adder, runner)``. :param name: subcommand :param adder: a function takes one object which is an instance of :class:`arg...
def locate_run(output, target, no_newline): """ Print location of RASH related file. """ from .config import ConfigStore cfstore = ConfigStore() path = getattr(cfstore, "{0}_path".format(target)) output.write(path) if not no_newline: output.write("\n")
def userBrowser(self, request, tag): """ Render a TDB of local users. """ f = LocalUserBrowserFragment(self.browser) f.docFactory = webtheme.getLoader(f.fragmentName) f.setFragmentParent(self) return f