text:
from __future__ import unicode_literals

import copy
import importlib
import threading

from django.db import models, router
from django.db.models import Q
from django.db.models.fields.proxy import OrderWrt
from django.conf import settings
from django.contrib import admin
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.encoding import smart_text
from django.utils.timezone import now
from django.utils.translation import string_concat

try:
    from django.apps import apps
except ImportError:  # Django < 1.7
    from django.db.models import get_app
try:
    from django.db.models.fields.related import ForwardManyToOneDescriptor as ManyToOneDescriptor
except ImportError:  # Django < 1.9
    from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ManyToOneDescriptor
try:
    from south.modelsinspector import add_introspection_rules
except ImportError:  # south not present
    pass
else:  # south configuration for CustomForeignKeyField
    add_introspection_rules(
        [], ["^simple_history.models.CustomForeignKeyField"])

from . import exceptions
from simple_history import register
from .manager import HistoryDescriptor

ALL_M2M_FIELDS = object()

registered_models = {}

def not_registered(model):
    if model._meta.proxy:
        return '%s%s' % (model._meta.db_table, model.__name__) not in registered_models
    return model._meta.db_table not in registered_models

class HistoricalRecords(object):
    thread = threading.local()

    def __init__(self, verbose_name=None, bases=(models.Model,),
                 user_related_name='+', table_name=None, inherit=False, m2m_fields=None):
        self.user_set_verbose_name = verbose_name
        self.user_related_name = user_related_name
        self.table_name = table_name
        self.inherit = inherit
        self.m2m_fields = m2m_fields
        try:
            if isinstance(bases, six.string_types):
                raise TypeError
            self.bases = tuple(bases)
        except TypeError:
            raise TypeError("The `bases` option must be a list or a tuple.")

    def contribute_to_class(self, cls, name):
        self.manager_name = name
        self.module = cls.__module__
        self.cls = cls
        models.signals.class_prepared.connect(self.finalize, weak=False)
        self.add_extra_methods(cls)
        self.setup_m2m_history(cls)

    def add_extra_methods(self, cls):
        def save_without_historical_record(self, *args, **kwargs):
            """
            Save model without saving a historical record

            Make sure you know what you're doing before you use this method.
            """
            self.skip_history_when_saving = True
            try:
                ret = self.save(*args, **kwargs)
            finally:
                del self.skip_history_when_saving
            return ret
        setattr(cls, 'save_without_historical_record',
                save_without_historical_record)

    def setup_m2m_history(self, cls):
        m2m_history_fields = self.m2m_fields
        if m2m_history_fields is ALL_M2M_FIELDS:
            for field in cls._meta.many_to_many:
                field = getattr(cls, field.name).field
                assert isinstance(field, models.fields.related.ManyToManyField), \
                    ('%s must be a ManyToManyField' % field.name)
                if not sum([
                        isinstance(item, HistoricalRecords) for item in field.remote_field.through.__dict__.values()
                ]):
                    through_model = field.remote_field.through
                    if through_model._meta.auto_created and not_registered(through_model):
                        through_model.history = HistoricalRecords()
                        register(through_model)
        elif m2m_history_fields:
            assert (isinstance(m2m_history_fields, list) or isinstance(m2m_history_fields, tuple)), \
                'm2m_history_fields must be a list or tuple'
            for field_name in m2m_history_fields:
                field = getattr(cls, field_name).field
                assert isinstance(field, models.fields.related.ManyToManyField), \
                    ('%s must be a ManyToManyField' % field_name)
                if not sum([
                        isinstance(item, HistoricalRecords) for item in field.remote_field.through.__dict__.values()
                ]):
                    through_model = field.remote_field.through
                    if through_model._meta.auto_created and not_registered(through_model):
                        through_model.history = HistoricalRecords()
                        register(through_model)

    def finalize(self, sender, **kwargs):
        try:
            hint_class = self.cls
        except AttributeError:  # called via `register`
            pass
        else:
            if hint_class is not sender:  # set in concrete
                if not (self.inherit and issubclass(sender, hint_class)):
                    return  # set in abstract
        if hasattr(sender._meta, 'simple_history_manager_attribute'):
            raise exceptions.MultipleRegistrationsError(
                '{}.{} registered multiple times for history tracking.'.format(
                    sender._meta.app_label,
                    sender._meta.object_name,
                )
            )
        if sender._meta.proxy:
            original_class = [base_class for base_class in sender.__bases__ if base_class._meta.abstract is False][0]
            # Parent model must be registered before the proxy model is
            if not_registered(original_class):
                # Ignore the `app` kwarg, since the proxy model may be in a different app than the original model
                register_kwargs = {
                    'manager_name': self.manager_name,
                    'records_class': self.__class__,
                    'verbose_name': self.user_set_verbose_name,
                    'bases': self.bases,
                    'user_related_name': self.user_related_name,
                    'm2m_fields': self.m2m_fields,
                }
                register(original_class, **register_kwargs)
            # Proxy models use their parent's history model
            history_model = getattr(sender, self.manager_name).model
        else:
            history_model = self.create_history_model(sender)
            module = importlib.import_module(self.module)
            setattr(module, history_model.__name__, history_model)
        # The HistoricalRecords object will be discarded,
        # so the signal handlers can't use weak references.
        models.signals.post_save.connect(self.post_save, sender=sender,
                                         weak=False)
        models.signals.pre_delete.connect(self.pre_delete, sender=sender,
                                          weak=False)
        models.signals.post_delete.connect(self.post_delete, sender=sender,
                                           weak=False)
        models.signals.m2m_changed.connect(self.m2m_changed, sender=sender, weak=False)

        descriptor = HistoryDescriptor(history_model)
        setattr(sender, self.manager_name, descriptor)
        sender._meta.simple_history_manager_attribute = self.manager_name

    def create_history_model(self, model):
        """
        Creates a historical model to associate with the model provided.
        """
        attrs = {'__module__': self.module}

        app_module = '%s.models' % model._meta.app_label
        if model.__module__ != self.module:
            # registered under different app
            attrs['__module__'] = self.module
        elif app_module != self.module:
            try:
                # Abuse an internal API because the app registry is loading.
                app = apps.app_configs[model._meta.app_label]
            except NameError:  # Django < 1.7
                models_module = get_app(model._meta.app_label).__name__
            else:
                models_module = app.name
            attrs['__module__'] = models_module

        fields = self.copy_fields(model)
        attrs.update(fields)
        attrs.update(self.get_extra_fields(model, fields))
        # type in python2 wants str as a first argument
        attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model)))
        if self.table_name is not None:
            attrs['Meta'].db_table = self.table_name
        name = 'Historical%s' % model._meta.object_name
        registered_models[model._meta.db_table] = model
        return python_2_unicode_compatible(
            type(str(name), self.bases, attrs))

    def copy_fields(self, model):
        """
        Creates copies of the model's original fields, returning
        a dictionary mapping field name to copied field object.
        """
        fields = {}
        for field in model._meta.fields:
            field = copy.copy(field)
            try:
                field.remote_field = copy.copy(field.remote_field)
            except AttributeError:
                field.remote_field = copy.copy(field.remote_field)
            if isinstance(field, OrderWrt):
                # OrderWrt is a proxy field, switch to a plain IntegerField
                field.__class__ = models.IntegerField
            if isinstance(field, models.ForeignKey):
                old_field = field
                field_arguments = {'db_constraint': False}
                if (getattr(old_field, 'one_to_one', False) or
                        isinstance(old_field, models.OneToOneField)):
                    FieldType = models.ForeignKey
                else:
                    FieldType = type(old_field)
                if getattr(old_field, 'to_fields', []):
                    field_arguments['to_field'] = old_field.to_fields[0]
                if getattr(old_field, 'db_column', None):
                    field_arguments['db_column'] = old_field.db_column
                field = FieldType(
                    old_field.remote_field.model,
                    related_name='+',
                    null=True,
                    blank=True,
                    primary_key=False,
                    db_index=True,
                    serialize=True,
                    unique=False,
                    on_delete=models.DO_NOTHING,
                    **field_arguments
                )
                field.name = old_field.name
            else:
                transform_field(field)
            fields[field.name] = field
        return fields

    def get_extra_fields(self, model, fields):
        """Return dict of extra fields added to the historical record model"""

        user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

        @models.permalink
        def revert_url(self):
            """URL for this change in the default admin site."""
            opts = model._meta
            app_label, model_name = opts.app_label, opts.model_name
            return ('%s:%s_%s_simple_history' %
                    (admin.site.name, app_label, model_name),
                    [getattr(self, opts.pk.attname), self.history_id])

        def get_instance(self):
            return model(**{
                field.attname: getattr(self, field.attname)
                for field in fields.values()
            })

        return {
            'history_id': models.AutoField(primary_key=True),
            'history_date': models.DateTimeField(),
            'history_user': models.ForeignKey(
                user_model, null=True, related_name=self.user_related_name,
                on_delete=models.SET_NULL),
            'history_type': models.CharField(max_length=1, choices=(
                ('+', 'Created'),
                ('~', 'Changed'),
                ('-', 'Deleted'),
            )),
            'history_object': HistoricalObjectDescriptor(model),
            'instance': property(get_instance),
            'instance_type': model,
            'revert_url': revert_url,
            '__str__': lambda self: '%s as of %s' % (self.history_object,
                                                     self.history_date)
        }

    def get_meta_options(self, model):
        """
        Returns a dictionary of fields that will be added to
        the Meta inner class of the historical record model.
        """
        meta_fields = {
            'ordering': ('-history_date', '-history_id'),
            'get_latest_by': 'history_date',
        }
        if self.user_set_verbose_name:
            name = self.user_set_verbose_name
        else:
            name = string_concat('historical ',
                                 smart_text(model._meta.verbose_name))
        meta_fields['verbose_name'] = name
        return meta_fields

    def post_save(self, instance, created, **kwargs):
        if not created and hasattr(instance, 'skip_history_when_saving'):
            return
        if not kwargs.get('raw', False):
            self.create_historical_record(instance, created and '+' or '~')

    def pre_delete(self, instance, **kwargs):
        """
        Creates deletion records for the through model of m2m fields. Also creates change records for objects on the
        other side of the m2m relationship.
        """
        for m2m_field in instance._meta.many_to_many:
            through_model = m2m_field.remote_field.through
            if hasattr(through_model._meta, 'simple_history_manager_attribute'):
                items = through_model.objects.filter(Q(**{m2m_field.m2m_column_name(): instance.pk}))
                for item in items:
                    self.create_historical_record(item, '-')
                for related in m2m_field.value_from_object(instance):
                    self.create_historical_record(related, '~')

    def post_delete(self, instance, **kwargs):
        self.create_historical_record(instance, '-')

    def m2m_changed(self, action, instance, sender, **kwargs):
        source_field_name, target_field_name = None, None
        for field_name, field_value in sender.__dict__.items():
            if isinstance(field_value, ManyToOneDescriptor):
                if field_value.field.remote_field.model == kwargs['model']:
                    target_field_name = field_name
                elif isinstance(instance, field_value.field.remote_field.model):
                    source_field_name = field_name
        items = sender.objects.filter(**{source_field_name: instance})
        if kwargs['pk_set']:
            items = items.filter(**{target_field_name + '__id__in': kwargs['pk_set']})
        for item in items:
            if action == 'post_add':
                if hasattr(item, 'skip_history_when_saving'):
                    continue
                self.create_historical_record(item, '+')
            elif action == 'pre_remove':
                self.create_historical_record(item, '-')
            elif action == 'pre_clear':
                self.create_historical_record(item, '-')
        if action == 'pre_clear':
            setattr(instance, '__pre_clear_items', items)
        elif action == 'post_add' and hasattr(instance, '__pre_clear_items'):
            other_items = getattr(instance, '__pre_clear_items')
            for item in other_items:
                target = getattr(item, target_field_name)
                if has_m2m_field(target, sender) and not [i for i in items if target == getattr(i, target_field_name)]:
                    self.create_historical_record(target, '~')
            for item in items:
                target = getattr(item, target_field_name)
                if has_m2m_field(target, sender) and not [
                    i for i in other_items if target == getattr(i, target_field_name)
                ]:
                    self.create_historical_record(target, '~')
            delattr(instance, '__pre_clear_items')

    def create_historical_record(self, instance, history_type):
        history_date = getattr(instance, '_history_date', now())
        history_user = self.get_history_user(instance)
        manager = getattr(instance, self.manager_name)
        attrs = {}
        for field in instance._meta.fields:
            attrs[field.attname] = getattr(instance, field.attname)
        manager.create(history_date=history_date, history_type=history_type,
                       history_user=history_user, **attrs)

    def get_history_user(self, instance):
        """Get the modifying user from instance or middleware."""
        try:
            return instance._history_user
        except AttributeError:
            try:
                if self.thread.request.user.is_authenticated:
                    return self.thread.request.user
                return None
            except AttributeError:
                return None

def transform_field(field):
    """Customize field appropriately for use in historical model"""
    field.name = field.attname
    if isinstance(field, models.AutoField):
        field.__class__ = convert_auto_field(field)

    elif isinstance(field, models.FileField):
        # Don't copy file, just path.
        field.__class__ = models.TextField

    # Historical instance shouldn't change create/update timestamps
    field.auto_now = False
    field.auto_now_add = False

    if field.primary_key or field.unique:
        # Unique fields can no longer be guaranteed unique,
        # but they should still be indexed for faster lookups.
        field.primary_key = False
        field._unique = False
        field.db_index = True
        field.serialize = True

def has_m2m_field(instance, through):
    for m2m_field in instance._meta.many_to_many:
        if through is m2m_field.remote_field.through:
            return True
    return False

def convert_auto_field(field):
    """Convert AutoField to a non-incrementing type

    The historical model gets its own AutoField, so any existing one
    must be replaced with an IntegerField.
    """
    connection = router.db_for_write(field.model)
    if settings.DATABASES[connection]['ENGINE'] in ('django_mongodb_engine',):
        # Check if AutoField is string for django-non-rel support
        return models.TextField
    return models.IntegerField

class HistoricalObjectDescriptor(object):
    def __init__(self, model):
        self.model = model

    def __get__(self, instance, owner):
        values = (getattr(instance, f.attname)
                  for f in self.model._meta.fields)
        return self.model(*values)


text:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { SkyAlertModule } from '@skyux/indicators';

import { SkyAlertFixture } from './alert-fixture';

//#region Test component
@Component({
  selector: 'sky-alert-test',
  template: `
    <sky-alert
      [alertType]="alertType"
      [closeable]="closeable"
      [closed]="closed"
      (closedChange)="closedChange()"
      data-sky-id="test-alert"
    >
      This is a sample alert.
    </sky-alert>
  `,
})
class TestComponent {
  public alertType = 'warning';

  public closeable = true;

  public closed = false;

  public closedChange() {}
}
//#endregion Test component

describe('Alert fixture', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [SkyAlertModule],
    });
  });

  it('should expose the expected properties', () => {
    const fixture = TestBed.createComponent(TestComponent);

    fixture.detectChanges();

    const alert = new SkyAlertFixture(fixture, 'test-alert');

    expect(alert.closeable).toBe(true);
    expect(alert.closed).toBe(false);
    expect(alert.text).toBe('This is a sample alert.');

    const validAlertTypes = ['info', 'success', 'warning', 'danger'];

    for (const validAlertType of validAlertTypes) {
      fixture.componentInstance.alertType = validAlertType;

      fixture.detectChanges();

      expect(alert.alertType).toBe(validAlertType);
    }

    fixture.componentInstance.alertType = 'invalid';

    fixture.detectChanges();

    expect(alert.alertType).toBeUndefined();
  });

  it('should provide a method for closing the alert', () => {
    const fixture = TestBed.createComponent(TestComponent);

    fixture.componentInstance.closeable = false;

    fixture.detectChanges();

    const alert = new SkyAlertFixture(fixture, 'test-alert');

    expect(() => alert.close()).toThrowError('The alert is not closeable.');

    fixture.componentInstance.closeable = true;

    fixture.detectChanges();

    expect(alert.closed).toBe(false);

    const closedChangeSpy = spyOn(fixture.componentInstance, 'closedChange');

    alert.close();

    fixture.detectChanges();

    expect(closedChangeSpy).toHaveBeenCalled();
    expect(alert.closed).toBe(true);
  });
});

redpajama_set_name: RedPajamaGithub


text:
const babel = require('babel-core');
const uglify = require('uglify-js');

let clientJS;

exports = module.exports = function(Models) {

  if (clientJS) {
    return clientJS;
  }

  let str = 'var Models = window.Models = {};\n';
  //TODO: refactor this later.  Could be a separate client side Types library
  str += 'var utils = Models.utils = {';
  for (var util in Models.utils) {
    str += `${util}: ${Models.utils[util]},`;
  }
  str += '__end: true};\n';

  str += 'var errors = Models.errors ={';
  for (var error in Models.errors) {
    str += `${error}: ${Models.errors[error]},`;
  }
  str += '__end: true};\n';

  str += 'var Validators = Models.Validators = {';
  for (var validator in Models.Validators) {
    str += `${validator}: ${Models.Validators[validator]},`;
  }
  str += '__end: true};\n';

  str += `Models.constants = ${JSON.stringify(Models.constants)};\n`;
  str += 'var Types = Models.Types = {';
  for (var type in Models.Types) {
    str += `${type}: ${Models.Types[type]},`;
  }
  str += '__end: true};\n';
  str += 'var ObjectID = Models.Types.ObjectID = String;\n';
  str += 'var DBRef = Models.Types.DBRef;\n';

  str += Models.Property.toString();
  str += `Models.Property = Property;\n`;
  str += Models.Common.toString();
  str += `Models.Common = Common;\n`;
  str += Models.Structure.toString();
  str += `Models.Structure = Structure;\n`;
  str += `Models.structures = {};\n`;
  str += 'var Extend;';

  for (let structure in Models.structures) {
    if (Models.structures[structure].def.extend) {
      str += `Extend = Models.structures.${
        Models.structures[structure].def.extend.name
      };`;
    } else {
      str += 'Extend = Structure;';
    }

    str += Models.structures[structure].toString();
    str += `; Models.structures.${structure} = ${structure};\n`;
    //str += `Models.structures.${structure}._clientInit();\n`;
    str += `Extend.children = Extend.children || {};\n`;
    str += `Extend.children['${structure}'] = Models.structures.${structure};`;
  }

  str += Models.Document.toString();
  str += `; Models.Document = Document;\n`;
  str += `Models.models = {};\n`;

  for (let model in Models.models) {
    if (Models.models[model].def.extend) {
      str += `Extend = Models.models.${Models.models[model].def.extend.name};`;
    } else {
      str += 'Extend = Document;';
    }

    str += Models.models[model].toString();
    str += `; Models.models.${model} = ${model};\n`;
    //str += `Models.models.${model}._clientInit();`;
    str += `Extend.children = Extend.children || {};\n`;
    str += `Extend.children['${model}'] = Models.structures.${model};\n`;
  }

  str += `setTimeout(function() {
      for (var name in Models.structures) {
        Models.structures[name]._clientInit();
      }
    }, 10);`;

  str += `setTimeout(function() {
      for (var name in Models.models) {
        Models.models[name]._clientInit();
      }
    }, 10);`;

  clientJS = str;
  clientJS = babel.transform(str, {
    compact: Models.constants.IS_PRODUCTION,
    presets: ['es2015'],
    plugins: ['transform-regenerator']
  }).code;

  clientJS = '(function() {\n' + clientJS + '\n})();';

  if (Models.constants.IS_PRODUCTION) {
    try {
      const result = uglify.minify(clientJS, {
        compress: { drop_console: true }
      });

      if (result.error) {
        console.error(result.error);
      } else {
        clientJS = result.code;
      }
    } catch (e) {
      console.error(e);
      console.error(e.stack);
    }
  }

  return clientJS;
};


text:
<?php
/**
 * Author: Andrey Morozov
 * Email: andrey@3davinci.ru
 * Date: 19.04.2017
 */

namespace Sberbank\Message;

use Sberbank\Entity\OrderBundle;
use Sberbank\Exception\InvalidRequestException;

/**
 * Class RegisterOrderRequest
 * @package Sberbank\Message
 */
class RegisterOrderRequest extends RequestAbstract
{
    const PAGE_VIEW_DESKTOP = 'DESKTOP';
    const PAGE_VIEW_MOBILE = 'MOBILE';

    /**
     * Номер (идентификатор) заказа в системе магазина, уникален для каждого магазина в пределах системы
     *
     * @param string|int $value
     * @return RequestAbstract
     */
    public function setOrderNumber($value): RequestAbstract
    {
        return $this->setParameter('orderNumber', $value);
    }

    /**
     * Сумма платежа в копейках (или центах)
     *
     * @param int $value
     * @return RequestAbstract
     */
    public function setAmount(int $value): RequestAbstract
    {
        return $this->setParameter('amount', $value);
    }

    /**
     * Адрес, на который требуется перенаправить пользователя в случае успешной оплаты. Адрес должен быть указан полностью,
     * включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет
     * перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setReturnUrl(string $value): RequestAbstract
    {
        return $this->setParameter('returnUrl', $value);
    }

    /**
     * Адрес, на который требуется перенаправить пользователя в случае неуспешной оплаты. Адрес должен быть указан полностью,
     * включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет
     * перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setFailUrl(string $value): RequestAbstract
    {
        return $this->setParameter('failUrl', $value);
    }

    /**
     * По значению данного параметра определяется, какие страницы платёжного интерфейса должны загружаться для клиента.
     * Возможные значения:
     *   DESKTOP – для загрузки страниц, верстка которых предназначена для отображения на экранах ПК;
     *   MOBILE – для загрузки страниц, верстка которых предназначена для отображения на экранах мобильных устройств;
     *   Если магазин создал страницы платёжного интерфейса, добавив в название файлов страниц произвольные префиксы,
     * передайте значение нужного префикса в параметре pageView для загрузки соответствующей страницы. Например,
     * при передаче значения iphone в архиве страниц платёжного интерфейса будет осуществляться поиск страниц с
     * названиями iphone_p ayment_<locale>.html и iphone_error_<locale>.html.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setPageView(string $value): RequestAbstract
    {
        return $this->setParameter('pageView', $value);
    }

    /**
     * Продолжительность жизни заказа в секундах.
     * В случае если параметр не задан, будет использовано значение, указанное в настройках мерчанта или время по
     * умолчанию (1200 секунд = 20 минут).
     *
     * @param int $value
     * @return RequestAbstract
     */
    public function setSessionTimeoutSecs(int $value): RequestAbstract
    {
        return $this->setParameter('sessionTimeoutSecs', $value);
    }

    /**
     * Номер (идентификатор) клиента в системе магазина. Используется для реализации функционала связок.
     * Может присутствовать, если магазину разрешено создание связок.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setClientId(string $value): RequestAbstract
    {
        return $this->setParameter('clientId', $value);
    }

    /**
     * Код валюты платежа ISO 4217. Если не указан, считается равным коду валюты по умолчанию.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setCurrency(string $value): RequestAbstract
    {
        return $this->setParameter('currency', $value);
    }

    /**
     * Язык в кодировке ISO 639-1. Если не указан, будет использован язык, указанный в настройках магазина как язык по умолчанию (default language).
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setLanguage(string $value): RequestAbstract
    {
        return $this->setParameter('language', $value);
    }

    /**
     * Чтобы зарегистрировать заказ от имени дочернего мерчанта, укажите его логин в этом параметре.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setMerchantLogin(string $value): RequestAbstract
    {
        return $this->setParameter('merchantLogin', $value);
    }

    /**
     * Идентификатор связки, созданной ранее. Может использоваться, только если у магазина есть разрешение на работу со связками.
     * Если этот параметр передаётся в данном запросе, то это означает:
     *  1. Данный заказ может быть оплачен только с помощью связки;
     *  2. Плательщик будет перенаправлен на платёжную страницу, где требуется только ввод CVC.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setBindingId(string $value): RequestAbstract
    {
        return $this->setParameter('bindingId', $value);
    }

    /**
     * Описание заказа в свободной форме
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setDescription(string $value): RequestAbstract
    {
        return $this->setParameter('description', mb_substr($value, 0, 512));
    }

    /**
     * Номер телефона клиента. Может быть следующего формата: ^((+7|7|8)?([0-9]){10})$.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setPhone(string $value): RequestAbstract
    {
        return $this->setParameter('phone', $value);
    }

    /**
     * Адрес электронной почты покупателя.
     *
     * @param string $value
     * @return RequestAbstract
     */
    public function setEmail(string $value): RequestAbstract
    {
        return $this->setParameter('email', $value);
    }

    /**
     * Блок, содержащий корзину товаров заказа.
     *
     * @param OrderBundle $value
     * @return RequestAbstract
     */
    public function setOrderBundle(OrderBundle $value): RequestAbstract
    {
        return $this->setParameter('orderBundle', json_encode($value->toArray()));
    }
    /**
     * @throws InvalidRequestException
     */
    public function validate()
    {
        parent::validate('orderNumber', 'amount', 'returnUrl');
    }

    /**
     * @return string
     */
    public function getMethodName(): string
    {
        return 'rest/register.do';
    }
}


text:
package ru.job4j;

import ru.job4j.models.User;
import java.util.*;

import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test.
 *
 * @author Sergey Mikhailov (mailto:mifodiy67@mail.ru)
 * @version $Id$
 * @since 0.1
 */
public class SortUserTest {

    /**
     * Test sort.
     */
    @Test
    public void whenSortThreeUsers() {
        SortUser sortUser = new SortUser();

        Set<User> result = new TreeSet<>();
        List<User> list = new ArrayList<>();

        User user1 = new User("Anton", 10);
        list.add(user1);

        User user2 = new User("Tom", 8);
        list.add(user2);

        User user3 = new User("Jack", 27);
        list.add(user3);

        result = sortUser.sort(list);

        Set<User> expected = new TreeSet<>();
        expected.add(user2);
        expected.add(user1);
        expected.add(user3);

        assertThat(result, is(expected));
    }

    /**
     * Test sort.
     */
    @Test
    public void whenSortNameLength() {
        SortUser sortUser = new SortUser();

        List<User> list = new ArrayList<>();
        List<User> result = new ArrayList<>();
        List<User> expected = new ArrayList<>();

        User user1 = new User("Anton", 10);
        list.add(user1);

        User user2 = new User("Tom", 8);
        list.add(user2);

        User user3 = new User("Jack", 27);
        list.add(user3);

        result = sortUser.sortNameLength(list);

        expected.add(user2);
        expected.add(user3);
        expected.add(user1);

        assertThat(result, is(expected));
    }

    /**
     * Test sort.
     */
    @Test
    public void whenSortByAllFields() {
        SortUser sortUser = new SortUser();

        List<User> list = new ArrayList<>();
        List<User> result = new ArrayList<>();
        List<User> expected = new ArrayList<>();

        User user1 = new User("Anton", 10);
        list.add(user1);

        User user2 = new User("Tom", 8);
        list.add(user2);

        User user3 = new User("Jack", 27);
        list.add(user3);

        User user4 = new User("Tom", 3);
        list.add(user4);

        result = sortUser.sortByAllFields(list);

        expected.add(user1);
        expected.add(user3);
        expected.add(user4);
        expected.add(user2);

        assertThat(result, is(expected));
    }
}


text:
package org.apache.cassandra.io.sstable.format;

import java.util.*;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.db.SerializationHeader;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.index.Index;
import org.apache.cassandra.io.FSWriteError;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTable;
import org.apache.cassandra.io.sstable.format.big.BigFormat;
import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
import org.apache.cassandra.io.sstable.metadata.MetadataComponent;
import org.apache.cassandra.io.sstable.metadata.MetadataType;
import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.concurrent.Transactional;

/**
 * This is the API all table writers must implement.
 *
 * TableWriter.create() is the primary way to create a writer for a particular format.
 * The format information is part of the Descriptor.
 */
public abstract class SSTableWriter extends SSTable implements Transactional
{
    protected long repairedAt;
    protected long maxDataAge = -1;
    protected final long keyCount;
    protected final MetadataCollector metadataCollector;
    protected final RowIndexEntry.IndexSerializer rowIndexEntrySerializer;
    protected final SerializationHeader header;
    protected final TransactionalProxy txnProxy = txnProxy();
    protected final Collection<SSTableFlushObserver> observers;

    protected abstract TransactionalProxy txnProxy();

    // due to lack of multiple inheritance, we use an inner class to proxy our Transactional implementation details
    protected abstract class TransactionalProxy extends AbstractTransactional
    {
        // should be set during doPrepare()
        protected SSTableReader finalReader;
        protected boolean openResult;
    }

    protected SSTableWriter(Descriptor descriptor,
                            long keyCount,
                            long repairedAt,
                            CFMetaData metadata,
                            MetadataCollector metadataCollector,
                            SerializationHeader header,
                            Collection<SSTableFlushObserver> observers)
    {
        super(descriptor, components(metadata), metadata);
        this.keyCount = keyCount;
        this.repairedAt = repairedAt;
        this.metadataCollector = metadataCollector;
        this.header = header != null ? header : SerializationHeader.makeWithoutStats(metadata); //null header indicates streaming from pre-3.0 sstable
        this.rowIndexEntrySerializer = descriptor.version.getSSTableFormat().getIndexSerializer(metadata, descriptor.version, header);
        this.observers = observers == null ? Collections.emptySet() : observers;
    }

    public static SSTableWriter create(Descriptor descriptor,
                                       Long keyCount,
                                       Long repairedAt,
                                       CFMetaData metadata,
                                       MetadataCollector metadataCollector,
                                       SerializationHeader header,
                                       Collection<Index> indexes,
                                       LifecycleTransaction txn)
    {
        Factory writerFactory = descriptor.getFormat().getWriterFactory();
        return writerFactory.open(descriptor, keyCount, repairedAt, metadata, metadataCollector, header, observers(descriptor, indexes, txn.opType()), txn);
    }

    public static SSTableWriter create(Descriptor descriptor,
                                       long keyCount,
                                       long repairedAt,
                                       int sstableLevel,
                                       SerializationHeader header,
                                       Collection<Index> indexes,
                                       LifecycleTransaction txn)
    {
        CFMetaData metadata = Schema.instance.getCFMetaData(descriptor);
        return create(metadata, descriptor, keyCount, repairedAt, sstableLevel, header, indexes, txn);
    }

    public static SSTableWriter create(CFMetaData metadata,
                                       Descriptor descriptor,
                                       long keyCount,
                                       long repairedAt,
                                       int sstableLevel,
                                       SerializationHeader header,
                                       Collection<Index> indexes,
                                       LifecycleTransaction txn)
    {
        MetadataCollector collector = new MetadataCollector(metadata.comparator).sstableLevel(sstableLevel);
        return create(descriptor, keyCount, repairedAt, metadata, collector, header, indexes, txn);
    }

    public static SSTableWriter create(String filename,
                                       long keyCount,
                                       long repairedAt,
                                       int sstableLevel,
                                       SerializationHeader header,
                                       Collection<Index> indexes,
                                       LifecycleTransaction txn)
    {
        return create(Descriptor.fromFilename(filename), keyCount, repairedAt, sstableLevel, header, indexes, txn);
    }

    @VisibleForTesting
    public static SSTableWriter create(String filename,
                                       long keyCount,
                                       long repairedAt,
                                       SerializationHeader header,
                                       Collection<Index> indexes,
                                       LifecycleTransaction txn)
    {
        Descriptor descriptor = Descriptor.fromFilename(filename);
        return create(descriptor, keyCount, repairedAt, 0, header, indexes, txn);
    }

    private static Set<Component> components(CFMetaData metadata)
    {
        Set<Component> components = new HashSet<Component>(Arrays.asList(Component.DATA,
                Component.PRIMARY_INDEX,
                Component.STATS,
                Component.SUMMARY,
                Component.TOC,
                Component.digestFor(BigFormat.latestVersion.uncompressedChecksumType())));

        if (metadata.params.bloomFilterFpChance < 1.0)
            components.add(Component.FILTER);

        if (metadata.params.compression.isEnabled())
        {
            components.add(Component.COMPRESSION_INFO);
        }
        else
        {
            // it would feel safer to actually add this component later in maybeWriteDigest(),
            // but the components are unmodifiable after construction
            components.add(Component.CRC);
        }
        return components;
    }

    private static Collection<SSTableFlushObserver> observers(Descriptor descriptor,
                                                              Collection<Index> indexes,
                                                              OperationType operationType)
    {
        if (indexes == null)
            return Collections.emptyList();

        List<SSTableFlushObserver> observers = new ArrayList<>(indexes.size());
        for (Index index : indexes)
        {
            SSTableFlushObserver observer = index.getFlushObserver(descriptor, operationType);
            if (observer != null)
            {
                observer.begin();
                observers.add(observer);
            }
        }

        return ImmutableList.copyOf(observers);
    }

    public abstract void mark();

    /**
     * Appends partition data to this writer.
     *
     * @param iterator the partition to write
     * @return the created index entry if something was written, that is if {@code iterator}
     * wasn't empty, {@code null} otherwise.
     *
     * @throws FSWriteError if a write to the dataFile fails
     */
    public abstract RowIndexEntry append(UnfilteredRowIterator iterator);

    public abstract long getFilePointer();

    public abstract long getOnDiskFilePointer();

    public abstract void resetAndTruncate();

    public SSTableWriter setRepairedAt(long repairedAt)
    {
        if (repairedAt > 0)
            this.repairedAt = repairedAt;
        return this;
    }

    public SSTableWriter setMaxDataAge(long maxDataAge)
    {
        this.maxDataAge = maxDataAge;
        return this;
    }

    public SSTableWriter setOpenResult(boolean openResult)
    {
        txnProxy.openResult = openResult;
        return this;
    }

    /**
     * Open the resultant SSTableReader before it has been fully written
     */
    public abstract SSTableReader openEarly();

    /**
     * Open the resultant SSTableReader once it has been fully written, but before the
     * _set_ of tables that are being written together as one atomic operation are all ready
     */
    public abstract SSTableReader openFinalEarly();

    public SSTableReader finish(long repairedAt, long maxDataAge, boolean openResult)
    {
        if (repairedAt > 0)
            this.repairedAt = repairedAt;
        this.maxDataAge = maxDataAge;
        return finish(openResult);
    }

    public SSTableReader finish(boolean openResult)
    {
        setOpenResult(openResult);
        txnProxy.finish();
        observers.forEach(SSTableFlushObserver::complete);
        return finished();
    }

    /**
     * Open the resultant SSTableReader once it has been fully written, and all related state
     * is ready to be finalised including other sstables being written involved in the same operation
     */
    public SSTableReader finished()
    {
        return txnProxy.finalReader;
    }

    // finalise our state on disk, including renaming
    public final void prepareToCommit()
    {
        txnProxy.prepareToCommit();
    }

    public final Throwable commit(Throwable accumulate)
    {
        try
        {
            return txnProxy.commit(accumulate);
        }
        finally
        {
            observers.forEach(SSTableFlushObserver::complete);
        }
    }

    public final Throwable abort(Throwable accumulate)
    {
        return txnProxy.abort(accumulate);
    }

    public final void close()
    {
        txnProxy.close();
    }

    public final void abort()
    {
        txnProxy.abort();
    }

    protected Map<MetadataType, MetadataComponent> finalizeMetadata()
    {
        return metadataCollector.finalizeMetadata(getPartitioner().getClass().getCanonicalName(),
                                                  metadata.params.bloomFilterFpChance,
                                                  repairedAt,
                                                  header);
    }

    protected StatsMetadata statsMetadata()
    {
        return (StatsMetadata) finalizeMetadata().get(MetadataType.STATS);
    }

    public static void rename(Descriptor tmpdesc, Descriptor newdesc, Set<Component> components)
    {
        for (Component component : Sets.difference(components, Sets.newHashSet(Component.DATA, Component.SUMMARY)))
        {
            FileUtils.renameWithConfirm(tmpdesc.filenameFor(component), newdesc.filenameFor(component));
        }

        // do -Data last because -Data present should mean the sstable was completely renamed before crash
        FileUtils.renameWithConfirm(tmpdesc.filenameFor(Component.DATA), newdesc.filenameFor(Component.DATA));

        // rename it without confirmation because summary can be available for loadNewSSTables but not for closeAndOpenReader
        FileUtils.renameWithOutConfirm(tmpdesc.filenameFor(Component.SUMMARY), newdesc.filenameFor(Component.SUMMARY));
    }

    public static abstract class Factory
    {
        public abstract SSTableWriter open(Descriptor descriptor,
                                           long keyCount,
                                           long repairedAt,
                                           CFMetaData metadata,
                                           MetadataCollector metadataCollector,
                                           SerializationHeader header,
                                           Collection<SSTableFlushObserver> observers,
                                           LifecycleTransaction txn);
    }
}


text:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

namespace UIWidgets {
	/// <summary>
	/// TreeViewNode drop support.
	/// Receive drops from TreeView and ListViewIcons.
	/// </summary>
	[AddComponentMenu("UI/UIWidgets/TreeViewNodeDropSupport")]
	[RequireComponent(typeof(TreeViewComponent))]
	public class TreeViewNodeDropSupport : MonoBehaviour, IDropSupport<TreeNode<TreeViewItem>>, IDropSupport<ListViewIconsItemDescription> {
		TreeViewComponent source;

		/// <summary>
		/// Gets the current TreeViewComponent.
		/// </summary>
		/// <value>Current TreeViewComponent.</value>
		public TreeViewComponent Source {
			get {
				if (source==null)
				{
					source = GetComponent<TreeViewComponent>();
				}
				return source;
			}
		}

		#region IDropSupport<TreeNode<TreeViewItem>>
		/// <summary>
		/// Determines whether this instance can receive drop with the specified data and eventData.
		/// </summary>
		/// <returns><c>true</c> if this instance can receive drop with the specified data and eventData; otherwise, <c>false</c>.</returns>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public bool CanReceiveDrop(TreeNode<TreeViewItem> data, PointerEventData eventData)
		{
			return data.CanBeParent(Source.Node);
		}

		/// <summary>
		/// Process dropped data.
		/// </summary>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public void Drop(TreeNode<TreeViewItem> data, PointerEventData eventData)
		{
			data.Parent = Source.Node;
		}

		/// <summary>
		/// Process canceled drop.
		/// </summary>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public void DropCanceled(TreeNode<TreeViewItem> data, PointerEventData eventData)
		{
		}
		#endregion

		#region IDropSupport<ListViewIconsItemDescription>
		/// <summary>
		/// Determines whether this instance can receive drop with the specified data and eventData.
		/// </summary>
		/// <returns><c>true</c> if this instance can receive drop with the specified data and eventData; otherwise, <c>false</c>.</returns>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public bool CanReceiveDrop(ListViewIconsItemDescription data, PointerEventData eventData)
		{
			return true;
		}

		/// <summary>
		/// Process dropped data.
		/// </summary>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public void Drop(ListViewIconsItemDescription data, PointerEventData eventData)
		{
			var node = Source.Node;
			if (node.Nodes==null)
			{
				node.Nodes = new ObservableList<TreeNode<TreeViewItem>>();
			}

			var newItem = new TreeViewItem(data.Name) {
				LocalizedName = data.LocalizedName,
				Icon = data.Icon,
				Value = data.Value
			};
			var newNode = new TreeNode<TreeViewItem>(newItem);
			node.Nodes.Add(newNode);
		}

		/// <summary>
		/// Process canceled drop.
		/// </summary>
		/// <param name="data">Data.</param>
		/// <param name="eventData">Event data.</param>
		public void DropCanceled(ListViewIconsItemDescription data, PointerEventData eventData)
		{
		}
		#endregion
	}
}


text:
/*
Faça um programa em Linguagem C, que leia um número inteiro, verifique se é positivo ou negativo. Se for positivo, emita uma mensagem ao usuário indicando se este número é par, ímpar ou neutro. Se for negativo, imprima a mensagem: "Valor Negativo!".
*/

#include <stdio.h>
#include <stdlib.h>

main() {
	int num;

	printf("Digite um numero inteiro: ");
	scanf("%i", &num);

	if(num >= 0) {
		if (num == 0) {
			printf("Numero neutro\n");
		} else if(num % 2 == 0) {
			printf("Numero par\n");
		} else {
			printf("Numero impar\n");
		}
	} else {
		printf("Valor negativo\n");
	}

	system("pause");
}


text:
package com.netflix.spinnaker.clouddriver.ecs.security;

import com.netflix.spinnaker.clouddriver.aws.security.NetflixAmazonCredentials;
import com.netflix.spinnaker.clouddriver.aws.security.NetflixAssumeRoleAmazonCredentials;
import com.netflix.spinnaker.clouddriver.aws.security.config.CredentialsConfig;
import com.netflix.spinnaker.clouddriver.aws.security.config.CredentialsLoader;
import com.netflix.spinnaker.clouddriver.security.AccountCredentials;
import com.netflix.spinnaker.clouddriver.security.AccountCredentialsRepository;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class EcsCredentialsInitializer {

  @Bean
  @ConfigurationProperties("ecs")
  public ECSCredentialsConfig ecsCredentialsConfig() {
    return new ECSCredentialsConfig();
  }

  @Bean
  @DependsOn("netflixAmazonCredentials")
  public List<? extends NetflixAmazonCredentials> netflixECSCredentials(
      CredentialsLoader<? extends NetflixAmazonCredentials> credentialsLoader,
      ECSCredentialsConfig credentialsConfig,
      AccountCredentialsRepository accountCredentialsRepository)
      throws Throwable {
    return synchronizeECSAccounts(
        credentialsLoader, credentialsConfig, accountCredentialsRepository);
  }

  private List<? extends NetflixAmazonCredentials> synchronizeECSAccounts(
      CredentialsLoader<? extends NetflixAmazonCredentials> credentialsLoader,
      ECSCredentialsConfig ecsCredentialsConfig,
      AccountCredentialsRepository accountCredentialsRepository)
      throws Throwable {

    // TODO: add support for mutable accounts.
    // List deltaAccounts = ProviderUtils.calculateAccountDeltas(accountCredentialsRepository,
    // NetflixAmazonCredentials.class, accounts);
    List<NetflixAmazonCredentials> credentials = new LinkedList<>();

    for (AccountCredentials accountCredentials : accountCredentialsRepository.getAll()) {
      if (accountCredentials instanceof NetflixAmazonCredentials) {
        for (ECSCredentialsConfig.Account ecsAccount : ecsCredentialsConfig.getAccounts()) {
          if (ecsAccount.getAwsAccount().equals(accountCredentials.getName())) {

            NetflixAmazonCredentials netflixAmazonCredentials =
                (NetflixAmazonCredentials) accountCredentials;

            // TODO: accountCredentials should be serializable or somehow cloneable.
            CredentialsConfig.Account account =
                EcsAccountBuilder.build(netflixAmazonCredentials, ecsAccount.getName(), "ecs");

            CredentialsConfig ecsCopy = new CredentialsConfig();
            ecsCopy.setAccounts(Collections.singletonList(account));

            NetflixECSCredentials ecsCredentials =
                new NetflixAssumeRoleEcsCredentials(
                    (NetflixAssumeRoleAmazonCredentials) credentialsLoader.load(ecsCopy).get(0),
                    ecsAccount.getAwsAccount());
            credentials.add(ecsCredentials);

            accountCredentialsRepository.save(ecsAccount.getName(), ecsCredentials);
            break;
          }
        }
      }
    }

    return credentials;
  }
}


text:
class OperationMatch < ActiveRecord::Base
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>float</title>
        <link rel='stylesheet' type='text/css' href='096977%20fg0805.css' />

                Sed non dolor ut tortor imperdiet hendrerit. Etiam
                malesuada.  Proin rutrum ligula eu nibh.

            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.  Nunc
            eros leo, molestie eu, laoreet eu, rhoncus suscipit, tortor.
            Fusce interdum, metus eu sagittis mollis, lorem augue fringilla
            leo, at pretium magna tortor sed ligula.  Nulla id nisl. Cras
            interdum velit sit amet lacus. In egestas. Integer aliquet.
            Phasellus sagittis congue dui.  Aenean purus neque, viverra at,
            imperdiet sit amet, dignissim vel, sapien. Suspendisse tristique.
            Fusce nunc.  Pellentesque ultrices magna in leo. Vestibulum
            aliquam quam fermentum sapien. Aenean velit erat, vestibulum sit
            amet, rhoncus a, viverra vitae, lacus. Etiam porttitor, mauris ut
            vulputate egestas, tortor dolor tincidunt leo, non scelerisque
            magna dui vitae urna. Vivamus ut massa. Vestibulum sit amet
            sapien et magna varius auctor. Sed a magna. Pellentesque nonummy
            odio nec metus. Pellentesque habitant morbi tristique senectus et
            netus et malesuada fames ac turpis egestas.

            Sed non dolor ut tortor imperdiet hendrerit. Etiam malesuada.
            Proin rutrum ligula eu nibh. Maecenas sit amet est. In eros.
            Proin elit lacus, volutpat at, sagittis et, convallis sit amet,
            sapien. Fusce bibendum augue vitae sapien. Morbi feugiat
            venenatis libero. Vestibulum porttitor. Cras neque ante, luctus
            luctus, elementum volutpat, euismod eget, nunc. Praesent ornare.
            Mauris cursus dolor.


text:
(function ($) {

Drupal.behaviors.fileFieldsetSummaries = {
  attach: function (context) {
    $('fieldset.file-form-destination', context).drupalSetSummary(function (context) {
      var scheme = $('.form-item-scheme input:checked', context).parent().text();
      return Drupal.t('Destination: @scheme', { '@scheme': scheme });
    });
    $('fieldset.file-form-user', context).drupalSetSummary(function (context) {
      var name = $('.form-item-name input', context).val() || Drupal.settings.anonymous;
      return Drupal.t('Associated with @name', { '@name': name });
    });
  }
};

})(jQuery);


text:
package cert_test

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"

	"github.com/cloudfoundry/bosh-agent/platform/cert"
	boshdir "github.com/cloudfoundry/bosh-agent/settings/directories"
	"github.com/cloudfoundry/bosh-utils/logger"
	boshsys "github.com/cloudfoundry/bosh-utils/system"
	fakesys "github.com/cloudfoundry/bosh-utils/system/fakes"
)

const cert1 string = `-----BEGIN CERTIFICATE-----
MIIEJDCCAwygAwIBAgIJAO+CqgiJnCgpMA0GCSqGSIb3DQEBBQUAMGkxCzAJBgNV
BAYTAkNBMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
qokoSBXzJCJTt2P681gyqBDr/hUYzqpoXUsOTRisScbEbaSv8hTiTeFJUMyNQAqn
DtmvI8bXKxU=
-----END CERTIFICATE-----`

var _ = Describe("Certificate Management", func() {
	var log logger.Logger
	BeforeEach(func() {
		log = logger.NewLogger(logger.LevelNone)
	})

	Describe("CertificateSplitting", func() {
		It("splits 2 back-to-back certificates", func() {
			certs := fmt.Sprintf("%s\n%s\n", cert1, cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(result[1]).To(Equal(cert1))
			Expect(len(result)).To(Equal(2))
		})

		It("splits 2 back-to-back certificates without trailing newline", func() {
			certs := fmt.Sprintf("%s\n%s", cert1, cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(result[1]).To(Equal(cert1))
			Expect(len(result)).To(Equal(2))
		})

		It("splits 2 back-to-back certificates ignoring junk between them", func() {
			certs := fmt.Sprintf("%s\n abcdefghij %s\n", cert1, cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(result[1]).To(Equal(cert1))
			Expect(len(result)).To(Equal(2))
		})

		It("handles 1 certificate with trailing newline", func() {
			certs := fmt.Sprintf("%s\n", cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(len(result)).To(Equal(1))
		})

		It("handles 1 certificate without trailing newline", func() {
			result := cert.SplitCerts(cert1)
			Expect(result[0]).To(Equal(cert1))
			Expect(len(result)).To(Equal(1))
		})

		It("ignores junk before the first certicate", func() {
			certs := fmt.Sprintf("abcdefg %s\n%s\n", cert1, cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(result[1]).To(Equal(cert1))
			Expect(len(result)).To(Equal(2))
		})

		It("ignores junk after the last certicate", func() {
			certs := fmt.Sprintf("%s\n%s\n abcdefghij", cert1, cert1)

			result := cert.SplitCerts(certs)
			Expect(result[0]).To(Equal(cert1))
			Expect(result[1]).To(Equal(cert1))
			Expect(len(result)).To(Equal(2))
		})

		It("returns an empty slice for an empty string", func() {
			result := cert.SplitCerts("")
			Expect(len(result)).To(Equal(0))
		})

		It("returns an empty slice for an non-empty string that does not contain any certificates", func() {
			result := cert.SplitCerts("abcdefghij")
			Expect(len(result)).To(Equal(0))
		})
	})

	Describe("DeleteFile()", func() {
		var (
			fakeFs *fakesys.FakeFileSystem
		)

		BeforeEach(func() {
			fakeFs = fakesys.NewFakeFileSystem()
		})

		It("only deletes the files with the given prefix", func() {
			err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/delete/stuff/in/different_file_1.bar", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{
				"/path/to/delete/stuff/in/delete_me_1.foo",
				"/path/to/delete/stuff/in/delete_me_2.foo",
			})
			count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_")
			Expect(err).ToNot(HaveOccurred())
			Expect(count).To(Equal(2))
			Expect(countFiles(fakeFs, "/path/to/delete/stuff/in/")).To(Equal(1))
		})

		It("only deletes the files in the given path", func() {
			err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/other/things/in/delete_me_3.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{
				"/path/to/delete/stuff/in/delete_me_1.foo",
				"/path/to/delete/stuff/in/delete_me_2.foo",
			})
			count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_")
			Expect(err).ToNot(HaveOccurred())
			Expect(count).To(Equal(2))
			Expect(countFiles(fakeFs, "/path/to/delete/stuff/in/")).To(Equal(0))
			Expect(countFiles(fakeFs, "/path/to/other/things/in/")).To(Equal(1))
		})

		It("returns an error when glob fails", func() {
			fakeFs.GlobErr = errors.New("couldn't walk")
			err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_")
			Expect(err).To(HaveOccurred())
			Expect(count).To(Equal(0))
		})

		It("returns an error when RemoveAll() fails", func() {
			fakeFs.RemoveAllStub = func(_ string) error {
				return errors.New("couldn't delete")
			}
			err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye")
			Expect(err).NotTo(HaveOccurred())
			fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{
				"/path/to/delete/stuff/in/delete_me_1.foo",
				"/path/to/delete/stuff/in/delete_me_2.bar",
			})
			count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_")
			Expect(err).To(HaveOccurred())
			Expect(count).To(Equal(0))
		})
	})

	Describe("cert.Manager implementations", func() {
		var (
			fakeFs        *fakesys.FakeFileSystem
			fakeCmdRunner *fakesys.FakeCmdRunner
			certManager   cert.Manager
		)

		SharedLinuxCertManagerExamples := func(certBasePath, certUpdateProgram string) {
			It("writes 1 cert to a file", func() {
				err := certManager.UpdateCertificates(cert1)
				Expect(err).NotTo(HaveOccurred())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeTrue())
			})

			It("writes each cert to its own file", func() {
				certs := fmt.Sprintf("%s\n%s\n", cert1, cert1)

				err := certManager.UpdateCertificates(certs)
				Expect(err).NotTo(HaveOccurred())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeTrue())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-2.crt", certBasePath))).To(BeTrue())
				Expect(countFiles(fakeFs, certBasePath)).To(Equal(2))
			})

			It("deletes all certs when passed an empty string", func() {
				err := fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye")
				Expect(err).NotTo(HaveOccurred())
				fakeFs.SetGlob(fmt.Sprintf("%s/bosh-trusted-cert-*", certBasePath), []string{
					fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath),
				})
				err = certManager.UpdateCertificates("")
				Expect(err).NotTo(HaveOccurred())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeFalse())
			})

			It("deletes existing cert files before writing new ones", func() {
				certs := fmt.Sprintf("%s\n%s\n", cert1, cert1)
				err := certManager.UpdateCertificates(certs)
				Expect(err).NotTo(HaveOccurred())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeTrue())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-2.crt", certBasePath))).To(BeTrue())
				Expect(countFiles(fakeFs, certBasePath)).To(Equal(2))

				fakeFs.SetGlob(fmt.Sprintf("%s/bosh-trusted-cert-*", certBasePath), []string{
					fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath),
					fmt.Sprintf("%s/bosh-trusted-cert-2.crt", certBasePath),
				})
				err = certManager.UpdateCertificates(cert1)
				Expect(err).NotTo(HaveOccurred())
				Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeTrue())
				Expect(countFiles(fakeFs, certBasePath)).To(Equal(1))
			})

			It("returns an error when writing new cert files fails", func() {
				fakeFs.WriteFileError = errors.New("NOT ALLOW")
				err := certManager.UpdateCertificates(cert1)
				Expect(err).To(HaveOccurred())
			})

			It("returns an error when deleting old certs fails", func() {
				fakeFs.RemoveAllStub = func(_ string) error {
					return errors.New("NOT ALLOW")
				}
				err := fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye")
				Expect(err).NotTo(HaveOccurred())
				fakeFs.SetGlob(fmt.Sprintf("%s/bosh-trusted-cert-*", certBasePath), []string{
					fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath),
				})

				err = certManager.UpdateCertificates("")
				Expect(err).To(HaveOccurred())
			})
		}

		Context("Ubuntu", func() {
			var (
				fakeResult   boshsys.Result
				fakeProcess1 *fakesys.FakeProcess
				fakeProcess2 *fakesys.FakeProcess
				fakeProcess3 *fakesys.FakeProcess
			)
			BeforeEach(func() {
				fakeFs = fakesys.NewFakeFileSystem()
				fakeCmdRunner = fakesys.NewFakeCmdRunner()
				fakeCmdRunner.AddCmdResult("/usr/sbin/update-ca-certificates", fakesys.FakeCmdResult{
					Stdout:     "",
					Stderr:     "",
					ExitStatus: 0,
					Sticky:     true,
				})
				certManager = cert.NewUbuntuCertManager(fakeFs, fakeCmdRunner, 1, log)
				fakeResult = boshsys.Result{
					Stdout:     "",
					Stderr:     "",
					ExitStatus: 0,
					Error:      nil,
				}

				fakeProcess1 = &fakesys.FakeProcess{WaitResult: fakeResult}
				fakeProcess2 = &fakesys.FakeProcess{WaitResult: fakeResult}
				fakeProcess3 = &fakesys.FakeProcess{WaitResult: fakeResult}

				fakeCmdRunner.AddProcess("/usr/sbin/update-ca-certificates -f", fakeProcess1)
				fakeCmdRunner.AddProcess("/usr/sbin/update-ca-certificates -f", fakeProcess2)
				fakeCmdRunner.AddProcess("/usr/sbin/update-ca-certificates -f", fakeProcess3)
			})

			SharedLinuxCertManagerExamples("/usr/local/share/ca-certificates", "/usr/sbin/update-ca-certificates")

			It("updates certs", func() {
				err := certManager.UpdateCertificates(cert1)

				Expect(fakeProcess1.Waited).To(BeTrue())
				Expect(fakeProcess1.TerminatedNicely).To(BeFalse())

				Expect(err).ToNot(HaveOccurred())
			})

			It("fails at first try and succeeds by killing and re-run", func() {
				fakeResult.ExitStatus = 143
				fakeResult.Error = errors.New("command failed")

				fakeProcess1.TerminatedNicelyCallBack = func(p *fakesys.FakeProcess) {}

				err := certManager.UpdateCertificates(cert1)

				Expect(fakeProcess1.Waited).To(BeTrue())
				Expect(fakeProcess1.TerminatedNicely).To(BeTrue())
				Expect(fakeProcess1.TerminateNicelyKillGracePeriod).To(Equal(5 * time.Second))
				Expect(fakeProcess2.Waited).To(BeTrue())
				Expect(fakeProcess2.TerminatedNicely).To(BeFalse())
				Expect(fakeProcess3.Waited).To(BeFalse())

				Expect(err).ToNot(HaveOccurred())
			})

			It("terminates update cert command nicely upon time-out", func() {
				fakeResult.ExitStatus = 143
				fakeResult.Error = errors.New("command failed")

				fakeProcess1.TerminatedNicelyCallBack = func(p *fakesys.FakeProcess) {}
				fakeProcess2.TerminatedNicelyCallBack = func(p *fakesys.FakeProcess) {}
				fakeProcess3.TerminatedNicelyCallBack = func(p *fakesys.FakeProcess) {}

				err := certManager.UpdateCertificates(cert1)

				Expect(fakeProcess1.Waited).To(BeTrue())
				Expect(fakeProcess1.TerminatedNicely).To(BeTrue())
				Expect(fakeProcess1.TerminateNicelyKillGracePeriod).To(Equal(5 * time.Second))
				Expect(fakeProcess2.Waited).To(BeTrue())
				Expect(fakeProcess2.TerminatedNicely).To(BeTrue())
				Expect(fakeProcess2.TerminateNicelyKillGracePeriod).To(Equal(5 * time.Second))
				Expect(fakeProcess3.Waited).To(BeTrue())
				Expect(fakeProcess3.TerminatedNicely).To(BeTrue())
				Expect(fakeProcess3.TerminateNicelyKillGracePeriod).To(Equal(5 * time.Second))

				Expect(err).To(HaveOccurred())
			})
		})

		Context("CentOS", func() {
			BeforeEach(func() {
				fakeFs = fakesys.NewFakeFileSystem()
				fakeCmdRunner = fakesys.NewFakeCmdRunner()
				fakeCmdRunner.AddCmdResult("/usr/bin/update-ca-trust", fakesys.FakeCmdResult{
					Stdout:     "",
					Stderr:     "",
					ExitStatus: 0,
					Sticky:     true,
				})
				certManager = cert.NewCentOSCertManager(fakeFs, fakeCmdRunner, 0, log)
			})

			SharedLinuxCertManagerExamples("/etc/pki/ca-trust/source/anchors", "/usr/bin/update-ca-trust")

			It("executes update cert command", func() {
				fakeCmdRunner = fakesys.NewFakeCmdRunner()
				fakeCmdRunner.AddCmdResult("/usr/bin/update-ca-trust", fakesys.FakeCmdResult{
					Stdout:     "",
					Stderr:     "",
					ExitStatus: 2,
					Error:      errors.New("command failed"),
				})
				certManager = cert.NewCentOSCertManager(fakeFs, fakeCmdRunner, 0, log)

				err := certManager.UpdateCertificates(cert1)
				Expect(err).To(HaveOccurred())
			})
		})

		Context("Windows", func() {
			const validCerts string = `-----BEGIN CERTIFICATE-----
MIIC0jCCAboCCQCuQJScK+G0WzANBgkqhkiG9w0BAQsFADArMQswCQYDVQQGEwJV
UzENMAsGA1UECBMEQk9TSDENMAsGA1UEChMEQk9TSDAeFw0xNjA4MDIxNDQ2MTla
Fw0xNzA4MDIxNDQ2MTlaMCsxCzAJBgNVBAYTAlVTMQ0wCwYDVQQIEwRCT1NIMQ0w
CwYDVQQKEwRCT1NIMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA22ea
D3XBlXOLDzcJOKKICYrkoHxT4wg+9ybRS9r/oAx+5xEwTdoUNvK3j7hUP4ttfCgT
qx9TUN+h4HzjDZQQ9oj8aUOhV83BLawUxDUOZbyDGUrHCKXkE5UKeiMjVtfmZNd0
0t+zepLF+helT0p+ogXFGFM6pKgfNoPHrf5R+KUqzvCoeMiL9nxO/yypfR+fnKOQ
KYGo55BlH0nYLAwKfefiUkaqAOMyQ7mdLf+iWT6CqfZ83OdNSXe8SmaDspnHkipu
/9+/VBEABv+IiAgLrosynSIA0DFP4vPYuV6PzHW8pXpTB6CSl8QwhPQv3SpgjXoB
O3rMc0pJ/2sSRIXKvQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBnbY4FOo28yWAJ
G5hkOReWl6f6y/LNa+W5B7zqoPuUpiYwujdDSGA+wsig46EK65mEK2NdGO2PnTKw
hP27FHbagskiu9h0PtEfBcRi6lNySOgQNFEqpB+maOzwOwYRRxdABBu0ieSaxYXI
TINuBZ/Fi1igmL4Auwl4mFLYn6ofrtZFOLp7a1vGDewZFG75V4t2IdKvN8HsCnPW
vHfs34+z5ZdCHWY7uQFmC1K+4oqKanG7Lw78bZ+HaU5fLb8CpvkiDmCDA/KXXpCS
En4cZ4+CJRoyzjaooDDOo/+9P7Mx1O12Ev/lna2laLLueUyTN3aVPbLvWsUrCr/1
NrjpvLIP
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIC0jCCAboCCQC/JcYWmGS6OTANBgkqhkiG9w0BAQsFADArMQswCQYDVQQGEwJV
UzENMAsGA1UECBMEQk9TSDENMAsGA1UEChMEQk9TSDAeFw0xNjA4MDIyMTQyMzJa
Fw0xNzA4MDIyMTQyMzJaMCsxCzAJBgNVBAYTAlVTMQ0wCwYDVQQIEwRCT1NIMQ0w
CwYDVQQKEwRCT1NIMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7Z4R
8dSoipPja6cnjs5x3bk2zfuHwSFW6XHOASNVQXxdSgbRixXeiSh0cJoT0FUvGnQX
ptU2WeMtx7ZrXp3YcO312bVxjyEBhzlvLhdqWHaATOucuvXi+sH+I4EXVhlHlbr7
+OhR85q0DCdF9x7U3xVJm/JG/cNXHtNB0aaYUZ9HXpVpt8yMdVGQCE8FMqNQ4DsU
/WHRCaTkoP3BXbza090yoGMSCT8IilrKUnwmtNZiDerWwTJfVz6oqIN8Ei+myJ4M
qvis48OQkOgg/e1RbrCGuF2L7q7Ja3j1RQWgEXrNiK45Eae3W6uhbTV6RXPrk9Xk
Si8Atvw03rkuqJjXYwIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQC6HK25lvP2PLmF
KRQ4z7qOvIVXNl9m4scHCsINF+VpZo+miXK2kMhOk6Bade+PG76dYRNhPXv0vWqe
QNHDW2J85dF1h0Dbdl84irCijSb1WOPHdRgqSMooTaRxn0mpRMKgUdOSuJTUj6N7
yHdf1gYNB8vt/NzTfl1gKc0KjK9L8I2Y0myq9Hu1aHVELFAKskhZJpnToZn1w6O0
WDtlweO/jTmDwyeIqzA/60LXAv7xfJMRoyNElqWHC+EeeuMnh6BJPSdwC8ynTP3R
SDRQj6MXyyS4LBMZA56DYXaXyR6pDTpmvBUNQ4FR0UgYm1GeGWo1kOUPjfs7sUQz
aAzOWRDC
-----END CERTIFICATE-----`

			var certThumbprints []string = []string{
				"23AC7706D032651BE146388FA8DF7B0B2DD7CFA6",
				"73C0BFD7BB53EC299B289CB86A010AE485F6D49B",
			}

			const getCertScript string = `
(Get-ChildItem Cert:\LocalMachine\Root | where { $_.Subject -eq "O=BOSH, S=BOSH, C=US" }).Length`

			const removeCertScript string = `
if (Test-Path %[1]s) {
	Remove-Item %[1]s
}`

			var tempDir string
			var dirProvider boshdir.Provider
			var fs boshsys.FileSystem

			BeforeEach(func() {
				if runtime.GOOS != "windows" {
					Skip("Only run on Windows")
				}

				fs = boshsys.NewOsFileSystem(log)
				var err error
				tempDir, err = fs.TempDir("")
				Expect(err).To(BeNil())
				dirProvider = boshdir.NewProvider(tempDir)
				certManager = cert.NewWindowsCertManager(fs, boshsys.NewExecCmdRunner(log), dirProvider, log)
			})

			AfterEach(func() {
				for _, thumbprint := range certThumbprints {
					cmd := exec.Command("powershell", "-Command", fmt.Sprintf(removeCertScript, `Cert:\LocalMachine\Root\`+thumbprint)) //nolint:gosec
					session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
					Expect(err).To(BeNil())
					Eventually(session).Should(gexec.Exit(0))
				}
				os.RemoveAll(tempDir)
			})

			It("should create the tmpDir if doesn't exist", func() {
				_, err := os.Stat(dirProvider.TmpDir())
				fmt.Println("BEfore", dirProvider.TmpDir(), err)
				missing := os.IsNotExist(err)
				Expect(missing).To(BeTrue())
				err = certManager.UpdateCertificates(validCerts)
				Expect(err).To(BeNil())
				_, err = os.Stat(dirProvider.TmpDir())
				Expect(err).To(BeNil())
			})

			Context("When TempDir exists", func() {
				BeforeEach(func() {
					err := fs.MkdirAll(dirProvider.TmpDir(), os.FileMode(0777))
					Expect(err).To(BeNil())
				})
				It("adds certs to the trusted cert chain", func() {
					err := certManager.UpdateCertificates(validCerts)
					Expect(err).To(BeNil())

					cmd := exec.Command("powershell", "-Command", getCertScript)
					session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
					Expect(err).To(BeNil())

					Eventually(session).Should(gexec.Exit(0))
					Eventually(session.Out).Should(gbytes.Say("2"))
				})

				It("returns an error when passed an invalid cert", func() {
					err := certManager.UpdateCertificates(cert1)
					Expect(err).NotTo(BeNil())
				})

				It("deletes all certs when passed an empty string", func() {
					err := certManager.UpdateCertificates(validCerts)
					Expect(err).To(BeNil())

					err = certManager.UpdateCertificates("")
					Expect(err).To(BeNil())

					cmd := exec.Command("powershell", "-Command", getCertScript)
					session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
					Expect(err).To(BeNil())

					Eventually(session).Should(gexec.Exit(0))
					Eventually(session.Out).Should(gbytes.Say("0"))
				})
			})

		})
	})
})

func countFiles(fs boshsys.FileSystem, dir string) (count int) {
	err := fs.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if filepath.Join(path) == filepath.Join(dir) { //nolint:gocritic
			return nil
		}
		count++
		return nil
	})
	Expect(err).NotTo(HaveOccurred())
	return
}


text:
/*	$NetBSD: tc_3maxplus.c,v 1.1 1998/04/19 07:59:13 jonathan Exp $	*/

/*
 * Copyright (c) 1998 Jonathan Stone.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Jonathan Stone for
 *      the NetBSD Project.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>			/* RCS ID & Copyright macro defns */
__KERNEL_RCSID(0, "$NetBSD: tc_3maxplus.c,v 1.1 1998/04/19 07:59:13 jonathan Exp $ ");

#include <sys/types.h>
#include <sys/device.h>
#include <dev/cons.h>
#include <dev/tc/tcvar.h>
#include <machine/autoconf.h>

#include <pmax/pmax/pmaxtype.h>
#include <pmax/pmax/kn03.h>

int	tcbus_match_3maxplus(struct device *, struct cfdata *, void *);
void	tcbus_attach_3maxplus(struct device *, struct device *, void *);

/*
 * The only builtin Turbochannel device on the kn03 (and kmin)
 * is the IOCTL asic, which is mapped into TC slot 3.
 */
const struct tc_builtin tc_kn03_builtins[] = {
	{ "IOCTL   ",	3, 0x0, TC_C(3), /*TC_C(3)*/ }
};

/* 3MAXPLUS TC slot addresses */
static struct tc_slotdesc tc_kn03_slots [4] = {
       	{ TC_KV(KN03_PHYS_TC_0_START), TC_C(0) },  /* 0 - tc option slot 0 */
	{ TC_KV(KN03_PHYS_TC_1_START), TC_C(1) },  /* 1 - tc option slot 1 */
	{ TC_KV(KN03_PHYS_TC_2_START), TC_C(2) },  /* 2 - tc option slot 2 */
	{ TC_KV(KN03_PHYS_TC_3_START), TC_C(3) }   /* 3 - IOasic on b'board */
};
int tc_kn03_nslots =
    sizeof(tc_kn03_slots) / sizeof(tc_kn03_slots[0]);

/*
 * 3MAXPLUS turbochannel autoconfiguration table
 */
struct tcbus_attach_args kn03_tc_desc =
{
	"tc",				/* XXX common substructure */
	0,				/* XXX bus_space_tag */
	TC_SPEED_25_MHZ,
	KN03_TC_NSLOTS, tc_kn03_slots,
	1, tc_kn03_builtins,
	0, /*,tc_ds_ioasic_intr_establish, */
	0 /* tc_ds_ioasic_intr_disestablish */
};

int
tcbus_match_3maxplus(parent, cfdata, aux)
        struct device *parent;
        struct cfdata *cfdata;
        void *aux;
{
	return (systype == DS_3MAXPLUS);
}

void
tcbus_attach_3maxplus(parent, self, aux)
        struct device *parent;
        struct device *self;
        void *aux;
{

}


text:
namespace osrm
{
namespace extractor
{

class CompressedEdgeContainer;

namespace detail
{
template <storage::Ownership Ownership> class SegmentDataContainerImpl;
}

namespace serialization
{
template <storage::Ownership Ownership>
inline void read(storage::io::FileReader &reader,
                 detail::SegmentDataContainerImpl<Ownership> &segment_data);
template <storage::Ownership Ownership>
inline void write(storage::io::FileWriter &writer,
                  const detail::SegmentDataContainerImpl<Ownership> &segment_data);
}

namespace detail
{
template <storage::Ownership Ownership> class SegmentDataContainerImpl
{
    template <typename T> using Vector = util::ViewOrVector<T, Ownership>;
    template <typename T, std::size_t Bits>
    using PackedVector = util::detail::PackedVector<T, Bits, Ownership>;

    friend CompressedEdgeContainer;

  public:
    // FIXME We should change the indexing to Edge-Based-Node id
    using DirectionalGeometryID = std::uint32_t;
    using SegmentOffset = std::uint32_t;
    using SegmentWeightVector = PackedVector<SegmentWeight, SEGMENT_WEIGHT_BITS>;
    using SegmentDurationVector = PackedVector<SegmentDuration, SEGMENT_DURAITON_BITS>;
    using SegmentDatasourceVector = Vector<DatasourceID>;

    SegmentDataContainerImpl() = default;

    SegmentDataContainerImpl(Vector<std::uint32_t> index_,
                             Vector<NodeID> nodes_,
                             SegmentWeightVector fwd_weights_,
                             SegmentWeightVector rev_weights_,
                             SegmentDurationVector fwd_durations_,
                             SegmentDurationVector rev_durations_,
                             SegmentDatasourceVector fwd_datasources_,
                             SegmentDatasourceVector rev_datasources_)
        : index(std::move(index_)), nodes(std::move(nodes_)), fwd_weights(std::move(fwd_weights_)),
          rev_weights(std::move(rev_weights_)), fwd_durations(std::move(fwd_durations_)),
          rev_durations(std::move(rev_durations_)), fwd_datasources(std::move(fwd_datasources_)),
          rev_datasources(std::move(rev_datasources_))
    {
    }

    auto GetForwardGeometry(const DirectionalGeometryID id)
    {
        const auto begin = nodes.begin() + index[id];
        const auto end = nodes.begin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseGeometry(const DirectionalGeometryID id)
    {
        return boost::adaptors::reverse(GetForwardGeometry(id));
    }

    auto GetForwardDurations(const DirectionalGeometryID id)
    {
        const auto begin = fwd_durations.begin() + index[id] + 1;
        const auto end = fwd_durations.begin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseDurations(const DirectionalGeometryID id)
    {
        const auto begin = rev_durations.begin() + index[id];
        const auto end = rev_durations.begin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetForwardWeights(const DirectionalGeometryID id)
    {
        const auto begin = fwd_weights.begin() + index[id] + 1;
        const auto end = fwd_weights.begin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseWeights(const DirectionalGeometryID id)
    {
        const auto begin = rev_weights.begin() + index[id];
        const auto end = rev_weights.begin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetForwardDatasources(const DirectionalGeometryID id)
    {
        const auto begin = fwd_datasources.begin() + index[id] + 1;
        const auto end = fwd_datasources.begin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseDatasources(const DirectionalGeometryID id)
    {
        const auto begin = rev_datasources.begin() + index[id];
        const auto end = rev_datasources.begin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetForwardGeometry(const DirectionalGeometryID id) const
    {
        const auto begin = nodes.cbegin() + index[id];
        const auto end = nodes.cbegin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseGeometry(const DirectionalGeometryID id) const
    {
        return boost::adaptors::reverse(GetForwardGeometry(id));
    }

    auto GetForwardDurations(const DirectionalGeometryID id) const
    {
        const auto begin = fwd_durations.cbegin() + index[id] + 1;
        const auto end = fwd_durations.cbegin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseDurations(const DirectionalGeometryID id) const
    {
        const auto begin = rev_durations.cbegin() + index[id];
        const auto end = rev_durations.cbegin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetForwardWeights(const DirectionalGeometryID id) const
    {
        const auto begin = fwd_weights.cbegin() + index[id] + 1;
        const auto end = fwd_weights.cbegin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseWeights(const DirectionalGeometryID id) const
    {
        const auto begin = rev_weights.cbegin() + index[id];
        const auto end = rev_weights.cbegin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetForwardDatasources(const DirectionalGeometryID id) const
    {
        const auto begin = fwd_datasources.cbegin() + index[id] + 1;
        const auto end = fwd_datasources.cbegin() + index[id + 1];

        return boost::make_iterator_range(begin, end);
    }

    auto GetReverseDatasources(const DirectionalGeometryID id) const
    {
        const auto begin = rev_datasources.cbegin() + index[id];
        const auto end = rev_datasources.cbegin() + index[id + 1] - 1;

        return boost::adaptors::reverse(boost::make_iterator_range(begin, end));
    }

    auto GetNumberOfGeometries() const { return index.size() - 1; }
    auto GetNumberOfSegments() const { return fwd_weights.size(); }

    friend void
    serialization::read<Ownership>(storage::io::FileReader &reader,
                                   detail::SegmentDataContainerImpl<Ownership> &segment_data);
    friend void serialization::write<Ownership>(
        storage::io::FileWriter &writer,
        const detail::SegmentDataContainerImpl<Ownership> &segment_data);

  private:
    Vector<std::uint32_t> index;
    Vector<NodeID> nodes;
    SegmentWeightVector fwd_weights;
    SegmentWeightVector rev_weights;
    SegmentDurationVector fwd_durations;
    SegmentDurationVector rev_durations;
    SegmentDatasourceVector fwd_datasources;
    SegmentDatasourceVector rev_datasources;
};
}

using SegmentDataView = detail::SegmentDataContainerImpl<storage::Ownership::View>;
using SegmentDataContainer = detail::SegmentDataContainerImpl<storage::Ownership::Container>;
}
}

#endif


text:
/*
Strike by Appiphony

Version: 1.0.0
Website: http://www.lightningstrike.io
GitHub: https://github.com/appiphony/Strike-Components
License: BSD 3-Clause License
*/
({
    show: function(component, event, helper){
        window.addEventListener('keyup', component._closeModal);

        var params = {
            preEvent: 'strike_evt_modalShow',
            afterEvent: 'strike_evt_modalShown',
            showModal: true,
            targetEl: 'modal'
        }

        component.set('v.showModal', params.showModal);
        helper.modalTransitioner(component, params);
    },
    hide: function(component, event, helper) {
        window.removeEventListener('keyup', component._closeModal);

        var params = {
            preEvent: 'strike_evt_modalHide',
            afterEvent: 'strike_evt_modalHidden',
            showModal: false,
            targetEl: 'backdrop'
        }

        component.set('v.showModal', params.showModal);
        helper.modalTransitioner(component, params);
    },
    modalTransitioner: function(component, params){
        var targetEl = component.find(params.targetEl).getElement();

        if (targetEl == null) {
            return;
        }

        var preEvent = component.getEvent(params.preEvent);
        var showModal = params.showModal;
        var preEventAttribute = showModal ? 'v.showingModal' : 'v.fadeIn'
        var afterEventAttribute = showModal ? 'v.fadeIn' : 'v.showingModal'

        component.set(preEventAttribute, showModal);
        preEvent.fire();

        if(showModal){
            //need to fadeIn on the next rendering cycle
            setTimeout($A.getCallback(function(){
                component.set(afterEventAttribute, showModal);
            }), 5);
        }
    }
})
/*
Copyright 2017 Appiphony, LLC

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


text:
#include "modules/map/tools/map_datachecker/server/pose_collection.h"

namespace apollo {
namespace hdmap {

PoseCollection::PoseCollection(std::shared_ptr<JsonConf> sp_conf) {
  sp_conf_ = sp_conf;
  Reset();
}

void PoseCollection::Reset() {
  sp_poses_ = std::make_shared<std::vector<FramePose>>();
}

void PoseCollection::Collect(const FramePose& pose) {
  if (sp_poses_ == nullptr) {
    sp_poses_ = std::make_shared<std::vector<FramePose>>();
  }
  sp_poses_->push_back(pose);
}

std::shared_ptr<std::vector<FramePose>> PoseCollection::GetPoses() const {
  return sp_poses_;
}

}  // namespace hdmap
}  // namespace apollo