repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
tjcsl/ion
intranet/apps/announcements/views.py
request_announcement_view
def request_announcement_view(request): """The request announcement page.""" if request.method == "POST": form = AnnouncementRequestForm(request.POST) logger.debug(form) logger.debug(form.data) if form.is_valid(): teacher_objs = form.cleaned_data["teachers_requested"...
python
def request_announcement_view(request): """The request announcement page.""" if request.method == "POST": form = AnnouncementRequestForm(request.POST) logger.debug(form) logger.debug(form.data) if form.is_valid(): teacher_objs = form.cleaned_data["teachers_requested"...
The request announcement page.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L81-L130
tjcsl/ion
intranet/apps/announcements/views.py
approve_announcement_view
def approve_announcement_view(request, req_id): """The approve announcement page. Teachers will be linked to this page from an email. req_id: The ID of the AnnouncementRequest """ req = get_object_or_404(AnnouncementRequest, id=req_id) requested_teachers = req.teachers_requested.all() logger....
python
def approve_announcement_view(request, req_id): """The approve announcement page. Teachers will be linked to this page from an email. req_id: The ID of the AnnouncementRequest """ req = get_object_or_404(AnnouncementRequest, id=req_id) requested_teachers = req.teachers_requested.all() logger....
The approve announcement page. Teachers will be linked to this page from an email. req_id: The ID of the AnnouncementRequest
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L147-L184
tjcsl/ion
intranet/apps/announcements/views.py
admin_approve_announcement_view
def admin_approve_announcement_view(request, req_id): """The administrator approval announcement request page. Admins will view this page through the UI. req_id: The ID of the AnnouncementRequest """ req = get_object_or_404(AnnouncementRequest, id=req_id) requested_teachers = req.teachers_req...
python
def admin_approve_announcement_view(request, req_id): """The administrator approval announcement request page. Admins will view this page through the UI. req_id: The ID of the AnnouncementRequest """ req = get_object_or_404(AnnouncementRequest, id=req_id) requested_teachers = req.teachers_req...
The administrator approval announcement request page. Admins will view this page through the UI. req_id: The ID of the AnnouncementRequest
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L201-L249
tjcsl/ion
intranet/apps/announcements/views.py
add_announcement_view
def add_announcement_view(request): """Add an announcement.""" if request.method == "POST": form = AnnouncementForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.content = saf...
python
def add_announcement_view(request): """Add an announcement.""" if request.method == "POST": form = AnnouncementForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.content = saf...
Add an announcement.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L268-L286
tjcsl/ion
intranet/apps/announcements/views.py
view_announcement_view
def view_announcement_view(request, id): """View an announcement. id: announcement id """ announcement = get_object_or_404(Announcement, id=id) return render(request, "announcements/view.html", {"announcement": announcement})
python
def view_announcement_view(request, id): """View an announcement. id: announcement id """ announcement = get_object_or_404(Announcement, id=id) return render(request, "announcements/view.html", {"announcement": announcement})
View an announcement. id: announcement id
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L290-L298
tjcsl/ion
intranet/apps/announcements/views.py
modify_announcement_view
def modify_announcement_view(request, id=None): """Modify an announcement. id: announcement id """ if request.method == "POST": announcement = get_object_or_404(Announcement, id=id) form = AnnouncementForm(request.POST, instance=announcement) if form.is_valid(): obj...
python
def modify_announcement_view(request, id=None): """Modify an announcement. id: announcement id """ if request.method == "POST": announcement = get_object_or_404(Announcement, id=id) form = AnnouncementForm(request.POST, instance=announcement) if form.is_valid(): obj...
Modify an announcement. id: announcement id
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L303-L330
tjcsl/ion
intranet/apps/announcements/views.py
delete_announcement_view
def delete_announcement_view(request, id): """Delete an announcement. id: announcement id """ if request.method == "POST": post_id = None try: post_id = request.POST["id"] except AttributeError: post_id = None try: a = Announcement.ob...
python
def delete_announcement_view(request, id): """Delete an announcement. id: announcement id """ if request.method == "POST": post_id = None try: post_id = request.POST["id"] except AttributeError: post_id = None try: a = Announcement.ob...
Delete an announcement. id: announcement id
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L335-L362
tjcsl/ion
intranet/apps/announcements/views.py
show_announcement_view
def show_announcement_view(request): """ Unhide an announcement that was hidden by the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model. """ if request.method == "POST": announcement_id = request.POST.get("announ...
python
def show_announcement_view(request): """ Unhide an announcement that was hidden by the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model. """ if request.method == "POST": announcement_id = request.POST.get("announ...
Unhide an announcement that was hidden by the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L367-L382
tjcsl/ion
intranet/apps/announcements/views.py
hide_announcement_view
def hide_announcement_view(request): """ Hide an announcement for the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model. """ if request.method == "POST": announcement_id = request.POST.get("announcement_id") ...
python
def hide_announcement_view(request): """ Hide an announcement for the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model. """ if request.method == "POST": announcement_id = request.POST.get("announcement_id") ...
Hide an announcement for the logged-in user. announcements_hidden in the user model is the related_name for "users_hidden" in the announcement model.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L387-L405
tjcsl/ion
intranet/apps/auth/forms.py
AuthenticateForm.is_valid
def is_valid(self): """Validates the username and password in the form.""" form = super(AuthenticateForm, self).is_valid() for f, error in self.errors.items(): if f != "__all__": self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error...
python
def is_valid(self): """Validates the username and password in the form.""" form = super(AuthenticateForm, self).is_valid() for f, error in self.errors.items(): if f != "__all__": self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error...
Validates the username and password in the form.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/forms.py#L37-L51
tjcsl/ion
intranet/apps/api/views.py
api_root
def api_root(request, format=None): r"""Welcome to the Ion API! Documentation is below. <pk\> refers to the unique id of a certain object - this is shown as "id" in most lists and references. The general form of the api link (with /api/ assumed to be prepended) is shown, along with an example URL. Al...
python
def api_root(request, format=None): r"""Welcome to the Ion API! Documentation is below. <pk\> refers to the unique id of a certain object - this is shown as "id" in most lists and references. The general form of the api link (with /api/ assumed to be prepended) is shown, along with an example URL. Al...
r"""Welcome to the Ion API! Documentation is below. <pk\> refers to the unique id of a certain object - this is shown as "id" in most lists and references. The general form of the api link (with /api/ assumed to be prepended) is shown, along with an example URL. All of the API methods, except for those r...
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/api/views.py#L18-L91
agoragames/kairos
kairos/redis_backend.py
RedisBackend._calc_keys
def _calc_keys(self, config, name, timestamp): ''' Calculate keys given a stat name and timestamp. ''' i_bucket = config['i_calc'].to_bucket( timestamp ) r_bucket = config['r_calc'].to_bucket( timestamp ) i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket) r_key = '%s:%s...
python
def _calc_keys(self, config, name, timestamp): ''' Calculate keys given a stat name and timestamp. ''' i_bucket = config['i_calc'].to_bucket( timestamp ) r_bucket = config['r_calc'].to_bucket( timestamp ) i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket) r_key = '%s:%s...
Calculate keys given a stat name and timestamp.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L51-L61
agoragames/kairos
kairos/redis_backend.py
RedisBackend._batch_insert
def _batch_insert(self, inserts, intervals, **kwargs): ''' Specialized batch insert ''' if 'pipeline' in kwargs: pipe = kwargs.get('pipeline') own_pipe = False else: pipe = self._client.pipeline(transaction=False) kwargs['pipeline'] = pipe own_pipe = True ttl_batch...
python
def _batch_insert(self, inserts, intervals, **kwargs): ''' Specialized batch insert ''' if 'pipeline' in kwargs: pipe = kwargs.get('pipeline') own_pipe = False else: pipe = self._client.pipeline(transaction=False) kwargs['pipeline'] = pipe own_pipe = True ttl_batch...
Specialized batch insert
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L100-L123
agoragames/kairos
kairos/redis_backend.py
RedisBackend._insert
def _insert(self, name, value, timestamp, intervals, **kwargs): ''' Insert the value. ''' if 'pipeline' in kwargs: pipe = kwargs.get('pipeline') else: pipe = self._client.pipeline(transaction=False) for interval,config in self._intervals.iteritems(): timestamps = self._normali...
python
def _insert(self, name, value, timestamp, intervals, **kwargs): ''' Insert the value. ''' if 'pipeline' in kwargs: pipe = kwargs.get('pipeline') else: pipe = self._client.pipeline(transaction=False) for interval,config in self._intervals.iteritems(): timestamps = self._normali...
Insert the value.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L125-L141
agoragames/kairos
kairos/redis_backend.py
RedisBackend._insert_data
def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None): '''Helper to insert data into redis''' # Calculate the TTL and abort if inserting into the past expire, ttl = config['expire'], config['ttl'](timestamp) if expire and not ttl: return i_bucket, r_bucket, i_...
python
def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None): '''Helper to insert data into redis''' # Calculate the TTL and abort if inserting into the past expire, ttl = config['expire'], config['ttl'](timestamp) if expire and not ttl: return i_bucket, r_bucket, i_...
Helper to insert data into redis
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L143-L173
agoragames/kairos
kairos/redis_backend.py
RedisBackend.delete
def delete(self, name): ''' Delete all the data in a named timeseries. ''' keys = self._client.keys('%s%s:*'%(self._prefix,name)) pipe = self._client.pipeline(transaction=False) for key in keys: pipe.delete( key ) pipe.execute() # Could be not technically the exact number of keys...
python
def delete(self, name): ''' Delete all the data in a named timeseries. ''' keys = self._client.keys('%s%s:*'%(self._prefix,name)) pipe = self._client.pipeline(transaction=False) for key in keys: pipe.delete( key ) pipe.execute() # Could be not technically the exact number of keys...
Delete all the data in a named timeseries.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L175-L188
agoragames/kairos
kairos/redis_backend.py
RedisBackend._get
def _get(self, name, interval, config, timestamp, **kws): ''' Fetch a single interval from redis. ''' i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp) fetch = kws.get('fetch') or self._type_get process_row = kws.get('process_row') or self._process_row rval = Order...
python
def _get(self, name, interval, config, timestamp, **kws): ''' Fetch a single interval from redis. ''' i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp) fetch = kws.get('fetch') or self._type_get process_row = kws.get('process_row') or self._process_row rval = Order...
Fetch a single interval from redis.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L190-L218
agoragames/kairos
kairos/redis_backend.py
RedisBackend._series
def _series(self, name, interval, config, buckets, **kws): ''' Fetch a series of buckets. ''' pipe = self._client.pipeline(transaction=False) step = config['step'] resolution = config.get('resolution',step) fetch = kws.get('fetch') or self._type_get process_row = kws.get('process_row') o...
python
def _series(self, name, interval, config, buckets, **kws): ''' Fetch a series of buckets. ''' pipe = self._client.pipeline(transaction=False) step = config['step'] resolution = config.get('resolution',step) fetch = kws.get('fetch') or self._type_get process_row = kws.get('process_row') o...
Fetch a series of buckets.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L220-L264
agoragames/kairos
kairos/redis_backend.py
RedisCount._type_insert
def _type_insert(self, handle, key, value): ''' Insert the value into the series. ''' if value!=0: if isinstance(value,float): handle.incrbyfloat(key, value) else: handle.incr(key,value)
python
def _type_insert(self, handle, key, value): ''' Insert the value into the series. ''' if value!=0: if isinstance(value,float): handle.incrbyfloat(key, value) else: handle.incr(key,value)
Insert the value into the series.
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L293-L301
tjcsl/ion
fabfile.py
_choose_from_list
def _choose_from_list(options, question): """Choose an item from a list.""" message = "" for index, value in enumerate(options): message += "[{}] {}\n".format(index, value) message += "\n" + question def valid(n): if int(n) not in range(len(options)): raise ValueError("N...
python
def _choose_from_list(options, question): """Choose an item from a list.""" message = "" for index, value in enumerate(options): message += "[{}] {}\n".format(index, value) message += "\n" + question def valid(n): if int(n) not in range(len(options)): raise ValueError("N...
Choose an item from a list.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L17-L31
tjcsl/ion
fabfile.py
runserver
def runserver(port=8080, debug_toolbar="yes", werkzeug="no", dummy_cache="no", short_cache="no", template_warnings="no", log_level="DEBUG", insecure="no"): """Clear compiled python files and start the Django dev server.""" if not port or (not isinstance(port, int) and not port.isdigit()): ...
python
def runserver(port=8080, debug_toolbar="yes", werkzeug="no", dummy_cache="no", short_cache="no", template_warnings="no", log_level="DEBUG", insecure="no"): """Clear compiled python files and start the Django dev server.""" if not port or (not isinstance(port, int) and not port.isdigit()): ...
Clear compiled python files and start the Django dev server.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L39-L58
tjcsl/ion
fabfile.py
clear_sessions
def clear_sessions(venv=None): """Clear all sessions for all sandboxes or for production.""" if "VIRTUAL_ENV" in os.environ: ve = os.path.basename(os.environ["VIRTUAL_ENV"]) else: ve = "" if venv is not None: ve = venv else: ve = prompt("Enter the name of the " ...
python
def clear_sessions(venv=None): """Clear all sessions for all sandboxes or for production.""" if "VIRTUAL_ENV" in os.environ: ve = os.path.basename(os.environ["VIRTUAL_ENV"]) else: ve = "" if venv is not None: ve = venv else: ve = prompt("Enter the name of the " ...
Clear all sessions for all sandboxes or for production.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L90-L122
tjcsl/ion
fabfile.py
clear_cache
def clear_cache(input=None): """Clear the production or sandbox redis cache.""" if input is not None: n = input else: n = _choose_from_list(["Production cache", "Sandbox cache"], "Which cache would you like to clear?") if n == 0: local("redis-cli -n {} FLUSHDB".format(REDIS_PROD...
python
def clear_cache(input=None): """Clear the production or sandbox redis cache.""" if input is not None: n = input else: n = _choose_from_list(["Production cache", "Sandbox cache"], "Which cache would you like to clear?") if n == 0: local("redis-cli -n {} FLUSHDB".format(REDIS_PROD...
Clear the production or sandbox redis cache.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L125-L135
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 conse...
python
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 conse...
Populate a database with data from fixtures.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L151-L167
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_DOCUME...
python
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_DOCUME...
Deploy to production.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L170-L198
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): """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))
Force migrations to apply for a given app.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L201-L206
tjcsl/ion
intranet/apps/users/models.py
UserManager.user_with_student_id
def user_with_student_id(self, student_id): """Get a unique user object by FCPS student ID. (Ex. 1624472)""" results = User.objects.filter(student_id=student_id) if len(results) == 1: return results.first() return None
python
def user_with_student_id(self, student_id): """Get a unique user object by FCPS student ID. (Ex. 1624472)""" results = User.objects.filter(student_id=student_id) if len(results) == 1: return results.first() return None
Get a unique user object by FCPS student ID. (Ex. 1624472)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L39-L44
tjcsl/ion
intranet/apps/users/models.py
UserManager.user_with_ion_id
def user_with_ion_id(self, student_id): """Get a unique user object by Ion ID. (Ex. 489)""" if isinstance(student_id, str) and not student_id.isdigit(): return None results = User.objects.filter(id=student_id) if len(results) == 1: return results.first() r...
python
def user_with_ion_id(self, student_id): """Get a unique user object by Ion ID. (Ex. 489)""" if isinstance(student_id, str) and not student_id.isdigit(): return None results = User.objects.filter(id=student_id) if len(results) == 1: return results.first() r...
Get a unique user object by Ion ID. (Ex. 489)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L46-L53
tjcsl/ion
intranet/apps/users/models.py
UserManager.user_with_name
def user_with_name(self, given_name=None, sn=None): """Get a unique user object by given name (first/nickname and last).""" results = [] if sn and not given_name: results = User.objects.filter(last_name=sn) elif given_name: query = {'first_name': given_name} ...
python
def user_with_name(self, given_name=None, sn=None): """Get a unique user object by given name (first/nickname and last).""" results = [] if sn and not given_name: results = User.objects.filter(last_name=sn) elif given_name: query = {'first_name': given_name} ...
Get a unique user object by given name (first/nickname and last).
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L59-L80
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 ...
python
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 ...
Return a list of user objects who have a birthday on a given date.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L82-L91
tjcsl/ion
intranet/apps/users/models.py
UserManager.get_students
def get_students(self): """Get user objects that are students (quickly).""" users = User.objects.filter(user_type="student", graduation_year__gte=settings.SENIOR_GRADUATION_YEAR) users = users.exclude(id__in=EXTRA) return users
python
def get_students(self): """Get user objects that are students (quickly).""" users = User.objects.filter(user_type="student", graduation_year__gte=settings.SENIOR_GRADUATION_YEAR) users = users.exclude(id__in=EXTRA) return users
Get user objects that are students (quickly).
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L97-L102
tjcsl/ion
intranet/apps/users/models.py
UserManager.get_teachers
def get_teachers(self): """Get user objects that are teachers (quickly).""" users = User.objects.filter(user_type="teacher") users = users.exclude(id__in=EXTRA) # Add possible exceptions handling here users = users | User.objects.filter(id__in=[31863, 32327, 32103, 33228]) ...
python
def get_teachers(self): """Get user objects that are teachers (quickly).""" users = User.objects.filter(user_type="teacher") users = users.exclude(id__in=EXTRA) # Add possible exceptions handling here users = users | User.objects.filter(id__in=[31863, 32327, 32103, 33228]) ...
Get user objects that are teachers (quickly).
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L104-L111
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...
python
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...
Get teachers sorted by last name. This is used for the announcement request page.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L113-L133
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 ret...
python
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 ret...
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
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L209-L222
tjcsl/ion
intranet/apps/users/models.py
User.last_first
def last_first(self): """Return a name in the format of: Lastname, Firstname [(Nickname)] """ return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "")
python
def last_first(self): """Return a name in the format of: Lastname, Firstname [(Nickname)] """ return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "")
Return a name in the format of: Lastname, Firstname [(Nickname)]
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L248-L252
tjcsl/ion
intranet/apps/users/models.py
User.last_first_id
def last_first_id(self): """Return a name in the format of: Lastname, Firstname [(Nickname)] (Student ID/ID/Username) """ return ("{}{} ".format(self.last_name, ", " + self.first_name if self.first_name else "") + ("({}) ".format(self.nickname) ...
python
def last_first_id(self): """Return a name in the format of: Lastname, Firstname [(Nickname)] (Student ID/ID/Username) """ return ("{}{} ".format(self.last_name, ", " + self.first_name if self.first_name else "") + ("({}) ".format(self.nickname) ...
Return a name in the format of: Lastname, Firstname [(Nickname)] (Student ID/ID/Username)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L255-L261
tjcsl/ion
intranet/apps/users/models.py
User.last_first_initial
def last_first_initial(self): """Return a name in the format of: Lastname, F [(Nickname)] """ return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname) ...
python
def last_first_initial(self): """Return a name in the format of: Lastname, F [(Nickname)] """ return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname) ...
Return a name in the format of: Lastname, F [(Nickname)]
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L264-L269
tjcsl/ion
intranet/apps/users/models.py
User.tj_email
def tj_email(self): """Get (or guess) a user's TJ email. If a fcps.edu or tjhsst.edu email is specified in their email list, use that. Otherwise, append the user's username to the proper email suffix, depending on whether they are a student or teacher. """ for ...
python
def tj_email(self): """Get (or guess) a user's TJ email. If a fcps.edu or tjhsst.edu email is specified in their email list, use that. Otherwise, append the user's username to the proper email suffix, depending on whether they are a student or teacher. """ for ...
Get (or guess) a user's TJ email. If a fcps.edu or tjhsst.edu email is specified in their email list, use that. Otherwise, append the user's username to the proper email suffix, depending on whether they are a student or teacher.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L285-L304
tjcsl/ion
intranet/apps/users/models.py
User.default_photo
def default_photo(self): """Returns default photo (in binary) that should be used Returns: Binary data """ preferred = self.preferred_photo if preferred is not None: return preferred.binary if preferred is None: if self.user_type == ...
python
def default_photo(self): """Returns default photo (in binary) that should be used Returns: Binary data """ preferred = self.preferred_photo if preferred is not None: return preferred.binary if preferred is None: if self.user_type == ...
Returns default photo (in binary) that should be used Returns: Binary data
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L307-L330
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...
python
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...
Dynamically generate dictionary of privacy options
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L343-L360
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.r...
python
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.r...
Return whether the currently logged in user is a teacher, and can view all of a student's information regardless of their privacy settings.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L362-L377
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): """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
Returns a user's age, based on their birthday. Returns: integer
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L400-L413
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 EighthSp...
python
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 EighthSp...
Determine whether the given user is associated with an. :class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity sponsoring information.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L639-L649
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: ret...
python
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: ret...
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
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L656-L668
tjcsl/ion
intranet/apps/users/models.py
User.get_eighth_sponsor
def get_eighth_sponsor(self): """Return the :class:`intranet.apps.eighth.models.EighthSponsor` that a given user is associated with. """ # FIXME: remove recursive dep from ..eighth.models import EighthSponsor try: sp = EighthSponsor.objects.get(user=self) ...
python
def get_eighth_sponsor(self): """Return the :class:`intranet.apps.eighth.models.EighthSponsor` that a given user is associated with. """ # FIXME: remove recursive dep from ..eighth.models import EighthSponsor try: sp = EighthSponsor.objects.get(user=self) ...
Return the :class:`intranet.apps.eighth.models.EighthSponsor` that a given user is associated with.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L696-L709
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...
python
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...
Return the user's absence count. If the user has no absences or is not a signup user, returns 0.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L735-L745
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): """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)
Return information about the user's absences.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L747-L752
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): """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)
Handle a graduated user being deleted.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L754-L758
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)) ...
python
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)) ...
Sets permission for personal information. Returns False silently if unable to set permission. Returns True if successful.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L829-L848
tjcsl/ion
intranet/apps/users/models.py
UserProperties.is_http_request_sender
def is_http_request_sender(self): """Checks if a user the HTTP request sender (accessing own info) Used primarily to load private personal information from the cache. (A student should see all info on his or her own profile regardless of how the permissions are set.) Returns: ...
python
def is_http_request_sender(self): """Checks if a user the HTTP request sender (accessing own info) Used primarily to load private personal information from the cache. (A student should see all info on his or her own profile regardless of how the permissions are set.) Returns: ...
Checks if a user the HTTP request sender (accessing own info) Used primarily to load private personal information from the cache. (A student should see all info on his or her own profile regardless of how the permissions are set.) Returns: Boolean
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L867-L888
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)...
python
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)...
Checks privacy options to see if an attribute is visible to public
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L890-L898
tjcsl/ion
intranet/apps/users/models.py
UserProperties.attribute_is_public
def attribute_is_public(self, permission): """ Checks if attribute is visible to public (regardless of admins status) """ try: parent = getattr(self, "parent_{}".format(permission)) student = getattr(self, "self_{}".format(permission)) return (parent and stude...
python
def attribute_is_public(self, permission): """ Checks if attribute is visible to public (regardless of admins status) """ try: parent = getattr(self, "parent_{}".format(permission)) student = getattr(self, "self_{}".format(permission)) return (parent and stude...
Checks if attribute is visible to public (regardless of admins status)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L900-L908
tjcsl/ion
intranet/apps/users/models.py
Grade.name_plural
def name_plural(self): """Return the grade's plural name (e.g. freshmen)""" return "freshmen" if (self._number and self._number == 9) else "{}s".format(self._name) if self._name else ""
python
def name_plural(self): """Return the grade's plural name (e.g. freshmen)""" return "freshmen" if (self._number and self._number == 9) else "{}s".format(self._name) if self._name else ""
Return the grade's plural name (e.g. freshmen)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/models.py#L1060-L1062
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.ha...
python
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.ha...
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.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/decorators.py#L10-L21
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 [...
python
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 [...
Get a user's personal info attributes to pass as an initial value to a PersonalInformationForm.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L17-L38
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_phot...
python
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_phot...
Get a user's preferred picture attributes to pass as an initial value to a PreferredPictureForm.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L64-L73
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, pty...
python
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, pty...
Get a user's privacy options to pass as an initial value to a PrivacyOptionsForm.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L110-L122
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_...
python
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_...
Get a user's notification options to pass as an initial value to a NotificationOptionsForm.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L167-L181
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: ...
python
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: ...
View and process updates to the preferences page.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L263-L322
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: ...
python
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: ...
View and edit privacy options for a user.
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/views.py#L326-L352
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.onB...
python
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.onB...
Shortcut only one at a time will work...
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L66-L83
codelv/enaml-native-barcode
src/zxing/android/android_barcode.py
AndroidBarcodeView.init_widget
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidBarcodeView, self).init_widget() d = self.declaration #: Observe activity state changes app = self.get_context() app.observe('state', self.on_activity_lifecycle_changed) if d.a...
python
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidBarcodeView, self).init_widget() d = self.declaration #: Observe activity state changes app = self.get_context() app.observe('state', self.on_activity_lifecycle_changed) if d.a...
Initialize the underlying widget.
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L126-L142
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...
python
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...
If the app pauses without pausing the barcode scanner the camera can't be reopened. So we must do it here.
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L144-L153
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): """ Cleanup the activty lifecycle listener """ if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
Cleanup the activty lifecycle listener
https://github.com/codelv/enaml-native-barcode/blob/dc3c4b41980c0f93d7fa828f48a751ae26daf297/src/zxing/android/android_barcode.py#L155-L159
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 Retur...
python
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 Retur...
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
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L16-L27
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['r...
python
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['r...
Get details about an observation. :param observation_id: :returns: a dict with details on the observation :raises: ObservationNotFound
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L30-L42
inbo/pyinaturalist
pyinaturalist/node_api.py
get_observations
def get_observations(params: Dict) -> Dict[str, Any]: """Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations. Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts) """ r = make_inaturalist_api_get_call('observations', ...
python
def get_observations(params: Dict) -> Dict[str, Any]: """Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations. Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts) """ r = make_inaturalist_api_get_call('observations', ...
Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations. Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts)
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L45-L52
inbo/pyinaturalist
pyinaturalist/node_api.py
get_all_observations
def get_all_observations(params: Dict) -> List[Dict[str, Any]]: """Like get_observations() but handles pagination so you get all the results in one shot. Some params will be overwritten: order_by, order, per_page, id_above (do NOT specify page when using this). Returns a list of dicts (one entry per obser...
python
def get_all_observations(params: Dict) -> List[Dict[str, Any]]: """Like get_observations() but handles pagination so you get all the results in one shot. Some params will be overwritten: order_by, order, per_page, id_above (do NOT specify page when using this). Returns a list of dicts (one entry per obser...
Like get_observations() but handles pagination so you get all the results in one shot. Some params will be overwritten: order_by, order, per_page, id_above (do NOT specify page when using this). Returns a list of dicts (one entry per observation)
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/node_api.py#L55-L85
inbo/pyinaturalist
pyinaturalist/rest_api.py
get_observation_fields
def get_observation_fields(search_query: str="", page: int=1) -> List[Dict[str, Any]]: """ Search the (globally available) observation :param search_query: :param page: :return: """ payload = { 'q': search_query, 'page': page } # type: Dict[str, Union[int, str]] res...
python
def get_observation_fields(search_query: str="", page: int=1) -> List[Dict[str, Any]]: """ Search the (globally available) observation :param search_query: :param page: :return: """ payload = { 'q': search_query, 'page': page } # type: Dict[str, Union[int, str]] res...
Search the (globally available) observation :param search_query: :param page: :return:
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L12-L25
inbo/pyinaturalist
pyinaturalist/rest_api.py
get_all_observation_fields
def get_all_observation_fields(search_query: str="") -> List[Dict[str, Any]]: """ Like get_observation_fields(), but handles pagination for you. :param search_query: a string to search """ results = [] # type: List[Dict[str, Any]] page = 1 while True: r = get_observation_fields(se...
python
def get_all_observation_fields(search_query: str="") -> List[Dict[str, Any]]: """ Like get_observation_fields(), but handles pagination for you. :param search_query: a string to search """ results = [] # type: List[Dict[str, Any]] page = 1 while True: r = get_observation_fields(se...
Like get_observation_fields(), but handles pagination for you. :param search_query: a string to search
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L28-L45
inbo/pyinaturalist
pyinaturalist/rest_api.py
put_observation_field_values
def put_observation_field_values(observation_id: int, observation_field_id: int, value: Any, access_token: str) -> Dict[str, Any]: # TODO: Also implement a put_or_update_observation_field_values() that deletes then recreates the field_value? # TODO: Write example use in docstrin...
python
def put_observation_field_values(observation_id: int, observation_field_id: int, value: Any, access_token: str) -> Dict[str, Any]: # TODO: Also implement a put_or_update_observation_field_values() that deletes then recreates the field_value? # TODO: Write example use in docstrin...
Sets an observation field (value) on an observation. :param observation_id: :param observation_field_id: :param value :param access_token: access_token: the access token, as returned by :func:`get_access_token()` :returns: iNaturalist's response as a dict, for example: {'id': 31, ...
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L48-L94
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: :retur...
python
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: :retur...
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}
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L97-L121
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', 'r...
python
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', 'r...
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()`
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L128-L143
inbo/pyinaturalist
pyinaturalist/rest_api.py
create_observations
def create_observations(params: Dict[str, Dict[str, Any]], access_token: str) -> List[Dict[str, Any]]: """Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response,...
python
def create_observations(params: Dict[str, Dict[str, Any]], access_token: str) -> List[Dict[str, Any]]: """Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response,...
Create a single or several (if passed an array) observations). :param params: :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNaturalist's JSON response, as a Python object :raise: requests.HTTPError, if the call is not successful. iNaturalist returns an erro...
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L146-L172
inbo/pyinaturalist
pyinaturalist/rest_api.py
update_observation
def update_observation(observation_id: int, params: Dict[str, Any], access_token: str) -> List[Dict[str, Any]]: """ Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed...
python
def update_observation(observation_id: int, params: Dict[str, Any], access_token: str) -> List[Dict[str, Any]]: """ Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed...
Update a single observation. See https://www.inaturalist.org/pages/api+reference#put-observations-id :param observation_id: the ID of the observation to update :param params: to be passed to iNaturalist API :param access_token: the access token, as returned by :func:`get_access_token()` :return: iNatu...
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L175-L192
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.d...
python
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.d...
Delete an observation. :param observation_id: :param access_token: :return:
https://github.com/inbo/pyinaturalist/blob/d380ede84bdf15eca8ccab9efefe08d2505fe6a8/pyinaturalist/rest_api.py#L197-L216
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 instanc...
python
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 instanc...
Create an instance based off this placeholder with some parent
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L36-L42
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): """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)
Lookup a field given a field placeholder
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L87-L91
digidotcom/python-suitcase
suitcase/fields.py
CRCField.validate
def validate(self, data, offset): """Raises :class:`SuitcaseChecksumException` if not valid""" recorded_checksum = self.field.getval() # convert negative offset to positive if offset < 0: offset += len(data) # replace checksum region with zero data = b''.joi...
python
def validate(self, data, offset): """Raises :class:`SuitcaseChecksumException` if not valid""" recorded_checksum = self.field.getval() # convert negative offset to positive if offset < 0: offset += len(data) # replace checksum region with zero data = b''.joi...
Raises :class:`SuitcaseChecksumException` if not valid
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L158-L174
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): """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()
Given the data of the entire packet return the checksum bytes
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L176-L181
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...
python
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...
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
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/fields.py#L1493-L1511
digidotcom/python-suitcase
suitcase/crc.py
crc16_kermit
def crc16_kermit(data, crc=0): """Calculate/Update the Kermit CRC16 checksum for some data""" tab = CRC16_KERMIT_TAB # minor optimization (now in locals) for byte in six.iterbytes(data): tbl_idx = (crc ^ byte) & 0xff crc = (tab[tbl_idx] ^ (crc >> 8)) & 0xffff return crc & 0xffff
python
def crc16_kermit(data, crc=0): """Calculate/Update the Kermit CRC16 checksum for some data""" tab = CRC16_KERMIT_TAB # minor optimization (now in locals) for byte in six.iterbytes(data): tbl_idx = (crc ^ byte) & 0xff crc = (tab[tbl_idx] ^ (crc >> 8)) & 0xffff return crc & 0xffff
Calculate/Update the Kermit CRC16 checksum for some data
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/crc.py#L91-L97
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. T...
python
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. T...
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 pa...
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/crc.py#L100-L114
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 byt...
python
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 byt...
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 ...
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/protocol.py#L113-L148
digidotcom/python-suitcase
suitcase/structure.py
Packer.unpack_stream
def unpack_stream(self, stream): """Unpack bytes from a stream of data field-by-field In the most basic case, the basic algorithm here is as follows:: for _name, field in self.ordered_fields: length = field.bytes_required data = stream.read(length) ...
python
def unpack_stream(self, stream): """Unpack bytes from a stream of data field-by-field In the most basic case, the basic algorithm here is as follows:: for _name, field in self.ordered_fields: length = field.bytes_required data = stream.read(length) ...
Unpack bytes from a stream of data field-by-field In the most basic case, the basic algorithm here is as follows:: for _name, field in self.ordered_fields: length = field.bytes_required data = stream.read(length) field.unpack(data) This logic i...
https://github.com/digidotcom/python-suitcase/blob/b53681a33efd350daf1b63094b1d21587e45a806/suitcase/structure.py#L73-L169
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.') ...
python
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.') ...
Check if input is valid URL
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/web.py#L46-L61
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...
python
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 Singleton instance to a dictionary. This behaves identically to HasProperties.serialize, except it also saves the identifying name in the dictionary as well.
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/singleton.py#L49-L61
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 ...
python
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 ...
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 a...
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/extras/singleton.py#L64-L97
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_mu...
python
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_mu...
Class decorator to add change notifications to builtin containers
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L50-L64
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 notific...
python
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 notific...
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.
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L66-L93
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 ...
python
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 ...
Wraps a container operator to ensure container class is maintained
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L95-L106
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 id...
python
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 id...
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, ...
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L108-L138
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...
python
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...
Validate Property instance for container items
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L140-L153
seequent/properties
properties/base/containers.py
Tuple.info
def info(self): """Supplemental description of the list, with length and type""" itext = self.class_info if self.prop.info: itext += ' (each item is {})'.format(self.prop.info) if self.max_length is None and self.min_length is None: return itext if self.ma...
python
def info(self): """Supplemental description of the list, with length and type""" itext = self.class_info if self.prop.info: itext += ' (each item is {})'.format(self.prop.info) if self.max_length is None and self.min_length is None: return itext if self.ma...
Supplemental description of the list, with length and type
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L243-L259
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(instan...
python
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(instan...
Check the class of the container and validate each element This returns a copy of the container to prevent unwanted sharing of pointers.
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L261-L281
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 Non...
python
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 Non...
Check if tuple and contained properties are valid
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L283-L305
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 seri...
python
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 seri...
Return a serialized copy of the tuple
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L307-L316
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_...
python
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_...
Return a deserialized copy of the tuple
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L318-L327
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 ] ret...
python
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 ] ret...
Return a copy of the tuple as a list If the tuple contains HasProperties instances, they are serialized.
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L340-L349
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): """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)
Redefine sphinx class to point to prop class
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/containers.py#L360-L365