prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*-
# Copyright 2011-2018 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
from builtins import str
import six
import datetime
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.core.exceptions import ValidationError
from django.utils import timezone
from lino import mixins
from lino.api import dd, rt, _, pgettext
from .choicelists import (
DurationUnits, Recurrencies, Weekdays, AccessClasses, PlannerColumns)
from .utils import setkw, dt2kw, when_text
from lino.modlib.checkdata.choicelists import Checker
from lino.modlib.printing.mixins import TypedPrintable
from lino.modlib.printing.mixins import Printable
from lino.modlib.users.mixins import UserAuthored, Assignable
from lino_xl.lib.postings.mixins import Postable
from lino_xl.lib.outbox.mixins import MailableType, Mailable
from lino_xl.lib.contacts.mixins import ContactRelated
from lino.modlib.office.roles import OfficeStaff
from .workflows import (TaskStates, EntryStates, GuestStates)
from .actions import UpdateGuests
from .mixins import Component
from .mixins import EventGenerator, RecurrenceSet, Reservation
from .mixins import Ended
from .mixins import MoveEntryNext, UpdateEntries, UpdateEntriesByEvent
from .actions import ShowEntriesByDay
from .ui import ConflictingEvents
DEMO_START_YEAR = 2013
class CalendarType(object):
def validate_calendar(self, cal):
pass
class LocalCalendar(CalendarType):
label = "Local Calendar"
class GoogleCalendar(CalendarType):
label = "Google Calendar"
def validate_calendar(self, cal):
if not cal.url_template:
cal.url_template = \
"https://%(username)s:%(password)[email protected]/calendar/dav/%(username)s/"
CALENDAR_CHOICES = []
CALENDAR_DICT = {}
def register_calendartype(name, instance):
CALENDAR_DICT[name] = instance
CALENDAR_CHOICES.append((name, instance.label))
register_calendartype('local', LocalCalendar())
register_calendartype('google', GoogleCalendar())
class DailyPlannerRow(mixins.BabelDesignated, mixins.Sequenced):
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'PlannerRow')
verbose_name = _("Planner row")
verbose_name_plural = _("Planner rows")
ordering = ['seqno']
start_time = models.TimeField(
blank=True, null=True,
verbose_name=_("Start time"))
end_time = models.TimeField(
blank=True, null=True,
verbose_name=_("End time"))
from lino.mixins.periods import ObservedDateRange
from etgen.html import E
from lino.utils import join_elems
class DailyPlannerRows(dd.Table):
model = 'cal.DailyPlannerRow'
column_names = "seqno designation start_time end_time"
required_roles = dd.login_required(OfficeStaff)
class DailyPlanner(DailyPlannerRows):
label = _("Daily planner")
editable = False
parameters = dict(
date=models.DateField(
_("Date"), help_text=_("Date to show")),
user=dd.ForeignKey('users.User', null=True, blank=True))
@classmethod
def param_defaults(cls, ar, **kw):
kw = super(DailyPlanner, cls).param_defaults(ar, **kw)
kw.update(date=dd.today())
# kw.update(end_date=dd.today())
# kw.update(user=ar.get_user())
return kw
@classmethod
def setup_columns(self):
names = ''
for i, vf in enumerate(self.get_ventilated_columns()):
self.add_virtual_field('vc' + str(i), vf)
names += ' ' + vf.name + ':20'
self.column_names = "overview {}".format(names)
#~ logger.info("20131114 setup_columns() --> %s",self.column_names)
@classmethod
def get_ventilated_columns(cls):
Event = rt.models.cal.Event
def fmt(e):
t = str(e.start_time)[:5]
u = e.user
if u is None:
return "{} {}".format(
t, e.room)
return t
u = u.initials or u.username or str(u)
return "{} {}".format(t, u)
def w(pc, verbose_name):
def func(fld, obj, ar):
# obj is the DailyPlannerRow instance
pv = ar.param_values
qs = Event.objects.filter(event_type__planner_column=pc)
if pv.user:
qs = qs.filter(user=pv.user)
if pv.date:
qs = qs.filter(start_date=pv.date)
if obj.start_time:
qs = qs.filter(start_time__gte=obj.start_time,
start_time__isnull=False)
if obj.end_time:
qs = qs.filter(start_time__lt=obj.end_time,
start_time__isnull=False)
if not obj.start_time and not obj.end_time:
qs = qs.filter(start_time__isnull=True)
qs = qs.order_by('start_time')
chunks = [e.obj2href(ar, fmt(e)) for e in qs]
return E.p(*join_elems(chunks))
return dd.VirtualField(dd.HtmlBox(verbose_name), func)
for pc in PlannerColumns.objects():
yield w(pc, pc.text)
class RemoteCalendar(mixins.Sequenced):
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'RemoteCalendar')
verbose_name = _("Remote Calendar")
verbose_name_plural = _("Remote Calendars")
ordering = ['seqno']
type = models.CharField(_("Type"), max_length=20,
default='local',
choices=CALENDAR_CHOICES)
url_template = models.CharField(_("URL template"),
max_length=200, blank=True) # ,null=True)
username = models.CharField(_("Username"),
max_length=200, blank=True) # ,null=True)
password = dd.PasswordField(_("Password"),
max_length=200, blank=True) # ,null=True)
readonly = models.BooleanField(_("read-only"), default=False)
def get_url(self):
if self.url_template:
return self.url_template % dict(
username=self.username,
password=self.password)
return ''
def save(self, *args, **kw):
ct = CALENDAR_DICT.get(self.type)
ct.validate_calendar(self)
super(RemoteCalendar, self).save(*args, **kw)
class Room(mixins.BabelNamed, ContactRelated):
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'Room')
verbose_name = _("Room")
verbose_name_plural = _("Rooms")
description = dd.RichTextField(_("Description"), blank=True)
dd.update_field(
Room, 'company', verbose_name=_("Responsible"))
dd.update_field(
Room, 'contact_person', verbose_name=_("Contact person"))
class Priority(mixins.BabelNamed):
class Meta:
app_label = 'cal'
verbose_name = _("Priority")
verbose_name_plural = _('Priorities')
ref = models.CharField(max_length=1)
@dd.python_2_unicode_compatible
class EventType(mixins.BabelNamed, mixins.Sequenced, MailableType):
templates_group = 'cal/Event'
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'EventType')
verbose_name = _("Calendar entry type")
verbose_name_plural = _("Calendar entry types")
ordering = ['seqno']
description = dd.RichTextField(
_("Description"), blank=True, format='html')
is_appointment = models.BooleanField(_("Appointment"), default=True)
all_rooms = models.BooleanField(_("Locks all rooms"), default=False)
locks_user = models.BooleanField(_("Locks the user"), default=False)
start_date = models.DateField(
verbose_name=_("Start date"),
blank=True, null=True)
event_label = dd.BabelCharField(
_("Entry label"), max_length=200, blank=True)
# , default=_("Calendar entry"))
# default values for a Babelfield don't work as expected
max_conflicting = models.PositiveIntegerField(
_("Simultaneous entries"), default=1)
max_days = models.PositiveIntegerField(
_("Maximum days"), default=1)
transparent = models.BooleanField(_("Transparent"), default=False)
planner_column = PlannerColumns.field(blank=True)
def __str__(self):
# when selecting an Event.event_type it is more natural to
# have the event_label. It seems that the current `name` field
# is actually never used.
return settings.SITE.babelattr(self, 'event_label') \
or settings.SITE.babelattr(self, 'name')
class GuestRole(mixins.BabelNamed):
templates_group = 'cal/Guest'
class Meta:
app_label = 'cal'
verbose_name = _("Guest Role")
verbose_name_plural = _("Guest Roles")
def default_color():
d = Calendar.objects.all().aggregate(models.Max('color'))
n = d['color__max'] or 0
return n + 1
class Calendar(mixins.BabelNamed):
COLOR_CHOICES = [i + 1 for i in range(32)]
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'Calendar')
verbose_name = _("Calendar")
verbose_name_plural = _("Calendars")
description = dd.RichTextField(_("Description"), blank=True, format='html')
color = models.IntegerField(
_("color"), default=default_color,
validators=[MinValueValidator(1), MaxValueValidator(32)]
)
# choices=COLOR_CHOICES)
class Subscription(UserAuthored):
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'Subscription')
verbose_name = _("Subscription")
verbose_name_plural = _("Subscriptions")
unique_together = ['user', 'calendar']
manager_roles_required = dd.login_required(OfficeStaff)
calendar = dd.ForeignKey(
'cal.Calendar', help_text=_("The calendar you want to subscribe to."))
is_hidden = models.BooleanField(
_("hidden"), default=False,
help_text=_("""Whether this subscription should "
"initially be displayed as a hidden calendar."""))
class Task(Component):
class Meta:
app_label = 'cal'
verbose_name = _("Task")
verbose_name_plural = _("Tasks")
abstract = dd.is_abstract_model(__name__, 'Task')
due_date = models.DateField(
blank=True, null=True,
verbose_name=_("Due date"))
due_time = models.TimeField(
blank=True, null=True,
verbose_name=_("Due time"))
# ~ done = models.BooleanField(_("Done"),default=False) # iCal:COMPLETED
# iCal:PERCENT
percent = models.IntegerField(_("Duration value"), null=True, blank=True)
state = TaskStates.field(
default=TaskStates.as_callable('todo')) # iCal:STATUS
# def before_ui_save(self, ar, **kw):
# if self.state == TaskStates.todo:
# self.state = TaskStates.started
# return super(Task, self).before_ui_save(ar, **kw)
# def on_user_change(self,request):
# if not self.state:
# self.state = TaskState.todo
# self.user_modified = True
def is_user_modified(self):
return self.state != TaskStates.todo
@classmethod
def on_analyze(cls, lino):
# lino.TASK_AUTO_FIELDS = dd.fields_list(cls,
cls.DISABLED_AUTO_FIELDS = dd.fields_list(
cls, """start_date start_time summary""")
super(Task, cls).on_analyze(lino)
# def __unicode__(self):
# ~ return "#" + str(self.pk)
class EventPolicy(mixins.BabelNamed, RecurrenceSet):
class Meta:
app_label = 'cal'
verbose_name = _("Recurrency policy")
verbose_name_plural = _('Recurrency policies')
abstract = dd.is_abstract_model(__name__, 'EventPolicy')
event_type = dd.ForeignKey(
'cal.EventType', null=True, blank=True)
class RecurrentEvent(mixins.BabelNamed, RecurrenceSet, EventGenerator,
UserAuthored):
class Meta:
app_label = 'cal'
verbose_name = _("Recurring event")
verbose_name_plural = _("Recurring events")
abstract = dd.is_abstract_model(__name__, 'RecurrentEvent')
event_type = dd.ForeignKey('cal.EventType', blank=True, null=True)
description = dd.RichTextField(
_("Description"), blank=True, format='html')
# def on_create(self,ar):
# super(RecurrentEvent,self).on_create(ar)
# self.event_type = settings.SITE.site_config.holiday_event_type
# def __unicode__(self):
# return self.summary
def update_cal_rset(self):
return self
def update_cal_from(self, ar):
return self.start_date
def update_cal_event_type(self):
return self.event_type
def update_cal_summary(self, et, i):
return six.text_type(self)
def care_about_conflicts(self, we):
return False
dd.update_field(
RecurrentEvent, 'every_unit',
default=Recurrencies.as_callable('yearly'), blank=False, null=False)
class ExtAllDayField(dd.VirtualField):
"""
An editable virtual field needed for
communication with the Ext.ensible CalendarPanel
because we consider the "all day" checkbox
equivalent to "empty start and end time fields".
"""
editable = True
def __init__(self, *args, **kw):
dd.VirtualField.__init__(self, models.BooleanField(*args, **kw), None)
def set_value_in_object(self, request, obj, value):
if value:
obj.end_time = None
obj.start_time = None
else:
if not obj.start_time:
obj.start_time = datetime.time(9, 0, 0)
if not obj.end_time:
pass
# obj.end_time = datetime.time(10, 0, 0)
# obj.save()
def value_from_object(self, obj, ar):
# logger.info("20120118 value_from_object() %s",dd.obj2str(obj))
return (obj.start_time is None)
@dd.python_2_unicode_compatible
class Event(Component, Ended, Assignable, TypedPrintable, Mailable, Postable):
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'Event')
# abstract = True
verbose_name = _("Calendar entry")
verbose_name_plural = _("Calendar entries")
# verbose_name = pgettext("cal", "Event")
# verbose_name_plural = pgettext("cal", "Events")
update_guests = UpdateGuests()
update_events = UpdateEntriesByEvent()
show_today = ShowEntriesByDay('start_date')
event_type = dd.ForeignKey('cal.EventType', blank=True, null=True)
transparent = models.BooleanField(_("Transparent"), default=False)
room = dd.ForeignKey('cal.Room', null=True, blank=True)
priority = dd.ForeignKey(Priority, null=True, blank=True)
state = EntryStates.field(
default=EntryStates.as_callable('suggested'))
all_day = ExtAllDayField(_("all day"))
move_next = MoveEntryNext()
show_conflicting = dd.ShowSlaveTable(ConflictingEvents)
def strftime(self):
if not self.start_date:
return ''
d = self.start_date.strftime(settings.SITE.date_format_strftime)
if self.start_time:
t = self.start_time.strftime(
settings.SITE.time_format_strftime)
return "%s %s" % (d, t)
else:
return d
def __str__(self):
if self.summary:
s = self.summary
elif self.event_type:
s = str(self.event_type)
elif self.pk:
s = self._meta.verbose_name + " #" + str(self.pk)
else:
s = _("Unsaved %s") % self._meta.verbose_name
when = self.strftime()
if when:
s = "{} ({})".format(s, when)
return s
def duration_veto(obj):
if obj.end_date is None:
return
et = obj.event_type
if et is None:
return
duration = obj.end_date - obj.start_date
# print (20161222, duration.days, et.max_days)
if duration.days > et.max_days:
return _(
"Event lasts {0} days but only {1} are allowed.").format(
duration.days, et.max_days)
def full_clean(self, *args, **kw):
et = self.event_type
if et and et.max_days == 1:
# avoid "Abandoning with 297 unsaved instances"
self.end_date = None
msg = self.duration_veto()
if msg is not None:
raise ValidationError(str(msg))
super(Event, self).full_clean(*args, **kw)
def get_change_observers(self):
# implements ChangeNotifier
if not self.is_user_modified():
return
for x in super(Event, self).get_change_observers():
yield x
for u in (self.user, self.assigned_to):
if u is not None:
yield (u, u.mail_mode)
def has_conflicting_events(self):
qs = self.get_conflicting_events()
if qs is None:
return False
if self.event_type is not None:
if self.event_type.transparent:
return False
# holidays (all room events) conflict also with events
# whose type otherwise would allow conflicting events
if qs.filter(event_type__all_rooms=True).count() > 0:
return True
n = self.event_type.max_conflicting - 1
else:
n = 0
# date = self.start_date
# if date.day == 9 and date.month == 3:
# dd.logger.info("20171130 has_conflicting_events() %s", qs.query)
return qs.count() > n
def get_conflicting_events(self):
if self.transparent:
return
# if self.event_type is not None and self.event_type.transparent:
# return
# return False
# Event = dd.resolve_model('cal.Event')
# ot = ContentType.objects.get_for_model(RecurrentEvent)
qs = self.__class__.objects.filter(transparent=False)
qs = qs.exclude(event_type__transparent=True)
# if self.state.transparent:
# # cancelled entries are basically transparent to all
# # others. Except if they have an owner, in which case we
# # wouldn't want Lino to put another automatic entry at
# # that date.
# if self.owner_id is None:
# return
# qs = qs.filter(
# owner_id=self.owner_id, owner_type=self.owner_type)
end_date = self.end_date or self.start_date
flt = Q(start_date=self.start_date, end_date__isnull=True)
flt |= Q(end_date__isnull=False,
start_date__lte=self.start_date, end_date__gte=end_date)
if end_date == self.start_date:
if self.start_time and self.end_time:
# the other starts before me and ends after i started
c1 = Q(start_time__lte=self.start_time,
end_time__gt=self.start_time)
# the other ends after me and started before i ended
c2 = Q(end_time__gte=self.end_time,
start_time__lt=self.end_time)
# the other is full day
c3 = Q(end_time__isnull=True, start_time__isnull=True)
flt &= (c1 | c2 | c3)
qs = qs.filter(flt)
# saved events don't conflict with themselves:
if self.id is not None:
qs = qs.exclude(id=self.id)
# automatic events never conflict with other generated events
# of same owner. Rule needed for update_events.
if self.auto_type:
qs = qs.exclude(
# auto_type=self.auto_type,
auto_type__isnull=False,
owner_id=self.owner_id, owner_type=self.owner_type)
# transparent events (cancelled or omitted) usually don't
# cause a conflict with other events (e.g. a holiday). But a
# cancelled course lesson should not tolerate another lesson
# of the same course on the same date.
ntstates = EntryStates.filter(transparent=False)
if self.owner_id is None:
if self.state.transparent:
return
qs = qs.filter(state__in=ntstates)
else:
if self.state.transparent:
qs = qs.filter(
owner_id=self.owner_id, owner_type=self.owner_type)
else:
qs = qs.filter(
Q(state__in=ntstates) | Q(
owner_id=self.owner_id, owner_type=self.owner_type))
if self.room is None:
# an entry that needs a room but doesn't yet have one,
# conflicts with any all-room entry (e.g. a holiday). For
# generated entries this list extends to roomed entries of
# the same generator.
if self.event_type is None or not self.event_type.all_rooms:
if self.owner_id is None:
qs = qs.filter(event_type__all_rooms=True)
else:
qs = qs.filter(
Q(event_type__all_rooms=True) | Q(
owner_id=self.owner_id, owner_type=self.owner_type))
else:
# other event in the same room
c1 = Q(room=self.room)
# other event locks all rooms (e.g. holidays)
# c2 = Q(room__isnull=False, event_type__all_rooms=True)
c2 = Q(event_type__all_rooms=True)
qs = qs.filter(c1 | c2)
if self.user is not None:
if self.event_type is not None:
if self.event_type.locks_user:
# c1 = Q(event_type__locks_user=False)
# c2 = Q(user=self.user)
# qs = qs.filter(c1|c2)
qs = qs.filter(user=self.user, event_type__locks_user=True)
# qs = Event.objects.filter(flt,owner_type=ot)
# if we.start_date.month == 7:
# print 20131011, self, we.start_date, qs.count()
# print 20131025, qs.query
return qs
def is_fixed_state(self):
return self.state.fixed
# return self.state in EntryStates.editable_states
def is_user_modified(self):
return self.state != EntryStates.suggested
def after_ui_save(self, ar, cw):
super(Event, self).after_ui_save(ar, cw)
self.update_guests.run_from_code(ar)
def before_state_change(self, ar, old, new):
super(Event, self).before_state_change(ar, old, new)
if new.noauto:
self.auto_type = None
def suggest_guests(self):
if self.owner:
for obj in self.owner.suggest_cal_guests(self):
yield obj
def get_event_summary(event, ar):
# from django.utils.translation import ugettext as _
s = event.summary
# if event.owner_id:
# s += " ({0})".format(event.owner)
if event.user is not None and event.user != ar.get_user():
if event.access_class == AccessClasses.show_busy:
s = _("Busy")
s = event.user.username + ': ' + unicode(s)
elif settings.SITE.project_model is not None \
and event.project is not None:
s += " " + unicode(_("with")) + " " + unicode(event.project)
if event.state:
s = ("(%s) " % unicode(event.state)) + s
n = event.guest_set.all().count()
if n:
s = ("[%d] " % n) + s
return s
def before_ui_save(self, ar, **kw):
# logger.info("20130528 before_ui_save")
if self.state is EntryStates.suggested:
self.state = EntryStates.draft
return super(Event, self).before_ui_save(ar, **kw)
def on_create(self, ar):
if self.event_type is None:
self.event_type = ar.user.event_type or \
settings.SITE.site_config.default_event_type
self.start_date = settings.SITE.today()
self.start_time = timezone.now().time()
# see also Assignable.on_create()
super(Event, self).on_create(ar)
# def on_create(self,ar):
# self.start_date = settings.SITE.today()
# self.start_time = datetime.datetime.now().time()
# ~ # default user is almost the same as for UserAuthored
# ~ # but we take the *real* user, not the "working as"
# if self.user_id is None:
# u = ar.user
# if u is not None:
# self.user = u
# super(Event,self).on_create(ar)
def get_postable_recipients(self):
"""return or yield a list of Partners"""
if self.project:
if isinstance(self.project, dd.plugins.cal.partner_model):
yield self.project
for g in self.guest_set.all():
yield g.partner
# if self.user.partner:
# yield self.user.partner
def get_mailable_type(self):
return self.event_type
def get_mailable_recipients(self):
if self.project:
if isinstance(self.project, dd.plugins.cal.partner_model):
yield ('to', self.project)
for g in self.guest_set.all():
yield ('to', g.partner)
if self.user.partner:
yield ('cc', self.user.partner)
# def get_mailable_body(self,ar):
# return self.description
@dd.displayfield(_("When"), sortable_by=['start_date', 'start_time'])
def when_text(self, ar):
txt = when_text(self.start_date, self.start_time)
if self.end_date and self.end_date != self.start_date:
txt += "-" + when_text(self.end_date, self.end_time)
return txt
@dd.displayfield(_("When"), sortable_by=['start_date', 'start_time'])
# def linked_date(self, ar):
def when_html(self, ar):
if ar is None:
return ''
EntriesByDay = settings.SITE.models.cal.EntriesByDay
txt = when_text(self.start_date, self.start_time)
return EntriesByDay.as_link(ar, self.start_date, txt)
# return self.obj2href(ar, txt)
@dd.displayfield(_("Link URL"))
def url(self, ar):
return 'foo'
@dd.virtualfield(dd.DisplayField(_("Reminder")))
def reminder(self, request):
return False
# reminder.return_type = dd.DisplayField(_("Reminder"))
def get_calendar(self):
# for sub in Subscription.objects.filter(user=ar.get_user()):
# if sub.contains_event(self):
# return sub
return None
@dd.virtualfield(dd.ForeignKey('cal.Calendar'))
def calendar(self, ar):
return self.get_calendar()
def get_print_language(self):
# if settings.SITE.project_model is not None and self.project:
if self.project:
return self.project.get_print_language()
if self.user:
return self.user.language
return settings.SITE.get_default_language()
@classmethod
def get_default_table(cls):
return OneEvent
@classmethod
def on_analyze(cls, lino):
cls.DISABLED_AUTO_FIELDS = dd.fields_list(cls, "summary")
super(Event, cls).on_analyze(lino)
def auto_type_changed(self, ar):
if self.auto_type:
self.summary = self.owner.update_cal_summary(
self.event_type, self.auto_type)
# def save(self, *args, **kwargs):
# if "Weekends" in str(self.owner):
# if not self.end_date:
# raise Exception("20180321")
# super(Event, self).save(*args, **kwargs)
dd.update_field(Event, 'user', verbose_name=_("Responsible user"))
class EntryChecker(Checker):
model = Event
def get_responsible_user(self, obj):
return obj.user or super(
EntryChecker, self).get_responsible_user(obj)
class EventGuestChecker(EntryChecker):
verbose_name = _("Entries without participants")
def get_checkdata_problems(self, obj, fix=False):
if not obj.state.edit_guests:
return
existing = set([g.partner.pk for g in obj.guest_set.all()])
if len(existing) == 0:
suggested = list(obj.suggest_guests())
if len(suggested) > 0:
msg = _("No participants although {0} suggestions exist.")
yield (True, msg.format(len(suggested)))
if fix:
for g in suggested:
g.save()
EventGuestChecker.activate()
class ConflictingEventsChecker(EntryChecker):
verbose_name = _("Check for conflicting calendar entries")
def get_checkdata_problems(self, obj, fix=False):
if not obj.has_conflicting_events():
return
qs = obj.get_conflicting_events()
num = qs.count()
if num == 1:
msg = _("Event conflicts with {0}.").format(qs[0])
else:
msg = _("Event conflicts with {0} other events.").format(num)
yield (False, msg)
ConflictingEventsChecker.activate()
class ObsoleteEventTypeChecker(EntryChecker):
verbose_name = _("Obsolete generated calendar entries")
def get_checkdata_problems(self, obj, fix=False):
if not obj.auto_type:
return
if obj.owner is None:
msg = _("Has auto_type but no owner.")
yield (False, msg)
return
et = obj.owner.update_cal_event_type()
if obj.event_type != et:
msg = _("Event type but {0} (should be {1}).").format(
obj.event_type, et)
autofix = False # TODO: make this configurable?
yield (autofix, msg)
if fix:
obj.event_type = et
obj.full_clean()
obj.save()
ObsoleteEventTypeChecker.activate()
DONT_FIX_LONG_ENTRIES = False
class LongEntryChecker(EntryChecker):
verbose_name = _("Too long-lasting calendar entries")
model = Event
def get_checkdata_problems(self, obj, fix=False):
msg = obj.duration_veto()
if msg is not None:
if DONT_FIX_LONG_ENTRIES:
yield (False, msg)
else:
yield (True, msg)
if fix:
obj.end_date = None
obj.full_clean()
obj.save()
LongEntryChecker.activate()
@dd.python_2_unicode_compatible
class Guest(Printable):
workflow_state_field = 'state'
allow_cascaded_delete = ['event']
class Meta:
app_label = 'cal'
abstract = dd.is_abstract_model(__name__, 'Guest')
# verbose_name = _("Participant")
# verbose_name_plural = _("Participants")
verbose_name = _("Presence")
verbose_name_plural = _("Presences")
unique_together = ['event', 'partner']
event = dd.ForeignKey('cal.Event')
partner = dd.ForeignKey(dd.plugins.cal.partner_model)
role = dd.ForeignKey(
'cal.GuestRole', verbose_name=_("Role"), blank=True, null=True)
state = GuestStates.field(default=GuestStates.as_callable('invited'))
remark = models.CharField(_("Remark"), max_length=200, blank=True)
# Define a `user` property because we want to use
# `lino.modlib.users.mixins.My`
def get_user(self):
# used to apply `owner` requirement in GuestState
return self.event.user
user = property(get_user)
# author_field_name = 'user'
def __str__(self):
return u'%s #%s (%s)' % (
self._meta.verbose_name, self.pk, self.event.strftime())
# def get_printable_type(self):
# return self.role
def get_mailable_type(self):
return self.role
def get_mailable_recipients(self):
yield ('to', self.partner)
@dd.displayfield(_("Event"))
def event_summary(self, ar):
if ar is None:
return ''
return ar.obj2html(self.event, self.event.get_event_summary(ar))
def migrate_reminder(obj, reminder_date, reminder_text,
delay_value, delay_type, reminder_done):
"""
This was used only for migrating to 1.2.0,
see :mod:`lino.projects.pcsw.migrate`.
"""
raise NotImplementedError(
"No longer needed (and no longer supported after 20111026).")
def delay2alarm(delay_type):
if delay_type == 'D':
return DurationUnits.days
if delay_type == 'W':
return DurationUnits.weeks
if delay_type == 'M':
return DurationUnits.months
if delay_type == 'Y':
return DurationUnits.years
# ~ # These constants must be unique for the whole Lino Site.
# ~ # Keep in sync with auto types defined in lino.projects.pcsw.models.Person<|fim▁hole|> summary = reminder_text
else:
summary = _('due date reached')
update_auto_task(
None, # REMINDER,
obj.user,
reminder_date,
summary, obj,
done=reminder_done,
alarm_value=delay_value,
alarm_unit=delay2alarm(delay_type))
# Inject application-specific fields to users.User.
dd.inject_field(settings.SITE.user_model,
'access_class',
AccessClasses.field(
default=AccessClasses.as_callable('public'),
verbose_name=_("Default access class"),
help_text=_(
"""The default access class for your calendar events and tasks.""")
))
dd.inject_field(settings.SITE.user_model,
'event_type',
dd.ForeignKey('cal.EventType',
blank=True, null=True,
verbose_name=_("Default Event Type"),
help_text=_("""The default event type for your calendar events.""")
))
dd.inject_field(
'system.SiteConfig',
'default_event_type',
dd.ForeignKey(
'cal.EventType',
blank=True, null=True,
verbose_name=_("Default Event Type"),
help_text=_("""The default type of events on this site.""")
))
dd.inject_field(
'system.SiteConfig',
'site_calendar',
dd.ForeignKey(
'cal.Calendar',
blank=True, null=True,
related_name="%(app_label)s_%(class)s_set_by_site_calender",
verbose_name=_("Site Calendar"),
help_text=_("""The default calendar of this site.""")))
dd.inject_field(
'system.SiteConfig',
'max_auto_events',
models.IntegerField(
_("Max automatic events"), default=72,
blank=True, null=True,
help_text=_(
"""Maximum number of automatic events to be generated.""")
))
dd.inject_field(
'system.SiteConfig',
'hide_events_before',
models.DateField(
_("Hide events before"),
blank=True, null=True,
help_text=_("""If this is specified, certain tables show only
events after the given date.""")
))
Reservation.show_today = ShowEntriesByDay('start_date')
if False: # removed 20160610 because it is probably not used
def update_reminders_for_user(user, ar):
n = 0
for model in rt.models_by_base(EventGenerator):
for obj in model.objects.filter(user=user):
obj.update_reminders(ar)
# logger.info("--> %s",unicode(obj))
n += 1
return n
class UpdateUserReminders(UpdateEntries):
"""
Users can invoke this to re-generate their automatic tasks.
"""
def run_from_ui(self, ar, **kw):
user = ar.selected_rows[0]
dd.logger.info("Updating reminders for %s", unicode(user))
n = update_reminders_for_user(user, ar)
msg = _("%(num)d reminders for %(user)s have been updated."
) % dict(user=user, num=n)
dd.logger.info(msg)
ar.success(msg, **kw)
@dd.receiver(dd.pre_analyze, dispatch_uid="add_update_reminders")
def pre_analyze(sender, **kw):
sender.user_model.define_action(update_reminders=UpdateUserReminders())
from .ui import *<|fim▁end|> | # REMINDER = 5
if reminder_text: |
<|file_name|>104.Maximum Depth of Binary Tree.java<|end_file_name|><|fim▁begin|>public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {<|fim▁hole|>}<|fim▁end|> | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
} |
<|file_name|>LISTIMP.H<|end_file_name|><|fim▁begin|>/*------------------------------------------------------------------------*/
/* */
/* LISTIMP.H */
/* */
/* Copyright Borland International 1991, 1992 */
/* All Rights Reserved */
/* */
/*------------------------------------------------------------------------*/
#if !defined( __LISTIMP_H )
#define __LISTIMP_H
<|fim▁hole|>
#if !defined( __DEFS_H )
#include <_defs.h>
#endif // __DEFS_H
#if !defined( __MEMMGR_H )
#include <MemMgr.h>
#endif // __MEMMGR_H
#pragma option -Vo-
#if defined( __BCOPT__ ) && !defined( _ALLOW_po )
#pragma option -po-
#endif
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_ListElement */
/* */
/* Node for templates BI_ListImp<T> and BI_IListImp<T> */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_ListImp;
template <class T> class _CLASSTYPE BI_ListBlockInitializer
{
protected:
BI_ListBlockInitializer()
{
PRECONDITION( count != UINT_MAX );
if( count++ == 0 )
BI_ListElement<T>::mgr =
new MemBlocks( sizeof(BI_ListElement<T>), 20 );
}
~BI_ListBlockInitializer()
{
PRECONDITION( count != 0 );
if( --count == 0 )
{
delete BI_ListElement<T>::mgr;
BI_ListElement<T>::mgr = 0;
}
}
static unsigned count;
};
template <class T> unsigned BI_ListBlockInitializer<T>::count = 0;
template <class T> class _CLASSTYPE BI_ListElement
{
public:
BI_ListElement( T t, BI_ListElement<T> _FAR *p ) :
data(t)
{
next = p->next;
p->next = this;
}
BI_ListElement();
BI_ListElement<T> _FAR *next;
T data;
void _FAR *operator new( size_t sz );
void operator delete( void _FAR * );
private:
friend class BI_ListBlockInitializer<T>;
static MemBlocks *mgr;
};
template <class T> MemBlocks *BI_ListElement<T>::mgr = 0;
inline BI_ListElement<void _FAR *>::BI_ListElement()
{
next = 0;
data = 0;
}
template <class T> inline BI_ListElement<T>::BI_ListElement()
{
next = 0;
}
template <class T> void _FAR *BI_ListElement<T>::operator new( size_t sz )
{
PRECONDITION( mgr != 0 );
return mgr->allocate( sz );
}
template <class T> void BI_ListElement<T>::operator delete( void _FAR *b )
{
PRECONDITION( mgr != 0 );
mgr->free( b );
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_ListImp */
/* */
/* Implements a list of objects of type T. Assumes that */
/* T has meaningful copy semantics and a default constructor. */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_ListIteratorImp;
template <class T> class _CLASSTYPE BI_ListImp :
private BI_ListBlockInitializer<T>
{
public:
friend class BI_ListIteratorImp<T>;
BI_ListImp()
{
initList();
}
~BI_ListImp()
{
flush();
}
T peekHead() const
{
return head.next->data;
}
void add( T );
void detach( T, int = 0 );
void flush( int del = 0 );
int isEmpty() const
{
return head.next == &tail;
}
void forEach( void (_FAR *)(T _FAR &, void _FAR *), void _FAR * );
T _FAR *firstThat( int (_FAR *)(const T _FAR &, void _FAR *),
void _FAR *
) const;
T _FAR *lastThat( int (_FAR *)(const T _FAR &, void _FAR *),
void _FAR *
) const;
protected:
BI_ListElement<T> head, tail;
virtual BI_ListElement<T> _FAR *findDetach( T t )
{
return findPred(t);
}
virtual BI_ListElement<T> _FAR *findPred( T );
private:
virtual void removeData( BI_ListElement<T> _FAR * )
{
}
void initList();
};
template <class T> void BI_ListImp<T>::initList()
{
head.next = &tail;
tail.next = &tail;
}
template <class T> void BI_ListImp<T>::add( T toAdd )
{
new BI_ListElement<T>( toAdd, &head );
}
template <class T> BI_ListElement<T> _FAR *BI_ListImp<T>::findPred( T t )
{
tail.data = t;
BI_ListElement<T> _FAR *cursor = &head;
while( !(t == cursor->next->data) )
cursor = cursor->next;
return cursor;
}
template <class T> void BI_ListImp<T>::detach( T toDetach, int del )
{
BI_ListElement<T> _FAR *pred = findDetach( toDetach );
BI_ListElement<T> _FAR *item = pred->next;
if( item != &tail )
{
pred->next = pred->next->next;
if( del != 0 )
removeData( item );
delete item;
}
}
template <class T> void BI_ListImp<T>::flush( int del )
{
BI_ListElement<T> _FAR *current = head.next;
while( current != &tail )
{
BI_ListElement<T> _FAR *temp = current;
current = current->next;
if( del != 0 )
removeData( temp );
delete temp;
}
initList();
}
template <class T>
void BI_ListImp<T>::forEach( void (_FAR *f)(T _FAR &, void _FAR *),
void _FAR *args
)
{
BI_ListElement<T> _FAR *cur = head.next;
while( cur->next != cur )
{
f( cur->data, args );
cur = cur->next;
}
}
template <class T>
T _FAR *BI_ListImp<T>::firstThat( int (_FAR *cond)(const T _FAR &, void _FAR *),
void _FAR *args
) const
{
BI_ListElement<T> _FAR *cur = head.next;
while( cur->next != cur )
if( cond( cur->data, args ) != 0 )
return &(cur->data);
else
cur = cur->next;
return 0;
}
template <class T>
T _FAR *BI_ListImp<T>::lastThat( int (_FAR *cond)(const T _FAR &, void _FAR *),
void _FAR *args
) const
{
T _FAR *res = 0;
BI_ListElement<T> _FAR *cur = head.next;
while( cur->next != cur )
{
if( cond( cur->data, args ) != 0 )
res = &(cur->data);
cur = cur->next;
}
return res;
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_SListImp */
/* */
/* Implements a sorted list of objects of type T. Assumes that */
/* T has meaningful copy semantics, a meaningful < operator, and a */
/* default constructor. */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_SListImp : public BI_ListImp<T>
{
public:
void add( T );
protected:
virtual BI_ListElement<T> _FAR *findDetach( T t );
virtual BI_ListElement<T> _FAR *findPred( T );
};
template <class T> void BI_SListImp<T>::add( T t )
{
new BI_ListElement<T>( t, findPred(t) );
}
template <class T> BI_ListElement<T> _FAR *BI_SListImp<T>::findDetach( T t )
{
BI_ListElement<T> _FAR *res = findPred(t);
if( res->next->data == t )
return res;
else
return &tail;
}
template <class T> BI_ListElement<T> _FAR *BI_SListImp<T>::findPred( T t )
{
tail.data = t;
BI_ListElement<T> _FAR *cursor = &head;
while( cursor->next->data < t )
cursor = cursor->next;
return cursor;
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_ListIteratorImp */
/* */
/* Implements a list iterator. This iterator works with any direct */
/* list. For indirect lists, see BI_IListIteratorImp. */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_ListIteratorImp
{
public:
BI_ListIteratorImp( const BI_ListImp<T> _FAR &l )
{
list = &l;
cur = list->head.next;
}
operator int()
{
return cur != &(list->tail);
}
T current()
{
return cur->data;
}
T operator ++ ( int )
{
BI_ListElement<T> _FAR *temp = cur;
cur = cur->next;
return temp->data;
}
T operator ++ ()
{
cur = cur->next;
return cur->data;
}
void restart()
{
cur = list->head.next;
}
private:
const BI_ListImp<T> _FAR *list;
BI_ListElement<T> _FAR *cur;
};
/*------------------------------------------------------------------------*/
/* */
/* template <class T, class Vect> class BI_InternalIListImp */
/* */
/* Implements a list of pointers to objects of type T. */
/* This is implemented through the form of BI_ListImp specified by List. */
/* Since pointers always have meaningful copy semantics, this class */
/* can handle any type of object. */
/* */
/*------------------------------------------------------------------------*/
template <class T, class List> class _CLASSTYPE BI_InternalIListImp :
public List
{
public:
T _FAR *peekHead() const
{
return (T _FAR *)List::peekHead();
}
void add( T _FAR *t )
{
List::add( t );
}
void detach( T _FAR *t, int del = 0 )
{
List::detach( t, del );
}
void forEach( void (_FAR *)(T _FAR &, void _FAR *), void _FAR * );
T _FAR *firstThat( int (_FAR *)(const T _FAR &, void _FAR *),
void _FAR *
) const;
T _FAR *lastThat( int (_FAR *)(const T _FAR &, void _FAR *),
void _FAR *
) const;
protected:
virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * ) = 0;
private:
virtual void removeData( BI_ListElement<void _FAR *> _FAR *block )
{
delete (T _FAR *)(block->data);
}
};
template <class T, class List>
void BI_InternalIListImp<T, List>::forEach( void (_FAR *f)(T _FAR &, void _FAR *),
void _FAR *args
)
{
BI_ListElement<void _FAR *> _FAR *cur = head.next;
while( cur->next != cur )
{
f( *(T _FAR *)cur->data, args );
cur = cur->next;
}
}
template <class T, class List>
T _FAR *BI_InternalIListImp<T, List>::firstThat( int (_FAR *cond)(const T _FAR &, void _FAR *),
void _FAR *args
) const
{
BI_ListElement<void _FAR *> _FAR *cur = head.next;
while( cur->next != cur )
if( cond( *(T _FAR *)(cur->data), args ) != 0 )
return (T _FAR *)cur->data;
else
cur = cur->next;
return 0;
}
template <class T, class List>
T _FAR *BI_InternalIListImp<T, List>::lastThat( int (_FAR *cond)(const T _FAR &, void _FAR *),
void _FAR *args
) const
{
T _FAR *res = 0;
BI_ListElement<void _FAR *> _FAR *cur = head.next;
while( cur->next != cur )
{
if( cond( *(T _FAR *)(cur->data), args ) != 0 )
res = (T _FAR *)(cur->data);
cur = cur->next;
}
return res;
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_IListImp */
/* */
/* Implements a list of pointers to objects of type T. */
/* This is implemented through the template BI_InternalIListImp. Since */
/* pointers always have meaningful copy semantics, this class */
/* can handle any type of object. */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_IListImp :
public BI_InternalIListImp<T, BI_ListImp<void _FAR *> >
{
protected:
virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * );
};
template <class T>
BI_ListElement<void _FAR *> _FAR *BI_IListImp<T>::findPred( void _FAR *t )
{
tail.data = t;
BI_ListElement<void _FAR *> _FAR *cursor = &head;
while( !(*(T _FAR *)t == *(T _FAR *)(cursor->next->data)) )
cursor = cursor->next;
return cursor;
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_ISListImp */
/* */
/* Implements a sorted list of pointers to objects of type T. */
/* This is implemented through the template BI_InternalIListImp. Since */
/* pointers always have meaningful copy semantics, this class */
/* can handle any type of object. */
/* */
/*------------------------------------------------------------------------*/
template <class T> class _CLASSTYPE BI_ISListImp :
public BI_InternalIListImp<T, BI_SListImp<void _FAR *> >
{
protected:
virtual BI_ListElement<void _FAR *> _FAR *findDetach( void _FAR * );
virtual BI_ListElement<void _FAR *> _FAR *findPred( void _FAR * );
};
template <class T>
BI_ListElement<void _FAR *> _FAR *BI_ISListImp<T>::findDetach( void _FAR *t )
{
BI_ListElement<void _FAR *> _FAR *res = findPred(t);
if( *(T _FAR *)(res->next->data) == *(T _FAR *)t )
return res;
else
return &tail;
}
template <class T>
BI_ListElement<void _FAR *> _FAR *BI_ISListImp<T>::findPred( void _FAR *t )
{
tail.data = t;
BI_ListElement<void _FAR *> _FAR *cursor = &head;
while( *(T _FAR *)(cursor->next->data) < *(T _FAR *)t )
cursor = cursor->next;
return cursor;
}
/*------------------------------------------------------------------------*/
/* */
/* template <class T> class BI_IListIteratorImp */
/* */
/* Implements a list iterator. This iterator works with any indirect */
/* list. For direct lists, see BI_ListIteratorImp. */
/* */
/*------------------------------------------------------------------------*/
template <class T>
class _CLASSTYPE BI_IListIteratorImp : public BI_ListIteratorImp<void _FAR *>
{
public:
BI_IListIteratorImp( const BI_ListImp<void _FAR *> _FAR &l ) :
BI_ListIteratorImp<void _FAR *>(l) {}
T _FAR *current()
{
return (T _FAR *)BI_ListIteratorImp<void _FAR *>::current();
}
T _FAR *operator ++ (int)
{
return (T _FAR *)BI_ListIteratorImp<void _FAR *>::operator ++ (1);
}
T _FAR *operator ++ ()
{
return (T _FAR *)BI_ListIteratorImp<void _FAR *>::operator ++ ();
}
};
#if defined( __BCOPT__ ) && !defined( _ALLOW_po )
#pragma option -po.
#endif
#pragma option -Vo.
#endif // __LISTIMP_H<|fim▁end|> | |
<|file_name|>__oldthermostat.py<|end_file_name|><|fim▁begin|>from hubs.ha import haremote as ha
from hubs.ha.hasshub import HAnode, RegisterDomain
from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested
from utils import timers
import functools
# noinspection PyTypeChecker
class Thermostat(HAnode): # deprecated version
def __init__(self, HAitem, d):
super(Thermostat, self).__init__(HAitem, **d)
self.Hub.RegisterEntity('climate', self.entity_id, self)
self.timerseq = 0
# noinspection PyBroadException
try:
self.temperature = self.attributes['temperature']
self.curtemp = self.attributes['current_temperature']
self.target_low = self.attributes['target_temp_low']
self.target_high = self.attributes['target_temp_high']
self.mode = self.attributes['operation_mode']
self.fan = self.attributes['fan_mode']
self.fanstates = self.attributes['fan_list']<|fim▁hole|>
# noinspection PyUnusedLocal
def ErrorFakeChange(self, param=None):
PostEvent(ConsoleEvent(CEvent.HubNodeChange, hub=self.Hub.name, node=self.entity_id, value=self.internalstate))
def Update(self, **ns):
if 'attributes' in ns: self.attributes = ns['attributes']
self.temperature = self.attributes['temperature']
self.curtemp = self.attributes['current_temperature']
self.target_low = self.attributes['target_temp_low']
self.target_high = self.attributes['target_temp_high']
self.mode = self.attributes['operation_mode']
self.fan = self.attributes['fan_mode']
PostIfInterested(self.Hub, self.entity_id, self.internalstate)
# noinspection DuplicatedCode
def PushSetpoints(self, t_low, t_high):
ha.call_service_async(self.Hub.api, 'climate', 'set_temperature',
{'entity_id': '{}'.format(self.entity_id), 'target_temp_high': str(t_high),
'target_temp_low': str(t_low)})
self.timerseq += 1
_ = timers.OnceTimer(5, start=True, name='fakepushsetpoint-{}'.format(self.timerseq),
proc=self.ErrorFakeChange)
def GetThermInfo(self):
if self.target_low is not None:
return self.curtemp, self.target_low, self.target_high, self.HVAC_state, self.mode, self.fan
else:
return self.curtemp, self.temperature, self.temperature, self.HVAC_state, self.mode, self.fan
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def _HVACstatechange(self, storeitem, old, new, param, chgsource):
self.HVAC_state = new
PostIfInterested(self.Hub, self.entity_id, new)
def _connectsensors(self, HVACsensor):
self.HVAC_state = HVACsensor.state
# noinspection PyProtectedMember
HVACsensor.SetSensorAlert(functools.partial(self._HVACstatechange))
def GetModeInfo(self):
return self.modelist, self.fanstates
def PushFanState(self, mode):
ha.call_service_async(self.Hub.api, 'climate', 'set_fan_mode',
{'entity_id': '{}'.format(self.entity_id), 'fan_mode': mode})
self.timerseq += 1
_ = timers.OnceTimer(5, start=True, name='fakepushfanstate-{}'.format(self.timerseq),
proc=self.ErrorFakeChange)
def PushMode(self, mode):
# noinspection PyBroadException
ha.call_service_async(self.Hub.api, 'climate', 'set_operation_mode',
{'entity_id': '{}'.format(self.entity_id), 'operation_mode': mode})
self.timerseq += 1
_ = timers.OnceTimer(5, start=True, name='fakepushmode -{}'.format(self.timerseq),
proc=self.ErrorFakeChange)
RegisterDomain('climate', Thermostat)<|fim▁end|> | self.modelist = self.attributes['operation_list']
except:
pass |
<|file_name|>update_sentry_404s.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from ...utils import update_sentry_404s
class Command(BaseCommand):
def handle(self, *args, **kwargs):
update_sentry_404s()<|fim▁end|> | from __future__ import unicode_literals
from django.core.management.base import BaseCommand
|
<|file_name|>equil_run.py<|end_file_name|><|fim▁begin|>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
#
# use pretty plotting if it can be imported
#
try:
import seaborn
except:
pass
sigma=5.67e-8
def find_tau(tot_trans,num_layers):
"""
# -TD- document using
"""
trans_layer=tot_trans**(1./num_layers)
tau_layer= -1.*np.log(trans_layer)
tau_layers=np.ones([num_layers])*tau_layer
tau_levels=np.cumsum(tau_layers)
tau_levels=np.concatenate(([0],tau_levels))
return tau_levels
def find_heights(press_levels,rho_layers):
"""
-TD- docstring using google style
"""
Rd=287.
g=9.8
press_layers=(press_levels[1:] + press_levels[:-1])/2.
del_press=(press_levels[1:] - press_levels[0:-1])
rho_layers=press_layers/(Rd*Temp_layers)
del_z= -1.*del_press/(rho_layers*g)
level_heights=np.cumsum(del_z)
level_heights=np.concatenate(([0],level_heights))
return level_heights
def fluxes(tau_levels,Temp_layers,T_surf):
"""
-TD- docstring using google style
"""
up_rad=np.empty_like(tau_levels)
down_rad=np.empty_like(tau_levels)
sfc_rad=sigma*T_surf**4.
up_rad[0]=sfc_rad
tot_levs=len(tau_levels)
for index in np.arange(1,tot_levs):
upper_lev=index
lower_lev=index - 1
layer_num=index-1
del_tau=tau_levels[upper_lev] - tau_levels[lower_lev]
trans=np.exp(-1.666*del_tau)
emiss=1 - trans
layer_rad=sigma*Temp_layers[layer_num]**4.*emiss
up_rad[upper_lev]=trans*up_rad[lower_lev] + layer_rad
down_rad[tot_levs-1]=0
for index in np.arange(1,tot_levs):
upper_lev=tot_levs - index
lower_lev=tot_levs - index -1
layer_num=tot_levs - index - 1
del_tau=tau_levels[upper_lev] - tau_levels[lower_lev]
trans=np.exp(-1.666*del_tau)
emiss=1 - trans
layer_rad=sigma*Temp_layers[layer_num]**4.*emiss
down_rad[lower_lev]=down_rad[upper_lev]*trans + layer_rad
return (up_rad,down_rad)
def heating_rate(net_up,height_levels,rho_layers):
"""
-TD- docstring using google style
"""
cpd=1004.
dFn_dz= -1.*np.diff(net_up)/np.diff(height_levels)
dT_dt=dFn_dz/(rho_layers*cpd)
return dT_dt
def time_step(heating_rate,Temp_layers,delta_time):
"""
-TD- docstring using google style
"""
Temp_layers[:] = Temp_layers[:] + heating_rate*delta_time
return Temp_layers
if __name__=="__main__":
tot_trans=0.2
num_layers=100
p_sfc=1000.*1.e2
p_top=100.*1.e2
g=9.8
T_sfc=300.
Rd=287. #J/kg/K
num_levels=num_layers+1
tau_levels=find_tau(tot_trans,num_layers)
press_levels=np.linspace(p_top,p_sfc,num_levels)
press_diff=np.diff(press_levels)[0]
press_levels=press_levels[::-1]
press_layers=(press_levels[1:] + press_levels[:-1])/2.
Temp_levels=np.ones([num_levels])*T_sfc
Temp_layers=(Temp_levels[1:] + Temp_levels[:-1])/2.
S0=241.
Tc=273.15
delta_time_hr=30 #time interval in hours
delta_time_sec=30*3600. #time interval in seconds
stop_time_hr=600*24. #stop time in hours
times=np.arange(0,stop_time_hr,delta_time_hr) #times in hours
tot_loops=len(times)
num_times=len(times)
#
# -TD- comment which variables are defined on levels, and which on layers
#
sfc_temp=np.empty([num_times],dtype=np.float64)
hours=np.empty_like(sfc_temp)
#
# -TD- describe what the 2-d arrays are used for
#
air_temps=np.empty([num_layers,num_times],dtype=np.float64)
up_flux_run=np.empty([num_levels,num_times],dtype=np.float64)
down_flux_run=np.empty_like(up_flux_run)
height_levels_run=np.empty_like(up_flux_run)
for index in np.arange(0,num_times):
rho_layers=press_layers/(Rd*Temp_layers)
height_levels=find_heights(press_levels,rho_layers)
up,down=fluxes(tau_levels,Temp_layers,T_sfc)
sfc_temp[index]=T_sfc
#<|fim▁hole|> #
if np.mod(index,50)==0:
the_frac=np.int(index/tot_loops*100.)
sys.stdout.write("\rpercent complete: %d%%" % the_frac)
sys.stdout.flush()
air_temps[:,index]=Temp_layers[:]
up,down=fluxes(tau_levels,Temp_layers,T_sfc)
up_flux_run[:,index]=up[:]
down_flux_run[:,index]=down[:]
height_levels_run[:,index]=height_levels[:]
dT_dt=heating_rate(up-down,height_levels,rho_layers)
Temp_layers[:]=time_step(dT_dt,Temp_layers,delta_time_sec)
#
# -TD- describe what the following statements do
#
net_downsfc=S0 + down[0]
T_sfc=(net_downsfc/sigma)**0.25
plt.close('all')
fig1,axis1=plt.subplots(1,1)
snapshots=[0,2,8,30,40,50,60,70]
days=times/24.
for the_snap in snapshots:
#
# -TD- describe what the label does
#
label="%3.1f" % days[the_snap]
height_levels=height_levels_run[:,the_snap]
layer_heights=(height_levels[1:] + height_levels[:-1])/2.
axis1.plot(air_temps[:,the_snap],layer_heights*1.e-3,label=label)
axis1.legend()
axis1.set_title('temperature profiles for {} days'.format(len(snapshots)))
axis1.set_xlabel('temperature (deg C)')
fig1.savefig("snapshots.png")
fig2,axis2=plt.subplots(1,1)
axis2.plot(days,sfc_temp-Tc)
axis2.set_title('surface temperature (deg C)')
axis2.set_ylabel('temperature (degC)')
axis2.set_xlabel('day')
axis2.set_xlim((0,100))
fig2.savefig("sfc_temp.png")
fig3,axis3=plt.subplots(1,1)
axis3.plot(days,sfc_temp - air_temps[0,:])
axis3.set_title('air-sea temperature difference (deg C)')
axis3.set_ylabel('surface - first layer temp (degC)')
axis3.set_xlabel('day')
axis3.set_xlim((0,100))
fig3.savefig("air_sea.png")
plt.show()<|fim▁end|> | # -TD- describe what this loop does |
<|file_name|>const-tuple-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>static X: Bar = Bar(1, 2);
pub fn main() {
match X {
Bar(x, y) => {
assert_eq!(x, 1);
assert_eq!(y, 2);
}
}
}<|fim▁end|> | // run-pass
struct Bar(isize, isize);
|
<|file_name|>histogram_example.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 20:47:53 2017
@author: fernando
"""
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
<|fim▁hole|>plt.style.use('ggplot')
df = pd.read_csv("/home/fernando/CoursePythonDS/DAT210x/Module3/Datasets/wheat.data")
print df.describe()
df[df.groove>5].asymmetry.plot.hist(alpha=0.3, normed=True)
df[df.groove<=5].asymmetry.plot.hist(alpha=0.5, normed=True)
plt.show()<|fim▁end|> | |
<|file_name|>infinite_emnist_test.py<|end_file_name|><|fim▁begin|># Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<|fim▁hole|># See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
import tensorflow_federated as tff
from utils.datasets import infinite_emnist
def _compute_dataset_length(dataset):
return dataset.reduce(0, lambda x, _: x + 1)
class InfiniteEmnistTest(tf.test.TestCase):
def test_element_type_structure_preserved(self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 5)
self.assertEqual(raw_client_data.element_type_structure,
inf_client_data.element_type_structure)
def test_pseudo_client_count(self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
self.assertLen(raw_client_data.client_ids, 1)
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 10)
self.assertLen(inf_client_data.client_ids, 10)
def test_first_pseudo_client_preserves_original(self):
raw_client_data = tff.simulation.datasets.emnist.get_synthetic()
inf_client_data = infinite_emnist.get_infinite(raw_client_data, 5)
raw_dataset = raw_client_data.dataset_computation(
raw_client_data.client_ids[0])
inf_dataset = inf_client_data.dataset_computation(
inf_client_data.client_ids[0])
length1 = _compute_dataset_length(raw_dataset)
length2 = _compute_dataset_length(inf_dataset)
self.assertEqual(length1, length2)
for raw_batch, inf_batch in zip(raw_dataset, inf_dataset):
self.assertAllClose(raw_batch, inf_batch)
def test_transform_modifies_data(self):
data = infinite_emnist.get_infinite(
tff.simulation.datasets.emnist.get_synthetic(), 3)
datasets = [data.dataset_computation(id) for id in data.client_ids]
lengths = [_compute_dataset_length(datasets[i]) for i in [0, 1, 2]]
self.assertEqual(lengths[0], lengths[1])
self.assertEqual(lengths[1], lengths[2])
for batch0, batch1, batch2 in zip(datasets[0], datasets[1], datasets[2]):
self.assertNotAllClose(batch0, batch1)
self.assertNotAllClose(batch1, batch2)
def test_dataset_computation_equals_create_tf_dataset(self):
synth_data = tff.simulation.datasets.emnist.get_synthetic()
data = infinite_emnist.get_infinite(synth_data, 3)
for client_id in data.client_ids:
comp_dataset = data.dataset_computation(client_id)
create_tf_dataset = data.create_tf_dataset_for_client(client_id)
for batch1, batch2 in zip(comp_dataset, create_tf_dataset):
# For some reason it appears tf.quantization.quantize_and_dequantize
# sometimes (very rarely-- on one pixel for this test) gives results
# that differ by a single bit between the serialized and the
# non-serialized versions. Hence we use atol just larger than 1 bit.
self.assertAllClose(batch1['pixels'], batch2['pixels'], atol=1.5 / 255)
if __name__ == '__main__':
tf.test.main()<|fim▁end|> | |
<|file_name|>api.go<|end_file_name|><|fim▁begin|>// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package ivs
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
const opBatchGetChannel = "BatchGetChannel"
// BatchGetChannelRequest generates a "aws/request.Request" representing the
// client's request for the BatchGetChannel operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See BatchGetChannel for more information on using the BatchGetChannel
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the BatchGetChannelRequest method.
// req, resp := client.BatchGetChannelRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/BatchGetChannel
func (c *IVS) BatchGetChannelRequest(input *BatchGetChannelInput) (req *request.Request, output *BatchGetChannelOutput) {
op := &request.Operation{
Name: opBatchGetChannel,
HTTPMethod: "POST",
HTTPPath: "/BatchGetChannel",
}
if input == nil {
input = &BatchGetChannelInput{}
}
output = &BatchGetChannelOutput{}
req = c.newRequest(op, input, output)
return
}
// BatchGetChannel API operation for Amazon Interactive Video Service.
//
// Performs GetChannel on multiple ARNs simultaneously.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation BatchGetChannel for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/BatchGetChannel
func (c *IVS) BatchGetChannel(input *BatchGetChannelInput) (*BatchGetChannelOutput, error) {
req, out := c.BatchGetChannelRequest(input)
return out, req.Send()
}
// BatchGetChannelWithContext is the same as BatchGetChannel with the addition of
// the ability to pass a context and additional request options.
//
// See BatchGetChannel for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) BatchGetChannelWithContext(ctx aws.Context, input *BatchGetChannelInput, opts ...request.Option) (*BatchGetChannelOutput, error) {
req, out := c.BatchGetChannelRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opBatchGetStreamKey = "BatchGetStreamKey"
// BatchGetStreamKeyRequest generates a "aws/request.Request" representing the
// client's request for the BatchGetStreamKey operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See BatchGetStreamKey for more information on using the BatchGetStreamKey
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the BatchGetStreamKeyRequest method.
// req, resp := client.BatchGetStreamKeyRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/BatchGetStreamKey
func (c *IVS) BatchGetStreamKeyRequest(input *BatchGetStreamKeyInput) (req *request.Request, output *BatchGetStreamKeyOutput) {
op := &request.Operation{
Name: opBatchGetStreamKey,
HTTPMethod: "POST",
HTTPPath: "/BatchGetStreamKey",
}
if input == nil {
input = &BatchGetStreamKeyInput{}
}
output = &BatchGetStreamKeyOutput{}
req = c.newRequest(op, input, output)
return
}
// BatchGetStreamKey API operation for Amazon Interactive Video Service.
//
// Performs GetStreamKey on multiple ARNs simultaneously.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation BatchGetStreamKey for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/BatchGetStreamKey
func (c *IVS) BatchGetStreamKey(input *BatchGetStreamKeyInput) (*BatchGetStreamKeyOutput, error) {
req, out := c.BatchGetStreamKeyRequest(input)
return out, req.Send()
}
// BatchGetStreamKeyWithContext is the same as BatchGetStreamKey with the addition of
// the ability to pass a context and additional request options.
//
// See BatchGetStreamKey for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) BatchGetStreamKeyWithContext(ctx aws.Context, input *BatchGetStreamKeyInput, opts ...request.Option) (*BatchGetStreamKeyOutput, error) {
req, out := c.BatchGetStreamKeyRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateChannel = "CreateChannel"
// CreateChannelRequest generates a "aws/request.Request" representing the
// client's request for the CreateChannel operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateChannel for more information on using the CreateChannel
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateChannelRequest method.
// req, resp := client.CreateChannelRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateChannel
func (c *IVS) CreateChannelRequest(input *CreateChannelInput) (req *request.Request, output *CreateChannelOutput) {
op := &request.Operation{
Name: opCreateChannel,
HTTPMethod: "POST",
HTTPPath: "/CreateChannel",
}
if input == nil {
input = &CreateChannelInput{}
}
output = &CreateChannelOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateChannel API operation for Amazon Interactive Video Service.
//
// Creates a new channel and an associated stream key to start streaming.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation CreateChannel for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ServiceQuotaExceededException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateChannel
func (c *IVS) CreateChannel(input *CreateChannelInput) (*CreateChannelOutput, error) {
req, out := c.CreateChannelRequest(input)
return out, req.Send()
}
// CreateChannelWithContext is the same as CreateChannel with the addition of
// the ability to pass a context and additional request options.
//
// See CreateChannel for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) CreateChannelWithContext(ctx aws.Context, input *CreateChannelInput, opts ...request.Option) (*CreateChannelOutput, error) {
req, out := c.CreateChannelRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateRecordingConfiguration = "CreateRecordingConfiguration"
// CreateRecordingConfigurationRequest generates a "aws/request.Request" representing the
// client's request for the CreateRecordingConfiguration operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateRecordingConfiguration for more information on using the CreateRecordingConfiguration
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateRecordingConfigurationRequest method.
// req, resp := client.CreateRecordingConfigurationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateRecordingConfiguration
func (c *IVS) CreateRecordingConfigurationRequest(input *CreateRecordingConfigurationInput) (req *request.Request, output *CreateRecordingConfigurationOutput) {
op := &request.Operation{
Name: opCreateRecordingConfiguration,
HTTPMethod: "POST",
HTTPPath: "/CreateRecordingConfiguration",
}
if input == nil {
input = &CreateRecordingConfigurationInput{}
}
output = &CreateRecordingConfigurationOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateRecordingConfiguration API operation for Amazon Interactive Video Service.
//
// Creates a new recording configuration, used to enable recording to Amazon
// S3.
//
// Known issue: In the us-east-1 region, if you use the Amazon Web Services
// CLI to create a recording configuration, it returns success even if the S3
// bucket is in a different region. In this case, the state of the recording
// configuration is CREATE_FAILED (instead of ACTIVE). (In other regions, the
// CLI correctly returns failure if the bucket is in a different region.)
//
// Workaround: Ensure that your S3 bucket is in the same region as the recording
// configuration. If you create a recording configuration in a different region
// as your S3 bucket, delete that recording configuration and create a new one
// with an S3 bucket from the correct region.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation CreateRecordingConfiguration for usage and error information.
//
// Returned Error Types:
// * InternalServerException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ConflictException
//
// * ServiceQuotaExceededException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateRecordingConfiguration
func (c *IVS) CreateRecordingConfiguration(input *CreateRecordingConfigurationInput) (*CreateRecordingConfigurationOutput, error) {
req, out := c.CreateRecordingConfigurationRequest(input)
return out, req.Send()
}
// CreateRecordingConfigurationWithContext is the same as CreateRecordingConfiguration with the addition of
// the ability to pass a context and additional request options.
//
// See CreateRecordingConfiguration for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) CreateRecordingConfigurationWithContext(ctx aws.Context, input *CreateRecordingConfigurationInput, opts ...request.Option) (*CreateRecordingConfigurationOutput, error) {
req, out := c.CreateRecordingConfigurationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateStreamKey = "CreateStreamKey"
// CreateStreamKeyRequest generates a "aws/request.Request" representing the
// client's request for the CreateStreamKey operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateStreamKey for more information on using the CreateStreamKey
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateStreamKeyRequest method.
// req, resp := client.CreateStreamKeyRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateStreamKey
func (c *IVS) CreateStreamKeyRequest(input *CreateStreamKeyInput) (req *request.Request, output *CreateStreamKeyOutput) {
op := &request.Operation{
Name: opCreateStreamKey,
HTTPMethod: "POST",
HTTPPath: "/CreateStreamKey",
}
if input == nil {
input = &CreateStreamKeyInput{}
}
output = &CreateStreamKeyOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateStreamKey API operation for Amazon Interactive Video Service.
//
// Creates a stream key, used to initiate a stream, for the specified channel
// ARN.
//
// Note that CreateChannel creates a stream key. If you subsequently use CreateStreamKey
// on the same channel, it will fail because a stream key already exists and
// there is a limit of 1 stream key per channel. To reset the stream key on
// a channel, use DeleteStreamKey and then CreateStreamKey.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation CreateStreamKey for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ServiceQuotaExceededException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/CreateStreamKey
func (c *IVS) CreateStreamKey(input *CreateStreamKeyInput) (*CreateStreamKeyOutput, error) {
req, out := c.CreateStreamKeyRequest(input)
return out, req.Send()
}
// CreateStreamKeyWithContext is the same as CreateStreamKey with the addition of
// the ability to pass a context and additional request options.
//
// See CreateStreamKey for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) CreateStreamKeyWithContext(ctx aws.Context, input *CreateStreamKeyInput, opts ...request.Option) (*CreateStreamKeyOutput, error) {
req, out := c.CreateStreamKeyRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteChannel = "DeleteChannel"
// DeleteChannelRequest generates a "aws/request.Request" representing the
// client's request for the DeleteChannel operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteChannel for more information on using the DeleteChannel
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteChannelRequest method.
// req, resp := client.DeleteChannelRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteChannel
func (c *IVS) DeleteChannelRequest(input *DeleteChannelInput) (req *request.Request, output *DeleteChannelOutput) {
op := &request.Operation{
Name: opDeleteChannel,
HTTPMethod: "POST",
HTTPPath: "/DeleteChannel",
}
if input == nil {
input = &DeleteChannelInput{}
}
output = &DeleteChannelOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// DeleteChannel API operation for Amazon Interactive Video Service.
//
// Deletes the specified channel and its associated stream keys.
//
// If you try to delete a live channel, you will get an error (409 ConflictException).
// To delete a channel that is live, call StopStream, wait for the Amazon EventBridge
// "Stream End" event (to verify that the stream's state was changed from Live
// to Offline), then call DeleteChannel. (See Using EventBridge with Amazon
// IVS (https://docs.aws.amazon.com/ivs/latest/userguide/eventbridge.html).)
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation DeleteChannel for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ConflictException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteChannel
func (c *IVS) DeleteChannel(input *DeleteChannelInput) (*DeleteChannelOutput, error) {
req, out := c.DeleteChannelRequest(input)
return out, req.Send()
}
// DeleteChannelWithContext is the same as DeleteChannel with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteChannel for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) DeleteChannelWithContext(ctx aws.Context, input *DeleteChannelInput, opts ...request.Option) (*DeleteChannelOutput, error) {
req, out := c.DeleteChannelRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeletePlaybackKeyPair = "DeletePlaybackKeyPair"
// DeletePlaybackKeyPairRequest generates a "aws/request.Request" representing the
// client's request for the DeletePlaybackKeyPair operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeletePlaybackKeyPair for more information on using the DeletePlaybackKeyPair
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeletePlaybackKeyPairRequest method.
// req, resp := client.DeletePlaybackKeyPairRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeletePlaybackKeyPair
func (c *IVS) DeletePlaybackKeyPairRequest(input *DeletePlaybackKeyPairInput) (req *request.Request, output *DeletePlaybackKeyPairOutput) {
op := &request.Operation{
Name: opDeletePlaybackKeyPair,
HTTPMethod: "POST",
HTTPPath: "/DeletePlaybackKeyPair",
}
if input == nil {
input = &DeletePlaybackKeyPairInput{}
}
output = &DeletePlaybackKeyPairOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// DeletePlaybackKeyPair API operation for Amazon Interactive Video Service.
//
// Deletes a specified authorization key pair. This invalidates future viewer
// tokens generated using the key pair’s privateKey. For more information,
// see Setting Up Private Channels (https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)
// in the Amazon IVS User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation DeletePlaybackKeyPair for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeletePlaybackKeyPair
func (c *IVS) DeletePlaybackKeyPair(input *DeletePlaybackKeyPairInput) (*DeletePlaybackKeyPairOutput, error) {
req, out := c.DeletePlaybackKeyPairRequest(input)
return out, req.Send()
}
// DeletePlaybackKeyPairWithContext is the same as DeletePlaybackKeyPair with the addition of
// the ability to pass a context and additional request options.
//
// See DeletePlaybackKeyPair for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) DeletePlaybackKeyPairWithContext(ctx aws.Context, input *DeletePlaybackKeyPairInput, opts ...request.Option) (*DeletePlaybackKeyPairOutput, error) {
req, out := c.DeletePlaybackKeyPairRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteRecordingConfiguration = "DeleteRecordingConfiguration"
// DeleteRecordingConfigurationRequest generates a "aws/request.Request" representing the
// client's request for the DeleteRecordingConfiguration operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteRecordingConfiguration for more information on using the DeleteRecordingConfiguration
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteRecordingConfigurationRequest method.
// req, resp := client.DeleteRecordingConfigurationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteRecordingConfiguration
func (c *IVS) DeleteRecordingConfigurationRequest(input *DeleteRecordingConfigurationInput) (req *request.Request, output *DeleteRecordingConfigurationOutput) {
op := &request.Operation{
Name: opDeleteRecordingConfiguration,
HTTPMethod: "POST",
HTTPPath: "/DeleteRecordingConfiguration",
}
if input == nil {
input = &DeleteRecordingConfigurationInput{}
}
output = &DeleteRecordingConfigurationOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// DeleteRecordingConfiguration API operation for Amazon Interactive Video Service.
//
// Deletes the recording configuration for the specified ARN.
//
// If you try to delete a recording configuration that is associated with a
// channel, you will get an error (409 ConflictException). To avoid this, for
// all channels that reference the recording configuration, first use UpdateChannel
// to set the recordingConfigurationArn field to an empty string, then use DeleteRecordingConfiguration.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation DeleteRecordingConfiguration for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * InternalServerException
//
// * AccessDeniedException
//
// * ValidationException
//
// * ConflictException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteRecordingConfiguration
func (c *IVS) DeleteRecordingConfiguration(input *DeleteRecordingConfigurationInput) (*DeleteRecordingConfigurationOutput, error) {
req, out := c.DeleteRecordingConfigurationRequest(input)
return out, req.Send()
}
// DeleteRecordingConfigurationWithContext is the same as DeleteRecordingConfiguration with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteRecordingConfiguration for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) DeleteRecordingConfigurationWithContext(ctx aws.Context, input *DeleteRecordingConfigurationInput, opts ...request.Option) (*DeleteRecordingConfigurationOutput, error) {
req, out := c.DeleteRecordingConfigurationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteStreamKey = "DeleteStreamKey"
// DeleteStreamKeyRequest generates a "aws/request.Request" representing the
// client's request for the DeleteStreamKey operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteStreamKey for more information on using the DeleteStreamKey
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteStreamKeyRequest method.
// req, resp := client.DeleteStreamKeyRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteStreamKey
func (c *IVS) DeleteStreamKeyRequest(input *DeleteStreamKeyInput) (req *request.Request, output *DeleteStreamKeyOutput) {
op := &request.Operation{
Name: opDeleteStreamKey,
HTTPMethod: "POST",
HTTPPath: "/DeleteStreamKey",
}
if input == nil {
input = &DeleteStreamKeyInput{}
}
output = &DeleteStreamKeyOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// DeleteStreamKey API operation for Amazon Interactive Video Service.
//
// Deletes the stream key for the specified ARN, so it can no longer be used
// to stream.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation DeleteStreamKey for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/DeleteStreamKey
func (c *IVS) DeleteStreamKey(input *DeleteStreamKeyInput) (*DeleteStreamKeyOutput, error) {
req, out := c.DeleteStreamKeyRequest(input)
return out, req.Send()
}
// DeleteStreamKeyWithContext is the same as DeleteStreamKey with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteStreamKey for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) DeleteStreamKeyWithContext(ctx aws.Context, input *DeleteStreamKeyInput, opts ...request.Option) (*DeleteStreamKeyOutput, error) {
req, out := c.DeleteStreamKeyRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetChannel = "GetChannel"
// GetChannelRequest generates a "aws/request.Request" representing the
// client's request for the GetChannel operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetChannel for more information on using the GetChannel
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetChannelRequest method.
// req, resp := client.GetChannelRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetChannel
func (c *IVS) GetChannelRequest(input *GetChannelInput) (req *request.Request, output *GetChannelOutput) {
op := &request.Operation{
Name: opGetChannel,
HTTPMethod: "POST",
HTTPPath: "/GetChannel",
}
if input == nil {
input = &GetChannelInput{}
}
output = &GetChannelOutput{}
req = c.newRequest(op, input, output)
return
}
// GetChannel API operation for Amazon Interactive Video Service.
//
// Gets the channel configuration for the specified channel ARN. See also BatchGetChannel.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetChannel for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetChannel
func (c *IVS) GetChannel(input *GetChannelInput) (*GetChannelOutput, error) {
req, out := c.GetChannelRequest(input)
return out, req.Send()
}
// GetChannelWithContext is the same as GetChannel with the addition of
// the ability to pass a context and additional request options.
//
// See GetChannel for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetChannelWithContext(ctx aws.Context, input *GetChannelInput, opts ...request.Option) (*GetChannelOutput, error) {
req, out := c.GetChannelRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetPlaybackKeyPair = "GetPlaybackKeyPair"
// GetPlaybackKeyPairRequest generates a "aws/request.Request" representing the
// client's request for the GetPlaybackKeyPair operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetPlaybackKeyPair for more information on using the GetPlaybackKeyPair
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetPlaybackKeyPairRequest method.
// req, resp := client.GetPlaybackKeyPairRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetPlaybackKeyPair
func (c *IVS) GetPlaybackKeyPairRequest(input *GetPlaybackKeyPairInput) (req *request.Request, output *GetPlaybackKeyPairOutput) {
op := &request.Operation{
Name: opGetPlaybackKeyPair,
HTTPMethod: "POST",
HTTPPath: "/GetPlaybackKeyPair",
}
if input == nil {
input = &GetPlaybackKeyPairInput{}
}
output = &GetPlaybackKeyPairOutput{}
req = c.newRequest(op, input, output)
return
}
// GetPlaybackKeyPair API operation for Amazon Interactive Video Service.
//
// Gets a specified playback authorization key pair and returns the arn and
// fingerprint. The privateKey held by the caller can be used to generate viewer
// authorization tokens, to grant viewers access to private channels. For more
// information, see Setting Up Private Channels (https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)
// in the Amazon IVS User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetPlaybackKeyPair for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetPlaybackKeyPair
func (c *IVS) GetPlaybackKeyPair(input *GetPlaybackKeyPairInput) (*GetPlaybackKeyPairOutput, error) {
req, out := c.GetPlaybackKeyPairRequest(input)
return out, req.Send()
}
// GetPlaybackKeyPairWithContext is the same as GetPlaybackKeyPair with the addition of
// the ability to pass a context and additional request options.
//
// See GetPlaybackKeyPair for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetPlaybackKeyPairWithContext(ctx aws.Context, input *GetPlaybackKeyPairInput, opts ...request.Option) (*GetPlaybackKeyPairOutput, error) {
req, out := c.GetPlaybackKeyPairRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetRecordingConfiguration = "GetRecordingConfiguration"
// GetRecordingConfigurationRequest generates a "aws/request.Request" representing the
// client's request for the GetRecordingConfiguration operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetRecordingConfiguration for more information on using the GetRecordingConfiguration
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetRecordingConfigurationRequest method.
// req, resp := client.GetRecordingConfigurationRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetRecordingConfiguration
func (c *IVS) GetRecordingConfigurationRequest(input *GetRecordingConfigurationInput) (req *request.Request, output *GetRecordingConfigurationOutput) {
op := &request.Operation{
Name: opGetRecordingConfiguration,
HTTPMethod: "POST",
HTTPPath: "/GetRecordingConfiguration",
}
if input == nil {
input = &GetRecordingConfigurationInput{}
}
output = &GetRecordingConfigurationOutput{}
req = c.newRequest(op, input, output)
return
}
// GetRecordingConfiguration API operation for Amazon Interactive Video Service.
//
// Gets the recording configuration for the specified ARN.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetRecordingConfiguration for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * InternalServerException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetRecordingConfiguration
func (c *IVS) GetRecordingConfiguration(input *GetRecordingConfigurationInput) (*GetRecordingConfigurationOutput, error) {
req, out := c.GetRecordingConfigurationRequest(input)
return out, req.Send()
}
// GetRecordingConfigurationWithContext is the same as GetRecordingConfiguration with the addition of
// the ability to pass a context and additional request options.
//
// See GetRecordingConfiguration for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetRecordingConfigurationWithContext(ctx aws.Context, input *GetRecordingConfigurationInput, opts ...request.Option) (*GetRecordingConfigurationOutput, error) {
req, out := c.GetRecordingConfigurationRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetStream = "GetStream"
// GetStreamRequest generates a "aws/request.Request" representing the
// client's request for the GetStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetStream for more information on using the GetStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetStreamRequest method.
// req, resp := client.GetStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStream
func (c *IVS) GetStreamRequest(input *GetStreamInput) (req *request.Request, output *GetStreamOutput) {
op := &request.Operation{
Name: opGetStream,
HTTPMethod: "POST",
HTTPPath: "/GetStream",
}
if input == nil {
input = &GetStreamInput{}
}
output = &GetStreamOutput{}
req = c.newRequest(op, input, output)
return
}
// GetStream API operation for Amazon Interactive Video Service.
//
// Gets information about the active (live) stream on a specified channel.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetStream for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * ChannelNotBroadcasting
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStream
func (c *IVS) GetStream(input *GetStreamInput) (*GetStreamOutput, error) {
req, out := c.GetStreamRequest(input)
return out, req.Send()
}
// GetStreamWithContext is the same as GetStream with the addition of
// the ability to pass a context and additional request options.
//
// See GetStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetStreamWithContext(ctx aws.Context, input *GetStreamInput, opts ...request.Option) (*GetStreamOutput, error) {
req, out := c.GetStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetStreamKey = "GetStreamKey"
// GetStreamKeyRequest generates a "aws/request.Request" representing the
// client's request for the GetStreamKey operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetStreamKey for more information on using the GetStreamKey
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetStreamKeyRequest method.
// req, resp := client.GetStreamKeyRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStreamKey
func (c *IVS) GetStreamKeyRequest(input *GetStreamKeyInput) (req *request.Request, output *GetStreamKeyOutput) {
op := &request.Operation{
Name: opGetStreamKey,
HTTPMethod: "POST",
HTTPPath: "/GetStreamKey",
}
if input == nil {
input = &GetStreamKeyInput{}
}
output = &GetStreamKeyOutput{}
req = c.newRequest(op, input, output)
return
}
// GetStreamKey API operation for Amazon Interactive Video Service.
//
// Gets stream-key information for a specified ARN.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetStreamKey for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStreamKey
func (c *IVS) GetStreamKey(input *GetStreamKeyInput) (*GetStreamKeyOutput, error) {
req, out := c.GetStreamKeyRequest(input)
return out, req.Send()
}
// GetStreamKeyWithContext is the same as GetStreamKey with the addition of
// the ability to pass a context and additional request options.
//
// See GetStreamKey for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetStreamKeyWithContext(ctx aws.Context, input *GetStreamKeyInput, opts ...request.Option) (*GetStreamKeyOutput, error) {
req, out := c.GetStreamKeyRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetStreamSession = "GetStreamSession"
// GetStreamSessionRequest generates a "aws/request.Request" representing the
// client's request for the GetStreamSession operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetStreamSession for more information on using the GetStreamSession
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetStreamSessionRequest method.
// req, resp := client.GetStreamSessionRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStreamSession
func (c *IVS) GetStreamSessionRequest(input *GetStreamSessionInput) (req *request.Request, output *GetStreamSessionOutput) {
op := &request.Operation{
Name: opGetStreamSession,
HTTPMethod: "POST",
HTTPPath: "/GetStreamSession",
}
if input == nil {
input = &GetStreamSessionInput{}
}
output = &GetStreamSessionOutput{}
req = c.newRequest(op, input, output)
return
}
// GetStreamSession API operation for Amazon Interactive Video Service.
//
// Gets metadata on a specified stream.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation GetStreamSession for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/GetStreamSession
func (c *IVS) GetStreamSession(input *GetStreamSessionInput) (*GetStreamSessionOutput, error) {
req, out := c.GetStreamSessionRequest(input)
return out, req.Send()
}
// GetStreamSessionWithContext is the same as GetStreamSession with the addition of
// the ability to pass a context and additional request options.
//
// See GetStreamSession for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) GetStreamSessionWithContext(ctx aws.Context, input *GetStreamSessionInput, opts ...request.Option) (*GetStreamSessionOutput, error) {
req, out := c.GetStreamSessionRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opImportPlaybackKeyPair = "ImportPlaybackKeyPair"
// ImportPlaybackKeyPairRequest generates a "aws/request.Request" representing the
// client's request for the ImportPlaybackKeyPair operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ImportPlaybackKeyPair for more information on using the ImportPlaybackKeyPair
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ImportPlaybackKeyPairRequest method.
// req, resp := client.ImportPlaybackKeyPairRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ImportPlaybackKeyPair
func (c *IVS) ImportPlaybackKeyPairRequest(input *ImportPlaybackKeyPairInput) (req *request.Request, output *ImportPlaybackKeyPairOutput) {
op := &request.Operation{
Name: opImportPlaybackKeyPair,
HTTPMethod: "POST",
HTTPPath: "/ImportPlaybackKeyPair",
}
if input == nil {
input = &ImportPlaybackKeyPairInput{}
}
output = &ImportPlaybackKeyPairOutput{}
req = c.newRequest(op, input, output)
return
}
// ImportPlaybackKeyPair API operation for Amazon Interactive Video Service.
//
// Imports the public portion of a new key pair and returns its arn and fingerprint.
// The privateKey can then be used to generate viewer authorization tokens,
// to grant viewers access to private channels. For more information, see Setting
// Up Private Channels (https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)
// in the Amazon IVS User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ImportPlaybackKeyPair for usage and error information.
//
// Returned Error Types:
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ConflictException
//
// * ServiceQuotaExceededException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ImportPlaybackKeyPair
func (c *IVS) ImportPlaybackKeyPair(input *ImportPlaybackKeyPairInput) (*ImportPlaybackKeyPairOutput, error) {
req, out := c.ImportPlaybackKeyPairRequest(input)
return out, req.Send()
}
// ImportPlaybackKeyPairWithContext is the same as ImportPlaybackKeyPair with the addition of
// the ability to pass a context and additional request options.
//
// See ImportPlaybackKeyPair for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ImportPlaybackKeyPairWithContext(ctx aws.Context, input *ImportPlaybackKeyPairInput, opts ...request.Option) (*ImportPlaybackKeyPairOutput, error) {
req, out := c.ImportPlaybackKeyPairRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opListChannels = "ListChannels"
// ListChannelsRequest generates a "aws/request.Request" representing the
// client's request for the ListChannels operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListChannels for more information on using the ListChannels
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListChannelsRequest method.
// req, resp := client.ListChannelsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListChannels
func (c *IVS) ListChannelsRequest(input *ListChannelsInput) (req *request.Request, output *ListChannelsOutput) {
op := &request.Operation{
Name: opListChannels,
HTTPMethod: "POST",
HTTPPath: "/ListChannels",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListChannelsInput{}
}
output = &ListChannelsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListChannels API operation for Amazon Interactive Video Service.
//
// Gets summary information about all channels in your account, in the Amazon
// Web Services region where the API request is processed. This list can be
// filtered to match a specified name or recording-configuration ARN. Filters
// are mutually exclusive and cannot be used together. If you try to use both
// filters, you will get an error (409 ConflictException).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListChannels for usage and error information.
//
// Returned Error Types:
// * AccessDeniedException
//
// * ValidationException
//
// * ConflictException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListChannels
func (c *IVS) ListChannels(input *ListChannelsInput) (*ListChannelsOutput, error) {
req, out := c.ListChannelsRequest(input)
return out, req.Send()
}
// ListChannelsWithContext is the same as ListChannels with the addition of
// the ability to pass a context and additional request options.
//
// See ListChannels for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListChannelsWithContext(ctx aws.Context, input *ListChannelsInput, opts ...request.Option) (*ListChannelsOutput, error) {
req, out := c.ListChannelsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListChannelsPages iterates over the pages of a ListChannels operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListChannels method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListChannels operation.
// pageNum := 0
// err := client.ListChannelsPages(params,
// func(page *ivs.ListChannelsOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListChannelsPages(input *ListChannelsInput, fn func(*ListChannelsOutput, bool) bool) error {
return c.ListChannelsPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListChannelsPagesWithContext same as ListChannelsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListChannelsPagesWithContext(ctx aws.Context, input *ListChannelsInput, fn func(*ListChannelsOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListChannelsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListChannelsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListChannelsOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListPlaybackKeyPairs = "ListPlaybackKeyPairs"
// ListPlaybackKeyPairsRequest generates a "aws/request.Request" representing the
// client's request for the ListPlaybackKeyPairs operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListPlaybackKeyPairs for more information on using the ListPlaybackKeyPairs
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListPlaybackKeyPairsRequest method.
// req, resp := client.ListPlaybackKeyPairsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListPlaybackKeyPairs
func (c *IVS) ListPlaybackKeyPairsRequest(input *ListPlaybackKeyPairsInput) (req *request.Request, output *ListPlaybackKeyPairsOutput) {
op := &request.Operation{
Name: opListPlaybackKeyPairs,
HTTPMethod: "POST",
HTTPPath: "/ListPlaybackKeyPairs",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListPlaybackKeyPairsInput{}
}
output = &ListPlaybackKeyPairsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListPlaybackKeyPairs API operation for Amazon Interactive Video Service.
//
// Gets summary information about playback key pairs. For more information,
// see Setting Up Private Channels (https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)
// in the Amazon IVS User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListPlaybackKeyPairs for usage and error information.
//
// Returned Error Types:
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListPlaybackKeyPairs
func (c *IVS) ListPlaybackKeyPairs(input *ListPlaybackKeyPairsInput) (*ListPlaybackKeyPairsOutput, error) {
req, out := c.ListPlaybackKeyPairsRequest(input)
return out, req.Send()
}
// ListPlaybackKeyPairsWithContext is the same as ListPlaybackKeyPairs with the addition of
// the ability to pass a context and additional request options.
//
// See ListPlaybackKeyPairs for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListPlaybackKeyPairsWithContext(ctx aws.Context, input *ListPlaybackKeyPairsInput, opts ...request.Option) (*ListPlaybackKeyPairsOutput, error) {
req, out := c.ListPlaybackKeyPairsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListPlaybackKeyPairsPages iterates over the pages of a ListPlaybackKeyPairs operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListPlaybackKeyPairs method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListPlaybackKeyPairs operation.
// pageNum := 0
// err := client.ListPlaybackKeyPairsPages(params,
// func(page *ivs.ListPlaybackKeyPairsOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListPlaybackKeyPairsPages(input *ListPlaybackKeyPairsInput, fn func(*ListPlaybackKeyPairsOutput, bool) bool) error {
return c.ListPlaybackKeyPairsPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListPlaybackKeyPairsPagesWithContext same as ListPlaybackKeyPairsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListPlaybackKeyPairsPagesWithContext(ctx aws.Context, input *ListPlaybackKeyPairsInput, fn func(*ListPlaybackKeyPairsOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListPlaybackKeyPairsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListPlaybackKeyPairsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListPlaybackKeyPairsOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListRecordingConfigurations = "ListRecordingConfigurations"
// ListRecordingConfigurationsRequest generates a "aws/request.Request" representing the
// client's request for the ListRecordingConfigurations operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListRecordingConfigurations for more information on using the ListRecordingConfigurations
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListRecordingConfigurationsRequest method.
// req, resp := client.ListRecordingConfigurationsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListRecordingConfigurations
func (c *IVS) ListRecordingConfigurationsRequest(input *ListRecordingConfigurationsInput) (req *request.Request, output *ListRecordingConfigurationsOutput) {
op := &request.Operation{
Name: opListRecordingConfigurations,
HTTPMethod: "POST",
HTTPPath: "/ListRecordingConfigurations",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListRecordingConfigurationsInput{}
}
output = &ListRecordingConfigurationsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListRecordingConfigurations API operation for Amazon Interactive Video Service.
//
// Gets summary information about all recording configurations in your account,
// in the Amazon Web Services region where the API request is processed.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListRecordingConfigurations for usage and error information.
//
// Returned Error Types:
// * InternalServerException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListRecordingConfigurations
func (c *IVS) ListRecordingConfigurations(input *ListRecordingConfigurationsInput) (*ListRecordingConfigurationsOutput, error) {
req, out := c.ListRecordingConfigurationsRequest(input)
return out, req.Send()
}
// ListRecordingConfigurationsWithContext is the same as ListRecordingConfigurations with the addition of
// the ability to pass a context and additional request options.
//
// See ListRecordingConfigurations for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListRecordingConfigurationsWithContext(ctx aws.Context, input *ListRecordingConfigurationsInput, opts ...request.Option) (*ListRecordingConfigurationsOutput, error) {
req, out := c.ListRecordingConfigurationsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListRecordingConfigurationsPages iterates over the pages of a ListRecordingConfigurations operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListRecordingConfigurations method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListRecordingConfigurations operation.
// pageNum := 0
// err := client.ListRecordingConfigurationsPages(params,
// func(page *ivs.ListRecordingConfigurationsOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListRecordingConfigurationsPages(input *ListRecordingConfigurationsInput, fn func(*ListRecordingConfigurationsOutput, bool) bool) error {
return c.ListRecordingConfigurationsPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListRecordingConfigurationsPagesWithContext same as ListRecordingConfigurationsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListRecordingConfigurationsPagesWithContext(ctx aws.Context, input *ListRecordingConfigurationsInput, fn func(*ListRecordingConfigurationsOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListRecordingConfigurationsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListRecordingConfigurationsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListRecordingConfigurationsOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListStreamKeys = "ListStreamKeys"
// ListStreamKeysRequest generates a "aws/request.Request" representing the
// client's request for the ListStreamKeys operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListStreamKeys for more information on using the ListStreamKeys
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListStreamKeysRequest method.
// req, resp := client.ListStreamKeysRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreamKeys
func (c *IVS) ListStreamKeysRequest(input *ListStreamKeysInput) (req *request.Request, output *ListStreamKeysOutput) {
op := &request.Operation{
Name: opListStreamKeys,
HTTPMethod: "POST",
HTTPPath: "/ListStreamKeys",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListStreamKeysInput{}
}
output = &ListStreamKeysOutput{}
req = c.newRequest(op, input, output)
return
}
// ListStreamKeys API operation for Amazon Interactive Video Service.
//
// Gets summary information about stream keys for the specified channel.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListStreamKeys for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreamKeys
func (c *IVS) ListStreamKeys(input *ListStreamKeysInput) (*ListStreamKeysOutput, error) {
req, out := c.ListStreamKeysRequest(input)
return out, req.Send()
}
// ListStreamKeysWithContext is the same as ListStreamKeys with the addition of
// the ability to pass a context and additional request options.
//
// See ListStreamKeys for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamKeysWithContext(ctx aws.Context, input *ListStreamKeysInput, opts ...request.Option) (*ListStreamKeysOutput, error) {
req, out := c.ListStreamKeysRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListStreamKeysPages iterates over the pages of a ListStreamKeys operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListStreamKeys method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListStreamKeys operation.
// pageNum := 0
// err := client.ListStreamKeysPages(params,
// func(page *ivs.ListStreamKeysOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListStreamKeysPages(input *ListStreamKeysInput, fn func(*ListStreamKeysOutput, bool) bool) error {
return c.ListStreamKeysPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListStreamKeysPagesWithContext same as ListStreamKeysPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamKeysPagesWithContext(ctx aws.Context, input *ListStreamKeysInput, fn func(*ListStreamKeysOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListStreamKeysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListStreamKeysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListStreamKeysOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListStreamSessions = "ListStreamSessions"
// ListStreamSessionsRequest generates a "aws/request.Request" representing the
// client's request for the ListStreamSessions operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListStreamSessions for more information on using the ListStreamSessions
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListStreamSessionsRequest method.
// req, resp := client.ListStreamSessionsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreamSessions
func (c *IVS) ListStreamSessionsRequest(input *ListStreamSessionsInput) (req *request.Request, output *ListStreamSessionsOutput) {
op := &request.Operation{
Name: opListStreamSessions,
HTTPMethod: "POST",
HTTPPath: "/ListStreamSessions",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListStreamSessionsInput{}
}
output = &ListStreamSessionsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListStreamSessions API operation for Amazon Interactive Video Service.
//
// Gets a summary of current and previous streams for a specified channel in
// your account, in the AWS region where the API request is processed.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListStreamSessions for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreamSessions
func (c *IVS) ListStreamSessions(input *ListStreamSessionsInput) (*ListStreamSessionsOutput, error) {
req, out := c.ListStreamSessionsRequest(input)
return out, req.Send()
}
// ListStreamSessionsWithContext is the same as ListStreamSessions with the addition of
// the ability to pass a context and additional request options.
//
// See ListStreamSessions for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamSessionsWithContext(ctx aws.Context, input *ListStreamSessionsInput, opts ...request.Option) (*ListStreamSessionsOutput, error) {
req, out := c.ListStreamSessionsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListStreamSessionsPages iterates over the pages of a ListStreamSessions operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListStreamSessions method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListStreamSessions operation.
// pageNum := 0
// err := client.ListStreamSessionsPages(params,
// func(page *ivs.ListStreamSessionsOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListStreamSessionsPages(input *ListStreamSessionsInput, fn func(*ListStreamSessionsOutput, bool) bool) error {
return c.ListStreamSessionsPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListStreamSessionsPagesWithContext same as ListStreamSessionsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamSessionsPagesWithContext(ctx aws.Context, input *ListStreamSessionsInput, fn func(*ListStreamSessionsOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListStreamSessionsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListStreamSessionsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListStreamSessionsOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListStreams = "ListStreams"
// ListStreamsRequest generates a "aws/request.Request" representing the
// client's request for the ListStreams operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListStreams for more information on using the ListStreams
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListStreamsRequest method.
// req, resp := client.ListStreamsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreams
func (c *IVS) ListStreamsRequest(input *ListStreamsInput) (req *request.Request, output *ListStreamsOutput) {
op := &request.Operation{
Name: opListStreams,
HTTPMethod: "POST",
HTTPPath: "/ListStreams",
Paginator: &request.Paginator{
InputTokens: []string{"nextToken"},
OutputTokens: []string{"nextToken"},
LimitToken: "maxResults",
TruncationToken: "",
},
}
if input == nil {
input = &ListStreamsInput{}
}
output = &ListStreamsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListStreams API operation for Amazon Interactive Video Service.
//
// Gets summary information about live streams in your account, in the Amazon
// Web Services region where the API request is processed.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListStreams for usage and error information.
//
// Returned Error Types:
// * AccessDeniedException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListStreams
func (c *IVS) ListStreams(input *ListStreamsInput) (*ListStreamsOutput, error) {
req, out := c.ListStreamsRequest(input)
return out, req.Send()
}
// ListStreamsWithContext is the same as ListStreams with the addition of
// the ability to pass a context and additional request options.
//
// See ListStreams for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamsWithContext(ctx aws.Context, input *ListStreamsInput, opts ...request.Option) (*ListStreamsOutput, error) {
req, out := c.ListStreamsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// ListStreamsPages iterates over the pages of a ListStreams operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListStreams method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over at most 3 pages of a ListStreams operation.
// pageNum := 0
// err := client.ListStreamsPages(params,
// func(page *ivs.ListStreamsOutput, lastPage bool) bool {
// pageNum++
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *IVS) ListStreamsPages(input *ListStreamsInput, fn func(*ListStreamsOutput, bool) bool) error {
return c.ListStreamsPagesWithContext(aws.BackgroundContext(), input, fn)
}
// ListStreamsPagesWithContext same as ListStreamsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListStreamsPagesWithContext(ctx aws.Context, input *ListStreamsInput, fn func(*ListStreamsOutput, bool) bool, opts ...request.Option) error {
p := request.Pagination{
NewRequest: func() (*request.Request, error) {
var inCpy *ListStreamsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.ListStreamsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
for p.Next() {
if !fn(p.Page().(*ListStreamsOutput), !p.HasNextPage()) {
break
}
}
return p.Err()
}
const opListTagsForResource = "ListTagsForResource"
// ListTagsForResourceRequest generates a "aws/request.Request" representing the
// client's request for the ListTagsForResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListTagsForResource for more information on using the ListTagsForResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListTagsForResourceRequest method.
// req, resp := client.ListTagsForResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListTagsForResource
func (c *IVS) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) {
op := &request.Operation{
Name: opListTagsForResource,
HTTPMethod: "GET",
HTTPPath: "/tags/{resourceArn}",
}
if input == nil {
input = &ListTagsForResourceInput{}
}
output = &ListTagsForResourceOutput{}
req = c.newRequest(op, input, output)
return
}
// ListTagsForResource API operation for Amazon Interactive Video Service.
//
// Gets information about Amazon Web Services tags for the specified ARN.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation ListTagsForResource for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * InternalServerException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/ListTagsForResource
func (c *IVS) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) {
req, out := c.ListTagsForResourceRequest(input)
return out, req.Send()
}
// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of
// the ability to pass a context and additional request options.
//
// See ListTagsForResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) {
req, out := c.ListTagsForResourceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opPutMetadata = "PutMetadata"
// PutMetadataRequest generates a "aws/request.Request" representing the
// client's request for the PutMetadata operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See PutMetadata for more information on using the PutMetadata
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the PutMetadataRequest method.
// req, resp := client.PutMetadataRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/PutMetadata
func (c *IVS) PutMetadataRequest(input *PutMetadataInput) (req *request.Request, output *PutMetadataOutput) {
op := &request.Operation{
Name: opPutMetadata,
HTTPMethod: "POST",
HTTPPath: "/PutMetadata",
}
if input == nil {
input = &PutMetadataInput{}
}
output = &PutMetadataOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// PutMetadata API operation for Amazon Interactive Video Service.
//
// Inserts metadata into the active stream of the specified channel. At most
// 5 requests per second per channel are allowed, each with a maximum 1 KB payload.
// (If 5 TPS is not sufficient for your needs, we recommend batching your data
// into a single PutMetadata call.) At most 155 requests per second per account
// are allowed. Also see Embedding Metadata within a Video Stream (https://docs.aws.amazon.com/ivs/latest/userguide/metadata.html)
// in the Amazon IVS User Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation PutMetadata for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * ChannelNotBroadcasting
//
// * ThrottlingException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/PutMetadata
func (c *IVS) PutMetadata(input *PutMetadataInput) (*PutMetadataOutput, error) {
req, out := c.PutMetadataRequest(input)
return out, req.Send()
}
// PutMetadataWithContext is the same as PutMetadata with the addition of
// the ability to pass a context and additional request options.
//
// See PutMetadata for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) PutMetadataWithContext(ctx aws.Context, input *PutMetadataInput, opts ...request.Option) (*PutMetadataOutput, error) {
req, out := c.PutMetadataRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opStopStream = "StopStream"
// StopStreamRequest generates a "aws/request.Request" representing the
// client's request for the StopStream operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See StopStream for more information on using the StopStream
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the StopStreamRequest method.
// req, resp := client.StopStreamRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/StopStream
func (c *IVS) StopStreamRequest(input *StopStreamInput) (req *request.Request, output *StopStreamOutput) {
op := &request.Operation{
Name: opStopStream,
HTTPMethod: "POST",
HTTPPath: "/StopStream",
}
if input == nil {
input = &StopStreamInput{}
}
output = &StopStreamOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// StopStream API operation for Amazon Interactive Video Service.
//
// Disconnects the incoming RTMPS stream for the specified channel. Can be used
// in conjunction with DeleteStreamKey to prevent further streaming to a channel.
//
// Many streaming client-software libraries automatically reconnect a dropped
// RTMPS session, so to stop the stream permanently, you may want to first revoke
// the streamKey attached to the channel.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation StopStream for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * ChannelNotBroadcasting
//
// * StreamUnavailable
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/StopStream
func (c *IVS) StopStream(input *StopStreamInput) (*StopStreamOutput, error) {
req, out := c.StopStreamRequest(input)
return out, req.Send()
}
// StopStreamWithContext is the same as StopStream with the addition of
// the ability to pass a context and additional request options.
//
// See StopStream for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) StopStreamWithContext(ctx aws.Context, input *StopStreamInput, opts ...request.Option) (*StopStreamOutput, error) {
req, out := c.StopStreamRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opTagResource = "TagResource"
// TagResourceRequest generates a "aws/request.Request" representing the
// client's request for the TagResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TagResource for more information on using the TagResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TagResourceRequest method.
// req, resp := client.TagResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/TagResource
func (c *IVS) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) {
op := &request.Operation{
Name: opTagResource,
HTTPMethod: "POST",
HTTPPath: "/tags/{resourceArn}",
}
if input == nil {
input = &TagResourceInput{}
}
output = &TagResourceOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// TagResource API operation for Amazon Interactive Video Service.
//
// Adds or updates tags for the Amazon Web Services resource with the specified
// ARN.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation TagResource for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * InternalServerException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/TagResource
func (c *IVS) TagResource(input *TagResourceInput) (*TagResourceOutput, error) {
req, out := c.TagResourceRequest(input)
return out, req.Send()
}
// TagResourceWithContext is the same as TagResource with the addition of
// the ability to pass a context and additional request options.
//
// See TagResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) {<|fim▁hole|> req.ApplyOptions(opts...)
return out, req.Send()
}
const opUntagResource = "UntagResource"
// UntagResourceRequest generates a "aws/request.Request" representing the
// client's request for the UntagResource operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UntagResource for more information on using the UntagResource
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UntagResourceRequest method.
// req, resp := client.UntagResourceRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/UntagResource
func (c *IVS) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) {
op := &request.Operation{
Name: opUntagResource,
HTTPMethod: "DELETE",
HTTPPath: "/tags/{resourceArn}",
}
if input == nil {
input = &UntagResourceInput{}
}
output = &UntagResourceOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler)
return
}
// UntagResource API operation for Amazon Interactive Video Service.
//
// Removes tags from the resource with the specified ARN.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation UntagResource for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * InternalServerException
//
// * ValidationException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/UntagResource
func (c *IVS) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) {
req, out := c.UntagResourceRequest(input)
return out, req.Send()
}
// UntagResourceWithContext is the same as UntagResource with the addition of
// the ability to pass a context and additional request options.
//
// See UntagResource for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) {
req, out := c.UntagResourceRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUpdateChannel = "UpdateChannel"
// UpdateChannelRequest generates a "aws/request.Request" representing the
// client's request for the UpdateChannel operation. The "output" return
// value will be populated with the request's response once the request completes
// successfully.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateChannel for more information on using the UpdateChannel
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UpdateChannelRequest method.
// req, resp := client.UpdateChannelRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/UpdateChannel
func (c *IVS) UpdateChannelRequest(input *UpdateChannelInput) (req *request.Request, output *UpdateChannelOutput) {
op := &request.Operation{
Name: opUpdateChannel,
HTTPMethod: "POST",
HTTPPath: "/UpdateChannel",
}
if input == nil {
input = &UpdateChannelInput{}
}
output = &UpdateChannelOutput{}
req = c.newRequest(op, input, output)
return
}
// UpdateChannel API operation for Amazon Interactive Video Service.
//
// Updates a channel's configuration. This does not affect an ongoing stream
// of this channel. You must stop and restart the stream for the changes to
// take effect.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Interactive Video Service's
// API operation UpdateChannel for usage and error information.
//
// Returned Error Types:
// * ResourceNotFoundException
//
// * AccessDeniedException
//
// * ValidationException
//
// * PendingVerification
//
// * ConflictException
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/ivs-2020-07-14/UpdateChannel
func (c *IVS) UpdateChannel(input *UpdateChannelInput) (*UpdateChannelOutput, error) {
req, out := c.UpdateChannelRequest(input)
return out, req.Send()
}
// UpdateChannelWithContext is the same as UpdateChannel with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateChannel for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *IVS) UpdateChannelWithContext(ctx aws.Context, input *UpdateChannelInput, opts ...request.Option) (*UpdateChannelOutput, error) {
req, out := c.UpdateChannelRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
type AccessDeniedException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// User does not have sufficient access to perform this action.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccessDeniedException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccessDeniedException) GoString() string {
return s.String()
}
func newErrorAccessDeniedException(v protocol.ResponseMetadata) error {
return &AccessDeniedException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *AccessDeniedException) Code() string {
return "AccessDeniedException"
}
// Message returns the exception's message.
func (s *AccessDeniedException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *AccessDeniedException) OrigErr() error {
return nil
}
func (s *AccessDeniedException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *AccessDeniedException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *AccessDeniedException) RequestID() string {
return s.RespMetadata.RequestID
}
// Object specifying a stream’s audio configuration.
type AudioConfiguration struct {
_ struct{} `type:"structure"`
// Number of audio channels.
Channels *int64 `locationName:"channels" type:"long"`
// Codec used for the audio encoding.
Codec *string `locationName:"codec" type:"string"`
// Number of audio samples recorded per second.
SampleRate *int64 `locationName:"sampleRate" type:"long"`
// The expected ingest bitrate (bits per second). This is configured in the
// encoder.
TargetBitrate *int64 `locationName:"targetBitrate" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AudioConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AudioConfiguration) GoString() string {
return s.String()
}
// SetChannels sets the Channels field's value.
func (s *AudioConfiguration) SetChannels(v int64) *AudioConfiguration {
s.Channels = &v
return s
}
// SetCodec sets the Codec field's value.
func (s *AudioConfiguration) SetCodec(v string) *AudioConfiguration {
s.Codec = &v
return s
}
// SetSampleRate sets the SampleRate field's value.
func (s *AudioConfiguration) SetSampleRate(v int64) *AudioConfiguration {
s.SampleRate = &v
return s
}
// SetTargetBitrate sets the TargetBitrate field's value.
func (s *AudioConfiguration) SetTargetBitrate(v int64) *AudioConfiguration {
s.TargetBitrate = &v
return s
}
// Error related to a specific channel, specified by its ARN.
type BatchError struct {
_ struct{} `type:"structure"`
// Channel ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Error code.
Code *string `locationName:"code" type:"string"`
// Error message, determined by the application.
Message *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchError) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchError) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *BatchError) SetArn(v string) *BatchError {
s.Arn = &v
return s
}
// SetCode sets the Code field's value.
func (s *BatchError) SetCode(v string) *BatchError {
s.Code = &v
return s
}
// SetMessage sets the Message field's value.
func (s *BatchError) SetMessage(v string) *BatchError {
s.Message = &v
return s
}
type BatchGetChannelInput struct {
_ struct{} `type:"structure"`
// Array of ARNs, one per channel.
//
// Arns is a required field
Arns []*string `locationName:"arns" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetChannelInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetChannelInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *BatchGetChannelInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "BatchGetChannelInput"}
if s.Arns == nil {
invalidParams.Add(request.NewErrParamRequired("Arns"))
}
if s.Arns != nil && len(s.Arns) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arns", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArns sets the Arns field's value.
func (s *BatchGetChannelInput) SetArns(v []*string) *BatchGetChannelInput {
s.Arns = v
return s
}
type BatchGetChannelOutput struct {
_ struct{} `type:"structure"`
Channels []*Channel `locationName:"channels" type:"list"`
// Each error object is related to a specific ARN in the request.
Errors []*BatchError `locationName:"errors" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetChannelOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetChannelOutput) GoString() string {
return s.String()
}
// SetChannels sets the Channels field's value.
func (s *BatchGetChannelOutput) SetChannels(v []*Channel) *BatchGetChannelOutput {
s.Channels = v
return s
}
// SetErrors sets the Errors field's value.
func (s *BatchGetChannelOutput) SetErrors(v []*BatchError) *BatchGetChannelOutput {
s.Errors = v
return s
}
type BatchGetStreamKeyInput struct {
_ struct{} `type:"structure"`
// Array of ARNs, one per channel.
//
// Arns is a required field
Arns []*string `locationName:"arns" min:"1" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetStreamKeyInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetStreamKeyInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *BatchGetStreamKeyInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "BatchGetStreamKeyInput"}
if s.Arns == nil {
invalidParams.Add(request.NewErrParamRequired("Arns"))
}
if s.Arns != nil && len(s.Arns) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arns", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArns sets the Arns field's value.
func (s *BatchGetStreamKeyInput) SetArns(v []*string) *BatchGetStreamKeyInput {
s.Arns = v
return s
}
type BatchGetStreamKeyOutput struct {
_ struct{} `type:"structure"`
Errors []*BatchError `locationName:"errors" type:"list"`
StreamKeys []*StreamKey `locationName:"streamKeys" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetStreamKeyOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s BatchGetStreamKeyOutput) GoString() string {
return s.String()
}
// SetErrors sets the Errors field's value.
func (s *BatchGetStreamKeyOutput) SetErrors(v []*BatchError) *BatchGetStreamKeyOutput {
s.Errors = v
return s
}
// SetStreamKeys sets the StreamKeys field's value.
func (s *BatchGetStreamKeyOutput) SetStreamKeys(v []*StreamKey) *BatchGetStreamKeyOutput {
s.StreamKeys = v
return s
}
// Object specifying a channel.
type Channel struct {
_ struct{} `type:"structure"`
// Channel ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Whether the channel is private (enabled for playback authorization). Default:
// false.
Authorized *bool `locationName:"authorized" type:"boolean"`
// Channel ingest endpoint, part of the definition of an ingest server, used
// when you set up streaming software.
IngestEndpoint *string `locationName:"ingestEndpoint" type:"string"`
// Channel latency mode. Use NORMAL to broadcast and deliver live video up to
// Full HD. Use LOW for near-real-time interaction with viewers. Default: LOW.
// (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low
// and Standard, respectively.)
LatencyMode *string `locationName:"latencyMode" type:"string" enum:"ChannelLatencyMode"`
// Channel name.
Name *string `locationName:"name" type:"string"`
// Channel playback URL.
PlaybackUrl *string `locationName:"playbackUrl" type:"string"`
// Recording-configuration ARN. A value other than an empty string indicates
// that recording is enabled. Default: "" (empty string, recording is disabled).
RecordingConfigurationArn *string `locationName:"recordingConfigurationArn" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
// Channel type, which determines the allowable resolution and bitrate. If you
// exceed the allowable resolution or bitrate, the stream probably will disconnect
// immediately. Default: STANDARD. Valid values:
//
// * STANDARD: Multiple qualities are generated from the original input,
// to automatically give viewers the best experience for their devices and
// network conditions. Resolution can be up to 1080p and bitrate can be up
// to 8.5 Mbps. Audio is transcoded only for renditions 360p and below; above
// that, audio is passed through.
//
// * BASIC: Amazon IVS delivers the original input to viewers. The viewer’s
// video-quality choice is limited to the original input. Resolution can
// be up to 480p and bitrate can be up to 1.5 Mbps.
Type *string `locationName:"type" type:"string" enum:"ChannelType"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Channel) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Channel) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *Channel) SetArn(v string) *Channel {
s.Arn = &v
return s
}
// SetAuthorized sets the Authorized field's value.
func (s *Channel) SetAuthorized(v bool) *Channel {
s.Authorized = &v
return s
}
// SetIngestEndpoint sets the IngestEndpoint field's value.
func (s *Channel) SetIngestEndpoint(v string) *Channel {
s.IngestEndpoint = &v
return s
}
// SetLatencyMode sets the LatencyMode field's value.
func (s *Channel) SetLatencyMode(v string) *Channel {
s.LatencyMode = &v
return s
}
// SetName sets the Name field's value.
func (s *Channel) SetName(v string) *Channel {
s.Name = &v
return s
}
// SetPlaybackUrl sets the PlaybackUrl field's value.
func (s *Channel) SetPlaybackUrl(v string) *Channel {
s.PlaybackUrl = &v
return s
}
// SetRecordingConfigurationArn sets the RecordingConfigurationArn field's value.
func (s *Channel) SetRecordingConfigurationArn(v string) *Channel {
s.RecordingConfigurationArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *Channel) SetTags(v map[string]*string) *Channel {
s.Tags = v
return s
}
// SetType sets the Type field's value.
func (s *Channel) SetType(v string) *Channel {
s.Type = &v
return s
}
type ChannelNotBroadcasting struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// The stream is offline for the given channel ARN.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ChannelNotBroadcasting) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ChannelNotBroadcasting) GoString() string {
return s.String()
}
func newErrorChannelNotBroadcasting(v protocol.ResponseMetadata) error {
return &ChannelNotBroadcasting{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ChannelNotBroadcasting) Code() string {
return "ChannelNotBroadcasting"
}
// Message returns the exception's message.
func (s *ChannelNotBroadcasting) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ChannelNotBroadcasting) OrigErr() error {
return nil
}
func (s *ChannelNotBroadcasting) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ChannelNotBroadcasting) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ChannelNotBroadcasting) RequestID() string {
return s.RespMetadata.RequestID
}
// Summary information about a channel.
type ChannelSummary struct {
_ struct{} `type:"structure"`
// Channel ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Whether the channel is private (enabled for playback authorization). Default:
// false.
Authorized *bool `locationName:"authorized" type:"boolean"`
// Channel latency mode. Use NORMAL to broadcast and deliver live video up to
// Full HD. Use LOW for near-real-time interaction with viewers. Default: LOW.
// (Note: In the Amazon IVS console, LOW and NORMAL correspond to Ultra-low
// and Standard, respectively.)
LatencyMode *string `locationName:"latencyMode" type:"string" enum:"ChannelLatencyMode"`
// Channel name.
Name *string `locationName:"name" type:"string"`
// Recording-configuration ARN. A value other than an empty string indicates
// that recording is enabled. Default: "" (empty string, recording is disabled).
RecordingConfigurationArn *string `locationName:"recordingConfigurationArn" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ChannelSummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ChannelSummary) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *ChannelSummary) SetArn(v string) *ChannelSummary {
s.Arn = &v
return s
}
// SetAuthorized sets the Authorized field's value.
func (s *ChannelSummary) SetAuthorized(v bool) *ChannelSummary {
s.Authorized = &v
return s
}
// SetLatencyMode sets the LatencyMode field's value.
func (s *ChannelSummary) SetLatencyMode(v string) *ChannelSummary {
s.LatencyMode = &v
return s
}
// SetName sets the Name field's value.
func (s *ChannelSummary) SetName(v string) *ChannelSummary {
s.Name = &v
return s
}
// SetRecordingConfigurationArn sets the RecordingConfigurationArn field's value.
func (s *ChannelSummary) SetRecordingConfigurationArn(v string) *ChannelSummary {
s.RecordingConfigurationArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *ChannelSummary) SetTags(v map[string]*string) *ChannelSummary {
s.Tags = v
return s
}
type ConflictException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Updating or deleting a resource can cause an inconsistent state.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ConflictException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ConflictException) GoString() string {
return s.String()
}
func newErrorConflictException(v protocol.ResponseMetadata) error {
return &ConflictException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ConflictException) Code() string {
return "ConflictException"
}
// Message returns the exception's message.
func (s *ConflictException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ConflictException) OrigErr() error {
return nil
}
func (s *ConflictException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ConflictException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ConflictException) RequestID() string {
return s.RespMetadata.RequestID
}
type CreateChannelInput struct {
_ struct{} `type:"structure"`
// Whether the channel is private (enabled for playback authorization). Default:
// false.
Authorized *bool `locationName:"authorized" type:"boolean"`
// Channel latency mode. Use NORMAL to broadcast and deliver live video up to
// Full HD. Use LOW for near-real-time interaction with viewers. (Note: In the
// Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard,
// respectively.) Default: LOW.
LatencyMode *string `locationName:"latencyMode" type:"string" enum:"ChannelLatencyMode"`
// Channel name.
Name *string `locationName:"name" type:"string"`
// Recording-configuration ARN. Default: "" (empty string, recording is disabled).
RecordingConfigurationArn *string `locationName:"recordingConfigurationArn" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
// Channel type, which determines the allowable resolution and bitrate. If you
// exceed the allowable resolution or bitrate, the stream probably will disconnect
// immediately. Default: STANDARD. Valid values:
//
// * STANDARD: Multiple qualities are generated from the original input,
// to automatically give viewers the best experience for their devices and
// network conditions. Resolution can be up to 1080p and bitrate can be up
// to 8.5 Mbps. Audio is transcoded only for renditions 360p and below; above
// that, audio is passed through.
//
// * BASIC: Amazon IVS delivers the original input to viewers. The viewer’s
// video-quality choice is limited to the original input. Resolution can
// be up to 480p and bitrate can be up to 1.5 Mbps.
Type *string `locationName:"type" type:"string" enum:"ChannelType"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateChannelInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateChannelInput) GoString() string {
return s.String()
}
// SetAuthorized sets the Authorized field's value.
func (s *CreateChannelInput) SetAuthorized(v bool) *CreateChannelInput {
s.Authorized = &v
return s
}
// SetLatencyMode sets the LatencyMode field's value.
func (s *CreateChannelInput) SetLatencyMode(v string) *CreateChannelInput {
s.LatencyMode = &v
return s
}
// SetName sets the Name field's value.
func (s *CreateChannelInput) SetName(v string) *CreateChannelInput {
s.Name = &v
return s
}
// SetRecordingConfigurationArn sets the RecordingConfigurationArn field's value.
func (s *CreateChannelInput) SetRecordingConfigurationArn(v string) *CreateChannelInput {
s.RecordingConfigurationArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateChannelInput) SetTags(v map[string]*string) *CreateChannelInput {
s.Tags = v
return s
}
// SetType sets the Type field's value.
func (s *CreateChannelInput) SetType(v string) *CreateChannelInput {
s.Type = &v
return s
}
type CreateChannelOutput struct {
_ struct{} `type:"structure"`
// Object specifying a channel.
Channel *Channel `locationName:"channel" type:"structure"`
// Object specifying a stream key.
StreamKey *StreamKey `locationName:"streamKey" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateChannelOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateChannelOutput) GoString() string {
return s.String()
}
// SetChannel sets the Channel field's value.
func (s *CreateChannelOutput) SetChannel(v *Channel) *CreateChannelOutput {
s.Channel = v
return s
}
// SetStreamKey sets the StreamKey field's value.
func (s *CreateChannelOutput) SetStreamKey(v *StreamKey) *CreateChannelOutput {
s.StreamKey = v
return s
}
type CreateRecordingConfigurationInput struct {
_ struct{} `type:"structure"`
// A complex type that contains a destination configuration for where recorded
// video will be stored.
//
// DestinationConfiguration is a required field
DestinationConfiguration *DestinationConfiguration `locationName:"destinationConfiguration" type:"structure" required:"true"`
// Recording-configuration name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
// A complex type that allows you to enable/disable the recording of thumbnails
// for a live session and modify the interval at which thumbnails are generated
// for the live session.
ThumbnailConfiguration *ThumbnailConfiguration `locationName:"thumbnailConfiguration" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRecordingConfigurationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRecordingConfigurationInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateRecordingConfigurationInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateRecordingConfigurationInput"}
if s.DestinationConfiguration == nil {
invalidParams.Add(request.NewErrParamRequired("DestinationConfiguration"))
}
if s.DestinationConfiguration != nil {
if err := s.DestinationConfiguration.Validate(); err != nil {
invalidParams.AddNested("DestinationConfiguration", err.(request.ErrInvalidParams))
}
}
if s.ThumbnailConfiguration != nil {
if err := s.ThumbnailConfiguration.Validate(); err != nil {
invalidParams.AddNested("ThumbnailConfiguration", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetDestinationConfiguration sets the DestinationConfiguration field's value.
func (s *CreateRecordingConfigurationInput) SetDestinationConfiguration(v *DestinationConfiguration) *CreateRecordingConfigurationInput {
s.DestinationConfiguration = v
return s
}
// SetName sets the Name field's value.
func (s *CreateRecordingConfigurationInput) SetName(v string) *CreateRecordingConfigurationInput {
s.Name = &v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateRecordingConfigurationInput) SetTags(v map[string]*string) *CreateRecordingConfigurationInput {
s.Tags = v
return s
}
// SetThumbnailConfiguration sets the ThumbnailConfiguration field's value.
func (s *CreateRecordingConfigurationInput) SetThumbnailConfiguration(v *ThumbnailConfiguration) *CreateRecordingConfigurationInput {
s.ThumbnailConfiguration = v
return s
}
type CreateRecordingConfigurationOutput struct {
_ struct{} `type:"structure"`
// An object representing a configuration to record a channel stream.
RecordingConfiguration *RecordingConfiguration `locationName:"recordingConfiguration" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRecordingConfigurationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateRecordingConfigurationOutput) GoString() string {
return s.String()
}
// SetRecordingConfiguration sets the RecordingConfiguration field's value.
func (s *CreateRecordingConfigurationOutput) SetRecordingConfiguration(v *RecordingConfiguration) *CreateRecordingConfigurationOutput {
s.RecordingConfiguration = v
return s
}
type CreateStreamKeyInput struct {
_ struct{} `type:"structure"`
// ARN of the channel for which to create the stream key.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateStreamKeyInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateStreamKeyInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateStreamKeyInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateStreamKeyInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *CreateStreamKeyInput) SetChannelArn(v string) *CreateStreamKeyInput {
s.ChannelArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *CreateStreamKeyInput) SetTags(v map[string]*string) *CreateStreamKeyInput {
s.Tags = v
return s
}
type CreateStreamKeyOutput struct {
_ struct{} `type:"structure"`
// Stream key used to authenticate an RTMPS stream for ingestion.
StreamKey *StreamKey `locationName:"streamKey" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateStreamKeyOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s CreateStreamKeyOutput) GoString() string {
return s.String()
}
// SetStreamKey sets the StreamKey field's value.
func (s *CreateStreamKeyOutput) SetStreamKey(v *StreamKey) *CreateStreamKeyOutput {
s.StreamKey = v
return s
}
type DeleteChannelInput struct {
_ struct{} `type:"structure"`
// ARN of the channel to be deleted.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteChannelInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteChannelInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteChannelInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteChannelInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *DeleteChannelInput) SetArn(v string) *DeleteChannelInput {
s.Arn = &v
return s
}
type DeleteChannelOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteChannelOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteChannelOutput) GoString() string {
return s.String()
}
type DeletePlaybackKeyPairInput struct {
_ struct{} `type:"structure"`
// ARN of the key pair to be deleted.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeletePlaybackKeyPairInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeletePlaybackKeyPairInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeletePlaybackKeyPairInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeletePlaybackKeyPairInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *DeletePlaybackKeyPairInput) SetArn(v string) *DeletePlaybackKeyPairInput {
s.Arn = &v
return s
}
type DeletePlaybackKeyPairOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeletePlaybackKeyPairOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeletePlaybackKeyPairOutput) GoString() string {
return s.String()
}
type DeleteRecordingConfigurationInput struct {
_ struct{} `type:"structure"`
// ARN of the recording configuration to be deleted.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRecordingConfigurationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRecordingConfigurationInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteRecordingConfigurationInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteRecordingConfigurationInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *DeleteRecordingConfigurationInput) SetArn(v string) *DeleteRecordingConfigurationInput {
s.Arn = &v
return s
}
type DeleteRecordingConfigurationOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRecordingConfigurationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteRecordingConfigurationOutput) GoString() string {
return s.String()
}
type DeleteStreamKeyInput struct {
_ struct{} `type:"structure"`
// ARN of the stream key to be deleted.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteStreamKeyInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteStreamKeyInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteStreamKeyInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteStreamKeyInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *DeleteStreamKeyInput) SetArn(v string) *DeleteStreamKeyInput {
s.Arn = &v
return s
}
type DeleteStreamKeyOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteStreamKeyOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DeleteStreamKeyOutput) GoString() string {
return s.String()
}
// A complex type that describes a location where recorded videos will be stored.
// Each member represents a type of destination configuration. For recording,
// you define one and only one type of destination configuration.
type DestinationConfiguration struct {
_ struct{} `type:"structure"`
// An S3 destination configuration where recorded videos will be stored.
S3 *S3DestinationConfiguration `locationName:"s3" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DestinationConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s DestinationConfiguration) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DestinationConfiguration) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DestinationConfiguration"}
if s.S3 != nil {
if err := s.S3.Validate(); err != nil {
invalidParams.AddNested("S3", err.(request.ErrInvalidParams))
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetS3 sets the S3 field's value.
func (s *DestinationConfiguration) SetS3(v *S3DestinationConfiguration) *DestinationConfiguration {
s.S3 = v
return s
}
type GetChannelInput struct {
_ struct{} `type:"structure"`
// ARN of the channel for which the configuration is to be retrieved.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetChannelInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetChannelInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetChannelInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetChannelInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *GetChannelInput) SetArn(v string) *GetChannelInput {
s.Arn = &v
return s
}
type GetChannelOutput struct {
_ struct{} `type:"structure"`
// Object specifying a channel.
Channel *Channel `locationName:"channel" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetChannelOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetChannelOutput) GoString() string {
return s.String()
}
// SetChannel sets the Channel field's value.
func (s *GetChannelOutput) SetChannel(v *Channel) *GetChannelOutput {
s.Channel = v
return s
}
type GetPlaybackKeyPairInput struct {
_ struct{} `type:"structure"`
// ARN of the key pair to be returned.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetPlaybackKeyPairInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetPlaybackKeyPairInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetPlaybackKeyPairInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetPlaybackKeyPairInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *GetPlaybackKeyPairInput) SetArn(v string) *GetPlaybackKeyPairInput {
s.Arn = &v
return s
}
type GetPlaybackKeyPairOutput struct {
_ struct{} `type:"structure"`
// A key pair used to sign and validate a playback authorization token.
KeyPair *PlaybackKeyPair `locationName:"keyPair" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetPlaybackKeyPairOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetPlaybackKeyPairOutput) GoString() string {
return s.String()
}
// SetKeyPair sets the KeyPair field's value.
func (s *GetPlaybackKeyPairOutput) SetKeyPair(v *PlaybackKeyPair) *GetPlaybackKeyPairOutput {
s.KeyPair = v
return s
}
type GetRecordingConfigurationInput struct {
_ struct{} `type:"structure"`
// ARN of the recording configuration to be retrieved.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRecordingConfigurationInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRecordingConfigurationInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetRecordingConfigurationInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetRecordingConfigurationInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *GetRecordingConfigurationInput) SetArn(v string) *GetRecordingConfigurationInput {
s.Arn = &v
return s
}
type GetRecordingConfigurationOutput struct {
_ struct{} `type:"structure"`
// An object representing a configuration to record a channel stream.
RecordingConfiguration *RecordingConfiguration `locationName:"recordingConfiguration" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRecordingConfigurationOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRecordingConfigurationOutput) GoString() string {
return s.String()
}
// SetRecordingConfiguration sets the RecordingConfiguration field's value.
func (s *GetRecordingConfigurationOutput) SetRecordingConfiguration(v *RecordingConfiguration) *GetRecordingConfigurationOutput {
s.RecordingConfiguration = v
return s
}
type GetStreamInput struct {
_ struct{} `type:"structure"`
// Channel ARN for stream to be accessed.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetStreamInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetStreamInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *GetStreamInput) SetChannelArn(v string) *GetStreamInput {
s.ChannelArn = &v
return s
}
type GetStreamKeyInput struct {
_ struct{} `type:"structure"`
// ARN for the stream key to be retrieved.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamKeyInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamKeyInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetStreamKeyInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetStreamKeyInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *GetStreamKeyInput) SetArn(v string) *GetStreamKeyInput {
s.Arn = &v
return s
}
type GetStreamKeyOutput struct {
_ struct{} `type:"structure"`
// Object specifying a stream key.
StreamKey *StreamKey `locationName:"streamKey" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamKeyOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamKeyOutput) GoString() string {
return s.String()
}
// SetStreamKey sets the StreamKey field's value.
func (s *GetStreamKeyOutput) SetStreamKey(v *StreamKey) *GetStreamKeyOutput {
s.StreamKey = v
return s
}
type GetStreamOutput struct {
_ struct{} `type:"structure"`
// Specifies a live video stream that has been ingested and distributed.
Stream *Stream `locationName:"stream" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamOutput) GoString() string {
return s.String()
}
// SetStream sets the Stream field's value.
func (s *GetStreamOutput) SetStream(v *Stream) *GetStreamOutput {
s.Stream = v
return s
}
type GetStreamSessionInput struct {
_ struct{} `type:"structure"`
// ARN of the channel resource
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
// Unique identifier for a live or previously live stream in the specified channel.
// If no streamId is provided, this returns the most recent stream session for
// the channel, if it exists.
StreamId *string `locationName:"streamId" min:"26" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamSessionInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamSessionInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetStreamSessionInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetStreamSessionInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if s.StreamId != nil && len(*s.StreamId) < 26 {
invalidParams.Add(request.NewErrParamMinLen("StreamId", 26))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *GetStreamSessionInput) SetChannelArn(v string) *GetStreamSessionInput {
s.ChannelArn = &v
return s
}
// SetStreamId sets the StreamId field's value.
func (s *GetStreamSessionInput) SetStreamId(v string) *GetStreamSessionInput {
s.StreamId = &v
return s
}
type GetStreamSessionOutput struct {
_ struct{} `type:"structure"`
// List of stream details.
StreamSession *StreamSession `locationName:"streamSession" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamSessionOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetStreamSessionOutput) GoString() string {
return s.String()
}
// SetStreamSession sets the StreamSession field's value.
func (s *GetStreamSessionOutput) SetStreamSession(v *StreamSession) *GetStreamSessionOutput {
s.StreamSession = v
return s
}
type ImportPlaybackKeyPairInput struct {
_ struct{} `type:"structure"`
// Playback-key-pair name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// The public portion of a customer-generated key pair.
//
// PublicKeyMaterial is a required field
PublicKeyMaterial *string `locationName:"publicKeyMaterial" type:"string" required:"true"`
// Any tags provided with the request are added to the playback key pair tags.
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ImportPlaybackKeyPairInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ImportPlaybackKeyPairInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ImportPlaybackKeyPairInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ImportPlaybackKeyPairInput"}
if s.PublicKeyMaterial == nil {
invalidParams.Add(request.NewErrParamRequired("PublicKeyMaterial"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetName sets the Name field's value.
func (s *ImportPlaybackKeyPairInput) SetName(v string) *ImportPlaybackKeyPairInput {
s.Name = &v
return s
}
// SetPublicKeyMaterial sets the PublicKeyMaterial field's value.
func (s *ImportPlaybackKeyPairInput) SetPublicKeyMaterial(v string) *ImportPlaybackKeyPairInput {
s.PublicKeyMaterial = &v
return s
}
// SetTags sets the Tags field's value.
func (s *ImportPlaybackKeyPairInput) SetTags(v map[string]*string) *ImportPlaybackKeyPairInput {
s.Tags = v
return s
}
type ImportPlaybackKeyPairOutput struct {
_ struct{} `type:"structure"`
// A key pair used to sign and validate a playback authorization token.
KeyPair *PlaybackKeyPair `locationName:"keyPair" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ImportPlaybackKeyPairOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ImportPlaybackKeyPairOutput) GoString() string {
return s.String()
}
// SetKeyPair sets the KeyPair field's value.
func (s *ImportPlaybackKeyPairOutput) SetKeyPair(v *PlaybackKeyPair) *ImportPlaybackKeyPairOutput {
s.KeyPair = v
return s
}
// Object specifying the ingest configuration set up by the broadcaster, usually
// in an encoder.
type IngestConfiguration struct {
_ struct{} `type:"structure"`
// Encoder settings for audio.
Audio *AudioConfiguration `locationName:"audio" type:"structure"`
// Encoder settings for video.
Video *VideoConfiguration `locationName:"video" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s IngestConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s IngestConfiguration) GoString() string {
return s.String()
}
// SetAudio sets the Audio field's value.
func (s *IngestConfiguration) SetAudio(v *AudioConfiguration) *IngestConfiguration {
s.Audio = v
return s
}
// SetVideo sets the Video field's value.
func (s *IngestConfiguration) SetVideo(v *VideoConfiguration) *IngestConfiguration {
s.Video = v
return s
}
type InternalServerException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Unexpected error during processing of request.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InternalServerException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InternalServerException) GoString() string {
return s.String()
}
func newErrorInternalServerException(v protocol.ResponseMetadata) error {
return &InternalServerException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *InternalServerException) Code() string {
return "InternalServerException"
}
// Message returns the exception's message.
func (s *InternalServerException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *InternalServerException) OrigErr() error {
return nil
}
func (s *InternalServerException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *InternalServerException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *InternalServerException) RequestID() string {
return s.RespMetadata.RequestID
}
type ListChannelsInput struct {
_ struct{} `type:"structure"`
// Filters the channel list to match the specified name.
FilterByName *string `locationName:"filterByName" type:"string"`
// Filters the channel list to match the specified recording-configuration ARN.
FilterByRecordingConfigurationArn *string `locationName:"filterByRecordingConfigurationArn" type:"string"`
// Maximum number of channels to return. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// The first channel to retrieve. This is used for pagination; see the nextToken
// response field.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListChannelsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListChannelsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListChannelsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListChannelsInput"}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFilterByName sets the FilterByName field's value.
func (s *ListChannelsInput) SetFilterByName(v string) *ListChannelsInput {
s.FilterByName = &v
return s
}
// SetFilterByRecordingConfigurationArn sets the FilterByRecordingConfigurationArn field's value.
func (s *ListChannelsInput) SetFilterByRecordingConfigurationArn(v string) *ListChannelsInput {
s.FilterByRecordingConfigurationArn = &v
return s
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListChannelsInput) SetMaxResults(v int64) *ListChannelsInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListChannelsInput) SetNextToken(v string) *ListChannelsInput {
s.NextToken = &v
return s
}
type ListChannelsOutput struct {
_ struct{} `type:"structure"`
// List of the matching channels.
//
// Channels is a required field
Channels []*ChannelSummary `locationName:"channels" type:"list" required:"true"`
// If there are more channels than maxResults, use nextToken in the request
// to get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListChannelsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListChannelsOutput) GoString() string {
return s.String()
}
// SetChannels sets the Channels field's value.
func (s *ListChannelsOutput) SetChannels(v []*ChannelSummary) *ListChannelsOutput {
s.Channels = v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListChannelsOutput) SetNextToken(v string) *ListChannelsOutput {
s.NextToken = &v
return s
}
type ListPlaybackKeyPairsInput struct {
_ struct{} `type:"structure"`
// The first key pair to retrieve. This is used for pagination; see the nextToken
// response field. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// Maximum number of key pairs to return.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListPlaybackKeyPairsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListPlaybackKeyPairsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListPlaybackKeyPairsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListPlaybackKeyPairsInput"}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListPlaybackKeyPairsInput) SetMaxResults(v int64) *ListPlaybackKeyPairsInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListPlaybackKeyPairsInput) SetNextToken(v string) *ListPlaybackKeyPairsInput {
s.NextToken = &v
return s
}
type ListPlaybackKeyPairsOutput struct {
_ struct{} `type:"structure"`
// List of key pairs.
//
// KeyPairs is a required field
KeyPairs []*PlaybackKeyPairSummary `locationName:"keyPairs" type:"list" required:"true"`
// If there are more key pairs than maxResults, use nextToken in the request
// to get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListPlaybackKeyPairsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListPlaybackKeyPairsOutput) GoString() string {
return s.String()
}
// SetKeyPairs sets the KeyPairs field's value.
func (s *ListPlaybackKeyPairsOutput) SetKeyPairs(v []*PlaybackKeyPairSummary) *ListPlaybackKeyPairsOutput {
s.KeyPairs = v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListPlaybackKeyPairsOutput) SetNextToken(v string) *ListPlaybackKeyPairsOutput {
s.NextToken = &v
return s
}
type ListRecordingConfigurationsInput struct {
_ struct{} `type:"structure"`
// Maximum number of recording configurations to return. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// The first recording configuration to retrieve. This is used for pagination;
// see the nextToken response field.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRecordingConfigurationsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRecordingConfigurationsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListRecordingConfigurationsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListRecordingConfigurationsInput"}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListRecordingConfigurationsInput) SetMaxResults(v int64) *ListRecordingConfigurationsInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListRecordingConfigurationsInput) SetNextToken(v string) *ListRecordingConfigurationsInput {
s.NextToken = &v
return s
}
type ListRecordingConfigurationsOutput struct {
_ struct{} `type:"structure"`
// If there are more recording configurations than maxResults, use nextToken
// in the request to get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
// List of the matching recording configurations.
//
// RecordingConfigurations is a required field
RecordingConfigurations []*RecordingConfigurationSummary `locationName:"recordingConfigurations" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRecordingConfigurationsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListRecordingConfigurationsOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListRecordingConfigurationsOutput) SetNextToken(v string) *ListRecordingConfigurationsOutput {
s.NextToken = &v
return s
}
// SetRecordingConfigurations sets the RecordingConfigurations field's value.
func (s *ListRecordingConfigurationsOutput) SetRecordingConfigurations(v []*RecordingConfigurationSummary) *ListRecordingConfigurationsOutput {
s.RecordingConfigurations = v
return s
}
type ListStreamKeysInput struct {
_ struct{} `type:"structure"`
// Channel ARN used to filter the list.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
// Maximum number of streamKeys to return. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// The first stream key to retrieve. This is used for pagination; see the nextToken
// response field.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamKeysInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamKeysInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListStreamKeysInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListStreamKeysInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *ListStreamKeysInput) SetChannelArn(v string) *ListStreamKeysInput {
s.ChannelArn = &v
return s
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListStreamKeysInput) SetMaxResults(v int64) *ListStreamKeysInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamKeysInput) SetNextToken(v string) *ListStreamKeysInput {
s.NextToken = &v
return s
}
type ListStreamKeysOutput struct {
_ struct{} `type:"structure"`
// If there are more stream keys than maxResults, use nextToken in the request
// to get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
// List of stream keys.
//
// StreamKeys is a required field
StreamKeys []*StreamKeySummary `locationName:"streamKeys" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamKeysOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamKeysOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamKeysOutput) SetNextToken(v string) *ListStreamKeysOutput {
s.NextToken = &v
return s
}
// SetStreamKeys sets the StreamKeys field's value.
func (s *ListStreamKeysOutput) SetStreamKeys(v []*StreamKeySummary) *ListStreamKeysOutput {
s.StreamKeys = v
return s
}
type ListStreamSessionsInput struct {
_ struct{} `type:"structure"`
// Channel ARN used to filter the list.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
// Maximum number of streams to return. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// The first stream to retrieve. This is used for pagination; see the nextToken
// response field.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamSessionsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamSessionsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListStreamSessionsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListStreamSessionsInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *ListStreamSessionsInput) SetChannelArn(v string) *ListStreamSessionsInput {
s.ChannelArn = &v
return s
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListStreamSessionsInput) SetMaxResults(v int64) *ListStreamSessionsInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamSessionsInput) SetNextToken(v string) *ListStreamSessionsInput {
s.NextToken = &v
return s
}
type ListStreamSessionsOutput struct {
_ struct{} `type:"structure"`
// If there are more streams than maxResults, use nextToken in the request to
// get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
// List of stream sessions.
//
// StreamSessions is a required field
StreamSessions []*StreamSessionSummary `locationName:"streamSessions" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamSessionsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamSessionsOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamSessionsOutput) SetNextToken(v string) *ListStreamSessionsOutput {
s.NextToken = &v
return s
}
// SetStreamSessions sets the StreamSessions field's value.
func (s *ListStreamSessionsOutput) SetStreamSessions(v []*StreamSessionSummary) *ListStreamSessionsOutput {
s.StreamSessions = v
return s
}
type ListStreamsInput struct {
_ struct{} `type:"structure"`
// Filters the stream list to match the specified criterion.
FilterBy *StreamFilters `locationName:"filterBy" type:"structure"`
// Maximum number of streams to return. Default: 50.
MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"`
// The first stream to retrieve. This is used for pagination; see the nextToken
// response field.
NextToken *string `locationName:"nextToken" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListStreamsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListStreamsInput"}
if s.MaxResults != nil && *s.MaxResults < 1 {
invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetFilterBy sets the FilterBy field's value.
func (s *ListStreamsInput) SetFilterBy(v *StreamFilters) *ListStreamsInput {
s.FilterBy = v
return s
}
// SetMaxResults sets the MaxResults field's value.
func (s *ListStreamsInput) SetMaxResults(v int64) *ListStreamsInput {
s.MaxResults = &v
return s
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamsInput) SetNextToken(v string) *ListStreamsInput {
s.NextToken = &v
return s
}
type ListStreamsOutput struct {
_ struct{} `type:"structure"`
// If there are more streams than maxResults, use nextToken in the request to
// get the next set.
NextToken *string `locationName:"nextToken" type:"string"`
// List of streams.
//
// Streams is a required field
Streams []*StreamSummary `locationName:"streams" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListStreamsOutput) GoString() string {
return s.String()
}
// SetNextToken sets the NextToken field's value.
func (s *ListStreamsOutput) SetNextToken(v string) *ListStreamsOutput {
s.NextToken = &v
return s
}
// SetStreams sets the Streams field's value.
func (s *ListStreamsOutput) SetStreams(v []*StreamSummary) *ListStreamsOutput {
s.Streams = v
return s
}
type ListTagsForResourceInput struct {
_ struct{} `type:"structure" nopayload:"true"`
// The ARN of the resource to be retrieved.
//
// ResourceArn is a required field
ResourceArn *string `location:"uri" locationName:"resourceArn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListTagsForResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if s.ResourceArn != nil && len(*s.ResourceArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetResourceArn sets the ResourceArn field's value.
func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput {
s.ResourceArn = &v
return s
}
type ListTagsForResourceOutput struct {
_ struct{} `type:"structure"`
// Tags is a required field
Tags map[string]*string `locationName:"tags" type:"map" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListTagsForResourceOutput) GoString() string {
return s.String()
}
// SetTags sets the Tags field's value.
func (s *ListTagsForResourceOutput) SetTags(v map[string]*string) *ListTagsForResourceOutput {
s.Tags = v
return s
}
type PendingVerification struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Your account is pending verification.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PendingVerification) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PendingVerification) GoString() string {
return s.String()
}
func newErrorPendingVerification(v protocol.ResponseMetadata) error {
return &PendingVerification{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *PendingVerification) Code() string {
return "PendingVerification"
}
// Message returns the exception's message.
func (s *PendingVerification) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *PendingVerification) OrigErr() error {
return nil
}
func (s *PendingVerification) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *PendingVerification) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *PendingVerification) RequestID() string {
return s.RespMetadata.RequestID
}
// A key pair used to sign and validate a playback authorization token.
type PlaybackKeyPair struct {
_ struct{} `type:"structure"`
// Key-pair ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Key-pair identifier.
Fingerprint *string `locationName:"fingerprint" type:"string"`
// Playback-key-pair name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PlaybackKeyPair) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PlaybackKeyPair) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *PlaybackKeyPair) SetArn(v string) *PlaybackKeyPair {
s.Arn = &v
return s
}
// SetFingerprint sets the Fingerprint field's value.
func (s *PlaybackKeyPair) SetFingerprint(v string) *PlaybackKeyPair {
s.Fingerprint = &v
return s
}
// SetName sets the Name field's value.
func (s *PlaybackKeyPair) SetName(v string) *PlaybackKeyPair {
s.Name = &v
return s
}
// SetTags sets the Tags field's value.
func (s *PlaybackKeyPair) SetTags(v map[string]*string) *PlaybackKeyPair {
s.Tags = v
return s
}
// Summary information about a playback key pair.
type PlaybackKeyPairSummary struct {
_ struct{} `type:"structure"`
// Key-pair ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Playback-key-pair name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PlaybackKeyPairSummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PlaybackKeyPairSummary) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *PlaybackKeyPairSummary) SetArn(v string) *PlaybackKeyPairSummary {
s.Arn = &v
return s
}
// SetName sets the Name field's value.
func (s *PlaybackKeyPairSummary) SetName(v string) *PlaybackKeyPairSummary {
s.Name = &v
return s
}
// SetTags sets the Tags field's value.
func (s *PlaybackKeyPairSummary) SetTags(v map[string]*string) *PlaybackKeyPairSummary {
s.Tags = v
return s
}
type PutMetadataInput struct {
_ struct{} `type:"structure"`
// ARN of the channel into which metadata is inserted. This channel must have
// an active stream.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
// Metadata to insert into the stream. Maximum: 1 KB per request.
//
// Metadata is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by PutMetadataInput's
// String and GoString methods.
//
// Metadata is a required field
Metadata *string `locationName:"metadata" min:"1" type:"string" required:"true" sensitive:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PutMetadataInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PutMetadataInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *PutMetadataInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "PutMetadataInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if s.Metadata == nil {
invalidParams.Add(request.NewErrParamRequired("Metadata"))
}
if s.Metadata != nil && len(*s.Metadata) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Metadata", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *PutMetadataInput) SetChannelArn(v string) *PutMetadataInput {
s.ChannelArn = &v
return s
}
// SetMetadata sets the Metadata field's value.
func (s *PutMetadataInput) SetMetadata(v string) *PutMetadataInput {
s.Metadata = &v
return s
}
type PutMetadataOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PutMetadataOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s PutMetadataOutput) GoString() string {
return s.String()
}
// An object representing a configuration to record a channel stream.
type RecordingConfiguration struct {
_ struct{} `type:"structure"`
// Recording-configuration ARN.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// A complex type that contains information about where recorded video will
// be stored.
//
// DestinationConfiguration is a required field
DestinationConfiguration *DestinationConfiguration `locationName:"destinationConfiguration" type:"structure" required:"true"`
// Recording-configuration name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// Indicates the current state of the recording configuration. When the state
// is ACTIVE, the configuration is ready for recording a channel stream.
//
// State is a required field
State *string `locationName:"state" type:"string" required:"true" enum:"RecordingConfigurationState"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
// A complex type that allows you to enable/disable the recording of thumbnails
// for a live session and modify the interval at which thumbnails are generated
// for the live session.
ThumbnailConfiguration *ThumbnailConfiguration `locationName:"thumbnailConfiguration" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RecordingConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RecordingConfiguration) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *RecordingConfiguration) SetArn(v string) *RecordingConfiguration {
s.Arn = &v
return s
}
// SetDestinationConfiguration sets the DestinationConfiguration field's value.
func (s *RecordingConfiguration) SetDestinationConfiguration(v *DestinationConfiguration) *RecordingConfiguration {
s.DestinationConfiguration = v
return s
}
// SetName sets the Name field's value.
func (s *RecordingConfiguration) SetName(v string) *RecordingConfiguration {
s.Name = &v
return s
}
// SetState sets the State field's value.
func (s *RecordingConfiguration) SetState(v string) *RecordingConfiguration {
s.State = &v
return s
}
// SetTags sets the Tags field's value.
func (s *RecordingConfiguration) SetTags(v map[string]*string) *RecordingConfiguration {
s.Tags = v
return s
}
// SetThumbnailConfiguration sets the ThumbnailConfiguration field's value.
func (s *RecordingConfiguration) SetThumbnailConfiguration(v *ThumbnailConfiguration) *RecordingConfiguration {
s.ThumbnailConfiguration = v
return s
}
// Summary information about a RecordingConfiguration.
type RecordingConfigurationSummary struct {
_ struct{} `type:"structure"`
// Recording-configuration ARN.
//
// Arn is a required field
Arn *string `locationName:"arn" type:"string" required:"true"`
// A complex type that contains information about where recorded video will
// be stored.
//
// DestinationConfiguration is a required field
DestinationConfiguration *DestinationConfiguration `locationName:"destinationConfiguration" type:"structure" required:"true"`
// Recording-configuration name. The value does not need to be unique.
Name *string `locationName:"name" type:"string"`
// Indicates the current state of the recording configuration. When the state
// is ACTIVE, the configuration is ready for recording a channel stream.
//
// State is a required field
State *string `locationName:"state" type:"string" required:"true" enum:"RecordingConfigurationState"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RecordingConfigurationSummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RecordingConfigurationSummary) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *RecordingConfigurationSummary) SetArn(v string) *RecordingConfigurationSummary {
s.Arn = &v
return s
}
// SetDestinationConfiguration sets the DestinationConfiguration field's value.
func (s *RecordingConfigurationSummary) SetDestinationConfiguration(v *DestinationConfiguration) *RecordingConfigurationSummary {
s.DestinationConfiguration = v
return s
}
// SetName sets the Name field's value.
func (s *RecordingConfigurationSummary) SetName(v string) *RecordingConfigurationSummary {
s.Name = &v
return s
}
// SetState sets the State field's value.
func (s *RecordingConfigurationSummary) SetState(v string) *RecordingConfigurationSummary {
s.State = &v
return s
}
// SetTags sets the Tags field's value.
func (s *RecordingConfigurationSummary) SetTags(v map[string]*string) *RecordingConfigurationSummary {
s.Tags = v
return s
}
type ResourceNotFoundException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Request references a resource which does not exist.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceNotFoundException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceNotFoundException) GoString() string {
return s.String()
}
func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error {
return &ResourceNotFoundException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ResourceNotFoundException) Code() string {
return "ResourceNotFoundException"
}
// Message returns the exception's message.
func (s *ResourceNotFoundException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ResourceNotFoundException) OrigErr() error {
return nil
}
func (s *ResourceNotFoundException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ResourceNotFoundException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ResourceNotFoundException) RequestID() string {
return s.RespMetadata.RequestID
}
// A complex type that describes an S3 location where recorded videos will be
// stored.
type S3DestinationConfiguration struct {
_ struct{} `type:"structure"`
// Location (S3 bucket name) where recorded videos will be stored.
//
// BucketName is a required field
BucketName *string `locationName:"bucketName" min:"3" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s S3DestinationConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s S3DestinationConfiguration) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *S3DestinationConfiguration) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "S3DestinationConfiguration"}
if s.BucketName == nil {
invalidParams.Add(request.NewErrParamRequired("BucketName"))
}
if s.BucketName != nil && len(*s.BucketName) < 3 {
invalidParams.Add(request.NewErrParamMinLen("BucketName", 3))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetBucketName sets the BucketName field's value.
func (s *S3DestinationConfiguration) SetBucketName(v string) *S3DestinationConfiguration {
s.BucketName = &v
return s
}
type ServiceQuotaExceededException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Request would cause a service quota to be exceeded.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceQuotaExceededException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ServiceQuotaExceededException) GoString() string {
return s.String()
}
func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error {
return &ServiceQuotaExceededException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ServiceQuotaExceededException) Code() string {
return "ServiceQuotaExceededException"
}
// Message returns the exception's message.
func (s *ServiceQuotaExceededException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ServiceQuotaExceededException) OrigErr() error {
return nil
}
func (s *ServiceQuotaExceededException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ServiceQuotaExceededException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ServiceQuotaExceededException) RequestID() string {
return s.RespMetadata.RequestID
}
type StopStreamInput struct {
_ struct{} `type:"structure"`
// ARN of the channel for which the stream is to be stopped.
//
// ChannelArn is a required field
ChannelArn *string `locationName:"channelArn" min:"1" type:"string" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StopStreamInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StopStreamInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *StopStreamInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "StopStreamInput"}
if s.ChannelArn == nil {
invalidParams.Add(request.NewErrParamRequired("ChannelArn"))
}
if s.ChannelArn != nil && len(*s.ChannelArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ChannelArn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetChannelArn sets the ChannelArn field's value.
func (s *StopStreamInput) SetChannelArn(v string) *StopStreamInput {
s.ChannelArn = &v
return s
}
type StopStreamOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StopStreamOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StopStreamOutput) GoString() string {
return s.String()
}
// Specifies a live video stream that has been ingested and distributed.
type Stream struct {
_ struct{} `type:"structure"`
// Channel ARN for the stream.
ChannelArn *string `locationName:"channelArn" min:"1" type:"string"`
// The stream’s health.
Health *string `locationName:"health" type:"string" enum:"StreamHealth"`
// URL of the master playlist, required by the video player to play the HLS
// stream.
PlaybackUrl *string `locationName:"playbackUrl" type:"string"`
// Time of the stream’s start. This is an ISO 8601 timestamp returned as a
// string.
StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"iso8601"`
// The stream’s state.
State *string `locationName:"state" type:"string" enum:"StreamState"`
// Unique identifier for a live or previously live stream in the specified channel.
StreamId *string `locationName:"streamId" min:"26" type:"string"`
// A count of concurrent views of the stream. Typically, a new view appears
// in viewerCount within 15 seconds of when video playback starts and a view
// is removed from viewerCount within 1 minute of when video playback ends.
// A value of -1 indicates that the request timed out; in this case, retry.
ViewerCount *int64 `locationName:"viewerCount" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Stream) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s Stream) GoString() string {
return s.String()
}
// SetChannelArn sets the ChannelArn field's value.
func (s *Stream) SetChannelArn(v string) *Stream {
s.ChannelArn = &v
return s
}
// SetHealth sets the Health field's value.
func (s *Stream) SetHealth(v string) *Stream {
s.Health = &v
return s
}
// SetPlaybackUrl sets the PlaybackUrl field's value.
func (s *Stream) SetPlaybackUrl(v string) *Stream {
s.PlaybackUrl = &v
return s
}
// SetStartTime sets the StartTime field's value.
func (s *Stream) SetStartTime(v time.Time) *Stream {
s.StartTime = &v
return s
}
// SetState sets the State field's value.
func (s *Stream) SetState(v string) *Stream {
s.State = &v
return s
}
// SetStreamId sets the StreamId field's value.
func (s *Stream) SetStreamId(v string) *Stream {
s.StreamId = &v
return s
}
// SetViewerCount sets the ViewerCount field's value.
func (s *Stream) SetViewerCount(v int64) *Stream {
s.ViewerCount = &v
return s
}
// Object specifying a stream’s events. For a list of events, see Using Amazon
// EventBridge with Amazon IVS (https://docs.aws.amazon.com/ivs/latest/userguide/eventbridge.html).
type StreamEvent struct {
_ struct{} `type:"structure"`
// UTC ISO-8601 formatted timestamp of when the event occurred.
EventTime *time.Time `locationName:"eventTime" type:"timestamp" timestampFormat:"iso8601"`
// Name that identifies the stream event within a type.
Name *string `locationName:"name" type:"string"`
// Logical group for certain events.
Type *string `locationName:"type" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamEvent) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamEvent) GoString() string {
return s.String()
}
// SetEventTime sets the EventTime field's value.
func (s *StreamEvent) SetEventTime(v time.Time) *StreamEvent {
s.EventTime = &v
return s
}
// SetName sets the Name field's value.
func (s *StreamEvent) SetName(v string) *StreamEvent {
s.Name = &v
return s
}
// SetType sets the Type field's value.
func (s *StreamEvent) SetType(v string) *StreamEvent {
s.Type = &v
return s
}
// Object specifying the stream attribute on which to filter.
type StreamFilters struct {
_ struct{} `type:"structure"`
// The stream’s health.
Health *string `locationName:"health" type:"string" enum:"StreamHealth"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamFilters) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamFilters) GoString() string {
return s.String()
}
// SetHealth sets the Health field's value.
func (s *StreamFilters) SetHealth(v string) *StreamFilters {
s.Health = &v
return s
}
// Object specifying a stream key.
type StreamKey struct {
_ struct{} `type:"structure"`
// Stream-key ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Channel ARN for the stream.
ChannelArn *string `locationName:"channelArn" min:"1" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
// Stream-key value.
//
// Value is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by StreamKey's
// String and GoString methods.
Value *string `locationName:"value" type:"string" sensitive:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamKey) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamKey) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *StreamKey) SetArn(v string) *StreamKey {
s.Arn = &v
return s
}
// SetChannelArn sets the ChannelArn field's value.
func (s *StreamKey) SetChannelArn(v string) *StreamKey {
s.ChannelArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *StreamKey) SetTags(v map[string]*string) *StreamKey {
s.Tags = v
return s
}
// SetValue sets the Value field's value.
func (s *StreamKey) SetValue(v string) *StreamKey {
s.Value = &v
return s
}
// Summary information about a stream key.
type StreamKeySummary struct {
_ struct{} `type:"structure"`
// Stream-key ARN.
Arn *string `locationName:"arn" min:"1" type:"string"`
// Channel ARN for the stream.
ChannelArn *string `locationName:"channelArn" min:"1" type:"string"`
// Array of 1-50 maps, each of the form string:string (key:value).
Tags map[string]*string `locationName:"tags" type:"map"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamKeySummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamKeySummary) GoString() string {
return s.String()
}
// SetArn sets the Arn field's value.
func (s *StreamKeySummary) SetArn(v string) *StreamKeySummary {
s.Arn = &v
return s
}
// SetChannelArn sets the ChannelArn field's value.
func (s *StreamKeySummary) SetChannelArn(v string) *StreamKeySummary {
s.ChannelArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *StreamKeySummary) SetTags(v map[string]*string) *StreamKeySummary {
s.Tags = v
return s
}
// Object that captures the Amazon IVS configuration that the customer provisioned,
// the ingest configurations that the broadcaster used, and the most recent
// Amazon IVS stream events it encountered.
type StreamSession struct {
_ struct{} `type:"structure"`
// The properties of the channel at the time of going live.
Channel *Channel `locationName:"channel" type:"structure"`
// UTC ISO-8601 formatted timestamp of when the channel went offline. For live
// streams, this is NULL.
EndTime *time.Time `locationName:"endTime" type:"timestamp" timestampFormat:"iso8601"`
// The properties of the incoming RTMP stream for the stream.
IngestConfiguration *IngestConfiguration `locationName:"ingestConfiguration" type:"structure"`
// The properties of recording the live stream.
RecordingConfiguration *RecordingConfiguration `locationName:"recordingConfiguration" type:"structure"`
// UTC ISO-8601 formatted timestamp of when the channel went live.
StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"iso8601"`
// Unique identifier for a live or previously live stream in the specified channel.
StreamId *string `locationName:"streamId" min:"26" type:"string"`
// List of Amazon IVS events that the stream encountered. The list is sorted
// by most recent events and contains up to 500 events. For Amazon IVS events,
// see Using Amazon EventBridge with Amazon IVS (https://docs.aws.amazon.com/ivs/latest/userguide/eventbridge.html).
TruncatedEvents []*StreamEvent `locationName:"truncatedEvents" type:"list"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSession) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSession) GoString() string {
return s.String()
}
// SetChannel sets the Channel field's value.
func (s *StreamSession) SetChannel(v *Channel) *StreamSession {
s.Channel = v
return s
}
// SetEndTime sets the EndTime field's value.
func (s *StreamSession) SetEndTime(v time.Time) *StreamSession {
s.EndTime = &v
return s
}
// SetIngestConfiguration sets the IngestConfiguration field's value.
func (s *StreamSession) SetIngestConfiguration(v *IngestConfiguration) *StreamSession {
s.IngestConfiguration = v
return s
}
// SetRecordingConfiguration sets the RecordingConfiguration field's value.
func (s *StreamSession) SetRecordingConfiguration(v *RecordingConfiguration) *StreamSession {
s.RecordingConfiguration = v
return s
}
// SetStartTime sets the StartTime field's value.
func (s *StreamSession) SetStartTime(v time.Time) *StreamSession {
s.StartTime = &v
return s
}
// SetStreamId sets the StreamId field's value.
func (s *StreamSession) SetStreamId(v string) *StreamSession {
s.StreamId = &v
return s
}
// SetTruncatedEvents sets the TruncatedEvents field's value.
func (s *StreamSession) SetTruncatedEvents(v []*StreamEvent) *StreamSession {
s.TruncatedEvents = v
return s
}
// Summary information about a stream session.
type StreamSessionSummary struct {
_ struct{} `type:"structure"`
// UTC ISO-8601 formatted timestamp of when the channel went offline. For live
// streams, this is NULL.
EndTime *time.Time `locationName:"endTime" type:"timestamp" timestampFormat:"iso8601"`
// If true, this stream encountered a quota breach or failure.
HasErrorEvent *bool `locationName:"hasErrorEvent" type:"boolean"`
// UTC ISO-8601 formatted timestamp of when the channel went live.
StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"iso8601"`
// Unique identifier for a live or previously live stream in the specified channel.
StreamId *string `locationName:"streamId" min:"26" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSessionSummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSessionSummary) GoString() string {
return s.String()
}
// SetEndTime sets the EndTime field's value.
func (s *StreamSessionSummary) SetEndTime(v time.Time) *StreamSessionSummary {
s.EndTime = &v
return s
}
// SetHasErrorEvent sets the HasErrorEvent field's value.
func (s *StreamSessionSummary) SetHasErrorEvent(v bool) *StreamSessionSummary {
s.HasErrorEvent = &v
return s
}
// SetStartTime sets the StartTime field's value.
func (s *StreamSessionSummary) SetStartTime(v time.Time) *StreamSessionSummary {
s.StartTime = &v
return s
}
// SetStreamId sets the StreamId field's value.
func (s *StreamSessionSummary) SetStreamId(v string) *StreamSessionSummary {
s.StreamId = &v
return s
}
// Summary information about a stream.
type StreamSummary struct {
_ struct{} `type:"structure"`
// Channel ARN for the stream.
ChannelArn *string `locationName:"channelArn" min:"1" type:"string"`
// The stream’s health.
Health *string `locationName:"health" type:"string" enum:"StreamHealth"`
// Time of the stream’s start. This is an ISO 8601 timestamp returned as a
// string.
StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"iso8601"`
// The stream’s state.
State *string `locationName:"state" type:"string" enum:"StreamState"`
// Unique identifier for a live or previously live stream in the specified channel.
StreamId *string `locationName:"streamId" min:"26" type:"string"`
// A count of concurrent views of the stream. Typically, a new view appears
// in viewerCount within 15 seconds of when video playback starts and a view
// is removed from viewerCount within 1 minute of when video playback ends.
// A value of -1 indicates that the request timed out; in this case, retry.
ViewerCount *int64 `locationName:"viewerCount" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSummary) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamSummary) GoString() string {
return s.String()
}
// SetChannelArn sets the ChannelArn field's value.
func (s *StreamSummary) SetChannelArn(v string) *StreamSummary {
s.ChannelArn = &v
return s
}
// SetHealth sets the Health field's value.
func (s *StreamSummary) SetHealth(v string) *StreamSummary {
s.Health = &v
return s
}
// SetStartTime sets the StartTime field's value.
func (s *StreamSummary) SetStartTime(v time.Time) *StreamSummary {
s.StartTime = &v
return s
}
// SetState sets the State field's value.
func (s *StreamSummary) SetState(v string) *StreamSummary {
s.State = &v
return s
}
// SetStreamId sets the StreamId field's value.
func (s *StreamSummary) SetStreamId(v string) *StreamSummary {
s.StreamId = &v
return s
}
// SetViewerCount sets the ViewerCount field's value.
func (s *StreamSummary) SetViewerCount(v int64) *StreamSummary {
s.ViewerCount = &v
return s
}
type StreamUnavailable struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// The stream is temporarily unavailable.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamUnavailable) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s StreamUnavailable) GoString() string {
return s.String()
}
func newErrorStreamUnavailable(v protocol.ResponseMetadata) error {
return &StreamUnavailable{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *StreamUnavailable) Code() string {
return "StreamUnavailable"
}
// Message returns the exception's message.
func (s *StreamUnavailable) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *StreamUnavailable) OrigErr() error {
return nil
}
func (s *StreamUnavailable) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *StreamUnavailable) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *StreamUnavailable) RequestID() string {
return s.RespMetadata.RequestID
}
type TagResourceInput struct {
_ struct{} `type:"structure"`
// ARN of the resource for which tags are to be added or updated.
//
// ResourceArn is a required field
ResourceArn *string `location:"uri" locationName:"resourceArn" min:"1" type:"string" required:"true"`
// Array of tags to be added or updated.
//
// Tags is a required field
Tags map[string]*string `locationName:"tags" type:"map" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TagResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if s.ResourceArn != nil && len(*s.ResourceArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1))
}
if s.Tags == nil {
invalidParams.Add(request.NewErrParamRequired("Tags"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetResourceArn sets the ResourceArn field's value.
func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput {
s.ResourceArn = &v
return s
}
// SetTags sets the Tags field's value.
func (s *TagResourceInput) SetTags(v map[string]*string) *TagResourceInput {
s.Tags = v
return s
}
type TagResourceOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TagResourceOutput) GoString() string {
return s.String()
}
type ThrottlingException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// Request was denied due to request throttling.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ThrottlingException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ThrottlingException) GoString() string {
return s.String()
}
func newErrorThrottlingException(v protocol.ResponseMetadata) error {
return &ThrottlingException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ThrottlingException) Code() string {
return "ThrottlingException"
}
// Message returns the exception's message.
func (s *ThrottlingException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ThrottlingException) OrigErr() error {
return nil
}
func (s *ThrottlingException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ThrottlingException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ThrottlingException) RequestID() string {
return s.RespMetadata.RequestID
}
// An object representing a configuration of thumbnails for recorded video.
type ThumbnailConfiguration struct {
_ struct{} `type:"structure"`
// Thumbnail recording mode. Default: INTERVAL.
RecordingMode *string `locationName:"recordingMode" type:"string" enum:"RecordingMode"`
// The targeted thumbnail-generation interval in seconds. This is configurable
// (and required) only if recordingMode is INTERVAL. Default: 60.
//
// Important: Setting a value for targetIntervalSeconds does not guarantee that
// thumbnails are generated at the specified interval. For thumbnails to be
// generated at the targetIntervalSeconds interval, the IDR/Keyframe value for
// the input video must be less than the targetIntervalSeconds value. See Amazon
// IVS Streaming Configuration (https://docs.aws.amazon.com/ivs/latest/userguide/streaming-config.html)
// for information on setting IDR/Keyframe to the recommended value in video-encoder
// settings.
TargetIntervalSeconds *int64 `locationName:"targetIntervalSeconds" min:"5" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ThumbnailConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ThumbnailConfiguration) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ThumbnailConfiguration) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ThumbnailConfiguration"}
if s.TargetIntervalSeconds != nil && *s.TargetIntervalSeconds < 5 {
invalidParams.Add(request.NewErrParamMinValue("TargetIntervalSeconds", 5))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetRecordingMode sets the RecordingMode field's value.
func (s *ThumbnailConfiguration) SetRecordingMode(v string) *ThumbnailConfiguration {
s.RecordingMode = &v
return s
}
// SetTargetIntervalSeconds sets the TargetIntervalSeconds field's value.
func (s *ThumbnailConfiguration) SetTargetIntervalSeconds(v int64) *ThumbnailConfiguration {
s.TargetIntervalSeconds = &v
return s
}
type UntagResourceInput struct {
_ struct{} `type:"structure" nopayload:"true"`
// ARN of the resource for which tags are to be removed.
//
// ResourceArn is a required field
ResourceArn *string `location:"uri" locationName:"resourceArn" min:"1" type:"string" required:"true"`
// Array of tags to be removed.
//
// TagKeys is a required field
TagKeys []*string `location:"querystring" locationName:"tagKeys" type:"list" required:"true"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UntagResourceInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"}
if s.ResourceArn == nil {
invalidParams.Add(request.NewErrParamRequired("ResourceArn"))
}
if s.ResourceArn != nil && len(*s.ResourceArn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1))
}
if s.TagKeys == nil {
invalidParams.Add(request.NewErrParamRequired("TagKeys"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetResourceArn sets the ResourceArn field's value.
func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput {
s.ResourceArn = &v
return s
}
// SetTagKeys sets the TagKeys field's value.
func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput {
s.TagKeys = v
return s
}
type UntagResourceOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UntagResourceOutput) GoString() string {
return s.String()
}
type UpdateChannelInput struct {
_ struct{} `type:"structure"`
// ARN of the channel to be updated.
//
// Arn is a required field
Arn *string `locationName:"arn" min:"1" type:"string" required:"true"`
// Whether the channel is private (enabled for playback authorization).
Authorized *bool `locationName:"authorized" type:"boolean"`
// Channel latency mode. Use NORMAL to broadcast and deliver live video up to
// Full HD. Use LOW for near-real-time interaction with viewers. (Note: In the
// Amazon IVS console, LOW and NORMAL correspond to Ultra-low and Standard,
// respectively.)
LatencyMode *string `locationName:"latencyMode" type:"string" enum:"ChannelLatencyMode"`
// Channel name.
Name *string `locationName:"name" type:"string"`
// Recording-configuration ARN. If this is set to an empty string, recording
// is disabled. A value other than an empty string indicates that recording
// is enabled
RecordingConfigurationArn *string `locationName:"recordingConfigurationArn" type:"string"`
// Channel type, which determines the allowable resolution and bitrate. If you
// exceed the allowable resolution or bitrate, the stream probably will disconnect
// immediately. Valid values:
//
// * STANDARD: Multiple qualities are generated from the original input,
// to automatically give viewers the best experience for their devices and
// network conditions. Resolution can be up to 1080p and bitrate can be up
// to 8.5 Mbps. Audio is transcoded only for renditions 360p and below; above
// that, audio is passed through.
//
// * BASIC: Amazon IVS delivers the original input to viewers. The viewer’s
// video-quality choice is limited to the original input. Resolution can
// be up to 480p and bitrate can be up to 1.5 Mbps.
Type *string `locationName:"type" type:"string" enum:"ChannelType"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateChannelInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateChannelInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateChannelInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UpdateChannelInput"}
if s.Arn == nil {
invalidParams.Add(request.NewErrParamRequired("Arn"))
}
if s.Arn != nil && len(*s.Arn) < 1 {
invalidParams.Add(request.NewErrParamMinLen("Arn", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetArn sets the Arn field's value.
func (s *UpdateChannelInput) SetArn(v string) *UpdateChannelInput {
s.Arn = &v
return s
}
// SetAuthorized sets the Authorized field's value.
func (s *UpdateChannelInput) SetAuthorized(v bool) *UpdateChannelInput {
s.Authorized = &v
return s
}
// SetLatencyMode sets the LatencyMode field's value.
func (s *UpdateChannelInput) SetLatencyMode(v string) *UpdateChannelInput {
s.LatencyMode = &v
return s
}
// SetName sets the Name field's value.
func (s *UpdateChannelInput) SetName(v string) *UpdateChannelInput {
s.Name = &v
return s
}
// SetRecordingConfigurationArn sets the RecordingConfigurationArn field's value.
func (s *UpdateChannelInput) SetRecordingConfigurationArn(v string) *UpdateChannelInput {
s.RecordingConfigurationArn = &v
return s
}
// SetType sets the Type field's value.
func (s *UpdateChannelInput) SetType(v string) *UpdateChannelInput {
s.Type = &v
return s
}
type UpdateChannelOutput struct {
_ struct{} `type:"structure"`
// Object specifying a channel.
Channel *Channel `locationName:"channel" type:"structure"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateChannelOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UpdateChannelOutput) GoString() string {
return s.String()
}
// SetChannel sets the Channel field's value.
func (s *UpdateChannelOutput) SetChannel(v *Channel) *UpdateChannelOutput {
s.Channel = v
return s
}
type ValidationException struct {
_ struct{} `type:"structure"`
RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"`
// The input fails to satisfy the constraints specified by an Amazon Web Services
// service.
ExceptionMessage *string `locationName:"exceptionMessage" type:"string"`
Message_ *string `locationName:"message" type:"string"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ValidationException) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ValidationException) GoString() string {
return s.String()
}
func newErrorValidationException(v protocol.ResponseMetadata) error {
return &ValidationException{
RespMetadata: v,
}
}
// Code returns the exception type name.
func (s *ValidationException) Code() string {
return "ValidationException"
}
// Message returns the exception's message.
func (s *ValidationException) Message() string {
if s.Message_ != nil {
return *s.Message_
}
return ""
}
// OrigErr always returns nil, satisfies awserr.Error interface.
func (s *ValidationException) OrigErr() error {
return nil
}
func (s *ValidationException) Error() string {
return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String())
}
// Status code returns the HTTP status code for the request's response error.
func (s *ValidationException) StatusCode() int {
return s.RespMetadata.StatusCode
}
// RequestID returns the service's response RequestID for request.
func (s *ValidationException) RequestID() string {
return s.RespMetadata.RequestID
}
// Object specifying a stream’s video configuration.
type VideoConfiguration struct {
_ struct{} `type:"structure"`
// Indicates the degree of required decoder performance for a profile. Normally
// this is set automatically by the encoder. For details, see the H.264 specification.
AvcLevel *string `locationName:"avcLevel" type:"string"`
// Indicates to the decoder the requirements for decoding the stream. For definitions
// of the valid values, see the H.264 specification.
AvcProfile *string `locationName:"avcProfile" type:"string"`
// Codec used for the video encoding.
Codec *string `locationName:"codec" type:"string"`
// Software or hardware used to encode the video.
Encoder *string `locationName:"encoder" type:"string"`
// The expected ingest bitrate (bits per second). This is configured in the
// encoder.
TargetBitrate *int64 `locationName:"targetBitrate" type:"long"`
// The expected ingest framerate. This is configured in the encoder.
TargetFramerate *int64 `locationName:"targetFramerate" type:"long"`
// Video-resolution height in pixels.
VideoHeight *int64 `locationName:"videoHeight" type:"long"`
// Video-resolution width in pixels.
VideoWidth *int64 `locationName:"videoWidth" type:"long"`
}
// String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VideoConfiguration) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s VideoConfiguration) GoString() string {
return s.String()
}
// SetAvcLevel sets the AvcLevel field's value.
func (s *VideoConfiguration) SetAvcLevel(v string) *VideoConfiguration {
s.AvcLevel = &v
return s
}
// SetAvcProfile sets the AvcProfile field's value.
func (s *VideoConfiguration) SetAvcProfile(v string) *VideoConfiguration {
s.AvcProfile = &v
return s
}
// SetCodec sets the Codec field's value.
func (s *VideoConfiguration) SetCodec(v string) *VideoConfiguration {
s.Codec = &v
return s
}
// SetEncoder sets the Encoder field's value.
func (s *VideoConfiguration) SetEncoder(v string) *VideoConfiguration {
s.Encoder = &v
return s
}
// SetTargetBitrate sets the TargetBitrate field's value.
func (s *VideoConfiguration) SetTargetBitrate(v int64) *VideoConfiguration {
s.TargetBitrate = &v
return s
}
// SetTargetFramerate sets the TargetFramerate field's value.
func (s *VideoConfiguration) SetTargetFramerate(v int64) *VideoConfiguration {
s.TargetFramerate = &v
return s
}
// SetVideoHeight sets the VideoHeight field's value.
func (s *VideoConfiguration) SetVideoHeight(v int64) *VideoConfiguration {
s.VideoHeight = &v
return s
}
// SetVideoWidth sets the VideoWidth field's value.
func (s *VideoConfiguration) SetVideoWidth(v int64) *VideoConfiguration {
s.VideoWidth = &v
return s
}
const (
// ChannelLatencyModeNormal is a ChannelLatencyMode enum value
ChannelLatencyModeNormal = "NORMAL"
// ChannelLatencyModeLow is a ChannelLatencyMode enum value
ChannelLatencyModeLow = "LOW"
)
// ChannelLatencyMode_Values returns all elements of the ChannelLatencyMode enum
func ChannelLatencyMode_Values() []string {
return []string{
ChannelLatencyModeNormal,
ChannelLatencyModeLow,
}
}
const (
// ChannelTypeBasic is a ChannelType enum value
ChannelTypeBasic = "BASIC"
// ChannelTypeStandard is a ChannelType enum value
ChannelTypeStandard = "STANDARD"
)
// ChannelType_Values returns all elements of the ChannelType enum
func ChannelType_Values() []string {
return []string{
ChannelTypeBasic,
ChannelTypeStandard,
}
}
const (
// RecordingConfigurationStateCreating is a RecordingConfigurationState enum value
RecordingConfigurationStateCreating = "CREATING"
// RecordingConfigurationStateCreateFailed is a RecordingConfigurationState enum value
RecordingConfigurationStateCreateFailed = "CREATE_FAILED"
// RecordingConfigurationStateActive is a RecordingConfigurationState enum value
RecordingConfigurationStateActive = "ACTIVE"
)
// RecordingConfigurationState_Values returns all elements of the RecordingConfigurationState enum
func RecordingConfigurationState_Values() []string {
return []string{
RecordingConfigurationStateCreating,
RecordingConfigurationStateCreateFailed,
RecordingConfigurationStateActive,
}
}
const (
// RecordingModeDisabled is a RecordingMode enum value
RecordingModeDisabled = "DISABLED"
// RecordingModeInterval is a RecordingMode enum value
RecordingModeInterval = "INTERVAL"
)
// RecordingMode_Values returns all elements of the RecordingMode enum
func RecordingMode_Values() []string {
return []string{
RecordingModeDisabled,
RecordingModeInterval,
}
}
const (
// StreamHealthHealthy is a StreamHealth enum value
StreamHealthHealthy = "HEALTHY"
// StreamHealthStarving is a StreamHealth enum value
StreamHealthStarving = "STARVING"
// StreamHealthUnknown is a StreamHealth enum value
StreamHealthUnknown = "UNKNOWN"
)
// StreamHealth_Values returns all elements of the StreamHealth enum
func StreamHealth_Values() []string {
return []string{
StreamHealthHealthy,
StreamHealthStarving,
StreamHealthUnknown,
}
}
const (
// StreamStateLive is a StreamState enum value
StreamStateLive = "LIVE"
// StreamStateOffline is a StreamState enum value
StreamStateOffline = "OFFLINE"
)
// StreamState_Values returns all elements of the StreamState enum
func StreamState_Values() []string {
return []string{
StreamStateLive,
StreamStateOffline,
}
}<|fim▁end|> | req, out := c.TagResourceRequest(input)
req.SetContext(ctx) |
<|file_name|>device_pyusb.py<|end_file_name|><|fim▁begin|># pywws - Python software for USB Wireless Weather Stations
# http://github.com/jim-easterbrook/pywws
# Copyright (C) 2008-15 Jim Easterbrook [email protected]
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Low level USB interface to weather station, using PyUSB v0.4.
Introduction
============
This module handles low level communication with the weather station
via the `PyUSB <http://sourceforge.net/apps/trac/pyusb/>`_ library. It
is one of several USB device modules, each of which uses a different
USB library interface. See :ref:`Installation - USB
library<dependencies-usb>` for details.
Testing
=======
Run :py:mod:`pywws.testweatherstation` with increased verbosity so it
reports which USB device access module is being used::
python -m pywws.testweatherstation -vv
18:28:09:pywws.weatherstation.CUSBDrive:using pywws.device_pyusb
0000 55 aa ff ff ff ff ff ff ff ff ff ff ff ff ff ff 05 20 01 41 11 00 00 00 81 00 00 0f 05 00 e0 51
0020 03 27 ce 27 00 00 00 00 00 00 00 12 02 14 18 27 41 23 c8 00 00 00 46 2d 2c 01 64 80 c8 00 00 00
0040 64 00 64 80 a0 28 80 25 a0 28 80 25 03 36 00 05 6b 00 00 0a 00 f4 01 12 00 00 00 00 00 00 00 00
0060 00 00 49 0a 63 12 05 01 7f 00 36 01 60 80 36 01 60 80 bc 00 7b 80 95 28 12 26 6c 28 25 26 c8 01
0080 1d 02 d8 00 de 00 ff 00 ff 00 ff 00 00 11 10 06 01 29 12 02 01 19 32 11 09 09 05 18 12 01 22 13
00a0 14 11 11 04 15 04 11 12 17 05 12 11 09 02 15 26 12 02 11 07 05 11 09 02 15 26 12 02 11 07 05 11
00c0 09 10 09 12 12 02 02 12 38 12 02 07 19 00 11 12 16 03 27 12 02 03 11 00 11 12 16 03 27 11 12 26
00e0 21 32 11 12 26 21 32 12 02 06 19 57 12 02 06 19 57 12 02 06 19 57 12 02 06 19 57 12 02 06 19 57
API
===
"""<|fim▁hole|>__docformat__ = "restructuredtext en"
import platform
import usb
class USBDevice(object):
def __init__(self, idVendor, idProduct):
"""Low level USB device access via PyUSB library.
:param idVendor: the USB "vendor ID" number, for example 0x1941.
:type idVendor: int
:param idProduct: the USB "product ID" number, for example 0x8021.
:type idProduct: int
"""
dev = self._find_device(idVendor, idProduct)
if not dev:
raise IOError("Weather station device not found")
self.devh = dev.open()
if not self.devh:
raise IOError("Open device failed")
self.devh.reset()
## if platform.system() is 'Windows':
## self.devh.setConfiguration(1)
try:
self.devh.claimInterface(0)
except usb.USBError:
# claim interface failed, try detaching kernel driver first
if not hasattr(self.devh, 'detachKernelDriver'):
raise RuntimeError(
"Please upgrade pyusb (or python-usb) to 0.4 or higher")
try:
self.devh.detachKernelDriver(0)
self.devh.claimInterface(0)
except usb.USBError:
raise IOError("Claim interface failed")
# device may have data left over from an incomplete read
for i in range(4):
try:
self.devh.interruptRead(0x81, 8, 1200)
except usb.USBError:
break
def __del__(self):
if self.devh:
try:
self.devh.releaseInterface()
except usb.USBError:
# interface was not claimed. No problem
pass
def _find_device(self, idVendor, idProduct):
"""Find a USB device by product and vendor id."""
for bus in usb.busses():
for device in bus.devices:
if (device.idVendor == idVendor and
device.idProduct == idProduct):
return device
return None
def read_data(self, size):
"""Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int)
"""
result = self.devh.interruptRead(0x81, size, 1200)
if result is None or len(result) < size:
raise IOError('pywws.device_libusb.USBDevice.read_data failed')
return list(result)
def write_data(self, buf):
"""Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
result = self.devh.controlMsg(
usb.ENDPOINT_OUT + usb.TYPE_CLASS + usb.RECIP_INTERFACE,
usb.REQ_SET_CONFIGURATION, buf, value=0x200, timeout=50)
if result != len(buf):
raise IOError('pywws.device_libusb.USBDevice.write_data failed')
return True<|fim▁end|> | |
<|file_name|>CustomTypeTest.java<|end_file_name|><|fim▁begin|>package org.codehaus.xfire.aegis.example;
import javax.xml.namespace.QName;
import org.codehaus.xfire.aegis.AbstractXFireAegisTest;
import org.codehaus.xfire.aegis.AegisBindingProvider;
import org.codehaus.xfire.aegis.type.TypeMapping;
import org.codehaus.xfire.aegis.type.basic.BeanType;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.codehaus.xfire.services.BeanService;
import org.codehaus.xfire.services.SimpleBean;
import org.codehaus.xfire.soap.SoapConstants;
import org.codehaus.xfire.wsdl.WSDLWriter;
import org.jdom.Document;
/**
* @author <a href="mailto:[email protected]">peter royal</a>
*/
public class CustomTypeTest
extends AbstractXFireAegisTest
{
public void testBeanService()
throws Exception
{
// START SNIPPET: types
ObjectServiceFactory osf = (ObjectServiceFactory) getServiceFactory();
AegisBindingProvider provider = (AegisBindingProvider) osf.getBindingProvider();
TypeMapping tm = provider.getTypeMappingRegistry().getDefaultTypeMapping();
// Create your custom type
BeanType type = new BeanType();
type.setTypeClass(SimpleBean.class);
type.setSchemaType(new QName("urn:ReallyNotSoSimpleBean", "SimpleBean"));
// register the type
tm.register(type);
Service service = getServiceFactory().create(BeanService.class);
getServiceRegistry().register(service);
// END SNIPPET: types
final Document response =
invokeService("BeanService",
"/org/codehaus/xfire/message/wrapped/WrappedCustomTypeTest.bean11.xml");
addNamespace("sb", "http://services.xfire.codehaus.org");
assertValid("/s:Envelope/s:Body/sb:getSubmitBeanResponse", response);
assertValid("//sb:getSubmitBeanResponse/sb:out", response);
assertValid("//sb:getSubmitBeanResponse/sb:out[text()=\"blah\"]", response);
final Document doc = getWSDLDocument("BeanService");
addNamespace("wsdl", WSDLWriter.WSDL11_NS);
addNamespace("wsdlsoap", WSDLWriter.WSDL11_SOAP_NS);
addNamespace("xsd", SoapConstants.XSD);
assertValid("/wsdl:definitions/wsdl:types", doc);
assertValid("/wsdl:definitions/wsdl:types/xsd:schema", doc);
assertValid("/wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='http://services.xfire.codehaus.org']",
doc);
assertValid(
"//xsd:schema[@targetNamespace='http://services.xfire.codehaus.org']/xsd:element[@name='getSubmitBean']",
doc);
assertValid(
"//xsd:element[@name='getSubmitBean']/xsd:complexType/xsd:sequence/xsd:element[@name='bleh'][@type='xsd:string']",
doc);
assertValid(<|fim▁hole|> assertValid("/wsdl:definitions/wsdl:types" +
"/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" +
"/xsd:complexType", doc);
assertValid("/wsdl:definitions/wsdl:types" +
"/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" +
"/xsd:complexType[@name=\"SimpleBean\"]", doc);
assertValid("/wsdl:definitions/wsdl:types" +
"/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" +
"/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@name=\"bleh\"]", doc);
assertValid("/wsdl:definitions/wsdl:types" +
"/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" +
"/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@name=\"howdy\"]", doc);
assertValid("/wsdl:definitions/wsdl:types" +
"/xsd:schema[@targetNamespace='urn:ReallyNotSoSimpleBean']" +
"/xsd:complexType[@name=\"SimpleBean\"]/xsd:sequence/xsd:element[@type=\"xsd:string\"]", doc);
assertValid(
"/wsdl:definitions/wsdl:service/wsdl:port/wsdlsoap:address[@location='http://localhost/services/BeanService']",
doc);
}
}<|fim▁end|> | "//xsd:element[@name='getSubmitBean']/xsd:complexType/xsd:sequence/xsd:element[@name='bean'][@type='ns1:SimpleBean']",
doc);
|
<|file_name|>stable_core.py<|end_file_name|><|fim▁begin|>import jarray
g = gs.open(gs.args[0])
istates = gs.associated(g, "initialState", True).getInitialStates()
ssrv = gs.service("stable")
def copy_path(values, coreNodes):<|fim▁hole|> for idx in coreNodes:
path[i] = values[idx]
i += 1
return path
def unfold_rec(values, jokers, stack, coreNodes):
if len(jokers) < 1:
path = copy_path(values, coreNodes)
if False:
for p in stack:
idx = 0
ident = True
for v in p:
if v != path[idx]:
ident = False
break
idx += 1
if ident:
return
stack.append( path )
return
idx, mx = jokers[0]
njk = jokers[1:]
for v in xrange(mx):
values[idx] = v
unfold_rec(values, njk, stack, coreNodes)
values[idx] = -1
def unfold(values, maxvalues, stack, coreNodes):
n = len(values)
jokers = [ (idx, maxvalues[idx]+1) for idx in xrange(n) if values[idx] == -1 ]
unfold_rec(values, jokers, stack, coreNodes)
return stack
def find_stable_states(model, nodeOrder):
maxvalues = []
coreNodes = []
inputNodes = []
coreOrder = []
idx = 0
for n in nodeOrder:
if n.isInput():
inputNodes.append(idx)
else:
coreNodes.append(idx)
coreOrder.append(n)
maxvalues.append( n.getMaxValue() )
idx += 1
unfoldNodes = xrange(len(coreNodes))
searcher = ssrv.getStableStateSearcher(model)
searcher.call()
paths = searcher.getPaths()
values = paths.getPath()
stack = []
for l in paths:
path = copy_path(values, coreNodes)
#stack.append(l)
unfold(path, maxvalues, stack, unfoldNodes)
for path in stack:
name = istates.nameState(path, coreOrder)
if name is None:
name = ""
state = ""
for v in path:
if v < 0: state += "*"
else: state += "%d" % v
print name + "\t" + state
# Get stable states for all perturbations
model = g.getModel()
find_stable_states(model, g.getNodeOrder())<|fim▁end|> | n = len(coreNodes)
path = jarray.zeros(n, 'b')
i = 0 |
<|file_name|>identity.rs<|end_file_name|><|fim▁begin|>use std::ops::Mul;
use num::One;
use structs::mat;
use traits::operations::{Inv, Transpose};
use traits::geometry::{Translate, Rotate, Transform, AbsoluteRotate};
impl One for mat::Identity {
#[inline]
fn one() -> mat::Identity {
mat::Identity::new()
}
}
impl Inv for mat::Identity {
fn inv(&self) -> Option<mat::Identity> {
Some(mat::Identity::new())
}
fn inv_mut(&mut self) -> bool {
true
}
}
impl<T: Clone> Mul<T> for mat::Identity {
type Output = T;
#[inline]
fn mul(self, other: T) -> T {
other
}
}
impl Transpose for mat::Identity {
#[inline]
fn transpose(&self) -> mat::Identity {
mat::Identity::new()
}
#[inline]
fn transpose_mut(&mut self) {
}
}
impl<V: Clone> Translate<V> for mat::Identity {
#[inline]
fn translate(&self, v: &V) -> V {
v.clone()
}
#[inline]
fn inv_translate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> Rotate<V> for mat::Identity {
#[inline]
fn rotate(&self, v: &V) -> V {
v.clone()
}
#[inline]
fn inv_rotate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> AbsoluteRotate<V> for mat::Identity {
#[inline]
fn absolute_rotate(&self, v: &V) -> V {
v.clone()
}
}
impl<V: Clone> Transform<V> for mat::Identity {
#[inline]<|fim▁hole|> }
#[inline]
fn inv_transform(&self, v: &V) -> V {
v.clone()
}
}<|fim▁end|> | fn transform(&self, v: &V) -> V {
v.clone() |
<|file_name|>test_cheat_sheet_plus.py<|end_file_name|><|fim▁begin|>"""The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`)
<|fim▁hole|>or safe (``include`` doesn't guard against circular reference). For a more complete example, see
`the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_.
"""
import genshi.builder as bldr
import dialects, core
import os
class Page(object):
root = 'test_pages'
def __init__(self,page_name):
self.name = page_name
def get_raw_body(self):
try:
f = open(os.path.join(self.root,self.name + '.txt'),'r')
s = f.read()
f.close()
return s
except IOError:
return None
def exists(self):
try:
f = open(os.path.join(self.root,self.name + '.txt'),'r')
f.close()
return True
except IOError:
return False
def class_func(page_name):
if not Page(page_name).exists():
return 'nonexistent'
def path_func(page_name):
if page_name == 'Home':
return 'FrontPage'
else:
return page_name
## Start of macros
def include(arg_string,body,isblock):
page = Page(arg_string.strip())
return text2html.generate(page.get_raw_body())
def include_raw(arg_string,body,isblock):
page = Page(arg_string.strip())
return bldr.tag.pre(page.get_raw_body(),class_='plain')
def include_source(arg_string,body,isblock):
page = Page(arg_string.strip())
return bldr.tag.pre(text2html.render(page.get_raw_body()))
def source(arg_string,body,isblock):
return bldr.tag.pre(text2html.render(body))
def pre(arg_string,body,isblock):
return bldr.tag.pre(body)
## End of macros
macros = {'include':include,
'include-raw':include_raw,
'include-source':include_source,
'source':source,
'pre':pre
}
def macro_dispatcher(macro_name,arg_string,body,isblock,environ):
if macro_name in macros:
return macros[macro_name](arg_string,body,isblock)
dialect = dialects.create_dialect(dialects.creole11_base,
wiki_links_base_url='',
wiki_links_space_char='',
# use_additions=True,
no_wiki_monospace=False,
wiki_links_class_func=class_func,
wiki_links_path_func=path_func,
macro_func=macro_dispatcher)
text2html = core.Parser(dialect)
if __name__ == '__main__':
text = Page('CheatSheetPlus').get_raw_body()
f = open(os.path.join('test_pages','CheatSheetPlus.html'),'r')
rendered = f.read()
f.close()
f = open(os.path.join('test_pages','template.html'),'r')
template = f.read()
f.close()
out = open(os.path.join('test_pages','out.html'),'w')
out.write(template % text2html(text))
out.close()
assert template % text2html(text) == rendered<|fim▁end|> | |
<|file_name|>ExitMenu.py<|end_file_name|><|fim▁begin|>import pygame
from pygame.locals import *
from Constants import Constants
from FadeTransition import FadeTransition
from Menu import Menu
from GW_Label import GW_Label
from GuiWidgetManager import GuiWidgetManager
from xml.sax import make_parser
from Localization import Localization
import os
class ExitMenu(Menu):
"Exit Menu"
def __init__(self):
"Set up the Exit menu"
Menu.__init__(self,"MoleFusion Exit Menu","sprites/back1.jpg")
self.parser = make_parser()
self.curHandler = Localization()
self.parser.setContentHandler(self.curHandler)
self.parser.parse(open("languages/ExitMenu_" + Constants.LANGUAGE + ".xml"))
self.title = GW_Label(self.curHandler.getText("title"),(0.5,0.1),(27,22,24))
self.game_by = GW_Label(self.curHandler.getText("game"),(0.5,0.3),(240,255,220))
self.music_by = GW_Label(self.curHandler.getText("music"),(0.5,0.5),(240,255,220))
self.web = GW_Label(self.curHandler.getText("web"),(0.5,0.7),(255,255,255))
self.widget_man = GuiWidgetManager([self.title,self.game_by,self.music_by,self.web])
self.time_speed=pygame.time.Clock()
self.exit=False
self.on_enter()
def on_enter(self):
pygame.event.clear()
self.screen.blit(self.background, (0, 0))
pygame.display.flip()
self.exit=False<|fim▁hole|> f = FadeTransition(2000,Constants.FADECOLOR,"to")
del f
self.exit=True
self.widget_man.set_draw(False)
def run(self):
while 1 and self.exit==False:
self.time_speed.tick(Constants.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.on_exit()
elif event.type == KEYDOWN or event.type == MOUSEBUTTONDOWN:
self.on_exit()
else:
pygame.event.post(event) #Reinject the event into the queue for maybe latter process
self.widget_man.run()<|fim▁end|> | self.widget_man.set_draw(True)
def on_exit(self):
pygame.event.clear() |
<|file_name|>test_string.py<|end_file_name|><|fim▁begin|>#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh imports
# Module under test
import bokeh.util.string as bus
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
class Test_escape(object):
def test_default_quote(self):
assert bus.escape("foo'bar") == "foo'bar"
assert bus.escape('foo"bar') == "foo"bar"
def test_quote_False(self):
assert bus.escape("foo'bar", quote=False) == "foo'bar"
assert bus.escape('foo"bar', quote=False) == 'foo"bar'
def test_quote_custom(self):
assert bus.escape("foo'bar", quote=('"'),) == "foo'bar"
assert bus.escape("foo'bar", quote=("'"),) == "foo'bar"
assert bus.escape('foo"bar', quote=("'"),) == 'foo"bar'
assert bus.escape('foo"bar', quote=('"'),) == "foo"bar"
def test_amp(self):
assert bus.escape("foo&bar") == "foo&bar"
def test_lt(self):
assert bus.escape("foo<bar") == "foo<bar"
def test_gt(self):
assert bus.escape("foo>bar") == "foo>bar"
class Test_format_doctring(object):
def test_no_argument(self):
doc__ = "hello world"
assert bus.format_docstring(doc__) == doc__
doc__ = None
assert bus.format_docstring(doc__) == None
def test_arguments_unused(self):
doc__ = "hello world"
assert bus.format_docstring(doc__, 'hello ', not_used='world') == doc__
doc__ = None
assert bus.format_docstring(doc__, 'hello ', not_used='world') == None
def test_arguments(self):
doc__ = "-- {}{as_parameter} --"
assert bus.format_docstring(doc__, 'hello ', as_parameter='world') == "-- hello world --"
doc__ = None
assert bus.format_docstring(doc__, 'hello ', as_parameter='world') == None
class Test_indent(object):
TEXT = "some text\nto indent\n goes here"
def test_default_args(self):
assert bus.indent(self.TEXT) == " some text\n to indent\n goes here"
def test_with_n(self):
assert bus.indent(self.TEXT, n=3) == " some text\n to indent\n goes here"<|fim▁hole|>
def test_with_ch(self):
assert bus.indent(self.TEXT, ch="-") == "--some text\n--to indent\n-- goes here"
class Test_nice_join(object):
def test_default(self):
assert bus.nice_join(["one"]) == "one"
assert bus.nice_join(["one", "two"]) == "one or two"
assert bus.nice_join(["one", "two", "three"]) == "one, two or three"
assert bus.nice_join(["one", "two", "three", "four"]) == "one, two, three or four"
def test_string_conjunction(self):
assert bus.nice_join(["one"], conjuction="and") == "one"
assert bus.nice_join(["one", "two"], conjuction="and") == "one and two"
assert bus.nice_join(["one", "two", "three"], conjuction="and") == "one, two and three"
assert bus.nice_join(["one", "two", "three", "four"], conjuction="and") == "one, two, three and four"
def test_None_conjunction(self):
assert bus.nice_join(["one"], conjuction=None) == "one"
assert bus.nice_join(["one", "two"], conjuction=None) == "one, two"
assert bus.nice_join(["one", "two", "three"], conjuction=None) == "one, two, three"
assert bus.nice_join(["one", "two", "three", "four"], conjuction=None) == "one, two, three, four"
def test_sep(self):
assert bus.nice_join(["one"], sep='; ') == "one"
assert bus.nice_join(["one", "two"], sep='; ') == "one or two"
assert bus.nice_join(["one", "two", "three"], sep='; ') == "one; two or three"
assert bus.nice_join(["one", "two", "three", "four"], sep="; ") == "one; two; three or four"
def test_snakify():
assert bus.snakify("MyClassName") == "my_class_name"
assert bus.snakify("My1Class23Name456") == "my1_class23_name456"
assert bus.snakify("MySUPERClassName") == "my_super_class_name"
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------<|fim▁end|> | |
<|file_name|>framework_file_generator.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python
# -*- coding: utf-8 -*-
# Developped with python 2.7.3
import os
import sys
import tools
import json
print("The frame :")
name = raw_input("-> name of the framework ?")
kmin = float(raw_input("-> Minimum boundary ?"))
kmax = float(raw_input("-> Maximum boundary ?"))
precision = float(raw_input("-> Precision (graduation axe) ?"))
nb_agent_per_graduation = int(raw_input("-> Number of agent per graduation ?"))
print("\nThis script generates the population distribution automatically : nb_agent_per_graduation is mapped.")
print("\n(!) Note : it needs to be improved by following a law (gaussian law for instance), currently it only distributes uniformly.")
<|fim▁hole|> distribution[i] = nb_agent_per_graduation
i+= precision
i = round(i, tools.get_round_precision(precision)) # fix : python >> 0.2 * 0.4
#print json.dumps(distribution); exit()
o = open(name+".frmwrk",'w')
o.write("# A framework is described as above : \n# in following order, we define min_boundary max_boundary precision frequences)\n")
o.write(json.dumps([kmin, kmax, precision, distribution]))
o.close()<|fim▁end|> | i=kmin
distribution = {}
while i < kmax+precision: |
<|file_name|>missile.cpp<|end_file_name|><|fim▁begin|>#include "missile.h"
#include "../../ObjManager.h"
#include "../../autogen/sprites.h"
#include "../../caret.h"
#include "../../common/misc.h"
#include "../../game.h"
#include "../../player.h"
#include "../../sound/SoundManager.h"
#include "../../trig.h"
#include "weapons.h"
#define STATE_WAIT_RECOIL_OVER 1
#define STATE_RECOIL_OVER 2
#define STATE_MISSILE_CAN_EXPLODE 3
struct MissileSettings
{
int maxspeed; // max speed of missile
int hitrange; //
int lifetime; // number of boomflashes to create on impact
int boomrange; // max dist away to create the boomflashes
int boomdamage; // damage dealt by contact with a boomflash (AoE damage)
} missile_settings[] = {
// Level 1-3 regular missile
// maxspd hit, life, range, bmdmg
{0xA00, 16, 10, 16, 1},
{0xA00, 16, 15, 32, 1},
{0xA00, 16, 5, 40, 1},
// Level 1-3 super missile
// maxspd hit, life, range, bmdmg
{0x1400, 12, 10, 16, 2},
{0x1400, 12, 14, 32, 2},
{0x1400, 12, 6, 40, 2}};
INITFUNC(AIRoutines)
{
AFTERMOVE(OBJ_MISSILE_SHOT, ai_missile_shot);
AFTERMOVE(OBJ_SUPERMISSILE_SHOT, ai_missile_shot);
ONTICK(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner_tick);
AFTERMOVE(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner);
}
/*
void c------------------------------() {}
*/
void ai_missile_shot(Object *o)
{
int index = o->shot.level + ((o->type == OBJ_SUPERMISSILE_SHOT) ? 3 : 0);
MissileSettings *settings = &missile_settings[index];
if (o->state == 0)
{
o->shot.damage = 0;
if (o->shot.level == 2)
{
// initilize wavey effect
o->xmark = o->x;
o->ymark = o->y;
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
// don't let it explode until the "recoil" effect is over.
o->state = STATE_WAIT_RECOIL_OVER;
// record position we were fired at (we won't explode until we pass it)
o->xmark2 = player->x;
o->ymark2 = player->y;
}
else
{
o->state = STATE_MISSILE_CAN_EXPLODE;
}
}
// accelerate according to current type and level of missile
// don't use LIMITX here as it can mess up recoil of level 3 super missiles
switch (o->shot.dir)
{
case RIGHT:
o->xinertia += o->shot.accel;
if (o->xinertia > settings->maxspeed)
o->xinertia = settings->maxspeed;
break;
case LEFT:
o->xinertia -= o->shot.accel;
if (o->xinertia < -settings->maxspeed)
o->xinertia = -settings->maxspeed;
break;
case UP:
o->yinertia -= o->shot.accel;
if (o->yinertia < -settings->maxspeed)
o->yinertia = -settings->maxspeed;
break;
case DOWN:
o->yinertia += o->shot.accel;
if (o->yinertia > settings->maxspeed)
o->yinertia = settings->maxspeed;
break;
}
// wavey effect for level 3
// (markx/y is used as a "speed" value here)
if (o->shot.level == 2)
{
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
{
if (o->y >= o->ymark)
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->yinertia += o->speed;
}
else
{
if (o->x >= o->xmark)
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->xinertia += o->speed;
}
}
// check if we hit an enemy
// level 3 missiles can not blow up while they are "recoiling"
// what we do is first wait until they're traveling in the direction
// they're pointing, then wait till they pass the player's original position.
switch (o->state)
{
case STATE_WAIT_RECOIL_OVER:
switch (o->shot.dir)
{
case LEFT:
if (o->xinertia <= 0)
o->state = STATE_RECOIL_OVER;
break;
case RIGHT:
if (o->xinertia >= 0)
o->state = STATE_RECOIL_OVER;
break;
case UP:
if (o->yinertia <= 0)
o->state = STATE_RECOIL_OVER;
break;
case DOWN:
if (o->yinertia >= 0)
o->state = STATE_RECOIL_OVER;
break;
}
if (o->state != STATE_RECOIL_OVER)
break;
case STATE_RECOIL_OVER:
switch (o->shot.dir)
{
case LEFT:
if (o->x <= o->xmark2 - (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case RIGHT:
if (o->x >= o->xmark2 + (2 * CSFI))<|fim▁hole|> o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case DOWN:
if (o->y >= o->ymark2 + (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
}
if (o->state != STATE_MISSILE_CAN_EXPLODE)
break;
case STATE_MISSILE_CAN_EXPLODE:
{
bool blow_up = false;
if (damage_enemies(o))
{
blow_up = true;
}
else
{ // check if we hit a wall
if (o->shot.dir == LEFT && o->blockl)
blow_up = true;
else if (o->shot.dir == RIGHT && o->blockr)
blow_up = true;
else if (o->shot.dir == UP && o->blocku)
blow_up = true;
else if (o->shot.dir == DOWN && o->blockd)
blow_up = true;
}
if (blow_up)
{
NXE::Sound::SoundManager::getInstance()->playSfx(NXE::Sound::SFX::SND_MISSILE_HIT);
if (!shot_destroy_blocks(o))
{
// create the boom-spawner object for the flashes, smoke, and AoE damage
int y = o->CenterY();
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
y -= 3 * CSFI;
Object *sp = CreateBullet(o->CenterX(), y, OBJ_MISSILE_BOOM_SPAWNER);
sp->shot.boomspawner.range = settings->hitrange;
sp->shot.boomspawner.booms_left = settings->lifetime;
sp->shot.damage = settings->boomdamage;
sp->shot.level = settings->boomdamage;
}
o->Delete();
return;
}
}
break;
}
if (--o->shot.ttl < 0)
shot_dissipate(o, EFFECT_STARPOOF);
// smoke trails
if (++o->timer > 2)
{
o->timer = 0;
Caret *trail = effect(o->CenterX() - o->xinertia, o->CenterY() - o->yinertia, EFFECT_SMOKETRAIL);
const int trailspd = 0x400;
switch (o->shot.dir)
{
case LEFT:
trail->xinertia = trailspd;
trail->y -= (2 * CSFI);
break;
case RIGHT:
trail->xinertia = -trailspd;
trail->y -= (2 * CSFI);
break;
case UP:
trail->yinertia = trailspd;
trail->x -= (1 * CSFI);
break;
case DOWN:
trail->yinertia = -trailspd;
trail->x -= (1 * CSFI);
break;
}
}
}
void ai_missile_boom_spawner(Object *o)
{
if (o->state == 0)
{
o->state = 1;
o->timer = 0;
o->xmark = o->x;
o->ymark = o->y;
// give us the same bounding box as the boomflash effects
o->sprite = SPR_BOOMFLASH;
o->invisible = true;
}
if (!(o->shot.boomspawner.booms_left % 3))
{
int range = 0;
switch (o->shot.level)
{
case 1:
range = 16;
break;
case 2:
range = 32;
break;
case 3:
range = 40;
break;
}
int x = o->CenterX() + (random(-range, range) * CSFI);
int y = o->CenterY() + (random(-range, range) * CSFI);
effect(x, y, EFFECT_BOOMFLASH);
missilehitsmoke(x, y, o->shot.boomspawner.range);
}
if (--o->shot.boomspawner.booms_left < 0)
o->Delete();
}
void ai_missile_boom_spawner_tick(Object *o)
{
damage_all_enemies_in_bb(o, FLAG_INVULNERABLE, o->CenterX(), o->CenterY(), o->shot.boomspawner.range);
}
static void missilehitsmoke(int x, int y, int range)
{
int smokex = x + (random(-range, range) * CSFI);
int smokey = y + (random(-range, range) * CSFI);
Object *smoke;
for (int i = 0; i < 2; i++)
{
smoke = CreateObject(smokex, smokey, OBJ_SMOKE_CLOUD);
smoke->sprite = SPR_MISSILEHITSMOKE;
vector_from_angle(random(0, 255), random(0x100, 0x3ff), &smoke->xinertia, &smoke->yinertia);
}
}<|fim▁end|> | o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case UP:
if (o->y <= o->ymark2 - (2 * CSFI)) |
<|file_name|>ActionDelete.java<|end_file_name|><|fim▁begin|>/**
* Copyright 2017-2019 The GreyCat Authors. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package greycat.internal.task;
import greycat.*;
import greycat.base.BaseNode;
import greycat.plugin.Job;
import greycat.struct.Buffer;
class ActionDelete implements Action {
@Override
public void eval(final TaskContext ctx) {
TaskResult previous = ctx.result();
DeferCounter counter = ctx.graph().newCounter(previous.size());
for (int i = 0; i < previous.size(); i++) {
if (previous.get(i) instanceof BaseNode) {
((Node) previous.get(i)).drop(new Callback() {
@Override
public void on(Object result) {<|fim▁hole|> counter.count();
}
});
}
}
counter.then(new Job() {
@Override
public void run() {
previous.clear();
ctx.continueTask();
}
});
}
@Override
public void serialize(final Buffer builder) {
builder.writeString(CoreActionNames.DELETE);
builder.writeChar(Constants.TASK_PARAM_OPEN);
builder.writeChar(Constants.TASK_PARAM_CLOSE);
}
@Override
public final String name() {
return CoreActionNames.DELETE;
}
}<|fim▁end|> | |
<|file_name|>usersubscription.go<|end_file_name|><|fim▁begin|>package apimanagement
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// UserSubscriptionClient is the apiManagement Client
type UserSubscriptionClient struct {
BaseClient
}
// NewUserSubscriptionClient creates an instance of the UserSubscriptionClient client.
func NewUserSubscriptionClient(subscriptionID string) UserSubscriptionClient {
return NewUserSubscriptionClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewUserSubscriptionClientWithBaseURI creates an instance of the UserSubscriptionClient client using a custom
// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure
// stack).
func NewUserSubscriptionClientWithBaseURI(baseURI string, subscriptionID string) UserSubscriptionClient {
return UserSubscriptionClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List lists the collection of subscriptions of the specified user.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// userID - user identifier. Must be unique in the current API Management service instance.
// filter - | Field | Usage | Supported operators | Supported functions
// |</br>|-------------|-------------|-------------|-------------|</br>| name | filter | ge, le, eq, ne, gt, lt
// | substringof, contains, startswith, endswith | </br>| displayName | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| stateComment | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| ownerId | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| scope | filter | ge, le, eq, ne, gt, lt | substringof,
// contains, startswith, endswith | </br>| userId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
// startswith, endswith | </br>| productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
// startswith, endswith | </br>
// top - number of records to return.
// skip - number of records to skip.
func (client UserSubscriptionClient) List(ctx context.Context, resourceGroupName string, serviceName string, userID string, filter string, top *int32, skip *int32) (result SubscriptionCollectionPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/UserSubscriptionClient.List")
defer func() {
sc := -1
if result.sc.Response.Response != nil {
sc = result.sc.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: serviceName,
Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}},
{TargetValue: userID,
Constraints: []validation.Constraint{{Target: "userID", Name: validation.MaxLength, Rule: 80, Chain: nil},
{Target: "userID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: top,
Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}}}}},
{TargetValue: skip,
Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil {
return result, validation.NewError("apimanagement.UserSubscriptionClient", "List", err.Error())
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, userID, filter, top, skip)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.sc.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "List", resp, "Failure sending request")
return
}
result.sc, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "List", resp, "Failure responding to request")
return
}
if result.sc.hasNextLink() && result.sc.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client UserSubscriptionClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, userID string, filter string, top *int32, skip *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": autorest.Encode("path", serviceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"userId": autorest.Encode("path", userID),
}
const APIVersion = "2019-12-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
if top != nil {
queryParameters["$top"] = autorest.Encode("query", *top)
}
if skip != nil {
queryParameters["$skip"] = autorest.Encode("query", *skip)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/users/{userId}/subscriptions", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.<|fim▁hole|>}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client UserSubscriptionClient) ListResponder(resp *http.Response) (result SubscriptionCollection, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client UserSubscriptionClient) listNextResults(ctx context.Context, lastResults SubscriptionCollection) (result SubscriptionCollection, err error) {
req, err := lastResults.subscriptionCollectionPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "apimanagement.UserSubscriptionClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client UserSubscriptionClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, userID string, filter string, top *int32, skip *int32) (result SubscriptionCollectionIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/UserSubscriptionClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, resourceGroupName, serviceName, userID, filter, top, skip)
return
}<|fim▁end|> | func (client UserSubscriptionClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client)) |
<|file_name|>DefaultChannelFuture.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2008 Trustin Heuiseung Lee
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA
*/
package net.gleamynode.netty.channel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import net.gleamynode.netty.logging.Logger;
public class DefaultChannelFuture implements ChannelFuture {
private static final Logger logger =
Logger.getLogger(DefaultChannelFuture.class);
private static final int DEAD_LOCK_CHECK_INTERVAL = 5000;
private static final Throwable CANCELLED = new Throwable();
private final Channel channel;
private final boolean cancellable;
private ChannelFutureListener firstListener;
private List<ChannelFutureListener> otherListeners;
private boolean done;
private Throwable cause;
private int waiters;
public DefaultChannelFuture(Channel channel, boolean cancellable) {
this.channel = channel;
this.cancellable = cancellable;
}
public Channel getChannel() {
return channel;
}
public synchronized boolean isDone() {
return done;
}
public synchronized boolean isSuccess() {
return cause == null;
}
public synchronized Throwable getCause() {
if (cause != CANCELLED) {
return cause;
} else {
return null;
}
}
public synchronized boolean isCancelled() {
return cause == CANCELLED;
}
public void addListener(ChannelFutureListener listener) {
if (listener == null) {
throw new NullPointerException("listener");
}
boolean notifyNow = false;
synchronized (this) {
if (done) {
notifyNow = true;
} else {
if (firstListener == null) {
firstListener = listener;
} else {
if (otherListeners == null) {
otherListeners = new ArrayList<ChannelFutureListener>(1);
}
otherListeners.add(listener);
}
}<|fim▁hole|> }
}
public void removeListener(ChannelFutureListener listener) {
if (listener == null) {
throw new NullPointerException("listener");
}
synchronized (this) {
if (!done) {
if (listener == firstListener) {
if (otherListeners != null && !otherListeners.isEmpty()) {
firstListener = otherListeners.remove(0);
} else {
firstListener = null;
}
} else if (otherListeners != null) {
otherListeners.remove(listener);
}
}
}
}
public ChannelFuture await() throws InterruptedException {
synchronized (this) {
while (!done) {
waiters++;
try {
this.wait(DEAD_LOCK_CHECK_INTERVAL);
checkDeadLock();
} finally {
waiters--;
}
}
}
return this;
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return await(unit.toMillis(timeout));
}
public boolean await(long timeoutMillis) throws InterruptedException {
return await0(timeoutMillis, true);
}
public ChannelFuture awaitUninterruptibly() {
synchronized (this) {
while (!done) {
waiters++;
try {
this.wait(DEAD_LOCK_CHECK_INTERVAL);
} catch (InterruptedException e) {
// Ignore.
} finally {
waiters--;
if (!done) {
checkDeadLock();
}
}
}
}
return this;
}
public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
return awaitUninterruptibly(unit.toMillis(timeout));
}
public boolean awaitUninterruptibly(long timeoutMillis) {
try {
return await0(timeoutMillis, false);
} catch (InterruptedException e) {
throw new InternalError();
}
}
private boolean await0(long timeoutMillis, boolean interruptable) throws InterruptedException {
long startTime = timeoutMillis <= 0 ? 0 : System.currentTimeMillis();
long waitTime = timeoutMillis;
synchronized (this) {
if (done) {
return done;
} else if (waitTime <= 0) {
return done;
}
waiters++;
try {
for (;;) {
try {
this.wait(Math.min(waitTime, DEAD_LOCK_CHECK_INTERVAL));
} catch (InterruptedException e) {
if (interruptable) {
throw e;
}
}
if (done) {
return true;
} else {
waitTime = timeoutMillis
- (System.currentTimeMillis() - startTime);
if (waitTime <= 0) {
return done;
}
}
}
} finally {
waiters--;
if (!done) {
checkDeadLock();
}
}
}
}
private void checkDeadLock() {
// IllegalStateException e = new IllegalStateException(
// "DEAD LOCK: " + ChannelFuture.class.getSimpleName() +
// ".await() was invoked from an I/O processor thread. " +
// "Please use " + ChannelFutureListener.class.getSimpleName() +
// " or configure a proper thread model alternatively.");
//
// StackTraceElement[] stackTrace = e.getStackTrace();
//
// // Simple and quick check.
// for (StackTraceElement s: stackTrace) {
// if (AbstractPollingIoProcessor.class.getName().equals(s.getClassName())) {
// throw e;
// }
// }
//
// // And then more precisely.
// for (StackTraceElement s: stackTrace) {
// try {
// Class<?> cls = DefaultChannelFuture.class.getClassLoader().loadClass(s.getClassName());
// if (IoProcessor.class.isAssignableFrom(cls)) {
// throw e;
// }
// } catch (Exception cnfe) {
// // Ignore
// }
// }
}
public void setSuccess() {
synchronized (this) {
// Allow only once.
if (done) {
return;
}
done = true;
if (waiters > 0) {
this.notifyAll();
}
}
notifyListeners();
}
public void setFailure(Throwable cause) {
synchronized (this) {
// Allow only once.
if (done) {
return;
}
this.cause = cause;
done = true;
if (waiters > 0) {
this.notifyAll();
}
}
notifyListeners();
}
public boolean cancel() {
if (!cancellable) {
return false;
}
synchronized (this) {
// Allow only once.
if (done) {
return false;
}
cause = CANCELLED;
done = true;
if (waiters > 0) {
this.notifyAll();
}
}
notifyListeners();
return true;
}
private void notifyListeners() {
// There won't be any visibility problem or concurrent modification
// because 'ready' flag will be checked against both addListener and
// removeListener calls.
if (firstListener != null) {
notifyListener(firstListener);
firstListener = null;
if (otherListeners != null) {
for (ChannelFutureListener l: otherListeners) {
notifyListener(l);
}
otherListeners = null;
}
}
}
private void notifyListener(ChannelFutureListener l) {
try {
l.operationComplete(this);
} catch (Throwable t) {
logger.warn(
"An exception was thrown by " +
ChannelFutureListener.class.getSimpleName() + ".", t);
}
}
}<|fim▁end|> | }
if (notifyNow) {
notifyListener(listener); |
<|file_name|>test_port.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
import unittest
from org.o3project.odenos.core.component.network.topology.port import Port
class PortTest(unittest.TestCase):
def setUp(self):
self.target = Port('Port', '1', 'PortId', 'NodeId', 'OutLink',
'InLink', {'Key': 'Val'})
def tearDown(self):
pass
def test_constructor(self):
self.assertEqual(self.target._body[Port.TYPE], 'Port')
self.assertEqual(self.target._body[Port.VERSION], '1')
self.assertEqual(self.target._body[Port.PORT_ID], 'PortId')
self.assertEqual(self.target._body[Port.NODE_ID], 'NodeId')
self.assertEqual(self.target._body[Port.OUT_LINK], 'OutLink')
self.assertEqual(self.target._body[Port.IN_LINK], 'InLink')
self.assertEqual(self.target._body[Port.ATTRIBUTES]['Key'], 'Val')
def test_type(self):
self.assertEqual(self.target.type, 'Port')
def test_version(self):
self.assertEqual(self.target.version, '1')
def test_port_id(self):
self.assertEqual(self.target.port_id, 'PortId')
def test_node_id(self):
self.assertEqual(self.target.node_id, 'NodeId')
def test_out_link(self):
self.assertEqual(self.target.out_link, 'OutLink')
def test_in_link(self):
self.assertEqual(self.target.in_link, 'InLink')
def test_attributes(self):
result = self.target.attributes
self.assertEqual(len(result), 1)
self.assertEqual(result['Key'], 'Val')
def test_create_from_packed(self):
packed = self.target.packed_object()
result = Port.create_from_packed(packed)
self.assertEqual(result.type, 'Port')
self.assertEqual(result.version, '1')
self.assertEqual(result.port_id, 'PortId')
self.assertEqual(result.node_id, 'NodeId')<|fim▁hole|> self.assertEqual(result.out_link, 'OutLink')
self.assertEqual(result.in_link, 'InLink')
self.assertEqual(len(result.attributes), 1)
self.assertEqual(result.attributes['Key'], 'Val')
def test_create_from_packed_without_version(self):
packed = {'type': 'Port', 'port_id': 'PortId', 'node_id': 'NodeId',
'out_link': 'OutLink', 'in_link': 'InLink',
'attributes': {'Key': 'Val'}}
result = Port.create_from_packed(packed)
self.assertEqual(result.type, 'Port')
self.assertEqual(result.version, None)
self.assertEqual(result.port_id, 'PortId')
self.assertEqual(result.node_id, 'NodeId')
self.assertEqual(result.out_link, 'OutLink')
self.assertEqual(result.in_link, 'InLink')
self.assertEqual(len(result.attributes), 1)
self.assertEqual(result.attributes['Key'], 'Val')
def test_packed_object(self):
result = self.target.packed_object()
self.assertEqual(result, {'type': 'Port', 'version': '1',
'port_id': 'PortId', 'node_id': 'NodeId',
'out_link': 'OutLink', 'in_link': 'InLink',
'attributes': {'Key': 'Val'}})
if __name__ == "__main__":
unittest.main()<|fim▁end|> | |
<|file_name|>DynamicEntity.go<|end_file_name|><|fim▁begin|>package Server
import (
"reflect"
"strings"
"code.myceliUs.com/Utility"
)
/**
* Implementation of the Entity. Dynamic entity use a map[string]interface {}
* to store object informations. All information in the Entity itself other
* than object are store.
*/
type DynamicEntity struct {
/** The entity uuid **/
uuid string
/** The entity typeName **/
typeName string
/** The parent uuid **/
parentUuid string
/** The relation with it parent **/
parentLnk string
/** Get entity by uuid function **/
getEntityByUuid func(string) (interface{}, error)
/** Put the entity on the cache **/
setEntity func(interface{})
/** Set the uuid function **/
generateUuid func(interface{}) string
}
// Contain entity that need to be save.
var (
needSave_ = make(map[string]bool)
)
func NewDynamicEntity() *DynamicEntity {
entity := new(DynamicEntity)
return entity
}
/**
* Thread safe function
*/
func (this *DynamicEntity) setValue(field string, value interface{}) error {
// Set the uuid if not already exist.
// Now I will try to retreive the entity from the cache.
infos := make(map[string]interface{})
infos["name"] = "setValue"
infos["uuid"] = this.uuid
infos["field"] = field
infos["value"] = value
infos["needSave"] = make(chan bool)
// set the values in the cache.
cache.m_setValue <- infos
needSave := <-infos["needSave"].(chan bool)
if needSave {
needSave_[this.uuid] = true
}
return nil
}
func (this *DynamicEntity) SetFieldValue(field string, value interface{}) error {
needSave_[this.uuid] = true
return this.setValue(field, value)
}
func (this *DynamicEntity) SetNeedSave(val bool) {
if val {
needSave_[this.uuid] = true
} else {
delete(needSave_, this.uuid)
}
}
func (this *DynamicEntity) IsNeedSave() bool {
if _, ok := needSave_[this.uuid]; ok {
return true
}
return false
}
/**
* Thread safe function
*/
func (this *DynamicEntity) getValue(field string) interface{} {
// Set child uuid's here if there is not already sets...
infos := make(map[string]interface{})
infos["name"] = "getValue"
infos["uuid"] = this.uuid
infos["field"] = field
infos["getValue"] = make(chan interface{})
cache.m_getValue <- infos
value := <-infos["getValue"].(chan interface{})
return value
}
func (this *DynamicEntity) GetFieldValue(field string) interface{} {
return this.getValue(field)
}
/**
* Thread safe function, apply only on none array field...
*/
func (this *DynamicEntity) deleteValue(field string) {
// Remove the field itself.
infos := make(map[string]interface{})
infos["name"] = "deleteValue"
infos["uuid"] = this.uuid
infos["field"] = field
cache.m_deleteValue <- infos
}
/**
* That function return a detach copy of the values contain in the object map.
* Only the uuid of all child values are keep. That map can be use to save the content
* of an entity in the cache.
*/
func (this *DynamicEntity) getValues() map[string]interface{} {
// Set child uuid's here if there is not already sets...
infos := make(map[string]interface{})
infos["name"] = "getValues"
infos["uuid"] = this.uuid
infos["getValues"] = make(chan map[string]interface{})
cache.m_getValues <- infos
values := <-infos["getValues"].(chan map[string]interface{})
return values
}
/**
* Remove reference and create sub entity entity.
*/
func (this *DynamicEntity) setObject(obj map[string]interface{}) {
// Here I will create the entity object.
object := make(map[string]interface{})
if obj["TYPENAME"] != nil {
this.typeName = obj["TYPENAME"].(string)
} else {
return
}
if obj["UUID"] != nil {
this.uuid = obj["UUID"].(string)
}
if obj["ParentUuid"] != nil {
this.parentUuid = obj["ParentUuid"].(string)
}
if obj["ParentLnk"] != nil {
this.parentLnk = obj["ParentLnk"].(string)
}
// Set uuid
ids := make([]interface{}, 0)
prototype, _ := GetServer().GetEntityManager().getEntityPrototype(this.typeName, this.typeName[0:strings.Index(this.typeName, ".")])
// skip The first element, the uuid
for i := 1; i < len(prototype.Ids); i++ {
ids = append(ids, obj[prototype.Ids[i]])
}
obj["Ids"] = ids
if len(this.uuid) == 0 {
// In that case I will set it uuid.
obj["UUID"] = generateEntityUuid(this.typeName, this.parentUuid, ids)
this.uuid = obj["UUID"].(string)
}
// Here I will initilalyse sub-entity if there one, so theire map will not be part of this entity.
for i := 0; i < len(prototype.Fields); i++ {
field := prototype.Fields[i]
val := obj[field]
fieldType := prototype.FieldsType[i]
if val != nil {
if strings.HasPrefix(field, "M_") {
if !strings.HasPrefix(fieldType, "[]xs.") && !strings.HasPrefix(fieldType, "xs.") {
if strings.HasPrefix(fieldType, "[]") {
if reflect.TypeOf(val).String() == "[]interface {}" {
uuids := make([]interface{}, 0)
for j := 0; j < len(val.([]interface{})); j++ {
if val.([]interface{})[j] != nil {
if reflect.TypeOf(val.([]interface{})[j]).String() == "map[string]interface {}" {
if val.([]interface{})[j].(map[string]interface{})["TYPENAME"] != nil {
// Set parent information if is not already set.
if !strings.HasSuffix(fieldType, ":Ref") {
val.([]interface{})[j].(map[string]interface{})["ParentUuid"] = obj["UUID"]
val.([]interface{})[j].(map[string]interface{})["ParentLnk"] = field
child := NewDynamicEntity()
child.setObject(val.([]interface{})[j].(map[string]interface{}))
GetServer().GetEntityManager().setEntity(child)
val.([]interface{})[j].(map[string]interface{})["UUID"] = child.GetUuid()
}
// Keep it on the cache
uuids = append(uuids, val.([]interface{})[j].(map[string]interface{})["UUID"])
}
} else {
object[field] = val
}
}
}
if len(uuids) > 0 {
object[field] = uuids
}
} else if reflect.TypeOf(val).String() == "[]map[string]interface {}" {
uuids := make([]interface{}, 0)
for j := 0; j < len(val.([]map[string]interface{})); j++ {
if val.([]map[string]interface{})[j]["TYPENAME"] != nil {
if !strings.HasSuffix(fieldType, ":Ref") {
// Set parent information if is not already set.
val.([]map[string]interface{})[j]["ParentUuid"] = obj["UUID"]
val.([]map[string]interface{})[j]["ParentLnk"] = field
child := NewDynamicEntity()
child.setObject(val.([]map[string]interface{})[j])
// keep the uuid in the map.
val.([]map[string]interface{})[j]["UUID"] = child.GetUuid()
}
// Keep it on the cache
uuids = append(uuids, val.([]map[string]interface{})[j]["UUID"])
} else {
object[field] = val
}
}
if len(uuids) > 0 {
object[field] = uuids
}
} else {
object[field] = val
}
} else {
if reflect.TypeOf(val).String() == "map[string]interface {}" {
if val.(map[string]interface{})["TYPENAME"] != nil {
if !strings.HasSuffix(fieldType, ":Ref") {
// Set parent information if is not already set.
val.(map[string]interface{})["ParentUuid"] = obj["UUID"]
val.(map[string]interface{})["ParentLnk"] = field
child := NewDynamicEntity()
child.setObject(val.(map[string]interface{}))
val.(map[string]interface{})["UUID"] = child.GetUuid()
}
// Keep it on the cache
object[field] = val.(map[string]interface{})["UUID"]
} else {
object[field] = val
}
} else {
object[field] = val
}
}
} else {
object[field] = val
}
} else {
object[field] = val
}
} else {
// Nil value...
if strings.HasPrefix(fieldType, "[]") {
// empty array...
if strings.HasSuffix(fieldType, ":Ref") {
object[field] = make([]string, 0)
} else {
object[field] = make([]interface{}, 0)
}
} else {
object[field] = nil
}
}
}
object["UUID"] = this.uuid
object["TYPENAME"] = this.typeName
object["ParentUuid"] = this.parentUuid
object["ParentLnk"] = this.parentLnk
object["Ids"] = ids
this.setValues(object)
}
/**
* Save the map[string]interface {} for that entity.
*/
func (this *DynamicEntity) setValues(values map[string]interface{}) {
// Set the uuid if not already exist.
// Now I will try to retreive the entity from the cache.
infos := make(map[string]interface{})
infos["name"] = "setValues"
infos["values"] = values
infos["needSave"] = make(chan bool, 0)
// set the values in the cache.
cache.m_setValues <- infos
// wait to see if the entity has change...
this.SetNeedSave(<-infos["needSave"].(chan bool))
LogInfo("---> entity ", this.uuid, "needSave", this.IsNeedSave())
}
/**
* This is function is use to remove a child entity from it parent.
* To remove other field type simply call 'setValue' with the new array values.
*/
func (this *DynamicEntity) removeValue(field string, uuid interface{}) {
values_ := this.getValue(field)
// Here no value aready exist.
if reflect.TypeOf(values_).String() == "[]string" {
values := make([]string, 0)
for i := 0; i < len(values_.([]string)); i++ {
if values_.([]string)[i] != uuid {
values = append(values, values_.([]string)[i])
}
}
this.setValue(field, values)
} else if reflect.TypeOf(values_).String() == "[]interface {}" {
values := make([]interface{}, 0)
for i := 0; i < len(values_.([]interface{})); i++ {
if values_.([]interface{})[i].(string) != uuid {
values = append(values, values_.([]interface{})[i])
}
}
this.setValue(field, values)
} else if reflect.TypeOf(values_).String() == "[]map[string]interface {}" {
values := make([]map[string]interface{}, 0)
for i := 0; i < len(values_.([]map[string]interface{})); i++ {
if values_.([]map[string]interface{})[i]["UUID"].(string) != uuid {
values = append(values, values_.([]map[string]interface{})[i])
}
}
this.setValue(field, values)
}
}
/**
* Return the type name of an entity
*/
func (this *DynamicEntity) GetTypeName() string {<|fim▁hole|> return this.typeName
}
/**
* Each entity must have one uuid.
*/
func (this *DynamicEntity) GetUuid() string {
if len(this.uuid) == 0 {
this.SetUuid(this.generateUuid(this))
}
return this.uuid // Can be an error here.
}
/** Give access to entity manager GetEntityByUuid function from Entities package. **/
func (this *DynamicEntity) SetEntityGetter(fct func(uuid string) (interface{}, error)) {
this.getEntityByUuid = fct
}
/** Give access to entity manager GetEntityByUuid function from Entities package. **/
func (this *DynamicEntity) SetEntitySetter(fct func(entity interface{})) {
this.setEntity = fct
}
/** Set the uuid generator function **/
func (this *DynamicEntity) SetUuidGenerator(fct func(entity interface{}) string) {
this.generateUuid = fct
}
/**
* Return the array of id's for a given entity, it not contain it UUID.
*/
func (this *DynamicEntity) Ids() []interface{} {
ids := make([]interface{}, 0)
typeName := this.GetTypeName()
prototype, err := GetServer().GetEntityManager().getEntityPrototype(typeName, typeName[0:strings.Index(typeName, ".")])
if err != nil {
return ids
}
// skip The first element, the uuid
for i := 1; i < len(prototype.Ids); i++ {
ids = append(ids, this.getValue(prototype.Ids[i]))
}
return ids
}
func (this *DynamicEntity) SetUuid(uuid string) {
if this.uuid != uuid {
this.setValue("UUID", uuid)
this.uuid = uuid // Keep local...
}
}
func (this *DynamicEntity) GetParentUuid() string {
return this.parentUuid
}
func (this *DynamicEntity) SetParentUuid(parentUuid string) {
if this.parentUuid != parentUuid {
this.setValue("ParentUuid", parentUuid)
this.parentUuid = parentUuid
}
}
/**
* The name of the relation with it parent.
*/
func (this *DynamicEntity) GetParentLnk() string {
return this.parentLnk
}
func (this *DynamicEntity) SetParentLnk(lnk string) {
if this.parentLnk != lnk {
this.setValue("ParentLnk", lnk)
this.parentLnk = lnk
}
}
func (this *DynamicEntity) GetParent() interface{} {
parent, err := GetServer().GetEntityManager().getEntityByUuid(this.GetParentUuid())
if err != nil {
return err
}
return parent
}
/**
* Return the list of all it childs.
*/
func (this *DynamicEntity) GetChilds() []interface{} {
var childs []interface{}
// I will get the childs by their uuid's if there already exist.
uuids := this.GetChildsUuid()
for i := 0; i < len(uuids); i++ {
child, _ := GetServer().GetEntityManager().getEntityByUuid(uuids[i])
if child != nil {
childs = append(childs, child)
}
}
return childs
}
/**
* Return the list of all it childs.
*/
func (this *DynamicEntity) GetChildsUuid() []string {
var childs []string
prototype, _ := GetServer().GetEntityManager().getEntityPrototype(this.GetTypeName(), strings.Split(this.GetTypeName(), ".")[0])
for i := 0; i < len(prototype.Fields); i++ {
field := prototype.Fields[i]
if strings.HasPrefix(field, "M_") {
fieldType := prototype.FieldsType[i]
if !strings.HasPrefix(fieldType, "[]xs.") && !strings.HasPrefix(fieldType, "xs.") && !strings.HasSuffix(fieldType, ":Ref") {
val := this.getValue(field)
if val != nil {
if strings.HasPrefix(fieldType, "[]") {
// The value is an array...
if reflect.TypeOf(val).String() == "[]interface {}" {
for j := 0; j < len(val.([]interface{})); j++ {
if Utility.IsValidEntityReferenceName(val.([]interface{})[j].(string)) {
childs = append(childs, val.([]interface{})[j].(string))
}
}
} else if reflect.TypeOf(val).String() == "[]string" {
for j := 0; j < len(val.([]string)); j++ {
if Utility.IsValidEntityReferenceName(val.([]string)[j]) {
childs = append(childs, val.([]string)[j])
}
}
}
} else {
// The value is not an array.
if Utility.IsValidEntityReferenceName(val.(string)) {
childs = append(childs, val.(string))
}
}
}
}
}
}
return childs
}
/**
* Return the list of reference UUID:FieldName where that entity is referenced.
*/
func (this *DynamicEntity) GetReferenced() []string {
referenced := this.getValue("Referenced").([]string)
if referenced == nil {
referenced = make([]string, 0)
this.setValue("Referenced", referenced)
}
// return the list of references
return referenced
}
/**
* Set a reference
*/
func (this *DynamicEntity) SetReferenced(uuid string, field string) {
referenced := this.GetReferenced()
if !Utility.Contains(referenced, uuid+":"+field) {
referenced = append(referenced, uuid+":"+field)
this.setValue("Referenced", referenced)
}
}
/**
* Remove a reference.
*/
func (this *DynamicEntity) RemoveReferenced(uuid string, field string) {
referenced := this.GetReferenced()
referenced_ := make([]string, 0)
for i := 0; i < len(referenced); i++ {
if referenced[i] != uuid+":"+field {
referenced_ = append(referenced_, referenced[i])
}
}
// Set back the value without the uuid:field.
this.setValue("Referenced", referenced_)
}<|fim▁end|> | |
<|file_name|>profiler.py<|end_file_name|><|fim▁begin|># This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs>
# Copyright (C) 2011-2012 Pierre-Antoine Champin <[email protected]> /
# Universite de Lyon <http://www.universite-lyon.fr>
#
# KTBS is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# KTBS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with KTBS. If not, see <http://www.gnu.org/licenses/>.
"""
This kTBS plugin allows to run the profiler on a per-request basis.<|fim▁hole|>
It will generate a temporary file named with the datetime and the URL,
which you can view with bin/view-profiler-dat, or a tool like
https://github.com/pwaller/pyprof2calltree.
Note that the profiler does not run the exact same code as the normal code:
it converts to a list the iterable returned by the WSGI application,
to ensure that all the code is actually ran in the profiler
(rather than differed by a generator).
"""
from cProfile import runctx as run_in_profiler
from datetime import datetime
from os.path import join
from tempfile import gettempdir
from webob import Request
import logging
LOG = logging.getLogger(__name__)
from rdfrest.http_server import \
register_middleware, unregister_middleware, MyResponse, TOP
class ProfilerMiddleware(object):
DIRECTORY = gettempdir()
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
req = Request(environ)
params = environ['rdfrest.parameters']
do_profiling = params.pop('profiler', None)
if do_profiling is None:
resp = req.get_response(self.app)
return resp(environ, start_response)
else:
filename = '%s--%s--%s.profiler.dat' % (
datetime.now().strftime('%Y-%m-%d-%H:%M:%S'),
req.method,
req.url.replace('/', '_'),
)
my_globals = dict(globals())
run_in_profiler("""
global RET
resp = req.get_response(self.app)
RET = list(resp(environ, start_response))
""",
my_globals, locals(),
join(self.DIRECTORY, filename))
return my_globals['RET']
def start_plugin(config):
if config.has_section('profiler') and config.has_option('profiler', 'directory'):
ProfilerMiddleware.DIRECTORY = config.get('profiler', 'directory')
register_middleware(TOP, ProfilerMiddleware)
def stop_plugin():
unregister_middleware(ProfilerMiddleware)<|fim▁end|> |
To enable the profiler, simply add 'profiler' as a URL parameter. |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Modoboa documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 3 22:29:25 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.intersphinx',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Modoboa'
copyright = u'2016, Antoine Nguyen'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.6'
# The full version, including alpha/beta/rc tags.
release = '1.6.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['.build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
html_theme = 'default'
else:
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Modoboadoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Modoboa.tex', u'Modoboa Documentation',
u'Antoine Nguyen', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples<|fim▁hole|># (source start file, name, description, authors, manual section).
man_pages = [
('index', 'modoboa', u'Modoboa Documentation',
[u'Antoine Nguyen'], 1)
]
intersphinx_mapping = {
'amavis': ('http://modoboa-amavis.readthedocs.org/en/latest/', None)
}<|fim▁end|> | |
<|file_name|>task-detail.component.ts<|end_file_name|><|fim▁begin|>/**
* Created by Quentin on 9/15/2016.
*/
import { Component, Input } from '@angular/core';<|fim▁hole|>@Component({
selector: 'task-detail',
templateUrl: './app/components/task-detail/task-detail.component.html',
styleUrls: ['./app/components/task-detail/task-detail.component.css'],
})
export class TaskDetailComponent {
}<|fim▁end|> | |
<|file_name|>Hello-world.js<|end_file_name|><|fim▁begin|>function helloWorld() {<|fim▁hole|><|fim▁end|> | return 'Hello World';
} |
<|file_name|>0003_auto_20161108_1710.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-08 20:10
from __future__ import unicode_literals
from django.db import migrations, models<|fim▁hole|>
class Migration(migrations.Migration):
dependencies = [
('persons', '0002_person_is_staff'),
]
operations = [
migrations.AlterField(
model_name='person',
name='staff_member',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='persons.Person'),
),
]<|fim▁end|> | import django.db.models.deletion |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#<|fim▁hole|># 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Implement upgrade recipes."""<|fim▁end|> | # You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc., |
<|file_name|>ControlMessageEncodingUtils.java<|end_file_name|><|fim▁begin|>package com.qinyadan.monitor.network.util;
import java.util.Map;
import com.qinyadan.monitor.network.control.ControlMessageDecoder;
import com.qinyadan.monitor.network.control.ControlMessageEncoder;
import com.qinyadan.monitor.network.control.ProtocolException;
public final class ControlMessageEncodingUtils {
private static final ControlMessageEncoder encoder = new ControlMessageEncoder();
<|fim▁hole|>
private ControlMessageEncodingUtils() {
}
public static byte[] encode(Map<String, Object> value) throws ProtocolException {
return encoder.encode(value);
}
public static Object decode(byte[] in) throws ProtocolException {
return decoder.decode(in);
}
}<|fim▁end|> | private static final ControlMessageDecoder decoder = new ControlMessageDecoder();
|
<|file_name|>GwUtill.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013 Nivis LLC.
* Email: [email protected]
* Website: http://www.nivis.com
*
* This program is free software: you can redistribute it and/or modify<|fim▁hole|>* the Free Software Foundation, version 3 of the License.
*
* Redistribution and use in source and binary forms must retain this
* copyright notice.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <WHartGateway/GwUtil.h>
#include <WHartGateway/GatewayConfig.h>
#include <WHartGateway/GatewayTypes.h>
#include <WHartStack/WHartStack.h>
namespace hart7 {
namespace gateway {
using namespace stack;
void FillGwIdentityResponse(C000_ReadUniqueIdentifier_Resp * p_pResp, GatewayConfig & config)
{
memset(p_pResp,0, sizeof(C000_ReadUniqueIdentifier_Resp));
// byte 0 = 254 - hardcoded
p_pResp->expandedDeviceType = Gateway_ExpandedType();
p_pResp->minReqPreamblesNo = config.m_u8MinReqPreamblesNo;
p_pResp->protocolMajorRevNo = 7;
p_pResp->deviceRevisionLevel = config.m_u8DevRevisionLevel;
p_pResp->softwareRevisionLevel = config.m_u8SoftwRevisionLevel;
// uint8_t
p_pResp->hardwareRevisionLevel = config.m_u8HWRevisionLevel_PhysicalSignCode >>3; // most significant 5 bits (7-3)
// uint8_t
uint8_t mask = 7; // 00000111
p_pResp->physicalSignalingCode = config.m_u8HWRevisionLevel_PhysicalSignCode & mask; // least significant 3 bits (2-0)
p_pResp->flags = config.m_u8Flags;
p_pResp->deviceID = Gateway_DeviceID24();
p_pResp->minRespPreamblesNo = config.m_u8MinRespPreamblesNo;
p_pResp->maxNoOfDeviceVars = config.m_u8MaxNoOfDevicesVar;
p_pResp->configChangeCounter = config.m_u16ConfigChangeCounter;
p_pResp->extendedFieldDeviceStatus = config.m_u8FlagBits;
uint16_t manufacturerIDCode;
memcpy(&manufacturerIDCode, config.m_u8ManufactCode, sizeof(manufacturerIDCode));
p_pResp->manufacturerIDCode = manufacturerIDCode;
uint16_t privateLabelDistributorCode;
memcpy(&privateLabelDistributorCode, config.m_u8ManufactLabel, sizeof(privateLabelDistributorCode));
p_pResp->privateLabelDistributorCode = privateLabelDistributorCode;
p_pResp->deviceProfile = DeviceProfileCodes_WIRELESSHART_GATEWAY;
}
} // namespace gateway
} // namespace hart7<|fim▁end|> | * it under the terms of the GNU General Public License as published by |
<|file_name|>main.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,<|fim▁hole|>"""A sample app that operates on GCS files with blobstore API's BlobReader."""
import cloudstorage
from google.appengine.api import app_identity
from google.appengine.ext import blobstore
import webapp2
class BlobreaderHandler(webapp2.RequestHandler):
def get(self):
# Get the default Cloud Storage Bucket name and create a file name for
# the object in Cloud Storage.
bucket = app_identity.get_default_gcs_bucket_name()
# Cloud Storage file names are in the format /bucket/object.
filename = '/{}/blobreader_demo'.format(bucket)
# Create a file in Google Cloud Storage and write something to it.
with cloudstorage.open(filename, 'w') as filehandle:
filehandle.write('abcde\n')
# In order to read the contents of the file using the Blobstore API,
# you must create a blob_key from the Cloud Storage file name.
# Blobstore expects the filename to be in the format of:
# /gs/bucket/object
blobstore_filename = '/gs{}'.format(filename)
blob_key = blobstore.create_gs_key(blobstore_filename)
# [START gae_blobstore_reader]
# Instantiate a BlobReader for a given Blobstore blob_key.
blob_reader = blobstore.BlobReader(blob_key)
# Instantiate a BlobReader for a given Blobstore blob_key, setting the
# buffer size to 1 MB.
blob_reader = blobstore.BlobReader(blob_key, buffer_size=1048576)
# Instantiate a BlobReader for a given Blobstore blob_key, setting the
# initial read position.
blob_reader = blobstore.BlobReader(blob_key, position=0)
# Read the entire value into memory. This may take a while depending
# on the size of the value and the size of the read buffer, and is not
# recommended for large values.
blob_reader_data = blob_reader.read()
# Write the contents to the response.
self.response.headers['Content-Type'] = 'text/plain'
self.response.write(blob_reader_data)
# Set the read position back to 0, then read and write 3 bytes.
blob_reader.seek(0)
blob_reader_data = blob_reader.read(3)
self.response.write(blob_reader_data)
self.response.write('\n')
# Set the read position back to 0, then read and write one line (up to
# and including a '\n' character) at a time.
blob_reader.seek(0)
for line in blob_reader:
self.response.write(line)
# [END gae_blobstore_reader]
# Delete the file from Google Cloud Storage using the blob_key.
blobstore.delete(blob_key)
app = webapp2.WSGIApplication([
('/', BlobreaderHandler),
('/blobreader', BlobreaderHandler)], debug=True)<|fim▁end|> | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
<|file_name|>series_rolling_median.py<|end_file_name|><|fim▁begin|># *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.<|fim▁hole|># PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
import pandas as pd
from numba import njit
@njit
def series_rolling_median():
series = pd.Series([4, 3, 5, 2, 6]) # Series of 4, 3, 5, 2, 6
out_series = series.rolling(3).median()
return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0
print(series_rolling_median())<|fim▁end|> | #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
<|file_name|>site_sections_test.go<|end_file_name|><|fim▁begin|>// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hugolib
import (
"fmt"
"path/filepath"
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources/page"
)
func TestNestedSections(t *testing.T) {
var (
c = qt.New(t)
cfg, fs = newTestCfg()
th = newTestHelper(cfg, fs, t)
)
cfg.Set("permalinks", map[string]string{
"perm a": ":sections/:title",
})
pageTemplate := `---
title: T%d_%d
---
Content
`
// Home page
writeSource(t, fs, filepath.Join("content", "_index.md"), fmt.Sprintf(pageTemplate, -1, -1))
// Top level content page
writeSource(t, fs, filepath.Join("content", "mypage.md"), fmt.Sprintf(pageTemplate, 1234, 5))
// Top level section without index content page
writeSource(t, fs, filepath.Join("content", "top", "mypage2.md"), fmt.Sprintf(pageTemplate, 12345, 6))
// Just a page in a subfolder, i.e. not a section.
writeSource(t, fs, filepath.Join("content", "top", "folder", "mypage3.md"), fmt.Sprintf(pageTemplate, 12345, 67))
for level1 := 1; level1 < 3; level1++ {
writeSource(t, fs, filepath.Join("content", "l1", fmt.Sprintf("page_1_%d.md", level1)),
fmt.Sprintf(pageTemplate, 1, level1))
}
// Issue #3586
writeSource(t, fs, filepath.Join("content", "post", "0000.md"), fmt.Sprintf(pageTemplate, 1, 2))
writeSource(t, fs, filepath.Join("content", "post", "0000", "0001.md"), fmt.Sprintf(pageTemplate, 1, 3))
writeSource(t, fs, filepath.Join("content", "elsewhere", "0003.md"), fmt.Sprintf(pageTemplate, 1, 4))
// Empty nested section, i.e. no regular content pages.
writeSource(t, fs, filepath.Join("content", "empty1", "b", "c", "_index.md"), fmt.Sprintf(pageTemplate, 33, -1))
// Index content file a the end and in the middle.
writeSource(t, fs, filepath.Join("content", "empty2", "b", "_index.md"), fmt.Sprintf(pageTemplate, 40, -1))
writeSource(t, fs, filepath.Join("content", "empty2", "b", "c", "d", "_index.md"), fmt.Sprintf(pageTemplate, 41, -1))
// Empty with content file in the middle.
writeSource(t, fs, filepath.Join("content", "empty3", "b", "c", "d", "_index.md"), fmt.Sprintf(pageTemplate, 41, -1))
writeSource(t, fs, filepath.Join("content", "empty3", "b", "empty3.md"), fmt.Sprintf(pageTemplate, 3, -1))
// Section with permalink config
writeSource(t, fs, filepath.Join("content", "perm a", "link", "_index.md"), fmt.Sprintf(pageTemplate, 9, -1))
for i := 1; i < 4; i++ {
writeSource(t, fs, filepath.Join("content", "perm a", "link", fmt.Sprintf("page_%d.md", i)),
fmt.Sprintf(pageTemplate, 1, i))
}
writeSource(t, fs, filepath.Join("content", "perm a", "link", "regular", fmt.Sprintf("page_%d.md", 5)),
fmt.Sprintf(pageTemplate, 1, 5))
writeSource(t, fs, filepath.Join("content", "l1", "l2", "_index.md"), fmt.Sprintf(pageTemplate, 2, -1))
writeSource(t, fs, filepath.Join("content", "l1", "l2_2", "_index.md"), fmt.Sprintf(pageTemplate, 22, -1))
writeSource(t, fs, filepath.Join("content", "l1", "l2", "l3", "_index.md"), fmt.Sprintf(pageTemplate, 3, -1))
for level2 := 1; level2 < 4; level2++ {
writeSource(t, fs, filepath.Join("content", "l1", "l2", fmt.Sprintf("page_2_%d.md", level2)),
fmt.Sprintf(pageTemplate, 2, level2))
}
for level2 := 1; level2 < 3; level2++ {
writeSource(t, fs, filepath.Join("content", "l1", "l2_2", fmt.Sprintf("page_2_2_%d.md", level2)),
fmt.Sprintf(pageTemplate, 2, level2))
}
for level3 := 1; level3 < 3; level3++ {
writeSource(t, fs, filepath.Join("content", "l1", "l2", "l3", fmt.Sprintf("page_3_%d.md", level3)),
fmt.Sprintf(pageTemplate, 3, level3))
}
writeSource(t, fs, filepath.Join("content", "Spaces in Section", "page100.md"), fmt.Sprintf(pageTemplate, 10, 0))
writeSource(t, fs, filepath.Join("layouts", "_default", "single.html"), "<html>Single|{{ .Title }}</html>")
writeSource(t, fs, filepath.Join("layouts", "_default", "list.html"),
`
{{ $sect := (.Site.GetPage "l1/l2") }}
<html>List|{{ .Title }}|L1/l2-IsActive: {{ .InSection $sect }}
{{ range .Paginator.Pages }}
PAG|{{ .Title }}|{{ $sect.InSection . }}
{{ end }}
{{/* https://github.com/gohugoio/hugo/issues/4989 */}}
{{ $sections := (.Site.GetPage "section" .Section).Sections.ByWeight }}
</html>`)
cfg.Set("paginate", 2)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
c.Assert(len(s.RegularPages()), qt.Equals, 21)
tests := []struct {
sections string
verify func(c *qt.C, p page.Page)
}{
{"elsewhere", func(c *qt.C, p page.Page) {
c.Assert(len(p.Pages()), qt.Equals, 1)
for _, p := range p.Pages() {
c.Assert(p.SectionsPath(), qt.Equals, "elsewhere")
}
}},
{"post", func(c *qt.C, p page.Page) {
c.Assert(len(p.Pages()), qt.Equals, 2)
for _, p := range p.Pages() {
c.Assert(p.Section(), qt.Equals, "post")
}
}},
{"empty1", func(c *qt.C, p page.Page) {
// > b,c
c.Assert(getPage(p, "/empty1/b"), qt.IsNil) // No _index.md page.
c.Assert(getPage(p, "/empty1/b/c"), qt.Not(qt.IsNil))
}},
{"empty2", func(c *qt.C, p page.Page) {
// > b,c,d where b and d have _index.md files.
b := getPage(p, "/empty2/b")
c.Assert(b, qt.Not(qt.IsNil))
c.Assert(b.Title(), qt.Equals, "T40_-1")
cp := getPage(p, "/empty2/b/c")
c.Assert(cp, qt.IsNil) // No _index.md
d := getPage(p, "/empty2/b/c/d")
c.Assert(d, qt.Not(qt.IsNil))
c.Assert(d.Title(), qt.Equals, "T41_-1")
c.Assert(cp.Eq(d), qt.Equals, false)
c.Assert(cp.Eq(cp), qt.Equals, true)
c.Assert(cp.Eq("asdf"), qt.Equals, false)
}},
{"empty3", func(c *qt.C, p page.Page) {
// b,c,d with regular page in b
b := getPage(p, "/empty3/b")
c.Assert(b, qt.IsNil) // No _index.md
e3 := getPage(p, "/empty3/b/empty3")
c.Assert(e3, qt.Not(qt.IsNil))<|fim▁hole|> c.Assert(e3.File().LogicalName(), qt.Equals, "empty3.md")
}},
{"empty3", func(c *qt.C, p page.Page) {
xxx := getPage(p, "/empty3/nil")
c.Assert(xxx, qt.IsNil)
}},
{"top", func(c *qt.C, p page.Page) {
c.Assert(p.Title(), qt.Equals, "Tops")
c.Assert(len(p.Pages()), qt.Equals, 2)
c.Assert(p.Pages()[0].File().LogicalName(), qt.Equals, "mypage2.md")
c.Assert(p.Pages()[1].File().LogicalName(), qt.Equals, "mypage3.md")
home := p.Parent()
c.Assert(home.IsHome(), qt.Equals, true)
c.Assert(len(p.Sections()), qt.Equals, 0)
c.Assert(home.CurrentSection(), qt.Equals, home)
active, err := home.InSection(home)
c.Assert(err, qt.IsNil)
c.Assert(active, qt.Equals, true)
c.Assert(p.FirstSection(), qt.Equals, p)
}},
{"l1", func(c *qt.C, p page.Page) {
c.Assert(p.Title(), qt.Equals, "L1s")
c.Assert(len(p.Pages()), qt.Equals, 4) // 2 pages + 2 sections
c.Assert(p.Parent().IsHome(), qt.Equals, true)
c.Assert(len(p.Sections()), qt.Equals, 2)
}},
{"l1,l2", func(c *qt.C, p page.Page) {
c.Assert(p.Title(), qt.Equals, "T2_-1")
c.Assert(len(p.Pages()), qt.Equals, 4) // 3 pages + 1 section
c.Assert(p.Pages()[0].Parent(), qt.Equals, p)
c.Assert(p.Parent().Title(), qt.Equals, "L1s")
c.Assert(p.RelPermalink(), qt.Equals, "/l1/l2/")
c.Assert(len(p.Sections()), qt.Equals, 1)
for _, child := range p.Pages() {
if child.IsSection() {
c.Assert(child.CurrentSection(), qt.Equals, child)
continue
}
c.Assert(child.CurrentSection(), qt.Equals, p)
active, err := child.InSection(p)
c.Assert(err, qt.IsNil)
c.Assert(active, qt.Equals, true)
active, err = p.InSection(child)
c.Assert(err, qt.IsNil)
c.Assert(active, qt.Equals, true)
active, err = p.InSection(getPage(p, "/"))
c.Assert(err, qt.IsNil)
c.Assert(active, qt.Equals, false)
isAncestor, err := p.IsAncestor(child)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, true)
isAncestor, err = child.IsAncestor(p)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, false)
isDescendant, err := p.IsDescendant(child)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = child.IsDescendant(p)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, true)
}
c.Assert(p.Eq(p.CurrentSection()), qt.Equals, true)
}},
{"l1,l2_2", func(c *qt.C, p page.Page) {
c.Assert(p.Title(), qt.Equals, "T22_-1")
c.Assert(len(p.Pages()), qt.Equals, 2)
c.Assert(p.Pages()[0].File().Path(), qt.Equals, filepath.FromSlash("l1/l2_2/page_2_2_1.md"))
c.Assert(p.Parent().Title(), qt.Equals, "L1s")
c.Assert(len(p.Sections()), qt.Equals, 0)
}},
{"l1,l2,l3", func(c *qt.C, p page.Page) {
nilp, _ := p.GetPage("this/does/not/exist")
c.Assert(p.Title(), qt.Equals, "T3_-1")
c.Assert(len(p.Pages()), qt.Equals, 2)
c.Assert(p.Parent().Title(), qt.Equals, "T2_-1")
c.Assert(len(p.Sections()), qt.Equals, 0)
l1 := getPage(p, "/l1")
isDescendant, err := l1.IsDescendant(p)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = l1.IsDescendant(nil)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = nilp.IsDescendant(p)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = p.IsDescendant(l1)
c.Assert(err, qt.IsNil)
c.Assert(isDescendant, qt.Equals, true)
isAncestor, err := l1.IsAncestor(p)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, true)
isAncestor, err = p.IsAncestor(l1)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, false)
c.Assert(p.FirstSection(), qt.Equals, l1)
isAncestor, err = p.IsAncestor(nil)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, false)
isAncestor, err = nilp.IsAncestor(l1)
c.Assert(err, qt.IsNil)
c.Assert(isAncestor, qt.Equals, false)
}},
{"perm a,link", func(c *qt.C, p page.Page) {
c.Assert(p.Title(), qt.Equals, "T9_-1")
c.Assert(p.RelPermalink(), qt.Equals, "/perm-a/link/")
c.Assert(len(p.Pages()), qt.Equals, 4)
first := p.Pages()[0]
c.Assert(first.RelPermalink(), qt.Equals, "/perm-a/link/t1_1/")
th.assertFileContent("public/perm-a/link/t1_1/index.html", "Single|T1_1")
last := p.Pages()[3]
c.Assert(last.RelPermalink(), qt.Equals, "/perm-a/link/t1_5/")
}},
}
home := s.getPage(page.KindHome)
for _, test := range tests {
test := test
t.Run(fmt.Sprintf("sections %s", test.sections), func(t *testing.T) {
t.Parallel()
c := qt.New(t)
sections := strings.Split(test.sections, ",")
p := s.getPage(page.KindSection, sections...)
c.Assert(p, qt.Not(qt.IsNil), qt.Commentf(fmt.Sprint(sections)))
if p.Pages() != nil {
c.Assert(p.Data().(page.Data).Pages(), deepEqualsPages, p.Pages())
}
c.Assert(p.Parent(), qt.Not(qt.IsNil))
test.verify(c, p)
})
}
c.Assert(home, qt.Not(qt.IsNil))
c.Assert(len(home.Sections()), qt.Equals, 9)
c.Assert(s.Info.Sections(), deepEqualsPages, home.Sections())
rootPage := s.getPage(page.KindPage, "mypage.md")
c.Assert(rootPage, qt.Not(qt.IsNil))
c.Assert(rootPage.Parent().IsHome(), qt.Equals, true)
// https://github.com/gohugoio/hugo/issues/6365
c.Assert(rootPage.Sections(), qt.HasLen, 0)
// Add a odd test for this as this looks a little bit off, but I'm not in the mood
// to think too hard a out this right now. It works, but people will have to spell
// out the directory name as is.
// If we later decide to do something about this, we will have to do some normalization in
// getPage.
// TODO(bep)
sectionWithSpace := s.getPage(page.KindSection, "Spaces in Section")
c.Assert(sectionWithSpace, qt.Not(qt.IsNil))
c.Assert(sectionWithSpace.RelPermalink(), qt.Equals, "/spaces-in-section/")
th.assertFileContent("public/l1/l2/page/2/index.html", "L1/l2-IsActive: true", "PAG|T2_3|true")
}
func TestNextInSectionNested(t *testing.T) {
t.Parallel()
pageContent := `---
title: "The Page"
weight: %d
---
Some content.
`
createPageContent := func(weight int) string {
return fmt.Sprintf(pageContent, weight)
}
b := newTestSitesBuilder(t)
b.WithSimpleConfigFile()
b.WithTemplates("_default/single.html", `
Prev: {{ with .PrevInSection }}{{ .RelPermalink }}{{ end }}|
Next: {{ with .NextInSection }}{{ .RelPermalink }}{{ end }}|
`)
b.WithContent("blog/page1.md", createPageContent(1))
b.WithContent("blog/page2.md", createPageContent(2))
b.WithContent("blog/cool/_index.md", createPageContent(1))
b.WithContent("blog/cool/cool1.md", createPageContent(1))
b.WithContent("blog/cool/cool2.md", createPageContent(2))
b.WithContent("root1.md", createPageContent(1))
b.WithContent("root2.md", createPageContent(2))
b.Build(BuildCfg{})
b.AssertFileContent("public/root1/index.html",
"Prev: /root2/|", "Next: |")
b.AssertFileContent("public/root2/index.html",
"Prev: |", "Next: /root1/|")
b.AssertFileContent("public/blog/page1/index.html",
"Prev: /blog/page2/|", "Next: |")
b.AssertFileContent("public/blog/page2/index.html",
"Prev: |", "Next: /blog/page1/|")
b.AssertFileContent("public/blog/cool/cool1/index.html",
"Prev: /blog/cool/cool2/|", "Next: |")
b.AssertFileContent("public/blog/cool/cool2/index.html",
"Prev: |", "Next: /blog/cool/cool1/|")
}<|fim▁end|> | |
<|file_name|>exact_length.py<|end_file_name|><|fim▁begin|>from .validator import Validator
from ..util import register_as_validator
class ExactLength(Validator):<|fim▁hole|> def __init__(self, exact_length):
super(ExactLength, self).__init__()
self.exact_length = exact_length
def validate(self, data, request=None, session=None):
return len(data) >= self.exact_length
register_as_validator(ExactLength)<|fim▁end|> | __validator_name__ = 'exact_length'
|
<|file_name|>messages.js<|end_file_name|><|fim▁begin|>var Message = require('../models/message');
exports.create = function(req, res) {
new Message({
senderID: req.body.senderID,
senderAlias: req.body.senderAlias,
acceptorID: req.body.acceptorID,
acceptorAlias: req.body.acceptorAlias,
subject: req.body.subject,
content: req.body.content
}).save(function(err, message) {
if (err) {
return res.send(400, err);
}
res.send(message);
});
};
exports.list = function(req, res) {
Message.find({}, function(err, messages) {
if (err) {
res.send(500, err);
}
res.send(messages || []);
});
};
exports.remove = function(req, res) {
var delFlag = false;
var saveFlag = false;
Message.findOne({_id: req.params.id}, function(err, doc){
if(doc.senderID == req.user._id){
if(doc.delFromAcceptor == 'true'){
delFlag=true;
}else{
doc.delFromSender = true;
saveFlag = true;
}
}
if(doc.acceptorID == req.user._id){
if(doc.delFromSender == 'true'){
delFlag = true;
}else{
doc.delFromAcceptor = true;
saveFlag = true;
}<|fim▁hole|> err ? res.send(500, err) : res.send('');
})
}
if(delFlag){
doc.remove(function(err, doc) {
err ? res.send(500, err) : res.send('');
});
}
});
};<|fim▁end|> | }
if(saveFlag){
doc.save(function(err, doc){ |
<|file_name|>ptref_tests.py<|end_file_name|><|fim▁begin|># encoding: utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
import urllib
from .check_utils import journey_basic_query
from .tests_mechanism import dataset, AbstractTestFixture
from .check_utils import *
@dataset({"main_ptref_test": {}})
class TestPtRef(AbstractTestFixture):
"""
Test the structure of the ptref response
"""
@staticmethod
def _test_links(response, pt_obj_name):
# Test the validity of links of 'previous', 'next', 'last', 'first'
wanted_links_type = ['previous', 'next', 'last', 'first']
for l in response['links']:
if l['type'] in wanted_links_type:
assert pt_obj_name in l['href']
# Test the consistency between links
wanted_links = [l['href'] for l in response['links'] if l['type'] in wanted_links_type]
if len(wanted_links) <= 1:
return
def _get_dict_to_compare(link):
url_dict = query_from_str(link)
url_dict.pop('start_page', None)
url_dict['url'] = link.split('?')[0]
return url_dict
url_dict = _get_dict_to_compare(wanted_links[0])
for l in wanted_links[1:]:
assert url_dict == _get_dict_to_compare(l)
def test_vj_default_depth(self):
"""default depth is 1"""
response = self.query_region("v1/vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert len(vjs) == 3
vj = vjs[0]
assert vj['id'] == 'vj1'
assert len(vj['stop_times']) == 2
assert vj['stop_times'][0]['arrival_time'] == '101500'
assert vj['stop_times'][0]['departure_time'] == '101500'
assert vj['stop_times'][1]['arrival_time'] == '111000'
assert vj['stop_times'][1]['departure_time'] == '111000'
#we added some comments on the vj, we should have them
com = get_not_null(vj, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == 'hello'
assert "feed_publishers" in response
feed_publishers = response["feed_publishers"]
for feed_publisher in feed_publishers:
is_valid_feed_publisher(feed_publisher)
feed_publisher = feed_publishers[0]
assert (feed_publisher["id"] == "c1")
assert (feed_publisher["name"] == "name-c1")
assert (feed_publisher["license"] == "ls-c1")
assert (feed_publisher["url"] == "ws-c1")
feed_publisher = feed_publishers[1]
assert (feed_publisher["id"] == "builder")
assert (feed_publisher["name"] == "canal tp")
assert (feed_publisher["license"] == "ODBL")
assert (feed_publisher["url"] == "www.canaltp.fr")
def test_vj_depth_0(self):
"""default depth is 1"""
response = self.query_region("v1/vehicle_journeys?depth=0")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=0)
def test_vj_depth_2(self):
"""default depth is 1"""
response = self.query_region("v1/vehicle_journeys?depth=2")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=2)
def test_vj_depth_3(self):
"""default depth is 1"""
response = self.query_region("v1/vehicle_journeys?depth=3")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=3)
def test_vj_show_codes_propagation(self):
"""stop_area:stop1 has a code, we should be able to find it when accessing it by the vj"""
response = self.query_region("stop_areas/stop_area:stop1/vehicle_journeys")
vjs = get_not_null(response, 'vehicle_journeys')
assert vjs
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
stop_points = [get_not_null(st, 'stop_point') for vj in vjs for st in vj['stop_times']]
stops1 = [s for s in stop_points if s['id'] == 'stop_area:stop1']
assert stops1
for stop1 in stops1:
# all reference to stop1 must have it's codes
codes = get_not_null(stop1, 'codes')
code_uic = [c for c in codes if c['type'] == 'code_uic']
assert len(code_uic) == 1 and code_uic[0]['value'] == 'bobette'
def test_ptref_without_current_datetime(self):
"""
stop_area:stop1 without message because _current_datetime is NOW()
"""
response = self.query_region("stop_areas/stop_area:stop1")
assert len(response['disruptions']) == 0
def test_ptref_with_current_datetime(self):
"""
stop_area:stop1 with _current_datetime
"""
response = self.query_region("stop_areas/stop_area:stop1?_current_datetime=20140115T235959")
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
messages = get_not_null(disruptions[0], 'messages')
assert(messages[0]['text']) == 'Disruption on StopArea stop_area:stop1'
def test_contributors(self):
"""test contributor formating"""
response = self.query_region("v1/contributors")
contributors = get_not_null(response, 'contributors')
assert len(contributors) == 1
ctr = contributors[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_datasets(self):
"""test dataset formating"""
response = self.query_region("v1/datasets")
datasets = get_not_null(response, 'datasets')
assert len(datasets) == 1
ds = datasets[0]
assert(ds["id"] == 'd1')
assert(ds["description"] == 'desc-d1')
assert(ds["system"] == 'sys-d1')
def test_contributor_by_dataset(self):
"""test contributor by dataset formating"""
response = self.query_region("datasets/d1/contributors")
ctrs = get_not_null(response, 'contributors')
assert len(ctrs) == 1
ctr = ctrs[0]
assert(ctr["id"] == 'c1')
assert(ctr["website"] == 'ws-c1')
assert(ctr["license"] == 'ls-c1')
def test_dataset_by_contributor(self):
"""test dataset by contributor formating"""
response = self.query_region("contributors/c1/datasets")
frs = get_not_null(response, 'datasets')
assert len(frs) == 1
fr = frs[0]
assert(fr["id"] == 'd1')
def test_line(self):
"""test line formating"""
response = self.query_region("v1/lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
assert l["text_color"] == 'FFD700'
#we know we have a geojson for this test so we can check it
geo = get_not_null(l, 'geojson')
shape(geo)
com = get_not_null(l, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
physical_modes = get_not_null(l, 'physical_modes')
assert len(physical_modes) == 1
is_valid_physical_mode(physical_modes[0], depth_check=1)
assert physical_modes[0]['id'] == 'physical_mode:Car'
assert physical_modes[0]['name'] == 'name physical_mode:Car'
line_group = get_not_null(l, 'line_groups')
assert len(line_group) == 1
is_valid_line_group(line_group[0], depth_check=0)
assert line_group[0]['name'] == 'A group'
assert line_group[0]['id'] == 'group:A'
self._test_links(response, 'lines')
def test_line_without_shape(self):
"""test line formating with shape disabled"""
response = self.query_region("v1/lines?disable_geojson=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we don't want a geojson since we have desactivate them
assert 'geojson' not in l
response = self.query_region("v1/lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
l = lines[0]
is_valid_line(l, depth_check=1)
#we check our geojson, just to be safe :)
assert 'geojson' in l
geo = get_not_null(l, 'geojson')
shape(geo)
def test_line_groups(self):
"""test line group formating"""
# Test for each possible range to ensure main_line is always at a depth of 0
for depth in range(0,3):
response = self.query_region("line_groups?depth={0}".format(depth))
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg, depth_check=depth)
if depth > 0:
com = get_not_null(lg, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
# test if line_groups are accessible through the ptref graph
response = self.query_region("routes/line:A:0/line_groups")
line_groups = get_not_null(response, 'line_groups')
assert len(line_groups) == 1
lg = line_groups[0]
is_valid_line_group(lg)
def test_line_codes(self):
"""test line formating"""
response = self.query_region("v1/lines/line:A?show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
l = lines[0]
codes = get_not_null(l, 'codes')
assert len(codes) == 4
is_valid_codes(codes)
def test_route(self):
"""test line formating"""
response = self.query_region("v1/routes")
routes = get_not_null(response, 'routes')
assert len(routes) == 3
r = [r for r in routes if r['id'] == 'line:A:0']
assert len(r) == 1
r = r[0]
is_valid_route(r, depth_check=1)
#we know we have a geojson for this test so we can check it
geo = get_not_null(r, 'geojson')
shape(geo)
com = get_not_null(r, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "I'm a happy comment"
self._test_links(response, 'routes')
def test_stop_areas(self):
"""test stop_areas formating"""
response = self.query_region("v1/stop_areas")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop1'))
is_valid_stop_area(s, depth_check=1)
com = get_not_null(s, 'comments')
assert len(com) == 2
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "comment on stop A"
assert com[1]['type'] == 'standard'
assert com[1]['value'] == "the stop is sad"
self._test_links(response, 'stop_areas')
def test_stop_area(self):
"""test stop_areas formating"""
response = self.query_region("v1/stop_areas/stop_area:stop1?depth=2")
stops = get_not_null(response, 'stop_areas')
assert len(stops) == 1
is_valid_stop_area(stops[0], depth_check=2)
modes = get_not_null(stops[0], 'physical_modes')
assert len(modes) == 1
modes = get_not_null(stops[0], 'commercial_modes')
assert len(modes) == 1
def test_stop_points(self):
"""test stop_points formating"""
response = self.query_region("v1/stop_points?depth=2")
stops = get_not_null(response, 'stop_points')
assert len(stops) == 3
s = next((s for s in stops if s['name'] == 'stop_area:stop2'))# yes, that's a stop_point
is_valid_stop_point(s, depth_check=2)
com = get_not_null(s, 'comments')
assert len(com) == 1
assert com[0]['type'] == 'standard'
assert com[0]['value'] == "hello bob"
modes = get_not_null(s, 'physical_modes')
assert len(modes) == 1
modes = get_not_null(s, 'commercial_modes')
assert len(modes) == 1
self._test_links(response, 'stop_points')
def test_company_default_depth(self):
"""default depth is 1"""
response = self.query_region("v1/companies")
companies = get_not_null(response, 'companies')
for company in companies:
is_valid_company(company, depth_check=1)
#we check afterward that we have the right data
#we know there is only one vj in the dataset
assert len(companies) == 1
company = companies[0]
assert company['id'] == 'CMP1'
self._test_links(response, 'companies')
def test_simple_crow_fly(self):
journey_basic_query = "journeys?from=9;9.001&to=stop_area%3Astop2&datetime=20140105T000000"
response = self.query_region(journey_basic_query)
#the response must be still valid (this test the kraken data reloading)
self.is_valid_journey_response(response, journey_basic_query)
def test_forbidden_uris_on_line(self):
"""test forbidden uri for lines"""
response = self.query_region("v1/lines")
lines = get_not_null(response, 'lines')
assert len(lines) == 3
assert len(lines[0]['physical_modes']) == 1
assert lines[0]['physical_modes'][0]['id'] == 'physical_mode:Car'
#there is only one line, so when we forbid it's physical mode, we find nothing
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Car")
assert code == 404
# for retrocompatibility purpose forbidden_id[] is the same
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_id[]=physical_mode:Car")
assert code == 404
# when we forbid another physical_mode, we find again our line
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines"
"?forbidden_uris[]=physical_mode:Bus")
assert code == 200
def test_simple_pt_objects(self):
response = self.query_region('pt_objects?q=stop2')
is_valid_pt_objects_response(response)
pt_objs = get_not_null(response, 'pt_objects')
assert len(pt_objs) == 1
assert get_not_null(pt_objs[0], 'id') == 'stop_area:stop2'
def test_query_with_strange_char(self):
q = b'stop_points/stop_point:stop_with name bob \" , é'
encoded_q = urllib.quote(q)
response = self.query_region(encoded_q)
stops = get_not_null(response, 'stop_points')
assert len(stops) == 1
is_valid_stop_point(stops[0], depth_check=1)
assert stops[0]["id"] == u'stop_point:stop_with name bob \" , é'
def test_filter_query_with_strange_char(self):
"""test that the ptref mechanism works an object with a weird id"""
response = self.query_region('stop_points/stop_point:stop_with name bob \" , é/lines')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_filter_query_with_strange_char_in_filter(self):
"""test that the ptref mechanism works an object with a weird id passed in filter args"""
response = self.query_region('lines?filter=stop_point.uri="stop_point:stop_with name bob \\\" , é"')
lines = get_not_null(response, 'lines')
assert len(lines) == 1
for l in lines:
is_valid_line(l)
def test_journey_with_strange_char(self):
#we use an encoded url to be able to check the links
query = 'journeys?from={}&to={}&datetime=20140105T070000'.format(urllib.quote_plus(b'stop_with name bob \" , é'), urllib.quote_plus(b'stop_area:stop1'))
response = self.query_region(query, display=True)
self.is_valid_journey_response(response, query)
def test_vj_period_filter(self):
"""with just a since in the middle of the period, we find vj1"""
response = self.query_region("vehicle_journeys?since=20140105T070000")
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert 'vj1' in (vj['id'] for vj in vjs)
# same with an until at the end of the day
response = self.query_region("vehicle_journeys?since=20140105T000000&until=20140106T0000")
vjs = get_not_null(response, 'vehicle_journeys')
assert 'vj1' in (vj['id'] for vj in vjs)
# there is no vj after the 8
response, code = self.query_no_assert("v1/coverage/main_ptref_test/vehicle_journeys?since=20140109T070000")
assert code == 404
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_line_by_code(self):
"""test the filter=type.has_code(key, value)"""
response = self.query_region("lines?filter=line.has_code(codeB, B)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeB, Bise)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response = self.query_region("lines?filter=line.has_code(codeC, C)&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'B' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'codeB']
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeB, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
response, code = self.query_no_assert("v1/coverage/main_ptref_test/lines?filter=line.has_code(codeC, rien)&show_codes=true")
assert code == 400
assert get_not_null(response, 'error')['message'] == 'ptref : Filters: Unable to find object'
def test_pt_ref_internal_method(self):
from jormungandr import i_manager
from navitiacommon import type_pb2
i = i_manager.instances['main_ptref_test']
assert len([r for r in i.ptref.get_objs(type_pb2.ROUTE)]) == 3
@dataset({"main_ptref_test": {}, "main_routing_test": {}})
class TestPtRefRoutingAndPtrefCov(AbstractTestFixture):
def test_external_code(self):
"""test the strange and ugly external code api"""
response = self.query("v1/lines?external_code=A&show_codes=true")
lines = get_not_null(response, 'lines')
assert len(lines) == 1
assert 'A' in [code['value'] for code in lines[0]['codes'] if code['type'] == 'external_code']
def test_invalid_url(self):
"""the following bad url was causing internal errors, it should only be a 404"""
_, status = self.query_no_assert("v1/coverage/lines/bob")
eq_(status, 404)
@dataset({"main_routing_test": {}})
class TestPtRefRoutingCov(AbstractTestFixture):
def test_with_coords(self):
"""test with a coord in the pt call, so a place nearby is actually called"""
response = self.query_region("coords/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
eq_(len(stops), 2)
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord(self):
"""some but with coord and not coords"""
response = self.query_region("coord/{coord}/stop_areas".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have A and C
eq_(len(stops), 2)
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_distance_different(self):
"""same as test_with_coord, but with 300m radius. so we find all stops"""
response = self.query_region("coords/{coord}/stop_areas?distance=300".format(coord=r_coord))
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
eq_(len(stops), 3)
assert set(["stopA", "stopB", "stopC"]) == set([s['name'] for s in stops])
def test_with_coord_and_filter(self):
"""
we now test with a more complex query, we want all stops with a metro within 300m of r
only A and C have a metro line
Note: the metro is physical_mode:0x1
"""
response = self.query_region("physical_modes/physical_mode:0x1/coords/{coord}/stop_areas"
"?distance=300".format(coord=r_coord), display=True)
stops = get_not_null(response, 'stop_areas')
for s in stops:
is_valid_stop_area(s)
#the default is the search for all stops within 200m, so we should have all 3 stops
#we should have 3 stops
eq_(len(stops), 2)
assert set(["stopA", "stopC"]) == set([s['name'] for s in stops])
def test_all_lines(self):
"""test with all lines in the pt call"""
response = self.query_region('lines')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 4)
assert {"1A", "1B", "1C", "1D"} == {l['code'] for l in lines}
def test_line_filter_line_code(self):
"""test filtering lines from line code 1A in the pt call"""
response = self.query_region('lines?filter=line.code=1A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 1)
assert "1A" == lines[0]['code']
def test_line_filter_line_code_with_resource_uri(self):
"""test filtering lines from line code 1A in the pt call with a resource uri"""
response = self.query_region('physical_modes/physical_mode:0x1/lines?filter=line.code=1D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 1)
assert "1D" == lines[0]['code']
def test_line_filter_line_code_empty_response(self):
"""test filtering lines from line code bob in the pt call
as no line has the code "bob" response returns no object"""
url = 'v1/coverage/main_routing_test/lines?filter=line.code=bob'
response, status = self.query_no_assert(url)
assert status == 400
assert 'error' in response
assert 'bad_filter' in response['error']['id']
def test_line_filter_route_code_ignored(self):
"""test filtering lines from route code bob in the pt call
as there is no attribute "code" for route, filter is invalid and ignored"""
response_all_lines = self.query_region('lines')
all_lines = get_not_null(response_all_lines, 'lines')
response = self.query_region('lines?filter=route.code=bob')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 4)
assert {l['code'] for l in all_lines} == {l['code'] for l in lines}
def test_route_filter_line_code(self):
"""test filtering routes from line code 1B in the pt call"""
response = self.query_region('routes?filter=line.code=1B')
assert 'error' not in response
routes = get_not_null(response, 'routes')
eq_(len(routes), 1)
assert "1B" == routes[0]['line']['code']
def test_headsign(self):
"""test basic usage of headsign"""
response = self.query_region('vehicle_journeys?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
eq_(len(vjs), 1)
def test_headsign_with_resource_uri(self):
"""test usage of headsign with resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
eq_(len(vjs), 1)
def test_headsign_with_code_filter_and_resource_uri(self):
"""test usage of headsign with code filter and resource uri"""
response = self.query_region('physical_modes/physical_mode:0x0/vehicle_journeys'
'?headsign=vjA&filter=line.code=1A')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
eq_(len(vjs), 1)
def test_multiple_resource_uri_no_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
then with multiple resource uris giving no result as nothing matches"""
response = self.query_region('physical_modes/physical_mode:0x0/lines/A')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 1)
response = self.query_region('lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 1)
response = self.query_region('physical_modes/physical_mode:0x1/lines/D')
assert 'error' not in response
lines = get_not_null(response, 'lines')
eq_(len(lines), 1)
response, status = self.query_region('physical_modes/physical_mode:0x0/lines/D', False)
assert status == 404
assert 'error' in response
assert 'unknown_object' in response['error']['id']
def test_multiple_resource_uri_with_final_collection_uri(self):
"""test usage of multiple resource uris with line and physical mode giving result,
as we match it with a final collection, so the intersection is what we want"""
response = self.query_region('physical_modes/physical_mode:0x1/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
eq_(len(stop_areas), 2)
response = self.query_region('physical_modes/physical_mode:0x0/lines/D/stop_areas')
assert 'error' not in response
stop_areas = get_not_null(response, 'stop_areas')
eq_(len(stop_areas), 1)
def test_headsign_stop_time_vj(self):
"""test basic print of headsign in stop_times for vj"""
response = self.query_region('vehicle_journeys?filter=vehicle_journey.name="vjA"')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
eq_(len(vjs), 1)
eq_(len(vjs[0]['stop_times']), 2)
eq_(vjs[0]['stop_times'][0]['headsign'], "A00")
eq_(vjs[0]['stop_times'][1]['headsign'], "vjA")
def test_headsign_display_info_journeys(self):
"""test basic print of headsign in section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
eq_(len(journeys), 1)
eq_(len(journeys[0]['sections']), 1)
eq_(journeys[0]['sections'][0]['display_informations']['headsign'], "A00")
def test_headsign_display_info_departures(self):
"""test basic print of headsign in display informations for departures"""
response = self.query_region('stop_points/stop_point:stopB/departures?from_datetime=20120615T000000')
assert 'error' not in response
departures = get_not_null(response, 'departures')
eq_(len(departures), 2)
assert {"A00", "vjB"} == {d['display_informations']['headsign'] for d in departures}
def test_headsign_display_info_arrivals(self):
"""test basic print of headsign in display informations for arrivals"""
response = self.query_region('stop_points/stop_point:stopB/arrivals?from_datetime=20120615T000000')
assert 'error' not in response
arrivals = get_not_null(response, 'arrivals')
eq_(len(arrivals), 1)
eq_(arrivals[0]['display_informations']['headsign'], "vehicle_journey 2")
def test_headsign_display_info_route_schedules(self):
"""test basic print of headsign in display informations for route schedules"""
response = self.query_region('routes/A:0/route_schedules?from_datetime=20120615T000000')
assert 'error' not in response
route_schedules = get_not_null(response, 'route_schedules')
eq_(len(route_schedules), 1)
eq_(len(route_schedules[0]['table']['headers']), 1)
display_info = route_schedules[0]['table']['headers'][0]['display_informations']
eq_(display_info['headsign'], "vjA")
assert {"A00", "vjA"} == set(display_info['headsigns'])
def test_trip_id_vj(self):
"""test basic print of trip and its id in vehicle_journeys"""
response = self.query_region('vehicle_journeys')
assert 'error' not in response
vjs = get_not_null(response, 'vehicle_journeys')
for vj in vjs:
is_valid_vehicle_journey(vj, depth_check=1)
assert any(vj['name'] == "vjB" and vj['trip']['id'] == "vjB" for vj in vjs)
def test_disruptions(self):
"""test the /disruptions api"""
response = self.query_region('disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 9
for d in disruptions:
is_valid_disruption(d)
# in pt_ref, the status is always active as the checked
# period is the validity period
assert d["status"] == "active"
# we test that we can access a specific disruption
response = self.query_region('disruptions/too_bad_line_C')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 1
# we can also display all disruptions of an object
response = self.query_region('lines/C/disruptions')
disruptions = get_not_null(response, 'disruptions')
assert len(disruptions) == 2
disruptions_uris = set([d['uri'] for d in disruptions])
eq_({"too_bad_line_C", "too_bad_all_lines"}, disruptions_uris)
# we can't access object from the disruption though (we don't think it to be useful for the moment)
response, status = self.query_region('disruptions/too_bad_line_C/lines', check=False)
eq_(status, 404)
e = get_not_null(response, 'error')
assert e['id'] == 'unknown_object'<|fim▁hole|> def test_trips(self):
"""test the /trips api"""
response = self.query_region('trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 4
for t in trips:
is_valid_trip(t)
# we test that we can access a specific trip
response = self.query_region('trips/vjA')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjA"
# we can also display trip of a vj
response = self.query_region('vehicle_journeys/vjB/trips')
trips = get_not_null(response, 'trips')
assert len(trips) == 1
assert get_not_null(trips[0], 'id') == "vjB"
def test_attributs_in_display_info_journeys(self):
"""test some attributs in display_information of a section for journeys"""
response = self.query_region('journeys?from=stop_point:stopB&to=stop_point:stopA&datetime=20120615T000000')
assert 'error' not in response
journeys = get_not_null(response, 'journeys')
eq_(len(journeys), 1)
eq_(len(journeys[0]['sections']), 1)
eq_(journeys[0]['sections'][0]['display_informations']['headsign'], "A00")
eq_(journeys[0]['sections'][0]['display_informations']['color'], "289728")
eq_(journeys[0]['sections'][0]['display_informations']['text_color'], "FFD700")<|fim▁end|> | assert e['message'] == 'ptref : Filters: Unable to find object'
|
<|file_name|>detail-quick.js<|end_file_name|><|fim▁begin|>/************************************************************************<|fim▁hole|> * This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
Espo.define('Views.Email.Record.DetailQuick', 'Views.Email.Record.Detail', function (Dep, Detail) {
return Dep.extend({
isWide: true,
sideView: false,
init: function () {
Dep.prototype.init.call(this);
this.columnCount = 2;
},
setup: function () {
Dep.prototype.setup.call(this);
},
});
});<|fim▁end|> | |
<|file_name|>test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
# -*- coding: UTF-8 -*-
import argparse
import os
import re
import subprocess
import sys
import traceback
import json
def main():
parser = argparse.ArgumentParser(description='Test discovery for Zabbix',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--discovery", dest="discovery", action='store_true', help="Режим обнаружения")
parser.add_argument('integers', metavar='N', type=int, nargs='*',
help='an integer for the accumulator')
args = parser.parse_args()
if args.discovery:
data = [
{"{#T1}": "1","{#T2}": "1"},
{"{#T1}": "1","{#T2}": "2"},
{"{#T1}": "2","{#T2}": "1"},
{"{#T1}": "2","{#T2}": "2"}
]
result = json.dumps({"data": data})
print result
else:
print str(args.integers[0] + args.integers[1])
if __name__ == "__main__":
try:
main()
except Exception, ex:
traceback.print_exc(file=sys.stdout)<|fim▁hole|><|fim▁end|> | exit(1)
exit(0) |
<|file_name|>SequentialTaskMaster.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.droids.impl;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import org.apache.droids.api.DelayTimer;
import org.apache.droids.api.Droid;
import org.apache.droids.api.Task;
import org.apache.droids.api.TaskExceptionHandler;
import org.apache.droids.api.TaskExceptionResult;
import org.apache.droids.api.TaskMaster;
import org.apache.droids.api.Worker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SequentialTaskMaster<T extends Task> implements TaskMaster<T>
{
private static final Logger LOG = LoggerFactory.getLogger(SequentialTaskMaster.class);
private final Object mutex;
private volatile boolean completed;
private volatile Date startedWorking = null;
private volatile Date finishedWorking = null;
private volatile int completedTask = 0;
private volatile T lastCompletedTask = null;
private volatile ExecutionState state = ExecutionState.INITIALIZED;
private DelayTimer delayTimer = null;
private TaskExceptionHandler exHandler = null;
public SequentialTaskMaster() {
super();
this.mutex = new Object();
}
/**
* The queue has been initialized
*/
@Override
public synchronized void start(final Queue<T> queue, final Droid<T> droid) {
this.completed = false;
this.startedWorking = new Date();
this.finishedWorking = null;
this.completedTask = 0;
this.state = ExecutionState.RUNNING;
boolean terminated = false;
while (!terminated) {
T task = queue.poll();<|fim▁hole|> if (task == null) {
break;
}
if (delayTimer != null) {
long delay = delayTimer.getDelayMillis();
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
}
Worker<T> worker = droid.getNewWorker();
try {
if (!task.isAborted()) {
worker.execute(task);
}
completedTask++;
lastCompletedTask = task;
} catch (Exception ex) {
TaskExceptionResult result = TaskExceptionResult.WARN;
if (exHandler != null) {
result = exHandler.handleException(ex);
}
switch (result) {
case WARN:
LOG.warn(ex.toString() + " " + task.getId());
if (LOG.isDebugEnabled()) {
LOG.debug(ex.toString(), ex);
}
break;
case FATAL:
LOG.error(ex.getMessage(), ex);
terminated = true;
break;
}
}
}
finishedWorking = new Date();
this.state = ExecutionState.STOPPED;
droid.finished();
synchronized (mutex) {
completed = true;
mutex.notifyAll();
}
}
@Override
public final void setExceptionHandler(TaskExceptionHandler exHandler) {
this.exHandler = exHandler;
}
@Override
public final void setDelayTimer(DelayTimer delayTimer) {
this.delayTimer = delayTimer;
}
public boolean isWorking() {
return startedWorking != null && finishedWorking == null;
}
@Override
public Date getStartTime() {
return startedWorking;
}
@Override
public Date getFinishedWorking() {
return finishedWorking;
}
@Override
public long getCompletedTasks() {
return completedTask;
}
@Override
public T getLastCompletedTask() {
return lastCompletedTask;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
if (timeout < 0) {
timeout = 0;
}
synchronized (this.mutex) {
long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
long remaining = timeout;
while (!completed) {
this.mutex.wait(remaining);
if (timeout >= 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
return false; // Reach if timeout is over and no finish.
}
}
}
}
return true;
}
@Override
public ExecutionState getExecutionState() {
return state;
}
}<|fim▁end|> | |
<|file_name|>suggestions.rs<|end_file_name|><|fim▁begin|>#[cfg(feature = "suggestions")]
use strsim;
/// Produces a string from a given list of possible values which is similar to
/// the passed in value `v` with a certain confidence.
/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
/// `Some("foo")`, whereas "blark" would yield `None`.
#[cfg(feature = "suggestions")]
#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
pub fn did_you_mean<'a, T, I>(v: &str,
possible_values: I)
-> Option<&'a str>
where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values.into_iter() {
let confidence = strsim::jaro_winkler(v, pv.as_ref());
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv.as_ref()));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
#[cfg(not(feature = "suggestions"))]
pub fn did_you_mean<'a, T, I>(_: &str,
_: I)
-> Option<&'a str><|fim▁hole|> None
}
/// A helper to determine message formatting
pub enum DidYouMeanMessageStyle {
/// Suggested value is a long flag
LongFlag,
/// Suggested value is one of various possible values
EnumValue,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn did_you_mean_possible_values() {
let p_vals = ["test", "possible", "values"];
assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
}
}<|fim▁end|> | where T: AsRef<str> + 'a,
I: IntoIterator<Item = &'a T>
{ |
<|file_name|>0002_auto_20170502_0952.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-02 09:52
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('cookiecutter_manager', '0002_auto_20170502_0952'),
('requirements_manager', '0001_initial'),
('marketplace', '0002_auto_20170502_0952'),
('pylint_manager', '0001_initial'),
('experiments_manager', '0001_initial'),
('build_manager', '0001_initial'),
('user_manager', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='experiment',
name='language',<|fim▁hole|> ),
migrations.AddField(
model_name='experiment',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_manager.WorkbenchUser'),
),
migrations.AddField(
model_name='experiment',
name='pylint',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='pylint_manager.PylintScan'),
),
migrations.AddField(
model_name='experiment',
name='requirements',
field=models.ManyToManyField(to='requirements_manager.Requirement'),
),
migrations.AddField(
model_name='experiment',
name='template',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cookiecutter_manager.CookieCutterTemplate'),
),
migrations.AddField(
model_name='experiment',
name='travis',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='build_manager.TravisInstance'),
),
migrations.AddField(
model_name='chosenexperimentsteps',
name='experiment',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='experiments_manager.Experiment'),
),
migrations.AddField(
model_name='chosenexperimentsteps',
name='step',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='experiments_manager.ExperimentStep'),
),
]<|fim▁end|> | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='marketplace.Language'), |
<|file_name|>TRandom.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|> * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.util;
import org.teavm.classlib.java.io.TSerializable;
import org.teavm.classlib.java.lang.TMath;
import org.teavm.classlib.java.lang.TObject;
import org.teavm.javascript.spi.GeneratedBy;
/**
*
* @author Alexey Andreev
*/
public class TRandom extends TObject implements TSerializable {
public TRandom() {
}
public TRandom(@SuppressWarnings("unused") long seed) {
}
public void setSeed(@SuppressWarnings("unused") long seed) {
}
protected int next(int bits) {
return (int)(random() * (1L << TMath.min(32, bits)));
}
public void nextBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; ++i) {
bytes[i] = (byte)next(8);
}
}
public int nextInt() {
return next(32);
}
public int nextInt(int n) {
return (int)(random() * n);
}
public long nextLong() {
return ((long)nextInt() << 32) | nextInt();
}
public boolean nextBoolean() {
return nextInt() % 2 == 0;
}
public float nextFloat() {
return (float)random();
}
public double nextDouble() {
return random();
}
@GeneratedBy(RandomNativeGenerator.class)
private static native double random();
}<|fim▁end|> | * you may not use this file except in compliance with the License. |
<|file_name|>login_utils.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/login_utils.h"
#include <algorithm>
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/prefs/pref_member.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/app_mode/app_mode_utils.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/login/chrome_restart_request.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
#include "chrome/browser/chromeos/login/input_events_blocker.h"
#include "chrome/browser/chromeos/login/login_display_host.h"
#include "chrome/browser/chromeos/login/oauth2_login_manager.h"
#include "chrome/browser/chromeos/login/oauth2_login_manager_factory.h"
#include "chrome/browser/chromeos/login/parallel_authenticator.h"
#include "chrome/browser/chromeos/login/profile_auth_data.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.h"
#include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_factory.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/supervised_user_manager.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/google/google_util_chromeos.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/pref_service_flags_storage.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/app_list/start_page_service.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/cryptohome/cryptohome_util.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_method_call_status.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/ime/input_method_manager.h"
#include "chromeos/settings/cros_settings_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "google_apis/gaia/gaia_auth_consumer.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"
using content::BrowserThread;
namespace chromeos {
namespace {
#if defined(ENABLE_RLZ)
// Flag file that disables RLZ tracking, when present.
const base::FilePath::CharType kRLZDisabledFlagName[] =
FILE_PATH_LITERAL(".rlz_disabled");
base::FilePath GetRlzDisabledFlagPath() {
return base::GetHomeDir().Append(kRLZDisabledFlagName);
}
#endif
} // namespace
struct DoBrowserLaunchOnLocaleLoadedData;
class LoginUtilsImpl
: public LoginUtils,
public OAuth2LoginManager::Observer,
public net::NetworkChangeNotifier::ConnectionTypeObserver,
public base::SupportsWeakPtr<LoginUtilsImpl> {
public:
LoginUtilsImpl()
: has_web_auth_cookies_(false),
delegate_(NULL),
exit_after_session_restore_(false),
session_restore_strategy_(
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN) {
net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
}
virtual ~LoginUtilsImpl() {
net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
}
// LoginUtils implementation:
virtual void DoBrowserLaunch(Profile* profile,
LoginDisplayHost* login_host) OVERRIDE;
virtual void PrepareProfile(
const UserContext& user_context,
const std::string& display_email,
bool has_cookies,
bool has_active_session,
LoginUtils::Delegate* delegate) OVERRIDE;
virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE;
virtual scoped_refptr<Authenticator> CreateAuthenticator(
LoginStatusConsumer* consumer) OVERRIDE;
virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE;
virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE;
// OAuth2LoginManager::Observer overrides.
virtual void OnSessionRestoreStateChanged(
Profile* user_profile,
OAuth2LoginManager::SessionRestoreState state) OVERRIDE;
virtual void OnNewRefreshTokenAvaiable(Profile* user_profile) OVERRIDE;
// net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
virtual void OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) OVERRIDE;
private:
typedef std::set<std::string> SessionRestoreStateSet;
// DoBrowserLaunch is split into two parts.
// This one is called after anynchronous locale switch.
void DoBrowserLaunchOnLocaleLoadedImpl(Profile* profile,
LoginDisplayHost* login_host);
// Callback for locale_util::SwitchLanguage().
static void DoBrowserLaunchOnLocaleLoaded(
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
const std::string& locale,
const std::string& loaded_locale,
const bool success);
// Restarts OAuth session authentication check.
void KickStartAuthentication(Profile* profile);
// Callback for Profile::CREATE_STATUS_CREATED profile state.
// Initializes basic preferences for newly created profile. Any other
// early profile initialization that needs to happen before
// ProfileManager::DoFinalInit() gets called is done here.
void InitProfilePreferences(Profile* user_profile,
const std::string& email);
// Callback for asynchronous profile creation.
void OnProfileCreated(const std::string& email,
Profile* profile,
Profile::CreateStatus status);
// Callback for asynchronous off the record profile creation.
void OnOTRProfileCreated(const std::string& email,
Profile* profile,
Profile::CreateStatus status);
// Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
// Profile is created, extensions and promo resources are initialized.
void UserProfileInitialized(Profile* user_profile);
// Callback for Profile::CREATE_STATUS_INITIALIZED profile state for an OTR
// login.
void OTRProfileInitialized(Profile* user_profile);
// Callback to resume profile creation after transferring auth data from
// the authentication profile.
void CompleteProfileCreate(Profile* user_profile);
// Finalized profile preparation.
void FinalizePrepareProfile(Profile* user_profile);
// Initializes member variables needed for session restore process via
// OAuthLoginManager.
void InitSessionRestoreStrategy();
// Restores GAIA auth cookies for the created user profile from OAuth2 token.
void RestoreAuthSession(Profile* user_profile,
bool restore_from_auth_cookies);
// Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
void InitRlz(Profile* user_profile, bool disabled);
// Attempts restarting the browser process and esures that this does
// not happen while we are still fetching new OAuth refresh tokens.
void AttemptRestart(Profile* profile);
UserContext user_context_;
// True if the authentication profile's cookie jar should contain
// authentication cookies from the authentication extension log in flow.
bool has_web_auth_cookies_;
// Has to be scoped_refptr, see comment for CreateAuthenticator(...).
scoped_refptr<Authenticator> authenticator_;
// Delegate to be fired when the profile will be prepared.
LoginUtils::Delegate* delegate_;
// Set of user_id for those users that we should restore authentication
// session when notified about online state change.
SessionRestoreStateSet pending_restore_sessions_;
// True if we should restart chrome right after session restore.
bool exit_after_session_restore_;
// Sesion restore strategy.
OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_;
// OAuth2 refresh token for session restore.
std::string oauth2_refresh_token_;
DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl);
};
class LoginUtilsWrapper {
public:
static LoginUtilsWrapper* GetInstance() {
return Singleton<LoginUtilsWrapper>::get();
}
LoginUtils* get() {
base::AutoLock create(create_lock_);
if (!ptr_.get())
reset(new LoginUtilsImpl);
return ptr_.get();
}
void reset(LoginUtils* ptr) {
ptr_.reset(ptr);
}
private:
friend struct DefaultSingletonTraits<LoginUtilsWrapper>;
LoginUtilsWrapper() {}
base::Lock create_lock_;
scoped_ptr<LoginUtils> ptr_;
DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper);
};
struct DoBrowserLaunchOnLocaleLoadedData {
DoBrowserLaunchOnLocaleLoadedData(LoginUtilsImpl* login_utils_impl,
Profile* profile,
LoginDisplayHost* display_host)
: login_utils_impl(login_utils_impl),
profile(profile),
display_host(display_host) {}
LoginUtilsImpl* login_utils_impl;
Profile* profile;
chromeos::LoginDisplayHost* display_host;
// Block UI events untill ResourceBundle is reloaded.
InputEventsBlocker input_events_blocker;
};
// static
void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded(
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
const std::string& /* locale */,
const std::string& /* loaded_locale */,
const bool /* success */) {
context->login_utils_impl->DoBrowserLaunchOnLocaleLoadedImpl(
context->profile, context->display_host);
}
// Called from DoBrowserLaunch() or from
// DoBrowserLaunchOnLocaleLoaded() depending on
// if locale switch was needed.
void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoadedImpl(
Profile* profile,
LoginDisplayHost* login_host) {
if (!UserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
UserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile);
return;
}
CommandLine user_flags(CommandLine::NO_PROGRAM);
about_flags::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs());
about_flags::ConvertFlagsToSwitches(&flags_storage_, &user_flags,
about_flags::kAddSentinels);
// Only restart if needed and if not going into managed mode.
// Don't restart browser if it is not first profile in session.
if (UserManager::Get()->GetLoggedInUsers().size() == 1 &&
!UserManager::Get()->IsLoggedInAsLocallyManagedUser() &&
!about_flags::AreSwitchesIdenticalToCurrentCommandLine(
user_flags, *CommandLine::ForCurrentProcess())) {
CommandLine::StringVector flags;
// argv[0] is the program name |CommandLine::NO_PROGRAM|.
flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
VLOG(1) << "Restarting to apply per-session flags...";
DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
UserManager::Get()->GetActiveUser()->email(), flags);
AttemptRestart(profile);
return;
}
if (login_host) {
login_host->SetStatusAreaVisible(true);
login_host->BeforeSessionStart();
}
BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);
VLOG(1) << "Launching browser...";
StartupBrowserCreator browser_creator;
int return_code;
chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
browser_creator.LaunchBrowser(*CommandLine::ForCurrentProcess(),
profile,
base::FilePath(),
chrome::startup::IS_PROCESS_STARTUP,
first_run,
&return_code);
// Triggers app launcher start page service to load start page web contents.
app_list::StartPageService::Get(profile);
// Mark login host for deletion after browser starts. This
// guarantees that the message loop will be referenced by the
// browser before it is dereferenced by the login host.
if (login_host)
login_host->Finalize();
UserManager::Get()->SessionStarted();
}
void LoginUtilsImpl::DoBrowserLaunch(Profile* profile,
LoginDisplayHost* login_host) {
if (browser_shutdown::IsTryingToQuit())
return;
User* const user = UserManager::Get()->GetUserByProfile(profile);
scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> data(<|fim▁hole|> new DoBrowserLaunchOnLocaleLoadedData(this, profile, login_host));
scoped_ptr<locale_util::SwitchLanguageCallback> callback(
new locale_util::SwitchLanguageCallback(
base::Bind(&LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded,
base::Passed(data.Pass()))));
if (!UserManager::Get()->
RespectLocalePreference(profile, user, callback.Pass())) {
DoBrowserLaunchOnLocaleLoadedImpl(profile, login_host);
}
}
void LoginUtilsImpl::PrepareProfile(
const UserContext& user_context,
const std::string& display_email,
bool has_cookies,
bool has_active_session,
LoginUtils::Delegate* delegate) {
BootTimesLoader* btl = BootTimesLoader::Get();
VLOG(1) << "Completing login for " << user_context.username;
if (!has_active_session) {
btl->AddLoginTimeMarker("StartSession-Start", false);
DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
user_context.username);
btl->AddLoginTimeMarker("StartSession-End", false);
}
btl->AddLoginTimeMarker("UserLoggedIn-Start", false);
UserManager* user_manager = UserManager::Get();
user_manager->UserLoggedIn(user_context.username,
user_context.username_hash,
false);
btl->AddLoginTimeMarker("UserLoggedIn-End", false);
// Switch log file as soon as possible.
if (base::SysInfo::IsRunningOnChromeOS())
logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
// Update user's displayed email.
if (!display_email.empty())
user_manager->SaveUserDisplayEmail(user_context.username, display_email);
user_context_ = user_context;
has_web_auth_cookies_ = has_cookies;
delegate_ = delegate;
InitSessionRestoreStrategy();
if (DemoAppLauncher::IsDemoAppSession(user_context.username)) {
g_browser_process->profile_manager()->CreateProfileAsync(
user_manager->GetUserProfileDir(user_context.username),
base::Bind(&LoginUtilsImpl::OnOTRProfileCreated, AsWeakPtr(),
user_context.username),
base::string16(), base::string16(), std::string());
} else {
// Can't use display_email because it is empty when existing user logs in
// using sing-in pod on login screen (i.e. user didn't type email).
g_browser_process->profile_manager()->CreateProfileAsync(
user_manager->GetUserProfileDir(user_context.username),
base::Bind(&LoginUtilsImpl::OnProfileCreated, AsWeakPtr(),
user_context.username),
base::string16(), base::string16(), std::string());
}
}
void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
if (delegate_ == delegate)
delegate_ = NULL;
}
void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile,
const std::string& user_id) {
if (UserManager::Get()->IsCurrentUserNew())
SetFirstLoginPrefs(user_profile->GetPrefs());
if (UserManager::Get()->IsLoggedInAsLocallyManagedUser()) {
User* active_user = UserManager::Get()->GetActiveUser();
std::string managed_user_sync_id =
UserManager::Get()->GetSupervisedUserManager()->
GetUserSyncId(active_user->email());
// TODO(ibraaaa): Remove that when 97% of our users are using M31.
// http://crbug.com/276163
if (managed_user_sync_id.empty())
managed_user_sync_id = "DUMMY_ID";
user_profile->GetPrefs()->SetString(prefs::kManagedUserId,
managed_user_sync_id);
} else {
// Make sure that the google service username is properly set (we do this
// on every sign in, not just the first login, to deal with existing
// profiles that might not have it set yet).
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfile(user_profile);
signin_manager->SetAuthenticatedUsername(user_id);
}
}
void LoginUtilsImpl::InitSessionRestoreStrategy() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
bool in_app_mode = chrome::IsRunningInForcedAppMode();
// Are we in kiosk app mode?
if (in_app_mode) {
if (command_line->HasSwitch(::switches::kAppModeOAuth2Token)) {
oauth2_refresh_token_ = command_line->GetSwitchValueASCII(
::switches::kAppModeOAuth2Token);
}
if (command_line->HasSwitch(::switches::kAppModeAuthCode)) {
user_context_.auth_code = command_line->GetSwitchValueASCII(
::switches::kAppModeAuthCode);
}
DCHECK(!has_web_auth_cookies_);
if (!user_context_.auth_code.empty()) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
} else if (!oauth2_refresh_token_.empty()) {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN;
} else {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
}
return;
}
if (has_web_auth_cookies_) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR;
} else if (!user_context_.auth_code.empty()) {
session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
} else {
session_restore_strategy_ =
OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
}
}
void LoginUtilsImpl::OnProfileCreated(
const std::string& user_id,
Profile* user_profile,
Profile::CreateStatus status) {
CHECK(user_profile);
switch (status) {
case Profile::CREATE_STATUS_CREATED:
InitProfilePreferences(user_profile, user_id);
break;
case Profile::CREATE_STATUS_INITIALIZED:
UserProfileInitialized(user_profile);
break;
case Profile::CREATE_STATUS_LOCAL_FAIL:
case Profile::CREATE_STATUS_REMOTE_FAIL:
case Profile::CREATE_STATUS_CANCELED:
case Profile::MAX_CREATE_STATUS:
NOTREACHED();
break;
}
}
void LoginUtilsImpl::OnOTRProfileCreated(
const std::string& user_id,
Profile* user_profile,
Profile::CreateStatus status) {
CHECK(user_profile);
switch (status) {
case Profile::CREATE_STATUS_CREATED:
InitProfilePreferences(user_profile, user_id);
break;
case Profile::CREATE_STATUS_INITIALIZED:
OTRProfileInitialized(user_profile);
break;
case Profile::CREATE_STATUS_LOCAL_FAIL:
case Profile::CREATE_STATUS_REMOTE_FAIL:
case Profile::CREATE_STATUS_CANCELED:
case Profile::MAX_CREATE_STATUS:
NOTREACHED();
break;
}
}
void LoginUtilsImpl::UserProfileInitialized(Profile* user_profile) {
BootTimesLoader* btl = BootTimesLoader::Get();
btl->AddLoginTimeMarker("UserProfileGotten", false);
if (user_context_.using_oauth) {
// Transfer proxy authentication cache, cookies (optionally) and server
// bound certs from the profile that was used for authentication. This
// profile contains cookies that auth extension should have already put in
// place that will ensure that the newly created session is authenticated
// for the websites that work with the used authentication schema.
ProfileAuthData::Transfer(authenticator_->authentication_profile(),
user_profile,
has_web_auth_cookies_, // transfer_cookies
base::Bind(
&LoginUtilsImpl::CompleteProfileCreate,
AsWeakPtr(),
user_profile));
return;
}
FinalizePrepareProfile(user_profile);
}
void LoginUtilsImpl::OTRProfileInitialized(Profile* user_profile) {
user_profile->OnLogin();
// Send the notification before creating the browser so additional objects
// that need the profile (e.g. the launcher) can be created first.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources(),
content::Details<Profile>(user_profile));
if (delegate_)
delegate_->OnProfilePrepared(user_profile);
}
void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) {
RestoreAuthSession(user_profile, has_web_auth_cookies_);
FinalizePrepareProfile(user_profile);
}
void LoginUtilsImpl::RestoreAuthSession(Profile* user_profile,
bool restore_from_auth_cookies) {
CHECK((authenticator_.get() && authenticator_->authentication_profile()) ||
!restore_from_auth_cookies);
if (chrome::IsRunningInForcedAppMode() ||
CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kOobeSkipPostLogin)) {
return;
}
exit_after_session_restore_ = false;
// Remove legacy OAuth1 token if we have one. If it's valid, we should already
// have OAuth2 refresh token in OAuth2TokenService that could be used to
// retrieve all other tokens and user_context.
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
login_manager->AddObserver(this);
login_manager->RestoreSession(
authenticator_.get() && authenticator_->authentication_profile()
? authenticator_->authentication_profile()->GetRequestContext()
: NULL,
session_restore_strategy_,
oauth2_refresh_token_,
user_context_.auth_code);
}
void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) {
BootTimesLoader* btl = BootTimesLoader::Get();
// Own TPM device if, for any reason, it has not been done in EULA
// wizard screen.
CryptohomeClient* client = DBusThreadManager::Get()->GetCryptohomeClient();
btl->AddLoginTimeMarker("TPMOwn-Start", false);
if (cryptohome_util::TpmIsEnabled() && !cryptohome_util::TpmIsBeingOwned()) {
if (cryptohome_util::TpmIsOwned()) {
client->CallTpmClearStoredPasswordAndBlock();
} else {
client->TpmCanAttemptOwnership(EmptyVoidDBusMethodCallback());
}
}
btl->AddLoginTimeMarker("TPMOwn-End", false);
if (UserManager::Get()->IsLoggedInAsRegularUser()) {
SAMLOfflineSigninLimiter* saml_offline_signin_limiter =
SAMLOfflineSigninLimiterFactory::GetForProfile(user_profile);
if (saml_offline_signin_limiter)
saml_offline_signin_limiter->SignedIn(user_context_.auth_flow);
}
user_profile->OnLogin();
// Send the notification before creating the browser so additional objects
// that need the profile (e.g. the launcher) can be created first.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
content::NotificationService::AllSources(),
content::Details<Profile>(user_profile));
// Initialize RLZ only for primary user.
if (UserManager::Get()->GetPrimaryUser() ==
UserManager::Get()->GetUserByProfile(user_profile)) {
InitRlzDelayed(user_profile);
}
// TODO(altimofeev): This pointer should probably never be NULL, but it looks
// like LoginUtilsImpl::OnProfileCreated() may be getting called before
// LoginUtilsImpl::PrepareProfile() has set |delegate_| when Chrome is killed
// during shutdown in tests -- see http://crosbug.com/18269. Replace this
// 'if' statement with a CHECK(delegate_) once the underlying issue is
// resolved.
if (delegate_)
delegate_->OnProfilePrepared(user_profile);
}
void LoginUtilsImpl::InitRlzDelayed(Profile* user_profile) {
#if defined(ENABLE_RLZ)
if (!g_browser_process->local_state()->HasPrefPath(prefs::kRLZBrand)) {
// Read brand code asynchronously from an OEM data and repost ourselves.
google_util::chromeos::InitBrand(
base::Bind(&LoginUtilsImpl::InitRlzDelayed, AsWeakPtr(), user_profile));
return;
}
base::PostTaskAndReplyWithResult(
base::WorkerPool::GetTaskRunner(false),
FROM_HERE,
base::Bind(&base::PathExists, GetRlzDisabledFlagPath()),
base::Bind(&LoginUtilsImpl::InitRlz, AsWeakPtr(), user_profile));
#endif
}
void LoginUtilsImpl::InitRlz(Profile* user_profile, bool disabled) {
#if defined(ENABLE_RLZ)
PrefService* local_state = g_browser_process->local_state();
if (disabled) {
// Empty brand code means an organic install (no RLZ pings are sent).
google_util::chromeos::ClearBrandForCurrentSession();
}
if (disabled != local_state->GetBoolean(prefs::kRLZDisabled)) {
// When switching to RLZ enabled/disabled state, clear all recorded events.
RLZTracker::ClearRlzState();
local_state->SetBoolean(prefs::kRLZDisabled, disabled);
}
// Init the RLZ library.
int ping_delay = user_profile->GetPrefs()->GetInteger(
first_run::GetPingDelayPrefName().c_str());
// Negative ping delay means to send ping immediately after a first search is
// recorded.
RLZTracker::InitRlzFromProfileDelayed(
user_profile, UserManager::Get()->IsCurrentUserNew(),
ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)));
if (delegate_)
delegate_->OnRlzInitialized(user_profile);
#endif
}
void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) {
VLOG(1) << "Completing incognito login";
// For guest session we ask session manager to restart Chrome with --bwsi
// flag. We keep only some of the arguments of this process.
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
CommandLine command_line(browser_command_line.GetProgram());
std::string cmd_line_str =
GetOffTheRecordCommandLine(start_url,
StartupUtils::IsOobeCompleted(),
browser_command_line,
&command_line);
RestartChrome(cmd_line_str);
}
void LoginUtilsImpl::SetFirstLoginPrefs(PrefService* prefs) {
VLOG(1) << "Setting first login prefs";
BootTimesLoader* btl = BootTimesLoader::Get();
std::string locale = g_browser_process->GetApplicationLocale();
// First, we'll set kLanguagePreloadEngines.
input_method::InputMethodManager* manager =
input_method::InputMethodManager::Get();
std::vector<std::string> input_method_ids;
manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
locale, manager->GetCurrentInputMethod(), &input_method_ids);
// Save the input methods in the user's preferences.
StringPrefMember language_preload_engines;
language_preload_engines.Init(prefs::kLanguagePreloadEngines,
prefs);
language_preload_engines.SetValue(JoinString(input_method_ids, ','));
btl->AddLoginTimeMarker("IMEStarted", false);
// Second, we'll set kLanguagePreferredLanguages.
std::vector<std::string> language_codes;
// The current locale should be on the top.
language_codes.push_back(locale);
// Add input method IDs based on the input methods, as there may be
// input methods that are unrelated to the current locale. Example: the
// hardware keyboard layout xkb:us::eng is used for logging in, but the
// UI language is set to French. In this case, we should set "fr,en"
// to the preferred languages preference.
std::vector<std::string> candidates;
manager->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds(
input_method_ids, &candidates);
for (size_t i = 0; i < candidates.size(); ++i) {
const std::string& candidate = candidates[i];
// Skip if it's already in language_codes.
if (std::count(language_codes.begin(), language_codes.end(),
candidate) == 0) {
language_codes.push_back(candidate);
}
}
// Save the preferred languages in the user's preferences.
StringPrefMember language_preferred_languages;
language_preferred_languages.Init(prefs::kLanguagePreferredLanguages,
prefs);
language_preferred_languages.SetValue(JoinString(language_codes, ','));
}
scoped_refptr<Authenticator> LoginUtilsImpl::CreateAuthenticator(
LoginStatusConsumer* consumer) {
// Screen locker needs new Authenticator instance each time.
if (ScreenLocker::default_screen_locker()) {
if (authenticator_.get())
authenticator_->SetConsumer(NULL);
authenticator_ = NULL;
}
if (authenticator_.get() == NULL) {
authenticator_ = new ParallelAuthenticator(consumer);
} else {
// TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
authenticator_->SetConsumer(consumer);
}
return authenticator_;
}
void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) {
UserManager* user_manager = UserManager::Get();
// We don't need to restore session for demo/guest/stub/public account users.
if (!user_manager->IsUserLoggedIn() ||
user_manager->IsLoggedInAsGuest() ||
user_manager->IsLoggedInAsPublicAccount() ||
user_manager->IsLoggedInAsDemoUser() ||
user_manager->IsLoggedInAsStub()) {
return;
}
User* user = user_manager->GetUserByProfile(user_profile);
DCHECK(user);
if (!net::NetworkChangeNotifier::IsOffline()) {
pending_restore_sessions_.erase(user->email());
RestoreAuthSession(user_profile, false);
} else {
// Even if we're online we should wait till initial
// OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
// end up canceling all request when initial network connection type is
// processed. See http://crbug.com/121643.
pending_restore_sessions_.insert(user->email());
}
}
void LoginUtilsImpl::OnSessionRestoreStateChanged(
Profile* user_profile,
OAuth2LoginManager::SessionRestoreState state) {
User::OAuthTokenStatus user_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
bool connection_error = false;
switch (state) {
case OAuth2LoginManager::SESSION_RESTORE_DONE:
user_status = User::OAUTH2_TOKEN_STATUS_VALID;
break;
case OAuth2LoginManager::SESSION_RESTORE_FAILED:
user_status = User::OAUTH2_TOKEN_STATUS_INVALID;
break;
case OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED:
connection_error = true;
break;
case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED:
case OAuth2LoginManager::SESSION_RESTORE_PREPARING:
case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS:
return;
}
// We should not be clearing existing token state if that was a connection
// error. http://crbug.com/295245
if (!connection_error) {
// We are in one of "done" states here.
UserManager::Get()->SaveUserOAuthStatus(
UserManager::Get()->GetLoggedInUser()->email(),
user_status);
}
login_manager->RemoveObserver(this);
}
void LoginUtilsImpl::OnNewRefreshTokenAvaiable(Profile* user_profile) {
// Check if we were waiting to restart chrome.
if (!exit_after_session_restore_)
return;
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
login_manager->RemoveObserver(this);
// Mark user auth token status as valid.
UserManager::Get()->SaveUserOAuthStatus(
UserManager::Get()->GetLoggedInUser()->email(),
User::OAUTH2_TOKEN_STATUS_VALID);
LOG(WARNING) << "Exiting after new refresh token fetched";
// We need to restart cleanly in this case to make sure OAuth2 RT is actually
// saved.
chrome::AttemptRestart();
}
void LoginUtilsImpl::OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) {
UserManager* user_manager = UserManager::Get();
if (type == net::NetworkChangeNotifier::CONNECTION_NONE ||
user_manager->IsLoggedInAsGuest() || !user_manager->IsUserLoggedIn()) {
return;
}
// Need to iterate over all users and their OAuth2 session state.
const UserList& users = user_manager->GetLoggedInUsers();
for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
Profile* user_profile = user_manager->GetProfileByUser(*it);
bool should_restore_session =
pending_restore_sessions_.find((*it)->email()) !=
pending_restore_sessions_.end();
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
if (login_manager->state() ==
OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
// If we come online for the first time after successful offline login,
// we need to kick off OAuth token verification process again.
login_manager->ContinueSessionRestore();
} else if (should_restore_session) {
pending_restore_sessions_.erase((*it)->email());
RestoreAuthSession(user_profile, has_web_auth_cookies_);
}
}
}
void LoginUtilsImpl::AttemptRestart(Profile* profile) {
if (session_restore_strategy_ !=
OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) {
chrome::AttemptRestart();
return;
}
// We can't really quit if the session restore process that mints new
// refresh token is still in progress.
OAuth2LoginManager* login_manager =
OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
if (login_manager->state() !=
OAuth2LoginManager::SESSION_RESTORE_PREPARING &&
login_manager->state() !=
OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
chrome::AttemptRestart();
return;
}
LOG(WARNING) << "Attempting browser restart during session restore.";
exit_after_session_restore_ = true;
}
// static
void LoginUtils::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kFactoryResetRequested, false);
registry->RegisterBooleanPref(prefs::kRollbackRequested, false);
registry->RegisterStringPref(prefs::kRLZBrand, std::string());
registry->RegisterBooleanPref(prefs::kRLZDisabled, false);
}
// static
LoginUtils* LoginUtils::Get() {
return LoginUtilsWrapper::GetInstance()->get();
}
// static
void LoginUtils::Set(LoginUtils* mock) {
LoginUtilsWrapper::GetInstance()->reset(mock);
}
// static
bool LoginUtils::IsWhitelisted(const std::string& username,
bool* wildcard_match) {
// Skip whitelist check for tests.
if (CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kOobeSkipPostLogin)) {
return true;
}
CrosSettings* cros_settings = CrosSettings::Get();
bool allow_new_user = false;
cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
if (allow_new_user)
return true;
return cros_settings->FindEmailInList(
kAccountsPrefUsers, username, wildcard_match);
}
} // namespace chromeos<|fim▁end|> | |
<|file_name|>othello.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
othello.py Humberto Henrique Campos Pinheiro
Game initialization and main loop
"""
import pygame
import ui
import player
import board
from config import BLACK, WHITE, HUMAN
import log
logger = log.setup_custom_logger('root')
# py2exe workaround
# import sys
# import os
# sys.stdout = open(os.devnull, 'w')
# sys.stderr = open(os.devnull, 'w')
class Othello:
"""
Game main class.<|fim▁hole|> def __init__(self):
""" Show options screen and start game modules"""
# start
self.gui = ui.Gui()
self.board = board.Board()
self.gui.show_menu(self.start)
def start(self, *args):
player1, player2, level = args
logger.info('Settings: player 1: %s, player 2: %s, level: %s ', player1, player2, level)
if player1 == HUMAN:
self.now_playing = player.Human(self.gui, BLACK)
else:
self.now_playing = player.Computer(BLACK, level + 3)
if player2 == HUMAN:
self.other_player = player.Human(self.gui, WHITE)
else:
self.other_player = player.Computer(WHITE, level + 3)
self.gui.show_game()
self.gui.update(self.board.board, 2, 2, self.now_playing.color)
def run(self):
clock = pygame.time.Clock()
while True:
clock.tick(60)
if self.board.game_ended():
whites, blacks, empty = self.board.count_stones()
if whites > blacks:
winner = WHITE
elif blacks > whites:
winner = BLACK
else:
winner = None
break
self.now_playing.get_current_board(self.board)
valid_moves = self.board.get_valid_moves(self.now_playing.color)
if valid_moves != []:
score, self.board = self.now_playing.get_move()
whites, blacks, empty = self.board.count_stones()
self.gui.update(self.board.board, blacks, whites,
self.now_playing.color)
self.now_playing, self.other_player = self.other_player, self.now_playing
self.gui.show_winner(winner)
pygame.time.wait(1000)
self.restart()
def restart(self):
self.board = board.Board()
self.gui.show_menu(self.start)
self.run()
def main():
game = Othello()
game.run()
if __name__ == '__main__':
main()<|fim▁end|> | """
|
<|file_name|>noise_stats.py<|end_file_name|><|fim▁begin|>from paths import rpath,mpath,opath
from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq
from pyspeckit.spectrum.readers import read_class
from astropy.table import Table
from astropy import log
from astropy.utils.console import ProgressBar
import numpy as np
import os
import pylab as pl
def tsys_data(plot=False):
if plot:
fig1 = pl.figure(1)
fig2 = pl.figure(2)
fig1.clf()
fig2.clf()
ax1 = fig1.gca()
ax2 = fig2.gca()
datadict = {}
tbldict = {}
for apex_filename in all_apexfiles:
log.info(apex_filename)
cl = read_class.ClassObject(apex_filename)
sourcereg,line,telescopes = get_source_tel_line(apex_filename)
sci_sources = [source for source in cl.sources
if _is_sci(source, sourcereg)]
datadict[apex_filename] = {t:[] for t in telescopes}
for telescope in telescopes:
log.info('{0}: {1}'.format(apex_filename, telescope))
selection = [x
for source in sci_sources
for x in cl.select_spectra(telescope=telescope,
line=line,
source=source)]
spdheader = cl.read_observations(selection, progressbar=True)
datadict[apex_filename][telescope] = zip(*[(sp.std(), h['TSYS'])
for sp,h in ProgressBar(spdheader)])
tbl = Table([datadict[apex_filename][t][ii]
for t in telescopes
for ii in (0,1)],
names=[t+"_"+s
for t in telescopes
for s in ('STDDEV','TSYS',)],
dtype=['float'
for t in telescopes
for s in ('STDDEV','TSYS',)
])<|fim▁hole|> tbl.write(os.path.basename(apex_filename)+"_tsys.fits", overwrite=True)
tbldict[apex_filename] = tbl
if plot:
ax1.plot(tbl['{0}_TSYS'.format(telescopes[0])],
tbl['{0}_STDDEV'.format(telescopes[0])],
',', alpha=0.8)
ax1.set_xlabel("TSYS")
ax1.set_ylabel("Std Dev")
fig1.savefig("StdDev_vs_TSYS_{0}.png".format(telescopes[0]))
ax2.plot(tbl['{0}_TSYS'.format(telescopes[1])],
tbl['{0}_STDDEV'.format(telescopes[1])],
',', alpha=0.8)
ax2.set_xlabel("TSYS")
ax2.set_ylabel("Std Dev")
pl.draw()
pl.show()
fig2.savefig("StdDev_vs_TSYS_{0}.png".format(telescopes[1]))
return datadict,tbldict<|fim▁end|> | log.info(os.path.basename(apex_filename)+"_tsys.fits") |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse('Page content')<|fim▁hole|><|fim▁end|> |
def custom(request):
return render(request, 'custom.html', {}) |
<|file_name|>artmac.cpp<|end_file_name|><|fim▁begin|>/////////////////////////////////////////////////////////////////////////////
// Name: src/osx/artmac.cpp
// Purpose: wxArtProvider instance with native Mac stock icons
// Author: Alan Shouls
// Created: 2006-10-30
// Copyright: (c) wxWindows team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if defined(__BORLANDC__)
#pragma hdrstop
#endif
#include "wx/artprov.h"
#ifndef WX_PRECOMP
#include "wx/image.h"
#endif
#include "wx/osx/private.h"
// ----------------------------------------------------------------------------
// wxMacArtProvider
// ----------------------------------------------------------------------------
<|fim▁hole|>class wxMacArtProvider : public wxArtProvider
{
protected:
#if wxOSX_USE_COCOA_OR_CARBON
virtual wxIconBundle CreateIconBundle(const wxArtID& id,
const wxArtClient& client);
#endif
#if wxOSX_USE_COCOA_OR_IPHONE
virtual wxBitmap CreateBitmap(const wxArtID& id,
const wxArtClient& client,
const wxSize& size)
{
return wxOSXCreateSystemBitmap(id, client, size);
}
#endif
};
/* static */ void wxArtProvider::InitNativeProvider()
{
PushBack(new wxMacArtProvider);
}
#if wxOSX_USE_COCOA_OR_CARBON
// ----------------------------------------------------------------------------
// helper macros
// ----------------------------------------------------------------------------
#define CREATE_STD_ICON(iconId, xpmRc) \
{ \
wxIconBundle icon(wxT(iconId), wxBITMAP_TYPE_ICON_RESOURCE); \
return icon; \
}
// Macro used in CreateBitmap to get wxICON_FOO icons:
#define ART_MSGBOX(artId, iconId, xpmRc) \
if ( id == artId ) \
{ \
CREATE_STD_ICON(#iconId, xpmRc) \
}
static wxIconBundle wxMacArtProvider_CreateIconBundle(const wxArtID& id)
{
ART_MSGBOX(wxART_ERROR, wxICON_ERROR, error)
ART_MSGBOX(wxART_INFORMATION, wxICON_INFORMATION, info)
ART_MSGBOX(wxART_WARNING, wxICON_WARNING, warning)
ART_MSGBOX(wxART_QUESTION, wxICON_QUESTION, question)
ART_MSGBOX(wxART_FOLDER, wxICON_FOLDER, folder)
ART_MSGBOX(wxART_FOLDER_OPEN, wxICON_FOLDER_OPEN, folder_open)
ART_MSGBOX(wxART_NORMAL_FILE, wxICON_NORMAL_FILE, deffile)
ART_MSGBOX(wxART_EXECUTABLE_FILE, wxICON_EXECUTABLE_FILE, exefile)
ART_MSGBOX(wxART_CDROM, wxICON_CDROM, cdrom)
ART_MSGBOX(wxART_FLOPPY, wxICON_FLOPPY, floppy)
ART_MSGBOX(wxART_HARDDISK, wxICON_HARDDISK, harddisk)
ART_MSGBOX(wxART_REMOVABLE, wxICON_REMOVABLE, removable)
ART_MSGBOX(wxART_DELETE, wxICON_DELETE, delete)
ART_MSGBOX(wxART_GO_BACK, wxICON_GO_BACK, back)
ART_MSGBOX(wxART_GO_FORWARD, wxICON_GO_FORWARD, forward)
ART_MSGBOX(wxART_GO_HOME, wxICON_GO_HOME, home)
ART_MSGBOX(wxART_HELP_SETTINGS, wxICON_HELP_SETTINGS, htmoptns)
ART_MSGBOX(wxART_HELP_PAGE, wxICON_HELP_PAGE, htmpage)
return wxNullIconBundle;
}
// ----------------------------------------------------------------------------
// CreateIconBundle
// ----------------------------------------------------------------------------
wxIconBundle wxMacArtProvider::CreateIconBundle(const wxArtID& id, const wxArtClient& client)
{
// On the Mac folders in lists are always drawn closed, so if an open
// folder icon is asked for we will ask for a closed one in its place
if ( client == wxART_LIST && id == wxART_FOLDER_OPEN )
return wxMacArtProvider_CreateIconBundle(wxART_FOLDER);
return wxMacArtProvider_CreateIconBundle(id);
}
#endif
// ----------------------------------------------------------------------------
// wxArtProvider::GetNativeSizeHint()
// ----------------------------------------------------------------------------
/*static*/
wxSize wxArtProvider::GetNativeSizeHint(const wxArtClient& client)
{
if ( client == wxART_TOOLBAR )
{
// See http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIcons/chapter_15_section_9.html:
// "32 x 32 pixels is the recommended size"
return wxSize(32, 32);
}
else if ( client == wxART_BUTTON || client == wxART_MENU )
{
// Mac UI doesn't use any images in neither buttons nor menus in
// general but the code using wxArtProvider can use wxART_BUTTON to
// find the icons of a roughly appropriate size for the buttons and
// 16x16 seems to be the best choice for this kind of use
return wxSize(16, 16);
}
return wxDefaultSize;
}<|fim▁end|> | |
<|file_name|>test_form.py<|end_file_name|><|fim▁begin|>import zeit.newsletter.testing
<|fim▁hole|> def test_form_should_save_entered_data_on_blur(self):
s = self.selenium
self.open('/repository/newsletter/@@checkout')
s.waitForElementPresent('id=metadata.subject')
s.assertValue('id=metadata.subject', '')
s.type('id=metadata.subject', 'flubber\t')
s.waitForElementNotPresent('css=.field.dirty')
# Re-open the page and verify that the data is still there
s.clickAndWait('link=Edit contents')
s.waitForElementPresent('id=metadata.subject')
s.assertValue('id=metadata.subject', 'flubber')<|fim▁end|> | class MetadataTest(zeit.newsletter.testing.SeleniumTestCase):
|
<|file_name|>machinelearning.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "machinelearning")]
extern crate rusoto_core;
extern crate rusoto_machinelearning;<|fim▁hole|>use rusoto_machinelearning::{
DescribeBatchPredictionsInput, DescribeDataSourcesInput, DescribeEvaluationsInput,
MachineLearning, MachineLearningClient,
};
// This service isn't available for new customers, but existing ones
// should still pass in this test.
#[tokio::test]
async fn should_describe_batch_predictions() {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeBatchPredictionsInput::default();
match client.describe_batch_predictions(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customers")),
};
}
#[tokio::test]
async fn should_describe_data_sources() {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeDataSourcesInput::default();
match client.describe_data_sources(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customers")),
};
}
#[tokio::test]
async fn should_describe_evaluations() {
let client = MachineLearningClient::new(Region::UsEast1);
let request = DescribeEvaluationsInput::default();
match client.describe_evaluations(request).await {
Ok(_) => (),
Err(e) => assert!(e
.to_string()
.contains("AmazonML is no longer available to new customers")),
};
}<|fim▁end|> |
use rusoto_core::Region; |
<|file_name|>parts_descriptor_test.py<|end_file_name|><|fim▁begin|>import amitgroup as ag<|fim▁hole|># This requires you to have the MNIST data set.
data, digits = ag.io.load_mnist('training', selection=slice(0, 100))
pd = ag.features.PartsDescriptor((5, 5), 20, patch_frame=1, edges_threshold=5, samples_per_image=10)
# Use only 100 of the digits
pd.train_from_images(data)
# Save the model to a file.
#pd.save('parts_model.npy')
# You can then load it again by
#pd = ag.features.PartsDescriptor.load(filename)
# Then you can extract features by
#features = pd.extract_features(image)
# Visualize the parts
ag.plot.images(pd.visparts)<|fim▁end|> | import numpy as np
ag.set_verbose(True)
|
<|file_name|>desc.rs<|end_file_name|><|fim▁begin|>/// Used in `SQLColAttributeW`.
#[repr(u16)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Desc {
/// `SQL_DESC_COUNT`. Returned in `NumericAttributePtr`. The number of columns available in the
/// result set. This returns 0 if there are no columns in the result set. The value in the
/// `column_number` argument is ignored.
Count = 1001,
/// `SQL_DESC_TYPE`. Retruned in `NumericAttributePtr`. A numeric value that specifies the SQL
/// data type. When ColumnNumber is equal to 0, SQL_BINARY is returned for variable-length
/// bookmarks and SQL_INTEGER is returned for fixed-length bookmarks. For the datetime and
/// interval data types, this field returns the verbose data type: SQL_DATETIME or SQL_INTERVAL.
/// Note: To work against ODBC 2.x drivers, use `SQL_DESC_CONCISE_TYPE` instead.
Type = 1002,
/// `SQL_DESC_LENGTH`. Returned in `NumericAttributePtr`. A numeric value that is either the
/// maximum or actual character length of a character string or binary data type. It is the
/// maximum character length for a fixed-length data type, or the actual character length for a
/// variable-length data type. Its value always excludes the null-termination byte that ends the
/// character string.
Length = 1003,
/// `SQL_DESC_OCTET_LENGTH_PTR`.
OctetLengthPtr = 1004,
/// `SQL_DESC_PRECISION`. Returned in `NumericAttributePtr`. A numeric value that for a numeric
/// data type denotes the applicable precision. For data types SQL_TYPE_TIME,
/// SQL_TYPE_TIMESTAMP, and all the interval data types that represent a time interval, its
/// value is the applicable precision of the fractional seconds component.
Precision = 1005,
/// `SQL_DESC_SCALE`. Returned in `NumericAttributePtr`. A numeric value that is the applicable
/// scale for a numeric data type. For DECIMAL and NUMERIC data types, this is the defined
/// scale. It is undefined for all other data types.
Scale = 1006,
/// `SQL_DESC_DATETIME_INTERVAL_CODE`.
DatetimeIntervalCode = 1007,
/// `SQL_DESC_NULLABLE`. Returned in `NumericAttributePtr`. `SQL_ NULLABLE` if the column can
/// have NULL values; SQL_NO_NULLS if the column does not have NULL values; or
/// SQL_NULLABLE_UNKNOWN if it is not known whether the column accepts NULL values.
Nullable = 1008,
/// `SQL_DESC_INDICATOR_PTR`<|fim▁hole|> /// the column alias does not apply, the column name is returned. In either case,
/// SQL_DESC_UNNAMED is set to SQL_NAMED. If there is no column name or a column alias, an empty
/// string is returned and SQL_DESC_UNNAMED is set to SQL_UNNAMED.
Name = 1011,
/// `SQL_DESC_UNNAMED`. Returned in `NumericAttributePtr`. SQL_NAMED or SQL_UNNAMED. If the
/// SQL_DESC_NAME field of the IRD contains a column alias or a column name, SQL_NAMED is
/// returned. If there is no column name or column alias, SQL_UNNAMED is returned.
Unnamed = 1012,
/// `SQL_DESC_OCTET_LENGTH`. Returned in `NumericAttributePtr`. The length, in bytes, of a
/// character string or binary data type. For fixed-length character or binary types, this is
/// the actual length in bytes. For variable-length character or binary types, this is the
/// maximum length in bytes. This value does not include the null terminator.
OctetLength = 1013,
/// `SQL_DESC_ALLOC_TYPE`.
AllocType = 1099,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_CHARACTER_SET_CATALOG`.
CharacterSetCatalog = 1018,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_CHARACTER_SET_SCHEMA`
CharacterSetSchema = 1019,
#[cfg(feature = "odbc_version_4")]
// `SQL_DESC_CHARACTER_SET_NAME`.
#[cfg(feature = "odbc_version_4")]
CharacterSetName = 1020,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_COLLATION_CATALOG`
CollationCatalog = 1015,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_COLLATION_SCHEMA`
CollationSchema = 1016,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_COLLATION_NAME`
CollationName = 1017,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_USER_DEFINED_TYPE_CATALOG`
UserDefinedTypeCatalog = 1026,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_USER_DEFINED_TYPE_SCHEMA`.
UserDefinedTypeSchema = 1027,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_USER_DEFINED_TYPE_NAME`.
UserDefinedTypeName = 1028,
// Extended Descriptors
/// `SQL_DESC_ARRAY_SIZE`
ArraySize = 20,
/// `SQL_DESC_ARRAY_STATUS_PTR`
ArrayStatusPtr = 21,
/// `SQL_DESC_AUTO_UNIQUE_VALUE`. Returned in `NumericAttributePtr`. `true` if the column is an
/// autoincrementing column. `false` if the column is not an autoincrementing column or is not
/// numeric. This field is valid for numeric data type columns only. An application can insert
/// values into a row containing an autoincrement column, but typically cannot update values in
/// the column. When an insert is made into an autoincrement column, a unique value is inserted
/// into the column at insert time. The increment is not defined, but is data source-specific.
/// An application should not assume that an autoincrement column starts at any particular point
/// or increments by any particular value.
AutoUniqueValue = 11,
/// `SQL_DESC_BASE_COLUMN_NAME`. Returned in `CharacterAttributePtr`. The base column name for
/// the result set column. If a base column name does not exist (as in the case of columns that
/// are expressions), then this variable contains an empty string.
BaseColumnName = 22,
/// `SQL_DESC_BASE_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the base table
/// that contains the column. If the base table name cannot be defined or is not applicable,
/// then this variable contains an empty string.
BaseTableName = 23,
/// `SQL_DESC_BIND_OFFSET_PTR`.
BindOffsetPtr = 24,
/// `SQL_DESC_BIND_TYPE`.
BindType = 25,
/// `SQL_DESC_CASE_SENSITIVE`. Returned in `NumericAttributePtr`. `true` if the column is
/// treated as case-sensitive for collations and comparisons. `false` if the column is not
/// treated as case-sensitive for collations and comparisons or is noncharacter.
CaseSensitive = 12,
/// `SQL_DESC_CATALOG_NAME`. Returned in `CharacterAttributePtr`. The catalog of the table that
/// contains the column. The returned value is implementation-defined if the column is an
/// expression or if the column is part of a view. If the data source does not support catalogs
/// or the catalog name cannot be determined, an empty string is returned. This VARCHAR record
/// field is not limited to 128 characters.
CatalogName = 17,
/// `SQL_DESC_CONCISE_TYPE`. Returned in `NumericAttributePtr`. The concise data type. For the
/// datetime and interval data types, this field returns the concise data type; for example,
/// SQL_TYPE_TIME or SQL_INTERVAL_YEAR.
ConciseType = 2,
/// `SQL_DESC_DATETIME_INTERVAL_PRECISION`
DatetimeIntervalPrecision = 26,
/// `SQL_DESC_DISPLAY_SIZE`. Returned in `NumericAttributePtr`. Maximum number of characters
/// required to display data from the column.
DisplaySize = 6,
/// `SQL_DESC_FIXED_PREC_SCALE`. Returned in `NumericAttributePtr`. `true` if the column has a
/// fixed precision and nonzero scale that are data source-specific. `false` if the column does
/// not have a fixed precision and nonzero scale that are data source-specific.
FixedPrecScale = 9,
/// `SQL_DESC_LABEL`. Returned in `CharacterAttributePtr`. The column label or title. For
/// example, a column named EmpName might be labeled Employee Name or might be labeled with an
/// alias. If a column does not have a label, the column name is returned. If the column is
/// unlabeled and unnamed, an empty string is returned.
Label = 18,
/// `SQL_DESC_LITERAL_PREFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record
/// field contains the character or characters that the driver recognizes as a prefix for a
/// literal of this data type. This field contains an empty string for a data type for which a
/// literal prefix is not applicable.
LiteralPrefix = 27,
/// `SQL_DESC_LITERAL_SUFFIX`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record
/// field contains the character or characters that the driver recognizes as a suffix for a
/// literal of this data type. This field contains an empty string for a data type for which a
/// literal suffix is not applicable.
LiteralSuffix = 28,
/// `SQL_DESC_LOCAL_TYPE_NAME`. Returned in `CharacterAttributePtr`. This VARCHAR(128) record
/// field contains any localized (native language) name for the data type that may be different
/// from the regular name of the data type. If there is no localized name, then an empty string
/// is returned. This field is for display purposes only. The character set of the string is
/// locale-dependent and is typically the default character set of the server.
LocalTypeName = 29,
/// `SQL_DESC_MAXIMUM_SCALE`.
MaximumScale = 30,
/// `SQL_DESC_MINIMUM_SCALE`.
MinimumScale = 31,
/// `SQL_DESC_NUM_PREC_RADIX`. Returned in `NumericAttributePtr`. If the data type in the
/// SQL_DESC_TYPE field is an approximate numeric data type, this SQLINTEGER field contains a
/// value of 2 because the SQL_DESC_PRECISION field contains the number of bits. If the data
/// type in the SQL_DESC_TYPE field is an exact numeric data type, this field contains a value
/// of 10 because the SQL_DESC_PRECISION field contains the number of decimal digits. This field
/// is set to 0 for all non-numeric data types.
NumPrecRadix = 32,
/// `SQL_DESC_PARAMETER_TYPE`.
ParameterType = 33,
/// `SQL_DESC_ROWS_PROCESSED_PTR`.
RowsProcessedPtr = 34,
#[cfg(feature = "odbc_version_3_50")]
/// `SQL_DESC_ROWVER`.
RowVer = 35,
/// `SQL_DESC_SCHEMA_NAME`. Returned in `CharacterAttributePtr`. The schema of the table that
/// contains the column. The returned value is implementation-defined if the column is an
/// expression or if the column is part of a view. If the data source does not support schemas
/// or the schema name cannot be determined, an empty string is returned. This VARCHAR record
/// field is not limited to 128 characters.
SchemaName = 16,
/// `SQL_DESC_SEARCHABLE`. Returned in `NumericAttributePtr`. `SQL_PRED_NONE` if the column
/// cannot be used in a WHERE clause. `SQL_PRED_CHAR` if the column can be used in a WHERE
/// clause but only with the LIKE predicate. `SQL_PRED_BASIC` if the column can be used in a
/// WHERE clause with all the comparison operators except LIKE. `SQL_PRED_SEARCHABLE` if the
/// column can be used in a WHERE clause with any comparison operator. Columns of type
/// `SQL_LONGVARCHAR` and `SQL_LONGVARBINARY` usually return `SQL_PRED_CHAR`.
Searchable = 13,
/// `SQL_DESC_TYPE_NAME`. Returned in `CharacterAttributePtr`. Data source-dependent data type
/// name; for example, "CHAR", "VARCHAR", "MONEY", "LONG VARBINARY", or "CHAR ( ) FOR BIT DATA".
/// If the type is unknown, an empty string is returned.
TypeName = 14,
/// `SQL_DESC_TABLE_NAME`. Returned in `CharacterAttributePtr`. The name of the table that
/// contains the column. The returned value is implementation-defined if the column is an
/// expression or if the column is part of a view. If the table name can not be determined an
/// empty string is returned.
TableName = 15,
/// `SQL_DESC_UNSIGNED`. Returned in `NumericAttributePtr`. `true` if the column is unsigned (or
/// not numeric). `false` if the column is signed.
Unsigned = 8,
/// `SQL_DESC_UPDATABLE`. Returned in `NumericAttributePtr`. Column is described by the values
/// for the defined constants: `SQL_ATTR_READONLY`, `SQL_ATTR_WRITE`,
/// `SQL_ATTR_READWRITE_UNKNOWN`.
/// `Updatable` Describes the updatability of the column in the result set, not the column in
/// the base table. The updatability of the base column on which the result set column is based
/// may be different from the value in this field. Whether a column is updatable can be based on
/// the data type, user privileges, and the definition of the result set itself. If it is
/// unclear whether a column is updatable, `SQL_ATTR_READWRITE_UNKNOWN` should be returned.
Updatable = 10,
#[cfg(feature = "odbc_version_4")]
/// `SQL_DESC_MIME_TYPE`.
MimeType = 36,
}<|fim▁end|> | IndicatorPtr = 1009,
/// `SQL_DESC_DATA_PTR`.
DataPtr = 1010,
/// `SQL_DESC_NAME`. Returned in `CharacterAttributePtr`. The column alias, if it applies. If |
<|file_name|>metadata.py<|end_file_name|><|fim▁begin|>"""Node metadata operations"""
import json
import logging
import http.client<|fim▁hole|>
logger = logging.getLogger(__name__)
ChangeSet = namedtuple('Changes', ['nodes', 'purged_nodes', 'checkpoint', 'reset'])
class MetadataMixin(object):
def get_node_list(self, **params) -> list:
""":param params: may include tempLink='True'"""
return self.BOReq.paginated_get(self.metadata_url + 'nodes', params)
def get_file_list(self) -> list:
return self.get_node_list(filters='kind:FILE')
def get_folder_list(self) -> list:
return self.get_node_list(filters='kind:FOLDER')
def get_asset_list(self) -> list:
return self.get_node_list(filters='kind:ASSET')
def get_trashed_folders(self) -> list:
return self.get_node_list(filters='status:TRASH AND kind:FOLDER')
def get_trashed_files(self) -> list:
return self.get_node_list(filters='status:TRASH AND kind:FILE')
def get_changes(self, checkpoint='', include_purged=False) -> 'Generator[ChangeSet]':
""" Generates a ChangeSet for each checkpoint in changes response. See
`<https://developer.amazon.com/public/apis/experience/cloud-drive/content/changes>`_."""
logger.info('Getting changes with checkpoint "%s".' % checkpoint)
body = {}
if checkpoint:
body['checkpoint'] = checkpoint
if include_purged:
body['includePurged'] = 'true'
r = self.BOReq.post(self.metadata_url + 'changes', data=json.dumps(body), stream=True)
if r.status_code not in OK_CODES:
r.close()
raise RequestError(r.status_code, r.text)
try:
for cs in self._iter_changes_lines(r):
yield cs
except (http.client.IncompleteRead, requests.exceptions.ChunkedEncodingError) as e:
logger.info(str(e))
raise RequestError(RequestError.CODE.INCOMPLETE_RESULT,
'[acd_api] reading changes terminated prematurely.')
except:
raise
finally:
r.close()
@staticmethod
def _iter_changes_lines(r: requests.Response) -> 'Generator[ChangeSet]':
"""Generates a ChangeSet per line in changes response
the expected return format should be:
{"checkpoint": str, "reset": bool, "nodes": []}
{"checkpoint": str, "reset": false, "nodes": []}
{"end": true}"""
end = False
pages = -1
for line in r.iter_lines(chunk_size=10 * 1024 ** 2, decode_unicode=False):
# filter out keep-alive new lines
if not line:
continue
reset = False
pages += 1
nodes = []
purged_nodes = []
try:
o = json.loads(line.decode('utf-8'))
except ValueError:
raise RequestError(RequestError.CODE.INCOMPLETE_RESULT,
'[acd_api] Invalid JSON in change set, page %i.' % pages)
try:
if o['end']:
end = True
continue
except KeyError:
pass
if o['reset']:
logger.info('Found "reset" tag in changes.')
reset = True
# could this actually happen?
if o['statusCode'] not in OK_CODES:
raise RequestError(RequestError.CODE.FAILED_SUBREQUEST,
'[acd_api] Partial failure in change request.')
for node in o['nodes']:
if node['status'] == 'PURGED':
purged_nodes.append(node['id'])
else:
nodes.append(node)
checkpoint = o['checkpoint']
logger.debug('Checkpoint: %s' % checkpoint)
yield ChangeSet(nodes, purged_nodes, checkpoint, reset)
logger.info('%i page(s) in changes.' % pages)
if not end:
logger.warning('End of change request not reached.')
def get_metadata(self, node_id: str, assets=False, temp_link=True) -> dict:
"""Gets a node's metadata."""
params = {'tempLink': 'true' if temp_link else 'false',
'asset': 'ALL' if assets else 'NONE'}
r = self.BOReq.get(self.metadata_url + 'nodes/' + node_id, params=params)
if r.status_code not in OK_CODES:
raise RequestError(r.status_code, r.text)
return r.json()
# this will increment the node's version attribute
def update_metadata(self, node_id: str, properties: dict) -> dict:
"""Update a node's properties like name, description, status, parents, ..."""
body = json.dumps(properties)
r = self.BOReq.patch(self.metadata_url + 'nodes/' + node_id, data=body)
if r.status_code not in OK_CODES:
raise RequestError(r.status_code, r.text)
return r.json()
def get_root_id(self) -> str:
"""Gets the ID of the root node
:returns: the topmost folder id"""
params = {'filters': 'isRoot:true'}
r = self.BOReq.get(self.metadata_url + 'nodes', params=params)
if r.status_code not in OK_CODES:
raise RequestError(r.status_code, r.text)
data = r.json()
if 'id' in data['data'][0]:
return data['data'][0]['id']
def list_children(self, node_id: str) -> list:
l = self.BOReq.paginated_get(self.metadata_url + 'nodes/' + node_id + '/children')
return l
def add_child(self, parent_id: str, child_id: str) -> dict:
"""Adds node with ID *child_id* to folder with ID *parent_id*.
:returns: updated child node dict"""
r = self.BOReq.put(self.metadata_url + 'nodes/' + parent_id + '/children/' + child_id)
if r.status_code not in OK_CODES:
logger.error('Adding child failed.')
raise RequestError(r.status_code, r.text)
return r.json()
def remove_child(self, parent_id: str, child_id: str) -> dict:
""":returns: updated child node dict"""
r = self.BOReq.delete(
self.metadata_url + 'nodes/' + parent_id + "/children/" + child_id)
# contrary to response code stated in API doc (202 ACCEPTED)
if r.status_code not in OK_CODES:
logger.error('Removing child failed.')
raise RequestError(r.status_code, r.text)
return r.json()
def move_node_from(self, node_id: str, old_parent_id: str, new_parent_id: str) -> dict:
"""Moves node with given ID from old parent to new parent.
Not tested with multi-parent nodes.
:returns: changed node dict"""
data = {'fromParent': old_parent_id, 'childId': node_id}
r = self.BOReq.post(self.metadata_url + 'nodes/' + new_parent_id + '/children',
data=json.dumps(data))
if r.status_code not in OK_CODES:
raise RequestError(r.status_code, r.text)
return r.json()
def move_node(self, node_id: str, parent_id: str) -> dict:
return self.update_metadata(node_id, {'parents': [parent_id]})
def rename_node(self, node_id: str, new_name: str) -> dict:
properties = {'name': new_name}
return self.update_metadata(node_id, properties)
def set_available(self, node_id: str) -> dict:
"""Sets node status from 'PENDING' to 'AVAILABLE'."""
properties = {'status': 'AVAILABLE'}
return self.update_metadata(node_id, properties)
def get_owner_id(self):
"""Provisional function for retrieving the security profile's name, a.k.a. owner id."""
node = self.create_file('acd_cli_get_owner_id')
self.move_to_trash(node['id'])
return node['createdBy']
def list_properties(self, node_id: str, owner_id: str) -> dict:
"""This will always return an empty dict if the accessor is not the owner.
:param owner_id: owner ID (return status 404 if empty)"""
r = self.BOReq.get(self.metadata_url + 'nodes/' + node_id + '/properties/' + owner_id)
if r.status_code not in OK_CODES:
raise RequestError(r.status_code, r.text)
return r.json()['data']
def add_property(self, node_id: str, owner_id: str, key: str, value: str) -> dict:
"""Adds or overwrites *key* property with *content*. Maximum number of keys per owner is 10.
:param value: string of length <= 500
:raises: RequestError: 404, <UnknownOperationException/> if owner is empty
RequestError: 400, {...} if maximum of allowed properties is reached
:returns dict: {'key': '<KEY>', 'location': '<NODE_ADDRESS>/properties/<OWNER_ID/<KEY>',
'value': '<VALUE>'}"""
ok_codes = [requests.codes.CREATED]
r = self.BOReq.put(self.metadata_url + 'nodes/' + node_id +
'/properties/' + owner_id + '/' + key,
data=json.dumps({'value': value}), acc_codes=ok_codes)
if r.status_code not in ok_codes:
raise RequestError(r.status_code, r.text)
return r.json()
def delete_property(self, node_id: str, owner_id: str, key: str):
"""Deletes *key* property from node with ID *node_id*."""
ok_codes = [requests.codes.NO_CONTENT]
r = self.BOReq.delete(self.metadata_url + 'nodes/' + node_id +
'/properties/' + owner_id + '/' + key, acc_codes=ok_codes)
if r.status_code not in ok_codes:
raise RequestError(r.status_code, r.text)
def delete_properties(self, node_id: str, owner_id: str):
"""Deletes all of the owner's properties. Uses multiple requests."""
ok_codes = [requests.codes.NO_CONTENT]
prop_dict = self.list_properties(node_id, owner_id)
for key in prop_dict:
r = self.BOReq.delete('%s/nodes/%s/properties/%s/%s'
% (self.metadata_url, node_id, owner_id, key), acc_codes=ok_codes)
if r.status_code not in ok_codes:
raise RequestError(r.status_code, r.text)<|fim▁end|> | from collections import namedtuple
from .common import * |
<|file_name|>test-playground.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit, ViewChild} from '@angular/core';
import {Api} from "@catflow/Api";
import {PublishSubject} from "@frontend/util/PublishSubject";
@Component({
selector: 'app-test-playground',
templateUrl: './test-playground.component.html',
styles: []
})
export class TestPlaygroundComponent implements OnInit {
@ViewChild('editorEl') editor;
constructor(public api: Api) {
let s = new PublishSubject<number>();
s.subscribe(val => console.info('before', val));
s.next(0);
s.next(1);
s.next(20);
s.subscribe(val => console.info('after', val));<|fim▁hole|>
editorReset() {
this.editor.modelFromJson(this.editor.modelJson);
}
ngOnInit() {
this.editor.networkObject = this.api.object(`/dataStructures/${71}/networks/${0}/`)
}
}<|fim▁end|> | s.next(30);
} |
<|file_name|>gmail.py<|end_file_name|><|fim▁begin|>import os
import string
#Enter your username and password below within double quotes
# eg. username="username" and password="password"
username="username"
password="password"
com="wget -O - https://"+username+":"+password+"@mail.google.com/mail/feed/atom --no-check-certificate"
temp=os.popen(com)
msg=temp.read()
index=string.find(msg,"<fullcount>")
index2=string.find(msg,"</fullcount>")
fc=int(msg[index+11:index2])
if fc==0:
print "0 new"<|fim▁hole|><|fim▁end|> | else:
print str(fc)+" new" |
<|file_name|>novo_sort.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import print_function
import argparse
from subprocess import check_call, CalledProcessError
import shlex
import sys
import logging
log = logging.getLogger( __name__ )
<|fim▁hole|>def novo_sort( bam_filename, output_filename ):
cmdline_str = "novosort -c 8 -m 8G -s -f {} -o {}".format( bam_filename, output_filename )
cmdline = newSplit(cmdline_str)
try:
check_call(cmdline)
except CalledProcessError:
print("Error running the nova-sort", file=sys.stderr)
def newSplit(value):
lex = shlex.shlex(value)
lex.quotes = '"'
lex.whitespace_split = True
lex.commenters = ''
return list(lex)
def main():
parser = argparse.ArgumentParser(description="Re-sorting aligned files by read position")
parser.add_argument('output_filename')
parser.add_argument('--bam_filename')
args = parser.parse_args()
novo_sort(args.bam_filename, args.output_filename)
if __name__ == "__main__":
main()<|fim▁end|> | |
<|file_name|>blockstore_field_data.py<|end_file_name|><|fim▁begin|>"""
Key-value store that holds XBlock field data read out of Blockstore
"""
from collections import namedtuple
from weakref import WeakKeyDictionary
import logging
from xblock.exceptions import InvalidScopeError, NoSuchDefinition
from xblock.fields import Field, BlockScope, Scope, UserScope, Sentinel
from xblock.field_data import FieldData
from openedx.core.djangoapps.xblock.learning_context.manager import get_learning_context_impl
from openedx.core.djangolib.blockstore_cache import (
get_bundle_version_files_cached,
get_bundle_draft_files_cached,
)
log = logging.getLogger(__name__)
ActiveBlock = namedtuple('ActiveBlock', ['olx_hash', 'changed_fields'])
DELETED = Sentinel('DELETED') # Special value indicating a field was reset to its default value
CHILDREN_INCLUDES = Sentinel('CHILDREN_INCLUDES') # Key for a pseudo-field that stores the XBlock's children info
MAX_DEFINITIONS_LOADED = 100 # How many of the most recently used XBlocks' field data to keep in memory at max.
class BlockInstanceUniqueKey(object):
"""
An empty object used as a unique key for each XBlock instance, see
get_weak_key_for_block() and BlockstoreFieldData._get_active_block(). Every
XBlock instance will get a unique one of these keys, even if they are
otherwise identical. Its purpose is similar to `id(block)`.
"""
def get_weak_key_for_block(block):
"""
Given an XBlock instance, return an object with the same lifetime as the
block, suitable as a key to hold block-specific data in a WeakKeyDictionary.
"""
# We would like to make the XBlock instance 'block' itself the key of
# BlockstoreFieldData.active_blocks, so that we have exactly one entry per
# XBlock instance in memory, and they'll each be automatically freed by the
# WeakKeyDictionary as needed. But because XModules implement
# __eq__() in a way that reads all field values, just attempting to use
# the block as a dict key here will trigger infinite recursion. So
# instead we key the dict on an arbitrary object,
# block key = BlockInstanceUniqueKey() which we create here. That way
# the weak reference will still cause the entry in the WeakKeyDictionary to
# be freed automatically when the block is no longer needed, and we
# still get one entry per XBlock instance.
if not hasattr(block, '_field_data_key_obj'):
block._field_data_key_obj = BlockInstanceUniqueKey() # pylint: disable=protected-access
return block._field_data_key_obj # pylint: disable=protected-access
def get_olx_hash_for_definition_key(def_key):
"""
Given a BundleDefinitionLocator, which identifies a specific version of an
OLX file, return the hash of the OLX file as given by the Blockstore API.
"""
if def_key.bundle_version:
# This is referring to an immutable file (BundleVersions are immutable so this can be aggressively cached)
files_list = get_bundle_version_files_cached(def_key.bundle_uuid, def_key.bundle_version)
else:
# This is referring to a draft OLX file which may be recently updated:
files_list = get_bundle_draft_files_cached(def_key.bundle_uuid, def_key.draft_name)
for entry in files_list:
if entry.path == def_key.olx_path:
return entry.hash_digest
raise NoSuchDefinition("Could not load OLX file for key {}".format(def_key))
class BlockstoreFieldData(FieldData):
"""
An XBlock FieldData implementation that reads XBlock field data directly out
of Blockstore.
It requires that every XBlock have a BundleDefinitionLocator as its
"definition key", since the BundleDefinitionLocator is what specifies the
OLX file path and version to use.
Within Blockstore there is no mechanism for setting different field values
at the usage level compared to the definition level, so we treat
usage-scoped fields identically to definition-scoped fields.
"""
def __init__(self):
"""
Initialize this BlockstoreFieldData instance.
"""
# loaded definitions: a dict where the key is the hash of the XBlock's
# olx file (as stated by the Blockstore API), and the values is the
# dict of field data as loaded from that OLX file. The field data dicts
# in this should be considered immutable, and never modified.
self.loaded_definitions = {}
# Active blocks: this holds the field data *changes* for all the XBlocks
# that are currently in memory being used for something. We only keep a
# weak reference so that the memory will be freed when the XBlock is no
# longer needed (e.g. at the end of a request)
# The key of this dictionary is on ID object owned by the XBlock itself
# (see _get_active_block()) and the value is an ActiveBlock object
# (which holds olx_hash and changed_fields)
self.active_blocks = WeakKeyDictionary()
super(BlockstoreFieldData, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
def _getfield(self, block, name):
"""
Return the field with the given `name` from `block`.
If the XBlock doesn't have such a field, raises a KeyError.
"""
# First, get the field from the class, if defined
block_field = getattr(block.__class__, name, None)
if block_field is not None and isinstance(block_field, Field):
return block_field
# Not in the class, so name really doesn't name a field
raise KeyError(name)
def _check_field(self, block, name):
"""
Given a block and the name of one of its fields, check that we will be
able to read/write it.
"""
if name == CHILDREN_INCLUDES:
return # This is a pseudo-field used in conjunction with BlockstoreChildrenData
field = self._getfield(block, name)
if field.scope in (Scope.children, Scope.parent): # lint-amnesty, pylint: disable=no-else-raise
# This field data store is focused on definition-level field data, and children/parent is mostly
# relevant at the usage level. Scope.parent doesn't even seem to be used?
raise NotImplementedError("Setting Scope.children/parent is not supported by BlockstoreFieldData.")
else:
if field.scope.user != UserScope.NONE:
raise InvalidScopeError("BlockstoreFieldData only supports UserScope.NONE fields")
if field.scope.block not in (BlockScope.DEFINITION, BlockScope.USAGE):
raise InvalidScopeError(
"BlockstoreFieldData does not support BlockScope.{} fields".format(field.scope.block)
)
# There is also BlockScope.TYPE but we don't need to support that;
# it's mostly relevant as Scope.preferences(UserScope.ONE, BlockScope.TYPE)
# Which would be handled by a user-aware FieldData implementation
def _get_active_block(self, block):
"""
Get the ActiveBlock entry for the specified block, creating it if
necessary.
"""
key = get_weak_key_for_block(block)
if key not in self.active_blocks:
self.active_blocks[key] = ActiveBlock(
olx_hash=get_olx_hash_for_definition_key(block.scope_ids.def_id),
changed_fields={},
)
return self.active_blocks[key]
def get(self, block, name):
"""
Get the given field value from Blockstore
If the XBlock has been making changes to its fields, the value will be
in self._get_active_block(block).changed_fields[name]
Otherwise, the value comes from self.loaded_definitions which is a dict
of OLX file field data, keyed by the hash of the OLX file.
"""
self._check_field(block, name)
entry = self._get_active_block(block)
if name in entry.changed_fields:
value = entry.changed_fields[name]
if value == DELETED:
raise KeyError # KeyError means use the default value, since this field was deliberately set to default
return value
try:
saved_fields = self.loaded_definitions[entry.olx_hash]
except KeyError:
if name == CHILDREN_INCLUDES:
# Special case: parse_xml calls add_node_as_child which calls 'block.children.append()'
# BEFORE parse_xml is done, and .append() needs to read the value of children. So
return [] # start with an empty list, it will get filled in.
# Otherwise, this is an anomalous get() before the XML was fully loaded:
# This could happen if an XBlock's parse_xml() method tried to read a field before setting it,
# if an XBlock read field data in its constructor (forbidden), or if an XBlock was loaded via
# some means other than runtime.get_block(). One way this can happen is if you log/print an XBlock during
# XML parsing, because ScopedStorageMixin.__repr__ will try to print all field values, and any fields which
# aren't mentioned in the XML (which are left at their default) will be "not loaded yet."
log.exception(
"XBlock %s tried to read from field data (%s) that wasn't loaded from Blockstore!",
block.scope_ids.usage_id, name,
)
raise # Just use the default value for now; any exception raised here is caught anyways
return saved_fields[name]
# If 'name' is not found, this will raise KeyError, which means to use the default value
def set(self, block, name, value):
"""
Set the value of the field named `name`
"""
entry = self._get_active_block(block)
entry.changed_fields[name] = value
<|fim▁hole|> self.set(block, name, DELETED)
def default(self, block, name):
"""
Get the default value for block's field 'name'.
The XBlock class will provide the default if KeyError is raised; this is
mostly for the purpose of context-specific overrides.
"""
raise KeyError(name)
def cache_fields(self, block):
"""
Cache field data:
This is called by the runtime after a block has parsed its OLX via its
parse_xml() methods and written all of its field values into this field
data store. The values will be stored in
self._get_active_block(block).changed_fields
so we know at this point that that isn't really "changed" field data,
it's the result of parsing the OLX. Save a copy into loaded_definitions.
"""
entry = self._get_active_block(block)
self.loaded_definitions[entry.olx_hash] = entry.changed_fields.copy()
# Reset changed_fields to indicate this block hasn't actually made any field data changes, just loaded from XML:
entry.changed_fields.clear()
if len(self.loaded_definitions) > MAX_DEFINITIONS_LOADED:
self.free_unused_definitions()
def has_changes(self, block):
"""
Does the specified block have any unsaved changes?
"""
entry = self._get_active_block(block)
return bool(entry.changed_fields)
def has_cached_definition(self, definition_key):
"""
Has the specified OLX file been loaded into memory?
"""
olx_hash = get_olx_hash_for_definition_key(definition_key)
return olx_hash in self.loaded_definitions
def free_unused_definitions(self):
"""
Free unused field data cache entries from self.loaded_definitions
as long as they're not in use.
"""
olx_hashes = set(self.loaded_definitions.keys())
olx_hashes_needed = set(entry.olx_hash for entry in self.active_blocks.values())
olx_hashes_safe_to_delete = olx_hashes - olx_hashes_needed
# To avoid doing this too often, randomly cull unused entries until
# we have only half as many as MAX_DEFINITIONS_LOADED in memory, if possible.
while olx_hashes_safe_to_delete and (len(self.loaded_definitions) > MAX_DEFINITIONS_LOADED / 2):
del self.loaded_definitions[olx_hashes_safe_to_delete.pop()]
class BlockstoreChildrenData(FieldData):
"""
An XBlock FieldData implementation that reads 'children' data out of
the definition fields in BlockstoreFieldData.
The children field contains usage keys and so is usage-specific; the
BlockstoreFieldData can only store field data that is not usage-specific. So
we store data about the <xblock-include /> elements that define the children
in BlockstoreFieldData (since that is not usage-specific), and this field
data implementation loads that <xblock-include /> data and transforms it
into the usage keys that comprise the standard .children field.
"""
def __init__(self, blockstore_field_data):
"""
Initialize this BlockstoreChildrenData instance.
"""
# The data store that holds Scope.usage and Scope.definition data:
self.authored_data_store = blockstore_field_data
super(BlockstoreChildrenData, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
def _check_field(self, block, name): # pylint: disable=unused-argument
"""
Given a block and the name of one of its fields, check that we will be
able to read/write it.
"""
if name != 'children':
raise InvalidScopeError("BlockstoreChildrenData can only read/write from a field named 'children'")
def get(self, block, name):
"""
Get the "children' field value.
We do this by reading the parsed <xblock-include /> values from
the regular authored data store and then transforming them to usage IDs.
"""
self._check_field(block, name)
children_includes = self.get_includes(block)
if not children_includes:
return []
# Now the .children field is required to be a list of usage IDs:
learning_context = get_learning_context_impl(block.scope_ids.usage_id)
child_usages = []
for parsed_include in children_includes:
child_usages.append(
learning_context.usage_for_child_include(
block.scope_ids.usage_id, block.scope_ids.def_id, parsed_include,
)
)
return child_usages
def set(self, block, name, value):
"""
Set the value of the field; requires name='children'
"""
self._check_field(block, name)
children_includes = self.authored_data_store.get(block, CHILDREN_INCLUDES)
if len(value) != len(children_includes):
raise RuntimeError(
"This runtime does not allow changing .children directly - use runtime.add_child_include instead."
)
# This is a no-op; the value of 'children' is derived from CHILDREN_INCLUDES
# so we never write to the children field directly. All we do is make sure it
# looks like it's still in sync with CHILDREN_INCLUDES
def get_includes(self, block):
"""
Get the list of <xblock-include /> elements representing this XBlock's
children.
"""
try:
return self.authored_data_store.get(block, CHILDREN_INCLUDES)
except KeyError:
# KeyError raised by an XBlock field data store means "use the
# default value", and the default value for the children field is an
# empty list.
return []
def append_include(self, block, parsed_include):
"""
Append an <xblock-include /> element to this XBlock's list of children
"""
self.authored_data_store.set(block, CHILDREN_INCLUDES, self.get_includes(block) + [parsed_include])
def delete(self, block, name):
"""
Reset the value of the field named `name` to the default
"""
self._check_field(block, name)
self.authored_data_store.set(block, CHILDREN_INCLUDES, [])
self.set(block, name, [])<|fim▁end|> | def delete(self, block, name):
"""
Reset the value of the field named `name` to the default
""" |
<|file_name|>hidsdi.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Alex Daniel Jones
// Licensed under the MIT License <LICENSE.md>
// Taken from hidsdi.h
#[repr(C)] #[derive(Clone, Copy, Debug)]<|fim▁hole|> pub Size: ::ULONG,
pub VendorID: ::USHORT,
pub ProductID: ::USHORT,
pub VersionNumber: ::USHORT,
}
pub type PHIDD_ATTRIBUTES = *mut HIDD_ATTRIBUTES;<|fim▁end|> | pub struct HIDD_ATTRIBUTES { |
<|file_name|>type-alias-impl-trait-with-cycle-error2.rs<|end_file_name|><|fim▁begin|>#![feature(type_alias_impl_trait)]
pub trait Bar<T> {
type Item;
}
type Foo = impl Bar<Foo, Item = Foo>;
//~^ ERROR: could not find defining uses
fn crash(x: Foo) -> Foo {<|fim▁hole|>fn main() {}<|fim▁end|> | x
}
|
<|file_name|>cube_shell.rs<|end_file_name|><|fim▁begin|>//! Functions and structures for interacting with cubic shells.
use range_abs::range_abs;
use std::cmp::{min, max};
use std::iter::range_inclusive;
use block_position::BlockPosition;
#[cfg(test)]
use std::collections::HashSet;
#[cfg(test)]
use cgmath::{Point, Vector3};
#[cfg(test)]
use test::{Bencher, black_box};
#[inline]
// TODO: This should return an iterator.
/// Generate the set of points corresponding to the surface of a cube made of voxels.
pub fn cube_shell(center: &BlockPosition, radius: i32) -> Vec<BlockPosition> {
let mut shell = Vec::new();
if radius == 0 {
shell.push(*center);
return shell;
}
macro_rules! add_square(
($dxs: expr, $dys: expr, $dzs: expr) => (
for dx in $dxs {
for dy in $dys {
for dz in $dzs {
shell.push(BlockPosition::new(
center.as_pnt().x + dx,
center.as_pnt().y + dy,
center.as_pnt().z + dz,
));
}
}
}
);
);
add_square!(
[-radius, radius].iter().cloned(),
range_abs(radius),
range_abs(radius)
);
add_square!(
range_abs(radius - 1),
[-radius, radius].iter().cloned(),
range_abs(radius)
);
add_square!(
range_abs(radius - 1),
range_abs(radius - 1),
[-radius, radius].iter().cloned()
);
shell
}
// TODO: This should return an iterator.
// TODO: This should diff cube_shells instead of whole cubes.
/// Return the blocks that are present in a cube of radius `radius` centered at `from`,
/// but not in one centered at `to`.
pub fn cube_diff(
from: &BlockPosition,
to: &BlockPosition,
radius: i32,
) -> Vec<BlockPosition> {
let mut ret = Vec::new();
macro_rules! add_square(
($xs: expr, $ys: expr, $zs: expr) => (
for x in $xs {
for y in $ys {
for z in $zs {
ret.push(BlockPosition::new(x, y, z));
}
}
}
);
);
let from = *from.as_pnt();
let to = *to.as_pnt();
add_square!(
if from.x < to.x {
range_inclusive(from.x - radius, min(from.x + radius, to.x - radius - 1))
} else {
range_inclusive(max(from.x - radius, to.x + radius + 1), from.x + radius)
},
range_inclusive(from.y - radius, from.y + radius),
range_inclusive(from.z - radius, from.z + radius)
);
add_square!(
if from.x < to.x {
range_inclusive(to.x - radius, from.x + radius)
} else {
range_inclusive(from.x - radius, to.x + radius)
},
if from.y < to.y {
range_inclusive(from.y - radius, min(from.y + radius, to.y - radius - 1))
} else {
range_inclusive(max(from.y - radius, to.y + radius + 1), from.y + radius)
},
range_inclusive(from.z - radius, from.z + radius)
);
add_square!(
if from.x < to.x {
range_inclusive(to.x - radius, from.x + radius)
} else {
range_inclusive(from.x - radius, to.x + radius)
},
if from.y < to.y {
range_inclusive(to.y - radius, from.y + radius)
} else {
range_inclusive(from.y - radius, to.y + radius)
},
if from.z < to.z {<|fim▁hole|> }
);
ret
}
#[cfg(test)]
/// the number of elements in a cube shell
pub fn cube_shell_area(radius: i32) -> u32 {
assert!(radius >= 0);
if radius == 0 {
return 1;
}
let width = 2 * radius + 1;
// volume of the cube
let outer = width * width * width;
// volume of the cube of radius r - 1.
let inner = (width - 2) * (width - 2) * (width - 2);
(outer - inner) as u32
}
#[test]
// Check that the surface area is correct for a few different shells.
fn test_surface_area() {
let centers = [
BlockPosition::new(0, 0, 0),
BlockPosition::new(2, 1, -4),
];
for center in centers.iter() {
for radius in 1..5 {
assert_eq!(
cube_shell(center, radius as i32).len() as u32,
cube_shell_area(radius)
);
}
}
}
#[test]
fn test_simple_shell() {
let center = BlockPosition::new(2, 0, -3);
let radius = 1;
let expected: HashSet<BlockPosition> = [
BlockPosition::new( 0, 0, 1),
BlockPosition::new( 0, 0, -1),
BlockPosition::new( 0, 1, 0),
BlockPosition::new( 0, 1, 1),
BlockPosition::new( 0, 1, -1),
BlockPosition::new( 0, -1, 0),
BlockPosition::new( 0, -1, 1),
BlockPosition::new( 0, -1, -1),
BlockPosition::new( 1, 0, 0),
BlockPosition::new( 1, 0, 1),
BlockPosition::new( 1, 0, -1),
BlockPosition::new( 1, 1, 0),
BlockPosition::new( 1, 1, 1),
BlockPosition::new( 1, 1, -1),
BlockPosition::new( 1, -1, 0),
BlockPosition::new( 1, -1, 1),
BlockPosition::new( 1, -1, -1),
BlockPosition::new(-1, 0, 0),
BlockPosition::new(-1, 0, 1),
BlockPosition::new(-1, 0, -1),
BlockPosition::new(-1, 1, 0),
BlockPosition::new(-1, 1, 1),
BlockPosition::new(-1, 1, -1),
BlockPosition::new(-1, -1, 0),
BlockPosition::new(-1, -1, 1),
BlockPosition::new(-1, -1, -1),
]
.iter()
.map(|p| p.clone() + center.as_pnt().to_vec())
.collect();
let actual = cube_shell(¢er, radius);
assert_eq!(expected, actual.into_iter().collect());
}
#[test]
fn test_shell_no_dups() {
let center = BlockPosition::new(2, 0, -3);
let radius = 2;
let expected = cube_shell(¢er, radius);
let actual: HashSet<BlockPosition> = expected.iter().map(|&x| x).collect();
assert_eq!(expected.len(), actual.len());
}
#[test]
fn test_simple_diff() {
let from = BlockPosition::new(2, 0, -3);
let to = from + Vector3::new(-1, 2, 0);
let radius = 1;
let expected: HashSet<BlockPosition> = [
BlockPosition::new( 1, 0, 0),
BlockPosition::new( 1, 1, 0),
BlockPosition::new( 1, -1, 0),
BlockPosition::new( 1, 0, 1),
BlockPosition::new( 1, 1, 1),
BlockPosition::new( 1, -1, 1),
BlockPosition::new( 1, 0, -1),
BlockPosition::new( 1, 1, -1),
BlockPosition::new( 1, -1, -1),
BlockPosition::new( 0, -1, 0),
BlockPosition::new( 0, 0, 0),
BlockPosition::new( 1, -1, 0),
BlockPosition::new( 1, 0, 0),
BlockPosition::new(-1, -1, 0),
BlockPosition::new(-1, 0, 0),
BlockPosition::new( 0, -1, -1),
BlockPosition::new( 0, 0, -1),
BlockPosition::new( 1, -1, -1),
BlockPosition::new( 1, 0, -1),
BlockPosition::new(-1, -1, -1),
BlockPosition::new(-1, 0, -1),
BlockPosition::new( 0, -1, 1),
BlockPosition::new( 0, 0, 1),
BlockPosition::new( 1, -1, 1),
BlockPosition::new( 1, 0, 1),
BlockPosition::new(-1, -1, 1),
BlockPosition::new(-1, 0, 1),
]
.iter()
.map(|p| p.clone() + from.as_pnt().to_vec())
.collect();
let actual = cube_diff(&from, &to, radius);
assert_eq!(expected, actual.into_iter().collect());
}
#[test]
fn test_diff_no_dups() {
let from = BlockPosition::new(2, 0, -3);
let to = from + Vector3::new(-1, 2, 0);
let radius = 2;
let expected = cube_diff(&from, &to, radius);
let actual: HashSet<BlockPosition> = expected.iter().map(|&x| x).collect();
assert_eq!(expected.len(), actual.len());
}
#[test]
fn test_no_diff() {
let center = BlockPosition::new(-5, 1, -7);
let radius = 3;
assert!(cube_diff(¢er, ¢er, radius).is_empty());
}
#[bench]
fn simple_shell_bench(_: &mut Bencher) {
black_box(cube_shell(&BlockPosition::new(0, 0, 0), 400));
}
#[bench]
fn simple_diff_bench(_: &mut Bencher) {
black_box(cube_diff(&BlockPosition::new(-1, 1, -1), &BlockPosition::new(0, 0, 0), 400));
}<|fim▁end|> | range_inclusive(from.z - radius, min(from.z + radius, to.z - radius - 1))
} else {
range_inclusive(max(from.z - radius, to.z + radius + 1), from.z + radius) |
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>PROJECT_DEFAULTS = 'Project Defaults'
PATHS = 'Paths'
_from_config = {
'author': None,
'email': None,
'license': None,
'language': None,
'type': None,
'parent': None,
'vcs': None,
'footprints': None
}
_from_args = {
'name': None,
'author': None,
'email': None,
'license': None,
'language': None,
'type': None,
'parent': None,
'vcs': None,
'footprint': None
}
def load_args(args):
from_args = _from_args.copy()
keys = _from_args.keys()
for key in keys:
if args.__contains__(key):
from_args[key] = args.__getattribute__(key)
return from_args
def load_config(config):
from_config = _from_config.copy()
keys = _from_config.keys()
if config:
if config.has_section(PROJECT_DEFAULTS):
for key in keys:
if config.has_option(PROJECT_DEFAULTS, key):
from_config[key] = config.get(PROJECT_DEFAULTS, key)
if config.has_section(PATHS):
for key in keys:
if config.has_option(PATHS, key):
from_config[key] = config.get(PATHS, key)
return from_config
def merge_configged_argged(configged, argged):
merged = configged.copy()
for key in argged.keys():
if True in [key == k for k in configged.keys()]:
# We only care about a None val if the key exists in configged
# this will overwrite the config so that args take percedence
if argged[key] is not None:
merged[key] = argged[key]
else:
# If the key is not already here, then it must be 'footprint', in
# which case we definitely want to include it since that is our
# highest priority and requires less args to generate a project
merged[key] = argged[key]
return merged
def footprint_requires(merged):
required = ['name', 'parent']
passed = 0
pass_requires = len(required)
for r in required:
if r in merged.keys():
if merged[r] is not None:
passed += 1
return passed == pass_requires
def solo_args_requires(args):
required = ['name', 'parent', 'language', 'type']
passed = 0
pass_requires = len(required)
for r in required:
if r in args.keys():
if args[r] is not None:
passed += 1
return passed == pass_requires
def validate_args(args, config):
if config is not None:
configged = load_config(config)
argged = load_args(args)
merged = merge_configged_argged(configged, argged)<|fim▁hole|> if merged['footprint'] is not None:
return footprint_requires(merged), merged
# If no footprint, we need name, parent, language, and type to perform
# footprint lookups
if None not in [merged['name'], merged['parent'], merged['language'],
merged['type']]:
return True, merged
return False, merged
argged = load_args(args)
return solo_args_requires(argged), argged<|fim▁end|> | # If footprint is provided, we only need name and parent |
<|file_name|>list_test.go<|end_file_name|><|fim▁begin|>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package node
import (
"reflect"
"testing"
"github.com/kubernetes/dashboard/src/app/backend/resource/common"
"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
"github.com/kubernetes/dashboard/src/app/backend/resource/metric"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
api "k8s.io/client-go/pkg/api/v1"
)
func TestGetNodeList(t *testing.T) {
cases := []struct {
node *api.Node
expected *NodeList
}{
{
&api.Node{
ObjectMeta: metaV1.ObjectMeta{Name: "test-node"},
Spec: api.NodeSpec{
Unschedulable: true,
},
},
&NodeList{
ListMeta: common.ListMeta{
TotalItems: 1,
},
CumulativeMetrics: make([]metric.Metric, 0),
Nodes: []Node{{
ObjectMeta: common.ObjectMeta{Name: "test-node"},
TypeMeta: common.TypeMeta{Kind: common.ResourceKindNode},
Ready: "Unknown",
AllocatedResources: NodeAllocatedResources{
CPURequests: 0,
CPURequestsFraction: 0,<|fim▁hole|> CPULimits: 0,
CPULimitsFraction: 0,
CPUCapacity: 0,
MemoryRequests: 0,
MemoryRequestsFraction: 0,
MemoryLimits: 0,
MemoryLimitsFraction: 0,
MemoryCapacity: 0,
AllocatedPods: 0,
PodCapacity: 0,
},
},
},
},
},
}
for _, c := range cases {
fakeClient := fake.NewSimpleClientset(c.node)
fakeHeapsterClient := FakeHeapsterClient{client: *fake.NewSimpleClientset()}
actual, _ := GetNodeList(fakeClient, dataselect.NoDataSelect, fakeHeapsterClient)
if !reflect.DeepEqual(actual, c.expected) {
t.Errorf("GetNodeList() == \ngot: %#v, \nexpected %#v", actual, c.expected)
}
}
}<|fim▁end|> | |
<|file_name|>dupe-symbols-3.rs<|end_file_name|><|fim▁begin|>// build-fail<|fim▁hole|>//
#![crate_type="rlib"]
#![allow(warnings)]
#[export_name="fail"]
pub fn a() {
}
#[no_mangle]
pub fn fail() {
//~^ symbol `fail` is already defined
}<|fim▁end|> | |
<|file_name|>webpack.config.dev.js<|end_file_name|><|fim▁begin|>import webpack from 'webpack';
import path from 'path';
export default {
debug: true,
devtool: 'cheap-module-eval-source-map',
noInfo: false,
entry: [
// 'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
'./src/index'
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './src'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
{test: /(\.css)$/, loaders: ['style', 'css']},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"},
{test: /\.(woff|woff2)$/, loader: "url?prefix=font/&limit=5000"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream"},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml"}<|fim▁hole|><|fim▁end|> | ]
}
}; |
<|file_name|>instantiation_validation_noisy_neighbors_benchmark.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 Intel Research and Development Ireland Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import instantiation_validation_benchmark as base
from experimental_framework import common
NUM_OF_NEIGHBORS = 'num_of_neighbours'
AMOUNT_OF_RAM = 'amount_of_ram'
NUMBER_OF_CORES = 'number_of_cores'
NETWORK_NAME = 'network'
SUBNET_NAME = 'subnet'
class InstantiationValidationNoisyNeighborsBenchmark(
base.InstantiationValidationBenchmark):
def __init__(self, name, params):
base.InstantiationValidationBenchmark.__init__(self, name, params)
if common.RELEASE == 'liberty':
temp_name = 'stress_workload_liberty.yaml'
else:
temp_name = 'stress_workload.yaml'
self.template_file = common.get_template_dir() + \
temp_name
self.stack_name = 'neighbour'
self.neighbor_stack_names = list()
def get_features(self):
features = super(InstantiationValidationNoisyNeighborsBenchmark,
self).get_features()
features['description'] = 'Instantiation Validation Benchmark ' \
'with noisy neghbors'
features['parameters'].append(NUM_OF_NEIGHBORS)
features['parameters'].append(AMOUNT_OF_RAM)
features['parameters'].append(NUMBER_OF_CORES)
features['parameters'].append(NETWORK_NAME)
features['parameters'].append(SUBNET_NAME)
features['allowed_values'][NUM_OF_NEIGHBORS] = \
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
features['allowed_values'][NUMBER_OF_CORES] = \
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
features['allowed_values'][AMOUNT_OF_RAM] = \
['256M', '1G', '2G', '3G', '4G', '5G', '6G', '7G', '8G', '9G',
'10G']
features['default_values'][NUM_OF_NEIGHBORS] = '1'
features['default_values'][NUMBER_OF_CORES] = '1'
features['default_values'][AMOUNT_OF_RAM] = '256M'
features['default_values'][NETWORK_NAME] = ''
features['default_values'][SUBNET_NAME] = ''
return features
def init(self):
super(InstantiationValidationNoisyNeighborsBenchmark, self).init()
common.replace_in_file(self.lua_file, 'local out_file = ""',
'local out_file = "' +
self.results_file + '"')
heat_param = dict()
heat_param['network'] = self.params[NETWORK_NAME]
heat_param['subnet'] = self.params[SUBNET_NAME]
heat_param['cores'] = self.params['number_of_cores']
heat_param['memory'] = self.params['amount_of_ram']
for i in range(0, int(self.params['num_of_neighbours'])):
stack_name = self.stack_name + str(i)
common.DEPLOYMENT_UNIT.deploy_heat_template(self.template_file,
stack_name,
heat_param)
self.neighbor_stack_names.append(stack_name)
def finalize(self):
common.replace_in_file(self.lua_file, 'local out_file = "' +
self.results_file + '"',
'local out_file = ""')
# destroy neighbor stacks
for stack_name in self.neighbor_stack_names:<|fim▁hole|><|fim▁end|> | common.DEPLOYMENT_UNIT.destroy_heat_template(stack_name)
self.neighbor_stack_names = list() |
<|file_name|>service.go<|end_file_name|><|fim▁begin|>//go:build linux
// +build linux
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v2
import (
"context"
"encoding/json"
"io"
"os"
"path/filepath"
goruntime "runtime"
"sync"
"syscall"
"time"
"github.com/containerd/cgroups"
cgroupsv2 "github.com/containerd/cgroups/v2"
eventstypes "github.com/containerd/containerd/api/events"
"github.com/containerd/containerd/api/types/task"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/pkg/oom"
oomv1 "github.com/containerd/containerd/pkg/oom/v1"
oomv2 "github.com/containerd/containerd/pkg/oom/v2"
"github.com/containerd/containerd/pkg/process"
"github.com/containerd/containerd/pkg/schedcore"
"github.com/containerd/containerd/pkg/stdio"
"github.com/containerd/containerd/pkg/userns"
"github.com/containerd/containerd/runtime/v2/runc"
"github.com/containerd/containerd/runtime/v2/runc/options"
"github.com/containerd/containerd/runtime/v2/shim"
taskAPI "github.com/containerd/containerd/runtime/v2/task"
"github.com/containerd/containerd/sys/reaper"
runcC "github.com/containerd/go-runc"
"github.com/containerd/typeurl"
"github.com/gogo/protobuf/proto"
ptypes "github.com/gogo/protobuf/types"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
exec "golang.org/x/sys/execabs"
"golang.org/x/sys/unix"
)
var (
_ = (taskAPI.TaskService)(&service{})
empty = &ptypes.Empty{}
)
// group labels specifies how the shim groups services.
// currently supports a runc.v2 specific .group label and the
// standard k8s pod label. Order matters in this list
var groupLabels = []string{
"io.containerd.runc.v2.group",
"io.kubernetes.cri.sandbox-id",
}
type spec struct {
Annotations map[string]string `json:"annotations,omitempty"`
}
// New returns a new shim service that can be used via GRPC
func New(ctx context.Context, id string, publisher shim.Publisher, shutdown func()) (shim.Shim, error) {
var (
ep oom.Watcher
err error
)
if cgroups.Mode() == cgroups.Unified {
ep, err = oomv2.New(publisher)
} else {
ep, err = oomv1.New(publisher)
}
if err != nil {
return nil, err
}
go ep.Run(ctx)
s := &service{
id: id,
context: ctx,
events: make(chan interface{}, 128),
ec: reaper.Default.Subscribe(),
ep: ep,
cancel: shutdown,
containers: make(map[string]*runc.Container),
}
go s.processExits()
runcC.Monitor = reaper.Default
if err := s.initPlatform(); err != nil {
shutdown()
return nil, errors.Wrap(err, "failed to initialized platform behavior")
}
go s.forward(ctx, publisher)
if address, err := shim.ReadAddress("address"); err == nil {
s.shimAddress = address
}
return s, nil
}
// service is the shim implementation of a remote shim over GRPC
type service struct {
mu sync.Mutex
eventSendMu sync.Mutex
context context.Context
events chan interface{}
platform stdio.Platform
ec chan runcC.Exit
ep oom.Watcher
// id only used in cleanup case
id string
containers map[string]*runc.Container
shimAddress string
cancel func()
}
func newCommand(ctx context.Context, id, containerdBinary, containerdAddress, containerdTTRPCAddress string) (*exec.Cmd, error) {
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return nil, err
}
self, err := os.Executable()
if err != nil {
return nil, err
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
args := []string{
"-namespace", ns,
"-id", id,
"-address", containerdAddress,
}
cmd := exec.Command(self, args...)
cmd.Dir = cwd
cmd.Env = append(os.Environ(), "GOMAXPROCS=4")
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
return cmd, nil
}
func readSpec() (*spec, error) {
f, err := os.Open("config.json")
if err != nil {
return nil, err
}
defer f.Close()
var s spec
if err := json.NewDecoder(f).Decode(&s); err != nil {
return nil, err
}
return &s, nil
}
func (s *service) StartShim(ctx context.Context, opts shim.StartOpts) (_ string, retErr error) {
cmd, err := newCommand(ctx, opts.ID, opts.ContainerdBinary, opts.Address, opts.TTRPCAddress)
if err != nil {
return "", err
}
grouping := opts.ID
spec, err := readSpec()
if err != nil {
return "", err
}
for _, group := range groupLabels {
if groupID, ok := spec.Annotations[group]; ok {
grouping = groupID
break
}
}
address, err := shim.SocketAddress(ctx, opts.Address, grouping)
if err != nil {
return "", err
}
socket, err := shim.NewSocket(address)
if err != nil {
// the only time where this would happen is if there is a bug and the socket
// was not cleaned up in the cleanup method of the shim or we are using the
// grouping functionality where the new process should be run with the same
// shim as an existing container
if !shim.SocketEaddrinuse(err) {
return "", errors.Wrap(err, "create new shim socket")
}
if shim.CanConnect(address) {
if err := shim.WriteAddress("address", address); err != nil {
return "", errors.Wrap(err, "write existing socket for shim")
}
return address, nil
}
if err := shim.RemoveSocket(address); err != nil {
return "", errors.Wrap(err, "remove pre-existing socket")
}
if socket, err = shim.NewSocket(address); err != nil {
return "", errors.Wrap(err, "try create new shim socket 2x")
}
}
defer func() {
if retErr != nil {
socket.Close()
_ = shim.RemoveSocket(address)
}
}()
// make sure that reexec shim-v2 binary use the value if need
if err := shim.WriteAddress("address", address); err != nil {
return "", err
}
f, err := socket.File()
if err != nil {
return "", err
}
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
goruntime.LockOSThread()
if os.Getenv("SCHED_CORE") != "" {
if err := schedcore.Create(schedcore.ProcessGroup); err != nil {
return "", errors.Wrap(err, "enable sched core support")
}
}
if err := cmd.Start(); err != nil {
f.Close()
return "", err
}
goruntime.UnlockOSThread()
defer func() {
if retErr != nil {
cmd.Process.Kill()
}
}()
// make sure to wait after start
go cmd.Wait()
if data, err := io.ReadAll(os.Stdin); err == nil {
if len(data) > 0 {
var any ptypes.Any
if err := proto.Unmarshal(data, &any); err != nil {
return "", err
}
v, err := typeurl.UnmarshalAny(&any)
if err != nil {
return "", err
}
if opts, ok := v.(*options.Options); ok {
if opts.ShimCgroup != "" {
if cgroups.Mode() == cgroups.Unified {
cg, err := cgroupsv2.LoadManager("/sys/fs/cgroup", opts.ShimCgroup)
if err != nil {
return "", errors.Wrapf(err, "failed to load cgroup %s", opts.ShimCgroup)
}
if err := cg.AddProc(uint64(cmd.Process.Pid)); err != nil {
return "", errors.Wrapf(err, "failed to join cgroup %s", opts.ShimCgroup)
}
} else {
cg, err := cgroups.Load(cgroups.V1, cgroups.StaticPath(opts.ShimCgroup))
if err != nil {
return "", errors.Wrapf(err, "failed to load cgroup %s", opts.ShimCgroup)
}
if err := cg.Add(cgroups.Process{
Pid: cmd.Process.Pid,
}); err != nil {
return "", errors.Wrapf(err, "failed to join cgroup %s", opts.ShimCgroup)
}
}
}
}
}
}
if err := shim.AdjustOOMScore(cmd.Process.Pid); err != nil {
return "", errors.Wrap(err, "failed to adjust OOM score for shim")
}
return address, nil
}
func (s *service) Cleanup(ctx context.Context) (*taskAPI.DeleteResponse, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
path := filepath.Join(filepath.Dir(cwd), s.id)
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return nil, err
}
runtime, err := runc.ReadRuntime(path)
if err != nil {
return nil, err
}
opts, err := runc.ReadOptions(path)
if err != nil {
return nil, err
}
root := process.RuncRoot
if opts != nil && opts.Root != "" {
root = opts.Root
}
r := process.NewRunc(root, path, ns, runtime, "", false)
if err := r.Delete(ctx, s.id, &runcC.DeleteOpts{
Force: true,
}); err != nil {
logrus.WithError(err).Warn("failed to remove runc container")
}
if err := mount.UnmountAll(filepath.Join(path, "rootfs"), 0); err != nil {
logrus.WithError(err).Warn("failed to cleanup rootfs mount")
}
return &taskAPI.DeleteResponse{
ExitedAt: time.Now(),
ExitStatus: 128 + uint32(unix.SIGKILL),
}, nil
}
// Create a new initial process and container with the underlying OCI runtime
func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (_ *taskAPI.CreateTaskResponse, err error) {
s.mu.Lock()
defer s.mu.Unlock()
container, err := runc.NewContainer(ctx, s.platform, r)
if err != nil {
return nil, err
}
s.containers[r.ID] = container
s.send(&eventstypes.TaskCreate{
ContainerID: r.ID,
Bundle: r.Bundle,
Rootfs: r.Rootfs,
IO: &eventstypes.TaskIO{
Stdin: r.Stdin,
Stdout: r.Stdout,
Stderr: r.Stderr,
Terminal: r.Terminal,
},
Checkpoint: r.Checkpoint,
Pid: uint32(container.Pid()),
})
return &taskAPI.CreateTaskResponse{
Pid: uint32(container.Pid()),
}, nil
}
// Start a process
func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
// hold the send lock so that the start events are sent before any exit events in the error case
s.eventSendMu.Lock()
p, err := container.Start(ctx, r)
if err != nil {
s.eventSendMu.Unlock()
return nil, errdefs.ToGRPC(err)
}
switch r.ExecID {
case "":
switch cg := container.Cgroup().(type) {
case cgroups.Cgroup:
if err := s.ep.Add(container.ID, cg); err != nil {
logrus.WithError(err).Error("add cg to OOM monitor")
}
case *cgroupsv2.Manager:
allControllers, err := cg.RootControllers()
if err != nil {
logrus.WithError(err).Error("failed to get root controllers")
} else {
if err := cg.ToggleControllers(allControllers, cgroupsv2.Enable); err != nil {
if userns.RunningInUserNS() {
logrus.WithError(err).Debugf("failed to enable controllers (%v)", allControllers)
} else {
logrus.WithError(err).Errorf("failed to enable controllers (%v)", allControllers)
}
}
}
if err := s.ep.Add(container.ID, cg); err != nil {
logrus.WithError(err).Error("add cg to OOM monitor")
}
}
s.send(&eventstypes.TaskStart{
ContainerID: container.ID,
Pid: uint32(p.Pid()),
})
default:
s.send(&eventstypes.TaskExecStarted{
ContainerID: container.ID,
ExecID: r.ExecID,
Pid: uint32(p.Pid()),
})
}
s.eventSendMu.Unlock()
return &taskAPI.StartResponse{
Pid: uint32(p.Pid()),
}, nil
}
// Delete the initial process and container
func (s *service) Delete(ctx context.Context, r *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
p, err := container.Delete(ctx, r)
if err != nil {
return nil, errdefs.ToGRPC(err)
}
// if we deleted an init task, send the task delete event
if r.ExecID == "" {
s.mu.Lock()
delete(s.containers, r.ID)
s.mu.Unlock()
s.send(&eventstypes.TaskDelete{
ContainerID: container.ID,
Pid: uint32(p.Pid()),
ExitStatus: uint32(p.ExitStatus()),
ExitedAt: p.ExitedAt(),
})
}
return &taskAPI.DeleteResponse{
ExitStatus: uint32(p.ExitStatus()),
ExitedAt: p.ExitedAt(),
Pid: uint32(p.Pid()),
}, nil
}
// Exec an additional process inside the container
func (s *service) Exec(ctx context.Context, r *taskAPI.ExecProcessRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
ok, cancel := container.ReserveProcess(r.ExecID)
if !ok {
return nil, errdefs.ToGRPCf(errdefs.ErrAlreadyExists, "id %s", r.ExecID)
}
process, err := container.Exec(ctx, r)
if err != nil {
cancel()
return nil, errdefs.ToGRPC(err)
}
s.send(&eventstypes.TaskExecAdded{
ContainerID: container.ID,
ExecID: process.ID(),
})
return empty, nil
}
// ResizePty of a process
func (s *service) ResizePty(ctx context.Context, r *taskAPI.ResizePtyRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.ResizePty(ctx, r); err != nil {
return nil, errdefs.ToGRPC(err)
}
return empty, nil
}
// State returns runtime state information for a process
func (s *service) State(ctx context.Context, r *taskAPI.StateRequest) (*taskAPI.StateResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
p, err := container.Process(r.ExecID)
if err != nil {
return nil, errdefs.ToGRPC(err)
}
st, err := p.Status(ctx)
if err != nil {
return nil, err
}
status := task.StatusUnknown
switch st {
case "created":
status = task.StatusCreated
case "running":
status = task.StatusRunning
case "stopped":
status = task.StatusStopped
case "paused":
status = task.StatusPaused
case "pausing":
status = task.StatusPausing
}
sio := p.Stdio()
return &taskAPI.StateResponse{
ID: p.ID(),
Bundle: container.Bundle,
Pid: uint32(p.Pid()),
Status: status,
Stdin: sio.Stdin,
Stdout: sio.Stdout,
Stderr: sio.Stderr,
Terminal: sio.Terminal,
ExitStatus: uint32(p.ExitStatus()),
ExitedAt: p.ExitedAt(),
}, nil
}
// Pause the container
func (s *service) Pause(ctx context.Context, r *taskAPI.PauseRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.Pause(ctx); err != nil {
return nil, errdefs.ToGRPC(err)
}
s.send(&eventstypes.TaskPaused{
ContainerID: container.ID,
})
return empty, nil
}
// Resume the container
func (s *service) Resume(ctx context.Context, r *taskAPI.ResumeRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.Resume(ctx); err != nil {
return nil, errdefs.ToGRPC(err)
}
s.send(&eventstypes.TaskResumed{
ContainerID: container.ID,
})
return empty, nil
}
// Kill a process with the provided signal
func (s *service) Kill(ctx context.Context, r *taskAPI.KillRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.Kill(ctx, r); err != nil {
return nil, errdefs.ToGRPC(err)
}
return empty, nil
}
// Pids returns all pids inside the container
func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
pids, err := s.getContainerPids(ctx, r.ID)
if err != nil {
return nil, errdefs.ToGRPC(err)
}
var processes []*task.ProcessInfo
for _, pid := range pids {
pInfo := task.ProcessInfo{
Pid: pid,
}
for _, p := range container.ExecdProcesses() {
if p.Pid() == int(pid) {
d := &options.ProcessDetails{
ExecID: p.ID(),
}
a, err := typeurl.MarshalAny(d)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal process %d info", pid)
}
pInfo.Info = a
break
}
}
processes = append(processes, &pInfo)
}
return &taskAPI.PidsResponse{
Processes: processes,
}, nil
}
// CloseIO of a process
func (s *service) CloseIO(ctx context.Context, r *taskAPI.CloseIORequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.CloseIO(ctx, r); err != nil {
return nil, err
}
return empty, nil
}
// Checkpoint the container
func (s *service) Checkpoint(ctx context.Context, r *taskAPI.CheckpointTaskRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.Checkpoint(ctx, r); err != nil {
return nil, errdefs.ToGRPC(err)
}
return empty, nil
}
// Update a running container
func (s *service) Update(ctx context.Context, r *taskAPI.UpdateTaskRequest) (*ptypes.Empty, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
if err := container.Update(ctx, r); err != nil {
return nil, errdefs.ToGRPC(err)
}
return empty, nil
}
// Wait for a process to exit
func (s *service) Wait(ctx context.Context, r *taskAPI.WaitRequest) (*taskAPI.WaitResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
p, err := container.Process(r.ExecID)
if err != nil {<|fim▁hole|> return nil, errdefs.ToGRPC(err)
}
p.Wait()
return &taskAPI.WaitResponse{
ExitStatus: uint32(p.ExitStatus()),
ExitedAt: p.ExitedAt(),
}, nil
}
// Connect returns shim information such as the shim's pid
func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {
var pid int
if container, err := s.getContainer(r.ID); err == nil {
pid = container.Pid()
}
return &taskAPI.ConnectResponse{
ShimPid: uint32(os.Getpid()),
TaskPid: uint32(pid),
}, nil
}
func (s *service) Shutdown(ctx context.Context, r *taskAPI.ShutdownRequest) (*ptypes.Empty, error) {
s.mu.Lock()
defer s.mu.Unlock()
// return out if the shim is still servicing containers
if len(s.containers) > 0 {
return empty, nil
}
if s.platform != nil {
s.platform.Close()
}
if s.shimAddress != "" {
_ = shim.RemoveSocket(s.shimAddress)
}
// please make sure that temporary resource has been cleanup
// before shutdown service.
s.cancel()
close(s.events)
return empty, nil
}
func (s *service) Stats(ctx context.Context, r *taskAPI.StatsRequest) (*taskAPI.StatsResponse, error) {
container, err := s.getContainer(r.ID)
if err != nil {
return nil, err
}
cgx := container.Cgroup()
if cgx == nil {
return nil, errdefs.ToGRPCf(errdefs.ErrNotFound, "cgroup does not exist")
}
var statsx interface{}
switch cg := cgx.(type) {
case cgroups.Cgroup:
stats, err := cg.Stat(cgroups.IgnoreNotExist)
if err != nil {
return nil, err
}
statsx = stats
case *cgroupsv2.Manager:
stats, err := cg.Stat()
if err != nil {
return nil, err
}
statsx = stats
default:
return nil, errdefs.ToGRPCf(errdefs.ErrNotImplemented, "unsupported cgroup type %T", cg)
}
data, err := typeurl.MarshalAny(statsx)
if err != nil {
return nil, err
}
return &taskAPI.StatsResponse{
Stats: data,
}, nil
}
func (s *service) processExits() {
for e := range s.ec {
s.checkProcesses(e)
}
}
func (s *service) send(evt interface{}) {
s.events <- evt
}
func (s *service) sendL(evt interface{}) {
s.eventSendMu.Lock()
s.events <- evt
s.eventSendMu.Unlock()
}
func (s *service) checkProcesses(e runcC.Exit) {
s.mu.Lock()
defer s.mu.Unlock()
for _, container := range s.containers {
if !container.HasPid(e.Pid) {
continue
}
for _, p := range container.All() {
if p.Pid() != e.Pid {
continue
}
if ip, ok := p.(*process.Init); ok {
// Ensure all children are killed
if runc.ShouldKillAllOnExit(s.context, container.Bundle) {
if err := ip.KillAll(s.context); err != nil {
logrus.WithError(err).WithField("id", ip.ID()).
Error("failed to kill init's children")
}
}
}
p.SetExited(e.Status)
s.sendL(&eventstypes.TaskExit{
ContainerID: container.ID,
ID: p.ID(),
Pid: uint32(e.Pid),
ExitStatus: uint32(e.Status),
ExitedAt: p.ExitedAt(),
})
return
}
return
}
}
func (s *service) getContainerPids(ctx context.Context, id string) ([]uint32, error) {
container, err := s.getContainer(id)
if err != nil {
return nil, err
}
p, err := container.Process("")
if err != nil {
return nil, errdefs.ToGRPC(err)
}
ps, err := p.(*process.Init).Runtime().Ps(ctx, id)
if err != nil {
return nil, err
}
pids := make([]uint32, 0, len(ps))
for _, pid := range ps {
pids = append(pids, uint32(pid))
}
return pids, nil
}
func (s *service) forward(ctx context.Context, publisher shim.Publisher) {
ns, _ := namespaces.Namespace(ctx)
ctx = namespaces.WithNamespace(context.Background(), ns)
for e := range s.events {
err := publisher.Publish(ctx, runc.GetTopic(e), e)
if err != nil {
logrus.WithError(err).Error("post event")
}
}
publisher.Close()
}
func (s *service) getContainer(id string) (*runc.Container, error) {
s.mu.Lock()
container := s.containers[id]
s.mu.Unlock()
if container == nil {
return nil, errdefs.ToGRPCf(errdefs.ErrNotFound, "container not created")
}
return container, nil
}
// initialize a single epoll fd to manage our consoles. `initPlatform` should
// only be called once.
func (s *service) initPlatform() error {
if s.platform != nil {
return nil
}
p, err := runc.NewPlatform()
if err != nil {
return err
}
s.platform = p
return nil
}<|fim▁end|> | |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put the linker script somewhere the top crate can find it<|fim▁hole|> .write_all(include_bytes!("stm32f411ve.ld"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=stm32f411ve.ld");
}<|fim▁end|> | let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("stm32f411ve.ld"))
.unwrap() |
<|file_name|>script.js<|end_file_name|><|fim▁begin|>/*
* ##### Sasson - advanced drupal theming. #####
*
* SITENAME scripts.
*
*/
<|fim▁hole|>// Drupal.behaviors.behaviorName = {
// attach: function(context) {
// // Do some magic...
// }
// };
})(jQuery);<|fim▁end|> | (function($) {
// DUPLICATE AND UNCOMMENT |
<|file_name|>taskrun.go<|end_file_name|><|fim▁begin|>package taskrun
import (
"errors"
"fmt"
"sync"
"github.com/taskcluster/taskcluster-worker/engines"
"github.com/taskcluster/taskcluster-worker/plugins"
"github.com/taskcluster/taskcluster-worker/runtime"
"github.com/taskcluster/taskcluster-worker/runtime/atomics"
"github.com/taskcluster/taskcluster-worker/runtime/client"
)
// A TaskRun holds the state of a running task.
//
// Methods on this object is not thread-safe, with the exception of Abort() and
// SetQueueClient() which are intended to be called from other threads.
type TaskRun struct {
// Constants
environment runtime.Environment
engine engines.Engine
pluginManager plugins.Plugin // use Plugin interface so we can mock it in tests
monitor runtime.Monitor
taskInfo runtime.TaskInfo
payload map[string]interface{}
// TaskContext
taskContext *runtime.TaskContext
controller *runtime.TaskContextController
// State
m sync.Mutex // lock protecting state variables
c sync.Cond // Broadcast when state changes
running bool // true, when a thread is advancing the stage
stage Stage // next stage to be run
success bool // true, if task is completed successfully
exception bool // true, if reason has a value
reason runtime.ExceptionReason
// Final error to return from Dispose()
fatalErr atomics.Bool // If we've seen ErrFatalInternalError
nonFatalErr atomics.Bool // If we've seen ErrNonFatalInternalError
// Flow state to be discarded at end if not nil
taskPlugin plugins.TaskPlugin
sandboxBuilder engines.SandboxBuilder
sandbox engines.Sandbox
resultSet engines.ResultSet
}
// New returns a new TaskRun
func New(options Options) *TaskRun {
// simple validation, having this a few places is just sane
options.mustBeValid()
t := &TaskRun{
environment: options.Environment,
engine: options.Engine,
pluginManager: options.PluginManager,
monitor: options.Monitor,
taskInfo: options.TaskInfo,
payload: options.Payload,
}
t.c.L = &t.m
// Create TaskContext and controller
var err error
t.taskContext, t.controller, err = runtime.NewTaskContext(
t.environment.TemporaryStorage.NewFilePath(),
t.taskInfo,
)
if err != nil {
t.monitor.WithTag("stage", "init").ReportError(err, "failed to create TaskContext")
// If we have an initial error, we just set state as resolved
t.stage = stageResolved
t.success = false
t.exception = true
t.reason = runtime.ReasonInternalError
t.fatalErr.Set(true)
} else {
t.controller.SetQueueClient(options.Queue)
}
return t
}
// SetQueueClient will update the queue client exposed through the TaskContext.
//
// This should be updated whenever the task is reclaimed.
func (t *TaskRun) SetQueueClient(queue client.Queue) {
if t.controller != nil {
t.controller.SetQueueClient(queue)
}
}
// SetCredentials is used to provide the task-specific temporary credentials,
// and update these whenever they change.
func (t *TaskRun) SetCredentials(clientID, accessToken, certificate string) {
if t.controller != nil {
t.controller.SetCredentials(clientID, accessToken, certificate)
}
}
// Abort will interrupt task execution.
func (t *TaskRun) Abort(reason AbortReason) {
t.m.Lock()
defer t.m.Unlock()
// If we are already resolved, we won't change the resolution
if t.stage == stageResolved {
debug("ignoring TaskRun.Abort() as TaskRun is resolved")
return
}
// Resolve this taskrun
t.stage = stageResolved
t.success = false
t.exception = true
// Set reason we are canceled
switch reason {
case WorkerShutdown:
t.reason = runtime.ReasonWorkerShutdown
case TaskCanceled:
t.reason = runtime.ReasonCanceled
default:
panic(fmt.Sprintf("Unknown AbortReason: %d", reason))
}
// Abort anything that's currently running
t.controller.Cancel()
// Inform anyone waiting for resolution
t.c.Broadcast()
}
// RunToStage will run all stages up-to and including the given stage.
//
// This will not rerun previous stages, the TaskRun structure always knows what
// stage it has executed. This is only useful for testing, the WaitForResult()
// method will run all stages before returning.
func (t *TaskRun) RunToStage(targetStage Stage) {
t.m.Lock()
defer t.m.Unlock()
// Validate input for santiy
if targetStage > StageFinished {
panic("RunToStage: stage > StageFinished is not allowed")
}
// We'll have no more than on thread running stages at any given time, so we
// wait till running is false
for t.running {
// if t.stage has advanced beyond stage, then we're done
if t.stage > targetStage {
return
}
t.c.Wait() // wait for state change
}
t.running = true // set running while we're inside the for-loop
for t.stage <= targetStage {
// Unlock so cancel can happen while we're running
stage := t.stage // take stage first, so we don't race
t.m.Unlock()
monitor := t.monitor.WithTag("stage", stage.String())
monitor.Debug("running stage: ", stage.String())
var err error
incidentID := monitor.CapturePanic(func() {
err = stages[stage](t)
})
t.m.Lock()<|fim▁hole|> // Handle errors
if err != nil || incidentID != "" {
reason := runtime.ReasonInternalError
if e, ok := runtime.IsMalformedPayloadError(err); ok {
for _, m := range e.Messages() {
t.controller.LogError(m)
}
reason = runtime.ReasonMalformedPayload
} else if err == runtime.ErrNonFatalInternalError {
t.nonFatalErr.Set(true)
} else if err == runtime.ErrFatalInternalError {
t.fatalErr.Set(true)
} else if err != nil {
incidentID = monitor.ReportError(err)
}
if incidentID != "" {
t.fatalErr.Set(true)
t.controller.LogError("Unhandled worker error encountered incidentID=", incidentID)
}
// Never change the resolution, if we've been cancelled or worker-shutdown
if t.stage != stageResolved {
t.stage = stageResolved
t.exception = true
t.success = false
t.reason = reason
}
}
// Never advance beyond stageResolved (could otherwise happen if cancel occurs)
if t.stage < stageResolved {
t.stage++
}
t.c.Broadcast()
}
// if resolved we always cancel the TaskContext
if t.stage == stageResolved {
t.controller.Cancel()
}
t.running = false
t.c.Broadcast()
}
// WaitForResult will run all stages up to and including StageFinished, before
// returning the resolution of the given TaskRun.
func (t *TaskRun) WaitForResult() (success bool, exception bool, reason runtime.ExceptionReason) {
t.RunToStage(StageFinished)
t.m.Lock()
success = t.success
exception = t.exception
reason = t.reason
t.m.Unlock()
return
}
func (t *TaskRun) capturePanicAndError(stage string, fn func() error) {
monitor := t.monitor.WithTag("stage", stage)
var err error
incidentID := monitor.CapturePanic(func() {
err = fn()
})
if incidentID != "" {
err = runtime.ErrFatalInternalError
}
switch err {
case runtime.ErrFatalInternalError:
t.fatalErr.Set(true)
case runtime.ErrNonFatalInternalError:
t.nonFatalErr.Set(true)
case nil:
return
default:
t.fatalErr.Set(true)
monitor.ReportError(err, "unhandled error in stage: ", stage)
}
}
// Dispose will finish any final processing dispose of all resources.
//
// If there was an unhandled error Dispose() returns either
// runtime.ErrFatalInternalError or runtime.ErrNonFatalInternalError.
// Any other error is reported/logged and runtime.ErrFatalInternalError is
// returned instead.
func (t *TaskRun) Dispose() error {
t.monitor.WithTag("stage", "dispose").Debug("running stage: dispose")
if t.controller != nil {
debug("canceling TaskContext and closing log")
t.controller.Cancel()
t.capturePanicAndError("dispose", t.controller.CloseLog)
}
if t.exception && t.taskPlugin != nil {
debug("running exception stage, reason = %s", t.reason.String())
t.capturePanicAndError("exception", func() error {
return t.taskPlugin.Exception(t.reason)
})
}
// Dispose of taskPlugin, if we have one
if t.taskPlugin != nil {
debug("disposing TaskPlugin")
t.capturePanicAndError("dispose", t.taskPlugin.Dispose)
t.taskPlugin = nil
}
if t.sandboxBuilder != nil {
debug("disposing SandboxBuilder")
t.capturePanicAndError("dispose", t.sandboxBuilder.Discard)
t.sandboxBuilder = nil
}
if t.sandbox != nil {
debug("disposing Sandbox")
t.capturePanicAndError("dispose", func() error {
err := t.sandbox.Abort()
if err == engines.ErrSandboxTerminated {
// If the TaskRun was interrupted before the 'waiting' stage, then the
// execution may have terminated, in which case calling WaitForResult()
// should be instant, and we get a ResultSet we'll dispose off later
err = nil
if t.resultSet == nil {
t.resultSet, err = t.sandbox.WaitForResult()
if err == engines.ErrSandboxAborted {
err = nil // Ignore the error, we'll warn about the contract violation
t.monitor.WithTag("stage", "dispose").ReportWarning(errors.New(
"Received ErrSandboxAborted from WaitForResult() after Abort() reported ErrSandboxTerminated",
), "contract violation during TaskRun.Dispose()")
}
}
}
return err
})
t.sandbox = nil
}
if t.resultSet != nil {
debug("disposing ResultSet")
t.capturePanicAndError("dispose", t.resultSet.Dispose)
t.resultSet = nil
}
if t.controller != nil {
debug("disposing TaskContext")
t.capturePanicAndError("dispose", t.controller.Dispose)
t.controller = nil
}
// We report any errors, so they'll be in sentry and logs, hence, we just
// notify caller about the fact that there was an unhandled error.
if t.fatalErr.Get() {
return runtime.ErrFatalInternalError
}
if t.nonFatalErr.Get() {
return runtime.ErrNonFatalInternalError
}
return nil
}<|fim▁end|> | |
<|file_name|>cacic_software.cpp<|end_file_name|><|fim▁begin|>#include "cacic_software.h"
cacic_software::cacic_software()
{
}
void cacic_software::iniciaColeta()
{
#ifdef Q_OS_WIN
this->coletaSoftware = coletaWin();
#elif defined(Q_OS_LINUX)
this->coletaSoftware = coletaLinux();
#endif
}
#if defined(Q_OS_WIN)
/***************************************************************
* Realiza a coleta de softwares do Windows por meio do regedit.
***************************************************************/
using namespace voidrealms::win32;
QJsonObject cacic_software::coletaWin()
{
QJsonObject softwaresJson;
QStringList regedit;
//No windows, ele armazena os dados em 2 locais diferentes se for x64. Um para programas x86 e outro pra x64.
regedit.append("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
regedit.append("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
foreach(QString registry, regedit){
VRegistry reg;
reg.OpenKey(HKEY_LOCAL_MACHINE, registry);
QStringList keys = reg.enum_Keys();
qDebug() << _exceptions;
foreach(QString key, keys){
if(!_exceptions.contains(key) ||
(_exceptions.contains(key) && !_exceptions[key].isEmpty())){
QVariantMap software;
VRegistry subReg;
subReg.OpenKey(HKEY_LOCAL_MACHINE, registry + key);
if (!subReg.get_REG_SZ("DisplayName").isEmpty())
software["description"] = subReg.get_REG_SZ("DisplayName");
if (!subReg.get_REG_SZ("Publisher").isEmpty())
software["publisher"] = subReg.get_REG_SZ("Publisher");
if (!subReg.get_REG_SZ("InstallLocation").isEmpty())
software["installLocation"] = subReg.get_REG_SZ("InstallLocation");
if (!subReg.get_REG_SZ("InstallDate").isEmpty())
software["installDate"] = subReg.get_REG_SZ("InstallDate");
if (!subReg.get_REG_SZ("URLInfoAbout").isEmpty())
software["url"] = subReg.get_REG_SZ("URLInfoAbout");
if (!subReg.get_REG_EXPAND_SZ("UninstallString").isEmpty())
software["uninstallString"] = subReg.get_REG_EXPAND_SZ("UninstallString");
if (!subReg.get_REG_EXPAND_SZ("QuietUninstallString").isEmpty())
software["quietUninstallString"] = subReg.get_REG_EXPAND_SZ("QuietUninstallString");
if (!subReg.get_REG_SZ("DisplayVersion").isEmpty())
software["version"] = subReg.get_REG_SZ("DisplayVersion");
software["name"] = key;
if(_exceptions.contains(key)){
foreach(QString value, _exceptions[key]){
qDebug() << value;
software.remove(value);
}
}
softwaresJson[key] = QJsonObject::fromVariantMap(software);
}
}
}
return softwaresJson;
}
#elif defined(Q_OS_LINUX)
QJsonObject cacic_software::coletaLinux()
{
OperatingSystem operatingSystem;
if( operatingSystem.getIdOs() == OperatingSystem::LINUX_ARCH ) {
return coletaArch();
} else /*if ( operatingSystem.getIdOs() == OperatingSystem::LINUX_DEBIAN ||
operatingSystem.getIdOs() == OperatingSystem::LINUX_UBUNTU )*/ {
return coletaDebian();
}
return QJsonObject();
}
QJsonObject cacic_software::coletaArch()
{
ConsoleObject console;
QJsonObject softwaresJson;
QStringList packages = console("pacman -Qe").split("\n");
foreach(QString package, packages) {
QString packageName = package.split(" ")[0];
if (!(packageName.isEmpty() || packageName.isNull()) &&
(!_exceptions.contains(packageName)
|| !(_exceptions.contains(packageName)
&& _exceptions[packageName].isEmpty()))){
QJsonObject packageJson;
QStringList packageInfo = console(QString("pacman -Qi ").append(packageName)).split("\n");
packageJson["name"] = QJsonValue::fromVariant(QString(packageName));
foreach(QString line, packageInfo) {
if(line.contains("Version") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("version")))
packageJson["version"] = line.split(":")[1].mid(1);
if(line.contains("Description") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("description")))
packageJson["description"] = line.split(":")[1].mid(1);
if(line.contains("URL")) {
QStringList url = line.split(":");
QString urlString;
for(int i = 1 ; i < url.size() ; ++i){
urlString.append(url[i]);
if(i == 1 ) urlString.append(":");
}
if(!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("url")))
packageJson["url"] = urlString.mid(1);
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("publisher")))
packageJson["publisher"] = urlString.mid(1);
}
// installSize não existe na coleta do Windows.
// if(line.contains("Installed size"))
// packageJson["installSize"] = line.split(":")[1].mid(1);
if(line.contains("Install Date") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installDate")))
packageJson["installDate"] = line.split(":")[1].mid(1);
}
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installLocation"))) {
QString location = console(QString("whereis ").append(packageName)).split("\n").at(0);
if(!location.split(":").at(1).isEmpty()) {
location = location.split(":").at(1).mid(1);
packageJson["installLocation"] = location;
}
}
softwaresJson[packageName] = packageJson;
}
}
return softwaresJson;
}
QJsonObject cacic_software::coletaDebian()
{
ConsoleObject console;
QJsonObject softwaresJson;
QStringList packages = console("dpkg --get-selections | grep -v '\^lib\\|\^fonts'").split("\n");
foreach(QString package, packages) {
QString packageName = package.split("\t")[0];
if (!(packageName.isEmpty() || packageName.isNull()) &&
(!_exceptions.contains(packageName)
|| !(_exceptions.contains(packageName)
&& _exceptions[packageName].isEmpty()))){
QJsonObject packageJson;
QStringList packageInfo = console(QString("apt-cache show ").append(packageName)).split("\n");
packageJson["name"] = QJsonValue::fromVariant(QString(packageName));
foreach(QString line, packageInfo) {
if(line.contains("Version:") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("version")))
packageJson["version"] = line.split(":")[1].mid(1);
if(line.contains("Description-en:") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("description"))){
packageJson["description"] = line.split(":")[1].mid(1);
}
if(line.contains("Homepage:")) {
QStringList url = line.split(":");
QString urlString;
for(int i = 1 ; i < url.size() ; ++i){
urlString.append(url[i]);
if(i == 1 ) urlString.append(":");
}<|fim▁hole|> if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("url")))
packageJson["url"] = urlString.mid(1);
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("publisher")))
packageJson["publisher"] = urlString.mid(1);
}
// installSize não existe na coleta do Windows.
// if(line.contains("Installed-Size:"))
// packageJson["installSize"] = line.split(":")[1].mid(1);
}
if (!packageName.isEmpty() &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installLocation"))){
QString treatedPackageName = packageName;
if(treatedPackageName.contains("amd64") || treatedPackageName.contains("i386"))
treatedPackageName = treatedPackageName.split(":").at(0);
QString location = console(QString("whereis ").append(treatedPackageName)).split("\n").at(0);
if(!location.split(":").at(1).isEmpty()) {
location = location.split(":").at(1).mid(1);
packageJson["installLocation"] = location;
}
}
softwaresJson[packageName] = packageJson;
}
// int counterPackages = softwaresJson.size();
}
return softwaresJson;
}
#endif
QHash<QString, QStringList> cacic_software::exceptions() const
{
return _exceptions;
}
void cacic_software::setExceptionClasses(const QHash<QString, QStringList> &exceptions)
{
_exceptions = exceptions;
}
QJsonObject cacic_software::toJsonObject()
{
return coletaSoftware;
}<|fim▁end|> | |
<|file_name|>multicriteria_base_recommender.py<|end_file_name|><|fim▁begin|>from abc import ABCMeta
from recommenders.similarity.weights_similarity_matrix_builder import \
WeightsSimilarityMatrixBuilder
from tripadvisor.fourcity import extractor
from recommenders.base_recommender import BaseRecommender
from utils import dictionary_utils
__author__ = 'fpena'
class MultiCriteriaBaseRecommender(BaseRecommender):
__metaclass__ = ABCMeta
def __init__(
self, name, similarity_metric=None,
significant_criteria_ranges=None):
super(MultiCriteriaBaseRecommender, self).__init__(name, None)
self._significant_criteria_ranges = significant_criteria_ranges
self._similarity_matrix_builder = WeightsSimilarityMatrixBuilder(similarity_metric)
self.user_cluster_dictionary = None
def load(self, reviews):
self.reviews = reviews
self.user_ids = extractor.get_groupby_list(self.reviews, 'user_id')
self.user_dictionary =\
extractor.initialize_cluster_users(self.reviews, self._significant_criteria_ranges)
self.user_cluster_dictionary = self.build_user_clusters(
self.reviews, self._significant_criteria_ranges)
if self._similarity_matrix_builder._similarity_metric is not None:
self.user_similarity_matrix =\
self._similarity_matrix_builder.build_similarity_matrix(
self.user_dictionary, self.user_ids)
def clear(self):
super(MultiCriteriaBaseRecommender, self).clear()
self.user_cluster_dictionary = None
# TODO: Add the item_id as a parameter in order to optimize the method
def get_neighbourhood(self, user_id):
cluster_name = self.user_dictionary[user_id].cluster
cluster_users = list(self.user_cluster_dictionary[cluster_name])
cluster_users.remove(user_id)
# We remove the given user from the cluster in order to avoid bias
if self._num_neighbors is None:
return cluster_users
similarity_matrix = self.user_similarity_matrix[user_id].copy()<|fim▁hole|> intersection_set = set.intersection(set(ordered_similar_users), set(cluster_users))
intersection_lst = [t for t in ordered_similar_users if t in intersection_set]
return intersection_lst # [:self._num_neighbors]
@staticmethod
def build_user_clusters(reviews, significant_criteria_ranges=None):
"""
Builds a series of clusters for users according to their significant
criteria. Users that have exactly the same significant criteria will belong
to the same cluster.
:param reviews: the list of reviews
:return: a dictionary where all the keys are the cluster names and the
values for those keys are list of users that belong to that cluster
"""
user_list = extractor.get_groupby_list(reviews, 'user_id')
user_cluster_dictionary = {}
for user in user_list:
weights = extractor.get_criteria_weights(reviews, user)
significant_criteria, cluster_name =\
extractor.get_significant_criteria(weights, significant_criteria_ranges)
if cluster_name in user_cluster_dictionary:
user_cluster_dictionary[cluster_name].append(user)
else:
user_cluster_dictionary[cluster_name] = [user]
return user_cluster_dictionary<|fim▁end|> | similarity_matrix.pop(user_id, None)
ordered_similar_users = dictionary_utils.sort_dictionary_keys(
similarity_matrix)
|
<|file_name|>TeamServiceImpl.java<|end_file_name|><|fim▁begin|>package info.thecodinglive.service;
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
public void addTeam(Team team) {
teamDao.addTeam(team);
}
@Override
public void updateTeam(Team team) {
teamDao.updateTeam(team);
}
@Override
public Team getTeam(int id) {
return teamDao.getTeam(id);
}
@Override
public void deleteTeam(int id) {
teamDao.deleteTeam(id);
}
<|fim▁hole|> public List<Team> getTeams() {
return teamDao.getTeams();
}
}<|fim▁end|> | @Override |
<|file_name|>core.cpp<|end_file_name|><|fim▁begin|>/*
*** MolShake Module - Core
*** src/modules/molshake/core.cpp
Copyright T. Youngs 2012-2018
This file is part of Dissolve.
Dissolve is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Dissolve is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Dissolve. If not, see <http://www.gnu.org/licenses/>.
*/
#include "modules/molshake/molshake.h"
// Static Members
List<Module> MolShakeModule::instances_;
/*
* Constructor / Destructor
*/
// Constructor
MolShakeModule::MolShakeModule() : Module()
{
// Add to instances list and set unique name for this instance
uniqueName_.sprintf("%s%02i", type(), instances_.nItems());
instances_.own(this);
// Set up variables / control parameters
setUpKeywords();
// Set representative colour
colour_[0] = 200;
colour_[1] = 0;
colour_[2] = 0;
}
// Destructor
MolShakeModule::~MolShakeModule()
{
}
<|fim▁hole|> * Instances
*/
// Create instance of this module
List<Module>& MolShakeModule::instances()
{
return instances_;
}
// Create instance of this module
Module* MolShakeModule::createInstance()
{
return new MolShakeModule;
}<|fim▁end|> | /* |
<|file_name|>account_move.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import ValidationError
from odoo import models, fields, api, _
from odoo.osv import expression
SII_VAT = '60805000-0'
class AccountMove(models.Model):
_inherit = "account.move"
partner_id_vat = fields.Char(related='partner_id.vat', string='VAT No')
l10n_latam_internal_type = fields.Selection(
related='l10n_latam_document_type_id.internal_type', string='L10n Latam Internal Type')
def _get_l10n_latam_documents_domain(self):
self.ensure_one()
if self.journal_id.company_id.account_fiscal_country_id != self.env.ref('base.cl') or not \
self.journal_id.l10n_latam_use_documents:
return super()._get_l10n_latam_documents_domain()
if self.journal_id.type == 'sale':
domain = [('country_id.code', '=', "CL"), ('internal_type', '!=', 'invoice_in')]
if self.company_id.partner_id.l10n_cl_sii_taxpayer_type == '1':
domain += [('code', '!=', '71')] # Companies with VAT Affected doesn't have "Boleta de honorarios Electrónica"
return domain
domain = [
('country_id.code', '=', 'CL'),
('internal_type', 'in', ['invoice', 'debit_note', 'credit_note', 'invoice_in'])]
if self.partner_id.l10n_cl_sii_taxpayer_type == '1' and self.partner_id_vat != '60805000-0':
domain += [('code', 'not in', ['39', '70', '71', '914', '911'])]
elif self.partner_id.l10n_cl_sii_taxpayer_type == '1' and self.partner_id_vat == '60805000-0':
domain += [('code', 'not in', ['39', '70', '71'])]
if self.move_type == 'in_invoice':
domain += [('internal_type', '!=', 'credit_note')]
elif self.partner_id.l10n_cl_sii_taxpayer_type == '2':
domain += [('code', 'in', ['70', '71', '56', '61'])]
elif self.partner_id.l10n_cl_sii_taxpayer_type == '3':
domain += [('code', 'in', ['35', '38', '39', '41', '56', '61'])]
elif not self.partner_id.l10n_cl_sii_taxpayer_type or self.partner_id.country_id != self.env.ref(
'base.cl') or self.partner_id.l10n_cl_sii_taxpayer_type == '4':
domain += [('code', 'in', [])]
return domain
def _check_document_types_post(self):
for rec in self.filtered(
lambda r: r.company_id.account_fiscal_country_id.code == "CL" and
r.journal_id.type in ['sale', 'purchase']):
tax_payer_type = rec.partner_id.l10n_cl_sii_taxpayer_type
vat = rec.partner_id.vat
country_id = rec.partner_id.country_id
latam_document_type_code = rec.l10n_latam_document_type_id.code
if (not tax_payer_type or not vat) and (country_id.code == "CL" and latam_document_type_code
and latam_document_type_code not in ['35', '38', '39', '41']):
raise ValidationError(_('Tax payer type and vat number are mandatory for this type of '
'document. Please set the current tax payer type of this customer'))
if rec.journal_id.type == 'sale' and rec.journal_id.l10n_latam_use_documents:<|fim▁hole|> if not ((tax_payer_type == '4' and latam_document_type_code in ['110', '111', '112']) or (
tax_payer_type == '3' and latam_document_type_code in ['39', '41', '61', '56'])):
raise ValidationError(_(
'Document types for foreign customers must be export type (codes 110, 111 or 112) or you \
should define the customer as an end consumer and use receipts (codes 39 or 41)'))
if rec.journal_id.type == 'purchase' and rec.journal_id.l10n_latam_use_documents:
if vat != SII_VAT and latam_document_type_code == '914':
raise ValidationError(_('The DIN document is intended to be used only with RUT 60805000-0'
' (Tesorería General de La República)'))
if not tax_payer_type or not vat:
if country_id.code == "CL" and latam_document_type_code not in [
'35', '38', '39', '41']:
raise ValidationError(_('Tax payer type and vat number are mandatory for this type of '
'document. Please set the current tax payer type of this supplier'))
if tax_payer_type == '2' and latam_document_type_code not in ['70', '71', '56', '61']:
raise ValidationError(_('The tax payer type of this supplier is incorrect for the selected type'
' of document.'))
if tax_payer_type in ['1', '3']:
if latam_document_type_code in ['70', '71']:
raise ValidationError(_('The tax payer type of this supplier is not entitled to deliver '
'fees documents'))
if latam_document_type_code in ['110', '111', '112']:
raise ValidationError(_('The tax payer type of this supplier is not entitled to deliver '
'imports documents'))
if tax_payer_type == '4' or country_id.code != "CL":
raise ValidationError(_('You need a journal without the use of documents for foreign '
'suppliers'))
@api.onchange('journal_id')
def _l10n_cl_onchange_journal(self):
if self.company_id.country_id.code == 'CL':
self.l10n_latam_document_type_id = False
def _post(self, soft=True):
self._check_document_types_post()
return super()._post(soft)
def _l10n_cl_get_formatted_sequence(self, number=0):
return '%s %06d' % (self.l10n_latam_document_type_id.doc_code_prefix, number)
def _get_starting_sequence(self):
""" If use documents then will create a new starting sequence using the document type code prefix and the
journal document number with a 6 padding number """
if self.journal_id.l10n_latam_use_documents and self.env.company.account_fiscal_country_id.code == "CL":
if self.l10n_latam_document_type_id:
return self._l10n_cl_get_formatted_sequence()
return super()._get_starting_sequence()
def _get_last_sequence_domain(self, relaxed=False):
where_string, param = super(AccountMove, self)._get_last_sequence_domain(relaxed)
if self.company_id.account_fiscal_country_id.code == "CL" and self.l10n_latam_use_documents:
where_string = where_string.replace('journal_id = %(journal_id)s AND', '')
where_string += ' AND l10n_latam_document_type_id = %(l10n_latam_document_type_id)s AND ' \
'company_id = %(company_id)s AND move_type IN %(move_type)s'
param['company_id'] = self.company_id.id or False
param['l10n_latam_document_type_id'] = self.l10n_latam_document_type_id.id or 0
param['move_type'] = (('in_invoice', 'in_refund') if
self.l10n_latam_document_type_id._is_doc_type_vendor() else ('out_invoice', 'out_refund'))
return where_string, param
def _get_name_invoice_report(self):
self.ensure_one()
if self.l10n_latam_use_documents and self.company_id.account_fiscal_country_id.code == 'CL':
return 'l10n_cl.report_invoice_document'
return super()._get_name_invoice_report()
def _l10n_cl_get_invoice_totals_for_report(self):
self.ensure_one()
tax_ids_filter = tax_line_id_filter = None
include_sii = self._l10n_cl_include_sii()
if include_sii:
tax_ids_filter = (lambda aml, tax: bool(tax.l10n_cl_sii_code != 14))
tax_line_id_filter = (lambda aml, tax: bool(tax.l10n_cl_sii_code != 14))
tax_lines_data = self._prepare_tax_lines_data_for_totals_from_invoice(
tax_ids_filter=tax_ids_filter, tax_line_id_filter=tax_line_id_filter)
if include_sii:
amount_untaxed = self.currency_id.round(
self.amount_total - sum([x['tax_amount'] for x in tax_lines_data if 'tax_amount' in x]))
else:
amount_untaxed = self.amount_untaxed
return self._get_tax_totals(self.partner_id, tax_lines_data, self.amount_total, amount_untaxed, self.currency_id)
def _l10n_cl_include_sii(self):
self.ensure_one()
return self.l10n_latam_document_type_id.code in ['39', '41', '110', '111', '112', '34']
def _is_manual_document_number(self):
if self.journal_id.company_id.country_id.code == 'CL':
return self.journal_id.type == 'purchase' and not self.l10n_latam_document_type_id._is_doc_type_vendor()
return super()._is_manual_document_number()<|fim▁end|> | if country_id.code != "CL": |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .menu import menu_handlers<|fim▁hole|>from .toolbar import toolbar_handlers
handlers = {}
handlers.update(menu_handlers)
handlers.update(main_handlers)
handlers.update(toolbar_handlers)
__all__ = ['handlers']<|fim▁end|> | from .main import main_handlers |
<|file_name|>board.rs<|end_file_name|><|fim▁begin|>use std::collections::btree_set::BTreeSet;
use std::ops::BitAnd;
use ::{Position, Color, Grid, Axes, Directions, Alignment};
use ::{get_alignments, get_free_threes, get_captures};
use functions::captures_on_alignement::captures_on_axis;
use ::directions::*;
/// Number of stones to take to win.
pub const STONES_COUNT_TO_WIN: usize = 10;
/// The main structure: allow you to play on the `Grid` with Gomoku rules.
#[derive(Debug, Clone)]
pub struct Board {
grid: Grid,
stones_black_takes: usize,
stones_white_takes: usize,
}
/// Indicates the error of placement you get
/// when you missplace a stone on the `Board`.
#[derive(Debug)]
pub enum Error {
TileNotEmpty,
DoubleFreeThrees(Axes<bool>),
}
/// Indicates the victory condition under the one
/// you win by placing a stone on the `Board`.
#[derive(Debug)]
pub enum Condition {
CapturedStones { total: usize, captures: Directions<bool> },
FiveStonesAligned(Axes<Alignment>),
}
/// Gives information on the last successful stone placement on the `Board`.
#[derive(Debug)]
pub enum Info {
Nothing,
Captures(Directions<bool>),
FiveStonesAligned { counteract: Vec<Position> }
}
/// The type returned by the board when placing a stone.
#[derive(Debug)]
pub enum PlaceResult {
Ok(Info),
Victory(Condition),
Err(Error),
}
use self::PlaceResult::*;
impl Board {
/// Returns the default `Board`.
pub fn new() -> Board {
Board {
grid: [[None; ::GRID_LEN]; ::GRID_LEN],
stones_black_takes: 0,
stones_white_takes: 0
}
}
/// Simply puts a stone on the board
pub fn raw_place_stone(&mut self, (x, y): Position, color: Color) {
self.grid[x][y] = Some(color)
}
/// Simply removes a stone from the board
pub fn raw_remove_stone(&mut self, (x, y): Position) {
self.grid[x][y] = None;
}
// TODO another solution ?
fn stones_taken(&self, color: Color) -> usize {
match color {
Color::Black => self.stones_black_takes,
Color::White => self.stones_white_takes,
}
}
fn mut_stones_taken(&mut self, color: Color) -> &mut usize {
match color {
Color::Black => &mut self.stones_black_takes,
Color::White => &mut self.stones_white_takes,
}
}
fn remove_captured_stones(&mut self, (x, y): Position, captures: &Directions<bool>) {
if captures[TOP] {
self.grid[x - 1][y] = None;
self.grid[x - 2][y] = None;
}
if captures[TOP_RIGHT] {
self.grid[x - 1][y + 1] = None;
self.grid[x - 2][y + 2] = None;
}
if captures[RIGHT] {
self.grid[x][y + 1] = None;
self.grid[x][y + 2] = None;
}
if captures[BOT_RIGHT] {
self.grid[x + 1][y + 1] = None;
self.grid[x + 2][y + 2] = None;
}
if captures[BOT] {
self.grid[x + 1][y] = None;
self.grid[x + 2][y] = None;
}
if captures[BOT_LEFT] {
self.grid[x + 1][y - 1] = None;
self.grid[x + 2][y - 2] = None;
}
if captures[LEFT] {
self.grid[x][y - 1] = None;
self.grid[x][y - 2] = None;
}
if captures[TOP_LEFT] {
self.grid[x - 1][y - 1] = None;
self.grid[x - 2][y - 2] = None;
}
}
fn update_captures(&mut self, pos: Position, color: Color, captures: &Directions<bool>) -> usize {
self.remove_captured_stones(pos, captures);
let nb_captures = captures.count(|x| *x);
*self.mut_stones_taken(color) += nb_captures * 2;
nb_captures
}
fn get_all_possible_captures(&self, color: Color) -> Vec<Position> {
let mut captures = Vec::new();
for x in 0..::GRID_LEN {
for y in 0..::GRID_LEN {
let pos = (x, y);
if let None = self.grid[x][y] {
for _ in get_captures(&self.grid, pos, color).iter().filter(|x| **x) {
let aligns = get_alignments(&self.grid, pos, color);
if get_free_threes(&self.grid, pos, color, &aligns).count(|x| *x) != 2 {
captures.push(pos);
}
}
}
}
}
captures
}
fn get_counter_alignments(&self, pos: Position, color: Color, alignments: &Axes<Alignment>) -> BTreeSet<Position> {
alignments.iter().enumerate()
.filter(|&(_, align)| align.len() >= 5)
.fold::<Option<BTreeSet<_>>, _>(None, |acc, (axis, align)| {
let capts = captures_on_axis(&self.grid, pos, color, *align, axis);
match acc {
Some(prev) => Some(prev.bitand(&capts)),
None => Some(capts),
}
}).unwrap()
}
/// Try placing a stone on board respecting rules
pub fn try_place_stone(&mut self, pos: Position, color: Color) -> PlaceResult {
let (x, y) = pos;
if self.grid[x][y].is_some() {
return Err(Error::TileNotEmpty)
}
let alignments = get_alignments(&self.grid, pos, color);
let free_threes = get_free_threes(&self.grid, pos, color, &alignments);
let captures = get_captures(&self.grid, pos, color);
if free_threes.count(|x| *x) == 2 {
Err(Error::DoubleFreeThrees(free_threes))
}
else {
self.raw_place_stone(pos, color);
let stones_taken = self.update_captures(pos, color, &captures);
if alignments.any(|x| x.len() >= 5) {
if self.stones_taken(-color) + 2 == STONES_COUNT_TO_WIN {
let captures = self.get_all_possible_captures(-color);
if !captures.is_empty() {
return Ok(Info::FiveStonesAligned {
counteract: captures
})
}
}
else {
let captures = self.get_counter_alignments(pos, color, &alignments);
if !captures.is_empty() {
return Ok(Info::FiveStonesAligned {
counteract: captures.iter().cloned().collect()
})
}
}
Victory(Condition::FiveStonesAligned(alignments))
}
else if stones_taken > 0 {
if self.stones_taken(color) >= STONES_COUNT_TO_WIN {
Victory(Condition::CapturedStones {
total: self.stones_taken(color),
captures: captures
})
}
else {
Ok(Info::Captures(captures))
}
}
else {
Ok(Info::Nothing)
}
}
}
}
#[cfg(test)]
mod tests {
use test::Bencher;
use color::Color;
use ::{Alignment, BoundState};
use super::{Board, PlaceResult};
use super::{Condition, Error};
use super::Info::*;
#[bench]
fn counteract_alignment_by_breaking(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, w, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[b, b, b, n, b, b, w, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 0,
stones_white_takes: 0,
};
let captures = vec![(0, 1), (3, 2), (3, 3)];
let pos = (1, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Ok(FiveStonesAligned { counteract }) => assert_eq!(counteract, captures),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn counteract_multiple_alignments_by_breaking(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, w, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[b, b, b, n, b, b, w, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 0,
stones_white_takes: 0,
};
let captures = vec![(0, 1), (3, 2)];
let pos = (1, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Ok(FiveStonesAligned { counteract }) => assert_eq!(counteract, captures),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn counteract_alignment_with_last_capture(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[b, b, b, n, b, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, b, b, w],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 0,
stones_white_takes: 8,
};
let captures = vec![(14, 15)];
let pos = (1, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Ok(FiveStonesAligned { counteract }) => assert_eq!(counteract, captures),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn victory_with_captures(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, b, w, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, w, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, w, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, b, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 8,
stones_white_takes: 0,
};
let pos = (2, 5);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Victory(Condition::CapturedStones {
total: 14,
captures
}) => assert_eq!(captures, [false, false, false, false, true, true, true, false].into()),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn placement_do_nothing(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, b, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 8,
stones_white_takes: 8,
};
let pos = (2, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Ok(Nothing) => (),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn placement_do_nothing_but_captures(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, b, w, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, w, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, w, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, b, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 2,
stones_white_takes: 0,
};
let pos = (2, 5);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Ok(Captures(captures)) => assert_eq!(captures, [false, false, false, false, true, true, true, false].into()),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn double_free_threes_cant_counteract_alignment(bencher: &mut Bencher) {
let b = Some(Color::Black);
let w = Some(Color::White);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, w, n, b, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, b, b, n, b, b, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, w, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, w, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 8,
stones_white_takes: 8,
};
let pos = (4, 6);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Victory(Condition::FiveStonesAligned(aligns)) => {
let alignment = Alignment(BoundState::Tile(None), 3, 2, BoundState::Tile(None));
assert_eq!(*aligns.horizontal(), alignment)
},
x => panic!("{:?}", x),
}
});
}
#[bench]
fn cant_place_on_double_free_threes(bencher: &mut Bencher) {
let b = Some(Color::Black);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, b, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {<|fim▁hole|> };
let pos = (4, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Err(Error::DoubleFreeThrees(axes)) => assert_eq!(axes, [true, false, true, false].into()),
x => panic!("{:?}", x),
}
});
}
#[bench]
fn cant_place_on_non_empty_tile(bencher: &mut Bencher) {
let b = Some(Color::Black);
let n = None;
let grid = [[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, b, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, b, b, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n],
[n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n]];
bencher.iter(|| {
let mut board = Board {
grid: grid,
stones_black_takes: 8,
stones_white_takes: 0,
};
let pos = (2, 3);
match board.try_place_stone(pos, Color::Black) {
PlaceResult::Err(Error::TileNotEmpty) => (),
x => panic!("{:?}", x),
}
});
}
}<|fim▁end|> | let mut board = Board {
grid: grid,
stones_black_takes: 8,
stones_white_takes: 0, |
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for uptee project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os<|fim▁hole|>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uptee.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)<|fim▁end|> | |
<|file_name|>GitMaterialShallowCloneTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config.materials.git;
import com.googlecode.junit.ext.JunitExtRunner;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.materials.RevisionContext;
import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext;
import com.thoughtworks.go.domain.materials.git.GitCommand;
import com.thoughtworks.go.domain.materials.git.GitTestRepo;
import com.thoughtworks.go.domain.materials.mercurial.StringRevision;
import com.thoughtworks.go.helper.TestRepo;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TestFileUtil;
import org.hamcrest.Matchers;
import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.thoughtworks.go.domain.materials.git.GitTestRepo.*;
import static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(JunitExtRunner.class)
public class GitMaterialShallowCloneTest {
private GitTestRepo repo;
private File workingDir;
@Before
public void setup() throws Exception {
repo = new GitTestRepo();
workingDir = TestFileUtil.createUniqueTempFolder("working");
}
@After
public void teardown() throws Exception {
TestRepo.internalTearDown();
}
@Test
public void defaultShallowFlagIsOff() throws Exception {
assertThat(new GitMaterial(repo.projectRepositoryUrl()).isShallowClone(), is(false));
assertThat(new GitMaterial(repo.projectRepositoryUrl(), null).isShallowClone(), is(false));
assertThat(new GitMaterial(repo.projectRepositoryUrl(), true).isShallowClone(), is(true));
assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl())).isShallowClone(), is(false));
assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl(), GitMaterialConfig.DEFAULT_BRANCH, true)).isShallowClone(), is(true));
assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl(), GitMaterialConfig.DEFAULT_BRANCH, false)).isShallowClone(), is(false));
TestRepo.internalTearDown();
}
@Test
public void shouldGetLatestModificationWithShallowClone() throws IOException {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
List<Modification> mods = material.latestModification(workingDir, context());
assertThat(mods.size(), is(1));
assertThat(mods.get(0).getComment(), Matchers.is("Added 'run-till-file-exists' ant target"));
assertThat(localRepoFor(material).isShallow(), is(true));
assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_0), is(false));
assertThat(localRepoFor(material).currentRevision(), is(REVISION_4.getRevision()));
}
@Test
public void shouldGetModificationSinceANotInitiallyClonedRevision() {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
List<Modification> modifications = material.modificationsSince(workingDir, REVISION_0, context());
assertThat(modifications.size(), is(4));
assertThat(modifications.get(0).getRevision(), is(REVISION_4.getRevision()));
assertThat(modifications.get(0).getComment(), is("Added 'run-till-file-exists' ant target"));
assertThat(modifications.get(1).getRevision(), is(REVISION_3.getRevision()));
assertThat(modifications.get(1).getComment(), is("adding build.xml"));
assertThat(modifications.get(2).getRevision(), is(REVISION_2.getRevision()));
assertThat(modifications.get(2).getComment(), is("Created second.txt from first.txt"));
assertThat(modifications.get(3).getRevision(), is(REVISION_1.getRevision()));
assertThat(modifications.get(3).getComment(), is("Added second line"));
}
@Test
public void shouldBeAbleToUpdateToRevisionNotFetched() {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(REVISION_3, REVISION_2, 2), context());
assertThat(localRepoFor(material).currentRevision(), is(REVISION_3.getRevision()));
assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_2), is(true));
assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_3), is(true));
}
@Test
public void configShouldIncludesShallowFlag() {
GitMaterialConfig shallowConfig = (GitMaterialConfig) new GitMaterial(repo.projectRepositoryUrl(), true).config();<|fim▁hole|> assertThat(shallowConfig.isShallowClone(), is(true));
GitMaterialConfig normalConfig = (GitMaterialConfig) new GitMaterial(repo.projectRepositoryUrl(), null).config();
assertThat(normalConfig.isShallowClone(), is(false));
}
@Test
public void xmlAttributesShouldIncludesShallowFlag() {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
assertThat(material.getAttributesForXml().get("shallowClone"), Is.<Object>is(true));
}
@Test
public void attributesShouldIncludeShallowFlag() {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
Map gitConfig = (Map) (material.getAttributes(false).get("git-configuration"));
assertThat(gitConfig.get("shallow-clone"), Is.<Object>is(true));
}
@Test
public void shouldConvertExistingRepoToFullRepoWhenShallowCloneIsOff() {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
material.latestModification(workingDir, context());
assertThat(localRepoFor(material).isShallow(), is(true));
material = new GitMaterial(repo.projectRepositoryUrl(), false);
material.latestModification(workingDir, context());
assertThat(localRepoFor(material).isShallow(), is(false));
}
@Test
public void withShallowCloneShouldGenerateANewMaterialWithOverriddenShallowConfig() {
GitMaterial original = new GitMaterial(repo.projectRepositoryUrl(), false);
assertThat(original.withShallowClone(true).isShallowClone(), is(true));
assertThat(original.withShallowClone(false).isShallowClone(), is(false));
assertThat(original.isShallowClone(), is(false));
}
@Test
public void updateToANewRevisionShouldNotResultInUnshallowing() throws IOException {
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(REVISION_4, REVISION_4, 1), context());
assertThat(localRepoFor(material).isShallow(), is(true));
List<Modification> modifications = repo.addFileAndPush("newfile", "add new file");
StringRevision newRevision = new StringRevision(modifications.get(0).getRevision());
material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(newRevision, newRevision, 1), context());
assertThat(new File(workingDir, "newfile").exists(), is(true));
assertThat(localRepoFor(material).isShallow(), is(true));
}
@Test
public void shouldUnshallowServerSideRepoCompletelyOnRetrievingModificationsSincePreviousRevision() {
SystemEnvironment mockSystemEnvironment = mock(SystemEnvironment.class);
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
when(mockSystemEnvironment.get(SystemEnvironment.GO_SERVER_SHALLOW_CLONE)).thenReturn(false);
material.modificationsSince(workingDir, REVISION_4, new TestSubprocessExecutionContext(mockSystemEnvironment, true));
assertThat(localRepoFor(material).isShallow(), is(false));
}
@Test
public void shouldNotUnshallowOnServerSideIfShallowClonePropertyIsOnAndRepoIsAlreadyShallow() {
SystemEnvironment mockSystemEnvironment = mock(SystemEnvironment.class);
GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true);
when(mockSystemEnvironment.get(SystemEnvironment.GO_SERVER_SHALLOW_CLONE)).thenReturn(true);
material.modificationsSince(workingDir, REVISION_4, new TestSubprocessExecutionContext(mockSystemEnvironment, false));
assertThat(localRepoFor(material).isShallow(), is(true));
}
private TestSubprocessExecutionContext context() {
return new TestSubprocessExecutionContext();
}
private GitCommand localRepoFor(GitMaterial material) {
return new GitCommand(material.getFingerprint(), workingDir, GitMaterialConfig.DEFAULT_BRANCH, false, new HashMap<>());
}
}<|fim▁end|> | |
<|file_name|>jeryatri.js<|end_file_name|><|fim▁begin|><|fim▁hole|>showWord(["n. ","branch medikal ki espesyalize nan trete granmoun ki avanse nan laj.<br>"])<|fim▁end|> | |
<|file_name|>profile.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack import profile
class Profile(profile.Profile):
<|fim▁hole|> def __init__(self, region, plugins=None, **kwargs):
super(Profile, self).__init__(plugins=plugins or ['rackspace'])
self.set_region(self.ALL, region)
global_services = ('cloudMetrics', 'cloudMetricsIngest',
'cloudMonitoring', 'rackCDN')
for service in self.get_services():
if service.service_name in global_services:
service.region = None<|fim▁end|> | |
<|file_name|>bernoulli.rs<|end_file_name|><|fim▁begin|>use distribution;
use random;
/// A Bernoulli distribution.
#[derive(Clone, Copy)]
pub struct Bernoulli {
p: f64,
q: f64,
pq: f64,
}
impl Bernoulli {
/// Create a Bernoulli distribution with success probability `p`.
///
/// It should hold that `p > 0` and `p < 1`.
#[inline]
pub fn new(p: f64) -> Bernoulli {
should!(p > 0.0 && p < 1.0);<|fim▁hole|> Bernoulli { p: p, q: 1.0 - p, pq: p * (1.0 - p) }
}
/// Create a Bernoulli distribution with failure probability `q`.
///
/// It should hold that `q > 0` and `q < 1`. This constructor is preferable
/// when `q` is very small.
#[inline]
pub fn with_failure(q: f64) -> Bernoulli {
should!(q > 0.0 && q < 1.0);
Bernoulli { p: 1.0 - q, q: q, pq: (1.0 - q) * q }
}
/// Return the success probability.
#[inline(always)]
pub fn p(&self) -> f64 { self.p }
/// Return the failure probability.
#[inline(always)]
pub fn q(&self) -> f64 { self.q }
}
impl distribution::Distribution for Bernoulli {
type Value = u8;
#[inline]
fn cdf(&self, x: f64) -> f64 {
if x < 0.0 {
0.0
} else if x < 1.0 {
self.q
} else {
1.0
}
}
}
impl distribution::Discrete for Bernoulli {
#[inline]
fn pmf(&self, x: u8) -> f64 {
if x == 0 {
self.q
} else if x == 1 {
self.p
} else {
0.0
}
}
}
impl distribution::Entropy for Bernoulli {
fn entropy(&self) -> f64 {
-self.q * self.q.ln() - self.p * self.p.ln()
}
}
impl distribution::Inverse for Bernoulli {
#[inline]
fn inv_cdf(&self, p: f64) -> u8 {
should!(0.0 <= p && p <= 1.0);
if p <= self.q { 0 } else { 1 }
}
}
impl distribution::Kurtosis for Bernoulli {
#[inline]
fn kurtosis(&self) -> f64 {
(1.0 - 6.0 * self.pq) / (self.pq)
}
}
impl distribution::Mean for Bernoulli {
#[inline]
fn mean(&self) -> f64 { self.p }
}
impl distribution::Median for Bernoulli {
fn median(&self) -> f64 {
use std::cmp::Ordering::*;
match self.p.partial_cmp(&self.q) {
Some(Less) => 0.0,
Some(Equal) => 0.5,
Some(Greater) => 1.0,
None => unreachable!(),
}
}
}
impl distribution::Modes for Bernoulli {
fn modes(&self) -> Vec<u8> {
use std::cmp::Ordering::*;
match self.p.partial_cmp(&self.q) {
Some(Less) => vec![0],
Some(Equal) => vec![0, 1],
Some(Greater) => vec![1],
None => unreachable!(),
}
}
}
impl distribution::Sample for Bernoulli {
#[inline]
fn sample<S>(&self, source: &mut S) -> u8 where S: random::Source {
if source.read::<f64>() < self.q { 0 } else { 1 }
}
}
impl distribution::Skewness for Bernoulli {
#[inline]
fn skewness(&self) -> f64 {
(1.0 - 2.0 * self.p) / (self.pq).sqrt()
}
}
impl distribution::Variance for Bernoulli {
#[inline]
fn variance(&self) -> f64 { self.pq }
}
#[cfg(test)]
mod tests {
use assert;
use prelude::*;
macro_rules! new(
(failure $q:expr) => (Bernoulli::with_failure($q));
($p:expr) => (Bernoulli::new($p));
);
#[test]
fn cdf() {
let d = new!(0.25);
let x = vec![-0.1, 0.0, 0.1, 0.25, 0.5, 1.0, 1.1];
let p = vec![0.0, 0.75, 0.75, 0.75, 0.75, 1.0, 1.0];
assert_eq!(&x.iter().map(|&x| d.cdf(x)).collect::<Vec<_>>(), &p);
}
#[test]
fn pmf() {
let d = new!(0.25);
assert_eq!(&(0..3).map(|x| d.pmf(x)).collect::<Vec<_>>(), &[0.75, 0.25, 0.0]);
}
#[test]
fn entropy() {
let d = vec![new!(0.25), new!(0.5), new!(0.75)];
assert::close(&d.iter().map(|d| d.entropy()).collect::<Vec<_>>(),
&vec![0.5623351446188083, 0.6931471805599453, 0.5623351446188083], 1e-16);
}
#[test]
fn inv_cdf() {
let d = new!(0.25);
let p = vec![0.0, 0.25, 0.5, 0.75, 0.75000000001, 1.0];
let x = vec![0, 0, 0, 0, 1, 1];
assert_eq!(&p.iter().map(|&p| d.inv_cdf(p)).collect::<Vec<_>>(), &x);
}
#[test]
fn kurtosis() {
assert_eq!(new!(0.5).kurtosis(), -2.0);
}
#[test]
fn mean() {
assert_eq!(new!(0.5).mean(), 0.5);
}
#[test]
fn median() {
assert_eq!(new!(0.25).median(), 0.0);
assert_eq!(new!(0.5).median(), 0.5);
assert_eq!(new!(0.75).median(), 1.0);
}
#[test]
fn modes() {
assert_eq!(new!(0.25).modes(), vec![0]);
assert_eq!(new!(0.5).modes(), vec![0, 1]);
assert_eq!(new!(0.75).modes(), vec![1]);
}
#[test]
fn sample() {
assert!(Independent(&new!(0.25), &mut random::default()).take(100)
.fold(0, |a, b| a + b) <= 100);
}
#[test]
fn skewness() {
assert_eq!(new!(0.5).skewness(), 0.0);
}
#[test]
fn variance() {
assert_eq!(new!(0.25).variance(), 0.1875);
}
}<|fim▁end|> | |
<|file_name|>EncryptDatav2.go<|end_file_name|><|fim▁begin|>// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// snippet-start:[kms.go-v2.EncryptData]
package main
import (
"context"
b64 "encoding/base64"
"flag"
"fmt"<|fim▁hole|> "github.com/aws/aws-sdk-go-v2/service/kms"
)
// KMSEncryptAPI defines the interface for the Encrypt function.
// We use this interface to test the function using a mocked service.
type KMSEncryptAPI interface {
Encrypt(ctx context.Context,
params *kms.EncryptInput,
optFns ...func(*kms.Options)) (*kms.EncryptOutput, error)
}
// EncryptText encrypts some text using an AWS Key Management Service (AWS KMS) key (KMS key).
// Inputs:
// c is the context of the method call, which includes the AWS Region.
// api is the interface that defines the method call.
// input defines the input arguments to the service call.
// Output:
// If success, an EncryptOutput object containing the result of the service call and nil.
// Otherwise, nil and an error from the call to Encrypt.
func EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) {
return api.Encrypt(c, input)
}
func main() {
keyID := flag.String("k", "", "The ID of a KMS key")
text := flag.String("t", "", "The text to encrypt")
flag.Parse()
if *keyID == "" || *text == "" {
fmt.Println("You must supply the ID of a KMS key and some text")
fmt.Println("-k KEY-ID -t \"text\"")
return
}
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic("configuration error, " + err.Error())
}
client := kms.NewFromConfig(cfg)
input := &kms.EncryptInput{
KeyId: keyID,
Plaintext: []byte(*text),
}
result, err := EncryptText(context.TODO(), client, input)
if err != nil {
fmt.Println("Got error encrypting data:")
fmt.Println(err)
return
}
blobString := b64.StdEncoding.EncodeToString(result.CiphertextBlob)
fmt.Println(blobString)
}
// snippet-end:[kms.go-v2.EncryptData]<|fim▁end|> |
"github.com/aws/aws-sdk-go-v2/config" |
<|file_name|>renderers.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from collections import OrderedDict
import logging
import re
import sys
import json
from django.conf import settings
from django.utils.encoding import smart_text
from contrib import drf_introspection
from django.db.models.fields import NOT_PROVIDED
from django.core.urlresolvers import NoReverseMatch
from django.core.exceptions import FieldDoesNotExist
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.utils import formatting
from rest_framework.reverse import reverse
from rest_framework import serializers, relations, fields
from pdc.apps.utils.utils import urldecode
"""
## Writing documentation in docstrings
Docstrings of each method will be available in browsable API as documentation.
These features are available to simplify writing the comments:
* the content is formatted as Markdown
* %(HOST_NAME)s and %(API_ROOT)s macros will be replaced by host name and URL
fragment for API, respectively
* %(FILTERS)s will be replaced a by a list of available query string filters
* %(SERIALIZER)s will be replaced by a code block with details about
serializer
* %(WRITABLE_SERIALIZER)s will do the same, but without read-only fields
* $URL:route-name:arg1:arg2...$ will be replaced by absolute URL
* $LINK:route-name:arg1:...$ will be replaced by a clickable link with
relative URL pointing to the specified place; arguments for LINK will be
wrapped in braces automatically
When the URL specification can not be resolve, "BAD URL" will be displayed on
the page and details about the error will be logged to the error log.
"""
PDC_APIROOT_DOC = """
The REST APIs make it possible to programmatic access the data in Product Definition Center(a.k.a. PDC).
Create new Product, import rpms and query components with contact informations, and more.
The REST API identifies users using Token which will be generated for all authenticated users.
**Please remember to use your token as HTTP header for every requests that need authentication.**
If you want to record the reason for change, you can add Header (-H "PDC-Change-Comment: reasonforchange") in request.
Responses are available in JSON format.
**NOTE:** in order to use secure HTTPS connections, you'd better to add server's certificate as trusted.
"""
URL_SPEC_RE = re.compile(r'\$(?P<type>URL|LINK):(?P<details>[^$]+)\$')
class ReadOnlyBrowsableAPIRenderer(BrowsableAPIRenderer):
template = "browsable_api/api.html"
methods_mapping = (
'list',
'retrieve',
'create',
'bulk_create',
'update',
'destroy',
'bulk_destroy',
'partial_update',
<|fim▁hole|> 'obtain',
'refresh',
)
def get_raw_data_form(self, data, view, method, request):
return None
def get_rendered_html_form(self, data, view, method, request):
return None
def get_context(self, data, accepted_media_type, renderer_context):
self.request = renderer_context['request']
super_class = super(ReadOnlyBrowsableAPIRenderer, self)
super_retval = super_class.get_context(data, accepted_media_type,
renderer_context)
if super_retval is not None:
del super_retval['put_form']
del super_retval['post_form']
del super_retval['delete_form']
del super_retval['options_form']
del super_retval['raw_data_put_form']
del super_retval['raw_data_post_form']
del super_retval['raw_data_patch_form']
del super_retval['raw_data_put_or_patch_form']
super_retval['display_edit_forms'] = False
super_retval['version'] = "1.0"
view = renderer_context['view']
super_retval['overview'] = self.get_overview(view)
return super_retval
def get_overview(self, view):
if view.__class__.__name__ == 'APIRoot':
return self.format_docstring(None, None, PDC_APIROOT_DOC)
overview = view.__doc__ or ''
return self.format_docstring(view, '<overview>', overview)
def get_description(self, view, *args):
if view.__class__.__name__ == 'APIRoot':
return ''
description = OrderedDict()
for method in self.methods_mapping:
func = getattr(view, method, None)
docstring = func and func.__doc__ or ''
if docstring:
description[method] = self.format_docstring(view, method, docstring)
return description
def format_docstring(self, view, method, docstring):
macros = settings.BROWSABLE_DOCUMENT_MACROS
if view:
macros['FILTERS'] = get_filters(view)
if '%(SERIALIZER)s' in docstring:
macros['SERIALIZER'] = get_serializer(view, include_read_only=True)
if '%(WRITABLE_SERIALIZER)s' in docstring:
macros['WRITABLE_SERIALIZER'] = get_serializer(view, include_read_only=False)
if hasattr(view, 'docstring_macros'):
macros.update(view.docstring_macros)
string = formatting.dedent(docstring)
formatted = string % macros
formatted = self.substitute_urls(view, method, formatted)
string = smart_text(formatted)
return formatting.markup_description(string)
def substitute_urls(self, view, method, text):
def replace_url(match):
type = match.groupdict()['type']
parts = match.groupdict()['details'].split(':')
url_name = parts[0]
args = parts[1:]
if type == 'LINK':
args = ['{%s}' % arg for arg in args]
try:
if type == 'LINK':
url = reverse(url_name, args=args)
return '[`%s`](%s)' % (urldecode(url), url)
return reverse(url_name, args=args, request=self.request)
except NoReverseMatch:
logger = logging.getLogger(__name__)
logger.error('Bad URL specifier <%s> in %s.%s'
% (match.group(0), view.__class__.__name__, method),
exc_info=sys.exc_info())
return 'BAD URL'
return URL_SPEC_RE.sub(replace_url, text)
FILTERS_CACHE = {}
FILTER_DEFS = {
'CharFilter': 'string',
'NullableCharFilter': 'string | null',
'BooleanFilter': 'bool',
'CaseInsensitiveBooleanFilter': 'bool',
'ActiveReleasesFilter': 'bool',
'MultiIntFilter': 'int',
}
LOOKUP_TYPES = {
'icontains': 'case insensitive, substring match',
'contains': 'substring match',
'iexact': 'case insensitive',
}
def get_filters(view):
"""
For a given view set returns which query filters are available for it a
Markdown formatted list. The list does not include query filters specified
on serializer or query arguments used for paging.
"""
if view in FILTERS_CACHE:
return FILTERS_CACHE[view]
allowed_keys = drf_introspection.get_allowed_query_params(view)
filter_class = getattr(view, 'filter_class', None)
filterset = filter_class() if filter_class is not None else None
filterset_fields = filterset.filters if filterset is not None else []
filter_fields = set(getattr(view, 'filter_fields', []))
extra_query_params = set(getattr(view, 'extra_query_params', []))
filters = []
for key in sorted(allowed_keys):
if key in filterset_fields:
# filter defined in FilterSet
filter = filterset_fields.get(key)
filter_type = FILTER_DEFS.get(filter.__class__.__name__, 'string')
lookup_type = LOOKUP_TYPES.get(filter.lookup_type)
if lookup_type:
lookup_type = ', %s' % lookup_type
filters.append(' * `%s` (%s%s)' % (key, filter_type, lookup_type or ''))
elif key in filter_fields or key in extra_query_params:
# filter defined in viewset directly; type depends on model, not easily available
filters.append(' * `%s`' % key)
# else filter defined somewhere else and not relevant here (e.g.
# serializer or pagination settings).
filters = '\n'.join(filters)
FILTERS_CACHE[view] = filters
return filters
SERIALIZERS_CACHE = {}
SERIALIZER_DEFS = {
'BooleanField': 'boolean',
'NullBooleanField': 'boolean',
'CharField': 'string',
'IntegerField': 'int',
'HyperlinkedIdentityField': 'url',
'DateTimeField': 'datetime',
'DateField': 'date',
'StringRelatedField': 'string',
'ReadOnlyField': 'data',
'EmailField': 'email address',
'SlugField': 'string',
'URLField': 'url',
}
def _get_type_from_str(str, default=None):
"""
Convert docstring into object suitable for inclusion as documentation. It
tries to parse the docstring as JSON, falling back on provided default
value.
"""
if str:
try:
return json.loads(str)
except ValueError:
pass
return default if default is not None else str
def _get_details_for_slug(serializer, field_name, field):
"""
For slug field, we ideally want to get Model.field format. However, in some
cases getting the model name is not possible, and only field name is
displayed.
"""
model = ''
if hasattr(field, 'queryset') and field.queryset:
model = field.queryset.model.__name__ + '.'
return '%s%s' % (model, field.slug_field)
def get_field_type(serializer, field_name, field, include_read_only):
"""
Try to describe a field type.
"""
if isinstance(field, (relations.ManyRelatedField, serializers.ListSerializer)):
# Many field, recurse on child and make it a list
if isinstance(field, relations.ManyRelatedField):
field = field.child_relation
else:
field = field.child
return [get_field_type(serializer, field_name, field, include_read_only)]
if field.__class__.__name__ in SERIALIZER_DEFS:
return SERIALIZER_DEFS[field.__class__.__name__]
elif isinstance(field, serializers.SlugRelatedField):
return _get_details_for_slug(serializer, field_name, field)
elif isinstance(field, serializers.SerializerMethodField):
# For method fields try to use docstring of the method.
method_name = field.method_name or 'get_{field_name}'.format(field_name=field_name)
method = getattr(serializer, method_name, None)
if method:
docstring = getattr(method, '__doc__')
return _get_type_from_str(docstring, docstring or 'method')
elif not include_read_only and hasattr(field, 'writable_doc_format'):
return _get_type_from_str(field.writable_doc_format)
elif hasattr(field, 'doc_format'):
return _get_type_from_str(field.doc_format)
elif isinstance(field, serializers.BaseSerializer):
return describe_serializer(field, include_read_only)
logger = logging.getLogger(__name__)
logger.error('Undocumented field %s' % field)
return 'UNKNOWN'
def get_default_value(serializer, field_name, field):
"""
Try to get default value for a field and format it nicely.
"""
value = field.default
if hasattr(value, 'doc_format'):
return (value.doc_format
if isinstance(value.doc_format, basestring)
else str(value.doc_format))
if value == fields.empty:
# Try to get default from model field.
try:
default = serializer.Meta.model._meta.get_field(field_name).default
return default if default != NOT_PROVIDED else None
except (FieldDoesNotExist, AttributeError):
return None
return value
def describe_serializer(serializer, include_read_only):
"""
Try to get description of a serializer. It tries to inspect all fields
separately, if the serializer does not have fields, it falls back to
`doc_format` class attribute (if present). If all fails, an error is
logged.
"""
data = {}
if hasattr(serializer, 'get_fields'):
for field_name, field in serializer.get_fields().iteritems():
notes = []
if field.read_only:
notes.append('read-only')
if not include_read_only:
continue
elif not field.required:
notes.append('optional')
default = json.dumps(get_default_value(serializer, field_name, field))
if not (default is None and field.allow_null):
notes.append('default=%s' % default)
if field.allow_null:
notes.append('nullable')
notes = ' (%s)' % ', '.join(notes) if notes else ''
data[field_name + notes] = get_field_type(serializer, field_name, field, include_read_only)
return data
elif hasattr(serializer.__class__, 'doc_format'):
return serializer.doc_format
else:
logger = logging.getLogger(__name__)
logger.error('Failed to get details for serializer %s' % serializer)
return 'data'
def get_serializer(view, include_read_only):
"""
For given view, return a Markdown code block with JSON description of the
serializer. If `include_read_only` is `False`, only writable fields will be
included.
"""
if (view, include_read_only) in SERIALIZERS_CACHE:
return SERIALIZERS_CACHE[(view, include_read_only)]
if not hasattr(view, 'get_serializer'):
return None
try:
serializer = view.get_serializer()
desc = json.dumps(describe_serializer(serializer, include_read_only),
indent=4, sort_keys=True)
doc = '\n'.join(' %s' % line for line in desc.split('\n'))
except AssertionError:
# Even when `get_serializer` is present, it may raise exception.
doc = None
SERIALIZERS_CACHE[(view, include_read_only)] = doc
return doc<|fim▁end|> | 'bulk_update',
# Token Auth methods |
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>from textwrap import dedent
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemapView(TestCase):
def setUp(self):
data = [
{
'path': '/firefox/all/',
'locale': 'de',
'lastmod': '2020-07-01T21:07:08.730133+00:00'
},
{
'path': '/firefox/',
'locale': 'de',
'lastmod': '2020-07-01T21:07:08.730133+00:00'
},
{
'path': '/privacy/',
'locale': 'fr',
},
{
'path': '/firefox/',
'locale': 'fr',
'lastmod': '2020-07-01T21:07:08.730133+00:00'
},
{
'path': '/keymaster/gatekeeper/there.is.only.xul',
'locale': NO_LOCALE,
'lastmod': '2020-07-01T21:07:08.730133+00:00'
},
{
'path': '/locales/',
'locale': NO_LOCALE,
},
]
SitemapURL.objects.bulk_create(SitemapURL(**kw) for kw in data)
def test_index(self):
good_resp = dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<sitemap>
<loc>https://www.mozilla.org/sitemap_none.xml</loc>
</sitemap>
<sitemap>
<loc>https://www.mozilla.org/de/sitemap.xml</loc>
</sitemap>
<sitemap>
<loc>https://www.mozilla.org/fr/sitemap.xml</loc>
</sitemap>
</sitemapindex>""")
resp = self.client.get('/sitemap.xml')
assert resp.content.decode() == good_resp
def test_none(self):
good_resp = dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul</loc>
<lastmod>2020-07-01T21:07:08.730133+00:00</lastmod>
</url>
<url>
<loc>https://www.mozilla.org/locales/</loc>
</url>
</urlset>""")
resp = self.client.get('/sitemap_none.xml')
assert resp.content.decode() == good_resp
def test_locales(self):
good_resp = dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://www.mozilla.org/de/firefox/</loc>
<lastmod>2020-07-01T21:07:08.730133+00:00</lastmod>
</url>
<url>
<loc>https://www.mozilla.org/de/firefox/all/</loc>
<lastmod>2020-07-01T21:07:08.730133+00:00</lastmod>
</url>
</urlset>""")
resp = self.client.get('/de/sitemap.xml')
assert resp.content.decode() == good_resp
<|fim▁hole|> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://www.mozilla.org/fr/firefox/</loc>
<lastmod>2020-07-01T21:07:08.730133+00:00</lastmod>
</url>
<url>
<loc>https://www.mozilla.org/fr/privacy/</loc>
</url>
</urlset>""")
resp = self.client.get('/fr/sitemap.xml')
assert resp.content.decode() == good_resp<|fim▁end|> | good_resp = dedent("""\
<?xml version="1.0" encoding="UTF-8"?> |
<|file_name|>sitemaps.py<|end_file_name|><|fim▁begin|>from django.contrib.sitemaps import Sitemap
from events.models import Event
class EventsSitemap(Sitemap):
changefreq = "never"
priority = 1.0
def items(self):
return Event.objects.public()<|fim▁hole|> def lastmod(self, obj):
return obj.date_modified<|fim▁end|> | |
<|file_name|>handler.go<|end_file_name|><|fim▁begin|>package synapse
import (
"fmt"
)
// Handler is the interface used
// to register server response callbacks.
type Handler interface {
// ServeCall handles a synapse request and<|fim▁hole|> // become invalid after the call is returned;
// no implementation of ServeCall should
// maintain a reference to either object
// after the function returns.
ServeCall(req Request, res ResponseWriter)
}
// Status represents
// a response status code
type Status int
// These are the status
// codes that can be passed
// to a ResponseWriter as
// an error to send to the
// client.
const (
StatusInvalid Status = iota // zero-value for Status
StatusOK // OK
StatusNotFound // no handler for the request method
StatusCondition // precondition failure
StatusBadRequest // mal-formed request
StatusNotAuthed // not authorized
StatusServerError // server-side error
StatusOther // other error
)
// ResponseError is the type of error
// returned by the client when the
// server sends a response with
// ResponseWriter.Error()
type ResponseError struct {
Code Status
Expl string
}
// Error implements error
func (e *ResponseError) Error() string {
return fmt.Sprintf("synapse: response error (%s): %s", e.Code, e.Expl)
}
// String returns the string representation of the status
func (s Status) String() string {
switch s {
case StatusOK:
return "OK"
case StatusNotFound:
return "not found"
case StatusCondition:
return "precondition failed"
case StatusBadRequest:
return "bad request"
case StatusNotAuthed:
return "not authorized"
case StatusServerError:
return "server error"
case StatusOther:
return "other"
default:
return fmt.Sprintf("Status(%d)", s)
}
}<|fim▁end|> | // writes a response. It should be safe to
// call ServeCall from multiple goroutines.
// Both the request and response interfaces |
<|file_name|>all.ts<|end_file_name|><|fim▁begin|>import { times, flatten } from "lodash"
import { APIOptions } from "./loaders/api"
// TODO: Type this and refactor, because I think things just kinda work by luck,
// because a static and a dynamic path loader take different number of
// arguments.
export const MAX_GRAPHQL_INT = 2147483647
export const allViaLoader = (
loader,
options: {
// For dynamic path loaders
path?: string | { [key: string]: any }
params?: { [key: string]: any }
api?: APIOptions
} = {}
) => {
const params = options.params ? { size: 25, ...options.params } : { size: 25 }
const invokeLoader = invocationParams =>
options.path<|fim▁hole|> const countParams = {
...params,
page: 1,
size: 0,
total_count: true,
}
return invokeLoader(countParams)
.then(({ headers }) => {
const count = parseInt(headers["x-total-count"] || "0", 10)
const pages = Math.ceil(count / params.size)
return Promise.all(
times(pages, i => {
const pageParams = { ...params, page: i + 1 }
return invokeLoader(pageParams).then(({ body }) => body)
})
)
})
.then(flatten)
}<|fim▁end|> | ? loader(options.path, invocationParams, options.api)
: loader(invocationParams, options.api) |
<|file_name|>PrefixReferenceProvider.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2007 Sascha Weinreuter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.relaxNG.references;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.LocalQuickFixProvider;
import com.intellij.codeInspection.XmlQuickFixFactory;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.BasicAttributeValueReference;
import com.intellij.psi.impl.source.xml.SchemaPrefix;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 24.07.2007
*/
public class PrefixReferenceProvider extends PsiReferenceProvider
{
private static final Logger LOG = Logger.getInstance("#org.intellij.plugins.relaxNG.references.PrefixReferenceProvider");
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context)
{
final XmlAttributeValue value = (XmlAttributeValue) element;
final String s = value.getValue();
final int i = s.indexOf(':');
if(i <= 0 || s.startsWith("xml:"))
{
return PsiReference.EMPTY_ARRAY;
}
return new PsiReference[]{
new PrefixReference(value, i)
};
}
private static class PrefixReference extends BasicAttributeValueReference implements EmptyResolveMessageProvider, LocalQuickFixProvider
{
public PrefixReference(XmlAttributeValue value, int length)
{
super(value, TextRange.from(1, length));
}
@Override
@Nullable
public PsiElement resolve()
{
final String prefix = getCanonicalText();
XmlTag tag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class);
while(tag != null)
{
if(tag.getLocalNamespaceDeclarations().containsKey(prefix))
{
final XmlAttribute attribute = tag.getAttribute("xmlns:" + prefix, "");
final TextRange textRange = TextRange.from("xmlns:".length(), prefix.length());
return new SchemaPrefix(attribute, textRange, prefix);
}
tag = tag.getParentTag();
}
return null;
}
@Override
public boolean isReferenceTo(PsiElement element)
{
if(element instanceof SchemaPrefix && element.getContainingFile() == myElement.getContainingFile())
{
final PsiElement e = resolve();
if(e instanceof SchemaPrefix)
{<|fim▁hole|> }
return super.isReferenceTo(element);
}
@Nullable
@Override
public LocalQuickFix[] getQuickFixes()
{
final PsiElement element = getElement();
final XmlElementFactory factory = XmlElementFactory.getInstance(element.getProject());
final String value = ((XmlAttributeValue) element).getValue();
final String[] name = value.split(":");
final XmlTag tag = factory.createTagFromText("<" + (name.length > 1 ? name[1] : value) + " />", XMLLanguage.INSTANCE);
return new LocalQuickFix[]{XmlQuickFixFactory.getInstance().createNSDeclarationIntentionFix(tag, getCanonicalText(), null)};
}
@Override
@NotNull
public Object[] getVariants()
{
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@Override
public boolean isSoft()
{
return false;
}
@Override
@NotNull
public String getUnresolvedMessagePattern()
{
return "Undefined namespace prefix ''{0}''";
}
}
}<|fim▁end|> | final String s = ((SchemaPrefix) e).getName();
return s != null && s.equals(((SchemaPrefix) element).getName());
} |
<|file_name|>kcoingui.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "kcoingui.h"
#include "kcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "init.h"
#include "ui_interface.h"
#include "util.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION < 0x050000
#include <QTextDocument>
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const QString KcoinGUI::DEFAULT_WALLET = "~Default";
KcoinGUI::KcoinGUI(const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelEncryptionIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
quitAction(0),
sendCoinsAction(0),
sendCoinsMenuAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
aboutAction(0),
receiveCoinsAction(0),
receiveCoinsMenuAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
trayIcon(0),
trayIconMenu(0),
notificator(0),
rpcConsole(0),
prevBlocks(0),
spinnerFrame(0),
platformStyle(platformStyle)
{
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("Kcoin Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if(enableWallet)
{
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon());
setWindowIcon(networkStyle->getTrayAndWindowIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
// This property is not implemented in Qt 5. Setting it has no effect.
// A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
setUnifiedTitleAndToolBarOnMac(true);
#endif
rpcConsole = new RPCConsole(platformStyle, 0);
#ifdef ENABLE_WALLET
if(enableWallet)
{
/** Create wallet frame and make it the central widget */
walletFrame = new WalletFrame(platformStyle, this);
setCentralWidget(walletFrame);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Disable size grip because it looks ugly and nobody needs it
statusBar()->setSizeGripEnabled(false);
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
if(enableWallet)
{
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
}
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
}
KcoinGUI::~KcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
delete rpcConsole;
}
void KcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(platformStyle->SingleColorIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Kcoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/send"), sendCoinsAction->text(), this);
sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());
sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());
receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and kcoin: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/receiving_addresses"), receiveCoinsAction->text(), this);
receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());
receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());
historyAction = new QAction(platformStyle->SingleColorIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
#ifdef ENABLE_WALLET
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
#endif // ENABLE_WALLET
quitAction = new QAction(platformStyle->TextColorIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&About Kcoin Core"), this);
aboutAction->setStatusTip(tr("Show information about Kcoin Core"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(platformStyle->TextColorIcon(":/icons/about_qt"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(platformStyle->TextColorIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Kcoin Core"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(platformStyle->TextColorIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Kcoin addresses to prove you own them"));
verifyMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/verify"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Kcoin addresses"));
openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
openAction = new QAction(platformStyle->TextColorIcon(":/icons/open"), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a kcoin: URI or payment request"));
showHelpMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/info"), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the Kcoin Core help message to get a list with possible Kcoin command-line options"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
if(walletFrame)
{
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
}
#endif // ENABLE_WALLET
}
void KcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
if(walletFrame)
{
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
if(walletFrame)
{
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
if(walletFrame)
{
help->addAction(openRPCConsoleAction);
}
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void KcoinGUI::createToolBars()
{
if(walletFrame)
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setMovable(false);
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
overviewAction->setChecked(true);
}
}
void KcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getLastBlockDate());
connect(clientModel, SIGNAL(numBlocksChanged(int,QDateTime)), this, SLOT(setNumBlocks(int,QDateTime)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
rpcConsole->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if(trayIconMenu)
{
// Disable context menu on tray icon
trayIconMenu->clear();
}
}
}
#ifdef ENABLE_WALLET
bool KcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
if(!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool KcoinGUI::setCurrentWallet(const QString& name)
{
if(!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void KcoinGUI::removeAllWallets()
{
if(!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void KcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
sendCoinsMenuAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
receiveCoinsMenuAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void KcoinGUI::createTrayIcon(const NetworkStyle *networkStyle)
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("Kcoin Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getTrayAndWindowIcon());
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void KcoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsMenuAction);
trayIconMenu->addAction(receiveCoinsMenuAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void KcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void KcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void KcoinGUI::aboutClicked()
{
if(!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void KcoinGUI::showHelpMessageClicked()
{
HelpMessageDialog *help = new HelpMessageDialog(this, false);
help->setAttribute(Qt::WA_DeleteOnClose);
help->show();
}
#ifdef ENABLE_WALLET
void KcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if(dlg.exec())
{
Q_EMIT receivedURI(dlg.getURI());
}
}
void KcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void KcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void KcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void KcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void KcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void KcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
#endif // ENABLE_WALLET
void KcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Kcoin network", "", count));
}
void KcoinGUI::setNumBlocks(int count, const QDateTime& blockDate)
{
if(!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime currentDate = QDateTime::currentDateTime();
qint64 secs = blockDate.secsTo(currentDate);
tooltip = tr("Processed %n block(s) of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
#ifdef ENABLE_WALLET
if(walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60*60;
const int DAY_IN_SECONDS = 24*60*60;
const int WEEK_IN_SECONDS = 7*24*60*60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if(secs < 2*DAY_IN_SECONDS)
{
timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
}
else if(secs < 2*WEEK_IN_SECONDS)
{
timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS);
}
else if(secs < YEAR_IN_SECONDS)
{
timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS);
}
else
{
qint64 years = secs / YEAR_IN_SECONDS;
qint64 remainder = secs % YEAR_IN_SECONDS;
timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if(count != prevBlocks)
{
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(
":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if(walletFrame)
walletFrame->showOutOfSyncWarning(true);
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void KcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Kcoin"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
}
else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Kcoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);<|fim▁hole|>
void KcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void KcoinGUI::closeEvent(QCloseEvent *event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(clientModel && clientModel->getOptionsModel())
{
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
// close rpcConsole in case it was open to make some space for the shutdown window
rpcConsole->close();
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
#ifdef ENABLE_WALLET
void KcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label)
{
// On new transaction, make an info balloon
QString msg = tr("Date: %1\n").arg(date) +
tr("Amount: %1\n").arg(KcoinUnits::formatWithUnit(unit, amount, true)) +
tr("Type: %1\n").arg(type);
if (!label.isEmpty())
msg += tr("Label: %1\n").arg(label);
else if (!address.isEmpty())
msg += tr("Address: %1\n").arg(address);
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
msg, CClientUIInterface::MSG_INFORMATION);
}
#endif // ENABLE_WALLET
void KcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void KcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
Q_FOREACH(const QUrl &uri, event->mimeData()->urls())
{
Q_EMIT receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool KcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
bool KcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient))
{
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void KcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void KcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if(!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void KcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void KcoinGUI::detectShutdown()
{
if (ShutdownRequested())
{
if(rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void KcoinGUI::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
static bool ThreadSafeMessageBox(KcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void KcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
void KcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :
optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
QList<KcoinUnits::Unit> units = KcoinUnits::availableUnits();
int max_width = 0;
const QFontMetrics fm(font());
Q_FOREACH (const KcoinUnits::Unit unit, units)
{
max_width = qMax(max_width, fm.width(KcoinUnits::name(unit)));
}
setMinimumSize(max_width, 0);
setAlignment(Qt::AlignRight | Qt::AlignVCenter);
setStyleSheet(QString("QLabel { color : %1 }").arg(platformStyle->SingleColor().name()));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu();
Q_FOREACH(KcoinUnits::Unit u, KcoinUnits::availableUnits())
{
QAction *menuAction = new QAction(QString(KcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *optionsModel)
{
if (optionsModel)
{
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
setText(KcoinUnits::name(newUnits));
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action)
{
optionsModel->setDisplayUnit(action->data());
}
}<|fim▁end|> | } |
<|file_name|>deref-non-pointer.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
match *1 { //~ ERROR: cannot be dereferenced
_ => { panic!(); }
}
}<|fim▁end|> | // |
<|file_name|>ee_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""Test for the ee.__init__ file."""
import six
import unittest
import ee
from ee import apitestcase
class EETestCase(apitestcase.ApiTestCase):
def setUp(self):
ee.Reset()
def testInitialization(self):
"""Verifies library initialization."""
def MockSend(path, params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {}
else:
raise Exception('Unexpected API call to %s with %s' % (path, params))
ee.data.send_ = MockSend
# Verify that the base state is uninitialized.
self.assertFalse(ee.data._initialized)
self.assertEqual(ee.data._api_base_url, None)
self.assertEqual(ee.ApiFunction._api, None)
self.assertFalse(ee.Image._initialized)
# Verify that ee.Initialize() sets the URL and initializes classes.
ee.Initialize(None, 'foo')
self.assertTrue(ee.data._initialized)
self.assertEqual(ee.data._api_base_url, 'foo/api')
self.assertEqual(ee.ApiFunction._api, {})
self.assertTrue(ee.Image._initialized)
# Verify that ee.Initialize(None) does not override custom URLs.
ee.Initialize(None)
self.assertTrue(ee.data._initialized)
self.assertEqual(ee.data._api_base_url, 'foo/api')
# Verify that ee.Reset() reverts everything to the base state.
ee.Reset()
self.assertFalse(ee.data._initialized)
self.assertEqual(ee.data._api_base_url, None)
self.assertEqual(ee.ApiFunction._api, None)
self.assertFalse(ee.Image._initialized)
def testCallAndApply(self):
"""Verifies library initialization."""
# Use a custom set of known functions.
def MockSend(path, params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {
'fakeFunction': {
'type': 'Algorithm',
'args': [
{'name': 'image1', 'type': 'Image'},
{'name': 'image2', 'type': 'Image'}
],
'returns': 'Image'
},
'Image.constant': apitestcase.BUILTIN_FUNCTIONS['Image.constant']
}
else:
raise Exception('Unexpected API call to %s with %s' % (path, params))
ee.data.send_ = MockSend
ee.Initialize(None)
image1 = ee.Image(1)
image2 = ee.Image(2)
expected = ee.Image(ee.ComputedObject(
ee.ApiFunction.lookup('fakeFunction'),
{'image1': image1, 'image2': image2}))
applied_with_images = ee.apply(
'fakeFunction', {'image1': image1, 'image2': image2})
self.assertEqual(expected, applied_with_images)
applied_with_numbers = ee.apply('fakeFunction', {'image1': 1, 'image2': 2})
self.assertEqual(expected, applied_with_numbers)
called_with_numbers = ee.call('fakeFunction', 1, 2)
self.assertEqual(expected, called_with_numbers)
# Test call and apply() with a custom function.
sig = {'returns': 'Image', 'args': [{'name': 'foo', 'type': 'Image'}]}
func = ee.CustomFunction(sig, lambda foo: ee.call('fakeFunction', 42, foo))
expected_custom_function_call = ee.Image(
ee.ComputedObject(func, {'foo': ee.Image(13)}))
self.assertEqual(expected_custom_function_call, ee.call(func, 13))
self.assertEqual(expected_custom_function_call, ee.apply(func, {'foo': 13}))
# Test None promotion.
called_with_null = ee.call('fakeFunction', None, 1)
self.assertEqual(None, called_with_null.args['image1'])
def testDynamicClasses(self):
"""Verifies dynamic class initialization."""
# Use a custom set of known functions.
def MockSend(path, unused_params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {
'Array': {
'type': 'Algorithm',
'args': [
{
'name': 'values',
'type': 'Serializable',
'description': ''
}
],
'description': '',
'returns': 'Array'
},
'Array.cos': {
'type': 'Algorithm',
'args': [
{
'type': 'Array',
'description': '',
'name': 'input'
}
],
'description': '',
'returns': 'Array'
},
'Kernel.circle': {
'returns': 'Kernel',
'args': [
{
'type': 'float',
'description': '',
'name': 'radius',
},
{
'default': 1.0,
'type': 'float',
'optional': True,
'description': '',
'name': 'scale'
},
{
'default': True,
'type': 'boolean',
'optional': True,
'description': '',
'name': 'normalize'
}
],
'type': 'Algorithm',
'description': ''
},
'Reducer.mean': {
'returns': 'Reducer',
'args': []
},
'fakeFunction': {
'returns': 'Array',
'args': [
{
'type': 'Reducer',
'description': '',
'name': 'kernel',
}
]
}
}
ee.data.send_ = MockSend
ee.Initialize(None)
# Verify that the expected classes got generated.
self.assertTrue(hasattr(ee, 'Array'))
self.assertTrue(hasattr(ee, 'Kernel'))
self.assertTrue(hasattr(ee.Array, 'cos'))
self.assertTrue(hasattr(ee.Kernel, 'circle'))
# Try out the constructors.
kernel = ee.ApiFunction('Kernel.circle').call(1, 2)
self.assertEqual(kernel, ee.Kernel.circle(1, 2))
array = ee.ApiFunction('Array').call([1, 2])
self.assertEqual(array, ee.Array([1, 2]))
self.assertEqual(array, ee.Array(ee.Array([1, 2])))
# Try out the member function.
self.assertEqual(
ee.ApiFunction('Array.cos').call(array),
ee.Array([1, 2]).cos())
# Test argument promotion.
f1 = ee.ApiFunction('Array.cos').call([1, 2])
f2 = ee.ApiFunction('Array.cos').call(ee.Array([1, 2]))
self.assertEqual(f1, f2)
self.assertTrue(isinstance(f1, ee.Array))
f3 = ee.call('fakeFunction', 'mean')
f4 = ee.call('fakeFunction', ee.Reducer.mean())
self.assertEqual(f3, f4)
try:
ee.call('fakeFunction', 'moo')
self.fail()
except ee.EEException as e:
self.assertTrue('Unknown algorithm: Reducer.moo' in str(e))
def testDynamicConstructor(self):
# Test the behavior of the dynamic class constructor.
# Use a custom set of known functions for classes Foo and Bar.
# Foo Foo(arg1, [arg2])
# Bar Foo.makeBar()
# Bar Foo.takeBar(Bar bar)
# Baz Foo.baz()
def MockSend(path, unused_params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {
'Foo': {
'returns': 'Foo',
'args': [
{'name': 'arg1', 'type': 'Object'},
{'name': 'arg2', 'type': 'Object', 'optional': True}
]
},
'Foo.makeBar': {
'returns': 'Bar',
'args': [{'name': 'foo', 'type': 'Foo'}]
},
'Foo.takeBar': {
'returns': 'Bar',
'args': [
{'name': 'foo', 'type': 'Foo'},
{'name': 'bar', 'type': 'Bar'}
]
},
'Bar.baz': {
'returns': 'Baz',
'args': [{'name': 'bar', 'type': 'Bar'}]
}
}
ee.data.send_ = MockSend
ee.Initialize(None)
# Try to cast something that's already of the right class.
x = ee.Foo('argument')
self.assertEqual(ee.Foo(x), x)
# Tests for dynamic classes, where there is a constructor.
#
# If there's more than 1 arg, call the constructor.
x = ee.Foo('a')
y = ee.Foo(x, 'b')
ctor = ee.ApiFunction.lookup('Foo')
self.assertEqual(y.func, ctor)
self.assertEqual(y.args, {'arg1': x, 'arg2': 'b'})
# Can't cast a primitive; call the constructor.
self.assertEqual(ctor, ee.Foo(1).func)
# A computed object, but not this class; call the constructor.
self.assertEqual(ctor, ee.Foo(ee.List([1, 2, 3])).func)
# Tests for dynamic classes, where there isn't a constructor.
#
# Foo.makeBar and Foo.takeBar should have caused Bar to be generated.
self.assertTrue(hasattr(ee, 'Bar'))
# Make sure we can create a Bar.
bar = ee.Foo(1).makeBar()
self.assertTrue(isinstance(bar, ee.Bar))
# Now cast something else to a Bar and verify it was just a cast.
cast = ee.Bar(ee.Foo(1))
self.assertTrue(isinstance(cast, ee.Bar))
self.assertEqual(ctor, cast.func)
# We shouldn't be able to cast with more than 1 arg.
try:
ee.Bar(x, 'foo')
self.fail('Expected an exception.')
except ee.EEException as e:
self.assertTrue('Too many arguments for ee.Bar' in str(e))
# We shouldn't be able to cast a primitive.
try:
ee.Bar(1)
self.fail('Expected an exception.')
except ee.EEException as e:
self.assertTrue('Must be a ComputedObject' in str(e))
def testDynamicConstructorCasting(self):
"""Test the behavior of casting with dynamic classes."""
self.InitializeApi()
result = ee.Geometry.Rectangle(1, 1, 2, 2).bounds(0, 'EPSG:4326')
expected = (ee.Geometry.Polygon([[1, 2], [1, 1], [2, 1], [2, 2]])
.bounds(ee.ErrorMargin(0), ee.Projection('EPSG:4326')))
self.assertEqual(expected, result)
def testPromotion(self):
"""Verifies object promotion rules."""
self.InitializeApi()
# Features and Images are both already Elements.
self.assertTrue(isinstance(ee._Promote(ee.Feature(None), 'Element'),
ee.Feature))
self.assertTrue(isinstance(ee._Promote(ee.Image(0), 'Element'), ee.Image))
# Promote an untyped object to an Element.
untyped = ee.ComputedObject('foo', {})
self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element))
# Promote an untyped variable to an Element.
untyped = ee.ComputedObject(None, None, 'foo')
self.assertTrue(isinstance(ee._Promote(untyped, 'Element'), ee.Element))
self.assertEqual('foo', ee._Promote(untyped, 'Element').varName)
def testUnboundMethods(self):
"""Verifies unbound method attachment to ee.Algorithms."""
# Use a custom set of known functions.
def MockSend(path, unused_params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {
'Foo': {
'type': 'Algorithm',
'args': [],
'description': '',
'returns': 'Object'
},
'Foo.bar': {
'type': 'Algorithm',
'args': [],
'description': '',
'returns': 'Object'
},
'Quux.baz': {
'type': 'Algorithm',
'args': [],
'description': '',
'returns': 'Object'
},
'last': {
'type': 'Algorithm',
'args': [],
'description': '',
'returns': 'Object'
}
}
ee.data.send_ = MockSend
ee.ApiFunction.importApi(lambda: None, 'Quux', 'Quux')
ee._InitializeUnboundMethods()
self.assertTrue(callable(ee.Algorithms.Foo))
self.assertTrue(callable(ee.Algorithms.Foo.bar))
self.assertTrue('Quux' not in ee.Algorithms)
self.assertEqual(ee.call('Foo.bar'), ee.Algorithms.Foo.bar())
self.assertNotEqual(ee.Algorithms.Foo.bar(), ee.Algorithms.last())
<|fim▁hole|> def testNonAsciiDocumentation(self):
"""Verifies that non-ASCII characters in documentation work."""
foo = u'\uFB00\u00F6\u01EB'
bar = u'b\u00E4r'
baz = u'b\u00E2\u00DF'
def MockSend(path, unused_params, unused_method=None, unused_raw=None):
if path == '/algorithms':
return {
'Foo': {
'type': 'Algorithm',
'args': [],
'description': foo,
'returns': 'Object'
},
'Image.bar': {
'type': 'Algorithm',
'args': [{
'name': 'bar',
'type': 'Bar',
'description': bar
}],
'description': '',
'returns': 'Object'
},
'Image.oldBar': {
'type': 'Algorithm',
'args': [],
'description': foo,
'returns': 'Object',
'deprecated': 'Causes fire'
},
'Image.baz': {
'type': 'Algorithm',
'args': [],
'description': baz,
'returns': 'Object'
}
}
ee.data.send_ = MockSend
ee.Initialize(None)
# The initialisation shouldn't blow up.
self.assertTrue(callable(ee.Algorithms.Foo))
self.assertTrue(callable(ee.Image.bar))
self.assertTrue(callable(ee.Image.baz))
self.assertTrue(callable(ee.Image.baz))
# In Python 2, the docstrings end up UTF-8 encoded. In Python 3, they remain
# Unicode.
if six.PY3:
self.assertEqual(ee.Algorithms.Foo.__doc__, foo)
self.assertIn(foo, ee.Image.oldBar.__doc__)
self.assertIn('DEPRECATED: Causes fire', ee.Image.oldBar.__doc__)
self.assertEqual(ee.Image.bar.__doc__, '\n\nArgs:\n bar: ' + bar)
self.assertEqual(ee.Image.baz.__doc__, baz)
else:
self.assertEqual(ee.Algorithms.Foo.__doc__,
'\xef\xac\x80\xc3\xb6\xc7\xab')
self.assertIn('\xef\xac\x80\xc3\xb6\xc7\xab', ee.Image.oldBar.__doc__)
self.assertIn('DEPRECATED: Causes fire', ee.Image.oldBar.__doc__)
self.assertEqual(ee.Image.bar.__doc__, '\n\nArgs:\n bar: b\xc3\xa4r')
self.assertEqual(ee.Image.baz.__doc__, 'b\xc3\xa2\xc3\x9f')
def testDatePromtion(self):
# Make a feature, put a time in it, and get it out as a date.
self.InitializeApi()
point = ee.Geometry.Point(1, 2)
feature = ee.Feature(point, {'x': 1, 'y': 2})
date_range = ee.call('DateRange', feature.get('x'), feature.get('y'))
# Check that the start and end args are wrapped in a call to Date.
self.assertEqual(date_range.args['start'].func._signature['name'], 'Date')
self.assertEqual(date_range.args['end'].func._signature['name'], 'Date')
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>from .base import BasePageTests
from django.contrib.sites.models import Site
from django.contrib.redirects.models import Redirect
class PageViewTests(BasePageTests):
def test_page_view(self):
r = self.client.get('/one/')
self.assertEqual(r.context['page'], self.p1)
# drafts are available only to staff users
self.p1.is_published = False
self.p1.save()
r = self.client.get('/one/')
self.assertEqual(r.status_code, 404)
self.client.login(username='staff_user', password='staff_user')
r = self.client.get('/one/')
self.assertEqual(r.status_code, 200)
def test_with_query_string(self):
r = self.client.get('/one/?foo')
self.assertEqual(r.context['page'], self.p1)
def test_redirect(self):
"""
Check that redirects still have priority over pages.<|fim▁hole|> new_path='http://redirected.example.com',
site=Site.objects.get_current()
)
response = self.client.get(redirect.old_path)
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], redirect.new_path)
redirect.delete()<|fim▁end|> | """
redirect = Redirect.objects.create(
old_path='/%s/' % self.p1.path, |
<|file_name|>config.service.ts<|end_file_name|><|fim▁begin|>// #docplaster
// #docregion , proto
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// #enddocregion proto
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
// #docregion rxjs-imports
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
// #enddocregion rxjs-imports
// #docregion config-interface
export interface Config {
heroesUrl: string;
textfile: string;
date: any;
}
// #enddocregion config-interface
// #docregion proto
@Injectable()
export class ConfigService {
// #enddocregion proto
// #docregion getConfig_1
configUrl = 'assets/config.json';
// #enddocregion getConfig_1
// #docregion proto
constructor(private http: HttpClient) { }
// #enddocregion proto
// #docregion getConfig, getConfig_1, getConfig_2, getConfig_3
getConfig() {
// #enddocregion getConfig_1, getConfig_2, getConfig_3
return this.http.get<Config>(this.configUrl)
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}
// #enddocregion getConfig
getConfig_1() {
// #docregion getConfig_1
return this.http.get<Config>(this.configUrl);
}
// #enddocregion getConfig_1
getConfig_2() {
// #docregion getConfig_2
// now returns an Observable of Config
return this.http.get<Config>(this.configUrl);
}
// #enddocregion getConfig_2
getConfig_3() {
// #docregion getConfig_3
return this.http.get<Config>(this.configUrl)
.pipe(
catchError(this.handleError)
);<|fim▁hole|> }
// #enddocregion getConfig_3
// #docregion getConfigResponse
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
// #enddocregion getConfigResponse
// #docregion handleError
private handleError(error: HttpErrorResponse) {
if (error.status === 0) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(
`Backend returned code ${error.status}, body was: `, error.error);
}
// Return an observable with a user-facing error message.
return throwError(
'Something bad happened; please try again later.');
}
// #enddocregion handleError
makeIntentionalError() {
return this.http.get('not/a/real/url')
.pipe(
catchError(this.handleError)
);
}
// #docregion proto
}
// #enddocregion proto<|fim▁end|> | |
<|file_name|>ConsulCatalogWatchTests.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.discovery;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
public class ConsulCatalogWatchTests {
@Test
public void isRunningReportsCorrectly() {
ConsulDiscoveryProperties properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties()));
ConsulCatalogWatch watch = new ConsulCatalogWatch(properties, null) {
@Override<|fim▁hole|> }
};
assertThat(watch.isRunning()).isFalse();
watch.start();
assertThat(watch.isRunning()).isTrue();
watch.stop();
assertThat(watch.isRunning()).isFalse();
}
}<|fim▁end|> | public void catalogServicesWatch() {
// do nothing |
<|file_name|>hltapi_playground.py<|end_file_name|><|fim▁begin|>#!/router/bin/python
import outer_packages
#from trex_stl_lib.trex_stl_hltapi import CTRexHltApi, CStreamsPerPort
from trex_stl_lib.trex_stl_hltapi import *
import traceback
import sys, time
from pprint import pprint
import argparse
def error(err = None):
if not err:
raise Exception('Unknown exception, look traceback')
if type(err) is str and not err.startswith('[ERR]'):
err = '[ERR] ' + err
print err
sys.exit(1)
def check_res(res):
if res['status'] == 0:
error('Encountered error:\n%s' % res['log'])
return res
def print_brief_stats(res):
title_str = ' '*3
tx_str = 'TX:'
rx_str = 'RX:'
for port_id, stat in res.iteritems():
if type(port_id) is not int:
continue
title_str += ' '*10 + 'Port%s' % port_id
tx_str += '%15s' % res[port_id]['aggregate']['tx']['total_pkts']
rx_str += '%15s' % res[port_id]['aggregate']['rx']['total_pkts']
print(title_str)
print(tx_str)
print(rx_str)
def wait_with_progress(seconds):
for i in range(0, seconds):
time.sleep(1)
sys.stdout.write('.')
sys.stdout.flush()
print('')
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Example of using stateless TRex via HLT API.', formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-v', dest = 'verbose', default = 0, help='Stateless API verbosity:\n0: No prints\n1: Commands and their status\n2: Same as 1 + ZMQ in&out')
parser.add_argument('--device', dest = 'device', default = 'localhost', help='Address of TRex server')
args = parser.parse_args()
hlt_client = CTRexHltApi(verbose = int(args.verbose))
print('Connecting to %s...' % args.device)
res = check_res(hlt_client.connect(device = args.device, port_list = [0, 1], username = 'danklei', break_locks = True, reset = True))
port_handle = res['port_handle']
print('Connected, got port handles %s' % port_handle)
ports_streams_dict = CStreamsPerPort()
print hlt_client.traffic_control(action = 'poll')
print hlt_client.traffic_config(mode = 'create', l2_encap = 'ethernet_ii_vlan', rate_pps = 1,
l3_protocol = 'ipv4',
#length_mode = 'imix', l3_length = 200,
ipv6_dst_mode = 'decrement', ipv6_dst_count = 300, ipv6_dst_addr = 'fe80:0:0:0:0:0:0:000f',
port_handle = port_handle, port_handle2 = port_handle[1],
#save_to_yaml = '/tmp/d1.yaml',
#stream_id = 1,
)
print hlt_client.traffic_control(action = 'poll')
print hlt_client.traffic_control(action = 'run')
print hlt_client.traffic_control(action = 'poll')
wait_with_progress(2)
print hlt_client.traffic_control(action = 'poll')
print hlt_client.traffic_control(action = 'stop')
print hlt_client.traffic_control(action = 'poll')
print hlt_client.traffic_stats(mode = 'aggregate')
print hlt_client.traffic_control(action = 'clear_stats')
wait_with_progress(1)
print hlt_client.traffic_stats(mode = 'aggregate')
wait_with_progress(1)
print hlt_client.traffic_stats(mode = 'aggregate')
wait_with_progress(1)
print hlt_client.traffic_stats(mode = 'aggregate')
wait_with_progress(1)
print hlt_client.traffic_stats(mode = 'aggregate')
#print res
#print hlt_client._streams_history
#print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
#print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[1])
#ports_streams_dict.add_streams_from_res(res)
sys.exit(0)
res = check_res(hlt_client.traffic_config(mode = 'create', l2_encap = 'ethernet_ii_vlan', rate_pps = 1,
port_handle = port_handle[0], port_handle2 = port_handle[1], save_to_yaml = '/tmp/d1.yaml',
l4_protocol = 'udp',
#udp_src_port_mode = 'decrement',
#udp_src_port_count = 10, udp_src_port = 5,
))
ports_streams_dict.add_streams_from_res(res)
sys.exit(0)
#print ports_streams_dict
#print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
res = check_res(hlt_client.traffic_config(mode = 'modify', port_handle = port_handle[0], stream_id = ports_streams_dict[0][0],
mac_src = '1-2-3:4:5:6', l4_protocol = 'udp', save_to_yaml = '/tmp/d2.yaml'))
#print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
#print hlt_client._streams_history
res = check_res(hlt_client.traffic_config(mode = 'modify', port_handle = port_handle[0], stream_id = ports_streams_dict[0][0],
mac_dst = '{ 7 7 7-7:7:7}', save_to_yaml = '/tmp/d3.yaml'))
#print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle))
res = check_res(hlt_client.traffic_config(mode = 'create', bidirectional = True, length_mode = 'fixed',
port_handle = port_handle[0], port_handle2 = port_handle[1],
transmit_mode = 'single_burst', pkts_per_burst = 100, rate_pps = 100,
mac_src = '1-2-3-4-5-6',
mac_dst = '6:5:4:4:5:6',
save_to_yaml = '/tmp/imix.yaml'))
ports_streams_dict.add_streams_from_res(res)
print('Create single_burst 100 packets rate_pps=100 on port 0')
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[0], transmit_mode = 'single_burst',
pkts_per_burst = 100, rate_pps = 100))
ports_streams_dict.add_streams_from_res(res)
# playground - creating various streams on port 1
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt2.yaml',
tcp_src_port_mode = 'decrement',
tcp_src_port_count = 10, tcp_dst_port_count = 10, tcp_dst_port_mode = 'random'))
ports_streams_dict.add_streams_from_res(res)
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt3.yaml',
l4_protocol = 'udp',
udp_src_port_mode = 'decrement',
udp_src_port_count = 10, udp_dst_port_count = 10, udp_dst_port_mode = 'random'))
ports_streams_dict.add_streams_from_res(res)
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt4.yaml',
length_mode = 'increment',
#ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2))
ports_streams_dict.add_streams_from_res(res)
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt5.yaml',
length_mode = 'decrement', frame_size_min = 100, frame_size_max = 3000,
#ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
#ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2
))
ports_streams_dict.add_streams_from_res(res)
# remove the playground
check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle[1]))
print('Create continuous stream for port 1, rate_pps = 1')
res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt1.yaml',
#length_mode = 'increment', l3_length_min = 200,
ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2))
check_res(hlt_client.traffic_control(action = 'run', port_handle = port_handle))
wait_with_progress(1)
print('Sample after 1 seconds (only packets count)')
res = check_res(hlt_client.traffic_stats(mode = 'all', port_handle = port_handle))
print_brief_stats(res)
print ''
print('Port 0 has finished the burst, put continuous instead with rate 1000. No stopping of other ports.')
check_res(hlt_client.traffic_control(action = 'stop', port_handle = port_handle[0]))<|fim▁hole|> res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[0], rate_pps = 1000))
ports_streams_dict.add_streams_from_res(res)
check_res(hlt_client.traffic_control(action = 'run', port_handle = port_handle[0]))
wait_with_progress(5)
print('Sample after another 5 seconds (only packets count)')
res = check_res(hlt_client.traffic_stats(mode = 'aggregate', port_handle = port_handle))
print_brief_stats(res)
print ''
print('Stop traffic at port 1')
res = check_res(hlt_client.traffic_control(action = 'stop', port_handle = port_handle[1]))
wait_with_progress(5)
print('Sample after another %s seconds (only packets count)' % 5)
res = check_res(hlt_client.traffic_stats(mode = 'aggregate', port_handle = port_handle))
print_brief_stats(res)
print ''
print('Full HLT stats:')
pprint(res)
check_res(hlt_client.cleanup_session())
except Exception as e:
print(traceback.print_exc())
print(e)
raise
finally:
print('Done.')<|fim▁end|> | check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle[0])) |
<|file_name|>bin.ts<|end_file_name|><|fim▁begin|>import log from 'electron-log'
import * as path from 'path'
import * as os from 'os'
const platform = os.platform()
const arch = os.arch()
export const basePath = path.resolve(
__dirname.replace('app.asar', 'app.asar.unpacked'),
'../../bin',
platform,
// arm64 is limit supported only for macOS
platform === 'darwin' && arch === 'arm64'
? 'arm64'
: 'x64',
)
const getBin = (name: string) => path.resolve(
basePath,
platform === 'win32' ? `${name}.exe` : name,<|fim▁hole|>)
export const pngquant = getBin('pngquant')
export const mozjpeg = getBin('moz-cjpeg')
export const cwebp = getBin('cwebp')
log.info('binPath', {
pngquant,
mozjpeg,
cwebp,
})<|fim▁end|> | |
<|file_name|>graph_interface.hpp<|end_file_name|><|fim▁begin|>#ifndef GRAPH_INTERFACE_HPP
#define GRAPH_INTERFACE_HPP
#include "graphdsl.hpp"
#include <vector>
#include <utility>
#include <type_traits>
namespace netalgo
{
template<typename NodeType, typename EdgeType>
class GraphInterface
{<|fim▁hole|> private:
static_assert(std::is_class<NodeType>::value, "NodeType must be a class type");
static_assert(std::is_class<EdgeType>::value, "EdgeType must be a class type");
template<typename U>
static std::false_type sfinae_checkid(bool, U NodeType::* = &NodeType::id()) {}
static std::true_type sfinae_checkid(int) {}
static_assert(decltype(sfinae_checkid(0))::value, "NodeType must contain member function id");
template<typename U>
static std::false_type sfinae_checkedge(bool, U EdgeType::* = &EdgeType::id()) {}
static std::true_type sfinae_checkedge(int) {}
static_assert(decltype(sfinae_checkedge(0))::value, "EdgeType must contain member function id");
template<typename U>
static std::false_type sfinae_checkedgefrom(bool, U EdgeType::* = &EdgeType::from()) {}
static std::true_type sfinae_checkedgefrom(int) {}
static_assert(decltype(sfinae_checkedgefrom(0))::value, "EdgeType must contain member function from");
template<typename U>
static std::false_type sfinae_checkedgeto(bool, U EdgeType::* = &EdgeType::to) {}
static std::true_type sfinae_checkedgeto(int) {}
static_assert(decltype(sfinae_checkedgeto(0))::value, "EdgeType must contain member function to");
static_assert(std::is_convertible<
decltype(std::declval<EdgeType>().from()),
decltype(std::declval<NodeType>().id())
>::value,
"EdgeType.from() must be convertible to NodeType.id()");
static_assert(std::is_convertible<
decltype(std::declval<EdgeType>().to()),
decltype(std::declval<NodeType>().id())
>::value,
"EdgeType.to() must be convertible to NodeType.id()");
public:
GraphInterface() = default;
GraphInterface(const GraphInterface&) = delete;
GraphInterface& operator=(const GraphInterface&) = delete;
GraphInterface(GraphInterface&&) = default;
virtual ~GraphInterface() {}
typedef std::vector<NodeType> NodesBundle;
typedef std::vector<EdgeType> EdgesBundle;
typedef std::pair<NodesBundle, EdgesBundle> ResultType;
typedef typename std::remove_const<
typename std::remove_reference<decltype(std::declval<NodeType>().id())>::type
>::type
NodeIdType;
typedef typename std::remove_const<
typename std::remove_reference<decltype(std::declval<EdgeType>().id())>::type
>::type
EdgeIdType;
virtual void setNode(const NodeType&) = 0;
virtual void setEdge(const EdgeType&) = 0;
virtual void setNodesBundle(const NodesBundle&) = 0;
virtual void setEdgesBundle(const EdgesBundle&) = 0;
virtual void removeNode(const NodeIdType&) = 0;
virtual void removeEdge(const EdgeIdType&) = 0;
virtual void destroy() = 0;
};
}
#endif<|fim▁end|> | |
<|file_name|>cast.hpp<|end_file_name|><|fim▁begin|>// (c) Copyright Fernando Luis Cacciola Carballal 2000-2004
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See library home page at http://www.boost.org/libs/numeric/conversion
//
// Contact the author at: [email protected]
//
//
// Revision History
//
// 19 Nov 2001 Syntatic changes as suggested by Darin Adler (Fernando Cacciola)
// 08 Nov 2001 Fixes to accommodate MSVC (Fernando Cacciola)
// 04 Nov 2001 Fixes to accommodate gcc2.92 (Fernando Cacciola)
// 30 Oct 2001 Some fixes suggested by Daryle Walker (Fernando Cacciola)
// 25 Oct 2001 Initial boostification (Fernando Cacciola)
// 23 Jan 2004 Inital add to cvs (post review)s
// 22 Jun 2011 Added support for specializing cast policies via numeric_cast_traits (Brandon Kohn).
//
#ifndef BOOST_NUMERIC_CONVERSION_CAST_25OCT2001_HPP
#define BOOST_NUMERIC_CONVERSION_CAST_25OCT2001_HPP
#include <boost/detail/workaround.hpp>
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
# include<boost/numeric/conversion/detail/old_numeric_cast.hpp>
#else
#include <boost/type.hpp>
#include <boost/numeric/conversion/converter.hpp>
#include <boost/numeric/conversion/numeric_cast_traits.hpp>
namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{
template <typename Target, typename Source>
inline Target numeric_cast( Source arg )
{
typedef numeric::conversion_traits<Target, Source> conv_traits;
typedef numeric::numeric_cast_traits<Target, Source> cast_traits;
typedef abt_boost::numeric::converter
<
Target,
Source, <|fim▁hole|> typename cast_traits::range_checking_policy
> converter;
return converter::convert(arg);
}
using numeric::bad_numeric_cast;
} // namespace abt_boost
#endif
#endif<|fim▁end|> | conv_traits,
typename cast_traits::overflow_policy,
typename cast_traits::rounding_policy,
abt_boost::numeric::raw_converter< conv_traits >, |
<|file_name|>parseInt.js<|end_file_name|><|fim▁begin|>import root from './_root.js';
import toString from './toString.js';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeParseInt = root.parseInt;
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string), radix || 0);
}
<|fim▁hole|><|fim▁end|> | export default parseInt; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.