INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Internal helper to retrieve the value for this Property from an entity. | def _retrieve_value(self, entity, default=None):
"""Internal helper to retrieve the value for this Property from an entity.
This returns None if no value is set, or the default argument if
given. For a repeated Property this returns a list if a value is
set, otherwise None. No additional transformati... |
Like _get_base_value () but always returns a list. | def _get_base_value_unwrapped_as_list(self, entity):
"""Like _get_base_value(), but always returns a list.
Returns:
A new list of unwrapped base values. For an unrepeated
property, if the value is missing or None, returns [None]; for a
repeated property, if the original value is missing or N... |
Call _from_base_type () if necessary. | def _opt_call_from_base_type(self, value):
"""Call _from_base_type() if necessary.
If the value is a _BaseValue instance, unwrap it and call all
_from_base_type() methods. Otherwise, return the value
unchanged.
"""
if isinstance(value, _BaseValue):
value = self._call_from_base_type(value... |
Call _to_base_type () if necessary. | def _opt_call_to_base_type(self, value):
"""Call _to_base_type() if necessary.
If the value is a _BaseValue instance, return it unchanged.
Otherwise, call all _validate() and _to_base_type() methods and
wrap it in a _BaseValue instance.
"""
if not isinstance(value, _BaseValue):
value = _B... |
Call all _from_base_type () methods on the value. | def _call_from_base_type(self, value):
"""Call all _from_base_type() methods on the value.
This calls the methods in the reverse method resolution order of
the property's class.
"""
methods = self._find_methods('_from_base_type', reverse=True)
call = self._apply_list(methods)
return call(va... |
Call all _validate () and _to_base_type () methods on the value. | def _call_to_base_type(self, value):
"""Call all _validate() and _to_base_type() methods on the value.
This calls the methods in the method resolution order of the
property's class.
"""
methods = self._find_methods('_validate', '_to_base_type')
call = self._apply_list(methods)
return call(v... |
Call the initial set of _validate () methods. | def _call_shallow_validation(self, value):
"""Call the initial set of _validate() methods.
This is similar to _call_to_base_type() except it only calls
those _validate() methods that can be called without needing to
call _to_base_type().
An example: suppose the class hierarchy is A -> B -> C ->
... |
Compute a list of composable methods. | def _find_methods(cls, *names, **kwds):
"""Compute a list of composable methods.
Because this is a common operation and the class hierarchy is
static, the outcome is cached (assuming that for a particular list
of names the reversed flag is either always on, or always off).
Args:
*names: One ... |
Return a single callable that applies a list of methods to a value. | def _apply_list(self, methods):
"""Return a single callable that applies a list of methods to a value.
If a method returns None, the last value is kept; if it returns
some other value, that replaces the last value. Exceptions are
not caught.
"""
def call(value):
for method in methods:
... |
Apply a function to the property value/ values of a given entity. | def _apply_to_values(self, entity, function):
"""Apply a function to the property value/values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each of the values in the list. The... |
Internal helper to get the value for this Property from an entity. | def _get_value(self, entity):
"""Internal helper to get the value for this Property from an entity.
For a repeated Property this initializes the value to an empty
list if it is not set.
"""
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(... |
Internal helper to delete the value for this Property from an entity. | def _delete_value(self, entity):
"""Internal helper to delete the value for this Property from an entity.
Note that if no value exists this is a no-op; deleted values will
not be serialized but requesting their value will return None (or
an empty list in the case of a repeated Property).
"""
if... |
Internal helper to ask if the entity has a value for this Property. | def _is_initialized(self, entity):
"""Internal helper to ask if the entity has a value for this Property.
This returns False if a value is stored but it is None.
"""
return (not self._required or
((self._has_value(entity) or self._default is not None) and
self._get_value(entity... |
Internal helper to serialize this property to a protocol buffer. | def _serialize(self, entity, pb, prefix='', parent_repeated=False,
projection=None):
"""Internal helper to serialize this property to a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
pb: The protocol buffer, an Enti... |
Internal helper to deserialize this property from a protocol buffer. | def _deserialize(self, entity, p, unused_depth=1):
"""Internal helper to deserialize this property from a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
p: A Property Message object (a protocol buffer).
depth: Optional nesting... |
Internal helper to check this property for specific requirements. | def _check_property(self, rest=None, require_indexed=True):
"""Internal helper to check this property for specific requirements.
Called by Model._check_properties().
Args:
rest: Optional subproperty to check, of the form 'name1.name2...nameN'.
Raises:
InvalidPropertyError if this property... |
Setter for key attribute. | def _set_value(self, entity, value):
"""Setter for key attribute."""
if value is not None:
value = _validate_key(value, entity=entity)
value = entity._validate_key(value)
entity._entity_key = value |
Override _get_value () to * not * raise UnprojectedPropertyError. | def _get_value(self, entity):
"""Override _get_value() to *not* raise UnprojectedPropertyError."""
value = self._get_user_value(entity)
if value is None and entity._projection:
# Invoke super _get_value() to raise the proper exception.
return super(StructuredProperty, self)._get_value(entity)
... |
Override for Property. _check_property (). | def _check_property(self, rest=None, require_indexed=True):
"""Override for Property._check_property().
Raises:
InvalidPropertyError if no subproperty is specified or if something
is wrong with the subproperty.
"""
if not rest:
raise InvalidPropertyError(
'Structured propert... |
Internal helper method to parse keywords that may be property names. | def __get_arg(cls, kwds, kwd):
"""Internal helper method to parse keywords that may be property names."""
alt_kwd = '_' + kwd
if alt_kwd in kwds:
return kwds.pop(alt_kwd)
if kwd in kwds:
obj = getattr(cls, kwd, None)
if not isinstance(obj, Property) or isinstance(obj, ModelKey):
... |
Internal helper to set attributes from keyword arguments. | def _set_attributes(self, kwds):
"""Internal helper to set attributes from keyword arguments.
Expando overrides this.
"""
cls = self.__class__
for name, value in kwds.iteritems():
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
if not isinstance(prop, Property... |
Internal helper to find uninitialized properties. | def _find_uninitialized(self):
"""Internal helper to find uninitialized properties.
Returns:
A set of property names.
"""
return set(name
for name, prop in self._properties.iteritems()
if not prop._is_initialized(self)) |
Internal helper to check for uninitialized properties. | def _check_initialized(self):
"""Internal helper to check for uninitialized properties.
Raises:
BadValueError if it finds any.
"""
baddies = self._find_uninitialized()
if baddies:
raise datastore_errors.BadValueError(
'Entity has uninitialized properties: %s' % ', '.join(baddi... |
Clear the kind map. Useful for testing. | def _reset_kind_map(cls):
"""Clear the kind map. Useful for testing."""
# Preserve "system" kinds, like __namespace__
keep = {}
for name, value in cls._kind_map.iteritems():
if name.startswith('__') and name.endswith('__'):
keep[name] = value
cls._kind_map.clear()
cls._kind_map.up... |
Get the model class for the kind. | def _lookup_model(cls, kind, default_model=None):
"""Get the model class for the kind.
Args:
kind: A string representing the name of the kind to lookup.
default_model: The model class to use if the kind can't be found.
Returns:
The model class for the requested kind.
Raises:
Ki... |
Compare two entities of the same class excluding keys. | def _equivalent(self, other):
"""Compare two entities of the same class, excluding keys."""
if other.__class__ is not self.__class__: # TODO: What about subclasses?
raise NotImplementedError('Cannot compare different model classes. '
'%s is not %s' % (self.__class__.__name... |
Internal helper to turn an entity into an EntityProto protobuf. | def _to_pb(self, pb=None, allow_partial=False, set_key=True):
"""Internal helper to turn an entity into an EntityProto protobuf."""
if not allow_partial:
self._check_initialized()
if pb is None:
pb = entity_pb.EntityProto()
if set_key:
# TODO: Move the key stuff into ModelAdapter.enti... |
Internal helper to copy the key into a protobuf. | def _key_to_pb(self, pb):
"""Internal helper to copy the key into a protobuf."""
key = self._key
if key is None:
pairs = [(self._get_kind(), None)]
ref = key_module._ReferenceFromPairs(pairs, reference=pb.mutable_key())
else:
ref = key.reference()
pb.mutable_key().CopyFrom(ref)
... |
Internal helper to create an entity from an EntityProto protobuf. | def _from_pb(cls, pb, set_key=True, ent=None, key=None):
"""Internal helper to create an entity from an EntityProto protobuf."""
if not isinstance(pb, entity_pb.EntityProto):
raise TypeError('pb must be a EntityProto; received %r' % pb)
if ent is None:
ent = cls()
# A key passed in override... |
Internal helper to get the Property for a protobuf - level property. | def _get_property_for(self, p, indexed=True, depth=0):
"""Internal helper to get the Property for a protobuf-level property."""
parts = p.name().split('.')
if len(parts) <= depth:
# Apparently there's an unstructured value here.
# Assume it is a None written for a missing value.
# (It coul... |
Internal helper to clone self. _properties if necessary. | def _clone_properties(self):
"""Internal helper to clone self._properties if necessary."""
cls = self.__class__
if self._properties is cls._properties:
self._properties = dict(cls._properties) |
Internal helper to create a fake Property. | def _fake_property(self, p, next, indexed=True):
"""Internal helper to create a fake Property."""
self._clone_properties()
if p.name() != next and not p.name().endswith('.' + next):
prop = StructuredProperty(Expando, next)
prop._store_value(self, _BaseValue(Expando()))
else:
compressed... |
Return a dict containing the entity s property values. | def _to_dict(self, include=None, exclude=None):
"""Return a dict containing the entity's property values.
Args:
include: Optional set of property names to include, default all.
exclude: Optional set of property names to skip, default none.
A name contained in both include and exclude is exc... |
Fix up the properties by calling their _fix_up () method. | def _fix_up_properties(cls):
"""Fix up the properties by calling their _fix_up() method.
Note: This is called by MetaModel, but may also be called manually
after dynamically updating a model class.
"""
# Verify that _get_kind() returns an 8-bit string.
kind = cls._get_kind()
if not isinstan... |
Internal helper to check the given properties exist and meet specified requirements. | def _check_properties(cls, property_names, require_indexed=True):
"""Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to addre... |
Create a Query object for this class. | def _query(cls, *args, **kwds):
"""Create a Query object for this class.
Args:
distinct: Optional bool, short hand for group_by = projection.
*args: Used to apply an initial filter
**kwds: are passed to the Query() constructor.
Returns:
A Query object.
"""
# Validating dist... |
Run a GQL query. | def _gql(cls, query_string, *args, **kwds):
"""Run a GQL query."""
from .query import gql # Import late to avoid circular imports.
return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string),
*args, **kwds) |
Write this entity to Cloud Datastore. | def _put_async(self, **ctx_options):
"""Write this entity to Cloud Datastore.
This is the asynchronous version of Model._put().
"""
if self._projection:
raise datastore_errors.BadRequestError('Cannot put a partial entity')
from . import tasklets
ctx = tasklets.get_context()
self._prep... |
Transactionally retrieves an existing entity or creates a new one. | def _get_or_insert(*args, **kwds):
"""Transactionally retrieves an existing entity or creates a new one.
Positional Args:
name: Key name to retrieve or create.
Keyword Args:
namespace: Optional namespace.
app: Optional app ID.
parent: Parent entity key, if any.
context_option... |
Transactionally retrieves an existing entity or creates a new one. | def _get_or_insert_async(*args, **kwds):
"""Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
"""
# NOTE: The signature is really weird here because we want to support
# models with properties named e.g. 'cls' or 'name'.
... |
Allocates a range of key IDs for this model class. | def _allocate_ids(cls, size=None, max=None, parent=None, **ctx_options):
"""Allocates a range of key IDs for this model class.
Args:
size: Number of IDs to allocate. Either size or max can be specified,
not both.
max: Maximum ID to allocate. Either size or max can be specified,
not ... |
Allocates a range of key IDs for this model class. | def _allocate_ids_async(cls, size=None, max=None, parent=None,
**ctx_options):
"""Allocates a range of key IDs for this model class.
This is the asynchronous version of Model._allocate_ids().
"""
from . import tasklets
ctx = tasklets.get_context()
cls._pre_allocate_ids... |
Returns an instance of Model class by ID. | def _get_by_id(cls, id, parent=None, **ctx_options):
"""Returns an instance of Model class by ID.
This is really just a shorthand for Key(cls, id, ...).get().
Args:
id: A string or integer key ID.
parent: Optional parent key of the model to get.
namespace: Optional namespace.
app: ... |
Returns an instance of Model class by ID ( and app namespace ). | def _get_by_id_async(cls, id, parent=None, app=None, namespace=None,
**ctx_options):
"""Returns an instance of Model class by ID (and app, namespace).
This is the asynchronous version of Model._get_by_id().
"""
key = Key(cls._get_kind(), id, parent=parent, app=app, namespace=name... |
Checks whether a specific hook is in its default state. | def _is_default_hook(default_hook, hook):
"""Checks whether a specific hook is in its default state.
Args:
cls: A ndb.model.Model class.
default_hook: Callable specified by ndb internally (do not override).
hook: The hook defined by a model class using _post_*_hook.
Raises:
TypeErr... |
Construct a Reference ; the signature is the same as for Key. | def _ConstructReference(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=None):
"""Construct a Reference; the signature is the same as for Key."""
if cls is not Key:
raise TypeError('Cannot construct Key r... |
Construct a Reference from a list of pairs. | def _ReferenceFromPairs(pairs, reference=None, app=None, namespace=None):
"""Construct a Reference from a list of pairs.
If a Reference is passed in as the second argument, it is modified
in place. The app and namespace are set from the corresponding
keyword arguments, with the customary defaults.
"""
if ... |
Construct a Reference from a serialized Reference. | def _ReferenceFromSerialized(serialized):
"""Construct a Reference from a serialized Reference."""
if not isinstance(serialized, basestring):
raise TypeError('serialized must be a string; received %r' % serialized)
elif isinstance(serialized, unicode):
serialized = serialized.encode('utf8')
return entit... |
Decode a url - safe base64 - encoded string. | def _DecodeUrlSafe(urlsafe):
"""Decode a url-safe base64-encoded string.
This returns the decoded string.
"""
if not isinstance(urlsafe, basestring):
raise TypeError('urlsafe must be a string; received %r' % urlsafe)
if isinstance(urlsafe, unicode):
urlsafe = urlsafe.encode('utf8')
mod = len(urlsaf... |
Construct a Reference ; the signature is the same as for Key. | def _parse_from_ref(cls, pairs=None, flat=None,
reference=None, serialized=None, urlsafe=None,
app=None, namespace=None, parent=None):
"""Construct a Reference; the signature is the same as for Key."""
if cls is not Key:
raise TypeError('Cannot construct Key ref... |
Return a Key constructed from all but the last ( kind id ) pairs. | def parent(self):
"""Return a Key constructed from all but the last (kind, id) pairs.
If there is only one (kind, id) pair, return None.
"""
pairs = self.__pairs
if len(pairs) <= 1:
return None
return Key(pairs=pairs[:-1], app=self.__app, namespace=self.__namespace) |
Return the string id in the last ( kind id ) pair if any. | def string_id(self):
"""Return the string id in the last (kind, id) pair, if any.
Returns:
A string id, or None if the key has an integer id or is incomplete.
"""
id = self.id()
if not isinstance(id, basestring):
id = None
return id |
Return the integer id in the last ( kind id ) pair if any. | def integer_id(self):
"""Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomplete.
"""
id = self.id()
if not isinstance(id, (int, long)):
id = None
return id |
Return a tuple of alternating kind and id values. | def flat(self):
"""Return a tuple of alternating kind and id values."""
flat = []
for kind, id in self.__pairs:
flat.append(kind)
flat.append(id)
return tuple(flat) |
Return the Reference object for this Key. | def reference(self):
"""Return the Reference object for this Key.
This is a entity_pb.Reference instance -- a protocol buffer class
used by the lower-level API to the datastore.
NOTE: The caller should not mutate the return value.
"""
if self.__reference is None:
self.__reference = _Cons... |
Return a url - safe string encoding this Key s Reference. | def urlsafe(self):
"""Return a url-safe string encoding this Key's Reference.
This string is compatible with other APIs and languages and with
the strings used to represent Keys in GQL and in the App Engine
Admin Console.
"""
# This is 3-4x faster than urlsafe_b64decode()
urlsafe = base64.b... |
Return a Future whose result is the entity for this Key. | def get_async(self, **ctx_options):
"""Return a Future whose result is the entity for this Key.
If no such entity exists, a Future is still returned, and the
Future's eventual return result be None.
"""
from . import model, tasklets
ctx = tasklets.get_context()
cls = model.Model._kind_map.g... |
Schedule deletion of the entity for this Key. | def delete_async(self, **ctx_options):
"""Schedule deletion of the entity for this Key.
This returns a Future, whose result becomes available once the
deletion is complete. If no such entity exists, a Future is still
returned. In all cases the Future's result is None (i.e. there is
no way to tell... |
Add an exception that should not be logged. | def add_flow_exception(exc):
"""Add an exception that should not be logged.
The argument must be a subclass of Exception.
"""
global _flow_exceptions
if not isinstance(exc, type) or not issubclass(exc, Exception):
raise TypeError('Expected an Exception subclass, got %r' % (exc,))
as_set = set(_flow_exc... |
Internal helper to initialize _flow_exceptions. | def _init_flow_exceptions():
"""Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported.
"""
global _flow_exceptions
_flow_exceptions = ()
add_flow_exception(datastore_errors.Rollback)
try:
from webob import exc
except ImportError:
... |
Public function to sleep some time. | def sleep(dt):
"""Public function to sleep some time.
Example:
yield tasklets.sleep(0.5) # Sleep for half a sec.
"""
fut = Future('sleep(%.3f)' % dt)
eventloop.queue_call(dt, fut.set_result, None)
return fut |
Helper to transfer result or errors from one Future to another. | def _transfer_result(fut1, fut2):
"""Helper to transfer result or errors from one Future to another."""
exc = fut1.get_exception()
if exc is not None:
tb = fut1.get_traceback()
fut2.set_exception(exc, tb)
else:
val = fut1.get_result()
fut2.set_result(val) |
Decorator to run a function as a tasklet when called. | def synctasklet(func):
"""Decorator to run a function as a tasklet when called.
Use this to wrap a request handler function that will be called by
some web application framework (e.g. a Django view function or a
webapp.RequestHandler.get method).
"""
taskletfunc = tasklet(func) # wrap at declaration time.... |
A sync tasklet that sets a fresh default Context. | def toplevel(func):
"""A sync tasklet that sets a fresh default Context.
Use this for toplevel view functions such as
webapp.RequestHandler.get() or Django view functions.
"""
synctaskletfunc = synctasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def add_context_wrapper(*args, **kwds):
... |
Creates a new context to connect to a remote Cloud Datastore instance. | def _make_cloud_datastore_context(app_id, external_app_ids=()):
"""Creates a new context to connect to a remote Cloud Datastore instance.
This should only be used outside of Google App Engine.
Args:
app_id: The application id to connect to. This differs from the project
id as it may have an additional... |
Internal helper to check a list of indexed fields. | def _analyze_indexed_fields(indexed_fields):
"""Internal helper to check a list of indexed fields.
Args:
indexed_fields: A list of names, possibly dotted names.
(A dotted name is a string containing names separated by dots,
e.g. 'foo.bar.baz'. An undotted name is a string containing no
dots, e.g. 'foo'... |
Construct a Model subclass corresponding to a Message subclass. | def _make_model_class(message_type, indexed_fields, **props):
"""Construct a Model subclass corresponding to a Message subclass.
Args:
message_type: A Message subclass.
indexed_fields: A list of dotted and undotted field names.
**props: Additional properties with which to seed the class.
Returns:
... |
Recursive helper for _to_base_type () to convert a message to an entity. | def _message_to_entity(msg, modelclass):
"""Recursive helper for _to_base_type() to convert a message to an entity.
Args:
msg: A Message instance.
modelclass: A Model subclass.
Returns:
An instance of modelclass.
"""
ent = modelclass()
for prop_name, prop in modelclass._properties.iteritems():... |
Recursive helper for _from_base_type () to convert an entity to a message. | def _projected_entity_to_message(ent, message_type):
"""Recursive helper for _from_base_type() to convert an entity to a message.
Args:
ent: A Model instance.
message_type: A Message subclass.
Returns:
An instance of message_type.
"""
msg = message_type()
analyzed = _analyze_indexed_fields(ent... |
Validate an Enum value. | def _validate(self, value):
"""Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._enum_type.
"""
if not isinstance(value, self._enum_type):
raise TypeError('Expected a %s instance, got %r instead' %
(self._enum_type.__name__, value)) |
Validate an Enum value. | def _validate(self, msg):
"""Validate an Enum value.
Raises:
TypeError if the value is not an instance of self._message_type.
"""
if not isinstance(msg, self._message_type):
raise TypeError('Expected a %s instance for %s property',
self._message_type.__name__,
... |
Convert a Message value to a Model instance ( entity ). | def _to_base_type(self, msg):
"""Convert a Message value to a Model instance (entity)."""
ent = _message_to_entity(msg, self._modelclass)
ent.blob_ = self._protocol_impl.encode_message(msg)
return ent |
Convert a Model instance ( entity ) to a Message value. | def _from_base_type(self, ent):
"""Convert a Model instance (entity) to a Message value."""
if ent._projection:
# Projection query result. Reconstitute the message from the fields.
return _projected_entity_to_message(ent, self._message_type)
blob = ent.blob_
if blob is not None:
prot... |
Compute and store a default value if necessary. | def _get_value(self, entity):
"""Compute and store a default value if necessary."""
value = super(_ClassKeyProperty, self)._get_value(entity)
if not value:
value = entity._class_key()
self._store_value(entity, value)
return value |
Override ; called by Model. _fix_up_properties (). | def _update_kind_map(cls):
"""Override; called by Model._fix_up_properties().
Update the kind map as well as the class map, except for PolyModel
itself (its class key is empty). Note that the kind map will
contain entries for all classes in a PolyModel hierarchy; they all
have the same kind, but d... |
Override. | def _from_pb(cls, pb, set_key=True, ent=None, key=None):
"""Override.
Use the class map to give the entity the correct subclass.
"""
prop_name = cls.class_._name
class_name = []
for plist in [pb.property_list(), pb.raw_property_list()]:
for p in plist:
if p.name() == prop_name:
... |
Override. | def _get_kind(cls):
"""Override.
Make sure that the kind returned is the root class of the
polymorphic hierarchy.
"""
bases = cls._get_hierarchy()
if not bases:
# We have to jump through some hoops to call the superclass'
# _get_kind() method. First, this is called by the metaclass... |
Internal helper to return the list of polymorphic base classes. | def _get_hierarchy(cls):
"""Internal helper to return the list of polymorphic base classes.
This returns a list of class objects, e.g. [Animal, Feline, Cat].
"""
bases = []
for base in cls.mro(): # pragma: no branch
if hasattr(base, '_get_hierarchy'):
bases.append(base)
del bases... |
Returns all potential envs in a basedir | def find_env_paths_in_basedirs(base_dirs):
"""Returns all potential envs in a basedir"""
# get potential env path in the base_dirs
env_path = []
for base_dir in base_dirs:
env_path.extend(glob.glob(os.path.join(
os.path.expanduser(base_dir), '*', '')))
# self.log.info("Found the ... |
Converts a list of paths to environments to env_data. | def convert_to_env_data(mgr, env_paths, validator_func, activate_func,
name_template, display_name_template, name_prefix):
"""Converts a list of paths to environments to env_data.
env_data is a structure {name -> (ressourcedir, kernel spec)}
"""
env_data = {}
for venv_dir in... |
Validates that this env contains an IPython kernel and returns info to start it | def validate_IPykernel(venv_dir):
"""Validates that this env contains an IPython kernel and returns info to start it
Returns: tuple
(ARGV, language, resource_dir)
"""
python_exe_name = find_exe(venv_dir, "python")
if python_exe_name is None:
python_exe_name = find_exe(venv_dir, "py... |
Validates that this env contains an IRkernel kernel and returns info to start it | def validate_IRkernel(venv_dir):
"""Validates that this env contains an IRkernel kernel and returns info to start it
Returns: tuple
(ARGV, language, resource_dir)
"""
r_exe_name = find_exe(venv_dir, "R")
if r_exe_name is None:
return [], None, None
# check if this is really an... |
Finds a exe with that name in the environment path | def find_exe(env_dir, name):
"""Finds a exe with that name in the environment path"""
if platform.system() == "Windows":
name = name + ".exe"
# find the binary
exe_name = os.path.join(env_dir, name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "bin", name)
... |
Finds kernel specs from virtualenv environments | def get_virtualenv_env_data(mgr):
"""Finds kernel specs from virtualenv environments
env_data is a structure {name -> (resourcedir, kernel spec)}
"""
if not mgr.find_virtualenv_envs:
return {}
mgr.log.debug("Looking for virtualenv environments in %s...", mgr.virtualenv_env_dirs)
# fi... |
Simply bash - specific wrapper around source - foreign | def source_bash(args, stdin=None):
"""Simply bash-specific wrapper around source-foreign
Returns a dict to be used as a new environment"""
args = list(args)
new_args = ['bash', '--sourcer=source']
new_args.extend(args)
return source_foreign(new_args, stdin=stdin) |
Simply zsh - specific wrapper around source - foreign | def source_zsh(args, stdin=None):
"""Simply zsh-specific wrapper around source-foreign
Returns a dict to be used as a new environment"""
args = list(args)
new_args = ['zsh', '--sourcer=source']
new_args.extend(args)
return source_foreign(new_args, stdin=stdin) |
Simple cmd. exe - specific wrapper around source - foreign. | def source_cmd(args, stdin=None):
"""Simple cmd.exe-specific wrapper around source-foreign.
returns a dict to be used as a new environment
"""
args = list(args)
fpath = locate_binary(args[0])
args[0] = fpath if fpath else args[0]
if not os.path.isfile(args[0]):
raise RuntimeError("C... |
Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces ; this function does not add these spaces. This implementation ... | def argvquote(arg, force=False):
""" Returns an argument quoted in such a way that that CommandLineToArgvW
on Windows will return the argument string unchanged.
This is the same thing Popen does when supplied with an list of arguments.
Arguments in a command line should be separated by spaces; this
... |
Returns a string that is usable by the Windows cmd. exe. The escaping is based on details here and emperical testing: http:// www. robvanderwoude. com/ escapechars. php | def escape_windows_cmd_string(s):
"""Returns a string that is usable by the Windows cmd.exe.
The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
"""
for c in '()%!^<>&|"':
s = s.replace(c, '^' + c)
s = s.replace('/?', '/.')
retur... |
Sources a file written in a foreign shell language. | def source_foreign(args, stdin=None):
"""Sources a file written in a foreign shell language."""
parser = _ensure_source_foreign_parser()
ns = parser.parse_args(args)
if ns.prevcmd is not None:
pass # don't change prevcmd if given explicitly
elif os.path.isfile(ns.files_or_code[0]):
... |
Checks that path is an executable regular file or a symlink towards one. This is roughly os. path isfile ( path ) and os. access ( path os. X_OK ). | def _is_executable_file(path):
"""Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
This function was forked from pexpect originally:
Copyright (c) 2013-2014, Pexpect development team
Copyright (c) 2012,... |
Extracts data from a foreign ( non - xonsh ) shells. Currently this gets the environment aliases and functions but may be extended in the future. | def foreign_shell_data(shell, interactive=True, login=False, envcmd=None,
aliascmd=None, extra_args=(), currenv=None,
safe=False, prevcmd='', postcmd='', funcscmd=None,
sourcer=None, use_tmpfile=False, tmpfile_ext=None,
runcmd=N... |
Converts to a boolean in a semantically meaningful way. | def to_bool(x):
""""Converts to a boolean in a semantically meaningful way."""
if isinstance(x, bool):
return x
elif isinstance(x, str):
return False if x.lower() in _FALSES else True
else:
return bool(x) |
Parses the environment portion of string into a dict. | def parse_env(s):
"""Parses the environment portion of string into a dict."""
m = ENV_RE.search(s)
if m is None:
return {}
g1 = m.group(1)
env = dict(ENV_SPLIT_RE.findall(g1))
return env |
Finds kernel specs from conda environments | def get_conda_env_data(mgr):
"""Finds kernel specs from conda environments
env_data is a structure {name -> (resourcedir, kernel spec)}
"""
if not mgr.find_conda_envs:
return {}
mgr.log.debug("Looking for conda environments in %s...", mgr.conda_env_dirs)
# find all potential env paths... |
Returns a list of path as given by conda env list -- json. | def _find_conda_env_paths_from_conda(mgr):
"""Returns a list of path as given by `conda env list --json`.
Returns empty list, if conda couldn't be called.
"""
# this is expensive, so make it configureable...
if not mgr.use_conda_directly:
return []
mgr.log.debug("Looking for conda envir... |
Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. | def validate_env(self, envname):
"""
Check the name of the environment against the black list and the
whitelist. If a whitelist is specified only it is checked.
"""
if self.whitelist_envs and envname in self.whitelist_envs:
return True
elif self.whitelist_envs... |
Get the data about the available environments. | def _get_env_data(self, reload=False):
"""Get the data about the available environments.
env_data is a structure {name -> (resourcedir, kernel spec)}
"""
# This is called much too often and finding-process is really expensive :-(
if not reload and getattr(self, "_env_data_cache... |
Returns a dict mapping kernel names to resource directories. | def find_kernel_specs_for_envs(self):
"""Returns a dict mapping kernel names to resource directories."""
data = self._get_env_data()
return {name: data[name][0] for name in data} |
Returns the dict of name - > kernel_spec for all environments | def get_all_kernel_specs_for_envs(self):
"""Returns the dict of name -> kernel_spec for all environments"""
data = self._get_env_data()
return {name: data[name][1] for name in data} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.