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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e666946269fea3b642c8321a | train | class | class AliasedClass(object):
r"""Represents an "aliased" form of a mapped class for usage with Query.
The ORM equivalent of a :func:`~sqlalchemy.sql.expression.alias`
construct, this object mimics the mapped class using a
``__getattr__`` scheme and maintains a reference to a
real :class:`~sqlalchemy... | class AliasedClass(object):
| r"""Represents an "aliased" form of a mapped class for usage with Query.
The ORM equivalent of a :func:`~sqlalchemy.sql.expression.alias`
construct, this object mimics the mapped class using a
``__getattr__`` scheme and maintains a reference to a
real :class:`~sqlalchemy.sql.expression.Alias` objec... | keyword arguments: %s" % ", ".join(kwargs.keys)
)
mapper = object_mapper(instance)
return mapper.identity_key_from_instance(instance)
class ORMAdapter(sql_util.ColumnAdapter):
"""ColumnAdapter subclass which excludes adaptation of entities from
non-matching mappers.
"""
... | 256 | 256 | 1,495 | 6 | 250 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | AliasedClass | AliasedClass | 421 | 605 | 421 | 421 | 932e6d0b013c9cc1841260bf212347eb0ac09a02 | bigcode/the-stack | train |
241629480eaf72dd04a2176a | train | function | def _getitem(iterable_query, item, allow_negative):
"""calculate __getitem__ in terms of an iterable query object
that also has a slice() method.
"""
def _no_negative_indexes():
if not allow_negative:
raise IndexError(
"negative indexes are not accepted by SQL "
... | def _getitem(iterable_query, item, allow_negative):
| """calculate __getitem__ in terms of an iterable query object
that also has a slice() method.
"""
def _no_negative_indexes():
if not allow_negative:
raise IndexError(
"negative indexes are not accepted by SQL "
"index / slice operators"
)... | available when running the test suite via the
``--reversetop`` flag.
"""
from sqlalchemy.orm import unitofwork, session, mapper, dependency
from sqlalchemy.util import topological
from sqlalchemy.testing.util import RandomSet
topological.set = (
unitofwork.set
) = session.set = ma... | 91 | 91 | 305 | 12 | 78 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _getitem | _getitem | 2,055 | 2,101 | 2,055 | 2,055 | 0c28b3f13cc533d15a3724c30fefa308fec20804 | bigcode/the-stack | train |
958ba277660cffc42fee5323 | train | function | def identity_key(*args, **kwargs):
r"""Generate "identity key" tuples, as are used as keys in the
:attr:`.Session.identity_map` dictionary.
This function has several call styles:
* ``identity_key(class, ident, identity_token=token)``
This form receives a mapped class and a primary key scalar or... | def identity_key(*args, **kwargs):
| r"""Generate "identity key" tuples, as are used as keys in the
:attr:`.Session.identity_map` dictionary.
This function has several call styles:
* ``identity_key(class, ident, identity_token=token)``
This form receives a mapped class and a primary key scalar or
tuple as an argument.
... | names.add(c.key)
m[c.key] = c
types[c.key] = c.type
colnamemaps[table] = m
def col(name, table):
try:
return colnamemaps[table][name]
except KeyError:
if cast_nulls:
return sql.cast(sql.null(), types[name]).label(name)
... | 234 | 234 | 781 | 9 | 225 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | identity_key | identity_key | 278 | 379 | 278 | 278 | 012596b602b0b0ca92961d5d1af0f5930cbcd9e2 | bigcode/the-stack | train |
c166f25b4e8316d89aff2bac | train | class | class _WrapUserEntity(object):
"""A wrapper used within the loader_criteria lambda caller so that
we can bypass declared_attr descriptors on unmapped mixins, which
normally emit a warning for such use.
might also be useful for other per-lambda instrumentations should
the need arise.
"""
d... | class _WrapUserEntity(object):
| """A wrapper used within the loader_criteria lambda caller so that
we can bypass declared_attr descriptors on unmapped mixins, which
normally emit a warning for such use.
might also be useful for other per-lambda instrumentations should
the need arise.
"""
def __init__(self, subject):
... | __,
", ".join(
mp.class_.__name__
for mp in self.with_polymorphic_mappers
if mp is not self.mapper
),
)
else:
return "aliased(%s)" % (self._target.__name__,)
class _WrapUserEntity(object):
| 64 | 64 | 179 | 7 | 57 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _WrapUserEntity | _WrapUserEntity | 898 | 921 | 898 | 898 | 296bb310564c9b8856282a9273b310fd2baf0536 | bigcode/the-stack | train |
3abc23504524597ebcf6079e | train | function | def _entity_isa(given, mapper):
"""determine if 'given' "is a" mapper, in terms of the given
would load rows of type 'mapper'.
"""
if given.is_aliased_class:
return mapper in given.with_polymorphic_mappers or given.mapper.isa(
mapper
)
elif given.with_polymorphic_mappers... | def _entity_isa(given, mapper):
| """determine if 'given' "is a" mapper, in terms of the given
would load rows of type 'mapper'.
"""
if given.is_aliased_class:
return mapper in given.with_polymorphic_mappers or given.mapper.isa(
mapper
)
elif given.with_polymorphic_mappers:
return mapper in given... | ._with_polymorphic_entities)
)
elif not entity.is_aliased_class:
return given.common_parent(entity.mapper)
else:
return (
entity._use_mapper_path
and given in entity.with_polymorphic_mappers
)
def _entity_isa(given, mapper):
| 64 | 64 | 105 | 10 | 54 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _entity_isa | _entity_isa | 2,004 | 2,016 | 2,004 | 2,004 | 893e4f9ac51078fb68594e03119b77acbbef0834 | bigcode/the-stack | train |
59ed6ee4548d2f9c94d9beae | train | class | class CascadeOptions(frozenset):
"""Keeps track of the options sent to
:paramref:`.relationship.cascade`"""
_add_w_all_cascades = all_cascades.difference(
["all", "none", "delete-orphan"]
)
_allowed_cascades = all_cascades
_viewonly_cascades = ["expunge", "all", "none", "refresh-expire... | class CascadeOptions(frozenset):
| """Keeps track of the options sent to
:paramref:`.relationship.cascade`"""
_add_w_all_cascades = all_cascades.difference(
["all", "none", "delete-orphan"]
)
_allowed_cascades = all_cascades
_viewonly_cascades = ["expunge", "all", "none", "refresh-expire"]
__slots__ = (
"sa... |
from .. import util
from ..engine.result import result_tuple
from ..sql import base as sql_base
from ..sql import coercions
from ..sql import expression
from ..sql import lambdas
from ..sql import roles
from ..sql import util as sql_util
from ..sql import visitors
from ..sql.annotation import SupportsCloneAnnotations
... | 141 | 141 | 471 | 8 | 133 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | CascadeOptions | CascadeOptions | 64 | 127 | 64 | 64 | a17a68dcb46d1690f17f3ea3b2077e81f762ddd0 | bigcode/the-stack | train |
6ec8dd987eb157ba62ed301d | train | function | def _validator_events(desc, key, validator, include_removes, include_backrefs):
"""Runs a validation method on an attribute value to be set or
appended.
"""
if not include_backrefs:
def detect_is_backref(state, initiator):
impl = state.manager[key].impl
return initiator... | def _validator_events(desc, key, validator, include_removes, include_backrefs):
| """Runs a validation method on an attribute value to be set or
appended.
"""
if not include_backrefs:
def detect_is_backref(state, initiator):
impl = state.manager[key].impl
return initiator.impl is not impl
if include_removes:
def append(state, value, ini... | values
self.expunge = "expunge" in values
self.delete_orphan = "delete-orphan" in values
if self.delete_orphan and not self.delete:
util.warn(
"The 'delete-orphan' cascade " "option requires 'delete'."
)
return self
def __repr__(self):
... | 153 | 153 | 512 | 18 | 135 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _validator_events | _validator_events | 130 | 193 | 130 | 130 | c47290cc4e6948c1610f79d6ed7b1d69db053454 | bigcode/the-stack | train |
d10efb28515a24a846d145e5 | train | function | def _orm_full_deannotate(element):
return sql_util._deep_deannotate(element)
| def _orm_full_deannotate(element):
| return sql_util._deep_deannotate(element)
| " annotations
passed by the :func:`_orm.foreign` and :func:`_orm.remote`
annotators.
"""
return sql_util._deep_deannotate(
element, values=("_orm_adapt", "parententity")
)
def _orm_full_deannotate(element):
| 64 | 64 | 20 | 9 | 55 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _orm_full_deannotate | _orm_full_deannotate | 1,640 | 1,641 | 1,640 | 1,640 | c4bf74b57414489c1abaa189faae2b77a52c3fc9 | bigcode/the-stack | train |
3fe872bd74d0c6db8826cda4 | train | class | class _ORMJoin(expression.Join):
"""Extend Join to support ORM constructs as input."""
__visit_name__ = expression.Join.__visit_name__
inherit_cache = True
def __init__(
self,
left,
right,
onclause=None,
isouter=False,
full=False,
_left_memo=Non... | class _ORMJoin(expression.Join):
| """Extend Join to support ORM constructs as input."""
__visit_name__ = expression.Join.__visit_name__
inherit_cache = True
def __init__(
self,
left,
right,
onclause=None,
isouter=False,
full=False,
_left_memo=None,
_right_memo=None,
... | :`.Bundle`.
May be overridden by subclasses.
.. seealso::
:ref:`bundles` - includes an example of subclassing.
"""
keyed_tuple = result_tuple(labels, [() for l in labels])
def proc(row):
return keyed_tuple([proc(row) for proc in procs])
retur... | 256 | 256 | 991 | 7 | 249 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | _ORMJoin | _ORMJoin | 1,644 | 1,787 | 1,644 | 1,644 | 98a1292c36a4f610acea63dc74c82af6b393d53a | bigcode/the-stack | train |
0f623d211724d2c5bb7f7819 | train | class | @inspection._self_inspects
class Bundle(
ORMColumnsClauseRole,
SupportsCloneAnnotations,
sql_base.MemoizedHasCacheKey,
InspectionAttr,
):
"""A grouping of SQL expressions that are returned by a :class:`.Query`
under one namespace.
The :class:`.Bundle` essentially allows nesting of the tuple... | @inspection._self_inspects
class Bundle(
ORMColumnsClauseRole,
SupportsCloneAnnotations,
sql_base.MemoizedHasCacheKey,
InspectionAttr,
):
| """A grouping of SQL expressions that are returned by a :class:`.Query`
under one namespace.
The :class:`.Bundle` essentially allows nesting of the tuple-based
results returned by a column-oriented :class:`_query.Query` object.
It also
is extensible via simple subclassing, where the primary cap... | , False) and flat:
raise sa_exc.ArgumentError(
"the 'flat' and 'selectable' arguments cannot be passed "
"simultaneously to with_polymorphic()"
)
if _existing_alias:
assert _existing_alias.mapper is primary_mapper
classes = util.to_set(classes)
new_cl... | 256 | 256 | 1,192 | 36 | 220 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | Bundle | Bundle | 1,439 | 1,613 | 1,439 | 1,445 | 95542b86dc871f08dda39efc33f9568bb320c95a | bigcode/the-stack | train |
614526a2716210210d2d9e38 | train | function | def was_deleted(object_):
"""Return True if the given object was deleted
within a session flush.
This is regardless of whether or not the object is
persistent or detached.
.. seealso::
:attr:`.InstanceState.was_deleted`
"""
state = attributes.instance_state(object_)
return s... | def was_deleted(object_):
| """Return True if the given object was deleted
within a session flush.
This is regardless of whether or not the object is
persistent or detached.
.. seealso::
:attr:`.InstanceState.was_deleted`
"""
state = attributes.instance_state(object_)
return state.was_deleted
| if the given object has a database
identity.
This typically corresponds to the object being
in either the persistent or detached state.
.. seealso::
:func:`.was_deleted`
"""
state = attributes.instance_state(object_)
return state.has_identity
def was_deleted(object_):
| 64 | 64 | 71 | 6 | 57 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | was_deleted | was_deleted | 1,932 | 1,946 | 1,932 | 1,932 | 53ca0611a7a0bea80dfd735fde1c308e6377dc22 | bigcode/the-stack | train |
a9b01e91ff5d950c94df9cf5 | train | function | def outerjoin(left, right, onclause=None, full=False, join_to_left=None):
"""Produce a left outer join between left and right clauses.
This is the "outer join" version of the :func:`_orm.join` function,
featuring the same behavior except that an OUTER JOIN is generated.
See that function's documentatio... | def outerjoin(left, right, onclause=None, full=False, join_to_left=None):
| """Produce a left outer join between left and right clauses.
This is the "outer join" version of the :func:`_orm.join` function,
featuring the same behavior except that an OUTER JOIN is generated.
See that function's documentation for other usage details.
"""
return _ORMJoin(left, right, oncla... | _left`` parameter is deprecated, and will be removed
in a future release. The parameter has no effect.
"""
return _ORMJoin(left, right, onclause, isouter, full)
def outerjoin(left, right, onclause=None, full=False, join_to_left=None):
| 64 | 64 | 97 | 20 | 44 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | outerjoin | outerjoin | 1,835 | 1,843 | 1,835 | 1,835 | fd581764dd1092341bcf400b3a752c5b40995243 | bigcode/the-stack | train |
508bd1929448947ff95bb765 | train | function | def with_polymorphic(
base,
classes,
selectable=False,
flat=False,
polymorphic_on=None,
aliased=False,
innerjoin=False,
_use_mapper_path=False,
_existing_alias=None,
):
"""Produce an :class:`.AliasedClass` construct which specifies
columns for descendant mappers of the given ... | def with_polymorphic(
base,
classes,
selectable=False,
flat=False,
polymorphic_on=None,
aliased=False,
innerjoin=False,
_use_mapper_path=False,
_existing_alias=None,
):
| """Produce an :class:`.AliasedClass` construct which specifies
columns for descendant mappers of the given base.
Using this method will ensure that each descendant mapper's
tables are included in the FROM clause, and will allow filter()
criterion to be used against those tables. The resulting
... | )
Above, functions on ``aggregated_unit_price`` which refer to
``.price`` will return the
``func.sum(UnitPrice.price).label('price')`` column, as it is
matched on the name "price". Ordinarily, the "price" function
wouldn't have any "column correspondence" to the actual
``UnitPrice.price`... | 256 | 256 | 959 | 50 | 206 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | with_polymorphic | with_polymorphic | 1,334 | 1,436 | 1,334 | 1,344 | 169591606a5ae0add57888622804477d7bbcab72 | bigcode/the-stack | train |
a9c01f6e49199a9a0e7e2434 | train | class | class AliasedInsp(
ORMEntityColumnsClauseRole,
ORMFromClauseRole,
sql_base.MemoizedHasCacheKey,
InspectionAttr,
):
"""Provide an inspection interface for an
:class:`.AliasedClass` object.
The :class:`.AliasedInsp` object is returned
given an :class:`.AliasedClass` using the
:func:`_... | class AliasedInsp(
ORMEntityColumnsClauseRole,
ORMFromClauseRole,
sql_base.MemoizedHasCacheKey,
InspectionAttr,
):
| """Provide an inspection interface for an
:class:`.AliasedClass` object.
The :class:`.AliasedInsp` object is returned
given an :class:`.AliasedClass` using the
:func:`_sa.inspect` function::
from sqlalchemy import inspect
from sqlalchemy.orm import aliased
my_alias = alias... | .ext.serializer extension
attr = getattr(mapped_class, key)
if hasattr(attr, "__call__") and hasattr(attr, "__self__"):
return types.MethodType(attr.__func__, self)
# attribute is a descriptor, that will be invoked against a
# "self"; so invoke the descriptor against this se... | 256 | 256 | 2,097 | 34 | 222 | vyonna6519/pitches | virtual/lib/python3.8/site-packages/sqlalchemy/orm/util.py | Python | AliasedInsp | AliasedInsp | 608 | 895 | 608 | 613 | 468b7b12970e296a4233d3ec6a3d554705dca5cd | bigcode/the-stack | train |
0c453121ae4d12b7679041f7 | train | class | class TestXGraphBasePass(unittest.TestCase):
xgraph_factory = XGraphFactory()
def test_xgraph_factory(self):
xlayers = [
XLayer(
name='in1',
type=['Input'],
bottoms=[],
tops=['conv1'],
targets=[]
)... | class TestXGraphBasePass(unittest.TestCase):
| xgraph_factory = XGraphFactory()
def test_xgraph_factory(self):
xlayers = [
XLayer(
name='in1',
type=['Input'],
bottoms=[],
tops=['conv1'],
targets=[]
),
XLayer(
name='in... | X.bottoms,
tops = X.tops
)
new_Xs.append(new_X)
else:
new_Xs.append(X)
return new_Xs
new_xgraph = self._replace_layer_pass(
xgraph = xgraph,
replace_func = replace_func
)
retur... | 80 | 82 | 276 | 10 | 69 | pankajdarak-xlnx/pyxir | tests/unit/graph/passing/test_base_pass.py | Python | TestXGraphBasePass | TestXGraphBasePass | 63 | 109 | 63 | 64 | fcb8936d0f28d362485e462df96bd01a20d9495d | bigcode/the-stack | train |
ad780e114cace7001b1d2212 | train | class | class TestPass(XGraphBasePass):
def execute(self, xgraph):
def replace_func(bottom_Xs, X, top_Xs):
""" Replace Convolution with Pooling operation """
new_Xs = []
if X.type[0] in ['Convolution']:
new_X = defaultXLayer()
new_X = new_X._rep... | class TestPass(XGraphBasePass):
| def execute(self, xgraph):
def replace_func(bottom_Xs, X, top_Xs):
""" Replace Convolution with Pooling operation """
new_Xs = []
if X.type[0] in ['Convolution']:
new_X = defaultXLayer()
new_X = new_X._replace(
type = ... | xir.graph.layer.xlayer import XLayer, ConvData, defaultXLayer
from pyxir.graph.xgraph_factory import XGraphFactory
from pyxir.graph.xgraph import XGraph
from pyxir.graph.passing.base_pass import XGraphBasePass
class TestPass(XGraphBasePass):
| 64 | 64 | 174 | 8 | 55 | pankajdarak-xlnx/pyxir | tests/unit/graph/passing/test_base_pass.py | Python | TestPass | TestPass | 30 | 59 | 30 | 31 | 0ec1d3da306bc43baaeb60bd4fa4f17368432af4 | bigcode/the-stack | train |
a533f3fee6f14cd8acfd69a7 | train | function | def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
| def masked_softmax_cross_entropy(preds, labels, mask):
| """Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
| import tensorflow as tf
def masked_softmax_cross_entropy(preds, labels, mask):
| 18 | 64 | 78 | 13 | 4 | zean-wen/gcn | gcn/metrics.py | Python | masked_softmax_cross_entropy | masked_softmax_cross_entropy | 4 | 10 | 4 | 4 | 2bd7e92b03fbafaea5b46e5d810ece2e96723a7e | bigcode/the-stack | train |
fc8e7140f5e77e7a3ba01792 | train | function | def masked_accuracy(preds, labels, mask):
"""Accuracy with masking."""
correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))
accuracy_all = tf.cast(correct_prediction, tf.float32)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
accuracy_all *= mask
retu... | def masked_accuracy(preds, labels, mask):
| """Accuracy with masking."""
correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))
accuracy_all = tf.cast(correct_prediction, tf.float32)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
accuracy_all *= mask
return tf.reduce_mean(accuracy_all)
| loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
def masked_accuracy(preds, labels, mask):
| 64 | 64 | 85 | 10 | 54 | zean-wen/gcn | gcn/metrics.py | Python | masked_accuracy | masked_accuracy | 13 | 20 | 13 | 13 | b052f7348a86b6798897f128f9697e9aa2685b0b | bigcode/the-stack | train |
8def62f5e563d461209dcd45 | train | function | @login_manager.user_loader
def load_user(user_id):
return User.query.filter_by(id=int(user_id)).first()
| @login_manager.user_loader
def load_user(user_id):
| return User.query.filter_by(id=int(user_id)).first()
| = LoginManager()
login_blueprint = Blueprint('login', __name__)
auth = OAuth()
secure_url_for = lambda x: url_for(x, _external=True, _scheme='https' if not current_app.debug else 'http')
dummy_enabled = False
@login_manager.user_loader
def load_user(user_id):
| 64 | 64 | 24 | 11 | 52 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | load_user | load_user | 16 | 18 | 16 | 17 | 01b048db2bee20b338edfe4559e7f9fcead807be | bigcode/the-stack | train |
a68b1ad5f38cb3507363ed82 | train | function | @login_blueprint.route("/logout")
def logout():
logout_user()
request_source = request.args.get('from') if request.args.get('from') is not None else "auth"
return render_template('logged-out.html', request_source=request_source)
| @login_blueprint.route("/logout")
def logout():
| logout_user()
request_source = request.args.get('from') if request.args.get('from') is not None else "auth"
return render_template('logged-out.html', request_source=request_source)
| '] = request.args.get('next', None)
return render_template('login.html', enable_dummy=dummy_enabled)
@login_blueprint.route("/demand_pebble")
@login_required
def demand_pebble():
return render_template('pebble.html')
@login_blueprint.route("/logout")
def logout():
| 64 | 64 | 52 | 10 | 54 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | logout | logout | 32 | 36 | 32 | 33 | 109fd40f5093345ea030cdc9ebd03a92890173f4 | bigcode/the-stack | train |
71739ff57e9392d5edb50710 | train | function | @login_blueprint.route("/demand_pebble")
@login_required
def demand_pebble():
return render_template('pebble.html')
| @login_blueprint.route("/demand_pebble")
@login_required
def demand_pebble():
| return render_template('pebble.html')
| _by(id=int(user_id)).first()
@login_blueprint.route("/")
def login():
session['next'] = request.args.get('next', None)
return render_template('login.html', enable_dummy=dummy_enabled)
@login_blueprint.route("/demand_pebble")
@login_required
def demand_pebble():
| 64 | 64 | 30 | 20 | 44 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | demand_pebble | demand_pebble | 27 | 30 | 27 | 29 | b4d383821abe3a9fa6a67b05ecb016aa58b7ab0f | bigcode/the-stack | train |
40aa00784c50eb6fa4a02316 | train | function | def redirect_next():
next_url = session.get('next') or '/'
if next_url.startswith('//') or ':' in next_url:
next_url = '/'
return redirect(next_url)
| def redirect_next():
| next_url = session.get('next') or '/'
if next_url.startswith('//') or ':' in next_url:
next_url = '/'
return redirect(next_url)
| render_template('pebble.html')
@login_blueprint.route("/logout")
def logout():
logout_user()
request_source = request.args.get('from') if request.args.get('from') is not None else "auth"
return render_template('logged-out.html', request_source=request_source)
def redirect_next():
| 64 | 64 | 39 | 4 | 60 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | redirect_next | redirect_next | 38 | 42 | 38 | 38 | 8982eba7e896225578442aca1325ccde4cc270c4 | bigcode/the-stack | train |
5ec6b696567ec6f7b3e2d822 | train | function | def prepare_state():
session['oauth_state'] = secrets.token_urlsafe()
| def prepare_state():
| session['oauth_state'] = secrets.token_urlsafe()
| is not None else "auth"
return render_template('logged-out.html', request_source=request_source)
def redirect_next():
next_url = session.get('next') or '/'
if next_url.startswith('//') or ':' in next_url:
next_url = '/'
return redirect(next_url)
def prepare_state():
| 64 | 64 | 16 | 4 | 60 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | prepare_state | prepare_state | 45 | 46 | 45 | 45 | 76b0b028496e43c3a8f3d9d0dd5fd6466ba3702d | bigcode/the-stack | train |
6f38e6edffe000f092682786 | train | function | def get_state():
return session['oauth_state']
| def get_state():
| return session['oauth_state']
| request_source=request_source)
def redirect_next():
next_url = session.get('next') or '/'
if next_url.startswith('//') or ':' in next_url:
next_url = '/'
return redirect(next_url)
def prepare_state():
session['oauth_state'] = secrets.token_urlsafe()
def get_state():
| 64 | 64 | 11 | 4 | 60 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | get_state | get_state | 49 | 50 | 49 | 49 | 96ec49995d2853c403af39bce565458c3b808499 | bigcode/the-stack | train |
81415f6890578930cfb542f9 | train | function | @login_blueprint.route("/")
def login():
session['next'] = request.args.get('next', None)
return render_template('login.html', enable_dummy=dummy_enabled)
| @login_blueprint.route("/")
def login():
| session['next'] = request.args.get('next', None)
return render_template('login.html', enable_dummy=dummy_enabled)
| _for = lambda x: url_for(x, _external=True, _scheme='https' if not current_app.debug else 'http')
dummy_enabled = False
@login_manager.user_loader
def load_user(user_id):
return User.query.filter_by(id=int(user_id)).first()
@login_blueprint.route("/")
def login():
| 64 | 64 | 36 | 8 | 56 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | login | login | 21 | 24 | 21 | 22 | e07f936f8707d5e64189e9491caeb05fd04a8929 | bigcode/the-stack | train |
88d5cb0ad6544535b02b403d | train | function | def init_app(app):
global dummy_enabled
if app.env == 'development':
dummy_enabled = True
app.register_blueprint(login_blueprint, url_prefix='/auth')
login_manager.login_view = 'login.login'
login_manager.init_app(app)
auth.init_app(app)
app.extensions['csrf'].exempt(login_blueprint)... | def init_app(app):
| global dummy_enabled
if app.env == 'development':
dummy_enabled = True
app.register_blueprint(login_blueprint, url_prefix='/auth')
login_manager.login_view = 'login.login'
login_manager.init_app(app)
auth.init_app(app)
app.extensions['csrf'].exempt(login_blueprint)
| idp_user_id=idp_user_id)
db.session.add(identity)
else:
print('Known identity')
if user != identity.user:
return render_template('already-associated.html')
db.session.commit()
login_user(identity.user, remember=True)
return redirect_next()
def ini... | 64 | 64 | 73 | 5 | 59 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | init_app | init_app | 92 | 100 | 92 | 92 | a61073e7a1bd17fff22676ecc6031c1116e3d712 | bigcode/the-stack | train |
8ab4452c0f2eba370479b28a | train | function | def validate_state():
if 'oauth_state' not in session:
abort(Response(render_template('login-timed-out.html'), 401))
expected_state = session['oauth_state']
if expected_state is None:
abort(Response(render_template('login-timed-out.html'), 401))
del session['oauth_state']
if request.... | def validate_state():
| if 'oauth_state' not in session:
abort(Response(render_template('login-timed-out.html'), 401))
expected_state = session['oauth_state']
if expected_state is None:
abort(Response(render_template('login-timed-out.html'), 401))
del session['oauth_state']
if request.args.get('state') != e... | _url = session.get('next') or '/'
if next_url.startswith('//') or ':' in next_url:
next_url = '/'
return redirect(next_url)
def prepare_state():
session['oauth_state'] = secrets.token_urlsafe()
def get_state():
return session['oauth_state']
def validate_state():
| 64 | 64 | 94 | 4 | 60 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | validate_state | validate_state | 53 | 61 | 53 | 53 | 5b90274aa49760ed9866c4707b3430df00323362 | bigcode/the-stack | train |
41deaeb403a2b3377f4b37c7 | train | function | def complete_auth_flow(idp_name, idp_user_id, user_name, user_email):
user = current_user._get_current_object()
identity = UserIdentity.query.filter_by(idp=idp_name, idp_user_id=idp_user_id).one_or_none()
if not user.is_authenticated:
if identity is not None:
user = identity.user
... | def complete_auth_flow(idp_name, idp_user_id, user_name, user_email):
| user = current_user._get_current_object()
identity = UserIdentity.query.filter_by(idp=idp_name, idp_user_id=idp_user_id).one_or_none()
if not user.is_authenticated:
if identity is not None:
user = identity.user
else:
if user_email is None or user_email == '':
... | if expected_state is None:
abort(Response(render_template('login-timed-out.html'), 401))
del session['oauth_state']
if request.args.get('state') != expected_state:
abort(Response(render_template('login-timed-out.html'), 401))
def complete_auth_flow(idp_name, idp_user_id, user_name, user_email):... | 74 | 74 | 247 | 19 | 55 | pebble-dev/rebble-auth-py | auth/login/base.py | Python | complete_auth_flow | complete_auth_flow | 64 | 89 | 64 | 64 | dae680923b4ea17d49c9afadd5c5a7bfb10ca483 | bigcode/the-stack | train |
84a1f67923fff41269b8575c | train | function | def main(argv=None):
parser = argparse.ArgumentParser(description='ML Trainer')
parser.add_argument(
'--project',
help='The GCS project to use',
required=True)
parser.add_argument(
'--gcs-path',
help='The GCS path to the trained model. The path should end with "../export/<model-name>... | def main(argv=None):
| parser = argparse.ArgumentParser(description='ML Trainer')
parser.add_argument(
'--project',
help='The GCS project to use',
required=True)
parser.add_argument(
'--gcs-path',
help='The GCS path to the trained model. The path should end with "../export/<model-name>".',
required=T... | 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASI... | 146 | 146 | 489 | 5 | 140 | bhjeong-goldenplanet/automl | ml/kubeflow-pipelines/components/cmle/deploy/deploy_model.py | Python | main | main | 24 | 87 | 24 | 24 | bfe4ae6a3aef11e33099785ed28eae2eee22a14d | bigcode/the-stack | train |
65bf43dd24d88df7725e944f | train | function | def generate_config(_network, _dataset, _loss, _auxloss=None):
for k, v in loss[_loss].items():
config[k] = v
if k in default:
default[k] = v
for k, v in network[_network].items():
config[k] = v
if k in default:
default[k] = v
for k, v in dataset[_dataset].items():
... | def generate_config(_network, _dataset, _loss, _auxloss=None):
| for k, v in loss[_loss].items():
config[k] = v
if k in default:
default[k] = v
for k, v in network[_network].items():
config[k] = v
if k in default:
default[k] = v
for k, v in dataset[_dataset].items():
config[k] = v
if k in default:
default[k] = v... | 'git'
auxloss.git.center_alpha = 0.05
auxloss.git.git_alpha = 0.01
auxloss.git.git_beta = 0.1
auxloss.git.git_p = 0.001
def generate_config(_network, _dataset, _loss, _auxloss=None):
| 64 | 64 | 187 | 17 | 46 | paranoidai/Fairface-Recognition-Solution | train/config.py | Python | generate_config | generate_config | 319 | 341 | 319 | 319 | 7a66a7b8f269815e9291efccd95ba1963c334478 | bigcode/the-stack | train |
16c461b28d12e0034800948d | train | function | def plot_prediction_experiment_comparison(m, s, exp, name='', filename=None):
""" Plot visualization of predicted and ground-truth data
Plot a visualization for a single prediction and ground-truth.
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc... | def plot_prediction_experiment_comparison(m, s, exp, name='', filename=None):
| """ Plot visualization of predicted and ground-truth data
Plot a visualization for a single prediction and ground-truth.
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc.
args:
M_pred: ndarray (H, N_batch, D) or (H, D) predicted mean ... | is None:
filename_i = None
else:
filename_i = filename + '_e_%d' % (ind)
plot_prediction_experiment_comparison(M_traj, S_traj, exp, name_i,
filename_i)
def plot_prediction_experiment_comparison(m, s, exp, name='', filename=None):
| 69 | 69 | 232 | 18 | 51 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | plot_prediction_experiment_comparison | plot_prediction_experiment_comparison | 164 | 188 | 164 | 164 | 697d4255b3eed9a506c434323f755e7c5f5d75d8 | bigcode/the-stack | train |
294fc981302c6f2cb5fef864 | train | function | def plot_predictions_experiments_comparison(M_pred, S_pred, exps, name='',
filename=None):
""" Plot visualization of predicted and ground-truth data
Individual visualizations are plotted for each element of the lists of
predicted and ground-truth experimental dat... | def plot_predictions_experiments_comparison(M_pred, S_pred, exps, name='',
filename=None):
| """ Plot visualization of predicted and ground-truth data
Individual visualizations are plotted for each element of the lists of
predicted and ground-truth experimental data.
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc.
args:
... | , 1, i + y_dim + 1)
plt.plot(t, u[:, i], color=colors[0])
plt.xlabel('Time t, dt = %f, H = %d' % (dt, H))
plt.ylabel(u_label[i])
# Save figure to file if requested
if filename is not None:
plt.savefig(filename + '.png')
plt.savefig(filename + '.svg')
plt.close(fi... | 125 | 125 | 418 | 24 | 101 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | plot_predictions_experiments_comparison | plot_predictions_experiments_comparison | 126 | 161 | 126 | 127 | d4bbb7b4facbb985d55a328156307314162a5f1e | bigcode/the-stack | train |
30ca85cf736ea6116c0ab844 | train | function | def plot_experiment(exp, name='', filename=None):
""" Plot single experiment's input/output data
args:
exp: dict, experimental data and configuration
name: string (optional), figure name
filename: string (optional), path + filename if figure should be saved
"""
u_dim, y_dim = e... | def plot_experiment(exp, name='', filename=None):
| """ Plot single experiment's input/output data
args:
exp: dict, experimental data and configuration
name: string (optional), figure name
filename: string (optional), path + filename if figure should be saved
"""
u_dim, y_dim = exp['u_dim'], exp['y_dim']
dt = exp['dt']
u... | of %d' % (ind+1, len(exps))
else:
name_i = 'Exp.: %d of %d' % (ind+1, len(exps))
# Filename if applicable
if filename is None:
filename_i = None
else:
filename_i = filename + '_e_%d' % (ind)
# Plot single experiment
plot_experiment(exp... | 105 | 105 | 350 | 11 | 94 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | plot_experiment | plot_experiment | 80 | 123 | 80 | 80 | b1033d2b57d5fd425726a08587cca2133994c790 | bigcode/the-stack | train |
8e0511c910c1960d05fa6c27 | train | function | def plot_task(task, filename=None):
""" Plot training and test experiments of the given task
args:
task: task object holding lists of training and test experiments
filename: prefix (path + nameprefix) to save plots
"""
train_exps = task.train_exps
test_exps = task.test_exps
task... | def plot_task(task, filename=None):
| """ Plot training and test experiments of the given task
args:
task: task object holding lists of training and test experiments
filename: prefix (path + nameprefix) to save plots
"""
train_exps = task.train_exps
test_exps = task.test_exps
task_name = task.name
# Figure name... | .6740, 0.1880],
[0.3010, 0.7450, 0.9330],
[0.6350, 0.0780, 0.1840]]*2
colors = matlab_colors
def plot_task(task, filename=None):
| 64 | 64 | 197 | 8 | 55 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | plot_task | plot_task | 26 | 49 | 26 | 26 | 02cf220a34dc9408e67ba9c2a1b570b68912b884 | bigcode/the-stack | train |
8039f987af9f2cae4e282bfc | train | function | def _plot_prediction_experiment_comparison_sampled(m, exp, name='',
filename=None):
""" Plot visualization of predicted samples and ground-truth data
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc.
... | def _plot_prediction_experiment_comparison_sampled(m, exp, name='',
filename=None):
| """ Plot visualization of predicted samples and ground-truth data
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc.
args:
m: ndarray (H, N_batch, D) samples of predicted mean value.
exp: dict, experimental data and configuration
... | gt = exp['u'][:, i]
plt.subplot(u_dim + y_dim, 1, i + y_dim + 1)
plt.plot(t, gt, label='Exp., In %d' % i, color=colors[0])
plt.plot(t, mean, label='Pred., In %d' % i, color=colors[1])
plt.fill_between(t, mean - 2*error, mean + 2*error,
facecolor=colors[1], alph... | 205 | 205 | 685 | 21 | 184 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | _plot_prediction_experiment_comparison_sampled | _plot_prediction_experiment_comparison_sampled | 254 | 321 | 254 | 255 | 35e82959e2f2affda8912086e795cf8af74ac014 | bigcode/the-stack | train |
90d8127f296fd3fdab02249f | train | function | def plot_experiments(exps, name='', filename=None):
""" Plot individual visualizations for a list of experiments
For each experiment in the list, a visualization of system input/output
data is shown.
If a filename is provided, the figure is saved to disc.
A figure name can be provided.
args:
... | def plot_experiments(exps, name='', filename=None):
| """ Plot individual visualizations for a list of experiments
For each experiment in the list, a visualization of system input/output
data is shown.
If a filename is provided, the figure is saved to disc.
A figure name can be provided.
args:
exps: list of experiments
name: strin... | + '_t_%s_test' % task_name
else:
filename_train = None
filename_test = None
plot_experiments(train_exps, name_train, filename_train)
plot_experiments(test_exps, name_test, filename_test)
def plot_experiments(exps, name='', filename=None):
| 69 | 69 | 230 | 13 | 56 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | plot_experiments | plot_experiments | 52 | 77 | 52 | 52 | cc9764b1c8b6736761e347054a286138414f761e | bigcode/the-stack | train |
987a9de85c71af271401577b | train | function | def _plot_prediction_experiment_comparison_gaussian(m, s, exp, name='',
filename=None):
""" Plot visualization of Gaussian prediction and ground-truth data
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to ... | def _plot_prediction_experiment_comparison_gaussian(m, s, exp, name='',
filename=None):
| """ Plot visualization of Gaussian prediction and ground-truth data
A figurename prefix can be given.
If a filename-prefix is given, the individual plots are saved to disc.
args:
m: ndarray (H, D) predicted mean
s: ndarray (H, D, D) predicted variance
exp: dict, experimental da... | , N_batch, D) or (H, D) predicted mean value.
S_pred: ndarray (H, N_batch, D, D) or (H, D, D) predicted variance.
exp: dict, experimental data and configuration
name: string (optional) figure tile prefix
filename: string (optional) path and filename if plot should be saved
"""
if... | 177 | 177 | 592 | 23 | 154 | boschresearch/PR-SSM | prssm/utils/plotting_functions.py | Python | _plot_prediction_experiment_comparison_gaussian | _plot_prediction_experiment_comparison_gaussian | 191 | 251 | 191 | 192 | 449a89a56a0b11d8fd6a50beeb4835062a86cdb0 | bigcode/the-stack | train |
794e00d1713018295e5e2e9a | train | class | class Migration(migrations.Migration):
dependencies = [
('classes', '0003_auto_20210117_2058'),
]
operations = [
migrations.AlterField(
model_name='class',
name='cost',
field=models.DecimalField(decimal_places=2, max_digits=8),
),
migrati... | class Migration(migrations.Migration):
| dependencies = [
('classes', '0003_auto_20210117_2058'),
]
operations = [
migrations.AlterField(
model_name='class',
name='cost',
field=models.DecimalField(decimal_places=2, max_digits=8),
),
migrations.AlterField(
model_name='... | # Generated by Django 3.1.5 on 2021-01-18 03:51
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
| 43 | 64 | 122 | 7 | 35 | Savimaster/Prodigy | prodigy_backend/classes/migrations/0004_auto_20210118_0351.py | Python | Migration | Migration | 7 | 24 | 7 | 8 | f6d5865ec5f28ca04e52ff5004f4fa734fbc5691 | bigcode/the-stack | train |
4aec089c5eb5599594069138 | train | function | def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
| def get_db():
| if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
| DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
| 63 | 64 | 26 | 4 | 59 | mark-solo/flskr-tdd-ttrl | app.py | Python | get_db | get_db | 27 | 30 | 27 | 27 | 846b7256f020e7d541e4809d91cd7d67b8120245 | bigcode/the-stack | train |
b88d67d4d4c9102ca0da380b | train | function | @app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
... | @app.route('/login', methods=['GET', 'POST'])
def login():
| error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('in... | ()
# views stuff
@app.route('/')
def index():
db = get_db()
cur = db.execute('SELECT * FROM entries ORDER BY id DESC')
entries = cur.fetchall()
return render_template('index.html', entries=entries)
@app.route('/login', methods=['GET', 'POST'])
def login():
| 63 | 64 | 106 | 15 | 48 | mark-solo/flskr-tdd-ttrl | app.py | Python | login | login | 45 | 57 | 45 | 46 | 2058104501a73e47d26e9005a73e5bd73625c122 | bigcode/the-stack | train |
f414ee94cf9be3807c666745 | train | function | @app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
| @app.teardown_appcontext
def close_db(error):
| if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
| _resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
| 64 | 64 | 25 | 11 | 52 | mark-solo/flskr-tdd-ttrl | app.py | Python | close_db | close_db | 32 | 35 | 32 | 33 | 70f5b184aebe15e5c1155f4f0ce97d5b95e97a11 | bigcode/the-stack | train |
31c8be4b3b2bf3040e55351f | train | function | @app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('index'))
| @app.route('/logout')
def logout():
| session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('index'))
| password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
| 63 | 64 | 31 | 8 | 55 | mark-solo/flskr-tdd-ttrl | app.py | Python | logout | logout | 59 | 63 | 59 | 60 | 40a562add95c3cbb7ada97b212e44d25285ebdb0 | bigcode/the-stack | train |
d678be9128153ec151df48a2 | train | function | @app.route('/delete/<post_id>', methods=['GET'])
def delete_entry(post_id):
result = {'status': 0, 'message': 'Error'}
try:
db = get_db()
db.execute('DELETE FROM entries WHERE id='+post_id)
db.commit()
result = {'status': 1, 'message': 'Post deleted'}
except Exception as e:
result = {'status': 0, 'message'... | @app.route('/delete/<post_id>', methods=['GET'])
def delete_entry(post_id):
| result = {'status': 0, 'message': 'Error'}
try:
db = get_db()
db.execute('DELETE FROM entries WHERE id='+post_id)
db.commit()
result = {'status': 1, 'message': 'Post deleted'}
except Exception as e:
result = {'status': 0, 'message': repr(e)}
return jsonify(result)
| INTO entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']]
)
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('index'))
@app.route('/delete/<post_id>', methods=['GET'])
def delete_entry(post_id):
| 63 | 64 | 98 | 18 | 45 | mark-solo/flskr-tdd-ttrl | app.py | Python | delete_entry | delete_entry | 78 | 89 | 78 | 79 | 1cb56d5ec432ab8757751e277e46a95ad7623a63 | bigcode/the-stack | train |
c776fdd59e6a24ee8ebd9189 | train | function | def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
| def init_db():
| with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
| 'my_precious'
USERNAME = 'admin'
PASSWORD = 'admin'
app = Flask(__name__)
app.config.from_object(__name__)
# DB stuff
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
| 64 | 64 | 45 | 4 | 59 | mark-solo/flskr-tdd-ttrl | app.py | Python | init_db | init_db | 20 | 25 | 20 | 20 | b8f6e71a759224db99ac38ef2ac9d0049912a283 | bigcode/the-stack | train |
46183a7f5b119d35dd1db9d0 | train | function | def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
| def connect_db():
| rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
| , \
abort, render_template, flash, jsonify
DATABASE = 'flaskr.db'
DEBUG = True
SECRET_KEY = 'my_precious'
USERNAME = 'admin'
PASSWORD = 'admin'
app = Flask(__name__)
app.config.from_object(__name__)
# DB stuff
def connect_db():
| 64 | 64 | 27 | 4 | 59 | mark-solo/flskr-tdd-ttrl | app.py | Python | connect_db | connect_db | 15 | 18 | 15 | 15 | eeeb03ad6bcf1e513ab3587e9d98efb78cb1a781 | bigcode/the-stack | train |
406f1cfe0327ba4a81023d8e | train | function | @app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute(
'INSERT INTO entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']]
)
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('inde... | @app.route('/add', methods=['POST'])
def add_entry():
| if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute(
'INSERT INTO entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']]
)
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('index'))
| return redirect(url_for('index'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('index'))
@app.route('/add', methods=['POST'])
def add_entry():
| 63 | 64 | 84 | 13 | 50 | mark-solo/flskr-tdd-ttrl | app.py | Python | add_entry | add_entry | 65 | 76 | 65 | 66 | d340111da643468a17c1b6c68972a72722160a59 | bigcode/the-stack | train |
9a7b4479e55baad60fc7a095 | train | function | @app.route('/')
def index():
db = get_db()
cur = db.execute('SELECT * FROM entries ORDER BY id DESC')
entries = cur.fetchall()
return render_template('index.html', entries=entries)
| @app.route('/')
def index():
| db = get_db()
cur = db.execute('SELECT * FROM entries ORDER BY id DESC')
entries = cur.fetchall()
return render_template('index.html', entries=entries)
| ()
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
# views stuff
@app.route('/')
def index():
| 64 | 64 | 42 | 6 | 57 | mark-solo/flskr-tdd-ttrl | app.py | Python | index | index | 38 | 43 | 38 | 39 | 066925a174131fe429c4c0800f3adee28ecef8f6 | bigcode/the-stack | train |
fc572139d8af9c277008a09a | train | class | class Migration(migrations.Migration):
dependencies = [
('home', '0018_auto_20190423_1027'),
]
operations = [
migrations.CreateModel(
name='Slide',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='I... | class Migration(migrations.Migration):
| dependencies = [
('home', '0018_auto_20190423_1027'),
]
operations = [
migrations.CreateModel(
name='Slide',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slide_img', mode... | # Generated by Django 2.2 on 2019-04-23 09:28
from django.db import migrations, models
class Migration(migrations.Migration):
| 36 | 64 | 114 | 7 | 28 | mohammedmosaad400/django-upperegypt | home/migrations/0019_slide.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 258431fd7103ed257637120e441118355a369056 | bigcode/the-stack | train |
4393f8c30f92e28aace614bd | train | class | class DiscriminatorLoss(BaseLayer):
def __init__(self):
super(DiscriminatorLoss, self).__init__()
self.softplus_fake = nn.Softplus()
self.softplus_real = nn.Softplus()
def forward(self, fake_scores_out, real_scores_out):
loss = torch.mean(self.softplus_fake(fake_scores_out)) + t... | class DiscriminatorLoss(BaseLayer):
| def __init__(self):
super(DiscriminatorLoss, self).__init__()
self.softplus_fake = nn.Softplus()
self.softplus_real = nn.Softplus()
def forward(self, fake_scores_out, real_scores_out):
loss = torch.mean(self.softplus_fake(fake_scores_out)) + torch.mean(self.softplus_real(-real_s... | import numpy as np
import torch.nn as nn
import torch
from base_layer import BaseLayer
class DiscriminatorLoss(BaseLayer):
| 28 | 64 | 89 | 7 | 20 | tms-byte/gan_sample | chapter7/stylegan2_pytorch/discriminator_loss.py | Python | DiscriminatorLoss | DiscriminatorLoss | 6 | 14 | 6 | 6 | c6be71c24edc281c94bf5844e8e1edfe2cd8186e | bigcode/the-stack | train |
93351917e353acad5012e044 | train | class | class EventsV1beta1Api(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiC... | class EventsV1beta1Api(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client ... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.12.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
i... | 111 | 256 | 13,775 | 9 | 101 | anemerovsky-essextec/python | kubernetes/client/apis/events_v1beta1_api.py | Python | EventsV1beta1Api | EventsV1beta1Api | 26 | 1,093 | 26 | 26 | a96cc0e9d4d86fb338f91ca025222cf7db6d13a2 | bigcode/the-stack | train |
23e2a3607f4afe3051d899e6 | train | function | def return_type_repr(signature) -> str:
return_type = signature.return_annotation
if return_type is inspect.Parameter.empty:
return 'torch.Tensor'
elif str(return_type)[:6] != '<class':
return sanitize(str(return_type))
elif return_type.__module__ == 'builtins':
return return_typ... | def return_type_repr(signature) -> str:
| return_type = signature.return_annotation
if return_type is inspect.Parameter.empty:
return 'torch.Tensor'
elif str(return_type)[:6] != '<class':
return sanitize(str(return_type))
elif return_type.__module__ == 'builtins':
return return_type.__name__
else:
return f'{r... | )[1:-1]).replace(', [', '[')
return type_repr
def param_type_repr(param) -> str:
if param.annotation is inspect.Parameter.empty:
return 'torch.Tensor'
return sanitize(re.split(r': | =', str(param))[1])
def return_type_repr(signature) -> str:
| 64 | 64 | 90 | 9 | 55 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | return_type_repr | return_type_repr | 59 | 68 | 59 | 59 | 43206ceb8a7401f5209fe51149ad3732a70d6407 | bigcode/the-stack | train |
da78586443b136700fcef5fc | train | function | def resolve_types(arg_types: Dict[str, str],
return_type_repr: str) -> List[Tuple[List[str], str]]:
out = []
for type_repr in arg_types.values():
if type_repr[:5] == 'Union':
out.append(split_types_repr(type_repr[6:-1]))
else:
out.append([type_repr])
... | def resolve_types(arg_types: Dict[str, str],
return_type_repr: str) -> List[Tuple[List[str], str]]:
| out = []
for type_repr in arg_types.values():
if type_repr[:5] == 'Union':
out.append(split_types_repr(type_repr[6:-1]))
else:
out.append([type_repr])
return [(x, return_type_repr) for x in product(*out)]
| signature.parameters
arg_types = OrderedDict((k, param_type_repr(v)) for k, v in ps.items())
return [(arg_types, return_type_repr(signature))]
def resolve_types(arg_types: Dict[str, str],
return_type_repr: str) -> List[Tuple[List[str], str]]:
| 63 | 64 | 90 | 27 | 37 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | resolve_types | resolve_types | 98 | 106 | 98 | 99 | 6aaecf7537e258a0a3921d657d068354b521565a | bigcode/the-stack | train |
3977b410ed3cec4c73863d54 | train | function | def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
source = inspect.getsource(func)
signature = inspect.signature(func)
# Parse `# type: (...) -> ...` annotation. Note that it is allowed to pass
# multiple `# type:` annotations in `forward()`.
iterator = re.finditer(r'#\s*type:\s*... | def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
| source = inspect.getsource(func)
signature = inspect.signature(func)
# Parse `# type: (...) -> ...` annotation. Note that it is allowed to pass
# multiple `# type:` annotations in `forward()`.
iterator = re.finditer(r'#\s*type:\s*\((.*)\)\s*->\s*(.*)\s*\n', source)
matches = list(iterator)
... | elif str(return_type)[:6] != '<class':
return sanitize(str(return_type))
elif return_type.__module__ == 'builtins':
return return_type.__name__
else:
return f'{return_type.__module__}.{return_type.__name__}'
def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
| 76 | 77 | 258 | 19 | 57 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | parse_types | parse_types | 71 | 95 | 71 | 71 | bf155dcb0bbe1e66a09ef8fe8386ee9edd6a5f5d | bigcode/the-stack | train |
f7af447afdced68a7776bb26 | train | function | def split_types_repr(types_repr: str) -> List[str]:
out = []
i = depth = 0
for j, char in enumerate(types_repr):
if char == '[':
depth += 1
elif char == ']':
depth -= 1
elif char == ',' and depth == 0:
out.append(types_repr[i:j].strip())
... | def split_types_repr(types_repr: str) -> List[str]:
| out = []
i = depth = 0
for j, char in enumerate(types_repr):
if char == '[':
depth += 1
elif char == ']':
depth -= 1
elif char == ',' and depth == 0:
out.append(types_repr[i:j].strip())
i = j + 1
out.append(types_repr[i:].strip())
... | import re
import inspect
import pyparsing as pp
from itertools import product
from collections import OrderedDict
from typing import Callable, Tuple, Dict, List
def split_types_repr(types_repr: str) -> List[str]:
| 48 | 64 | 101 | 13 | 34 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | split_types_repr | split_types_repr | 9 | 21 | 9 | 9 | 6cef48940e55880492904421760a860b28785bb6 | bigcode/the-stack | train |
4e250e27a2140d3b0eb72ecf | train | function | def sanitize(type_repr: str):
type_repr = type_repr.replace('typing.', '')
type_repr = type_repr.replace('torch_sparse.tensor.', '')
type_repr = type_repr.replace('Adj', 'Union[Tensor, SparseTensor]')
# Replace `Union[..., NoneType]` by `Optional[...]`.
sexp = pp.nestedExpr(opener='[', closer=']')
... | def sanitize(type_repr: str):
| type_repr = type_repr.replace('typing.', '')
type_repr = type_repr.replace('torch_sparse.tensor.', '')
type_repr = type_repr.replace('Adj', 'Union[Tensor, SparseTensor]')
# Replace `Union[..., NoneType]` by `Optional[...]`.
sexp = pp.nestedExpr(opener='[', closer=']')
tree = sexp.parseString(f'... | = depth = 0
for j, char in enumerate(types_repr):
if char == '[':
depth += 1
elif char == ']':
depth -= 1
elif char == ',' and depth == 0:
out.append(types_repr[i:j].strip())
i = j + 1
out.append(types_repr[i:].strip())
return out
def ... | 89 | 89 | 297 | 7 | 81 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | sanitize | sanitize | 24 | 50 | 24 | 24 | aa3a3c5c47d1e458b04ad0ffd5bf47514f66657d | bigcode/the-stack | train |
5c3577f20438cf1f0146fbcc | train | function | def param_type_repr(param) -> str:
if param.annotation is inspect.Parameter.empty:
return 'torch.Tensor'
return sanitize(re.split(r': | =', str(param))[1])
| def param_type_repr(param) -> str:
| if param.annotation is inspect.Parameter.empty:
return 'torch.Tensor'
return sanitize(re.split(r': | =', str(param))[1])
| tree[i] = union_to_optional_(e)
return tree
tree = union_to_optional_(tree)
type_repr = re.sub(r'\'|\"', '', str(tree)[1:-1]).replace(', [', '[')
return type_repr
def param_type_repr(param) -> str:
| 64 | 64 | 39 | 9 | 54 | KiddoZhu/pytorch_geometric | torch_geometric/nn/conv/utils/typing.py | Python | param_type_repr | param_type_repr | 53 | 56 | 53 | 53 | 12739d9b89b1ee988db54c53790ac8043b4d8359 | bigcode/the-stack | train |
fe66d029216e6a95917007ee | train | class | class TemporaryDirectory(object):
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in ... | class TemporaryDirectory(object):
| """Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed.
"""
def _... | return old_mkdtemp(**kwargs)
else:
from tempfile import mkdtemp
# XXX backport: ResourceWarning was added in Python 3.2.
# For earlier versions, fall back to RuntimeWarning instead.
_ResourceWarning = RuntimeWarning if sys.version_info < (3, 2) else ResourceWarning
class TemporaryDirectory(object):
| 72 | 72 | 241 | 5 | 66 | bopopescu/localstackvenv | venv/lib/python2.7/site-packages/backports/tempfile.py | Python | TemporaryDirectory | TemporaryDirectory | 40 | 75 | 40 | 40 | 6d16b14f6fb4eae5ad7276199fe05a18eaf03fd1 | bigcode/the-stack | train |
1a453658dce7678a18e80f7b | train | class | class emSensors(object):
def __init__(self, mode=None):
logging.info('Sensors')
self.mode = mode
self.altitude = None
self.temperature = None
self.sealevelpressure = None
self.pressure = None
thread = Thread(target=self.emSensorsPoller)
thread.star... | class emSensors(object):
| def __init__(self, mode=None):
logging.info('Sensors')
self.mode = mode
self.altitude = None
self.temperature = None
self.sealevelpressure = None
self.pressure = None
thread = Thread(target=self.emSensorsPoller)
thread.start()
def emSensorsPoll... | #! /usr/bin/python
import logging
import os
from sensors.emaltitude import emAltitudeGet
from sensors.empressure import emPressureGet
from sensors.emsealevelpressure import emSeaLevelPressureGet
from sensors.emtemperature import emTemperatureGet
from threading import Thread
class emSensors(object):
| 64 | 64 | 203 | 5 | 58 | xe1gyq/EekMex | spacecraft/subsystems/emsensors.py | Python | emSensors | emSensors | 12 | 38 | 12 | 13 | 9b1a68d62ae62905af53057e04502547134f9db4 | bigcode/the-stack | train |
c7b83f3b60485a5853a04d80 | train | function | @pytest.mark.asyncio
async def test_set_address(account_factory):
_, account, registry = account_factory
await signer.send_transaction(account, registry.contract_address, 'set_L1_address', [L1_ADDRESS])
execution_info = await registry.get_L1_address(account.contract_address).call()
assert execution_inf... | @pytest.mark.asyncio
async def test_set_address(account_factory):
| _, account, registry = account_factory
await signer.send_transaction(account, registry.contract_address, 'set_L1_address', [L1_ADDRESS])
execution_info = await registry.get_L1_address(account.contract_address).call()
assert execution_info.result == (L1_ADDRESS,)
| ("openzeppelin/account/AddressRegistry.cairo")
)
account = await starknet.deploy(
contract_path("openzeppelin/account/Account.cairo"),
constructor_calldata=[signer.public_key]
)
return starknet, account, registry
@pytest.mark.asyncio
async def test_set_address(account_factory):
| 64 | 64 | 71 | 13 | 50 | pscott/cairo-contracts | tests/account/test_AddressRegistry.py | Python | test_set_address | test_set_address | 25 | 31 | 25 | 26 | d1942880551b7e34aeeb23c8e4573cc369cf6b2e | bigcode/the-stack | train |
def4e2e19690501d4c864326 | train | function | @pytest.mark.asyncio
async def test_update_address(account_factory):
_, account, registry = account_factory
await signer.send_transaction(account, registry.contract_address, 'set_L1_address', [L1_ADDRESS])
execution_info = await registry.get_L1_address(account.contract_address).call()
assert execution... | @pytest.mark.asyncio
async def test_update_address(account_factory):
| _, account, registry = account_factory
await signer.send_transaction(account, registry.contract_address, 'set_L1_address', [L1_ADDRESS])
execution_info = await registry.get_L1_address(account.contract_address).call()
assert execution_info.result == (L1_ADDRESS,)
# set new address
await signer... |
await signer.send_transaction(account, registry.contract_address, 'set_L1_address', [L1_ADDRESS])
execution_info = await registry.get_L1_address(account.contract_address).call()
assert execution_info.result == (L1_ADDRESS,)
@pytest.mark.asyncio
async def test_update_address(account_factory):
| 63 | 64 | 127 | 13 | 50 | pscott/cairo-contracts | tests/account/test_AddressRegistry.py | Python | test_update_address | test_update_address | 34 | 47 | 34 | 35 | 31c04a49c6523c74199e3b4040223cca9197baca | bigcode/the-stack | train |
271277229c38016bd68f99bf | train | function | @pytest.fixture(scope='module')
async def account_factory():
starknet = await Starknet.empty()
registry = await starknet.deploy(
contract_path("openzeppelin/account/AddressRegistry.cairo")
)
account = await starknet.deploy(
contract_path("openzeppelin/account/Account.cairo"),
con... | @pytest.fixture(scope='module')
async def account_factory():
| starknet = await Starknet.empty()
registry = await starknet.deploy(
contract_path("openzeppelin/account/AddressRegistry.cairo")
)
account = await starknet.deploy(
contract_path("openzeppelin/account/Account.cairo"),
constructor_calldata=[signer.public_key]
)
return stark... | d5aF5bf1D1762F925BDADdC4201F984
ANOTHER_ADDRESS = 0xd9e1ce17f2641f24ae83637ab66a2cca9c378b9f
@pytest.fixture(scope='module')
async def account_factory():
| 64 | 64 | 82 | 11 | 52 | pscott/cairo-contracts | tests/account/test_AddressRegistry.py | Python | account_factory | account_factory | 11 | 22 | 11 | 12 | b27180890909577f88f3ff9a9a188fc528c48197 | bigcode/the-stack | train |
22a189f0a4fda3dbfffc2012 | train | class | class BaseDNNGameModel(BaseGameModel):
model = None
def __init__(self, long_name, short_name, abbreviation):
BaseGameModel.__init__(self, long_name, short_name, abbreviation)
def move(self, environment):
if self.model is None:
self.model = DeepNeuralNetModel(Constants.MODEL_DI... | class BaseDNNGameModel(BaseGameModel):
| model = None
def __init__(self, long_name, short_name, abbreviation):
BaseGameModel.__init__(self, long_name, short_name, abbreviation)
def move(self, environment):
if self.model is None:
self.model = DeepNeuralNetModel(Constants.MODEL_DIRECTORY + "dnn/")
BaseGameModel.... |
import random
import copy
import numpy as np
from statistics import mean
from game.models.base_game_model import BaseGameModel
from tf_models.dnn_model import DeepNeuralNetModel
from game.helpers.constants import Constants
class BaseDNNGameModel(BaseGameModel):
| 58 | 64 | 88 | 10 | 47 | emcxcme/slitherin | game/models/domain_specific/dnn_ai_solver.py | Python | BaseDNNGameModel | BaseDNNGameModel | 11 | 21 | 11 | 12 | 5413a330475e87223326ac87235a081add9b693e | bigcode/the-stack | train |
87ee921e5177d6ac218f5719 | train | class | class DNNSolver(BaseDNNGameModel):
def __init__(self):
BaseDNNGameModel.__init__(self, "Deep Neural Net", "deep_neural_net", "dnn")
def move(self, environment):
BaseDNNGameModel.move(self, environment)
predicted_action = self._predict(environment, self.model)
return predicted_a... | class DNNSolver(BaseDNNGameModel):
| def __init__(self):
BaseDNNGameModel.__init__(self, "Deep Neural Net", "deep_neural_net", "dnn")
def move(self, environment):
BaseDNNGameModel.move(self, environment)
predicted_action = self._predict(environment, self.model)
return predicted_action
| .__init__(self, long_name, short_name, abbreviation)
def move(self, environment):
if self.model is None:
self.model = DeepNeuralNetModel(Constants.MODEL_DIRECTORY + "dnn/")
BaseGameModel.move(self, environment)
class DNNSolver(BaseDNNGameModel):
| 64 | 64 | 78 | 10 | 54 | emcxcme/slitherin | game/models/domain_specific/dnn_ai_solver.py | Python | DNNSolver | DNNSolver | 24 | 32 | 24 | 25 | fd2efad11834cf3e37c40a6770a1a2cd7e2a11cd | bigcode/the-stack | train |
fb6707d492cf5d0959fd1409 | train | class | class DNNTrainer(BaseDNNGameModel):
def __init__(self):
BaseDNNGameModel.__init__(self, "Deep Neural Net", "deep_neural_net_trainer", "dnnt")
def move(self, environment):
BaseDNNGameModel.move(self, environment)
print ("")
print (self.long_name + ": train and test")
pri... | class DNNTrainer(BaseDNNGameModel):
| def __init__(self):
BaseDNNGameModel.__init__(self, "Deep Neural Net", "deep_neural_net_trainer", "dnnt")
def move(self, environment):
BaseDNNGameModel.move(self, environment)
print ("")
print (self.long_name + ": train and test")
print ("")
while True:
... | import random
import copy
import numpy as np
from statistics import mean
from game.models.base_game_model import BaseGameModel
from tf_models.dnn_model import DeepNeuralNetModel
from game.helpers.constants import Constants
class BaseDNNGameModel(BaseGameModel):
model = None
def __init__(self, long_name, sho... | 223 | 223 | 744 | 10 | 212 | emcxcme/slitherin | game/models/domain_specific/dnn_ai_solver.py | Python | DNNTrainer | DNNTrainer | 35 | 117 | 35 | 36 | f762951dd17a18bcd14a710703bc27ff14643b5c | bigcode/the-stack | train |
096e35f1bd3f5e04cd6077fb | train | function | def usage():
""" Print the usage of the script """
print_version()
print ("Usage: python3 " + os.path.basename(sys.argv[0]) + " [options]")
print ("Options:")
print (" -h, --help Displays this help message")
print (" -v, --version Displays the version of the script")
print (" ... | def usage():
| """ Print the usage of the script """
print_version()
print ("Usage: python3 " + os.path.basename(sys.argv[0]) + " [options]")
print ("Options:")
print (" -h, --help Displays this help message")
print (" -v, --version Displays the version of the script")
print (" -V, --verbos... | from . import log
from . import version
PROGRAM_NAME = "AstroReduce"
CURRENT_DATE_TIME = datetime.datetime.now().strftime("%y-%m-%dT%H:%M:%S")
def print_version():
""" Print the version of the script """
print (PROGRAM_NAME + ": v" + version.__version__)
def usage():
| 71 | 71 | 238 | 3 | 68 | zstuartp/astro-reduce | astroreduce/main.py | Python | usage | usage | 22 | 38 | 22 | 22 | 4dee765446b9dedc2b80dd48071eaef634ac2a32 | bigcode/the-stack | train |
ce605d8cdcbfb6d0284baa81 | train | function | def print_version():
""" Print the version of the script """
print (PROGRAM_NAME + ": v" + version.__version__)
| def print_version():
| """ Print the version of the script """
print (PROGRAM_NAME + ": v" + version.__version__)
| import os
import sys
from . import env
from . import flatfield as ff
from . import log
from . import version
PROGRAM_NAME = "AstroReduce"
CURRENT_DATE_TIME = datetime.datetime.now().strftime("%y-%m-%dT%H:%M:%S")
def print_version():
| 64 | 64 | 27 | 4 | 60 | zstuartp/astro-reduce | astroreduce/main.py | Python | print_version | print_version | 17 | 19 | 17 | 17 | da3a3d65b3d831c938127224277174349e5ef240 | bigcode/the-stack | train |
615b8f744009393aaa7860c3 | train | function | def main():
light_dir = "./lights"
dark_dir = "./darks"
mdark_dir = "./mdarks"
flat_dir = "./flats"
mflat_dir = "./mflats"
output_dir = "./output"
level = 0
OPTIONS = "vhiVl:d:D:f:F:o:L:k"
LONG_OPTIONS = [
"version",
"help",
"verbose",
"light-dir",
... | def main():
| light_dir = "./lights"
dark_dir = "./darks"
mdark_dir = "./mdarks"
flat_dir = "./flats"
mflat_dir = "./mflats"
output_dir = "./output"
level = 0
OPTIONS = "vhiVl:d:D:f:F:o:L:k"
LONG_OPTIONS = [
"version",
"help",
"verbose",
"light-dir",
"dark-... | l light_dir Uncorrected images directory")
print (" -o output_dir Correct images output directory")
print (" -d dark_dir Raw dark images directory")
print (" -D mdark_dir Master dark images output directory")
print (" -f flat_dir Raw flat images directory")
print (" -F... | 143 | 143 | 478 | 3 | 140 | zstuartp/astro-reduce | astroreduce/main.py | Python | main | main | 41 | 111 | 41 | 41 | b3426e1bf392295ee1e36f353578073aec02f318 | bigcode/the-stack | train |
c43b894ac9b2ccb81e72684e | train | function | def run(ceph_cluster, **kw):
try:
start = timeit.default_timer()
tc = "11334"
file_name = "file"
log.info("Running cephfs %s test case" % (tc))
fs_util = FsUtils(ceph_cluster)
config = kw.get("config")
build = config.get("build", config.get("rhbuild"))
... | def run(ceph_cluster, **kw):
| try:
start = timeit.default_timer()
tc = "11334"
file_name = "file"
log.info("Running cephfs %s test case" % (tc))
fs_util = FsUtils(ceph_cluster)
config = kw.get("config")
build = config.get("build", config.get("rhbuild"))
client_info, rc = fs_util.ge... | import timeit
import traceback
from ceph.ceph import CommandFailed
from tests.cephfs.cephfs_utils import FsUtils
from utility.log import Log
log = Log(__name__)
def run(ceph_cluster, **kw):
| 51 | 256 | 1,676 | 10 | 41 | julpark-rh/cephci | tests/cephfs/CEPH-11334.py | Python | run | run | 11 | 181 | 11 | 11 | f7dc411066573097ee56d1e4c44aa1c18eb4281a | bigcode/the-stack | train |
7b8cd745abcce65fedfd5db9 | train | function | @option(Configs.transformer)
def transformer_c(c: Configs):
"""
Initialize the [configurable transformer](../configs.html) encoder for our autoregressive model.
"""
tc = TransformerConfigs()
tc.n_src_vocab = c.n_tokens
tc.n_tgt_vocab = c.n_tokens
return tc
| @option(Configs.transformer)
def transformer_c(c: Configs):
| """
Initialize the [configurable transformer](../configs.html) encoder for our autoregressive model.
"""
tc = TransformerConfigs()
tc.n_src_vocab = c.n_tokens
tc.n_tgt_vocab = c.n_tokens
return tc
| gressive_model(c: Configs):
"""
Initialize the auto-regressive model
"""
m = AutoregressiveModel(c.transformer.src_embed, c.transformer.encoder, c.transformer.generator)
return m.to(c.device)
@option(Configs.transformer)
def transformer_c(c: Configs):
| 64 | 64 | 69 | 15 | 49 | BioGeek/annotated_deep_learning_paper_implementations | labml_nn/transformers/glu_variants/experiment.py | Python | transformer_c | transformer_c | 74 | 83 | 74 | 75 | c5132a069cf413b3e5e947109e529b0a404661a9 | bigcode/the-stack | train |
ce17442cea2443823d9a8632 | train | class | class Configs(NLPAutoRegressionConfigs):
"""
## Configurations
The default configs can and will be over-ridden when we start the experiment
"""
transformer: TransformerConfigs
model: AutoregressiveModel
| class Configs(NLPAutoRegressionConfigs):
| """
## Configurations
The default configs can and will be over-ridden when we start the experiment
"""
transformer: TransformerConfigs
model: AutoregressiveModel
| (len(src)).to(src.device)
# Embed the tokens (`src`) and run it through the the transformer
res = self.encoder(self.src_embed(src), self.src_mask)
# Generate logits of the next token
return self.generator(res), None
class Configs(NLPAutoRegressionConfigs):
| 64 | 64 | 50 | 10 | 53 | BioGeek/annotated_deep_learning_paper_implementations | labml_nn/transformers/glu_variants/experiment.py | Python | Configs | Configs | 54 | 62 | 54 | 54 | b04cf0415061086b84cf633b68ead8a71b52fa8f | bigcode/the-stack | train |
5484aa5edf58838ab108edfa | train | function | @option(Configs.model)
def autoregressive_model(c: Configs):
"""
Initialize the auto-regressive model
"""
m = AutoregressiveModel(c.transformer.src_embed, c.transformer.encoder, c.transformer.generator)
return m.to(c.device)
| @option(Configs.model)
def autoregressive_model(c: Configs):
| """
Initialize the auto-regressive model
"""
m = AutoregressiveModel(c.transformer.src_embed, c.transformer.encoder, c.transformer.generator)
return m.to(c.device)
| Configs(NLPAutoRegressionConfigs):
"""
## Configurations
The default configs can and will be over-ridden when we start the experiment
"""
transformer: TransformerConfigs
model: AutoregressiveModel
@option(Configs.model)
def autoregressive_model(c: Configs):
| 64 | 64 | 57 | 15 | 48 | BioGeek/annotated_deep_learning_paper_implementations | labml_nn/transformers/glu_variants/experiment.py | Python | autoregressive_model | autoregressive_model | 65 | 71 | 65 | 66 | f1353839bed31148501d2a0ccf4d4815976db167 | bigcode/the-stack | train |
30a56fadd7a514408a7aa176 | train | function | def main():
# Create experiment
experiment.create(name="glu_variants")
# Create configs
conf = Configs()
# Load configurations
experiment.configs(conf,
# A dictionary of configurations to override
{'tokenizer': 'character',
'p... | def main():
# Create experiment
| experiment.create(name="glu_variants")
# Create configs
conf = Configs()
# Load configurations
experiment.configs(conf,
# A dictionary of configurations to override
{'tokenizer': 'character',
'prompt_separator': '',
... | c.transformer.encoder, c.transformer.generator)
return m.to(c.device)
@option(Configs.transformer)
def transformer_c(c: Configs):
"""
Initialize the [configurable transformer](../configs.html) encoder for our autoregressive model.
"""
tc = TransformerConfigs()
tc.n_src_vocab = c.n_tokens
... | 94 | 94 | 314 | 8 | 85 | BioGeek/annotated_deep_learning_paper_implementations | labml_nn/transformers/glu_variants/experiment.py | Python | main | main | 86 | 129 | 86 | 87 | b69a448f96f5a16c2cd2f5705b941c7343a1ca48 | bigcode/the-stack | train |
6e8b0d1a61eb3abed0050f5b | train | class | class AutoregressiveModel(Module):
"""
## Auto regressive model
"""
def __init__(self, src_embed: Module, encoder: Encoder, generator: Generator):
super().__init__()
# Token embedding module
self.src_embed = src_embed
# Transformer based encoder
self.encoder = en... | class AutoregressiveModel(Module):
| """
## Auto regressive model
"""
def __init__(self, src_embed: Module, encoder: Encoder, generator: Generator):
super().__init__()
# Token embedding module
self.src_embed = src_embed
# Transformer based encoder
self.encoder = encoder
# Next token generati... | .utils.pytorch import get_modules
from labml_helpers.module import Module
from labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs
from labml_nn.transformers import Encoder, Generator, TransformerConfigs
from labml_nn.transformers.utils import subsequent_mask
class AutoregressiveModel(Module):
| 66 | 66 | 220 | 7 | 58 | BioGeek/annotated_deep_learning_paper_implementations | labml_nn/transformers/glu_variants/experiment.py | Python | AutoregressiveModel | AutoregressiveModel | 27 | 51 | 27 | 27 | f16175d3987315af657136c815698ea740c78ba2 | bigcode/the-stack | train |
56042574ac51aa9fa0dea96d | train | function | def test_linkedit(tmp_path):
original = lief.parse(get_sample('MachO/MachO64_x86-64_binary_id.bin'))
output = f"{tmp_path}/test_id.bin"
config = lief.MachO.Builder.config_t()
config.linkedit = False
lief.MachO.Builder.write(original, output, config)
modified = lief.parse(output)
checked,... | def test_linkedit(tmp_path):
| original = lief.parse(get_sample('MachO/MachO64_x86-64_binary_id.bin'))
output = f"{tmp_path}/test_id.bin"
config = lief.MachO.Builder.config_t()
config.linkedit = False
lief.MachO.Builder.write(original, output, config)
modified = lief.parse(output)
checked, err = lief.MachO.check_layou... | #!/usr/bin/env python
import lief
from utils import get_sample, is_apple_m1, is_osx, sign, chmod_exe, is_github_ci
lief.logging.set_level(lief.logging.LOGGING_LEVEL.INFO)
def test_linkedit(tmp_path):
| 55 | 64 | 99 | 7 | 48 | rafael-santiago/LIEF | tests/macho/test_builder_config.py | Python | test_linkedit | test_linkedit | 8 | 20 | 8 | 8 | a0c3f8313a423e845e9ae69116d94e9556c550d6 | bigcode/the-stack | train |
20974d4ead58eb4c55a2d1f2 | train | function | def test_fat(tmp_path):
original = lief.parse(get_sample('MachO/FAT_MachO_x86-x86-64-binary_fatall.bin'))
output = f"{tmp_path}/test_fatall.bin"
config = lief.MachO.Builder.config_t()
config.linkedit = False
lief.MachO.Builder.write(original, output, config)
modified = lief.parse(output)
... | def test_fat(tmp_path):
| original = lief.parse(get_sample('MachO/FAT_MachO_x86-x86-64-binary_fatall.bin'))
output = f"{tmp_path}/test_fatall.bin"
config = lief.MachO.Builder.config_t()
config.linkedit = False
lief.MachO.Builder.write(original, output, config)
modified = lief.parse(output)
checked, err = lief.Mac... | config = lief.MachO.Builder.config_t()
config.linkedit = False
lief.MachO.Builder.write(original, output, config)
modified = lief.parse(output)
checked, err = lief.MachO.check_layout(modified)
assert checked, err
def test_fat(tmp_path):
| 64 | 64 | 107 | 7 | 56 | rafael-santiago/LIEF | tests/macho/test_builder_config.py | Python | test_fat | test_fat | 22 | 34 | 22 | 22 | 918289e1cf037228f6667f4665aee32fe1a76275 | bigcode/the-stack | train |
f4712266d7952cab5039e1b9 | train | class | class Box():
'''
Class defining a square on the coordinate system via a center point and
half of square width.
'''
def __init__(self, center, half_width, half_height = None):
'''
Construct a Box object.
Args:
center: a Point type specifying the center of the sq... | class Box():
| '''
Class defining a square on the coordinate system via a center point and
half of square width.
'''
def __init__(self, center, half_width, half_height = None):
'''
Construct a Box object.
Args:
center: a Point type specifying the center of the square
... | 2.y)/2)
half_width = abs(p1.x-center.x)
half_height = abs(p1.y-center.y)
return center, half_width, half_height
class Point():
'''
Represents an (x,y) coordinate point on a grid.
'''
def __init__(self, x, y):
'''
Constructs a coordinate Point.
Args:
x: ... | 155 | 155 | 518 | 3 | 152 | husmen/Trajectory-Mapping | server/prquadtree.py | Python | Box | Box | 38 | 105 | 38 | 38 | e46ff1d77d90c0eaa98b740039e3bc95833694d3 | bigcode/the-stack | train |
c110569d8043e9266e041fd8 | train | function | def box_from_2p(p1,p2):
''' docstring '''
center = Point((p1.x+p2.x)/2, (p1.y+p2.y)/2)
half_width = abs(p1.x-center.x)
half_height = abs(p1.y-center.y)
return center, half_width, half_height
| def box_from_2p(p1,p2):
| ''' docstring '''
center = Point((p1.x+p2.x)/2, (p1.y+p2.y)/2)
half_width = abs(p1.x-center.x)
half_height = abs(p1.y-center.y)
return center, half_width, half_height
| '''
Implementation of a Point Range Quadtree.
'''
from math import sqrt
from random import uniform
def box_from_2p(p1,p2):
| 32 | 64 | 72 | 11 | 20 | husmen/Trajectory-Mapping | server/prquadtree.py | Python | box_from_2p | box_from_2p | 8 | 13 | 8 | 8 | e53369f2bd2a4f698020414110dc74d954e34746 | bigcode/the-stack | train |
e773738b8f938fbcb80fd96b | train | class | class Point():
'''
Represents an (x,y) coordinate point on a grid.
'''
def __init__(self, x, y):
'''
Constructs a coordinate Point.
Args:
x: x-position
y: y-position
'''
self.x = float(x)
self.y = float(y)
def __str__(self):
... | class Point():
| '''
Represents an (x,y) coordinate point on a grid.
'''
def __init__(self, x, y):
'''
Constructs a coordinate Point.
Args:
x: x-position
y: y-position
'''
self.x = float(x)
self.y = float(y)
def __str__(self):
'''
... | ''' docstring '''
center = Point((p1.x+p2.x)/2, (p1.y+p2.y)/2)
half_width = abs(p1.x-center.x)
half_height = abs(p1.y-center.y)
return center, half_width, half_height
class Point():
| 64 | 64 | 115 | 3 | 60 | husmen/Trajectory-Mapping | server/prquadtree.py | Python | Point | Point | 15 | 36 | 15 | 15 | cfb0ae6f5b0daa443a972de17ec4e95996a7558d | bigcode/the-stack | train |
a3be939886b91b0adbb6f523 | train | class | class PRQuadTree():
'''
Class representing a Point Range Quadtree.
'''
# number of coordinate points to store per node
QT_NODE_CAPACITY = 1
def __init__(self, box):
'''
Constructs a PR Quadtree given an initial square.
Args:
box: a Box representing init... | class PRQuadTree():
| '''
Class representing a Point Range Quadtree.
'''
# number of coordinate points to store per node
QT_NODE_CAPACITY = 1
def __init__(self, box):
'''
Constructs a PR Quadtree given an initial square.
Args:
box: a Box representing initial square
'... | _bound):
return True
return False
def intersect(self, other_box):
'''
Checks if the provided box/square intersects with this square.
Args:
other_box: another Box object
Returns:
A boolean indicating if the two intersect anywhere
... | 256 | 256 | 1,215 | 5 | 250 | husmen/Trajectory-Mapping | server/prquadtree.py | Python | PRQuadTree | PRQuadTree | 107 | 286 | 107 | 107 | 8412d5da29ef455acae034c6fc0b8570a0c99072 | bigcode/the-stack | train |
82f19232862ff9e3bbe596b2 | train | function | def rust_wasm_bindgen_repositories(register_default_toolchain = True):
"""Declare dependencies needed for [rust_wasm_bindgen](#rust_wasm_bindgen).
Args:
register_default_toolchain (bool, optional): If True, the default [rust_wasm_bindgen_toolchain](#rust_wasm_bindgen_toolchain)
(`@rules_rus... | def rust_wasm_bindgen_repositories(register_default_toolchain = True):
| """Declare dependencies needed for [rust_wasm_bindgen](#rust_wasm_bindgen).
Args:
register_default_toolchain (bool, optional): If True, the default [rust_wasm_bindgen_toolchain](#rust_wasm_bindgen_toolchain)
(`@rules_rust//wasm_bindgen:default_wasm_bindgen_toolchain`) is registered. This to... | _defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("//wasm_bindgen/raze:crates.bzl", "rules_rust_wasm_bindgen_fetch_remote_crates")
# buildifier: disable=unnamed-macro
def rust_wasm_bindgen_repositories(register_default_toolchain = True):
| 84 | 84 | 283 | 15 | 68 | yesudeep/rules_rust | wasm_bindgen/repositories.bzl | Python | rust_wasm_bindgen_repositories | rust_wasm_bindgen_repositories | 21 | 40 | 21 | 21 | 6ffd1d6fc105e9ee712cc4dff500d1d2946c066a | bigcode/the-stack | train |
86fd1ea52aec5e47061816cf | train | class | class Observation(object):
time = datetime(1970, 1, 1, tzinfo=tzutc())
temperature = None
wind_speed = None
wind_gust = None
wind_direction = None
humidity = None
cloud_coverage = None
pressure = None
dew_point = None
precipitation = None
precipitation_1h = None
weather_s... | class Observation(object):
| time = datetime(1970, 1, 1, tzinfo=tzutc())
temperature = None
wind_speed = None
wind_gust = None
wind_direction = None
humidity = None
cloud_coverage = None
pressure = None
dew_point = None
precipitation = None
precipitation_1h = None
weather_symbol = None
radiation_... | import os
from datetime import datetime
from dateutil.tz import tzutc
from dateutil.parser import parse as parse_dt
class Observation(object):
| 31 | 202 | 675 | 4 | 26 | kipe/fmi | fmi/observation.py | Python | Observation | Observation | 7 | 88 | 7 | 7 | f694cc0ea2af7b0556ee87e178ab113aa7c32682 | bigcode/the-stack | train |
44c8b493c4716673e24929f3 | train | class | class Forecast(Observation):
pass
| class Forecast(Observation):
| pass
| def as_influx_measurement(self):
return {
'time': self.time,
'fields': {
key: value
for key, value in self.__dict__.items()
if key not in ['time'] and value is not None
}
}
class Forecast(Observation):
| 64 | 64 | 8 | 5 | 59 | kipe/fmi | fmi/observation.py | Python | Forecast | Forecast | 91 | 92 | 91 | 91 | 6e53c9c2a7a6b2886bf5dd48bbec85dd50f2bcd3 | bigcode/the-stack | train |
4dbf1de764db1fb9eb14b138 | train | function | def test_web_summarygrid(browser, basic_html):
html_dir, dvcs = basic_html
with tools.preview(html_dir) as base_url:
get_with_retry(browser, base_url)
assert browser.title == 'airspeed velocity of an unladen asv'
# Open a graph display
browser.find_element_by_link_text('params... | def test_web_summarygrid(browser, basic_html):
| html_dir, dvcs = basic_html
with tools.preview(html_dir) as base_url:
get_with_retry(browser, base_url)
assert browser.title == 'airspeed velocity of an unladen asv'
# Open a graph display
browser.find_element_by_link_text('params_examples.track_param').click()
# Veri... | tools.run_asv_with_conf(conf, 'publish')
shutil.rmtree(join(tmpdir, 'env'))
finally:
os.chdir(cwd)
util.write_json(join(tmpdir, 'tag.json'), [asv.__version__])
return conf.html_dir, dvcs
def test_web_summarygrid(browser, basic_html):
| 70 | 70 | 236 | 10 | 59 | ColCarroll/asv | test/test_web.py | Python | test_web_summarygrid | test_web_summarygrid | 115 | 140 | 115 | 115 | 25c167f679988408e5587b09561c71a6b61c5368 | bigcode/the-stack | train |
df8852dcbc3d5d1994c2f727 | train | function | @pytest.fixture(scope="session")
def basic_html(request):
if hasattr(request.config, 'cache'):
# Cache the generated html, if py.test is new enough to support it
cache_dir = request.config.cache.makedir("asv-test_web-basic_html")
tmpdir = join(six.text_type(cache_dir), 'cached')
if ... | @pytest.fixture(scope="session")
def basic_html(request):
| if hasattr(request.config, 'cache'):
# Cache the generated html, if py.test is new enough to support it
cache_dir = request.config.cache.makedir("asv-test_web-basic_html")
tmpdir = join(six.text_type(cache_dir), 'cached')
if os.path.isdir(tmpdir):
# Cached result found
... | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import re
import shutil
import time
import tempfile
from os.path import join, abspath, dirname
import six
from... | 131 | 222 | 741 | 11 | 119 | ColCarroll/asv | test/test_web.py | Python | basic_html | basic_html | 26 | 112 | 26 | 27 | 8025679823006a160f7cacc9320ec74b71a6bfec | bigcode/the-stack | train |
666d5926dcaeb7ac32c250a4 | train | function | def test_web_regressions(browser, basic_html):
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
html_dir, dvcs = basic_html
bad_commit_hash = dvcs.get_hash('master~9')
browser.s... | def test_web_regressions(browser, basic_html):
| from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
html_dir, dvcs = basic_html
bad_commit_hash = dvcs.get_hash('master~9')
browser.set_window_size(1200, 900)
with tools.previ... | return conf.html_dir, dvcs
def test_web_summarygrid(browser, basic_html):
html_dir, dvcs = basic_html
with tools.preview(html_dir) as base_url:
get_with_retry(browser, base_url)
assert browser.title == 'airspeed velocity of an unladen asv'
# Open a graph display
browser.... | 256 | 256 | 1,090 | 11 | 245 | ColCarroll/asv | test/test_web.py | Python | test_web_regressions | test_web_regressions | 143 | 241 | 143 | 143 | 1bfcf50b4b9f7e45d0b741c348c3bdabb1b0a6d6 | bigcode/the-stack | train |
62122c614c1781d29fbb9125 | train | function | def test_web_summarylist(browser, basic_html):
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceExceptio... | def test_web_summarylist(browser, basic_html):
| from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
ignore_exc = (NoSuchElementException, St... | (table_rows) == 2
# Check that a plot of some sort appears on mouseover. The
# page needs to be scrolled first so that the mouseover popup
# has enough space to appear.
regression_1 = browser.find_element_by_link_text('params_examples.track_find_test(1)')
y = regression_1.loca... | 163 | 163 | 546 | 10 | 153 | ColCarroll/asv | test/test_web.py | Python | test_web_summarylist | test_web_summarylist | 244 | 297 | 244 | 244 | fa06336a55e5ad5dc361f0fa01c936aae0d0812f | bigcode/the-stack | train |
9cd0daac86c1a4cf9ee14a27 | train | function | def decision_step(Rover):
# Implement conditionals to decide what to do given perception data
# Here you're all set up with some basic functionality but you'll need to
# improve on this decision tree to do a good job of navigating autonomously!
# Example:
# Check if we have vision data to make dec... | def decision_step(Rover):
# Implement conditionals to decide what to do given perception data
# Here you're all set up with some basic functionality but you'll need to
# improve on this decision tree to do a good job of navigating autonomously!
# Example:
# Check if we have vision data to make dec... | if Rover.nav_angles is not None:
# Check for Rover.mode status
if Rover.mode == 'forward':
# Check the extent of navigable terrain
if len(Rover.nav_angles) >= Rover.stop_forward:
# If mode is forward, navigable terrain looks good
# and velo... | import numpy as np
# This is where you can build a decision tree for determining throttle, brake and steer
# commands based on the output of the perception_step() function
def decision_step(Rover):
# Implement conditionals to decide what to do given perception data
# Here you're all set up with some basic fu... | 106 | 256 | 1,135 | 70 | 35 | ruspaul013/RoboND-Rover-Project | code/decision.py | Python | decision_step | decision_step | 5 | 107 | 5 | 12 | 90d1e8b4276fe1ff4b1bb8ec1010a30bf2bb2911 | bigcode/the-stack | train |
d5ae13d686b0ba6e75d16be3 | train | class | class FOXIE(AdobePassIE):
_VALID_URL = r"https?://(?:www\.)?fox\.com/watch/(?P<id>[\da-fA-F]+)"
_TESTS = [
{
# clip
"url": "https://www.fox.com/watch/4b765a60490325103ea69888fb2bd4e8/",
"md5": "ebd296fcc41dd4b19f8115d8461a3165",
"info_dict": {
... | class FOXIE(AdobePassIE):
| _VALID_URL = r"https?://(?:www\.)?fox\.com/watch/(?P<id>[\da-fA-F]+)"
_TESTS = [
{
# clip
"url": "https://www.fox.com/watch/4b765a60490325103ea69888fb2bd4e8/",
"md5": "ebd296fcc41dd4b19f8115d8461a3165",
"info_dict": {
"id": "4b765a604903251... | # coding: utf-8
from __future__ import unicode_literals
import json
import uuid
from .adobepass import AdobePassIE
from ..compat import (
compat_HTTPError,
compat_str,
compat_urllib_parse_unquote,
)
from ..utils import (
ExtractorError,
int_or_none,
parse_age_limit,
parse_duration,
try... | 96 | 256 | 1,328 | 8 | 88 | Pagasis/YouTua | youtuatools/extractor/fox.py | Python | FOXIE | FOXIE | 23 | 172 | 23 | 23 | 5eb66e74d45ba29deecccbd0f052c3f12c83b8f9 | bigcode/the-stack | train |
e327827778ed596871e4a6bb | train | function | def Model2Feature(data, net, checkpoint, dim=512, width=224, root=None, nThreads=16, batch_size=100, pool_feature=False, model=None, org_feature=False, args=None):
dataset_name = data
if model is None:
model = models.create(net, dim=dim, pretrained=False)
resume = checkpoint
model.load_s... | def Model2Feature(data, net, checkpoint, dim=512, width=224, root=None, nThreads=16, batch_size=100, pool_feature=False, model=None, org_feature=False, args=None):
| dataset_name = data
if model is None:
model = models.create(net, dim=dim, pretrained=False)
resume = checkpoint
model.load_state_dict(resume['state_dict'], strict=False)
model = torch.nn.DataParallel(model).cuda()
data = dataset.Dataset(data, width=width, root=root, mode="tes... | # coding=utf-8
from __future__ import absolute_import, print_function
import torch
from torch.backends import cudnn
from evaluations import extract_features
import models
from data import dataset
from utils.serialization import load_checkpoint
cudnn.benchmark = True
def Model2Feature(data, net, checkpoint, dim=512, wi... | 101 | 155 | 518 | 45 | 55 | xuefeicao/UDML_SS | Model2Feature.py | Python | Model2Feature | Model2Feature | 13 | 53 | 13 | 13 | 1af1d1918f69497f62305177b010b4bb73767260 | bigcode/the-stack | train |
431a6003c0cac9b276f6f471 | train | function | def unescape(text):
"""Interpolate escape sequences."""
# escape_decode is unofficial/unsupported
# https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
return escape_decode(text.encode('utf-8'))[0].decode('utf-8')
| def unescape(text):
| """Interpolate escape sequences."""
# escape_decode is unofficial/unsupported
# https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
return escape_decode(text.encode('utf-8'))[0].decode('utf-8')
| a banner using a bitmap font
(c) 2019--2021 Rob Hagemans, licence: https://opensource.org/licenses/MIT
"""
import sys
import argparse
import logging
from codecs import escape_decode
import monobit
from monobit.base import pair
def unescape(text):
| 64 | 64 | 63 | 5 | 58 | trevorld/monobit | banner.py | Python | unescape | unescape | 17 | 21 | 17 | 17 | 625f30692dba3871b39ae8fd2ae9a4dd804cc47b | bigcode/the-stack | train |
999e7efd6067d9d1c70cd491 | train | function | def create_private_path_extractor(mqtt_private_path):
def extractor(topic_path):
if topic_path.startswith('~/'):
return '{}/{}'.format(mqtt_private_path, topic_path[2:])
return topic_path
return extractor
| def create_private_path_extractor(mqtt_private_path):
| def extractor(topic_path):
if topic_path.startswith('~/'):
return '{}/{}'.format(mqtt_private_path, topic_path[2:])
return topic_path
return extractor
| = params.get('userdata', {})
if userdata:
client.user_data_set(userdata)
# configure will params
will_params = params.get('will', {})
if will_params:
client.will_set(**will_params)
return client
def create_private_path_extractor(mqtt_private_path):
| 64 | 64 | 50 | 11 | 52 | alvarovillena/mqtt_bridge | src/mqtt_bridge/mqtt_client.py | Python | create_private_path_extractor | create_private_path_extractor | 53 | 58 | 53 | 53 | 772b7a569f7a0a50bdae1aa79a6f9d09c5c05b9e | bigcode/the-stack | train |
06ca18336907c298fdb8c68c | train | function | def default_mqtt_client_factory(params):
u""" MQTT Client factory
:param dict param: configuration parameters
:return mqtt.Client: MQTT Client
"""
# create client
client_params = params.get('client', {})
client = mqtt.Client(**client_params)
# configure tls
tls_params = params.get(... | def default_mqtt_client_factory(params):
| u""" MQTT Client factory
:param dict param: configuration parameters
:return mqtt.Client: MQTT Client
"""
# create client
client_params = params.get('client', {})
client = mqtt.Client(**client_params)
# configure tls
tls_params = params.get('tls', {})
if tls_params:
tls... | # -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
def default_mqtt_client_factory(params):
| 25 | 94 | 314 | 8 | 16 | alvarovillena/mqtt_bridge | src/mqtt_bridge/mqtt_client.py | Python | default_mqtt_client_factory | default_mqtt_client_factory | 5 | 50 | 5 | 5 | b8878f898a2a31030e60543f3f14aa53b1d8aef7 | bigcode/the-stack | train |
8ece4e5d6ca97c20042764cf | train | function | @pytest.fixture(scope='function')
def future(event_loop):
"""Return a future that is used for managing function tests."""
_future = asyncio.Future(loop=event_loop)
return _future
| @pytest.fixture(scope='function')
def future(event_loop):
| """Return a future that is used for managing function tests."""
_future = asyncio.Future(loop=event_loop)
return _future
| AN_CLUSTER_NAME')
if not cluster_name:
raise ValueError('Missing env variable: STAN_CLUSTER_NAME')
await sc.connect(cluster_name, client_id, nats=nc)
yield sc
await sc.close()
await nc.close()
@pytest.fixture(scope='function')
def future(event_loop):
| 64 | 64 | 40 | 11 | 53 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | future | future | 194 | 198 | 194 | 195 | 151499faa317ed364607d93341c1ea3f4faf6c5f | bigcode/the-stack | train |
ee121490b39a9ecaa2d660b6 | train | function | @pytest.fixture
def create_mock_coro(mocker, monkeypatch):
"""Return a mocked coroutine, and optionally patch-it in."""
def _create_mock_patch_coro(to_patch=None):
mock = mocker.Mock()
async def _coro(*args, **kwargs):
return mock(*args, **kwargs)
if to_patch: # <-- may no... | @pytest.fixture
def create_mock_coro(mocker, monkeypatch):
| """Return a mocked coroutine, and optionally patch-it in."""
def _create_mock_patch_coro(to_patch=None):
mock = mocker.Mock()
async def _coro(*args, **kwargs):
return mock(*args, **kwargs)
if to_patch: # <-- may not need/want to patch anything
monkeypatch.setat... | await sc.close()
await nc.close()
@pytest.fixture(scope='function')
def future(event_loop):
"""Return a future that is used for managing function tests."""
_future = asyncio.Future(loop=event_loop)
return _future
@pytest.fixture
def create_mock_coro(mocker, monkeypatch):
| 64 | 64 | 113 | 14 | 49 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | create_mock_coro | create_mock_coro | 201 | 214 | 201 | 202 | 7c1616e2ed4487b0a24e2fe4c0a618848e3fa288 | bigcode/the-stack | train |
7353f2f7be36c15edbe6b98b | train | function | @pytest.fixture(scope='function')
@pytest.mark.asyncio
async def entity_stan(app, event_loop, client_id):
"""Create a stan connection for each function.
Uses environment variables for the cluster name.
"""
nc = Nats()
sc = Stan()
await nc.connect(io_loop=event_loop)
cluster_name = os.gete... | @pytest.fixture(scope='function')
@pytest.mark.asyncio
async def entity_stan(app, event_loop, client_id):
| """Create a stan connection for each function.
Uses environment variables for the cluster name.
"""
nc = Nats()
sc = Stan()
await nc.connect(io_loop=event_loop)
cluster_name = os.getenv('STAN_CLUSTER_NAME')
if not cluster_name:
raise ValueError('Missing env variable: STAN_CLU... | event_loop, name='entity.filing.tester')
await sc.connect(cluster_name, client_id, nats=nc)
yield sc
await sc.close()
await nc.close()
@pytest.fixture(scope='function')
@pytest.mark.asyncio
async def entity_stan(app, event_loop, client_id):
| 64 | 64 | 127 | 24 | 40 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | entity_stan | entity_stan | 169 | 191 | 169 | 171 | 2699c60966a0a0bf37aa891bcf0e3fee0a7736b7 | bigcode/the-stack | train |
a4d5557f3bbab039b80628f2 | train | function | @pytest.fixture(scope='session')
def app():
"""Return a session-wide application configured in TEST mode."""
# _app = create_app('testing')
_app = Flask(__name__)
_app.config.from_object(get_named_config('testing'))
db.init_app(_app)
return _app
| @pytest.fixture(scope='session')
def app():
| """Return a session-wide application configured in TEST mode."""
# _app = create_app('testing')
_app = Flask(__name__)
_app.config.from_object(get_named_config('testing'))
db.init_app(_app)
return _app
| utcnow(monkeypatch):
"""Fixture to return a static time for utcnow()."""
class _Datetime:
@classmethod
def utcnow(cls):
return FROZEN_DATETIME
monkeypatch.setattr(datetime, 'datetime', _Datetime)
@pytest.fixture(scope='session')
def app():
| 64 | 64 | 63 | 9 | 55 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | app | app | 58 | 66 | 58 | 59 | e42fe3ef5f38e11c323c59d925caaf82794e1d40 | bigcode/the-stack | train |
6e881df8ba756be9b73d1366 | train | function | @pytest.fixture(scope='function')
@pytest.mark.asyncio
async def stan(event_loop, client_id):
"""Create a stan connection for each function, to be used in the tests."""
nc = Nats()
sc = Stan()
cluster_name = 'test-cluster'
await nc.connect(io_loop=event_loop, name='entity.filing.tester')
await... | @pytest.fixture(scope='function')
@pytest.mark.asyncio
async def stan(event_loop, client_id):
| """Create a stan connection for each function, to be used in the tests."""
nc = Nats()
sc = Stan()
cluster_name = 'test-cluster'
await nc.connect(io_loop=event_loop, name='entity.filing.tester')
await sc.connect(cluster_name, client_id, nats=nc)
yield sc
await sc.close()
await nc... |
# public_port = docker_services.wait_for_service("nats", 4222)
# dsn = "{docker_services.docker_ip}:{public_port}".format(**locals())
# return dsn
@pytest.fixture(scope='function')
@pytest.mark.asyncio
async def stan(event_loop, client_id):
| 64 | 64 | 104 | 20 | 43 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | stan | stan | 151 | 166 | 151 | 153 | adf3efe70b20554a17b3b96053328d89a73958a3 | bigcode/the-stack | train |
9ce2f9e8828843835b307ab3 | train | function | @pytest.fixture(scope='session')
def client_ctx(app): # pylint: disable=redefined-outer-name
"""Return session-wide Flask test client."""
with app.test_client() as _client:
yield _client
| @pytest.fixture(scope='session')
def client_ctx(app): # pylint: disable=redefined-outer-name
| """Return session-wide Flask test client."""
with app.test_client() as _client:
yield _client
| outer-name
"""Return a session-wide Flask test client."""
return app.test_client()
@pytest.fixture(scope='session')
def jwt():
"""Return a session-wide jwt manager."""
return _jwt
@pytest.fixture(scope='session')
def client_ctx(app): # pylint: disable=redefined-outer-name
| 64 | 64 | 46 | 22 | 41 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | client_ctx | client_ctx | 87 | 91 | 87 | 88 | 995aa8d1495d076e9fd60f236c90e79fcbcf8381 | bigcode/the-stack | train |
2fbf9877bf531071af4ef5ad | train | function | @pytest.fixture(scope='session')
def jwt():
"""Return a session-wide jwt manager."""
return _jwt
| @pytest.fixture(scope='session')
def jwt():
| """Return a session-wide jwt manager."""
return _jwt
| .fixture
def config(app):
"""Return the application config."""
return app.config
@pytest.fixture(scope='session')
def client(app): # pylint: disable=redefined-outer-name
"""Return a session-wide Flask test client."""
return app.test_client()
@pytest.fixture(scope='session')
def jwt():
| 64 | 64 | 23 | 9 | 55 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | jwt | jwt | 81 | 84 | 81 | 82 | 239e52a7a2923d090159acb35a7ac799b6f35209 | bigcode/the-stack | train |
d42b2f6ac55acb0ec7112f07 | train | function | @pytest.fixture(scope='session')
def client(app): # pylint: disable=redefined-outer-name
"""Return a session-wide Flask test client."""
return app.test_client()
| @pytest.fixture(scope='session')
def client(app): # pylint: disable=redefined-outer-name
| """Return a session-wide Flask test client."""
return app.test_client()
| _app.config.from_object(get_named_config('testing'))
db.init_app(_app)
return _app
@pytest.fixture
def config(app):
"""Return the application config."""
return app.config
@pytest.fixture(scope='session')
def client(app): # pylint: disable=redefined-outer-name
| 64 | 64 | 37 | 21 | 42 | rstens/lear | queue_services/entity-pay/tests/conftest.py | Python | client | client | 75 | 78 | 75 | 76 | 7fe928d75e794834ab1cf36968f957c269d0b73f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.