text:
import { expect } from 'chai';
import * as Rx from 'rxjs/Rx';
import { hot, cold, expectObservable, expectSubscriptions } from '../helpers/marble-testing';

declare const type: Function;

const Observable = Rx.Observable;
const queueScheduler = Rx.Scheduler.queue;

/** @test {combineLatest} */
describe('Observable.combineLatest', () => {
  it('should combineLatest the provided observables', () => {
    const firstSource =  hot('----a----b----c----|');
    const secondSource = hot('--d--e--f--g--|');
    const expected =         '----uv--wx-y--z----|';

    const combined = Observable.combineLatest(firstSource, secondSource,
      (a, b) => '' + a + b);

    expectObservable(combined).toBe(expected, {u: 'ad', v: 'ae', w: 'af', x: 'bf', y: 'bg', z: 'cg'});
  });

  it('should combine an immediately-scheduled source with an immediately-scheduled second', (done) => {
    const a = Observable.of<number>(1, 2, 3, queueScheduler);
    const b = Observable.of<number>(4, 5, 6, 7, 8, queueScheduler);
    const r = [[1, 4], [2, 4], [2, 5], [3, 5], [3, 6], [3, 7], [3, 8]];

    //type definition need to be updated
    Observable.combineLatest(a, b, queueScheduler).subscribe((vals) => {
      expect(vals).to.deep.equal(r.shift());
    }, (x) => {
      done(new Error('should not be called'));
    }, () => {
      expect(r.length).to.equal(0);
      done();
    });
  });

  it('should accept array of observables', () => {
    const firstSource =  hot('----a----b----c----|');
    const secondSource = hot('--d--e--f--g--|');
    const expected =         '----uv--wx-y--z----|';

    const combined = Observable.combineLatest([firstSource, secondSource],
      (a: string, b: string) => '' + a + b);

    expectObservable(combined).toBe(expected, {u: 'ad', v: 'ae', w: 'af', x: 'bf', y: 'bg', z: 'cg'});
  });

  it('should work with two nevers', () => {
    const e1 = cold( '-');
    const e1subs =   '^';
    const e2 = cold( '-');
    const e2subs =   '^';
    const expected = '-';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with never and empty', () => {
    const e1 = cold( '-');
    const e1subs =   '^';
    const e2 = cold( '|');
    const e2subs =   '(^!)';
    const expected = '-';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with empty and never', () => {
    const e1 = cold( '|');
    const e1subs =   '(^!)';
    const e2 = cold( '-');
    const e2subs =   '^';
    const expected = '-';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with empty and empty', () => {
    const e1 = cold('|');
    const e1subs =  '(^!)';
    const e2 = cold('|');
    const e2subs =  '(^!)';
    const expected = '|';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with hot-empty and hot-single', () => {
    const values = {
      a: 1,
      b: 2,
      c: 3,
      r: 1 + 3 //a + c
    };
    const e1 =        hot('-a-^-|', values);
    const e1subs =           '^ !';
    const e2 =        hot('-b-^-c-|', values);
    const e2subs =           '^   !';
    const expected =         '----|';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with hot-single and hot-empty', () => {
    const values = {
      a: 1, b: 2, c: 3
    };
    const e1 =        hot('-a-^-|', values);
    const e1subs =           '^ !';
    const e2 =        hot('-b-^-c-|', values);
    const e2subs =           '^   !';
    const expected =         '----|';

    const result = Observable.combineLatest(e2, e1, (x, y) => x + y);

    expectObservable(result).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with hot-single and never', () => {
    const values = {
      a: 1
    };
    const e1 =        hot('-a-^-|', values);
    const e1subs =           '^ !';
    const e2 =        hot('------', values); //never
    const e2subs =           '^  ';
    const expected =         '-'; //never

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with never and hot-single', () => {
    const values = {
      a: 1, b: 2
    };
    const e1 =        hot('--------', values); //never
    const e1subs =           '^    ';
    const e2 =        hot('-a-^-b-|', values);
    const e2subs =           '^   !';
    const expected =         '-----'; //never

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with hot and hot', () => {
    const e1 =   hot('--a--^--b--c--|', { a: 'a', b: 'b', c: 'c' });
    const e1subs =        '^        !';
    const e2 =   hot('---e-^---f--g--|', { e: 'e', f: 'f', g: 'g' });
    const e2subs =        '^         !';
    const expected =      '----x-yz--|';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, { x: 'bf', y: 'cf', z: 'cg' });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with empty and error', () => {
    const e1 =   hot('----------|'); //empty
    const e1subs =   '^     !';
    const e2 =   hot('------#', null, 'shazbot!'); //error
    const e2subs =   '^     !';
    const expected = '------#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'shazbot!');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with error and empty', () => {
    const e1 =   hot('--^---#', null, 'too bad, honk'); //error
    const e1subs =     '^   !';
    const e2 =   hot('--^--------|'); //empty
    const e2subs =     '^   !';
    const expected =   '----#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'too bad, honk');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with hot and throw', () => {
    const e1 =    hot('-a-^--b--c--|', { a: 1, b: 2, c: 3});
    const e1subs =       '^ !';
    const e2 =    hot('---^-#', null, 'bazinga');
    const e2subs =       '^ !';
    const expected =     '--#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'bazinga');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with throw and hot', () => {
    const e1 =    hot('---^-#', null, 'bazinga');
    const e1subs =       '^ !';
    const e2 =    hot('-a-^--b--c--|', { a: 1, b: 2, c: 3});
    const e2subs =       '^ !';
    const expected =     '--#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'bazinga');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with throw and throw', () => {
    const e1 =    hot('---^----#', null, 'jenga');
    const e1subs =       '^ !';
    const e2 =    hot('---^-#', null, 'bazinga');
    const e2subs =       '^ !';
    const expected =     '--#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'bazinga');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with error and throw', () => {
    const e1 =    hot('-a-^--b--#', { a: 1, b: 2 }, 'wokka wokka');
    const e1subs =       '^ !';
    const e2 =    hot('---^-#', null, 'flurp');
    const e2subs =       '^ !';
    const expected =     '--#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'flurp');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with throw and error', () => {
    const e1 =    hot('---^-#', null, 'flurp');
    const e1subs =       '^ !';
    const e2 =    hot('-a-^--b--#', { a: 1, b: 2 }, 'wokka wokka');
    const e2subs =       '^ !';
    const expected =     '--#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'flurp');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with never and throw', () => {
    const e1 =    hot('---^-----------');
    const e1subs =       '^     !';
    const e2 =    hot('---^-----#', null, 'wokka wokka');
    const e2subs =       '^     !';
    const expected =     '------#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'wokka wokka');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with throw and never', () => {
    const e1 =    hot('---^----#', null, 'wokka wokka');
    const e1subs =       '^    !';
    const e2 =    hot('---^-----------');
    const e2subs =       '^    !';
    const expected =     '-----#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'wokka wokka');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with some and throw', () => {
    const e1 =    hot('---^----a---b--|', { a: 1, b: 2 });
    const e1subs =       '^  !';
    const e2 =    hot('---^--#', null, 'wokka wokka');
    const e2subs =       '^  !';
    const expected =     '---#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, { a: 1, b: 2}, 'wokka wokka');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should work with throw and some', () => {
    const e1 =    hot('---^--#', null, 'wokka wokka');
    const e1subs =       '^  !';
    const e2 =    hot('---^----a---b--|', { a: 1, b: 2 });
    const e2subs =       '^  !';
    const expected =     '---#';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, { a: 1, b: 2}, 'wokka wokka');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should handle throw after complete left', () => {
    const left =  hot('--a--^--b---|', { a: 1, b: 2 });
    const leftSubs =       '^      !';
    const right = hot('-----^--------#', null, 'bad things');
    const rightSubs =      '^        !';
    const expected =       '---------#';

    const result = Observable.combineLatest(left, right, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'bad things');
    expectSubscriptions(left.subscriptions).toBe(leftSubs);
    expectSubscriptions(right.subscriptions).toBe(rightSubs);
  });

  it('should handle throw after complete right', () => {
    const left =   hot('-----^--------#', null, 'bad things');
    const leftSubs =        '^        !';
    const right =  hot('--a--^--b---|', { a: 1, b: 2 });
    const rightSubs =       '^      !';
    const expected =        '---------#';

    const result = Observable.combineLatest(left, right, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'bad things');
    expectSubscriptions(left.subscriptions).toBe(leftSubs);
    expectSubscriptions(right.subscriptions).toBe(rightSubs);
  });

  it('should handle interleaved with tail', () => {
    const e1 = hot('-a--^--b---c---|', { a: 'a', b: 'b', c: 'c' });
    const e1subs =     '^          !';
    const e2 = hot('--d-^----e---f--|', { d: 'd', e: 'e', f: 'f'});
    const e2subs =     '^           !';
    const expected =   '-----x-y-z--|';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, { x: 'be', y: 'ce', z: 'cf' });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should handle two consecutive hot observables', () => {
    const e1 = hot('--a--^--b--c--|', { a: 'a', b: 'b', c: 'c' });
    const e1subs =      '^        !';
    const e2 = hot('-----^----------d--e--f--|', { d: 'd', e: 'e', f: 'f' });
    const e2subs =      '^                   !';
    const expected =    '-----------x--y--z--|';

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result).toBe(expected, { x: 'cd', y: 'ce', z: 'cf' });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should handle two consecutive hot observables with error left', () => {
    const left =  hot('--a--^--b--c--#', { a: 'a', b: 'b', c: 'c' }, 'jenga');
    const leftSubs =       '^        !';
    const right = hot('-----^----------d--e--f--|', { d: 'd', e: 'e', f: 'f' });
    const rightSubs =      '^        !';
    const expected =       '---------#';

    const result = Observable.combineLatest(left, right, (x, y) => x + y);

    expectObservable(result).toBe(expected, null, 'jenga');
    expectSubscriptions(left.subscriptions).toBe(leftSubs);
    expectSubscriptions(right.subscriptions).toBe(rightSubs);
  });

  it('should handle two consecutive hot observables with error right', () => {
    const left =  hot('--a--^--b--c--|', { a: 'a', b: 'b', c: 'c' });
    const leftSubs =       '^        !';
    const right = hot('-----^----------d--e--f--#', { d: 'd', e: 'e', f: 'f' }, 'dun dun dun');
    const rightSubs =      '^                   !';
    const expected =       '-----------x--y--z--#';

    const result = Observable.combineLatest(left, right, (x, y) => x + y);

    expectObservable(result).toBe(expected, { x: 'cd', y: 'ce', z: 'cf' }, 'dun dun dun');
    expectSubscriptions(left.subscriptions).toBe(leftSubs);
    expectSubscriptions(right.subscriptions).toBe(rightSubs);
  });

  it('should handle selector throwing', () => {
    const e1 = hot('--a--^--b--|', { a: 1, b: 2});
    const e1subs =      '^  !';
    const e2 = hot('--c--^--d--|', { c: 3, d: 4});
    const e2subs =      '^  !';
    const expected =    '---#';

    const result = Observable.combineLatest(e1, e2, (x, y) => { throw 'ha ha ' + x + ', ' + y; });

    expectObservable(result).toBe(expected, null, 'ha ha 2, 4');
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should allow unsubscribing early and explicitly', () => {
    const e1 =   hot('--a--^--b--c---d-| ');
    const e1subs =        '^        !    ';
    const e2 =   hot('---e-^---f--g---h-|');
    const e2subs =        '^        !    ';
    const expected =      '----x-yz--    ';
    const unsub =         '         !    ';
    const values = { x: 'bf', y: 'cf', z: 'cg' };

    const result = Observable.combineLatest(e1, e2, (x, y) => x + y);

    expectObservable(result, unsub).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  it('should not break unsubscription chains when unsubscribed explicitly', () => {
    const e1 =   hot('--a--^--b--c---d-| ');
    const e1subs =        '^        !    ';
    const e2 =   hot('---e-^---f--g---h-|');
    const e2subs =        '^        !    ';
    const expected =      '----x-yz--    ';
    const unsub =         '         !    ';
    const values = { x: 'bf', y: 'cf', z: 'cg' };

    const result = Observable.combineLatest(
        e1.mergeMap((x) => Observable.of(x)),
        e2.mergeMap((x) => Observable.of(x)),
        (x, y) => x + y
    ).mergeMap((x) => Observable.of(x));

    expectObservable(result, unsub).toBe(expected, values);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
    expectSubscriptions(e2.subscriptions).toBe(e2subs);
  });

  type('should support promises', () => {
    /* tslint:disable:no-unused-variable */
    let a: Promise<number>;
    let b: Promise<string>;
    let c: Promise<boolean>;
    let o1: Rx.Observable<[number, string, boolean]> = Observable.combineLatest(a, b, c);
    let o2: Rx.Observable<boolean> = Observable.combineLatest(a, b, c, (aa, bb, cc) => !!aa && !!bb && cc);
    /* tslint:enable:no-unused-variable */
  });

  type('should support observables', () => {
    /* tslint:disable:no-unused-variable */
    let a: Rx.Observable<number>;
    let b: Rx.Observable<string>;
    let c: Rx.Observable<boolean>;
    let o1: Rx.Observable<[number, string, boolean]> = Observable.combineLatest(a, b, c);
    let o2: Rx.Observable<boolean> = Observable.combineLatest(a, b, c, (aa, bb, cc) => !!aa && !!bb && cc);
    /* tslint:enable:no-unused-variable */
  });

  type('should support mixed observables and promises', () => {
    /* tslint:disable:no-unused-variable */
    let a: Promise<number>;
    let b: Rx.Observable<string>;
    let c: Promise<boolean>;
    let d: Rx.Observable<string[]>;
    let o1: Rx.Observable<[number, string, boolean, string[]]> = Observable.combineLatest(a, b, c, d);
    let o2: Rx.Observable<boolean> = Observable.combineLatest(a, b, c, d, (aa, bb, cc, dd) => !!aa && !!bb && cc && !!dd.length);
    /* tslint:enable:no-unused-variable */
  });

  type('should support arrays of promises', () => {
    /* tslint:disable:no-unused-variable */
    let a: Promise<number>[];
    let o1: Rx.Observable<number[]> = Observable.combineLatest(a);
    let o2: Rx.Observable<number[]> = Observable.combineLatest(...a);
    let o3: Rx.Observable<number> = Observable.combineLatest(a, (...x: any[]) => x.length);
    /* tslint:enable:no-unused-variable */
  });

  type('should support arrays of observables', () => {
    /* tslint:disable:no-unused-variable */
    let a: Rx.Observable<number>[];
    let o1: Rx.Observable<number[]> = Observable.combineLatest(a);
    let o2: Rx.Observable<number[]> = Observable.combineLatest(...a);
    let o3: Rx.Observable<number> = Observable.combineLatest(a, (...x: any[]) => x.length);
    /* tslint:enable:no-unused-variable */
  });

  type('should return Array<T> when given a single promise', () => {
    /* tslint:disable:no-unused-variable */
    let a: Promise<number>;
    let o1: Rx.Observable<number[]> = Observable.combineLatest(a);
    /* tslint:enable:no-unused-variable */
  });

  type('should return Array<T> when given a single observable', () => {
    /* tslint:disable:no-unused-variable */
    let a: Rx.Observable<number>;
    let o1: Rx.Observable<number[]> = Observable.combineLatest(a);
    /* tslint:enable:no-unused-variable */
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace _10.CarSalesman
{
    public class Startup
    {
        public static void Main()
        {
            var numberOfEngines = int.Parse(Console.ReadLine());
            var engines = new HashSet<Engine>();

            for (int i = 0; i < numberOfEngines; i++)
            {
                var engineArgs = Console.ReadLine().Split();
                var engine = new Engine(engineArgs[0], int.Parse(engineArgs[1]));
                if (engineArgs.Length == 3)
                {
                    int displacement;
                    if (int.TryParse(engineArgs[2], out displacement))
                    {
                        engine.Displacement = displacement.ToString();
                    }
                    else
                    {
                        engine.Efficiency = engineArgs[2];
                    }

                }
                else if(engineArgs.Length == 4)
                {
                    int displacement = int.Parse(engineArgs[2]);
                    string eff = engineArgs[3];

                    engine.Displacement = displacement.ToString();
                    engine.Efficiency = eff;
                }

                engines.Add(engine);
            }

            var numberOfCars = int.Parse(Console.ReadLine());
            var cars = new HashSet<Car>();
            for (int i = 0; i < numberOfCars; i++)
            {
                // "<Model> <Engine> <Weight> <Color>
                var carArgs = Console.ReadLine().Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
                var car = new Car(carArgs[0], engines.FirstOrDefault(e => e.Model == carArgs[1]));
                if (carArgs.Length == 3)
                {
                    int weight;
                    if (int.TryParse(carArgs[2], out weight))
                    {
                        car.Weight = weight.ToString();
                    }
                    else
                    {
                        car.Color = carArgs[2];
                    }
                }
                else if(carArgs.Length == 4)
                {
                    car.Weight = carArgs[2];
                    car.Color = carArgs[3];
                }

                cars.Add(car);
            }

            foreach (Car car in cars)
            {
                Console.WriteLine(car.ToString());
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<title>dlib C++ Library - gpu_data_abstract.h</title>

// Copyright (C) 2015  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_GPU_DaTA_ABSTRACT_H_
#ifdef DLIB_GPU_DaTA_ABSTRACT_H_

#include "cuda_errors.h"
#include "../serialize.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    class gpu_data
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This object is a block of size() floats, all stored contiguously in memory.
                Importantly, it keeps two copies of the floats, one on the host CPU side
                and another on the GPU device side. It automatically performs the necessary
                host/device transfers to keep these two copies of the data in sync.

                All transfers to the device happen asynchronously with respect to the
                default CUDA stream so that CUDA kernel computations can overlap with data
                transfers.  However, any transfers from the device to the host happen
                synchronously in the default CUDA stream.  Therefore, you should perform
                all your CUDA kernel launches on the default stream so that transfers back
                to the host do not happen before the relevant computations have completed.

                If DLIB_USE_CUDA is not #defined then this object will not use CUDA at all.
                Instead, it will simply store one host side memory block of floats.

            THREAD SAFETY
                Instances of this object are not thread-safe.  So don't touch one from
                multiple threads at the same time.
        !*/
    public:

        gpu_data(
        );
        /*!
            ensures
                - #size() == 0
                - #host() == nullptr
                - #device() == nullptr
                - #host_ready() == true
                - #device_ready() == true
                - #device_id() == 0
        !*/

        // This object is not copyable, however, it is movable.
        gpu_data(const gpu_data&) = delete;
        gpu_data& operator=(const gpu_data&) = delete;
        gpu_data(gpu_data&& item);
        gpu_data& operator=(gpu_data&& item);

        int device_id(
        ) const;
        /*!
            ensures
                - returns the ID of the CUDA device that allocated this memory. I.e. the
                  number returned by cudaGetDevice() when the memory was allocated.
                - If CUDA is not being used then this function always returns 0.
        !*/

        void async_copy_to_device(
        );
        /*!
            ensures
                - if (!device_ready()) then
                    - Begins asynchronously copying host data to the device once it is safe
                      to do so.  I.e. This function will wait until any previously
                      scheduled CUDA kernels, which are using the device() memory block,
                      have completed before transferring the new data to the device.
                    - A call to device() that happens before the transfer completes will
                      block until the transfer is complete.  That is, it is safe to call
                      async_copy_to_device() and then immediately call device().
        !*/

        void set_size(
            size_t new_size
        );
        /*!
            ensures
                - #size() == new_size
        !*/

        bool host_ready (
        ) const;
        /*!
            ensures
                - returns true if and only if the host's copy of the data is current.  The
                  host's data is current if there aren't any modifications to the data
                  which were made on the device side that have yet to be copied to the
                  host.
        !*/

        bool device_ready (
        ) const;
        /*!
            ensures
                - returns true if and only if the device's copy of the data is current.
                  The device's data is current if there aren't any modifications to the
                  data which were made on the host side that have yet to be copied to the
                  device.
        !*/

        const float* host(
        ) const;
        /*!
            ensures
                - returns a pointer to the host memory block of size() contiguous float
                  values or nullptr if size()==0.
                - if (!host_ready()) then
                    - copies the data from the device to the host, while this is happening
                      the call to host() blocks.
                - #host_ready() == true
        !*/

        float* host(
        );
        /*!
            ensures
                - returns a pointer to the host memory block of size() contiguous float
                  values or nullptr if size()==0.
                - if (!host_ready()) then
                    - copies the data from the device to the host, while this is happening
                      the call to host() blocks.
                - #host_ready() == true
                - #device_ready() == false
                  I.e. Marks the device side data as out of date so that the next call to
                  device() will perform a host to device transfer.  If you want to begin
                  the transfer immediately then you can call async_copy_to_device() after
                  calling host().
        !*/

        float* host_write_only(
        );
        /*!
            ensures
                - This function returns the same pointer as host(), except that it never
                  performs a device to host memory copy.  Instead, it immediately marks the
                  device side data as out of date, effectively discarding it.  Therefore,
                  the values in the data pointed to by host_write_only() are undefined and
                  you should only call host_write_only() if you are going to assign to
                  every memory location in the returned memory block.
                - #host_ready() == true
                - #device_ready() == false
        !*/

        const float* device(
        ) const;
        /*!
            requires
                - DLIB_USE_CUDA is #defined
            ensures
                - returns a pointer to the device memory block of size() contiguous float
                  values or nullptr if size()==0.
                - if (!device_ready()) then
                    - copies the data from the host to the device, while this is happening
                      the call to device() blocks.
                - #device_ready() == true
        !*/

        float* device(
        );
        /*!
            requires
                - DLIB_USE_CUDA is #defined
            ensures
                - returns a pointer to the device memory block of size() contiguous float
                  values or nullptr if size()==0.
                - if (!device_ready()) then
                    - copies the data from the host to the device, while this is happening
                      the call to device() blocks.
                - #host_ready() == false
                - #device_ready() == true
        !*/

        float* device_write_only(
        );
        /*!
            requires
                - DLIB_USE_CUDA is #defined
            ensures
                - This function returns the same pointer as device(), except that it never
                  performs a host to device memory copy.  Instead, it immediately marks the
                  host side data as out of date, effectively discarding it.  Therefore, the
                  values in the data pointed to by device_write_only() are undefined and
                  you should only call device_write_only() if you are going to assign to
                  every memory location in the returned memory block.
                - #host_ready() == false
                - #device_ready() == true
        !*/

        size_t size(
        ) const;
        /*!
            ensures
                - returns the number of floats contained in this object.
        !*/

        void swap (
            gpu_data& item
        );
        /*!
            ensures
                - swaps the state of *this and item
        !*/

    };

    void serialize(const gpu_data& item, std::ostream& out);
    void deserialize(gpu_data& item, std::istream& in);
    /*!
        provides serialization support
    !*/

    void memcpy (
        gpu_data& dest,
        const gpu_data& src
    );
    /*!
        requires
            - dest.size() == src.size()
        ensures
            - Copies the data in src to dest.  If the device data is current (i.e.
              device_ready()==true) on both src and dest then the copy will happen entirely
              on the device side.
            - It doesn't matter what GPU device is selected by cudaSetDevice().  You can
              always copy gpu_data objects to and from each other regardless.
            - This function blocks until the copy has completed.
    !*/

    void memcpy (
        gpu_data& dest,
        size_t dest_offset,
        const gpu_data& src,
        size_t src_offset,
        size_t num
    );
    /*!
        requires
            - dest_offset + num <= dest.size()
            - src_offset  + num <= src.size()
        ensures
            - Copies the data in src to dest, but only copies data in the range
              [src.host()+src_offset, src.host()+src_offset+num) to
              [dest.host()+dest_offset, dest.host()+dest_offset+num).  Therefore, it is
              just like the above memcpy() except that you can specify some subset of data
              in a gpu_data object to be copied.
            - Like the above version of memcpy(), the copy will happen in the most
              efficient way, automatically using the appropriate type of host/device
              transfers based on where data is currently resident.
            - It doesn't matter what GPU device is selected by cudaSetDevice().  You can
              always copy gpu_data objects to and from each other regardless.
            - This function blocks until the copy has completed.
    !*/

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_GPU_DaTA_ABSTRACT_H_


text:
using System;
using UnityEngine;
using UnityEngine.Networking;
using Zenject;

public class RegimentController : NetworkBehaviour {

	[SyncVar] public string RegimentName = "";
	[SyncVar] public int BattalionCount = 0;
	[SyncVar] public string VeterencyLevel = "";
	[SyncVar(hook = "LocationChange")] private string _location = "";
	[SyncVar] public string BrigadeMember = "";
	[SyncVar] public string RegimentInsignia = "";
	[SyncVar] public string BrigadeInsignia = "";

	[Inject] SystemRegistry _sysRegistry;
	[Inject] RegimentChit.Factory _chitFactory;

	private RegimentChit _chit = null;

	public void Setup( string regimentName, int battalions, string veterency, string location,
						string brigade, string regimentInsignia, string brigadeInsignia )
	{
		RegimentName = regimentName;
		BattalionCount = battalions;
		VeterencyLevel = veterency;
		BrigadeMember = brigade;
		RegimentInsignia = regimentInsignia;
		BrigadeInsignia = brigadeInsignia;

		_location = location;
	}

	void Start()
	{
		LocationChange(_location);
		gameObject.name = RegimentName;
	}

	public void LocationChange( string newLocation )
	{
		if ( _chit != null ) GameObject.Destroy(_chit.gameObject);

		_location = newLocation;
		transform.parent = _sysRegistry.Lookup( _location ).transform;

		_chit = _chitFactory.Create(this);
		_chit.transform.SetParent( transform.parent, false );

		//if (isClient) CmdSetLocation( newLocation );
	}

	/*[Command]
	public void CmdSetLocation( string newLocation )
	{
		LocationChange( newLocation );
	}*/

	public class Factory : Factory<RegimentController> {}
}


text:
import axios from 'axios';
import settings from 'src/settings';

export function getRealtime () {
  return axios.get('/api/realtime', {
    baseURL: settings.server,
    params: {
      userId: settings.userId,
      spaceCode: settings.spaceCode,
      roomTag: settings.roomTag,
    }
  });
}


text:
<!doctype html>
<title>document.write</title>


text:
package name.chengchao.monitor.mymongo.common.model;

/**
 * @author charles.chengc 2015年6月30日 下午2:47:06
 */
public class Result {

    /**
     * 方法调用是否成功
     */
    private boolean success  = true;
    /**
     * 错误信息
     */
    private String  errorMsg = "";

    private Object  data;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}


text:
package cmd

import (
	"fmt"
	"strconv"

	"github.com/josephlewis42/paraphrase/paraphrase"
	"github.com/spf13/cobra"
	"gopkg.in/AlecAivazis/survey.v1"
)

const background = `
Unlike a regular search engine, Paraphrase uses "fingerprints" to look for
similarity between a search and the documents it knows about.

It does this by looking at windows of text, for example a window of length 10
produces 4 windows:

     Hello, world!
    [Hello, wor]
     [ello, worl]
      [llo, world]
       [lo, world!]

These windows get fingerprinted to form a list of document fingerprints. For
example:

	[Hello, wor]	-> 10
	 [ello, worl]	-> 45
	  [llo, world]	-> 23
	   [lo, world!]	-> 0

	[10, 45, 23, 0]

Finally, we need to choose which fingerprints to save. Again we run a window
over the fingerprints and choose the smallest in each window as "defining
characteristics" of the document. For example, a fingerprint window of size 2:

	[10, 45, 23, 0] -> [10, 45], [45, 23], [23, 0] -> [10, 23, 0]
`

func init() {
	RootCmd.AddCommand(initCmd)
}

var initCmd = &cobra.Command{
	Use:   "init",
	Short: "Initializes paraphrase",
	Long:  `Sets up paraphrase with some questions and answers`,
	RunE: func(cmd *cobra.Command, args []string) error {

		fmt.Println(background)

		settings := paraphrase.NewDefaultSettings()

		for {
			windowSize := ""
			survey.AskOne(&survey.Input{
				Message: "What size window would you like to use?",
				Help:    `Larger windows mean a smaller database, but requires longer query texts to get matches.`,
				Default: strconv.FormatInt(int64(settings.WindowSize), 10),
			}, &windowSize, nil)
			size, err := strconv.ParseInt(windowSize, 10, 64)
			if err != nil {
				return err
			}
			settings.WindowSize = int(size)

			kgram := ""
			survey.AskOne(&survey.Input{
				Message: "What size k-gram would you like to use?",
				Help:    `Larger k-grams mean more certainty in matches, but may miss small changes.`,
				Default: strconv.FormatInt(int64(settings.FingerprintSize), 10),
			}, &kgram, nil)
			size, err = strconv.ParseInt(kgram, 10, 64)
			if err != nil {
				return err
			}
			settings.FingerprintSize = int(size)

			robustQuestion := &survey.Confirm{
				Message: "Would you like to use robust winnowing?",
				Help: `Robust winnowing can reduce the size of the index if you're planning on indexing
data with many repeated sections but may skew search rankings slightly.`,
				Default: settings.RobustHash,
			}
			survey.AskOne(robustQuestion, &settings.RobustHash, nil)

			correct := true
			lookCorrect := &survey.Confirm{
				Message: "Do these settings look correct?",
				Default: correct,
			}
			survey.AskOne(lookCorrect, &correct, nil)

			if correct {
				break
			}
		}

		// Creates a new database in the given directory with the given settings
		_, err := paraphrase.Create(projectBase, settings)
		return err
	},
}


text:
package com.ibm.dcs.example_java;

import com.ibm.watson.developer_cloud.document_conversion.v1.DocumentConversion;

import java.io.File;

import static com.ibm.dcs.Environment.DEFAULT;

public class JSingleConversion {

    public static void main(String[] args) {
        File book = new File("alices_adventures_in_wonderland.pdf");

        DocumentConversion service = new DocumentConversion();
        service.setUsernameAndPassword(DEFAULT.getUsername(), DEFAULT.getPassword());

        String text = service.convertDocumentToText(book);

        System.out.println(text.substring(0, 1024*10));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>spring-cloud-stream</artifactId>
	<packaging>jar</packaging>
	<name>spring-cloud-stream</name>
	<description>Messaging Microservices with Spring Integration</description>

	<parent>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-stream-parent</artifactId>
		<version>1.0.0.BUILD-SNAPSHOT</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-messaging</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-stream-tuple</artifactId>
			<version>1.0.0.BUILD-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.retry</groupId>
			<artifactId>spring-retry</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
mydatepicker

Angular 2 date picker - Angular 2 reusable UI component.

Source code of the component is here

Similar date range picker is here

Normal mode

            <sample-date-picker-normal>loading...</sample-date-picker-normal>

Inline mode

            <sample-date-picker-inline>loading...</sample-date-picker-inline>

Access modifier example

            <sample-date-picker-access-modifier>loading...</sample-date-picker-access-modifier>


text:
/*

FTT with 3D Logo

© Guillaume Gonnet
License GPLv2

*/

(function() {

	var canvasFft = $("#fft1 canvas")[0],
		ctxFft = canvasFft.getContext('2d');

		h = 0,
		w = 0,

		countFft = 150;

	ctxFft.fillStyle = "#ff0077";

	var loaded = false;

	var coeffX = 15;
	var coeffY = 7;

	var scale = 350;
	var active = false;

	var camera, scene, renderer, composer, logo;

	function init() {

		// Camera
		camera = new THREE.PerspectiveCamera( 30, 1, 1, 10000 );
		camera.position.z = 2200;

		// Scene
		scene = new THREE.Scene();
		scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 );
		scene.add( camera );

		// Light
		var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 );
		light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 );
		scene.add( light );

		var light = new THREE.DirectionalLight( 0x497f13, 1 );
		light.position.set( 0, -1, 0 );
		scene.add( light );

		// Renderer
		renderer = new THREE.WebGLRenderer( { antialias: true } );
		renderer.domElement.style.position = "absolute";

		renderer.setClearColor( 0, 1 );

		$("#fft1")[0].appendChild( renderer.domElement );

		// Post Processing

		var hblur = new THREE.ShaderPass( THREE.HorizontalBlurShader );
		hblur.uniforms[ 'h' ].value =  1 / window.innerWidth;

		var vblur = new THREE.ShaderPass( THREE.VerticalBlurShader);
		vblur.uniforms[ 'v' ].value =  1 / window.innerHeight;

		var blurAmountX = 15 / window.innerWidth,
			shaderBlur = THREE.TriangleBlurShader,
			effectBlurX = new THREE.ShaderPass( shaderBlur, 'texture' );

		effectBlurX.uniforms[ 'delta' ].value = new THREE.Vector2( blurAmountX, 0 );

		var effectFocus = new THREE.ShaderPass( THREE.FocusShader );
		effectFocus.uniforms[ 'sampleDistance' ].value = 0.99; //0.94
		effectFocus.uniforms[ 'waveFactor' ].value = 0.003;  //0.00125

		var renderScene = new THREE.RenderPass( scene, camera );

		composer = new THREE.EffectComposer( renderer );
		composer.addPass( renderScene );

		composer.addPass( hblur );
		composer.addPass( vblur );
		composer.addPass( effectBlurX );
		composer.addPass( effectFocus );

		vblur.renderToScreen = true;
		effectFocus.renderToScreen = true;

		// Loader
		var loader = new THREE.JSONLoader();
		loader.load( "asset/model4.js", createGeometry);

	}

	function createGeometry(geometry, materials) {

		var x = 0, y = -250, z = -300;

		geometry.computeBoundingBox();
		var bb = geometry.boundingBox;

		logo = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) );
		logo.position.set( x, y - bb.min.y * scale, z );
		logo.rotation.y = Math.PI * 2;
		logo.scale.set( scale, scale, scale );
		scene.add( logo );

		loaded = true;
		animate();
	}

	function animate() {

		if(!loaded)  return;

		logo.scale.set( scale, scale, scale );

		if(scale < 360)
			scale = 350;
		else
			scale -= 10;

		if(Math.abs(camera.position.x) > 600)
			coeffX = -coeffX;

		if(Math.abs(camera.position.y) > 500)
			coeffY = -coeffY;

		camera.position.x += coeffX;
		camera.position.y += coeffY;

		camera.lookAt(scene.position);

		//renderer.render( scene, camera );
		composer.render( 0.1 );

		if(!active) return;

		requestAnimationFrame(animate);
	}

	init();

	var fft = {

		onKick: function() {
			scale = 500;
		},

		offKick: function() {

		},

		update: function() {

			var spectrum = dancer.getSpectrum(),
				width = w * 0.42,
				height = h / countFft;

			ctxFft.clearRect( 0, 0, w, h );
			ctxFft.fillStyle = "#666";
			for ( var i = 0, l = spectrum.length; i < l && i < countFft; i++ ) {
				ctxFft.fillRect( 0, i * height, spectrum[ i ] * width, height);
				ctxFft.fillRect( w, i * height, -spectrum[ i ] * width, height);
			}
		},

		onResize: function(height, width) {
			camera.aspect = width / height;
			camera.updateProjectionMatrix();

			renderer.setSize( width, height );

			canvasFft.height = h = height;
			canvasFft.width = w = width;
			fft.reset();
		},

		reset: function() {
			ctxFft.clearRect( 0, 0, w, h );
		},

		on: function() {
			active = true;
			requestAnimationFrame(animate);
		},

		off: function() {
			active = false;
		}
	}

	fft.onResize(wHeight, wWidth);

	FFTManager[1] = fft;

})();


text:
package pl.tajchert.wear.businesscard.util;

public class ValuesCons {
    public final static String PREFS_KEY = "pl.tajchert.wear.businesscard";
	public final static String PREFS_NAME = "pl.tajchert.wear.businesscard.contact.name";
	public final static String PREFS_SURNAME = "pl.tajchert.wear.businesscard.contact.surname";
	public final static String PREFS_EMAIL = "pl.tajchert.wear.businesscard.contact.email";
	public final static String PREFS_PHONE = "pl.tajchert.wear.businesscard.contact.phone";
	public final static String PREFS_WEBSITE = "pl.tajchert.wear.businesscard.contact.url";
    public final static String PREFS_ADDRESS = "pl.tajchert.wear.businesscard.contact.address";

    public final static String PREFS_QR_CONTENT = "pl.tajchert.wear.businesscard.qr.content";

    //Wear stuff
    public final static String WEAR_PATH = "/business_card";
    public final static String WEAR_QR_CODE = "qr_code";

    public final static int TIMEOUT_MS = 10000;
}


text:
RSpec.describe Spree::Admin::ProductsController, type: :controller do
  stub_authorization!

  let(:user) { create(:user) }
  let(:product) { create(:product) }

  before { allow(controller).to receive(:spree_current_user).and_return(user) }

  context 'related' do
    it 'is not routable' do
      get :related, params: { id: product.id }
      expect(response.status).to be(200)
    end

    it 'responds to model_class as Spree::Relation' do
      expect(controller.send(:model_class)).to eq Spree::Product
    end
  end
end


text:
import AbstractService from './AbstractService';
import SearchParameters from '../domain/SearchParameters';
import RestApiService from './RestApiService';

class WorkflowTaskInstanceService extends AbstractService {

  getApiPath() {
    return '/workflow-tasks';
  }

  getNiceLabel(task) {
    if (!task) {
      return '';
    }
    return task.taskName;
  }

  supportsAuthorization() {
    return true;
  }

  supportsBulkAction() {
    return true;
  }

  getGroupPermission() {
    return 'WORKFLOWTASK';
  }

  completeTask(id, formData) {
    return RestApiService.put(this.getApiPath() + `/${id}/complete`, formData);
  }

  /**
   * Returns default searchParameters for current entity type
   *
   * @return {object} searchParameters
   */
  getDefaultSearchParameters() {
    return super.getDefaultSearchParameters().setName(SearchParameters.NAME_QUICK).clearSort().setSort('taskCreated', 'desc');
  }
}

export default WorkflowTaskInstanceService;


text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.returnExports = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){

'use strict';

/**
 * Indicates if `Symbol.toStringTag`exists and is the correct type.
 * `true`, if it exists and is the correct type, otherwise `false`.
 *
 * @type boolean
 */
module.exports = _dereq_('has-symbol-support-x') && typeof Symbol.toStringTag === 'symbol';

},{"has-symbol-support-x":2}],2:[function(_dereq_,module,exports){
/**
 * @file Tests if ES6 Symbol is supported.
 * @version 1.4.0
 * @author Xotic750 <Xotic750@gmail.com>
 * @copyright  Xotic750
 * @license {@link <https://opensource.org/licenses/MIT> MIT}
 * @module has-symbol-support-x
 */

'use strict';

/**
 * Indicates if `Symbol`exists and creates the correct type.
 * `true`, if it exists and creates the correct type, otherwise `false`.
 *
 * @type boolean
 */
module.exports = typeof Symbol === 'function' && typeof Symbol('') === 'symbol';

},{}]},{},[1])(1)
});


text:
.. _utils:

Utilities
=========

.. autoclass:: properties.utils.Sentinel

.. autofunction:: properties.filter_props

.. autoclass:: properties.ValidationError

.. autoclass:: properties.SelfReferenceError


text: add_lunch_combo turbo_z2-eng


text:
package org.vertexium.cypher.functions.date;

import org.vertexium.cypher.VertexiumCypherQueryContext;
import org.vertexium.cypher.exceptions.VertexiumCypherException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateFunction extends DateParseFunction {
    private static final DateTimeFormatter[] PATTERNS = new DateTimeFormatter[]{
        DateTimeFormatter.ofPattern("yyyy-MM-dd")
    };

    @Override
    protected Object parseString(VertexiumCypherQueryContext ctx, String str) {
        for (DateTimeFormatter pattern : PATTERNS) {
            try {
                return LocalDate.parse(str, pattern).atStartOfDay(ctx.getZoneId());
            } catch (DateTimeParseException ex) {
                // Try the next one
            }
        }
        throw new VertexiumCypherException("Could not parse date: " + str);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Function template swap</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.string_literal_hpp" title="Header <boost/log/utility/string_literal.hpp>">
<link rel="prev" href="operator_idm45961915120192.html" title="Function template operator<<">
<link rel="next" href="str_literal.html" title="Function template str_literal">

Function template swap

boost::log::swap — External swap.

Synopsis

// In header: <boost/log/utility/string_literal.hpp>

template<typename CharT, typename TraitsT>
  constexpr void
  swap(basic_string_literal< CharT, TraitsT > & left,
       basic_string_literal< CharT, TraitsT > & right);

Copyright © 2007-2021 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
/* Hey, there's your missing semicolon, lunr.js! */
;

/* Truncate a string after the given number of characters */
String.prototype.truncate = function(n) {
  if (this.length > n) {
    while (this[n] != ' ' && --n > 0);
    return this.substring(0, n) + '…';
  }
  return this;
}

/* Wrap an HTMLElement around each element in an HTMLElement array */
HTMLElement.prototype.wrap = function (elms) {
  if (!elms.length) elms = [elms];
  for (var i = elms.length - 1; i >= 0; i--) {
    var child = (i > 0) ? this.cloneNode(true) : this;
    var el = elms[i];

    /* Cache current parent and sibling */
    var parent  = el.parentNode,
        sibling = el.nextSibling;

    /* Wrap the element and remove it from its current parent */
    child.appendChild(el);
    if (sibling) {
      parent.insertBefore(child, sibling);
    } else {
      parent.appendChild(child);
    }
  }
}

/* ----------------------------------------------------------------------------
 * Application logic
 * ------------------------------------------------------------------------- */

/* Initialize application upon DOM ready */
document.addEventListener('DOMContentLoaded', function() {
  'use strict';

  /* Test for iOS */
  Modernizr.addTest('ios', function() {
    return !!navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
  });

  /* Test for web application context */
  Modernizr.addTest('standalone', function() {
    return !!navigator.standalone;
  });

  /* Attack FastClick to mitigate 300ms delay on touch devices */
  FastClick.attach(document.body);

  /* Grab relevant elements from the DOM */
  var toggle  = document.getElementById('toggle-search'),
      reset   = document.getElementById('reset-search'),
      drawer  = document.querySelector('.drawer'),
      anchors = document.querySelectorAll('.anchor'),
      search  = document.querySelector('.search .field'),
      query   = document.querySelector('.query'),
      meta    = document.querySelector('.results .meta');

/* ----------------------------------------------------------------------------
 * Initialize drawer
 * ------------------------------------------------------------------------- */

  /* Automatically close drawer when anchors are clicked */
  Array.prototype.forEach.call(anchors, function(item) {
    item.querySelector('a').addEventListener('click', function() {
      document.getElementById('toggle-drawer').checked = false;
      document.body.classList.remove('toggle-drawer');
     $('.button.button-menu').trigger('click');
    });
  });

  /* Align drawer to window offset */
  var pageYOffsetLast = window.pageYOffset;
  var align = function() {
    var boundary = window.pageYOffset + window.innerHeight;
    var clipping = Math.max(0, window.innerHeight - drawer.offsetHeight);

    /* Ensure alignment with footer if at end of document */
    if (boundary > document.body.clientHeight - (96 - clipping)) {
      if (drawer.style.position != 'absolute') {
        drawer.style.position = 'absolute';
        drawer.style.top      = null;
        drawer.style.bottom   = 0;
      }

    /* Pin drawer to top, if window is higher than drawer */
    } else if (drawer.offsetHeight < window.innerHeight) {
      if (drawer.style.position != 'fixed') {
        drawer.style.position = 'fixed';
        drawer.style.top = 0;
        drawer.style.bottom = null;
      }

    /* If the drawer is not pinned, check if we need to pin it */
    } else if (drawer.style.position != 'fixed') {

      /* Pin drawer to bottom of window */
      if (boundary > drawer.offsetTop + drawer.offsetHeight) {
        drawer.style.position = 'fixed';
        drawer.style.top = null;
        drawer.style.bottom = -96 + 'px';

      /* Pin drawer to top of window */
      } else if (window.pageYOffset < drawer.offsetTop) {
        drawer.style.position = 'fixed';
        drawer.style.top = 0;
        drawer.style.bottom = null;
      }

    /* If the drawer is pinned, check if we have to unpin it */
    } else {
      if (window.pageYOffset > pageYOffsetLast) {
        if (drawer.style.top) {
          drawer.style.position = 'absolute';
          drawer.style.top = Math.max(0, pageYOffsetLast) + 'px';
          drawer.style.bottom = null;
        }
      } else if (drawer.style.bottom) {
        drawer.style.position = 'absolute';
        drawer.style.top = (boundary - drawer.offsetHeight) + 'px';
        drawer.style.bottom = null;
      }
    }

    /* Update last offset (mitigiate negative offsets in Safari) */
    pageYOffsetLast = Math.max(0, window.pageYOffset);
  }

  /* Check for media query events */
  var check = function() {
    var main = document.querySelector('.main');
    window.removeEventListener('scroll', align);

    /* Reset drawer position when entering collapsed mode */
    if (matchMedia("only screen and (max-width: 959px)").matches) {
      drawer.style.position = null;
      drawer.style.top      = null;
      drawer.style.bottom   = null;

    /* Check if the scroll handler needs to be registered */
    } else if (drawer.offsetHeight + 96 < main.offsetHeight) {
      window.addEventListener('scroll', align);
      align();
    }
  }

  /* Register resize handler and fire once */
  if (!Modernizr.ios) {
    window.addEventListener('resize', check);
    check();
  }

/* ----------------------------------------------------------------------------
 * Initialize search index
 * ------------------------------------------------------------------------- */

  /* Initialize index */
  var initialize = function() {
    pegasus(base_url + '/mkdocs/search_index.json').then(

      /* Request successful, we got the index */
      function(data, xhr) {

        /* Create index */
        var index = lunr(function() {
          this.field('title', { boost: 10 });
          this.ref('location');
        });

        /* Index articles */
        var articles = {};
        data.docs.map(function(article) {
          article.location = base_url + article.location;
          articles[article.location] = article;
          index.add(article);
        });

        /* Register keyhandler to execute search on key up */
        query.addEventListener('keyup', function() {
          var container = document.querySelector('.results .list');
          //first time
            $('.results').css('display', 'block');
          while (container.firstChild)
            container.removeChild(container.firstChild);

          /* Abort, if the query is empty */
          var bar = document.querySelector('.bar.search');
          if (!query.value.length) {
            while (meta.firstChild)
              meta.removeChild(meta.firstChild);

            /* Restore state */
            bar.classList.remove('non-empty');
            return;
          }

          /* Show reset button */
          bar.classList.add('non-empty');

          /* Execute search */
          var results = index.search(query.value);
          results.map(function(result) {
            var article = articles[result.ref];

            /* Create article container */
            var teaser = document.createElement('article');
            teaser.classList.add('result');

            /* Create title element */
            var title = document.createElement('h1');
            title.innerHTML = article.title;
            teaser.appendChild(title);

            // /* Create text element */
            // var text = document.createElement('p');
            // text.innerHTML = article.text.truncate(140);
            // teaser.appendChild(text);

            /* Create a link referring to the article */
            var link = document.createElement('a');
            link.href = article.location;
            link.appendChild(teaser);

            /* Create url element */
            var url = document.createElement('span');
            url.innerHTML = link.href.split('#')[0];
            teaser.appendChild(url);

            /* Close search and jump to anchor when on same page */
            var parts = link.href.split('#');
            if (parts[0] == document.location.href.split('#')[0]) {
              link.addEventListener('click', function(e) {
                document.body.classList.remove('toggle-search');
                document.body.classList.remove('locked');
                toggle.checked = false;

                /* Don't catch anchors if the search doesn't cover the page */
                if (matchMedia('only screen and (min-width: 960px)').matches)
                  return;

                /* Prevent default to intercept scroll-to behaviour and
                   stop propagation, as this interferes with the link-lock in
                   the web application context, which opens all internal links
                   inside the same context */
                e.preventDefault();
                e.stopPropagation();

                /* Scroll to chapter, if given */
                if (parts.length != 1) {
                  var chapter = document.getElementById(parts[1]);
                  if (chapter) {

                    /* Scroll to chapter, but wait for 100ms to prevent flashes
                       on iOS. A short timeout seems to do the trick */
                    setTimeout(function() {
                      chapter.scrollIntoView && chapter.scrollIntoView() ||
                        window.scrollTo(0, chapter.offsetTop);
                    }, 100);
                  }
                }
              });
            }

            /* Add article to search results */
            container.appendChild(link);
          });

          /* Show number of search results */
          var number = document.createElement('strong');
          number.innerHTML = results.length + ' search result'
            + (results.length != 1 ? 's' : '');

          /* Update number */
          while (meta.firstChild)
            meta.removeChild(meta.firstChild);
          meta.appendChild(number);
        });
      },

      /* Handle error */
      function(data, xhr) {
        console.error(data, xhr.status);
      }
    );

    /* Remove listener, as we only have to initialize once */
    toggle.removeEventListener('click', initialize);
  };

  /* Initialize on first click */
  toggle.addEventListener('click', initialize);

/* ----------------------------------------------------------------------------
 * Initialize search modal
 * ------------------------------------------------------------------------- */

  /* Intercept click on search mode toggle */
  var offset = 0;
  toggle.addEventListener('click', function(e) {
    var list = document.body.classList;
    var lock = !matchMedia('only screen and (min-width: 960px)').matches;

    /* Exiting search mode */
    if (list.contains('locked')) {
      list.remove('locked');

      /* Scroll to former position, but wait for 100ms to prevent flashes
         on iOS. A short timeout seems to do the trick */
      if (lock)
        setTimeout(function() {
          window.scrollTo(0, offset);
        }, 100);

    /* Entering search mode */
    } else {
      offset = window.scrollY;

      /* First timeout: scroll to top after transition, to omit flickering */
      if (lock)
        setTimeout(function(){
          window.scrollTo(0, 0);
        }, 400);

      /* Second timeout: Lock body after finishing transition and scrolling to
         top and focus input field. Sadly, the focus event is not dispatched
         on iOS Safari and there's nothing we can do about it. */
      setTimeout(function() {

        /* This additional check is necessary to handle fast subsequent clicks
           on the toggle and the timeout to lock the body must be cancelled */
        if (this.checked) {
          if (lock)
            list.add('locked');
          setTimeout(function() {
            query.focus();
          }, 200);
        }
      }.bind(this), 450);
    }
  });

  /* Dispatch input focus on touch of search section */
  search.addEventListener('touchstart', function() {
    query.focus();
  });

  /* Exit search mode when pressing ESC */
  window.addEventListener('keyup', function(e) {
    var code = e.keyCode || e.which;
    if (code == 27) {
      query.blur();

      /* Exit locked state */
      document.body.classList.remove('toggle-search');
      document.body.classList.remove('locked');
      toggle.checked = false;
    }
  });

  /* Delete search results upon click on "x" */
  var empty = document.getElementById('reset-search');
  empty.addEventListener('click', function() {
    var container = document.querySelector('.results .list');
    while (container.firstChild)
      container.removeChild(container.firstChild);

    /* Hide search button */
    var bar = document.querySelector('.bar.search');
    bar.classList.remove('non-empty');

    /* Reset number of search results */
    meta.innerHTML = '';

    /* Empty search input */
    query.value = '';
    query.focus();
  });

/* ----------------------------------------------------------------------------
 * Initialize scroll spy
 * ------------------------------------------------------------------------- */

  /* Retrieve vertical offset of article chapters */
  var chapters = document.querySelectorAll('h2');
  chapters = Array.prototype.map.call(chapters, function(item) {
    return item.offsetTop;
  });

  /* Update currently active chapter, if the new chapter is two thirds
     into the viewport - account for iOS web application context */
  var visible = null;
  document.addEventListener('scroll', function() {
    var offset = window.scrollY + (window.innerHeight / 3),
        active = chapters.length - 1;
    for (var c = 0; c < active; c++)
      if (offset < chapters[c + 1])
        active = c;

    /* Update anchors, if a new chapter became visible */
    if (active != visible) {
      visible = active;
      Array.prototype.forEach.call(anchors, function(item, index) {
        var link = item.querySelector('a');
        if (index != visible || link.classList.add('current'))
          link.classList.remove('current');
      });
    }
  });

/* ----------------------------------------------------------------------------
 * Fix syntax highlighting
 * ------------------------------------------------------------------------- */

  /* Fix highlighting for function calls */
  var functions = document.querySelectorAll('.n + .p');
  Array.prototype.forEach.call(functions, function(item) {
    var text = item.innerText || item.textContent;
    if (text && text[0] == '(')
      item.previousSibling.classList.add('f');
  });

/* ----------------------------------------------------------------------------
 * Progressive structure enhancement
 * ------------------------------------------------------------------------- */

  /* Wrap all data tables */
  var tables = document.querySelectorAll('table');
  Array.prototype.forEach.call(tables, function(item) {
    var wrapper = document.createElement('div');
    wrapper.classList.add('data');
    wrapper.wrap(item);
  });

/* ----------------------------------------------------------------------------
 * Fix overflow scrolling on iOS
 * ------------------------------------------------------------------------- */

  /* Force 1px scroll offset to trigger overflow scrolling */
  if (Modernizr.ios) {
    var scrollable = document.querySelectorAll(
      '.scrollable, .standalone .article');
    Array.prototype.forEach.call(scrollable, function(item) {
      item.addEventListener('touchstart', function() {
        var top = this.scrollTop;

        /* We're at the top of the container */
        if (top == 0) {
          this.scrollTop = 1;

        /* We're at the bottom of the container */
        } else if (top + this.offsetHeight == this.scrollHeight) {
          this.scrollTop = top - 1;
        }
      });
    });
  }

  /* Prevent scrolling on project, overlay and header */
  var prevented = document.querySelectorAll('.project, .overlay, .header');
  Array.prototype.forEach.call(prevented, function(item) {
    item.addEventListener('touchmove', function(e) {
      e.preventDefault();
    });
  });

/* ----------------------------------------------------------------------------
 * Fallback for browsers that don't support :checked
 * ------------------------------------------------------------------------- */

  /* Set representative class on body for active toggle */
  var toggles = document.querySelectorAll('.toggle');
  Array.prototype.forEach.call(toggles, function(item) {
    item.addEventListener('click', function() {
      document.body.classList.toggle(this.id);
    });
  });

/* ----------------------------------------------------------------------------
 * Initialize GitHub star button
 * ------------------------------------------------------------------------- */

  /* Get Stars for current repository */
  if (repo_id) {
    pegasus('https://api.github.com/repos/' + repo_id).then(

      /* Request successful, we got the stars */
      function(data, xhr) {
        var count = data.stargazers_count;
        if (count > 10000)
          count = (count / 1000).toFixed(0) + 'k';
        else if (count > 1000)
          count = (count / 1000).toFixed(1) + 'k';

        /* Set number of stars */
        var stars = document.querySelector('.repo-stars .count');
        stars.innerHTML = count;
      },

      /* Handle error */
      function(data, xhr) {
        console.error(data, xhr.status);
      }
    );
  }
});

/* ----------------------------------------------------------------------------
 * Collapse logic
 * ------------------------------------------------------------------------- */

var openPane = function(){
    var spanParent = $(this).parent();
    $(spanParent.find('.expand-icon')[0]).html(' -');
    spanParent.children('ul').show();

    $(this).one('click', closePane);
    ///add a hover class only while closed
};
var closePane = function(){

    var spanParent = $(this).parent();
    $(spanParent.find('.expand-icon')[0]).html(' +');
    spanParent.children('ul').hide();
    $(this).one('click', openPane);
};
//first click goes to openPane function, second to closePane
$('.expandable-nav').one('click', openPane);
//here we simulate a click event on new page load, for any currently selected page
//this way, browser will 'remember' that section has been expanded, and should open closePane on first click
$($('.current.sechead').find('.expandable-nav')[0]).trigger('click');

//
//var switchToXBtn = function(event){
//    $(this).find('.toggle-button').removeClass('icon-menu').addClass('icon-close');
//    $('.button.button-menu').one('click', switchToMenuBtn);
//
//    var btn = $(this);
//    $('.drawer').mouseleave(function(){
//       $('body').one('click', function(){
//                        $('.button.button-menu').trigger('click');
//        $('.drawer').unbind('mouseleave');
//    });
//    });
//
////    $('.header').mouseleave(function(){
////       $('body').one('click', function(){
////            $('.button.button-menu').trigger('click');
////                $('.header').unbind('mouseleave');
////       });
////       });
//    };
//
//
//
////        $('.button.button-menu').trigger('click');
//
//var switchToMenuBtn = function(){
//      $(this).find('.toggle-button').removeClass('icon-close').addClass('icon-menu');
//    $('.button.button-menu').one('click', switchToXBtn);
//};
//
//$('.button.button-menu').one('click', switchToXBtn);


text:
package com.github.ccook.gtk.model.object.widget.container.bin;

import com.github.ccook.gtk.model.object.widget.container.GtkBin;

/**
 * Created by cam on 10/22/16.
 */
public class GtkMenuItem extends GtkBin {
}


text:
---
external help file: Microsoft.Azure.Commands.EventHub.dll-Help.xml
Module Name: AzureRM
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.eventhub/set-azurermeventhubauthorizationrule
schema: 2.0.0
---

# Set-AzureRmEventHubAuthorizationRule

## SYNOPSIS
Updates the specified authorization rule on an Event Hub.

## SYNTAX

### NamespaceAuthorizationRuleSet (Default)
```
Set-AzureRmEventHubAuthorizationRule [-ResourceGroupName] <String> [-Namespace] <String> [-Name] <String>
 [[-InputObject] <SharedAccessAuthorizationRuleAttributes>] [[-Rights] <String[]>]
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

### EventhubAuthorizationRuleSet
```
Set-AzureRmEventHubAuthorizationRule [-ResourceGroupName] <String> [-Namespace] <String> [-EventHub] <String>
 [-Name] <String> [[-InputObject] <SharedAccessAuthorizationRuleAttributes>] [[-Rights] <String[]>]
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

### AuthoRuleInputObjectSet
```
Set-AzureRmEventHubAuthorizationRule [-ResourceGroupName] <String> [-Name] <String>
 [-InputObject] <SharedAccessAuthorizationRuleAttributes> [-DefaultProfile <IAzureContextContainer>] [-WhatIf]
 [-Confirm] [<CommonParameters>]
```

### AuthoRulePropertiesSet
```
Set-AzureRmEventHubAuthorizationRule [-ResourceGroupName] <String> [-Name] <String> [-Rights] <String[]>
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The Set-AzureRmEventHubAuthorizationRule cmdlet updates the specified authorization rule on the given Event Hub.

## EXAMPLES

### Example 1
```
PS C:\> Set-AzureRmEventHubAuthorizationRule -ResourceGroupName MyResourceGroupName -NamespaceName MyNamespaceName -EventHubName MyEventHubName -AuthorizationRuleName MyAuthRuleName -Rights @("Manage")
```

Updates the authorization rule \`MyAuthRuleName\` to grant Manage rights to the Event Hub \`MyEventHubName\`, scoped by the namespace \`MyNamespaceName\`.

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure.

```yaml
Type: IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -EventHub
EventHub Name.

```yaml
Type: String
Parameter Sets: EventhubAuthorizationRuleSet
Aliases: EventHubName

Required: True
Position: 2
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -InputObject
{{Fill InputObject Description}}

```yaml
Type: SharedAccessAuthorizationRuleAttributes
Parameter Sets: NamespaceAuthorizationRuleSet, EventhubAuthorizationRuleSet
Aliases: AuthRuleObj

Required: False
Position: 4
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

```yaml
Type: SharedAccessAuthorizationRuleAttributes
Parameter Sets: AuthoRuleInputObjectSet
Aliases: AuthRuleObj

Required: True
Position: 4
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -Name
AuthorizationRule Name.

```yaml
Type: String
Parameter Sets: (All)
Aliases: AuthorizationRuleName

Required: True
Position: 3
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Namespace
Namespace Name.

```yaml
Type: String
Parameter Sets: NamespaceAuthorizationRuleSet
Aliases: NamespaceName

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

```yaml
Type: String
Parameter Sets: EventhubAuthorizationRuleSet
Aliases: NamespaceName

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ResourceGroupName
Resource group name.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Rights
Required if 'AuthruleObj' not specified.
Rights; for example, @("Listen","Send","Manage")

```yaml
Type: String[]
Parameter Sets: NamespaceAuthorizationRuleSet, EventhubAuthorizationRuleSet
Aliases:
Accepted values: Listen, Send, Manage

Required: False
Position: 4
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

```yaml
Type: String[]
Parameter Sets: AuthoRulePropertiesSet
Aliases:
Accepted values: Listen, Send, Manage

Required: True
Position: 4
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### Microsoft.Azure.Commands.EventHub.Models.SharedAccessAuthorizationRuleAttributes

## NOTES

## RELATED LINKS


text:
using System;
using System.Diagnostics.Contracts;
using System.Drawing;

namespace TrackballScroll
{
    abstract class State
    {
        public enum CallNextHook
        {
            FALSE,
            TRUE
        }

        public class Result
        {
            public State NextState { get; }
            public CallNextHook CallNextHook { get; }
            public WinAPI.INPUT[] Input { get; }

            public Result(State nextState)
                : this(nextState, CallNextHook.TRUE, null)
            { }

            public Result(State nextState, CallNextHook callNextHook, WinAPI.INPUT[] input)
            {
                NextState = nextState;
                CallNextHook = callNextHook;
                Input = input;
            }
        }

        [Pure]
        public abstract Result Process(IntPtr wParam, WinAPI.MSLLHOOKSTRUCT llHookStruct, Properties.Settings settings);

        // Instead of handling different scaling values on multiple monitors, they both position variants are stored independantly.
        public WinAPI.POINT Origin { get; } // Origin contains original screen resolution values as reported by the event message.

        protected State(WinAPI.POINT origin)
        {
            Origin = origin;
        }

        [Pure]
        protected uint GetXButton(uint llHookStructMouseData)
        {
            return (llHookStructMouseData & 0xFFFF0000) >> 16; // see https://msdn.microsoft.com/de-de/library/windows/desktop/ms644970(v=vs.85).aspx
        }

    }

    class StateNormal : State
    {
        public StateNormal()
            : base(new WinAPI.POINT())
        { }

        [Pure]
        public override Result Process(IntPtr wParam, WinAPI.MSLLHOOKSTRUCT llHookStruct, Properties.Settings settings)
        {
            if (WinAPI.MouseMessages.WM_XBUTTONDOWN == (WinAPI.MouseMessages)wParam)
            { // NORMAL->DOWN: remember position
                var xbutton = GetXButton(llHookStruct.mouseData);
                if (!(settings.useX1 && xbutton == 1) && !(settings.useX2 && xbutton == 2))
                {
                    return new Result(this);
                }

                return new Result(new StateDown(llHookStruct.pt), CallNextHook.FALSE, null);
            }
            return new Result(this);
        }
    }

    class StateDown : State
    {
        public StateDown(WinAPI.POINT origin)
            : base(origin)
        { }

        [Pure]
        public override Result Process(IntPtr wParam, WinAPI.MSLLHOOKSTRUCT llHookStruct, Properties.Settings settings)
        {
            if (WinAPI.MouseMessages.WM_XBUTTONUP == (WinAPI.MouseMessages)wParam)
            { // DOWN->NORMAL: middle button click
                var xbutton = GetXButton(llHookStruct.mouseData);

                if (!(settings.useX1 && xbutton == 1) && !(settings.useX2 && xbutton == 2))
                {
                    return new Result(this);
                }

                if (!settings.emulateMiddleButton)
                {
                    return new Result(new StateNormal(), CallNextHook.FALSE, null);
                }

                var input = InputMiddleClick(llHookStruct.pt);
                return new Result(new StateNormal(), CallNextHook.FALSE, input);
            }
            else if (WinAPI.MouseMessages.WM_MOUSEMOVE == (WinAPI.MouseMessages)wParam)
            { // DOWN->SCROLL
                return new Result(new StateScroll(Origin, 0, 0), CallNextHook.FALSE, null);
            }
            return new Result(this);
        }

        [Pure]
        public WinAPI.INPUT[] InputMiddleClick(WinAPI.POINT pt)
        {
            WinAPI.INPUT[] input = new WinAPI.INPUT[2];
            input[0].type = WinAPI.INPUT_MOUSE;
            input[0].mi.dx = pt.x;
            input[0].mi.dy = pt.y;
            input[0].mi.mouseData = 0x0;
            input[0].mi.dwFlags = (uint)WinAPI.MouseEvent.MOUSEEVENTF_MIDDLEDOWN; // middle button down
            input[0].mi.time = 0x0;
            input[0].mi.dwExtraInfo = IntPtr.Zero;
            input[1].type = WinAPI.INPUT_MOUSE;
            input[1].mi.dx = pt.x;
            input[1].mi.dy = pt.y;
            input[1].mi.mouseData = 0x0;
            input[1].mi.dwFlags = (uint)WinAPI.MouseEvent.MOUSEEVENTF_MIDDLEUP; // middle button up
            input[1].mi.time = 0x0;
            input[1].mi.dwExtraInfo = IntPtr.Zero;
            return input;
        }
    }

    class StateScroll : State
    {
        private static readonly int X_THRESHOLD = 10;   // threshold in pixels to trigger wheel event
        private static readonly int Y_THRESHOLD = 10;   // threshold in pixels to trigger wheel event
        private static readonly uint WHEEL_FACTOR = 1; // number of wheel events. The lines scrolled per wheel event are determined by the Microsoft Windows mouse wheel settings.

        public int Xcount { get; } // accumulated horizontal movement while in state SCROLL
        public int Ycount { get; } // accumulated vertical   movement while in state SCROLL

        public StateScroll(WinAPI.POINT origin, int xcount, int ycount)
            : base(origin)
        {
            Xcount = xcount;
            Ycount = ycount;
        }

        [Pure]
        public override Result Process(IntPtr wParam, WinAPI.MSLLHOOKSTRUCT llHookStruct, Properties.Settings settings)
        {
            if (WinAPI.MouseMessages.WM_XBUTTONUP == (WinAPI.MouseMessages)wParam)
            { // SCROLL->NORMAL
                var xbutton = GetXButton(llHookStruct.mouseData);
                if (!(settings.useX1 && xbutton == 1) && !(settings.useX2 && xbutton == 2))
                {
                    return new Result(this);
                }

                return new Result(new StateNormal(), CallNextHook.FALSE, null);
            }

            WinAPI.INPUT[] input = null;

            if (WinAPI.MouseMessages.WM_MOUSEMOVE == (WinAPI.MouseMessages)wParam)
            { // SCROLL->SCROLL: wheel event
                int x = Xcount;
                int y = Ycount;

                if (Xcount < -X_THRESHOLD || Xcount > X_THRESHOLD)
                {
                    uint mouseData = (uint)((settings.reverseHorizontalScroll?-1:1) * WinAPI.WHEEL_DELTA * Xcount / X_THRESHOLD);
                    x = Xcount - (Xcount / X_THRESHOLD) * X_THRESHOLD; // integer division
                    if (settings.preferAxis)
                    {
                        y = 0;
                    }
                    input = InputWheel(llHookStruct.pt, mouseData, WinAPI.MouseEvent.MOUSEEVENTF_HWHEEL);
                }

                if (Ycount < -Y_THRESHOLD || Ycount > Y_THRESHOLD)
                {
                    uint mouseData = (uint)( (settings.reverseVerticalScroll?1:-1) * WinAPI.WHEEL_DELTA * Ycount / Y_THRESHOLD);
                    if (settings.preferAxis)
                    {
                        x = 0;
                    }
                    y = Ycount - (Ycount / Y_THRESHOLD) * Y_THRESHOLD; // integer division
                    input = InputWheel(llHookStruct.pt, mouseData, WinAPI.MouseEvent.MOUSEEVENTF_WHEEL);
                }

                x += llHookStruct.pt.x - Origin.x;
                y += llHookStruct.pt.y - Origin.y;

                return new Result(new StateScroll(Origin, x, y), CallNextHook.FALSE, input);
            }

            return new Result(this);
        }

        // MOUSEEVENTF_HWHEEL or MOUSEEVENTF_WHEEL
        [Pure]
        private WinAPI.INPUT[] InputWheel(WinAPI.POINT pt, uint mouseData, WinAPI.MouseEvent wheel_type)
        {
            var input = new WinAPI.INPUT[WHEEL_FACTOR];
            for (uint i = 0; i < WHEEL_FACTOR; ++i)
            {
                input[i].type = WinAPI.INPUT_MOUSE;
                input[i].mi.dx = pt.x;
                input[i].mi.dy = pt.y;
                input[i].mi.mouseData = mouseData;
                input[i].mi.dwFlags = (uint)wheel_type;
                input[i].mi.time = 0x0;
                input[i].mi.dwExtraInfo = IntPtr.Zero;
            }
            return input;
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/css/metro-bootstrap.min.css">
    <link rel="stylesheet" href="/css/metro-bootstrap-responsive.min.css">
    <link rel="stylesheet" href="/css/iconFont.min.css">

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />

1

2

3

4

5

6

7

8

9

10

11

12

span3

span3

span3

span3

span2

span2

span2

span2

span2

span2

span6

span6

span12


text:
import {AfterViewInit, Component, ElementRef, HostListener, Input, OnChanges, SimpleChanges, ViewChild} from '@angular/core';

import {MemoryProfileProtoOrNull} from 'org_xprof/frontend/app/common/interfaces/data_table';
import {MemoryProfileSnapshot} from 'org_xprof/frontend/app/common/interfaces/data_table';

const MAX_CHART_WIDTH = 1500;

/** A Memory Timeline Graph view component. */
@Component({
  selector: 'memory-timeline-graph',
  templateUrl: './memory_timeline_graph.ng.html',
  styleUrls: ['./memory_timeline_graph.scss']
})
export class MemoryTimelineGraph implements AfterViewInit, OnChanges {
  /** The memory profile data. */
  @Input() memoryProfileProtoOrNull: MemoryProfileProtoOrNull = null;

  /** The selected memory ID to show memory profile for. */
  @Input() memoryId: string = '';

  @ViewChild('chart', {static: false}) chartRef!: ElementRef;

  title = 'Memory Timeline Graph';
  height = 465;
  width = 0;
  chart: google.visualization.AreaChart|null = null;

  ngAfterViewInit() {
    this.loadGoogleChart();
  }

  ngOnChanges(changes: SimpleChanges) {
    setTimeout(() => {
      this.width = 0;
      this.drawChart();
    }, 100);
  }

  @HostListener('window:resize')
  onResize() {
    this.drawChart();
  }

  drawChart() {
    if (!this.chartRef || !this.chart || this.memoryId === '' ||
        !this.memoryProfileProtoOrNull ||
        !this.memoryProfileProtoOrNull.memoryProfilePerAllocator) {
      return;
    }

    this.width =
        Math.min(MAX_CHART_WIDTH, this.chartRef.nativeElement.offsetWidth);

    let snapshots =
        this.memoryProfileProtoOrNull.memoryProfilePerAllocator[this.memoryId]
            .memoryProfileSnapshots;
    // If version is set to 1, this means the backend is using the new snapshot
    // sampling algorithm, timeline data is stored in sampledTimelineSnapshots.
    if (this.memoryProfileProtoOrNull.version === 1) {
      snapshots =
          this.memoryProfileProtoOrNull.memoryProfilePerAllocator[this.memoryId]
              .sampledTimelineSnapshots;
    }

    if (!snapshots) return;
    snapshots.sort((a, b) => Number(a.timeOffsetPs) - Number(b.timeOffsetPs));

    // CPU allocator does not provide the free memory bytes stats, in this case,
    // do not display the free memory line in timeline graph.
    let hasFreeMemoryData = false;
    for (let i = 0; i < snapshots.length; i++) {
      const stats = snapshots[i].aggregationStats;
      if (stats && stats.freeMemoryBytes !== '0') {
        hasFreeMemoryData = true;
        break;
      }
    }

    const dataTable = new google.visualization.DataTable();
    dataTable.addColumn('number', 'timestamp(ps)');
    dataTable.addColumn('number', 'stack');
    dataTable.addColumn('number', 'heap');
    dataTable.addColumn({type: 'string', role: 'tooltip'});
    if (hasFreeMemoryData) {
      dataTable.addColumn('number', 'free');
    }
    dataTable.addColumn('number', 'fragmentation');

    for (let i = 0; i < snapshots.length; i++) {
      const stats = snapshots[i].aggregationStats;
      if (!stats || !snapshots[i].timeOffsetPs) {
        continue;
      }
      const row = [
        this.picoToMilli(snapshots[i].timeOffsetPs),
        this.bytesToGiBs(stats.stackReservedBytes),
        this.bytesToGiBs(stats.heapAllocatedBytes),
        this.getMetadataTooltip(snapshots[i])
      ];
      if (hasFreeMemoryData) {
        row.push(this.bytesToGiBs(stats.freeMemoryBytes));
      }
      row.push((stats.fragmentation || 0) * 100);
      dataTable.addRow(row);
    }

    const fragmentationProperty = {
      'targetAxisIndex': 1,  // Using string parameter to prevent renaming.
      type: 'line',
      lineDashStyle: [4, 4],
    };
    const lineProperty = {'targetAxisIndex': 0};
    const seriesWithFreeMemory = {
      0: lineProperty,
      1: lineProperty,
      2: lineProperty,
      3: fragmentationProperty,
    };
    const seriesWithoutFreeMemory = {
      0: lineProperty,
      1: lineProperty,
      2: fragmentationProperty,
    };

    const options = {
      curveType: 'none',
      chartArea: {left: 60, right: 60, width: '100%'},
      hAxis: {
        title: 'Timestamp (ms)',
        textStyle: {bold: true},
      },
      vAxes: {
        0: {
          title: 'Memory Usage (GiBs)',
          minValue: 0,
          textStyle: {bold: true},
        },
        1: {
          title: 'Fragmentation (%)',
          minValue: 0,
          maxValue: 100,
          textStyle: {bold: true},
        },
      },
      series: hasFreeMemoryData ? seriesWithFreeMemory :
                                  seriesWithoutFreeMemory,
      // tslint:disable-next-line:no-any
      legend: {position: 'top' as any},
      tooltip: {
        trigger: 'selection',
      },
      colors: ['red', 'orange', 'green'],
      height: this.height,
      isStacked: true,
      explorer: {
        actions: ['dragToZoom', 'rightClickToReset'],
        maxZoomIn: .001,
        maxZoomOut: 10,
      },
    };
    this.chart.draw(
        dataTable, options as google.visualization.AreaChartOptions);
  }

  bytesToGiBs(stat: string|number|undefined) {
    if (!stat) return 0;
    return Number(stat) / Math.pow(2, 30);
  }

  picoToMilli(timePs: string|undefined) {
    if (!timePs) return 0;
    return Number(timePs) / Math.pow(10, 9);
  }

  getMetadataTooltip(snapshot: MemoryProfileSnapshot|undefined) {
    if (!snapshot) return '';
    const timestampMs = this.picoToMilli(snapshot.timeOffsetPs);
    const stats = snapshot.aggregationStats;
    const metadata = snapshot.activityMetadata;
    if (!stats || !metadata || !metadata.requestedBytes ||
        !metadata.allocationBytes || !metadata.memoryActivity) {
      return '';
    }
    let requestedSizeGib = this.bytesToGiBs(metadata.requestedBytes);
    let allocationSizeGib = this.bytesToGiBs(metadata.allocationBytes);
    if (metadata.memoryActivity === 'DEALLOCATION') {
      requestedSizeGib = -requestedSizeGib;
      allocationSizeGib = -allocationSizeGib;
    }
    const memInUseGib = this.bytesToGiBs(
                                Number(stats.stackReservedBytes) +
                                Number(stats.heapAllocatedBytes))
                            .toFixed(4);
    let metadataTooltip = 'timestamp(ms): ' + timestampMs.toFixed(1);
    metadataTooltip += '\nevent: ' + metadata.memoryActivity.toLowerCase();
    if (Number(metadata.requestedBytes) > 0) {
      metadataTooltip +=
          '\nrequested_size(GiBs): ' + requestedSizeGib.toFixed(4);
    }
    metadataTooltip +=
        '\nallocation_size(GiBs): ' + allocationSizeGib.toFixed(4);
    if (metadata.tfOpName) {
      metadataTooltip += '\ntf_op: ' + metadata.tfOpName;
    }
    if (metadata.stepId) {
      metadataTooltip += '\nstep_id: ' + metadata.stepId;
    }
    if (metadata.regionType) {
      metadataTooltip += '\nregion_type: ' + metadata.regionType;
    }
    if (metadata.dataType && metadata.dataType !== 'INVALID') {
      metadataTooltip += '\ndata_type: ' + metadata.dataType;
    }
    if (metadata.tensorShape) {
      metadataTooltip += '\ntensor_shape: ' + metadata.tensorShape;
    }
    metadataTooltip += '\n\nmemory_in_use(GiBs): ' + memInUseGib;
    return metadataTooltip;
  }

  loadGoogleChart() {
    if (!google || !google.charts) {
      setTimeout(() => {
        this.loadGoogleChart();
      }, 100);
    }

    google.charts.safeLoad({'packages': ['corechart']});
    google.charts.setOnLoadCallback(() => {
      this.chart =
          new google.visualization.AreaChart(this.chartRef.nativeElement);
      this.drawChart();
    });
  }
}


text:
Entities:
 - shoe: brand, model, price
 - customer: full name, email, password
 - order: code, date, address

Relations:
 - A customer may place many orders, but one order belongs to one customer only.
 - An order may include multiple shoes, and one shoe may be present in several orders. Attributes: size and color

E-R diagram:

    Customer              Order                Shoe
    ===========   ---<   =========   >-----<   =======
     full name            code        size      brand
     email                date        color     model
     password             address     units     price

Tables:
 - Shoe: brand, model, price
 - Customer: full_name, email, password
 - Order: code, date, address
 - Item: size, color, units

Keys:
 - Shoe: *brand, *model, price
 - Customer: full_name, *email, password
 - Order: *code, date, address, ~customer_email
 - Item: *size, *color, units, *~shoe_brand, *~shoe_model, *~order_code

Relational diagram:

    Customer             Order                     Item                   Shoe
    ===========   ---<   ================   ---<   =============   >---   =======
     full_name           *code                     *size                  *brand
    *email                date                     *color                 *model
     password             address                   units                  price
                         ~customer_email           *~shoe_brand
                                                   *~shoe_model
                                                   *~order_code

%%sql
    SELECT brand, model, price
    FROM shoe
    ORDER BY price ASC
    LIMIT 1

%%sql
    SELECT brand, COUNT(*)
    FROM shoe
    GROUP BY brand

%%sql
    SELECT SUM(units)
    FROM "order"
    JOIN item
      ON "order".code = item.order_code
    WHERE code = 4521

%%sql
    SELECT brand, COUNT(*)
    FROM shoe
    JOIN item
      ON item.shoe_brand = shoe.brand AND item.shoe_model = shoe.model
    GROUP BY shoe.brand

%%sql
    SELECT brand, model, COUNT(*)
    FROM shoe
    JOIN item
      ON item.shoe_brand = shoe.brand AND item.shoe_model = shoe.model
    GROUP BY shoe.brand, shoe.model

%%sql
    SELECT address
    FROM "order"
    JOIN customer
      ON customer.email = "order".customer_email
    WHERE customer.full_name = 'Joan Clarke'
    ORDER BY "order".date DESC
    LIMIT 3

%%sql
    SELECT shoe.brand, shoe.model, item.color, item.size
    FROM customer
    JOIN "order"
      ON customer.email = "order".customer_email
    JOIN item
      ON "order".code = item.order_code
    JOIN shoe
      ON shoe.brand = item.shoe_brand AND shoe.model = item.shoe_model
    WHERE customer.full_name = 'Grace Hopper'

%%sql
    SELECT SUM(shoe.price) AS amount
    FROM customer
    JOIN "order"
      ON customer.email = "order".customer_email
    JOIN item
      ON "order".code = item.order_code
    JOIN shoe
      ON shoe.brand = item.shoe_brand AND shoe.model = item.shoe_model
    WHERE customer.full_name = 'Grace Hopper'

    SELECT id
    FROM galaxy
    WHERE flux_g != NULL

    SELECT id
    FROM galaxy
    WHERE flux_g != NULL
      AND flux_r != NULL
      AND flux_i != NULL
      AND flux_z != NULL
      AND flux_y != NULL

    !!!

    Galaxy          Measure
    ======   ---<   ============
    *id             *~galaxy_id
     ra             *band
     dec             flux

    SELECT galaxy_id
    FROM measure
    WHERE band = 'g'

    SELECT galaxy_id
    FROM measure
    GROUP BY galaxy_id
    HAVING COUNT(flux) = 3

    SELECT galaxy_id
    FROM measure
    GROUP BY galaxy_id
    HAVING COUNT(flux) >= 3