text:
import uuid
from datetime import datetime, timedelta
from functools import partial

import pytest
from freezegun import freeze_time
from sqlalchemy.exc import IntegrityError

from app.dao.jobs_dao import (
    can_letter_job_be_cancelled,
    dao_cancel_letter_job,
    dao_create_job,
    dao_get_future_scheduled_job_by_id_and_service_id,
    dao_get_job_by_service_id_and_job_id,
    dao_get_jobs_by_service_id,
    dao_get_jobs_older_than_data_retention,
    dao_get_notification_outcomes_for_job,
    dao_set_scheduled_jobs_to_pending,
    dao_update_job,
    find_jobs_with_missing_rows,
    find_missing_row_for_job,
)
from app.models import (
    EMAIL_TYPE,
    JOB_STATUS_FINISHED,
    LETTER_TYPE,
    SMS_TYPE,
    Job,
)
from tests.app.db import (
    create_job,
    create_notification,
    create_service,
    create_service_contact_list,
    create_template,
)

def test_should_count_of_statuses_for_notifications_associated_with_job(sample_template, sample_job):
    create_notification(sample_template, job=sample_job, status="created")
    create_notification(sample_template, job=sample_job, status="created")
    create_notification(sample_template, job=sample_job, status="created")
    create_notification(sample_template, job=sample_job, status="sending")
    create_notification(sample_template, job=sample_job, status="delivered")

    results = dao_get_notification_outcomes_for_job(sample_template.service_id, sample_job.id)
    assert {row.status: row.count for row in results} == {
        "created": 3,
        "sending": 1,
        "delivered": 1,
    }

def test_should_return_zero_length_array_if_no_notifications_for_job(sample_service, sample_job):
    assert len(dao_get_notification_outcomes_for_job(sample_job.id, sample_service.id)) == 0

def test_should_return_notifications_only_for_this_job(sample_template):
    job_1 = create_job(sample_template)
    job_2 = create_job(sample_template)

    create_notification(sample_template, job=job_1, status="created")
    create_notification(sample_template, job=job_2, status="sent")

    results = dao_get_notification_outcomes_for_job(sample_template.service_id, job_1.id)
    assert {row.status: row.count for row in results} == {"created": 1}

def test_should_return_notifications_only_for_this_service(sample_notification_with_job):
    other_service = create_service(service_name="one")
    other_template = create_template(service=other_service)
    other_job = create_job(other_template)

    create_notification(other_template, job=other_job)

    assert len(dao_get_notification_outcomes_for_job(sample_notification_with_job.service_id, other_job.id)) == 0
    assert len(dao_get_notification_outcomes_for_job(other_service.id, sample_notification_with_job.id)) == 0

def test_create_sample_job(sample_template):
    assert Job.query.count() == 0

    job_id = uuid.uuid4()
    data = {
        "id": job_id,
        "service_id": sample_template.service.id,
        "template_id": sample_template.id,
        "template_version": sample_template.version,
        "original_file_name": "some.csv",
        "notification_count": 1,
        "created_by": sample_template.created_by,
    }

    job = Job(**data)
    dao_create_job(job)

    assert Job.query.count() == 1
    job_from_db = Job.query.get(job_id)
    assert job == job_from_db
    assert job_from_db.notifications_delivered == 0
    assert job_from_db.notifications_failed == 0

def test_get_job_by_id(sample_job):
    job_from_db = dao_get_job_by_service_id_and_job_id(sample_job.service.id, sample_job.id)
    assert sample_job == job_from_db

def test_get_jobs_for_service(sample_template):
    one_job = create_job(sample_template)

    other_service = create_service(service_name="other service")
    other_template = create_template(service=other_service)
    other_job = create_job(other_template)

    one_job_from_db = dao_get_jobs_by_service_id(one_job.service_id).items
    other_job_from_db = dao_get_jobs_by_service_id(other_job.service_id).items

    assert len(one_job_from_db) == 1
    assert one_job == one_job_from_db[0]

    assert len(other_job_from_db) == 1
    assert other_job == other_job_from_db[0]

    assert one_job_from_db != other_job_from_db

def test_get_jobs_for_service_with_limit_days_param(sample_template):
    one_job = create_job(sample_template)
    old_job = create_job(sample_template, created_at=datetime.now() - timedelta(days=8))

    jobs = dao_get_jobs_by_service_id(one_job.service_id).items

    assert len(jobs) == 2
    assert one_job in jobs
    assert old_job in jobs

    jobs_limit_days = dao_get_jobs_by_service_id(one_job.service_id, limit_days=7).items
    assert len(jobs_limit_days) == 1
    assert one_job in jobs_limit_days
    assert old_job not in jobs_limit_days

@freeze_time("2017-06-10")
def test_get_jobs_for_service_with_limit_days_edge_case(sample_template):
    one_job = create_job(sample_template)
    just_after_midnight_job = create_job(sample_template, created_at=datetime(2017, 6, 2, 23, 0, 1))
    just_before_midnight_job = create_job(sample_template, created_at=datetime(2017, 6, 2, 22, 59, 0))

    jobs_limit_days = dao_get_jobs_by_service_id(one_job.service_id, limit_days=7).items
    assert len(jobs_limit_days) == 2
    assert one_job in jobs_limit_days
    assert just_after_midnight_job in jobs_limit_days
    assert just_before_midnight_job not in jobs_limit_days

def test_get_jobs_for_service_in_processed_at_then_created_at_order(notify_db_session, sample_template):
    from_hour = partial(datetime, 2001, 1, 1)

    created_jobs = [
        create_job(sample_template, created_at=from_hour(2), processing_started=None),
        create_job(sample_template, created_at=from_hour(1), processing_started=None),
        create_job(sample_template, created_at=from_hour(1), processing_started=from_hour(4)),
        create_job(sample_template, created_at=from_hour(2), processing_started=from_hour(3)),
    ]

    jobs = dao_get_jobs_by_service_id(sample_template.service.id).items

    assert len(jobs) == len(created_jobs)

    for index in range(0, len(created_jobs)):
        assert jobs[index].id == created_jobs[index].id

def test_get_jobs_for_service_by_contact_list(sample_template):
    contact_list = create_service_contact_list()
    job_1 = create_job(sample_template)
    job_2 = create_job(sample_template, contact_list_id=contact_list.id)

    assert dao_get_jobs_by_service_id(sample_template.service.id).items == [
        job_2,
        job_1,
    ]

    assert dao_get_jobs_by_service_id(sample_template.service.id, contact_list_id=contact_list.id,).items == [
        job_2,
    ]

def test_update_job(sample_job):
    assert sample_job.job_status == "pending"

    sample_job.job_status = "in progress"

    dao_update_job(sample_job)

    job_from_db = Job.query.get(sample_job.id)

    assert job_from_db.job_status == "in progress"

def test_set_scheduled_jobs_to_pending_gets_all_jobs_in_scheduled_state_before_now(sample_template):
    one_minute_ago = datetime.utcnow() - timedelta(minutes=1)
    one_hour_ago = datetime.utcnow() - timedelta(minutes=60)
    job_new = create_job(sample_template, scheduled_for=one_minute_ago, job_status="scheduled")
    job_old = create_job(sample_template, scheduled_for=one_hour_ago, job_status="scheduled")
    jobs = dao_set_scheduled_jobs_to_pending()
    assert len(jobs) == 2
    assert jobs[0].id == job_old.id
    assert jobs[1].id == job_new.id

def test_set_scheduled_jobs_to_pending_gets_ignores_jobs_not_scheduled(sample_template, sample_job):
    one_minute_ago = datetime.utcnow() - timedelta(minutes=1)
    job_scheduled = create_job(sample_template, scheduled_for=one_minute_ago, job_status="scheduled")
    jobs = dao_set_scheduled_jobs_to_pending()
    assert len(jobs) == 1
    assert jobs[0].id == job_scheduled.id

def test_set_scheduled_jobs_to_pending_gets_ignores_jobs_scheduled_in_the_future(sample_scheduled_job):
    jobs = dao_set_scheduled_jobs_to_pending()
    assert len(jobs) == 0

def test_set_scheduled_jobs_to_pending_updates_rows(sample_template):
    one_minute_ago = datetime.utcnow() - timedelta(minutes=1)
    one_hour_ago = datetime.utcnow() - timedelta(minutes=60)
    create_job(sample_template, scheduled_for=one_minute_ago, job_status="scheduled")
    create_job(sample_template, scheduled_for=one_hour_ago, job_status="scheduled")
    jobs = dao_set_scheduled_jobs_to_pending()
    assert len(jobs) == 2
    assert jobs[0].job_status == "pending"
    assert jobs[1].job_status == "pending"

def test_get_future_scheduled_job_gets_a_job_yet_to_send(sample_scheduled_job):
    result = dao_get_future_scheduled_job_by_id_and_service_id(sample_scheduled_job.id, sample_scheduled_job.service_id)
    assert result.id == sample_scheduled_job.id

@freeze_time("2016-10-31 10:00:00")
def test_should_get_jobs_seven_days_old(sample_template):
    """
    Jobs older than seven days are deleted, but only two day's worth (two-day window)
    """
    seven_days_ago = datetime.utcnow() - timedelta(days=7)
    within_seven_days = seven_days_ago + timedelta(seconds=1)

    eight_days_ago = seven_days_ago - timedelta(days=1)

    nine_days_ago = eight_days_ago - timedelta(days=2)
    nine_days_one_second_ago = nine_days_ago - timedelta(seconds=1)

    create_job(sample_template, created_at=seven_days_ago)
    create_job(sample_template, created_at=within_seven_days)
    job_to_delete = create_job(sample_template, created_at=eight_days_ago)
    create_job(sample_template, created_at=nine_days_ago, archived=True)
    create_job(sample_template, created_at=nine_days_one_second_ago, archived=True)

    jobs = dao_get_jobs_older_than_data_retention(notification_types=[sample_template.template_type])

    assert len(jobs) == 1
    assert jobs[0].id == job_to_delete.id

def test_get_jobs_for_service_is_paginated(notify_db_session, sample_service, sample_template):
    with freeze_time("2015-01-01T00:00:00") as the_time:
        for _ in range(10):
            the_time.tick(timedelta(hours=1))
            create_job(sample_template)

    res = dao_get_jobs_by_service_id(sample_service.id, page=1, page_size=2)

    assert res.per_page == 2
    assert res.total == 10
    assert len(res.items) == 2
    assert res.items[0].created_at == datetime(2015, 1, 1, 10)
    assert res.items[1].created_at == datetime(2015, 1, 1, 9)

    res = dao_get_jobs_by_service_id(sample_service.id, page=2, page_size=2)

    assert len(res.items) == 2
    assert res.items[0].created_at == datetime(2015, 1, 1, 8)
    assert res.items[1].created_at == datetime(2015, 1, 1, 7)

@pytest.mark.parametrize(
    "file_name",
    [
        "Test message",
        "Report",
    ],
)
def test_get_jobs_for_service_doesnt_return_test_messages(
    sample_template,
    sample_job,
    file_name,
):
    create_job(
        sample_template,
        original_file_name=file_name,
    )

    jobs = dao_get_jobs_by_service_id(sample_job.service_id).items

    assert jobs == [sample_job]

@freeze_time("2016-10-31 10:00:00")
def test_should_get_jobs_seven_days_old_filters_type(sample_service):
    eight_days_ago = datetime.utcnow() - timedelta(days=8)
    letter_template = create_template(sample_service, template_type=LETTER_TYPE)
    sms_template = create_template(sample_service, template_type=SMS_TYPE)
    email_template = create_template(sample_service, template_type=EMAIL_TYPE)

    job_to_remain = create_job(letter_template, created_at=eight_days_ago)
    create_job(sms_template, created_at=eight_days_ago)
    create_job(email_template, created_at=eight_days_ago)

    jobs = dao_get_jobs_older_than_data_retention(notification_types=[EMAIL_TYPE, SMS_TYPE])

    assert len(jobs) == 2
    assert job_to_remain.id not in [job.id for job in jobs]

@freeze_time("2016-10-31 10:00:00")
def test_should_get_jobs_seven_days_old_by_scheduled_for_date(sample_service):
    six_days_ago = datetime.utcnow() - timedelta(days=6)
    eight_days_ago = datetime.utcnow() - timedelta(days=8)
    letter_template = create_template(sample_service, template_type=LETTER_TYPE)

    create_job(letter_template, created_at=eight_days_ago)
    create_job(letter_template, created_at=eight_days_ago, scheduled_for=eight_days_ago)
    job_to_remain = create_job(letter_template, created_at=eight_days_ago, scheduled_for=six_days_ago)

    jobs = dao_get_jobs_older_than_data_retention(notification_types=[LETTER_TYPE])

    assert len(jobs) == 2
    assert job_to_remain.id not in [job.id for job in jobs]

def assert_job_stat(job, result, sent, delivered, failed):
    assert result.job_id == job.id
    assert result.original_file_name == job.original_file_name
    assert result.created_at == job.created_at
    assert result.scheduled_for == job.scheduled_for
    assert result.template_id == job.template_id
    assert result.template_version == job.template_version
    assert result.job_status == job.job_status
    assert result.service_id == job.service_id
    assert result.notification_count == job.notification_count
    assert result.sent == sent
    assert result.delivered == delivered
    assert result.failed == failed

@freeze_time("2019-06-13 13:00")
def test_dao_cancel_letter_job_cancels_job_and_returns_number_of_cancelled_notifications(sample_letter_template):
    job = create_job(template=sample_letter_template, notification_count=1, job_status="finished")
    notification = create_notification(template=job.template, job=job, status="created")
    result = dao_cancel_letter_job(job)
    assert result == 1
    assert notification.status == "cancelled"
    assert job.job_status == "cancelled"

@freeze_time("2019-06-13 13:00")
def test_can_letter_job_be_cancelled_returns_true_if_job_can_be_cancelled(sample_letter_template):
    job = create_job(template=sample_letter_template, notification_count=1, job_status="finished")
    create_notification(template=job.template, job=job, status="created")
    result, errors = can_letter_job_be_cancelled(job)
    assert result
    assert not errors

@freeze_time("2019-06-13 13:00")
def test_can_letter_job_be_cancelled_returns_false_and_error_message_if_notification_status_sending(
    sample_letter_template,
):
    job = create_job(template=sample_letter_template, notification_count=2, job_status="finished")
    create_notification(template=job.template, job=job, status="sending")
    create_notification(template=job.template, job=job, status="created")
    result, errors = can_letter_job_be_cancelled(job)
    assert not result
    assert errors == "It's too late to cancel sending, these letters have already been sent."

def test_can_letter_job_be_cancelled_returns_false_and_error_message_if_letters_already_sent_to_dvla(
    sample_letter_template,
):
    with freeze_time("2019-06-13 13:00"):
        job = create_job(template=sample_letter_template, notification_count=1, job_status="finished")
        letter = create_notification(template=job.template, job=job, status="created")

    with freeze_time("2019-06-13 17:32"):
        result, errors = can_letter_job_be_cancelled(job)
    assert not result
    assert errors == "It's too late to cancel sending, these letters have already been sent."
    assert letter.status == "created"
    assert job.job_status == "finished"

@freeze_time("2019-06-13 13:00")
def test_can_letter_job_be_cancelled_returns_false_and_error_message_if_not_a_letter_job(sample_template):
    job = create_job(template=sample_template, notification_count=1, job_status="finished")
    create_notification(template=job.template, job=job, status="created")
    result, errors = can_letter_job_be_cancelled(job)
    assert not result
    assert errors == "Only letter jobs can be cancelled through this endpoint. This is not a letter job."

@freeze_time("2019-06-13 13:00")
def test_can_letter_job_be_cancelled_returns_false_and_error_message_if_job_not_finished(sample_letter_template):
    job = create_job(template=sample_letter_template, notification_count=1, job_status="in progress")
    create_notification(template=job.template, job=job, status="created")
    result, errors = can_letter_job_be_cancelled(job)
    assert not result
    assert errors == "We are still processing these letters, please try again in a minute."

@freeze_time("2019-06-13 13:00")
def test_can_letter_job_be_cancelled_returns_false_and_error_message_if_notifications_not_in_db_yet(
    sample_letter_template,
):
    job = create_job(template=sample_letter_template, notification_count=2, job_status="finished")
    create_notification(template=job.template, job=job, status="created")
    result, errors = can_letter_job_be_cancelled(job)
    assert not result
    assert errors == "We are still processing these letters, please try again in a minute."

def test_can_letter_job_be_cancelled_respects_bst(sample_letter_template):
    job = create_job(template=sample_letter_template, created_at=datetime(2020, 4, 9, 23, 30), job_status="finished")
    create_notification(template=job.template, job=job, status="created", created_at=datetime(2020, 4, 9, 23, 32))

    with freeze_time("2020-04-10 10:00"):
        result, errors = can_letter_job_be_cancelled(job)

    assert not errors
    assert result

def test_find_jobs_with_missing_rows(sample_email_template):
    healthy_job = create_job(
        template=sample_email_template,
        notification_count=3,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=20),
    )
    for i in range(0, 3):
        create_notification(job=healthy_job, job_row_number=i)
    job_with_missing_rows = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=20),
    )
    for i in range(0, 4):
        create_notification(job=job_with_missing_rows, job_row_number=i)

    results = find_jobs_with_missing_rows()

    assert len(results) == 1
    assert results[0] == job_with_missing_rows

def test_find_jobs_with_missing_rows_returns_nothing_for_a_job_completed_less_than_10_minutes_ago(
    sample_email_template,
):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=9),
    )
    for i in range(0, 4):
        create_notification(job=job, job_row_number=i)

    results = find_jobs_with_missing_rows()

    assert len(results) == 0

def test_find_jobs_with_missing_rows_returns_nothing_for_a_job_completed_more_that_a_day_ago(sample_email_template):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(days=1),
    )
    for i in range(0, 4):
        create_notification(job=job, job_row_number=i)

    results = find_jobs_with_missing_rows()

    assert len(results) == 0

@pytest.mark.parametrize("status", ["pending", "in progress", "cancelled", "scheduled"])
def test_find_jobs_with_missing_rows_doesnt_return_jobs_that_are_not_finished(sample_email_template, status):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=status,
        processing_finished=datetime.utcnow() - timedelta(minutes=11),
    )
    for i in range(0, 4):
        create_notification(job=job, job_row_number=i)

    results = find_jobs_with_missing_rows()

    assert len(results) == 0

def test_find_missing_row_for_job(sample_email_template):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=11),
    )
    create_notification(job=job, job_row_number=0)
    create_notification(job=job, job_row_number=1)
    create_notification(job=job, job_row_number=3)
    create_notification(job=job, job_row_number=4)

    results = find_missing_row_for_job(job.id, 5)
    assert len(results) == 1
    assert results[0].missing_row == 2

def test_find_missing_row_for_job_more_than_one_missing_row(sample_email_template):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=11),
    )
    create_notification(job=job, job_row_number=0)
    create_notification(job=job, job_row_number=1)
    create_notification(job=job, job_row_number=4)

    results = find_missing_row_for_job(job.id, 5)
    assert len(results) == 2
    assert results[0].missing_row == 2
    assert results[1].missing_row == 3

def test_find_missing_row_for_job_return_none_when_row_isnt_missing(sample_email_template):
    job = create_job(
        template=sample_email_template,
        notification_count=5,
        job_status=JOB_STATUS_FINISHED,
        processing_finished=datetime.utcnow() - timedelta(minutes=11),
    )
    for i in range(0, 5):
        create_notification(job=job, job_row_number=i)

    results = find_missing_row_for_job(job.id, 5)
    assert len(results) == 0

def test_unique_key_on_job_id_and_job_row_number(sample_email_template):
    job = create_job(template=sample_email_template)
    create_notification(job=job, job_row_number=0)
    with pytest.raises(expected_exception=IntegrityError):
        create_notification(job=job, job_row_number=0)

def test_unique_key_on_job_id_and_job_row_number_no_error_if_row_number_for_different_job(sample_email_template):
    job_1 = create_job(template=sample_email_template)
    job_2 = create_job(template=sample_email_template)
    create_notification(job=job_1, job_row_number=0)
    create_notification(job=job_2, job_row_number=0)


text:
foam.CLASS({
  package: 'foam.nanos.google.api.auth',
  name: 'GoogleApiAuthService',
  javaImports: [
    'com.google.api.client.auth.oauth2.Credential',
    'com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp',
    'com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver',
    'com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow',
    'com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets',
    'com.google.api.client.http.javanet.NetHttpTransport',
    'com.google.api.client.json.JsonFactory',
    'com.google.api.client.json.jackson2.JacksonFactory',
    'com.google.api.client.util.store.FileDataStoreFactory',
    'foam.dao.DAO',
    'foam.nanos.app.AppConfig',
    'java.io.FileInputStream',
    'java.io.IOException',
    'java.io.InputStreamReader',
    'javax.servlet.http.HttpServletRequest',
    'java.util.Arrays',
    'java.util.List'
  ],
  constants: [
    {
      name: 'JSON_FACTORY',
      javaType: 'com.google.api.client.json.JsonFactory',
      javaValue: `JacksonFactory.getDefaultInstance();`
    }
  ],
  methods: [
    {
      name: 'getCredentials',
      javaType: 'com.google.api.client.auth.oauth2.Credential',
      args: [
        {
          name: 'x',
          type: 'Context',
        },
        {
          name: 'HTTP_TRANSPORT',
          javaType: 'com.google.api.client.http.javanet.NetHttpTransport'
        },
        {
          name: 'scopes',
          javaType: 'List<String>'
        }
      ],
      javaThrows: [
        'java.io.IOException'
      ],
      javaCode: `
        HttpServletRequest req = (HttpServletRequest)x.get(HttpServletRequest.class);
        GoogleApiCredentials credentialsConfig = (GoogleApiCredentials) ((DAO)getX().get("googleApiCredentialsDAO")).find(req.getServerName());

        if ( credentialsConfig == null )
          return null;
        GoogleClientSecrets.Details details = new GoogleClientSecrets.Details()
                .setClientId(credentialsConfig.getClientId())
                .setClientSecret(credentialsConfig.getClientSecret())
                .setAuthUri(credentialsConfig.getAuthUri())
                .setTokenUri(credentialsConfig.getTokenUri())
                .setRedirectUris(Arrays.asList(credentialsConfig.getRedirectUris()));

        GoogleClientSecrets clientSecrets = new GoogleClientSecrets().setInstalled(details);
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                  HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
                  .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(credentialsConfig.getTokensFolderPath() + "/tokens/")))
                  .build();

        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(credentialsConfig.getPort()).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
      `
    },
    {
      name: 'addHttpTimeout',
      javaType: [
        'com.google.api.client.http.HttpRequestInitializer'
      ],
      args: [
        {
          final: true,
          name: 'requestInitializer',
          javaType: 'com.google.api.client.http.HttpRequestInitializer'
        }
      ],
      javaCode: `
      return new com.google.api.client.http.HttpRequestInitializer() {
        @Override
        public void initialize(com.google.api.client.http.HttpRequest httpRequest) throws IOException {
          requestInitializer.initialize(httpRequest);
          httpRequest.setConnectTimeout(60000);
          httpRequest.setReadTimeout(3 * 60000);
        }
      };
      `
    }
  ]
});

redpajama_set_name: RedPajamaGithub


text:
Chef LWRP to build applications with using [buildpacks](https://devcenter.heroku.com/articles/buildpacks).

## Supported Platforms

* Debian GNU/Linux
* Ubuntu Linux

## Examples

Run `detect` and `compile` against `/var/www/my_app_name`.

```rb
buildpack "my_app_name" do
  buildpack_url "https://github.com/heroku/heroku-buildpack-ruby.git"
  build_dir "/var/www/my_app_name"
  cache_dir "/var/cache/my_app_name"
  env_dir "/var/lib/my_app_name"
end
```

## License and Authors

Copyright 2015 Yamashita, Yuu (yuu@treasure-data.com)

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.


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

package XrefParser::miRBaseParser;

use strict;
use warnings;
use Carp;
use DBI;

use base qw(XrefParser::BaseParser);

sub run {

  my ($self, $ref_arg) = @_;
  my $source_id    = $ref_arg->{source_id};
  my $species_id   = $ref_arg->{species_id};
  my $files        = $ref_arg->{files};
  my $verbose      = $ref_arg->{verbose};

  if((!defined $source_id) or (!defined $species_id) or (!defined $files) ){
    croak "Need to pass source_id, species_id and files as pairs";
  }
  $verbose |=0;

  my $file = @{$files}[0];

  if(!defined($species_id)){
    $species_id = $self->get_species_id_for_filename($file);
  }

  my $xrefs = $self->create_xrefs($source_id, $file, $species_id);
  if(!defined($xrefs)){
    return 1; #error
  }
  # upload
  if(!defined($self->upload_xref_object_graphs($xrefs))){
    return 1;
  }
  return 0; # successfull

}

# --------------------------------------------------------------------------------
# Parse file into array of xref objects

sub create_xrefs {

  my ($self, $source_id, $file, $species_id) = @_;

  my %species2name = $self->species_id2name();
  my @names   = @{$species2name{$species_id}};

  my %name2species_id     = map{ $_=>$species_id } @names;

  my $file_io = $self->get_filehandle($file);
  if ( !defined $file_io ) {
    print STDERR "ERROR: Could not open $file\n";
    return 1;    # 1 is an error
  }

  my @xrefs;

  local $/ = "\n\/\/";

  while ($_ = $file_io->getline()) {

    my $xref;

    my $entry = $_;
    chomp $entry;

    next if (!$entry);

    my ($header, $sequence) = split (/\nSQ/, $entry, 2);
    # remove newlines
    my @seq_lines = split (/\n/, $sequence) if ($sequence);
    # drop the information line
    shift @seq_lines;
    # put onto one line
    $sequence = join("", @seq_lines);
    # make uppercase
    $sequence = uc($sequence);
    # replace Ts for Us
    $sequence =~ s/U/T/g;
    # remove numbers and whitespace
    $sequence =~ s/[\d+,\s+]//g;

#    print "$header\n";
    my ($name) = $header =~ /\nID\s+(\S+)\s+/;
    my ($acc) = $header =~ /\nAC\s+(\S+);\s+/;
    my ($description) = $header =~ /\nDE\s+(.+)\s+stem-loop/;
    my @description_parts = split (/\s+/, $description) if ($description);
    # remove the miRNA identifier
    pop @description_parts;
    my $species =  join(" ", @description_parts);
    $xref->{SEQUENCE_TYPE} = 'dna';
    $xref->{STATUS} = 'experimental';
    $xref->{SOURCE_ID} = $source_id;
    $species = lc $species;
    $species =~ s/ /_/;

    my $species_id_check = $name2species_id{$species};

    next if (!defined($species_id_check));

    # skip xrefs for species that aren't in the species table
    if (defined($species_id) and $species_id == $species_id_check) {

      $xref->{ACCESSION} = $acc;
      $xref->{LABEL} = $name;
      $xref->{DESCRIPTION} = $name;
      $xref->{SEQUENCE} = $sequence;
      $xref->{SPECIES_ID} = $species_id;

      # TODO synonyms, dependent xrefs etc
      push @xrefs, $xref;
    }
  }

  $file_io->close();

  print "Read " . scalar(@xrefs) ." xrefs from $file\n";

  return \@xrefs;

}

1;


text:
import { addStrings } from './vulcan-lib';

addStrings('en', {
  'accounts.error_incorrect_password': 'Incorrect password',
  'accounts.error_email_required': 'Email required',
  'accounts.error_email_already_exists': 'Email already exists',
  'accounts.error_invalid_email': 'Invalid email',
  'accounts.error_minchar': 'Your password is too short',
  'accounts.error_username_required': 'Username required',
  'accounts.error_accounts_': '',
  'accounts.error_unknown': 'Unknown error',
  'accounts.error_user_not_found': 'User not found',
  'accounts.error_username_already_exists': 'Username already exists',
  'accounts.enter_username_or_email': 'Enter username or email',
  'accounts.error_internal_server_error': 'Internal server error',
  'accounts.error_token_expired': 'Invalid password reset token',
  'accounts.username_or_email': 'Username or email',
  'accounts.enter_username': 'Enter username',
  'accounts.username': 'Username',
  'accounts.enter_email': 'Enter email',
  'accounts.email': 'Email',
  'accounts.enter_password': 'Enter password',
  'accounts.password': 'Password',
  'accounts.choose_password': 'Choose password',
  'accounts.change_password': 'Change password',
  'accounts.reset_your_password': 'Reset your password',
  'accounts.set_password': 'Set password',
  'accounts.enter_new_password': 'Enter new password',
  'accounts.new_password': 'New password',
  'accounts.forgot_password': 'Forgot password',
  'accounts.sign_up': 'Sign up',
  'accounts.sign_in': 'Sign in',
  'accounts.sign_out': 'Sign out',
  'accounts.cancel': 'Cancel',
  'accounts.or_use': 'or use',
  'accounts.info_email_sent': 'Email sent.',
  'accounts.info_password_changed': 'Password changed.',
  'accounts.logging_in': 'Logging in…',
  'accounts.email_verified': 'Your email address has been verified.',

  'forms.submit': 'Submit',
  'forms.cancel': 'Cancel',
  'forms.select_option': '-- select option --',
  'forms.delete': 'Delete',
  'forms.delete_confirm': 'Delete document?',
  'forms.revert': 'Revert',
  'forms.confirm_discard': 'Discard changes?',

  'users.profile': 'Profile',
  'users.complete_profile': 'Complete your Profile',
  'users.profile_completed': 'Profile completed.',
  'users.edit_account': 'Edit Account',
  'users.edit_success': 'User "{name}" edited',
  'users.log_in': 'Log In',
  'users.sign_up': 'Sign Up',
  'users.sign_up_log_in': 'Sign Up/Log In',
  'users.log_out': 'Log Out',
  'users.bio': 'Bio',
  'users.displayName': 'Display Name',
  'users.email': 'Email',
  'users.twitterUsername': 'Twitter Username',
  'users.website': 'Website',
  'users.groups': 'Groups',
  'users.avatar': 'Avatar',
  'users.notifications': 'Notifications',
  'users.notifications_users': 'New Users Notifications',
  'users.notifications_posts': 'New Posts Notifications',
  'users.newsletter_subscribeToNewsletter': 'Subscribe to newsletter',
  'users.users_admin': 'Admin',
  'users.admin': 'Admin',
  'users.isAdmin': 'Admin',
  'users.posts': 'Posts',
  'users.upvoted_posts': 'Upvoted Posts',
  'users.please_log_in': 'Please log in',
  'users.please_sign_up_log_in': 'Please sign up or log in',
  'users.cannot_post': 'Sorry, you do not have permission to post at this time',
  'users.cannot_comment': 'Sorry, you do not have permission to comment at this time',
  'users.subscribe': 'Subscribe to this user\'s posts',
  'users.unsubscribe': 'Unsubscribe to this user\'s posts',
  'users.subscribed': `You have subscribed to this user's posts.`,
  'users.unsubscribed': `You have unsubscribed from this user's posts.`,
  'users.subscribers': 'Subscribers',
  'users.delete': 'Delete user',
  'users.delete_confirm': 'Delete this user?',
  'users.email_already_taken': 'This email is already taken: {value}',

  'settings': 'Settings',
  'settings.json_message': 'Note: settings already provided in your settings.json file will be disabled.',
  'settings.edit': 'Edit Settings',
  'settings.edited': 'Settings edited (please reload).',
  'settings.title': 'Title',
  'settings.siteUrl': 'Site URL',
  'settings.description': 'Description',
  'settings.siteImage': 'Site Image',
  'settings.defaultEmail': 'Default Email',
  'settings.scoreUpdate': 'Score Update',
  'settings.postsPerPage': 'Posts Per Page',
  'settings.twitterAccount': 'Twitter Account',
  'settings.facebookPage': 'Facebook Page',
  'settings.locale': 'Locale',
  'settings.requireViewInvite': 'Require View Invite',
  'settings.requirePostInvite': 'Require Post Invite',
  'settings.scoreUpdateInterval': 'Score Update Interval',

  'app.loading': 'Loading…',
  'app.404': 'Sorry, we couldn\'t find what you were looking for.',
  'app.missing_document':  'Sorry, we couldn\'t find the document you were looking for.',
  'app.powered_by': 'Built with Vulcan.js',
  'app.or': 'Or',
  'app.noPermission': 'Sorry, you do not have the permission to do this at this time.',
  'app.operation_not_allowed': 'Sorry, you don\'t have the rights to perform the operation "{value}"',
  'app.document_not_found': 'Document not found (id: {value})',
  'app.disallowed_property_detected': 'Disallowed property detected: {value}',
  'app.something_bad_happened': 'Something bad happened...',
  'app.embedly_not_authorized': 'Invalid Embedly API key provided in the settings file. To find your key, log into https://app.embed.ly -> API',

  'cards.edit': 'Edit',
  'datatable.new': 'New',
  'datatable.edit': 'Edit',

  'admin': 'Admin',
  'notifications': 'Notifications',

  'errors.expectedType': 'Expected a field "{label}" of type {dataType}, got "{value}" instead.',
  'errors.required': 'Field "{label}" is required.',
  'errors.maxString': 'Field "{label}" is limited to {max} characters.',
});


text:
import connection from '../../config/database';

module.exports.register = (server, options, next) => {
  // AIAM? check for manager status....

  async function managerCheck(id) {
    const status = await connection
      .table('employees')
      .filter({ supervisor_userid: id.toUpperCase() })
      .count();

    return await status > 0;
  }

  async function getTeam(id, next) {
    try {
      const field = await managerCheck(id) ? 'userid' : 'supervisor_userid';
      const team = await connection
        .table('employees')
        .filter({ userid: id.toUpperCase() }) // Find requested employee.
        .innerJoin(
          connection
            .table('employees')
            // Filter out any employees on "Secondment". This is from a combination
            // of "actingOrHDAFlag" and "HDA_termination_date".
            .filter(document =>
              connection
                .and(document('actingOrHDAFlag').eq('N'))
                .and(document('HDA_termination_date').ne(''))
                .not())
            // Filter out the requested employee from the team.
            .filter(document =>
              connection
                .expr([id.toUpperCase()])
                .contains(document('userid'))
                .not()),
          (staff, team) =>

            // Equvilent of a self join to return all employees with the same "Manager"
            staff(field).eq(team('supervisor_userid'))

        )
        .zip()
        .orderBy('surname')
        .run();
      if (team) next(null, team);
      else next('error');
    } catch (error) {
      next(error);
    }
  }

  server.method('db.getTeam', getTeam, {});

  next();
};

module.exports.register.attributes = {
  name: 'method.db.getTeam',
};


text:
\hypertarget{uno__runner_8cpp}{
\section{\-C\-:/\-Users/\-Gary/\-Documents/\-School/my-\/random-\/cpp-\/libraries/trunk/projects/graduate/cs6364/semester\-\_\-project/semester\-\_\-project/uno\-\_\-runner.cpp \-File \-Reference}
\label{uno__runner_8cpp}\index{\-C\-:/\-Users/\-Gary/\-Documents/\-School/my-\/random-\/cpp-\/libraries/trunk/projects/graduate/cs6364/semester\-\_\-project/semester\-\_\-project/uno\-\_\-runner.\-cpp@{\-C\-:/\-Users/\-Gary/\-Documents/\-School/my-\/random-\/cpp-\/libraries/trunk/projects/graduate/cs6364/semester\-\_\-project/semester\-\_\-project/uno\-\_\-runner.\-cpp}}
}

\-Contains the functions for running and playign an \-Uno game.

{\ttfamily \#include \char`\"{}uno\-\_\-deck.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-card.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-player.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-ai\-\_\-player.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-human\-\_\-player.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-gstate.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-pstate.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-action.\-h\char`\"{}}\*
{\ttfamily \#include \char`\"{}uno\-\_\-runner.\-h\char`\"{}}\*
{\ttfamily \#include $<$ctime$>$}\*
{\ttfamily \#include $<$algorithm$>$}\*
{\ttfamily \#include $<$iostream$>$}\*

\subsection{\-Detailed \-Description}
\-Contains the functions for running and playign an \-Uno game. \begin{DoxySeeAlso}{\-See also}
\hyperlink{uno__runner_8h}{uno\-\_\-runner.\-h}
\end{DoxySeeAlso}


text:
FactoryGirl.define do
  factory :session_type, class: OpenConferenceWare::SessionType do
    sequence(:title) { |n| "Session Type #{n}" }
    description { |record| "#{record.title} description" }
    duration "45"

    # :belongs_to association
    # * :event
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html SYSTEM "about:legacy-compat">

    <title>phpDox - Test Method</title>
    <link rel="stylesheet" type="text/css" href="../../css/style.css" media="screen"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

/**phpDox

          Overview

          Namespaces

          Classes

          Source

            Overview

            Classes

            Akamai\Open\EdgeGrid

            Client

setMaxBodySize

            Introduction

            Synopsis

            Parameter

            Return

            Tests

            Source

Akamai\Open\EdgeGrid\Client::setMaxBodySize

Set the max body size

Signature

          public function setMaxBodySize(int
        $max_body_size )

Parameters

$max_body_size
                —
                int

Returns

$this

Test Coverage

Information

Coverage: 2/2 Lines (100%)

Tests: 14

Passed: 14 (100%)

Tests

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #0

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #1

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #2

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #3

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #4

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #5

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #6

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #7

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #8

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #9

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #10

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #11

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #12

[ PASSED ] — Akamai\Open\EdgeGrid\Tests\Handler\AuthenticationTest::testMakeAuthHeaderPsr7 with data set #13

      Generated using phpDox 0.8.2-dev - Copyright (C) 2010 - 2016 by Arne Blankerts


text:
Listen to events that bubble up from elements matching the specified `node` selector:
```js
cy.on('tap', 'node', function(evt){
  var node = evt.target;
  console.log( 'tapped ' + node.id() );
});
```

Listen to all tap events that the core receives:

```js
cy.on('tap', function(event){
  // target holds a reference to the originator
  // of the event (core or element)
  var evtTarget = event.target;

  if( evtTarget === cy ){
    console.log('tap on background');
  } else {
    console.log('tap on some element');
  }
});
```


text:
from __future__ import unicode_literals

import abc

import datetime
from django.db import models

# region ODM2 Core models
from django.db.models.query_utils import Q

class ODM2QuerySet(models.QuerySet):
    def for_display(self):
        return self.all()

    for_display.queryset_only = True

class AffiliationQuerySet(ODM2QuerySet):
    def for_display(self):
        return self.select_related('person').prefetch_related('organization')

class OrganizationQuerySet(ODM2QuerySet):
    def exclude_vendors(self):
        return self.exclude(organization_type__in=['Vendor', 'Manufacturer'])

    def only_vendors(self):
        return self.filter(organization_type__in=['Vendor', 'Manufacturer'])

class MethodQuerySet(ODM2QuerySet):
    def instrument_deployment_methods(self):
        return self.filter(method_type='Instrument deployment')

class ActionQuerySet(ODM2QuerySet):
    def deployments(self):
        return self.filter(Q(action_type='Equipment deployment') | Q(action_type='Instrument deployment'))

    def equipment_deployments(self):
        return self.filter(action_type='Equipment deployment')

    def instrument_deployments(self):
        return self.filter(action_type='Instrument deployment')

class ActionByQuerySet(ODM2QuerySet):
    def for_display(self):
        return self.select_related('action').prefetch_related('affiliation__person', 'affiliation__organization')

class FeatureActionQuerySet(ODM2QuerySet):
    def for_display(self):
        return self.select_related('action').prefetch_related('sampling_feature')

    def with_results(self):
        return self.prefetch_related('results__timeseriesresult__values', 'results__variable', 'results__unit')

class RelatedActionManager(models.Manager):
    def get_queryset(self):
        queryset = super(RelatedActionManager, self).get_queryset()
        return queryset.prefetch_related('related_action', 'action')

class ResultManager(models.Manager):
    def get_queryset(self):
        queryset = super(ResultManager, self).get_queryset()
        return queryset.prefetch_related(
            'variable', 'unit', 'taxonomic_classifier', 'processing_level'
        )

class DataLoggerFileManager(models.Manager):
    def get_queryset(self):
        queryset = super(DataLoggerFileManager, self).get_queryset()
        return queryset.prefetch_related('program')

class DataLoggerFileColumnManager(models.Manager):
    def get_queryset(self):
        queryset = super(DataLoggerFileColumnManager, self).get_queryset()
        return queryset.DataLoggerFileColumnManager('result')

# endregion

# region ODM2 Equipment Extension

class EquipmentModelQuerySet(ODM2QuerySet):
    def for_display(self):
        return self.prefetch_related('model_manufacturer')

class InstrumentOutputVariableManager(models.Manager):
    def get_queryset(self):
        queryset = super(InstrumentOutputVariableManager, self).get_queryset()
        return queryset.prefetch_related('model', 'variable', 'instrument_method', 'instrument_raw_output_unit')

class EquipmentManager(models.Manager):
    def get_queryset(self):
        queryset = super(EquipmentManager, self).get_queryset()
        return queryset.prefetch_related('equipment_model', 'equipment_owner', 'equipment_vendor')

class CalibrationReferenceEquipmentManager(models.Manager):
    def get_queryset(self):
        queryset = super(CalibrationReferenceEquipmentManager, self).get_queryset()
        return queryset.prefetch_related('action', 'equipment')

class EquipmentUsedManager(models.Manager):
    def get_queryset(self):
        queryset = super(EquipmentUsedManager, self).get_queryset()
        return queryset.prefetch_related('action', 'equipment')

class MaintenanceActionManager(models.Manager):
    def get_queryset(self):
        queryset = super(MaintenanceActionManager, self).get_queryset()
        return queryset.prefetch_related('action')

class RelatedEquipmentManager(models.Manager):
    def get_queryset(self):
        queryset = super(RelatedEquipmentManager, self).get_queryset()
        return queryset.prefetch_related('equipment', 'related_equipment')

class CalibrationActionManager(models.Manager):
    def get_queryset(self):
        queryset = super(CalibrationActionManager, self).get_queryset()
        return queryset.prefetch_related('instrument_output_variable')

# endregion

class TimeSeriesValuesQuerySet(ODM2QuerySet):
    def recent(self):
        return self.filter(value_datetime__gte=datetime.datetime.now() - datetime.timedelta(days=1))


text:
var defineWellKnownSymbol = require('../internals/define-well-known-symbol');

// `Symbol.match` well-known symbol
// https://tc39.github.io/ecma262/#sec-symbol.match
defineWellKnownSymbol('match');


text:
using namespace Microsoft::Graphics::Canvas;
using namespace Microsoft::Graphics::Canvas::Effects;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::Enumeration;
using namespace Platform;

#ifdef USE_LOCALLY_EMULATED_UAP_APIS
namespace EffectsAbi = ABI::Microsoft::Graphics::Canvas::Effects;
#else
namespace EffectsAbi = ABI::Windows::Graphics::Effects;
#endif

using EffectsAbi::IGraphicsEffectD2D1Interop;

TEST_CLASS(CanvasBitmapTests)
{
    TEST_METHOD(CanvasEffect_IGraphicsEffectD2D1Interop)
    {
        // Use gaussian blur for testing IGraphicsEffectD2D1Interop interface
        auto blurEffect = ref new GaussianBlurEffect();
        auto blurInterop = As<IGraphicsEffectD2D1Interop>(blurEffect);

        GUID id;
        ThrowIfFailed(blurInterop->GetEffectId(&id));
        Assert::IsTrue(id == CLSID_D2D1GaussianBlur);

        // Check sources initial vector
        UINT count;
        ThrowIfFailed(blurInterop->GetSourceCount(&count));
        Assert::AreEqual(1U, count);

        ComPtr<EffectsAbi::IGraphicsEffectSource> source;
        ThrowIfFailed(blurInterop->GetSource(0, &source));
        Assert::IsNull(source.Get());

        // Check initial properties vector
        ThrowIfFailed(blurInterop->GetPropertyCount(&count));
        Assert::AreEqual(3U, count);

        ComPtr<ABI::Windows::Foundation::IPropertyValue> prop;

        for (unsigned int i = 0; i < 3U; ++i)
        {
            ThrowIfFailed(blurInterop->GetProperty(i, &prop));
            Assert::IsNotNull(prop.Get());
        }

        // Check null parameters.
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetEffectId(nullptr));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetSourceCount(nullptr));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetSource(0, nullptr));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetPropertyCount(nullptr));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetProperty(0, nullptr));

        // Check out of range accesses.
        Assert::AreEqual(E_BOUNDS, blurInterop->GetSource((unsigned)-1, &source));
        Assert::AreEqual(E_BOUNDS, blurInterop->GetSource(1, &source));

        Assert::AreEqual(E_BOUNDS, blurInterop->GetProperty((unsigned)-1, &prop));
        Assert::AreEqual(E_BOUNDS, blurInterop->GetProperty(3, &prop));
    }

    TEST_METHOD(CanvasEffect_FloatProperty)
    {
        // Use gaussian blur StandardDeviation float property for testing
        GaussianBlurEffect^ blurEffect = ref new GaussianBlurEffect();

        // Check float property access through strongly typed interface
        Assert::AreEqual(3.0f, blurEffect->BlurAmount);
        float newValue = 5.0f;
        blurEffect->BlurAmount = newValue;
        Assert::AreEqual(newValue, blurEffect->BlurAmount);

        // Check that IGraphicsEffectD2D1Interop interface connects to the same data
        auto blurInterop = As<IGraphicsEffectD2D1Interop>(blurEffect);

        ComPtr<ABI::Windows::Foundation::IPropertyValue> prop;
        ThrowIfFailed(blurInterop->GetProperty(0, &prop));

        float propValue = 0;
        ThrowIfFailed(prop->GetSingle(&propValue));
        Assert::AreEqual(newValue, propValue);

        // Try setting not valid data.
        // For StandardDeviation in GaussianBlur valid range is (0.0f;250.0f)
        Assert::ExpectException<Platform::InvalidArgumentException^>(
            [&]
            {
                blurEffect->BlurAmount = -1.0f;
            });

        Assert::ExpectException<Platform::InvalidArgumentException^>(
            [&]
            {
                blurEffect->BlurAmount = 300.0f;
            });
    }

    TEST_METHOD(CanvasEffect_EnumProperty)
    {
        // Use gaussian blur Optimization enum property for testing
        GaussianBlurEffect^ blurEffect = ref new GaussianBlurEffect();

        // Check enum property access through strongly typed interface
        Assert::IsTrue(EffectOptimization::Balanced == blurEffect->Optimization);
        EffectOptimization newValue = EffectOptimization::Speed;
        blurEffect->Optimization = newValue;
        Assert::IsTrue(newValue == blurEffect->Optimization);

        // Check that IGraphicsEffectD2D1Interop interface connects to the same data
        auto blurInterop = As<IGraphicsEffectD2D1Interop>(blurEffect);

        ComPtr<ABI::Windows::Foundation::IPropertyValue> prop;
        ThrowIfFailed(blurInterop->GetProperty(1, &prop));

        unsigned propValue = 0;
        ThrowIfFailed(prop->GetUInt32(&propValue));
        Assert::AreEqual((unsigned)newValue, propValue);
    }

    TEST_METHOD(CanvasEffect_UnsupportedEnums)
    {
        // Use Transform3DEffect effect for testing unsupported enums
        Transform3DEffect^ transformEffect = ref new Transform3DEffect();

        transformEffect->InterpolationMode = CanvasImageInterpolation::Anisotropic;
        Assert::IsTrue(CanvasImageInterpolation::Anisotropic == transformEffect->InterpolationMode);

        Assert::ExpectException<Platform::InvalidArgumentException^>(
            [&]
            {
                transformEffect->InterpolationMode = CanvasImageInterpolation::HighQualityCubic;
            });

        // Check that transformEffect did not change it's interpolation mode
        Assert::IsTrue(CanvasImageInterpolation::Anisotropic == transformEffect->InterpolationMode);
    }

    TEST_METHOD(CanvasEffect_Matrix4x4Propery)
    {
        // Use Transform3D TransformMatrix property for testing
        Transform3DEffect^ transformEffect = ref new Transform3DEffect();

        // Check enum property access through strongly typed interface
        float4x4 matrix;
        float newValue = 5.0f;
        matrix.m22 = newValue;
        transformEffect->TransformMatrix = matrix;
        Assert::AreEqual(newValue, static_cast<float4x4>(transformEffect->TransformMatrix).m22);

        // Check that IGraphicsEffectD2D1Interop interface connects to the same data
        auto transformInterop = As<IGraphicsEffectD2D1Interop>(transformEffect);

        // Transformation matrix is propery #2 in property array
        ComPtr<ABI::Windows::Foundation::IPropertyValue> prop;
        ThrowIfFailed(transformInterop->GetProperty(2, &prop));

        ComArray<float> propertyArray;
        ThrowIfFailed(prop->GetSingleArray(propertyArray.GetAddressOfSize(), propertyArray.GetAddressOfData()));

        Assert::AreEqual(16u, propertyArray.GetSize());

        Assert::AreEqual(matrix.m11, propertyArray[0]);
        Assert::AreEqual(matrix.m12, propertyArray[1]);
        Assert::AreEqual(matrix.m13, propertyArray[2]);
        Assert::AreEqual(matrix.m14, propertyArray[3]);

        Assert::AreEqual(matrix.m21, propertyArray[4]);
        Assert::AreEqual(matrix.m22, propertyArray[5]);
        Assert::AreEqual(matrix.m23, propertyArray[6]);
        Assert::AreEqual(matrix.m24, propertyArray[7]);

        Assert::AreEqual(matrix.m31, propertyArray[8]);
        Assert::AreEqual(matrix.m32, propertyArray[9]);
        Assert::AreEqual(matrix.m33, propertyArray[10]);
        Assert::AreEqual(matrix.m34, propertyArray[11]);

        Assert::AreEqual(matrix.m41, propertyArray[12]);
        Assert::AreEqual(matrix.m42, propertyArray[13]);
        Assert::AreEqual(matrix.m43, propertyArray[14]);
        Assert::AreEqual(matrix.m44, propertyArray[15]);
    }

    TEST_METHOD(CanvasEffect_LimitedSources)
    {
        // Use gaussian for testing limited sources
        GaussianBlurEffect^ blurEffect = ref new GaussianBlurEffect();

        Assert::IsNull(blurEffect->Source);

        // Set same effect as source for reference testing
        blurEffect->Source = blurEffect;
        Assert::IsTrue(blurEffect == blurEffect->Source);

        // Check that IGraphicsEffectD2D1Interop interface connects to the same data
        auto blurInterop = As<IGraphicsEffectD2D1Interop>(blurEffect);

        unsigned count;
        ThrowIfFailed(blurInterop->GetSourceCount(&count));
        Assert::AreEqual(1U, count);

        ComPtr<EffectsAbi::IGraphicsEffectSource> source;
        ThrowIfFailed(blurInterop->GetSource(0, &source));
        Assert::IsTrue(IsSameInstance(reinterpret_cast<IInspectable*>(blurEffect), source.Get()));
    }

    TEST_METHOD(CanvasEffect_UnlimitedSources)
    {
        // Use Composite effect for testing unlimited sources
        CompositeEffect^ compositeEffect = ref new CompositeEffect();

        // All unlimited sources supposed to have 0 size sources vector by default
        Assert::AreEqual(0U, compositeEffect->Sources->Size);

        // Set same effect as source for reference testing
        unsigned int sourceNumber = 10;
        for (unsigned int i = 0; i < sourceNumber; i++)
        {
            compositeEffect->Sources->Append(compositeEffect);
        }
        Assert::AreEqual(sourceNumber, compositeEffect->Sources->Size);
        for (unsigned int i = 0; i < sourceNumber; i++)
        {
            Assert::IsTrue(compositeEffect == compositeEffect->Sources->GetAt(i));
        }
    }

    TEST_METHOD(CanvasEffect_GetNamedPropertyMapping)
    {
        using EffectsAbi::GRAPHICS_EFFECT_PROPERTY_MAPPING;
        using EffectsAbi::GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT;

        GaussianBlurEffect^ blurEffect = ref new GaussianBlurEffect();
        auto blurInterop = As<IGraphicsEffectD2D1Interop>(blurEffect);

        UINT index = static_cast<UINT>(-1);
        GRAPHICS_EFFECT_PROPERTY_MAPPING mapping = static_cast<GRAPHICS_EFFECT_PROPERTY_MAPPING>(-1);

        // Look up properties that exist.
        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"BlurAmount", &index, &mapping));

        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, index);
        Assert::AreEqual<UINT>(GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT, mapping);

        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"Optimization", &index, &mapping));

        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_OPTIMIZATION, index);
        Assert::AreEqual<UINT>(GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT, mapping);

        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"BorderMode", &index, &mapping));

        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE, index);
        Assert::AreEqual<UINT>(GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT, mapping);

        // Property look up should be case-insensitive.
        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"bluramount", &index, &mapping));
        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, index);

        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"OPTIMIZATION", &index, &mapping));
        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_OPTIMIZATION, index);

        ThrowIfFailed(blurInterop->GetNamedPropertyMapping(L"bORdERmODE", &index, &mapping));
        Assert::AreEqual<UINT>(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE, index);

        // Look up properties that do not exist.
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"xBlurAmount", &index, &mapping));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"BlurAmountx", &index, &mapping));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"!@#$%^&*", &index, &mapping));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"", &index, &mapping));

        // Null parameters.
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(nullptr, &index, &mapping));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"BlurAmount", nullptr, &mapping));
        Assert::AreEqual(E_INVALIDARG, blurInterop->GetNamedPropertyMapping(L"BlurAmount", &index, nullptr));
    }
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anais Soc. Biol. Pernambuco 15(2): 437 (1957)

#### Original name
Parodiopsis torrendii Bat. & H. Maia

### Remarks
null


text:
These are miscellaneous checks for TensorBoard support.

## TensorBoard compatibility

See `uat/tensorboard-versions.md` for TensorBoard version
compatibility tests.

## Runs Monitor

The class `guild.tensorboard.RunsMonitor` is responsible for running
in a background thread that monitors a list of runs and applies
changes as needed to a TB log directory.

    >>> from guild.tensorboard import RunsMonitor

We a log directory.

    >>> logdir = mkdtemp()

For our runs, we use the `tensorboard` project.

    >>> project = Project(sample("projects", "tensorboard"))

We can use the project `runs` method as the run callback for the
monitor.

We can also provide a function for naming the run directories the
monitor uses.

    >>> run_name = lambda run: "run-%s" % run.short_id

Our monitor:

    >>> monitor = RunsMonitor(logdir, project.list_runs, run_name_cb=run_name)

Run monitors are typically run in a polling thread. For our tests, we
use the `run_once` method to explicitly check each step of our tests.

Our log directory is initially empty.

    >>> find(logdir)
    <empty>

With no runs, there's nothing to setup.

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs

    >>> find(logdir)
    <empty>

Let's run three sample operations.

    >>> project.run("op")
    m1: 1.123

    >>> project.run("op", flags={"a": 2.0, "c": "hola"})
    m1: 1.123

    >>> project.run("op", flags={"a": 3, "b": "3.0", "c": "bonjour"})
    m1: 1.123

    >>> project.print_runs(flags=True)
    op  a=3 b=3.0 c=bonjour d=yes extra_metrics=0
    op  a=2.0 b=2 c=hola d=yes extra_metrics=0
    op  a=1.0 b=2 c=hello d=yes extra_metrics=0

The combination of these runs defines the hyperparameters (hparams)
and metrics setup by the runs monitor. The hparam TB plugin does not
modify the hparam settings when it reads subsequent experiment
summaries. Any runs the monitor handles after this first set must fit
within the hparam domain scheme to be displayed as expected in the
hparam tab.

We run three runs of specific values to establish the following hparam
scheme:

- Flag `a` consists of three numbers, so is created as an unbounded
  `RealInterval` by the monitor.

- Flag `b` is of mixed type and so will not have a domain. The hparam
  interface does not support filtering or log scale options for
  hparams without a domain.

- Flag `c` consists of three strings: hello, hola, and bonjour. These
  are defined using a `Discrete` domain, which supports filtering by
  checking and unchecking values.

- Flag `d` conists only of boolean values and will be created with a
  special `Discrete` domain consisting of only True and False
  options. Note that even though False does not appear in any of the
  runs, the monitor adds it as an option.

Let's run the monitor, capturing debug output.

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

The monitor generates the following logs:

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link from '.../.guild/events.out.tfevents...' to '.../.guild/events.out.tfevents...'
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link from '.../.guild/events.out.tfevents...' to '.../.guild/events.out.tfevents...'
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link from '.../.guild/events.out.tfevents...' to '.../.guild/events.out.tfevents...'

Note the following from the log output:

- The experiment summaries are the same. Guild writes new summaries
  for each run using the combined information on hparms and metrics
  for all available runs.

- Each run events log is linked within the monitor log dir.

And the log dir:

    >>> find(logdir)
    run-.../.guild/events.out.tfevents.0000000000.hparams
    run-.../.guild/events.out.tfevents...
    run-.../.guild/events.out.tfevents.9999999999.time
    run-.../.guild/events.out.tfevents.0000000000.hparams
    run-.../.guild/events.out.tfevents...
    run-.../.guild/events.out.tfevents.9999999999.time
    run-.../.guild/events.out.tfevents.0000000000.hparams
    run-.../.guild/events.out.tfevents...
    run-.../.guild/events.out.tfevents.9999999999.time

For subsequent tests in this section we assert file count in logdir.

    >>> len(findl(logdir))
    9

Now the fun begins! Each new run that arrives may or may not fall
within the scheme inferred from the first set of runs. Runs that fall
within the scheme are logged without warning. Runs that do not
generate one or more warnings.

Let's generate a run that falls within the scheme, specifically:

- `a` is a number
- `b` is a number
- `c` is one of the three known string values
- `d` is boolean

    >>> project.run("op", flags={"a": 0, "b": 1, "c": "hola", "d": False})
    m1: 1.123

With this new run, let's run the monitor.

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link ...

Note the same hparam experiment scheme.

Next we generate a run that falls outside the scheme.

- `a` is not a number
- `c` is not one of the three original values
- `d` is not a boolean

We need to use force-flags because the values violate our operation
flag type constraints.

    >>> project.run("op", flags={"a": "zero", "c": "bye", "d": "a_str"}, force_flags=True)
    m1: 1.123

When we ask the monitor to process this run, it logs warnings about
each incompatibility.

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs
    WARNING: Runs found with hyperparameter values that cannot be displayed in the
             HPARAMS plugin: a=zero, c=bye. Restart this command to view them.
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link ...

Next we generate a run with flags that weren't in the original set.

    >>> project.run("op", flags={"e": 123}, force_flags=True)
    m1: 1.123

In this case, the monitor warns of new hyperparameters.

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs
    WARNING: Runs found with new hyperparameters: e. These hyperparameters
             will NOT appear in the HPARAMS plugin. Restart this command to view them.
    WARNING: Runs found with hyperparameter values that cannot be displayed in the
             HPARAMS plugin: a=zero, c=bye. Restart this command to view them.
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link ...

Note that the monitor warns of the full set of incompatible hparam
items - not just of the more recently added run. This is
less-than-ideal as it is preferable to include specific about each
run, but this approach is sufficient to call attention to the issue.

Finally, we generate a run that logs scalars that are not part of the
original set. This too causes the monitor to log a warning.

    >>> project.run("op", flags={"extra_metrics": 2})
    m1: 1.123
    m2: 1.123
    m3: 1.123

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    DEBUG: [guild] Refreshing runs
    WARNING: Runs found with new hyperparameters: e. These hyperparameters
             will NOT appear in the HPARAMS plugin. Restart this command to view them.
    WARNING: Runs found with hyperparameter values that cannot be displayed in the
             HPARAMS plugin: a=zero, c=bye. Restart this command to view them.
    WARNING: Runs found with new metrics: m2, m3. These runs will NOT appear in the
             HPARAMS plugin. Restart this command to view them.
    DEBUG: [guild] hparam experiment:
           hparams=['a', 'b', 'c', 'd', 'extra_metrics', 'sourcecode']
           metrics=['m1', 'time']
    DEBUG: [guild] Creating link ...

## Run names

The name shown in TensorBoard for a run is determined by a run name
callback function. If a callback is not provided, Guild generates a
value using run attributes including the run label.

Here's a monitor that uses the default name:

    >>> monitor = RunsMonitor(logdir, project.list_runs, run_name_cb=None)

Let's clear our runs.

    >>> project.delete_runs()
    ???

Generate a run and show monitor processing.

    >>> project.run("op")
    m1: 1.123

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()
    ???
    DEBUG: [guild] Creating link from '...' to '... op ... a=1.0 b=2 c=hello d=yes extra_metrics=0...'

Note the use of the flag assignments, which is the run label.

    >>> project.print_runs(labels=True)
    op  a=1.0 b=2 c=hello d=yes extra_metrics=0

Here's a custom run name callback function:

    >>> def run_name(run):
    ...     return "the run <%s>" % run.short_id

    >>> monitor = RunsMonitor(logdir, project.list_runs, run_name_cb=run_name)

Delete our runs again.

    >>> project.delete_runs()
    ???

Generate a run and show monitor processing.

    >>> project.run("op")
    m1: 1.123

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()  # doctest: -WINDOWS
    ???
    DEBUG: [guild] Creating link from '...' to '...the run <...>...'

    >>> log.print_all()  # doctest: +WINDOWS_ONLY
    ???
    DEBUG: [guild] Creating link from '...' to '...the run _..._...'

Guild provides a safe-guard against invalid DOM characters used in the
run name. This ensures that the run can be selected in TensorBoard UI
(see issue #230).

Here's a function that deliberately inserts a invalid DOM character
(an ellipsis).

    >>> def run_name(run):
    ...     return u"the run <%s> \u2026" % run.short_id

    >>> monitor = RunsMonitor(logdir, project.list_runs, run_name_cb=run_name)

Delete our runs.

    >>> project.delete_runs()
    ???

Generate a run and show monitor processing.

    >>> project.run("op")
    m1: 1.123

    >>> with LogCapture(log_level=0) as log:
    ...     monitor.run_once()

    >>> log.print_all()  # doctest: -WINDOWS
    ???
    DEBUG: [guild] Creating link from '...' to '...the run <...> ?...'

    >>> log.print_all()  # doctest: +WINDOWS_ONLY
    ???
    DEBUG: [guild] Creating link from '...' to '...the run _..._ _...'

## Misc Tests

Run label template for --run-name-flags arg:

    >>> from guild.commands import tensorboard_impl as impl

    >>> impl._run_label_template("")
    ''

    >>> impl._run_label_template("foo")
    'foo=${foo}'

    >>> impl._run_label_template("foo,bar")
    'foo=${foo} bar=${bar}'

    >>> impl._run_label_template("foo bar")
    'foo=${foo} bar=${bar}'

    >>> impl._run_label_template("  foo, bar,  ")
    'foo=${foo} bar=${bar}'


text:
/* See srba-slam_main.cpp for docs */

#include "srba-run-generic-impl.h"

#include "CDatasetParser_Cartesian_3D.h"

// Explicit instantiation:
template struct RBA_Run_Factory<kf2kf_poses::SE3,landmarks::Euclidean3D,observations::Cartesian_3D>;

// Register this RBA problem:
RBA_Run_BasePtr my_creator_se3_lm3d_cart3d(RBASLAM_Params &config)
{
	if (config.arg_se3.isSet() && config.arg_lm3d.isSet() && config.arg_obs.getValue()=="Cartesian_3D")
		return RBA_Run_Factory<kf2kf_poses::SE3,landmarks::Euclidean3D,observations::Cartesian_3D>::create();

	return RBA_Run_BasePtr();
}

struct TMyRegister_se3_lm3d_cart3d
{
	TMyRegister_se3_lm3d_cart3d()
	{
		RBA_implemented_registry & reg = RBA_implemented_registry::getInstance();
		reg.doRegister( &my_creator_se3_lm3d_cart3d, "--se3 --lm-3d --obs Cartesian_3D" );
	}
};

static TMyRegister_se3_lm3d_cart3d my_initializer_se3_lm3d_cart3d;


text:
use fuzz_helper::{process_ctap_specific_type, InputType};
use libfuzzer_sys::fuzz_target;

// Fuzz inputs as CTAP2 make credential command parameters encoded in cbor.
// For a more generic fuzz target including all CTAP commands, you can use
// fuzz_target_process_ctap_command.
fuzz_target!(|data: &[u8]| {
    process_ctap_specific_type(data, InputType::CborMakeCredentialParameter);
});


text:
var adjective = prompt("Type an adjective:");
var verb = prompt("Type a verb:");
var noun = prompt("Type a noun:");
var story = "
There once was a " + adjective;
story += " programmer who wanted to use Javascript to " + verb;
story += " the " + noun + ".
";
document.write(story);


text:
using System;
using System.Diagnostics;
using Mono.Unix;

using Hyena;
using Banshee.Base;
using Banshee.ServiceStack;

namespace Banshee.Web
{
    public class Browser
    {
        public delegate bool OpenUrlHandler (string uri);

        private static OpenUrlHandler open_handler = null;
        public static OpenUrlHandler OpenHandler {
            get { return open_handler; }
            set { open_handler = value; }
        }

        public static bool Open (string url)
        {
            try {
                url = Uri.EscapeUriString (url);
                if (open_handler != null) {
                    return open_handler (url);
                } else {
                    Process.Start (url);
                    return true;
                }
            } catch(Exception e) {
                Log.Warning (Catalog.GetString ("Could not launch URL"),
                    String.Format (Catalog.GetString ("{0} could not be opened: {1}\n\n " +
                        "Check your 'Preferred Applications' settings."), url, e.Message), true);
                return false;
            }
        }

        public static readonly string UserAgent = String.Format ("Banshee {0} (http://banshee-project.org/)",
            Application.Version);
    }
}


text:
/**
 * \file
 * \brief Pmap code common for x86 archs
 */

/*
 * Copyright (c) 2011, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#include <barrelfish/barrelfish.h>
#include <barrelfish/pmap.h>
#include "target/x86/pmap_x86.h"

/*
 * The serialisation format is depressingly ad-hoc, and assumes a depth-first
 * walk of the tree. Each vnode is encoded as an entry in an array.
 *
 * We abuse the slot of the first entry, which is the root and thus is always
 * zero, to store the number of entries in the array.
 */
struct serial_entry {
    uint16_t entry;     ///< Entry #
    uint8_t depth;      ///< Depth of this node (0 = root)
    cslot_t slot;       ///< Slot number (in page cnode) of vnode cap
};

static errval_t serialise_tree(int depth, struct vnode *v,
                               struct serial_entry *out,
                               size_t outlen, size_t *outpos)
{
    assert(v != NULL);
    errval_t err;

    // don't serialise leaf pages (yet!)
    if (!v->is_vnode) {
        return SYS_ERR_OK;
    }

    if (*outpos >= outlen) {
        return LIB_ERR_SERIALISE_BUFOVERFLOW;
    }

    // serialise this node
    out[(*outpos)++] = (struct serial_entry) {
        .depth = depth,
        .entry = v->entry,
        .slot = v->u.vnode.cap.slot,
    };

    // depth-first walk
    for (struct vnode *c = v->u.vnode.children; c != NULL; c = c->next) {
        err = serialise_tree(depth + 1, c, out, outlen, outpos);
        if (err_is_fail(err)) {
            return err;
        }
    }

    return SYS_ERR_OK;
}

/**
 * \brief Serialise vtree to a flat structure, for passing to another process
 *
 * This is used by spawn_vspace to communicate the vnode capabilities to the child.
 */
errval_t pmap_x86_serialise(struct pmap *pmap, void *buf, size_t buflen)
{
    errval_t err;
    struct pmap_x86 *pmapx = (struct pmap_x86 *)pmap;

    // XXX: check alignment of buffer
    assert((uintptr_t)buf % sizeof(uintptr_t) == 0);

    struct serial_entry *out = buf;
    size_t outlen = buflen / sizeof(struct serial_entry);
    size_t outpos = 0;

    err = serialise_tree(0, &pmapx->root, out, outlen, &outpos);
    if (err_is_ok(err)) {
        // store length in first entry's slot number
        assert(out[0].slot == 0);
        out[0].slot = outpos;
    }

    return err;
}

static errval_t deserialise_tree(struct pmap *pmap, struct serial_entry **in,
                                 size_t *inlen, int depth, struct vnode *parent)
{
    errval_t err;
    struct pmap_x86 *pmapx = (struct pmap_x86 *)pmap;

    if (*inlen == 0) {
        return SYS_ERR_OK;
    }

    while (*inlen > 0 && (*in)->depth == depth) {
        // ensure slab allocator has sufficient space
        err = pmapx->refill_slabs(pmapx);
        if (err_is_fail(err)) {
            return err_push(err, LIB_ERR_SLAB_REFILL);
        }

        // allocate storage for the new vnode
        struct vnode *n = slab_alloc(&pmapx->slab);
        assert(n != NULL);

        // populate it and append to parent's list of children
        n->is_vnode  = true;
        n->entry     = (*in)->entry;
        n->u.vnode.cap.cnode = cnode_page;
        n->u.vnode.cap.slot  = (*in)->slot;
        n->u.vnode.children  = NULL;
        n->next      = parent->u.vnode.children;
        parent->u.vnode.children = n;

        (*in)++;
        (*inlen)--;

        // is next entry a child of the last node?
        if (*inlen > 0 && (*in)->depth > depth) {
            assert((*in)->depth == depth + 1); // depth-first, no missing nodes
            err = deserialise_tree(pmap, in, inlen, depth + 1, n);
            if (err_is_fail(err)) {
                return err;
            }
        }
    }

    assert((*in)->depth < depth);
    return SYS_ERR_OK;
}

/**
 * \brief Deserialise vtree from a flat structure, for importing from another process
 *
 * This is used in a newly-spawned child
 */
errval_t pmap_x86_deserialise(struct pmap *pmap, void *buf, size_t buflen)
{
    struct pmap_x86 *pmapx = (struct pmap_x86 *)pmap;
    errval_t err;

    // XXX: check alignment of buffer
    assert((uintptr_t)buf % sizeof(uintptr_t) == 0);

    // extract length and sanity-check
    struct serial_entry *in = buf;
    assert(buflen > sizeof(struct serial_entry));
    size_t inlen = in[0].slot;
    assert(inlen * sizeof(struct serial_entry) <= buflen);
    in++;
    inlen--;

    err = deserialise_tree(pmap, &in, &inlen, 1, &pmapx->root);
    if (err_is_ok(err)) {
        // XXX: now that we know where our vnodes are, we can support mappings
        // in the bottom of the address space. However, we still don't know
        // exactly where our text and data are mapped (because we don't yet
        // serialise vregions or memobjs), so instead we pad _end.
        extern char _end;
        pmapx->min_mappable_va = ROUND_UP((lvaddr_t)&_end, 64 * 1024)
                                   + 64 * 1024;
    }

    return err;
}

/**
 * \brief Determine a suitable address for a given memory object
 *
 * \param pmap    The pmap object
 * \param memobj  The memory object to determine the address for
 * \param alignment Minimum alignment
 * \param retvaddr Pointer to return the determined address
 *
 * Relies on vspace.c code maintaining an ordered list of vregions
 */
errval_t pmap_x86_determine_addr(struct pmap *pmap, struct memobj *memobj,
                                 size_t alignment, genvaddr_t *retvaddr)
{
    struct pmap_x86 *pmapx = (struct pmap_x86 *)pmap;
    genvaddr_t vaddr;

    struct vregion *walk = pmap->vspace->head;
    assert(walk != NULL); // assume there's always at least one existing entry

    if (alignment == 0) {
        alignment = BASE_PAGE_SIZE;
    } else {
        alignment = ROUND_UP(alignment, BASE_PAGE_SIZE);
    }
    size_t size = ROUND_UP(memobj->size, alignment);

    // if there's space before the first object, map it there
    genvaddr_t minva = ROUND_UP(pmapx->min_mappable_va, alignment);
    if (minva + size <= vregion_get_base_addr(walk)) {
        vaddr = minva;
        goto out;
    }

    while (walk->next) { // Try to insert between existing mappings
        genvaddr_t walk_base = vregion_get_base_addr(walk);
        genvaddr_t walk_size = ROUND_UP(vregion_get_size(walk), BASE_PAGE_SIZE);
        genvaddr_t walk_end = ROUND_UP(walk_base + walk_size, alignment);
        genvaddr_t next_base = vregion_get_base_addr(walk->next);

        // sanity-check for page alignment
        assert(walk_base % BASE_PAGE_SIZE == 0);
        assert(next_base % BASE_PAGE_SIZE == 0);

        if (next_base > walk_end + size) {
            vaddr = walk_end;
            goto out;
        }

        walk = walk->next;
    }

    // Place beyond last mapping, with alignment
    vaddr = ROUND_UP((vregion_get_base_addr(walk)
                      + ROUND_UP(vregion_get_size(walk), BASE_PAGE_SIZE)),
                     alignment);

 out:
    // Ensure that we haven't run out of address space
    if (vaddr + memobj->size > pmapx->max_mappable_va) {
        return LIB_ERR_OUT_OF_VIRTUAL_ADDR;
    }

    assert(retvaddr != NULL);
    *retvaddr = vaddr;

    return SYS_ERR_OK;
}


text:
enum {
    MLHudAlertTypeInfo = 0,
    MLHudAlertTypeWarn,
    MLHudAlertTypeError,
    MLHudAlertTypeSuccess,
    MLHudAlertTypeLoading,
};
typedef int MLHudAlertType;

@interface MLHudAlert : NSWindowController {
    NSTimer *dismissTimer;
    NSEvent *clickEvent;
}

+ (void) alertWithWindow: (NSWindow *) window type: (MLHudAlertType) type message: (NSString *) message;
+ (void) dismisWindow;

@end


text:
package io.fabric8.itests.paxexam.support;

import io.fabric8.api.Container;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;

public class WaitForProvisionTaskTest {

    @Test
    public void testStraightSuccess() throws Exception {
        Container container = createMock(Container.class);
        expect(container.getId()).andReturn("container").anyTimes();
        expect(container.isAlive()).andReturn(true).anyTimes();
        expect(container.isManaged()).andReturn(true).anyTimes();
        expect(container.getProvisionStatus()).andReturn("success").anyTimes();
        expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
        expect(container.getProvisionException()).andReturn(null).anyTimes();

        replay(container);

        WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 10000L);
        assertTrue(task.call());
        verify(container);
    }

    @Test
    public void testSuccess() throws Exception {
        Container container = createMock(Container.class);
        expect(container.getId()).andReturn("container").anyTimes();
        expect(container.isAlive()).andReturn(false).times(6);
        expect(container.isAlive()).andReturn(true).anyTimes();
        expect(container.isManaged()).andReturn(true).anyTimes();
        expect(container.getProvisionStatus()).andReturn("").times(3);
        expect(container.getProvisionStatus()).andReturn("analyzing").times(3);
        expect(container.getProvisionStatus()).andReturn("success").anyTimes();
        expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
        expect(container.getProvisionException()).andReturn(null).anyTimes();

        replay(container);

        WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 10000L);
        assertTrue(task.call());
        verify(container);
    }

    @Test
    public void testProvisioningException() throws Exception {
        Container container = createMock(Container.class);
        expect(container.getId()).andReturn("container").anyTimes();
        expect(container.isAlive()).andReturn(true).anyTimes();
        expect(container.isManaged()).andReturn(true).anyTimes();
        expect(container.getProvisionStatus()).andReturn("success").anyTimes();
        expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
        expect(container.getProvisionException()).andReturn(null).times(1);
        expect(container.getProvisionException()).andReturn("Resolution Exception").anyTimes();

        replay(container);

        WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 10000L);
        assertFalse(task.call());
        verify(container);
    }

    @Test
    public void testProvisioningError() throws Exception {
        Container container = createMock(Container.class);
        expect(container.getId()).andReturn("container").anyTimes();
        expect(container.isAlive()).andReturn(true).anyTimes();
        expect(container.isManaged()).andReturn(true).anyTimes();
        expect(container.getProvisionStatus()).andReturn("").times(5);
        expect(container.getProvisionStatus()).andReturn(Container.PROVISION_ERROR).anyTimes();
        expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
        expect(container.getProvisionException()).andReturn(null).anyTimes();

        replay(container);

        WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 10000L);
        assertFalse(task.call());
        verify(container);
    }

    @Test
    public void testProvisioningTimeout() throws Exception {
        Container container = createMock(Container.class);
        expect(container.getId()).andReturn("container").anyTimes();
        expect(container.isAlive()).andReturn(true).anyTimes();
        expect(container.isManaged()).andReturn(true).anyTimes();
        expect(container.getProvisionStatus()).andReturn("").anyTimes();
        expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
        expect(container.getProvisionException()).andReturn(null).anyTimes();

        replay(container);

        WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 4000L);
        assertFalse(task.call());
        verify(container);
    }
}


text: All about class.


text:
import Observable from "./observable";
/** @hidden */
export default function delay<V>(src: Observable<V>, delay: number): Observable<V>;