@try_delegation<EOL><INDENT>def apply_handler(self, method_data, *args, **kwargs):<DEDENT>

if isinstance(method_data, tuple):<EOL><INDENT>len_method = len(method_data)<EOL>method = method_data[<NUM_LIT:0>]<EOL>if <NUM_LIT:1> < len_method:<EOL><INDENT>args = method_data[<NUM_LIT:1>]<EOL><DEDENT>if <NUM_LIT:2> < len_method:<EOL><INDENT>kwargs = method_data[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>method = method_data<EOL><DEDENT>return method(*args, **kwargs)<EOL>

Call the dispatched function, optionally with other data
        stored/created during .register and .prepare. Assume the arguments
        passed in by the dispathcer are the only ones required.


@functools.wraps(method)<EOL>def delegator(self, *args, **kwargs):<EOL><INDENT>if self.try_delegation:<EOL><INDENT>inst = getattr(self, '<STR_LIT>', None)<EOL>if inst is not None:<EOL><INDENT>method_name = (self.delegator_prefix or '<STR_LIT>') + method.__name__<EOL>func = getattr(inst, method_name, None)<EOL>if func is not None:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT><DEDENT>return method(self, *args, **kwargs)<EOL><DEDENT>return delegator<EOL>

This decorator wraps descriptor methods with a new method that tries
    to delegate to a function of the same name defined on the owner instance
    for convenience for dispatcher clients.


@try_delegation<EOL><INDENT>def register(self, method, args, kwargs):<DEDENT>

invoc = self.dump_invoc(*args, **kwargs)<EOL>self.registry.append((invoc, method.__name__))<EOL>

Given a single decorated handler function,
        prepare, append desired data to self.registry.


return self.registry<EOL>

Given all the registered handlers for this
        dispatcher instance, return any data required
        by the dispatch method.

        Can be overridden to provide more efficiency,
        simplicity, etc.


@try_delegation<EOL><INDENT>def gen_methods(self, *args, **kwargs):<DEDENT>

dispatched = False<EOL>for invoc, methodname in self.registry:<EOL><INDENT>args, kwargs = self.loads(invoc)<EOL>yield getattr(self.inst, methodname), args, kwargs<EOL>dispatched = True<EOL><DEDENT>if dispatched:<EOL><INDENT>return<EOL><DEDENT>generic_handler = getattr(self.inst, '<STR_LIT>', None)<EOL>if generic_handler is not None:<EOL><INDENT>yield generic_handler, args, kwargs<EOL><DEDENT>msg = '<STR_LIT>'<EOL>raise self.DispatchError(msg % ((args, kwargs), self.inst))<EOL>

Find all method names this input dispatches to. This method
        can accept *args, **kwargs, but it's the gen_dispatch method's
        job of passing specific args to handler methods.


@try_delegation<EOL><INDENT>def get_method(self, *args, **kwargs):<DEDENT>

for method in self.gen_methods(*args, **kwargs):<EOL><INDENT>return method<EOL><DEDENT>msg = '<STR_LIT>'<EOL>raise self.DispatchError(msg % ((args, kwargs), self.inst))<EOL>

Find the first method this input dispatches to.


@try_delegation<EOL><INDENT>def dispatch(self, *args, **kwargs):<DEDENT>

for result in self.gen_dispatch(*args, **kwargs):<EOL><INDENT>return result<EOL><DEDENT>

Find and evaluate/return the first method this input dispatches to.


@try_delegation<EOL><INDENT>def gen_dispatch(self, *args, **kwargs):<DEDENT>

dispatched = False<EOL>for method_data in self.gen_methods(*args, **kwargs):<EOL><INDENT>dispatched = True<EOL>result = self.apply_handler(method_data, *args, **kwargs)<EOL>yield result<EOL><DEDENT>if dispatched:<EOL><INDENT>return<EOL><DEDENT>msg = '<STR_LIT>'<EOL>raise self.DispatchError(msg % ((args, kwargs), self.inst))<EOL>

Find and evaluate/yield every method this input dispatches to.


kwargs = NoClobberDict(kwargs)<EOL>if isinstance(method_data, tuple):<EOL><INDENT>len_method = len(method_data)<EOL>method = method_data[<NUM_LIT:0>]<EOL>if <NUM_LIT:1> < len_method:<EOL><INDENT>args += method_data[<NUM_LIT:1>]<EOL><DEDENT>if <NUM_LIT:2> < len_method:<EOL><INDENT>kwargs.update(method_data[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>method = method_data<EOL><DEDENT>return method(*args, **kwargs)<EOL>

Call the dispatched function, optionally with other data
        stored/created during .register and .prepare

        The naivette in this function is likely source of future pain. It
        doesn't do very smart things when the decorator invocation AND the
        dispatcher.dispatch invocation both pass arguments.


return result<EOL>

Given an applied function result, yield from it.


@try_delegation<EOL><INDENT>def gen_method_keys(self, *args, **kwargs):<DEDENT>

token = args[<NUM_LIT:0>]<EOL>for mro_type in type(token).__mro__[:-<NUM_LIT:1>]:<EOL><INDENT>name = mro_type.__name__<EOL>yield name<EOL><DEDENT>

Given a node, return the string to use in computing the
        matching visitor methodname. Can also be a generator of strings.


@try_delegation<EOL><INDENT>@dedupe<EOL>def gen_methods(self, *args, **kwargs):<DEDENT>

token = args[<NUM_LIT:0>]<EOL>inst = self.inst<EOL>prefix = self._method_prefix<EOL>for method_key in self.gen_method_keys(*args, **kwargs):<EOL><INDENT>method = getattr(inst, prefix + method_key, None)<EOL>if method is not None:<EOL><INDENT>yield method<EOL><DEDENT><DEDENT>typename = type(token).__name__<EOL>yield from self.check_basetype(<EOL>token, typename, self.builtins.get(typename))<EOL>for basetype_name in self.interp_types:<EOL><INDENT>yield from self.check_basetype(<EOL>token, basetype_name, getattr(self.types, basetype_name, None))<EOL><DEDENT>for basetype_name in self.abc_types:<EOL><INDENT>yield from self.check_basetype(<EOL>token, basetype_name, getattr(self.collections, basetype_name, None))<EOL><DEDENT>yield from self.gen_generic()<EOL>

Find all method names this input dispatches to.


def activate_selected(self, request, queryset):

queryset.update(active=True)<EOL>count = queryset.count()<EOL>if count == <NUM_LIT:1>:<EOL><INDENT>message = _('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>message = _('<STR_LIT>')<EOL>message.format(count=count)  <EOL><DEDENT>self.message_user(request, message)<EOL>


def deactivate_selected(self, request, queryset):

queryset.update(active=False)<EOL>count = queryset.count()<EOL>if count == <NUM_LIT:1>:<EOL><INDENT>message = _('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>message = _('<STR_LIT>')<EOL>message.format(count=count)  <EOL><DEDENT>self.message_user(request, message)<EOL>


super(OrganizationsApiTestCase, self).setUp()<EOL>self.test_organization = api.add_organization({<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT:description>': '<STR_LIT>'<EOL>})<EOL>


Organization.objects.create(<EOL>name='<STR_LIT>',<EOL>description='<STR_LIT>',<EOL>active=active<EOL>)<EOL>


super(OrganizationsTestCaseBase, self).setUp()<EOL>self.test_course_key = CourseKey.from_string('<STR_LIT>')<EOL>


return {<EOL>'<STR_LIT:id>': organization.id,<EOL>'<STR_LIT:name>': organization.name,<EOL>'<STR_LIT>': organization.short_name,<EOL>'<STR_LIT:description>': organization.description,<EOL>'<STR_LIT>': organization.logo<EOL>}<EOL>


return {<EOL>'<STR_LIT:id>': organization_course.organization.id,<EOL>'<STR_LIT:name>': organization_course.organization.name,<EOL>'<STR_LIT>': organization_course.organization.short_name,<EOL>'<STR_LIT:description>': organization_course.organization.description,<EOL>'<STR_LIT>': organization_course.organization.logo,<EOL>'<STR_LIT>': organization_course.course_id<EOL>}<EOL>

OrganizationCourse serialization (composite object)


return [serialize_organization(organization) for organization in organizations]<EOL>

Organization serialization
Converts list of objects to list of dicts


if course_key is None:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>CourseKey.from_string(text_type(course_key))<EOL><DEDENT>except (InvalidKeyError, UnicodeDecodeError):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>


if organization_data is None:<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT:id>' in organization_data and not organization_data.get('<STR_LIT:id>'):<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT:name>' in organization_data and not organization_data.get('<STR_LIT:name>'):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>


record.active = True<EOL>record.save()<EOL>

Enables database records by setting the 'active' attribute to True
The queries in this module filter out inactive records as part of their criteria
This effectively allows us to soft-delete records so they are not lost forever


record.active = False<EOL>record.save()<EOL>

Disables database records by setting the 'active' attribute to False
The queries in this module filter out inactive records as part of their criteria
This effectively allows us to soft-delete records so they are not lost forever


[_activate_organization_course_relationship(record) for record<EOL>in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=False)]<EOL>[_activate_record(record) for record<EOL>in internal.Organization.objects.filter(id=organization.id, active=False)]<EOL>

Activates an inactivated (soft-deleted) organization as well as any inactive relationships


[_inactivate_organization_course_relationship(record) for record<EOL>in internal.OrganizationCourse.objects.filter(organization_id=organization.id, active=True)]<EOL>[_inactivate_record(record) for record<EOL>in internal.Organization.objects.filter(id=organization.id, active=True)]<EOL>

Inactivates an activated organization as well as any active relationships


<EOL>relationship = internal.OrganizationCourse.objects.get(<EOL>id=relationship.id,<EOL>active=False,<EOL>organization__active=True<EOL>)<EOL>_activate_record(relationship)<EOL>

Activates an inactive organization-course relationship


relationship = internal.OrganizationCourse.objects.get(<EOL>id=relationship.id,<EOL>active=True<EOL>)<EOL>_inactivate_record(relationship)<EOL>

Inactivates an active organization-course relationship


<EOL>if not organization.get('<STR_LIT:name>'):<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>organization_obj = serializers.deserialize_organization(organization)<EOL>try:<EOL><INDENT>organization = internal.Organization.objects.get(<EOL>name=organization_obj.name,<EOL>)<EOL>if not organization.active:<EOL><INDENT>_activate_organization(organization_obj)<EOL><DEDENT><DEDENT>except internal.Organization.DoesNotExist:<EOL><INDENT>organization = internal.Organization.objects.create(<EOL>name=organization_obj.name,<EOL>short_name=organization_obj.short_name,<EOL>description=organization_obj.description,<EOL>logo=organization_obj.logo,<EOL>active=True<EOL>)<EOL><DEDENT>return serializers.serialize_organization(organization)<EOL>

Inserts a new organization into app/local state given the following dictionary:
{
    'name': string,
    'description': string
}
Returns an updated dictionary including a new 'id': integer field/value


organization_obj = serializers.deserialize_organization(organization)<EOL>try:<EOL><INDENT>organization = internal.Organization.objects.get(id=organization_obj.id)<EOL>organization.name = organization_obj.name<EOL>organization.short_name = organization_obj.short_name<EOL>organization.description = organization_obj.description<EOL>organization.logo = organization_obj.logo<EOL>organization.active = organization_obj.active<EOL><DEDENT>except internal.Organization.DoesNotExist:<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>return serializers.serialize_organization(organization)<EOL>

Updates an existing organization in app/local state
Returns a dictionary representation of the object


organization_obj = serializers.deserialize_organization(organization)<EOL>_inactivate_organization(organization_obj)<EOL>

Inactivates an existing organization from app/local state
No return currently defined for this operation


organization = {'<STR_LIT:id>': organization_id}<EOL>if not organization_id:<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>organizations = serializers.serialize_organizations(<EOL>internal.Organization.objects.filter(id=organization_id, active=True)<EOL>)<EOL>if not organizations:<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>return organizations[<NUM_LIT:0>]<EOL>

Retrieves a specific organization from app/local state
Returns a dictionary representation of the object


organization = {'<STR_LIT>': organization_short_name}<EOL>if not organization_short_name:<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>organizations = serializers.serialize_organizations(internal.Organization.objects.filter(<EOL>active=True, short_name=organization_short_name<EOL>))<EOL>if not organizations:<EOL><INDENT>exceptions.raise_exception("<STR_LIT>", organization, exceptions.InvalidOrganizationException)<EOL><DEDENT>return organizations[<NUM_LIT:0>]<EOL>

Retrieves a specific organization from app/local state by short name
Returns a dictionary representation of the object


return serializers.serialize_organizations(internal.Organization.objects.filter(active=True))<EOL>

Retrieves the set of active organizations from app/local state
Returns a list-of-dicts representation of the object


Inserts a new organization-course relationship into app/local state
No response currently defined for this operation


Removes an existing organization-course relationship from app/local state
No response currently defined for this operation


organization_obj = serializers.deserialize_organization(organization)<EOL>queryset = internal.OrganizationCourse.objects.filter(<EOL>organization=organization_obj,<EOL>active=True<EOL>).select_related('<STR_LIT>')<EOL>return [serializers.serialize_organization_with_course(organization) for organization in queryset]<EOL>

Retrieves the set of courses currently linked to the specified organization


queryset = internal.OrganizationCourse.objects.filter(<EOL>course_id=text_type(course_key),<EOL>active=True<EOL>).select_related('<STR_LIT>')<EOL>return [serializers.serialize_organization_with_course(organization) for organization in queryset]<EOL>

Retrieves the organizations linked to the specified course


[_inactivate_record(record) for record in internal.OrganizationCourse.objects.filter(<EOL>course_id=text_type(course_key),<EOL>active=True<EOL>)]<EOL>

Inactivates references to course keys within this app (ref: receivers.py and api.py)


if not validators.course_key_is_valid(course_key):<EOL><INDENT>exceptions.raise_exception(<EOL>"<STR_LIT>",<EOL>course_key,<EOL>exceptions.InvalidCourseKeyException<EOL>)<EOL><DEDENT>


_validate_organization_data(organization_data)<EOL>organization = data.create_organization(organization_data)<EOL>return organization<EOL>

Passes a new organization to the data layer for storage


_validate_organization_data(organization_data)<EOL>return data.update_organization(organization_data)<EOL>

Passes an updated organization to the data layer for storage


return data.fetch_organization(organization_id)<EOL>


return data.fetch_organization_by_short_name(organization_short_name)<EOL>

Retrieves the organization filtered by short name


return data.fetch_organizations()<EOL>

Retrieves the active organizations managed by the system


organization = {<EOL>'<STR_LIT:id>': organization_id,<EOL>}<EOL>data.delete_organization(organization)<EOL>


_validate_course_key(course_key)<EOL>_validate_organization_data(organization_data)<EOL>data.create_organization_course(<EOL>organization=organization_data,<EOL>course_key=course_key<EOL>)<EOL>

Adds a organization-course link to the system


_validate_organization_data(organization_data)<EOL>return data.fetch_organization_courses(organization=organization_data)<EOL>

Retrieves the set of courses for a given organization
Returns an array of course identifiers


_validate_organization_data(organization)<EOL>_validate_course_key(course_key)<EOL>return data.delete_organization_course(course_key=course_key, organization=organization)<EOL>

Removes the specfied course from the specified organization


_validate_course_key(course_key)<EOL>return data.fetch_course_organizations(course_key=course_key)<EOL>

Retrieves the set of organizations for a given course
Returns an array of dicts containing organizations


_validate_course_key(course_key)<EOL>data.delete_course_references(course_key)<EOL>

Removes course references from application state
See edx-platform/lms/djangoapps/courseware/management/commands/delete_course_references.py


return reverse('<STR_LIT>', kwargs={'<STR_LIT>': organization.short_name})<EOL>


def raise_exception(entity_type, entity, exception):

raise exception(<EOL>u'<STR_LIT>'.format(entity_type, entity).encode('<STR_LIT:utf-8>')<EOL>)<EOL>


comment = kwargs['<STR_LIT>']<EOL>if comment.content_type.app_label == "<STR_LIT>" and comment.content_type.name == "<STR_LIT>":<EOL><INDENT>from .models import Update<EOL>item = Update.objects.get(id=comment.object_pk)<EOL>item.save()<EOL><DEDENT>

When a Comment is added, updates the Update to set "last_updated" time


from happenings.models import Event<EOL>start_period = today - datetime.timedelta(days=<NUM_LIT:2>)<EOL>end_period = today + datetime.timedelta(days=days)<EOL>if featured:<EOL><INDENT>return Event.objects.filter(<EOL>featured=True,<EOL>start_date__gte=start_period,<EOL>start_date__lte=end_period<EOL>).count()<EOL><DEDENT>return Event.objects.filter(start_date__gte=start_period, start_date__lte=end_period).count()<EOL>

Returns count of upcoming events for a given number of days, either featured or all
Usage:
{% get_upcoming_events_count DAYS as events_count %}
with days being the number of days you want, or 5 by default


@register.simple_tag<EOL>def get_upcoming_events(num, days, featured=False):

from happenings.models import Event<EOL>start_date = today - datetime.timedelta(days=days)<EOL>events = Event.objects.filter(start_date__gt=start_date).order_by('<STR_LIT>')<EOL>if featured:<EOL><INDENT>events = events.filter(featured=True)<EOL><DEDENT>events = events[:num]<EOL>return events<EOL>

Get upcoming events.
Allows slicing to a given number,
picking the number of days to hold them after they've started
and whether they should be featured or not.
Usage:
{% get_upcoming_events 5 14 featured as events %}
Would return no more than 5 Featured events,
holding them for 14 days past their start date.


@register.simple_tag<EOL>def get_events_by_date_range(days_out, days_hold, max_num=<NUM_LIT:5>, featured=False):

from happenings.models import Event<EOL>range_start = today - datetime.timedelta(days=days_hold)<EOL>range_end = today + datetime.timedelta(days=days_out)<EOL>events = Event.objects.filter(<EOL>start_date__gte=range_start,<EOL>start_date__lte=range_end<EOL>).order_by('<STR_LIT>')<EOL>if featured:<EOL><INDENT>events = events.filter(featured=True)<EOL><DEDENT>events = events[:max_num]<EOL>return events<EOL>

Get upcoming events for a given number of days (days out)
Allows specifying number of days to hold events after they've started
The max number to show (defaults to 5)
and whether they should be featured or not.
Usage:
{% get_events_by_date_range 14 3 3 'featured' as events %}
Would return no more than 3 featured events,
that fall within the next 14 days or have ended within the past 3.


from happenings.models import Update<EOL>time = update.pub_time<EOL>event = update.event<EOL>try:<EOL><INDENT>next = Update.objects.filter(<EOL>event=event,<EOL>pub_time__gt=time<EOL>).order_by('<STR_LIT>').only('<STR_LIT:title>')[<NUM_LIT:0>]<EOL><DEDENT>except:<EOL><INDENT>next = None<EOL><DEDENT>try:<EOL><INDENT>previous = Update.objects.filter(<EOL>event=event,<EOL>pub_time__lt=time<EOL>).order_by('<STR_LIT>').only('<STR_LIT:title>')[<NUM_LIT:0>]<EOL><DEDENT>except:<EOL><INDENT>previous = None<EOL><DEDENT>return {'<STR_LIT>': next, '<STR_LIT>': previous, '<STR_LIT>': event}<EOL>

attempts to get next and previous on updates


event = get_object_or_404(Event, slug=slug)<EOL>start = event.start_date<EOL>start = datetime.datetime(start.year, start.month, start.day)<EOL>if event.end_date:<EOL><INDENT>end = event.end_date<EOL>end = datetime.datetime(end.year, end.month, end.day)<EOL><DEDENT>else:<EOL><INDENT>end = start<EOL><DEDENT>cal = card_me.iCalendar()<EOL>cal.add('<STR_LIT>').value = '<STR_LIT>'<EOL>vevent = cal.add('<STR_LIT>')<EOL>vevent.add('<STR_LIT>').value = start<EOL>vevent.add('<STR_LIT>').value = end<EOL>vevent.add('<STR_LIT>').value = datetime.datetime.now()<EOL>vevent.add('<STR_LIT>').value = event.name<EOL>response = HttpResponse(cal.serialize(), content_type='<STR_LIT>')<EOL>response['<STR_LIT>'] = '<STR_LIT>'<EOL>response['<STR_LIT>'] = '<STR_LIT>'<EOL>return response<EOL>

Creates an ical .ics file for an event using python-card-me.


event = get_object_or_404(Event, slug=slug)<EOL>comments = event.all_comments<EOL>page = int(request.GET.get('<STR_LIT>', <NUM_LIT>))  <EOL>is_paginated = False<EOL>if comments:<EOL><INDENT>paginator = Paginator(comments, <NUM_LIT:50>)  <EOL>try:<EOL><INDENT>comments = paginator.page(page)<EOL><DEDENT>except EmptyPage:<EOL><INDENT>comments = paginator.page(paginator.num_pages)<EOL><DEDENT>is_paginated = comments.has_other_pages()<EOL><DEDENT>return render(request, '<STR_LIT>', {<EOL>"<STR_LIT>": event,<EOL>"<STR_LIT>": comments,<EOL>"<STR_LIT>": comments,<EOL>"<STR_LIT>": comments,<EOL>"<STR_LIT>": page,<EOL>"<STR_LIT>": is_paginated,<EOL>"<STR_LIT:key>": key<EOL>})<EOL>

Returns a list view of all comments for a given event.
Combines event comments and update comments in one list.


event = get_object_or_404(Event, slug=slug)<EOL>updates = Update.objects.filter(event__slug=slug)<EOL>if event.recently_ended():<EOL><INDENT>updates = updates.order_by('<STR_LIT:id>')<EOL><DEDENT>else:<EOL><INDENT>updates = updates.order_by('<STR_LIT>')<EOL><DEDENT>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': event,<EOL>'<STR_LIT>': updates,<EOL>})<EOL>

Returns a list view of updates for a given event.
If the event is over, it will be in chronological order.
If the event is upcoming or still going,
it will be in reverse chronological order.


event = get_object_or_404(Event, slug=slug)<EOL>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': event,<EOL>'<STR_LIT>': event.eventvideo_set.all()<EOL>})<EOL>

Displays list of videos for given event.


form = AddEventForm(request.POST or None)<EOL>if form.is_valid():<EOL><INDENT>instance = form.save(commit=False)<EOL>instance.sites = settings.SITE_ID<EOL>instance.submitted_by = request.user<EOL>instance.approved = True<EOL>instance.slug = slugify(instance.name)<EOL>instance.save()<EOL>messages.success(request, '<STR_LIT>')<EOL>return HttpResponseRedirect(reverse('<STR_LIT>'))<EOL><DEDENT>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': form,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>})<EOL>


event = get_object_or_404(Event, slug=slug)<EOL>form = MemoryForm(request.POST or None, request.FILES or None)<EOL>if form.is_valid():<EOL><INDENT>instance = form.save(commit=False)<EOL>instance.user = request.user<EOL>instance.event = event<EOL>instance.save()<EOL>msg = "<STR_LIT>"<EOL>if request.FILES:<EOL><INDENT>photo_list = request.FILES.getlist('<STR_LIT>')<EOL>photo_count = len(photo_list)<EOL>for upload_file in photo_list:<EOL><INDENT>process_upload(upload_file, instance, form, event, request)<EOL><DEDENT>if photo_count > <NUM_LIT:1>:<EOL><INDENT>msg += "<STR_LIT>".format(photo_count)<EOL><DEDENT>else:<EOL><INDENT>msg += "<STR_LIT>".format(photo_count)<EOL><DEDENT><DEDENT>messages.success(request, msg)<EOL>return HttpResponseRedirect('<STR_LIT>')<EOL><DEDENT>return render(request, '<STR_LIT>', {'<STR_LIT>': form, '<STR_LIT>': event})<EOL>


def process_upload(upload_file, instance, form, event, request):

caption = form.cleaned_data.get('<STR_LIT>')<EOL>upload_name = upload_file.name.lower()<EOL>if upload_name.endswith('<STR_LIT>') or upload_name.endswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>upload = Image(<EOL>event=event,<EOL>image=upload_file,<EOL>caption=caption,<EOL>)<EOL>upload.save()<EOL>instance.photos.add(upload)<EOL><DEDENT>except Exception as error:<EOL><INDENT>messages.error(request, '<STR_LIT>'.format(error))<EOL><DEDENT><DEDENT>

Helper function that actually processes and saves the upload(s).
Segregated out for readability.


cleaned = super(EventForm, self).clean()<EOL>if Event.objects.filter(name=cleaned['<STR_LIT:name>'], start_date=cleaned['<STR_LIT>']).count():<EOL><INDENT>raise forms.ValidationError(u'<STR_LIT>')<EOL><DEDENT>return cleaned<EOL>

Validate that an event with this name on this date does not exist.


lapsed = datetime.datetime.now() - datetime.timedelta(days=<NUM_LIT>)<EOL>for event in self.filter(start_date__lte=lapsed, featured=<NUM_LIT:0>, recap='<STR_LIT>'):<EOL><INDENT>event.delete()<EOL><DEDENT>

Removes old events. This is provided largely as a convenience for maintenance
purposes (daily_cleanup). if an Event has passed by more than X days
as defined by Lapsed and has no related special events it will be deleted
to free up the event name and remove clutter.
For best results, set this up to run regularly as a cron job.


if self.ended():<EOL><INDENT>end_date = self.end_date if self.end_date else self.start_date<EOL>if end_date >= offset.date():<EOL><INDENT>return True<EOL><DEDENT><DEDENT>

Determines if event ended recently (within 5 days).
Useful for attending list.


if self.start_date <= datetime.date.today():<EOL><INDENT>return True<EOL><DEDENT>


return True<EOL>

Determine if comments should be allowed.
Probably need some more robust logic here :-)
Maybe something like "If event has been over for a month, no more comments."
Or something.


try:<EOL><INDENT>return self.image_set.all()[<NUM_LIT:0>].image<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>

Returns first image object from set for an image representation


self_imgs = self.image_set.all()<EOL>update_ids = self.update_set.values_list('<STR_LIT:id>', flat=True)<EOL>u_images = UpdateImage.objects.filter(update__id__in=update_ids)<EOL>return list(chain(self_imgs, u_images))<EOL>

Returns chained list of event and update images.


self_imgs = self.image_set.count()<EOL>update_ids = self.update_set.values_list('<STR_LIT:id>', flat=True)<EOL>u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()<EOL>count = self_imgs + u_images<EOL>return count<EOL>

Gets count of all images from both event and updates.


images = self.get_all_images()[<NUM_LIT:0>:<NUM_LIT>]<EOL>video = []<EOL>if supports_video:<EOL><INDENT>video = self.eventvideo_set.all()[<NUM_LIT:0>:<NUM_LIT:10>]<EOL><DEDENT>return list(chain(images, video))[<NUM_LIT:0>:<NUM_LIT:15>]<EOL>

Gets images and videos to populate top assets.

Map is built separately.


return self.event.comments_open<EOL>

Based on the update's event's comments open status


return True<EOL>


ctype = ContentType.objects.get(app_label__exact="<STR_LIT>", model__exact='<STR_LIT>')<EOL>update_ctype = ContentType.objects.get(app_label__exact="<STR_LIT>", model__exact='<STR_LIT>')<EOL>update_ids = self.update_set.values_list('<STR_LIT:id>', flat=True)<EOL>return Comment.objects.filter(<EOL>Q(content_type=ctype.id, object_pk=self.id) |<EOL>Q(content_type=update_ctype.id, object_pk__in=update_ids)<EOL>)<EOL>

Returns combined list of event and update comments.


return self.event.comments_open<EOL>


<EOL>return {<EOL>'<STR_LIT>': self.device.device.is_alive()<EOL>}<EOL>

Returns a flag with the state of the connection.


<EOL>bib = []<EOL>if not isinstance(string, six.text_type):<EOL><INDENT>string = string.decode('<STR_LIT:utf-8>')<EOL><DEDENT>for key, value in special_chars:<EOL><INDENT>string = string.replace(key, value)<EOL><DEDENT>string = re.sub(r'<STR_LIT>', r'<STR_LIT>', string)<EOL>entries = re.findall(<EOL>r'<STR_LIT>',<EOL>string)<EOL>for entry in entries:<EOL><INDENT>pairs = re.findall(r'<STR_LIT>', entry[<NUM_LIT:2>])<EOL>bib.append({'<STR_LIT:type>': entry[<NUM_LIT:0>].lower(), '<STR_LIT:key>': entry[<NUM_LIT:1>]})<EOL>for key, value in pairs:<EOL><INDENT>key = key.lower()<EOL>if value and value[<NUM_LIT:0>] == '<STR_LIT:">' and value[-<NUM_LIT:1>] == '<STR_LIT:">':<EOL><INDENT>value = value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>if value and value[<NUM_LIT:0>] == '<STR_LIT:{>' and value[-<NUM_LIT:1>] == '<STR_LIT:}>':<EOL><INDENT>value = value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>if key not in ['<STR_LIT>', '<STR_LIT:title>']:<EOL><INDENT>value = value.replace('<STR_LIT:}>', '<STR_LIT>').replace('<STR_LIT:{>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if value.startswith('<STR_LIT:{>') and value.endswith('<STR_LIT:}>'):<EOL><INDENT>value = value[<NUM_LIT:1>:]<EOL>value = value[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>value = value.strip()<EOL>value = re.sub(r'<STR_LIT>', '<STR_LIT:U+0020>', value)<EOL>bib[-<NUM_LIT:1>][key] = value<EOL><DEDENT><DEDENT>return bib<EOL>

Takes a string in BibTex format and returns a list of BibTex entries, where
each entry is a dictionary containing the entries' key-value pairs.

@type  string: string
@param string: bibliography in BibTex format

@rtype: list
@return: a list of dictionaries representing a bibliography


types = Type.objects.filter(hidden=False)<EOL>publications = Publication.objects.select_related()<EOL>publications = publications.filter(external=False, type__in=types)<EOL>publications = publications.order_by('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>if not publications:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>populate(publications)<EOL>return render_template(template, context['<STR_LIT>'], {'<STR_LIT>': publications})<EOL>


pbl = Publication.objects.filter(pk=int(id))<EOL>if len(pbl) < <NUM_LIT:1>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>pbl[<NUM_LIT:0>].links = pbl[<NUM_LIT:0>].customlink_set.all()<EOL>pbl[<NUM_LIT:0>].files = pbl[<NUM_LIT:0>].customfile_set.all()<EOL>return render_template(<EOL>'<STR_LIT>', context['<STR_LIT>'], {'<STR_LIT>': pbl[<NUM_LIT:0>]})<EOL>


def get_publication_list(context, list, template='<STR_LIT>'):

list = List.objects.filter(list__iexact=list)<EOL>if not list:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>list = list[<NUM_LIT:0>]<EOL>publications = list.publication_set.all()<EOL>publications = publications.order_by('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>if not publications:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>populate(publications)<EOL>return render_template(<EOL>template, context['<STR_LIT>'], {'<STR_LIT:list>': list, '<STR_LIT>': publications})<EOL>


string = string.replace('<STR_LIT:{>', '<STR_LIT>').replace('<STR_LIT:}>', '<STR_LIT>')<EOL>def tex_replace(match):<EOL><INDENT>returnsub(r'<STR_LIT>', r'<STR_LIT>',<EOL>sub(r'<STR_LIT>', r'<STR_LIT>',<EOL>sub(r'<STR_LIT>', r'<STR_LIT>',<EOL>sub(r'<STR_LIT>', r'<STR_LIT>',<EOL>sub(r'<STR_LIT>' + GREEK_LETTERS + '<STR_LIT:)>', r'<STR_LIT>', match.group(<NUM_LIT:1>))))))<EOL><DEDENT>return mark_safe(sub(r'<STR_LIT>', tex_replace, escape(string)))<EOL>


type2genre = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>tp = str(self.type).lower()<EOL>return type2genre.get(tp, tp)<EOL>

Guesses an appropriate MODS XML genre type.


<EOL>self.authors = self.authors.replace('<STR_LIT>', '<STR_LIT:U+002CU+0020>')<EOL>self.authors = self.authors.replace('<STR_LIT>', '<STR_LIT:U+002CU+0020>')<EOL>self.authors = self.authors.replace('<STR_LIT>', '<STR_LIT:U+002CU+0020>')<EOL>self.authors = self.authors.replace('<STR_LIT:;>', '<STR_LIT:U+002C>')<EOL>self.authors_list = [author.strip() for author in self.authors.split('<STR_LIT:U+002C>')]<EOL>self.authors_list_simple = []<EOL>self.authors_list_split = []<EOL>self.title_ends_with_punct = self.title[-<NUM_LIT:1>] in ['<STR_LIT:.>', '<STR_LIT:!>', '<STR_LIT:?>']if len(self.title) > <NUM_LIT:0> else False<EOL>suffixes = ['<STR_LIT:I>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', "<STR_LIT>", "<STR_LIT>"]<EOL>prefixes = ['<STR_LIT>']<EOL>prepositions = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>for i, author in enumerate(self.authors_list):<EOL><INDENT>if author == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>names = author.split('<STR_LIT:U+0020>')<EOL>if (len(names[-<NUM_LIT:1>]) <= <NUM_LIT:3>)and names[-<NUM_LIT:1>] not in suffixesand all(c in ascii_uppercase for c in names[-<NUM_LIT:1>]):<EOL><INDENT>names = [c + '<STR_LIT:.>' for c in names[-<NUM_LIT:1>]] + names[:-<NUM_LIT:1>]<EOL><DEDENT>num_suffixes = <NUM_LIT:0><EOL>for name in names[::-<NUM_LIT:1>]:<EOL><INDENT>if name in suffixes:<EOL><INDENT>num_suffixes += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>for j, name in enumerate(names[:-<NUM_LIT:1> - num_suffixes]):<EOL><INDENT>if j == <NUM_LIT:0> and name in prefixes:<EOL><INDENT>continue<EOL><DEDENT>if j > <NUM_LIT:0> and name in prepositions:<EOL><INDENT>continue<EOL><DEDENT>if (len(name) > <NUM_LIT:2>) or (len(name) and (name[-<NUM_LIT:1>] != '<STR_LIT:.>')):<EOL><INDENT>k = name.find('<STR_LIT:->')<EOL>if <NUM_LIT:0> < k + <NUM_LIT:1> < len(name):<EOL><INDENT>names[j] = name[<NUM_LIT:0>] + '<STR_LIT>' + name[k + <NUM_LIT:1>] + '<STR_LIT:.>'<EOL><DEDENT>else:<EOL><INDENT>names[j] = name[<NUM_LIT:0>] + '<STR_LIT:.>'<EOL><DEDENT><DEDENT><DEDENT>if len(names):<EOL><INDENT>self.authors_list[i] = '<STR_LIT:U+0020>'.join(names)<EOL>if len(names) > <NUM_LIT:1>:<EOL><INDENT>for name in names[<NUM_LIT:0>].split('<STR_LIT:->'):<EOL><INDENT>name_simple = self.simplify_name('<STR_LIT:U+0020>'.join([name, names[-<NUM_LIT:1>]]))<EOL>self.authors_list_simple.append(name_simple)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.authors_list_simple.append(self.simplify_name(names[<NUM_LIT:0>]))<EOL><DEDENT>num_prepositions = <NUM_LIT:0><EOL>for name in names:<EOL><INDENT>if name in prepositions:<EOL><INDENT>num_prepositions += <NUM_LIT:1><EOL><DEDENT><DEDENT>sp = <NUM_LIT:1> + num_suffixes + num_prepositions<EOL>self.authors_list_split.append(<EOL>('<STR_LIT:U+0020>'.join(names[:-sp]), '<STR_LIT:U+0020>'.join(names[-sp:])))<EOL><DEDENT><DEDENT>self.authors_bibtex = '<STR_LIT>'.join(self.authors_list)<EOL>if len(self.authors_list) > <NUM_LIT:2>:<EOL><INDENT>self.authors = '<STR_LIT>'.join([<EOL>'<STR_LIT:U+002CU+0020>'.join(self.authors_list[:-<NUM_LIT:1>]),<EOL>self.authors_list[-<NUM_LIT:1>]])<EOL><DEDENT>elif len(self.authors_list) > <NUM_LIT:1>:<EOL><INDENT>self.authors = '<STR_LIT>'.join(self.authors_list)<EOL><DEDENT>else:<EOL><INDENT>self.authors = self.authors_list[<NUM_LIT:0>]<EOL><DEDENT>

Parse authors string to create lists of authors.


warnings.warn(<EOL>_("<STR_LIT>"),<EOL>DeprecationWarning<EOL>)<EOL>return self.down()<EOL>


warnings.warn(<EOL>_("<STR_LIT>"),<EOL>DeprecationWarning<EOL>)<EOL>return self.up()<EOL>


try:<EOL><INDENT>replacement = qs[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>return<EOL><DEDENT>if not self._valid_ordering_reference(replacement):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>self, self.__class__, self.order_with_respect_to,<EOL>self._get_order_with_respect_to()<EOL>)<EOL>)<EOL><DEDENT>self.order, replacement.order = replacement.order, self.order<EOL>self.save()<EOL>replacement.save()<EOL>

Swap the positions of this object with a reference object.


self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('<STR_LIT>'))<EOL>


self.swap(self.get_ordering_queryset().filter(order__gt=self.order))<EOL>


if order is None or self.order == order:<EOL><INDENT>return<EOL><DEDENT>qs = self.get_ordering_queryset()<EOL>if self.order > order:<EOL><INDENT>qs.filter(order__lt=self.order, order__gte=order).update(order=F('<STR_LIT>') + <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>qs.filter(order__gt=self.order, order__lte=order).update(order=F('<STR_LIT>') - <NUM_LIT:1>)<EOL><DEDENT>self.order = order<EOL>self.save()<EOL>

Move object to a certain position, updating all affected objects to move accordingly up or down.


if not self._valid_ordering_reference(ref):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>self, self.__class__, self.order_with_respect_to,<EOL>self._get_order_with_respect_to()<EOL>)<EOL>)<EOL><DEDENT>if self.order == ref.order:<EOL><INDENT>return<EOL><DEDENT>if self.order > ref.order:<EOL><INDENT>o = ref.order<EOL><DEDENT>else:<EOL><INDENT>o = self.get_ordering_queryset().filter(order__lt=ref.order).aggregate(Max('<STR_LIT>')).get('<STR_LIT>') or <NUM_LIT:0><EOL><DEDENT>self.to(o)<EOL>

Move this object above the referenced object.


if not self._valid_ordering_reference(ref):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>self, self.__class__, self.order_with_respect_to,<EOL>self._get_order_with_respect_to()<EOL>)<EOL>)<EOL><DEDENT>if self.order == ref.order:<EOL><INDENT>return<EOL><DEDENT>if self.order > ref.order:<EOL><INDENT>o = self.get_ordering_queryset().filter(order__gt=ref.order).aggregate(Min('<STR_LIT>')).get('<STR_LIT>') or <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>o = ref.order<EOL><DEDENT>self.to(o)<EOL>

Move this object below the referenced object.


o = self.get_ordering_queryset().aggregate(Min('<STR_LIT>')).get('<STR_LIT>')<EOL>self.to(o)<EOL>

Move this object to the top of the ordered stack.


o = self.get_ordering_queryset().aggregate(Max('<STR_LIT>')).get('<STR_LIT>')<EOL>self.to(o)<EOL>

Move this object to the bottom of the ordered stack.


func.__doc__ = doc<EOL>


__import__(name)<EOL>return sys.modules[name]<EOL>

Import module, returning the module after the last dot.


setattr(_MovedItems, move.name, move)<EOL>


try:<EOL><INDENT>delattr(_MovedItems, name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>del moves.__dict__[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError("<STR_LIT>" % (name,))<EOL><DEDENT><DEDENT>


return iter(getattr(d, _iterkeys)(**kw))<EOL>

Return an iterator over the keys of a dictionary.


return iter(getattr(d, _itervalues)(**kw))<EOL>

Return an iterator over the values of a dictionary.


return iter(getattr(d, _iteritems)(**kw))<EOL>

Return an iterator over the (key, value) pairs of a dictionary.


return iter(getattr(d, _iterlists)(**kw))<EOL>

Return an iterator over the (key, [values]) pairs of a dictionary.


return meta("<STR_LIT>", bases, {})<EOL>


def wrapper(cls):<EOL><INDENT>orig_vars = cls.__dict__.copy()<EOL>orig_vars.pop('<STR_LIT>', None)<EOL>orig_vars.pop('<STR_LIT>', None)<EOL>slots = orig_vars.get('<STR_LIT>')<EOL>if slots is not None:<EOL><INDENT>if isinstance(slots, str):<EOL><INDENT>slots = [slots]<EOL><DEDENT>for slots_var in slots:<EOL><INDENT>orig_vars.pop(slots_var)<EOL><DEDENT><DEDENT>return metaclass(cls.__name__, cls.__bases__, orig_vars)<EOL><DEDENT>return wrapper<EOL>

Class decorator for creating a class with a metaclass.


customlinks = CustomLink.objects.filter(publication__in=publications)<EOL>customfiles = CustomFile.objects.filter(publication__in=publications)<EOL>publications_ = {}<EOL>for publication in publications:<EOL><INDENT>publication.links = []<EOL>publication.files = []<EOL>publications_[publication.id] = publication<EOL><DEDENT>for link in customlinks:<EOL><INDENT>publications_[link.publication_id].links.append(link)<EOL><DEDENT>for file in customfiles:<EOL><INDENT>publications_[file.publication_id].files.append(file)<EOL><DEDENT>

Load custom links and files from database and attach to publications.


id = request.GET.get('<STR_LIT:id>')<EOL>format = request.GET.get('<STR_LIT>')<EOL>if format is not None:<EOL><INDENT>try:<EOL><INDENT>publications = Publication.objects.filter(pk=int(id))<EOL>if not publications:<EOL><INDENT>raise ValueError<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>return HttpResponse('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']),<EOL>content_type="<STR_LIT>",<EOL>status=<NUM_LIT>)<EOL><DEDENT>if format == '<STR_LIT>':<EOL><INDENT>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': publications[<NUM_LIT:0>]<EOL>},<EOL>content_type='<STR_LIT>')<EOL><DEDENT>if format == '<STR_LIT>':<EOL><INDENT>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': publications<EOL>},<EOL>content_type='<STR_LIT>')<EOL><DEDENT>if format == '<STR_LIT>':<EOL><INDENT>return render(request, '<STR_LIT>', {<EOL>'<STR_LIT>': publications<EOL>},<EOL>content_type='<STR_LIT>')<EOL><DEDENT>return HttpResponse('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']),<EOL>content_type="<STR_LIT>",<EOL>status=<NUM_LIT>)<EOL><DEDENT>if id is not None:<EOL><INDENT>return HttpResponse('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(id),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']), content_type="<STR_LIT>")<EOL><DEDENT>return HttpResponse('<STR_LIT:\n>'.join([<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']), content_type="<STR_LIT>")<EOL>

This view implements unAPI 1.0 (see http://unapi.info).


sys.stdout.write('<STR_LIT>' % tests.countTestCases())<EOL>res = unittest.TestResult()<EOL>suite.run(res)<EOL>if res.wasSuccessful():<EOL><INDENT>sys.stdout.write('<STR_LIT>')<EOL>return<EOL><DEDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>for problems, kind in ((res.errors, '<STR_LIT:error>'),<EOL>(res.failures, '<STR_LIT>')):<EOL><INDENT>if len(problems):<EOL><INDENT>head = '<STR_LIT>' % (len(problems),<EOL>kind,<EOL>'<STR_LIT:s>' if len(problems) != <NUM_LIT:1> else '<STR_LIT>')<EOL>sys.stdout.write('<STR_LIT>' %<EOL>(head, '<STR_LIT>' * len(head)))<EOL><DEDENT>for problem in problems:<EOL><INDENT>func = problem[<NUM_LIT:0>]._testMethodName[<NUM_LIT:5>:]<EOL>environ = '<STR_LIT>' if isinstance(problem[<NUM_LIT:0>],<EOL>BrokenCtypesTest)else '<STR_LIT>'<EOL>sys.stdout.write(<EOL>'<STR_LIT>' %<EOL>(func, environ, '<STR_LIT:\n>'.join(map(lambda s: '<STR_LIT:U+0020>' + s,<EOL>problem[<NUM_LIT:1>].splitlines())))<EOL>)<EOL><DEDENT><DEDENT>sys.stdout.write('<STR_LIT>' %<EOL>(res.testsRun - len(res.failures) - len(res.errors)))<EOL>

unittest is basically a disaster, so let's do this ourselves.


imp.reload(uptime)<EOL>

__boottime affects how boottime() and its helpers work, and it may be
set as a side-effect by any function. To be on the safe side, just
reload the whole module every time.


<EOL>try:<EOL><INDENT>f = open('<STR_LIT>', '<STR_LIT:r>')<EOL>up = float(f.readline().split()[<NUM_LIT:0>])<EOL>f.close()<EOL>return up<EOL><DEDENT>except (IOError, ValueError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>libc = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>except OSError:<EOL><INDENT>try:<EOL><INDENT>libc = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except OSError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if not hasattr(libc, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>buf = ctypes.create_string_buffer(<NUM_LIT>) <EOL>if libc.sysinfo(buf) < <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>up = struct.unpack_from('<STR_LIT>', buf.raw)[<NUM_LIT:0>]<EOL>if up < <NUM_LIT:0>:<EOL><INDENT>up = None<EOL><DEDENT>return up<EOL>

Returns uptime in seconds or None, on Linux.


global __boottime<EOL>try:<EOL><INDENT>f = open('<STR_LIT>', '<STR_LIT:r>')<EOL>for line in f:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>__boottime = int(line.split()[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>if datetime is None:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>return datetime.fromtimestamp(__boottime)<EOL><DEDENT>except (IOError, IndexError):<EOL><INDENT>return None<EOL><DEDENT>

A way to figure out the boot time directly on Linux.


global __boottime<EOL>try:<EOL><INDENT>__boottime = os.stat('<STR_LIT>').st_ctime<EOL>return time.time() - __boottime<EOL><DEDENT>except (NameError, OSError):<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on AmigaOS.


try:<EOL><INDENT>libroot = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except (AttributeError, OSError):<EOL><INDENT>return None<EOL><DEDENT>if not hasattr(libroot, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>libroot.system_time.restype = ctypes.c_int64<EOL>return libroot.system_time() / <NUM_LIT><EOL>

Returns uptime in seconds on None, on BeOS/Haiku.


global __boottime<EOL>try:<EOL><INDENT>libc = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>except OSError:<EOL><INDENT>try:<EOL><INDENT>libc = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except OSError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if not hasattr(libc, '<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>sz = ctypes.c_uint(<NUM_LIT:0>)<EOL>libc.sysctlbyname('<STR_LIT>', None, ctypes.byref(sz), None, <NUM_LIT:0>)<EOL>if sz.value != struct.calcsize('<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>buf = ctypes.create_string_buffer(sz.value)<EOL>libc.sysctlbyname('<STR_LIT>', buf, ctypes.byref(sz), None, <NUM_LIT:0>)<EOL>sec, usec = struct.unpack('<STR_LIT>', buf.raw)<EOL>if usec > <NUM_LIT>:<EOL><INDENT>usec = <NUM_LIT:0.><EOL><DEDENT>__boottime = sec + usec / <NUM_LIT><EOL>up = time.time() - __boottime<EOL>if up < <NUM_LIT:0>:<EOL><INDENT>up = None<EOL><DEDENT>return up<EOL>

Returns uptime in seconds or None, on BSD (including OS X).


try:<EOL><INDENT>return MacOS.GetTicks() / <NUM_LIT><EOL><DEDENT>except NameError:<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on Mac OS.


try:<EOL><INDENT>f = open('<STR_LIT>', '<STR_LIT:r>')<EOL>up = float(f.read())<EOL>f.close()<EOL>return up<EOL><DEDENT>except (IOError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on MINIX.


<EOL>try:<EOL><INDENT>f = open('<STR_LIT>', '<STR_LIT:r>')<EOL>s, ns, ct, cf = f.read().split()<EOL>f.close()<EOL>return float(ct) / float(cf)<EOL><DEDENT>except (IOError, ValueError):<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on Plan 9.


try:<EOL><INDENT>up = swi.swi('<STR_LIT>', '<STR_LIT>')<EOL>if up < <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return up / <NUM_LIT><EOL><DEDENT>except NameError:<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on RISC OS.


global __boottime<EOL>try:<EOL><INDENT>kstat = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except (AttributeError, OSError):<EOL><INDENT>return None<EOL><DEDENT>KSTAT_STRLEN = <NUM_LIT>   <EOL>class anon_union(ctypes.Union):<EOL><INDENT>_fields_ = [('<STR_LIT:c>', ctypes.c_char * <NUM_LIT:16>),<EOL>('<STR_LIT:time>', ctypes.c_int)]<EOL><DEDENT>class kstat_named_t(ctypes.Structure):<EOL><INDENT>_fields_ = [('<STR_LIT:name>', ctypes.c_char * KSTAT_STRLEN),<EOL>('<STR_LIT>', ctypes.c_char),<EOL>('<STR_LIT:value>', anon_union)]<EOL><DEDENT>kstat.kstat_open.restype = ctypes.c_void_p<EOL>kstat.kstat_lookup.restype = ctypes.c_void_p<EOL>kstat.kstat_lookup.argtypes = [ctypes.c_void_p,<EOL>ctypes.c_char_p,<EOL>ctypes.c_int,<EOL>ctypes.c_char_p]<EOL>kstat.kstat_read.restype = ctypes.c_int<EOL>kstat.kstat_read.argtypes = [ctypes.c_void_p,<EOL>ctypes.c_void_p,<EOL>ctypes.c_void_p]<EOL>kstat.kstat_data_lookup.restype = ctypes.POINTER(kstat_named_t)<EOL>kstat.kstat_data_lookup.argtypes = [ctypes.c_void_p,<EOL>ctypes.c_char_p]<EOL>kc = kstat.kstat_open()<EOL>if not kc:<EOL><INDENT>return None<EOL><DEDENT>ksp = kstat.kstat_lookup(kc, '<STR_LIT>', <NUM_LIT:0>, '<STR_LIT>')<EOL>if ksp and kstat.kstat_read(kc, ksp, None) != -<NUM_LIT:1>:<EOL><INDENT>data = kstat.kstat_data_lookup(ksp, '<STR_LIT>')<EOL>if data:<EOL><INDENT>__boottime = data.contents.value.time<EOL><DEDENT><DEDENT>kstat.kstat_close(kc)<EOL>if __boottime is not None:<EOL><INDENT>return time.time() - __boottime<EOL><DEDENT>return None<EOL>

Returns uptime in seconds or None, on Solaris.


global __boottime<EOL>try:<EOL><INDENT>__boottime = os.stat('<STR_LIT>').st_mtime<EOL>return time.time() - __boottime<EOL><DEDENT>except (NameError, OSError):<EOL><INDENT>return None<EOL><DEDENT>

Returns uptime in seconds or None, on Syllable.


if hasattr(ctypes, '<STR_LIT>') and hasattr(ctypes.windll, '<STR_LIT>'):<EOL><INDENT>lib = ctypes.windll.kernel32<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>lib = ctypes.CDLL('<STR_LIT>')<EOL><DEDENT>except (AttributeError, OSError):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if hasattr(lib, '<STR_LIT>'):<EOL><INDENT>lib.GetTickCount64.restype = ctypes.c_uint64<EOL>return lib.GetTickCount64() / <NUM_LIT><EOL><DEDENT>if hasattr(lib, '<STR_LIT>'):<EOL><INDENT>lib.GetTickCount.restype = ctypes.c_uint32<EOL>return lib.GetTickCount() / <NUM_LIT><EOL><DEDENT>return None<EOL>

Returns uptime in seconds or None, on Windows. Warning: may return
incorrect answers after 49.7 days on versions older than Vista.


if __boottime is not None:<EOL><INDENT>return time.time() - __boottime<EOL><DEDENT>return {'<STR_LIT>': _uptime_amiga,<EOL>'<STR_LIT>': _uptime_amiga,<EOL>'<STR_LIT>': _uptime_beos,<EOL>'<STR_LIT>': _uptime_linux,<EOL>'<STR_LIT>': _uptime_osx,<EOL>'<STR_LIT>': _uptime_beos,<EOL>'<STR_LIT>': _uptime_linux,<EOL>'<STR_LIT>': _uptime_linux,<EOL>'<STR_LIT>': _uptime_linux,<EOL>'<STR_LIT>': _uptime_mac,<EOL>'<STR_LIT>': _uptime_minix,<EOL>'<STR_LIT>': _uptime_riscos,<EOL>'<STR_LIT>': _uptime_solaris,<EOL>'<STR_LIT>': _uptime_syllable,<EOL>'<STR_LIT:win32>': _uptime_windows,<EOL>'<STR_LIT>': _uptime_windows}.get(sys.platform, _uptime_bsd)() or_uptime_bsd() or _uptime_plan9() or _uptime_linux() or_uptime_windows() or _uptime_solaris() or _uptime_beos() or_uptime_amiga() or _uptime_riscos() or _uptime_posix() or_uptime_syllable() or _uptime_mac() or _uptime_osx()<EOL>

Returns uptime in seconds if even remotely possible, or None if not.


global __boottime<EOL>if __boottime is None:<EOL><INDENT>up = uptime()<EOL>if up is None:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if __boottime is None:<EOL><INDENT>_boottime_linux()<EOL><DEDENT>if datetime is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return datetime.fromtimestamp(__boottime or time.time() - up)<EOL>

Returns boot time if remotely possible, or None if not.


path = os.path.join(root, path)<EOL>potentialPaths = itertools.chain((path,), __get_numbered_paths(path))<EOL>potentialPaths = six.moves.filterfalse(os.path.exists, potentialPaths)<EOL>return next(potentialPaths)<EOL>

Return a pathname possibly with a number appended to it so that it is
    unique in the directory.


format = '<STR_LIT>' % splitext_files_only(filepath)<EOL>return map(lambda n: format % n, itertools.count(<NUM_LIT:1>))<EOL>

Append numbers in sequential order to the filename or folder name
    Numbers should be appended before the extension on a filename.


return (<EOL>(filepath, '<STR_LIT>') if os.path.isdir(filepath) else os.path.splitext(filepath)<EOL>)<EOL>

Custom version of splitext that doesn't perform splitext on directories


log.debug('<STR_LIT>', mod_time)<EOL>mtime = calendar.timegm(mod_time.utctimetuple())<EOL>mtime += mod_time.microsecond / <NUM_LIT><EOL>atime = os.stat(filename).st_atime<EOL>os.utime(filename, (atime, mtime))<EOL>


ts = os.stat(filename).st_mtime<EOL>return datetime.datetime.utcfromtimestamp(ts)<EOL>

Get the modified time for a file as a datetime instance


parts = list(os.path.splitext(filename))<EOL>parts[<NUM_LIT:1>:<NUM_LIT:1>] = [content]<EOL>return '<STR_LIT>'.join(parts)<EOL>

Given a filename and some content, insert the content just before
the extension.

>>> insert_before_extension('pages.pdf', '-old')
'pages-old.pdf'


specs = (<EOL>os.path.join(dirpath, dirname, spec)<EOL>for dirpath, dirnames, filenames in os.walk(root)<EOL>for dirname in dirnames<EOL>)<EOL>return itertools.chain.from_iterable(<EOL>glob.iglob(spec)<EOL>for spec in specs<EOL>)<EOL>

Like iglob, but recurse directories

>>> any('path.py' in result for result in recursive_glob('.', '*.py'))
True

>>> all(result.startswith('.') for result in recursive_glob('.', '*.py'))
True

>>> len(list(recursive_glob('.', '*.foo')))
0


assert system == '<STR_LIT>', '<STR_LIT>'<EOL>special_characters = r'<STR_LIT>' + '<STR_LIT>'.join(map(chr, range(<NUM_LIT:32>)))<EOL>pattern = '<STR_LIT:|>'.join(map(re.escape, special_characters))<EOL>pattern = re.compile(pattern)<EOL>return pattern.sub('<STR_LIT:_>', name)<EOL>

Encode the name for a suitable name in the given filesystem
>>> encode('Test :1')
'Test _1'


fd, filename = tempfile.mkstemp(*args, **kwargs)<EOL>os.close(fd)<EOL>try:<EOL><INDENT>yield filename<EOL><DEDENT>finally:<EOL><INDENT>os.remove(filename)<EOL><DEDENT>

A wrapper around tempfile.mkstemp to create the file in a context and
delete it after.


return os.path.splitext(filename)[<NUM_LIT:0>] + new_ext<EOL>

>>> replace_extension('.pdf', 'myfile.doc')
'myfile.pdf'


return functools.partial(replace_extension, new_ext)<EOL>

A reusable function to replace a file's extension with another

>>> repl = ExtensionReplacer('.pdf')
>>> repl('myfile.doc')
'myfile.pdf'
>>> repl('myfile.txt')
'myfile.pdf'
>>> repl('myfile')
'myfile.pdf'


@functools.wraps(func)<EOL>def make_if_not_present():<EOL><INDENT>dir = func()<EOL>if not os.path.isdir(dir):<EOL><INDENT>os.makedirs(dir)<EOL><DEDENT>return dir<EOL><DEDENT>return make_if_not_present<EOL>

wrap a function that returns a dir, making sure it exists


def read_chunks(file, chunk_size=<NUM_LIT>, update_func=lambda x: None):

while(True):<EOL><INDENT>res = file.read(chunk_size)<EOL>if not res:<EOL><INDENT>break<EOL><DEDENT>update_func(len(res))<EOL>yield res<EOL><DEDENT>

Read file in chunks of size chunk_size (or smaller).
If update_func is specified, call it on every chunk with the amount
read.


full_path = os.path.abspath(path)<EOL>name = os.path.basename(full_path)<EOL>def no(path):<EOL><INDENT>return False<EOL><DEDENT>platform_hidden = globals().get('<STR_LIT>' + platform.system(), no)<EOL>return name.startswith('<STR_LIT:.>') or platform_hidden(full_path)<EOL>

Check whether a file is presumed hidden, either because
the pathname starts with dot or because the platform
indicates such.


<EOL>items = [(key, value) for key, value in kwargs.items()<EOL>if not key.startswith("<STR_LIT:_>")]<EOL>params, skip_params = {}, False<EOL>for key, value in items:<EOL><INDENT>if hasattr(value, '<STR_LIT>') or isinstance(value, bytes):<EOL><INDENT>params[key] = value<EOL>skip_params = True<EOL><DEDENT>elif isinstance(value, bool):<EOL><INDENT>params[key] = "<STR_LIT:true>" if value else "<STR_LIT:false>"<EOL><DEDENT>elif isinstance(value, iterable):<EOL><INDENT>params[key] = "<STR_LIT:U+002C>".join(map(str, value))<EOL><DEDENT>elif value is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>params[key] = str(value)<EOL><DEDENT><DEDENT>kwargs = {key[<NUM_LIT:1>:]: value for key, value in kwargs.items()<EOL>if key.startswith("<STR_LIT:_>")}<EOL>if method == "<STR_LIT>" and not kwargs.get('<STR_LIT:data>', None) and params:<EOL><INDENT>kwargs['<STR_LIT:data>'] = params  <EOL><DEDENT>elif not kwargs.get('<STR_LIT>', None) and params:<EOL><INDENT>kwargs['<STR_LIT>'] = params<EOL><DEDENT>return kwargs, skip_params<EOL>

Request params can be extracted from the ``**kwargs``

Arguments starting with `_` will be stripped from it, so they
can be used as an argument for the request
(eg. "_headers" → "headers" in the kwargs returned by this
function while "headers" would be inserted into the parameters
of the request)

Parameters
----------
method : str
    method to use to make the request
kwargs : dict
    Keywords arguments given to the request

Returns
-------
dict
    New requests parameters, correctly formatted


def __init__(self, compression=True, user_agent=None, headers=None):

super().__init__()<EOL>if user_agent is None:<EOL><INDENT>self['<STR_LIT>'] = "<STR_LIT>" + __version__<EOL><DEDENT>else:<EOL><INDENT>self['<STR_LIT>'] = user_agent<EOL><DEDENT>if compression:<EOL><INDENT>self['<STR_LIT>'] = "<STR_LIT>"<EOL><DEDENT>if headers is not None:<EOL><INDENT>for key, value in headers.items():<EOL><INDENT>self[key] = value<EOL><DEDENT><DEDENT>


async def prepare_request(self, method, url,<EOL>headers=None,<EOL>skip_params=False,<EOL>proxy=None,<EOL>**kwargs):

if method.lower() == "<STR_LIT>":<EOL><INDENT>key = '<STR_LIT:data>'<EOL><DEDENT>else:<EOL><INDENT>key = '<STR_LIT>'<EOL><DEDENT>if key in kwargs and not skip_params:<EOL><INDENT>request_params = {key: kwargs.pop(key)}<EOL><DEDENT>else:<EOL><INDENT>request_params = {}<EOL><DEDENT>request_params.update(dict(method=method.upper(), url=url))<EOL>coro = self.sign(**request_params, skip_params=skip_params,<EOL>headers=headers)<EOL>request_params['<STR_LIT>'] = await utils.execute(coro)<EOL>request_params['<STR_LIT>'] = proxy<EOL>kwargs.update(request_params)<EOL>return kwargs<EOL>

prepare all the arguments for the request

Parameters
----------
method : str
    HTTP method used by the request
url : str
    The url to request
headers : dict, optional
    Additionnal headers
proxy : str
    proxy of the request
skip_params : bool
    Don't use the parameters to sign the request

Returns
-------
dict
    Parameters of the request correctly formatted


h = self.copy()<EOL>if headers is not None:<EOL><INDENT>keys = set(headers.keys())<EOL>if h.get('<STR_LIT>', False):<EOL><INDENT>keys -= {'<STR_LIT>'}<EOL><DEDENT>for key in keys:<EOL><INDENT>h[key] = headers[key]<EOL><DEDENT><DEDENT>return h<EOL>

Make sure the user doesn't override the Authorization header


@abstractmethod<EOL><INDENT>def sign(self, *args, headers=None, **kwargs):<DEDENT>

sign, that is, generate the `Authorization` headers before making
a request


def __new__(cls, name, bases, attrs, **kwargs):

tasks = {'<STR_LIT>': set()}<EOL>for base in bases:<EOL><INDENT>if hasattr(base, '<STR_LIT>'):<EOL><INDENT>for key, value in base._tasks.items():<EOL><INDENT>tasks[key] |= value<EOL><DEDENT><DEDENT><DEDENT>for attr in attrs.values():<EOL><INDENT>if isinstance(attr, task):<EOL><INDENT>tasks['<STR_LIT>'].add(attr)<EOL><DEDENT><DEDENT>attrs['<STR_LIT>'] = tasks<EOL>attrs['<STR_LIT>'] = EventStreams()<EOL>return super().__new__(cls, name, bases, attrs)<EOL>

put the :class:`~peony.commands.tasks.Task`s in the right place


@staticmethod<EOL><INDENT>def _get_base_url(base_url, api, version):<DEDENT>

format_args = {}<EOL>if "<STR_LIT>" in base_url:<EOL><INDENT>if api == "<STR_LIT>":<EOL><INDENT>base_url = base_url.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>format_args['<STR_LIT>'] = api<EOL><DEDENT><DEDENT>if "<STR_LIT>" in base_url:<EOL><INDENT>if version == "<STR_LIT>":<EOL><INDENT>base_url = base_url.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>format_args['<STR_LIT:version>'] = version<EOL><DEDENT><DEDENT>return base_url.format(api=api, version=version)<EOL>

create the base url for the api

Parameters
----------
base_url : str
    format of the base_url using {api} and {version}
api : str
    name of the api to use
version : str
    version of the api

Returns
-------
str
    the base url of the api you want to use


defaults = None, self.api_version, self._suffix, self.base_url<EOL>keys = ['<STR_LIT>', '<STR_LIT:version>', '<STR_LIT>', '<STR_LIT>']<EOL>if isinstance(values, dict):<EOL><INDENT>values = [values.get(key, defaults[i])<EOL>for i, key in enumerate(keys)]<EOL><DEDENT>elif isinstance(values, set):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif isinstance(values, str):<EOL><INDENT>values = [values, *defaults[<NUM_LIT:1>:]]<EOL><DEDENT>elif isinstance(values, tuple):<EOL><INDENT>if len(values) < len(keys):<EOL><INDENT>padding = (None,) * (len(keys) - len(values))<EOL>values += padding<EOL><DEDENT>values = [default if value is None else value<EOL>for value, default in zip(values, defaults)<EOL>if (value, default) != (None, None)]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" + values.__class__.__name__)<EOL><DEDENT>api, version, suffix, base_url = values<EOL>base_url = self._get_base_url(base_url, api, version)<EOL>if api in self.streaming_apis:<EOL><INDENT>return StreamingAPIPath([base_url], suffix=suffix, client=self)<EOL><DEDENT>else:<EOL><INDENT>return APIPath([base_url], suffix=suffix, client=self)<EOL><DEDENT>

Access the api you want

This permits the use of any API you could know about

For most api you only need to type

>>> self[api]  # api is the api you want to access

You can specify a custom api version using the syntax

>>> self[api, version]  # version is the api version as a str

For more complex requests

>>> self[api, version, suffix, base_url]

Returns
-------
.api.BaseAPIPath
    To access an API endpoint


async def request(self, method, url, future,<EOL>headers=None,<EOL>session=None,<EOL>encoding=None,<EOL>**kwargs):

await self.setup<EOL>req_kwargs = await self.headers.prepare_request(<EOL>method=method,<EOL>url=url,<EOL>headers=headers,<EOL>proxy=self.proxy,<EOL>**kwargs<EOL>)<EOL>if encoding is None:<EOL><INDENT>encoding = self.encoding<EOL><DEDENT>session = session if (session is not None) else self._session<EOL>logger.debug("<STR_LIT>" % req_kwargs)<EOL>async with session.request(**req_kwargs) as response:<EOL><INDENT>if response.status < <NUM_LIT>:<EOL><INDENT>data = await data_processing.read(response, self._loads,<EOL>encoding=encoding)<EOL>future.set_result(data_processing.PeonyResponse(<EOL>data=data,<EOL>headers=response.headers,<EOL>url=response.url,<EOL>request=req_kwargs<EOL>))<EOL><DEDENT>else:  <EOL><INDENT>await exceptions.throw(response, loads=self._loads,<EOL>encoding=encoding, url=url)<EOL><DEDENT><DEDENT>

Make requests to the REST API

Parameters
----------
future : asyncio.Future
    Future used to return the response
method : str
    Method to be used by the request
url : str
    URL of the resource
headers : .oauth.PeonyHeaders
    Custom headers (doesn't overwrite `Authorization` headers)
session : aiohttp.ClientSession, optional
    Client session used to make the request

Returns
-------
data.PeonyResponse
    Response to the request


def stream_request(self, method, url, headers=None, _session=None,<EOL>*args, **kwargs):

return StreamResponse(<EOL>method=method,<EOL>url=url,<EOL>client=self,<EOL>headers=headers,<EOL>session=_session,<EOL>proxy=self.proxy,<EOL>**kwargs<EOL>)<EOL>

Make requests to the Streaming API

Parameters
----------
method : str
    Method to be used by the request
url : str
    URL of the resource
headers : dict
    Custom headers (doesn't overwrite `Authorization` headers)
_session : aiohttp.ClientSession, optional
    The session to use for this specific request, the session
    given as argument of :meth:`__init__` is used by default

Returns
-------
.stream.StreamResponse
    Stream context for the request


cls._streams.append(event_stream)<EOL>return event_stream<EOL>

Decorator to attach an event stream to the class


tasks = self._get_tasks()<EOL>tasks.extend(self._streams.get_tasks(self))<EOL>return tasks<EOL>

Get the tasks attached to the instance

Returns
-------
list
    List of tasks (:class:`asyncio.Task`)


tasks = self.get_tasks()<EOL>self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)<EOL>try:<EOL><INDENT>await self._gathered_tasks<EOL><DEDENT>except CancelledError:<EOL><INDENT>pass<EOL><DEDENT>


self.loop.run_until_complete(self.arun())<EOL>


tasks = self._get_close_tasks()<EOL>if tasks:<EOL><INDENT>await asyncio.wait(tasks)<EOL><DEDENT>self._session = None<EOL>


api = self['<STR_LIT>', general.twitter_api_version,<EOL>"<STR_LIT>", general.twitter_base_api_url]<EOL>return await api.help.configuration.get()<EOL>

create a ``twitter_configuration`` attribute with the response
of the endpoint
https://api.twitter.com/1.1/help/configuration.json


api = self['<STR_LIT>', general.twitter_api_version,<EOL>"<STR_LIT>", general.twitter_base_api_url]<EOL>return await api.account.verify_credentials.get()<EOL>

create a ``user`` attribute with the response of the endpoint
https://api.twitter.com/1.1/account/verify_credentials.json


if isinstance(media, bytes):<EOL><INDENT>media = io.BytesIO(media)<EOL><DEDENT>chunk = media.read(chunk_size)<EOL>is_coro = asyncio.iscoroutine(chunk)<EOL>if is_coro:<EOL><INDENT>chunk = await chunk<EOL><DEDENT>if media_type is None:<EOL><INDENT>media_metadata = await utils.get_media_metadata(chunk, path)<EOL>media_type, media_category = media_metadata<EOL><DEDENT>elif media_category is None:<EOL><INDENT>media_category = utils.get_category(media_type)<EOL><DEDENT>response = await self.upload.media.upload.post(<EOL>command="<STR_LIT>",<EOL>total_bytes=media_size,<EOL>media_type=media_type,<EOL>media_category=media_category,<EOL>**params<EOL>)<EOL>media_id = response['<STR_LIT>']<EOL>i = <NUM_LIT:0><EOL>while chunk:<EOL><INDENT>if is_coro:<EOL><INDENT>req = self.upload.media.upload.post(command="<STR_LIT>",<EOL>media_id=media_id,<EOL>media=chunk,<EOL>segment_index=i)<EOL>chunk, _ = await asyncio.gather(media.read(chunk_size), req)<EOL><DEDENT>else:<EOL><INDENT>await self.upload.media.upload.post(command="<STR_LIT>",<EOL>media_id=media_id,<EOL>media=chunk,<EOL>segment_index=i)<EOL>chunk = media.read(chunk_size)<EOL><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>status = await self.upload.media.upload.post(command="<STR_LIT>",<EOL>media_id=media_id)<EOL>if '<STR_LIT>' in status:<EOL><INDENT>while status['<STR_LIT>'].get('<STR_LIT:state>') != "<STR_LIT>":<EOL><INDENT>processing_info = status['<STR_LIT>']<EOL>if processing_info.get('<STR_LIT:state>') == "<STR_LIT>":<EOL><INDENT>error = processing_info.get('<STR_LIT:error>', {})<EOL>message = error.get('<STR_LIT:message>', str(status))<EOL>raise exceptions.MediaProcessingError(data=status,<EOL>message=message,<EOL>**params)<EOL><DEDENT>delay = processing_info['<STR_LIT>']<EOL>await asyncio.sleep(delay)<EOL>status = await self.upload.media.upload.get(<EOL>command="<STR_LIT>",<EOL>media_id=media_id,<EOL>**params<EOL>)<EOL><DEDENT><DEDENT>return response<EOL>

upload media in chunks

Parameters
----------
media : file object
    a file object of the media
media_size : int
    size of the media
path : str, optional
    filename of the media
media_type : str, optional
    mime type of the media
media_category : str, optional
    twitter media category, must be used with ``media_type``
chunk_size : int, optional
    size of a chunk in bytes
params : dict, optional
    additional parameters of the request

Returns
-------
.data_processing.PeonyResponse
    Response of the request


if isinstance(file_, str):<EOL><INDENT>url = urlparse(file_)<EOL>if url.scheme.startswith('<STR_LIT:http>'):<EOL><INDENT>media = await self._session.get(file_)<EOL><DEDENT>else:<EOL><INDENT>path = urlparse(file_).path.strip("<STR_LIT>")<EOL>media = await utils.execute(open(path, '<STR_LIT:rb>'))<EOL><DEDENT><DEDENT>elif hasattr(file_, '<STR_LIT>') or isinstance(file_, bytes):<EOL><INDENT>media = file_<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>media_size = await utils.get_size(media)<EOL>if chunked is not None:<EOL><INDENT>size_test = False<EOL><DEDENT>else:<EOL><INDENT>size_test = await self._size_test(media_size, size_limit)<EOL><DEDENT>if isinstance(media, aiohttp.ClientResponse):<EOL><INDENT>media = media.content<EOL><DEDENT>if chunked or (size_test and chunked is None):<EOL><INDENT>args = media, media_size, file_, media_type, media_category<EOL>response = await self._chunked_upload(*args, **params)<EOL><DEDENT>else:<EOL><INDENT>response = await self.upload.media.upload.post(media=media,<EOL>**params)<EOL><DEDENT>if not hasattr(file_, '<STR_LIT>') and not getattr(media, '<STR_LIT>', True):<EOL><INDENT>media.close()<EOL><DEDENT>return response<EOL>

upload a media on twitter

Parameters
----------
file_ : str or pathlib.Path or file
    Path to the file or file object
media_type : str, optional
    mime type of the media
media_category : str, optional
    Twitter's media category of the media, must be used with
    ``media_type``
chunked : bool, optional
    If True, force the use of the chunked upload for the media
size_limit : int, optional
    If set, the media will be sent using a multipart upload if
    its size is over ``size_limit`` bytes
params : dict
    parameters used when making the request

Returns
-------
.data_processing.PeonyResponse
    Response of the request


async def get_oauth_token(consumer_key, consumer_secret, callback_uri="<STR_LIT>"):

client = BasePeonyClient(consumer_key=consumer_key,<EOL>consumer_secret=consumer_secret,<EOL>api_version="<STR_LIT>",<EOL>suffix="<STR_LIT>")<EOL>response = await client.api.oauth.request_token.post(<EOL>_suffix="<STR_LIT>",<EOL>oauth_callback=callback_uri<EOL>)<EOL>return parse_token(response)<EOL>

Get a temporary oauth token

Parameters
----------
consumer_key : str
    Your consumer key
consumer_secret : str
    Your consumer secret
callback_uri : str, optional
    Callback uri, defaults to 'oob'

Returns
-------
dict
    Temporary tokens


url = "<STR_LIT>" + oauth_token<EOL>try:<EOL><INDENT>browser = webbrowser.open(url)<EOL>await asyncio.sleep(<NUM_LIT:2>)<EOL>if not browser:<EOL><INDENT>raise RuntimeError<EOL><DEDENT><DEDENT>except RuntimeError:<EOL><INDENT>print("<STR_LIT>" + url)<EOL><DEDENT>verifier = input("<STR_LIT>")<EOL>return verifier<EOL>

Open authorize page in a browser,
print the url if it didn't work

Arguments
---------
oauth_token : str
    The oauth token received in :func:`get_oauth_token`

Returns
-------
str
    The PIN entered by the user


async def get_access_token(consumer_key, consumer_secret,<EOL>oauth_token, oauth_token_secret,<EOL>oauth_verifier, **kwargs):

get the access token of the user

Parameters
----------
consumer_key : str
    Your consumer key
consumer_secret : str
    Your consumer secret
oauth_token : str
    OAuth token from :func:`get_oauth_token`
oauth_token_secret : str
    OAuth token secret from :func:`get_oauth_token`
oauth_verifier : str
    OAuth verifier from :func:`get_oauth_verifier`

Returns
-------
dict
    Access tokens


async def async_oauth_dance(consumer_key, consumer_secret, callback_uri="<STR_LIT>"):

token = await get_oauth_token(consumer_key, consumer_secret, callback_uri)<EOL>oauth_verifier = await get_oauth_verifier(token['<STR_LIT>'])<EOL>token = await get_access_token(<EOL>consumer_key,<EOL>consumer_secret,<EOL>oauth_verifier=oauth_verifier,<EOL>**token<EOL>)<EOL>token = dict(<EOL>consumer_key=consumer_key,<EOL>consumer_secret=consumer_secret,<EOL>access_token=token['<STR_LIT>'],<EOL>access_token_secret=token['<STR_LIT>']<EOL>)<EOL>return token<EOL>

OAuth dance to get the user's access token

Parameters
----------
consumer_key : str
    Your consumer key
consumer_secret : str
    Your consumer secret
callback_uri : str
    Callback uri, defaults to 'oob'

Returns
-------
dict
    Access tokens


items = response.split("<STR_LIT:&>")<EOL>items = [item.split("<STR_LIT:=>") for item in items]<EOL>return {key: value for key, value in items}<EOL>

parse the responses containing the tokens

Parameters
----------
response : str
    The response containing the tokens

Returns
-------
dict
    The parsed tokens


def oauth_dance(consumer_key, consumer_secret,<EOL>oauth_callback="<STR_LIT>", loop=None):

loop = asyncio.get_event_loop() if loop is None else loop<EOL>coro = async_oauth_dance(consumer_key, consumer_secret, oauth_callback)<EOL>return loop.run_until_complete(coro)<EOL>

OAuth dance to get the user's access token

It calls async_oauth_dance and create event loop of not given

Parameters
----------
consumer_key : str
    Your consumer key
consumer_secret : str
    Your consumer secret
oauth_callback : str
    Callback uri, defaults to 'oob'
loop : event loop
    asyncio event loop

Returns
-------
dict
    Access tokens


def oauth2_dance(consumer_key, consumer_secret, loop=None):

loop = asyncio.get_event_loop() if loop is None else loop<EOL>client = BasePeonyClient(consumer_key=consumer_key,<EOL>consumer_secret=consumer_secret,<EOL>auth=oauth.OAuth2Headers)<EOL>loop.run_until_complete(client.headers.sign())<EOL>return client.headers.token<EOL>

oauth2 dance

Parameters
----------
consumer_key : str
    Your consumer key
consumer_secret : str
    Your consumer secret
loop : event loop, optional
    event loop to use

Returns
-------
str
    Bearer token


def loads(json_data, encoding="<STR_LIT:utf-8>", **kwargs):

if isinstance(json_data, bytes):<EOL><INDENT>json_data = json_data.decode(encoding)<EOL><DEDENT>return json.loads(json_data, object_hook=JSONData, **kwargs)<EOL>

Custom loads function with an object_hook and automatic decoding

Parameters
----------
json_data : str
    The JSON data to decode
*args
    Positional arguments, passed to :func:`json.loads`
encoding : :obj:`str`, optional
    The encoding of the bytestring
**kwargs
    Keyword arguments passed to :func:`json.loads`

Returns
-------
:obj:`dict` or :obj:`list`
    Decoded json data


async def read(response, loads=loads, encoding=None):

ctype = response.headers.get('<STR_LIT:Content-Type>', "<STR_LIT>").lower()<EOL>try:<EOL><INDENT>if "<STR_LIT:application/json>" in ctype:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return await response.json(encoding=encoding, loads=loads)<EOL><DEDENT>if "<STR_LIT:text>" in ctype:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return await response.text(encoding=encoding)<EOL><DEDENT><DEDENT>except (UnicodeDecodeError, json.JSONDecodeError) as exc:<EOL><INDENT>data = await response.read()<EOL>raise exceptions.PeonyDecodeError(response=response,<EOL>data=data,<EOL>exception=exc)<EOL><DEDENT>return await response.read()<EOL>

read the data of the response

Parameters
----------
response : aiohttp.ClientResponse
    response
loads : callable
    json loads function
encoding : :obj:`str`, optional
    character encoding of the response, if set to None
    aiohttp should guess the right encoding

Returns
-------
:obj:`bytes`, :obj:`str`, :obj:`dict` or :obj:`list`
    the data returned depends on the response


return getattr(self.data, key)<EOL>


return self.data[key]<EOL>


return iter(self.data)<EOL>


return str(self.data)<EOL>


return repr(self.data)<EOL>


return len(self.data)<EOL>


def __init__(self, request, parameter, force=False):

self.param = parameter<EOL>self.force = force<EOL>self._response_key = None<EOL>self._response_list = False<EOL>super().__init__(request)<EOL>

Keep all the arguments as class attributes


request = self.request(**self.kwargs)<EOL>response = await request<EOL>data = self.get_data(response)<EOL>if data:<EOL><INDENT>await self.call_on_response(data)<EOL><DEDENT>elif not self.force:<EOL><INDENT>raise StopAsyncIteration<EOL><DEDENT>return response<EOL>

return each response until getting an empty data


if self._response_list:<EOL><INDENT>return response<EOL><DEDENT>elif self._response_key is None:<EOL><INDENT>if hasattr(response, "<STR_LIT>"):<EOL><INDENT>for key, data in response.items():<EOL><INDENT>if (hasattr(data, "<STR_LIT>")<EOL>and not hasattr(data, "<STR_LIT>")<EOL>and len(data) > <NUM_LIT:0><EOL>and '<STR_LIT:id>' in data[<NUM_LIT:0>]):<EOL><INDENT>self._response_key = key<EOL>return data<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self._response_list = True<EOL>return response<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return response[self._response_key]<EOL><DEDENT>raise NoDataFound(response=response, url=self.request.get_url())<EOL>


@abstractmethod<EOL><INDENT>async def call_on_response(self, response):<DEDENT>

function that prepares for the next request


self.kwargs[self.param] = data[-<NUM_LIT:1>]['<STR_LIT:id>'] - <NUM_LIT:1><EOL>

The parameter is set to the id of the tweet at index i - 1


since_id = self.kwargs.get(self.param, <NUM_LIT:0>) + <NUM_LIT:1><EOL>if self.fill_gaps:<EOL><INDENT>if data[-<NUM_LIT:1>]['<STR_LIT:id>'] != since_id:<EOL><INDENT>max_id = data[-<NUM_LIT:1>]['<STR_LIT:id>'] - <NUM_LIT:1><EOL>responses = with_max_id(self.request(**self.kwargs,<EOL>max_id=max_id))<EOL>async for tweets in responses:<EOL><INDENT>data.extend(tweets)<EOL><DEDENT><DEDENT>if data[-<NUM_LIT:1>]['<STR_LIT:id>'] == self.last_id:<EOL><INDENT>data = data[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if not data and not self.force:<EOL><INDENT>raise StopAsyncIteration<EOL><DEDENT>await self.set_param(data)<EOL>

Try to fill the gaps and strip last tweet from the response
if its id is that of the first tweet of the last response

Parameters
----------
data : list
    The response data


if self.kwargs.get('<STR_LIT>', -<NUM_LIT:1>) != <NUM_LIT:0>:<EOL><INDENT>response = await self.request(**self.kwargs)<EOL>self.kwargs['<STR_LIT>'] = response['<STR_LIT>']<EOL>return response<EOL><DEDENT>else:<EOL><INDENT>raise StopAsyncIteration<EOL><DEDENT>

return each response until getting 0 as next cursor


@wraps(func)<EOL>def decorated(self, k, *args):<EOL><INDENT>if not isinstance(k, str):<EOL><INDENT>msg = "<STR_LIT>" % self.__class__.__name__<EOL>raise ValueError(msg)<EOL><DEDENT>if not k.startswith(self.prefix):<EOL><INDENT>k = self.prefix + k<EOL><DEDENT>return func(self, k, *args)<EOL><DEDENT>return decorated<EOL>

Raise error for keys that are not strings
and add the prefix if it is missing


return super().__getitem__(k)<EOL>


if self.strict:<EOL><INDENT>match = self.prog.match(text)<EOL>if match:<EOL><INDENT>cmd = match.group()<EOL>if cmd in self:<EOL><INDENT>return cmd<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>words = self.prog.findall(text)<EOL>for word in words:<EOL><INDENT>if word in self:<EOL><INDENT>return word<EOL><DEDENT><DEDENT><DEDENT>

Analyze the text to get the right function

Parameters
----------
text : str
    The text that could call a function


cmd = self._get(data.text)<EOL>try:<EOL><INDENT>if cmd is not None:<EOL><INDENT>command = self[cmd](*args, data=data)<EOL>return await peony.utils.execute(command)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>peony.utils.log_error(fmt.format(cmd=cmd))<EOL><DEDENT>


stripped_chars = "<STR_LIT>"<EOL>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>docstring = func.__doc__.lstrip("<STR_LIT>")<EOL>if "<STR_LIT:\n>" in docstring:<EOL><INDENT>i = docstring.index("<STR_LIT:\n>")<EOL>return docstring[:i].rstrip(stripped_chars)<EOL><DEDENT>elif docstring:<EOL><INDENT>return docstring.rstrip(stripped_chars)<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Find the message shown when someone calls the help command

Parameters
----------
func : function
    the function

Returns
-------
str
    The help message for this command


def permission_check(data, command_permissions,<EOL>command=None, permissions=None):

if permissions:<EOL><INDENT>pass<EOL><DEDENT>elif command:<EOL><INDENT>if hasattr(command, '<STR_LIT>'):<EOL><INDENT>permissions = command.permissions<EOL><DEDENT>else:<EOL><INDENT>return True  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise RuntimeError(msg.format(name="<STR_LIT>"))<EOL><DEDENT>return any(data['<STR_LIT>']['<STR_LIT:id>'] in command_permissions[permission]<EOL>for permission in permissions<EOL>if permission in command_permissions)<EOL>

Check the permissions of the user requesting a command

Parameters
----------
data : dict
    message data
command_permissions : dict
    permissions of the command, contains all the roles as key and users
    with these permissions as values
command : function
    the command that is run
permissions : tuple or list
    a list of permissions for the command

Returns
-------
bool
    True if the user has the right permissions, False otherwise


<EOL>n '<STR_LIT>' in data or '<STR_LIT>' in data<EOL>

Event triggered on connection to an userstream

For more information:
https://dev.twitter.com/streaming/overview/messages-types#friends-lists-friends


Event triggered when a direct message is received

For more information:
https://dev.twitter.com/streaming/overview/messages-types#direct-messages


@events.alias(on, '<STR_LIT>', '<STR_LIT>')<EOL>@events.priority(-<NUM_LIT:1>)<EOL>def retweeted_status(data):

return tweet(data) and '<STR_LIT>' in data<EOL>

Event triggered when the data corresponds to a retweet

For more information:
https://dev.twitter.com/overview/api/tweets


return '<STR_LIT:text>' in data<EOL>

Event triggered when the data corresponds to a tweet
If there is no handler for the :func:`retweeted_status` event
then the data could correspond to a retweet

For more information:
https://dev.twitter.com/overview/api/tweets


Event triggered when an user deletes a tweet

For more information:
https://dev.twitter.com/streaming/overview/messages-types#status-deletion-notices-delete


Event triggered when an user deletes their location on a range of
    tweets

For more information:
https://dev.twitter.com/streaming/overview/messages-types#location-deletion-notices-scrub-geo


Event triggered when the data corresponds to a stream limit notice

For more information:
https://dev.twitter.com/streaming/overview/messages-types#limit-notices-limit


Event triggered upon receiving a status withheld notice

For more information:
https://dev.twitter.com/streaming/overview/messages-types#withheld-content-notices-status-withheld-user-withheld


Event triggered upon receiving a status withheld notice

For more information:
https://dev.twitter.com/streaming/overview/messages-types#user-withheld


Event triggered upon receiving a disconnect notice
Note that the disconnect message may not be received when experiencing
network issues.

For more information:
https://dev.twitter.com/streaming/overview/messages-types#disconnect-messages-disconnect


Event triggered when receiving a warning

For more information:

* https://dev.twitter.com/streaming/overview/messages-types#stall-warnings-warning
* https://dev.twitter.com/streaming/overview/messages-types#too-many-follows-warning


<EOL>n (warning(data)<EOL>and data.get('<STR_LIT>').get('<STR_LIT:code>') == "<STR_LIT>")<EOL>

Event triggered when receiving a stall warning

For more information:
https://dev.twitter.com/streaming/overview/messages-types#stall-warnings-warning


Event triggered when receiving a "too many follows" warning

For more information:
https://dev.twitter.com/streaming/overview/messages-types#too-many-follows-warning


Event triggered when the user is deauthorized

For more information:
https://dev.twitter.com/streaming/overview/messages-types#events-event


For more information:
https://dev.twitter.com/streaming/overview/messages-types#events-event


Event triggered when an user updates their profile

For more information:
https://dev.twitter.com/streaming/overview/messages-types#user_update


Event triggered upon receiving a control message

For more information:
https://dev.twitter.com/streaming/overview/messages-types#control-messages-control


event_triggered on the first connection to a stream


return connected(data) or stream_restart(data)<EOL>

event triggered on connection or reconnection to a stream


@events.alias(on, '<STR_LIT>', '<STR_LIT>')<EOL>def stream_restart():


@events.alias(on, '<STR_LIT>', '<STR_LIT>')<EOL>def reconnecting_in():

Event triggered when a stream restart is scheduled

the data contains the number of seconds to wait is seconds as its
``'reconnecting_in'`` item.


return True<EOL>

Event triggered when the data didn't trigger any handled event


def with_prefix(self, prefix, strict=False):

def decorated(func):<EOL><INDENT>return EventHandler(func=func, event=self.event,<EOL>prefix=prefix, strict=strict)<EOL><DEDENT>return decorated<EOL>

decorator to handle commands with prefixes

Parameters
----------
prefix : str
    the prefix of the command
strict : bool, optional
    If set to True the command must be at the beginning
    of the message. Defaults to False.

Returns
-------
function
    a decorator that returns an :class:`EventHandler` instance


def enveloped_event(data):<EOL><INDENT>return '<STR_LIT>' in data and self._func(data.get('<STR_LIT:message>'))<EOL><DEDENT>return self.__class__(enveloped_event, self.__name__)<EOL>

returns an :class:`Event` that can be used for site streams


logger.debug("<STR_LIT>")<EOL>await self.client.setup<EOL>if self.session is None:<EOL><INDENT>self.session = self.client._session<EOL><DEDENT>kwargs = await self.client.headers.prepare_request(**self.kwargs)<EOL>request = self.client.error_handler(self.session.request)<EOL>return await request(timeout=<NUM_LIT:0>, **kwargs)<EOL>

Connect to the stream

Returns
-------
asyncio.coroutine
    The streaming response


with async_timeout.timeout(self.timeout):<EOL><INDENT>self.response = await self._connect()<EOL><DEDENT>if self.response.status in range(<NUM_LIT:200>, <NUM_LIT>):<EOL><INDENT>self._error_timeout = <NUM_LIT:0><EOL>self.state = NORMAL<EOL><DEDENT>elif self.response.status == <NUM_LIT>:<EOL><INDENT>self.state = DISCONNECTION<EOL><DEDENT>elif self.response.status in range(<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>self.state = RECONNECTION<EOL><DEDENT>elif self.response.status in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>self.state = ENHANCE_YOUR_CALM<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise await exceptions.throw(self.response,<EOL>loads=self.client._loads,<EOL>url=self.kwargs['<STR_LIT:url>'])<EOL><DEDENT>logger.debug("<STR_LIT>" % self.state)<EOL>

Create the connection

Returns
-------
self

Raises
------
exception.PeonyException
    On a response status in 4xx that are not status 420 or 429
    Also on statuses in 1xx or 3xx since this should not be the status
    received here


if self.response is None:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>await self.connect()<EOL>return {'<STR_LIT>': True}<EOL><DEDENT>line = b'<STR_LIT>'<EOL>try:<EOL><INDENT>if self.state != NORMAL:<EOL><INDENT>if self._reconnecting:<EOL><INDENT>return await self.restart_stream()<EOL><DEDENT>else:<EOL><INDENT>return await self.init_restart()<EOL><DEDENT><DEDENT>while not line:<EOL><INDENT>if self.response.content.at_eof():<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.state = EOF<EOL>return await self.init_restart()<EOL><DEDENT>with async_timeout.timeout(<NUM_LIT>):<EOL><INDENT>line = await self.response.content.readline()<EOL>line = line.strip(b'<STR_LIT:\r\n>')<EOL>logger.debug("<STR_LIT>" % line)<EOL><DEDENT><DEDENT>if line in rate_limit_notices:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise StreamLimit(line)<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>return self.loads(line)<EOL><DEDENT>except HandledErrors as e:<EOL><INDENT>logger.debug("<STR_LIT>" % (e.__class__.__name__, e))<EOL>self.state = ERROR<EOL>return await self.init_restart()<EOL><DEDENT>except ClientConnectionError:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.state = DISCONNECTION<EOL>return await self.init_restart()<EOL><DEDENT>except CancelledError:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>raise StopAsyncIteration<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.state = ERROR<EOL>return await self.init_restart(error=e)<EOL><DEDENT>

Decode each line using json

Returns
-------
dict
    Decoded JSON data


async def init_restart(self, error=None):

if error:<EOL><INDENT>utils.log_error(logger=logger)<EOL><DEDENT>if self.state == DISCONNECTION:<EOL><INDENT>if self._error_timeout < MAX_DISCONNECTION_TIMEOUT:<EOL><INDENT>self._error_timeout += DISCONNECTION_TIMEOUT<EOL><DEDENT>logger.info("<STR_LIT>"<EOL>% self._error_timeout)<EOL><DEDENT>elif self.state == RECONNECTION:<EOL><INDENT>if self._error_timeout < RECONNECTION_TIMEOUT:<EOL><INDENT>self._error_timeout = RECONNECTION_TIMEOUT<EOL><DEDENT>elif self._error_timeout < MAX_RECONNECTION_TIMEOUT:<EOL><INDENT>self._error_timeout *= <NUM_LIT:2><EOL><DEDENT>logger.info("<STR_LIT>"<EOL>% self._error_timeout)<EOL><DEDENT>elif self.state == ENHANCE_YOUR_CALM:<EOL><INDENT>if self._error_timeout < ENHANCE_YOUR_CALM_TIMEOUT:<EOL><INDENT>self._error_timeout = ENHANCE_YOUR_CALM_TIMEOUT<EOL><DEDENT>else:<EOL><INDENT>self._error_timeout *= <NUM_LIT:2><EOL><DEDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% self._error_timeout)<EOL><DEDENT>elif self.state == EOF:<EOL><INDENT>pass  <EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>" % self.state)<EOL><DEDENT>self._reconnecting = True<EOL>return {'<STR_LIT>': self._error_timeout, '<STR_LIT:error>': error}<EOL>

Restart the stream on error

Parameters
----------
error : bool, optional
    Whether to print the error or not


await self.response.release()<EOL>await asyncio.sleep(self._error_timeout)<EOL>await self.connect()<EOL>logger.info("<STR_LIT>")<EOL>self._reconnecting = False<EOL>return {'<STR_LIT>': True}<EOL>


return self<EOL>

Prepare the stream

Returns
-------
StreamResponse
    The stream iterator


await self.client.setup<EOL>return self<EOL>


if getattr(self, '<STR_LIT>', None) is not None:<EOL><INDENT>if not self.response.closed:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.response.close()<EOL><DEDENT><DEDENT>


code = getattr(func, '<STR_LIT>', None)<EOL>if code is None:<EOL><INDENT>code = func.__call__.__code__<EOL><DEDENT>return code.co_varnames[skip:code.co_argcount]<EOL>

Hackish way to get the arguments of a function

Parameters
----------
func : callable
    Function to get the arguments from
skip : int, optional
    Arguments to skip, defaults to 0 set it to 1 to skip the
    ``self`` argument of a method.

Returns
-------
tuple
    Function's arguments


def log_error(msg=None, exc_info=None, logger=None, **kwargs):

if logger is None:<EOL><INDENT>logger = _logger<EOL><DEDENT>if not exc_info:<EOL><INDENT>exc_info = sys.exc_info()<EOL><DEDENT>if msg is None:<EOL><INDENT>msg = "<STR_LIT>"<EOL><DEDENT>exc_class, exc_msg, _ = exc_info<EOL>if all(info is not None for info in exc_info):<EOL><INDENT>logger.error(msg, exc_info=exc_info)<EOL><DEDENT>

log an exception and its traceback on the logger defined

Parameters
----------
msg : str, optional
    A message to add to the error
exc_info : tuple
    Information about the current exception
logger : logging.Logger
    logger to use


async def get_media_metadata(data, path=None):

if isinstance(data, bytes):<EOL><INDENT>media_type = await get_type(data, path)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>media_category = get_category(media_type)<EOL>_logger.info("<STR_LIT>" % (media_type,<EOL>media_category))<EOL>return media_type, media_category<EOL>

Get all the file's metadata and read any kind of file object

Parameters
----------
data : bytes
    first bytes of the file (the mimetype shoudl be guessed from the
    file headers
path : str, optional
    path to the file

Returns
-------
str
    The mimetype of the media
str
    The category of the media on Twitter


if hasattr(media, '<STR_LIT>'):<EOL><INDENT>await execute(media.seek(<NUM_LIT:0>, os.SEEK_END))<EOL>size = await execute(media.tell())<EOL>await execute(media.seek(<NUM_LIT:0>))<EOL><DEDENT>elif hasattr(media, '<STR_LIT>'):<EOL><INDENT>size = int(media.headers['<STR_LIT>'])<EOL><DEDENT>elif isinstance(media, bytes):<EOL><INDENT>size = len(media)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>",<EOL>type(media).__name__)<EOL><DEDENT>_logger.info("<STR_LIT>" % size)<EOL>return size<EOL>

Get the size of a file

Parameters
----------
media : file object
    The file object of the media

Returns
-------
int
    The size of the file


if magic:<EOL><INDENT>if not media:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>_logger.debug("<STR_LIT>")<EOL>media_type = mime.from_buffer(media[:<NUM_LIT>])<EOL><DEDENT>else:<EOL><INDENT>media_type = None<EOL>if path:<EOL><INDENT>_logger.debug("<STR_LIT>")<EOL>media_type = mime.guess_type(path)[<NUM_LIT:0>]<EOL><DEDENT>if media_type is None:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise RuntimeError(msg)<EOL><DEDENT><DEDENT>return media_type<EOL>

Parameters
----------
media : file object
    A file object of the image
path : str, optional
    The path to the file

Returns
-------
str
    The mimetype of the media
str
    The category of the media on Twitter


if asyncio.iscoroutine(coro):<EOL><INDENT>return await coro<EOL><DEDENT>else:<EOL><INDENT>return coro<EOL><DEDENT>

run a function or coroutine

Parameters
----------
coro : asyncio.coroutine or function


logging.basicConfig(level=logging.WARNING)<EOL>peony.logger.setLevel(logging.DEBUG)<EOL>

activates error messages, useful during development


def __new__(cls, name, bases, attrs, **kwargs):

handlers = {}<EOL>for base in bases:<EOL><INDENT>if hasattr(base, '<STR_LIT>'):<EOL><INDENT>for key, value in base._handlers.items():<EOL><INDENT>handlers[key] = value<EOL><DEDENT><DEDENT><DEDENT>for attr in attrs.values():<EOL><INDENT>if isinstance(attr, Handle):<EOL><INDENT>for exception in attr.exceptions:<EOL><INDENT>handlers[exception] = attr.handler<EOL><DEDENT><DEDENT><DEDENT>attrs['<STR_LIT>'] = handlers<EOL>return super().__new__(cls, name, bases, attrs)<EOL>

put the :class:`~peony.utils.Handle`s in the right place


return "<STR_LIT:/>".join(self._path) + (suffix or self._suffix)<EOL>

Build the url using the _path attribute

Parameters
----------
suffix : str
    String to be appended to the url

Returns
-------
str
    Path to the endpoint


if isinstance(key, str):<EOL><INDENT>if key.lower() in general.request_methods:<EOL><INDENT>return self._request(key)<EOL><DEDENT>else:<EOL><INDENT>new_path = self._path + [key]<EOL><DEDENT><DEDENT>elif isinstance(key, (tuple, list)):<EOL><INDENT>key = [str(i) for i in key]<EOL>new_path = self._path + key<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" % (key, type(key)))<EOL><DEDENT>return self.__class__(path=new_path,<EOL>suffix=self._suffix,<EOL>client=self.client)<EOL>

Where the magic happens

If the key is a request method (eg. get) call the _request
attribute with the method as argument

otherwise append the key to the _path attribute

>>> api = APIPath()  # you would have to add more arguments
>>> api['client']    # appends 'client' to _path

Parameters
----------
key : :obj:`str`, :obj:`tuple` or :obj:`list`
    Key used to access an API endpoint and appended to the
    path attribute

Returns
-------
BaseAPIPath
    New APIPath instance with a new ``path`` value


return self[k]<EOL>

Call __getitem__ when trying to get an attribute from the
    instance

If your path contains an actual attribute of the instance
you should call __getitem__ instead


Make a request for the endpoint

Parameters
----------
method : str
    method to use to make the request


if isinstance(data, dict):<EOL><INDENT>if '<STR_LIT>' in data:<EOL><INDENT>error = data['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>error = data.get('<STR_LIT:error>', None)<EOL><DEDENT>if isinstance(error, dict):<EOL><INDENT>if error.get('<STR_LIT:code>') in errors:<EOL><INDENT>return error<EOL><DEDENT><DEDENT><DEDENT>

return the error if there is a corresponding exception


async def throw(response, loads=None, encoding=None, **kwargs):

if loads is None:<EOL><INDENT>loads = data_processing.loads<EOL><DEDENT>data = await data_processing.read(response, loads=loads,<EOL>encoding=encoding)<EOL>error = get_error(data)<EOL>if error is not None:<EOL><INDENT>exception = errors[error['<STR_LIT:code>']]<EOL>raise exception(response=response, error=error, data=data, **kwargs)<EOL><DEDENT>if response.status in statuses:<EOL><INDENT>exception = statuses[response.status]<EOL>raise exception(response=response, data=data, **kwargs)<EOL><DEDENT>raise PeonyException(response=response, data=data, **kwargs)<EOL>

Get the response data if possible and raise an exception


def __init__(self, response=None, error=None, data=None, url=None,<EOL>message=None):

self.response = response<EOL>self.data = data<EOL>self.error = error<EOL>self.url = url<EOL>if not message:<EOL><INDENT>message = self.get_message()<EOL><DEDENT>if url:<EOL><INDENT>message += "<STR_LIT>" + url<EOL><DEDENT>super().__init__(message)<EOL>

Add the response and data attributes

Extract message from the error if not explicitly given


def decorator(exception):<EOL><INDENT>self[code] = exception<EOL>return exception<EOL><DEDENT>return decorator<EOL>

Decorator to associate a code to an exception


return int(self.response.headers.get('<STR_LIT>', <NUM_LIT:0>))<EOL>

Time when the limit will be reset

Returns
-------
int
    Time when the limit will be reset


return max(self.reset - time(), <NUM_LIT:0>)<EOL>

Time in seconds until the limit will be reset

Returns
-------
int
    Time in seconds until the limit will be reset


media = None<EOL>min_size = <NUM_LIT:0><EOL>for kwargs in formats:<EOL><INDENT>f = io.BytesIO()<EOL>if img.mode == "<STR_LIT>" and kwargs['<STR_LIT>'] != "<STR_LIT>":<EOL><INDENT>if min_size < <NUM_LIT:5> * <NUM_LIT>**<NUM_LIT:2>:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>img.convert('<STR_LIT>')<EOL><DEDENT><DEDENT>img.save(f, **kwargs)<EOL>size = f.tell()<EOL>if media is None or size < min_size:<EOL><INDENT>if media is not None:<EOL><INDENT>media.close()<EOL><DEDENT>media = f<EOL>min_size = size<EOL><DEDENT>else:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT>return media<EOL>

Convert the image to all the formats specified
Parameters
----------
img : PIL.Image.Image
    The image to convert
formats : list
    List of all the formats to use
Returns
-------
io.BytesIO
    A file object containing the converted image


def optimize_media(file_, max_size, formats):

if not PIL:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise RuntimeError(msg)<EOL><DEDENT>img = PIL.Image.open(file_)<EOL>ratio = max(hw / max_hw for hw, max_hw in zip(img.size, max_size))<EOL>if ratio > <NUM_LIT:1>:<EOL><INDENT>size = tuple(int(hw // ratio) for hw in img.size)<EOL>img = img.resize(size, PIL.Image.ANTIALIAS)<EOL><DEDENT>media = convert(img, formats)<EOL>if not hasattr(file_, '<STR_LIT>'):<EOL><INDENT>img.close()<EOL><DEDENT>return media<EOL>

Optimize an image
Resize the picture to the ``max_size``, defaulting to the large
photo size of Twitter in :meth:`PeonyClient.upload_media` when
used with the ``optimize_media`` argument.
Parameters
----------
file_ : file object
    the file object of an image
max_size : :obj:`tuple` or :obj:`list` of :obj:`int`
    a tuple in the format (width, height) which is maximum size of
    the picture returned by this function
formats : :obj`list` or :obj:`tuple` of :obj:`dict`
    a list of all the formats to convert the picture to
Returns
-------
file
    The smallest file created in this function


settings = await self.api.account.settings.get()<EOL>tz = settings.time_zone.tzinfo_name<EOL>os.environ['<STR_LIT>'] = tz<EOL>time.tzset()<EOL>

set the environment timezone to the timezone
set in your twitter settings


return tempfile.NamedTemporaryFile(mode='<STR_LIT:w>',<EOL>dir=os.path.dirname(filename),<EOL>prefix=os.path.basename(filename),<EOL>suffix=os.fsencode('<STR_LIT>'),<EOL>delete=False)<EOL>

Create a NamedTemporaryFile instance to be passed to atomic_writer


f = _tempfile(os.fsencode(filename))<EOL>try:<EOL><INDENT>yield f<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL>os.replace(f.name, filename)<EOL><DEDENT>

Open a NamedTemoraryFile handle in a context manager


with open(os.fsencode(str(filename)), "<STR_LIT:r>") as f:<EOL><INDENT>data = json.load(f)<EOL>results = [i for i in data if i["<STR_LIT>"] == str(uuid)]<EOL>if results:<EOL><INDENT>return results<EOL><DEDENT>return None<EOL><DEDENT>


with atomic_write(os.fsencode(str(filename))) as temp_file:<EOL><INDENT>with open(os.fsencode(str(filename))) as products_file:<EOL><INDENT>products_data = json.load(products_file)<EOL><DEDENT>uuid_list = [i for i in filter(<EOL>lambda z: z["<STR_LIT>"] == str(item["<STR_LIT>"]), products_data)]<EOL>if len(uuid_list) == <NUM_LIT:0>:<EOL><INDENT>products_data.append(item)<EOL>json.dump(products_data, temp_file)<EOL>return True<EOL><DEDENT>return None<EOL><DEDENT>