text:
import eventlet
import mock

from oslo_config import cfg
from oslo_messaging import conffixture

from congress import exception

from congress.dse2 import data_service
from congress.dse2 import datasource_manager as ds_manager
from congress.dse2 import dse_node
from congress.tests.api import base as api_base
from congress.tests import base
from congress.tests import helper

# Leave this in place for manual testing.
# For manual testing, support using rabbit driver instead of fake
USE_RABBIT = False
# if len(sys.argv) > 1:
#     driver_flg = sys.argv[1].lower()
#     if driver_flg == '--rabbit':
#         USE_RABBIT = True
#     elif driver_flg != '--fake':
#         print("Usage: %s [--fake | --rabbit]" % sys.argv[0])
#         sys.exit(1)
#     sys.argv[1:] = sys.argv[2:]

class _PingRpcEndpoint(object):
    def __init__(self, node_id):
        self.node_id = node_id
        self.ping_receive_count = 0
        self.ping_received_from = []

    def ping(self, client_ctxt, **args):
        return args

    def ping_test(self, client_ctxt, **args):
        self.ping_receive_count += 1
        self.ping_received_from.append(client_ctxt)
        return args

class _PingRpcService(data_service.DataService):
    def __init__(self, service_id, node_id):
        self.endpoints = [_PingRpcEndpoint(node_id)]
        super(_PingRpcService, self).__init__(service_id)

    def rpc_endpoints(self):
        return self.endpoints

class TestDseNode(base.SqlTestCase):

    def setUp(self):
        super(TestDseNode, self).setUp()

        if USE_RABBIT:
            self.messaging_config = cfg.CONF
        else:
            mc_fixture = conffixture.ConfFixture(cfg.CONF)
            mc_fixture.conf.transport_url = 'kombu+memory://'
            self.messaging_config = mc_fixture.conf
        self.messaging_config.rpc_response_timeout = 1

    def test_start_stop(self):
        # create node and register services
        node = helper.make_dsenode_new_partition('test_node',
                                                 self.messaging_config, [])
        services = []
        for i in range(2):
            service = data_service.DataService('test-service-%s' % i)
            node.register_service(service)
            services.append(service)
        for s in node.get_services(True):
            self.assertTrue(s._running,
                            "Service '%s' started" % str(s))
        self.assertEqual(set(services), set(node.get_services()),
                         "All services accounted for on node.")
        self.assertTrue(node._rpc_server._started,
                        "RPC server is started")
        self.assertTrue(node._control_bus._running,
                        "Control Bus is started")

        # stop node
        node.stop()
        node.wait()
        self.assertFalse(node._running,
                         "Node is stopped after node start")
        for idx, s in enumerate(node.get_services(True)):
            self.assertFalse(s._running,
                             "Service '%s' stopped after node stop" % str(s))
        # TODO(pballand): fix bug
        # self.assertFalse(node._rpc_server._started,
        #                  "RPC server is stopped after node stop")
        self.assertFalse(node._control_bus._running,
                         "Control Bus is stopped after node stop")

        # restart node
        node.start()
        for s in node.get_services(True):
            self.assertTrue(s._running,
                            "Service '%s' started" % str(s))
        self.assertEqual(set(services), set(node.get_services()),
                         "All services accounted for on node.")
        self.assertTrue(node._rpc_server._started,
                        "RPC server is started")
        self.assertTrue(node._control_bus._running,
                        "Control Bus is started")

    def test_context(self):
        # Context must not only rely on node_id to prohibit multiple instances
        # of a node_id on the DSE
        part = helper.get_new_partition()
        n1 = helper.make_dsenode_same_partition(part, 'node_id',
                                                self.messaging_config, [])
        n2 = helper.make_dsenode_same_partition(part, 'node_id',
                                                self.messaging_config, [])
        self.assertEqual(n1._message_context, n1._message_context,
                         "Comparison of context from the same node is equal")
        self.assertNotEqual(n1._message_context, n2._message_context,
                            "Comparison of context from the different nodes "
                            "is not equal")

    def test_node_rpc(self):
        """Validate calling RPCs on DseNode"""
        part = helper.get_new_partition()
        nodes = []
        endpoints = []
        for i in range(3):
            nid = 'rpcnode%s' % i
            endpoints.append(_PingRpcEndpoint(nid))
            nodes.append(
                helper.make_dsenode_same_partition(
                    part, nid, self.messaging_config, [endpoints[-1]]))

        # Send from each node to each other node
        for i, source in enumerate(nodes):
            # intentionally including self in RPC target
            for j, target in enumerate(nodes):
                scount = endpoints[j].ping_receive_count
                args = {'arg1': 1, 'arg2': 'a'}
                ret = source.invoke_node_rpc(target.node_id, 'ping_test', args)
                self.assertEqual(ret, args, "Ping echoed arguments")
                ecount = endpoints[j].ping_receive_count
                self.assertEqual(ecount - scount, 1,
                                 "Node %s received ping (%s was sending)"
                                 % (nodes[j].node_id, nodes[i].node_id))
                self.assertEqual(
                    endpoints[j].ping_received_from[-1]['node_id'],
                    nodes[i].node_id,
                    "Last ping received on %s was from %s" % (
                        nodes[j].node_id, nodes[i].node_id))

    def test_node_broadcast_rpc(self):
        """Validate calling RPCs on DseNode"""
        part = helper.get_new_partition()
        nodes = []
        endpoints = []
        for i in range(3):
            nid = 'rpcnode%s' % i
            endpoints.append(_PingRpcEndpoint(nid))
            nodes.append(
                helper.make_dsenode_same_partition(
                    part, nid, self.messaging_config, [endpoints[-1]]))

        # Send from each node to all other nodes
        for i, source in enumerate(nodes):
            scounts = []
            for j, target in enumerate(nodes):
                scounts.append(endpoints[j].ping_receive_count)
            source.broadcast_node_rpc('ping_test', {'arg1': 1, 'arg2': 'a'})
            eventlet.sleep(0.5)  # wait for async delivery
            for j, target in enumerate(nodes):
                ecount = endpoints[j].ping_receive_count
                self.assertEqual(ecount - scounts[j], 1,
                                 "Node %s received ping (%s was sending)"
                                 % (nodes[j].node_id, source.node_id))
                self.assertEqual(
                    endpoints[j].ping_received_from[-1]['node_id'],
                    source.node_id,
                    "Last ping received on %s was from %s" % (
                        nodes[j].node_id, source.node_id))

    def test_service_rpc(self):
        part = helper.get_new_partition()
        nodes = []
        services = []
        for i in range(3):
            nid = 'svc_rpc_node%s' % i
            node = helper.make_dsenode_same_partition(
                part, nid, self.messaging_config)
            service = _PingRpcService('srpc_node_svc%s' % i, nid)
            node.register_service(service)
            nodes.append(node)
            services.append(service)

        # Send from each node to each other node
        for i, source in enumerate(nodes):
            # intentionally including self in RPC target
            for j, service in enumerate(services):
                ep = nodes[j]._services[-1].endpoints[0]
                scount = ep.ping_receive_count
                args = {'arg1': 1, 'arg2': 'a'}
                ret = source.invoke_service_rpc(
                    service.service_id, 'ping_test', args)
                self.assertEqual(ret, args, "Ping echoed arguments")
                ecount = ep.ping_receive_count
                self.assertEqual(ecount - scount, 1,
                                 "Node %s received ping (%s was sending)"
                                 % (nodes[j].node_id, nodes[i].node_id))
                self.assertEqual(
                    ep.ping_received_from[-1]['node_id'],
                    nodes[i].node_id,
                    "Last ping received on %s was from %s" % (
                        nodes[j].node_id, nodes[i].node_id))

    def test_broadcast_service_rpc(self):
        part = helper.get_new_partition()
        nodes = []
        services = []
        for i in range(3):
            nid = 'svc_rpc_node%s' % i
            node = helper.make_dsenode_same_partition(
                part, nid, self.messaging_config)
            service = _PingRpcService('tbsr_svc', nid)
            node.register_service(service)
            nodes.append(node)
            services.append(service)

        # Send from each node to all services
        for i, source in enumerate(nodes):
            scounts = []
            for j, target in enumerate(nodes):
                ep = nodes[j]._services[-1].endpoints[0]
                scounts.append(ep.ping_receive_count)
            source.broadcast_service_rpc(
                'tbsr_svc', 'ping_test', {'arg1': 1, 'arg2': 'a'})
            eventlet.sleep(0.5)  # wait for async delivery
            for j, target in enumerate(nodes):
                ep = nodes[j]._services[-1].endpoints[0]
                ecount = ep.ping_receive_count
                self.assertEqual(ecount - scounts[j], 1,
                                 "Node %s received ping (%s was sending)"
                                 % (nodes[j].node_id, source.node_id))
                self.assertEqual(
                    ep.ping_received_from[-1]['node_id'],
                    source.node_id,
                    "Last ping received on %s was from %s" % (
                        nodes[j].node_id, source.node_id))

    def test_get_global_service_names(self):
        node = helper.make_dsenode_new_partition('test_node',
                                                 self.messaging_config, [])
        test1 = _PingRpcService('test1', 'test1')
        test2 = _PingRpcService('test2', 'test2')
        node.register_service(test1)
        node.register_service(test2)
        actual = set(node.get_global_service_names())
        self.assertEqual(actual, set(['test1', 'test2']))

    def test_unregister_service(self):
        node = helper.make_dsenode_new_partition('test_node',
                                                 self.messaging_config, [])
        test1 = _PingRpcService('test1', 'test1')
        uuid1 = '1c5d6da0-64ae-11e6-8852-000c29242e6f'
        test1.ds_id = uuid1
        test2 = _PingRpcService('test2', 'test2')
        uuid2 = 'd36d3781-e9e4-4278-bbf4-9f5fef7c5101'
        test2.ds_id = uuid2
        node.register_service(test1)
        node.register_service(test2)
        actual = set(node.get_global_service_names())
        self.assertEqual(actual, set(['test1', 'test2']))

        # unregister by service_id
        node.unregister_service(service_id='test1')
        actual = set(node.get_global_service_names())
        self.assertEqual(actual, set(['test2']))

        # unregister by uuid
        node.unregister_service(uuid_=uuid2)
        actual = set(node.get_global_service_names())
        self.assertEqual(actual, set())

    def _get_datasource_request(self):
        # leave ID out--generated during creation
        return {'name': 'datasource1',
                'driver': 'fake_datasource',
                'description': 'hello world!',
                'enabled': True,
                'type': None,
                'config': {'auth_url': 'foo',
                           'username': 'armax',
                           'password': '<hidden>',
                           'tenant_name': 'armax'}}

    @mock.patch.object(dse_node.DseNode, 'get_driver_info')
    def test_missing_driver_datasources(self, mock_driver_info):
        services = api_base.setup_config(api=False, policy=False)
        node = services['node']
        ds_manager = services['ds_manager']
        ds = self._get_datasource_request()
        ds_manager.add_datasource(ds)
        mock_driver_info.side_effect = [exception.DriverNotFound]
        node.delete_missing_driver_datasources()
        self.assertRaises(exception.DatasourceNotFound,
                          node.get_datasource, 'datasource1')

class TestDSManagerService(base.TestCase):

    def setUp(self):
        super(TestDSManagerService, self).setUp()

    def test_ds_manager_endpoints_add_ds(self):
        ds_manager_service = ds_manager.DSManagerService('test_mgr')
        node_mock = mock.MagicMock()
        ds_manager_service.add_datasource = mock.MagicMock()
        ds_manager_service.add_datasource.return_value = 'add_datasource'
        ds_manager_service.node = node_mock
        endpoints = ds_manager.DSManagerEndpoints(ds_manager_service)

        expect_ret = 'add_datasource'
        self.assertEqual(expect_ret, endpoints.add_datasource('context', {}))

        ds_manager_service.add_datasource.assert_called_with({})

    def test_ds_manager_endpoints_delete_ds(self):
        ds_manager_service = ds_manager.DSManagerService('test_mgr')
        node_mock = mock.MagicMock()
        ds_manager_service.delete_datasource = mock.MagicMock()
        ds_manager_service.delete_datasource.return_value = 'delete_datasource'
        ds_manager_service.node = node_mock
        endpoints = ds_manager.DSManagerEndpoints(ds_manager_service)

        expect_ret = 'delete_datasource'
        self.assertEqual(expect_ret,
                         endpoints.delete_datasource('context', 'ds-id'))

        ds_manager_service.delete_datasource.assert_called_with('ds-id')

# Leave this to make manual testing with RabbitMQ easy
# if __name__ == '__main__':
#     import unittest
#     unittest.main(verbosity=2)


text:
import { ActiveDescendantKeyManager } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { hasModifierKey } from '@angular/cdk/keycodes';
import {
  AfterContentInit,
  AfterViewInit,
  Attribute,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChildren,
  ElementRef,
  EventEmitter,
  Inject,
  Input,
  OnChanges,
  OnDestroy,
  Optional,
  Output,
  QueryList,
  SimpleChanges,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { fromEvent, interval, merge, of, Subscription } from 'rxjs';
import { debounce, take } from 'rxjs/operators';
import { BooleanInput, Key } from '../../../utils';
import type { NovoChipList } from '../../chips';
import {
  CanDisable,
  CanDisableCtor,
  HasOverlayCtor,
  mixinDisabled,
  mixinOverlay,
  NovoOptgroup,
  NovoOption,
  NovoOptionSelectionChange,
  NOVO_OPTION_PARENT_COMPONENT,
} from '../../common';
import { NovoOverlayTemplateComponent } from '../../common/overlay';
import { NovoFieldElement, NOVO_FORM_FIELD } from '../field';
import { NovoFieldControl } from '../field-control';

/** Event object that is emitted when an autocomplete option is selected. */
export class NovoOptionSelectedEvent {
  constructor(
    /** Reference to the autocomplete panel that emitted the event. */
    public source: NovoAutocompleteElement,
    /** Option that was selected. */
    public option: NovoOption,
  ) {}
}

// Boilerplate for applying mixins
class NovoAutocompleteBase {
  constructor() {}
}
const NovoAutocompleteMixins: HasOverlayCtor & CanDisableCtor & typeof NovoAutocompleteBase = mixinOverlay(
  mixinDisabled(NovoAutocompleteBase),
);

@Component({
  selector: 'novo-autocomplete',
  templateUrl: 'autocomplete.component.html',
  styleUrls: ['autocomplete.component.scss'],
  host: {
    class: 'novo-autocomplete',
    // Always set the tabindex to -1 so that it doesn't overlap with any custom tabindex the
    // consumer may have provided, while still being able to receive focus.
    '[attr.tabindex]': 'disabled ? null : -1',
  },
  providers: [{ provide: NOVO_OPTION_PARENT_COMPONENT, useExisting: NovoAutocompleteElement }],
  exportAs: 'novoAutocomplete',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NovoAutocompleteElement
  extends NovoAutocompleteMixins
  implements CanDisable, AfterContentInit, AfterViewInit, OnChanges, OnDestroy
{
  private _stateChanges = Subscription.EMPTY;
  private _activeOptionChanges = Subscription.EMPTY;
  private _selectedOptionChanges = Subscription.EMPTY;
  private _keyDownChanges = Subscription.EMPTY;

  /** Manages active item in option list based on key events. */
  private _keyManager: ActiveDescendantKeyManager<NovoOption>;

  /** Old value of the native input. Used to work around issues with the `input` event on IE. */
  private _previousValue: string | number | null;

  @ContentChildren(NovoOptgroup, { descendants: true }) optionGroups: QueryList<NovoOptgroup>;
  @ContentChildren(NovoOption, { descendants: true }) options: QueryList<NovoOption>;

  /** Event that is emitted whenever an option from the list is selected. */
  @Output() readonly optionSelected: EventEmitter<NovoOptionSelectedEvent> = new EventEmitter<NovoOptionSelectedEvent>();
  /** Emits whenever an option is activated using the keyboard. */
  @Output() readonly optionActivated: EventEmitter<NovoOptionSelectedEvent> = new EventEmitter<NovoOptionSelectedEvent>();

  /** Tabindex for the toggle. */
  @Input() tabIndex: number | null;

  /** Key to use to trigger autocomplete. used for textarea. */
  @Input() triggerOn: (control: NovoFieldControl<any>) => boolean = (control) => control.focused;

  /** Function that maps an option's control value to its display value in the trigger. */
  @Input() displayWith: ((value: any) => string) | null = null;

  /** Screenreader label for the button. */
  @Input('aria-label') ariaLabel: string;

  /** Whether the user should be allowed to select multiple options. */
  @Input()
  get multiple(): boolean {
    return this._multiple;
  }
  set multiple(value: boolean) {
    this._multiple = coerceBooleanProperty(value);
  }
  private _multiple: boolean = false;

  /** Whether the toggle button is disabled. */
  @Input()
  @BooleanInput()
  get disabled(): boolean {
    if (this._disabled === undefined && this._formField?._control) {
      return this._formField._control.disabled;
    }
    return !!this._disabled;
  }
  set disabled(value: boolean) {
    this._disabled = coerceBooleanProperty(value);
  }
  private _disabled: boolean;

  /** Element for the panel containing the autocomplete options. */
  @ViewChild(NovoOverlayTemplateComponent)
  overlay: NovoOverlayTemplateComponent;

  element: ElementRef;

  constructor(
    private _elementRef: ElementRef,
    private cdr: ChangeDetectorRef,
    @Attribute('tabindex') defaultTabIndex: string,
    @Optional() @Inject(NOVO_FORM_FIELD) private _formField: NovoFieldElement,
  ) {
    super();
    const parsedTabIndex = Number(defaultTabIndex);
    this.tabIndex = parsedTabIndex || parsedTabIndex === 0 ? parsedTabIndex : null;
  }

  ngOnChanges(changes: SimpleChanges) {
    this._watchStateChanges();
    this._watchSelectionEvents();
  }

  ngOnDestroy() {
    this._stateChanges.unsubscribe();
    this._activeOptionChanges.unsubscribe();
    this._selectedOptionChanges.unsubscribe();
    this._keyDownChanges.unsubscribe();
  }

  ngAfterContentInit() {
    this._keyManager = new ActiveDescendantKeyManager<NovoOption>(this.options).withWrap();
    this._activeOptionChanges = this._keyManager.change.subscribe((index) => {
      this.optionActivated.emit({ source: this, option: this.options.toArray()[index] || null });
    });
    this.element = this._formField.getConnectedOverlayOrigin() || this._elementRef;
    this._keyDownChanges = fromEvent(this.element.nativeElement, 'keydown').subscribe((event: KeyboardEvent) => this._handleKeydown(event));
    this.options.changes.subscribe(() => {
      this._watchStateChanges();
      this._watchSelectionEvents();
      Promise.resolve().then(() => {
        this.checkSelectedOptions();
      });
    });
  }

  ngAfterViewInit() {
    this._watchStateChanges();
    this._watchSelectionEvents();
  }

  checkPanel() {
    const isTriggered = this.triggerOn(this._formField._control);
    if (isTriggered && this.element) {
      this.openPanel();
    }
  }

  private _setTriggerValue(option: NovoOption): void {
    const toDisplay = this.displayWith ? this.displayWith(option) : option?.viewValue;
    // Simply falling back to an empty string if the display value is falsy does not work properly.
    // The display value can also be the number zero and shouldn't fall back to an empty string.
    const displayValue = toDisplay != null ? toDisplay : '';
    const optionValue = option.value;
    // If it's used within a `NovoField`, we should set it through the property so it can go
    // through change detection.
    if (this._formField) {
      const { controlType, lastCaretPosition = 0 } = this._formField._control;
      if (controlType === 'textarea') {
        const currentValue = this._formField._control.value.split('');
        currentValue.splice(lastCaretPosition, 0, displayValue);
        this._formField._control.value = currentValue.join('');
      } else if (controlType === 'chip-list') {
        const chipList = this._formField._control as NovoChipList;
        const currentValue = this._formField._control.value;
        if (currentValue.includes(optionValue)) {
          chipList.removeValue(optionValue);
        } else {
          chipList.addValue(optionValue);
        }
      } else {
        let valueToEmit: any = optionValue;
        if (this.multiple) {
          const currentValue = this._formField._control.value;
          if (Array.isArray(currentValue)) {
            if (currentValue.includes(optionValue)) {
              valueToEmit = currentValue.filter((it) => it === optionValue);
            } else {
              valueToEmit = [...currentValue, optionValue];
            }
          } else if (currentValue === optionValue) {
            valueToEmit = [];
          } else {
            valueToEmit = [currentValue, optionValue];
          }
        }
        this._formField._control.value = valueToEmit;
      }
    } else {
      // this._element.nativeElement.value = inputValue;
      console.warn(`AutoComplete only intended to be used within a NovoField`);
    }
    this._previousValue = optionValue;
  }

  /**
   * Clear any previous selected option and emit a selection change event for this option
   */
  private _clearPreviousSelectedOption(skip: NovoOption) {
    this.options.forEach((option) => {
      if (option !== skip && option.selected) {
        option.deselect();
      }
    });
  }

  /** Emits the `select` event. */
  private _emitSelectEvent(option: NovoOption): void {
    const event = new NovoOptionSelectedEvent(this, option);
    this.optionSelected.emit(event);
  }

  /**
   * This method closes the panel, and if a value is specified, also sets the associated
   * control to that value. It will also mark the control as dirty if this interaction
   * stemmed from the user.
   */
  private _setValueAndClose(event: NovoOptionSelectionChange | null): void {
    if (event && event.source) {
      if (!this.multiple) this._clearPreviousSelectedOption(event.source);
      this._setTriggerValue(event.source);
      // this._onChange(event.source.value);
      // this._element.nativeElement.focus();
      // this._formField._control.focus();
      this._emitSelectEvent(event.source);
      this._watchSelectionEvents();
    }

    if (!this.multiple) this.closePanel();
  }

  private _watchSelectionEvents() {
    const selectionEvents = this.options ? merge(...this.options.map((option) => option.onSelectionChange)) : of();
    this._selectedOptionChanges.unsubscribe();
    this._selectedOptionChanges = selectionEvents.pipe(take(1)).subscribe((evt: NovoOptionSelectionChange) => {
      this._setValueAndClose(evt);
    });
  }

  private _watchStateChanges() {
    const inputStateChanged = this._formField.stateChanges;
    this._stateChanges.unsubscribe();
    this._stateChanges = merge(inputStateChanged)
      .pipe(debounce(() => interval(10)))
      .subscribe(() => {
        this.checkSelectedOptions();
        this.checkPanel();
        this.cdr.markForCheck();
      });
  }

  /** The currently active option, coerced to MatOption type. */
  get activeOption(): NovoOption | null {
    if (this._keyManager) {
      return this._keyManager.activeItem;
    }

    return null;
  }

  _handleKeydown(event: KeyboardEvent): void {
    const key = event.key;

    // Prevent the default action on all escape key presses. This is here primarily to bring IE
    // in line with other browsers. By default, pressing escape on IE will cause it to revert
    // the input value to the one that it had on focus, however it won't dispatch any events
    // which means that the model value will be out of sync with the view.
    if (key === Key.Escape && !hasModifierKey(event)) {
      event.preventDefault();
    }

    if (this.activeOption && key === Key.Enter && this.panelOpen) {
      this.activeOption._selectViaInteraction();
      // this._resetActiveItem();
      event.preventDefault();
    } else {
      const prevActiveItem = this._keyManager.activeItem;
      const isArrowKey = key === Key.ArrowUp || key === Key.ArrowDown;

      if (this.panelOpen || key === Key.Tab) {
        this._keyManager.onKeydown(event);
      } else if (isArrowKey && !this.overlay.panelOpen) {
        this.openPanel();
      }

      // if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) {
      //   this._scrollToOption(this.autocomplete._keyManager.activeItemIndex || 0);
      // }
    }
  }

  private checkSelectedOptions() {
    if (this.multiple && Array.isArray(this._formField._control.value)) {
      const value = this._formField._control.value;
      this.options.forEach((option) => option.deselect());
      value.forEach((currentValue: any) => this._selectValue(currentValue));
    }
  }
  /**
   * Finds and selects and option based on its value.
   * @returns Option that has the corresponding value.
   */
  private _selectValue(value: any): NovoOption | undefined {
    const correspondingOption = this.options.find((option: NovoOption) => {
      return option.value === value;
    });
    correspondingOption?.select();
    return correspondingOption;
  }
}

redpajama_set_name: RedPajamaGithub


text:
import { helper } from '@ember/component/helper';

export function truncateText(params, hash) {
  var value = params[0];
  var len = hash.limit;
  var out = '';

  if (value !== undefined) {
    out = value.substr(0, len);

    if (value.length > len) {
      out += '...';
    }

  } else {
    out = '';
  }

  return out;
}

export default helper(truncateText);


text:
module DashboardEdit {
  import IFeature = csComp.Services.IFeature;
  import IFeatureType = csComp.Services.IFeatureType;
  import IPropertyType = csComp.Services.IPropertyType;
  import IPropertyTypeData = csComp.Services.IPropertyTypeData;

  export interface IDashboardEditScope extends ng.IScope {
    vm: DashboardEditCtrl;

  }

  export class DashboardEditCtrl {
    private scope: IDashboardEditScope;

    public dashboard : csComp.Services.Dashboard;

    // $inject annotation.
    // It provides $injector with information about dependencies to be injected into constructor
    // it is better to have it close to the constructor, because the parameters must match in count and type.
    // See http://docs.angularjs.org/guide/di
    public static $inject = [
      '$scope',
      'mapService',
      'layerService',
      'messageBusService',
      'dashboardService'
    ];

    // dependencies are injected via AngularJS $injector
    // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html
    constructor(
      private $scope: IDashboardEditScope,
      private $mapService: csComp.Services.MapService,
      private $layerService: csComp.Services.LayerService,
      private $messageBusService: csComp.Services.MessageBusService,
      private $dashboardService: csComp.Services.DashboardService
      ) {
      this.scope = $scope;
      $scope.vm = this;
      this.dashboard = $scope.$parent["data"];
      console.log(this.dashboard);

    }

    public toggleTimeline() {
        //this.$dashboardService.mainDashboard.showTimeline = !this.$dashboardService.mainDashboard.showTimeline;
        this.checkTimeline();
    }

    public toggleMap() {
        setTimeout(() => {
            this.checkMap();
        }, 100);

    }

    public checkMap() {
      var db = this.$layerService.project.activeDashboard;
        if (db.showMap != this.$layerService.visual.mapVisible) {
            if (db.showMap) {
                this.$layerService.visual.mapVisible = true;
            } else {
                this.$layerService.visual.mapVisible = false;
            }
            if (this.$scope.$root.$$phase != '$apply' && this.$scope.$root.$$phase != '$digest') { this.$scope.$apply(); }
        }

        if (db.showMap && this.dashboard.baselayer) {
            this.$messageBusService.publish("map","setbaselayer",this.dashboard.baselayer);
        }
    }

    public checkTimeline() {
        var db = this.$layerService.project.activeDashboard;

        if (db.timeline) {

            var s = new Date(db.timeline.start);
            var e = new Date();
            if (db.timeline.end) e = new Date(db.timeline.end);
            //this.$messageBusService.publish("timeline", "updateTimerange", { "start": s, "end": e});
                this.$messageBusService.publish("timeline", "updateTimerange", { start: s, end: e });

            //this.$layerService.project.timeLine.setFocus(db.timeline.focusDate, db.timeline.startDate, db.timeline.endDate);
        }

        if (db.showTimeline != this.$mapService.timelineVisible) {
            if (db.showTimeline) {
                this.$mapService.timelineVisible = true;
            } else {
                this.$mapService.timelineVisible = false;
            }

            if (this.$scope.$root.$$phase != '$apply' && this.$scope.$root.$$phase != '$digest') { this.$scope.$apply(); }
        }
    }

  }
}


text:
<?php

namespace reservasBundle\Entity;

/**
 * Alergenos
 */
class Alergenos
{
    /**
     * @var integer
     */
    private $idalergenos;

    /**
     * @var string
     */
    private $nombre;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $reservasreservas;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->reservasreservas = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get idalergenos
     *
     * @return integer
     */
    public function getIdalergenos()
    {
        return $this->idalergenos;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     *
     * @return Alergenos
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Add reservasreserva
     *
     * @param \reservasBundle\Entity\Reservas $reservasreserva
     *
     * @return Alergenos
     */
    public function addReservasreserva(\reservasBundle\Entity\Reservas $reservasreserva)
    {
        $this->reservasreservas[] = $reservasreserva;

        return $this;
    }

    /**
     * Remove reservasreserva
     *
     * @param \reservasBundle\Entity\Reservas $reservasreserva
     */
    public function removeReservasreserva(\reservasBundle\Entity\Reservas $reservasreserva)
    {
        $this->reservasreservas->removeElement($reservasreserva);
    }

    /**
     * Get reservasreservas
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getReservasreservas()
    {
        return $this->reservasreservas;
    }
    public function toArray(){
      $array=array(
        'Id'=>$this->getIdalergenos(),
        'Nombre'=>$this->getNombre()
      );
      return $array;
    }
}


text:
"""Produce MQM scores from MQM ratings tsv file."""

import collections
import csv
import json
from absl import app
from absl import flags
import glob

flags.DEFINE_string('input', '/dev/stdin', 'Input MQM ratings tsv file.')
flags.DEFINE_string('output', '/dev/stdout', 'Output MQM score file.')
flags.DEFINE_string(
    'weights', 'Major:5 Minor:1 Neutral:0 '
    'Major/Non-translation!:25 Minor/Fluency/Punctuation:0.1',
    'List of weight specs, in format: "severity[/category[/subcategory]]:wt". '
    'The most specific match is applied to each error.')
flags.DEFINE_bool('unbabel', False, 'Input tsv is in Unbabel format.')
flags.DEFINE_bool(
    'recompute_unbabel', False,
    'Apply Google-style weights to Unbabel ratings rather than reading scores '
    'directly from mqm field in last column of tsv.')
flags.DEFINE_bool(
    'force_contiguous', True,
    'Raise an error if annotated segments within a doc aren\'t contiguous')

FLAGS = flags.FLAGS

def Score(weights, items):
  while items:
    if '/'.join(items) in weights:
      return weights['/'.join(items)]
    items = items[:-1]
  return 0

def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  weights = {}
  for e in FLAGS.weights.split():
    c, w = e.split(':')
    weights[c] = float(w)

  scores = {}  # sys -> doc > doc_id -> rater -> [score]
  quoting = csv.QUOTE_MINIMAL if FLAGS.unbabel else csv.QUOTE_NONE
  with open(FLAGS.input) as f:
    for row in csv.DictReader(f, delimiter='\t', quoting=quoting):
      system, doc, doc_id = row['system'], row['doc'], int(row['doc_id'])
      if FLAGS.unbabel and not FLAGS.recompute_unbabel:
        score = json.loads(row['misc'])['mqm']
      else:
        score = Score(weights, [row['severity']] + row['category'].split('/'))
      if system not in scores:
        scores[system] = {}
      if doc not in scores[system]:
        scores[system][doc] = {}
      if doc_id not in scores[system][doc]:
        scores[system][doc][doc_id] = collections.defaultdict(list)
      scores[system][doc][doc_id][row['rater']].append(score)

  if FLAGS.force_contiguous:
    for system in scores:
      for doc in scores[system]:
        ids = sorted(scores[system][doc])
        if ids != list(range(min(ids), max(ids) + 1)):
          raise ValueError(f'Non-contiguous segments for {system}/{doc}')

  with open(FLAGS.output, 'w') as f:
    for system in scores:
      for doc in scores[system]:
        for doc_id in sorted(scores[system][doc]):
          rater_scores = {}
          for rater, vals in scores[system][doc][doc_id].items():
            if FLAGS.unbabel and not FLAGS.recompute_unbabel:
              rater_scores[rater] = sum(vals) / len(vals)
            else:
              rater_scores[rater] = sum(vals)
          global_score = sum(rater_scores.values()) / len(rater_scores)
          if not FLAGS.unbabel or FLAGS.recompute_unbabel:
            global_score *= -1
          f.write(f'{system}\t{doc}\t{doc_id}\t{global_score}')
          for rater in sorted(rater_scores):
            f.write(f'\t{rater}={rater_scores[rater]}')
          f.write('\n')

if __name__ == '__main__':
  app.run(main)


text:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace HaagsVertaler
{
  public class Startup
  {
      public Startup(IConfiguration configuration)
      {
          Configuration = configuration;
      }

      public IConfiguration Configuration { get; }

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddResponseCompression();
          services.AddRazorPages()
              .AddRazorRuntimeCompilation();
      }

      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Error");
              app.UseHsts();
          }

          app.UseHttpsRedirection();
          app.UseStaticFiles(new StaticFileOptions()
          {
              HttpsCompression = Microsoft.AspNetCore.Http.Features.HttpsCompressionMode.Compress,
              OnPrepareResponse = (context) =>
              {
                  var headers = context.Context.Response.GetTypedHeaders();
                  headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue
                  {
                      Public = true,
                      MaxAge = TimeSpan.FromDays(365)
                  };
              }
          });

          app.UseRouting();

          app.UseAuthorization();

          app.UseEndpoints(endpoints =>
          {
              endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Home}/{action=Index}/{id?}");
          });
      }
  }
}


text:
<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../css/print.css" rel="stylesheet" type="text/css" media="print">

  <meta name="description" content="Documentation for the chrome.pageCapture module, which is part of the Google Chrome  extension APIs."><title>chrome.pageCapture - Google Chrome Extensions - Google Code</title>
    <link href="../css/ApiRefStyles.css" rel="stylesheet" type="text/css">
  <link href="../css/shared.css" rel="stylesheet" type="text/css">

    You are viewing extension docs in chrome via the 'file:' scheme: are you expecting to see local changes when you refresh? You'll need run chrome with --allow-file-access-from-files.

    WARNING: This is the BETA documentation.
    It may not work with the stable release of Chrome.
    <select id="branchChooser">
      <option>Choose a different version...
      </option><option value="">Stable
      </option><option value="beta">Beta
      </option><option value="dev">Dev
      </option><option value="trunk">Trunk
    </option></select>

    WARNING: This is unofficial documentation. It may not work with the
    current release of Chrome.
    <button id="goToOfficialDocs">Go to the official docs</button>

      Skip to page content
      Skip to main navigation

          <form action="http://www.google.com/cse" id="cse" style="margin-top:0.5em">

              <input type="hidden" name="cx" value="002967670403910741006:61_cvzfqtno">
              <input type="hidden" name="ie" value="UTF-8">
              <input type="text" name="q" value="" size="55">
              <input class="gsc-search-button" type="submit" name="sa" value="Search">

              e.g. "page action" or "tabs"

          </form>

Google Chrome Extensions (Labs)

            Home

            Docs

            FAQ

            Samples

            Group

            Questions?

Getting Started

Overview

What's New?

Developer's Guide

Browser UI

Browser Actions

Context Menus

Desktop Notifications

Omnibox

Options Pages

Override Pages

Page Actions

Browser Interaction

Bookmarks

Cookies

Developer Tools

Events

History

Management

Tabs

Windows

Implementation

Accessibility

Background Pages

Content Scripts

Cross-Origin XHR

Internationalization

Message Passing

Optional Permissions

NPAPI Plugins

Finishing

Hosting

Other Deployment Options

Packaged Apps

Tutorials

Debugging

Google Analytics

OAuth

Reference

Formats

Manifest Files

Match Patterns

Permission Warnings

chrome.* APIs

Other APIs

Samples

More

Chrome Web Store

Hosted Apps

Themes

chrome.pageCapture

Contents

              Manifest

                API reference: chrome.pageCapture

            Methods

                saveAsMHTML

The pageCapture API allows you to save a tab as MHTML.

MHTML is a standard format
supported by most browsers. It encapsulates in a single file a page and all
its resources (CSS files, images..).

Note that for security reasons a MHTML file can only be loaded from the file
system and that it can only be loaded in the main frame.

Manifest

You must declare the "pageCapture" permission
in the extension manifest
to use the history API.
For example:

{
  "name": "My extension",
  ...
  "permissions": [
    "pageCapture"
  ],
  ...
}

API reference: chrome.pageCapture

Methods

saveAsMHTML

                  chrome.pageCapture.saveAsMHTML(object
                      <var>details</var>, function
                      <var>callback</var>)

Saves the content of the tab with given id as MHTML.

Parameters

            <var>details</var>

                  (

                        object

                  )

            Undocumented.

            <var>tabId</var>

                  (

                        integer

                  )

The id of the tab to save as MHTML.

            <var>callback</var>

                  (

                        function

                  )

Called when the MHTML has been generated.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(blob mhtmlData) {...};

            <var>mhtmlData</var>

                  (
                    optional

                        blob

                  )

The MHTML data as a Blob.

  Except as otherwise noted,
  the content of this page is licensed under the Creative Commons
  Attribution 3.0 License, and code samples are licensed under the
  BSD License.

  ©2011 Google


text:
<?php

namespace Fingerpaint;

/**
 * A theme class to provide core functionality for the theme.
 *
 * PHP Version 5.5+
 *
 * @category Themes
 * @package  Fingerpaint_Theme_Extensions
 * @author   Fingerpaint Developers <devs@fingerpaintmarketing.com>
 * @license  Copyright 2015 Fingerpaint. All rights reserved.
 * @link     http://fingerpaintmarketing.com
 */
class Site_Theme extends Theme {

	/**
	 * A function to return the result of any get function in the instance of this class.
	 *
	 * @param string $func The function part to use when getting the result to return.
	 *
	 * @access public
	 * @return mixed
	 */
	public static function get( $func ) {
		return call_user_func( [ get_called_class(), 'get_' . $func ] );
	}

	/**
	 * A function to echo the result of any get function in the instance of this class.
	 *
	 * @param string $func THe function part to use when getting the result to echo.
	 *
	 * @access public
	 * @return void
	 */
	public static function the( $func ) {
		echo self::get( $func );
	}

	/**
	 * An action hook to register widgets.
	 *
	 * @see https://developer.wordpress.org/reference/hooks/widgets_init/
	 *
	 * @access public
	 * @return void
	 */
	public static function action_widgets_init() {

		/* Register custom sidebars. */
		register_sidebar( [
			'name'          => __( 'Social Links', 'sage' ),
			'id'            => 'sidebar-social-links',
			'before_widget' => '
',
			'after_widget'  => '
',
			'before_title'  => '
',
			'after_title'   => '
',
		] );

		/* Register custom widgets. */
		register_widget( __NAMESPACE__ . '\\Widget_Social_Link' );
	}

	/**
	 * Action hook to register custom scripts and styles.
	 *
	 * @see https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
	 *
	 * @access public
	 * @return void
	 */
	public static function action_wp_enqueue_scripts() {

		/* Store the theme path for use in Sage scripts. */
		wp_localize_script( 'sage_js', 'themes_path', substr( get_template_directory(), strpos( get_template_directory(), 'wp-content/' ) ) );

		/* Add the Wistia Embed Shepherd script to help with Google Analytics integration. */
		// IF USING WISTIA, UNCOMMENT THIS SECTION.
		//wp_enqueue_script( 'wistia-embed-shepherd', '//fast.wistia.com/assets/external/embed_shepherd-v1.js' );
	}

	/**
	 * A filter for the confirmation to add custom JavaScript to fire Google Analytics events.
	 *
	 * @param mixed $confirmation The confirmation message or array to be filtered.
	 * @param array $form The current form.
	 * @param array $lead The current entry array.
	 * @param bool $is_ajax Whether the form is configured to be submitted via AJAX or not.
	 *
	 * @see https://www.gravityhelp.com/documentation/article/gform_confirmation/
	 *
	 * @access public
	 * @return mixed
	 */
	public static function filter_gform_confirmation( $confirmation, $form, $lead, $is_ajax ) {

		/* If the confirmation is not configured to be text, bail out. */
		if ( is_array( $confirmation ) ) {
			return $confirmation;
		}

		/* Set default form values for Google Analytics events. */
		$events = [
			[
				'category' => 'Forms',
				'action'   => 'Submitted',
				'label'    => strip_tags( $form['title'] ),
			],
		];

		/* Override or augment default event values in specific cases, if needed. */
		switch ( $form['id'] ) {
		}

		/* Add Google Analytics tracking snippet to confirmation message dynamically. */
		$ga_function_calls = [ ];
		foreach ( $events as $event ) {

			/* Build base function call. */
			$function_call = 'ga(\'send\', \'event\', \'' . $event['category'] . '\', \'' . $event['action'] . '\'';

			/* If a label is specified, add it. */
			if ( ! empty( $event['label'] ) ) {
				$function_call .= ', \'' . $event['label'] . '\'';
			}

			/* If a value is specified, add it. */
			if ( ! empty( $event['value'] ) && is_int( $event['value'] ) ) {
				$function_call .= ', ' . $event['value'];
			}

			/* Close the function call and add it to the array of function calls. */
			$function_call .= ');';
			$ga_function_calls[] = $function_call;
		}

		/* Flatten function calls array into return-delimited string. */
		$ga_function_calls = implode( "\n", $ga_function_calls );

		return $confirmation . <<<HTML

HTML;
	}

	/**
	 * A filter function for the Gravity Forms tabindex.
	 *
	 * @param int $tabindex What Gravity Forms wants to use as the tab index.
	 * @param RGFormsModel $form The form object.
	 *
	 * @see https://www.gravityhelp.com/documentation/article/gform_tabindex/
	 *
	 * @return bool False to disable tabindex completely.
	 */
	public static function filter_gform_tabindex( $tabindex, $form ) {
		return false;
	}

	/**
	 * Initialization function. Registers action and filter hooks.
	 *
	 * @access public
	 * @return void
	 */
	public static function init() {

		/* Register action hooks. */
		add_action( 'widgets_init', [ get_called_class(), 'action_widgets_init' ] );
		add_action( 'wp_enqueue_scripts', [ get_called_class(), 'action_wp_enqueue_scripts' ], 1000 );

		/* Register filter hooks. */
		add_filter( 'gform_confirmation', [ get_called_class(), 'filter_gform_confirmation' ], 10, 4 );
		add_filter( 'gform_tabindex', [ get_called_class(), 'filter_gform_tabindex' ], 10, 2 );
	}
}


text:
/*Constants (these are accessible by Smooth.WHATEVER in user space)
*/

(function() {
  var AbstractInterpolator, CubicInterpolator, Enum, LinearInterpolator, NearestInterpolator, PI, SincFilterInterpolator, Smooth, clipClamp, clipMirror, clipPeriodic, defaultConfig, getColumn, getType, isValidNumber, k, makeLanczosWindow, makeScaledFunction, makeSincKernel, normalizeScaleTo, shallowCopy, sin, sinc, v, validateNumber, validateVector,
    __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

  Enum = {
    /*Interpolation methods
    */
    METHOD_NEAREST: 'nearest',
    METHOD_LINEAR: 'linear',
    METHOD_CUBIC: 'cubic',
    METHOD_LANCZOS: 'lanczos',
    METHOD_SINC: 'sinc',
    /*Input clipping modes
    */
    CLIP_CLAMP: 'clamp',
    CLIP_ZERO: 'zero',
    CLIP_PERIODIC: 'periodic',
    CLIP_MIRROR: 'mirror',
    /* Constants for control over the cubic interpolation tension
    */
    CUBIC_TENSION_DEFAULT: 0,
    CUBIC_TENSION_CATMULL_ROM: 0
  };

  defaultConfig = {
    method: Enum.METHOD_CUBIC,
    cubicTension: Enum.CUBIC_TENSION_DEFAULT,
    clip: Enum.CLIP_CLAMP,
    scaleTo: 0,
    sincFilterSize: 2,
    sincWindow: void 0
  };

  /*Index clipping functions
  */

  clipClamp = function(i, n) {
    return Math.max(0, Math.min(i, n - 1));
  };

  clipPeriodic = function(i, n) {
    i = i % n;
    if (i < 0) i += n;
    return i;
  };

  clipMirror = function(i, n) {
    var period;
    period = 2 * (n - 1);
    i = clipPeriodic(i, period);
    if (i > n - 1) i = period - i;
    return i;
  };

  /*
  Abstract scalar interpolation class which provides common functionality for all interpolators

  Subclasses must override interpolate().
  */

  AbstractInterpolator = (function() {

    function AbstractInterpolator(array, config) {
      this.array = array.slice(0);
      this.length = this.array.length;
      if (!(this.clipHelper = {
        clamp: this.clipHelperClamp,
        zero: this.clipHelperZero,
        periodic: this.clipHelperPeriodic,
        mirror: this.clipHelperMirror
      }[config.clip])) {
        throw "Invalid clip: " + config.clip;
      }
    }

    AbstractInterpolator.prototype.getClippedInput = function(i) {
      if ((0 <= i && i < this.length)) {
        return this.array[i];
      } else {
        return this.clipHelper(i);
      }
    };

    AbstractInterpolator.prototype.clipHelperClamp = function(i) {
      return this.array[clipClamp(i, this.length)];
    };

    AbstractInterpolator.prototype.clipHelperZero = function(i) {
      return 0;
    };

    AbstractInterpolator.prototype.clipHelperPeriodic = function(i) {
      return this.array[clipPeriodic(i, this.length)];
    };

    AbstractInterpolator.prototype.clipHelperMirror = function(i) {
      return this.array[clipMirror(i, this.length)];
    };

    AbstractInterpolator.prototype.interpolate = function(t) {
      throw 'Subclasses of AbstractInterpolator must override the interpolate() method.';
    };

    return AbstractInterpolator;

  })();

  NearestInterpolator = (function(_super) {

    __extends(NearestInterpolator, _super);

    function NearestInterpolator() {
      NearestInterpolator.__super__.constructor.apply(this, arguments);
    }

    NearestInterpolator.prototype.interpolate = function(t) {
      return this.getClippedInput(Math.round(t));
    };

    return NearestInterpolator;

  })(AbstractInterpolator);

  LinearInterpolator = (function(_super) {

    __extends(LinearInterpolator, _super);

    function LinearInterpolator() {
      LinearInterpolator.__super__.constructor.apply(this, arguments);
    }

    LinearInterpolator.prototype.interpolate = function(t) {
      var k;
      k = Math.floor(t);
      t -= k;
      return (1 - t) * this.getClippedInput(k) + t * this.getClippedInput(k + 1);
    };

    return LinearInterpolator;

  })(AbstractInterpolator);

  CubicInterpolator = (function(_super) {

    __extends(CubicInterpolator, _super);

    function CubicInterpolator(array, config) {
      this.tangentFactor = 1 - Math.max(0, Math.min(1, config.cubicTension));
      CubicInterpolator.__super__.constructor.apply(this, arguments);
    }

    CubicInterpolator.prototype.getTangent = function(k) {
      return this.tangentFactor * (this.getClippedInput(k + 1) - this.getClippedInput(k - 1)) / 2;
    };

    CubicInterpolator.prototype.interpolate = function(t) {
      var k, m, p, t2, t3;
      k = Math.floor(t);
      m = [this.getTangent(k), this.getTangent(k + 1)];
      p = [this.getClippedInput(k), this.getClippedInput(k + 1)];
      t -= k;
      t2 = t * t;
      t3 = t * t2;
      return (2 * t3 - 3 * t2 + 1) * p[0] + (t3 - 2 * t2 + t) * m[0] + (-2 * t3 + 3 * t2) * p[1] + (t3 - t2) * m[1];
    };

    return CubicInterpolator;

  })(AbstractInterpolator);

  sin = Math.sin, PI = Math.PI;

  sinc = function(x) {
    if (x === 0) {
      return 1;
    } else {
      return sin(PI * x) / (PI * x);
    }
  };

  makeLanczosWindow = function(a) {
    return function(x) {
      return sinc(x / a);
    };
  };

  makeSincKernel = function(window) {
    return function(x) {
      return sinc(x) * window(x);
    };
  };

  SincFilterInterpolator = (function(_super) {

    __extends(SincFilterInterpolator, _super);

    function SincFilterInterpolator(array, config) {
      SincFilterInterpolator.__super__.constructor.apply(this, arguments);
      this.a = config.sincFilterSize;
      if (!config.sincWindow) throw 'No sincWindow provided';
      this.kernel = makeSincKernel(config.sincWindow);
    }

    SincFilterInterpolator.prototype.interpolate = function(t) {
      var k, n, sum, _ref, _ref2;
      k = Math.floor(t);
      sum = 0;
      for (n = _ref = k - this.a + 1, _ref2 = k + this.a; _ref <= _ref2 ? n <= _ref2 : n >= _ref2; _ref <= _ref2 ? n++ : n--) {
        sum += this.kernel(t - n) * this.getClippedInput(n);
      }
      return sum;
    };

    return SincFilterInterpolator;

  })(AbstractInterpolator);

  getColumn = function(arr, i) {
    var row, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = arr.length; _i < _len; _i++) {
      row = arr[_i];
      _results.push(row[i]);
    }
    return _results;
  };

  makeScaledFunction = function(f, baseScale, scaleRange) {
    var scaleFactor, translation;
    if (scaleRange.join === '0,1') {
      return f;
    } else {
      scaleFactor = baseScale / (scaleRange[1] - scaleRange[0]);
      translation = scaleRange[0];
      return function(t) {
        return f(scaleFactor * (t - translation));
      };
    }
  };

  getType = function(x) {
    return Object.prototype.toString.call(x).slice('[object '.length, -1);
  };

  validateNumber = function(n) {
    if (isNaN(n)) throw 'NaN in Smooth() input';
    if (getType(n) !== 'Number') throw 'Non-number in Smooth() input';
    if (!isFinite(n)) throw 'Infinity in Smooth() input';
  };

  validateVector = function(v, dimension) {
    var n, _i, _len;
    if (getType(v) !== 'Array') throw 'Non-vector in Smooth() input';
    if (v.length !== dimension) throw 'Inconsistent dimension in Smooth() input';
    for (_i = 0, _len = v.length; _i < _len; _i++) {
      n = v[_i];
      validateNumber(n);
    }
  };

  isValidNumber = function(n) {
    return (getType(n) === 'Number') && isFinite(n) && !isNaN(n);
  };

  normalizeScaleTo = function(s) {
    var invalidErr;
    invalidErr = "scaleTo param must be number or array of two numbers";
    switch (getType(s)) {
      case 'Number':
        if (!isValidNumber(s)) throw invalidErr;
        s = [0, s];
        break;
      case 'Array':
        if (s.length !== 2) throw invalidErr;
        if (!(isValidNumber(s[0]) && isValidNumber(s[1]))) throw invalidErr;
        break;
      default:
        throw invalidErr;
    }
    return s;
  };

  shallowCopy = function(obj) {
    var copy, k, v;
    copy = {};
    for (k in obj) {
      if (!__hasProp.call(obj, k)) continue;
      v = obj[k];
      copy[k] = v;
    }
    return copy;
  };

  Smooth = function(arr, config) {
    var baseDomainEnd, dimension, i, interpolator, interpolatorClass, interpolators, k, n, properties, smoothFunc, v;
    if (config == null) config = {};
    properties = {};
    config = shallowCopy(config);
    properties.config = shallowCopy(config);
    if (config.scaleTo == null) config.scaleTo = config.period;
    if (config.sincFilterSize == null) {
      config.sincFilterSize = config.lanczosFilterSize;
    }
    for (k in defaultConfig) {
      if (!__hasProp.call(defaultConfig, k)) continue;
      v = defaultConfig[k];
      if (config[k] == null) config[k] = v;
    }
    if (!(interpolatorClass = {
      nearest: NearestInterpolator,
      linear: LinearInterpolator,
      cubic: CubicInterpolator,
      lanczos: SincFilterInterpolator,
      sinc: SincFilterInterpolator
    }[config.method])) {
      throw "Invalid method: " + config.method;
    }
    if (config.method === 'lanczos') {
      config.sincWindow = makeLanczosWindow(config.sincFilterSize);
    }
    if (arr.length < 2) throw 'Array must have at least two elements';
    properties.count = arr.length;
    smoothFunc = (function() {
      var _i, _j, _len, _len2;
      switch (getType(arr[0])) {
        case 'Number':
          properties.dimension = 'scalar';
          if (Smooth.deepValidation) {
            for (_i = 0, _len = arr.length; _i < _len; _i++) {
              n = arr[_i];
              validateNumber(n);
            }
          }
          interpolator = new interpolatorClass(arr, config);
          return function(t) {
            return interpolator.interpolate(t);
          };
        case 'Array':
          properties.dimension = dimension = arr[0].length;
          if (!dimension) throw 'Vectors must be non-empty';
          if (Smooth.deepValidation) {
            for (_j = 0, _len2 = arr.length; _j < _len2; _j++) {
              v = arr[_j];
              validateVector(v, dimension);
            }
          }
          interpolators = (function() {
            var _results;
            _results = [];
            for (i = 0; 0 <= dimension ? i < dimension : i > dimension; 0 <= dimension ? i++ : i--) {
              _results.push(new interpolatorClass(getColumn(arr, i), config));
            }
            return _results;
          })();
          return function(t) {
            var interpolator, _k, _len3, _results;
            _results = [];
            for (_k = 0, _len3 = interpolators.length; _k < _len3; _k++) {
              interpolator = interpolators[_k];
              _results.push(interpolator.interpolate(t));
            }
            return _results;
          };
        default:
          throw "Invalid element type: " + (getType(arr[0]));
      }
    })();
    if (config.clip === 'periodic') {
      baseDomainEnd = arr.length;
    } else {
      baseDomainEnd = arr.length - 1;
    }
    config.scaleTo || (config.scaleTo = baseDomainEnd);
    properties.domain = normalizeScaleTo(config.scaleTo);
    smoothFunc = makeScaledFunction(smoothFunc, baseDomainEnd, properties.domain);
    properties.domain.sort();
    /*copy properties
    */
    for (k in properties) {
      if (!__hasProp.call(properties, k)) continue;
      v = properties[k];
      smoothFunc[k] = v;
    }
    return smoothFunc;
  };

  for (k in Enum) {
    if (!__hasProp.call(Enum, k)) continue;
    v = Enum[k];
    Smooth[k] = v;
  }

  Smooth.deepValidation = true;

  (typeof exports !== "undefined" && exports !== null ? exports : window).Smooth = Smooth;

}).call(this);


text:
using System.Collections.Generic;
using Scientia.HtmlRenderer.Core.Utils;

namespace Scientia.HtmlRenderer.Core.Dom
{
    internal sealed class HtmlTag
    {
        #region Fields and Consts

        ///
        /// the name of the html tag
        ///
        private readonly string _Name;

        ///
        /// if the tag is single placed; in other words it doesn't have a separate closing tag;
        ///
        private readonly bool _IsSingle;

        ///
        /// collection of attributes and their value the html tag has
        ///
        private readonly Dictionary<string, string> _Attributes;

        #endregion

        ///
        /// Init.
        ///
        /// <param name="name">the name of the html tag</param>
        /// <param name="isSingle">if the tag is single placed; in other words it doesn't have a separate closing tag;</param>
        /// <param name="attributes">collection of attributes and their value the html tag has</param>
        public HtmlTag(string name, bool isSingle, Dictionary<string, string> attributes = null)
        {
            ArgChecker.AssertArgNotNullOrEmpty(name, "name");

            this._Name = name;
            this._IsSingle = isSingle;
            this._Attributes = attributes;
        }

        ///
        /// Gets the name of this tag
        ///
        public string Name
        {
            get { return this._Name; }
        }

        ///
        /// Gets collection of attributes and their value the html tag has
        ///
        public Dictionary<string, string> Attributes
        {
            get { return this._Attributes; }
        }

        ///
        /// Gets if the tag is single placed; in other words it doesn't have a separate closing tag;

        /// e.g.

        ///
        public bool IsSingle
        {
            get { return this._IsSingle; }
        }

        ///
        /// is the html tag has attributes.
        ///
        /// <returns>true - has attributes, false - otherwise</returns>
        public bool HasAttributes()
        {
            return this._Attributes != null && this._Attributes.Count > 0;
        }

        ///
        /// Gets a boolean indicating if the attribute list has the specified attribute
        ///
        /// <param name="attribute">attribute name to check if exists</param>
        /// <returns>true - attribute exists, false - otherwise</returns>
        public bool HasAttribute(string attribute)
        {
            return this._Attributes != null && this._Attributes.ContainsKey(attribute);
        }

        ///
        /// Get attribute value for given attribute name or null if not exists.
        ///
        /// <param name="attribute">attribute name to get by</param>
        /// <param name="defaultValue">optional: value to return if attribute is not specified</param>
        /// <returns>attribute value or null if not found</returns>
        public string TryGetAttribute(string attribute, string defaultValue = null)
        {
            return this._Attributes != null && this._Attributes.ContainsKey(attribute) ? this._Attributes[attribute] : defaultValue;
        }

        public override string ToString()
        {
            return string.Format("<{0}>", this._Name);
        }
    }
}


text:
@interface CMHomeBanner : NSObject<CMHomeDataProtocol>

@property (nonatomic,strong)NSString * actionType;

@end


text:
namespace ggk {

// "0000180A-0000-1000-8000-00805f9b34fb"
struct GattUuid
{
	static constexpr const char *kGattStandardUuidPart1Prefix = "0000";
	static constexpr const char *kGattStandardUuidSuffix = "-0000-1000-8000-00805f9b34fb";

	// Construct a GattUuid from a partial or complete string UUID
	//
	// This constructor will do the best it can with the data it is given. It will first clean the input by removing all non-hex
	// characters (see `clean`) and the remaining characters are processed in the following way:
	//
	//     4-character string is treated as a 16-bit UUID
	//     8-character string is treated as a 32-bit UUID
	//     32-character string is treated as a 128-bit UUID
	//
	// If the input string is not one of the above lengths, the  UUID will be left uninitialized as an empty string with a bit
	// count of 0.
	//
	// Finally, dashes are inserted into the string at the appropriate locations (see `dashify`).
	GattUuid(const char *strUuid)
	{
		*this = GattUuid(std::string(strUuid));
	}

	// Construct a GattUuid from a partial or complete string UUID
	//
	// This constructor will do the best it can with the data it is given. It will first clean the input by removing all non-hex
	// characters (see `clean`) and the remaining characters are processed in the following way:
	//
	//     4-character string is treated as a 16-bit UUID
	//     8-character string is treated as a 32-bit UUID
	//     32-character string is treated as a 128-bit UUID
	//
	// If the input string is not one of the above lengths, the  UUID will be left uninitialized as an empty string with a bit
	// count of 0.
	//
	// Finally, dashes are inserted into the string at the appropriate locations (see `dashify`).
	GattUuid(std::string strUuid)
	{
		// Clean the string
		strUuid = clean(strUuid);

		// It's hex, so each character represents 4 bits
		bitCount = strUuid.length() * 4;

		if (bitCount == 16)
		{
			strUuid = kGattStandardUuidPart1Prefix + strUuid + kGattStandardUuidSuffix;
		}
		else if (bitCount == 32)
		{
			strUuid += kGattStandardUuidSuffix;
		}
		else if (bitCount != 128)
		{
			bitCount = 0;
			strUuid = "";
		}

		uuid = dashify(strUuid);
	}

	// Constructs a GattUuid from a 16-bit Uuid value
	//
	// The result will take the form:
	//
	//     0000????-0000-1000-8000-00805f9b34fb
	//
	// ...where "????" is replaced by the 4-digit hex value of `part`
	GattUuid(const uint16_t part)
	{
		bitCount = 16;
		char partStr[5];
		snprintf(partStr, sizeof(partStr), "%04x", part);
		uuid = std::string(kGattStandardUuidPart1Prefix) + partStr + kGattStandardUuidSuffix;
	}

	// Constructs a GattUuid from a 32-bit Uuid value
	//
	// The result will take the form:
	//
	//     ????????-0000-1000-8000-00805f9b34fb
	//
	// ...where "????????" is replaced by the 8-digit hex value of `part`
	GattUuid(const uint32_t part)
	{
		bitCount = 32;
		char partStr[9];
		snprintf(partStr, sizeof(partStr), "%08x", part);
		uuid = std::string(partStr) + kGattStandardUuidSuffix;
	}

	// Constructs a GattUuid from a 5-part set of input values
	//
	// The result will take the form:
	//
	//     11111111-2222-3333-4444-555555555555
	//
	// ...where each digit represents the part from which its hex digits will be pulled from.
	//
	// Note that `part5` is a 48-bit value and will be masked such that only the lower 48-bits of `part5` are used with all other
	// bits ignored.
	GattUuid(const uint32_t part1, const uint16_t part2, const uint16_t part3, const uint16_t part4, const uint64_t part5)
	{
		bitCount = 128;
		char partsStr[37];
		uint32_t part5a = (part5 >> 4) & 0xffffffff;
		uint32_t part5b = part5 & 0xffff;
		snprintf(partsStr, sizeof(partsStr), "%08x-%04x-%04x-%04x-%08x%04x", part1, part2, part3, part4, part5a, part5b);
		uuid = std::string(partsStr);
	}

	// Returns the bit count of the input when the GattUuid was constructed. Valid values are 16, 32, 128.
	//
	// If the GattUuid was constructed imporperly, this method will return 0.
	int getBitCount() const
	{
		return bitCount;
	}

	// Returns the 16-bit portion of the GATT UUID or an empty string if the GattUuid was not created correctly
	//
	// Note that a 16-bit GATT UUID is only valid for standarg GATT UUIDs (prefixed with "0000" and ending with
	// "0000-1000-8000-00805f9b34fb").
	std::string toString16() const
	{
		if (uuid.empty()) { return uuid; }
		return uuid.substr(4, 4);
	}

	// Returns the 32-bit portion of the GATT UUID or an empty string if the GattUuid was not created correctly
	//
	// Note that a 32-bit GATT UUID is only valid for standarg GATT UUIDs (ending with "0000-1000-8000-00805f9b34fb").
	std::string toString32() const
	{
		if (uuid.empty()) { return uuid; }
		return uuid.substr(0, 8);
	}

	// Returns the full 128-bit GATT UUID or an empty string if the GattUuid was not created correctly
	std::string toString128() const
	{
		return uuid;
	}

	// Returns a string form of the UUID, based on the bit count used when the UUID was created. A 16-bit UUID will return a
	// 4-character hex string. A 32-bit UUID will return an 8-character hex string. Otherwise the UUID is assumed to be 128 bits
	// (which is only true if it was created correctly) and the full UUID is returned
	std::string toString() const
	{
		if (bitCount == 16) return toString16();
		if (bitCount == 32) return toString32();
		return toString128();
	}

	// Returns a new string containing the lower case contents of `strUuid` with all non-hex characters (0-9, A-F) removed
	static std::string clean(const std::string &strUuid)
	{
		if (strUuid.empty()) return strUuid;

		// Lower case
		std::string cleanStr = strUuid;
		std::transform(cleanStr.begin(), cleanStr.end(), cleanStr.begin(), ::tolower);

		// Remove all non-hex characters
		cleanStr.erase
		(
			std::remove_if
			(
				cleanStr.begin(),
				cleanStr.end(),
				[](char c)
				{
					return !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
				}
			), cleanStr.end()
		);

		return cleanStr;
	}

	// Returns a clean string (see `clean`) that has dashes ('-') inserted at the proper locations. If the string is not a full
	// UUID, this routine will cleanup and add as many dashes as possible until it runs out of characters.
	//
	// Example transforms:
	//
	//     "0000180A-0000-1000-8000-00805f9b34fb"        -> "0000180a-0000-1000-8000-00805f9b34fb"
	//     "0000180A00001000800000805f9b34fb"            -> "0000180a-0000-1000-8000-00805f9b34fb"
	//     "0000180A/0000.1000_zzzzzz_8000+00805f9b34fb" -> "0000180a-0000-1000-8000-00805f9b34fb"
	//     "0000180A"                                    -> "0000180a"
	//     "0000180A.0000.100"                           -> "0000180a-0000-100"
	//     "rqzp"                                        -> ""
	//
	static std::string dashify(const std::string &str)
	{
		// Ensure we have a clean string to start with
		std::string dashed = clean(str);

		// Add each dash, provided there are enough characters
		if (dashed.length() > 8) { dashed.insert(8, 1, '-'); }
		if (dashed.length() > 13) { dashed.insert(13, 1, '-'); }
		if (dashed.length() > 18) { dashed.insert(18, 1, '-'); }
		if (dashed.length() > 23) { dashed.insert(23, 1, '-'); }
		return dashed;
	}

private:

	std::string uuid;
	int bitCount;
};

}; // namespace ggk


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hintersphere.booklogger"
    android:versionCode="8"
	android:versionName="1.3">

	<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" />
	<uses-permission android:name="android.permission.INTERNET"/>
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

	<application
	    android:icon="@drawable/launcherico"
		android:label="@string/app_name"
		android:allowBackup="true">
        <activity
            android:name=".BookLoggerActivity"
            android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<activity android:name=".BookListEditActivity" />
		<activity android:name=".BookListEntryActivity" />
		<activity android:name=".BookListDetailActivity"
		    	  android:windowSoftInputMode="stateHidden|adjustPan" />
		<activity android:name="com.google.ads.AdActivity"
				  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
	</application>
</manifest>


text: sudo apt-get remove thunderbird


text:
package org.optaplanner.examples.cloudbalancing.app;

import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.examples.cloudbalancing.persistence.CloudBalancingDao;
import org.optaplanner.examples.cloudbalancing.swingui.CloudBalancingPanel;
import org.optaplanner.examples.common.app.CommonApp;
import org.optaplanner.examples.common.persistence.SolutionDao;
import org.optaplanner.examples.common.swingui.SolutionPanel;

public class CloudBalancingApp extends CommonApp {

    public static final String SOLVER_CONFIG
            = "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml";

    public static void main(String[] args) {
        prepareSwingEnvironment();
        new CloudBalancingApp().init();
    }

    public CloudBalancingApp() {
        super("Cloud balancing",
                "Assign processes to computers.\n\n" +
                "Each computer must have enough hardware to run all of its processes.\n" +
                "Each used computer inflicts a maintenance cost.",
                CloudBalancingPanel.LOGO_PATH);
    }

    @Override
    protected Solver createSolver() {
        SolverFactory solverFactory = SolverFactory.createFromXmlResource(SOLVER_CONFIG);
        return solverFactory.buildSolver();
    }

    @Override
    protected SolutionPanel createSolutionPanel() {
        return new CloudBalancingPanel();
    }

    @Override
    protected SolutionDao createSolutionDao() {
        return new CloudBalancingDao();
    }

}


text:
package org.elasticsearch.action.bulk;

import com.google.common.collect.ImmutableList;
import io.crate.core.collections.RowN;
import io.crate.executor.transport.ShardUpsertRequest;
import io.crate.executor.transport.ShardUpsertResponse;
import io.crate.executor.transport.TransportActionProvider;
import io.crate.jobs.ExecutionState;
import io.crate.metadata.ReferenceIdent;
import io.crate.metadata.ReferenceInfo;
import io.crate.metadata.TableIdent;
import io.crate.operation.collect.ShardingProjector;
import io.crate.planner.RowGranularity;
import io.crate.planner.symbol.InputColumn;
import io.crate.planner.symbol.Reference;
import io.crate.planner.symbol.Symbol;
import io.crate.test.integration.CrateUnitTest;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import io.crate.types.IntegerType;
import io.crate.types.StringType;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.create.TransportBulkCreateIndicesAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.routing.operation.OperationRouting;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.index.shard.ShardId;
import org.junit.Test;
import org.mockito.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class BulkShardProcessorTest extends CrateUnitTest {

    TableIdent charactersIdent = new TableIdent(null, "characters");

    Reference idRef = new Reference(new ReferenceInfo(
            new ReferenceIdent(charactersIdent, "id"), RowGranularity.DOC, DataTypes.INTEGER));

    Reference fooRef = new Reference(new ReferenceInfo(
            new ReferenceIdent(charactersIdent, "foo"), RowGranularity.DOC, DataTypes.STRING));

    @Captor
    private ArgumentCaptor<ActionListener<BulkShardResponse>> bulkShardResponseListener;

    @Mock(answer = Answers.RETURNS_MOCKS)
    ClusterService clusterService;

    @Test
    public void testNonEsRejectedExceptionDoesNotResultInRetryButAborts() throws Throwable {
        expectedException.expect(RuntimeException.class);
        expectedException.expectMessage("a random exception");

        final AtomicReference<ActionListener<ShardUpsertResponse>> ref = new AtomicReference<>();
        TransportShardUpsertActionDelegate transportShardBulkActionDelegate = new TransportShardUpsertActionDelegate() {
            @Override
            public void execute(ShardUpsertRequest request, ActionListener<ShardUpsertResponse> listener) {
                ref.set(listener);
            }
        };

        Map<Reference, Symbol> insertAssignments = new HashMap<Reference, Symbol>(){{
            put(idRef, new InputColumn(0, IntegerType.INSTANCE));
            put(fooRef, new InputColumn(1, StringType.INSTANCE));
        }};

        ShardingProjector shardingProjector = new ShardingProjector(
                ImmutableList.of(idRef.ident().columnIdent()),
                ImmutableList.<Symbol>of(new InputColumn(0, IntegerType.INSTANCE)),
                null
        );
        shardingProjector.startProjection(mock(ExecutionState.class));

        BulkRetryCoordinator bulkRetryCoordinator = new BulkRetryCoordinator(
                ImmutableSettings.EMPTY
        );
        BulkRetryCoordinatorPool coordinatorPool = mock(BulkRetryCoordinatorPool.class);
        when(coordinatorPool.coordinator(any(ShardId.class))).thenReturn(bulkRetryCoordinator);

        ShardUpsertRequest.Builder builder = new ShardUpsertRequest.Builder(
                new DataType[0],
                Collections.<Integer>emptyList(),
                TimeValue.timeValueMillis(10),
                false,
                false,
                null,
                insertAssignments,
                null,
                UUID.randomUUID()
        );

        final BulkShardProcessor<ShardUpsertRequest, ShardUpsertResponse> bulkShardProcessor = new BulkShardProcessor<>(
                clusterService,
                ImmutableSettings.EMPTY,
                mock(TransportBulkCreateIndicesAction.class),
                shardingProjector,
                false,
                1,
                coordinatorPool,
                builder,
                transportShardBulkActionDelegate,
                UUID.randomUUID()
        );
        try {
            bulkShardProcessor.add("foo", new RowN(new Object[]{1, "bar1"}), null);

            ActionListener<ShardUpsertResponse> listener = ref.get();
            listener.onFailure(new RuntimeException("a random exception"));
            assertFalse(bulkShardProcessor.add("foo", new RowN(new Object[]{2, "bar2"}), null));
            bulkShardProcessor.result().get();
        } catch (ExecutionException e) {
            throw e.getCause();
        } finally {
            bulkRetryCoordinator.close();
        }
    }

    @Test
    public void testThatAddAfterFailureBlocksDueToRetry() throws Exception {
        ClusterService clusterService = mock(ClusterService.class);
        OperationRouting operationRouting = mock(OperationRouting.class);

        mockShard(operationRouting, 1);
        mockShard(operationRouting, 2);
        mockShard(operationRouting, 3);
        when(clusterService.operationRouting()).thenReturn(operationRouting);

        // listener will be executed 2 times, once for the successfully added row and once for the failure
        final CountDownLatch listenerLatch = new CountDownLatch(2);
        final AtomicReference<ActionListener<ShardUpsertResponse>> ref = new AtomicReference<>();
        TransportShardUpsertActionDelegate transportShardUpsertActionDelegate = new TransportShardUpsertActionDelegate() {
            @Override
            public void execute(ShardUpsertRequest request, ActionListener<ShardUpsertResponse> listener) {
                ref.set(listener);
                listenerLatch.countDown();
            }
        };

        Map<Reference, Symbol> insertAssignments = new HashMap<Reference, Symbol>(){{
            put(idRef, new InputColumn(0, IntegerType.INSTANCE));
            put(fooRef, new InputColumn(1, StringType.INSTANCE));
        }};

        ShardingProjector shardingProjector = new ShardingProjector(
                ImmutableList.of(idRef.ident().columnIdent()),
                ImmutableList.<Symbol>of(new InputColumn(0, IntegerType.INSTANCE)),
                null
        );
        shardingProjector.startProjection(mock(ExecutionState.class));

        TransportActionProvider transportActionProvider = mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS.get());
        when(transportActionProvider.transportShardUpsertActionDelegate()).thenReturn(transportShardUpsertActionDelegate);
        BulkRetryCoordinator bulkRetryCoordinator = new BulkRetryCoordinator(
                ImmutableSettings.EMPTY
        );
        BulkRetryCoordinatorPool coordinatorPool = mock(BulkRetryCoordinatorPool.class);
        when(coordinatorPool.coordinator(any(ShardId.class))).thenReturn(bulkRetryCoordinator);

        ShardUpsertRequest.Builder builder = new ShardUpsertRequest.Builder(
                new DataType[0],
                Collections.<Integer>emptyList(),
                TimeValue.timeValueMillis(10),
                false,
                false,
                null,
                insertAssignments,
                null,
                UUID.randomUUID()
        );

        final BulkShardProcessor<ShardUpsertRequest, ShardUpsertResponse> bulkShardProcessor = new BulkShardProcessor<>(
                clusterService,
                ImmutableSettings.EMPTY,
                mock(TransportBulkCreateIndicesAction.class),
                shardingProjector,
                false,
                1,
                coordinatorPool,
                builder,
                transportShardUpsertActionDelegate,
                UUID.randomUUID()
        );
        bulkShardProcessor.add("foo", new RowN(new Object[]{1, "bar1"}), null);
        final ActionListener<ShardUpsertResponse> listener = ref.get();

        listener.onFailure(new EsRejectedExecutionException());
        // wait, failure retry lock is done in decoupled thread
        listenerLatch.await(10, TimeUnit.SECONDS);

        final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        try {
            final AtomicBoolean hadBlocked = new AtomicBoolean(false);
            final AtomicBoolean hasBlocked = new AtomicBoolean(true);
            final CountDownLatch latch = new CountDownLatch(1);
            scheduledExecutorService.execute(new Runnable() {
                @Override
                public void run() {
                    scheduledExecutorService.schedule(new Runnable() {
                        @Override
                        public void run() {
                            hadBlocked.set(hasBlocked.get());
                            latch.countDown();
                        }
                    }, 10, TimeUnit.MILLISECONDS);
                    bulkShardProcessor.add("foo", new RowN(new Object[]{2, "bar2"}), null);
                    hasBlocked.set(false);
                }
            });
            latch.await();
            assertTrue(hadBlocked.get());
        } finally {
            scheduledExecutorService.shutdownNow();
            bulkRetryCoordinator.close();
        }
    }

    private void mockShard(OperationRouting operationRouting, Integer shardId) {
        ShardIterator shardIterator = mock(ShardIterator.class);
        when(operationRouting.indexShards(
                any(ClusterState.class),
                anyString(),
                anyString(),
                Matchers.eq(shardId.toString()),
                anyString())).thenReturn(shardIterator);
        when(shardIterator.shardId()).thenReturn(new ShardId("foo", shardId));
    }
}


text:
using System;
using Umbraco.Cms.Core.Models;

namespace Umbraco.Cms.Tests.Common;

public class TestClone : IDeepCloneable, IEquatable<TestClone>
{
    public TestClone(Guid id)
    {
        Id = id;
        IsClone = true;
    }

    public TestClone() => Id = Guid.NewGuid();

    public Guid Id { get; }

    public bool IsClone { get; }

    public object DeepClone() => new TestClone(Id);

    /// <summary>
    ///     Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <returns>
    ///     true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
    /// </returns>
    /// <param name="other">An object to compare with this object.</param>
    public bool Equals(TestClone other)
    {
        if (other is null)
        {
            return false;
        }

        if (ReferenceEquals(this, other))
        {
            return true;
        }

        return Id.Equals(other.Id);
    }

    /// <summary>
    ///     Determines whether the specified object is equal to the current object.
    /// </summary>
    /// <returns>
    ///     true if the specified object  is equal to the current object; otherwise, false.
    /// </returns>
    /// <param name="obj">The object to compare with the current object. </param>
    public override bool Equals(object obj)
    {
        if (obj is null)
        {
            return false;
        }

        if (ReferenceEquals(this, obj))
        {
            return true;
        }

        if (obj.GetType() != GetType())
        {
            return false;
        }

        return Equals((TestClone)obj);
    }

    /// <summary>
    ///     Serves as the default hash function.
    /// </summary>
    /// <returns>
    ///     A hash code for the current object.
    /// </returns>
    public override int GetHashCode() => Id.GetHashCode();

    public static bool operator ==(TestClone left, TestClone right) => Equals(left, right);

    public static bool operator !=(TestClone left, TestClone right) => Equals(left, right) == false;
}


text:
package com.rackspacecloud.blueflood.service;

import java.util.Collection;

public interface ZKBasedShardLockManagerMBean {
    public Collection<Integer> getHeldShards();
    public Collection<Integer> getUnheldShards();
    public Collection<Integer> getErrorShards();

    public long getMinLockHoldTimeMillis();
    public void setMinLockHoldTimeMillis(long millis);

    public long getLockDisinterestedTimeMillis();
    public void setLockDisinterestedTimeMillis(long millis);

    public void forceLockScavenge();
    public long getSecondsSinceLastScavenge();
    public String getZkConnectionStatus();

    public boolean release(int shard);
    public boolean acquire(int shard);
}


text:
import os

from cryptography import fernet
from oslo_config import cfg
from oslo_log import log as logging

from tacker.common import utils
from tacker import context as t_context
from tacker.extensions import nfvo
from tacker.keymgr import API as KEYMGR_API
from tacker import manager
from tacker.plugins.common import constants

LOG = logging.getLogger(__name__)
CONF = cfg.CONF

class VimClient(object):
    def get_vim(self, context, vim_id=None, region_name=None):
        """Get Vim information for provided VIM id

        Initiate the NFVO plugin, request VIM information for the provided
        VIM id and validate region
        """
        nfvo_plugin = manager.TackerManager.get_service_plugins().get(
            constants.NFVO)

        if not vim_id:
            LOG.debug('VIM id not provided. Attempting to find default '
                      'VIM information')
            try:
                vim_info = nfvo_plugin.get_default_vim(context)
            except Exception as ex:
                LOG.error('Fail to get default vim due to %s', ex)
                raise nfvo.VimDefaultNotDefined()
        else:
            try:
                vim_info = nfvo_plugin.get_vim(context, vim_id,
                                               mask_password=False)
            except Exception:
                raise nfvo.VimNotFoundException(vim_id=vim_id)
        LOG.debug('VIM info found for vim id %s', vim_id)
        if region_name and not self.region_valid(vim_info['placement_attr']
                                                 ['regions'], region_name):
            raise nfvo.VimRegionNotFoundException(region_name=region_name)

        vim_auth = self._build_vim_auth(vim_info)
        vim_res = {'vim_auth': vim_auth, 'vim_id': vim_info['id'],
                   'vim_name': vim_info.get('name', vim_info['id']),
                   'vim_type': vim_info['type'],
                   'tenant': vim_info['tenant_id'],
                   'placement_attr': vim_info.get('placement_attr', {}),
                   'extra': vim_info.get('extra', {})}
        return vim_res

    @staticmethod
    def region_valid(vim_regions, region_name):
        return region_name in vim_regions

    def _build_vim_auth(self, vim_info):
        LOG.debug('VIM id is %s', vim_info['id'])
        vim_auth = vim_info['auth_cred']

        # decode password
        if ('password' in vim_auth) and (vim_auth['password'] is not None):
            vim_auth['password'] = self._decode_vim_auth(vim_info['id'],
                                                         vim_auth,
                                                         vim_auth['password'])
        # decode bearer_token
        if 'bearer_token' in vim_auth:
            vim_auth['bearer_token'] = self.\
                _decode_vim_auth(vim_info['id'],
                                 vim_auth,
                                 vim_auth['bearer_token'])
        # decode ssl_ca_cert
        if utils.none_from_string(vim_auth.get('ssl_ca_cert')) is not None:
            vim_auth['ssl_ca_cert'] = self.\
                _decode_vim_auth(vim_info['id'],
                                 vim_auth,
                                 vim_auth['ssl_ca_cert'])

        # decode client_secret
        if 'client_secret' in vim_auth and vim_auth['client_secret']:
            vim_auth['client_secret'] = self._decode_vim_auth(
                vim_info['id'],
                vim_auth,
                vim_auth['client_secret'])

        vim_auth['auth_url'] = vim_info['auth_url']

        # These attributes are needless for authentication
        # from keystone, so we remove them.
        needless_attrs = ['key_type', 'secret_uuid']
        for attr in needless_attrs:
            if attr in vim_auth:
                vim_auth.pop(attr, None)
        return vim_auth

    def _decode_vim_auth(self, vim_id, auth, secret_value):
        """Decode Vim credentials

        Decrypt VIM cred, get fernet Key from local_file_system or
        barbican.
        """
        cred = secret_value.encode('utf-8')
        if auth.get('key_type') == 'barbican_key':
            keystone_conf = CONF.keystone_authtoken
            secret_uuid = auth['secret_uuid']
            keymgr_api = KEYMGR_API(keystone_conf.auth_url)
            k_context = t_context.generate_tacker_service_context()
            secret_obj = keymgr_api.get(k_context, secret_uuid)
            vim_key = secret_obj.payload
        else:
            vim_key = self._find_vim_key(vim_id)

        f = fernet.Fernet(vim_key)
        if not f:
            LOG.error('Unable to decode VIM auth')
            raise nfvo.VimNotFoundException(vim_id=vim_id)
        return f.decrypt(cred).decode('utf-8')

    @staticmethod
    def _find_vim_key(vim_id):
        key_file = os.path.join(CONF.vim_keys.openstack, vim_id)
        LOG.debug('Attempting to open key file for vim id %s', vim_id)
        try:
            with open(key_file, 'r') as f:
                return f.read()
        except Exception:
            LOG.error('VIM id invalid or key not found for  %s', vim_id)
            raise nfvo.VimKeyNotFoundException(vim_id=vim_id)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>InputFileDetails (Gradle API 2.8)</title>
    <meta name="date" content="2015-10-20">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Package: org.gradle.api.tasks.incremental

[Java] Interface InputFileDetails

 A change to an input file.

Methods Summary

Methods

                            Type
                            Name and description

                            File
                            getFile()
The input file, which may no longer exist.

                            boolean
                            isAdded()
Was the file added?

                            boolean
                            isModified()
Was the file modified?

                            boolean
                            isRemoved()
Was the file removed?

Method Detail

public File getFile()

 The input file, which may no longer exist.

Returns:

the input file

public boolean isAdded()

 Was the file added?

Returns:

true if the file was added since the last execution

public boolean isModified()

 Was the file modified?

Returns:

if the file was modified

public boolean isRemoved()

 Was the file removed?

Returns:

true if the file was removed since the last execution

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Gradle API 2.8


text:
var attr = DS.attr;

Watchtower.AppAdapter =  DS.RESTAdapter.extend({
    pathForType: function(type) {
        return 'software';
    },
    jqXHRs: [],
    ajaxOptions: function(url, type, hash) {
        // Get default AjaxOptions
        var ajaxOptions = this._super(url, type, hash);

        // If the function was defined in the DS.RESTAdapter object,
        // we must call it in out new beforeSend hook.
        var defaultBeforeSend = function(){};
        if(typeof ajaxOptions.beforeSend === 'function'){
            defaultBeforeSend = ajaxOptions.beforeSend;
        }
        ajaxOptions.beforeSend = function(jqXHR, settings){
            defaultBeforeSend(jqXHR, settings);
            this.jqXHRs.push(jqXHR); // Keep the jqXHR somewhere.
            var lastInsertIndex = this.jqXHRs.length - 1;
            jqXHR.always(function(){
                // Destroy the jqXHRs because the call is finished and
                // we don't need it anymore.
                this.jqXHRs.splice(lastInsertIndex,1);
            });
        };

        return ajaxOptions;
    },

    cancelQuery: function(){
        this.jqXHRs.forEach(function(req){
            req.abort();
        });
    }
});

Watchtower.App = DS.Model.extend({
    trackName:         DS.attr('string'),
    description:       DS.attr('string'),
    artistName:        DS.attr('string'),
    artworkUrl60:      DS.attr('string'),
    userRatingCount:   DS.attr('number'),
    version:           DS.attr('string'),
    averageUserRating: DS.attr('number'),
    trackViewUrl:      DS.attr('string'),
    isSelected:        DS.attr('boolean', {defaultValue: false})
});