id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
15,800
tjcsl/ion
fabfile.py
load_fixtures
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
def load_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)
[ "def", "load_fixtures", "(", ")", ":", "if", "local", "(", "\"pwd\"", ",", "capture", "=", "True", ")", "==", "PRODUCTION_DOCUMENT_ROOT", ":", "abort", "(", "\"Refusing to automatically load fixtures into production database!\"", ")", "if", "not", "confirm", "(", "\...
Populate a database with data from fixtures.
[ "Populate", "a", "database", "with", "data", "from", "fixtures", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L151-L167
15,801
tjcsl/ion
fabfile.py
deploy
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
def deploy(): _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.")
[ "def", "deploy", "(", ")", ":", "_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...
Deploy to production.
[ "Deploy", "to", "production", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L170-L198
15,802
tjcsl/ion
fabfile.py
forcemigrate
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
def forcemigrate(app=None): if app is None: abort("No app name given.") local("./manage.py migrate {} --fake".format(app)) local("./manage.py migrate {}".format(app))
[ "def", "forcemigrate", "(", "app", "=", "None", ")", ":", "if", "app", "is", "None", ":", "abort", "(", "\"No app name given.\"", ")", "local", "(", "\"./manage.py migrate {} --fake\"", ".", "format", "(", "app", ")", ")", "local", "(", "\"./manage.py migrate ...
Force migrations to apply for a given app.
[ "Force", "migrations", "to", "apply", "for", "a", "given", "app", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L201-L206
15,803
tjcsl/ion
intranet/apps/users/models.py
UserManager.users_with_birthday
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
def users_with_birthday(self, month, day): 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
[ "def", "users_with_birthday", "(", "self", ",", "month", ",", "day", ")", ":", "users", "=", "User", ".", "objects", ".", "filter", "(", "properties___birthday__month", "=", "month", ",", "properties___birthday__day", "=", "day", ")", "results", "=", "[", "]...
Return a list of user objects who have a birthday on a given date.
[ "Return", "a", "list", "of", "user", "objects", "who", "have", "a", "birthday", "on", "a", "given", "date", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L82-L91
15,804
tjcsl/ion
intranet/apps/users/models.py
UserManager.get_teachers_sorted
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
def get_teachers_sorted(self): 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
[ "def", "get_teachers_sorted", "(", "self", ")", ":", "teachers", "=", "self", ".", "get_teachers", "(", ")", "teachers", "=", "[", "(", "u", ".", "last_name", ",", "u", ".", "first_name", ",", "u", ".", "id", ")", "for", "u", "in", "teachers", "]", ...
Get teachers sorted by last name. This is used for the announcement request page.
[ "Get", "teachers", "sorted", "by", "last", "name", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L113-L133
15,805
tjcsl/ion
intranet/apps/users/models.py
User.member_of
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
def member_of(self, group): if isinstance(group, Group): group = group.name return self.groups.filter(name=group).exists()
[ "def", "member_of", "(", "self", ",", "group", ")", ":", "if", "isinstance", "(", "group", ",", "Group", ")", ":", "group", "=", "group", ".", "name", "return", "self", ".", "groups", ".", "filter", "(", "name", "=", "group", ")", ".", "exists", "(...
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
[ "Returns", "whether", "a", "user", "is", "a", "member", "of", "a", "certain", "group", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L209-L222
15,806
tjcsl/ion
intranet/apps/users/models.py
User.permissions
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
def permissions(self): # 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
[ "def", "permissions", "(", "self", ")", ":", "# 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", "...
Dynamically generate dictionary of privacy options
[ "Dynamically", "generate", "dictionary", "of", "privacy", "options" ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L343-L360
15,807
tjcsl/ion
intranet/apps/users/models.py
User._current_user_override
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
def _current_user_override(self): 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
[ "def", "_current_user_override", "(", "self", ")", ":", "try", ":", "# threadlocals is a module, not an actual thread locals object", "request", "=", "threadlocals", ".", "request", "(", ")", "if", "request", "is", "None", ":", "return", "False", "requesting_user", "=...
Return whether the currently logged in user is a teacher, and can view all of a student's information regardless of their privacy settings.
[ "Return", "whether", "the", "currently", "logged", "in", "user", "is", "a", "teacher", "and", "can", "view", "all", "of", "a", "student", "s", "information", "regardless", "of", "their", "privacy", "settings", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L362-L377
15,808
tjcsl/ion
intranet/apps/users/models.py
User.age
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
def age(self): date = datetime.today().date() b = self.birthday if b: return int((date - b).days / 365) return None
[ "def", "age", "(", "self", ")", ":", "date", "=", "datetime", ".", "today", "(", ")", ".", "date", "(", ")", "b", "=", "self", ".", "birthday", "if", "b", ":", "return", "int", "(", "(", "date", "-", "b", ")", ".", "days", "/", "365", ")", ...
Returns a user's age, based on their birthday. Returns: integer
[ "Returns", "a", "user", "s", "age", "based", "on", "their", "birthday", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L400-L413
15,809
tjcsl/ion
intranet/apps/users/models.py
User.is_eighth_sponsor
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
def is_eighth_sponsor(self): # FIXME: remove recursive dep from ..eighth.models import EighthSponsor return EighthSponsor.objects.filter(user=self).exists()
[ "def", "is_eighth_sponsor", "(", "self", ")", ":", "# FIXME: remove recursive dep", "from", ".", ".", "eighth", ".", "models", "import", "EighthSponsor", "return", "EighthSponsor", ".", "objects", ".", "filter", "(", "user", "=", "self", ")", ".", "exists", "(...
Determine whether the given user is associated with an. :class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity sponsoring information.
[ "Determine", "whether", "the", "given", "user", "is", "associated", "with", "an", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L639-L649
15,810
tjcsl/ion
intranet/apps/users/models.py
User.frequent_signups
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
def frequent_signups(self): 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
[ "def", "frequent_signups", "(", "self", ")", ":", "key", "=", "\"{}:frequent_signups\"", ".", "format", "(", "self", ".", "username", ")", "cached", "=", "cache", ".", "get", "(", "key", ")", "if", "cached", ":", "return", "cached", "freq_signups", "=", ...
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
[ "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" ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L656-L668
15,811
tjcsl/ion
intranet/apps/users/models.py
User.absence_count
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
def absence_count(self): # FIXME: remove recursive dep from ..eighth.models import EighthSignup return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True).count()
[ "def", "absence_count", "(", "self", ")", ":", "# FIXME: remove recursive dep", "from", ".", ".", "eighth", ".", "models", "import", "EighthSignup", "return", "EighthSignup", ".", "objects", ".", "filter", "(", "user", "=", "self", ",", "was_absent", "=", "Tru...
Return the user's absence count. If the user has no absences or is not a signup user, returns 0.
[ "Return", "the", "user", "s", "absence", "count", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L735-L745
15,812
tjcsl/ion
intranet/apps/users/models.py
User.absence_info
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
def absence_info(self): # FIXME: remove recursive dep from ..eighth.models import EighthSignup return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True)
[ "def", "absence_info", "(", "self", ")", ":", "# FIXME: remove recursive dep", "from", ".", ".", "eighth", ".", "models", "import", "EighthSignup", "return", "EighthSignup", ".", "objects", ".", "filter", "(", "user", "=", "self", ",", "was_absent", "=", "True...
Return information about the user's absences.
[ "Return", "information", "about", "the", "user", "s", "absences", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L747-L752
15,813
tjcsl/ion
intranet/apps/users/models.py
User.handle_delete
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
def handle_delete(self): from intranet.apps.eighth.models import EighthScheduledActivity EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update( archived_member_count=F('archived_member_count')+1)
[ "def", "handle_delete", "(", "self", ")", ":", "from", "intranet", ".", "apps", ".", "eighth", ".", "models", "import", "EighthScheduledActivity", "EighthScheduledActivity", ".", "objects", ".", "filter", "(", "eighthsignup_set__user", "=", "self", ")", ".", "up...
Handle a graduated user being deleted.
[ "Handle", "a", "graduated", "user", "being", "deleted", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L754-L758
15,814
tjcsl/ion
intranet/apps/users/models.py
UserProperties.set_permission
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
def set_permission(self, permission, value, parent=False, admin=False): 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
[ "def", "set_permission", "(", "self", ",", "permission", ",", "value", ",", "parent", "=", "False", ",", "admin", "=", "False", ")", ":", "try", ":", "if", "not", "getattr", "(", "self", ",", "'parent_{}'", ".", "format", "(", "permission", ")", ")", ...
Sets permission for personal information. Returns False silently if unable to set permission. Returns True if successful.
[ "Sets", "permission", "for", "personal", "information", ".", "Returns", "False", "silently", "if", "unable", "to", "set", "permission", ".", "Returns", "True", "if", "successful", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L829-L848
15,815
tjcsl/ion
intranet/apps/users/models.py
UserProperties.attribute_is_visible
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
def attribute_is_visible(self, permission): 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))
[ "def", "attribute_is_visible", "(", "self", ",", "permission", ")", ":", "try", ":", "parent", "=", "getattr", "(", "self", ",", "\"parent_{}\"", ".", "format", "(", "permission", ")", ")", "student", "=", "getattr", "(", "self", ",", "\"self_{}\"", ".", ...
Checks privacy options to see if an attribute is visible to public
[ "Checks", "privacy", "options", "to", "see", "if", "an", "attribute", "is", "visible", "to", "public" ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L890-L898
15,816
tjcsl/ion
intranet/apps/auth/decorators.py
admin_required
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
def admin_required(group): def in_admin_group(user): return user.is_authenticated and user.has_admin_permission(group) return user_passes_test(in_admin_group)
[ "def", "admin_required", "(", "group", ")", ":", "def", "in_admin_group", "(", "user", ")", ":", "return", "user", ".", "is_authenticated", "and", "user", ".", "has_admin_permission", "(", "group", ")", "return", "user_passes_test", "(", "in_admin_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.
[ "Decorator", "that", "requires", "the", "user", "to", "be", "in", "a", "certain", "admin", "group", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/decorators.py#L10-L21
15,817
tjcsl/ion
intranet/apps/preferences/views.py
get_personal_info
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
def get_personal_info(user): # 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
[ "def", "get_personal_info", "(", "user", ")", ":", "# change this to not use other_phones", "num_phones", "=", "len", "(", "user", ".", "phones", ".", "all", "(", ")", "or", "[", "]", ")", "num_emails", "=", "len", "(", "user", ".", "emails", ".", "all", ...
Get a user's personal info attributes to pass as an initial value to a PersonalInformationForm.
[ "Get", "a", "user", "s", "personal", "info", "attributes", "to", "pass", "as", "an", "initial", "value", "to", "a", "PersonalInformationForm", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L17-L38
15,818
tjcsl/ion
intranet/apps/preferences/views.py
get_preferred_pic
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
def get_preferred_pic(user): # 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
[ "def", "get_preferred_pic", "(", "user", ")", ":", "# FIXME: remove this hardcoded junk", "preferred_pic", "=", "{", "\"preferred_photo\"", ":", "\"AUTO\"", "}", "if", "user", ".", "preferred_photo", ":", "preferred_pic", "[", "\"preferred_photo\"", "]", "=", "user", ...
Get a user's preferred picture attributes to pass as an initial value to a PreferredPictureForm.
[ "Get", "a", "user", "s", "preferred", "picture", "attributes", "to", "pass", "as", "an", "initial", "value", "to", "a", "PreferredPictureForm", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L64-L73
15,819
tjcsl/ion
intranet/apps/preferences/views.py
get_privacy_options
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
def get_privacy_options(user): 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
[ "def", "get_privacy_options", "(", "user", ")", ":", "privacy_options", "=", "{", "}", "for", "ptype", "in", "user", ".", "permissions", ":", "for", "field", "in", "user", ".", "permissions", "[", "ptype", "]", ":", "if", "ptype", "==", "\"self\"", ":", ...
Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm.
[ "Get", "a", "user", "s", "privacy", "options", "to", "pass", "as", "an", "initial", "value", "to", "a", "PrivacyOptionsForm", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L110-L122
15,820
tjcsl/ion
intranet/apps/preferences/views.py
get_notification_options
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
def get_notification_options(user): 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
[ "def", "get_notification_options", "(", "user", ")", ":", "notification_options", "=", "{", "}", "notification_options", "[", "\"receive_news_emails\"", "]", "=", "user", ".", "receive_news_emails", "notification_options", "[", "\"receive_eighth_emails\"", "]", "=", "us...
Get a user's notification options to pass as an initial value to a NotificationOptionsForm.
[ "Get", "a", "user", "s", "notification", "options", "to", "pass", "as", "an", "initial", "value", "to", "a", "NotificationOptionsForm", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L167-L181
15,821
tjcsl/ion
intranet/apps/preferences/views.py
preferences_view
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
def preferences_view(request): 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)
[ "def", "preferences_view", "(", "request", ")", ":", "user", "=", "request", ".", "user", "if", "request", ".", "method", "==", "\"POST\"", ":", "logger", ".", "debug", "(", "dict", "(", "request", ".", "POST", ")", ")", "phone_formset", ",", "email_form...
View and process updates to the preferences page.
[ "View", "and", "process", "updates", "to", "the", "preferences", "page", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L263-L322
15,822
tjcsl/ion
intranet/apps/preferences/views.py
privacy_options_view
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
def privacy_options_view(request): 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)
[ "def", "privacy_options_view", "(", "request", ")", ":", "if", "\"user\"", "in", "request", ".", "GET", ":", "user", "=", "User", ".", "objects", ".", "user_with_ion_id", "(", "request", ".", "GET", ".", "get", "(", "\"user\"", ")", ")", "elif", "\"stude...
View and edit privacy options for a user.
[ "View", "and", "edit", "privacy", "options", "for", "a", "user", "." ]
5d722b0725d572039bb0929fd5715a4070c82c72
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L326-L352
15,823
codelv/enaml-native-barcode
src/zxing/android/android_barcode.py
IntentIntegrator.scan
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
def scan(cls, formats=ALL_CODE_TYPES, camera=-1): 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
[ "def", "scan", "(", "cls", ",", "formats", "=", "ALL_CODE_TYPES", ",", "camera", "=", "-", "1", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "r", "=", "app", ".", "create_future", "(", ")", "#: Initiate a scan", "pkg", "=", "B...
Shortcut only one at a time will work...
[ "Shortcut", "only", "one", "at", "a", "time", "will", "work", "..." ]
dc3c4b41980c0f93d7fa828f48a751ae26daf297
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L66-L83
15,824
codelv/enaml-native-barcode
src/zxing/android/android_barcode.py
AndroidBarcodeView.on_activity_lifecycle_changed
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
def on_activity_lifecycle_changed(self, change): d = self.declaration if d.active: if change['value'] == 'paused': self.widget.pause(now=True) elif change['value'] == 'resumed': self.widget.resume()
[ "def", "on_activity_lifecycle_changed", "(", "self", ",", "change", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "active", ":", "if", "change", "[", "'value'", "]", "==", "'paused'", ":", "self", ".", "widget", ".", "pause", "(", "no...
If the app pauses without pausing the barcode scanner the camera can't be reopened. So we must do it here.
[ "If", "the", "app", "pauses", "without", "pausing", "the", "barcode", "scanner", "the", "camera", "can", "t", "be", "reopened", ".", "So", "we", "must", "do", "it", "here", "." ]
dc3c4b41980c0f93d7fa828f48a751ae26daf297
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L144-L153
15,825
codelv/enaml-native-barcode
src/zxing/android/android_barcode.py
AndroidBarcodeView.destroy
def destroy(self): """ Cleanup the activty lifecycle listener """ if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
python
def destroy(self): if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "widget", ":", "self", ".", "set_active", "(", "False", ")", "super", "(", "AndroidBarcodeView", ",", "self", ")", ".", "destroy", "(", ")" ]
Cleanup the activty lifecycle listener
[ "Cleanup", "the", "activty", "lifecycle", "listener" ]
dc3c4b41980c0f93d7fa828f48a751ae26daf297
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L155-L159
15,826
inbo/pyinaturalist
pyinaturalist/node_api.py
make_inaturalist_api_get_call
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
def make_inaturalist_api_get_call(endpoint: str, params: Dict, **kwargs) -> requests.Response: headers = {'Accept': 'application/json'} response = requests.get(urljoin(INAT_NODE_API_BASE_URL, endpoint), params, headers=headers, **kwargs) return response
[ "def", "make_inaturalist_api_get_call", "(", "endpoint", ":", "str", ",", "params", ":", "Dict", ",", "*", "*", "kwargs", ")", "->", "requests", ".", "Response", ":", "headers", "=", "{", "'Accept'", ":", "'application/json'", "}", "response", "=", "requests...
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
[ "Make", "an", "API", "call", "to", "iNaturalist", "." ]
d380ede84bdf15eca8ccab9efefe08d2505fe6a8
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L16-L27
15,827
inbo/pyinaturalist
pyinaturalist/node_api.py
get_observation
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
def get_observation(observation_id: int) -> Dict[str, Any]: r = get_observations(params={'id': observation_id}) if r['results']: return r['results'][0] raise ObservationNotFound()
[ "def", "get_observation", "(", "observation_id", ":", "int", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "r", "=", "get_observations", "(", "params", "=", "{", "'id'", ":", "observation_id", "}", ")", "if", "r", "[", "'results'", "]", ":", "...
Get details about an observation. :param observation_id: :returns: a dict with details on the observation :raises: ObservationNotFound
[ "Get", "details", "about", "an", "observation", "." ]
d380ede84bdf15eca8ccab9efefe08d2505fe6a8
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L30-L42
15,828
inbo/pyinaturalist
pyinaturalist/rest_api.py
get_access_token
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
def get_access_token(username: str, password: str, app_id: str, app_secret: str) -> str: 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.")
[ "def", "get_access_token", "(", "username", ":", "str", ",", "password", ":", "str", ",", "app_id", ":", "str", ",", "app_secret", ":", "str", ")", "->", "str", ":", "payload", "=", "{", "'client_id'", ":", "app_id", ",", "'client_secret'", ":", "app_sec...
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}
[ "Get", "an", "access", "token", "using", "the", "user", "s", "iNaturalist", "username", "and", "password", "." ]
d380ede84bdf15eca8ccab9efefe08d2505fe6a8
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L97-L121
15,829
inbo/pyinaturalist
pyinaturalist/rest_api.py
add_photo_to_observation
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
def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str): 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()
[ "def", "add_photo_to_observation", "(", "observation_id", ":", "int", ",", "file_object", ":", "BinaryIO", ",", "access_token", ":", "str", ")", ":", "data", "=", "{", "'observation_photo[observation_id]'", ":", "observation_id", "}", "file_data", "=", "{", "'file...
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()`
[ "Upload", "a", "picture", "and", "assign", "it", "to", "an", "existing", "observation", "." ]
d380ede84bdf15eca8ccab9efefe08d2505fe6a8
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L128-L143
15,830
inbo/pyinaturalist
pyinaturalist/rest_api.py
delete_observation
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
def delete_observation(observation_id: int, access_token: str) -> List[Dict[str, Any]]: 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()
[ "def", "delete_observation", "(", "observation_id", ":", "int", ",", "access_token", ":", "str", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "headers", "=", "_build_auth_header", "(", "access_token", ")", "headers", "[", "'Conten...
Delete an observation. :param observation_id: :param access_token: :return:
[ "Delete", "an", "observation", "." ]
d380ede84bdf15eca8ccab9efefe08d2505fe6a8
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L197-L216
15,831
digidotcom/python-suitcase
suitcase/fields.py
FieldPlaceholder.create_instance
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
def create_instance(self, parent): self.kwargs['instantiate'] = True self.kwargs['parent'] = parent instance = self.cls(*self.args, **self.kwargs) instance._field_seqno = self._field_seqno return instance
[ "def", "create_instance", "(", "self", ",", "parent", ")", ":", "self", ".", "kwargs", "[", "'instantiate'", "]", "=", "True", "self", ".", "kwargs", "[", "'parent'", "]", "=", "parent", "instance", "=", "self", ".", "cls", "(", "*", "self", ".", "ar...
Create an instance based off this placeholder with some parent
[ "Create", "an", "instance", "based", "off", "this", "placeholder", "with", "some", "parent" ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L36-L42
15,832
digidotcom/python-suitcase
suitcase/fields.py
BaseField._ph2f
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
def _ph2f(self, placeholder): if issubclass(placeholder.cls, FieldAccessor): return placeholder.cls.access(self._parent, placeholder) return self._parent.lookup_field_by_placeholder(placeholder)
[ "def", "_ph2f", "(", "self", ",", "placeholder", ")", ":", "if", "issubclass", "(", "placeholder", ".", "cls", ",", "FieldAccessor", ")", ":", "return", "placeholder", ".", "cls", ".", "access", "(", "self", ".", "_parent", ",", "placeholder", ")", "retu...
Lookup a field given a field placeholder
[ "Lookup", "a", "field", "given", "a", "field", "placeholder" ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L87-L91
15,833
digidotcom/python-suitcase
suitcase/fields.py
CRCField.packed_checksum
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
def packed_checksum(self, data): self.field.setval(self.algo(data[self.start:self.end])) sio = BytesIO() self.field.pack(sio) return sio.getvalue()
[ "def", "packed_checksum", "(", "self", ",", "data", ")", ":", "self", ".", "field", ".", "setval", "(", "self", ".", "algo", "(", "data", "[", "self", ".", "start", ":", "self", ".", "end", "]", ")", ")", "sio", "=", "BytesIO", "(", ")", "self", ...
Given the data of the entire packet return the checksum bytes
[ "Given", "the", "data", "of", "the", "entire", "packet", "return", "the", "checksum", "bytes" ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L176-L181
15,834
digidotcom/python-suitcase
suitcase/fields.py
FieldAccessor.access
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
def access(cls, parent, placeholder): 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
[ "def", "access", "(", "cls", ",", "parent", ",", "placeholder", ")", ":", "try", ":", "return", "parent", ".", "lookup_field_by_placeholder", "(", "placeholder", ")", "except", "KeyError", ":", "field_placeholder", ",", "name", "=", "placeholder", ".", "args",...
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
[ "Resolve", "the", "deferred", "field", "attribute", "access", "." ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L1493-L1511
15,835
digidotcom/python-suitcase
suitcase/crc.py
crc16_ccitt
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
def crc16_ccitt(data, crc=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
[ "def", "crc16_ccitt", "(", "data", ",", "crc", "=", "0", ")", ":", "tab", "=", "CRC16_CCITT_TAB", "# minor optimization (now in locals)", "for", "byte", "in", "six", ".", "iterbytes", "(", "data", ")", ":", "crc", "=", "(", "(", "(", "crc", "<<", "8", ...
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.
[ "Calculate", "the", "crc16", "ccitt", "checksum", "of", "some", "data" ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/crc.py#L100-L114
15,836
digidotcom/python-suitcase
suitcase/protocol.py
StreamProtocolHandler.feed
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
def feed(self, new_bytes): 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()
[ "def", "feed", "(", "self", ",", "new_bytes", ")", ":", "self", ".", "_available_bytes", "+=", "new_bytes", "callbacks", "=", "[", "]", "try", ":", "while", "True", ":", "packet", "=", "six", ".", "next", "(", "self", ".", "_packet_generator", ")", "if...
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.
[ "Feed", "a", "new", "set", "of", "bytes", "into", "the", "protocol", "handler" ]
b53681a33efd350daf1b63094b1d21587e45a806
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/protocol.py#L113-L148
15,837
seequent/properties
properties/extras/web.py
URL.validate
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
def validate(self, instance, value): 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
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "value", "=", "super", "(", "URL", ",", "self", ")", ".", "validate", "(", "instance", ",", "value", ")", "parsed_url", "=", "urlparse", "(", "value", ")", "if", "not", "parsed_...
Check if input is valid URL
[ "Check", "if", "input", "is", "valid", "URL" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/web.py#L46-L61
15,838
seequent/properties
properties/extras/singleton.py
Singleton.serialize
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
def serialize(self, include_class=True, save_dynamic=False, **kwargs): 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
[ "def", "serialize", "(", "self", ",", "include_class", "=", "True", ",", "save_dynamic", "=", "False", ",", "*", "*", "kwargs", ")", ":", "json_dict", "=", "super", "(", "Singleton", ",", "self", ")", ".", "serialize", "(", "include_class", "=", "include...
Serialize Singleton instance to a dictionary. This behaves identically to HasProperties.serialize, except it also saves the identifying name in the dictionary as well.
[ "Serialize", "Singleton", "instance", "to", "a", "dictionary", "." ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/singleton.py#L49-L61
15,839
seequent/properties
properties/extras/singleton.py
Singleton.deserialize
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
def deserialize(cls, value, trusted=False, strict=False, assert_valid=False, **kwargs): 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
[ "def", "deserialize", "(", "cls", ",", "value", ",", "trusted", "=", "False", ",", "strict", "=", "False", ",", "assert_valid", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", ...
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
[ "Create", "a", "Singleton", "instance", "from", "a", "serialized", "dictionary", "." ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/singleton.py#L64-L97
15,840
seequent/properties
properties/base/containers.py
add_properties_callbacks
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
def add_properties_callbacks(cls): 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
[ "def", "add_properties_callbacks", "(", "cls", ")", ":", "for", "name", "in", "cls", ".", "_mutators", ":", "#pylint: disable=protected-access", "if", "not", "hasattr", "(", "cls", ",", "name", ")", ":", "continue", "setattr", "(", "cls", ",", "name", ",", ...
Class decorator to add change notifications to builtin containers
[ "Class", "decorator", "to", "add", "change", "notifications", "to", "builtin", "containers" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L50-L64
15,841
seequent/properties
properties/base/containers.py
properties_mutator
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
def properties_mutator(cls, name, ioper=False): 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
[ "def", "properties_mutator", "(", "cls", ",", "name", ",", "ioper", "=", "False", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Mutate if not part of HasProperties; copy/modify/set otherwise\"\"\"", "if", "(...
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.
[ "Wraps", "a", "mutating", "container", "method", "to", "add", "HasProperties", "notifications" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L66-L93
15,842
seequent/properties
properties/base/containers.py
properties_operator
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
def properties_operator(cls, name): 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
[ "def", "properties_operator", "(", "cls", ",", "name", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Perform operation and cast to container class\"\"\"", "output", "=", "getattr", "(", "super", "(", "cls"...
Wraps a container operator to ensure container class is maintained
[ "Wraps", "a", "container", "operator", "to", "ensure", "container", "class", "is", "maintained" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L95-L106
15,843
seequent/properties
properties/base/containers.py
observable_copy
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
def observable_copy(value, name, instance): 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
[ "def", "observable_copy", "(", "value", ",", "name", ",", "instance", ")", ":", "container_class", "=", "value", ".", "__class__", "if", "container_class", "in", "OBSERVABLE_REGISTRY", ":", "observable_class", "=", "OBSERVABLE_REGISTRY", "[", "container_class", "]",...
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.
[ "Return", "an", "observable", "container", "for", "HasProperties", "notifications" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L108-L138
15,844
seequent/properties
properties/base/containers.py
validate_prop
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
def validate_prop(value): 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
[ "def", "validate_prop", "(", "value", ")", ":", "if", "(", "isinstance", "(", "value", ",", "CLASS_TYPES", ")", "and", "issubclass", "(", "value", ",", "HasProperties", ")", ")", ":", "value", "=", "Instance", "(", "''", ",", "value", ")", "if", "not",...
Validate Property instance for container items
[ "Validate", "Property", "instance", "for", "container", "items" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L140-L153
15,845
seequent/properties
properties/base/containers.py
Tuple.validate
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
def validate(self, instance, value): 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)
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "not", "self", ".", "coerce", "and", "not", "isinstance", "(", "value", ",", "self", ".", "_class_container", ")", ":", "self", ".", "error", "(", "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.
[ "Check", "the", "class", "of", "the", "container", "and", "validate", "each", "element" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L261-L281
15,846
seequent/properties
properties/base/containers.py
Tuple.assert_valid
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
def assert_valid(self, instance, value=None): 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
[ "def", "assert_valid", "(", "self", ",", "instance", ",", "value", "=", "None", ")", ":", "valid", "=", "super", "(", "Tuple", ",", "self", ")", ".", "assert_valid", "(", "instance", ",", "value", ")", "if", "not", "valid", ":", "return", "False", "i...
Check if tuple and contained properties are valid
[ "Check", "if", "tuple", "and", "contained", "properties", "are", "valid" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L283-L305
15,847
seequent/properties
properties/base/containers.py
Tuple.serialize
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
def serialize(self, value, **kwargs): 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
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'include_class'", ":", "kwargs", ".", "get", "(", "'include_class'", ",", "True", ")", "}", ")", "if", "self", ".", "serializer", "i...
Return a serialized copy of the tuple
[ "Return", "a", "serialized", "copy", "of", "the", "tuple" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L307-L316
15,848
seequent/properties
properties/base/containers.py
Tuple.deserialize
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
def deserialize(self, value, **kwargs): 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)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'trusted'", ":", "kwargs", ".", "get", "(", "'trusted'", ",", "False", ")", "}", ")", "if", "self", ".", "deserializer", "is", "...
Return a deserialized copy of the tuple
[ "Return", "a", "deserialized", "copy", "of", "the", "tuple" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L318-L327
15,849
seequent/properties
properties/base/containers.py
Tuple.to_json
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
def to_json(value, **kwargs): serial_list = [ val.serialize(**kwargs) if isinstance(val, HasProperties) else val for val in value ] return serial_list
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "serial_list", "=", "[", "val", ".", "serialize", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "val", ",", "HasProperties", ")", "else", "val", "for", "val", "in", "value", ...
Return a copy of the tuple as a list If the tuple contains HasProperties instances, they are serialized.
[ "Return", "a", "copy", "of", "the", "tuple", "as", "a", "list" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L340-L349
15,850
seequent/properties
properties/base/containers.py
Tuple.sphinx_class
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
def sphinx_class(self): classdoc = self.prop.sphinx_class().replace( ':class:`', '{info} of :class:`' ) return classdoc.format(info=self.class_info)
[ "def", "sphinx_class", "(", "self", ")", ":", "classdoc", "=", "self", ".", "prop", ".", "sphinx_class", "(", ")", ".", "replace", "(", "':class:`'", ",", "'{info} of :class:`'", ")", "return", "classdoc", ".", "format", "(", "info", "=", "self", ".", "c...
Redefine sphinx class to point to prop class
[ "Redefine", "sphinx", "class", "to", "point", "to", "prop", "class" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L360-L365
15,851
seequent/properties
properties/base/containers.py
Dictionary.assert_valid
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
def assert_valid(self, instance, value=None): 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
[ "def", "assert_valid", "(", "self", ",", "instance", ",", "value", "=", "None", ")", ":", "valid", "=", "super", "(", "Dictionary", ",", "self", ")", ".", "assert_valid", "(", "instance", ",", "value", ")", "if", "not", "valid", ":", "return", "False",...
Check if dict and contained properties are valid
[ "Check", "if", "dict", "and", "contained", "properties", "are", "valid" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L600-L615
15,852
seequent/properties
properties/base/containers.py
Dictionary.serialize
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
def serialize(self, value, **kwargs): 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
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'include_class'", ":", "kwargs", ".", "get", "(", "'include_class'", ",", "True", ")", "}", ")", "if", "self", ".", "serializer", "i...
Return a serialized copy of the dict
[ "Return", "a", "serialized", "copy", "of", "the", "dict" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L617-L636
15,853
seequent/properties
properties/base/containers.py
Dictionary.deserialize
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
def deserialize(self, value, **kwargs): 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)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'trusted'", ":", "kwargs", ".", "get", "(", "'trusted'", ",", "False", ")", "}", ")", "if", "self", ".", "deserializer", "is", "...
Return a deserialized copy of the dict
[ "Return", "a", "deserialized", "copy", "of", "the", "dict" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L638-L657
15,854
seequent/properties
properties/base/containers.py
Dictionary.to_json
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
def to_json(value, **kwargs): serial_dict = { key: ( val.serialize(**kwargs) if isinstance(val, HasProperties) else val ) for key, val in iteritems(value) } return serial_dict
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "serial_dict", "=", "{", "key", ":", "(", "val", ".", "serialize", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "val", ",", "HasProperties", ")", "else", "val", ")", "for"...
Return a copy of the dictionary If the values are HasProperties instances, they are serialized
[ "Return", "a", "copy", "of", "the", "dictionary" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L673-L685
15,855
seequent/properties
properties/utils.py
filter_props
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
def filter_props(has_props_cls, input_dict, include_immutable=True): 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)
[ "def", "filter_props", "(", "has_props_cls", ",", "input_dict", ",", "include_immutable", "=", "True", ")", ":", "props_dict", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "iter", "(", "input_dict", ".", "items", "(", ")", ")", "if", "(", "k"...
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'}
[ "Split", "a", "dictionary", "based", "keys", "that", "correspond", "to", "Properties" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/utils.py#L13-L64
15,856
seequent/properties
properties/base/union.py
Union.default
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
def default(self): 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
[ "def", "default", "(", "self", ")", ":", "prop_def", "=", "getattr", "(", "self", ",", "'_default'", ",", "utils", ".", "undefined", ")", "for", "prop", "in", "self", ".", "props", ":", "if", "prop", ".", "default", "is", "utils", ".", "undefined", "...
Default value of the property
[ "Default", "value", "of", "the", "property" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L125-L134
15,857
seequent/properties
properties/base/union.py
Union._try_prop_method
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
def _try_prop_method(self, instance, value, method_name): 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)
[ "def", "_try_prop_method", "(", "self", ",", "instance", ",", "value", ",", "method_name", ")", ":", "error_messages", "=", "[", "]", "for", "prop", "in", "self", ".", "props", ":", "try", ":", "return", "getattr", "(", "prop", ",", "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.
[ "Helper", "method", "to", "perform", "a", "method", "on", "each", "of", "the", "union", "props" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L164-L185
15,858
seequent/properties
properties/base/union.py
Union.assert_valid
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
def assert_valid(self, instance, value=None): 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')
[ "def", "assert_valid", "(", "self", ",", "instance", ",", "value", "=", "None", ")", ":", "valid", "=", "super", "(", "Union", ",", "self", ")", ".", "assert_valid", "(", "instance", ",", "value", ")", "if", "not", "valid", ":", "return", "False", "i...
Check if the Union has a valid value
[ "Check", "if", "the", "Union", "has", "a", "valid", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L191-L200
15,859
seequent/properties
properties/base/union.py
Union.serialize
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
def serialize(self, value, **kwargs): 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)
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'include_class'", ":", "kwargs", ".", "get", "(", "'include_class'", ",", "True", ")", "}", ")", "if", "self", ".", "serializer", "i...
Return a serialized value If no serializer is provided, it uses the serialize method of the prop corresponding to the value
[ "Return", "a", "serialized", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L202-L219
15,860
seequent/properties
properties/base/union.py
Union.deserialize
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
def deserialize(self, value, **kwargs): 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)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'trusted'", ":", "kwargs", ".", "get", "(", "'trusted'", ",", "False", ")", "}", ")", "if", "self", ".", "deserializer", "is", "...
Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value
[ "Return", "a", "deserialized", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L221-L252
15,861
seequent/properties
properties/base/union.py
Union.to_json
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
def to_json(value, **kwargs): if isinstance(value, HasProperties): return value.serialize(**kwargs) return value
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "HasProperties", ")", ":", "return", "value", ".", "serialize", "(", "*", "*", "kwargs", ")", "return", "value" ]
Return value, serialized if value is a HasProperties instance
[ "Return", "value", "serialized", "if", "value", "is", "a", "HasProperties", "instance" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/union.py#L258-L262
15,862
seequent/properties
properties/basic.py
accept_kwargs
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
def accept_kwargs(func): 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
[ "def", "accept_kwargs", "(", "func", ")", ":", "def", "wrapped", "(", "val", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Perform a function on a value, ignoring kwargs if necessary\"\"\"", "try", ":", "return", "func", "(", "val", ",", "*", "*", "kwargs", ")", "...
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.
[ "Wrap", "a", "function", "that", "may", "not", "accept", "kwargs", "so", "they", "are", "accepted" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L34-L53
15,863
seequent/properties
properties/basic.py
GettableProperty.terms
def terms(self): """Initialization terms and options for Property""" terms = PropertyTerms( self.name, self.__class__, self._args, self._kwargs, self.meta ) return terms
python
def terms(self): terms = PropertyTerms( self.name, self.__class__, self._args, self._kwargs, self.meta ) return terms
[ "def", "terms", "(", "self", ")", ":", "terms", "=", "PropertyTerms", "(", "self", ".", "name", ",", "self", ".", "__class__", ",", "self", ".", "_args", ",", "self", ".", "_kwargs", ",", "self", ".", "meta", ")", "return", "terms" ]
Initialization terms and options for Property
[ "Initialization", "terms", "and", "options", "for", "Property" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L146-L155
15,864
seequent/properties
properties/basic.py
GettableProperty.tag
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
def tag(self, *tag, **kwtags): 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
[ "def", "tag", "(", "self", ",", "*", "tag", ",", "*", "*", "kwtags", ")", ":", "if", "not", "tag", ":", "pass", "elif", "len", "(", "tag", ")", "==", "1", "and", "isinstance", "(", "tag", "[", "0", "]", ",", "dict", ")", ":", "self", ".", "...
Tag a Property instance with metadata dictionary
[ "Tag", "a", "Property", "instance", "with", "metadata", "dictionary" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L209-L219
15,865
seequent/properties
properties/basic.py
GettableProperty.equal
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
def equal(self, value_a, value_b): #pylint: disable=no-self-use equal = value_a == value_b if hasattr(equal, '__iter__'): return all(equal) return equal
[ "def", "equal", "(", "self", ",", "value_a", ",", "value_b", ")", ":", "#pylint: disable=no-self-use", "equal", "=", "value_a", "==", "value_b", "if", "hasattr", "(", "equal", ",", "'__iter__'", ")", ":", "return", "all", "(", "equal", ")", "return", "equa...
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
[ "Check", "if", "two", "valid", "Property", "values", "are", "equal" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L264-L275
15,866
seequent/properties
properties/basic.py
GettableProperty.get_property
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
def get_property(self): scope = self def fget(self): """Call the HasProperties _get method""" return self._get(scope.name) return property(fget=fget, doc=scope.sphinx())
[ "def", "get_property", "(", "self", ")", ":", "scope", "=", "self", "def", "fget", "(", "self", ")", ":", "\"\"\"Call the HasProperties _get method\"\"\"", "return", "self", ".", "_get", "(", "scope", ".", "name", ")", "return", "property", "(", "fget", "=",...
Establishes access of GettableProperty values
[ "Establishes", "access", "of", "GettableProperty", "values" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L277-L286
15,867
seequent/properties
properties/basic.py
GettableProperty.deserialize
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
def deserialize(self, value, **kwargs): #pylint: disable=unused-argument 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)
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=unused-argument", "kwargs", ".", "update", "(", "{", "'trusted'", ":", "kwargs", ".", "get", "(", "'trusted'", ",", "False", ")", "}", ")", "if", "self"...
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.
[ "Deserialize", "input", "value", "to", "valid", "Property", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L302-L314
15,868
seequent/properties
properties/basic.py
GettableProperty.sphinx
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
def sphinx(self): 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
[ "def", "sphinx", "(", "self", ")", ":", "try", ":", "assert", "__IPYTHON__", "classdoc", "=", "''", "except", "(", "NameError", ",", "AssertionError", ")", ":", "scls", "=", "self", ".", "sphinx_class", "(", ")", "classdoc", "=", "' ({})'", ".", "format"...
Generate Sphinx-formatted documentation for the Property
[ "Generate", "Sphinx", "-", "formatted", "documentation", "for", "the", "Property" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L359-L374
15,869
seequent/properties
properties/basic.py
GettableProperty.sphinx_class
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
def sphinx_class(self): 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)
[ "def", "sphinx_class", "(", "self", ")", ":", "classdoc", "=", "':class:`{cls} <{pref}.{cls}>`'", "if", "self", ".", "__module__", ".", "split", "(", "'.'", ")", "[", "0", "]", "==", "'properties'", ":", "pref", "=", "'properties'", "else", ":", "pref", "=...
Property class name formatted for Sphinx doc linking
[ "Property", "class", "name", "formatted", "for", "Sphinx", "doc", "linking" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L376-L383
15,870
seequent/properties
properties/basic.py
DynamicProperty.setter
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
def setter(self, func): 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
[ "def", "setter", "(", "self", ",", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "'setter must be callable function'", ")", "if", "hasattr", "(", "func", ",", "'__code__'", ")", "and", "func", ".", "__code__",...
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.
[ "Register", "a", "set", "function", "for", "the", "DynamicProperty" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L521-L535
15,871
seequent/properties
properties/basic.py
DynamicProperty.deleter
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
def deleter(self, func): 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
[ "def", "deleter", "(", "self", ",", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "'deleter must be callable function'", ")", "if", "hasattr", "(", "func", ",", "'__code__'", ")", "and", "func", ".", "__code__...
Register a delete function for the DynamicProperty This function may only take one argument, self.
[ "Register", "a", "delete", "function", "for", "the", "DynamicProperty" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L542-L554
15,872
seequent/properties
properties/basic.py
Property.sphinx
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
def sphinx(self): 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)
[ "def", "sphinx", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "default", ")", ":", "default_val", "=", "self", ".", "default", "(", ")", "default_str", "=", "'new instance of {}'", ".", "format", "(", "default_val", ".", "__class__", ".", "...
Basic docstring formatted for Sphinx docs
[ "Basic", "docstring", "formatted", "for", "Sphinx", "docs" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L685-L706
15,873
seequent/properties
properties/basic.py
Boolean.validate
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
def validate(self, instance, value): if self.cast: value = bool(value) if not isinstance(value, BOOLEAN_TYPES): self.error(instance, value) return value
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "self", ".", "cast", ":", "value", "=", "bool", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "BOOLEAN_TYPES", ")", ":", "self", ".", "error", "(", "i...
Checks if value is a boolean
[ "Checks", "if", "value", "is", "a", "boolean" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L732-L738
15,874
seequent/properties
properties/basic.py
Boolean.from_json
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
def from_json(value, **kwargs): 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))
[ "def", "from_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "value", "=", "value", ".", "upper", "(", ")", "if", "value", "in", "(", "'TRUE'", ",", "'Y'", ",", "'YES'", ",", ...
Coerces JSON string to boolean
[ "Coerces", "JSON", "string", "to", "boolean" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L744-L754
15,875
seequent/properties
properties/basic.py
Complex.validate
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
def validate(self, instance, value): 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
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "try", ":", "compval", "=", "complex", "(", "value", ")", "if", "not", "self", ".", "cast", "and", "(", "abs", "(", "value", ".", "real", "-", "compval", ".", "real", ")", "...
Checks that value is a complex number Floats and Integers are coerced to complex numbers
[ "Checks", "that", "value", "is", "a", "complex", "number" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L907-L925
15,876
seequent/properties
properties/basic.py
String.validate
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
def validate(self, instance, value): 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
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "value_type", "=", "type", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "self", ".", "error", "(", "instance", ",", "value", ")", "...
Check if value is a string, and strips it and changes case
[ "Check", "if", "value", "is", "a", "string", "and", "strips", "it", "and", "changes", "case" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1021-L1037
15,877
seequent/properties
properties/basic.py
StringChoice.info
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
def info(self): 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))
[ "def", "info", "(", "self", ")", ":", "if", "self", ".", "descriptions", "is", "None", ":", "choice_list", "=", "[", "'\"{}\"'", ".", "format", "(", "choice", ")", "for", "choice", "in", "self", ".", "choices", "]", "else", ":", "choice_list", "=", "...
Formatted string to display the available choices
[ "Formatted", "string", "to", "display", "the", "available", "choices" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1073-L1084
15,878
seequent/properties
properties/basic.py
StringChoice.validate
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
def validate(self, instance, value): #pylint: disable=inconsistent-return-statements 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.')
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "#pylint: disable=inconsistent-return-statements", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "self", ".", "error", "(", "instance", ",", "value", ")", "for",...
Check if input is a valid string based on the choices
[ "Check", "if", "input", "is", "a", "valid", "string", "based", "on", "the", "choices" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1158-L1168
15,879
seequent/properties
properties/basic.py
Color.validate
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
def validate(self, instance, value): 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)
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "value", "=", "COLORS_NAMED", ".", "get", "(", "value", ",", "value", ")", "if", "value", ".", "upper", "(", ")"...
Check if input is valid color and converts to RGB
[ "Check", "if", "input", "is", "valid", "color", "and", "converts", "to", "RGB" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1184-L1212
15,880
seequent/properties
properties/basic.py
DateTime.validate
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
def validate(self, instance, value): 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.', )
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "self", "....
Check if value is a valid datetime object or JSON datetime string
[ "Check", "if", "value", "is", "a", "valid", "datetime", "object", "or", "JSON", "datetime", "string" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1236-L1253
15,881
seequent/properties
properties/basic.py
Uuid.validate
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
def validate(self, instance, value): if not isinstance(value, uuid.UUID): self.error(instance, value) return value
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "uuid", ".", "UUID", ")", ":", "self", ".", "error", "(", "instance", ",", "value", ")", "return", "value" ]
Check that value is a valid UUID instance
[ "Check", "that", "value", "is", "a", "valid", "UUID", "instance" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1283-L1287
15,882
seequent/properties
properties/basic.py
File.valid_modes
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
def valid_modes(self): default_mode = (self.mode,) if self.mode is not None else None return getattr(self, '_valid_mode', default_mode)
[ "def", "valid_modes", "(", "self", ")", ":", "default_mode", "=", "(", "self", ".", "mode", ",", ")", "if", "self", ".", "mode", "is", "not", "None", "else", "None", "return", "getattr", "(", "self", ",", "'_valid_mode'", ",", "default_mode", ")" ]
Valid modes of an open file
[ "Valid", "modes", "of", "an", "open", "file" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1341-L1344
15,883
seequent/properties
properties/basic.py
File.validate
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
def validate(self, instance, value): 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
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", "and", "self", ".", "mode", "is", "not", "None", ":", "try", ":", "value", "=", "open", "(", "value", ",", "self", ...
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.
[ "Checks", "that", "the", "value", "is", "a", "valid", "file", "open", "in", "the", "correct", "mode" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1376-L1396
15,884
seequent/properties
properties/basic.py
Renamed.display_warning
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
def display_warning(self): 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 )
[ "def", "display_warning", "(", "self", ")", ":", "if", "self", ".", "warn", ":", "warnings", ".", "warn", "(", "\"\\nProperty '{}' is deprecated and may be removed in the \"", "\"future. Please use '{}'.\"", ".", "format", "(", "self", ".", "name", ",", "self", ".",...
Display a FutureWarning about using a Renamed Property
[ "Display", "a", "FutureWarning", "about", "using", "a", "Renamed", "Property" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/basic.py#L1475-L1482
15,885
seequent/properties
properties/base/instance.py
Instance.validate
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
def validate(self, instance, value): 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)
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "try", ":", "if", "isinstance", "(", "value", ",", "self", ".", "instance_class", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", ...
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.
[ "Check", "if", "value", "is", "valid", "type", "of", "instance_class" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/instance.py#L89-L111
15,886
seequent/properties
properties/base/instance.py
Instance.assert_valid
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
def assert_valid(self, instance, value=None): 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
[ "def", "assert_valid", "(", "self", ",", "instance", ",", "value", "=", "None", ")", ":", "valid", "=", "super", "(", "Instance", ",", "self", ")", ".", "assert_valid", "(", "instance", ",", "value", ")", "if", "not", "valid", ":", "return", "False", ...
Checks if valid, including HasProperty instances pass validation
[ "Checks", "if", "valid", "including", "HasProperty", "instances", "pass", "validation" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/instance.py#L113-L122
15,887
seequent/properties
properties/base/instance.py
Instance.serialize
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
def serialize(self, value, **kwargs): 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)
[ "def", "serialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'include_class'", ":", "kwargs", ".", "get", "(", "'include_class'", ",", "True", ")", "}", ")", "if", "self", ".", "serializer", "i...
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.
[ "Serialize", "instance", "to", "JSON" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/instance.py#L125-L139
15,888
seequent/properties
properties/base/instance.py
Instance.to_json
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
def to_json(value, **kwargs): 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__) )
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "HasProperties", ")", ":", "return", "value", ".", "serialize", "(", "*", "*", "kwargs", ")", "try", ":", "return", "json", ".", "loads", "(", ...
Convert instance to JSON
[ "Convert", "instance", "to", "JSON" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/instance.py#L161-L172
15,889
seequent/properties
properties/base/instance.py
Instance.sphinx_class
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
def sphinx_class(self): classdoc = ':class:`{cls} <{pref}.{cls}>`'.format( cls=self.instance_class.__name__, pref=self.instance_class.__module__, ) return classdoc
[ "def", "sphinx_class", "(", "self", ")", ":", "classdoc", "=", "':class:`{cls} <{pref}.{cls}>`'", ".", "format", "(", "cls", "=", "self", ".", "instance_class", ".", "__name__", ",", "pref", "=", "self", ".", "instance_class", ".", "__module__", ",", ")", "r...
Redefine sphinx class so documentation links to instance_class
[ "Redefine", "sphinx", "class", "so", "documentation", "links", "to", "instance_class" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/instance.py#L183-L189
15,890
seequent/properties
properties/link.py
properties_observer
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
def properties_observer(instance, prop, callback, **kwargs): change_only = kwargs.get('change_only', True) observer(instance, prop, callback, change_only=change_only)
[ "def", "properties_observer", "(", "instance", ",", "prop", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "change_only", "=", "kwargs", ".", "get", "(", "'change_only'", ",", "True", ")", "observer", "(", "instance", ",", "prop", ",", "callback", "...
Adds properties callback handler
[ "Adds", "properties", "callback", "handler" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/link.py#L13-L16
15,891
seequent/properties
properties/link.py
directional_link._update
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
def _update(self, *_): 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
[ "def", "_update", "(", "self", ",", "*", "_", ")", ":", "if", "getattr", "(", "self", ",", "'_unlinked'", ",", "False", ")", ":", "return", "if", "getattr", "(", "self", ",", "'_updating'", ",", "False", ")", ":", "return", "self", ".", "_updating", ...
Set target value to source value
[ "Set", "target", "value", "to", "source", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/link.py#L110-L122
15,892
seequent/properties
properties/math.py
Array.validate
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
def validate(self, instance, value): 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.')
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "self", ".", "error", "(", "instance", ",", "value", ")", ...
Determine if array is valid based on shape and dtype
[ "Determine", "if", "array", "is", "valid", "based", "on", "shape", "and", "dtype" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/math.py#L140-L164
15,893
seequent/properties
properties/math.py
Array.error
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
def error(self, instance, value, error_class=None, extra=''): 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)
[ "def", "error", "(", "self", ",", "instance", ",", "value", ",", "error_class", "=", "None", ",", "extra", "=", "''", ")", ":", "error_class", "=", "error_class", "or", "ValidationError", "if", "not", "isinstance", "(", "value", ",", "(", "list", ",", ...
Generates a ValueError on setting property to an invalid value
[ "Generates", "a", "ValueError", "on", "setting", "property", "to", "an", "invalid", "value" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/math.py#L178-L211
15,894
seequent/properties
properties/math.py
Array.deserialize
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
def deserialize(self, value, **kwargs): 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])
[ "def", "deserialize", "(", "self", ",", "value", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'trusted'", ":", "kwargs", ".", "get", "(", "'trusted'", ",", "False", ")", "}", ")", "if", "self", ".", "deserializer", "is", "...
De-serialize the property value from JSON If no deserializer has been registered, this converts the value to the wrapper class with given dtype.
[ "De", "-", "serialize", "the", "property", "value", "from", "JSON" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/math.py#L213-L224
15,895
seequent/properties
properties/math.py
Array.to_json
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
def to_json(value, **kwargs): 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())
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "def", "_recurse_list", "(", "val", ")", ":", "if", "val", "and", "isinstance", "(", "val", "[", "0", "]", ",", "list", ")", ":", "return", "[", "_recurse_list", "(", "v", ")", "f...
Convert array to JSON list nan values are converted to string 'nan', inf values to 'inf'.
[ "Convert", "array", "to", "JSON", "list" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/math.py#L227-L236
15,896
seequent/properties
properties/math.py
BaseVector.validate
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
def validate(self, instance, value): 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
[ "def", "validate", "(", "self", ",", "instance", ",", "value", ")", ":", "value", "=", "super", "(", "BaseVector", ",", "self", ")", ".", "validate", "(", "instance", ",", "value", ")", "if", "self", ".", "length", "is", "not", "None", ":", "try", ...
Check shape and dtype of vector and scales it to given length
[ "Check", "shape", "and", "dtype", "of", "vector", "and", "scales", "it", "to", "given", "length" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/math.py#L278-L292
15,897
raphaelm/django-i18nfield
i18nfield/strings.py
LazyI18nString.localize
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
def localize(self, lng: str) -> str: 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)
[ "def", "localize", "(", "self", ",", "lng", ":", "str", ")", "->", "str", ":", "if", "self", ".", "data", "is", "None", ":", "return", "\"\"", "if", "isinstance", "(", "self", ".", "data", ",", "dict", ")", ":", "firstpart", "=", "lng", ".", "spl...
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.
[ "Evaluate", "the", "given", "string", "with", "respect", "to", "the", "locale", "defined", "by", "lng", "." ]
fb707931e4498ab1b609eaa0323bb5c3d5f7c7e7
https://github.com/raphaelm/django-i18nfield/blob/fb707931e4498ab1b609eaa0323bb5c3d5f7c7e7/i18nfield/strings.py#L48-L81
15,898
seequent/properties
properties/handlers.py
_set_listener
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
def _set_listener(instance, obs): 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]
[ "def", "_set_listener", "(", "instance", ",", "obs", ")", ":", "if", "obs", ".", "names", "is", "everything", ":", "names", "=", "list", "(", "instance", ".", "_props", ")", "else", ":", "names", "=", "obs", ".", "names", "for", "name", "in", "names"...
Add listeners to a HasProperties instance
[ "Add", "listeners", "to", "a", "HasProperties", "instance" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/handlers.py#L89-L98
15,899
seequent/properties
properties/handlers.py
_get_listeners
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
def _get_listeners(instance, change): 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 []
[ "def", "_get_listeners", "(", "instance", ",", "change", ")", ":", "if", "(", "change", "[", "'mode'", "]", "not", "in", "listeners_disabled", ".", "_quarantine", "and", "#pylint: disable=protected-access", "change", "[", "'name'", "]", "in", "instance", ".", ...
Gets listeners of changed Property on a HasProperties instance
[ "Gets", "listeners", "of", "changed", "Property", "on", "a", "HasProperties", "instance" ]
096b07012fff86b0a880c8c018320c3b512751b9
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/handlers.py#L101-L108