signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def bail(self, msg=None):
if msg:<EOL><INDENT>self.show('<STR_LIT>' + msg)<EOL><DEDENT>sys.exit(<NUM_LIT:1>)<EOL>
Exit uncleanly with an optional message
f8946:c2:m1
def input(self, filter_fn, prompt):
while True:<EOL><INDENT>try:<EOL><INDENT>return filter_fn(input(prompt))<EOL><DEDENT>except InvalidInputError as e:<EOL><INDENT>if e.message:<EOL><INDENT>self.show('<STR_LIT>' + e.message)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise RejectWarning<EOL><DEDENT><DEDENT>
Prompt user until valid input is received. RejectWarning is raised if a KeyboardInterrupt is caught.
f8946:c2:m2
def text(self, prompt, default=None):
prompt = prompt if prompt is not None else '<STR_LIT>'<EOL>prompt += "<STR_LIT>".format(default) if default is not None else '<STR_LIT>'<EOL>return self.input(curry(filter_text, default=default), prompt)<EOL>
Prompts the user for some text, with optional default
f8946:c2:m3
def account(self, prompt, default=None):
return self.text(prompt, default)<EOL>
Prompts the user for an account, with optional default TODO: for now, this just wraps text, but conformity to account name style should be checked
f8946:c2:m4
def decimal(self, prompt, default=None, lower=None, upper=None):
prompt = prompt if prompt is not None else "<STR_LIT>"<EOL>prompt += "<STR_LIT>".format(default) if default is not None else '<STR_LIT>'<EOL>return self.input(<EOL>curry(filter_decimal, default=default, lower=lower, upper=upper),<EOL>prompt<EOL>)<EOL>
Prompts user to input decimal, with optional default and bounds.
f8946:c2:m5
def pastdate(self, prompt, default=None):
prompt = prompt if prompt is not None else "<STR_LIT>"<EOL>if default is not None:<EOL><INDENT>prompt += "<STR_LIT>" + default.strftime('<STR_LIT>') + "<STR_LIT:]>"<EOL><DEDENT>prompt += '<STR_LIT>'<EOL>return self.input(curry(filter_pastdate, default=default), prompt)<EOL>
Prompts user to input a date in the past.
f8946:c2:m6
def yn(self, prompt, default=None):
if default is True:<EOL><INDENT>opts = "<STR_LIT>"<EOL><DEDENT>elif default is False:<EOL><INDENT>opts = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>opts = "<STR_LIT>"<EOL><DEDENT>prompt += opts<EOL>return self.input(curry(filter_yn, default=default), prompt)<EOL>
Prompts the user for yes/no confirmation, with optional default
f8946:c2:m7
def choose(self, prompt, items, default=None):
if default is not None and (default >= len(items) or default < <NUM_LIT:0>):<EOL><INDENT>raise IndexError<EOL><DEDENT>prompt = prompt if prompt is not None else "<STR_LIT>"<EOL>self.show(prompt + '<STR_LIT:\n>')<EOL>self.show("<STR_LIT:\n>".join(number(items))) <EOL>prompt = "<STR_LIT>"<EOL>prompt += "<STR_LIT>".format(default) if default is not None else '<STR_LIT>'<EOL>return items[self.input(<EOL>curry(filter_int, default=default, start=<NUM_LIT:0>, stop=len(items)),<EOL>prompt<EOL>)]<EOL>
Prompts the user to choose one item from a list. The default, if provided, is an index; the item of that index will be returned.
f8946:c2:m8
def append(self, item):
if item in self:<EOL><INDENT>self.items[item[<NUM_LIT:0>]].append(item[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>self.items[item[<NUM_LIT:0>]] = [item[<NUM_LIT:1>]]<EOL><DEDENT>
Append an item to the score set. item is a pair tuple, the first element of which is a valid dict key and the second of which is a numeric value.
f8948:c0:m2
def scores(self):
return map(<EOL>lambda x: (x[<NUM_LIT:0>], sum(x[<NUM_LIT:1>]) * len(x[<NUM_LIT:1>]) ** -<NUM_LIT>),<EOL>iter(self.items.viewitems())<EOL>)<EOL>
Return a list of the items with their final scores. The final score of each item is its average score multiplied by the square root of its length. This reduces to sum * len^(-1/2).
f8948:c0:m3
def highest(self):
scores = self.scores()<EOL>if not scores:<EOL><INDENT>return None<EOL><DEDENT>maxscore = max(map(score, scores))<EOL>return filter(lambda x: score(x) == maxscore, scores)<EOL>
Return the items with the higest score. If this ScoreSet is empty, returns None.
f8948:c0:m4
def __init__(self, **kwargs):
self.dropped = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else False<EOL>self.date = kwargs['<STR_LIT:date>'] if '<STR_LIT:date>' in kwargs else None<EOL>self.desc = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else None<EOL>self.amount = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else None<EOL>self.dst = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else None<EOL>self.src = kwargs['<STR_LIT:src>'] if '<STR_LIT:src>' in kwargs else None<EOL>
Initialise the transaction object
f8949:c3:m0
def ledger(self):
self.balance() <EOL>s = "<STR_LIT>".format(<EOL>self.date.year,<EOL>self.date.month,<EOL>self.date.day,<EOL>self.desc.replace('<STR_LIT:\n>', '<STR_LIT:U+0020>')<EOL>)<EOL>for src in self.src:<EOL><INDENT>s += "<STR_LIT>".format(src)<EOL><DEDENT>for dst in self.dst:<EOL><INDENT>s += "<STR_LIT>".format(dst)<EOL><DEDENT>return s<EOL>
Convert to a Ledger transaction (no trailing blank line)
f8949:c3:m3
def summary(self):
return "<STR_LIT:\n>".join([<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" + self.date.strftime("<STR_LIT>"),<EOL>"<STR_LIT>" + self.desc.replace('<STR_LIT:\n>', '<STR_LIT:U+0020>'),<EOL>"<STR_LIT>".format(self.amount),<EOL>"<STR_LIT>".format(<EOL>"<STR_LIT:U+002CU+0020>".join(map(lambda x: x.account, self.src)) if self.srcelse "<STR_LIT>"<EOL>),<EOL>"<STR_LIT>".format(<EOL>"<STR_LIT:U+002CU+0020>".join(map(lambda x: x.account, self.dst)) if self.dstelse "<STR_LIT>"<EOL>),<EOL>"<STR_LIT>"<EOL>])<EOL>
Return a string summary of transaction
f8949:c3:m4
def check(self):
if not self.date:<EOL><INDENT>raise XnDataError("<STR_LIT>")<EOL><DEDENT>if not self.desc:<EOL><INDENT>raise XnDataError("<STR_LIT>")<EOL><DEDENT>if not self.dst:<EOL><INDENT>raise XnDataError("<STR_LIT>")<EOL><DEDENT>if not self.src:<EOL><INDENT>raise XnDataError("<STR_LIT>")<EOL><DEDENT>if not self.amount:<EOL><INDENT>raise XnDataError("<STR_LIT>")<EOL><DEDENT>
Check this transaction for completeness
f8949:c3:m5
def balance(self):
self.check()<EOL>if not sum(map(lambda x: x.amount, self.src)) == -self.amount:<EOL><INDENT>raise XnBalanceError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if not sum(map(lambda x: x.amount, self.dst)) == self.amount:<EOL><INDENT>raise XnBalanceError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return True<EOL>
Check this transaction for correctness
f8949:c3:m6
def match_rules(self, rules):
try:<EOL><INDENT>self.check()<EOL>return None<EOL><DEDENT>except XnDataError:<EOL><INDENT>pass<EOL><DEDENT>scores = {}<EOL>for r in rules:<EOL><INDENT>outcomes = r.match(self)<EOL>if not outcomes:<EOL><INDENT>continue<EOL><DEDENT>for outcome in outcomes:<EOL><INDENT>if isinstance(outcome, rule.SourceOutcome):<EOL><INDENT>key = '<STR_LIT:src>'<EOL><DEDENT>elif isinstance(outcome, rule.DestinationOutcome):<EOL><INDENT>key = '<STR_LIT>'<EOL><DEDENT>elif isinstance(outcome, rule.DescriptionOutcome):<EOL><INDENT>key = '<STR_LIT>'<EOL><DEDENT>elif isinstance(outcome, rule.DropOutcome):<EOL><INDENT>key = '<STR_LIT>'<EOL><DEDENT>elif isinstance(outcome, rule.RebateOutcome):<EOL><INDENT>key = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise KeyError<EOL><DEDENT>if key not in scores:<EOL><INDENT>scores[key] = score.ScoreSet() <EOL><DEDENT>scores[key].append((outcome.value, outcome.score))<EOL><DEDENT><DEDENT>return scores<EOL>
Process this transaction against the given ruleset Returns a dict of fields with ScoreSet values, which may be empty. Notably, the rule processing will be shortcircuited if the Xn is already complete - in this case, None is returned.
f8949:c3:m7
def apply_outcomes(self, outcomes, uio, dropped=False, prevxn=None):
if self.dropped and not dropped:<EOL><INDENT>return<EOL><DEDENT>if '<STR_LIT>' in outcomes:<EOL><INDENT>highscore = score.score(outcomes['<STR_LIT>'].highest()[<NUM_LIT:0>])<EOL>if highscore >= threshold['<STR_LIT:y>']:<EOL><INDENT>self.dropped = True<EOL><DEDENT>elif highscore < threshold['<STR_LIT>']:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>uio.show('<STR_LIT>')<EOL>uio.show('<STR_LIT>')<EOL>uio.show(self.summary())<EOL>if highscore >= threshold['<STR_LIT>']:<EOL><INDENT>default = True<EOL><DEDENT>elif highscore >= threshold['<STR_LIT:?>']:<EOL><INDENT>default = None<EOL><DEDENT>else:<EOL><INDENT>default = False<EOL><DEDENT>try:<EOL><INDENT>self.dropped = uio.yn('<STR_LIT>', default)<EOL><DEDENT>except ui.RejectWarning:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>if self.dropped and not dropped:<EOL><INDENT>return<EOL><DEDENT>if '<STR_LIT>' in outcomes and not self.src and prevxn is not None:<EOL><INDENT>ratio = self.amount / prevxn.amount<EOL>def scale(dst_ep):<EOL><INDENT>amount = (dst_ep.amount * ratio).quantize(dst_ep.amount)<EOL>return Endpoint(dst_ep.account, -amount)<EOL><DEDENT>self.src = map(scale, prevxn.dst)<EOL>self.src[<NUM_LIT:0>].amount -= self.amount + sum(x.amount for x in self.src)<EOL><DEDENT>for outcome in ['<STR_LIT:src>', '<STR_LIT>']:<EOL><INDENT>if outcome not in outcomes or getattr(self, outcome):<EOL><INDENT>continue<EOL><DEDENT>endpoints = []<EOL>highest = outcomes[outcome].highest()<EOL>try:<EOL><INDENT>highscore = score.score(highest[<NUM_LIT:0>])<EOL>if len(highest) == <NUM_LIT:1>:<EOL><INDENT>if highscore >= threshold['<STR_LIT:y>']:<EOL><INDENT>endpoints = [<EOL>Endpoint(score.value(highest[<NUM_LIT:0>]), self.amount)<EOL>]<EOL><DEDENT>else:<EOL><INDENT>uio.show('<STR_LIT>' + outcome + '<STR_LIT>')<EOL>uio.show('<STR_LIT>')<EOL>uio.show(self.summary())<EOL>prompt = '<STR_LIT>'.format(<EOL>score.value(highest[<NUM_LIT:0>])<EOL>)<EOL>if highscore >= threshold['<STR_LIT>']:<EOL><INDENT>default = True<EOL><DEDENT>elif highscore >= threshold['<STR_LIT:?>']:<EOL><INDENT>default = None<EOL><DEDENT>else:<EOL><INDENT>default = False<EOL><DEDENT>if uio.yn(prompt, default):<EOL><INDENT>endpoints = [<EOL>Endpoint(<EOL>score.value(highest[<NUM_LIT:0>]),<EOL>self.amount<EOL>)<EOL>]<EOL><DEDENT>else:<EOL><INDENT>raise ui.RejectWarning('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>uio.show('<STR_LIT>' + outcome + '<STR_LIT>')<EOL>uio.show('<STR_LIT>')<EOL>uio.show(self.summary())<EOL>prompt = '<STR_LIT>'<EOL>endpoints = [<EOL>Endpoint(<EOL>uio.choose(prompt, map(score.value, highest)),<EOL>self.amount<EOL>)<EOL>]<EOL><DEDENT><DEDENT>except ui.RejectWarning:<EOL><INDENT>uio.show("<STR_LIT:\n>")<EOL>uio.show('<STR_LIT>' + outcome + '<STR_LIT>')<EOL>try:<EOL><INDENT>endpoints = []<EOL>remaining = self.amount<EOL>while remaining:<EOL><INDENT>uio.show('<STR_LIT>'.format(remaining))<EOL>account = uio.text(<EOL>'<STR_LIT>',<EOL>score.value(highest[<NUM_LIT:0>]) if highest else None<EOL>)<EOL>amount = uio.decimal(<EOL>'<STR_LIT>',<EOL>default=remaining,<EOL>lower=<NUM_LIT:0>,<EOL>upper=remaining<EOL>)<EOL>endpoints.append(Endpoint(account, amount))<EOL>remaining = self.amount- sum(map(lambda x: x.amount, endpoints))<EOL><DEDENT><DEDENT>except ui.RejectWarning:<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT><DEDENT>if outcome == '<STR_LIT:src>':<EOL><INDENT>endpoints = map(<EOL>lambda x: Endpoint(x.account, -x.amount),<EOL>endpoints<EOL>)<EOL><DEDENT>setattr(self, outcome, endpoints)<EOL><DEDENT>
Apply the given outcomes to this rule. If user intervention is required, outcomes are not applied unless a ui.UI is supplied.
f8949:c3:m8
def complete(self, uio, dropped=False):
if self.dropped and not dropped:<EOL><INDENT>return<EOL><DEDENT>for end in ['<STR_LIT:src>', '<STR_LIT>']:<EOL><INDENT>if getattr(self, end):<EOL><INDENT>continue <EOL><DEDENT>uio.show('<STR_LIT>' + end + '<STR_LIT>')<EOL>uio.show('<STR_LIT>')<EOL>uio.show(self.summary())<EOL>try:<EOL><INDENT>endpoints = []<EOL>remaining = self.amount<EOL>while remaining:<EOL><INDENT>account = uio.text('<STR_LIT>', None)<EOL>amount = uio.decimal(<EOL>'<STR_LIT>',<EOL>default=remaining,<EOL>lower=<NUM_LIT:0>,<EOL>upper=remaining<EOL>)<EOL>endpoints.append(Endpoint(account, amount))<EOL>remaining = self.amount- sum(map(lambda x: x.amount, endpoints))<EOL><DEDENT><DEDENT>except ui.RejectWarning:<EOL><INDENT>sys.exit("<STR_LIT>")<EOL><DEDENT>if end == '<STR_LIT:src>':<EOL><INDENT>endpoints = map(<EOL>lambda x: Endpoint(x.account, -x.amount),<EOL>endpoints<EOL>)<EOL><DEDENT>setattr(self, end, endpoints)<EOL><DEDENT>
Query for all missing information in the transaction
f8949:c3:m9
def process(self, rules, uio, prevxn=None):
self.apply_outcomes(self.match_rules(rules), uio, prevxn=prevxn)<EOL>
Matches rules and applies outcomes
f8949:c3:m10
def configure(host=DEFAULT_HOST, port=DEFAULT_PORT, prefix='<STR_LIT>'):
global _client<EOL>logging.info("<STR_LIT>".format(host, port, prefix))<EOL>_client = statsdclient.StatsdClient(host, port, prefix)<EOL>
>>> configure() >>> configure('localhost', 8125, 'mymetrics')
f8951:m0
def timing(metric, value):
_client.timing(metric, value)<EOL>
>>> timing("metric", 33)
f8951:m1
def gauge(metric, value):
_client.gauge(metric, value)<EOL>
>>> gauge("gauge", 23)
f8951:m2
def count(metric, value=<NUM_LIT:1>, sample_rate=<NUM_LIT:1>):
_client.count(metric, value, sample_rate)<EOL>
>>> count("metric") >>> count("metric", 3) >>> count("metric", -2)
f8951:m3
def timeit(metric, func, *args, **kwargs):
return _client.timeit(metric, func, *args, **kwargs)<EOL>
>>> import time >>> timeit("metric", time.sleep, 0.1) >>> resetclient() >>> timeit("metric", time.sleep, 0.1)
f8951:m4
def resetclient():
global _client<EOL>_client = NullClient()<EOL>
Reset client to None >>> resetclient()
f8951:m5
def timed(prefix=None):
def decorator(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>metricname = func.__name__<EOL>if prefix:<EOL><INDENT>metricname = prefix + '<STR_LIT:.>' + metricname<EOL><DEDENT>def wrapped(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>return timeit(metricname, func, *args, **kwargs)<EOL><DEDENT>return wrapped<EOL><DEDENT>return decorator<EOL>
Decorator to time execution of function. Metric name is function name (as given under f.__name__). Optionally provide a prefix (without the '.'). >>> @timed() ... def f(): ... print('ok') ... >>> f() ok >>> @timed(prefix='mymetrics') ... def g(): ... print('ok') ... >>> g() ok
f8951:m6
def time_methods(obj, methods, prefix=None):
if prefix:<EOL><INDENT>prefix = prefix + '<STR_LIT:.>'<EOL><DEDENT>else:<EOL><INDENT>prefix = '<STR_LIT>'<EOL><DEDENT>for method in methods:<EOL><INDENT>current_method = getattr(obj, method)<EOL>new_method = timed(prefix)(current_method)<EOL>setattr(obj, method, new_method)<EOL><DEDENT>
Patch obj so calls to given methods are timed >>> class C(object): ... def m1(self): ... return 'ok' ... ... def m2(self, arg): ... return arg ... >>> c = C() >>> time_methods(c, ['m1', 'm2']) >>> c.m1() 'ok' >>> c.m2('ok') 'ok' >>> c = C() >>> time_methods(c, ['m1'], 'mymetrics')
f8951:m7
def timeit(self, _metric, func, *args, **kwargs):
return func(*args, **kwargs)<EOL>
Dummy timeit
f8951:c0:m0
def count(self, *args, **kwargs):
pass<EOL>
Dummy count
f8951:c0:m1
def timing(self, *args):
pass<EOL>
Dummy timing
f8951:c0:m2
def gauge(self, *args):
pass<EOL>
Dummy gauge
f8951:c0:m3
def timeit(func, *args, **kwargs):
start_time = time.time()<EOL>res = func(*args, **kwargs)<EOL>timing = time.time() - start_time<EOL>return res, timing<EOL>
Time execution of function. Returns (res, seconds). >>> res, timing = timeit(time.sleep, 1)
f8953:m0
def __init__(self, host='<STR_LIT:localhost>', port=<NUM_LIT>, prefix="<STR_LIT>"):
self.addr = (host, port)<EOL>self.prefix = prefix + "<STR_LIT:.>" if prefix else "<STR_LIT>"<EOL>
Sends statistics to the stats daemon over UDP >>> client = StatsdClient()
f8953:c0:m0
def timing(self, stats, value):
self.update_stats(stats, value, self.SC_TIMING)<EOL>
Log timing information >>> client = StatsdClient() >>> client.timing('example.timing', 500) >>> client.timing(('example.timing23', 'example.timing29'), 500)
f8953:c0:m1
def gauge(self, stats, value):
self.update_stats(stats, value, self.SC_GAUGE)<EOL>
Log gauges >>> client = StatsdClient() >>> client.gauge('example.gauge', 47) >>> client.gauge(('example.gauge41', 'example.gauge43'), 47)
f8953:c0:m2
def set(self, stats, value):
self.update_stats(stats, value, self.SC_SET)<EOL>
Log set >>> client = StatsdClient() >>> client.set('example.set', "set") >>> client.set(('example.set61', 'example.set67'), "2701")
f8953:c0:m3
def increment(self, stats, sample_rate=<NUM_LIT:1>):
self.count(stats, <NUM_LIT:1>, sample_rate)<EOL>
Increments one or more stats counters >>> client = StatsdClient() >>> client.increment('example.increment') >>> client.increment('example.increment', 0.5)
f8953:c0:m4
def decrement(self, stats, sample_rate=<NUM_LIT:1>):
self.count(stats, -<NUM_LIT:1>, sample_rate)<EOL>
Decrements one or more stats counters >>> client = StatsdClient() >>> client.decrement('example.decrement')
f8953:c0:m5
def count(self, stats, value, sample_rate=<NUM_LIT:1>):
self.update_stats(stats, value, self.SC_COUNT, sample_rate)<EOL>
Updates one or more stats counters by arbitrary value >>> client = StatsdClient() >>> client.count('example.counter', 17)
f8953:c0:m6
def timeit(self, metric, func, *args, **kwargs):
(res, seconds) = timeit(func, *args, **kwargs)<EOL>self.timing(metric, seconds * <NUM_LIT>)<EOL>return res<EOL>
Times given function and log metric in ms for duration of execution. >>> import time >>> client = StatsdClient() >>> client.timeit("latency", time.sleep, 0.5)
f8953:c0:m7
def update_stats(self, stats, value, _type, sample_rate=<NUM_LIT:1>):
stats = self.format(stats, value, _type, self.prefix)<EOL>self.send(self.sample(stats, sample_rate), self.addr)<EOL>
Pipeline function that formats data, samples it and passes to send() >>> client = StatsdClient() >>> client.update_stats('example.update_stats', 73, "c", 0.9)
f8953:c0:m8
@staticmethod<EOL><INDENT>def format(keys, value, _type, prefix="<STR_LIT>"):<DEDENT>
data = {}<EOL>value = "<STR_LIT>".format(value, _type)<EOL>if not isinstance(keys, (list, tuple)):<EOL><INDENT>keys = [keys]<EOL><DEDENT>for key in keys:<EOL><INDENT>data[prefix + key] = value<EOL><DEDENT>return data<EOL>
General format function. >>> StatsdClient.format("example.format", 2, "T") {'example.format': '2|T'} >>> StatsdClient.format(("example.format31", "example.format37"), "2", ... "T") {'example.format31': '2|T', 'example.format37': '2|T'} >>> StatsdClient.format("example.format", 2, "T", "prefix.") {'prefix.example.format': '2|T'}
f8953:c0:m9
@staticmethod<EOL><INDENT>def sample(data, sample_rate):<DEDENT>
if sample_rate >= <NUM_LIT:1>:<EOL><INDENT>return data<EOL><DEDENT>elif sample_rate < <NUM_LIT:1>:<EOL><INDENT>if random() <= sample_rate:<EOL><INDENT>sampled_data = {}<EOL>for stat, value in data.items():<EOL><INDENT>sampled_data[stat] = "<STR_LIT>".format(value, sample_rate)<EOL><DEDENT>return sampled_data<EOL><DEDENT><DEDENT>return {}<EOL>
Sample data dict TODO(rbtz@): Convert to generator >>> StatsdClient.sample({"example.sample2": "2"}, 1) {'example.sample2': '2'} >>> StatsdClient.sample({"example.sample3": "3"}, 0) {} >>> from random import seed >>> seed(1) >>> StatsdClient.sample({"example.sample5": "5", ... "example.sample7": "7"}, 0.99) {'example.sample5': '5|@0.99', 'example.sample7': '7|@0.99'} >>> StatsdClient.sample({"example.sample5": "5", ... "example.sample7": "7"}, 0.01) {}
f8953:c0:m10
@staticmethod<EOL><INDENT>def send(_dict, addr):<DEDENT>
<EOL>udp_sock = socket(AF_INET, SOCK_DGRAM)<EOL>for item in _dict.items():<EOL><INDENT>udp_sock.sendto("<STR_LIT::>".join(item).encode('<STR_LIT:utf-8>'), addr)<EOL><DEDENT>
Sends key/value pairs via UDP. >>> StatsdClient.send({"example.send":"11|c"}, ("127.0.0.1", 8125))
f8953:c0:m11
def get_next_token(string):
STOP_CHARS = "<STR_LIT>"<EOL>UNARY_CHARS = "<STR_LIT>"<EOL>if string[<NUM_LIT:0>] in STOP_CHARS:<EOL><INDENT>return string[<NUM_LIT:0>], string[<NUM_LIT:1>:]<EOL><DEDENT>expression = []<EOL>for i, c in enumerate(string):<EOL><INDENT>if c in STOP_CHARS:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>expression.append(c)<EOL><DEDENT><DEDENT>return "<STR_LIT>".join(expression), string[i:]<EOL>
"eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str returns a tuple of (expression [ex: \\Phi], remaining_chars [ex: _{z}(L) = \\sum_{i=1}^{N}...])
f8956:m2
def print_math(math_expression_lst, name = "<STR_LIT>", out='<STR_LIT:html>', formatter = lambda x: x):
try: shutil.rmtree('<STR_LIT>')<EOL>except: pass<EOL>pth = get_cur_path()+print_math_template_path<EOL>shutil.copytree(pth, '<STR_LIT>')<EOL>html_loc = None<EOL>if out == "<STR_LIT:html>":<EOL><INDENT>html_loc = pth+"<STR_LIT>"<EOL><DEDENT>if out == "<STR_LIT>": <EOL><INDENT>from IPython.display import display, HTML<EOL>html_loc = pth+"<STR_LIT>"<EOL><DEDENT>html = open(html_loc).read()<EOL>html = html.replace("<STR_LIT>", json.dumps(math_expression_lst))<EOL>if out == "<STR_LIT>": <EOL><INDENT>display(HTML(html))<EOL><DEDENT>elif out == "<STR_LIT:html>":<EOL><INDENT>with open(name, "<STR_LIT>") as out_f:<EOL><INDENT>out_f.write(html)<EOL><DEDENT><DEDENT>
Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. Args: math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX out (string): {"html"|"notebook"}: HTML by default. Specifies output medium. formatter (function): function that cleans up the string for KaTeX. Returns: A HTML file in the directory where this function is called, or displays HTML output in a notebook.
f8960:m0
def __init__(self, lookup_function, columns):
<EOL>self.lookup_function = lookup_function<EOL>self.columns = columns<EOL>
Constructor. @ param lookup_function: a function that can take a query of some sort and return values based on it
f8961:c0:m0
def __init__(self, index, docs, dictionary):
self.index = index<EOL>self.docs = docs<EOL>self.dictionary = dictionary<EOL>self.columns = ["<STR_LIT>", "<STR_LIT>"]<EOL>lookup_function = self._query<EOL>Index.__init__(self, lookup_function, self.columns)<EOL>
GensimMathIndex Constructor Args: index (gensim.similarities.docsim.Similarity): A gensim index object docs (list): A list of the strings you are indexing, with the index corresponding to the gensim index. dictionary (gensim.corpora.dictionary.Dictionary): The same dictionary used to create the gensim index Returns: A table object Usage example: >>> gmi = GensimMathIndex(index, clean_docs, dictionary, tokenize_latex, ["neighbor", "similarity_score"]) >>> q.query("\\frac") >>> {'neighbors': [{'neighbor': {'data': u'\\begin{aligned}\\min_{L,S}\\sum_{m=1}^{M}\\sum_{i=1}^{N_{m}}&\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\&+\\gamma\\|L\\|_{1}+\\lambda\\|L\\|^{2}_{F}\\\\\\end{aligned}', 'fmt': 'math'}, 'similarity_score': {'data': 0.07059364020824432}}, ... Passing to a Table: ... >>> t = Table(gmi)
f8961:c1:m0
def _get_next_token(self, string):
STOP_CHARS = "<STR_LIT>"<EOL>UNARY_CHARS = "<STR_LIT>"<EOL>if string[<NUM_LIT:0>] in STOP_CHARS:<EOL><INDENT>return string[<NUM_LIT:0>], string[<NUM_LIT:1>:]<EOL><DEDENT>expression = []<EOL>for i, c in enumerate(string):<EOL><INDENT>if c in STOP_CHARS:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>expression.append(c)<EOL><DEDENT><DEDENT>return "<STR_LIT>".join(expression), string[i:]<EOL>
"eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str returns a tuple of (expression [ex: \\Phi], remaining_chars [ex: _{z}(L) = \\sum_{i=1}^{N}...])
f8961:c1:m1
def _tokenize_latex(self, exp):
tokens = []<EOL>prevexp = "<STR_LIT>"<EOL>while exp:<EOL><INDENT>t, exp = self._get_next_token(exp)<EOL>if t.strip() != "<STR_LIT>":<EOL><INDENT>tokens.append(t)<EOL><DEDENT>if prevexp == exp:<EOL><INDENT>break<EOL><DEDENT>prevexp = exp<EOL><DEDENT>return tokens<EOL>
Internal method to tokenize latex
f8961:c1:m2
def _convert_query(self, query):
query = self.dictionary.doc2bow(self._tokenize_latex(query))<EOL>sims = self.index[query]<EOL>neighbors = sorted(sims, key=lambda item: -item[<NUM_LIT:1>])<EOL>neighbors = {"<STR_LIT>":[{self.columns[<NUM_LIT:0>]: {"<STR_LIT:data>": self.docs[n[<NUM_LIT:0>]], "<STR_LIT>": "<STR_LIT>"}, self.columns[<NUM_LIT:1>]: {"<STR_LIT:data>": float(n[<NUM_LIT:1>])}} for n in neighbors]} if neighbors else {"<STR_LIT>": []}<EOL>return neighbors<EOL>
Convert query into an indexable string.
f8961:c1:m3
def _query(self, q):
return self._convert_query(q)<EOL>
Internal query method to pass to parent interface
f8961:c1:m4
def __init__(self, index, port = <NUM_LIT>):
self.index = index<EOL>self.server = None<EOL>self.port = port if port else find_free_port()<EOL>self.settings = index.columns<EOL>self.docs = index.docs<EOL>self._create_settings()<EOL>self.html_path = get_cur_path()+'<STR_LIT>'<EOL>self.cleanup_flag = False<EOL>
Table Constructor todo::make sure this is memory efficient Args: Index (Index): An Index object with a valid .query method and a .columns attribute. Returns: A table object Usage example >>> Table(ind)
f8962:c0:m0
def __del__(self):
del self.server<EOL>if self.cleanup_flag:<EOL><INDENT>shutil.rmtree('<STR_LIT>')<EOL><DEDENT>
Class destructor
f8962:c0:m1
def shutdown(self):
del self.server<EOL>
Shuts the server down
f8962:c0:m2
def _create_settings(self):
self.settings = {<EOL>"<STR_LIT>": [{"<STR_LIT>": s, "<STR_LIT>": s} for s in self.settings],<EOL>"<STR_LIT:port>": self.port,<EOL>"<STR_LIT>": construct_trie(self.docs)<EOL>}<EOL>
Creates the settings object that will be sent to the frontend vizualization
f8962:c0:m3
def print_table(self, public = False):
self._listen()<EOL>
"prints" a javascript visualization that can be run in the browser locally (and initializes listening on a port to serve data to the viz. Args: public (boolean): indicates whether or not the table should be visible on a public address. Returns: A webpage Usage example ... initialize index >>> t = Table(ind) >>> t.print_table(public = true) ...
f8962:c0:m4
def serve_table(self, public = False, port = None):
self._listen()<EOL>
"prints" a javascript visualization that can be run in the browser locally (and initializes listening on a port to serve data to the viz. Args: public (boolean): indicates whether or not the table should be visible on a public address. port (int): the port to serve the table on Returns: A webpage Usage example ... initialize index >>> t = Table(ind) >>> t.serve_table(public = true) ... starts serving the table to a public address
f8962:c0:m5
def run_server(self):
app = build_app()<EOL>run(app, host='<STR_LIT:localhost>', port=self.port)<EOL>
Runs a server to handle queries to the index without creating the javascript table.
f8962:c0:m6
def print_ipython(self):
from IPython.display import display, HTML<EOL>self._listen()<EOL>try: shutil.rmtree('<STR_LIT>')<EOL>except: None<EOL>shutil.copytree(self.html_path, '<STR_LIT>')<EOL>pth = "<STR_LIT>"<EOL>html = open(pth).read()<EOL>html = html.replace("<STR_LIT>", '<STR_LIT>'+str(self.port)+'<STR_LIT:">')<EOL>display(HTML(html))<EOL>
Renders the javascript table to a jupyter/ipython notebook cell Usage example: >>> t = Table(ind) >>> t.print_ipython() ... renders the table to notebook cell
f8962:c0:m7
def _listen(self):
self.server = Server(self)<EOL>
Initializing listening on a socket to serve data to the javascript table.
f8962:c0:m8
def _print_html(self):
cur_path = os.path.dirname(os.path.realpath(sys.argv[<NUM_LIT:0>]))<EOL>shutil.copytree(cur_path+'<STR_LIT>', '<STR_LIT>')<EOL>
Internal method to call the javascript/html table.
f8962:c0:m9
def __init__(self, lst):
list.__init__(self, lst)<EOL>self.server = None<EOL>self.port = find_free_port()<EOL>self.html_path = get_cur_path()+'<STR_LIT>'<EOL>
MathList Constructor todo:: share a port among lists. Or maybe close the server after serving from it? Args: lst (list): A list of LaTeX math to be rendered by KaTeX Returns: A math list object Usage example >>> lst = ["\int x = y", "x + 6"] >>> MathList(lst) ... see nicely formatted math.
f8963:c0:m0
def __del__(self):
del self.server<EOL>
Class destructor
f8963:c0:m1
def shutdown(self):
del self.server<EOL>
Shuts the server down
f8963:c0:m2
def serve_table(self, public = False, port = None):
self._listen()<EOL>
"prints" a javascript visualization that can be run in the browser locally (and initializes listening on a port to serve data to the viz. Args: public (boolean): indicates whether or not the table should be visible on a public address. port (int): the port to serve the table on Returns: A webpage Usage example ... initialize index >>> t = Table(ind) >>> t.serve_table(public = true) ... starts serving the table to a public address
f8963:c0:m3
def print_ipython(self):
pass<EOL>
Renders the javascript table to a jupyter/ipython notebook cell Usage example: >>> t = Table(ind) >>> t.print_ipython() ... renders the table to notebook cell
f8963:c0:m4
def _re_flatten(p):
if '<STR_LIT:(>' not in p:<EOL><INDENT>return p<EOL><DEDENT>return re.sub(r'<STR_LIT>', lambda m: m.group(<NUM_LIT:0>) if<EOL>len(m.group(<NUM_LIT:1>)) % <NUM_LIT:2> else m.group(<NUM_LIT:1>) + '<STR_LIT>', p)<EOL>
Turn all capturing groups in a regular expression pattern into non-capturing groups.
f8968:m7
def abort(code=<NUM_LIT>, text='<STR_LIT>'):
raise HTTPError(code, text)<EOL>
Aborts execution and causes a HTTP error.
f8968:m11
def redirect(url, code=None):
if not code:<EOL><INDENT>code = <NUM_LIT> if request.get('<STR_LIT>') == "<STR_LIT>" else <NUM_LIT><EOL><DEDENT>res = response.copy(cls=HTTPResponse)<EOL>res.status = code<EOL>res.body = "<STR_LIT>"<EOL>res.set_header('<STR_LIT>', urljoin(request.url, url))<EOL>raise res<EOL>
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
f8968:m12
def _file_iter_range(fp, offset, bytes, maxread=<NUM_LIT> * <NUM_LIT>):
fp.seek(offset)<EOL>while bytes > <NUM_LIT:0>:<EOL><INDENT>part = fp.read(min(bytes, maxread))<EOL>if not part: break<EOL>bytes -= len(part)<EOL>yield part<EOL><DEDENT>
Yield chunks from a range in a file. No chunk is bigger than maxread.
f8968:m13
def static_file(filename, root,<EOL>mimetype=True,<EOL>download=False,<EOL>charset='<STR_LIT>',<EOL>etag=None):
root = os.path.join(os.path.abspath(root), '<STR_LIT>')<EOL>filename = os.path.abspath(os.path.join(root, filename.strip('<STR_LIT>')))<EOL>headers = dict()<EOL>if not filename.startswith(root):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.path.exists(filename) or not os.path.isfile(filename):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if not os.access(filename, os.R_OK):<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>if mimetype is True:<EOL><INDENT>if download and download is not True:<EOL><INDENT>mimetype, encoding = mimetypes.guess_type(download)<EOL><DEDENT>else:<EOL><INDENT>mimetype, encoding = mimetypes.guess_type(filename)<EOL><DEDENT>if encoding: headers['<STR_LIT>'] = encoding<EOL><DEDENT>if mimetype:<EOL><INDENT>if (mimetype[:<NUM_LIT:5>] == '<STR_LIT>' or mimetype == '<STR_LIT>')and charset and '<STR_LIT>' not in mimetype:<EOL><INDENT>mimetype += '<STR_LIT>' % charset<EOL><DEDENT>headers['<STR_LIT:Content-Type>'] = mimetype<EOL><DEDENT>if download:<EOL><INDENT>download = os.path.basename(filename if download is True else download)<EOL>headers['<STR_LIT>'] = '<STR_LIT>' % download<EOL><DEDENT>stats = os.stat(filename)<EOL>headers['<STR_LIT>'] = clen = stats.st_size<EOL>headers['<STR_LIT>'] = email.utils.formatdate(stats.st_mtime,<EOL>usegmt=True)<EOL>headers['<STR_LIT>'] = email.utils.formatdate(time.time(), usegmt=True)<EOL>getenv = request.environ.get<EOL>if etag is None:<EOL><INDENT>etag = '<STR_LIT>' % (stats.st_dev, stats.st_ino, stats.st_mtime,<EOL>clen, filename)<EOL>etag = hashlib.sha1(tob(etag)).hexdigest()<EOL><DEDENT>if etag:<EOL><INDENT>headers['<STR_LIT>'] = etag<EOL>check = getenv('<STR_LIT>')<EOL>if check and check == etag:<EOL><INDENT>return HTTPResponse(status=<NUM_LIT>, **headers)<EOL><DEDENT><DEDENT>ims = getenv('<STR_LIT>')<EOL>if ims:<EOL><INDENT>ims = parse_date(ims.split("<STR_LIT:;>")[<NUM_LIT:0>].strip())<EOL><DEDENT>if ims is not None and ims >= int(stats.st_mtime):<EOL><INDENT>return HTTPResponse(status=<NUM_LIT>, **headers)<EOL><DEDENT>body = '<STR_LIT>' if request.method == '<STR_LIT>' else open(filename, '<STR_LIT:rb>')<EOL>headers["<STR_LIT>"] = "<STR_LIT>"<EOL>range_header = getenv('<STR_LIT>')<EOL>if range_header:<EOL><INDENT>ranges = list(parse_range_header(range_header, clen))<EOL>if not ranges:<EOL><INDENT>return HTTPError(<NUM_LIT>, "<STR_LIT>")<EOL><DEDENT>offset, end = ranges[<NUM_LIT:0>]<EOL>headers["<STR_LIT>"] = "<STR_LIT>" % (offset, end - <NUM_LIT:1>, clen)<EOL>headers["<STR_LIT>"] = str(end - offset)<EOL>if body: body = _file_iter_range(body, offset, end - offset)<EOL>return HTTPResponse(body, status=<NUM_LIT>, **headers)<EOL><DEDENT>return HTTPResponse(body, **headers)<EOL>
Open a file in a safe way and return an instance of :exc:`HTTPResponse` that can be sent back to the client. :param filename: Name or path of the file to send, relative to ``root``. :param root: Root path for file lookups. Should be an absolute directory path. :param mimetype: Provide the content-type header (default: guess from file extension) :param download: If True, ask the browser to open a `Save as...` dialog instead of opening the file with the associated program. You can specify a custom filename as a string. If not specified, the original filename is used (default: False). :param charset: The charset for files with a ``text/*`` mime-type. (default: UTF-8) :param etag: Provide a pre-computed ETag header. If set to ``False``, ETag handling is disabled. (default: auto-generate ETag header) While checking user input is always a good idea, this function provides additional protection against malicious ``filename`` parameters from breaking out of the ``root`` directory and leaking sensitive information to an attacker. Read-protected files or files outside of the ``root`` directory are answered with ``403 Access Denied``. Missing files result in a ``404 Not Found`` response. Conditional requests (``If-Modified-Since``, ``If-None-Match``) are answered with ``304 Not Modified`` whenever possible. ``HEAD`` and ``Range`` requests (used by download managers to check or continue partial downloads) are also handled automatically.
f8968:m14
def debug(mode=True):
global DEBUG<EOL>if mode: warnings.simplefilter('<STR_LIT:default>')<EOL>DEBUG = bool(mode)<EOL>
Change the debug level. There is only one debug level supported at the moment.
f8968:m15
def parse_date(ims):
try:<EOL><INDENT>ts = email.utils.parsedate_tz(ims)<EOL>return time.mktime(ts[:<NUM_LIT:8>] + (<NUM_LIT:0>, )) - (ts[<NUM_LIT:9>] or <NUM_LIT:0>) - time.timezone<EOL><DEDENT>except (TypeError, ValueError, IndexError, OverflowError):<EOL><INDENT>return None<EOL><DEDENT>
Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch.
f8968:m17
def parse_auth(header):
try:<EOL><INDENT>method, data = header.split(None, <NUM_LIT:1>)<EOL>if method.lower() == '<STR_LIT>':<EOL><INDENT>user, pwd = touni(base64.b64decode(tob(data))).split('<STR_LIT::>', <NUM_LIT:1>)<EOL>return user, pwd<EOL><DEDENT><DEDENT>except (KeyError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
f8968:m18
def parse_range_header(header, maxlen=<NUM_LIT:0>):
if not header or header[:<NUM_LIT:6>] != '<STR_LIT>': return<EOL>ranges = [r.split('<STR_LIT:->', <NUM_LIT:1>) for r in header[<NUM_LIT:6>:].split('<STR_LIT:U+002C>') if '<STR_LIT:->' in r]<EOL>for start, end in ranges:<EOL><INDENT>try:<EOL><INDENT>if not start: <EOL><INDENT>start, end = max(<NUM_LIT:0>, maxlen - int(end)), maxlen<EOL><DEDENT>elif not end: <EOL><INDENT>start, end = int(start), maxlen<EOL><DEDENT>else: <EOL><INDENT>start, end = int(start), min(int(end) + <NUM_LIT:1>, maxlen)<EOL><DEDENT>if <NUM_LIT:0> <= start < end <= maxlen:<EOL><INDENT>yield start, end<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Yield (start, end) ranges parsed from a HTTP Range header. Skip unsatisfiable ranges. The end index is non-inclusive.
f8968:m19
def _parse_http_header(h):
values = []<EOL>if '<STR_LIT:">' not in h: <EOL><INDENT>for value in h.split('<STR_LIT:U+002C>'):<EOL><INDENT>parts = value.split('<STR_LIT:;>')<EOL>values.append((parts[<NUM_LIT:0>].strip(), {}))<EOL>for attr in parts[<NUM_LIT:1>:]:<EOL><INDENT>name, value = attr.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>values[-<NUM_LIT:1>][<NUM_LIT:1>][name.strip()] = value.strip()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>lop, key, attrs = '<STR_LIT:U+002C>', None, {}<EOL>for quoted, plain, tok in _hsplit(h):<EOL><INDENT>value = plain.strip() if plain else quoted.replace('<STR_LIT>', '<STR_LIT:">')<EOL>if lop == '<STR_LIT:U+002C>':<EOL><INDENT>attrs = {}<EOL>values.append((value, attrs))<EOL><DEDENT>elif lop == '<STR_LIT:;>':<EOL><INDENT>if tok == '<STR_LIT:=>':<EOL><INDENT>key = value<EOL><DEDENT>else:<EOL><INDENT>attrs[value] = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif lop == '<STR_LIT:=>' and key:<EOL><INDENT>attrs[key] = value<EOL>key = None<EOL><DEDENT>lop = tok<EOL><DEDENT><DEDENT>return values<EOL>
Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results. :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``) :return: List of (value, params) tuples. The second element is a (possibly empty) dict.
f8968:m20
def _lscmp(a, b):
return not sum(<NUM_LIT:0> if x == y else <NUM_LIT:1><EOL>for x, y in zip(a, b)) and len(a) == len(b)<EOL>
Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix.
f8968:m22
def cookie_encode(data, key, digestmod=None):
depr(<NUM_LIT:0>, <NUM_LIT>, "<STR_LIT>",<EOL>"<STR_LIT>")<EOL>digestmod = digestmod or hashlib.sha256<EOL>msg = base64.b64encode(pickle.dumps(data, -<NUM_LIT:1>))<EOL>sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=digestmod).digest())<EOL>return tob('<STR_LIT:!>') + sig + tob('<STR_LIT:?>') + msg<EOL>
Encode and sign a pickle-able object. Return a (byte) string
f8968:m23
def cookie_decode(data, key, digestmod=None):
depr(<NUM_LIT:0>, <NUM_LIT>, "<STR_LIT>",<EOL>"<STR_LIT>")<EOL>data = tob(data)<EOL>if cookie_is_encoded(data):<EOL><INDENT>sig, msg = data.split(tob('<STR_LIT:?>'), <NUM_LIT:1>)<EOL>digestmod = digestmod or hashlib.sha256<EOL>hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest()<EOL>if _lscmp(sig[<NUM_LIT:1>:], base64.b64encode(hashed)):<EOL><INDENT>return pickle.loads(base64.b64decode(msg))<EOL><DEDENT><DEDENT>return None<EOL>
Verify and decode an encoded string. Return an object or None.
f8968:m24
def cookie_is_encoded(data):
depr(<NUM_LIT:0>, <NUM_LIT>, "<STR_LIT>",<EOL>"<STR_LIT>")<EOL>return bool(data.startswith(tob('<STR_LIT:!>')) and tob('<STR_LIT:?>') in data)<EOL>
Return True if the argument looks like a encoded cookie.
f8968:m25
def html_escape(string):
return string.replace('<STR_LIT:&>', '<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>').replace('<STR_LIT:>>', '<STR_LIT>').replace('<STR_LIT:">', '<STR_LIT>').replace("<STR_LIT:'>", '<STR_LIT>')<EOL>
Escape HTML special characters ``&<>`` and quotes ``'"``.
f8968:m26
def html_quote(string):
return '<STR_LIT>' % html_escape(string).replace('<STR_LIT:\n>', '<STR_LIT>').replace('<STR_LIT:\r>', '<STR_LIT>').replace('<STR_LIT:\t>', '<STR_LIT>')<EOL>
Escape and quote a string to be used as an HTTP attribute.
f8968:m27
def yieldroutes(func):
path = '<STR_LIT:/>' + func.__name__.replace('<STR_LIT>', '<STR_LIT:/>').lstrip('<STR_LIT:/>')<EOL>spec = getargspec(func)<EOL>argc = len(spec[<NUM_LIT:0>]) - len(spec[<NUM_LIT:3>] or [])<EOL>path += ('<STR_LIT>' * argc) % tuple(spec[<NUM_LIT:0>][:argc])<EOL>yield path<EOL>for arg in spec[<NUM_LIT:0>][argc:]:<EOL><INDENT>path += '<STR_LIT>' % arg<EOL>yield path<EOL><DEDENT>
Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example:: a() -> '/a' b(x, y) -> '/b/<x>/<y>' c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>' d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
f8968:m28
def path_shift(script_name, path_info, shift=<NUM_LIT:1>):
if shift == <NUM_LIT:0>: return script_name, path_info<EOL>pathlist = path_info.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>scriptlist = script_name.strip('<STR_LIT:/>').split('<STR_LIT:/>')<EOL>if pathlist and pathlist[<NUM_LIT:0>] == '<STR_LIT>': pathlist = []<EOL>if scriptlist and scriptlist[<NUM_LIT:0>] == '<STR_LIT>': scriptlist = []<EOL>if <NUM_LIT:0> < shift <= len(pathlist):<EOL><INDENT>moved = pathlist[:shift]<EOL>scriptlist = scriptlist + moved<EOL>pathlist = pathlist[shift:]<EOL><DEDENT>elif <NUM_LIT:0> > shift >= -len(scriptlist):<EOL><INDENT>moved = scriptlist[shift:]<EOL>pathlist = moved + pathlist<EOL>scriptlist = scriptlist[:shift]<EOL><DEDENT>else:<EOL><INDENT>empty = '<STR_LIT>' if shift < <NUM_LIT:0> else '<STR_LIT>'<EOL>raise AssertionError("<STR_LIT>" % empty)<EOL><DEDENT>new_script_name = '<STR_LIT:/>' + '<STR_LIT:/>'.join(scriptlist)<EOL>new_path_info = '<STR_LIT:/>' + '<STR_LIT:/>'.join(pathlist)<EOL>if path_info.endswith('<STR_LIT:/>') and pathlist: new_path_info += '<STR_LIT:/>'<EOL>return new_script_name, new_path_info<EOL>
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
f8968:m29
def auth_basic(check, realm="<STR_LIT>", text="<STR_LIT>"):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*a, **ka):<EOL><INDENT>user, password = request.auth or (None, None)<EOL>if user is None or not check(user, password):<EOL><INDENT>err = HTTPError(<NUM_LIT>, text)<EOL>err.add_header('<STR_LIT>', '<STR_LIT>' % realm)<EOL>return err<EOL><DEDENT>return func(*a, **ka)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>
Callback decorator to require HTTP auth (basic). TODO: Add route(check_auth=...) parameter.
f8968:m30
def make_default_app_wrapper(name):
@functools.wraps(getattr(Bottle, name))<EOL>def wrapper(*a, **ka):<EOL><INDENT>return getattr(app(), name)(*a, **ka)<EOL><DEDENT>return wrapper<EOL>
Return a callable that relays calls to the current default app.
f8968:m31
def load(target, **namespace):
module, target = target.split("<STR_LIT::>", <NUM_LIT:1>) if '<STR_LIT::>' in target else (target, None)<EOL>if module not in sys.modules: __import__(module)<EOL>if not target: return sys.modules[module]<EOL>if target.isalnum(): return getattr(sys.modules[module], target)<EOL>package_name = module.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>namespace[package_name] = sys.modules[package_name]<EOL>return eval('<STR_LIT>' % (module, target), namespace)<EOL>
Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
f8968:m32
def load_app(target):
global NORUN<EOL>NORUN, nr_old = True, NORUN<EOL>tmp = default_app.push() <EOL>try:<EOL><INDENT>rv = load(target) <EOL>return rv if callable(rv) else tmp<EOL><DEDENT>finally:<EOL><INDENT>default_app.remove(tmp) <EOL>NORUN = nr_old<EOL><DEDENT>
Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter.
f8968:m33
def run(app=None,<EOL>server='<STR_LIT>',<EOL>host='<STR_LIT:127.0.0.1>',<EOL>port=<NUM_LIT>,<EOL>interval=<NUM_LIT:1>,<EOL>reloader=False,<EOL>quiet=False,<EOL>plugins=None,<EOL>debug=None,<EOL>config=None, **kargs):
if NORUN: return<EOL>if reloader and not os.environ.get('<STR_LIT>'):<EOL><INDENT>import subprocess<EOL>lockfile = None<EOL>try:<EOL><INDENT>fd, lockfile = tempfile.mkstemp(prefix='<STR_LIT>', suffix='<STR_LIT>')<EOL>os.close(fd) <EOL>while os.path.exists(lockfile):<EOL><INDENT>args = [sys.executable] + sys.argv<EOL>environ = os.environ.copy()<EOL>environ['<STR_LIT>'] = '<STR_LIT:true>'<EOL>environ['<STR_LIT>'] = lockfile<EOL>p = subprocess.Popen(args, env=environ)<EOL>while p.poll() is None: <EOL><INDENT>os.utime(lockfile, None) <EOL>time.sleep(interval)<EOL><DEDENT>if p.poll() != <NUM_LIT:3>:<EOL><INDENT>if os.path.exists(lockfile): os.unlink(lockfile)<EOL>sys.exit(p.poll())<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>if os.path.exists(lockfile):<EOL><INDENT>os.unlink(lockfile)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>try:<EOL><INDENT>if debug is not None: _debug(debug)<EOL>app = app or default_app()<EOL>if isinstance(app, basestring):<EOL><INDENT>app = load_app(app)<EOL><DEDENT>if not callable(app):<EOL><INDENT>raise ValueError("<STR_LIT>" % app)<EOL><DEDENT>for plugin in plugins or []:<EOL><INDENT>if isinstance(plugin, basestring):<EOL><INDENT>plugin = load(plugin)<EOL><DEDENT>app.install(plugin)<EOL><DEDENT>if config:<EOL><INDENT>app.config.update(config)<EOL><DEDENT>if server in server_names:<EOL><INDENT>server = server_names.get(server)<EOL><DEDENT>if isinstance(server, basestring):<EOL><INDENT>server = load(server)<EOL><DEDENT>if isinstance(server, type):<EOL><INDENT>server = server(host=host, port=port, **kargs)<EOL><DEDENT>if not isinstance(server, ServerAdapter):<EOL><INDENT>raise ValueError("<STR_LIT>" % server)<EOL><DEDENT>server.quiet = server.quiet or quiet<EOL>if not server.quiet:<EOL><INDENT>_stderr("<STR_LIT>" %<EOL>(__version__, repr(server)))<EOL>_stderr("<STR_LIT>" %<EOL>(server.host, server.port))<EOL>_stderr("<STR_LIT>")<EOL><DEDENT>if reloader:<EOL><INDENT>lockfile = os.environ.get('<STR_LIT>')<EOL>bgcheck = FileCheckerThread(lockfile, interval)<EOL>with bgcheck:<EOL><INDENT>server.run(app)<EOL><DEDENT>if bgcheck.status == '<STR_LIT>':<EOL><INDENT>sys.exit(<NUM_LIT:3>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>server.run(app)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>except (SystemExit, MemoryError):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>if not reloader: raise<EOL>if not getattr(server, '<STR_LIT>', quiet):<EOL><INDENT>print_exc()<EOL><DEDENT>time.sleep(interval)<EOL>sys.exit(<NUM_LIT:3>)<EOL><DEDENT>
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter.
f8968:m34
def template(*args, **kwargs):
tpl = args[<NUM_LIT:0>] if args else None<EOL>for dictarg in args[<NUM_LIT:1>:]:<EOL><INDENT>kwargs.update(dictarg)<EOL><DEDENT>adapter = kwargs.pop('<STR_LIT>', SimpleTemplate)<EOL>lookup = kwargs.pop('<STR_LIT>', TEMPLATE_PATH)<EOL>tplid = (id(lookup), tpl)<EOL>if tplid not in TEMPLATES or DEBUG:<EOL><INDENT>settings = kwargs.pop('<STR_LIT>', {})<EOL>if isinstance(tpl, adapter):<EOL><INDENT>TEMPLATES[tplid] = tpl<EOL>if settings: TEMPLATES[tplid].prepare(**settings)<EOL><DEDENT>elif "<STR_LIT:\n>" in tpl or "<STR_LIT:{>" in tpl or "<STR_LIT:%>" in tpl or '<STR_LIT:$>' in tpl:<EOL><INDENT>TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)<EOL><DEDENT>else:<EOL><INDENT>TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)<EOL><DEDENT><DEDENT>if not TEMPLATES[tplid]:<EOL><INDENT>abort(<NUM_LIT>, '<STR_LIT>' % tpl)<EOL><DEDENT>return TEMPLATES[tplid].render(kwargs)<EOL>
Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).
f8968:m35
def view(tpl_name, **defaults):
def decorator(func):<EOL><INDENT>@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>result = func(*args, **kwargs)<EOL>if isinstance(result, (dict, DictMixin)):<EOL><INDENT>tplvars = defaults.copy()<EOL>tplvars.update(result)<EOL>return template(tpl_name, **tplvars)<EOL><DEDENT>elif result is None:<EOL><INDENT>return template(tpl_name, defaults)<EOL><DEDENT>return result<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>
Decorator: renders a template for a handler. The handler can control its behavior like that: - return a dict of template vars to fill out the template - return something other than a dict and the view decorator will not process the template, but return the handler result as is. This includes returning a HTTPResponse(dict) to get, for instance, JSON with autojson or other castfilters.
f8968:m36
def add_filter(self, name, func):
self.filters[name] = func<EOL>
Add a filter. The provided function is called with the configuration string as parameter and must return a (regexp, to_python, to_url) tuple. The first element is a string, the last two are callables or None.
f8968:c9:m1
def add(self, rule, method, target, name=None):
anons = <NUM_LIT:0> <EOL>keys = [] <EOL>pattern = '<STR_LIT>' <EOL>filters = [] <EOL>builder = [] <EOL>is_static = True<EOL>for key, mode, conf in self._itertokens(rule):<EOL><INDENT>if mode:<EOL><INDENT>is_static = False<EOL>if mode == '<STR_LIT:default>': mode = self.default_filter<EOL>mask, in_filter, out_filter = self.filters[mode](conf)<EOL>if not key:<EOL><INDENT>pattern += '<STR_LIT>' % mask<EOL>key = '<STR_LIT>' % anons<EOL>anons += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>pattern += '<STR_LIT>' % (key, mask)<EOL>keys.append(key)<EOL><DEDENT>if in_filter: filters.append((key, in_filter))<EOL>builder.append((key, out_filter or str))<EOL><DEDENT>elif key:<EOL><INDENT>pattern += re.escape(key)<EOL>builder.append((None, key))<EOL><DEDENT><DEDENT>self.builder[rule] = builder<EOL>if name: self.builder[name] = builder<EOL>if is_static and not self.strict_order:<EOL><INDENT>self.static.setdefault(method, {})<EOL>self.static[method][self.build(rule)] = (target, None)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>re_pattern = re.compile('<STR_LIT>' % pattern)<EOL>re_match = re_pattern.match<EOL><DEDENT>except re.error as e:<EOL><INDENT>raise RouteSyntaxError("<STR_LIT>" % (rule, e))<EOL><DEDENT>if filters:<EOL><INDENT>def getargs(path):<EOL><INDENT>url_args = re_match(path).groupdict()<EOL>for name, wildcard_filter in filters:<EOL><INDENT>try:<EOL><INDENT>url_args[name] = wildcard_filter(url_args[name])<EOL><DEDENT>except ValueError:<EOL><INDENT>raise HTTPError(<NUM_LIT>, '<STR_LIT>')<EOL><DEDENT><DEDENT>return url_args<EOL><DEDENT><DEDENT>elif re_pattern.groupindex:<EOL><INDENT>def getargs(path):<EOL><INDENT>return re_match(path).groupdict()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>getargs = None<EOL><DEDENT>flatpat = _re_flatten(pattern)<EOL>whole_rule = (rule, flatpat, target, getargs)<EOL>if (flatpat, method) in self._groups:<EOL><INDENT>if DEBUG:<EOL><INDENT>msg = '<STR_LIT>'<EOL>warnings.warn(msg % (method, rule), RuntimeWarning)<EOL><DEDENT>self.dyna_routes[method][<EOL>self._groups[flatpat, method]] = whole_rule<EOL><DEDENT>else:<EOL><INDENT>self.dyna_routes.setdefault(method, []).append(whole_rule)<EOL>self._groups[flatpat, method] = len(self.dyna_routes[method]) - <NUM_LIT:1><EOL><DEDENT>self._compile(method)<EOL>
Add a new rule or replace the target for an existing rule.
f8968:c9:m3
def build(self, _name, *anons, **query):
builder = self.builder.get(_name)<EOL>if not builder:<EOL><INDENT>raise RouteBuildError("<STR_LIT>", _name)<EOL><DEDENT>try:<EOL><INDENT>for i, value in enumerate(anons):<EOL><INDENT>query['<STR_LIT>' % i] = value<EOL><DEDENT>url = '<STR_LIT>'.join([f(query.pop(n)) if n else f for (n, f) in builder])<EOL>return url if not query else url + '<STR_LIT:?>' + urlencode(query)<EOL><DEDENT>except KeyError as E:<EOL><INDENT>raise RouteBuildError('<STR_LIT>' % E.args[<NUM_LIT:0>])<EOL><DEDENT>
Build an URL by filling the wildcards in a rule.
f8968:c9:m5
def match(self, environ):
verb = environ['<STR_LIT>'].upper()<EOL>path = environ['<STR_LIT>'] or '<STR_LIT:/>'<EOL>if verb == '<STR_LIT>':<EOL><INDENT>methods = ['<STR_LIT>', verb, '<STR_LIT:GET>', '<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>methods = ['<STR_LIT>', verb, '<STR_LIT>']<EOL><DEDENT>for method in methods:<EOL><INDENT>if method in self.static and path in self.static[method]:<EOL><INDENT>target, getargs = self.static[method][path]<EOL>return target, getargs(path) if getargs else {}<EOL><DEDENT>elif method in self.dyna_regexes:<EOL><INDENT>for combined, rules in self.dyna_regexes[method]:<EOL><INDENT>match = combined(path)<EOL>if match:<EOL><INDENT>target, getargs = rules[match.lastindex - <NUM_LIT:1>]<EOL>return target, getargs(path) if getargs else {}<EOL><DEDENT><DEDENT><DEDENT><DEDENT>allowed = set([])<EOL>nocheck = set(methods)<EOL>for method in set(self.static) - nocheck:<EOL><INDENT>if path in self.static[method]:<EOL><INDENT>allowed.add(method)<EOL><DEDENT><DEDENT>for method in set(self.dyna_regexes) - allowed - nocheck:<EOL><INDENT>for combined, rules in self.dyna_regexes[method]:<EOL><INDENT>match = combined(path)<EOL>if match:<EOL><INDENT>allowed.add(method)<EOL><DEDENT><DEDENT><DEDENT>if allowed:<EOL><INDENT>allow_header = "<STR_LIT:U+002C>".join(sorted(allowed))<EOL>raise HTTPError(<NUM_LIT>, "<STR_LIT>", Allow=allow_header)<EOL><DEDENT>raise HTTPError(<NUM_LIT>, "<STR_LIT>" + repr(path))<EOL>
Return a (target, url_args) tuple or raise HTTPError(400/404/405).
f8968:c9:m6
@cached_property<EOL><INDENT>def call(self):<DEDENT>
return self._make_callback()<EOL>
The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.
f8968:c10:m1
def reset(self):
self.__dict__.pop('<STR_LIT>', None)<EOL>
Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.
f8968:c10:m2
def prepare(self):
self.call<EOL>
Do all on-demand work immediately (useful for debugging).
f8968:c10:m3