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>".forma...
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['<...
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...
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 "<S...
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><INDEN...
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><INDE...
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>pas...
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>remain...
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>re...
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.forma...
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><DEDEN...
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....
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...
"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) = \\s...
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<E...
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"|...
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....
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...
"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) = \\s...
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...
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 ...
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: ...
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: ...
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(filena...
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 mimetyp...
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(...
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...
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 (valu...
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>:...
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><INDE...
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...
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_...
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....
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>retu...
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:.>')[...
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 funct...
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>e...
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 ...
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...
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:<EO...
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. ...
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_filte...
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 ...
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 se...
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