code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
while True: # Generate a UUID username, removing dashes and the last 2 chars # to make it fit into the 30 char User.username field. Gracefully # handle any unlikely, but possible duplicate usernames. username = str(uuid.uuid4()) username = use...
def _generate_username(self)
Generate a unique username
5.418278
5.247088
1.032626
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex) model_cache_backend.share_model_cache_info(model_cache_info)
def update_model_cache(table_name)
Updates model cache by generating a new key for the model
5.130592
4.895702
1.047979
logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model._meta.db_table for f in sender._meta.get_fields() if f.related_model is not None and (((f.one_to_many or f.o...
def invalidate_model_cache(sender, instance, **kwargs)
Signal receiver for models to invalidate model cache of sender and related models. Model cache is invalidated by generating new key for each model. Parameters ~~~~~~~~~~ sender The model class instance The actual instance being saved.
2.920112
2.970402
0.98307
logger.debug('Received m2m_changed signals from sender {0}'.format(sender)) update_model_cache(instance._meta.db_table) update_model_cache(model._meta.db_table)
def invalidate_m2m_cache(sender, instance, model, **kwargs)
Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The class of the objects that are added to, removed from or cleared from the r...
4.716671
5.556781
0.848814
value = self._get_lookup(self.operator, self.value) self.params.append(self.value) return self.params
def get_params(self)
returns a list
9.717435
8.594677
1.130634
self.wheres.append(u"%s %s" % (lookup_cast(operator) % self.db_field, self.operator)) return self.wheres
def get_wheres(self)
returns a list
12.32225
11.758908
1.047908
sql = self.sql() key, created = self.get_or_create_model_key() if created: db_table = self.model._meta.db_table logger.debug('created new key {0} for model {1}'.format(key, db_table)) model_cache_info = ModelCacheInfo(db_table, key) model_...
def generate_key(self)
Generate cache key for the current query. If a new key is created for the model it is then shared with other consumers.
3.829765
3.329602
1.150217
clone = self.query.clone() sql, params = clone.get_compiler(using=self.db).as_sql() return sql % params
def sql(self)
Get sql for the current query.
6.355694
5.306257
1.197774
model_cache_info = model_cache_backend.retrieve_model_cache_info(self.model._meta.db_table) if not model_cache_info: return uuid.uuid4().hex, True return model_cache_info.table_key, False
def get_or_create_model_key(self)
Get or create key for the model. Returns ~~~~~~~ (model_key, boolean) tuple
4.496447
4.913461
0.915128
logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model._meta.db_table for f in self.model._meta.get_fields() if ((f.one_to_many or f.one_to_one) and f.auto...
def invalidate_model_cache(self)
Invalidate model cache by generating new key for the model.
2.713299
2.682636
1.01143
if not hasattr(self, '_cache_backend'): if hasattr(django.core.cache, 'caches'): self._cache_backend = django.core.cache.caches[_cache_name] else: self._cache_backend = django.core.cache.get_cache(_cache_name) return self._cache_backend
def cache_backend(self)
Get the cache backend Returns ~~~~~~~ Django cache backend
2.231666
2.280777
0.978467
pathname, filename = os.path.split(filename) modname = re.match( r'(?P<modname>\w+)\.py', filename).group('modname') file, path, desc = imp.find_module(modname, [pathname]) try: imp.load_module(modname, file, path, desc) finally: file.close()
def import_file(filename)
Import a file that will trigger the population of Orca. Parameters ---------- filename : str
2.601964
3.237355
0.803731
@wraps(func) def wrapper(**kwargs): if not orca.is_table(kwargs['table_name']): abort(404) return func(**kwargs) return wrapper
def check_is_table(func)
Decorator that will check whether the "table_name" keyword argument to the wrapped function matches a registered Orca table.
3.081829
2.779096
1.108932
@wraps(func) def wrapper(**kwargs): table_name = kwargs['table_name'] col_name = kwargs['col_name'] if not orca.is_table(table_name): abort(404) if col_name not in orca.get_table(table_name).columns: abort(404) return func(**kwargs) retur...
def check_is_column(func)
Decorator that will check whether the "table_name" and "col_name" keyword arguments to the wrapped function match a registered Orca table and column.
2.189466
1.965868
1.11374
@wraps(func) def wrapper(**kwargs): name = kwargs['inj_name'] if not orca.is_injectable(name): abort(404) return func(**kwargs) return wrapper
def check_is_injectable(func)
Decorator that will check whether the "inj_name" keyword argument to the wrapped function matches a registered Orca injectable.
4.055326
2.854647
1.420605
tables = orca.list_tables() cols = {t: orca.get_table(t).columns for t in tables} steps = orca.list_steps() injectables = orca.list_injectables() broadcasts = orca.list_broadcasts() return jsonify( tables=tables, columns=cols, steps=steps, injectables=injectables, broadcast...
def schema()
All tables, columns, steps, injectables and broadcasts registered with Orca. Includes local columns on tables.
3.596697
2.066454
1.740517
table = orca.get_table(table_name).to_frame() buf = StringIO() table.info(verbose=True, buf=buf) info = buf.getvalue() return info, 200, {'Content-Type': 'text/plain'}
def table_info(table_name)
Return the text result of table.info(verbose=True).
3.379636
2.787274
1.212524
preview = orca.get_table(table_name).to_frame().head() return ( preview.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
def table_preview(table_name)
Returns the first five rows of a table as JSON. Inlcudes all columns. Uses Pandas' "split" JSON format.
3.698243
3.460651
1.068655
desc = orca.get_table(table_name).to_frame().describe() return ( desc.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
def table_describe(table_name)
Return summary statistics of a table as JSON. Includes all columns. Uses Pandas' "split" JSON format.
3.563289
3.353852
1.062447
if orca.table_type(table_name) == 'dataframe': return jsonify(type='dataframe') filename, lineno, source = \ orca.get_raw_table(table_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify( type='function', filename=filename, line...
def table_definition(table_name)
Get the source of a table function. If a table is registered DataFrame and not a function then all that is returned is {'type': 'dataframe'}. If the table is a registered function then the JSON returned has keys "type", "filename", "lineno", "text", and "html". "text" is the raw text of the functi...
6.339112
4.2741
1.483146
table = orca.get_table(table_name) # column to aggregate column = request.args.get('column', None) if not column or column not in table.columns: abort(400) # column or index level to group by by = request.args.get('by', None) level = request.args.get('level', None) if (not...
def table_groupbyagg(table_name)
Perform a groupby on a table and return an aggregation on a single column. This depends on some request parameters in the URL. "column" and "agg" must always be present, and one of "by" or "level" must be present. "column" is the table column on which aggregation will be performed, "agg" is the aggrega...
2.567972
2.479009
1.035887
col = orca.get_table(table_name).get_column(col_name).head(10) return ( col.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
def column_preview(table_name, col_name)
Return the first ten elements of a column as JSON in Pandas' "split" format.
3.383832
3.11803
1.085247
col_type = orca.get_table(table_name).column_type(col_name) if col_type != 'function': return jsonify(type=col_type) filename, lineno, source = \ orca.get_raw_column(table_name, col_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return json...
def column_definition(table_name, col_name)
Get the source of a column function. If a column is a registered Series and not a function then all that is returned is {'type': 'series'}. If the column is a registered function then the JSON returned has keys "type", "filename", "lineno", "text", and "html". "text" is the raw text of the functio...
4.424475
3.458907
1.279154
col_desc = orca.get_table(table_name).get_column(col_name).describe() return ( col_desc.to_json(orient='split'), 200, {'Content-Type': 'application/json'})
def column_describe(table_name, col_name)
Return summary statistics of a column as JSON. Uses Pandas' "split" JSON format.
3.513022
3.311176
1.060959
csv = orca.get_table(table_name).get_column(col_name).to_csv(path=None) return csv, 200, {'Content-Type': 'text/csv'}
def column_csv(table_name, col_name)
Return a column as CSV using Pandas' default CSV output.
3.806608
3.381411
1.125745
i = orca.get_injectable(inj_name) return jsonify(type=str(type(i)), repr=repr(i))
def injectable_repr(inj_name)
Returns the type and repr of an injectable. JSON response has "type" and "repr" keys.
7.212374
4.347127
1.659113
inj_type = orca.injectable_type(inj_name) if inj_type == 'variable': return jsonify(type='variable') else: filename, lineno, source = \ orca.get_injectable_func_source_data(inj_name) html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify( ...
def injectable_definition(inj_name)
Get the source of an injectable function. If an injectable is a registered Python variable and not a function then all that is returned is {'type': 'variable'}. If the column is a registered function then the JSON returned has keys "type", "filename", "lineno", "text", and "html". "text" is the raw ...
4.445422
3.496686
1.271324
casts = [{'cast': b[0], 'onto': b[1]} for b in orca.list_broadcasts()] return jsonify(broadcasts=casts)
def list_broadcasts()
List all registered broadcasts as a list of objects with keys "cast" and "onto".
8.87796
4.581995
1.937575
if not orca.is_broadcast(cast_name, onto_name): abort(404) b = orca.get_broadcast(cast_name, onto_name) return jsonify( cast=b.cast, onto=b.onto, cast_on=b.cast_on, onto_on=b.onto_on, cast_index=b.cast_index, onto_index=b.onto_index)
def broadcast_definition(cast_name, onto_name)
Return the definition of a broadcast as an object with keys "cast", "onto", "cast_on", "onto_on", "cast_index", and "onto_index". These are the same as the arguments to the ``broadcast`` function.
2.799401
2.280952
1.227295
if not orca.is_step(step_name): abort(404) filename, lineno, source = \ orca.get_step(step_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify(filename=filename, lineno=lineno, text=source, html=html)
def step_definition(step_name)
Get the source of a step function. Returned object has keys "filename", "lineno", "text" and "html". "text" is the raw text of the function, "html" has been marked up by Pygments.
4.072432
3.460949
1.176681
if not fmt: fmt = US_LOG_FMT if not datefmt: datefmt = US_LOG_DATE_FMT handler.setFormatter(logging.Formatter(fmt=fmt, datefmt=datefmt)) if level is not None: handler.setLevel(level) logger = logging.getLogger('orca') logger.addHandler(handler) if propagate i...
def _add_log_handler( handler, level=None, fmt=None, datefmt=None, propagate=None)
Add a logging handler to Orca. Parameters ---------- handler : logging.Handler subclass level : int, optional An optional logging level that will apply only to this stream handler. fmt : str, optional An optional format string that will be used for the log messages. ...
2.302687
2.149034
1.071499
_add_log_handler( logging.StreamHandler(), fmt=fmt, datefmt=datefmt, propagate=False)
def log_to_stream(level=None, fmt=None, datefmt=None)
Send log messages to the console. Parameters ---------- level : int, optional An optional logging level that will apply only to this stream handler. fmt : str, optional An optional format string that will be used for the log messages. datefmt : str, optional ...
6.345307
8.364433
0.758606
_add_log_handler( logging.FileHandler(filename), fmt=fmt, datefmt=datefmt)
def log_to_file(filename, level=None, fmt=None, datefmt=None)
Send log output to the given file. Parameters ---------- filename : str level : int, optional An optional logging level that will apply only to this stream handler. fmt : str, optional An optional format string that will be used for the log messages. datefmt : st...
5.32823
6.758887
0.78833
_TABLES.clear() _COLUMNS.clear() _STEPS.clear() _BROADCASTS.clear() _INJECTABLES.clear() _TABLE_CACHE.clear() _COLUMN_CACHE.clear() _INJECTABLE_CACHE.clear() for m in _MEMOIZED.values(): m.value.clear_cached() _MEMOIZED.clear() logger.debug('pipeline state cleare...
def clear_all()
Clear any and all stored state from Orca.
4.970047
5.042567
0.985619
if not scope: _TABLE_CACHE.clear() _COLUMN_CACHE.clear() _INJECTABLE_CACHE.clear() for m in _MEMOIZED.values(): m.value.clear_cached() logger.debug('pipeline cache cleared') else: for d in (_TABLE_CACHE, _COLUMN_CACHE, _INJECTABLE_CACHE): ...
def clear_cache(scope=None)
Clear all cached data. Parameters ---------- scope : {None, 'step', 'iteration', 'forever'}, optional Clear cached values with a given scope. By default all cached values are removed.
3.811996
3.751672
1.016079
# Map registered variable labels to expressions. if not expressions: expressions = [] offset = len(names) - len(expressions) labels_map = dict(tz.concatv( tz.compatibility.zip(names[:offset], names[:offset]), tz.compatibility.zip(names[offset:], expressions))) all_varia...
def _collect_variables(names, expressions=None)
Map labels and expressions to registered variables. Handles argument matching. Example: _collect_variables(names=['zones', 'zone_id'], expressions=['parcels.zone_id']) Would return a dict representing: {'parcels': <DataFrameWrapper for zones>, 'zone_i...
5.66607
5.137852
1.102809
if isinstance(table, Callable): table = TableFuncWrapper(table_name, table, cache=cache, cache_scope=cache_scope, copy_col=copy_col) else: table = DataFrameWrapper(table_name, table, copy_col=copy_col) # clear any cached data from a previously registere...
def add_table( table_name, table, cache=False, cache_scope=_CS_FOREVER, copy_col=True)
Register a table with Orca. Parameters ---------- table_name : str Should be globally unique to this table. table : pandas.DataFrame or function If a function, the function should return a DataFrame. The function's argument names and keyword argument values will be match...
3.166793
2.864315
1.105602
def decorator(func): if table_name: name = table_name else: name = func.__name__ add_table( name, func, cache=cache, cache_scope=cache_scope, copy_col=copy_col) return func return decorator
def table( table_name=None, cache=False, cache_scope=_CS_FOREVER, copy_col=True)
Decorates functions that return DataFrames. Decorator version of `add_table`. Table name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argument name "iter_var"...
2.196821
2.522288
0.870964
table = get_raw_table(table_name) if isinstance(table, TableFuncWrapper): table = table() return table
def get_table(table_name)
Get a registered table. Decorated functions will be converted to `DataFrameWrapper`. Parameters ---------- table_name : str Returns ------- table : `DataFrameWrapper`
6.02025
8.115495
0.741822
table = get_raw_table(table_name) if isinstance(table, DataFrameWrapper): return 'dataframe' elif isinstance(table, TableFuncWrapper): return 'function'
def table_type(table_name)
Returns the type of a registered table. The type can be either "dataframe" or "function". Parameters ---------- table_name : str Returns ------- table_type : {'dataframe', 'function'}
5.211332
4.906992
1.062022
if isinstance(column, Callable): column = \ _ColumnFuncWrapper( table_name, column_name, column, cache=cache, cache_scope=cache_scope) else: column = _SeriesWrapper(table_name, column_name, column) # clear any cached data from a previously re...
def add_column( table_name, column_name, column, cache=False, cache_scope=_CS_FOREVER)
Add a new column to a table from a Series or callable. Parameters ---------- table_name : str Table with which the column will be associated. column_name : str Name for the column. column : pandas.Series or callable Series should have an index matching the table to which it ...
3.294986
3.259081
1.011017
def decorator(func): if column_name: name = column_name else: name = func.__name__ add_column( table_name, name, func, cache=cache, cache_scope=cache_scope) return func return decorator
def column(table_name, column_name=None, cache=False, cache_scope=_CS_FOREVER)
Decorates functions that return a Series. Decorator version of `add_column`. Series index must match the named table. Column name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated ...
2.569965
2.743588
0.936717
return {cname: col for (tname, cname), col in _COLUMNS.items() if tname == table_name}
def _columns_for_table(table_name)
Return all of the columns registered for a given table. Parameters ---------- table_name : str Returns ------- columns : dict of column wrappers Keys will be column names.
6.821861
10.356737
0.658688
try: return _COLUMNS[(table_name, column_name)] except KeyError: raise KeyError('column {!r} not found for table {!r}'.format( column_name, table_name))
def get_raw_column(table_name, column_name)
Get a wrapped, registered column. This function cannot return columns that are part of wrapped DataFrames, it's only for columns registered directly through Orca. Parameters ---------- table_name : str column_name : str Returns ------- wrapped : _SeriesWrapper or _ColumnFuncWrappe...
3.23854
3.729692
0.868313
cache = {} @wraps(f) def wrapper(*args, **kwargs): try: cache_key = ( args or None, frozenset(kwargs.items()) if kwargs else None) in_cache = cache_key in cache except TypeError: raise TypeError( 'function arguments mu...
def _memoize_function(f, name, cache_scope=_CS_FOREVER)
Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters ---------- f : function name : str Name of injectable. cache_scope : {'step', 'iteration', 'forever'}, optional Scope for which to cache data. Default is to cache forever (or u...
2.803828
3.037714
0.923006
if isinstance(value, Callable): if autocall: value = _InjectableFuncWrapper( name, value, cache=cache, cache_scope=cache_scope) # clear any cached data from a previously registered value value.clear_cached() elif not autocall and memoize: ...
def add_injectable( name, value, autocall=True, cache=False, cache_scope=_CS_FOREVER, memoize=False)
Add a value that will be injected into other functions. Parameters ---------- name : str value If a callable and `autocall` is True then the function's argument names and keyword argument values will be matched to registered variables when the function needs to be evalua...
3.857288
4.097395
0.9414
def decorator(func): if name: n = name else: n = func.__name__ add_injectable( n, func, autocall=autocall, cache=cache, cache_scope=cache_scope, memoize=memoize) return func return decorator
def injectable( name=None, autocall=True, cache=False, cache_scope=_CS_FOREVER, memoize=False)
Decorates functions that will be injected into other functions. Decorator version of `add_injectable`. Name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argum...
2.011394
2.694465
0.746491
i = get_raw_injectable(name) return i() if isinstance(i, _InjectableFuncWrapper) else i
def get_injectable(name)
Get an injectable by name. *Does not* evaluate wrapped functions. Parameters ---------- name : str Returns ------- injectable Original value or evaluated value of an _InjectableFuncWrapper.
7.521064
6.44251
1.167412
if injectable_type(name) != 'function': raise ValueError('injectable {!r} is not a function'.format(name)) inj = get_raw_injectable(name) if isinstance(inj, _InjectableFuncWrapper): return utils.func_source_data(inj._func) elif hasattr(inj, '__wrapped__'): return utils.fun...
def get_injectable_func_source_data(name)
Return data about an injectable function's source, including file name, line number, and source code. Parameters ---------- name : str Returns ------- filename : str lineno : int The line number on which the function starts. source : str
3.051527
3.674383
0.830487
if isinstance(func, Callable): logger.debug('registering step {!r}'.format(step_name)) _STEPS[step_name] = _StepFuncWrapper(step_name, func) else: raise TypeError('func must be a callable')
def add_step(step_name, func)
Add a step function to Orca. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argument name "iter_var" may be used to have the current iteration variable injected. Parameters ---------- ...
3.666565
3.92545
0.93405
def decorator(func): if step_name: name = step_name else: name = func.__name__ add_step(name, func) return func return decorator
def step(step_name=None)
Decorates functions that will be called by the `run` function. Decorator version of `add_step`. step name defaults to name of function. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argumen...
2.691105
2.993719
0.898917
logger.debug( 'registering broadcast of table {!r} onto {!r}'.format(cast, onto)) _BROADCASTS[(cast, onto)] = \ Broadcast(cast, onto, cast_on, onto_on, cast_index, onto_index)
def broadcast(cast, onto, cast_on=None, onto_on=None, cast_index=False, onto_index=False)
Register a rule for merging two tables by broadcasting one onto the other. Parameters ---------- cast, onto : str Names of registered tables. cast_on, onto_on : str, optional Column names used for merge, equivalent of ``left_on``/``right_on`` parameters of pandas.merge. ...
3.947258
4.101452
0.962405
tables = set(tables) casts = tz.keyfilter( lambda x: x[0] in tables and x[1] in tables, _BROADCASTS) if tables - set(tz.concat(casts.keys())): raise ValueError('Not enough links to merge all tables.') return casts
def _get_broadcasts(tables)
Get the broadcasts associated with a set of tables. Parameters ---------- tables : sequence of str Table names for which broadcasts have been registered. Returns ------- casts : dict of `Broadcast` Keys are tuples of strings like (cast_name, onto_name).
7.307509
8.299111
0.880517
if is_broadcast(cast_name, onto_name): return _BROADCASTS[(cast_name, onto_name)] else: raise KeyError( 'no rule found for broadcasting {!r} onto {!r}'.format( cast_name, onto_name))
def get_broadcast(cast_name, onto_name)
Get a single broadcast. Broadcasts are stored data about how to do a Pandas join. A Broadcast object is a namedtuple with these attributes: - cast: the name of the table being broadcast - onto: the name of the table onto which "cast" is broadcast - cast_on: The optional name of a colum...
3.794706
4.463166
0.850227
for k, v in t.items(): for tname in _all_reachable_tables(v): yield tname yield k
def _all_reachable_tables(t)
A generator that provides all the names of tables that can be reached via merges starting at the given target table.
3.504682
3.732392
0.938991
if key in d: return d else: for v in d.values(): return _recursive_getitem(v, key) else: raise KeyError('Key not found: {}'.format(key))
def _recursive_getitem(d, key)
Descend into a dict of dicts to return the one that contains a given key. Every value in the dict must be another dict.
2.762477
2.580897
1.070356
d = d[tz.first(d)] for k, v in d.items(): yield {k: v}
def _dict_value_to_pairs(d)
Takes the first value of a dictionary (which it self should be a dictionary) and turns it into a series of {key: value} dicts. For example, _dict_value_to_pairs({'c': {'a': 1, 'b': 2}}) will yield {'a': 1} and {'b': 2}.
8.184318
11.704535
0.699243
if all(_is_leaf_node(d) for d in _dict_value_to_pairs(merge_node)): return merge_node else: for d in tz.remove(_is_leaf_node, _dict_value_to_pairs(merge_node)): return _next_merge(d) else: raise OrcaError('No node found for next merge.')
def _next_merge(merge_node)
Gets a node that has only leaf nodes below it. This table and the ones below are ready to be merged to make a new leaf node.
5.221391
4.913374
1.062689
table_names = set() for s in steps: table_names |= get_step(s)._tables_used() return list(table_names)
def get_step_table_names(steps)
Returns a list of table names injected into the provided steps. Parameters ---------- steps: list of str Steps to gather table inputs from. Returns ------- list of str
4.466512
5.840474
0.764752
if table_names is None: table_names = list_tables() tables = (get_table(t) for t in table_names) key_template = '{}/{{}}'.format(prefix) if prefix is not None else '{}' # set compression options to zlib level-1 if compress arg is True complib = compress and 'zlib' or None compleve...
def write_tables(fname, table_names=None, prefix=None, compress=False, local=False)
Writes tables to a pandas.HDFStore file. Parameters ---------- fname : str File name for HDFStore. Will be opened in append mode and closed at the end of this function. table_names: list of str, optional, default None List of tables to write. If None, all registered tables will ...
3.254016
3.315794
0.981369
global _INJECTABLES original = _INJECTABLES.copy() _INJECTABLES.update(kwargs) yield _INJECTABLES = original
def injectables(**kwargs)
Temporarily add injectables to the pipeline environment. Takes only keyword arguments. Injectables will be returned to their original state when the context manager exits.
3.558792
3.509503
1.014045
global _TABLES original = _TABLES.copy() for k, v in kwargs.items(): if not isinstance(v, pd.DataFrame): raise ValueError('tables only accepts DataFrames') add_table(k, v) yield _TABLES = original
def temporary_tables(**kwargs)
Temporarily set DataFrames as registered tables. Tables will be returned to their original state when the context manager exits. Caching is not enabled for tables registered via this function.
4.851484
4.52161
1.072955
with injectables(**kwargs): vars = _collect_variables([name], [name]) return vars[name]
def eval_variable(name, **kwargs)
Execute a single variable function registered with Orca and return the result. Any keyword arguments are temporarily set as injectables. This gives the value as would be injected into a function. Parameters ---------- name : str Name of variable to evaluate. Use variable expressions...
16.131571
19.177423
0.841175
extra_cols = _columns_for_table(self.name) if columns is not None: columns = [columns] if isinstance(columns, str) else columns columns = set(columns) set_extra_cols = set(extra_cols) local_cols = set(self.local.columns) & columns - set_extra_col...
def to_frame(self, columns=None)
Make a DataFrame with the given columns. Will always return a copy of the underlying table. Parameters ---------- columns : sequence or string, optional Sequence of the column names desired in the DataFrame. A string can also be passed if only one column is desi...
2.831368
3.021718
0.937006
logger.debug('updating column {!r} in table {!r}'.format( column_name, self.name)) self.local[column_name] = series
def update_col(self, column_name, series)
Add or replace a column in the underlying DataFrame. Parameters ---------- column_name : str Column to add or replace. series : pandas.Series or sequence Column data.
4.980483
5.41893
0.91909
with log_start_finish( 'getting single column {!r} from table {!r}'.format( column_name, self.name), logger): extra_cols = _columns_for_table(self.name) if column_name in extra_cols: with log_start_finish( ...
def get_column(self, column_name)
Returns a column as a Series. Parameters ---------- column_name : str Returns ------- column : pandas.Series
3.331396
3.864562
0.862037
extra_cols = list_columns_for_table(self.name) if column_name in extra_cols: col = _COLUMNS[(self.name, column_name)] if isinstance(col, _SeriesWrapper): return 'series' elif isinstance(col, _ColumnFuncWrapper): return 'funct...
def column_type(self, column_name)
Report column type as one of 'local', 'series', or 'function'. Parameters ---------- column_name : str Returns ------- col_type : {'local', 'series', 'function'} 'local' means that the column is part of the registered table, 'series' means the co...
4.422907
4.234888
1.044398
logger.debug('updating column {!r} in table {!r}'.format( column_name, self.name)) col_dtype = self.local[column_name].dtype if series.dtype != col_dtype: if cast: series = series.astype(col_dtype) else: err_msg = "Dat...
def update_col_from_series(self, column_name, series, cast=False)
Update existing values in a column from another series. Index values must match in both column and series. Optionally casts data type to match the existing column. Parameters --------------- column_name : str series : panas.Series cast: bool, optional, default Fa...
2.608544
2.621041
0.995232
_TABLE_CACHE.pop(self.name, None) for col in _columns_for_table(self.name).values(): col.clear_cached() logger.debug('cleared cached columns for table {!r}'.format(self.name))
def clear_cached(self)
Remove cached results from this table's computed columns.
4.949446
4.212556
1.174927
if self._columns: return self._columns else: self._call_func() return self._columns
def local_columns(self)
Only the columns contained in the DataFrame returned by the wrapped function. (No registered columns included.)
5.965687
4.750925
1.25569
if _CACHING and self.cache and self.name in _TABLE_CACHE: logger.debug('returning table {!r} from cache'.format(self.name)) return _TABLE_CACHE[self.name].value with log_start_finish( 'call function to get frame for table {!r}'.format( ...
def _call_func(self)
Call the wrapped function and return the result wrapped by DataFrameWrapper. Also updates attributes like columns, index, and length.
4.752474
4.066377
1.168724
frame = self._call_func() return DataFrameWrapper(self.name, frame, copy_col=self.copy_col).get_column(column_name)
def get_column(self, column_name)
Returns a column as a Series. Parameters ---------- column_name : str Returns ------- column : pandas.Series
10.004715
11.394864
0.878002
x = _COLUMN_CACHE.pop((self.table_name, self.name), None) if x is not None: logger.debug( 'cleared cached value for column {!r} in table {!r}'.format( self.name, self.table_name))
def clear_cached(self)
Remove any cached result of this column.
4.299822
3.343595
1.285988
x = _INJECTABLE_CACHE.pop(self.name, None) if x: logger.debug( 'injectable {!r} removed from cache'.format(self.name))
def clear_cached(self)
Clear a cached result for this injectable.
7.024894
4.807514
1.461232
args = list(self._argspec.args) if self._argspec.defaults: default_args = list(self._argspec.defaults) else: default_args = [] # Combine names from argument names and argument default values. names = args[:len(args) - len(default_args)] + default_...
def _tables_used(self)
Tables injected into the step. Returns ------- tables : set of str
3.149985
3.297612
0.955232
if root: start = root else: index = random.randint(0, len(nodes) - 1) start = nodes[index] # A queue to BFS instead DFS to_visit = deque() cnodes = copy(nodes) visited = set() # Format is (parent, parent_edge, neighbor, neighbor_field) to_visit.append((None, ...
def qbe_tree(graph, nodes, root=None)
Given a graph, nodes to explore and an optinal root, do a breadth-first search in order to return the tree.
2.897599
2.863433
1.011932
length_items = len(items) lengths = [len(i) for i in items] length = reduce(lambda x, y: x * y, lengths) repeats = [reduce(lambda x, y: x * y, lengths[i:]) for i in range(1, length_items)] + [1] if k is not None: k = k % length # Python division by default is inte...
def combine(items, k=None)
Create a matrix in wich each row is a tuple containing one of solutions or solution k-esima.
3.61747
3.482099
1.038876
"Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) return base64.encodestring(pickled + get_query_hash(pickled).encode())
def pickle_encode(session_dict)
Returns the given session dictionary pickled and encoded as a string.
5.286646
4.058415
1.302638
filename = inspect.getsourcefile(func) lineno = inspect.getsourcelines(func)[1] source = inspect.getsource(func) return filename, lineno, source
def func_source_data(func)
Return data about a function source, including file name, line number, and source code. Parameters ---------- func : object May be anything support by the inspect module, such as a function, method, or class. Returns ------- filename : str lineno : int The line ...
2.318898
2.432513
0.953293
if any(self.errors): # Don't bother validating the formset unless each form is valid on # its own return (selects, aliases, froms, wheres, sorts, groups_by, params) = self.get_query_parts() if not selects: validation_message = _(u...
def clean(self)
Checks that there is almost one field to select
5.516786
4.987062
1.10622
selects = [] aliases = [] froms = [] wheres = [] sorts = [] groups_by = [] params = [] app_model_labels = None lookup_cast = self._db_operations.lookup_cast qn = self._db_operations.quote_name uqn = self._unquote_name ...
def get_query_parts(self)
Return SQL query for cleaned data
2.744979
2.716697
1.01041
add_extra_ids = (admin_name is not None) if not query: sql = self.get_raw_query(limit=limit, offset=offset, add_extra_ids=add_extra_ids) else: sql = query if settings.DEBUG: print(sql) cursor = self...
def get_results(self, limit=None, offset=None, query=None, admin_name=None, row_number=False)
Fetch all results after perform SQL query and
2.650738
2.693049
0.984289
if '; charset=' in content_type: return tuple(content_type.split('; charset=')) else: if 'text' in content_type: encoding = 'ISO-8859-1' else: try: format = formats.find_by_content_type(content_type) except formats.UnknownFormat: ...
def parse_content_type(content_type)
Return a tuple of content type and charset. :param content_type: A string describing a content type.
2.636078
2.80732
0.939002
components = [item.strip() for item in header.split(',')] l = [] for component in components: if ';' in component: subcomponents = [item.strip() for item in component.split(';')] l.append( ( subcomponents[0], # eg. 'text/html' ...
def parse_http_accept_header(header)
Return a list of content types listed in the HTTP Accept header ordered by quality. :param header: A string describing the contents of the HTTP Accept header.
2.444238
2.401194
1.017926
return MultiPartParser( META=request.META, input_data=StringIO(request.body), upload_handlers=request.upload_handlers, encoding=request.encoding ).parse()
def parse_multipart_data(request)
Parse a request with multipart data. :param request: A HttpRequest instance.
5.90417
7.590386
0.777848
routes = deepcopy(routes) def dispatch(request, GET=False, POST=False, PUT=False, DELETE=False, PATCH=False, **kwargs): # Return HTTP 405 Method Not Allowed if the request method isn't routed if request.method == 'GET' and not GET \ or request.method == 'POST' and not POS...
def resource(views, routes, prefix='')
Route a collection of views. :param views: A reference to the class that defines the views. :param routes: A list of routes. :param prefix: A string to prefix the routes by, or ``''`` by default.
2.284122
2.335386
0.978049
def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): self.supported_formats = formats return function(self, *args, **kwargs) return wrapper return decorator
def override_supported_formats(formats)
Override the views class' supported formats for the decorated function. Arguments: formats -- A list of strings describing formats, e.g. ``['html', 'json']``.
2.215123
2.425893
0.913116
def decorator(function): function.route = routes.route( regex = regex, view = function.__name__, method = method, name = name ) @wraps(function) def wrapper(self, *args, **kwargs): return function(self, *args, **kwarg...
def route(regex, method, name)
Route the decorated view. :param regex: A string describing a regular expression to which the request path will be matched. :param method: A string describing the HTTP method that this view accepts. :param name: A string describing the name of the URL pattern. ``regex`` may also be a lambda that a...
3.05641
3.22732
0.947043
def decorator(function): @wraps(function) def wrapper(self, *args, **kwargs): returns = getattr(self, method_name)(*args, **kwargs) if returns is None: return function(self, *args, **kwargs) else: if isinstance(returns, HttpRe...
def before(method_name)
Run the given method prior to the decorated view. If you return anything besides ``None`` from the given method, its return values will replace the arguments of the decorated view. If you return an instance of ``HttpResponse`` from the given method, Respite will return it immediately without deleg...
2.216354
2.653505
0.835255
objects = self.model.objects.all() return self._render( request = request, template = 'index', context = { cc2us(pluralize(self.model.__name__)): objects, }, status = 200 )
def index(self, request)
Render a list of objects.
6.320935
5.860355
1.078592
form = (self.form or generate_form(self.model))() return self._render( request = request, template = 'new', context = { 'form': form }, status = 200 )
def new(self, request)
Render a form to create a new object.
4.592947
4.209957
1.090972
form = (self.form or generate_form(self.model))(request.POST) if form.is_valid(): object = form.save() return self._render( request = request, template = 'show', context = { cc2us(self.model.__name__):...
def create(self, request)
Create a new object.
3.456001
3.344859
1.033228
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name...
def edit(self, request, id)
Render a form to edit an object.
3.52643
3.402215
1.03651
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name...
def update(self, request, id)
Update an object.
2.433177
2.394623
1.016101
try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.' % self.model.__name...
def replace(self, request, id)
Replace an object.
2.603266
2.57837
1.009656
try: object = self.model.objects.get(id=id) object.delete() except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be...
def destroy(self, request, id)
Delete an object.
2.795945
2.759878
1.013068
# Building search query # queries generated by different search_fields are ANDed # if a search field is defined for more than one field, are put together with OR and_query = Q() for fieldname in fields_dict: search_field = fields_dict[fieldname] if fieldname in params_dict and ...
def build_q(fields_dict, params_dict, request=None)
Returns a Q object from filters config and actual parmeters.
2.547813
2.531858
1.006302
sfdict = {} for klass in tuple(cls.__bases__) + (cls, ): if hasattr(klass, 'search_fields'): sfdict.update(klass.search_fields) return sfdict
def get_search_fields(cls)
Returns search fields in sfdict
4.142842
2.822433
1.467827
for format in FORMATS: if identifier in [format.name, format.acronym, format.extension]: return format raise UnknownFormat('No format found with name, acronym or extension "%s"' % identifier)
def find(identifier)
Find and return a format by name, acronym or extension. :param identifier: A string describing the format.
4.678859
3.343885
1.399228
for format in FORMATS: if name == format.name: return format raise UnknownFormat('No format found with name "%s"' % name)
def find_by_name(name)
Find and return a format by name. :param name: A string describing the name of the format.
4.770147
4.639719
1.028111