text:
from typing import Any
from datetime import datetime

from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from crispy_forms import bootstrap as twbscrispy
from crispy_forms import layout as crispy
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

from corehq.apps.hqwebapp import crispy as hqcrispy
from corehq.apps.userreports.dbaccessors import get_report_configs_for_domain
from corehq.apps.userreports.ui.fields import JsonField
from corehq.motech.models import ConnectionSettings

from .const import (
    DHIS2_UID_MESSAGE,
    DHIS2_UID_RE,
    SEND_FREQUENCY_CHOICES,
    SEND_FREQUENCY_MONTHLY,
    SEND_FREQUENCY_QUARTERLY,
    SEND_FREQUENCY_WEEKLY,
    COMPLETE_DATE_CHOICES,
    COMPLETE_DATE_EMPTY,
    COMPLETE_DATE_COLUMN
)
from .models import SQLDataSetMap, SQLDataValueMap
from corehq.apps.userreports.models import ReportConfiguration
from corehq.apps.userreports.reports.data_source import ConfigurableReportDataSource
from corehq.apps.userreports.util import get_report_config_or_not_found

class DataSetMapForm(forms.ModelForm):
    description = forms.CharField(
        label=_('Description'),
    )
    frequency = forms.ChoiceField(
        label=_('Frequency'),
        choices=SEND_FREQUENCY_CHOICES,
        initial=SEND_FREQUENCY_MONTHLY,
    )
    day_to_send = forms.CharField(
        label=_('Day to send data'),
        help_text=_('Day of the month if "Frequency" is monthly or quarterly. '
                    'Day of the week if "Frequency" is weekly, where Monday '
                    'is 1 and Sunday is 7.'),
    )
    data_set_id = forms.CharField(
        label=_('DataSetID'),
        help_text=_('The DHIS2 ID of this DataSet'),
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
        required=True,
    )
    org_unit_id = forms.CharField(
        label=_('OrgUnitID'),
        required=True,
        help_text=_('The UCR column name specifying the OrgUnitID or a static OrgUnitID.'),
    )
    period = forms.CharField(
        label=_('Period'),
        help_text=_('The UCR column name specifying the Period or a static Period. '
                    'Week periods use the format yyyyWn (e.g. "2004W10" for '
                    'week 10, 2004). Month periods use the format yyyyMM '
                    '(e.g. "200403" for March 2004). Quarter periods use the '
                    'format yyyyQn (e.g. "2004Q1" for January-March 2004). '
                    'If the UCR has a date filter then leave the field blank to '
                    'filter the UCR by the date range of the previous '
                    'period.'),
        required=False,
    )
    attribute_option_combo_id = forms.CharField(
        label=_('AttributeOptionComboID'),
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
        required=False,
    )
    complete_date_option = forms.ChoiceField(
        label=_('CompleteDate'),
        choices=COMPLETE_DATE_CHOICES,
        initial=COMPLETE_DATE_EMPTY,
    )
    complete_date_column = forms.CharField(
        label='CompleteDate Column Name',
        required=False,
    )

    class Meta:
        model = SQLDataSetMap
        fields = [
            'description',
            'connection_settings',
            'ucr_id',
            'frequency',
            'day_to_send',
            'data_set_id',
            'org_unit_id',
            'org_unit_column',
            'period',
            'period_column',
            'attribute_option_combo_id',
            'complete_date_column',
            'complete_date_option',
        ]

    def __init__(self, domain, *args, **kwargs):
        from corehq.motech.dhis2.views import DataSetMapListView
        kwargs['initial'] = add_initial_properties(kwargs.get('instance'), kwargs.get('initial'))

        super().__init__(*args, **kwargs)
        self.domain = domain
        self.fields['connection_settings'] = get_connection_settings_field(domain)
        self.fields['ucr_id'] = get_ucr_field(domain)

        self.helper = hqcrispy.HQFormHelper()

        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _('DataSet Details'),
                crispy.Field('description'),
                crispy.Field('connection_settings'),
                crispy.Field('ucr_id'),
                crispy.Field('frequency'),
                crispy.Field('day_to_send'),
                crispy.Field('data_set_id'),
                crispy.Field('org_unit_id'),
                crispy.Field('period'),
                crispy.Field('attribute_option_combo_id'),
                crispy.Field('complete_date_option'),
                crispy.Field('complete_date_column'),
            ),
            hqcrispy.FormActions(
                twbscrispy.StrictButton(
                    _("Save"),
                    type="submit",
                    css_class="btn btn-primary",
                ),
                hqcrispy.LinkButton(
                    _("Cancel"),
                    reverse(
                        DataSetMapListView.urlname,
                        kwargs={'domain': self.domain},
                    ),
                    css_class="btn btn-default",
                ),
            ),
        )

    def save(self, commit=True):
        self.instance.domain = self.domain
        return super().save(commit)

    def clean(self):
        cleaned_data = super().clean()

        if (
            cleaned_data.get('frequency') == SEND_FREQUENCY_WEEKLY
            and not _int_in_range(cleaned_data.get('day_to_send'), 1, 7)
        ):
            self.add_error('day_to_send', _(
                'Enter a day of the week, where Monday is 1 and Sunday is 7.'
            ))

        elif (
            cleaned_data.get('frequency') != SEND_FREQUENCY_WEEKLY
            and not _int_in_range(cleaned_data.get('day_to_send'), 1, 28)
        ):
            self.add_error('day_to_send', _(
                'Enter a day of the month that occurs in every month (i.e. '
                'from 1 to 28).'
            ))

        ucr_id = cleaned_data.get('ucr_id')
        ucr = None
        if ucr_id:
            ucr = get_report_config_or_not_found(self.domain, ucr_id)

        if cleaned_data.get('org_unit_id'):
            org_unit_id = cleaned_data.get('org_unit_id')

            # Check if the user input corresponds to one of the UCR's columns
            # If so, populate 'org_unit_column', else 'org_unit_id'
            if ucr_has_field(ucr, org_unit_id):
                # Save user period input appropriately as period_column
                cleaned_data['org_unit_column'] = cleaned_data['org_unit_id']
                cleaned_data['org_unit_id'] = None

            else:
                try:
                    org_unit_validator = RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)
                    org_unit_validator(org_unit_id)
                    # Ensure org_unit_column and org_unit_id is not both saved
                    if cleaned_data['org_unit_column']:
                        cleaned_data['org_unit_column'] = None

                except ValidationError:
                    self.add_error('org_unit_id', org_unit_validator.message)

        if cleaned_data.get('period'):
            period = cleaned_data.get('period')

            # Check if the user input corresponds to one of the UCR's columns
            # If so, populate 'period_column', else 'period'
            if ucr_has_field(ucr, period):
                # Save user period input appropriately as period_column
                cleaned_data['period_column'] = cleaned_data['period']
                cleaned_data['period'] = None

            else:
                period_validators = {
                    SEND_FREQUENCY_WEEKLY: RegexValidator(r'^\d{4}W\d{1,2}$', _(
                        '"Frequency" is set to "Weekly". Please enter a valid '
                        'week period in the format yyyyWn (e.g. "2004W10" for '
                        'week 10, 2004), or enter a valid column.'
                    )),
                    SEND_FREQUENCY_MONTHLY: RegexValidator(r'^\d{6}$', _(
                        '"Frequency" is set to "Monthly". Please enter a valid '
                        'month period in the format yyyyMM (e.g. "200403" for '
                        'March 2004), or enter a valid column.'
                    )),
                    SEND_FREQUENCY_QUARTERLY: RegexValidator(r'^\d{4}Q\d$', _(
                        '"Frequency" is set to "Quarterly". Please enter a valid '
                        'quarter period in the format yyyyQn (e.g. "2004Q1" for '
                        'January-March 2004), or enter a valid column.'
                    )),
                }
                validate_period = period_validators[cleaned_data.get('frequency')]
                try:
                    validate_period(cleaned_data.get('period'))

                    # Ensure period column and period is not both saved
                    if cleaned_data['period_column'] is not None:
                        cleaned_data['period_column'] = None

                except ValidationError:
                    self.add_error('period', validate_period.message)

        selected_complete_date_option = cleaned_data.get('complete_date_option')

        if selected_complete_date_option == COMPLETE_DATE_COLUMN:
            column_name = cleaned_data.get('complete_date_column')

            if not column_name:
                self.add_error('complete_date_column', 'Cannot be empty.')
            elif ucr_has_field(ucr, column_name):
                if valid_ucr_date_column(ucr, column_name):
                    cleaned_data['complete_date_column'] = column_name
                else:
                    self.add_error(
                        'complete_date_column',
                        'Please make sure the column values are formatted as yyyy-mm-dd'
                    )
            else:
                self.add_error('complete_date_column', 'Column does not exist in UCR.')
        else:
            cleaned_data['complete_date_column'] = None

        return self.cleaned_data

def add_initial_properties(instance, kwargs_initial):
    if instance is not None:
        if instance.period_column:
            kwargs_initial['period'] = instance.period_column

        if instance.org_unit_column:
            kwargs_initial['org_unit_id'] = instance.org_unit_column

    return kwargs_initial

def ucr_has_field(ucr: ReportConfiguration, field):
    return any(c.column_id == field for c in ucr.report_columns)

def valid_ucr_date_column(ucr, column_name):
    data_source = ConfigurableReportDataSource.from_spec(ucr, include_prefilters=True)

    for datum in data_source.get_data():
        value = datum.get(column_name)

        try:
            if type(value) is not str:
                return False
            else:
                datetime.strptime(value, "%Y-%m-%d")
        except ValueError:
            return False
    return True

def get_connection_settings_field(domain):
    from corehq.motech.views import ConnectionSettingsListView

    connection_settings = ConnectionSettings.objects.filter(domain=domain)
    url = reverse(ConnectionSettingsListView.urlname,
                  kwargs={'domain': domain})
    return forms.ModelChoiceField(
        label=_("Connection Settings"),
        queryset=connection_settings,
        required=True,
        help_text=_(f'Add/Edit Connections Settings')
    )

def get_ucr_field(domain):
    from corehq.apps.userreports.views import UserConfigReportsHomeView

    ucrs = get_report_configs_for_domain(domain)
    url = reverse(UserConfigReportsHomeView.urlname,
                  kwargs={'domain': domain})
    return forms.ChoiceField(
        label=_("User Configurable Report"),
        choices=[(ucr.get_id, ucr.title) for ucr in ucrs],
        required=True,
        help_text=_(
            'DataSet Maps map CommCare UCRs to DHIS2 DataSets. '
            'More info. '
            f'Go to Configurable Reports to define a UCR.')
    )

class DataValueMapBaseForm(forms.ModelForm):
    column = forms.CharField(
        label=_('Column'),
        required=True,
    )
    data_element_id = forms.CharField(
        label=_('Data element ID'),
        required=True,
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
    )
    category_option_combo_id = forms.CharField(
        label=_('Category option combo ID'),
        required=False,
        validators=[RegexValidator(DHIS2_UID_RE, DHIS2_UID_MESSAGE)],
    )
    comment = forms.CharField(
        label=_('Comment'),
        required=False,
    )

    class Meta:
        model = SQLDataValueMap
        fields = [
            'column',
            'data_element_id',
            'category_option_combo_id',
            'comment',
        ]

    def __init__(self, dataset_map, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.dataset_map = dataset_map
        self.helper = self.get_form_helper()

    def get_form_helper(self):
        raise NotImplementedError

    def save(self, commit=True):
        self.instance.dataset_map = self.dataset_map
        return super().save(commit)

class DataValueMapCreateForm(DataValueMapBaseForm):

    def get_form_helper(self):
        helper = FormHelper()
        helper.form_style = 'inline'
        helper.form_show_labels = False
        helper.layout = crispy.Layout(
            twbscrispy.InlineField('column'),
            twbscrispy.InlineField('data_element_id'),
            twbscrispy.InlineField('category_option_combo_id'),
            twbscrispy.InlineField('comment'),
            twbscrispy.StrictButton(
                mark_safe(f' {_("Add")}'),  # nosec: no user input
                css_class='btn-primary',
                type='submit',
            )
        )
        return helper

class DataValueMapUpdateForm(DataValueMapBaseForm):
    id = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        model = SQLDataValueMap
        fields = [
            'id',
            'column',
            'data_element_id',
            'category_option_combo_id',
            'comment',
        ]

    def get_form_helper(self):
        helper = FormHelper()
        helper.form_style = 'default'
        helper.form_show_labels = True
        helper.layout = crispy.Layout(
            crispy.Div(
                crispy.Field('id'),
                crispy.Field('column'),
                crispy.Field('data_element_id'),
                crispy.Field('category_option_combo_id'),
                crispy.Field('comment'),
                css_class='modal-body',
            ),
            twbscrispy.FormActions(
                twbscrispy.StrictButton(
                    "Update DataValue Map",
                    css_class='btn btn-primary',
                    type='submit',
                ),
                crispy.HTML('<button type="button" '
                            '        class="btn btn-default" '
                            '        data-dismiss="modal">'
                            'Cancel'
                            '</button>'),
                css_class='modal-footer',
            )
        )
        return helper

class Dhis2ConfigForm(forms.Form):
    form_configs = JsonField(expected_type=list)

    def __init__(self, *args, **kwargs):
        super(Dhis2ConfigForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', _('Save Changes')))

    def clean_form_configs(self):
        errors = _validate_form_configs(self.cleaned_data['form_configs'])
        if errors:
            raise ValidationError(errors)
        return self.cleaned_data['form_configs']

class Dhis2EntityConfigForm(forms.Form):
    """
    Dhis2EntityConfig.case_configs is a list. Dhis2EntityConfigForm has
    one case_config, and is used in a formset.
    """
    case_config = JsonField()

    def clean_case_config(self):
        errors = []
        case_config = self.cleaned_data['case_config']
        if not isinstance(case_config, dict):
            raise ValidationError(
                _('The "case_type" property is a dictionary, not a "%(data_type)s".'),
                params={'data_type': type(case_config).__name__}
            )
        if not case_config.get('case_type'):
            errors.append(ValidationError(
                _('The "%(property)s" property is required.'),
                params={'property': 'case_type'},
                code='required_property',
            ))
        if 'form_configs' not in case_config:
            errors.append(ValidationError(
                _('The "%(property)s" property is required.'),
                params={'property': 'form_configs'},
                code='required_property',
            ))
        elif not isinstance(case_config['form_configs'], list):
            raise ValidationError(
                _('The "form_configs" property is a dictionary, not a "%(data_type)s".'),
                params={'data_type': type(case_config['form_configs']).__name__}
            )
        else:
            errors.extend(_validate_form_configs(case_config['form_configs']))
        if errors:
            raise ValidationError(errors)
        return self.cleaned_data['case_config']

def _validate_form_configs(form_configs):
    errors = []
    for form_config in form_configs:
        if form_config.get('xmlns'):
            required_msg = _('The "%(property)s" property is required for '
                             'form "{}".').format(form_config['xmlns'])
        else:
            required_msg = _('The "%(property)s" property is required.')

        if not form_config.get('xmlns'):
            errors.append(ValidationError(
                '{} {}'.format(required_msg, _('Please specify the XMLNS of the form.')),
                params={'property': 'xmlns'},
                code='required_property',
            ))
        if not form_config.get('program_id'):
            errors.append(ValidationError(
                '{} {}'.format(required_msg, _('Please specify the DHIS2 Program of the event.')),
                params={'property': 'program_id'},
                code='required_property',
            ))
        if not form_config.get('datavalue_maps'):
            errors.append(ValidationError(
                '{} {}'.format(required_msg, _('Please map CommCare values to DHIS2 data elements.')),
                params={'property': 'datavalue_maps'},
                code='required_property',
            ))
    return errors

def _int_in_range(value: Any, lower: int, upper: int) -> bool:
    """
    Casts as int and returns True if lower <= value <= upper

    >>> _int_in_range(5, 1, 7)
    True

    """
    try:
        value_int = int(value)
    except (TypeError, ValueError):
        return False
    return lower <= value_int <= upper


text:
"""
The Yaml Extension adds the :class:`YamlOutputHandler` to render
output in pure Yaml, as well as the :class:`YamlConfigHandler` that allows
applications to use Yaml configuration files as a drop-in replacement of
the default :class:`cement.ext.ext_configparser.ConfigParserConfigHandler`.

Requirements
------------

 * pyYaml (``pip install pyYaml``)

Configuration
-------------

This extension does not honor any application configuration settings.

Usage
_____

**myapp.conf**

.. code-block:: yaml

    ---
    myapp:
        foo: bar

**myapp.py**

.. code-block:: python

    from cement.core.foundation import CementApp

    class MyApp(CementApp):
        class Meta:
            label = 'myapp'
            extensions = ['yaml']
            config_handler = 'yaml'

            # you probably don't want to do this.. but you can
            # output_handler = 'yaml'

    with MyApp() as app:
        app.run()

        # create some data
        data = dict(foo=app.config.get('myapp', 'foo'))

        app.render(data)

In general, you likely would not set ``output_handler`` to ``yaml``, but
rather another type of output handler that displays readable output to the
end-user (i.e. Mustache, Genshi, or Tabulate).  By default Cement
adds the ``-o`` command line option to allow the end user to override the
output handler.  For example: passing ``-o yaml`` will override the default
output handler and set it to ``YamlOutputHandler``.

See ``CementApp.Meta.handler_override_options``.

.. code-block:: console

    $ python myapp.py -o yaml
    {foo: bar}

"""

import yaml
from ..core import output
from ..utils.misc import minimal_logger
from ..ext.ext_configparser import ConfigParserConfigHandler

LOG = minimal_logger(__name__)

def suppress_output_before_run(app):
    """
    This is a ``post_argument_parsing`` hook that suppresses console output if
    the ``YamlOutputHandler`` is triggered via command line.

    :param app: The application object.

    """
    if not hasattr(app.pargs, 'output_handler_override'):
        return
    elif app.pargs.output_handler_override == 'yaml':
        app._suppress_output()

def unsuppress_output_before_render(app, data):
    """
    This is a ``pre_render`` that unsuppresses console output if
    the ``YamlOutputHandler`` is triggered via command line so that the Yaml
    is the only thing in the output.

    :param app: The application object.

    """
    if not hasattr(app.pargs, 'output_handler_override'):
        return
    elif app.pargs.output_handler_override == 'yaml':
        app._unsuppress_output()

def suppress_output_after_render(app, out_text):
    """
    This is a ``post_render`` hook that suppresses console output again after
    rendering, only if the ``YamlOutputHandler`` is triggered via command
    line.

    :param app: The application object.

    """
    if not hasattr(app.pargs, 'output_handler_override'):
        return
    elif app.pargs.output_handler_override == 'yaml':
        app._suppress_output()

class YamlOutputHandler(output.CementOutputHandler):

    """
    This class implements the :ref:`IOutput <cement.core.output>`
    interface.  It provides Yaml output from a data dictionary and uses
    `pyYaml <http://pyYaml.org/wiki/PyYamlDocumentation>`_ to dump it to
    STDOUT.  Please see the developer documentation on
    :ref:`Output Handling <dev_output_handling>`.

    This handler forces Cement to suppress console output until
    ``app.render`` is called (keeping the output pure Yaml).  If
    troubleshooting issues, you will need to pass the ``--debug`` option in
    order to unsuppress output and see what's happening.

    """

    class Meta:

        """Handler meta-data."""

        interface = output.IOutput
        label = 'yaml'

        #: Whether or not to include ``yaml`` as an available to choice
        #: to override the ``output_handler`` via command line options.
        overridable = True

    def __init__(self, *args, **kw):
        super(YamlOutputHandler, self).__init__(*args, **kw)
        self.config = None

    def _setup(self, app_obj):
        self.app = app_obj

    def render(self, data_dict, template=None, **kw):
        """
        Take a data dictionary and render it as Yaml output.  Note that the
        template option is received here per the interface, however this
        handler just ignores it.  Additional keyword arguments passed to
        ``yaml.dump()``.

        :param data_dict: The data dictionary to render.
        :keyword template: Ignored in this output handler implementation.
        :returns: A Yaml encoded string.
        :rtype: ``str``

        """
        LOG.debug("rendering output as yaml via %s" % self.__module__)
        return yaml.dump(data_dict, **kw)

class YamlConfigHandler(ConfigParserConfigHandler):

    """
    This class implements the :ref:`IConfig <cement.core.config>`
    interface, and provides the same functionality of
    :ref:`ConfigParserConfigHandler <cement.ext.ext_configparser>`
    but with Yaml configuration files.  See
    `pyYaml <http://pyYaml.org/wiki/PyYamlDocumentation>`_ for more
    information on pyYaml.

    **Note** This extension has an external dependency on `pyYaml`.  You must
    include `pyYaml` in your application's dependencies as Cement explicitly
    does *not* include external dependencies for optional extensions.

    """
    class Meta:
        label = 'yaml'

    def __init__(self, *args, **kw):
        super(YamlConfigHandler, self).__init__(*args, **kw)

    def _parse_file(self, file_path):
        """
        Parse Yaml configuration file settings from file_path, overwriting
        existing config settings.  If the file does not exist, returns False.

        :param file_path: The file system path to the Yaml configuration file.
        :returns: boolean

        """
        self.merge(yaml.load(open(file_path)))

        # FIX ME: Should check that file was read properly, however if not it
        # will likely raise an exception anyhow.
        return True

def load(app):
    app.hook.register('post_argument_parsing', suppress_output_before_run)
    app.hook.register('pre_render', unsuppress_output_before_render)
    app.hook.register('post_render', suppress_output_after_render)
    app.handler.register(YamlOutputHandler)
    app.handler.register(YamlConfigHandler)

redpajama_set_name: RedPajamaGithub


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

@SuppressWarnings("all")
public class AlarmEvent extends Event {
    public AlarmEventArgument alarm;

    public AlarmEventArgument getAlarm() {
        return this.alarm;
    }

    public void setAlarm(AlarmEventArgument alarm) {
        this.alarm = alarm;
    }
}


text:
package ru.stqa.pft.addressbook.appmanager;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import ru.stqa.pft.addressbook.model.ContactData;

/**
 * Created by User on 30.10.2016.
 */
public class ContactHelper extends HelperBase{

  public ContactHelper(WebDriver wd) {
    super (wd);
  }

  public void submitContactCreation() {
      click(By.xpath("//div[@id='content']/form/input[21]"));
  }

  public void fillContactForm(ContactData contactData, boolean creation) {
    type(By.name("firstname"), contactData.getName());
    type(By.name("lastname"), contactData.getSurname());
    type(By.name("mobile"), contactData.getPhone());
    type(By.name("email"), contactData.getEmail());

    if (creation) {
      new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
    } else {
      Assert.assertFalse(isElementPresent(By.name("new_group")));
    }
  }

  public void initContactCreation() {
      click(By.linkText("add new"));
  }

  public void selectContact() {
    click(By.name("selected[]"));
  }

  public void deleteSelectedContacts() {
    click(By.xpath("//div[@id='content']/form[2]/div[2]input"));
  }

  public void initContactModification() {
    click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
  }

  public void submitContactModification() {
    click(By.xpath("//div[@id='content']/form[1]/input[22]"));
  }

  public void returnToHomePage() {
    click(By.linkText("home page"));
  }

  public void acceptAlert() {wd.switchTo().alert().accept();
  }

  public void createContact(ContactData contactData) {
    initContactCreation();
    fillContactForm(contactData, true);
    submitContactCreation();
    returnToHomePage();
  }

  public boolean isThereAContact() {
    return isElementPresent(By.name("selected[]"));
  }
}


text:
package org.me.calculator;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for multiply complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="multiply">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="i" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="j" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "multiply", propOrder = {
    "i",
    "j"
})
public class Multiply {

    protected int i;
    protected int j;

    /**
     * Gets the value of the i property.
     *
     */
    public int getI() {
        return i;
    }

    /**
     * Sets the value of the i property.
     *
     */
    public void setI(int value) {
        this.i = value;
    }

    /**
     * Gets the value of the j property.
     *
     */
    public int getJ() {
        return j;
    }

    /**
     * Sets the value of the j property.
     *
     */
    public void setJ(int value) {
        this.j = value;
    }

}


text:
$:.unshift '../lib'
require 'gearman'

client = Gearman::Client.new('localhost:4730')

# Create 100 foreground jobs, one at a time
(1..100).each do |jid|
  data = rand(36**8).to_s(36)
  puts "#{jid} #{data}"
  task = Gearman::Task.new('reverse_string', data)
  task.on_complete {|d| puts d }
  client.do_task(task)
end


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>Table of Contents - RDoc Documentation</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

Table of Contents - RDoc Documentation

Pages

    example

Classes/Modules

    Ability

    AdminController

    AdminHelper

    ApplicationController

    ApplicationHelper

    Assignment

    AssignmentController

    AssignmentDefinition

    AssignmentDefinitionToUser

    AssignmentHelper

    AssignmentPairing

    Authentication

    AuthenticationsController

    AuthenticationsHelper

    Course

    CourseController

    CourseGroup

    CourseHelper

    Deprecated

    Emailer

    ErrorsController

    FacultyController

    FacultyHelper

    FileSubmission

    FileSubmissionUploader

    FileSubmissionsController

    FileSubmissionsHelper

    HomeController

    HomeHelper

    PairingHelper

    QuestionExtra

    RegistrationsController

    ReviewAnswer

    ReviewAssignment

    ReviewAssignmentController

    ReviewAssignmentHelper

    ReviewMapping

    ReviewQuestion

    StudentInCourse

    TaForCourse

    User

Methods

::new — Ability

::search — User

#active_for_authentication? — User

#add_student — CourseController

#add_user — AdminController

#admin_count — ApplicationHelper

#answer_form — ReviewAssignmentController

#assignment_pairings — Assignment

#completed? — ReviewMapping

#contact_us — HomeController

#create — AssignmentController

#create — ReviewAssignmentController

#create — AuthenticationsController

#create — CourseController

#create — FileSubmissionsController

#create_and_invite_user — ApplicationHelper

#create_pairings — PairingHelper

#create_pairings_mk_2 — PairingHelper

#delete — FileSubmissionsController

#delete_user — AdminController

#deprecated — Deprecated

#destroy — User

#destroy — AuthenticationsController

#devise_mapping — ApplicationHelper

#download — AssignmentController

#downloadAll — AssignmentController

#edit — CourseController

#edit — ReviewAssignmentController

#edit — AssignmentController

#end_date_buffered — ReviewAssignment

#end_date_buffered — Assignment

#faculty_count — ApplicationHelper

#file_complaint — Emailer

#find_file_submission — ReviewAssignment

#find_pair — ReviewAssignment

#friendly_full_name — User

#full_name — User

#full_save_path — FileSubmission

#getFacultyFileSubmissions — Assignment

#get_depth — PairingHelper

#get_groups — Course

#get_latest_assignment_pairing — PairingHelper

#get_seed — PairingHelper

#get_students — Course

#get_tas — Course

#grades — ReviewAssignmentController

#group — PairingHelper

#grouped? — ReviewAssignment

#has_not_started — Assignment

#has_not_started? — Assignment

#import_students_and_tas — Course

#index — AdminController

#index — HomeController

#index — FacultyController

#index — AuthenticationsController

#index — AssignmentController

#is_active — Assignment

#is_active? — ReviewAssignment

#is_active? — Assignment

#is_late — Assignment

#is_late? — ReviewAssignment

#is_late? — Assignment

#is_over — Assignment

#is_over? — Assignment

#is_over? — ReviewAssignment

#is_user_ta — Course

#manage_groups — CourseController

#new — FileSubmissionsController

#new — CourseController

#not_found — ApplicationController

#open_spreadsheet — Course

#other_user — ReviewMapping

#pair — PairingHelper

#pair_assignment_mk_2 — PairingHelper

#pairings — ReviewAssignmentController

#pretty_end_date — ReviewAssignment

#pretty_end_date — Assignment

#pretty_start_date — Assignment

#pretty_start_date — ReviewAssignment

#professor_of — User

#requires — ApplicationHelper

#resource — ApplicationHelper

#resource_name — ApplicationHelper

#routing — ErrorsController

#save_directory — FileSubmission

#search_users — AdminController

#send_contact_email — HomeController

#set_type — ReviewQuestion

#show — CourseController

#show_error — Emailer

#signup_confirmation — Emailer

#store_dir — FileSubmissionUploader

#student_count — ApplicationHelper

#student_in — User

#student_submit — ReviewAssignmentController

#submit_edit — CourseController

#submit_new — AssignmentController

#submitchanges — AssignmentController

#ta_count — ApplicationHelper

#ta_in — User

#to_csv — ReviewAssignment

#user_can_download — FileSubmission

#user_can_download_all — Assignment

#username — User

#view — AssignmentController

#view — ReviewAssignmentController

#view_admin — AdminController

#view_faculty — AdminController

#view_feedback — ReviewAssignmentController

#view_live — FileSubmissionsController

#view_recent_activity — AdminController

#view_students — AdminController

#view_submission — ReviewAssignmentController

#view_user_info — AdminController

#zip_and_flatten — PairingHelper

[Validate]

Generated by RDoc 3.12.

Generated with the Darkfish Rdoc Generator 3.


text:
extern "C" {
#include "ampi.h"
}
using namespace std;

// Communciation

void MPI_Irecv(double *buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void MPI_Isend(double *buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void MPI_Wait(int *request, int *status);
//void MPI_Wait(double *buf, int *request, int *status);
void MPI_Reduce(double *sendbuf, double *recvbuf, int &nelements, int &ampi_double, int &op, int &root, int &ampi_comm);

// First order

// Communciation

void a1_MPI_Irecv(int bmode, double *buf, double *&a1_buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void a1_MPI_Isend(int bmode, double *buf, double *&a1_buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void a1_MPI_Wait(int bmode, int *request, int *status);
void a1_MPI_Reduce(int bmode, double *sendbuf, double *a1_sendbuf, double *recvbuf, double *a1_recvbuf, int &nelements, int &ampi_double, int &op, int &root, int &ampi_comm);

// Forward over Reverse

// Communciation

void t2_a1_MPI_Irecv(int bmode, double * buf, double * t2_buf, double *&a1_buf, double *&t2_a1_buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void t2_a1_MPI_Isend(int bmode, double * buf, double * t2_buf, double *&a1_buf, double *&t2_a1_buf, int &nelements, int &ampi_double, int &target, int &tag, int &ampi_comm, int *request);
void t2_a1_MPI_Wait(int bmode, int *request, int *status);
void t2_a1_MPI_Reduce(int bmode, double *sendbuf, double *t2_sendbuf, double *a1_sendbuf, double *t2_a1_sendbuf, double *recvbuf, double *t2_recvbuf, double *a1_recvbuf, double *t2_a1_recvbuf, int &nelements, int &ampi_double, int &op, int &root, int &ampi_comm);

// Buffer allocation

void t2_a1_dcc_malloc(int bmode, double *&buf, double *&t2_buf, double *&a1_buf, double *&t2_a1_buf, int &size);
void t2_a1_dcc_free(int bmode, double *&buf, double *&t2_buf, double *&a1_buf, double *&t2_a1_buf);

void t2_a1_print_num(int bmode, double &num, double &t2_num, double &a1_num, double &t2_a1_num);
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/character_left"
        android:showAsAction="always"
        android:title="@string/character_left">
    </item>

    <item
        android:id="@+id/send_tweet"
        android:showAsAction="always"
        android:onClick="onSendTweetClicked"
        android:enabled="false"
        android:title="@string/send_tweet">
    </item>

</menu>


text:
        Add member

        <form ng-submit="save(member)">
            <fieldset>
                <legend>Member data</legend>

                    Name:
                    <input id="name" ng-model="member.name" class="form-control" required/>

                    Phone:
                    <input id="phone" ng-model="member.phone" class="form-control"/>

                    eMail:
                    <input id="email" class="form-control" ng-model="member.emailAddress" type="email"/>

                    More eMail adresses
                    <select id="alternativEmail" size="3" ng-model="selectedAlternatives"
                            ng-options="alternative.name for alternative in member.alternativeAddresses">
                    </select>

                    <ng-form class="form-inline">

                                Additional eMail:
                                <input id="newEmail" ng-model="newEmail" type="email" class="form-control"
                                       placeholder="eMail address">

                            <button class="btn" ng-click="moveAddress()">
                                Add
                            </button>

                    </ng-form>

                <button type="submit" class="btn btn-primary" ng-click="saveMember()">Save
                </button>
                <button type="button" class="btn" ng-click="cancelEditMember()">Cancel</button>
            </fieldset>
        </form>

{{member|json}}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Ark</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#partOfSpeech</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">noun</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/gs/ark</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#definition</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">In the Old Testament, the boat built by Noah to preserve life during the great flood.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/bd/ark?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/triple-index/ark?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/tg/ark?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/flood-at-noahs-time</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/noah-1</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/rainbow</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/ark-of-the-covenant</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/guide-to-the-scriptures</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/ark</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">4</sem:object>
  </sem:triple>
</sem:triples>


text:
package org.genericsystem.ir;

import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.genericsystem.cv.utils.NewClassCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;

public class NewClassCreatorVerticle extends ActionVerticle {

	private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

	public static final String ACTION = "newClassCreation";

	@Override
	public String getAction() {
		return ACTION;
	}

	@Override
	protected void handle(Future<Object> future, JsonObject task) {
		Path filePath = Paths.get(DistributedVerticle.BASE_PATH + task.getString(DistributedVerticle.FILENAME));
		logger.info("Creating a new class for image ", filePath);
		Path savedFile = NewClassCreator.createNewClass(Paths.get(DistributedVerticle.BASE_PATH, "/classes/"), filePath);
		if (savedFile != null)
			future.complete(savedFile.toString());
		else
			future.fail("Unable to create the class");
	}

	@Override
	protected void handleResult(AsyncResult<Object> res, JsonObject task) {
		if (res.succeeded()) {
			Path path = Paths.get((String) res.result());
			Path relative = Paths.get(DistributedVerticle.BASE_PATH).relativize(path);
			logger.info("Created new class {} for file {}", relative.getParent(), path.getFileName());
			addTask(relative.toString(), AddImageToEngineVerticle.ACTION);
		} else
			throw new IllegalStateException("Error while creating a new class for image " + task.getString(DistributedVerticle.FILENAME), res.cause());
	}
}


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Lightup
{
    using System;
    using System.Collections.Immutable;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;

    internal readonly partial struct FunctionPointerCallingConventionSyntaxWrapper : ISyntaxWrapper<CSharpSyntaxNode>
    {
        internal const string WrappedTypeName = "Microsoft.CodeAnalysis.CSharp.Syntax.FunctionPointerCallingConventionSyntax";
        private static readonly Type WrappedType;

        private static readonly Func<CSharpSyntaxNode, SyntaxToken> ManagedOrUnmanagedKeywordAccessor;
        private static readonly Func<CSharpSyntaxNode, CSharpSyntaxNode> UnmanagedCallingConventionListAccessor;
        private static readonly Func<CSharpSyntaxNode, SyntaxToken, CSharpSyntaxNode> WithManagedOrUnmanagedKeywordAccessor;
        private static readonly Func<CSharpSyntaxNode, CSharpSyntaxNode, CSharpSyntaxNode> WithUnmanagedCallingConventionListAccessor;

        private readonly CSharpSyntaxNode node;

        static FunctionPointerCallingConventionSyntaxWrapper()
        {
            WrappedType = SyntaxWrapperHelper.GetWrappedType(typeof(FunctionPointerCallingConventionSyntaxWrapper));
            ManagedOrUnmanagedKeywordAccessor = LightupHelpers.CreateSyntaxPropertyAccessor<CSharpSyntaxNode, SyntaxToken>(WrappedType, nameof(ManagedOrUnmanagedKeyword));
            UnmanagedCallingConventionListAccessor = LightupHelpers.CreateSyntaxPropertyAccessor<CSharpSyntaxNode, CSharpSyntaxNode>(WrappedType, nameof(UnmanagedCallingConventionList));
            WithManagedOrUnmanagedKeywordAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<CSharpSyntaxNode, SyntaxToken>(WrappedType, nameof(ManagedOrUnmanagedKeyword));
            WithUnmanagedCallingConventionListAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<CSharpSyntaxNode, CSharpSyntaxNode>(WrappedType, nameof(UnmanagedCallingConventionList));
        }

        private FunctionPointerCallingConventionSyntaxWrapper(CSharpSyntaxNode node)
        {
            this.node = node;
        }

        public CSharpSyntaxNode SyntaxNode => this.node;

        public SyntaxToken ManagedOrUnmanagedKeyword
        {
            get
            {
                return ManagedOrUnmanagedKeywordAccessor(this.SyntaxNode);
            }
        }

        public FunctionPointerUnmanagedCallingConventionListSyntaxWrapper UnmanagedCallingConventionList
        {
            get
            {
                return (FunctionPointerUnmanagedCallingConventionListSyntaxWrapper)UnmanagedCallingConventionListAccessor(this.SyntaxNode);
            }
        }

        public static explicit operator FunctionPointerCallingConventionSyntaxWrapper(SyntaxNode node)
        {
            if (node == null)
            {
                return default;
            }

            if (!IsInstance(node))
            {
                throw new InvalidCastException($"Cannot cast '{node.GetType().FullName}' to '{WrappedTypeName}'");
            }

            return new FunctionPointerCallingConventionSyntaxWrapper((CSharpSyntaxNode)node);
        }

        public static implicit operator CSharpSyntaxNode(FunctionPointerCallingConventionSyntaxWrapper wrapper)
        {
            return wrapper.node;
        }

        public static bool IsInstance(SyntaxNode node)
        {
            return node != null && LightupHelpers.CanWrapNode(node, WrappedType);
        }

        public FunctionPointerCallingConventionSyntaxWrapper WithManagedOrUnmanagedKeyword(SyntaxToken managedOrUnmanagedKeyword)
        {
            return new FunctionPointerCallingConventionSyntaxWrapper(WithManagedOrUnmanagedKeywordAccessor(this.SyntaxNode, managedOrUnmanagedKeyword));
        }

        public FunctionPointerCallingConventionSyntaxWrapper WithUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntaxWrapper unmanagedCallingConventionList)
        {
            return new FunctionPointerCallingConventionSyntaxWrapper(WithUnmanagedCallingConventionListAccessor(this.SyntaxNode, unmanagedCallingConventionList));
        }
    }
}


text:
DEFINE_HASHTABLE(table, 9);

struct person {
	const char *name;
	struct hnode hnode;
};

int
main(int argc, char *argv[])
{
	hash_init(table);

	struct person daniel  = { .name = "Daniel",  .hnode = HNODE_INIT };
	struct person daniela = { .name = "Daniela", .hnode = HNODE_INIT };
	struct person adam    = { .name = "Adam",    .hnode = HNODE_INIT };
	struct person eve     = { .name = "Eve",     .hnode = HNODE_INIT };
	struct person robot   = { .name = "Robot",   .hnode = HNODE_INIT };

	hash_add(table, &daniel.hnode, hash_string(daniel.name));
	hash_add(table, &daniela.hnode, hash_string(daniela.name));
	hash_add(table, &adam.hnode, hash_string(adam.name));
	hash_add(table, &eve.hnode, hash_string(eve.name));
	hash_add(table, &robot.hnode, hash_string(robot.name));

	return 0;
}


text:
#include "pch.hpp"
#include "tex/field_type.hpp"

/*!! include 'tex/field_type' !! 68 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */

namespace be::gfx::tex {

///////////////////////////////////////////////////////////////////////////////
bool is_valid(FieldType constant) noexcept {
   switch (constant) {
      case FieldType::none:
      case FieldType::unorm:
      case FieldType::snorm:
      case FieldType::uint:
      case FieldType::sint:
      case FieldType::ufloat:
      case FieldType::sfloat:
      case FieldType::expo:
         return true;
      default:
         return false;
   }
}

///////////////////////////////////////////////////////////////////////////////
const char* field_type_name(FieldType constant) noexcept {
   switch (constant) {
      case FieldType::none:   return "none";
      case FieldType::unorm:  return "unorm";
      case FieldType::snorm:  return "snorm";
      case FieldType::uint:   return "uint";
      case FieldType::sint:   return "sint";
      case FieldType::ufloat: return "ufloat";
      case FieldType::sfloat: return "sfloat";
      case FieldType::expo:   return "expo";
      default:
         return "?";
   }
}

///////////////////////////////////////////////////////////////////////////////
std::array<const FieldType, 8> field_type_values() noexcept {
   return ::be::EnumTraits<FieldType>::values<>();
}

///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, FieldType constant) {
   if (is_valid(constant)) {
      os << field_type_name(constant);
   } else {
      os << static_cast<I64>(static_cast<U8>(constant));
   }
   return os;
}

///////////////////////////////////////////////////////////////////////////////
bool is_unsigned(FieldType constant) noexcept {
   switch (constant) {
      case FieldType::unorm:  return true;
      case FieldType::uint:   return true;
      case FieldType::ufloat: return true;
      default:
         return false;
   }
}

} // be::gfx::tex

/* ######################### END OF GENERATED CODE ######################### */


text:
// Copyright 2022 The Oppia 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.

/**
 * @fileoverview Page object for the subscription dashboard,
 * for use in WebdriverIO tests.
 */
var action = require('./action.js');
var waitFor = require('./waitFor.js');

var SubscriptionDashboardPage = function() {
  var subscriptionButton = $('.e2e-test-subscription-button');
  var subscribeLabel = $('.e2e-test-subscribe-label');
  var subscriptionNameElement = $('.e2e-test-subscription-name');
  var subscriptionNameSelector = function() {
    return $$('.e2e-test-subscription-name');
  };
  var unsubscribeLabel = $('.e2e-test-unsubscribe-label');

  this.navigateToUserSubscriptionPage = async function(userName) {
    await browser.url('/profile/' + userName);
    await waitFor.pageToFullyLoad();
  };

  this.expectSubscriptionFirstNameToMatch = async function(name) {
    await waitFor.visibilityOf(
      subscriptionNameElement, 'First Subscriber Name is not visible');
    var subscriptionName = await subscriptionNameSelector();
    var firstSubscriberNameElem = subscriptionName[0];
    expect(await firstSubscriberNameElem.getText()).toMatch(name);
  };

  this.expectSubscriptionLastNameToMatch = async function(name) {
    await waitFor.visibilityOf(
      subscriptionNameElement, 'Last Subscriber Name is not visible');
    var subscriptionName = await subscriptionNameSelector();
    var lastElement = subscriptionName.length - 1;
    var lastSubscriberNameElem = subscriptionName[lastElement];
    expect(await lastSubscriberNameElem.getText()).toMatch(name);
  };

  this.expectSubscriptionCountToEqual = async function(value) {
    await waitFor.visibilityOf(
      subscriptionNameElement,
      'Subscriber Name Card takes too long to appear');
    var subscriptionName = await subscriptionNameSelector();
    expect(subscriptionName.length).toEqual(value);
  };

  this.navigateToSubscriptionButton = async function() {
    await waitFor.elementToBeClickable(
      subscriptionButton, 'Subscription button is not clickable');
    var subscribeButtonStatusBeforeClick = await subscriptionButton.getText();
    await action.click('Subscription Button', subscriptionButton);
    if (subscribeButtonStatusBeforeClick === 'SUBSCRIBE') {
      await waitFor.visibilityOf(
        unsubscribeLabel,
        'Unsubscribe button is not visible.');
    } else {
      await waitFor.visibilityOf(
        subscribeLabel,
        'Subscribe button is not visible.');
    }
  };
};

exports.SubscriptionDashboardPage = SubscriptionDashboardPage;


text:
using mesos::internal::master::allocator::DRFSorter;

using std::list;
using std::string;

namespace mesos {
namespace internal {
namespace tests {

TEST(SorterTest, DRFSorter)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  Resources totalResources = Resources::parse("cpus:100;mem:100").get();
  sorter.add(slaveId, totalResources);

  sorter.add("a");
  Resources aResources = Resources::parse("cpus:5;mem:5").get();
  sorter.allocated("a", slaveId, aResources);

  Resources bResources = Resources::parse("cpus:6;mem:6").get();
  sorter.add("b");
  sorter.allocated("b", slaveId, bResources);

  // shares: a = .05, b = .06
  EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());

  Resources cResources = Resources::parse("cpus:1;mem:1").get();
  sorter.add("c");
  sorter.allocated("c", slaveId, cResources);

  Resources dResources = Resources::parse("cpus:3;mem:1").get();
  sorter.add("d");
  sorter.allocated("d", slaveId, dResources);

  // shares: a = .05, b = .06, c = .01, d = .03
  EXPECT_EQ(list<string>({"c", "d", "a", "b"}), sorter.sort());

  sorter.remove("a");
  Resources bUnallocated = Resources::parse("cpus:4;mem:4").get();
  sorter.unallocated("b", slaveId, bUnallocated);

  // shares: b = .02, c = .01, d = .03
  EXPECT_EQ(list<string>({"c", "b", "d"}), sorter.sort());

  Resources eResources = Resources::parse("cpus:1;mem:5").get();
  sorter.add("e");
  sorter.allocated("e", slaveId, eResources);

  Resources removedResources = Resources::parse("cpus:50;mem:0").get();
  sorter.remove(slaveId, removedResources);
  // total resources is now cpus = 50, mem = 100

  // shares: b = .04, c = .02, d = .06, e = .05
  EXPECT_EQ(list<string>({"c", "b", "e", "d"}), sorter.sort());

  Resources addedResources = Resources::parse("cpus:0;mem:100").get();
  sorter.add(slaveId, addedResources);
  // total resources is now cpus = 50, mem = 200

  Resources fResources = Resources::parse("cpus:5;mem:1").get();
  sorter.add("f");
  sorter.allocated("f", slaveId, fResources);

  Resources cResources2 = Resources::parse("cpus:0;mem:15").get();
  sorter.allocated("c", slaveId, cResources2);

  // shares: b = .04, c = .08, d = .06, e = .025, f = .1
  EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());

  EXPECT_TRUE(sorter.contains("b"));

  EXPECT_FALSE(sorter.contains("a"));

  EXPECT_EQ(5, sorter.count());

  sorter.deactivate("d");

  EXPECT_TRUE(sorter.contains("d"));

  EXPECT_EQ(list<string>({"e", "b", "c", "f"}), sorter.sort());

  EXPECT_EQ(5, sorter.count());

  sorter.activate("d");

  EXPECT_EQ(list<string>({"e", "b", "d", "c", "f"}), sorter.sort());
}

TEST(SorterTest, WDRFSorter)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  sorter.add(slaveId, Resources::parse("cpus:100;mem:100").get());

  sorter.add("a");

  sorter.allocated("a", slaveId, Resources::parse("cpus:5;mem:5").get());

  sorter.add("b", 2);
  sorter.allocated("b", slaveId, Resources::parse("cpus:6;mem:6").get());

  // shares: a = .05, b = .03
  EXPECT_EQ(list<string>({"b", "a"}), sorter.sort());

  sorter.add("c");
  sorter.allocated("c", slaveId, Resources::parse("cpus:4;mem:4").get());

  // shares: a = .05, b = .03, c = .04
  EXPECT_EQ(list<string>({"b", "c", "a"}), sorter.sort());

  sorter.add("d", 10);
  sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:20").get());

  // shares: a = .05, b = .03, c = .04, d = .02
  EXPECT_EQ(list<string>({"d", "b", "c", "a"}), sorter.sort());

  sorter.remove("b");

  EXPECT_EQ(list<string>({"d", "c", "a"}), sorter.sort());

  sorter.allocated("d", slaveId, Resources::parse("cpus:10;mem:25").get());

  // shares: a = .05, c = .04, d = .045
  EXPECT_EQ(list<string>({"c", "d", "a"}), sorter.sort());

  sorter.add("e", .1);
  sorter.allocated("e", slaveId, Resources::parse("cpus:1;mem:1").get());

  // shares: a = .05, c = .04, d = .045, e = .1
  EXPECT_EQ(list<string>({"c", "d", "a", "e"}), sorter.sort());

  sorter.remove("a");

  EXPECT_EQ(list<string>({"c", "d", "e"}), sorter.sort());
}

TEST(SorterTest, WDRFSorterUpdateWeight)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  Resources totalResources = Resources::parse("cpus:100;mem:100").get();

  sorter.add(slaveId, totalResources);

  sorter.add("a");
  sorter.allocated("a", slaveId, Resources::parse("cpus:5;mem:5").get());

  sorter.add("b");
  sorter.allocated("b", slaveId, Resources::parse("cpus:6;mem:6").get());

  // shares: a = .05, b = .06
  EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());

  // Increase b's  weight to flip the sort order.
  sorter.update("b", 2);

  // shares: a = .05, b = .03
  EXPECT_EQ(list<string>({"b", "a"}), sorter.sort());
}

// Some resources are split across multiple resource objects (e.g.
// persistent volumes). This test ensures that the shares for these
// are accounted correctly.
TEST(SorterTest, SplitResourceShares)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  sorter.add("a");
  sorter.add("b");

  Resource disk1 = Resources::parse("disk", "5", "*").get();
  disk1.mutable_disk()->mutable_persistence()->set_id("ID2");
  disk1.mutable_disk()->mutable_volume()->set_container_path("data");

  Resource disk2 = Resources::parse("disk", "5", "*").get();
  disk2.mutable_disk()->mutable_persistence()->set_id("ID2");
  disk2.mutable_disk()->mutable_volume()->set_container_path("data");

  sorter.add(
      slaveId,
      Resources::parse("cpus:100;mem:100;disk:95").get() + disk1 + disk2);

  // Now, allocate resources to "a" and "b". Note that "b" will have
  // more disk if the shares are accounted correctly!
  sorter.allocated(
      "a", slaveId, Resources::parse("cpus:9;mem:9;disk:9").get());
  sorter.allocated(
      "b", slaveId, Resources::parse("cpus:9;mem:9").get() + disk1 + disk2);

  EXPECT_EQ(list<string>({"a", "b"}), sorter.sort());
}

TEST(SorterTest, UpdateAllocation)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  sorter.add("a");
  sorter.add("b");

  sorter.add(slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());

  sorter.allocated(
      "a", slaveId, Resources::parse("cpus:10;mem:10;disk:10").get());

  // Construct an offer operation.
  Resource volume = Resources::parse("disk", "5", "*").get();
  volume.mutable_disk()->mutable_persistence()->set_id("ID");
  volume.mutable_disk()->mutable_volume()->set_container_path("data");

  // Compute the updated allocation.
  Resources oldAllocation = sorter.allocation("a", slaveId);
  Try<Resources> newAllocation = oldAllocation.apply(CREATE(volume));
  ASSERT_SOME(newAllocation);

  // Update the resources for the client.
  sorter.update("a", slaveId, oldAllocation, newAllocation.get());

  hashmap<SlaveID, Resources> allocation = sorter.allocation("a");
  EXPECT_EQ(1u, allocation.size());
  EXPECT_EQ(newAllocation.get(), allocation[slaveId]);
  EXPECT_EQ(newAllocation.get(), sorter.allocation("a", slaveId));
}

// We aggregate resources from multiple slaves into the sorter.
// Since non-scalar resources don't aggregate well across slaves,
// we need to keep track of the SlaveIDs of the resources. This
// tests that no resources vanish in the process of aggregation
// by inspecting the result of 'allocation'.
TEST(SorterTest, MultipleSlaves)
{
  DRFSorter sorter;

  SlaveID slaveA;
  slaveA.set_value("agentA");

  SlaveID slaveB;
  slaveB.set_value("agentB");

  sorter.add("framework");

  Resources slaveResources =
    Resources::parse("cpus:2;mem:512;ports:[31000-32000]").get();

  sorter.add(slaveA, slaveResources);
  sorter.add(slaveB, slaveResources);

  sorter.allocated("framework", slaveA, slaveResources);
  sorter.allocated("framework", slaveB, slaveResources);

  EXPECT_EQ(2u, sorter.allocation("framework").size());
  EXPECT_EQ(slaveResources, sorter.allocation("framework", slaveA));
  EXPECT_EQ(slaveResources, sorter.allocation("framework", slaveB));
}

// We aggregate resources from multiple slaves into the sorter. Since
// non-scalar resources don't aggregate well across slaves, we need to
// keep track of the SlaveIDs of the resources. This tests that no
// resources vanish in the process of aggregation by performing update
// allocations from unreserved to reserved resources.
TEST(SorterTest, MultipleSlavesUpdateAllocation)
{
  DRFSorter sorter;

  SlaveID slaveA;
  slaveA.set_value("agentA");

  SlaveID slaveB;
  slaveB.set_value("agentB");

  sorter.add("framework");

  Resources slaveResources =
    Resources::parse("cpus:2;mem:512;disk:10;ports:[31000-32000]").get();

  sorter.add(slaveA, slaveResources);
  sorter.add(slaveB, slaveResources);

  sorter.allocated("framework", slaveA, slaveResources);
  sorter.allocated("framework", slaveB, slaveResources);

  // Construct an offer operation.
  Resource volume = Resources::parse("disk", "5", "*").get();
  volume.mutable_disk()->mutable_persistence()->set_id("ID");
  volume.mutable_disk()->mutable_volume()->set_container_path("data");

  // Compute the updated allocation.
  Try<Resources> newAllocation = slaveResources.apply(CREATE(volume));
  ASSERT_SOME(newAllocation);

  // Update the resources for the client.
  sorter.update("framework", slaveA, slaveResources, newAllocation.get());
  sorter.update("framework", slaveB, slaveResources, newAllocation.get());

  EXPECT_EQ(2u, sorter.allocation("framework").size());
  EXPECT_EQ(newAllocation.get(), sorter.allocation("framework", slaveA));
  EXPECT_EQ(newAllocation.get(), sorter.allocation("framework", slaveB));
}

// This test verifies that when the total pool of resources is updated
// the sorting order of clients reflects the new total.
TEST(SorterTest, UpdateTotal)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  sorter.add("a");
  sorter.add("b");

  sorter.add(slaveId, Resources::parse("cpus:10;mem:100").get());

  // Dominant share of "a" is 0.2 (cpus).
  sorter.allocated(
      "a", slaveId, Resources::parse("cpus:2;mem:1").get());

  // Dominant share of "b" is 0.1 (cpus).
  sorter.allocated(
      "b", slaveId, Resources::parse("cpus:1;mem:2").get());

  list<string> sorted = sorter.sort();
  ASSERT_EQ(2u, sorted.size());
  EXPECT_EQ("b", sorted.front());
  EXPECT_EQ("a", sorted.back());

  // Update the total resources by removing the previous total and
  // adding back the new total.
  sorter.remove(slaveId, Resources::parse("cpus:10;mem:100").get());
  sorter.add(slaveId, Resources::parse("cpus:100;mem:10").get());

  // Now the dominant share of "a" is 0.1 (mem) and "b" is 0.2 (mem),
  // which should change the sort order.
  sorted = sorter.sort();
  ASSERT_EQ(2u, sorted.size());
  EXPECT_EQ("a", sorted.front());
  EXPECT_EQ("b", sorted.back());
}

// Similar to the above 'UpdateTotal' test, but tests the scenario
// when there are multiple slaves.
TEST(SorterTest, MultipleSlavesUpdateTotal)
{
  DRFSorter sorter;

  SlaveID slaveA;
  slaveA.set_value("agentA");

  SlaveID slaveB;
  slaveB.set_value("agentB");

  sorter.add("a");
  sorter.add("b");

  sorter.add(slaveA, Resources::parse("cpus:5;mem:50").get());
  sorter.add(slaveB, Resources::parse("cpus:5;mem:50").get());

  // Dominant share of "a" is 0.2 (cpus).
  sorter.allocated(
      "a", slaveA, Resources::parse("cpus:2;mem:1").get());

  // Dominant share of "b" is 0.1 (cpus).
  sorter.allocated(
      "b", slaveB, Resources::parse("cpus:1;mem:3").get());

  list<string> sorted = sorter.sort();
  ASSERT_EQ(2u, sorted.size());
  EXPECT_EQ("b", sorted.front());
  EXPECT_EQ("a", sorted.back());

  // Update the total resources of slaveA by removing the previous
  // total and adding the new total.
  sorter.remove(slaveA, Resources::parse("cpus:5;mem:50").get());
  sorter.add(slaveA, Resources::parse("cpus:95;mem:50").get());

  // Now the dominant share of "a" is 0.02 (cpus) and "b" is 0.03
  // (mem), which should change the sort order.
  sorted = sorter.sort();
  ASSERT_EQ(2u, sorted.size());
  EXPECT_EQ("a", sorted.front());
  EXPECT_EQ("b", sorted.back());
}

// This test verifies that revocable resources are properly accounted
// for in the DRF sorter.
TEST(SorterTest, RevocableResources)
{
  DRFSorter sorter;

  SlaveID slaveId;
  slaveId.set_value("agentId");

  sorter.add("a");
  sorter.add("b");

  // Create a total resource pool of 10 revocable cpus and 10 cpus and
  // 10 MB mem.
  Resource revocable = Resources::parse("cpus", "10", "*").get();
  revocable.mutable_revocable();
  Resources total = Resources::parse("cpus:10;mem:100").get() + revocable;

  sorter.add(slaveId, revocable);

  // Dominant share of "a" is 0.1 (cpus).
  Resources a = Resources::parse("cpus:2;mem:1").get();
  sorter.allocated("a", slaveId, a);

  // Dominant share of "b" is 0.5 (cpus).
  revocable = Resources::parse("cpus", "9", "*").get();
  revocable.mutable_revocable();
  Resources b = Resources::parse("cpus:1;mem:1").get() + revocable;
  sorter.allocated("b", slaveId, b);

  // Check that the allocations are correct.
  ASSERT_EQ(a, sorter.allocation("a", slaveId));
  ASSERT_EQ(b, sorter.allocation("b", slaveId));

  // Check that the sort is correct.
  list<string> sorted = sorter.sort();
  ASSERT_EQ(2u, sorted.size());
  EXPECT_EQ("a", sorted.front());
  EXPECT_EQ("b", sorted.back());
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {


text:
{% extends "withnav_template.html" %}
{% from "components/page-header.html" import page_header %}
{% from "govuk_frontend_jinja/components/back-link/macro.html" import govukBackLink %}

{% block service_page_title %}
  Uploaded letters
{% endblock %}

{% block backLink %}
  {{ govukBackLink({ "href": url_for('main.uploads', service_id=current_service.id) }) }}
{% endblock %}

{% block maincolumn_content %}

  {{ page_header('Uploaded letters') }}

  {% if notifications %}

      {{ total|message_count('letter') }}

      {{ letter_printing_statement }}

  {% else %}

      No letters printing {{ letter_print_day }}

  {% endif %}

  {% include 'views/activity/notifications.html' %}

{% endblock %}


text:
<?php

namespace Relay\Middleware;

/**
 *
 * Handles URL-encoded content.
 *
 * @package relay/middleware
 *
 */
class FormContentHandler extends ContentHandler
{
    /**
     *
     * Checks if the content type is appropriate for handling.
     *
     * @param string $mime The mime type.
     *
     * @return boolean
     *
     */
    protected function isApplicableMimeType($mime)
    {
        return 'application/x-www-form-urlencoded' === $mime;
    }

    /**
     *
     * Parses the request body.
     *
     * @param string $body The request body.
     *
     * @return mixed
     *
     * @uses throwException()
     *
     */
    protected function getParsedBody($body)
    {
        parse_str($body, $parsed);
        return $parsed;
    }
}


text:
\documentclass[a4paper, 12pt]{scrartcl}

%===============================================================================
% Packages
%===============================================================================
\usepackage{fontspec}
\usepackage{geometry}
\usepackage[ngerman]{babel} % Use new german language definition
\usepackage{hyperref} % Hyperlinks in PDFs
\usepackage{amsmath, amsfonts, amssymb} % Math packages
\usepackage{graphicx} % For Graphics
\usepackage{xcolor} % For coloring texts
\usepackage{times} % Times New Roman Font
\usepackage{tikz} % The TikZ vector graphic library
\usepackage{fancyhdr} % Fancy headings
\usepackage{nameref} % References for names instead of numbers
\usepackage[absolute]{textpos} % Absolute positioning
\usepackage{titlesec} % Customizable ((Sub)Sub)Sections
\usepackage[titles]{tocloft} % Customizable ToC, LoF, …
\usepackage{pdfpages} % Embedding pdfs
\usepackage{wallpaper} % Background images
\usepackage{tikz-er2} % Entity relation diagrams
\usepackage{listings} % Code listings
\usepackage{acronym} % Using acronyms
\usepackage{natbib} % Literature

%===============================================================================
% Tikz-Librarys
%===============================================================================
\usetikzlibrary{positioning}
\usetikzlibrary{shadows}

\tikzstyle{every node} = [font=\sffamily]
\tikzstyle{every entity} = [top color=kiba!10, bottom color=kiba!70,
                            draw=kiba!80!black, drop shadow, font=\sffamily\bfseries]
\tikzstyle{every weak entity} = [drop shadow={shadow xshift=.7ex,
                                 shadow yshift=-.7ex}]
\tikzstyle{every attribute} = [top color=white, bottom color=black!10,
                               draw=black!50, node distance=1cm, drop shadow]
\tikzstyle{every relationship} = [top color=white, bottom color=red!20,
                                  draw=red!50!black!100, drop shadow, font=\sffamily\itshape]
\tikzstyle{cty} = [auto, font=\sffamily\footnotesize]
\tikzstyle{every isa} = [top color=white, bottom color=green!20,
                         draw=green!50!black!100, drop shadow]

%===============================================================================
% BibTeX
%===============================================================================
\makeatletter
\newcommand{\bibstyle@dinat}%
	{\bibpunct{(}{)}{;}{a}{}{,~}%
		\gdef\NAT@biblabelnum##1{\textbf{##1}}}
\makeatother

%===============================================================================
% Listings
%===============================================================================
\lstset{
	emph={KBABranchDao, KBAAccountDao, KBACustomerDao, KBATransactionDao, KBAExchangeRateDao, KBACustomerDao, KBACreditRatingDao, KBAMessageDao, KBAAuth, KBADependencyInjector, KibaTests, KBABootstrap},
	emph={[2]NSString, XCTAssert},
	language=[Objective]C,
	morekeywords={new,@,},
	backgroundcolor=\color{black!3},
	columns=fullflexible,
	basicstyle=\ttfamily\footnotesize,
	keywordstyle=\bfseries\ttfamily\color{blue!50!red!80!black},
	stringstyle=\color{red!70!black}\ttfamily,
	identifierstyle=\ttfamily\itshape,
	commentstyle=\color{green!30!black}\ttfamily\itshape,
	emphstyle={\color{orange!70!black}\bfseries\texttt},
	emphstyle={[2]\color{green!60!blue!50!black}\bfseries\texttt},
	showstringspaces=false,
	flexiblecolumns=false,
	tabsize=4,
	lineskip={-1pt}
}
\makeatletter
\begingroup\let\newcounter\@gobble\let\setcounter\@gobbletwo
  \globaldefs\@ne \let\c@loldepth\@ne
  \newlistof{listings}{lol}{\lstlistlistingname}
\endgroup
\let\l@lstlisting\l@listings
\AtBeginDocument{\addtocontents{lol}{\protect\addvspace{10\p@}}}
\makeatother
\renewcommand{\lstlistoflistings}{\listoflistings}

%===============================================================================
% Definitions
%===============================================================================
%\newcommand{\semantischerAusdruck}[1]{%
%	... was macht das ... #1

\newcommand{\Stichwort}[1]{%
	\textbf{#1}}
\setlength{\parskip}{6pt}
\renewcommand{\headrulewidth}{0pt}
\linespread{1.5}
\geometry{a4paper}
\geometry{left=25mm,right=25mm,bottom=30mm,top=30mm}
\geometry{footnotesep=5mm}
\geometry{headsep=10mm}
\geometry{head=10mm}
\geometry{bindingoffset=0mm}
\definecolor{kiba}{HTML}{41707C}
\newcommand{\pre}[1]{%
	\texttt{#1}}
\renewcommand\UrlFont{}

%===============================================================================
% Collaborative
%===============================================================================
\definecolor{markus}{HTML}{FF3118}
\definecolor{alex}{HTML}{3152A5}
\definecolor{julius}{HTML}{639C18}
\definecolor{marco}{HTML}{844D18}
\definecolor{michael}{HTML}{A50063}
\definecolor{corny}{HTML}{0084A5}

\makeatletter
\def\name@markus{Markus Fasselt}
\def\name@alex{Alexander Droste}
\def\name@julius{Julius Wulk}
\def\name@marco{Marco F. Jendryczko}
\def\name@michael{Michael Schaarschmidt}
\def\name@corny{Konstantin S. M. Möllers}
\newcommand{\currentAuthor}{kiba}
\newcommand{\authoredSection}[2]{%
	\renewcommand{\currentAuthor}{#1}%
	\pagebreak
	\section[#2]{#2 {\normalfont\sffamily\small von \csname name@#1\endcsname}}}
\makeatother
\renewcommand{\lstlistingname}{Programmausdruck}
\renewcommand{\lstlistlistingname}{Programmausdrucksverzeichnis}

%===============================================================================
% Head / Foot
%===============================================================================
\pagestyle{fancy}
\fancyhf{}
\makeatletter
\fancyhead[L]{}
\fancyhead[R]{\sffamily\itshape Projektbericht "KiBa"-App}
\fancyfoot[C]{}
\fancyfoot[R]{\sffamily\thepage}
\makeatother

%===============================================================================
% Font
%===============================================================================
\setmainfont{TeX Gyre Termes}
\setsansfont[
	Extension = .ttf,
	Path = Fonts/,
	BoldFont = TheSansUHHBold,
	BoldItalicFont = TheSansUHHBolditalic,
	ItalicFont = TheSansUHHRegularItalic
]{TheSansUHHRegular}
\setmonofont[
	Extension = .otf,
	Path = Fonts/,
	BoldFont = lmmonolt10-bold,
	BoldItalicFont = lmmonolt10-boldoblique,
	ItalicFont = lmmonolt10-oblique
]{lmmono12-regular}
\defaultfontfeatures{Ligatures=TeX}

%===============================================================================
% Sections
%===============================================================================
\titleformat{\section}[hang]{\Large\sffamily\bfseries\color{\currentAuthor}}{\thesection\quad}{0pt}{}
\titleformat{\subsection}[hang]{\large\sffamily\itshape}{\thesubsection\quad}{0pt}{}
\titleformat{\subsubsection}[hang]{\large\sffamily}{\thesubsubsection\quad}{0pt}{}

%===============================================================================
% Table of Contents
%===============================================================================
\renewcommand{\cftdotsep}{\cftnodots}
\renewcommand{\cftsecfont}{\bfseries\sffamily}
\renewcommand{\cftfigpresnum}{Abb. }
\renewcommand{\cfttabpresnum}{Tab. }
\renewcommand{\cftlistingspresnum}{Prog. }
\renewcommand{\cftfigaftersnum}{:}
\renewcommand{\cfttabaftersnum}{:}
\renewcommand{\cftlistingsaftersnum}{:}
\setlength{\cftfignumwidth}{2cm}
\setlength{\cfttabnumwidth}{2cm}
\setlength{\cftlistingsnumwidth}{2cm}
\setlength{\cftfigindent}{0cm}
\setlength{\cfttabindent}{0cm}
\setlength{\cftbeforelistingsskip}{-2mm}
\setlength{\cftlistingsindent}{0cm}
\setlength{\cftbeforesubsecskip}{-1mm}
\setlength{\cftbeforesubsubsecskip}{-1mm}
\setlength{\cftsubsecindent}{0cm}
\setlength{\cftsubsubsecindent}{0cm}
\def\tocnumwidth{13mm}
\setlength{\cftsecnumwidth}{\tocnumwidth}
\setlength{\cftsubsecnumwidth}{\tocnumwidth}
\setlength{\cftsubsubsecnumwidth}{\tocnumwidth}

%===============================================================================
% Meta Description
%===============================================================================
\author{%
	Alexander Droste\vphantom{yMö}\\[-2pt]
    Markus Fasselt\vphantom{yöM}\\[-2pt]
    Marco F. Jendryczko\vphantom{yMö}\\[-2pt]
    Konstantin S. M. Möllers \vphantom{yMö}\\[-2pt]
    Michael Schaarschmidt\vphantom{yöM}\\[-2pt]
    Julius Wulk\vphantom{yMö}}
\title{Die "KiBa"-App}
\date{Wintersemester 2013/14}
\hypersetup{pdftitle = {Die \glqq{}KiBa\grqq{}-App},
            pdfsubject = {Projektbericht der App},
            pdfauthor = {Droste, Fasselt, Jendryczko, M\"ollers, Schaarschmidt, Wulk},
            pdfcreator = {Gruppe 1 - KiBa},
            pdfproducer = {KiBa App PDF},
            linkbordercolor = {.25390625 .4375 .484375},
            urlbordercolor = {.25390625 .4375 .484375}}

%===============================================================================
% Document
%===============================================================================
\begin{document}

\input{Titlepage}
\newpage

\tableofcontents
\newpage

%===============================================================================
% Listings
%===============================================================================
\phantomsection
\addcontentsline{toc}{section}{\lstlistlistingname}
\lstlistoflistings

%===============================================================================
% Acronyms
%===============================================================================
\section*{Abkürzungsverzeichnis}
\phantomsection
\addcontentsline{toc}{section}{Abkürzungsverzeichnis}
\begin{acronym}[SOAP]
	\acro{DAO}{Data Access Object}
	\acro{REST}{Representational State Transfer}
	\acro{SOAP}{Simple Object Access Protocol}
	\acro{VCS}{Version Control System (Versionsverwaltung)}
\end{acronym}
\newpage

%===============================================================================
% Parts
%===============================================================================
\input{Parts/Einleitung}
\input{Parts/Idee}
\input{Parts/Kontexterkundung}
\input{Parts/UIUX}
\input{Parts/Vorgehen}
\input{Parts/Ergebnis}
\input{Parts/Architektur}
\input{Parts/Toolchain}
\input{Parts/Qualitaetssicherung}
\input{Parts/Fazit}
\newpage
\renewcommand{\currentAuthor}{kiba}

%===============================================================================
% Bibliography
%===============================================================================
\def\mybibname{Literaturverzeichnis}
\renewcommand\bibname{\mybibname}
\renewcommand\refname{\mybibname}
\nocite *
\bibliographystyle{dinat}
\bibliography{Literature}

\end{document}


text:
package pca9685

import (
	"math"
	"sync"
	"time"

	"github.com/golang/glog"
	"github.com/kidoman/embd"
	"github.com/kidoman/embd/util"
)

const (
	clockFreq        = 25000000
	pwmControlPoints = 4096

	mode1RegAddr    = 0x00
	preScaleRegAddr = 0xFE

	pwm0OnLowReg = 0x6

	// inspired by arduino's default freq for analogWrites
	defaultFreq = 490
)

// PCA9685 represents a PCA9685 PWM generator.
type PCA9685 struct {
	Bus  embd.I2CBus
	Addr byte
	Freq int

	initialized bool
	mu          sync.RWMutex
}

// New creates a new PCA9685 interface.
func New(bus embd.I2CBus, addr byte) *PCA9685 {
	return &PCA9685{
		Bus:  bus,
		Addr: addr,
	}
}

func (d *PCA9685) mode1Reg() (byte, error) {
	return d.Bus.ReadByteFromReg(d.Addr, mode1RegAddr)
}

func (d *PCA9685) setup() error {
	d.mu.RLock()
	if d.initialized {
		d.mu.RUnlock()
		return nil
	}
	d.mu.RUnlock()

	d.mu.Lock()
	defer d.mu.Unlock()

	mode1Reg, err := d.mode1Reg()
	if err != nil {
		return err
	}

	glog.V(1).Infof("pca9685: read MODE1 Reg [regAddr: %#02x] Value: [%v]", mode1RegAddr, mode1Reg)

	if err := d.sleep(); err != nil {
		return err
	}

	if d.Freq == 0 {
		d.Freq = defaultFreq
	}
	preScaleValue := byte(math.Floor(float64(clockFreq/(pwmControlPoints*d.Freq))+float64(0.5)) - 1)
	glog.V(1).Infof("pca9685: calculated prescale value = %#02x", preScaleValue)
	if err := d.Bus.WriteByteToReg(d.Addr, preScaleRegAddr, byte(preScaleValue)); err != nil {
		return err
	}
	glog.V(1).Infof("pca9685: prescale value [%#02x] written to PRE_SCALE Reg [regAddr: %#02x]", preScaleValue, preScaleRegAddr)

	if err := d.wake(); err != nil {
		return err
	}

	newmode := ((mode1Reg | 0x01) & 0xDF)
	if err := d.Bus.WriteByteToReg(d.Addr, mode1RegAddr, newmode); err != nil {
		return err
	}

	glog.V(1).Infof("pca9685: new mode [%#02x] [disabling register auto increment] written to MODE1 Reg [regAddr: %#02x]", newmode, mode1RegAddr)

	d.initialized = true

	glog.V(1).Infof("pca9685: driver initialized with pwm freq: %v", d.Freq)

	return nil
}

// SetPwm sets the ON and OFF time registers for pwm signal shaping.
// channel: 0-15
// onTime/offTime: 0-4095
func (d *PCA9685) SetPwm(channel, onTime, offTime int) error {
	if err := d.setup(); err != nil {
		return err
	}

	onTimeLowReg := byte(pwm0OnLowReg + (4 * channel))

	onTimeLow := byte(onTime & 0xFF)
	onTimeHigh := byte(onTime >> 8)
	offTimeLow := byte(offTime & 0xFF)
	offTimeHigh := byte(offTime >> 8)

	if err := d.Bus.WriteByteToReg(d.Addr, onTimeLowReg, onTimeLow); err != nil {
		return err
	}

	glog.V(2).Infof("pca9685: writing on-time low [%#02x] to CHAN%v_ON_L reg [reg: %#02x]", onTimeLow, channel, onTimeLowReg)

	onTimeHighReg := onTimeLowReg + 1
	if err := d.Bus.WriteByteToReg(d.Addr, onTimeHighReg, onTimeHigh); err != nil {
		return err
	}
	glog.V(2).Infof("pca9685: writing on-time high [%#02x] to CHAN%v_ON_H reg [reg: %#02x]", onTimeHigh, channel, onTimeHighReg)

	offTimeLowReg := onTimeHighReg + 1
	if err := d.Bus.WriteByteToReg(d.Addr, offTimeLowReg, offTimeLow); err != nil {
		return err
	}
	glog.V(2).Infof("pca9685: writing off-time low [%#02x] to CHAN%v_OFF_L reg [reg: %#02x]", offTimeLow, channel, offTimeLowReg)

	offTimeHighReg := offTimeLowReg + 1
	if err := d.Bus.WriteByteToReg(d.Addr, offTimeHighReg, offTimeHigh); err != nil {
		return err
	}
	glog.V(2).Infof("pca9685: writing off-time high [%#02x] to CHAN%v_OFF_H reg [reg: %#02x]", offTimeHigh, channel, offTimeHighReg)

	return nil
}

type pwmChannel struct {
	d *PCA9685

	channel int
}

func (p *pwmChannel) SetMicroseconds(us int) error {
	return p.d.setMicroseconds(p.channel, us)
}

// SetAnalog is a convinience method which allows easy manipulation of the PWM
// based on a (0-255) range value.
func (p *pwmChannel) SetAnalog(value byte) error {
	offTime := util.Map(int64(value), 0, 255, 0, pwmControlPoints-1)
	return p.d.SetPwm(p.channel, 0, int(offTime))
}

func (d *PCA9685) ServoChannel(channel int) *pwmChannel {
	return &pwmChannel{d: d, channel: channel}
}

func (d *PCA9685) AnalogChannel(channel int) *pwmChannel {
	return &pwmChannel{d: d, channel: channel}
}

// SetMicroseconds is a convinience method which allows easy servo control.
func (d *PCA9685) setMicroseconds(channel, us int) error {
	offTime := us * d.Freq * pwmControlPoints / 1000000
	return d.SetPwm(channel, 0, offTime)
}

// Close stops the controller and resets mode and pwm controller registers.
func (d *PCA9685) Close() error {
	if err := d.setup(); err != nil {
		return err
	}

	if err := d.sleep(); err != nil {
		return err
	}

	glog.V(1).Infof("pca9685: reset request received")

	if err := d.Bus.WriteByteToReg(d.Addr, mode1RegAddr, 0x00); err != nil {
		return err
	}

	glog.V(1).Infof("pca9685: cleaning up all PWM control registers")

	for regAddr := 0x06; regAddr <= 0x45; regAddr++ {
		if err := d.Bus.WriteByteToReg(d.Addr, byte(regAddr), 0x00); err != nil {
			return err
		}
	}

	if glog.V(1) {
		glog.Infof("pca9685: done Cleaning up all PWM control registers")
		glog.Infof("pca9685: controller reset")
	}

	return nil
}

func (d *PCA9685) sleep() error {
	glog.V(1).Infof("pca9685: sleep request received")

	mode1Reg, err := d.mode1Reg()
	if err != nil {
		return err
	}
	sleepmode := (mode1Reg & 0x7F) | 0x10
	if err := d.Bus.WriteByteToReg(d.Addr, mode1RegAddr, sleepmode); err != nil {
		return err
	}
	if glog.V(1) {
		glog.Infof("pca9685: sleep mode [%#02x] written to MODE1 Reg [regAddr: %#02x]", sleepmode, mode1RegAddr)
		glog.Infoln("pca9685: controller set to Sleep mode")
	}

	return nil
}

// Sleep puts the controller in sleep mode. Does not change the pwm control registers.
func (d *PCA9685) Sleep() error {
	if err := d.setup(); err != nil {
		return err
	}

	return d.sleep()
}

func (d *PCA9685) wake() error {
	glog.V(1).Infoln("pca9685: wake request received")

	mode1Reg, err := d.mode1Reg()
	if err != nil {
		return err
	}
	wakeMode := mode1Reg & 0xEF
	if (mode1Reg & 0x80) == 0x80 {
		if err := d.Bus.WriteByteToReg(d.Addr, mode1RegAddr, wakeMode); err != nil {
			return err
		}
		glog.V(1).Infof("pca9685: wake mode [%#02x] written to MODE1 Reg [regAddr: %#02x]", wakeMode, mode1RegAddr)

		time.Sleep(500 * time.Microsecond)
	}

	restartOpCode := wakeMode | 0x80
	if err := d.Bus.WriteByteToReg(d.Addr, mode1RegAddr, restartOpCode); err != nil {
		return err
	}
	glog.V(1).Infof("pca9685: restart mode [%#02x] written to MODE1 Reg [regAddr: %#02x]", restartOpCode, mode1RegAddr)

	return nil
}

// Wake allows the controller to exit sleep mode and resume with PWM generation.
func (d *PCA9685) Wake() error {
	if err := d.setup(); err != nil {
		return err
	}

	return d.wake()
}


text:
var is_object = require("./../support/is-object");

module.exports = function is_path_invalidation(pathValue) {
    return is_object(pathValue) && (typeof pathValue.invalidated === "Boolean");
};


text:
'use strict';

var Spreadsheet = require('edit-google-spreadsheet');
var extend = require('util')._extend;

module.exports = function (grunt) {

    grunt.registerMultiTask('gss_to_json', 'Read Google Spreadsheet and save as JSON.', function () {
        var options = this.options({
            debug: false,
            prettify: false,
            includeInfo: false,
            headerIsFirstRow: true
        });

        var done = this.async();

        var filename = this.files.pop().dest;

        if (!options.worksheetName && !options.worksheetId) {
            grunt.log.warn("Worksheet name or id must be specified.");
        }

        if (!options.spreadsheetName && !options.spreadsheetId) {
            grunt.log.warn("Spreadsheet name or id must be specified.");
        }
            Spreadsheet.load(
                options,
                function sheetReady(err, spreadsheet) {
                    if (err) {
                        return done(new Error(err));
                    }

                    spreadsheet.receive(function (err, rows, info) {
                        if (err) {
                            return done(new Error(err));
                        }

                        if (!options.spreadsheetId) {
                            grunt.log.writeln('For better performance, set spreadsheetId "' + info.spreadsheetId + '".');
                        }

                        if (!options.worksheetId) {
                            grunt.log.writeln('For better performance, set worksheetId "' + info.worksheetId + '".');
                        }

                        var header = extend(rows["1"]);
                        if (header) {
                            delete header["1"];
                        }
                        var tmp = [];
                        Object.keys(header).map(function (key) {
                            tmp.push(header[key]);
                        });

                        if (options.headerIsFirstRow) {
                            delete rows["1"];
                        }

                        var data = [];
                        tmp.map(function (i) {
                            data[i] = {};
                            Object.keys(rows).map(function (row) {
                                    var token = rows[row]['1'].trim().toLowerCase().split(".").join("_").split("-").join("_");
                                    var translate = rows[row][tmp.indexOf(i) + 2];
                                    var obj = {};
                                    obj[token] = translate;
                                    data[i][token] = translate;
                                }
                            );
                        });

                        tmp.forEach(function (i) {
                            grunt.file.write(filename + "/" + i + ".json", JSON.stringify(data[i]));
                            grunt.log.writeln('Spreadsheet data written to "' + filename + '/' + i + '.json".');
                        });

                        done(data);
                    });
                });
        });
};


text:
description: Like find_field, but requires that field_name be unique.

<meta itemprop="name" content="recsim_ng.core.network.find_unique_field" />
<meta itemprop="path" content="Stable" />

# recsim_ng.core.network.find_unique_field

View
source

Like `find_field`, but requires that `field_name` be unique.

recsim_ng.core.network.find_unique_field(
    network_value: recsim_ng.core.network.NetworkValue,
    field_name: Text
) -> Tuple[Text, FieldValue]

<colgroup><col width="214px"><col></colgroup>

Args

`network_value`

A `NetworkValue`; see `Network`.

`field_name`

The name of a `Value` field.

<colgroup><col width="214px"><col></colgroup>

Returns

A pair of (1) the `Variable` in `network_value` with a field named
`field_name` and (2) the value of that field.

<colgroup><col width="214px"><col></colgroup>

Raises

`ValueError`

If there is not exactly one `Variable` in `network_value` that
has a field named `field_name`.


text:
<!--
 Copyright 2020 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.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<FlowCallout name="Shared.Logging">
    <SharedFlowBundle>logging-v1</SharedFlowBundle>
</FlowCallout>


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

$lang['version_not_supported'] = 'CodeIgniter version is not supported by DevelBar,Please check %s for update.';
$lang['sec'] = 'sec';
$lang['request'] = 'Request';
$lang['method'] = 'Method';
$lang['controller'] = 'Controller';
$lang['action'] = 'Action';
$lang['function'] = 'Function';
$lang['parameters'] = 'Parameters';
$lang['database'] = 'Database';
$lang['total_execution_time'] = 'Total Execution Time';
$lang['no_queries'] = 'No queries were run';
$lang['benchmarks'] = 'Benchmarks';
$lang['hooks'] = 'Hooks';
$lang['libraries'] = 'Libraries';
$lang['config'] = 'Configuration';
$lang['session'] = 'Session';
$lang['helpers'] = 'Helpers';
$lang['views'] = 'Views';
$lang['models'] = 'Models';
$lang['memory_usage'] = 'Memory usage';
$lang['ci_version'] = 'CodeIgniter version : %s';
$lang['info'] = 'Info';
$lang['update_message'] = 'Update is available to %s';
$lang['develbar_version'] = 'DevelBar version : %s';
$lang['php_version'] = 'PHP version : %s';
$lang['default_language'] = 'Default language : %s';


text:
namespace P01_HospitalDatabase.Data.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public class Medicament
    {
        //[Key]
        public int MedicamentId { get; set; }

        //[Required]
        //[MaxLength(50)]
        public string Name { get; set; }

        public ICollection<PatientMedicament> Prescriptions { get; set; } = new List<PatientMedicament>();
    }
}


text:
#import "NSObject.h"

#import "TSKAVPlayerControllerDelegate-Protocol.h"

@class AVQueuePlayer, KNSoundtrack, TSKAVQueuePlayerController;

// Not exported
@interface KNPlaybackAudioController : NSObject <TSKAVPlayerControllerDelegate>
{
    KNSoundtrack *mSoundtrack;
    AVQueuePlayer *mAudioPlayer;
    TSKAVQueuePlayerController *mPlayerController;
    unsigned int mAudioPlaybackIsQueued:1;
    unsigned int mIsObservingPlayerItemStatus:1;
    _Bool mIsPlaying;
    _Bool mIsPaused;
}

@property(readonly, nonatomic, getter=isPlaying) _Bool playing; // @synthesize playing=mIsPlaying;
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4;
- (void)playbackDidStopForPlayerController:(id)arg1;
- (void)playerController:(id)arg1 playbackDidFailWithError:(id)arg2;
- (void)p_stopAudioPlayback;
- (void)p_tearDownAudioPlayback;
- (void)p_startAudioPlayback;
- (void)p_initAudioPlaybackAtMediaIndex:(unsigned long long)arg1;
- (void)resume;
- (void)pause;
- (void)interruptAndReset;
- (void)audioPlayerDidFinishPlaying:(id)arg1 successfully:(_Bool)arg2;
- (void)stop;
- (void)startAtMediaIndex:(unsigned long long)arg1 time:(double)arg2;
- (void)start;
- (void)dealloc;
- (id)initWithSoundtrack:(id)arg1;

@end


text:
            {{A.title}} Score: {{A.score}} out of {{A.maxPoints}}.

                Details of question-wise score will
                be accessible only after due date of this assessment.

Q.{{$index + 1}} {{q.points}} points.

                        <input disabled type="checkbox" ng-model="opt.marked"/> {{opt.answer}}

                    <input disabled type="text" ng-model="opt.response" ng-show="q.type === 'FTXT'"/>

                        Correct
                        ({{q.feedback}})