code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def move(self, start_dt): """Move the entry to start at a different time. This method automatically moves children of the entry to preserve their start time relative to the parent's start time. """ if self.type == TimetableEntryType.SESSION_BLOCK: diff = start_dt - s...
Move the entry to start at a different time. This method automatically moves children of the entry to preserve their start time relative to the parent's start time.
move
python
indico/indico
indico/modules/events/timetable/models/entries.py
https://github.com/indico/indico/blob/master/indico/modules/events/timetable/models/entries.py
MIT
def get_file_metadata(self): """Get a dict of extra metadata to store on the File. This is usually not needed, but could be used e.g. to add some flag which is then used in a validator of the form accepting the file uploaded here. """
Get a dict of extra metadata to store on the File. This is usually not needed, but could be used e.g. to add some flag which is then used in a validator of the form accepting the file uploaded here.
get_file_metadata
python
indico/indico
indico/modules/files/controllers.py
https://github.com/indico/indico/blob/master/indico/modules/files/controllers.py
MIT
def validate_upload_file_size(*files): """Validate size of one or more uploaded files. Validation is done using the `MAX_UPLOAD_FILE_SIZE` config. """ max_upload_file_size = config.MAX_UPLOAD_FILE_SIZE * 1024 * 1024 if not max_upload_file_size: return True for file in files: fil...
Validate size of one or more uploaded files. Validation is done using the `MAX_UPLOAD_FILE_SIZE` config.
validate_upload_file_size
python
indico/indico
indico/modules/files/util.py
https://github.com/indico/indico/blob/master/indico/modules/files/util.py
MIT
def as_attachment(self): """Return the file as an attachment in the format expected by the util `make_email`.""" with self.open() as f: return secure_filename(self.filename, 'file'), f.read(), self.content_type
Return the file as an attachment in the format expected by the util `make_email`.
as_attachment
python
indico/indico
indico/modules/files/models/files.py
https://github.com/indico/indico/blob/master/indico/modules/files/models/files.py
MIT
def __new__(cls, name_or_id, provider=None, _group=None): """Create the correct GroupProxy for the group type.""" if provider is None or provider == 'indico': obj = object.__new__(_LocalGroupProxy) obj.id = int(name_or_id) else: obj = object.__new__(_Multipass...
Create the correct GroupProxy for the group type.
__new__
python
indico/indico
indico/modules/groups/core.py
https://github.com/indico/indico/blob/master/indico/modules/groups/core.py
MIT
def search(cls, name, exact=False, providers=None): """Search for groups. :param name: The group name to search for. :param exact: If only exact matches should be found (much faster) :param providers: ``None`` to search in all providers and local groups. May be...
Search for groups. :param name: The group name to search for. :param exact: If only exact matches should be found (much faster) :param providers: ``None`` to search in all providers and local groups. May be a set specifying providers to search...
search
python
indico/indico
indico/modules/groups/core.py
https://github.com/indico/indico/blob/master/indico/modules/groups/core.py
MIT
def serialize_group(group): """Serialize group to JSON-like object.""" return { 'id': group.id if group.is_local else group.name, 'name': group.name, 'provider': group.provider, 'provider_title': group.provider_title if not group.is_local else None, 'identifier': group.id...
Serialize group to JSON-like object.
serialize_group
python
indico/indico
indico/modules/groups/util.py
https://github.com/indico/indico/blob/master/indico/modules/groups/util.py
MIT
def render_entry(cls, entry): """Render the log entry row. :param entry: A :class:`.EventLogEntry` """ template = f'{cls.plugin.name}:{cls.template_name}' if cls.plugin is not None else cls.template_name return render_template(template, entry=entry, data=cls.get_data(entry), **c...
Render the log entry row. :param entry: A :class:`.EventLogEntry`
render_entry
python
indico/indico
indico/modules/logs/renderers.py
https://github.com/indico/indico/blob/master/indico/modules/logs/renderers.py
MIT
def make_diff_log(changes, fields): """Create a value for log data containing change information. :param changes: a dict mapping attributes to ``(old, new)`` tuples :param fields: a dict mapping attributes to field metadata. for simple cases this may be a string with the human-friendly ...
Create a value for log data containing change information. :param changes: a dict mapping attributes to ``(old, new)`` tuples :param fields: a dict mapping attributes to field metadata. for simple cases this may be a string with the human-friendly title, for more advanced fields it sho...
make_diff_log
python
indico/indico
indico/modules/logs/util.py
https://github.com/indico/indico/blob/master/indico/modules/logs/util.py
MIT
def render_changes(a, b, type_): """Render the comparison of `a` and `b` as HTML. :param a: old value :param b: new value :param type_: the type determining how the values should be compared """ if type_ in ('number', 'enum', 'bool', 'datetime', 'timedelta'): if a in (None, ''): ...
Render the comparison of `a` and `b` as HTML. :param a: old value :param b: new value :param type_: the type determining how the values should be compared
render_changes
python
indico/indico
indico/modules/logs/util.py
https://github.com/indico/indico/blob/master/indico/modules/logs/util.py
MIT
def user_id(cls): """The ID of the user associated with the entry.""" return db.Column( db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=True )
The ID of the user associated with the entry.
user_id
python
indico/indico
indico/modules/logs/models/entries.py
https://github.com/indico/indico/blob/master/indico/modules/logs/models/entries.py
MIT
def user(cls): """The user associated with the log entry.""" return db.relationship( 'User', lazy=False, backref=db.backref( cls.user_backref_name, lazy='dynamic' ), foreign_keys=[cls.user_id] )
The user associated with the log entry.
user
python
indico/indico
indico/modules/logs/models/entries.py
https://github.com/indico/indico/blob/master/indico/modules/logs/models/entries.py
MIT
def render(self): """Render the log entry to be displayed. If the renderer is not available anymore, e.g. because of a disabled plugin, ``None`` is returned. """ renderer = self.renderer return renderer.render_entry(self) if renderer else None
Render the log entry to be displayed. If the renderer is not available anymore, e.g. because of a disabled plugin, ``None`` is returned.
render
python
indico/indico
indico/modules/logs/models/entries.py
https://github.com/indico/indico/blob/master/indico/modules/logs/models/entries.py
MIT
def get_recent_news(): """Get a list of recent news for the home page.""" settings = news_settings.get_all() if not settings['show_recent']: return [] delta = timedelta(days=settings['max_age']) if settings['max_age'] else None return (NewsItem.query .filter(db.cast(NewsItem.crea...
Get a list of recent news for the home page.
get_recent_news
python
indico/indico
indico/modules/news/util.py
https://github.com/indico/indico/blob/master/indico/modules/news/util.py
MIT
def _serializable_room(room, reservations=None): """Serializable room. :param room: Room :param reservations: MultiDict mapping for room id => reservations """ from indico.modules.rb.schemas import RoomLegacyAPISchema data = RoomLegacyAPISchema().dump(room) data['_type'] = 'Room' if res...
Serializable room. :param room: Room :param reservations: MultiDict mapping for room id => reservations
_serializable_room
python
indico/indico
indico/modules/rb/api.py
https://github.com/indico/indico/blob/master/indico/modules/rb/api.py
MIT
def _serializable_room_minimal(room): """Serializable minimal room data (inside reservations). :param room: A `Room` """ from indico.modules.rb.schemas import RoomLegacyMinimalAPISchema data = RoomLegacyMinimalAPISchema().dump(room) data['_type'] = 'Room' return data
Serializable minimal room data (inside reservations). :param room: A `Room`
_serializable_room_minimal
python
indico/indico
indico/modules/rb/api.py
https://github.com/indico/indico/blob/master/indico/modules/rb/api.py
MIT
def _serializable_reservation(reservation_data, include_room=False, user=None): """Serializable reservation (standalone or inside room). :param reservation_data: Reservation data :param include_room: Include minimal room information """ from indico.modules.rb.schemas import ReservationLegacyAPISche...
Serializable reservation (standalone or inside room). :param reservation_data: Reservation data :param include_room: Include minimal room information
_serializable_reservation
python
indico/indico
indico/modules/rb/api.py
https://github.com/indico/indico/blob/master/indico/modules/rb/api.py
MIT
def rb_check_user_access(user): """Check if the user has access to the room booking system.""" from indico.modules.rb import rb_settings if rb_is_admin(user): return True if rb_is_location_manager(user): return True if not rb_settings.acls.get('authorized_principals'): # everyone ha...
Check if the user has access to the room booking system.
rb_check_user_access
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def rb_is_admin(user): """Check if the user is a room booking admin.""" from indico.modules.rb import rb_settings if user is None: return False if user.is_admin: return True return rb_settings.acls.contains_user('admin_principals', user)
Check if the user is a room booking admin.
rb_is_admin
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def rb_check_if_visible(user): """Check if user should see links to the room booking system.""" from indico.modules.rb import rb_settings if not rb_settings.get('hide_module_if_unauthorized'): return True return rb_check_user_access(user)
Check if user should see links to the room booking system.
rb_check_if_visible
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def generate_spreadsheet_from_occurrences(occurrences): """Generate spreadsheet data from a given booking occurrence list. :param occurrences: The booking occurrences to include in the spreadsheet """ headers = ['Room', 'Booking ID', 'Booked for', 'Reason', 'Occurrence start', 'Occurrence end'] row...
Generate spreadsheet data from a given booking occurrence list. :param occurrences: The booking occurrences to include in the spreadsheet
generate_spreadsheet_from_occurrences
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def _find_first_entry_start_dt(event, day): """Find the first timetable entry on a given day.""" if not (event.start_dt_local.date() <= day <= event.end_dt_local.date()): raise ValueError('Day out of event bounds.') entries = event.timetable_entries.filter(TimetableEntry.parent_id.is_(None), ...
Find the first timetable entry on a given day.
_find_first_entry_start_dt
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def get_booking_params_for_event(event): """Get a set of RB interface parameters suitable for this event. These parameters can then be used to construct a URL that will lead to a pre-filled search that matches the start/end times for a given day. :param event: `Event` object """ data = {'param...
Get a set of RB interface parameters suitable for this event. These parameters can then be used to construct a URL that will lead to a pre-filled search that matches the start/end times for a given day. :param event: `Event` object
get_booking_params_for_event
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def check_impossible_repetition(data): """Check for broken repetition data. This checks that a repetition using weekdays has a date range containing at least one of the specified weekdays. """ from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence try: start_...
Check for broken repetition data. This checks that a repetition using weekdays has a date range containing at least one of the specified weekdays.
check_impossible_repetition
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def check_empty_candidates(candidates): """Check for empty candidates. This checks that a created time-series has at least one occurrence to filter by (similar to :func:`check_impossible_repetition` but without the need to pass all the data). """ if not candidates: raise ExpectedError(_('Th...
Check for empty candidates. This checks that a created time-series has at least one occurrence to filter by (similar to :func:`check_impossible_repetition` but without the need to pass all the data).
check_empty_candidates
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def format_weekdays(weekdays): """Format a list of weekdays into a nice readable string.""" assert weekdays return ', '.join(x.capitalize() for x in sorted(weekdays, key=lambda x: WEEKDAYS.index(x)))
Format a list of weekdays into a nice readable string.
format_weekdays
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def check_repeat_frequency(old_frequency, new_frequency): """Prevent changing the repeat frequency of an existing booking.""" from indico.modules.rb.models.reservations import RepeatFrequency if ( (old_frequency == RepeatFrequency.WEEK and new_frequency == RepeatFrequency.MONTH) or (old_fre...
Prevent changing the repeat frequency of an existing booking.
check_repeat_frequency
python
indico/indico
indico/modules/rb/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/util.py
MIT
def approve(self, notify_blocker=True): """Approve the room blocking, rejecting all colliding reservations/occurrences.""" self.state = BlockedRoomState.accepted # Get colliding reservations start_dt = datetime.combine(self.blocking.start_date, time()) end_dt = datetime.combine(...
Approve the room blocking, rejecting all colliding reservations/occurrences.
approve
python
indico/indico
indico/modules/rb/models/blocked_rooms.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/blocked_rooms.py
MIT
def can_override(self, user, room=None, explicit_only=False, allow_admin=True): """Check if a user can override the blocking. The following persons are authorized to override a blocking: - the creator of the blocking - anyone on the blocking's ACL - unless explicit_only is set: ...
Check if a user can override the blocking. The following persons are authorized to override a blocking: - the creator of the blocking - anyone on the blocking's ACL - unless explicit_only is set: rb admins and room managers (if a room is given)
can_override
python
indico/indico
indico/modules/rb/models/blockings.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/blockings.py
MIT
def room_name_format(self): """Translate Postgres' format syntax (e.g. `%1$s/%2$s-%3$s`) to Python's.""" placeholders = ['building', 'floor', 'number', 'site'] return re.sub( r'%(\d)\$s', lambda m: '{%s}' % placeholders[int(m.group(1)) - 1], # noqa: UP031 sel...
Translate Postgres' format syntax (e.g. `%1$s/%2$s-%3$s`) to Python's.
room_name_format
python
indico/indico
indico/modules/rb/models/locations.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/locations.py
MIT
def create_from_data(cls, room, data, user, *, prebook=None, ignore_admin=False, force_internal_note=False): """Create a new reservation. :param room: The Room that's being booked. :param data: A dict containing the booking data, usually from a :class:`NewBookingConfirmForm` instance :p...
Create a new reservation. :param room: The Room that's being booked. :param data: A dict containing the booking data, usually from a :class:`NewBookingConfirmForm` instance :param user: The :class:`.User` who creates the booking. :param prebook: Instead of determining the booking type f...
create_from_data
python
indico/indico
indico/modules/rb/models/reservations.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/reservations.py
MIT
def modify(self, data, user, extra_fields: dict | None): """Modify an existing reservation. :param data: A dict containing the booking data, usually from a :class:`CreateBookingSchema` instance :param user: The :class:`.User` who modifies the booking. :param extra_fields: A dict contain...
Modify an existing reservation. :param data: A dict containing the booking data, usually from a :class:`CreateBookingSchema` instance :param user: The :class:`.User` who modifies the booking. :param extra_fields: A dict containing the extra fields data from the schema
modify
python
indico/indico
indico/modules/rb/models/reservations.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/reservations.py
MIT
def map_recurrence_weekdays_to_rrule(weekdays): """Map weekdays from database to rrule weekdays.""" # Return none if no weekdays are provided if not weekdays: return None weekdays_map = { 'mon': rrule.MO, 'tue': rrule.TU, 'wed': rrule.WE, ...
Map weekdays from database to rrule weekdays.
map_recurrence_weekdays_to_rrule
python
indico/indico
indico/modules/rb/models/reservation_occurrences.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/reservation_occurrences.py
MIT
def find_with_attribute(cls, attribute): """Search rooms which have a specific attribute.""" return (Room.query .with_entities(Room, RoomAttributeAssociation.value) .join(RoomAttributeAssociation) .join(RoomAttribute) .filter(RoomAttribute....
Search rooms which have a specific attribute.
find_with_attribute
python
indico/indico
indico/modules/rb/models/rooms.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/rooms.py
MIT
def filter_available(start_dt, end_dt, repetition, include_blockings=True, include_pre_bookings=True, include_pending_blockings=False): """Return a SQLAlchemy filter criterion ensuring that the room is available during the given time.""" # Check availability against reservation ...
Return a SQLAlchemy filter criterion ensuring that the room is available during the given time.
filter_available
python
indico/indico
indico/modules/rb/models/rooms.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/rooms.py
MIT
def get_permissions_for_user(cls, user, allow_admin=True): """Get the permissions for all rooms for a user. In case of multipass-based groups it will try to get a list of all groups the user is in, and if that's not possible check the permissions one by one for each room (which may resu...
Get the permissions for all rooms for a user. In case of multipass-based groups it will try to get a list of all groups the user is in, and if that's not possible check the permissions one by one for each room (which may result in many group membership lookups). It is recommend...
get_permissions_for_user
python
indico/indico
indico/modules/rb/models/rooms.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/rooms.py
MIT
def proxy_to_reservation_if_last_valid_occurrence(f): """Forward a method call to `self.reservation` if there is only one occurrence.""" @wraps(f) def wrapper(self, *args, **kwargs): from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence if not kwargs.pop('propaga...
Forward a method call to `self.reservation` if there is only one occurrence.
proxy_to_reservation_if_last_valid_occurrence
python
indico/indico
indico/modules/rb/models/util.py
https://github.com/indico/indico/blob/master/indico/modules/rb/models/util.py
MIT
def notify_request(owner, blocking, blocked_rooms): """Notify room owner about blockings he has to approve. Expect only blockings for rooms owned by the specified owner. """ with owner.force_user_locale(): tpl = get_template_module('rb/emails/blockings/awaiting_confirmation_email_to_manager.txt...
Notify room owner about blockings he has to approve. Expect only blockings for rooms owned by the specified owner.
notify_request
python
indico/indico
indico/modules/rb/notifications/blockings.py
https://github.com/indico/indico/blob/master/indico/modules/rb/notifications/blockings.py
MIT
def notify_request_response(blocked_room): """ Notify blocking creator about approval/rejection of his blocking request for a room. """ user = blocked_room.blocking.created_by_user with user.force_user_locale(): tpl = get_template_module('rb/emails/blockings/state_email_to_user.txt', ...
Notify blocking creator about approval/rejection of his blocking request for a room.
notify_request_response
python
indico/indico
indico/modules/rb/notifications/blockings.py
https://github.com/indico/indico/blob/master/indico/modules/rb/notifications/blockings.py
MIT
def get_matching_events(start_dt, end_dt, repeat_frequency, repeat_interval, recurrence_weekdays): """Get events suitable for booking linking. This finds events that overlap with an occurrence of a booking with the given dates where the user is a manager. """ occurrences = ReservationOccurrence.cre...
Get events suitable for booking linking. This finds events that overlap with an occurrence of a booking with the given dates where the user is a manager.
get_matching_events
python
indico/indico
indico/modules/rb/operations/bookings.py
https://github.com/indico/indico/blob/master/indico/modules/rb/operations/bookings.py
MIT
def get_booking_edit_calendar_data(booking, booking_changes): """Return calendar-related data for the booking edit modal.""" room = booking.room booking_details = serialize_booking_details(booking) old_date_range = booking_details['date_range'] booking_availability = dict(booking_details['occurrence...
Return calendar-related data for the booking edit modal.
get_booking_edit_calendar_data
python
indico/indico
indico/modules/rb/operations/bookings.py
https://github.com/indico/indico/blob/master/indico/modules/rb/operations/bookings.py
MIT
def search_for_rooms(filters, allow_admin=False, availability=None): """Search for a room, using the provided filters. :param filters: The filters, provided as a dictionary :param allow_admin: A boolean specifying whether admins have override privileges :param availability: A boolean specifying whether...
Search for a room, using the provided filters. :param filters: The filters, provided as a dictionary :param allow_admin: A boolean specifying whether admins have override privileges :param availability: A boolean specifying whether (un)available rooms should be provided, or `None` ...
search_for_rooms
python
indico/indico
indico/modules/rb/operations/rooms.py
https://github.com/indico/indico/blob/master/indico/modules/rb/operations/rooms.py
MIT
def has_any_templates(event: Event) -> bool: """Check if any receipt templates are available for the event.""" event_category = event.category or Category.get_root() return (ReceiptTemplate.query .filter(~ReceiptTemplate.is_deleted, or_(ReceiptTemplate.category_id.in_(categ['...
Check if any receipt templates are available for the event.
has_any_templates
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def has_any_receipts(regform: RegistrationForm) -> bool: """Check if any receipts have been generated available for the regform.""" return (ReceiptFile.query .filter(ReceiptFile.registration.has(is_deleted=False, registration_form=regform), ~ReceiptFile.is_deleted) .h...
Check if any receipts have been generated available for the regform.
has_any_receipts
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def get_other_templates(obj: Event | Category, user) -> list[ReceiptTemplate]: """Get all templates not owned or inherited by a given event/category.""" # XXX the can_manage check here causes some amount of query spam, but this is acceptable because # - usually only admins have access to manage templates (w...
Get all templates not owned or inherited by a given event/category.
get_other_templates
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def compile_jinja_code(code: str, template_context: dict, *, use_stack: bool = False) -> str: """Compile Jinja template of receipt in a sandboxed environment.""" try: undefined_config = {'undefined': SilentUndefined} if use_stack else {} env = SandboxedEnvironment(**undefined_config, autoescape=...
Compile Jinja template of receipt in a sandboxed environment.
compile_jinja_code
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def sandboxed_url_fetcher(event: Event, allow_event_images: bool = False) -> t.Callable[[str], dict]: """Fetch also "event-local" URLs. More info on fetchers: https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#url-fetchers """ allow_external_urls = receipts_settings.get('allow_external_ur...
Fetch also "event-local" URLs. More info on fetchers: https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#url-fetchers
sandboxed_url_fetcher
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def create_pdf(event: Event, html_sources: list[str], css: str) -> BytesIO: """Create a PDF based on the given HTML sources. :param event: The `Event` the PDF relates to :param html_sources: list of HTML pages (source) which will be rendered into the final document :param css: CSS stylesheet to include...
Create a PDF based on the given HTML sources. :param event: The `Event` the PDF relates to :param html_sources: list of HTML pages (source) which will be rendered into the final document :param css: CSS stylesheet to include :return: a the rendered PDF blob
create_pdf
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def get_dummy_preview_data(custom_fields: dict, custom_fields_values: dict | None = None) -> dict: """Get dummy preview data for rendering a document template. Most document templates are written inthe context of a category, so it is not possible to use real event/registration data for previewing it. This ...
Get dummy preview data for rendering a document template. Most document templates are written inthe context of a category, so it is not possible to use real event/registration data for previewing it. This function serializes dummy data that can be used instead.
get_dummy_preview_data
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def get_preview_placeholders(value): """Get a flat list of placeholders from the template context.""" placeholders = _get_preview_placeholders(value) placeholders.sort(key=lambda x: ( not x[0].startswith('custom_fields.'), not x[0].startswith('event.'), x[0].startswith('registration....
Get a flat list of placeholders from the template context.
get_preview_placeholders
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def get_event_attachment_images(event: Event) -> dict[str, Attachment]: """Get a dict of the event's attached images indexed by the attachment's ID.""" attached_items = get_attached_items(event) all_attachments = attached_items.get('files', []).copy() for folder in attached_items.get('folders', []): ...
Get a dict of the event's attached images indexed by the attachment's ID.
get_event_attachment_images
python
indico/indico
indico/modules/receipts/util.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/util.py
MIT
def test_bulk_download_receipts(test_client, dummy_user, dummy_event, create_event, dummy_receipt_file): """Make sure one cannot download receipts from a different event.""" dummy_user.is_admin = True with test_client.session_transaction() as sess: sess.set_session_user(dummy_user) url = '/event...
Make sure one cannot download receipts from a different event.
test_bulk_download_receipts
python
indico/indico
indico/modules/receipts/controllers/access_test.py
https://github.com/indico/indico/blob/master/indico/modules/receipts/controllers/access_test.py
MIT
def get_search_provider(only_active=True): """Get the search provider to use for a search. :param only_active: Whether to check that the provider is active; in case it isn't, the default InternalSearch provider will be used. """ from indico.modules.search...
Get the search provider to use for a search. :param only_active: Whether to check that the provider is active; in case it isn't, the default InternalSearch provider will be used.
get_search_provider
python
indico/indico
indico/modules/search/base.py
https://github.com/indico/indico/blob/master/indico/modules/search/base.py
MIT
def search(self, query, user=None, page=None, object_types=(), *, admin_override_enabled=False, **params): """Search using a custom service across multiple targets. :param query: Keyword based query string :param user: The user performing the search (for access checks) :p...
Search using a custom service across multiple targets. :param query: Keyword based query string :param user: The user performing the search (for access checks) :param page: The result page to show :param object_types: A filter for a specific `SearchTarget` :param admin_override_...
search
python
indico/indico
indico/modules/search/base.py
https://github.com/indico/indico/blob/master/indico/modules/search/base.py
MIT
def _add_user_id(endpoint, values): """Add user id to user-specific urls if one was set for the current page. This ensures that the URLs we have both with an without user id always preserve the user id if there is one, but regular users don't end up with the user id in the URL all the time. Note t...
Add user id to user-specific urls if one was set for the current page. This ensures that the URLs we have both with an without user id always preserve the user id if there is one, but regular users don't end up with the user id in the URL all the time. Note that this needs to be replicated in other bl...
_add_user_id
python
indico/indico
indico/modules/users/blueprint.py
https://github.com/indico/indico/blob/master/indico/modules/users/blueprint.py
MIT
def get_events_in_categories(category_ids, user, from_, limit=10): """Get all the user-accessible events in a given set of categories.""" tz = session.tzinfo # Find events (past and future) which are closest to the current time time_delta = now_utc(False) - Event.start_dt absolute_time_delta = db.fu...
Get all the user-accessible events in a given set of categories.
get_events_in_categories
python
indico/indico
indico/modules/users/controllers.py
https://github.com/indico/indico/blob/master/indico/modules/users/controllers.py
MIT
def test_invalid_request(): """Test data export request with invalid options.""" from indico.modules.users.controllers import RHUserDataExportAPI rh = RHUserDataExportAPI() request.method = 'POST' request.form = MultiDict({'options': 'test'}) with pytest.raises(UnprocessableEntity): rh....
Test data export request with invalid options.
test_invalid_request
python
indico/indico
indico/modules/users/controllers_test.py
https://github.com/indico/indico/blob/master/indico/modules/users/controllers_test.py
MIT
def export_user_data(user, options, include_files): """Generate a zip file containing user data and files and save it in `user.data_export_request`.""" export_request = user.data_export_request if export_request and export_request.is_running: return try: export_request = initialize_new_...
Generate a zip file containing user data and files and save it in `user.data_export_request`.
export_user_data
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_user_files(export_request): """Get all files tied to a given user.""" user = export_request.user options = export_request.selected_options if DataExportOptions.attachments in options: for attachment in get_attachments(user): yield attachment.file if DataExportOptions.ab...
Get all files tied to a given user.
get_user_files
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_registrations(user): """Get all registrations linked to the user.""" return (user.registrations .options(subqueryload('data').joinedload('field_data').joinedload('field').joinedload('parent'), joinedload('registration_form').load_only('id', 'event_id'), ...
Get all registrations linked to the user.
get_registrations
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_registration_files(user): """Get all files uploaded in registration file fields.""" return (RegistrationData.query .join(Registration) .filter(Registration.user == user, RegistrationData.filename.isnot(None)) .all())
Get all files uploaded in registration file fields.
get_registration_files
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_registration_documents(user): """Get all documents generated for a registration.""" return (ReceiptFile.query .join(Registration) .filter(Registration.user == user, ReceiptFile.file_id.isnot(None), ReceiptFile.is_published) .all...
Get all documents generated for a registration.
get_registration_documents
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_attachments(user): """Get all attachments uploaded by the user.""" folder_strategy = joinedload('folder') folder_strategy.joinedload('event').load_only('id') folder_strategy.joinedload('contribution').load_only('id', 'event_id') folder_strategy.joinedload('subcontribution').load_only('id', '...
Get all attachments uploaded by the user.
get_attachments
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_subcontributions(user): """Get all subcontributions linked to the user (speaker).""" query = (db.session.query(SubContribution.id) .filter(SubContribution.person_links.any(SubContributionPersonLink.person.has(user=user))) .all()) subcontribution_ids = {scid for scid, in que...
Get all subcontributions linked to the user (speaker).
get_subcontributions
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_survey_submissions(user): """Get all survey submissions linked to the user.""" return (user.survey_submissions .options(joinedload('survey'), joinedload('answers').joinedload('question')) .all())
Get all survey submissions linked to the user.
get_survey_submissions
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def build_storage_path(file): """Build a path under which a given file be stored in the exported zip file. The path includes both the id (to ensure uniqueness) and the title/name for easy navigation. """ if isinstance(file, RegistrationData): event = file.registration.event prefix =...
Build a path under which a given file be stored in the exported zip file. The path includes both the id (to ensure uniqueness) and the title/name for easy navigation.
build_storage_path
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def convert_to_yaml(data): """Convert data to yaml with a nicer indentation style. Normal output does not indent lists, e.g.: key: - 1 - 2 Using this function, the list becomes indented: key: - 1 - 2 See: https://github.com/yaml/pyyaml/issues/234 ...
Convert data to yaml with a nicer indentation style. Normal output does not indent lists, e.g.: key: - 1 - 2 Using this function, the list becomes indented: key: - 1 - 2 See: https://github.com/yaml/pyyaml/issues/234
convert_to_yaml
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def get_old_requests(days): """Get successful export requests older than the specified number of days.""" return (DataExportRequest.query .filter(DataExportRequest.requested_dt < (now_utc() - timedelta(days=days)), DataExportRequest.state == DataExportRequestState.success) ...
Get successful export requests older than the specified number of days.
get_old_requests
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def notify_data_export_success(export_request): """Send an email to a user when a data export has finished.""" with export_request.user.force_user_locale(): template = get_template_module('users/emails/data_export_success.txt', user=export_request.user, link=url_fo...
Send an email to a user when a data export has finished.
notify_data_export_success
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def notify_data_export_failure(export_request): """Send an email to a user when a data export has failed.""" with export_request.user.force_user_locale(): template = get_template_module('users/emails/data_export_failure.txt', user=export_request.user, link=url_for(...
Send an email to a user when a data export has failed.
notify_data_export_failure
python
indico/indico
indico/modules/users/export.py
https://github.com/indico/indico/blob/master/indico/modules/users/export.py
MIT
def _add_file(self, data, original, **kwargs): """For file fields, export also the file metadata.""" if original.filename: file_data = RegistrationFileExportSchema().dump(original) return data | {'file': file_data} else: return data
For file fields, export also the file metadata.
_add_file
python
indico/indico
indico/modules/users/export_schemas.py
https://github.com/indico/indico/blob/master/indico/modules/users/export_schemas.py
MIT
def _add_file(self, data, original, **kwargs): """Export the attached file if there is one.""" if original.file: file_data = AttachmentFileExportSchema().dump(original.file) return data | {'file': file_data}
Export the attached file if there is one.
_add_file
python
indico/indico
indico/modules/users/export_schemas.py
https://github.com/indico/indico/blob/master/indico/modules/users/export_schemas.py
MIT
def update_storage_paths(data, include_files): """Recursively filter out or rename storage paths in the user schema.""" if isinstance(data, list): return [update_storage_paths(item, include_files) for item in data] elif isinstance(data, dict): data = {key: update_storage_paths(value, include...
Recursively filter out or rename storage paths in the user schema.
update_storage_paths
python
indico/indico
indico/modules/users/export_schemas.py
https://github.com/indico/indico/blob/master/indico/modules/users/export_schemas.py
MIT
def extend_form(self, form_class): """Create a subclass of the form containing the extra field.""" form_class = type('ExtendedUserPreferencesForm', (form_class,), {}) for name, field in self.fields.items(): name = self._prefix + name if hasattr(form_class, name): ...
Create a subclass of the form containing the extra field.
extend_form
python
indico/indico
indico/modules/users/ext.py
https://github.com/indico/indico/blob/master/indico/modules/users/ext.py
MIT
def create_user(email, data, identity=None, settings=None, other_emails=None, from_moderation=True): """Create a new user. This may also convert a pending user to a proper user in case the email address matches such a user. :param email: The primary email address of the user. :param data: The data...
Create a new user. This may also convert a pending user to a proper user in case the email address matches such a user. :param email: The primary email address of the user. :param data: The data used to populate the user. :param identity: An `Identity` to associate with the user. :param settin...
create_user
python
indico/indico
indico/modules/users/operations.py
https://github.com/indico/indico/blob/master/indico/modules/users/operations.py
MIT
def delete_or_anonymize_user(user): """Delete or anonymize a user. Deletes the user, and all their associated data. If it is not possible to delete the user, it will instead fallback to anonymizing the user. """ user_repr = repr(user) signals.users.db_deleted.send(user, flushed=False) try: ...
Delete or anonymize a user. Deletes the user, and all their associated data. If it is not possible to delete the user, it will instead fallback to anonymizing the user.
delete_or_anonymize_user
python
indico/indico
indico/modules/users/operations.py
https://github.com/indico/indico/blob/master/indico/modules/users/operations.py
MIT
def user_data_export_cleanup(days=30): """Clean up old user data exports. Files belonging to old data exports are marked for deletion by setting `claimed=False`. The files will then be automatically deleted by the daily `delete_unclaimed_files` task. :param days: minimum age of the data export to ...
Clean up old user data exports. Files belonging to old data exports are marked for deletion by setting `claimed=False`. The files will then be automatically deleted by the daily `delete_unclaimed_files` task. :param days: minimum age of the data export to be marked for removal
user_data_export_cleanup
python
indico/indico
indico/modules/users/tasks.py
https://github.com/indico/indico/blob/master/indico/modules/users/tasks.py
MIT
def get_related_categories(user, detailed=True): """Get the related categories of a user for the dashboard.""" favorites = set() if user.favorite_categories: favorites = set(Category.query .filter(Category.id.in_(c.id for c in user.favorite_categories)) ...
Get the related categories of a user for the dashboard.
get_related_categories
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def get_suggested_categories(user): """Get the suggested categories of a user for the dashboard.""" related = set(get_related_categories(user, detailed=False)) res = [] category_strategy = contains_eager('category') category_strategy.subqueryload('acl_entries') category_strategy.undefer('chain_t...
Get the suggested categories of a user for the dashboard.
get_suggested_categories
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def serialize_user(user): """Serialize user to JSON-like object.""" return { 'id': user.id, 'title': user.title, 'identifier': user.identifier, 'name': user.display_full_name, 'familyName': user.last_name, 'firstName': user.first_name, 'affiliation': user....
Serialize user to JSON-like object.
serialize_user
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def search_users(exact=False, include_deleted=False, include_pending=False, include_blocked=False, external=False, allow_system_user=False, **criteria): """Search for users. :param exact: Indicates if only exact matches should be returned. This is MUCH faster than a non-exact...
Search for users. :param exact: Indicates if only exact matches should be returned. This is MUCH faster than a non-exact saerch, especially when searching external users. :param include_deleted: Indicates if also users marked as deleted should be ...
search_users
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def get_user_by_email(email, create_pending=False): """Find a user based on his email address. :param email: The email address of the user. :param create_pending: If True, this function searches for external users and creates a new pending User in case ...
Find a user based on his email address. :param email: The email address of the user. :param create_pending: If True, this function searches for external users and creates a new pending User in case no existing user was found. :return: A :class:`.User` i...
get_user_by_email
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def merge_users(source, target, force=False): """Merge two users together, unifying all related data. :param source: source user (will be set as deleted) :param target: target user (final) """ if source.is_deleted and not force: raise ValueError(f'Source user {source} has been deleted. Merg...
Merge two users together, unifying all related data. :param source: source user (will be set as deleted) :param target: target user (final)
merge_users
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def anonymize_user(user): """Anonymize a user, removing all their personal data.""" signals.users.anonymized.send(user, flushed=False) user.first_name = '<anonymous>' user.last_name = f'<anonymous-{user.id}>' user.title = UserTitle.none user.affiliation = '' user.affiliation_id = None us...
Anonymize a user, removing all their personal data.
anonymize_user
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def get_color_for_user_id(user_id: int | str): """Calculate a unique color for a user based on their id. :param user_id: the user ID (int), or otherwise a string (external search results) """ if isinstance(user_id, int): return user_colors[user_id % len(user_colors)] else: return us...
Calculate a unique color for a user based on their id. :param user_id: the user ID (int), or otherwise a string (external search results)
get_color_for_user_id
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def send_default_avatar(user: User | str | None): """Send a user's default avatar as an SVG. :param user: A `User` object, string (external search results, registrations) or `None` (blank avatar) """ if not user: text = '' color = '#cccccc' elif isinstance(user, str): text =...
Send a user's default avatar as an SVG. :param user: A `User` object, string (external search results, registrations) or `None` (blank avatar)
send_default_avatar
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def get_mastodon_server_name(url): """Query a Mastodon server for its name.""" if not (server_url := strip_path_from_url(url)): return None try: resp = requests.get(f'{server_url}/api/v2/instance') resp.raise_for_status() data = resp.json() except (requests.RequestExcept...
Query a Mastodon server for its name.
get_mastodon_server_name
python
indico/indico
indico/modules/users/util.py
https://github.com/indico/indico/blob/master/indico/modules/users/util.py
MIT
def get(self, user, name, default=SettingsProxyBase.default_sentinel): """Retrieve the value of a single setting. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param name: Setting name :param default: Default value in case the setting does not exist :return: The settin...
Retrieve the value of a single setting. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param name: Setting name :param default: Default value in case the setting does not exist :return: The settings's value or the default value
get
python
indico/indico
indico/modules/users/models/settings.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/settings.py
MIT
def set(self, user, name, value): """Set a single setting. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param name: Setting name :param value: Setting value; must be JSON-serializable """ self._check_name(name) UserSetting.set(self.module, name, self._...
Set a single setting. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param name: Setting name :param value: Setting value; must be JSON-serializable
set
python
indico/indico
indico/modules/users/models/settings.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/settings.py
MIT
def set_multi(self, user, items): """Set multiple settings at once. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param items: Dict containing the new settings """ for name in items: self._check_name(name) items = {k: self._convert_from_python(k, v)...
Set multiple settings at once. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param items: Dict containing the new settings
set_multi
python
indico/indico
indico/modules/users/models/settings.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/settings.py
MIT
def delete(self, user, *names): """Delete settings. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param names: One or more names of settings to delete """ for name in names: self._check_name(name) UserSetting.delete(self.module, *names, **user) ...
Delete settings. :param user: ``{'user': user}`` or ``{'user_id': id}`` :param names: One or more names of settings to delete
delete
python
indico/indico
indico/modules/users/models/settings.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/settings.py
MIT
def merge_users(cls, target, source): """Merge the suggestions for two users. :param target: The target user of the merge. :param source: The user that is being merged into `target`. """ target_suggestions = {x.category: x for x in target.suggested_categories} for sugges...
Merge the suggestions for two users. :param target: The target user of the merge. :param source: The user that is being merged into `target`.
merge_users
python
indico/indico
indico/modules/users/models/suggestions.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/suggestions.py
MIT
def get_full_name(self, *, show_title=False, last_name_first=True, last_name_upper=True, abbrev_first_name=True, _show_empty_names=False): """Return the person's name in the specified notation. :param last_name_first: if "lastname, firstname" instead of ...
Return the person's name in the specified notation. :param last_name_first: if "lastname, firstname" instead of "firstname lastname" should be used :param last_name_upper: if the last name should be all-uppercase :param abbrev_first_name: if the first name should...
get_full_name
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def display_full_name(self): """Return the full name using the user's preferred name format.""" if has_request_context(): return format_display_full_name(session.user, self) else: return format_display_full_name(None, self)
Return the full name using the user's preferred name format.
display_full_name
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def local_identity(self): """The main (most recently used) local identity.""" identities = sorted(self.local_identities, key=attrgetter('safe_last_login_dt'), reverse=True) return identities[0] if identities else None
The main (most recently used) local identity.
local_identity
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def last_login_dt(self): """The datetime when the user last logged in.""" if not self.identities: return None return max(self.identities, key=attrgetter('safe_last_login_dt')).last_login_dt
The datetime when the user last logged in.
last_login_dt
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def synced_fields(self): """The fields of the user whose values are currently synced. This set is always a subset of the synced fields define in synced fields of the idp in 'indico.conf'. """ synced_fields = self.settings.get('synced_fields') # If synced_fields is missin...
The fields of the user whose values are currently synced. This set is always a subset of the synced fields define in synced fields of the idp in 'indico.conf'.
synced_fields
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def synced_values(self): """The values from the synced identity for the user. Those values are not the actual user's values and might differ if they are not set as synchronized. """ identity = self._get_synced_identity(refresh=False) if identity is None: retu...
The values from the synced identity for the user. Those values are not the actual user's values and might differ if they are not set as synchronized.
synced_values
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def log(self, realm, kind, module, summary, user=None, type_='simple', data=None, meta=None): """Create a new log entry for the user. :param realm: A value from :class:`.UserLogRealm` indicating the realm of the action. :param kind: A value from :class:`.LogKind` indicatin...
Create a new log entry for the user. :param realm: A value from :class:`.UserLogRealm` indicating the realm of the action. :param kind: A value from :class:`.LogKind` indicating the kind of the action that was performed. :param module: A human-friendly...
log
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT
def iter_identifiers(self, check_providers=False, providers=None): """Yields ``(provider, identifier)`` tuples for the user. :param check_providers: If True, providers are searched for additional identifiers once all existing identifiers h...
Yields ``(provider, identifier)`` tuples for the user. :param check_providers: If True, providers are searched for additional identifiers once all existing identifiers have been yielded. :param providers: May be a set containing provider n...
iter_identifiers
python
indico/indico
indico/modules/users/models/users.py
https://github.com/indico/indico/blob/master/indico/modules/users/models/users.py
MIT