uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
3c023c1723a0c430b9766f30
train
function
def _is_literal(element): return not isinstance(element, Visitable) and \ not hasattr(element, '__clause_element__')
def _is_literal(element):
return not isinstance(element, Visitable) and \ not hasattr(element, '__clause_element__')
exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' " "function to indicate a SQL expression " "literal, or 'literal()' to indicate a " "bound value." % (element, )) else: return element def _is_literal(...
64
64
28
6
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_is_literal
_is_literal
4,333
4,335
4,333
4,333
5e7b6ad617bbbdf6367ab328e1bbe27327000c02
bigcode/the-stack
train
d475d5563fa0e6d4a4025de1
train
class
class CollectionAggregate(UnaryExpression): """Forms the basis for right-hand collection operator modifiers ANY and ALL. The ANY and ALL keywords are available in different ways on different backends. On PostgreSQL, they only work for an ARRAY type. On MySQL, they only work for subqueries. "...
class CollectionAggregate(UnaryExpression):
"""Forms the basis for right-hand collection operator modifiers ANY and ALL. The ANY and ALL keywords are available in different ways on different backends. On PostgreSQL, they only work for an ARRAY type. On MySQL, they only work for subqueries. """ @classmethod def _create_any(cls,...
(other.element, **kw) ) def _negate(self): if self.negate is not None: return UnaryExpression( self.element, operator=self.negate, negate=self.operator, modifier=self.modifier, type_=self.type, ...
189
189
631
7
181
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
CollectionAggregate
CollectionAggregate
2,854
2,936
2,854
2,854
162d806e4f19d4a1289773cfa84b1ec178bf9dc0
bigcode/the-stack
train
18bd0d565b2b639f35f71ddf
train
class
class Over(ColumnElement): """Represent an OVER clause. This is a special operator against a so-called "window" function, as well as any aggregate function, which produces results relative to the result set itself. It's supported only by certain database backends. """ __visit_name__ =...
class Over(ColumnElement):
"""Represent an OVER clause. This is a special operator against a so-called "window" function, as well as any aggregate function, which produces results relative to the result set itself. It's supported only by certain database backends. """ __visit_name__ = 'over' order_by = Non...
@util.memoized_property def _is_implicitly_boolean(self): return self.element._is_implicitly_boolean @property def _key_label(self): return self._label @property def _label(self): return getattr(self.element, '_label', None) or self.anon_label def _copy_internals...
256
256
1,361
5
251
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Over
Over
3,140
3,323
3,140
3,140
bab16af155a96ab4dfef4c081b545d45edb07fef
bigcode/the-stack
train
61de749c6dbd36f5189b8d84
train
function
def _cloned_difference(a, b): all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if not all_overlap.intersection(elem._cloned_set))
def _cloned_difference(a, b):
all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if not all_overlap.intersection(elem._cloned_set))
The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if all_overlap.intersection(elem._cloned_set)) def _cloned_difference(a, b):
64
64
49
9
55
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_cloned_difference
_cloned_difference
4,213
4,216
4,213
4,213
d080b7c6b9767c1be1b0db6ee264214f9090d8ea
bigcode/the-stack
train
341cb790ccb9b566e4266dd1
train
function
def _literal_as_text(element, warn=False): if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() elif isinstance(element, util.string_types): if warn: util.warn_limited( "Textual ...
def _literal_as_text(element, warn=False):
if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() elif isinstance(element, util.string_types): if warn: util.warn_limited( "Textual SQL expression %(expr)r should be " ...
, ColumnElement) and \ element._order_by_label_element is not None: return _label_reference(element) else: return _literal_as_text(element) def _expression_literal_as_text(element): return _literal_as_text(element, warn=True) def _literal_as_text(element, warn=False):
64
64
162
10
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_literal_as_text
_literal_as_text
4,299
4,318
4,299
4,299
9034bfc0ddf5bc095b89fcded6736bfa3f42f0d5
bigcode/the-stack
train
2193eaa73e6e07436424be3f
train
class
class TypeClause(ClauseElement): """Handle a type keyword in a SQL statement. Used by the ``Case`` statement. """ __visit_name__ = 'typeclause' def __init__(self, type): self.type = type
class TypeClause(ClauseElement):
"""Handle a type keyword in a SQL statement. Used by the ``Case`` statement. """ __visit_name__ = 'typeclause' def __init__(self, type): self.type = type
() d['callable'] = None d['value'] = v return d def __repr__(self): return 'BindParameter(%r, %r, type_=%r)' % (self.key, self.value, self.type) class TypeClause(ClauseElement):
64
64
55
7
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
TypeClause
TypeClause
1,212
1,222
1,212
1,212
9a9f5cde643626016ae764ee8b6d440618491b94
bigcode/the-stack
train
51c2a48b988ea31e34c79062
train
class
class Cast(ColumnElement): """Represent a ``CAST`` expression. :class:`.Cast` is produced using the :func:`.cast` factory function, as in:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ]) Det...
class Cast(ColumnElement):
"""Represent a ``CAST`` expression. :class:`.Cast` is produced using the :func:`.cast` factory function, as in:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ]) Details on :class:`.Cast` usag...
column` stores a string name that will be assumed to be part of a table and may be quoted as such, :func:`.literal_column` can be that, or any other arbitrary column-oriented expression. :param text: the text of the expression; can be any SQL expression. Quoting rules will not be applied. To spec...
198
198
661
5
193
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Cast
Cast
2,316
2,400
2,316
2,316
3599c2b0d19881b265fab383612a13bcac6e7bed
bigcode/the-stack
train
2274e5491c121c2efd6574be
train
class
class WithinGroup(ColumnElement): """Represent a WITHIN GROUP (ORDER BY) clause. This is a special operator against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including ``percentile_cont()``, ``rank()``, ``dense_rank()``, etc. It's supported only by certain d...
class WithinGroup(ColumnElement):
"""Represent a WITHIN GROUP (ORDER BY) clause. This is a special operator against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including ``percentile_cont()``, ``rank()``, ``dense_rank()``, etc. It's supported only by certain database backends, such as PostgreS...
`` element has been renamed to ``.element``. The two attributes are synonymous though ``.func`` is read-only. """ return self.element @util.memoized_property def type(self): return self.element.type def get_children(self, **kwargs): return [c for c i...
219
220
736
6
213
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
WithinGroup
WithinGroup
3,326
3,424
3,326
3,326
473306ac3403898be4947215af224fed1f8c003c
bigcode/the-stack
train
9c263550bf93790f548ff70e
train
class
class TypeCoerce(ColumnElement): """Represent a Python-side type-coercion wrapper. :class:`.TypeCoerce` supplies the :func:`.expression.type_coerce` function; see that function for usage details. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces a persistent :class:`.TypeCo...
class TypeCoerce(ColumnElement):
"""Represent a Python-side type-coercion wrapper. :class:`.TypeCoerce` supplies the :func:`.expression.type_coerce` function; see that function for usage details. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces a persistent :class:`.TypeCoerce` wrapper object rather than ...
not render the ``CAST`` expression in SQL. :param expression: A SQL expression, such as a :class:`.ColumnElement` expression or a Python string which will be coerced into a bound literal value. :param type_: A :class:`.TypeEngine` class or instance indicating the ty...
236
236
789
7
228
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
TypeCoerce
TypeCoerce
2,403
2,503
2,403
2,403
2e6c327612801d109fe9e9508b41592ed5a7bc60
bigcode/the-stack
train
cccfc85998d6c64734d72a95
train
class
class Tuple(ClauseList, ColumnElement): """Represent a SQL tuple.""" def __init__(self, *clauses, **kw): """Return a :class:`.Tuple`. Main usage is to produce a composite IN construct:: from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( ...
class Tuple(ClauseList, ColumnElement):
"""Represent a SQL tuple.""" def __init__(self, *clauses, **kw): """Return a :class:`.Tuple`. Main usage is to produce a composite IN construct:: from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] ...
@property def _select_iterable(self): return (self, ) def self_group(self, against=None): if not self.clauses: return self else: return super(BooleanClauseList, self).self_group(against=against) def _negate(self): return ClauseList._negate(self) a...
98
99
330
9
89
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Tuple
Tuple
2,033
2,074
2,033
2,033
bb7b351af3714ba39e4a22110b308f95e73e9384
bigcode/the-stack
train
c4128f596b16d95dcce83314
train
class
class _defer_none_name(_defer_name): """indicate a 'deferred' name that was ultimately the value None.""" __slots__ = ()
class _defer_none_name(_defer_name):
"""indicate a 'deferred' name that was ultimately the value None.""" __slots__ = ()
NONE_NAME elif isinstance(value, conv): return value else: return super(_defer_name, cls).__new__(cls, value) def __reduce__(self): return self.__class__, (util.text_type(self), ) class _defer_none_name(_defer_name):
64
64
34
11
53
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_defer_none_name
_defer_none_name
4,119
4,121
4,119
4,119
91f729b922b885325e1e70c79d64ca630b6a5d91
bigcode/the-stack
train
d0e5dd40f3c403453215d36c
train
class
class AnnotatedColumnElement(Annotated): def __init__(self, element, values): Annotated.__init__(self, element, values) ColumnElement.comparator._reset(self) for attr in ('name', 'key', 'table'): if self.__dict__.get(attr, False) is None: self.__dict__.pop(attr) ...
class AnnotatedColumnElement(Annotated):
def __init__(self, element, values): Annotated.__init__(self, element, values) ColumnElement.comparator._reset(self) for attr in ('name', 'key', 'table'): if self.__dict__.get(attr, False) is None: self.__dict__.pop(attr) def _with_annotations(self, values): ...
_embedded) if c is None: raise exc.InvalidRequestError( "Given column '%s', attached to table '%s', " "failed to locate a corresponding column from table '%s'" % (column, getattr(column, 'table', None), fromclause.description) ...
78
78
260
8
69
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
AnnotatedColumnElement
AnnotatedColumnElement
4,448
4,482
4,448
4,448
636f57aef2c9d32c81d01bca25199c6e834c8050
bigcode/the-stack
train
5ed7394a67559618a120d8d9
train
class
class Slice(ColumnElement): """Represent SQL for a Python array-slice object. This is not a specific SQL construct at this level, but may be interpreted by specific dialects, e.g. PostgreSQL. """ __visit_name__ = 'slice' def __init__(self, start, stop, step): self.start = start ...
class Slice(ColumnElement):
"""Represent SQL for a Python array-slice object. This is not a specific SQL construct at this level, but may be interpreted by specific dialects, e.g. PostgreSQL. """ __visit_name__ = 'slice' def __init__(self, start, stop, step): self.start = start self.stop = stop s...
): if self.negate is not None: return BinaryExpression( self.left, self.right, self.negate, negate=self.operator, type_=self.type, modifiers=self.modifiers) else: return super(BinaryEx...
64
64
118
5
59
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Slice
Slice
3,061
3,078
3,061
3,061
32f96ec3206b8b326143ba0d17bf578885aeb48b
bigcode/the-stack
train
c5e1fbacbc7c340ee9f12d61
train
function
def _find_columns(clause): """locate Column objects within the given expression.""" cols = util.column_set() traverse(clause, {}, {'column': cols.add}) return cols
def _find_columns(clause):
"""locate Column objects within the given expression.""" cols = util.column_set() traverse(clause, {}, {'column': cols.add}) return cols
') or \ isinstance(element, functions.FunctionElement): return element.label(None) else: return element def _is_column(col): """True if ``col`` is an instance of :class:`.ColumnElement`.""" return isinstance(col, ColumnElement) def _find_columns(clause):
64
64
41
7
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_find_columns
_find_columns
4,234
4,239
4,234
4,234
880aad0f78b0a9857f4c2860bdc95635889bb207
bigcode/the-stack
train
6ff21b58583dc61fd4d7c22b
train
function
def _const_expr(element): if isinstance(element, (Null, False_, True_)): return element elif element is None: return Null() elif element is False: return False_() elif element is True: return True_() else: raise exc.ArgumentError( "Expected None, F...
def _const_expr(element):
if isinstance(element, (Null, False_, True_)): return element elif element is None: return Null() elif element is False: return False_() elif element is True: return True_() else: raise exc.ArgumentError( "Expected None, False, or True" )
) " "for more specificity", { "column": util.ellipses_string(element), "literal_column": "literal_column" if guess_is_literal else "column" }) return ColumnClause( element, is_literal=guess_is_literal) def _const_exp...
64
64
76
6
58
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_const_expr
_const_expr
4,409
4,421
4,409
4,409
487be70b98cb39955e0682c5739f5f0f306c8589
bigcode/the-stack
train
392086da57aff5ae22df9f40
train
class
class quoted_name(util.MemoizedSlots, util.text_type): """Represent a SQL identifier combined with quoting preferences. :class:`.quoted_name` is a Python unicode/str subclass which represents a particular identifier name along with a ``quote`` flag. This ``quote`` flag, when set to ``True`` or ``F...
class quoted_name(util.MemoizedSlots, util.text_type):
"""Represent a SQL identifier combined with quoting preferences. :class:`.quoted_name` is a Python unicode/str subclass which represents a particular identifier name along with a ``quote`` flag. This ``quote`` flag, when set to ``True`` or ``False``, overrides automatic quoting behavior for th...
is None: c.key = self.key c._proxies = [self] if selectable._is_clone_of is not None: c._is_clone_of = \ selectable._is_clone_of.columns.get(c.key) if attach: selectable._columns[c.key] = c return c class CollationClause(ColumnEleme...
234
234
783
13
221
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
quoted_name
quoted_name
3,947
4,032
3,947
3,947
493585c294554399c3e58680530f23755498f9a6
bigcode/the-stack
train
0603ccb516b671ca24adca80
train
function
def _expression_literal_as_text(element): return _literal_as_text(element, warn=True)
def _expression_literal_as_text(element):
return _literal_as_text(element, warn=True)
(element, '__clause_element__'): element = element.__clause_element__() if isinstance(element, ColumnElement) and \ element._order_by_label_element is not None: return _label_reference(element) else: return _literal_as_text(element) def _expression_literal_as_text(element):
64
64
19
8
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_expression_literal_as_text
_expression_literal_as_text
4,295
4,296
4,295
4,295
4c308609bdeadfa1a7df5acf8aa49565ddb1d86a
bigcode/the-stack
train
61288a09515ec3212ea88af3
train
class
class SavepointClause(_IdentifiedClause): __visit_name__ = 'savepoint'
class SavepointClause(_IdentifiedClause):
__visit_name__ = 'savepoint'
class _IdentifiedClause(Executable, ClauseElement): __visit_name__ = 'identified' _execution_options = \ Executable._execution_options.union({'autocommit': False}) def __init__(self, ident): self.ident = ident class SavepointClause(_IdentifiedClause):
64
64
19
9
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
SavepointClause
SavepointClause
3,935
3,936
3,935
3,935
9ed38f8801639b04f42a771797acbc08a03c273e
bigcode/the-stack
train
a39bf44b546a88066edd8443
train
class
class _anonymous_label(_truncated_label): """A unicode subclass used to identify anonymously generated names.""" __slots__ = () def __add__(self, other): return _anonymous_label( quoted_name( util.text_type.__add__(self, util.text_type(other)), self....
class _anonymous_label(_truncated_label):
"""A unicode subclass used to identify anonymously generated names.""" __slots__ = () def __add__(self, other): return _anonymous_label( quoted_name( util.text_type.__add__(self, util.text_type(other)), self.quote) ) def __radd__(self, o...
slots__ = () _NONE_NAME = _defer_none_name("_unnamed_") # for backwards compatibility in case # someone is re-implementing the # _truncated_identifier() sequence in a custom # compiler _generated_label = _truncated_label class _anonymous_label(_truncated_label):
64
64
161
9
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_anonymous_label
_anonymous_label
4,132
4,158
4,132
4,132
2708d32fc09061a707ce18acbbb75ff89b3b720d
bigcode/the-stack
train
6b500bba1cfd60297c8eea17
train
class
class ColumnElement(operators.ColumnOperators, ClauseElement): """Represent a column-oriented SQL expression suitable for usage in the "columns" clause, WHERE clause etc. of a statement. While the most familiar kind of :class:`.ColumnElement` is the :class:`.Column` object, :class:`.ColumnElement` serv...
class ColumnElement(operators.ColumnOperators, ClauseElement):
"""Represent a column-oriented SQL expression suitable for usage in the "columns" clause, WHERE clause etc. of a statement. While the most familiar kind of :class:`.ColumnElement` is the :class:`.Column` object, :class:`.ColumnElement` serves as the basis for any unit that may be present in a SQL e...
to be at the :class:`.ColumnElement`. level """ return and_(self, other) def __or__(self, other): """'or' at the ClauseElement level. .. deprecated:: 0.9.5 - conjunctions are intended to be at the :class:`.ColumnElement`. level """ return or...
256
256
2,992
11
245
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
ColumnElement
ColumnElement
500
842
500
500
9ee3e6563d5453faa671de1b61be87332cdbe135
bigcode/the-stack
train
aad3a39c2e9f345622b4c4c2
train
function
def literal(value, type_=None): r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`.ColumnElement` subclass, such as a :cla...
def literal(value, type_=None):
r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`.ColumnElement` subclass, such as a :class:`~sqlalchemy.schema.Column` o...
syntax. .. versionadded:: 0.9.5 .. seealso:: :meth:`.ColumnElement.between` """ expr = _literal_as_binds(expr) return expr.between(lower_bound, upper_bound, symmetric=symmetric) def literal(value, type_=None):
64
64
203
8
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
literal
literal
113
130
113
113
54149801f278cd138b5a0fed05f7782ee24436af
bigcode/the-stack
train
0560e6517ea16e8edb169488
train
class
class Grouping(ColumnElement): """Represent a grouping within a column expression""" __visit_name__ = 'grouping' def __init__(self, element): self.element = element self.type = getattr(element, 'type', type_api.NULLTYPE) def self_group(self, against=None): return self @ut...
class Grouping(ColumnElement):
"""Represent a grouping within a column expression""" __visit_name__ = 'grouping' def __init__(self, element): self.element = element self.type = getattr(element, 'type', type_api.NULLTYPE) def self_group(self, against=None): return self @util.memoized_property def _i...
start, stop, step): self.start = start self.stop = stop self.step = step self.type = type_api.NULLTYPE def self_group(self, against=None): assert against is operator.getitem return self class IndexExpression(BinaryExpression): """Represent the class of express...
87
87
291
6
80
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Grouping
Grouping
3,087
3,133
3,087
3,087
2e847d41db8a4c1ff7e431c86c170520b99b92fa
bigcode/the-stack
train
e6f624e87a3efe90fd06ca2b
train
class
class Case(ColumnElement): """Represent a ``CASE`` expression. :class:`.Case` is produced using the :func:`.case` factory function, as in:: from sqlalchemy import case stmt = select([users_table]).\ where( case( [ ...
class Case(ColumnElement):
"""Represent a ``CASE`` expression. :class:`.Case` is produced using the :func:`.case` factory function, as in:: from sqlalchemy import case stmt = select([users_table]).\ where( case( [ ...
), (5, 12), (10, 19)] ) .. warning:: The composite IN construct is not supported by all backends, and is currently known to work on PostgreSQL and MySQL, but not SQLite. Unsupported backends will raise a subclass of :class:`~sqlalchemy.exc.DBAPIErr...
256
256
1,495
5
251
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Case
Case
2,077
2,280
2,077
2,077
db3f90f3a4a432fc08459d6029c7e0f26c9212a0
bigcode/the-stack
train
ee2ac26eefec09dd660d2ca0
train
function
def _string_or_unprintable(element): if isinstance(element, util.string_types): return element else: try: return str(element) except Exception: return "unprintable element %r" % element
def _string_or_unprintable(element):
if isinstance(element, util.string_types): return element else: try: return str(element) except Exception: return "unprintable element %r" % element
`. Existing :class:`._truncated_label` and :class:`._anonymous_label` objects are passed unchanged. """ if isinstance(value, _truncated_label): return value else: return _truncated_label(value) def _string_or_unprintable(element):
64
64
50
9
55
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_string_or_unprintable
_string_or_unprintable
4,175
4,182
4,175
4,175
1824ba6d0a7caa11ce4a007aea4d9a85bded94c6
bigcode/the-stack
train
351f1c935e189af5a40ad738
train
class
class BindParameter(ColumnElement): r"""Represent a "bound expression". :class:`.BindParameter` is invoked explicitly using the :func:`.bindparam` function, as in:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('u...
class BindParameter(ColumnElement):
r"""Represent a "bound expression". :class:`.BindParameter` is invoked explicitly using the :func:`.bindparam` function, as in:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username')) Detailed discussion ...
0.7 """ return Cast(self, type_) def label(self, name): """Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`~.expression.label` function. if 'name' is None, an anonymous label name will be generated. """ return Lab...
256
256
3,025
6
250
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
BindParameter
BindParameter
845
1,209
845
845
6d87ad7f080a16a322190b0fc10c4cc6d53e9e13
bigcode/the-stack
train
f8a7684ab8f6611d710f0f9c
train
function
def _is_column(col): """True if ``col`` is an instance of :class:`.ColumnElement`.""" return isinstance(col, ColumnElement)
def _is_column(col):
"""True if ``col`` is an instance of :class:`.ColumnElement`.""" return isinstance(col, ColumnElement)
.intersection(elem._cloned_set)) @util.dependencies("sqlalchemy.sql.functions") def _labeled(functions, element): if not hasattr(element, 'name') or \ isinstance(element, functions.FunctionElement): return element.label(None) else: return element def _is_column(col):
64
64
33
6
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_is_column
_is_column
4,228
4,231
4,228
4,228
242397d53d53ae95b19c92fea164e16e8e7bf9f1
bigcode/the-stack
train
28a4e6eb121a770ce9d7c9d4
train
function
def _corresponding_column_or_error(fromclause, column, require_embedded=False): c = fromclause.corresponding_column(column, require_embedded=require_embedded) if c is None: raise exc.InvalidRequestError( "Given column...
def _corresponding_column_or_error(fromclause, column, require_embedded=False):
c = fromclause.corresponding_column(column, require_embedded=require_embedded) if c is None: raise exc.InvalidRequestError( "Given column '%s', attached to table '%s', " "failed to locate a corresponding column from table '%s'" ...
False, or True" ) def _type_from_args(args): for a in args: if not a.type._isnull: return a.type else: return type_api.NULLTYPE def _corresponding_column_or_error(fromclause, column, require_embedded=False):
64
64
107
20
43
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_corresponding_column_or_error
_corresponding_column_or_error
4,432
4,445
4,432
4,433
ab52141bce60ddf736be4b4b77c26edea5350002
bigcode/the-stack
train
33f35c0d464b551edcb74f3c
train
class
class _label_reference(ColumnElement): """Wrap a column expression as it appears in a 'reference' context. This expression is any that includes an _order_by_label_element, which is a Label, or a DESC / ASC construct wrapping a Label. The production of _label_reference() should occur when an expression...
class _label_reference(ColumnElement):
"""Wrap a column expression as it appears in a 'reference' context. This expression is any that includes an _order_by_label_element, which is a Label, or a DESC / ASC construct wrapping a Label. The production of _label_reference() should occur when an expression is added to this context; this inc...
_copy_internals(self, clone=_clone, **kw): self.expr = clone(self.expr, **kw) def get_children(self, **kwargs): return self.expr, @property def _from_objects(self): return self.expr._from_objects class _label_reference(ColumnElement):
64
64
176
7
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_label_reference
_label_reference
2,534
2,556
2,534
2,534
58c6a9b121f9075a2334d99df7b11fccd9a5c178
bigcode/the-stack
train
b0fc3e6322510429afb977c7
train
function
def not_(clause): """Return a negation of the given clause, i.e. ``NOT(clause)``. The ``~`` operator is also overloaded on all :class:`.ColumnElement` subclasses to produce the same result. """ return operators.inv(_literal_as_binds(clause))
def not_(clause):
"""Return a negation of the given clause, i.e. ``NOT(clause)``. The ``~`` operator is also overloaded on all :class:`.ColumnElement` subclasses to produce the same result. """ return operators.inv(_literal_as_binds(clause))
available from the :class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters`` attribute, which returns a dictionary containing the values. """ return BindParameter( key, None, type_=type_, unique=False, isoutparam=True) def not_(clause):
64
64
69
6
58
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
not_
not_
149
157
149
149
996890cecfdaa7d6e96502e6a1f2235eaba6e403
bigcode/the-stack
train
192ce81640472f047584d5c7
train
function
def between(expr, lower_bound, upper_bound, symmetric=False): """Produce a ``BETWEEN`` predicate clause. E.g.:: from sqlalchemy import between stmt = select([users_table]).where(between(users_table.c.id, 5, 7)) Would produce SQL resembling:: SELECT id, name FROM user WHERE id BET...
def between(expr, lower_bound, upper_bound, symmetric=False):
"""Produce a ``BETWEEN`` predicate clause. E.g.:: from sqlalchemy import between stmt = select([users_table]).where(between(users_table.c.id, 5, 7)) Would produce SQL resembling:: SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2 The :func:`.between` function is a s...
``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters. .. versionchanged:: 1.2 quoting is automatically applied to COLLATE expressions...
129
129
431
13
116
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
between
between
59
110
59
59
cfa7ec884c0f59e5efc673f2db41e7d081be6ba0
bigcode/the-stack
train
aafc4cddc7ed20f73684c6b8
train
function
def _column_as_key(element): if isinstance(element, util.string_types): return element if hasattr(element, '__clause_element__'): element = element.__clause_element__() try: return element.key except AttributeError: return None
def _column_as_key(element):
if isinstance(element, util.string_types): return element if hasattr(element, '__clause_element__'): element = element.__clause_element__() try: return element.key except AttributeError: return None
column-based functions are more performance critical # and are fine just checking for __clause_element__(). It is only # _interpret_as_from() where we'd like to be able to receive ORM entities # that have no defined namespace, hence inspect() is needed there. def _column_as_key(element):
64
64
57
7
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_column_as_key
_column_as_key
4,253
4,261
4,253
4,253
51d5a92f3b8adbcf114acab12256243e1a84d545
bigcode/the-stack
train
f4fa5da3663bc129d59fd89c
train
class
class ClauseList(ClauseElement): """Describe a list of clauses, separated by an operator. By default, is comma-separated, such as a column listing. """ __visit_name__ = 'clauselist' def __init__(self, *clauses, **kwargs): self.operator = kwargs.pop('operator', operators.comma_op) ...
class ClauseList(ClauseElement):
"""Describe a list of clauses, separated by an operator. By default, is comma-separated, such as a column listing. """ __visit_name__ = 'clauselist' def __init__(self, *clauses, **kwargs): self.operator = kwargs.pop('operator', operators.comma_op) self.group = kwargs.pop('group', ...
= 1 The :func:`.true` and :func:`.false` constants also feature "short circuit" operation within an :func:`.and_` or :func:`.or_` conjunction:: >>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).whe...
192
193
644
7
185
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
ClauseList
ClauseList
1,813
1,897
1,813
1,813
d9c62ad8c6beed386a58091e048e400ed2d3780c
bigcode/the-stack
train
778f3fc842331ff579f6af10
train
class
class BooleanClauseList(ClauseList, ColumnElement): __visit_name__ = 'clauselist' def __init__(self, *arg, **kw): raise NotImplementedError( "BooleanClauseList has a private constructor") @classmethod def _construct(cls, operator, continue_on, skip_on, *clauses, **kw): conv...
class BooleanClauseList(ClauseList, ColumnElement):
__visit_name__ = 'clauselist' def __init__(self, *arg, **kw): raise NotImplementedError( "BooleanClauseList has a private constructor") @classmethod def _construct(cls, operator, continue_on, skip_on, *clauses, **kw): convert_clauses = [] clauses = [ _e...
: return self def compare(self, other, **kw): """Compare this :class:`.ClauseList` to the given :class:`.ClauseList`, including a comparison of all the clause items. """ if not isinstance(other, ClauseList) and len(self.clauses) == 1: return self.clauses[0]....
255
255
852
11
243
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
BooleanClauseList
BooleanClauseList
1,900
2,026
1,900
1,900
058a2c51a4c4ea6725bffa2432b3658f20eae2b6
bigcode/the-stack
train
cd4e9a69ad59bcb2c9dca55a
train
class
class conv(_truncated_label): """Mark a string indicating that a name has already been converted by a naming convention. This is a string subclass that indicates a name that should not be subject to any further naming conventions. E.g. when we create a :class:`.Constraint` using a naming conventio...
class conv(_truncated_label):
"""Mark a string indicating that a name has already been converted by a naming convention. This is a string subclass that indicates a name that should not be subject to any further naming conventions. E.g. when we create a :class:`.Constraint` using a naming convention as follows:: m ...
identify symbolic " "names that may require truncation.""" __slots__ = () def __new__(cls, value, quote=None): quote = getattr(value, "quote", quote) # return super(_truncated_label, cls).__new__(cls, value, quote, True) return super(_truncated_label, cls).__new__(cls, value, quot...
122
122
408
7
114
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
conv
conv
4,053
4,097
4,053
4,053
39f596bbe18285d521c99081d665de5199a27e4e
bigcode/the-stack
train
98b5f6f0f601558d583e3930
train
function
def _literal_and_labels_as_label_reference(element): if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() if isinstance(element, ColumnElement) and \ element._orde...
def _literal_and_labels_as_label_reference(element):
if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() if isinstance(element, ColumnElement) and \ element._order_by_label_element is not None: return _label...
def _literal_as_label_reference(element): if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() return _literal_as_text(element) def _literal_and_labels_as_label_reference(elem...
64
64
87
10
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_literal_and_labels_as_label_reference
_literal_and_labels_as_label_reference
4,281
4,292
4,281
4,281
2bdb4232b8bfe397a08232585be3ac24cff0005b
bigcode/the-stack
train
05fe9feb05937d5a9085975f
train
class
class _textual_label_reference(ColumnElement): __visit_name__ = 'textual_label_reference' def __init__(self, element): self.element = element @util.memoized_property def _text_clause(self): return TextClause._create_text(self.element)
class _textual_label_reference(ColumnElement):
__visit_name__ = 'textual_label_reference' def __init__(self, element): self.element = element @util.memoized_property def _text_clause(self): return TextClause._create_text(self.element)
def __init__(self, element): self.element = element def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) @property def _from_objects(self): return () class _textual_label_reference(ColumnElement):
63
64
60
9
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_textual_label_reference
_textual_label_reference
2,559
2,567
2,559
2,559
a0ac4863b18b47ac6b663375ec91ceb459dfcf3d
bigcode/the-stack
train
a4283644508ce05e6ddcbcad
train
function
def _cloned_intersection(a, b): """return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in ...
def _cloned_intersection(a, b):
"""return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if all_overlap....
(*[x._cloned_set for x in elements]) def _select_iterables(elements): """expand tables into individual columns in the given list of column expressions. """ return itertools.chain(*[c._select_iterable for c in elements]) def _cloned_intersection(a, b):
64
64
89
10
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_cloned_intersection
_cloned_intersection
4,201
4,210
4,201
4,201
a75d8f820df3a1621f7634cadf71085b030b9ad5
bigcode/the-stack
train
2df1a649254aa5f1aaa40087
train
class
class ColumnClause(Immutable, ColumnElement): """Represents a column expression from any textual string. The :class:`.ColumnClause`, a lightweight analogue to the :class:`.Column` class, is typically invoked using the :func:`.column` function, as in:: from sqlalchemy import column id,...
class ColumnClause(Immutable, ColumnElement):
"""Represents a column expression from any textual string. The :class:`.ColumnClause`, a lightweight analogue to the :class:`.Column` class, is typically invoked using the :func:`.column` function, as in:: from sqlalchemy import column id, name = column("id"), column("name") s...
def primary_key(self): return self.element.primary_key @property def foreign_keys(self): return self.element.foreign_keys def get_children(self, **kwargs): return self.element, def _copy_internals(self, clone=_clone, anonymize_labels=False, **kw): self._element = clon...
256
256
1,943
9
246
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
ColumnClause
ColumnClause
3,663
3,915
3,663
3,663
553c57c8c473ffcc7305c2aef21e7e42ce687abd
bigcode/the-stack
train
0ca2e223d7ccd218c9cb24cd
train
function
def _no_literals(element): if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): raise exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' " "function to indicate a SQL expression " ...
def _no_literals(element):
if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): raise exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' " "function to indicate a SQL expression " "li...
.text_type(element)) elif isinstance(element, (util.NoneType, bool)): return _const_expr(element) else: raise exc.ArgumentError( "SQL expression object or string expected, got object of type %r " "instead" % type(element) ) def _no_literals(element):
64
64
94
6
58
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_no_literals
_no_literals
4,321
4,330
4,321
4,321
7a92a40599295393888ac9b48d333cfe9542f9cc
bigcode/the-stack
train
241794e6a1c766e757fff847
train
class
class Null(ColumnElement): """Represent the NULL keyword in a SQL statement. :class:`.Null` is accessed as a constant via the :func:`.null` function. """ __visit_name__ = 'null' @util.memoized_property def type(self): return type_api.NULLTYPE @classmethod def _instance(c...
class Null(ColumnElement):
"""Represent the NULL keyword in a SQL statement. :class:`.Null` is accessed as a constant via the :func:`.null` function. """ __visit_name__ = 'null' @util.memoized_property def type(self): return type_api.NULLTYPE @classmethod def _instance(cls): """Return a co...
b.key, clone(b, **kw)) for b in self._bindparams.values()) def get_children(self, **kwargs): return list(self._bindparams.values()) def compare(self, other): return isinstance(other, TextClause) and other.text == self.text class Null(ColumnElement):
64
64
111
5
58
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Null
Null
1,664
1,685
1,664
1,664
ea337f4019833079389493a25c2f4de5f2b53966
bigcode/the-stack
train
c719763c6265e67c8c014320
train
function
def literal_column(text, type_=None): r"""Produce a :class:`.ColumnClause` object that has the :paramref:`.column.is_literal` flag set to True. :func:`.literal_column` is similar to :func:`.column`, except that it is more often used as a "standalone" column expression that renders exactly as stated...
def literal_column(text, type_=None):
r"""Produce a :class:`.ColumnClause` object that has the :paramref:`.column.is_literal` flag set to True. :func:`.literal_column` is similar to :func:`.column`, except that it is more often used as a "standalone" column expression that renders exactly as stated; while :func:`.column` stores a strin...
None: yield self.value for x, y in self.whens: yield x yield y if self.else_ is not None: yield self.else_ @property def _from_objects(self): return list(itertools.chain(*[x._from_objects for x in sel...
83
84
280
9
74
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
literal_column
literal_column
2,283
2,313
2,283
2,283
983b614f19c2074867b4929cddc9494703cfa631
bigcode/the-stack
train
1928e5f3d42b2d0ca0cc5959
train
function
def _interpret_as_column_or_from(element): if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, (util.NoneType...
def _interpret_as_column_or_from(element):
if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, (util.NoneType, bool)): return _const_expr(el...
_=None): if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): if element is None: return Null() else: return BindParameter(name, element, type_=type_, unique=True) else: return element ...
93
93
311
9
84
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_interpret_as_column_or_from
_interpret_as_column_or_from
4,369
4,406
4,369
4,369
ddb41f12eed22c06f711666ba334e8e9aa72961b
bigcode/the-stack
train
941df2006f7ccae52530c83f
train
class
class CollationClause(ColumnElement): __visit_name__ = "collation" def __init__(self, collation): self.collation = collation
class CollationClause(ColumnElement):
__visit_name__ = "collation" def __init__(self, collation): self.collation = collation
c._proxies = [self] if selectable._is_clone_of is not None: c._is_clone_of = \ selectable._is_clone_of.columns.get(c.key) if attach: selectable._columns[c.key] = c return c class CollationClause(ColumnElement):
64
64
35
7
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
CollationClause
CollationClause
3,918
3,922
3,918
3,918
bb9a5bb92a6aba512eb670e4647b8927b7b0551b
bigcode/the-stack
train
0d8a62933680ba591405e538
train
function
def _as_truncated(value): """coerce the given value to :class:`._truncated_label`. Existing :class:`._truncated_label` and :class:`._anonymous_label` objects are passed unchanged. """ if isinstance(value, _truncated_label): return value else: return _truncated_label(value)
def _as_truncated(value):
"""coerce the given value to :class:`._truncated_label`. Existing :class:`._truncated_label` and :class:`._anonymous_label` objects are passed unchanged. """ if isinstance(value, _truncated_label): return value else: return _truncated_label(value)
) ) def apply_map(self, map_): if self.quote is not None: # preserve quoting only if necessary return quoted_name(self % map_, self.quote) else: # else skip the constructor call return self % map_ def _as_truncated(value):
63
64
77
7
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_as_truncated
_as_truncated
4,161
4,172
4,161
4,161
b49b1e100c05dae5e1d7a8db4fb71d89339bd724
bigcode/the-stack
train
0511912a0fbff8bf1635b00f
train
function
def _select_iterables(elements): """expand tables into individual columns in the given list of column expressions. """ return itertools.chain(*[c._select_iterable for c in elements])
def _select_iterables(elements):
"""expand tables into individual columns in the given list of column expressions. """ return itertools.chain(*[c._select_iterable for c in elements])
unprintable element %r" % element def _expand_cloned(elements): """expand the given set of ClauseElements to be the set of all 'cloned' predecessors. """ return itertools.chain(*[x._cloned_set for x in elements]) def _select_iterables(elements):
64
64
42
7
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_select_iterables
_select_iterables
4,193
4,198
4,193
4,193
791c034e9e0ed69258550a27ba0056d25f8c3c90
bigcode/the-stack
train
44201cf42c694017fbfb07fa
train
function
def _literal_as_binds(element, name=None, type_=None): if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): if element is None: return Null() else: return BindParameter(name, element, type_=type_, ...
def _literal_as_binds(element, name=None, type_=None):
if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): if element is None: return Null() else: return BindParameter(name, element, type_=type_, unique=True) else: return element
isinstance(element, ColumnElement): raise exc.ArgumentError( "Column-based expression object expected for argument " "'%s'; got: '%s', type %s" % (name, element, type(element))) return element def _literal_as_binds(element, name=None, type_=None):
64
64
78
15
48
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_literal_as_binds
_literal_as_binds
4,355
4,364
4,355
4,355
47f14df39372d63dc207db7579f1d1bfaf5f9f3c
bigcode/the-stack
train
e642c8053837048b06dc425b
train
function
def _clause_element_as_expr(element): if hasattr(element, '__clause_element__'): return element.__clause_element__() else: return element
def _clause_element_as_expr(element):
if hasattr(element, '__clause_element__'): return element.__clause_element__() else: return element
column_as_key(element): if isinstance(element, util.string_types): return element if hasattr(element, '__clause_element__'): element = element.__clause_element__() try: return element.key except AttributeError: return None def _clause_element_as_expr(element):
64
64
35
9
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_clause_element_as_expr
_clause_element_as_expr
4,264
4,268
4,264
4,264
2a97a37db17ac18108c9a1f0915ff9c51d751e38
bigcode/the-stack
train
8baa6a771285714a5a04d3df
train
class
class _truncated_label(quoted_name): """A unicode subclass used to identify symbolic " "names that may require truncation.""" __slots__ = () def __new__(cls, value, quote=None): quote = getattr(value, "quote", quote) # return super(_truncated_label, cls).__new__(cls, value, quote, True...
class _truncated_label(quoted_name):
"""A unicode subclass used to identify symbolic " "names that may require truncation.""" __slots__ = () def __new__(cls, value, quote=None): quote = getattr(value, "quote", quote) # return super(_truncated_label, cls).__new__(cls, value, quote, True) return super(_truncated_lab...
upper() def __repr__(self): backslashed = self.encode('ascii', 'backslashreplace') if not util.py2k: backslashed = backslashed.decode('ascii') return "'%s'" % backslashed class _truncated_label(quoted_name):
64
64
131
9
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_truncated_label
_truncated_label
4,035
4,050
4,035
4,035
872f6eb77371ea0d3d1b7eb12cb07af5029bfb40
bigcode/the-stack
train
f74844c3401e04d20d7d1d99
train
class
class TextClause(Executable, ClauseElement): """Represent a literal SQL text fragment. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The :class:`.Text` construct is produced using the :func:`.text` function; see that functi...
class TextClause(Executable, ClauseElement):
"""Represent a literal SQL text fragment. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The :class:`.Text` construct is produced using the :func:`.text` function; see that function for full documentation. .. seealso:: ...
( '%%(%d %s)s' % (id(self), self._orig_key or 'param')) def compare(self, other, **kw): """Compare this :class:`BindParameter` to the given clause.""" return isinstance(other, BindParameter) \ and self.type._compare_type_affinity(other.type) \ and se...
256
256
3,622
9
246
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
TextClause
TextClause
1,225
1,661
1,225
1,225
1f0d5057229694ab85740b351d20416c2a248017
bigcode/the-stack
train
2c9937bf93a1075b1d5e017e
train
function
@util.dependencies("sqlalchemy.sql.functions") def _labeled(functions, element): if not hasattr(element, 'name') or \ isinstance(element, functions.FunctionElement): return element.label(None) else: return element
@util.dependencies("sqlalchemy.sql.functions") def _labeled(functions, element):
if not hasattr(element, 'name') or \ isinstance(element, functions.FunctionElement): return element.label(None) else: return element
oned_difference(a, b): all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if not all_overlap.intersection(elem._cloned_set)) @util.dependencies("sqlalchemy.sql.functions") def _labeled(functions, element):
64
64
50
18
46
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_labeled
_labeled
4,219
4,225
4,219
4,220
a15237aafe08c0f6539b48460f54bb3e1d4385c6
bigcode/the-stack
train
f3fc62fb58a360d2edef5af5
train
function
def _only_column_elements(element, name): if hasattr(element, '__clause_element__'): element = element.__clause_element__() if not isinstance(element, ColumnElement): raise exc.ArgumentError( "Column-based expression object expected for argument " "'%s'; got: '%s', type %...
def _only_column_elements(element, name):
if hasattr(element, '__clause_element__'): element = element.__clause_element__() if not isinstance(element, ColumnElement): raise exc.ArgumentError( "Column-based expression object expected for argument " "'%s'; got: '%s', type %s" % (name, element, type(element))) r...
return not isinstance(element, Visitable) and \ not hasattr(element, '__clause_element__') def _only_column_elements_or_none(element, name): if element is None: return None else: return _only_column_elements(element, name) def _only_column_elements(element, name):
64
64
81
9
55
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_only_column_elements
_only_column_elements
4,345
4,352
4,345
4,345
3674ebbb4b5ba683c9751df9ad81f9c0a9abe690
bigcode/the-stack
train
da3dbbea4ed718cc7e51fbda
train
class
class Extract(ColumnElement): """Represent a SQL EXTRACT clause, ``extract(field FROM expr)``.""" __visit_name__ = 'extract' def __init__(self, field, expr, **kwargs): """Return a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extrac...
class Extract(ColumnElement):
"""Represent a SQL EXTRACT clause, ``extract(field FROM expr)``.""" __visit_name__ = 'extract' def __init__(self, field, expr, **kwargs): """Return a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.f...
self.clause._from_objects @util.memoized_property def typed_expression(self): if isinstance(self.clause, BindParameter): bp = self.clause._clone() bp.type = self.type return bp else: return self.clause class Extract(ColumnElement):
64
64
181
5
58
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Extract
Extract
2,506
2,531
2,506
2,506
4fcbf45c8636adf3ea7f0f87374067a8dd4b6a58
bigcode/the-stack
train
1b6ef2b8d27f2556b81a28b4
train
function
def _expand_cloned(elements): """expand the given set of ClauseElements to be the set of all 'cloned' predecessors. """ return itertools.chain(*[x._cloned_set for x in elements])
def _expand_cloned(elements):
"""expand the given set of ClauseElements to be the set of all 'cloned' predecessors. """ return itertools.chain(*[x._cloned_set for x in elements])
return _truncated_label(value) def _string_or_unprintable(element): if isinstance(element, util.string_types): return element else: try: return str(element) except Exception: return "unprintable element %r" % element def _expand_cloned(elements):
64
64
47
7
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_expand_cloned
_expand_cloned
4,185
4,190
4,185
4,185
5fad85a4cbee62dae63a6e39592c325206d7fb6b
bigcode/the-stack
train
18ca847ddd5014889a8fa3ac
train
class
class ReleaseSavepointClause(_IdentifiedClause): __visit_name__ = 'release_savepoint'
class ReleaseSavepointClause(_IdentifiedClause):
__visit_name__ = 'release_savepoint'
__(self, ident): self.ident = ident class SavepointClause(_IdentifiedClause): __visit_name__ = 'savepoint' class RollbackToSavepointClause(_IdentifiedClause): __visit_name__ = 'rollback_to_savepoint' class ReleaseSavepointClause(_IdentifiedClause):
64
64
21
10
54
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
ReleaseSavepointClause
ReleaseSavepointClause
3,943
3,944
3,943
3,943
cac15395c6e88bf2173b6938b1b6ab17164fee7f
bigcode/the-stack
train
6f8e87b79e0b6c1ed8dbb23f
train
function
def _only_column_elements_or_none(element, name): if element is None: return None else: return _only_column_elements(element, name)
def _only_column_elements_or_none(element, name):
if element is None: return None else: return _only_column_elements(element, name)
'literal()' to indicate a " "bound value." % (element, )) else: return element def _is_literal(element): return not isinstance(element, Visitable) and \ not hasattr(element, '__clause_element__') def _only_column_elements_or_none(element, name):
64
64
34
11
53
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_only_column_elements_or_none
_only_column_elements_or_none
4,338
4,342
4,338
4,338
59a00e11eb9a5fa97e6c394ff34e0413b661b356
bigcode/the-stack
train
beafafc2fde8c1dc759397ab
train
function
def _literal_as_label_reference(element): if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() return _literal_as_text(element)
def _literal_as_label_reference(element):
if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() return _literal_as_text(element)
clause_element__() try: return element.key except AttributeError: return None def _clause_element_as_expr(element): if hasattr(element, '__clause_element__'): return element.__clause_element__() else: return element def _literal_as_label_reference(element):
64
64
54
8
55
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_literal_as_label_reference
_literal_as_label_reference
4,271
4,278
4,271
4,271
11e58671c68d91cb57a46e4afddddfdf7192cb6d
bigcode/the-stack
train
4d233e92519d6a5451e7ef37
train
class
class Label(ColumnElement): """Represents a column label (AS). Represent a label, as typically applied to any column-level element using the ``AS`` sql keyword. """ __visit_name__ = 'label' def __init__(self, name, element, type_=None): """Return a :class:`Label` object for the ...
class Label(ColumnElement):
"""Represents a column label (AS). Represent a label, as typically applied to any column-level element using the ``AS`` sql keyword. """ __visit_name__ = 'label' def __init__(self, name, element, type_=None): """Return a :class:`Label` object for the given :class:`.ColumnElem...
filter(MyClass.y > 5).over(order_by='x') is shorthand for:: from sqlalchemy import over, funcfilter over(funcfilter(func.rank(), MyClass.y > 5), order_by='x') See :func:`~.expression.over` for a full description. """ return Over( self, partition_by...
241
242
808
5
236
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
Label
Label
3,543
3,660
3,543
3,543
fdd4cf2e381c892ac962281fe96bded6f55ac46b
bigcode/the-stack
train
246697614d8f007d69ed3388
train
class
class _IdentifiedClause(Executable, ClauseElement): __visit_name__ = 'identified' _execution_options = \ Executable._execution_options.union({'autocommit': False}) def __init__(self, ident): self.ident = ident
class _IdentifiedClause(Executable, ClauseElement):
__visit_name__ = 'identified' _execution_options = \ Executable._execution_options.union({'autocommit': False}) def __init__(self, ident): self.ident = ident
if attach: selectable._columns[c.key] = c return c class CollationClause(ColumnElement): __visit_name__ = "collation" def __init__(self, collation): self.collation = collation class _IdentifiedClause(Executable, ClauseElement):
64
64
55
11
52
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_IdentifiedClause
_IdentifiedClause
3,925
3,932
3,925
3,926
3dac0e770b773871f32f64e195fd886c66e05691
bigcode/the-stack
train
ae054114abcfad01f72b12b2
train
class
class IndexExpression(BinaryExpression): """Represent the class of expressions that are like an "index" operation. """ pass
class IndexExpression(BinaryExpression):
"""Represent the class of expressions that are like an "index" operation. """ pass
init__(self, start, stop, step): self.start = start self.stop = stop self.step = step self.type = type_api.NULLTYPE def self_group(self, against=None): assert against is operator.getitem return self class IndexExpression(BinaryExpression):
64
64
27
6
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
IndexExpression
IndexExpression
3,081
3,084
3,081
3,081
ab6b45d5291f06e036a50ad9ec17312c3ecc5c76
bigcode/the-stack
train
7f48a755b38b78ea6a972b60
train
function
def collate(expression, collation): """Return the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters. ...
def collate(expression, collation):
"""Return the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters. .. versionchanged:: 1.2 quoting...
Annotated import itertools from .base import Executable, PARSE_AUTOCOMMIT, Immutable, NO_ARG from .base import _generative import numbers import re import operator def _clone(element, **kw): return element._clone() def collate(expression, collation):
64
64
135
8
56
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
collate
collate
33
56
33
33
a2ca38911a648eec868c1a1ddbf3ed9321563ffc
bigcode/the-stack
train
826ea5cd63f39141d4195b23
train
class
class _defer_name(_truncated_label): """mark a name as 'deferred' for the purposes of automated name generation. """ __slots__ = () def __new__(cls, value): if value is None: return _NONE_NAME elif isinstance(value, conv): return value else: ...
class _defer_name(_truncated_label):
"""mark a name as 'deferred' for the purposes of automated name generation. """ __slots__ = () def __new__(cls, value): if value is None: return _NONE_NAME elif isinstance(value, conv): return value else: return super(_defer_name, cls).__...
5"`` and not ``"ck_t_ck_t_x5"`` .. versionadded:: 0.9.4 .. seealso:: :ref:`constraint_naming_conventions` """ __slots__ = () class _defer_name(_truncated_label):
63
64
109
10
53
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_defer_name
_defer_name
4,100
4,116
4,100
4,100
1826789e3fbe0f1772ff2ad0d0020cd441285a2c
bigcode/the-stack
train
f858d81d8f14a7f8acea1fab
train
class
class BinaryExpression(ColumnElement): """Represent an expression that is ``LEFT <operator> RIGHT``. A :class:`.BinaryExpression` is generated automatically whenever two column expressions are used in a Python binary expression:: >>> from sqlalchemy.sql import column >>> column('a') + colu...
class BinaryExpression(ColumnElement):
"""Represent an expression that is ``LEFT <operator> RIGHT``. A :class:`.BinaryExpression` is generated automatically whenever two column expressions are used in a Python binary expression:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.express...
other, **kwargs): # comparison operators should never call reverse_operate assert not operators.is_comparison(op) raise exc.ArgumentError( "Only comparison operators may be used with ANY/ALL") class AsBoolean(UnaryExpression): def __init__(self, element, operator, negate): ...
204
204
682
6
198
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
BinaryExpression
BinaryExpression
2,960
3,058
2,960
2,960
b92d08272f52db6ecde25473f9205748c21190ae
bigcode/the-stack
train
13e7b609a366451f29ffb0a6
train
class
class AsBoolean(UnaryExpression): def __init__(self, element, operator, negate): self.element = element self.type = type_api.BOOLEANTYPE self.operator = operator self.negate = negate self.modifier = None self.wraps_column_expression = True self._is_implicitly...
class AsBoolean(UnaryExpression):
def __init__(self, element, operator, negate): self.element = element self.type = type_api.BOOLEANTYPE self.operator = operator self.negate = negate self.modifier = None self.wraps_column_expression = True self._is_implicitly_boolean = element._is_implicitly_b...
, **kwargs) def reverse_operate(self, op, other, **kwargs): # comparison operators should never call reverse_operate assert not operators.is_comparison(op) raise exc.ArgumentError( "Only comparison operators may be used with ANY/ALL") class AsBoolean(UnaryExpression):
64
64
154
7
57
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
AsBoolean
AsBoolean
2,939
2,957
2,939
2,940
75a52cc36e79823786bc64ac3145bc1cea7d8366
bigcode/the-stack
train
8b19ed3ebd1768c6ddd1f01b
train
class
class True_(ColumnElement): """Represent the ``true`` keyword, or equivalent, in a SQL statement. :class:`.True_` is accessed as a constant via the :func:`.true` function. """ __visit_name__ = 'true' @util.memoized_property def type(self): return type_api.BOOLEANTYPE def _ne...
class True_(ColumnElement):
"""Represent the ``true`` keyword, or equivalent, in a SQL statement. :class:`.True_` is accessed as a constant via the :func:`.true` function. """ __visit_name__ = 'true' @util.memoized_property def type(self): return type_api.BOOLEANTYPE def _negate(self): return F...
())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature better integrated behavior within conjunctions and on dialects that d...
122
123
411
6
116
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
True_
True_
1,747
1,810
1,747
1,747
36edae8e8303a7c692670400b06a018e1442e10e
bigcode/the-stack
train
9d6752ecb4053e61d18d786a
train
function
def _clone(element, **kw): return element._clone()
def _clone(element, **kw):
return element._clone()
import Visitable, cloned_traverse, traverse from .annotation import Annotated import itertools from .base import Executable, PARSE_AUTOCOMMIT, Immutable, NO_ARG from .base import _generative import numbers import re import operator def _clone(element, **kw):
64
64
14
8
55
gujun4990/sqlalchemy
lib/sqlalchemy/sql/elements.py
Python
_clone
_clone
29
30
29
29
1158fd32c55b5658e839d32d88d5119830987bde
bigcode/the-stack
train
ba885cebbe034fae596e621d
train
class
class TestPluginCanHandleUrlCinerGroup(PluginCanHandleUrl): __plugin__ = CinerGroup should_match = [ 'http://showtv.com.tr/canli-yayin', 'http://haberturk.com/canliyayin', 'http://showmax.com.tr/canliyayin', 'http://showturk.com.tr/canli-yayin/showturk', 'http://bloomber...
class TestPluginCanHandleUrlCinerGroup(PluginCanHandleUrl):
__plugin__ = CinerGroup should_match = [ 'http://showtv.com.tr/canli-yayin', 'http://haberturk.com/canliyayin', 'http://showmax.com.tr/canliyayin', 'http://showturk.com.tr/canli-yayin/showturk', 'http://bloomberght.com/tv', 'http://haberturk.tv/canliyayin', ]...
from streamlink.plugins.cinergroup import CinerGroup from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlCinerGroup(PluginCanHandleUrl):
37
64
114
15
21
xcgx/streamlink
tests/plugins/test_cinergroup.py
Python
TestPluginCanHandleUrlCinerGroup
TestPluginCanHandleUrlCinerGroup
5
15
5
5
31ebb495d4d91a36ffd457d23fd78aa928878ea6
bigcode/the-stack
train
1d62c9bb9385029616153046
train
function
def Ii11Ii1I ( lisp_sockets ) : for O00oO in lisp_sockets : if ( O00oO == None ) : continue I11i1I1I = "/tmp/lisp-lig" if ( O00oO == oO0Oo ) else "" lisp . lisp_close_socket ( O00oO , I11i1I1I ) if 54 - 54: o0oOOo0O0Ooo - I1IiiI + OoooooooOO return if 70 - 70: Ii1I / I11i . iII111i % Oo0Ooo if 67 - 67: OoOo...
def Ii11Ii1I ( lisp_sockets ) :
for O00oO in lisp_sockets : if ( O00oO == None ) : continue I11i1I1I = "/tmp/lisp-lig" if ( O00oO == oO0Oo ) else "" lisp . lisp_close_socket ( O00oO , I11i1I1I ) if 54 - 54: o0oOOo0O0Ooo - I1IiiI + OoooooooOO return if 70 - 70: Ii1I / I11i . iII111i % Oo0Ooo if 67 - 67: OoOoOO00 * o0oOOo0O0Ooo . IiII - OoO...
iiI if 33 - 33: o0oOOo0O0Ooo + OOooOOo * OoO0O00 - Oo0Ooo / oO0o % Ii1I if 21 - 21: OoO0O00 * iIii1I11I1II1 % oO0o * i1IIi def Ii11Ii1I ( lisp_sockets ) :
93
93
310
13
79
farinacci/lispers.net
build/releases/release-0.578/ob/lisp-lig.py
Python
Ii11Ii1I
Ii11Ii1I
138
151
138
138
5f43dd09b02bd83171a33ce8ae090a99cf868702
bigcode/the-stack
train
039851d7eb1890dcb9321b26
train
function
def ii1I ( record_count , nonce , packet ) : if 76 - 76: O0 / o0oOOo0O0Ooo . I1IiiI * Ii1I - OOooOOo for Oooo in range ( record_count ) : O00o = lisp . lisp_eid_record ( ) packet = O00o . decode ( packet ) if ( packet == None ) : break print ( "EID-prefix: {}, ttl: {}, rloc-set:" . format ( O00o . print_prefi...
def ii1I ( record_count , nonce , packet ) :
if 76 - 76: O0 / o0oOOo0O0Ooo . I1IiiI * Ii1I - OOooOOo for Oooo in range ( record_count ) : O00o = lisp . lisp_eid_record ( ) packet = O00o . decode ( packet ) if ( packet == None ) : break print ( "EID-prefix: {}, ttl: {}, rloc-set:" . format ( O00o . print_prefix ( ) , O00o . print_ttl ( ) ) ) if 61 - 61...
i return ( OoOooOOOO , i11iiII , I1iiiiI1iII , IiIi11i ) if 55 - 55: OoOoOO00 % i1IIi / Ii1I - oO0o - O0 / II111iiii if 28 - 28: iIii1I11I1II1 - i1IIi if 70 - 70: OoO0O00 . OoO0O00 - OoO0O00 / I1ii11iIi11i * OOooOOo if 86 - 86: i11iIiiIii + Ii1I + ooOoO0o * I11i + o0oOOo0O0Ooo if 61 - 61: OoO0O00 / i11iIiiIii if...
256
256
1,294
13
242
farinacci/lispers.net
build/releases/release-0.578/ob/lisp-lig.py
Python
ii1I
ii1I
84
137
84
84
07fdbb4d677effd2cf3598b89136ae26a553707a
bigcode/the-stack
train
e701f3d7e16e41747537321a
train
function
def o000o0o00o0Oo ( socket_list , lisp_ephem_listen_socket , lisp_listen_socket , lisp_ipc_socket ) : if 80 - 80: OoooooooOO . I1IiiI OOO0O , oo0ooO0oOOOOo , oO000OoOoo00o = select . select ( socket_list , [ ] , [ ] , 2 ) if 31 - 31: II111iiii + OoO0O00 . I1Ii111 if ( lisp_ephem_listen_socket in OOO0O ) : OoOooO...
def o000o0o00o0Oo ( socket_list , lisp_ephem_listen_socket , lisp_listen_socket , lisp_ipc_socket ) :
if 80 - 80: OoooooooOO . I1IiiI OOO0O , oo0ooO0oOOOOo , oO000OoOoo00o = select . select ( socket_list , [ ] , [ ] , 2 ) if 31 - 31: II111iiii + OoO0O00 . I1Ii111 if ( lisp_ephem_listen_socket in OOO0O ) : OoOooOOOO , i11iiII , I1iiiiI1iII , IiIi11i = lisp . lisp_receive ( lisp_ephem_listen_socket , False ) if 4...
72: II111iiii - OoOoOO00 if 91 - 91: OoO0O00 . i11iIiiIii / oO0o % I11i / OoO0O00 - i11iIiiIii if 8 - 8: o0oOOo0O0Ooo * I1ii11iIi11i * iIii1I11I1II1 . IiII / IiII % IiII if 22 - 22: Ii1I . IiII if 41 - 41: I1Ii111 . ooOoO0o * IiII % i11iIiiIii def o000o0o00o0Oo ( socket_list , lisp_ephem_listen_socket , lisp_listen_soc...
180
180
600
35
144
farinacci/lispers.net
build/releases/release-0.578/ob/lisp-lig.py
Python
o000o0o00o0Oo
o000o0o00o0Oo
59
83
59
60
7571f62a67ae54206f1f8f48e2a6c435b77ab475
bigcode/the-stack
train
a6db36175d7ae1b23c287cff
train
function
def test_settle_wrong_state_fail( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel_and_deposit: Callable, get_block: Callable, create_close_signature_for_no_balance_proof: Callable, ) -> None: """ settleChannel() fails on OPENED state and on CLOSED state before the...
def test_settle_wrong_state_fail( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel_and_deposit: Callable, get_block: Callable, create_close_signature_for_no_balance_proof: Callable, ) -> None:
""" settleChannel() fails on OPENED state and on CLOSED state before the settlement block """ (A, B) = get_accounts(2) vals_A = ChannelValues(deposit=35) vals_B = ChannelValues(deposit=40) channel_identifier = create_channel_and_deposit(A, B, vals_A.deposit, vals_B.deposit) (settle_timeout, sta...
ferred_amount ) == post_balance_A # B's settlement works correctly assert pre_balance_B + settlement.participant2_balance == post_balance_B # The externally_transferred_amount stays in the contract assert ( pre_balance_contract - settlement.participant1_balance - settlement...
142
142
475
58
83
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_wrong_state_fail
test_settle_wrong_state_fail
397
452
397
404
d70f56f12fa94708aae001c092faaf8c34700eb4
bigcode/the-stack
train
5692e80edd93305d944b0efd
train
function
def test_settle_single_direct_transfer_for_closing_party( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, ) -> None: ...
def test_settle_single_direct_transfer_for_closing_party( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, ) -> None:
""" Test settle of a channel with one direct transfer to the participant that called close. """ (A, B) = get_accounts(2) (vals_A, vals_B) = ( ChannelValues(deposit=1, withdrawn=0, transferred=0), ChannelValues(deposit=10, withdrawn=0, transferred=5), ) settle_timeout = TEST_S...
# Some manual checks for the final balances, in case the settlement algorithms # used in `settle_state_tests` are incorrect # FIXME after setTotalWithdraw is implemented again post_balance_A = pre_balance_A + 33 post_balance_B = pre_balance_B + 15 post_balance_contract = pre_balance_contract - 48 ...
199
199
665
74
124
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_single_direct_transfer_for_closing_party
test_settle_single_direct_transfer_for_closing_party
160
230
160
169
d83bb415ecbea7cb1a1eb5065816554cdc1cdd48
bigcode/the-stack
train
7bcd52ea2d7f0e981f22f033
train
function
def test_settle_wrong_balance_hash( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel_and_deposit: Callable, close_and_update_channel: Callable, reveal_secrets: Callable, ) -> None: """ Calling settleChannel() with various wrong arguments and see failures """ (A...
def test_settle_wrong_balance_hash( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel_and_deposit: Callable, close_and_update_channel: Callable, reveal_secrets: Callable, ) -> None:
""" Calling settleChannel() with various wrong arguments and see failures """ (A, B) = get_accounts(2) vals_A = ChannelValues( deposit=35, withdrawn=0, transferred=5, locked_amounts=LockedAmounts(claimable_locked=10, unclaimable_locked=2), ) vals_B = ChannelValues( ...
act({"from": A}) (settle_block_number, state) = token_network.functions.getChannelInfo( channel_identifier, A, B ).call() assert state == ChannelState.CLOSED assert settle_block_number == TEST_SETTLE_TIMEOUT_MIN + get_block(txn_hash) assert web3.eth.blockNumber < settle_block_number wi...
256
256
1,236
55
200
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_wrong_balance_hash
test_settle_wrong_balance_hash
455
579
455
462
eefac158b7ce87ae5da2afaa1b28b8899b1b241d
bigcode/the-stack
train
5d68514e89edb79cb0e5210c
train
function
def test_settle_channel_event( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, event_handler: Callable, ) -> None: """ A successful settl...
def test_settle_channel_event( web3: Web3, get_accounts: Callable, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, event_handler: Callable, ) -> None:
""" A successful settleChannel() call causes a SETTLED event """ ev_handler = event_handler(token_network) (A, B) = get_accounts(2) deposit_A = 10 settle_timeout = TEST_SETTLE_TIMEOUT_MIN channel_identifier = create_channel(A, B)[0] channel_deposit(channel_identifier, A, deposit_A, B) ...
with pytest.raises(TransactionFailed): call_settle(token_network, channel_identifier, A, vals_A, B, vals_B_fail) vals_B_fail.locksroot = fake_bytes(32, "01") with pytest.raises(TransactionFailed): call_settle(token_network, channel_identifier, A, vals_A, B, vals_B_fail) # Channel is settl...
166
166
556
69
97
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_channel_event
test_settle_channel_event
582
641
582
591
588e7aa9e343e166e26d0a0718d5af73196ea529
bigcode/the-stack
train
2a7000b0e931588b2ae0e07b
train
function
def test_settlement_with_unauthorized_token_transfer( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, assign_tokens: Callable, create_channel_and_deposit: Callable, withdraw_channel: Callable, close_and_update_channel: Callable, ) -> None: """ A p...
def test_settlement_with_unauthorized_token_transfer( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, assign_tokens: Callable, create_channel_and_deposit: Callable, withdraw_channel: Callable, close_and_update_channel: Callable, ) -> None:
""" A participant transfers some tokens to the contract and so loses them """ externally_transferred_amount = 5 (A, B) = get_accounts(2) (vals_A, vals_B) = ( ChannelValues(deposit=35, withdrawn=10, transferred=0), ChannelValues(deposit=40, withdrawn=10, transferred=0), ) vals_A.l...
chain computation onchain_settlement = get_onchain_settlement_amounts(vals_B, vals_A) assert expected_settlement.participant1_balance == onchain_settlement.participant1_balance assert expected_settlement.participant2_balance == onchain_settlement.participant2_balance assert custom_token.functions.balan...
192
192
642
69
123
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settlement_with_unauthorized_token_transfer
test_settlement_with_unauthorized_token_transfer
323
394
323
332
98bc2fd29188527efd200ae1d22623868afecba7
bigcode/the-stack
train
7ea4b6e70feb565b9a2b2992
train
function
def test_settle_single_direct_transfer_for_counterparty( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, create_c...
def test_settle_single_direct_transfer_for_counterparty( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel: Callable, channel_deposit: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, create_c...
""" Test settle of a channel with one direct transfer to the participant that did not call close. """ (A, B) = get_accounts(2) (vals_A, vals_B) = ( ChannelValues(deposit=10, withdrawn=0, transferred=5), ChannelValues(deposit=1, withdrawn=0, transferred=0), ) settle_timeout = ...
_amounts(vals_A, vals_B) # Calculate how much A and B receive according to onchain computation onchain_settlement = get_onchain_settlement_amounts(vals_A, vals_B) assert expected_settlement.participant1_balance == onchain_settlement.participant1_balance assert expected_settlement.participant2_balance =...
228
228
762
85
143
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_single_direct_transfer_for_counterparty
test_settle_single_direct_transfer_for_counterparty
233
320
233
243
c043931994c5583fe553376d934f23178a0b9ffd
bigcode/the-stack
train
e2c22de94dabc05f6a7f86fb
train
function
def test_settle_no_bp_success( web3: Web3, custom_token: Contract, token_network: Contract, create_channel_and_deposit: Callable, get_accounts: Callable, create_close_signature_for_no_balance_proof: Callable, ) -> None: """ The simplest settlement without any balance proofs provided """ ...
def test_settle_no_bp_success( web3: Web3, custom_token: Contract, token_network: Contract, create_channel_and_deposit: Callable, get_accounts: Callable, create_close_signature_for_no_balance_proof: Callable, ) -> None:
""" The simplest settlement without any balance proofs provided """ (A, B) = get_accounts(2) deposit_A = 10 deposit_B = 6 settle_timeout = TEST_SETTLE_TIMEOUT_MIN channel_identifier = create_channel_and_deposit(A, B, deposit_A, deposit_B) closing_sig = create_close_signature_for_no_balance_p...
fake_bytes, get_onchain_settlement_amounts, get_settlement_amounts, ) from raiden_contracts.utils.events import check_channel_settled from raiden_contracts.utils.pending_transfers import ( get_pending_transfers_tree_with_generated_lists, ) def test_settle_no_bp_success( web3: Web3, custom_token: Co...
114
114
381
58
56
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_no_bp_success
test_settle_no_bp_success
34
81
34
41
ebb59ed41726236bbf486c71b4306f1893625926
bigcode/the-stack
train
7d4e933deeae2e2588c7d1b9
train
function
def test_settle_channel_state( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel_and_deposit: Callable, withdraw_channel: Callable, close_and_update_channel: Callable, settle_state_tests: Callable, ) -> None: """ settleChannel() with ...
def test_settle_channel_state( web3: Web3, get_accounts: Callable, custom_token: Contract, token_network: Contract, create_channel_and_deposit: Callable, withdraw_channel: Callable, close_and_update_channel: Callable, settle_state_tests: Callable, ) -> None:
""" settleChannel() with some balance proofs """ (A, B) = get_accounts(2) vals_A = ChannelValues( deposit=40, withdrawn=10, transferred=20020, locked_amounts=LockedAmounts(claimable_locked=3, unclaimable_locked=4), ) vals_B = ChannelValues( deposit=35, ...
token_network.functions.settleChannel( channel_identifier=channel_identifier, participant1=A, participant1_transferred_amount=0, participant1_locked_amount=0, participant1_locksroot=LOCKSROOT_OF_NO_LOCKS, participant2=B, participant2_transferred_amount=0, ...
195
195
650
66
128
palango/raiden-contracts
raiden_contracts/tests/test_channel_settle.py
Python
test_settle_channel_state
test_settle_channel_state
84
157
84
93
09789a3e15181f19d4705be306da3a07ea8a035d
bigcode/the-stack
train
13e0e94f05497ea7bb1a805d
train
class
class Migration(migrations.Migration): dependencies = [ ('classy', '0019_remove_classification_review_classy_id'), ] operations = [ migrations.RemoveField( model_name='classification_logs', name='action_flag', ), migrations.RemoveField( m...
class Migration(migrations.Migration):
dependencies = [ ('classy', '0019_remove_classification_review_classy_id'), ] operations = [ migrations.RemoveField( model_name='classification_logs', name='action_flag', ), migrations.RemoveField( model_name='classification_logs', ...
# Generated by Django 2.0.1 on 2018-03-06 18:58 from django.db import migrations class Migration(migrations.Migration):
36
64
76
7
28
Krocodial/DSC
classy/migrations/0020_auto_20180306_1058.py
Python
Migration
Migration
6
21
6
7
63c6300f683243feb78fd353961f1288fd5e69b3
bigcode/the-stack
train
c8be9ca2abffb554b5cf83da
train
function
def validate_user(username, minlen): """Checks if the received username matches the required conditions.""" if type(username) != str: raise TypeError("username must be a string") if minlen < 1: raise ValueError("minlen must be at least 1") # Usernames can't be shorter than minlen ...
def validate_user(username, minlen):
"""Checks if the received username matches the required conditions.""" if type(username) != str: raise TypeError("username must be a string") if minlen < 1: raise ValueError("minlen must be at least 1") # Usernames can't be shorter than minlen if len(username) < minlen: ...
#!/usr/bin/env python3 import re def validate_user(username, minlen):
18
64
173
8
9
HumbleTurtle/it-cert-automation-practice
Course3/Lab4/validations.py
Python
validate_user
validate_user
5
25
5
5
fcbf56351383fdbb5096f92516e71715f12cdfca
bigcode/the-stack
train
49e6042a30a86ad55cbd5297
train
class
class AdditionalCodeFilterBackend(TamatoFilterBackend, AdditionalCodeFilterMixin): pass
class AdditionalCodeFilterBackend(TamatoFilterBackend, AdditionalCodeFilterMixin):
pass
", delimiter=" "), "code", "sid", StringAgg("descriptions__description", delimiter=" "), ) # XXX order is significant search_regex = COMBINED_ADDITIONAL_CODE_AND_TYPE_ID class AdditionalCodeFilterBackend(TamatoFilterBackend, AdditionalCodeFilterMixin):
64
64
19
16
47
uktrade/tamato
additional_codes/filters.py
Python
AdditionalCodeFilterBackend
AdditionalCodeFilterBackend
40
41
40
40
dac6537a157034b5d5495bc6d2659aa85e6ff406
bigcode/the-stack
train
5ca846579d08400a84d9f8a2
train
class
class AdditionalCodeFilterMixin(TamatoFilterMixin): """ Filter mixin to allow custom filtering on type__sid, sid, code and description. Also provides a regex to split combined type__sid and code. e.g. "8001" -> "8", "001" """ search_fields = ( StringAgg("type__sid", delimiter=" "),...
class AdditionalCodeFilterMixin(TamatoFilterMixin):
""" Filter mixin to allow custom filtering on type__sid, sid, code and description. Also provides a regex to split combined type__sid and code. e.g. "8001" -> "8", "001" """ search_fields = ( StringAgg("type__sid", delimiter=" "), "code", "sid", StringAgg("d...
from common.filters import type_choices COMBINED_ADDITIONAL_CODE_AND_TYPE_ID = re.compile( r"(?P<type__sid>[A-Z0-9])(?P<code>[A-Z0-9]{3})", ) class AdditionalCodeFilterMixin(TamatoFilterMixin):
64
64
125
11
53
uktrade/tamato
additional_codes/filters.py
Python
AdditionalCodeFilterMixin
AdditionalCodeFilterMixin
21
37
21
21
9fb45d0a08621ba58c947293aaa5ed673abb4735
bigcode/the-stack
train
07ab6c63c47772e8f079d70e
train
class
class AdditionalCodeFilter( TamatoFilter, AdditionalCodeFilterMixin, StartYearMixin, ActiveStateMixin, ): """ FilterSet for Additional Codes. Provides multiple choice widgets for Type SIDs, the start year of the additional code as well as filters for the code and SID """ additi...
class AdditionalCodeFilter( TamatoFilter, AdditionalCodeFilterMixin, StartYearMixin, ActiveStateMixin, ):
""" FilterSet for Additional Codes. Provides multiple choice widgets for Type SIDs, the start year of the additional code as well as filters for the code and SID """ additional_code_type = LazyMultipleChoiceFilter( choices=type_choices(models.AdditionalCodeType.objects.latest_approved(...
is significant search_regex = COMBINED_ADDITIONAL_CODE_AND_TYPE_ID class AdditionalCodeFilterBackend(TamatoFilterBackend, AdditionalCodeFilterMixin): pass class AdditionalCodeFilter( TamatoFilter, AdditionalCodeFilterMixin, StartYearMixin, ActiveStateMixin, ):
64
64
182
27
36
uktrade/tamato
additional_codes/filters.py
Python
AdditionalCodeFilter
AdditionalCodeFilter
44
71
44
49
a273792b0122a83ce5f3252ad4dccb63bc516e47
bigcode/the-stack
train
b1469d56c9a610196f27c293
train
class
class ModeratorModelTest(TestCase): def setUp(self): self.user = self.make_user("testuser1") self.moderator = Moderator.objects.create(user=self.user) self.category = make_category() self.moderator.categories.add(self.category) self.user2 = self.make_user("testuser2") ...
class ModeratorModelTest(TestCase):
def setUp(self): self.user = self.make_user("testuser1") self.moderator = Moderator.objects.create(user=self.user) self.category = make_category() self.moderator.categories.add(self.category) self.user2 = self.make_user("testuser2") self.moderator2 = Moderator.o...
from test_plus import TestCase from forum.accounts.tests.utils import make_superuser from forum.categories.tests.utils import make_category from forum.comments.models import Comment from forum.comments.tests.utils import make_comment from forum.moderation.models import Moderator from forum.threads.models import Thread...
77
256
2,103
7
69
successIA/Forum
forum/moderation/tests/test_models.py
Python
ModeratorModelTest
ModeratorModelTest
12
248
12
12
7750781e41c68a965a546bc8f00e3ac080479f87
bigcode/the-stack
train
078a595d983e4519987498c7
train
class
class ApiAsset(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: str=None, created_at: datetime=None, name: str=None, description: str=None, featured: bool=None, publish_approved: bool=None, related_assets: L...
class ApiAsset(Model):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: str=None, created_at: datetime=None, name: str=None, description: str=None, featured: bool=None, publish_approved: bool=None, related_assets: List[str]=None, filter_c...
# Copyright 2021 The MLX Contributors # # SPDX-License-Identifier: Apache-2.0 # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class ...
84
256
1,554
5
78
krishnakumar27/mlx
api/server/swagger_server/models/api_asset.py
Python
ApiAsset
ApiAsset
15
253
15
15
7fe2ce40d3ee25b7bcb5f383c87e045081aba9a5
bigcode/the-stack
train
fccb265245473dd2f54c7ffa
train
class
class SimpleTypeDelegate(ComboSpinBoxDelegate): """Extends the double spin and combo bod delegate specifically for working with SimpleType model extensions containing `value` and `unit` fields and dealing with the possibility of many different extended types.""" def __init__(self, parent, types, minimu...
class SimpleTypeDelegate(ComboSpinBoxDelegate):
"""Extends the double spin and combo bod delegate specifically for working with SimpleType model extensions containing `value` and `unit` fields and dealing with the possibility of many different extended types.""" def __init__(self, parent, types, minimum=0, maximum=99, suffix='', decimals=3, singleSte...
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ---------------------------------------------------------------------------------------------------------------------- # =====================================================================================================================...
86
87
293
10
76
jwjulien/alphabrew
alphabrew/GUI/Delegates/SimpleTypeDelegate.py
Python
SimpleTypeDelegate
SimpleTypeDelegate
36
62
36
36
7545ff213abffe614741be13150e3ccd2cce788d
bigcode/the-stack
train
93e919c2fe8a505154c60fcc
train
function
async def init_integration_empty_response(hass) -> MockConfigEntry: """Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", return_value=[] ...
async def init_integration_empty_response(hass) -> MockConfigEntry:
"""Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", return_value=[] ), patch( "homeassistant.components.nightscout.Nightscout...
scoutAPI.get_server_status", return_value=SERVER_STATUS, ): entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry async def init_integration_empty_response(hass) -> MockConfigEntry:
64
64
143
15
48
csseal/core
tests/components/nightscout/__init__.py
Python
init_integration_empty_response
init_integration_empty_response
61
74
61
61
d0afa3cb0fc94189d5ca5153409aadbc35fe6d21
bigcode/the-stack
train
27bf3c29fae57520f33aab0d
train
function
async def init_integration_unavailable(hass) -> MockConfigEntry: """Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", side_effect=...
async def init_integration_unavailable(hass) -> MockConfigEntry:
"""Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", side_effect=ClientConnectionError(), ), patch( "homeassistant.com...
scoutAPI.get_server_status", return_value=SERVER_STATUS, ): entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry async def init_integration_unavailable(hass) -> MockConfigEntry:
64
64
148
15
48
csseal/core
tests/components/nightscout/__init__.py
Python
init_integration_unavailable
init_integration_unavailable
44
58
44
44
30b1283048610c18cd8db27c47723d020ea33b14
bigcode/the-stack
train
96755909d444d2403534e3dd
train
function
async def init_integration(hass) -> MockConfigEntry: """Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", return_value=GLUCOSE_REA...
async def init_integration(hass) -> MockConfigEntry:
"""Set up the Nightscout integration in Home Assistant.""" entry = MockConfigEntry(domain=DOMAIN, data={CONF_URL: "https://some.url:1234"},) with patch( "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", return_value=GLUCOSE_READINGS, ), patch( "homeassistant.component...
14:02.032Z","serverTimeEpoch":1596651242032,"apiEnabled":true,"careportalEnabled":true,"boluscalcEnabled":true,"settings":{},"extendedSettings":{},"authorized":null}' ) ) async def init_integration(hass) -> MockConfigEntry:
64
64
149
13
51
csseal/core
tests/components/nightscout/__init__.py
Python
init_integration
init_integration
27
41
27
27
9399b92554ab32190a4a31264fe02549d1e4ca97
bigcode/the-stack
train
2ba12ccd8462abce609c1c72
train
class
class BugsTestCase(unittest.TestCase): def test_emptyDesc(self): """does it work without any options or keywords?""" ovc, args = parse({}, [], exit_on_error=False) self.assertEqual(ovc.ovc_values(), {}) self.assertEqual(args, []) def test_emptyOpts(self): """does it wor...
class BugsTestCase(unittest.TestCase):
def test_emptyDesc(self): """does it work without any options or keywords?""" ovc, args = parse({}, [], exit_on_error=False) self.assertEqual(ovc.ovc_values(), {}) self.assertEqual(args, []) def test_emptyOpts(self): """does it work without any options but _arguments?"""...
#!/usr/bin/env python3 from jpylib.pgetopt import parse import unittest # test cases to reproduce bugs found class BugsTestCase(unittest.TestCase):
36
64
122
8
27
jyrgenn/jpylib
tests/test_pg_squish_bugs.py
Python
BugsTestCase
BugsTestCase
8
21
8
9
be2d59bd76be1a7fc7fb3042b41e37c3f320b43a
bigcode/the-stack
train
437c9cd6ee365981c0e1f3f7
train
class
class CobamasDatasetFactory: def __init__(self): self.logger = logging.getLogger(self.__class__.__name__) def load_data(self, path): self.logger.info("Loading data...") with np.load(path) as npz: converters = npz["converters"] data = npz["data"] senso...
class CobamasDatasetFactory:
def __init__(self): self.logger = logging.getLogger(self.__class__.__name__) def load_data(self, path): self.logger.info("Loading data...") with np.load(path) as npz: converters = npz["converters"] data = npz["data"] sensors = npz["sensors"] ...
from typing import Union, List import pathlib import numpy as np from datasets.SensorData import SensorDataTimeOrig import Utils import logging class CobamasDatasetFactory:
37
212
708
6
30
n-1-l-s/cobamas-sensor-od
CobamasDatasetFactory.py
Python
CobamasDatasetFactory
CobamasDatasetFactory
9
62
9
9
31ecae424010169b249ccbdb4a31792af4199223
bigcode/the-stack
train
6b30a1c2c92ab0c48f02fd27
train
class
class SimpleSerializer: """The SimpleSerializer handles serialization to and from pickle and json. :param target: Default location (directory) to store checkpoint. This may be overridden in the `checkpoint` method. Defaults to None. """ def __init__(self, target: Optional[str] = None): ...
class SimpleSerializer:
"""The SimpleSerializer handles serialization to and from pickle and json. :param target: Default location (directory) to store checkpoint. This may be overridden in the `checkpoint` method. Defaults to None. """ def __init__(self, target: Optional[str] = None): self.target = target ...
""" Serializers help store (checkpoint) the state of your population during or after running your evolutionary algorithm. By default, each Population is initialized with a SimpleSerializer, which you can use to store the individuals in your population in pickle or json format using the .checkpoint() method of the popul...
115
237
792
4
110
bahia14/Evol
evol/serialization.py
Python
SimpleSerializer
SimpleSerializer
19
95
19
19
238d05b6503dd07f75bd80e752d960e77271d9e5
bigcode/the-stack
train
463283314c3b88aef08b8aae
train
function
@click.command() @click.option("-m", "--max", type=int, default=10, help="The maximum number of results to return") @click.argument("keyword") def cli(max: int, keyword: str): """ A tool for searching San Francison Bay Area Library system. """ for result in limit(SearchClient().search(keyword=keyword), ...
@click.command() @click.option("-m", "--max", type=int, default=10, help="The maximum number of results to return") @click.argument("keyword") def cli(max: int, keyword: str):
""" A tool for searching San Francison Bay Area Library system. """ for result in limit(SearchClient().search(keyword=keyword), max): print(result)
import click from . import SearchClient, limit, logger @click.command() @click.option("-m", "--max", type=int, default=10, help="The maximum number of results to return") @click.argument("keyword") def cli(max: int, keyword: str):
56
64
79
43
12
dang3r/libraria
libraria/cli.py
Python
cli
cli
6
14
6
9
e111e930e96dd95cb995ef7491fc8bdfd5f277d7
bigcode/the-stack
train
393797d2ff917bbee458b78a
train
function
def to_french_short_weekday(weekday: int) -> str: return to_french_weekday(weekday)[:3]
def to_french_short_weekday(weekday: int) -> str:
return to_french_weekday(weekday)[:3]
', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ] return MONTHS[month_number-1] def to_french_short_weekday(weekday: int) -> str:
64
64
28
15
49
tducret/allocine-python
allocine/__init__.py
Python
to_french_short_weekday
to_french_short_weekday
199
200
199
199
034f5b8fc24496585dc4d9b52182f0de08d26cd2
bigcode/the-stack
train
85892cbba170e6dee13d9d13
train
function
def build_program_str(showtimes: List[Showtime]): schedules = [Schedule(s.date_time) for s in showtimes] return build_weekly_schedule_str(schedules)
def build_program_str(showtimes: List[Showtime]):
schedules = [Schedule(s.date_time) for s in showtimes] return build_weekly_schedule_str(schedules)
_date]] hours_str = ', '.join(hours) if grouped_showtimes.get(hours_str) is None: grouped_showtimes[hours_str] = [] grouped_showtimes[hours_str].append(available_date) return grouped_showtimes def build_program_str(showtimes: List[Showtime]):
64
64
37
12
51
tducret/allocine-python
allocine/__init__.py
Python
build_program_str
build_program_str
298
300
298
298
4990b97b0f75b6cf46d48079637bf6a6aa2ba5e1
bigcode/the-stack
train
18393b5ab4b52d73d829a4c2
train
function
def check_schedules_within_week(schedule_list: List[Schedule]) -> bool: schedule_dates = [s.date for s in schedule_list] min_date = min(schedule_dates) max_date = max(schedule_dates) delta = (max_date - min_date) if delta >= timedelta(days=7): raise ValueError( 'Schedule list con...
def check_schedules_within_week(schedule_list: List[Schedule]) -> bool:
schedule_dates = [s.date for s in schedule_list] min_date = min(schedule_dates) max_date = max(schedule_dates) delta = (max_date - min_date) if delta >= timedelta(days=7): raise ValueError( 'Schedule list contains more days than the typical movie week') # Check that the week ...
= [] grouped_showtimes[hours_str].append(available_date) return grouped_showtimes def build_program_str(showtimes: List[Showtime]): schedules = [Schedule(s.date_time) for s in showtimes] return build_weekly_schedule_str(schedules) def check_schedules_within_week(schedule_list: List[Schedule]) -> ...
75
75
252
17
58
tducret/allocine-python
allocine/__init__.py
Python
check_schedules_within_week
check_schedules_within_week
303
324
303
303
132fe61f5e22031f3aaabd23a5feb01da491a782
bigcode/the-stack
train
0233a29cf9c273d960ec6bfa
train
function
def get_showtimes_of_a_day(showtimes: List[Showtime], *, date: date): return [showtime for showtime in showtimes if showtime.date == date]
def get_showtimes_of_a_day(showtimes: List[Showtime], *, date: date):
return [showtime for showtime in showtimes if showtime.date == date]
' else: weekly_schedule += f'{grouped_dates} {hours_str}; ' if weekly_schedule: weekly_schedule = weekly_schedule[:-2] # Remove trailing comma return weekly_schedule def get_showtimes_of_a_day(showtimes: List[Showtime], *, date: date):
64
64
40
20
43
tducret/allocine-python
allocine/__init__.py
Python
get_showtimes_of_a_day
get_showtimes_of_a_day
433
435
433
433
3f00463763294d23efe115bf530487b409495552
bigcode/the-stack
train
0968c46dc118aaaad8de76b7
train
function
def get_hour_short_str(hour: datetime.time) -> str: # Ex: 9h, 11h, 23h30 # Minus in '%-H' removes the leading 0 return hour.strftime('%-Hh%M').replace('h00', 'h')
def get_hour_short_str(hour: datetime.time) -> str: # Ex: 9h, 11h, 23h30 # Minus in '%-H' removes the leading 0
return hour.strftime('%-Hh%M').replace('h00', 'h')
property def short_day_str(self) -> str: return short_day_str(self.date) def get_hour_short_str(hour: datetime.time) -> str: # Ex: 9h, 11h, 23h30 # Minus in '%-H' removes the leading 0
64
64
63
44
20
tducret/allocine-python
allocine/__init__.py
Python
get_hour_short_str
get_hour_short_str
168
171
168
170
2eda4913ce2e8e5138a6e0d6284ff84747fb1661
bigcode/the-stack
train
7962ddbfa8277a7ccbd7f282
train
function
def get_french_month(month_number: int) -> str: MONTHS = [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ] return MONTHS[month_number-1]
def get_french_month(month_number: int) -> str:
MONTHS = [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ] return MONTHS[month_number-1]
def to_french_weekday(weekday: int) -> str: DAYS = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'] return DAYS[weekday] def get_french_month(month_number: int) -> str:
64
64
79
13
51
tducret/allocine-python
allocine/__init__.py
Python
get_french_month
get_french_month
191
196
191
191
cf43fca22347b5f728d30dabca917f138d515873
bigcode/the-stack
train
86873b91d4e329bd4c1ee8c5
train
class
@dataclass class Showtime(Schedule): movie: MovieVersion def __str__(self): return f'{self.date_str} : {self.movie}'
@dataclass class Showtime(Schedule):
movie: MovieVersion def __str__(self): return f'{self.date_str} : {self.movie}'
datetime.time) -> str: # Ex: 9h, 11h, 23h30 # Minus in '%-H' removes the leading 0 return hour.strftime('%-Hh%M').replace('h00', 'h') @dataclass class Showtime(Schedule):
64
64
34
8
56
tducret/allocine-python
allocine/__init__.py
Python
Showtime
Showtime
174
179
174
175
8902ef5d16c8b19fa9a5bf79fdcf37e8f6f4cf76
bigcode/the-stack
train
d8909301052842d8474cbfe3
train
function
def __get_time_weight(t: time) -> timedelta: """ Return a timedelta taking into account night time. Basically, it allows to sort a list of times 18h>23h>0h30 and not 0h30>18h>23h """ _NIGHT_TIME = [time(hour=0), time(hour=5)] delta = timedelta(hours=t.hour, minutes=t.minute) if t >= ...
def __get_time_weight(t: time) -> timedelta:
""" Return a timedelta taking into account night time. Basically, it allows to sort a list of times 18h>23h>0h30 and not 0h30>18h>23h """ _NIGHT_TIME = [time(hour=0), time(hour=5)] delta = timedelta(hours=t.hour, minutes=t.minute) if t >= min(_NIGHT_TIME) and t <= max(_NIGHT_TIME): ...
the dict values ex: {'key': [time(hour=12), time(hour=9)]} => timedelta(hour=9) """ weights = [__get_time_weight(t) for t in d[1]] return min(weights) def __get_time_weight(t: time) -> timedelta:
64
64
121
12
52
tducret/allocine-python
allocine/__init__.py
Python
__get_time_weight
__get_time_weight
357
366
357
357
84e1b3aeb1d0550c2d091d6231f48bbe37a35c73
bigcode/the-stack
train