_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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", "fixtures/eighth/activities.json", "fixtures/eighth/scheduled_activities.json", "fixtures/eighth/signups.json", "fixtures/announcements/announcements.json" ] for f in files: local("./manage.py loaddata " + f)
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") else: puts("Python requirements already satisfied.") with prefix("source /usr/local/virtualenvs/ion/bin/activate"): local("./manage.py collectstatic --noinput", shell="/bin/bash") local("./manage.py migrate", shell="/bin/bash") restart_production_gunicorn(skip=True) puts("Deploy complete.")
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 {} --fake".format(app)) local("./manage.py migrate {}".format(app))
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 = [] for user in users: # TODO: permissions system results.append(user) return 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])) # Hack to return QuerySet in given order id_list = [t[2] for t in teachers] clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(id_list)]) ordering = 'CASE %s END' % clauses queryset = User.objects.filter(id__in=id_list).extra(select={'ordering': ordering}, order_by=('ordering',)) return queryset
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 """ if isinstance(group, Group): group = group.name return self.groups.filter(name=group).exists()
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(): split_field = field.name.split('_', 1) if len(split_field) <= 0 or split_field[0] not in ['self', 'parent']: continue permissions_dict[split_field[0]][split_field[1]] = getattr(self.properties, field.name) return permissions_dict
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 can_view_anyway = requesting_user and (requesting_user.is_teacher or requesting_user.is_eighthoffice or requesting_user.is_eighth_admin) except (AttributeError, KeyError) as e: logger.error("Could not check teacher/eighth override: {}".format(e)) can_view_anyway = False return can_view_anyway
python
{ "resource": "" }
q15808
User.age
train
def age(self): """Returns a user's age, based on their birthday. Returns: integer """ date = datetime.today().date() b = self.birthday if b: return int((date - b).days / 365) return None
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 dep from ..eighth.models import EighthSponsor return EighthSponsor.objects.filter(user=self).exists()
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( scheduled_activity__activity__deleted=True).values('scheduled_activity__activity').annotate( count=Count('scheduled_activity__activity')).filter(count__gte=settings.SIMILAR_THRESHOLD).order_by('-count') cache.set(key, freq_signups, timeout=60 * 60 * 24 * 7) return freq_signups
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 return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True).count()
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 return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True)
python
{ "resource": "" }
q15813
User.handle_delete
train
def handle_delete(self): """Handle a graduated user being deleted.""" from intranet.apps.eighth.models import EighthScheduledActivity EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update( archived_member_count=F('archived_member_count')+1)
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. if parent and not value: setattr(self, 'self_{}'.format(permission), False) self.save() return True except Exception as e: logger.error("Error occurred setting permission {} to {}: {}".format(permission, value, e)) return 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)) student = getattr(self, "self_{}".format(permission)) return (parent and student) or (self.is_http_request_sender() or self._current_user_override()) except Exception: logger.error("Could not retrieve permissions for {}".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 is in the "admin_polls" group or in the "admin_all" group. """ def in_admin_group(user): return user.is_authenticated and user.has_admin_permission(group) return user_passes_test(in_admin_group)
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 i in range(num_emails): personal_info["email_{}".format(i)] = user.emails.all()[i] for i in range(num_websites): personal_info["website_{}".format(i)] = user.websites.all()[i] num_fields = {"phones": num_phones, "emails": num_emails, "websites": num_websites} return personal_info, num_fields
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"} if user.preferred_photo: preferred_pic["preferred_photo"] = user.preferred_photo.grade_number return preferred_pic
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": privacy_options["{}-{}".format(field, ptype)] = user.permissions[ptype][field] else: privacy_options[field] = user.permissions[ptype][field] return privacy_options
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: notification_options["primary_email"] = user.primary_email except Email.DoesNotExist: user.primary_email = None user.save() notification_options["primary_email"] = None return notification_options
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 preferred_pic = None preferred_pic_form = None privacy_options = get_privacy_options(user) logger.debug(privacy_options) privacy_options_form = PrivacyOptionsForm(user, initial=privacy_options) notification_options = get_notification_options(user) logger.debug(notification_options) notification_options_form = NotificationOptionsForm(user, initial=notification_options) context = { "phone_formset": phone_formset, "email_formset": email_formset, "website_formset": website_formset, "preferred_pic_form": preferred_pic_form, "privacy_options_form": privacy_options_form, "notification_options_form": notification_options_form, "bus_route_form": bus_route_form if settings.ENABLE_BUS_APP else None } return render(request, "preferences/preferences.html", context)
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) else: privacy_options = get_privacy_options(user) privacy_options_form = PrivacyOptionsForm(user, initial=privacy_options) context = {"privacy_options_form": privacy_options_form, "profile_user": user} else: context = {"profile_user": user} return render(request, "preferences/privacy_options.html", context)
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) if formats: intent.setDesiredBarcodeFormats(formats) if camera != -1: intent.setCameraId(camera) intent.initiateScan() return r
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: if change['value'] == 'paused': self.widget.pause(now=True) elif change['value'] == 'resumed': self.widget.resume()
python
{ "resource": "" }
q15825
AndroidBarcodeView.destroy
train
def destroy(self): """ Cleanup the activty lifecycle listener """ if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
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: 'GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE' kwargs are passed to requests.request Returns a requests.Response object """ headers = {'Accept': 'application/json'} response = requests.get(urljoin(INAT_NODE_API_BASE_URL, endpoint), params, headers=headers, **kwargs) return response
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 """ r = get_observations(params={'id': observation_id}) if r['results']: return r['results'][0] raise 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 } response = requests.post("{base_url}/oauth/token".format(base_url=INAT_BASE_URL), payload) try: return response.json()["access_token"] except KeyError: raise AuthenticationError("Authentication error, please check credentials.")
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} response = requests.post(url="{base_url}/observation_photos".format(base_url=INAT_BASE_URL), headers=_build_auth_header(access_token), data=data, files=file_data) return response.json()
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, id=observation_id), headers=headers) response.raise_for_status() # According to iNaturalist documentation, proper JSON should be returned. It seems however that the response is # currently empty (while the requests succeed), so you may receive a JSONDecode exception. # TODO: report to iNaturalist team if the issue persists return response.json()
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 instance = self.cls(*self.args, **self.kwargs) instance._field_seqno = self._field_seqno return instance
python
{ "resource": "" }
q15832
BaseField._ph2f
train
def _ph2f(self, placeholder): """Lookup a field given a field placeholder""" if issubclass(placeholder.cls, FieldAccessor): return placeholder.cls.access(self._parent, placeholder) return self._parent.lookup_field_by_placeholder(placeholder)
python
{ "resource": "" }
q15833
CRCField.packed_checksum
train
def packed_checksum(self, data): """Given the data of the entire packet return the checksum bytes""" self.field.setval(self.algo(data[self.start:self.end])) sio = BytesIO() self.field.pack(sio) return sio.getvalue()
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) # Instantiate the real FieldAccessor that wraps the attribute. accessor = cls(field, name, parent=parent, instantiate=True) # Keep this instance alive, and reuse it for future references. parent._placeholder_to_field[placeholder] = accessor return accessor
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, then the resultant checksum from this function should be 0. """ tab = CRC16_CCITT_TAB # minor optimization (now in locals) for byte in six.iterbytes(data): crc = (((crc << 8) & 0xff00) ^ tab[((crc >> 8) & 0xff) ^ byte]) return crc & 0xffff
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 reset the buffered entirely # TODO: black hole may not be the best. What should the logging # behavior be? self.reset() # callbacks are partials that are bound to packet already. We do # this in order to separate out parsing activity (and error handling) # from the execution of callbacks. Callbacks should not in any way # rely on the parsers position in the byte stream. for callback in callbacks: callback()
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.') parse_result = ParseResult( scheme=parsed_url.scheme, netloc=parsed_url.netloc, path=parsed_url.path, params='' if self.remove_parameters else parsed_url.params, query='' if self.remove_parameters else parsed_url.query, fragment='' if self.remove_fragment else parsed_url.fragment, ) parse_result = parse_result.geturl() return parse_result
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( include_class=include_class, save_dynamic=save_dynamic, **kwargs ) json_dict['_singleton_id'] = self._singleton_id return json_dict
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: raise ValueError('Singleton classes must contain identifying name') if identifier in cls._SINGLETONS: return cls._SINGLETONS[identifier] value = value.copy() name = value.get('name', None) value.update({'name': identifier}) newinst = super(Singleton, cls).deserialize( value, trusted=trusted, strict=strict, assert_valid=assert_valid, **kwargs ) if name: newinst.name = name return newinst
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): continue setattr(cls, name, properties_operator(cls, name)) for name in cls._ioperators: #pylint: disable=protected-access if not hasattr(cls, name): continue setattr(cls, name, properties_mutator(cls, name, True)) return cls
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 not getattr(self._instance, self._name) ): return getattr(super(cls, self), name)(*args, **kwargs) copy = cls(self) val = getattr(copy, name)(*args, **kwargs) if not ioper: setattr(self._instance, self._name, copy) self._instance = None self._name = '' return val wrapped = getattr(cls, name) wrapper.__name__ = wrapped.__name__ wrapper.__doc__ = wrapped.__doc__ return wrapper
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, **kwargs) return cls(output) wrapped = getattr(cls, name) wrapper.__name__ = wrapped.__name__ wrapper.__doc__ = wrapped.__doc__ return wrapper
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: observable_class = add_properties_callbacks( type(container_class)( str('Observable{}'.format(container_class.__name__)), (container_class,), MUTATOR_CATEGORIES, ) ) OBSERVABLE_REGISTRY[container_class] = observable_class value = observable_class(value) value._name = name value._instance = instance return value
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 ' 'HasProperties class') if value.default is not utils.undefined: warn('Contained prop default ignored: {}'.format(value.default), RuntimeWarning) return value
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: out_class = value.__class__ out = [] for val in value: try: out += [self.prop.validate(instance, val)] except ValueError: self.error(instance, val, extra='This item is invalid.') return out_class(out)
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 and len(value) > self.max_length) ): self.error( instance=instance, value=value, extra='(Length is {})'.format(len(value)), ) for val in value: if not self.prop.assert_valid(instance, val): return False return True
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: return None serial_list = [self.prop.serialize(val, **kwargs) for val in value] return serial_list
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: return None output_list = [self.prop.deserialize(val, **kwargs) for val in value] return self._class_container(output_list)
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 isinstance(val, HasProperties) else val for val in value ] return serial_list
python
{ "resource": "" }
q15850
Tuple.sphinx_class
train
def sphinx_class(self): """Redefine sphinx class to point to prop class""" classdoc = self.prop.sphinx_class().replace( ':class:`', '{info} of :class:`' ) return classdoc.format(info=self.class_info)
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): if self.key_prop: self.key_prop.assert_valid(instance, key) if self.value_prop: self.value_prop.assert_valid(instance, val) return True
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) ) for key, val in iteritems(value) ] try: serial_dict = {key: val for key, val in serial_tuples} except TypeError as err: raise TypeError('Dictionary property {} cannot be serialized - ' 'keys contain {}'.format(self.name, err)) return serial_dict
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) ] try: output_dict = {key: val for key, val in output_tuples} except TypeError as err: raise TypeError('Dictionary property {} cannot be deserialized - ' 'keys contain {}'.format(self.name, err)) return self._class_container(output_dict)
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: ( val.serialize(**kwargs) if isinstance(val, HasProperties) else val ) for key, val in iteritems(value) } return serial_dict
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', } (props, others) = properties.filter_props(Profile, bio_dict) assert set(props) == {'name', 'age'} assert set(others) == {'hometown', 'email'} """ props_dict = { k: v for k, v in iter(input_dict.items()) if ( k in has_props_cls._props and ( include_immutable or any( hasattr(has_props_cls._props[k], att) for att in ('required', 'new_name') ) ) ) } others_dict = {k: v for k, v in iter(input_dict.items()) if k not in props_dict} return (props_dict, others_dict)
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 if prop_def is utils.undefined: prop_def = prop.default break return prop_def
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 += [ err_tup.message for err_tup in err.error_tuples ] if error_messages: extra = 'Possible explanation:' for message in error_messages: extra += '\n - {}'.format(message) else: extra = '' self.error(instance, value, extra=extra)
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: value = instance._get(self.name) if value is None: return True return self._try_prop_method(instance, value, 'assert_valid')
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: try: prop.validate(None, value) except GENERIC_ERRORS: continue return prop.serialize(value, **kwargs) return self.to_json(value, **kwargs)
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) ] kwargs = kwargs.copy() kwargs.update({ 'strict': kwargs.get('strict') or self.strict_instances, 'assert_valid': self.strict_instances, }) if isinstance(value, dict) and value.get('__class__'): clsname = value.get('__class__') for prop in instance_props: if clsname == prop.instance_class.__name__: return prop.deserialize(value, **kwargs) for prop in self.props: try: out_val = prop.deserialize(value, **kwargs) prop.validate(None, out_val) return out_val except GENERIC_ERRORS: continue return self.from_json(value, **kwargs)
python
{ "resource": "" }
q15861
Union.to_json
train
def to_json(value, **kwargs): """Return value, serialized if value is a HasProperties instance""" if isinstance(value, HasProperties): return value.serialize(**kwargs) return value
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 using this, the original functions may simply take a single value. """ def wrapped(val, **kwargs): """Perform a function on a value, ignoring kwargs if necessary""" try: return func(val, **kwargs) except TypeError: return func(val) return wrapped
python
{ "resource": "" }
q15863
GettableProperty.terms
train
def terms(self): """Initialization terms and options for Property""" terms = PropertyTerms( self.name, self.__class__, self._args, self._kwargs, self.meta ) return terms
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 TypeError('Tags must be provided as key-word arguments or ' 'a dictionary') self._meta.update(kwtags) return self
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 as values """ equal = value_a == value_b if hasattr(equal, '__iter__'): return all(equal) return equal
python
{ "resource": "" }
q15866
GettableProperty.get_property
train
def get_property(self): """Establishes access of GettableProperty values""" scope = self def fget(self): """Call the HasProperties _get method""" return self._get(scope.name) return property(fget=fget, doc=scope.sphinx())
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. """ kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: return self.deserializer(value, **kwargs) if value is None: return None return self.from_json(value, **kwargs)
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( name=self.name, cls=classdoc, doc=self.doc, info=', {}'.format(self.info) if self.info else '', ) return prop_doc
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: pref = text_type(self.__module__) return classdoc.format(cls=self.__class__.__name__, pref=pref)
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 func.__code__.co_argcount != 2: raise TypeError('setter must be a function with two arguments') if func.__name__ != self.name: raise TypeError('setter function must have same name as getter') self._set_func = func return self
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 with two arguments') if func.__name__ != self.name: raise TypeError('deleter function must have same name as getter') self._del_func = func return self
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) try: if default_val is None or default_val is undefined: default_str = '' elif len(default_val) == 0: #pylint: disable=len-as-condition default_str = '' else: default_str = ', Default: {}'.format(default_str) except TypeError: default_str = ', Default: {}'.format(default_str) prop_doc = super(Property, self).sphinx() return '{doc}{default}'.format(doc=prop_doc, default=default_str)
python
{ "resource": "" }
q15873
Boolean.validate
train
def validate(self, instance, value): """Checks if value is a boolean""" if self.cast: value = bool(value) if not isinstance(value, BOOLEAN_TYPES): self.error(instance, value) return 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 ('FALSE', 'N', 'NO', 'OFF'): return False if isinstance(value, int): return value raise ValueError('Could not load boolean from JSON: {}'.format(value))
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( instance=instance, value=value, extra='Not within tolerance range of {}.'.format(TOL), ) except (TypeError, ValueError, AttributeError): self.error(instance, value) return compval
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: #pylint: disable=no-member self.error(instance, value, extra='Regex does not match.') value = value.strip(self.strip) if self.change_case == 'upper': value = value.upper() elif self.change_case == 'lower': value = value.lower() if self.unicode: value = text_type(value) else: value = value_type(value) return value
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: choice_list = [ '"{}" ({})'.format(choice, self.descriptions[choice]) for choice in self.choices ] if len(self.choices) == 2: return 'either {} or {}'.format(choice_list[0], choice_list[1]) return 'any of {}'.format(', '.join(choice_list))
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) for key, val in self.choices.items(): test_value = value if self.case_sensitive else value.upper() test_key = key if self.case_sensitive else key.upper() test_val = val if self.case_sensitive else [_.upper() for _ in val] if test_value == test_key or test_value in test_val: return key self.error(instance, value, extra='Not an available choice.')
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, extra='Hex color must be base 16 (0-F)') if not isinstance(value, (list, tuple)): self.error(instance, value, extra='Color must be a list or tuple of length 3') if len(value) != 3: self.error(instance, value, extra='Color must be length 3') for val in value: if not isinstance(val, integer_types) or not 0 <= val <= 255: self.error(instance, value, extra='Color values must be ints 0-255.') return tuple(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.', ) try: return self.from_json(value) except ValueError: self.error( instance=instance, value=value, extra='Invalid format for converting to datetime.', )
python
{ "resource": "" }
q15881
Uuid.validate
train
def validate(self, instance, value): """Check that value is a valid UUID instance""" if not isinstance(value, uuid.UUID): self.error(instance, value) return value
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 return getattr(self, '_valid_mode', default_mode)
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') if not hasattr(value, 'mode') or self.valid_modes is None: pass elif value.mode not in self.valid_modes: self.error(instance, value, extra='Invalid mode: {}'.format(value.mode)) if getattr(value, 'closed', False): self.error(instance, value, extra='File is closed.') return value
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 " "future. Please use '{}'.".format(self.name, self.new_name), FutureWarning, stacklevel=3 )
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): return self.instance_class(**value) return self.instance_class(value) except GENERIC_ERRORS as err: if hasattr(err, 'error_tuples'): extra = '({})'.format(' & '.join( err_tup.message for err_tup in err.error_tuples )) else: extra = '' self.error(instance, value, extra=extra)
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 is None: value = instance._get(self.name) if isinstance(value, HasProperties): value.validate() return True
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: return self.serializer(value, **kwargs) if value is None: return None if isinstance(value, HasProperties): return value.serialize(**kwargs) return self.to_json(value, **kwargs)
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( "Cannot convert type {} to JSON without calling 'serialize' " "on an instance of Instance Property and registering a custom " "serializer".format(value.__class__.__name__) )
python
{ "resource": "" }
q15889
Instance.sphinx_class
train
def sphinx_class(self): """Redefine sphinx class so documentation links to instance_class""" classdoc = ':class:`{cls} <{pref}.{cls}>`'.format( cls=self.instance_class.__name__, pref=self.instance_class.__module__, ) return classdoc
python
{ "resource": "" }
q15890
properties_observer
train
def properties_observer(instance, prop, callback, **kwargs): """Adds properties callback handler""" change_only = kwargs.get('change_only', True) observer(instance, prop, callback, change_only=change_only)
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: setattr(self.target[0], self.target[1], self.transform( getattr(self.source[0], self.source[1]) )) finally: self._updating = False
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: return value for shape in self.shape: if len(shape) != value.ndim: continue for i, shp in enumerate(shape): if shp not in ('*', value.shape[i]): break else: return value self.error(instance, value, extra='Invalid shape.')
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, cls=instance.__class__.__name__, ) message = ( '{prefix} must be {info}. {desc} was specified. {extra}'.format( prefix=prefix, info=self.info, desc=val_description, extra=extra, ) ) if issubclass(error_class, ValidationError): raise error_class(message, 'invalid', self.name, instance) raise error_class(message)
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: return self.deserializer(value, **kwargs) if value is None: return None return self.wrapper(value).astype(self.dtype[0])
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 v in val] return [str(v) if np.isnan(v) or np.isinf(v) else v for v in val] return _recurse_list(value.tolist())
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( instance, value, error_class=ZeroDivValidationError, extra='The vector must have a length specified.' ) return value
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): return self.data[firstpart] elif similar and any([self.data.get(s) for s in similar]): for s in similar: if self.data.get(s): return self.data.get(s) elif self.data.get(settings.LANGUAGE_CODE): return self.data[settings.LANGUAGE_CODE] elif len(self.data): return list(self.data.items())[0][1] else: return "" else: return str(self.data)
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 instance._listeners: instance._listeners[name] = {typ: [] for typ in LISTENER_TYPES} instance._listeners[name][obs.mode] += [obs]
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 change['name'] in instance._listeners ): return instance._listeners[change['name']][change['mode']] return []
python
{ "resource": "" }