_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q15800
load_fixtures
train
def load_fixtures(): """Populate a database with data from fixtures.""" if local("pwd", capture=True) == PRODUCTION_DOCUMENT_ROOT: abort("Refusing to automatically load fixtures into production database!") if not confirm("Are you sure you want to load all fixtures? This could have unintended consequences if the database is not empty."): abort("Aborted.") files = [ "fixtures/users/users.json", "fixtures/eighth/sponsors.json", "fixtures/eighth/rooms.json", "fixtures/eighth/blocks.json",
python
{ "resource": "" }
q15801
deploy
train
def deploy(): """Deploy to production.""" _require_root() if not confirm("This will apply any available migrations to the database. Has the database been backed up?"): abort("Aborted.") if not confirm("Are you sure you want to deploy?"): abort("Aborted.") with lcd(PRODUCTION_DOCUMENT_ROOT): with shell_env(PRODUCTION="TRUE"): local("git pull") with open("requirements.txt", "r") as req_file: requirements = req_file.read().strip().split() try: pkg_resources.require(requirements) except pkg_resources.DistributionNotFound: local("pip install -r requirements.txt") except Exception: traceback.format_exc() local("pip install -r requirements.txt")
python
{ "resource": "" }
q15802
forcemigrate
train
def forcemigrate(app=None): """Force migrations to apply for a given app.""" if app is None: abort("No app name given.") local("./manage.py migrate
python
{ "resource": "" }
q15803
UserManager.users_with_birthday
train
def users_with_birthday(self, month, day): """Return a list of user objects who have a birthday on a given date.""" users = User.objects.filter(properties___birthday__month=month, properties___birthday__day=day) results = []
python
{ "resource": "" }
q15804
UserManager.get_teachers_sorted
train
def get_teachers_sorted(self): """Get teachers sorted by last name. This is used for the announcement request page. """ teachers = self.get_teachers() teachers = [(u.last_name, u.first_name, u.id) for u in teachers] for t in teachers: if t is None or t[0] is None or t[1] is None or t[2] is None: teachers.remove(t) for t in teachers: if t[0] is None or len(t[0]) <= 1: teachers.remove(t) teachers.sort(key=lambda u: (u[0], u[1]))
python
{ "resource": "" }
q15805
User.member_of
train
def member_of(self, group): """Returns whether a user is a member of a certain group. Args: group The name of a group (string) or a group object Returns: Boolean
python
{ "resource": "" }
q15806
User.permissions
train
def permissions(self): """Dynamically generate dictionary of privacy options """ # TODO: optimize this, it's kind of a bad solution for listing a mostly # static set of files. # We could either add a permissions dict as an attribute or cache this # in some way. Creating a dict would be another place we have to define # the permission, so I'm not a huge fan, but it would definitely be the # easier option. permissions_dict = {"self": {}, "parent": {}} for field in self.properties._meta.get_fields():
python
{ "resource": "" }
q15807
User._current_user_override
train
def _current_user_override(self): """Return whether the currently logged in user is a teacher, and can view all of a student's information regardless of their privacy settings.""" try: # threadlocals is a module, not an actual thread locals object request = threadlocals.request() if request is None: return False requesting_user = request.user if isinstance(requesting_user, AnonymousUser) or not requesting_user.is_authenticated: return False
python
{ "resource": "" }
q15808
User.age
train
def age(self): """Returns a user's age, based on their birthday. Returns: integer
python
{ "resource": "" }
q15809
User.is_eighth_sponsor
train
def is_eighth_sponsor(self): """Determine whether the given user is associated with an. :class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity sponsoring information. """ # FIXME: remove recursive
python
{ "resource": "" }
q15810
User.frequent_signups
train
def frequent_signups(self): """Return a QuerySet of activity id's and counts for the activities that a given user has signed up for more than `settings.SIMILAR_THRESHOLD` times""" key = "{}:frequent_signups".format(self.username) cached = cache.get(key) if cached: return cached freq_signups = self.eighthsignup_set.exclude(scheduled_activity__activity__administrative=True).exclude( scheduled_activity__activity__special=True).exclude(scheduled_activity__activity__restricted=True).exclude(
python
{ "resource": "" }
q15811
User.absence_count
train
def absence_count(self): """Return the user's absence count. If the user has no absences or is not a signup user, returns 0. """ # FIXME: remove recursive dep from ..eighth.models import EighthSignup
python
{ "resource": "" }
q15812
User.absence_info
train
def absence_info(self): """Return information about the user's absences.""" # FIXME: remove recursive dep from ..eighth.models import EighthSignup
python
{ "resource": "" }
q15813
User.handle_delete
train
def handle_delete(self): """Handle a graduated user being deleted.""" from intranet.apps.eighth.models import EighthScheduledActivity
python
{ "resource": "" }
q15814
UserProperties.set_permission
train
def set_permission(self, permission, value, parent=False, admin=False): """ Sets permission for personal information. Returns False silently if unable to set permission. Returns True if successful. """ try: if not getattr(self, 'parent_{}'.format(permission)) and not parent and not admin: return False level = 'parent' if parent else 'self' setattr(self, '{}_{}'.format(level, permission), value) # Set student permission to false if parent sets permission to false.
python
{ "resource": "" }
q15815
UserProperties.attribute_is_visible
train
def attribute_is_visible(self, permission): """ Checks privacy options to see if an attribute is visible to public """ try: parent = getattr(self, "parent_{}".format(permission))
python
{ "resource": "" }
q15816
admin_required
train
def admin_required(group): """Decorator that requires the user to be in a certain admin group. For example, @admin_required("polls") would check whether a user
python
{ "resource": "" }
q15817
get_personal_info
train
def get_personal_info(user): """Get a user's personal info attributes to pass as an initial value to a PersonalInformationForm.""" # change this to not use other_phones num_phones = len(user.phones.all() or []) num_emails = len(user.emails.all() or []) num_websites = len(user.websites.all() or []) personal_info = {} for i in range(num_phones): personal_info["phone_{}".format(i)] = user.phones.all()[i] for
python
{ "resource": "" }
q15818
get_preferred_pic
train
def get_preferred_pic(user): """Get a user's preferred picture attributes to pass as an initial value to a PreferredPictureForm.""" # FIXME: remove this hardcoded junk preferred_pic = {"preferred_photo": "AUTO"}
python
{ "resource": "" }
q15819
get_privacy_options
train
def get_privacy_options(user): """Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm.""" privacy_options = {} for ptype in user.permissions: for field in user.permissions[ptype]: if ptype == "self":
python
{ "resource": "" }
q15820
get_notification_options
train
def get_notification_options(user): """Get a user's notification options to pass as an initial value to a NotificationOptionsForm.""" notification_options = {} notification_options["receive_news_emails"] = user.receive_news_emails notification_options["receive_eighth_emails"] = user.receive_eighth_emails try:
python
{ "resource": "" }
q15821
preferences_view
train
def preferences_view(request): """View and process updates to the preferences page.""" user = request.user if request.method == "POST": logger.debug(dict(request.POST)) phone_formset, email_formset, website_formset, errors = save_personal_info(request, user) if user.is_student: preferred_pic_form = save_preferred_pic(request, user) bus_route_form = save_bus_route(request, user) else: preferred_pic_form = None bus_route_form = None privacy_options_form = save_privacy_options(request, user) notification_options_form = save_notification_options(request, user) for error in errors: messages.error(request, error) try: save_gcm_options(request, user) except AttributeError: pass return redirect("preferences") else: phone_formset = PhoneFormset(instance=user, prefix='pf') email_formset = EmailFormset(instance=user, prefix='ef') website_formset = WebsiteFormset(instance=user, prefix='wf') if user.is_student: preferred_pic = get_preferred_pic(user) bus_route = get_bus_route(user) logger.debug(preferred_pic) preferred_pic_form = PreferredPictureForm(user, initial=preferred_pic) bus_route_form = BusRouteForm(user, initial=bus_route) else: bus_route_form = None
python
{ "resource": "" }
q15822
privacy_options_view
train
def privacy_options_view(request): """View and edit privacy options for a user.""" if "user" in request.GET: user = User.objects.user_with_ion_id(request.GET.get("user")) elif "student_id" in request.GET: user = User.objects.user_with_student_id(request.GET.get("student_id")) else: user = request.user if not user: messages.error(request, "Invalid user.") user = request.user if user.is_eighthoffice: user = None if user: if request.method == "POST": privacy_options_form = save_privacy_options(request, user)
python
{ "resource": "" }
q15823
IntentIntegrator.scan
train
def scan(cls, formats=ALL_CODE_TYPES, camera=-1): """ Shortcut only one at a time will work... """ app = AndroidApplication.instance() r = app.create_future() #: Initiate a scan pkg = BarcodePackage.instance() pkg.setBarcodeResultListener(pkg.getId()) pkg.onBarcodeResult.connect(r.set_result) intent = cls(app)
python
{ "resource": "" }
q15824
AndroidBarcodeView.on_activity_lifecycle_changed
train
def on_activity_lifecycle_changed(self, change): """ If the app pauses without pausing the barcode scanner the camera can't be reopened. So we must do it here. """ d = self.declaration if d.active:
python
{ "resource": "" }
q15825
AndroidBarcodeView.destroy
train
def destroy(self): """ Cleanup the activty lifecycle listener """ if self.widget:
python
{ "resource": "" }
q15826
make_inaturalist_api_get_call
train
def make_inaturalist_api_get_call(endpoint: str, params: Dict, **kwargs) -> requests.Response: """Make an API call to iNaturalist. endpoint is a string such as 'observations' !! do not put / in front method:
python
{ "resource": "" }
q15827
get_observation
train
def get_observation(observation_id: int) -> Dict[str, Any]: """Get details about an observation. :param observation_id: :returns: a dict with details on the observation :raises: ObservationNotFound """
python
{ "resource": "" }
q15828
get_access_token
train
def get_access_token(username: str, password: str, app_id: str, app_secret: str) -> str: """ Get an access token using the user's iNaturalist username and password. (you still need an iNaturalist app to do this) :param username: :param password: :param app_id: :param app_secret: :return: the access token, example use: headers = {"Authorization": "Bearer %s" % access_token} """ payload = { 'client_id': app_id, 'client_secret': app_secret, 'grant_type': "password", 'username': username, 'password': password
python
{ "resource": "" }
q15829
add_photo_to_observation
train
def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str): """Upload a picture and assign it to an existing observation. :param observation_id: the ID of the observation :param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'rb') :param access_token: the access token, as returned by :func:`get_access_token()` """ data = {'observation_photo[observation_id]': observation_id} file_data = {'file': file_object}
python
{ "resource": "" }
q15830
delete_observation
train
def delete_observation(observation_id: int, access_token: str) -> List[Dict[str, Any]]: """ Delete an observation. :param observation_id: :param access_token: :return: """ headers = _build_auth_header(access_token) headers['Content-type'] = 'application/json' response = requests.delete(url="{base_url}/observations/{id}.json".format(base_url=INAT_BASE_URL,
python
{ "resource": "" }
q15831
FieldPlaceholder.create_instance
train
def create_instance(self, parent): """Create an instance based off this placeholder with some parent""" self.kwargs['instantiate'] = True self.kwargs['parent'] = parent
python
{ "resource": "" }
q15832
BaseField._ph2f
train
def _ph2f(self, placeholder): """Lookup a field given a field placeholder""" if issubclass(placeholder.cls, FieldAccessor):
python
{ "resource": "" }
q15833
CRCField.packed_checksum
train
def packed_checksum(self, data): """Given the data of the entire packet return the checksum bytes"""
python
{ "resource": "" }
q15834
FieldAccessor.access
train
def access(cls, parent, placeholder): """Resolve the deferred field attribute access. :param cls: the FieldAccessor class :param parent: owning structure of the field being accessed :param placeholder: FieldPlaceholder object which holds our info :returns: FieldAccessor instance for that field's attribute """ try: return parent.lookup_field_by_placeholder(placeholder) except KeyError: field_placeholder, name = placeholder.args # Find the field whose attribute is being accessed. field = parent.lookup_field_by_placeholder(field_placeholder)
python
{ "resource": "" }
q15835
crc16_ccitt
train
def crc16_ccitt(data, crc=0): """Calculate the crc16 ccitt checksum of some data A starting crc value may be specified if desired. The input data is expected to be a sequence of bytes (string) and the output is an integer in the range (0, 0xFFFF). No packing is done to the resultant crc value. To check the value a checksum, just pass in the data byes and checksum value. If the data matches the checksum,
python
{ "resource": "" }
q15836
StreamProtocolHandler.feed
train
def feed(self, new_bytes): """Feed a new set of bytes into the protocol handler These bytes will be immediately fed into the parsing state machine and if new packets are found, the ``packet_callback`` will be executed with the fully-formed message. :param new_bytes: The new bytes to be fed into the stream protocol handler. """ self._available_bytes += new_bytes callbacks = [] try: while True: packet = six.next(self._packet_generator) if packet is None: break else: callbacks.append(partial(self.packet_callback, packet)) except Exception: # When we receive an exception, we assume that the _available_bytes # has already been updated and we just choked on a field. That # is, unless the number of _available_bytes has not changed. In # that case, we
python
{ "resource": "" }
q15837
URL.validate
train
def validate(self, instance, value): """Check if input is valid URL""" value = super(URL, self).validate(instance, value) parsed_url = urlparse(value) if not parsed_url.scheme or not parsed_url.netloc: self.error(instance, value, extra='URL needs scheme and netloc.')
python
{ "resource": "" }
q15838
Singleton.serialize
train
def serialize(self, include_class=True, save_dynamic=False, **kwargs): """Serialize Singleton instance to a dictionary. This behaves identically to HasProperties.serialize, except it also saves the identifying name in the dictionary as well. """ json_dict = super(Singleton, self).serialize(
python
{ "resource": "" }
q15839
Singleton.deserialize
train
def deserialize(cls, value, trusted=False, strict=False, assert_valid=False, **kwargs): """Create a Singleton instance from a serialized dictionary. This behaves identically to HasProperties.deserialize, except if the singleton is already found in the singleton registry the existing value is used. .. note:: If property values differ from the existing singleton and the input dictionary, the new values from the input dictionary will be ignored """ if not isinstance(value, dict): raise ValueError('HasProperties must deserialize from dictionary') identifier = value.pop('_singleton_id', value.get('name')) if identifier is None:
python
{ "resource": "" }
q15840
add_properties_callbacks
train
def add_properties_callbacks(cls): """Class decorator to add change notifications to builtin containers""" for name in cls._mutators: #pylint: disable=protected-access if not hasattr(cls, name): continue setattr(cls, name, properties_mutator(cls, name)) for name in cls._operators: #pylint: disable=protected-access if not hasattr(cls, name):
python
{ "resource": "" }
q15841
properties_mutator
train
def properties_mutator(cls, name, ioper=False): """Wraps a mutating container method to add HasProperties notifications If the container is not part of a HasProperties instance, behavior is unchanged. However, if it is part of a HasProperties instance the new method calls set, triggering change notifications. """ def wrapper(self, *args, **kwargs): """Mutate if not part of HasProperties; copy/modify/set otherwise""" if ( getattr(self, '_instance', None) is None or getattr(self, '_name', '') == '' or self is
python
{ "resource": "" }
q15842
properties_operator
train
def properties_operator(cls, name): """Wraps a container operator to ensure container class is maintained""" def wrapper(self, *args, **kwargs): """Perform operation and cast to container class""" output = getattr(super(cls, self), name)(*args,
python
{ "resource": "" }
q15843
observable_copy
train
def observable_copy(value, name, instance): """Return an observable container for HasProperties notifications This method creates a new container class to allow HasProperties instances to :code:`observe_mutations`. It returns a copy of the input value as this new class. The output class behaves identically to the input value's original class, except when it is used as a property on a HasProperties instance. In that case, it notifies the HasProperties instance of any mutations or operations. """ container_class = value.__class__ if container_class in OBSERVABLE_REGISTRY: observable_class = OBSERVABLE_REGISTRY[container_class] elif container_class in OBSERVABLE_REGISTRY.values(): observable_class = container_class else:
python
{ "resource": "" }
q15844
validate_prop
train
def validate_prop(value): """Validate Property instance for container items""" if ( isinstance(value, CLASS_TYPES) and issubclass(value, HasProperties) ): value = Instance('', value) if not isinstance(value, basic.Property): raise TypeError('Contained prop must be a Property instance or '
python
{ "resource": "" }
q15845
Tuple.validate
train
def validate(self, instance, value): """Check the class of the container and validate each element This returns a copy of the container to prevent unwanted sharing of pointers. """ if not self.coerce and not isinstance(value, self._class_container): self.error(instance, value) if self.coerce and not isinstance(value, CONTAINERS): value = [value] if not isinstance(value, self._class_container): out_class = self._class_container else:
python
{ "resource": "" }
q15846
Tuple.assert_valid
train
def assert_valid(self, instance, value=None): """Check if tuple and contained properties are valid""" valid = super(Tuple, self).assert_valid(instance, value) if not valid: return False if value is None: value = instance._get(self.name) if value is None: return True if ( (self.min_length is not None and len(value) < self.min_length) or (self.max_length is not None
python
{ "resource": "" }
q15847
Tuple.serialize
train
def serialize(self, value, **kwargs): """Return a serialized copy of the tuple""" kwargs.update({'include_class': kwargs.get('include_class', True)}) if self.serializer is not None: return self.serializer(value, **kwargs) if value is None:
python
{ "resource": "" }
q15848
Tuple.deserialize
train
def deserialize(self, value, **kwargs): """Return a deserialized copy of the tuple""" kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: return self.deserializer(value, **kwargs) if value is None:
python
{ "resource": "" }
q15849
Tuple.to_json
train
def to_json(value, **kwargs): """Return a copy of the tuple as a list If the tuple contains HasProperties instances, they are serialized. """ serial_list = [ val.serialize(**kwargs) if
python
{ "resource": "" }
q15850
Tuple.sphinx_class
train
def sphinx_class(self): """Redefine sphinx class to point to prop class""" classdoc =
python
{ "resource": "" }
q15851
Dictionary.assert_valid
train
def assert_valid(self, instance, value=None): """Check if dict and contained properties are valid""" valid = super(Dictionary, self).assert_valid(instance, value) if not valid: return False if value is None: value = instance._get(self.name) if value is None: return True if self.key_prop or self.value_prop: for key, val in iteritems(value):
python
{ "resource": "" }
q15852
Dictionary.serialize
train
def serialize(self, value, **kwargs): """Return a serialized copy of the dict""" kwargs.update({'include_class': kwargs.get('include_class', True)}) if self.serializer is not None: return self.serializer(value, **kwargs) if value is None: return None serial_tuples = [ ( self.key_prop.serialize(key, **kwargs), self.value_prop.serialize(val, **kwargs) )
python
{ "resource": "" }
q15853
Dictionary.deserialize
train
def deserialize(self, value, **kwargs): """Return a deserialized copy of the dict""" kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: return self.deserializer(value, **kwargs) if value is None: return None output_tuples = [ ( self.key_prop.deserialize(key, **kwargs), self.value_prop.deserialize(val, **kwargs) ) for key, val in iteritems(value)
python
{ "resource": "" }
q15854
Dictionary.to_json
train
def to_json(value, **kwargs): """Return a copy of the dictionary If the values are HasProperties instances, they are serialized """ serial_dict = { key: (
python
{ "resource": "" }
q15855
filter_props
train
def filter_props(has_props_cls, input_dict, include_immutable=True): """Split a dictionary based keys that correspond to Properties Returns: **(props_dict, others_dict)** - Tuple of two dictionaries. The first contains key/value pairs from the input dictionary that correspond to the Properties of the input HasProperties class. The second contains the remaining key/value pairs. **Parameters**: * **has_props_cls** - HasProperties class or instance used to filter the dictionary * **input_dict** - Dictionary to filter * **include_immutable** - If True (the default), immutable properties (i.e. Properties that inherit from GettableProperty but not Property) are included in props_dict. If False, immutable properties are excluded from props_dict. For example .. code:: class Profile(properties.HasProperties): name = properties.String('First and last name') age = properties.Integer('Age, years') bio_dict = { 'name': 'Bill', 'age': 65, 'hometown': 'Bakersfield', 'email': 'bill@gmail.com',
python
{ "resource": "" }
q15856
Union.default
train
def default(self): """Default value of the property""" prop_def = getattr(self, '_default', utils.undefined) for prop in self.props: if prop.default is utils.undefined: continue
python
{ "resource": "" }
q15857
Union._try_prop_method
train
def _try_prop_method(self, instance, value, method_name): """Helper method to perform a method on each of the union props This method gathers all errors and returns them at the end if the method on each of the props fails. """ error_messages = [] for prop in self.props: try: return getattr(prop, method_name)(instance, value) except GENERIC_ERRORS as err: if hasattr(err, 'error_tuples'): error_messages += [
python
{ "resource": "" }
q15858
Union.assert_valid
train
def assert_valid(self, instance, value=None): """Check if the Union has a valid value""" valid = super(Union, self).assert_valid(instance, value) if not valid: return False if value is None:
python
{ "resource": "" }
q15859
Union.serialize
train
def serialize(self, value, **kwargs): """Return a serialized value If no serializer is provided, it uses the serialize method of the prop corresponding to the value """ kwargs.update({'include_class': kwargs.get('include_class', True)}) if self.serializer is not None: return self.serializer(value, **kwargs) if value is None: return None for prop in self.props:
python
{ "resource": "" }
q15860
Union.deserialize
train
def deserialize(self, value, **kwargs): """Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value """ kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: return self.deserializer(value, **kwargs) if value is None: return None instance_props = [ prop for prop in self.props if isinstance(prop, Instance)
python
{ "resource": "" }
q15861
Union.to_json
train
def to_json(value, **kwargs): """Return value, serialized if value is a HasProperties instance"""
python
{ "resource": "" }
q15862
accept_kwargs
train
def accept_kwargs(func): """Wrap a function that may not accept kwargs so they are accepted The output function will always have call signature of :code:`func(val, **kwargs)`, whereas the original function may have call signatures of :code:`func(val)` or :code:`func(val, **kwargs)`. In the case of the former, rather than erroring, kwargs are just ignored. This method is called on serializer/deserializer function; these functions always receive kwargs from serialize, but by
python
{ "resource": "" }
q15863
GettableProperty.terms
train
def terms(self): """Initialization terms and options for Property""" terms = PropertyTerms( self.name, self.__class__,
python
{ "resource": "" }
q15864
GettableProperty.tag
train
def tag(self, *tag, **kwtags): """Tag a Property instance with metadata dictionary""" if not tag: pass elif len(tag) == 1 and isinstance(tag[0], dict): self._meta.update(tag[0]) else: raise
python
{ "resource": "" }
q15865
GettableProperty.equal
train
def equal(self, value_a, value_b): #pylint: disable=no-self-use """Check if two valid Property values are equal .. note:: This method assumes that :code:`None` and :code:`properties.undefined` are never passed in
python
{ "resource": "" }
q15866
GettableProperty.get_property
train
def get_property(self): """Establishes access of GettableProperty values""" scope = self
python
{ "resource": "" }
q15867
GettableProperty.deserialize
train
def deserialize(self, value, **kwargs): #pylint: disable=unused-argument """Deserialize input value to valid Property value This method uses the Property :code:`deserializer` if available. Otherwise, it uses :code:`from_json`. Any keyword arguments are passed through to these methods. """
python
{ "resource": "" }
q15868
GettableProperty.sphinx
train
def sphinx(self): """Generate Sphinx-formatted documentation for the Property""" try: assert __IPYTHON__ classdoc = '' except (NameError, AssertionError): scls = self.sphinx_class() classdoc = ' ({})'.format(scls) if scls else '' prop_doc = '**{name}**{cls}: {doc}{info}'.format(
python
{ "resource": "" }
q15869
GettableProperty.sphinx_class
train
def sphinx_class(self): """Property class name formatted for Sphinx doc linking""" classdoc = ':class:`{cls} <{pref}.{cls}>`' if self.__module__.split('.')[0] == 'properties': pref = 'properties' else:
python
{ "resource": "" }
q15870
DynamicProperty.setter
train
def setter(self, func): """Register a set function for the DynamicProperty This function must take two arguments, self and the new value. Input value to the function is validated with prop validation prior to execution. """ if not callable(func): raise TypeError('setter must be callable function') if hasattr(func, '__code__') and
python
{ "resource": "" }
q15871
DynamicProperty.deleter
train
def deleter(self, func): """Register a delete function for the DynamicProperty This function may only take one argument, self. """ if not callable(func): raise TypeError('deleter must be callable function') if hasattr(func, '__code__') and func.__code__.co_argcount != 1: raise TypeError('deleter must be a function
python
{ "resource": "" }
q15872
Property.sphinx
train
def sphinx(self): """Basic docstring formatted for Sphinx docs""" if callable(self.default): default_val = self.default() default_str = 'new instance of {}'.format( default_val.__class__.__name__ ) else: default_val = self.default default_str = '{}'.format(self.default)
python
{ "resource": "" }
q15873
Boolean.validate
train
def validate(self, instance, value): """Checks if value is a boolean""" if self.cast: value = bool(value)
python
{ "resource": "" }
q15874
Boolean.from_json
train
def from_json(value, **kwargs): """Coerces JSON string to boolean""" if isinstance(value, string_types): value = value.upper() if value in ('TRUE', 'Y', 'YES', 'ON'): return True if value in
python
{ "resource": "" }
q15875
Complex.validate
train
def validate(self, instance, value): """Checks that value is a complex number Floats and Integers are coerced to complex numbers """ try: compval = complex(value) if not self.cast and ( abs(value.real - compval.real) > TOL or abs(value.imag - compval.imag) > TOL ): self.error(
python
{ "resource": "" }
q15876
String.validate
train
def validate(self, instance, value): """Check if value is a string, and strips it and changes case""" value_type = type(value) if not isinstance(value, string_types): self.error(instance, value) if self.regex is not None and self.regex.search(value) is None:
python
{ "resource": "" }
q15877
StringChoice.info
train
def info(self): """Formatted string to display the available choices""" if self.descriptions is None: choice_list = ['"{}"'.format(choice) for choice in self.choices] else:
python
{ "resource": "" }
q15878
StringChoice.validate
train
def validate(self, instance, value): #pylint: disable=inconsistent-return-statements """Check if input is a valid string based on the choices""" if not isinstance(value, string_types): self.error(instance, value)
python
{ "resource": "" }
q15879
Color.validate
train
def validate(self, instance, value): """Check if input is valid color and converts to RGB""" if isinstance(value, string_types): value = COLORS_NAMED.get(value, value) if value.upper() == 'RANDOM': value = random.choice(COLORS_20) value = value.upper().lstrip('#') if len(value) == 3: value = ''.join(v*2 for v in value) if len(value) != 6: self.error(instance, value, extra='Color must be known name ' 'or a hex with 6 digits. e.g. "#FF0000"') try: value = [ int(value[i:i + 6 // 3], 16) for i in range(0, 6, 6 // 3) ] except ValueError: self.error(instance, value,
python
{ "resource": "" }
q15880
DateTime.validate
train
def validate(self, instance, value): """Check if value is a valid datetime object or JSON datetime string""" if isinstance(value, datetime.datetime): return value if not isinstance(value, string_types): self.error( instance=instance, value=value, extra='Cannot convert non-strings to datetime.', )
python
{ "resource": "" }
q15881
Uuid.validate
train
def validate(self, instance, value): """Check that value is a valid UUID instance"""
python
{ "resource": "" }
q15882
File.valid_modes
train
def valid_modes(self): """Valid modes of an open file""" default_mode = (self.mode,) if self.mode is not None else None
python
{ "resource": "" }
q15883
File.validate
train
def validate(self, instance, value): """Checks that the value is a valid file open in the correct mode If value is a string, it attempts to open it with the given mode. """ if isinstance(value, string_types) and self.mode is not None: try: value = open(value, self.mode) except (IOError, TypeError): self.error(instance, value, extra='Cannot open file: {}'.format(value)) if not all([hasattr(value, attr) for attr in ('read', 'seek')]): self.error(instance, value, extra='Not a file-like object')
python
{ "resource": "" }
q15884
Renamed.display_warning
train
def display_warning(self): """Display a FutureWarning about using a Renamed Property""" if self.warn: warnings.warn( "\nProperty '{}' is deprecated and may be removed in the "
python
{ "resource": "" }
q15885
Instance.validate
train
def validate(self, instance, value): """Check if value is valid type of instance_class If value is an instance of instance_class, it is returned unmodified. If value is either (1) a keyword dictionary with valid parameters to construct an instance of instance_class or (2) a valid input argument to construct instance_class, then a new instance is created and returned. """ try: if isinstance(value, self.instance_class): return value if isinstance(value, dict):
python
{ "resource": "" }
q15886
Instance.assert_valid
train
def assert_valid(self, instance, value=None): """Checks if valid, including HasProperty instances pass validation""" valid = super(Instance, self).assert_valid(instance, value) if not valid: return False if value
python
{ "resource": "" }
q15887
Instance.serialize
train
def serialize(self, value, **kwargs): """Serialize instance to JSON If the value is a HasProperties instance, it is serialized with the include_class argument passed along. Otherwise, to_json is called. """ kwargs.update({'include_class': kwargs.get('include_class', True)}) if self.serializer is not None:
python
{ "resource": "" }
q15888
Instance.to_json
train
def to_json(value, **kwargs): """Convert instance to JSON""" if isinstance(value, HasProperties): return value.serialize(**kwargs) try: return json.loads(json.dumps(value)) except TypeError: raise TypeError(
python
{ "resource": "" }
q15889
Instance.sphinx_class
train
def sphinx_class(self): """Redefine sphinx class so documentation links to instance_class""" classdoc =
python
{ "resource": "" }
q15890
properties_observer
train
def properties_observer(instance, prop, callback, **kwargs): """Adds properties callback
python
{ "resource": "" }
q15891
directional_link._update
train
def _update(self, *_): """Set target value to source value""" if getattr(self, '_unlinked', False): return if getattr(self, '_updating', False): return self._updating = True try:
python
{ "resource": "" }
q15892
Array.validate
train
def validate(self, instance, value): """Determine if array is valid based on shape and dtype""" if not isinstance(value, (tuple, list, np.ndarray)): self.error(instance, value) if self.coerce: value = self.wrapper(value) valid_class = ( self.wrapper if isinstance(self.wrapper, type) else np.ndarray ) if not isinstance(value, valid_class): self.error(instance, value) allowed_kinds = ''.join(TYPE_MAPPINGS[typ] for typ in self.dtype) if value.dtype.kind not in allowed_kinds: self.error(instance, value, extra='Invalid dtype.') if self.shape is None:
python
{ "resource": "" }
q15893
Array.error
train
def error(self, instance, value, error_class=None, extra=''): """Generates a ValueError on setting property to an invalid value""" error_class = error_class or ValidationError if not isinstance(value, (list, tuple, np.ndarray)): super(Array, self).error(instance, value, error_class, extra) if isinstance(value, (list, tuple)): val_description = 'A {typ} of length {len}'.format( typ=value.__class__.__name__, len=len(value) ) else: val_description = 'An array of shape {shp} and dtype {typ}'.format( shp=value.shape, typ=value.dtype ) if instance is None: prefix = '{} property'.format(self.__class__.__name__) else: prefix = "The '{name}' property of a {cls} instance".format( name=self.name,
python
{ "resource": "" }
q15894
Array.deserialize
train
def deserialize(self, value, **kwargs): """De-serialize the property value from JSON If no deserializer has been registered, this converts the value to the wrapper class with given dtype. """ kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None:
python
{ "resource": "" }
q15895
Array.to_json
train
def to_json(value, **kwargs): """Convert array to JSON list nan values are converted to string 'nan', inf values to 'inf'. """ def _recurse_list(val): if val and isinstance(val[0], list): return [_recurse_list(v) for
python
{ "resource": "" }
q15896
BaseVector.validate
train
def validate(self, instance, value): """Check shape and dtype of vector and scales it to given length""" value = super(BaseVector, self).validate(instance, value) if self.length is not None: try: value.length = self._length_array(value) except ZeroDivisionError: self.error(
python
{ "resource": "" }
q15897
LazyI18nString.localize
train
def localize(self, lng: str) -> str: """ Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will give you the string in the first language available. :param lng: A locale code, e.g. ``de``. If you specify a code including a country or region like ``de-AT``, exact matches will be used preferably, but if only a ``de`` or ``de-AT`` translation exists, this might be returned as well. """ if self.data is None: return "" if isinstance(self.data, dict): firstpart = lng.split('-')[0] similar = [l for l in self.data.keys() if (l.startswith(firstpart + "-") or firstpart == l) and l != lng] if self.data.get(lng): return self.data[lng] elif self.data.get(firstpart):
python
{ "resource": "" }
q15898
_set_listener
train
def _set_listener(instance, obs): """Add listeners to a HasProperties instance""" if obs.names is everything: names = list(instance._props) else: names = obs.names for name in names: if name not in
python
{ "resource": "" }
q15899
_get_listeners
train
def _get_listeners(instance, change): """Gets listeners of changed Property on a HasProperties instance""" if ( change['mode'] not in listeners_disabled._quarantine and #pylint: disable=protected-access
python
{ "resource": "" }