code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
_try_callback(self, fn) else: self._queue.put(dill.dumps(fn)) if self._process is None: self._process = mp.Process(target=self._execute_tasks) self._process.start()
def add_done_callback(self, fn): # pylint: disable=invalid-name if self._operation.done
Enters a polling loop on OperationsClient.get_operation, and once the operation is done or cancelled, calls the function with this _OperationFuture. Added callables are called in the order that they were added.
4.946441
5.745938
0.860859
# Check exceptional case: return none if no metadata if not self._operation.HasField('metadata'): return None # Return expected metadata return _from_any(self._metadata_type, self._operation.metadata)
def metadata(self)
Returns the value of Operation.metadata from the last call to OperationsClient.get_operation (or if only the initial API call has been made, the metadata from that first call).
10.951527
7.669252
1.427978
return '{0} {1} ON {2}'.format(self.join_type, self.right_table.get_sql(), self.get_condition())
def get_sql(self)
Generates the JOIN sql for the join tables and join condition :rtype: str :return: the JOIN sql for the join tables and join condition
4.785872
4.369999
1.095165
if left_table: self.left_table = TableFactory( table=left_table, owner=self.owner, ) else: self.left_table = self.get_left_table()
def set_left_table(self, left_table=None)
Sets the left table for this join clause. If no table is specified, the first table in the query will be used :type left_table: str or dict or :class:`Table <querybuilder.tables.Table>` or None :param left_table: The left table being joined with. This can be a string of the table na...
3.207489
4.497282
0.713206
if self.left_table: return self.left_table if len(self.owner.tables): return self.owner.tables[0]
def get_left_table(self)
Returns the left table if one was specified, otherwise the first table in the query is returned :rtype: :class:`Table <querybuilder.tables.Table>` :return: the left table if one was specified, otherwise the first table in the query
3.904987
4.285315
0.911249
# Django 1.7 method if hasattr(table.model._meta, 'get_all_related_objects'): return table.model._meta.get_all_related_objects() else: # Django > 1.7 return [ f for f in table.model._meta.get_fields() if (f.one_to_many ...
def get_all_related_objects(self, table)
Fix for django 1.10 to replace deprecated code. Keep support for django 1.7
2.24847
2.039068
1.102695
self.right_table = table if self.left_table is None: return # find table prefix if type(self.left_table) is ModelTable and type(self.right_table) is ModelTable: # loop through fields to find the field for this model # check if this join type...
def set_right_table(self, table)
Sets the right table for this join clause and try to automatically set the condition if one isn't specified
2.281445
2.257246
1.01072
if self.condition: return self.condition if type(self.right_table) is ModelTable and type(self.right_table) is ModelTable: # loop through fields to find the field for this model # check if this join type is for a related field for field in self....
def get_condition(self)
Determines the condition to be used in the condition part of the join sql. :return: The condition for the join clause :rtype: str or None
2.325974
2.256094
1.030973
# reset arg index and args self.arg_index = 0 self.args = {} # build the WHERE sql portion if needed if len(self.wheres): where = self.build_where_part(self.wheres) return 'WHERE {0} '.format(where) return ''
def get_sql(self)
Builds and returns the WHERE portion of the sql :return: the WHERE portion of the sql :rtype: str
6.478014
5.734173
1.129721
if operator in ('contains', 'icontains'): value = '%{0}%'.format(value) elif operator == 'startswith': value = '{0}%'.format(value) return value
def get_condition_value(self, operator, value)
Gets the condition value based on the operator and value :param operator: the condition operator name :type operator: str :param value: the value to be formatted based on the condition operator :type value: object :return: the comparison operator from the Where class's comparis...
2.712415
3.581584
0.757323
where_parts = [] # loop through each child of the Q condition for where in wheres.children: # if this child is another Q object, recursively build the where part if type(where) is Q: where_parts.append(self.build_where_part(where)) e...
def build_where_part(self, wheres)
Recursive method that builds the where parts. Any Q objects that have children will also be built with ``self.build_where_part()`` :rtype: str :return: The composed where string
2.785396
2.765826
1.007076
named_arg = '{0}A{1}'.format(self.arg_prefix, self.arg_index) self.args[named_arg] = value self.arg_index += 1 return named_arg
def set_arg(self, value)
Set the query param in self.args based on the prefix and arg index and auto increment the arg_index :return: the string placeholder for the arg :rtype: str
3.598626
3.208418
1.12162
if self.desc: direction = 'DESC' else: direction = 'ASC' if use_alias: return '{0} {1}'.format(self.field.get_identifier(), direction) return '{0} {1}'.format(self.field.get_select_sql(), direction)
def get_name(self, use_alias=True)
Gets the name to reference the sorted field :return: the name to reference the sorted field :rtype: str
3.645519
3.383224
1.077528
sql = '' if self.limit and self.limit > 0: sql += 'LIMIT {0} '.format(self.limit) if self.offset and self.offset > 0: sql += 'OFFSET {0} '.format(self.offset) return sql
def get_sql(self)
Generates the sql used for the limit clause of a Query :return: the sql for the limit clause of a Query :rtype: str
2.24721
2.136864
1.051639
self.sql = '' self.tables = [] self.joins = [] self._where = Where() self.groups = [] self.sorters = [] self._limit = None self.table_prefix = '' self.is_inner = False self.with_tables = [] self._distinct = False se...
def init_defaults(self)
Sets the default values for this instance
4.943459
4.737792
1.04341
# self.mark_dirty() self.tables.append(TableFactory( table=table, fields=fields, schema=schema, owner=self, **kwargs )) return self
def from_table(self, table=None, fields='*', schema=None, **kwargs)
Adds a ``Table`` and any optional fields to the list of tables this query is selecting from. :type table: str or dict or :class:`Table <querybuilder.tables.Table>` or :class:`Query <querybuilder.query.Query>` or :class:`ModelBase <django:django.db.models.base.ModelBase>` ...
4.885457
5.125322
0.9532
table = TableFactory( table=table, **kwargs ) self.tables.append(table) self.field_names = field_names self.values = values return self
def insert_into(self, table=None, field_names=None, values=None, **kwargs)
Bulk inserts a list of values into a table :type table: str or dict or :class:`Table <querybuilder.tables.Table>` or :class:`Query <querybuilder.query.Query>` or :class:`ModelBase <django:django.db.models.base.ModelBase>` :param table: The table to select fields from. This can be a string o...
4.534177
5.521955
0.821118
table = TableFactory( table=table, **kwargs ) self.tables.append(table) self.field_names = field_names self.values = values self.field_names_pk = pk
def update_table(self, table=None, field_names=None, values=None, pk=None, **kwargs)
Bulk updates rows in a table :type table: str or dict or :class:`Table <querybuilder.tables.Table>` or :class:`Query <querybuilder.query.Query>` or :class:`ModelBase <django:django.db.models.base.ModelBase>` :param table: The table to select fields from. This can be a string of the table ...
4.33297
5.267399
0.822601
# self.mark_dirty() # TODO: fix bug when joining from simple table to model table with no condition # it assumes left_table.model # if there is no left table, assume the query's first table # TODO: add test for auto left table to replace old auto left table # if...
def join(self, right_table=None, fields=None, condition=None, join_type='JOIN', schema=None, left_table=None, extract_fields=True, prefix_fields=False, field_prefix=None, allow_duplicates=False)
Joins a table to another table based on a condition and adds fields from the joined table to the returned fields. :type right_table: str or dict or :class:`Table <querybuilder.tables.Table>` :param right_table: The table being joined with. This can be a string of the table name, a d...
3.191321
3.119638
1.022978
return self.join( right_table=right_table, fields=fields, condition=condition, join_type=join_type, schema=schema, left_table=left_table, extract_fields=extract_fields, prefix_fields=prefix_fields, ...
def join_left(self, right_table=None, fields=None, condition=None, join_type='LEFT JOIN', schema=None, left_table=None, extract_fields=True, prefix_fields=False, field_prefix=None, allow_duplicates=False)
Wrapper for ``self.join`` with a default join of 'LEFT JOIN' :type right_table: str or dict or :class:`Table <querybuilder.tables.Table>` :param right_table: The table being joined with. This can be a string of the table name, a dict of {'alias': table}, or a ``Table`` instance :ty...
1.364604
1.521753
0.896731
# self.mark_dirty() if q is not None: self._where.wheres.add(q, where_type) if len(kwargs): for key, value in kwargs.items(): q = Q(**{ key: value }) self._where.wheres.add(q, where_type) ...
def where(self, q=None, where_type='AND', **kwargs)
Adds a where condition as a Q object to the query's ``Where`` instance. :type q: :class:`Q <django:django.db.models.Q>` :param q: A django ``Q`` instance. This will be added to the query's ``Where`` object. If no Q object is passed, the kwargs will be examined for params to be added to Q ob...
3.245204
3.462949
0.937122
new_group_item = Group( field=field, table=table, ) if allow_duplicates is False: for group_item in self.groups: if group_item.field.get_identifier() == new_group_item.field.get_identifier(): return self s...
def group_by(self, field=None, table=None, allow_duplicates=False)
Adds a group by clause to the query by adding a ``Group`` instance to the query's groups list :type field: str or dict or :class:`Field <querybuilder.fields.Field>` :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type...
2.921146
3.068197
0.952073
self.sorters.append(Sorter( field=field, table=table, desc=desc )) return self
def order_by(self, field=None, table=None, desc=False)
Adds an order by clause to the query by adding a ``Sorter`` instance to the query's sorters list :type field: str or dict or :class:`Field <querybuilder.fields.Field>` :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :t...
3.75823
4.889612
0.768615
table_index = 0 table_names = {} for table in self.tables + self.with_tables: table_prefix = 'T{0}'.format(table_index) auto_alias = '{0}{1}'.format(self.table_prefix, table_prefix) identifier = table.get_identifier() if identifier is Non...
def check_name_collisions(self)
Checks if there are any tables referenced by the same identifier and updated the auto_alias accordingly. This is called when generating the sql for a query and should only be called internally.
4.974303
4.114449
1.208984
# TODO: enable caching # if self.sql and use_cache and not debug: # return self.sql # auto alias any naming collisions self.check_name_collisions() # if debugging, return the debug formatted sql if debug: return self.format_sql() ...
def get_sql(self, debug=False, use_cache=True)
Generates the sql for this query and returns the sql as a string. :type debug: bool :param debug: If True, the sql will be returned in a format that is easier to read and debug. Defaults to False :type use_cache: bool :param use_cache: If True, the query will returned the c...
3.30578
3.273972
1.009716
field_names = self.get_field_names() pk = field_names[0] update_field_names = field_names[1:] num_columns = len(rows[0]) if num_columns < 2: raise Exception('At least 2 fields must be passed to get_update_sql') all_null_indices = [ all(r...
def get_update_sql(self, rows)
Returns SQL UPDATE for rows ``rows`` .. code-block:: sql UPDATE table_name SET field1 = new_values.field1 field2 = new_values.field2 FROM ( VALUES (1, 'value1', 'value2'), (2, 'value1', ...
2.436032
2.37867
1.024115
ModelClass = self.tables[0].model # Use all fields except pk unless the uniqueness constraint is the pk field. Null pk field rows will be # excluded in the upsert method before calling this method all_fields = [field for field in ModelClass._meta.fields if field.column != auto_...
def get_upsert_sql( self, rows, unique_fields, update_fields, auto_field_name=None, only_insert=False, return_rows=True )
Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT) INSERT INTO table_name (field1, field2) VALUES (1, 'two') ON CONFLICT (unique_field) DO UPDATE SET field2 = EXCLUDED.field2;
2.213427
2.240604
0.98787
# TODO: finish adding the other parts of the sql generation sql = '' # build SELECT select_segment = self.build_select_fields() select_segment = select_segment.replace('SELECT ', '', 1) fields = [field.strip() for field in select_segment.split(',')] sql ...
def format_sql(self)
Builds the sql in a format that is easy for humans to read and debug :return: The formatted sql for this query :rtype: str
1.787405
1.784208
1.001792
field_names = [] for table in self.tables: field_names.extend(table.get_field_names()) for join_item in self.joins: field_names.extend(join_item.right_table.get_field_names()) return field_names
def get_field_names(self)
Builds a list of the field names for all tables and joined tables by calling ``get_field_names()`` on each table :return: list of field names :rtype: list of str
2.335819
2.348706
0.994513
field_identifiers = [] for table in self.tables: field_identifiers += table.get_field_identifiers() for join_item in self.joins: field_identifiers += join_item.right_table.get_field_identifiers() return field_identifiers
def get_field_identifiers(self)
Builds a list of the field identifiers for all tables and joined tables by calling ``get_field_identifiers()`` on each table :return: list of field identifiers :rtype: list of str
2.574596
2.523111
1.020405
field_sql = [] # get the field sql for each table for table in self.tables: field_sql += table.get_field_sql() # get the field sql for each join table for join_item in self.joins: field_sql += join_item.right_table.get_field_sql() # com...
def build_select_fields(self)
Generates the sql for the SELECT portion of the query :return: the SELECT portion of the query :rtype: str
3.446324
3.393541
1.015554
table_parts = [] # get the table sql for each table for table in self.tables: sql = table.get_sql() if len(sql): table_parts.append(sql) # combine all table sql separated by a comma sql = 'FROM {0} '.format(', '.join(table_parts)...
def build_from_table(self)
Generates the sql for the FROM portion of the query :return: the FROM portion of the query :rtype: str
4.886402
4.343659
1.124951
join_parts = [] # get the sql for each join object for join_item in self.joins: join_parts.append(join_item.get_sql()) # if there are any joins, combine them if len(join_parts): combined_joins = ' '.join(join_parts) return '{0} '.for...
def build_joins(self)
Generates the sql for the JOIN portion of the query :return: the JOIN portion of the query :rtype: str
3.278151
3.226451
1.016024
# check if there are any groupings if len(self.groups): groups = [] # get the group sql for each grouping for group in self.groups: groups.append(group.get_name()) return 'GROUP BY {0} '.format(', '.join(groups)) return ''
def build_groups(self)
Generates the sql for the GROUP BY portion of the query :return: the GROUP BY portion of the query :rtype: str
5.180717
4.42811
1.169961
# check if there are any sorters if len(self.sorters): sorters = [] # get the sql for each sorter for sorter in self.sorters: sorters.append(sorter.get_name(use_alias=use_alias)) return 'ORDER BY {0} '.format(', '.join(sorters)) ...
def build_order_by(self, use_alias=True)
Generates the sql for the ORDER BY portion of the query :type use_alias: bool :param use_alias: If True, the alias for the field will be used in the order by. This is an option before query windows do not use the alias. Defaults to True. :return: the ORDER BY portion of the query ...
3.646921
3.581312
1.01832
table = TableFactory(table) identifier = table.get_identifier() join_tables = [join_item.right_table for join_item in self.joins] for table in (self.tables + join_tables): if table.get_identifier() == identifier: return table return None
def find_table(self, table)
Finds a table by name or alias. The FROM tables and JOIN tables are included in the search. :type table: str or :class:`ModelBase <django:django.db.models.base.ModelBase>` :param table: string of the table name or alias or a ModelBase instance :return: The table if it is found, otherwi...
4.292149
4.912458
0.873727
field_names = self.get_field_names() query = Query(self.connection).from_table(deepcopy(self), alias=alias) self.__dict__.update(query.__dict__) # set explicit field names self.tables[0].set_fields(field_names) field_names = self.get_field_names() retur...
def wrap(self, alias=None)
Wraps the query by selecting all fields from itself :rtype: :class:`Query <querybuilder.query.Query>` :return: The wrapped query
5.314495
4.888563
1.087128
connection = self.connection del self.connection copied_query = deepcopy(self) copied_query.connection = connection self.connection = connection return copied_query
def copy(self)
Deeply copies everything in the query object except the connection object is shared
5.039102
3.19907
1.575177
for table in self.tables + self.with_tables: if type(table) is QueryTable: self._where.args.update(table.query.get_args()) return self._where.args
def get_args(self)
Gets the args for the query which will be escaped when being executed by the db. All inner queries are inspected and their args are combined with this query's args. :return: all args for this query as a dict :rtype: dict
7.78369
6.593166
1.180569
cursor = self.get_cursor() if sql is None: sql = self.get_sql() sql_args = self.get_args() elif sql_args is None: sql_args = {} cursor.execute('EXPLAIN {0}'.format(sql), sql_args) rows = self._fetch_all_as_dict(cursor) return ...
def explain(self, sql=None, sql_args=None)
Runs EXPLAIN on this query :type sql: str or None :param sql: The sql to run EXPLAIN on. If None is specified, the query will use ``self.get_sql()`` :type sql_args: dict or None :param sql_args: A dictionary of the arguments to be escaped in the query. If None and ...
2.59114
2.478757
1.045338
# Check if we need to set a safe limit if bypass_safe_limit is False: if Query.enable_safe_limit: if self.count() > Query.safe_limit: self.limit(Query.safe_limit) # determine which sql to use if sql is None: sql = self...
def select(self, return_models=False, nest=False, bypass_safe_limit=False, sql=None, sql_args=None)
Executes the SELECT statement and returns the rows as a list of dictionaries or a list of model instances :type return_models: bool :param return_models: Set to True to return a list of models instead of a list of dictionaries. Defaults to False :type nest: bool :pa...
3.28049
3.145804
1.042814
if len(rows) == 0: return sql, sql_args = self.get_insert_sql(rows) # get the cursor to execute the query cursor = self.get_cursor() # execute the query cursor.execute(sql, sql_args)
def insert(self, rows)
Inserts records into the db # TODO: implement this
2.990185
2.824616
1.058617
if len(rows) == 0: return sql, sql_args = self.get_update_sql(rows) # get the cursor to execute the query cursor = self.get_cursor() # execute the query cursor.execute(sql, sql_args)
def update(self, rows)
Updates records in the db
3.027797
2.987681
1.013427
# Get auto field name (a model can only have one AutoField) for field in model_class._meta.fields: if isinstance(field, AutoField): return field.column return None
def get_auto_field_name(self, model_class)
If one of the unique_fields is the model's AutoField, return the field name, otherwise return None
5.21682
4.064608
1.283474
if len(rows) == 0: return ModelClass = self.tables[0].model rows_with_null_auto_field_value = [] # Get auto field name (a model can only have one AutoField) auto_field_name = self.get_auto_field_name(ModelClass) # Check if unique fields list conta...
def upsert(self, rows, unique_fields, update_fields, return_rows=False, return_models=False)
Performs an upsert with the set of models defined in rows. If the unique field which is meant to cause a conflict is an auto increment field, then the field should be excluded when its value is null. In this case, an upsert will be performed followed by a bulk_create
2.131257
2.092505
1.018519
query_copy = self.copy() if not query_copy.tables: raise Exception('No tables specified to do a count') for table in query_copy.tables: del table.fields[:] query_copy.tables[0].add_field(CountField('*')) del query_copy.sorters[:] return ...
def get_count_query(self)
Copies the query object and alters the field list and order by to do a more efficient count
5.118517
4.230578
1.209886
rows = self.get_count_query().select(bypass_safe_limit=True) return list(rows[0].values())[0]
def count(self, field='*')
Returns a COUNT of the query by wrapping the query and performing a COUNT aggregate of the specified field :param field: the field to pass to the COUNT aggregate. Defaults to '*' :type field: str :return: The number of rows that the query will return :rtype: int
14.025455
16.873558
0.831209
q = Query(self.connection).from_table(self, fields=[ MaxField(field) ]) rows = q.select(bypass_safe_limit=True) return list(rows[0].values())[0]
def max(self, field)
Returns the maximum value of a field in the result set of the query by wrapping the query and performing a MAX aggregate of the specified field :param field: the field to pass to the MAX aggregate :type field: str :return: The maximum value of the specified field :rtype: int
9.451456
11.579568
0.816218
q = Query(self.connection).from_table(self, fields=[ MinField(field) ]) rows = q.select(bypass_safe_limit=True) return list(rows[0].values())[0]
def min(self, field)
Returns the minimum value of a field in the result set of the query by wrapping the query and performing a MIN aggregate of the specified field :param field: the field to pass to the MIN aggregate :type field: str :return: The minimum value of the specified field :rtype: int
9.578313
11.315225
0.846498
q = Query(self.connection).from_table(self, fields=[ SumField(field) ]) rows = q.select(bypass_safe_limit=True) return list(rows[0].values())[0]
def sum(self, field)
Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field :rtype: int
9.397724
11.457002
0.82026
q = Query(self.connection).from_table(self, fields=[ AvgField(field) ]) rows = q.select(bypass_safe_limit=True) return list(rows[0].values())[0]
def avg(self, field)
Returns the average of the field in the result set of the query by wrapping the query and performing an AVG aggregate of the specified field :param field: the field to pass to the AVG aggregate :type field: str :return: The average of the specified field :rtype: int
9.078805
11.089632
0.818675
desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
def _fetch_all_as_dict(self, cursor)
Iterates over the result set and converts each row to a dictionary :return: A list of dictionaries where each row is a dictionary :rtype: list of dict
2.422862
3.16707
0.765017
# TODO: implement caching and debug sql = '' sql += self.build_partition_by_fields() sql += self.build_order_by(use_alias=False) sql += self.build_limit() sql = sql.strip() sql = 'OVER ({0})'.format(sql) self.sql = sql return self.sql
def get_sql(self, debug=False, use_cache=True)
Generates the sql for this query window and returns the sql as a string. :type debug: bool :param debug: If True, the sql will be returned in a format that is easier to read and debug. Defaults to False :type use_cache: bool :param use_cache: If True, the query will returne...
5.208129
5.868649
0.887449
if len(keypath) == 0: return dict keys = keypath.split('.') value = dict for key in keys: if key in value: value = value[key] else: return None return value
def value_for_keypath(dict, keypath)
Returns the value of a keypath in a dictionary if the keypath exists or None if the keypath does not exist.
2.244765
2.170947
1.034002
if len(keypath) == 0: return None keys = keypath.split(delimeter) if len(keys) > 1: key = keys[0] if create_if_needed: item[key] = item.get(key, {}) if key in item: if set_value_for_keypath(item[key], delimeter.join(keys[1:]), value, ...
def set_value_for_keypath(item, keypath, value, create_if_needed=False, delimeter='.')
Sets the value for a keypath in a dictionary if the keypath exists. This modifies the original dictionary.
1.9352
1.893035
1.022274
alias = self.get_alias() if alias: if self.cast: return 'CAST({0} AS {1}) AS "{2}"'.format(self.get_select_sql(), self.cast.upper(), alias) return '{0} AS "{1}"'.format(self.get_select_sql(), alias) if self.cast: return 'CAST({0} AS {...
def get_sql(self)
Gets the SELECT sql part for a field Ex: field_name AS alias :return: the sql for this field used in the SELECT portion of the query :rtype: str
2.419413
2.305869
1.049242
alias = None if self.alias: alias = self.alias elif self.auto_alias: alias = self.auto_alias if self.table and self.table.prefix_fields: field_prefix = self.table.get_field_prefix() if alias: alias = '{0}__{1}'.for...
def get_alias(self)
Gets the alias for the field or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :return: The field alias, auto_alias, or None :rtype: str or None
2.720944
2.317262
1.174206
if self.table: return '{0}.{1}'.format(self.table.get_identifier(), self.name) return '{0}'.format(self.name)
def get_select_sql(self)
Gets the SELECT field portion for the field without the alias. If the field has a table, it will be included here like table.field :return: Gets the SELECT field portion for the field without the alias :rtype: str
4.232777
3.655175
1.158023
super(MultiField, self).set_table(table) if self.field and self.field.table is None: self.field.set_table(self.table)
def set_table(self, table)
Setter for the table of this field. Also sets the inner field's table.
3.82796
2.765733
1.384067
return '{0}({1}{2}){3}'.format( self.name.upper(), self.get_distinct(), self.get_field_identifier(), self.get_over(), )
def get_select_sql(self)
Gets the SELECT field portion for the field without the alias. If the field has a table, it will be included here like AggregateFunction(table.field) :return: Gets the SELECT field portion for the field without the alias :rtype: str
5.948329
6.158095
0.965936
if self.default is None: return '{0}, {1}'.format(self.field.get_select_sql(), self.offset) return "{0}, {1}, '{2}'".format(self.field.get_select_sql(), self.offset, self.default)
def get_field_identifier(self)
Return the lag/lead function with the offset and default value
3.873887
3.091879
1.252923
return '(({0}) - ({1}({2}){3}))'.format( self.field.get_select_sql(), self.name.upper(), self.get_field_identifier(), self.get_over(), )
def get_select_sql(self)
Calculate the difference between this record's value and the lag/lead record's value
7.871521
6.276607
1.254105
# ignore the original date field self.ignore = True datetime_str = None # create an alias for the unix timestamp extraction epoch_alias = '{0}__{1}'.format(self.field.get_name(), 'epoch') if self.name == 'all': datetime_str = self.field ...
def generate_auto_fields(self)
Generates any auto fields needed to properly group this date part. Ex: a Day field will create Year, Month, Day fields and group by Year, Month, Day
3.331921
3.210464
1.037832
self.table.add_field({ alias: field }) if add_group: self.table.owner.group_by(alias)
def add_to_table(self, field, alias, add_group=False)
Adds this field to the field's table and optionally group by it :param field: The field to add to the table :type field: str or :class:`Field <querybuilder.fields.Field>` :param alias: The alias for the field :type alias: str :param add_group: Whether or not the table should g...
6.229549
6.202628
1.00434
alias = self.get_alias() if alias: return '{0} AS {1}'.format(self.get_from_name(), alias) return self.get_identifier()
def get_sql(self)
Gets the FROM sql portion for this table Ex: table_name AS alias :returns: Returns the table identifier to be used in the FROM sql portion of the query :rtype: str
5.294823
4.262515
1.242183
alias = None if self.alias: alias = self.alias elif self.auto_alias: alias = self.auto_alias return alias
def get_alias(self)
Gets the alias for the table or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :returns: The table alias, auto_alias, or None :rtype: str or None
4.112308
2.858463
1.438643
field = FieldFactory( field, ) field.set_table(self) # make sure field is not already added field_name = field.get_name() for existing_field in self.fields: if existing_field.get_name() == field_name: return None ...
def add_field(self, field)
Adds a field to this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or Field
3.735262
4.195859
0.890226
new_field = FieldFactory( field, ) new_field.set_table(self) new_field_identifier = new_field.get_identifier() for field in self.fields: if field.get_identifier() == new_field_identifier: self.fields.remove(field) r...
def remove_field(self, field)
Removes a field from this table :param field: This can be a string of a field name, a dict of {'alias': field}, or a ``Field`` instance :type field: str or dict or :class:`Field <querybuilder.fields.Field>`
3.237412
3.652051
0.886464
if isinstance(fields, string_types): fields = [fields] elif type(fields) is tuple: fields = list(fields) field_objects = [self.add_field(field) for field in fields] return field_objects
def add_fields(self, fields)
Adds all of the passed fields to the table's current field list :param fields: The fields to select from ``table``. This can be a single field, a tuple of fields, or a list of fields. Each field can be a string or ``Field`` instance :type fields: str or tuple or list of str or l...
2.994828
3.705644
0.80818
if alias: field = alias field = FieldFactory(field, table=self, alias=alias) identifier = field.get_identifier() for field in self.fields: if field.get_identifier() == identifier: return field return None
def find_field(self, field=None, alias=None)
Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: :class:`Field <querybuilder.fields.Field>` or None
3.797073
4.928815
0.770383
super(SimpleTable, self).init_defaults() self.name = self.table
def init_defaults(self)
Sets the name of the table to the passed in table value
9.576739
5.221218
1.834197
super(ModelTable, self).init_defaults() self.model = self.table self.name = self.model._meta.db_table
def init_defaults(self)
Sets a model instance variable to the table value and sets the name to the table name as determined from the model class
5.909405
2.978211
1.984213
if self.extract_fields and field.name == '*': field.ignore = True fields = [model_field.column for model_field in self.model._meta.fields] self.add_fields(fields)
def before_add_field(self, field)
If extract_fields is set to True, then '*' fields will be removed and each individual field will read from the model meta data and added.
6.049628
3.959305
1.527952
super(QueryTable, self).init_defaults() self.query = self.table self.query.is_inner = True
def init_defaults(self)
Sets a query instance variable to the table value
10.350347
5.735678
1.804555
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file: # Run the command popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file) popen.wait() stderr_file.seek(0) stdout_file.seek(0) stderr = stderr_file.read...
def run_command(cmd_to_run)
Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run` to temporary files. Using the temporary files gets around subprocess.PIPE's issues with handling large buffers. Note: this command will block the python process until `cmd_to_run` has completed. Returns a tuple, containing th...
1.982304
1.909928
1.037895
logging.log(level, "%sname: %s", prefix, self.__name) logging.log(level, "%soptions: %s", prefix, self.__options)
def log(self, level, prefix = '')
Writes the contents of the Extension to the logging system.
4.003693
3.62599
1.104165
bits = [] for opt in sorted(self.__options): # handle the case where this is a negated option m = re.match(r'^! (.*)', opt) if m: bits.extend(['!', "--%s" % m.group(1)]) else: bits.append("--%s" % opt) ...
def specbits(self)
Returns the array of arguments that would be given to iptables for the current Extension.
3.214064
3.128606
1.027315
logging.log(level, "%sin interface: %s", prefix, self.in_interface) logging.log(level, "%sout interface: %s", prefix, self.out_interface) logging.log(level, "%ssource: %s", prefix, self.source) logging.log(level, "%sdestination: %s", prefix, self.destination) logging.log...
def log(self, level, prefix = '')
Writes the contents of the Rule to the logging system.
2.12674
2.028927
1.048209
def host_bits(opt, optval): # handle the case where this is a negated value m = re.match(r'^!\s*(.*)', optval) if m: return ['!', opt, m.group(1)] else: return [opt, optval] bits = [] if self.protocol: ...
def specbits(self)
Returns the array of arguments that would be given to iptables for the current Rule.
2.364025
2.158425
1.095254
chains = odict() for line in data.splitlines(True): m = re_chain.match(line) if m: policy = None if m.group(2) != '-': policy = m.group(2) chains[m.group(1)] = { 'policy': policy, 'packets': int(m.group(3)),...
def parse_chains(data)
Parse the chain definitions.
2.423029
2.350366
1.030916
rules = [] for line in data.splitlines(True): m = re_rule.match(line) if m and m.group(3) == chain: rule = parse_rule(m.group(4)) rule.packets = int(m.group(1)) rule.bytes = int(m.group(2)) rules.append(rule) return rules
def parse_rules(data, chain)
Parse the rules for the specified chain.
2.414811
2.235354
1.080281
self.__connection_string = conn_params.get('connection_string', '') conn = self.Database.connect(**conn_params) return conn
def _get_new_connection(self, conn_params)
Opens a connection to the database.
6.911978
5.763552
1.199257
from django.conf import settings settings_dict = self.settings_dict options = settings_dict.get('OPTIONS', {}) autocommit = options.get('autocommit', False) conn_params = { 'server': settings_dict['HOST'], 'database': settings_dict['NAME'], ...
def get_connection_params(self)
Returns a dict of parameters suitable for get_new_connection.
2.899888
2.85479
1.015797
cursor = self.connection.cursor() cursor.tzinfo_factory = self.tzinfo_factory return cursor
def create_cursor(self, name=None)
Creates a cursor. Assumes that a connection is established.
4.305677
4.214811
1.021559
major, minor, _, _ = self.get_server_version(make_connection=make_connection) return '{}.{}'.format(major, minor)
def __get_dbms_version(self, make_connection=True)
Returns the 'DBMS Version' string
3.420985
3.342773
1.023397
buffer = [] for table in self.__tables: buffer.extend(table.get_buffer()) return buffer
def get_buffer(self)
Get the change buffers.
5.831944
4.687316
1.244197
prog = args[0] if len(args) < 2: self.usage(prog) return 1 command = args[1] if command == "start": self.start() elif command == "stop": self.stop() elif command == "restart": self.stop() se...
def run(self, args)
Process command line arguments and run the given command command (start, stop, restart).
2.056811
1.819966
1.130137
self.clear() self.setDefaultPolicy() self.acceptIcmp() self.acceptInput('lo')
def start(self)
Start the firewall.
44.50795
20.137527
2.210199
args = ['-X'] if chainname: args.append(chainname) self.__run_iptables(args)
def delete_chain(self, chainname=None)
Attempts to delete the specified user-defined chain (all the chains in the table if none is given).
7.300465
6.096205
1.197543
args = ['-F'] if chainname: args.append(chainname) self.__run_iptables(args)
def flush_chain(self, chainname=None)
Flushes the specified chain (all the chains in the table if none is given). This is equivalent to deleting all the rules one by one.
7.274163
4.951346
1.469128
data = self.__run([self.__iptables_save, '-t', self.__name, '-c']) return netfilter.parser.parse_rules(data, chainname)
def list_rules(self, chainname)
Returns a list of Rules in the specified chain.
11.329708
11.505853
0.984691
while len(self.__buffer) > 0: self.__run(self.__buffer.pop(0))
def commit(self)
Commits any buffered commands. This is only useful if auto_commit is False.
5.696562
4.773367
1.193405
to_delete = [] to_delete.append(await self.bot.send_message(self.message.channel, 'What page do you want to go to?')) msg = await self.bot.wait_for_message(author=self.author, channel=self.message.channel, check=lambda m: m.content.isdigit()...
async def numbered_page(self)
lets you type a page number to go to
2.129637
2.024438
1.051964
e = discord.Embed() messages = ['Welcome to the interactive paginator!\n'] messages.append('This interactively allows you to see pages of text by navigating with ' \ 'reactions. They are as follows:\n') for (emoji, func) in self.reaction_emojis: ...
async def show_help(self)
shows this message
3.738992
3.698366
1.010985
await self.bot.delete_message(self.message) self.paginating = False
async def stop_pages(self)
stops the interactive pagination session
6.695246
4.355922
1.537044
await self.show_page(1, first=True) while self.paginating: react = await self.bot.wait_for_reaction(message=self.message, check=self.react_check, timeout=120.0) if react is None: self.paginating = False try: await self...
async def paginate(self)
Actually paginate the entries and run the interactive loop if necessary.
3.329013
3.059203
1.088196
data = self.bot.config.get("meta", {}) tosend = data.get('send_dms', True) data['send_dms'] = not tosend await self.bot.config.put('meta', data) await self.bot.responses.toggle(message="Forwarding of DMs to owner has been {status}.", success=data['send_dms'])
async def _senddms(self)
Toggles sending DMs to owner.
7.281842
5.763316
1.263481
await self.bot.responses.failure(message="Bot shutting down") await self.bot.logout()
async def _quit(self)
Quits the bot.
13.426966
11.567218
1.160777
data = self.bot.config.get("meta", {}) data['default_color'] = str(color) await self.bot.config.put('meta', data) await self.bot.responses.basic(message="The default color has been updated.")
async def _setcolor(self, *, color : discord.Colour)
Sets the default color of embeds.
5.510715
4.813387
1.144873
msg = copy.copy(ctx.message) msg.content = command for i in range(times): await self.bot.process_commands(msg)
async def _do(self, ctx, times: int, *, command)
Repeats a command a specified number of times.
2.91386
2.557119
1.139509