code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def method(self, *args, **kwargs): f = getattr(self.out_connection, funcname) p = functools.partial(f, *args, **kwargs) self.reactor.scheduler.execute_after(0, p) method.__name__ = funcname return method
def _wrap_execute_after(funcname)
Warp the given method, so it gets executed by the reactor Wrap a method of :data:`IRCCLient.out_connection`. The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class. :param funcname: the name of a :class:`irc.client.ServerConnection` method :type funcname: :class:`str`...
3.397359
2.887583
1.176541
methods = ['action', 'admin', 'cap', 'ctcp', 'ctcp_reply', 'globops', 'info', 'invite', 'ison', 'join', 'kick', 'links', 'list', 'lusers', 'mode', 'motd', 'names', 'nick', 'notice', 'oper', 'part', 'part', 'pass_', 'ping', 'pong', 'privmsg', ...
def add_serverconnection_methods(cls)
Add a bunch of methods to an :class:`irc.client.SimpleIRCClient` to send commands and messages. Basically it wraps a bunch of methdos from :class:`irc.client.ServerConnection` to be :meth:`irc.schedule.IScheduler.execute_after`. That way, you can easily send, even if the IRCClient is running in ...
3.848386
3.616599
1.06409
# This loop should specifically *not* be mutex-locked. # Otherwise no other thread would ever be able to change # the shared state of a Reactor object running this function. log.debug("process_forever(timeout=%s)", timeout) self._looping.set() while self._looping...
def process_forever(self, timeout=0.2)
Run an infinite loop, processing data from connections. This method repeatedly calls process_once. :param timeout: Parameter to pass to :meth:`irc.client.Reactor.process_once` :type timeout: :class:`float`
9.728595
9.183686
1.059334
log.debug('Shutting down %s' % self) self.disconnect_all() self._looping.clear()
def shutdown(self)
Disconnect all connections and end the loop :returns: None :rtype: None :raises: None
7.307405
7.186461
1.016829
c = connection.ServerConnection3(self) with self.mutex: self.connections.append(c) return c
def server(self, )
Creates and returns a ServerConnection :returns: a server connection :rtype: :class:`connection.ServerConnection3` :raises: None
8.158509
6.521454
1.251026
import sys from .__init__ import __version__ init_file = find_init(shell) if os.path.exists(init_file): sys.stdout.write(INIT_TEMPLATE.format( file=init_file, version=__version__)) else: raise RuntimeError( "Shell '{0}' is not supported.".format(shell_nam...
def init_run(shell, no_daemon, daemon_options, daemon_outfile)
Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell other than $SHELL, you can give --shell option:: eval $(%(pro...
3.513251
4.252551
0.826151
cur_mod = sys.modules[func.__module__] data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC' cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False) if has_date: if hasattr(cur_mod, 'FILE_WITH_DATE'): file_fmt = getattr(cur_mod, 'FILE_WITH_DA...
def cache_file(symbol, func, has_date, root, date_type='date')
Data file Args: symbol: symbol func: use function to categorize data has_date: contains date in data file root: root path date_type: parameters pass to utils.cur_time, [date, time, time_path, ...] Returns: str: date file
2.814926
2.737002
1.028471
default = dict([ (param.name, param.default) for param in inspect.signature(func).parameters.values() if param.default != getattr(inspect, '_empty') ]) @wraps(func) def wrapper(*args, **kwargs): default.update(kwargs) kwargs.update(default) cur_mod ...
def update_data(func)
Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function
2.75774
2.857166
0.965201
d_file = data_file(file_fmt=file_fmt, info=info, **kwargs) if append and files.exists(d_file): data = pd.DataFrame(pd.concat([pd.read_parquet(d_file), data], sort=False)) if drop_dups is not None: data.drop_duplicates(subset=utils.tolist(drop_dups), inplace=True) if not dat...
def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs)
Save data to file Args: data: pd.DataFrame file_fmt: data file format in terms of f-strings append: if append data to existing data drop_dups: list, drop duplicates in columns info: dict, infomation to be hashed and passed to f-strings **kwargs: additional parameters...
2.926099
3.928443
0.74485
if isinstance(info, dict): kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest() kwargs.update(info) return utils.fstr(fmt=file_fmt, **kwargs)
def data_file(file_fmt, info=None, **kwargs)
Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name
4.079776
3.401561
1.199383
import matplotlib.pyplot as plt from pandas import plotting if cols is None: cols = data.columns if plot_kw is None: plot_kw = [{}] * len(cols) if len(cols) == 0: return num_colors = len(utils.flatten(cols)) # Get default color style from pandas colors = getattr(getattr(plotting, ...
def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs)
Plot data with multiple scaels together Args: data: DataFrame of data cols: columns to be plotted spacing: spacing between legends color_map: customized colors in map plot_kw: kwargs for each plot **kwargs: kwargs for the first plot Returns: ax for plot ...
2.603169
2.613585
0.996014
import matplotlib.pyplot as plt if plot_kw is None: plot_kw = [dict()] * len(cols) _, axes = plt.subplots(nrows=1, ncols=len(cols), **kwargs) plt.subplots_adjust(wspace=wspace) for n, col in enumerate(cols): data.loc[:, col].plot(ax=axes[n], **plot_kw[n]) return axes
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs)
Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for plots Examples: >>> import pandas as pd >>> import ...
2.327625
2.537211
0.917395
from .config import ConfigStore from .indexer import Indexer cfstore = ConfigStore() indexer = Indexer(cfstore, check_duplicate, keep_json, record_path) indexer.index_all()
def index_run(record_path, keep_json, check_duplicate)
Convert raw JSON records into sqlite3 DB. Normally RASH launches a daemon that takes care of indexing. See ``rash daemon --help``.
4.411829
4.501473
0.980086
# 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 True: ...
def list(self)
List all available data logging sessions
8.071728
7.106497
1.135824
# 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(DataLogging(data=DataLoggingReportOpenSessions(sessions=[]))) ...
def download(self, session_id)
Download a specific session. Returns (session_info, data)
3.319164
3.238672
1.024853
# 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())) enabled = False while True: res...
def get_send_enable(self)
Return true if sending of sessions is enabled on the watch
7.160183
7.1356
1.003445
self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting)))
def set_send_enable(self, setting)
Set the send enable setting on the watch
28.245556
28.250433
0.999827
if isinstance(level, str): level = getattr(logging, level.upper()) elif isinstance(level, int): pass else: raise ValueError('{0!r} is not a proper log level.'.format(level)) return level
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.
2.749258
2.413534
1.1391
level = loglevel(cfstore.daemon_log_level) handler = logging.FileHandler(filename=cfstore.daemon_log_path) handler.setLevel(level) logger.setLevel(level) logger.addHandler(handler)
def setup_daemon_log_file(cfstore)
Attach file handler to RASH logger. :type cfstore: rash.config.ConfigStore
2.831771
3.580098
0.790976
assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleto...
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 options can be given as keyword arguments: methodname: the method name for a methodCall pac...
3.170136
2.805843
1.129833
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 encoded
def gzip_encode(data)
data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952
2.299058
2.397683
0.958866
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() else: decoded = gzf.read(max_decode + 1) except IOError: raise ValueError(...
def gzip_decode(data, max_decode=20971520)
gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952
2.764998
2.819727
0.980591
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 == 'action_checkbox': yield { "text": text, ...
def result_headers(context, cl): for i, field_name in enumerate(cl.list_display)
Generates the list column headers.
3.945774
3.926703
1.004857
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_headers(context, cl)
Displays the headers and data list together
4.144526
4.29067
0.965939
sorted_fields = False ascending = None class_attrib = 'sortable' orig_sort_field = sort_field if context.get('current_sort_field') == sort_field: sort_field = '-%s' % sort_field visible_name = '-%s' % (visible_name or orig_sort_field) sorted_fields = True ascendi...
def sort_link(context, text, sort_field, visible_name=None)
Usage: {% sort_link "text" "field_name" %} Usage: {% sort_link "text" "field_name" "Visible name" %}
2.427133
2.437167
0.995883
"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 auto_sort(parser, token)
usage: {% auto_sort queryset %}
2.961725
2.42813
1.219755
m = cls._parse_regexp.match(tagstring) return cls(name=m.group('name'), value=m.group('value'), vendor=m.group('vendor'))
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
3.797818
4.955147
0.766439
emoteid, occstr = emotestr.split(':') occurences = [] for occ in occstr.split(','): start, end = occ.split('-') occurences.append((int(start), int(end))) return cls(int(emoteid), occurences)
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
2.510085
3.243263
0.773938
source = Chatter(event.source) return cls(source, event.target, event.arguments[0], event.tags)
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
9.904349
10.232962
0.967887
if tags is None: return attrmap = {'color': 'color', 'emotes': 'emotes', 'subscriber': 'subscriber', 'turbo': 'turbo', 'user-type': 'user_type'} for t in tags: attr = attrmap.get(t.name) if not attr: ...
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 ...
3.345338
2.384624
1.402878
if emotes is None: self._emotes = [] return es = [] for estr in emotes.split('/'): es.append(Emote.from_str(estr)) self._emotes = es
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
3.75103
4.363631
0.859612
n, d = exact_ratio(start) T = type(start) partials = {d: n} # map {denominator: sum of numerators} # Micro-optimizations. coerce_types_ = coerce_types exact_ratio_ = exact_ratio partials_get = partials.get # Add numerators for each denominator, and track the "current" type. for...
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.
4.304005
4.332984
0.993312
try: try: # int, Fraction return x.numerator, x.denominator except AttributeError: # float try: return x.as_integer_ratio() except AttributeError: # Decimal try: retur...
def exact_ratio(x)
Convert Real number x exactly to (numerator, denominator) pair. x is expected to be an int, Fraction, Decimal or float.
3.344836
2.870765
1.165137
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, den)
def decimal_to_ratio(d)
Convert Decimal d to exact integer ratio (numerator, denominator).
4.503926
4.28777
1.050412
# Get the common/fast cases out of the way first. if T1 is T2: return T1 if T1 is int: return 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, flo...
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 | +----------+-----------+----------...
3.022233
2.772812
1.089952
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 table[i][1] != maxfreq: ...
def counts(data)
Generate a table of sorted (value, frequency) pairs.
3.784542
3.287272
1.151271
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 mean(data)
Return the sample arithmetic mean of data. If ``data`` is empty, StatisticsError will be raised.
2.799374
2.737278
1.022685
data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") if n % 2 == 1: return data[n // 2] else: i = n // 2 return (data[i - 1] + data[i]) / 2
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:
2.004367
2.123546
0.943877
data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") if n % 2 == 1: return data[n // 2] else: return data[n // 2 - 1]
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.
2.574167
2.581042
0.997336
data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") return data[n // 2]
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.
4.063291
4.136086
0.9824
# Generate a table of sorted (value, frequency) pairs. table = counts(data) if len(table) == 1: return table[0][0] elif table: raise StatisticsError( 'no unique mode; found %d equally common values' % len(table) ) else: raise StatisticsError('no mode ...
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.
5.402381
5.201816
1.038557
if c is None: c = mean(data) ss = sum((x - c) ** 2 for x in data) # The following sum should mathematically equal zero, but due to rounding # error may not. ss -= sum((x - c) for x in data) ** 2 / len(data) assert not ss < 0, 'negative sum of square deviations: %f' % ss return s...
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.
4.373337
3.772219
1.159354
if iter(data) is data: data = 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 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 sample from a pop...
2.94545
3.683791
0.79957
if iter(data) 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 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 variance from t...
3.502224
4.23657
0.826665
var = variance(data, xbar) try: return var.sqrt() except AttributeError: return math.sqrt(var)
def stdev(data, xbar=None)
Return the square root of the sample variance. See ``variance`` for arguments and other details.
3.913718
5.250248
0.745435
var = pvariance(data, mu) 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.
4.328955
5.286487
0.818872
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, data)), 1.0 / len(data))
def geometric_mean(data)
Return the geometric mean of data
3.687307
3.430171
1.074963
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 harmonic_mean(data)
Return the harmonic mean of data
3.69255
3.367238
1.096611
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 kurtosis(data)
Return the kurtosis of the data's distribution
4.044072
3.830261
1.055821
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 percentile(data, n)
Return the n-th percentile of the given data Assume that the data are already sorted
3.959859
3.838695
1.031564
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_, std, count) res = {x: 0 for x in bins} for value in data: fo...
def get_histogram(data)
Return the histogram relative to the given data Assume that the data are already sorted
3.074153
2.974807
1.033396
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_histogram_bins(min_, max_, std, count)
Return optimal bins given the input parameters
2.912899
2.822332
1.032089
w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
def _get_bin_width(stdev, count)
Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501
4.667331
4.408712
1.058661
m = len(x) n = len(y) # L[i, j] will contain the length of the longest common subsequence of # x[0..i - 1] and y[0..j - 1]. L = _np.zeros((m + 1, n + 1), dtype=int) for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: continue ...
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'] >>> _longe...
1.67771
1.759807
0.953349
# TODO: private function of packages should not be used. graph, center = _nx.drawing.layout._process_params(graph, center, dim) num_nodes = len(graph) if num_nodes == 0: return {} elif num_nodes == 1: return {_nx.utils.arbitrary_element(graph): center} paddims = max(0, (di...
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 holds the numerical value used for the node ...
4.211018
4.548093
0.925887
# TODO: private function of packages should not be used. graph, center = _nx.drawing.layout._process_params(graph, center, dim) num_nodes = len(graph) if num_nodes == 0: return {} elif num_nodes == 1: return {_nx.utils.arbitrary_element(graph): center} if sources is None: ...
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 : `str` or `None`, optional The node attribute that holds the numerical value used for the nod...
3.460425
3.548894
0.975071
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) # noqa if with_labels: if offset is None: # TODO: This changes the...
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.Graph` A NetworkX graph. pos : mapping, o...
3.89964
3.938052
0.990246
# Figure out an endianness. endianness = (default_endianness or DEFAULT_ENDIANNESS) if hasattr(self, '_Meta'): endianness = self._Meta.get('endianness', endianness) inferred_fields = set() for k, v in iteritems(self._type_mapping): inferred_field...
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 ``'>'`...
4.043097
3.748282
1.078654
if not hasattr(self, '_Meta'): raise ReferenceError("Can't serialise a packet that doesn't have an endpoint ID.") serialised = self.serialise() return struct.pack('!HH', len(serialised), self._Meta['endpoint']) + serialised
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.
6.895041
6.293244
1.095626
length = struct.unpack_from('!H', message, 0)[0] + 4 if len(message) < length: raise IncompleteMessage() command, = struct.unpack_from('!H', message, 2) if command in _PacketRegistry: return _PacketRegistry[command].parse(message[4:length])[0], length ...
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 ``None``. Also r...
3.754174
3.49062
1.075504
obj = cls() offset = 0 if hasattr(cls, '_Meta'): default_endianness = cls._Meta.get('endianness', default_endianness) for k, v in iteritems(cls._type_mapping): try: value, length = v.buffer_to_value(obj, message, offset, default_endianness...
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 message: The message to decode. :typ...
3.36596
3.306819
1.017884
pattern = [] for query in kwds.pop('pattern', []): expansion = config.search.alias.get(query) if expansion is None: pattern.append(query) else: parser = SafeArgumentParser() search_add_arguments(parser) ns = parser.parse_args(expansion...
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.
3.337022
3.505776
0.951864
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 = kwds[key] if val: dt = parse_datet...
def preprocess_kwds(kwds)
Preprocess keyword arguments for `DataBase.search_command_record`.
3.808682
3.62395
1.050975
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.get('v')) kwargs.setdefault('words', kwargs.get('...
def __fix_args(kwargs)
Set all named arguments shortcuts and flags.
2.492736
2.353556
1.059136
# 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 = kwargs.get('max_count') f_quiet = kwargs.get('quiet') # use the grep_iter to build the return list ret = [] for v...
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 accept lists ...
5.44214
5.521328
0.985658
# unify flags (convert shortcuts to full name) __fix_args(kwargs) # parse the params that are relevant to this function f_offset = kwargs.get('byte_offset') f_line_number = kwargs.get('line_number') f_trim = kwargs.get('trim') f_after_context = kwargs.get('after_context') f_before_...
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. :param kwargs: See grep() hel...
4.223833
4.174473
1.011824
if strip: line = line.strip() elif strip_eol and line.endswith('\n'): line = line[:-1] return line
def __process_line(line, strip_eol, strip)
process a single line value.
2.483689
2.339192
1.061772
# currently found position position = -1 end_pos = -1 # check if fixed strings mode if kwargs.get('fixed_strings'): # if case insensitive fix case if kwargs.get('ignore_case'): pattern = pattern.lower() curr_line = curr_line.lower() # if patter...
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).
3.121334
3.125699
0.998603
parser = argparse.ArgumentParser( formatter_class=Formatter, description=__doc__, epilog=EPILOG, ) subparsers = parser.add_subparsers() for (name, adder, runner) in commands: subp = subparsers.add_parser( name, formatter_class=Formatter, ...
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 ...
2.73256
2.262036
1.208009
from .config import ConfigStore cfstore = ConfigStore() path = getattr(cfstore, "{0}_path".format(target)) output.write(path) if not no_newline: output.write("\n")
def locate_run(output, target, no_newline)
Print location of RASH related file.
5.677576
5.001909
1.135082
f = LocalUserBrowserFragment(self.browser) f.docFactory = webtheme.getLoader(f.fragmentName) f.setFragmentParent(self) return f
def userBrowser(self, request, tag)
Render a TDB of local users.
12.36612
10.09879
1.224515
userCreator = liveform.LiveForm( self.createUser, [liveform.Parameter( "localpart", liveform.TEXT_INPUT, unicode, "localpart"), liveform.Parameter( "domain", ...
def userCreate(self, request, tag)
Render a form for creating new users.
3.702462
3.532811
1.048022
loginSystem = self.browser.store.parent.findUnique(userbase.LoginSystem) if password is None: password = u''.join([random.choice(string.ascii_letters + string.digits) for i in xrange(8)]) loginSystem.addAccount(localpart, domain, password)
def createUser(self, localpart, domain, password=None)
Create a new, blank user account with the given name and domain and, if specified, with the given password. @type localpart: C{unicode} @param localpart: The local portion of the username. ie, the C{'alice'} in C{'alice@example.com'}. @type domain: C{unicode} @param do...
4.443181
4.693609
0.946645
loginAccount = loginMethod.account return actionClass( self, loginMethod.localpart + u'@' + loginMethod.domain, loginAccount)
def doAction(self, loginMethod, actionClass)
Show the form for the requested action.
9.262051
9.203124
1.006403
def makeRemover(i): def remover(s3lected): if s3lected: return self.products[i] return None return remover f = liveform.LiveForm( self._endow, [liveform.Parameter( 'products...
def productForm(self, request, tag)
Render a L{liveform.LiveForm} -- the main purpose of this fragment -- which will allow the administrator to endow or deprive existing users using Products.
7.604955
6.715033
1.132527
return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open()
def getStore(self, name, domain)
Convenience method for the REPL. I got tired of typing this string every time I logged in.
34.421497
30.982035
1.111015
store = self.store.parent if ssl: port = SSLPort(store=store, portNumber=portNumber, certificatePath=FilePath(certPath), factory=factory, interface=interface) else: port = TCPPort(store=store, portNumber=portN...
def createPort(self, portNumber, ssl, certPath, factory, interface=u'')
Create a new listening port. @type portNumber: C{int} @param portNumber: Port number on which to listen. @type ssl: C{bool} @param ssl: Indicates whether this should be an SSL port or not. @type certPath: C{str} @param ssl: If C{ssl} is true, a path to a certificate fi...
3.103373
3.268824
0.949385
factory = super(FactoryColumn, self).extractValue(model, item) return factory.__class__.__name__.decode('ascii')
def extractValue(self, model, item)
Get the class name of the factory referenced by a port. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). @rtype: C{unicode} @return: The name of the class...
10.767503
8.571191
1.256244
certPath = super(CertificateColumn, self).extractValue(model, item) return certPath.path.decode('utf-8', 'replace')
def extractValue(self, model, item)
Get the path referenced by this column's attribute. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). @rtype: C{unicode}
8.027004
7.586122
1.058117
return self.siteStore.getItemByID(self.webTranslator.linkFrom(link))
def itemFromLink(self, link)
@type link: C{unicode} @param link: A webID to translate into an item. @rtype: L{Item} @return: The item to which the given link referred.
24.349413
30.926338
0.787336
f = PortScrollingFragment( self.store, TCPPort, (TCPPort.portNumber, TCPPort.interface, FactoryColumn(TCPPort.factory))) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) return tag[f]
def tcpPorts(self, req, tag)
Create and return a L{PortScrollingFragment} for the L{TCPPort} items in site store.
15.176031
8.141346
1.864069
f = PortScrollingFragment( self.store, SSLPort, (SSLPort.portNumber, SSLPort.interface, CertificateColumn(SSLPort.certificatePath), FactoryColumn(SSLPort.factory))) f.setFragmentParent(self) f.docFactory = webthe...
def sslPorts(self, req, tag)
Create and return a L{PortScrollingFragment} for the L{SSLPort} items in the site store.
13.002492
7.545238
1.723271
def port(s): n = int(s) if n < 0 or n > 65535: raise ValueError(s) return n factories = [] for f in self.store.parent.powerupsFor(IProtocolFactoryFactory): factories.append((f.__class__.__name__.decode('ascii'), ...
def createPortForm(self, req, tag)
Create and return a L{LiveForm} for adding a new L{TCPPort} or L{SSLPort} to the site store.
6.915823
6.23003
1.110079
route = router.bindRoute(receiver) d = amp.callRemote( Connect, origin=route.localRouteName, protocol=protocol) def cbGotRoute(result): route.connectTo(result['route']) return receiver d.addCallback(cbGotRoute) return d
def connectRoute(amp, router, receiver, protocol)
Connect the given receiver to a new box receiver for the given protocol. After connecting this router to an AMP server, use this method similarly to how you would use C{reactor.connectTCP} to establish a new connection to an HTTP, SMTP, or IRC server. @param receiver: An L{IBoxReceiver} which will...
5.596653
9.172198
0.610176
pad = secureRandom(16).encode('hex') self._oneTimePads[pad] = userStore.idInParent def expirePad(): self._oneTimePads.pop(pad, None) self.callLater(self.ONE_TIME_PAD_DURATION, expirePad) return pad
def generateOneTimePad(self, userStore)
Generate a pad which can be used to authenticate via AMP. This pad will expire in L{ONE_TIME_PAD_DURATION} seconds.
4.956338
4.054202
1.222519
factory = ServerFactory() def protocol(): proto = CredReceiver() proto.portal = Portal( self.loginSystem, [self.loginSystem, OneTimePadChecker(self._oneTimePads)]) return proto factory.protocol = protoc...
def getFactory(self)
Return a server factory which creates AMP protocol instances.
10.731202
10.145737
1.057706
for factory in self.store.powerupsFor(IBoxReceiverFactory): # XXX What if there's a duplicate somewhere? if factory.protocol == protocol: receiver = factory.getBoxReceiver() route = self.router.bindRoute(receiver) # This might be b...
def accept(self, origin, protocol)
Create a new route attached to a L{IBoxReceiver} created by the L{IBoxReceiverFactory} with the indicated protocol. @type origin: C{unicode} @param origin: The identifier of a route on the peer which will be associated with this connection. Boxes sent back by the protocol ...
10.170753
7.638715
1.331474
if interface is IBoxReceiver: router = Router() connector = self.connectorFactory(router) router.bindRoute(connector, None).connectTo(None) return router raise NotImplementedError()
def indirect(self, interface)
Create a L{Router} to handle AMP boxes received over an AMP connection.
14.045597
8.819631
1.592538
with open(file, 'rb') as fh: content = fh.readlines() if len(content) == 1: return content[0].decode('utf-8').strip('\n') return default
def getfirstline(file, default)
Returns the first line of a file.
2.705207
2.724347
0.992974
stats_dict = {} with os.popen('sacct --noheader --format JobId,Elapsed,TotalCPU,Partition,NTasks,AveRSS,State,ExitCode,start,end -P -j ' + str(job_id)) as f: try: line = f.readline() if line in ["SLURM accounting storage is disabled", "slurm_load_job ...
def job_stats_enhanced(job_id)
Get full job and step stats for job_id
2.405239
2.394724
1.004391
if not isinstance(string_item, str): raise TypeError("Expected str but got {} instead".format(type(string_item).__name__)) try: item = json.loads(string_item) except json.JSONDecodeError: raise JsonRpcParseError() if isinstance(item, dict): return JsonRpcRequest.fr...
def parse_json_structure(string_item)
Given a raw representation of a json structure, returns the parsed corresponding data structure (``JsonRpcRequest`` or ``JsonRpcRequestBatch``) :param string_item: :return:
3.282851
3.048901
1.076733
for key in ("method", "jsonrpc"): if key not in d: raise JsonRpcInvalidRequestError() # check jsonrpc version jsonrpc = d.get("jsonrpc", None) if jsonrpc != "2.0": raise JsonRpcInvalidRequestError() # check method method ...
def from_dict(cls, d)
Validates a dict instance and transforms it in a :py:class:`gemstone.core.structs.JsonRpcRequest` instance :param d: The dict instance :return: A :py:class:`gemstone.core.structs.JsonRpcRequest` if everything goes well, or None if the validation fails
1.99504
1.95906
1.018366
if not isinstance(item, JsonRpcResponse): raise TypeError( "Expected JsonRpcResponse but got {} instead".format(type(item).__name__)) self.items.append(item)
def add_item(self, item)
Adds an item to the batch.
4.818903
4.177249
1.153607
distance = kwargs.pop('distance') azimuth = np.radians(kwargs.pop('azimuth')) latitude = np.radians(kwargs.pop('latitude')) longitude = np.radians(kwargs.pop('longitude')) rmajor = kwargs.pop('rmajor', 6378137.0) rminor = kwargs.pop('rminor', 6356752.3142) f = (rmajor...
def great_circle(**kwargs)
Named arguments: distance = distance to travel, or numpy array of distances azimuth = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths latitude = latitude, in DECIMAL DEGREES, or numpy array of latitudes longitude = longitude, in DECIMAL DEGREES, or numpy array of ...
2.586211
2.10091
1.230995
sy = kwargs.pop('start_latitude') sx = kwargs.pop('start_longitude') ey = kwargs.pop('end_latitude') ex = kwargs.pop('end_longitude') rmajor = kwargs.pop('rmajor', 6378137.0) rminor = kwargs.pop('rminor', 6356752.3142) f = (rmajor - rminor) / rmajor if (np.ma....
def great_distance(**kwargs)
Named arguments: start_latitude = starting latitude, in DECIMAL DEGREES start_longitude = starting longitude, in DECIMAL DEGREES end_latitude = ending latitude, in DECIMAL DEGREES end_longitude = ending longitude, in DECIMAL DEGREES rmajor = radius of earth's major...
1.928086
1.801918
1.070019
subvol_path = os.path.join(self.path, str(subvol)) builtin_path = os.path.join(subvol_path, MANIFEST_DIR[1:], str(subvol)) manifest_path = os.path.join(MANIFEST_DIR, str(subvol)) if os.path.exists(builtin_path): # Stream the manifest written into the (read-only) tem...
def manifest(self, subvol)
Generator for manifest, yields 7-tuples
3.711133
3.646388
1.017756
def wrapper(func): func._event_handler = True func._handled_event = event_name return func return wrapper
def event_handler(event_name)
Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a JSON (dict, list, str, int, bool, float ...
5.391866
7.714928
0.698887
def wrapper(func): # validation if name: method_name = name else: method_name = func.__name__ if not METHOD_NAME_REGEX.match(method_name): raise ValueError("Invalid method name: '{}'".format(method_name)) @functools.wraps(func) ...
def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False)
Marks a method as exposed via JSON RPC. :param name: the name of the exposed method. Must contains only letters, digits, dots and underscores. If not present or is set explicitly to ``None``, this parameter will default to the name of the exposed method. If two me...
2.323203
2.304151
1.008268
''' Check if a related database exists ''' return self.db_name in map( lambda x: x['name'], self._db.get_database_list() )
def available(self)
Check if a related database exists
10.059615
6.987545
1.439649
''' sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table ''' return_squares = False sort_by = 'COUNT' # logic for accepting kwarg inputs for key,value in kwargs.iteritems(): if key == 'sort_by': sort_by = value if key == ...
def make_geohash_tables(table,listofprecisions,**kwargs)
sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table
3.752456
3.153219
1.19004