text:
import {
  ddescribe,
  describe,
  xdescribe,
  it,
  iit,
  xit,
  expect,
  beforeEach,
  afterEach,
  AsyncTestCompleter,
  inject,
  beforeEachBindings
} from 'angular2/test_lib';

import {CONST_EXPR, stringify, isType, Type, isBlank} from 'angular2/src/core/facade/lang';
import {PromiseWrapper, Promise} from 'angular2/src/core/facade/async';
import {TemplateParser} from 'angular2/src/compiler/template_parser';
import {
  CommandVisitor,
  TextCmd,
  NgContentCmd,
  BeginElementCmd,
  BeginComponentCmd,
  EmbeddedTemplateCmd,
  TemplateCmd,
  visitAllCommands,
  CompiledTemplate
} from 'angular2/src/core/compiler/template_commands';
import {CommandCompiler} from 'angular2/src/compiler/command_compiler';
import {
  NormalizedDirectiveMetadata,
  TypeMetadata,
  NormalizedTemplateMetadata
} from 'angular2/src/compiler/directive_metadata';
import {SourceModule, SourceExpression, moduleRef} from 'angular2/src/compiler/source_module';
import {ViewEncapsulation} from 'angular2/src/core/render/api';
import {evalModule} from './eval_module';
import {
  escapeSingleQuoteString,
  codeGenValueFn,
  codeGenExportVariable
} from 'angular2/src/compiler/util';
import {TEST_BINDINGS} from './test_bindings';

const BEGIN_ELEMENT = 'BEGIN_ELEMENT';
const END_ELEMENT = 'END_ELEMENT';
const BEGIN_COMPONENT = 'BEGIN_COMPONENT';
const END_COMPONENT = 'END_COMPONENT';
const TEXT = 'TEXT';
const NG_CONTENT = 'NG_CONTENT';
const EMBEDDED_TEMPLATE = 'EMBEDDED_TEMPLATE';

// Attention: These module names have to correspond to real modules!
const THIS_MODULE_NAME = 'angular2/test/compiler/command_compiler_spec';
var THIS_MODULE_REF = moduleRef(THIS_MODULE_NAME);
var TEMPLATE_COMMANDS_MODULE_REF = moduleRef('angular2/src/core/compiler/template_commands');

// Attention: read by eval!
export class RootComp {}
export class SomeDir {}
export class AComp {}

var RootCompTypeMeta =
    new TypeMetadata({id: 1, name: 'RootComp', runtime: RootComp, moduleId: THIS_MODULE_NAME});
var SomeDirTypeMeta =
    new TypeMetadata({id: 2, name: 'SomeDir', runtime: SomeDir, moduleId: THIS_MODULE_NAME});
var ACompTypeMeta =
    new TypeMetadata({id: 3, name: 'AComp', runtime: AComp, moduleId: THIS_MODULE_NAME});

var NESTED_COMPONENT = new CompiledTemplate(45, () => []);

export function main() {
  describe('CommandCompiler', () => {
    beforeEachBindings(() => TEST_BINDINGS);

    var parser: TemplateParser;
    var commandCompiler: CommandCompiler;
    var componentTemplateFactory: Function;

    beforeEach(inject([TemplateParser, CommandCompiler], (_templateParser, _commandCompiler) => {
      parser = _templateParser;
      commandCompiler = _commandCompiler;
    }));

    function createComp({type, selector, template, encapsulation, ngContentSelectors}: {
      type?: TypeMetadata,
      selector?: string,
      template?: string,
      encapsulation?: ViewEncapsulation,
      ngContentSelectors?: string[]
    }): NormalizedDirectiveMetadata {
      if (isBlank(encapsulation)) {
        encapsulation = ViewEncapsulation.None;
      }
      if (isBlank(selector)) {
        selector = 'root';
      }
      if (isBlank(ngContentSelectors)) {
        ngContentSelectors = [];
      }
      if (isBlank(template)) {
        template = '';
      }
      return new NormalizedDirectiveMetadata({
        selector: selector,
        isComponent: true,
        type: type,
        template: new NormalizedTemplateMetadata({
          template: template,
          ngContentSelectors: ngContentSelectors,
          encapsulation: encapsulation
        })
      });
    }

    function createDirective(type: TypeMetadata, selector: string): NormalizedDirectiveMetadata {
      return new NormalizedDirectiveMetadata({selector: selector, isComponent: false, type: type});
    }

    function createTests(run: Function) {
      describe('text', () => {

        it('should create unbound text commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: 'a'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([[TEXT, 'a', false, null]]);
                   async.done();
                 });
           }));

        it('should create bound text commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: '{{a}}'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([[TEXT, null, true, null]]);
                   async.done();
                 });
           }));

      });

      describe('elements', () => {

        it('should create unbound element commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: '
'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([
                     [BEGIN_ELEMENT, 'div', ['a', 'b'], [], [], [], false, null],
                     [END_ELEMENT]
                   ]);
                   async.done();
                 });
           }));

        it('should create bound element commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: '
'
             });
             var dir = createDirective(SomeDirTypeMeta, '[a]');
             run(rootComp, [dir])
                 .then((data) => {
                   expect(data).toEqual([
                     [
                       BEGIN_ELEMENT,
                       'div',
                       ['a', 'b'],
                       ['click'],
                       ['someVar', 'someValue'],
                       ['SomeDirType'],
                       true,
                       null
                     ],
                     [END_ELEMENT]
                   ]);
                   async.done();
                 });
           }));

        it('should emulate style encapsulation', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: '
',
               encapsulation: ViewEncapsulation.Emulated
             });
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([
                     [BEGIN_ELEMENT, 'div', ['_ngcontent-1', ''], [], [], [], false, null],
                     [END_ELEMENT]
                   ]);
                   async.done();
                 });
           }));

        it('should create nested nodes', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: '
a
'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([
                     [BEGIN_ELEMENT, 'div', [], [], [], [], false, null],
                     [TEXT, 'a', false, null],
                     [END_ELEMENT]
                   ]);
                   async.done();
                 });
           }));
      });

      describe('components', () => {

        it('should create component commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: ''
             });
             var comp = createComp({type: ACompTypeMeta, selector: 'a'});
             run(rootComp, [comp])
                 .then((data) => {
                   expect(data).toEqual([
                     [
                       BEGIN_COMPONENT,
                       'a',
                       ['a', 'b'],
                       ['click'],
                       ['someVar', 'someValue'],
                       ['ACompType'],
                       false,
                       null,
                       3
                     ],
                     [END_COMPONENT]
                   ]);
                   async.done();
                 });
           }));

        it('should emulate style encapsulation on host elements',
           inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: '',
               encapsulation: ViewEncapsulation.Emulated
             });
             var comp = createComp(
                 {type: ACompTypeMeta, selector: 'a', encapsulation: ViewEncapsulation.Emulated});
             run(rootComp, [comp])
                 .then((data) => {
                   expect(data).toEqual([
                     [
                       BEGIN_COMPONENT,
                       'a',
                       ['_nghost-3', '', '_ngcontent-1', ''],
                       [],
                       [],
                       ['ACompType'],
                       false,
                       null,
                       3
                     ],
                     [END_COMPONENT]
                   ]);
                   async.done();
                 });
           }));

        it('should set nativeShadow flag', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: ''});
             var comp = createComp(
                 {type: ACompTypeMeta, selector: 'a', encapsulation: ViewEncapsulation.Native});
             run(rootComp, [comp])
                 .then((data) => {
                   expect(data).toEqual([
                     [BEGIN_COMPONENT, 'a', [], [], [], ['ACompType'], true, null, 3],
                     [END_COMPONENT]
                   ]);
                   async.done();
                 });
           }));

        it('should create nested nodes and set ngContentIndex',
           inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({type: RootCompTypeMeta, template: 't'});
             var comp = createComp({type: ACompTypeMeta, selector: 'a', ngContentSelectors: ['*']});
             run(rootComp, [comp])
                 .then((data) => {
                   expect(data).toEqual([
                     [BEGIN_COMPONENT, 'a', [], [], [], ['ACompType'], false, null, 3],
                     [TEXT, 't', false, 0],
                     [END_COMPONENT]
                   ]);
                   async.done();
                 });
           }));
      });

      describe('embedded templates', () => {
        it('should create embedded template commands', inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: '<template a="b" #some-var="someValue"></template>'
             });
             var dir = createDirective(SomeDirTypeMeta, '[a]');
             run(rootComp, [dir])
                 .then((data) => {
                   expect(data).toEqual([
                     [
                       EMBEDDED_TEMPLATE,
                       ['a', 'b'],
                       ['someVar', 'someValue'],
                       ['SomeDirType'],
                       false,
                       null,
                       []
                     ]
                   ]);
                   async.done();
                 });
           }));

        it('should created nested nodes', inject([AsyncTestCompleter], (async) => {
             var rootComp =
                 createComp({type: RootCompTypeMeta, template: '<template>t</template>'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual(
                       [[EMBEDDED_TEMPLATE, [], [], [], false, null, [[TEXT, 't', false, null]]]]);
                   async.done();
                 });
           }));

        it('should calculate wether the template is merged based on nested ng-content elements',
           inject([AsyncTestCompleter], (async) => {
             var rootComp = createComp({
               type: RootCompTypeMeta,
               template: '<template><ng-content></ng-content></template>'
             });
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual(
                       [[EMBEDDED_TEMPLATE, [], [], [], true, null, [[NG_CONTENT, null]]]]);
                   async.done();
                 });
           }));

      });

      describe('ngContent', () => {
        it('should create ng-content commands', inject([AsyncTestCompleter], (async) => {
             var rootComp =
                 createComp({type: RootCompTypeMeta, template: '<ng-content></ng-content>'});
             run(rootComp, [])
                 .then((data) => {
                   expect(data).toEqual([[NG_CONTENT, null]]);
                   async.done();
                 });
           }));
      });
    }

    describe('compileComponentRuntime', () => {
      beforeEach(() => {
        componentTemplateFactory = (directive: NormalizedDirectiveMetadata) => {
          return new CompiledTemplate(directive.type.id, () => []);
        };
      });

      function run(component: NormalizedDirectiveMetadata,
                   directives: NormalizedDirectiveMetadata[]): Promise<any[][]> {
        var parsedTemplate =
            parser.parse(component.template.template, directives, component.type.name);
        var commands = commandCompiler.compileComponentRuntime(component, parsedTemplate,
                                                               componentTemplateFactory);
        return PromiseWrapper.resolve(humanize(commands));
      }

      createTests(run);
    });

    describe('compileComponentCodeGen', () => {
      beforeEach(() => {
        componentTemplateFactory = (directive: NormalizedDirectiveMetadata) => {
          return `new ${TEMPLATE_COMMANDS_MODULE_REF}CompiledTemplate(${directive.type.id}, ${codeGenValueFn([], '{}')})`;
        };
      });

      function run(component: NormalizedDirectiveMetadata,
                   directives: NormalizedDirectiveMetadata[]): Promise<any[][]> {
        var parsedTemplate =
            parser.parse(component.template.template, directives, component.type.name);
        var sourceModule = commandCompiler.compileComponentCodeGen(component, parsedTemplate,
                                                                   componentTemplateFactory);
        var testableModule = createTestableModule(sourceModule).getSourceWithImports();
        return evalModule(testableModule.source, testableModule.imports, null);
      }

      createTests(run);
    });

  });
}

// Attention: read by eval!
export function humanize(cmds: TemplateCmd[]): any[][] {
  var visitor = new CommandHumanizer();
  visitAllCommands(visitor, cmds);
  return visitor.result;
}

function checkAndStringifyType(type: Type): string {
  expect(isType(type)).toBe(true);
  return `${stringify(type)}Type`;
}

class CommandHumanizer implements CommandVisitor {
  result: any[][] = [];
  visitText(cmd: TextCmd, context: any): any {
    this.result.push([TEXT, cmd.value, cmd.isBound, cmd.ngContentIndex]);
    return null;
  }
  visitNgContent(cmd: NgContentCmd, context: any): any {
    this.result.push([NG_CONTENT, cmd.ngContentIndex]);
    return null;
  }
  visitBeginElement(cmd: BeginElementCmd, context: any): any {
    this.result.push([
      BEGIN_ELEMENT,
      cmd.name,
      cmd.attrNameAndValues,
      cmd.eventNames,
      cmd.variableNameAndValues,
      cmd.directives.map(checkAndStringifyType),
      cmd.isBound,
      cmd.ngContentIndex
    ]);
    return null;
  }
  visitEndElement(context: any): any {
    this.result.push([END_ELEMENT]);
    return null;
  }
  visitBeginComponent(cmd: BeginComponentCmd, context: any): any {
    this.result.push([
      BEGIN_COMPONENT,
      cmd.name,
      cmd.attrNameAndValues,
      cmd.eventNames,
      cmd.variableNameAndValues,
      cmd.directives.map(checkAndStringifyType),
      cmd.nativeShadow,
      cmd.ngContentIndex,
      // TODO humanizeTemplate(cmd.template)
      cmd.template.id
    ]);
    return null;
  }
  visitEndComponent(context: any): any {
    this.result.push([END_COMPONENT]);
    return null;
  }
  visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any {
    this.result.push([
      EMBEDDED_TEMPLATE,
      cmd.attrNameAndValues,
      cmd.variableNameAndValues,
      cmd.directives.map(checkAndStringifyType),
      cmd.isMerged,
      cmd.ngContentIndex,
      humanize(cmd.children)
    ]);
    return null;
  }
}

function createTestableModule(source: SourceExpression): SourceModule {
  var resultExpression = `${THIS_MODULE_REF}humanize(${source.expression})`;
  var testableSource = `${source.declarations.join('\n')}
  ${codeGenExportVariable('run')}${codeGenValueFn(['_'], resultExpression)};`;
  return new SourceModule(null, testableSource);
}


text:
void MakeChain(const char *prefix){
  gSystem->Exec(Form("find %s |grep calibTree | grep root > calib.list",prefix));
  AliXRDPROOFtoolkit::FilterList("calib.list","* dcs",1);
  AliXRDPROOFtoolkit toolkit;
  TChain * chain = toolkit.MakeChain("calib.list.Good","dcs",0,2000);
  chain->Lookup();
  TTree * tree = chain->CopyTree("1");
  TFile f("calibTimeSummary.root","recreate");
  tree->Write("dcs");
  f.Close();
}

redpajama_set_name: RedPajamaGithub


text:
function configure(module) {
  "use strict";
  /*global MessageChannel,XMLHttpRequest*/
  module.description = 'This module implements what web browsers and workers have in common.';
  module.requires = {
    loose: 'Std.Management.Loose'
  };
  module.test = () => typeof MessageChannel !== 'undefined' &&
    typeof XMLHttpRequest !== 'undefined';
  module.provides = {
    'Std.HTTP.Client with Std.HTTP.WebClient': (Provider, required) =>
      Provider.spawn(required.loose)
  };
}


text:
/*************************************************************************/
/*  audio_server.h                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef AUDIO_SERVER_H
#define AUDIO_SERVER_H

#include "core/math/audio_frame.h"
#include "core/object.h"
#include "core/os/os.h"
#include "core/variant.h"
#include "servers/audio/audio_effect.h"

class AudioDriverDummy;
class AudioStream;
class AudioStreamSample;

class AudioDriver {
	static AudioDriver *singleton;
	uint64_t _last_mix_time;
	uint64_t _last_mix_frames;

#ifdef DEBUG_ENABLED
	uint64_t prof_ticks;
	uint64_t prof_time;
#endif

protected:
	Vector<int32_t> input_buffer;
	unsigned int input_position;
	unsigned int input_size;

	void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true);
	void update_mix_time(int p_frames);
	void input_buffer_init(int driver_buffer_frames);
	void input_buffer_write(int32_t sample);

#ifdef DEBUG_ENABLED
	_FORCE_INLINE_ void start_counting_ticks() { prof_ticks = OS::get_singleton()->get_ticks_usec(); }
	_FORCE_INLINE_ void stop_counting_ticks() { prof_time += OS::get_singleton()->get_ticks_usec() - prof_ticks; }
#else
	_FORCE_INLINE_ void start_counting_ticks() {}
	_FORCE_INLINE_ void stop_counting_ticks() {}
#endif

public:
	double get_time_since_last_mix(); //useful for video -> audio sync
	double get_time_to_next_mix();

	enum SpeakerMode {
		SPEAKER_MODE_STEREO,
		SPEAKER_SURROUND_31,
		SPEAKER_SURROUND_51,
		SPEAKER_SURROUND_71,
	};

	static AudioDriver *get_singleton();
	void set_singleton();

	virtual const char *get_name() const = 0;

	virtual Error init() = 0;
	virtual void start() = 0;
	virtual int get_mix_rate() const = 0;
	virtual SpeakerMode get_speaker_mode() const = 0;
	virtual Array get_device_list();
	virtual String get_device();
	virtual void set_device(String device) {}
	virtual void lock() = 0;
	virtual void unlock() = 0;
	virtual void finish() = 0;

	virtual Error capture_start() { return FAILED; }
	virtual Error capture_stop() { return FAILED; }
	virtual void capture_set_device(const String &p_name) {}
	virtual String capture_get_device() { return "Default"; }
	virtual Array capture_get_device_list(); // TODO: convert this and get_device_list to PoolStringArray

	virtual float get_latency() { return 0; }

	SpeakerMode get_speaker_mode_by_total_channels(int p_channels) const;
	int get_total_channels_by_speaker_mode(SpeakerMode) const;

	Vector<int32_t> get_input_buffer() { return input_buffer; }
	unsigned int get_input_position() { return input_position; }
	unsigned int get_input_size() { return input_size; }

#ifdef DEBUG_ENABLED
	uint64_t get_profiling_time() const { return prof_time; }
	void reset_profiling_time() { prof_time = 0; }
#endif

	AudioDriver();
	virtual ~AudioDriver() {}
};

class AudioDriverManager {
	enum {

		MAX_DRIVERS = 10
	};

	static const int DEFAULT_MIX_RATE = 44100;
	static const int DEFAULT_OUTPUT_LATENCY = 15;

	static AudioDriver *drivers[MAX_DRIVERS];
	static int driver_count;

	static AudioDriverDummy dummy_driver;

public:
	static void add_driver(AudioDriver *p_driver);
	static void initialize(int p_driver);
	static int get_driver_count();
	static AudioDriver *get_driver(int p_driver);
};

class AudioBusLayout;

class AudioServer : public Object {
	GDCLASS(AudioServer, Object);

public:
	//re-expose this here, as AudioDriver is not exposed to script
	enum SpeakerMode {
		SPEAKER_MODE_STEREO,
		SPEAKER_SURROUND_31,
		SPEAKER_SURROUND_51,
		SPEAKER_SURROUND_71,
	};

	enum {
		AUDIO_DATA_INVALID_ID = -1
	};

	typedef void (*AudioCallback)(void *p_userdata);

private:
	uint64_t mix_time;
	int mix_size;

	uint32_t buffer_size;
	uint64_t mix_count;
	uint64_t mix_frames;
#ifdef DEBUG_ENABLED
	uint64_t prof_time;
#endif

	float channel_disable_threshold_db;
	uint32_t channel_disable_frames;

	int channel_count;
	int to_mix;

	float global_rate_scale;

	struct Bus {
		StringName name;
		bool solo;
		bool mute;
		bool bypass;

		bool soloed;

		//Each channel is a stereo pair.
		struct Channel {
			bool used;
			bool active;
			AudioFrame peak_volume;
			Vector<AudioFrame> buffer;
			Vector<Ref<AudioEffectInstance>> effect_instances;
			uint64_t last_mix_with_audio;
			Channel() {
				last_mix_with_audio = 0;
				used = false;
				active = false;
				peak_volume = AudioFrame(AUDIO_MIN_PEAK_DB, AUDIO_MIN_PEAK_DB);
			}
		};

		Vector<Channel> channels;

		struct Effect {
			Ref<AudioEffect> effect;
			bool enabled;
#ifdef DEBUG_ENABLED
			uint64_t prof_time;
#endif
		};

		Vector<Effect> effects;
		float volume_db;
		StringName send;
		int index_cache;
	};

	Vector<Vector<AudioFrame>> temp_buffer; //temp_buffer for each level
	Vector<Bus *> buses;
	Map<StringName, Bus *> bus_map;

	void _update_bus_effects(int p_bus);

	static AudioServer *singleton;

	// TODO create an audiodata pool to optimize memory

	Map<void *, uint32_t> audio_data;
	size_t audio_data_total_mem;
	size_t audio_data_max_mem;

	Mutex audio_data_lock;

	void init_channels_and_buffers();

	void _mix_step();

	struct CallbackItem {
		AudioCallback callback;
		void *userdata;

		bool operator<(const CallbackItem &p_item) const {
			return (callback == p_item.callback ? userdata < p_item.userdata : callback < p_item.callback);
		}
	};

	Set<CallbackItem> callbacks;
	Set<CallbackItem> update_callbacks;

	friend class AudioDriver;
	void _driver_process(int p_frames, int32_t *p_buffer);

protected:
	static void _bind_methods();

public:
	_FORCE_INLINE_ int get_channel_count() const {
		switch (get_speaker_mode()) {
			case SPEAKER_MODE_STEREO:
				return 1;
			case SPEAKER_SURROUND_31:
				return 2;
			case SPEAKER_SURROUND_51:
				return 3;
			case SPEAKER_SURROUND_71:
				return 4;
		}
		ERR_FAIL_V(1);
	}

	//do not use from outside audio thread
	bool thread_has_channel_mix_buffer(int p_bus, int p_buffer) const;
	AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
	int thread_get_mix_buffer_size() const;
	int thread_find_bus_index(const StringName &p_name);

	void set_bus_count(int p_count);
	int get_bus_count() const;

	void remove_bus(int p_index);
	void add_bus(int p_at_pos = -1);

	void move_bus(int p_bus, int p_to_pos);

	void set_bus_name(int p_bus, const String &p_name);
	String get_bus_name(int p_bus) const;
	int get_bus_index(const StringName &p_bus_name) const;

	int get_bus_channels(int p_bus) const;

	void set_bus_volume_db(int p_bus, float p_volume_db);
	float get_bus_volume_db(int p_bus) const;

	void set_bus_send(int p_bus, const StringName &p_send);
	StringName get_bus_send(int p_bus) const;

	void set_bus_solo(int p_bus, bool p_enable);
	bool is_bus_solo(int p_bus) const;

	void set_bus_mute(int p_bus, bool p_enable);
	bool is_bus_mute(int p_bus) const;

	void set_bus_bypass_effects(int p_bus, bool p_enable);
	bool is_bus_bypassing_effects(int p_bus) const;

	void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
	void remove_bus_effect(int p_bus, int p_effect);

	int get_bus_effect_count(int p_bus);
	Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
	Ref<AudioEffectInstance> get_bus_effect_instance(int p_bus, int p_effect, int p_channel = 0);

	void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);

	void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
	bool is_bus_effect_enabled(int p_bus, int p_effect) const;

	float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
	float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;

	bool is_bus_channel_active(int p_bus, int p_channel) const;

	void set_global_rate_scale(float p_scale);
	float get_global_rate_scale() const;

	virtual void init();
	virtual void finish();
	virtual void update();
	virtual void load_default_bus_layout();

	/* MISC config */

	virtual void lock();
	virtual void unlock();

	virtual SpeakerMode get_speaker_mode() const;
	virtual float get_mix_rate() const;

	virtual float read_output_peak_db() const;

	static AudioServer *get_singleton();

	virtual double get_output_latency() const;
	virtual double get_time_to_next_mix() const;
	virtual double get_time_since_last_mix() const;

	void *audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data = nullptr);
	void audio_data_free(void *p_data);

	size_t audio_data_get_total_memory_usage() const;
	size_t audio_data_get_max_memory_usage() const;

	void add_callback(AudioCallback p_callback, void *p_userdata);
	void remove_callback(AudioCallback p_callback, void *p_userdata);

	void add_update_callback(AudioCallback p_callback, void *p_userdata);
	void remove_update_callback(AudioCallback p_callback, void *p_userdata);

	void set_bus_layout(const Ref<AudioBusLayout> &p_bus_layout);
	Ref<AudioBusLayout> generate_bus_layout() const;

	Array get_device_list();
	String get_device();
	void set_device(String device);

	Array capture_get_device_list();
	String capture_get_device();
	void capture_set_device(const String &p_name);

	AudioServer();
	virtual ~AudioServer();
};

VARIANT_ENUM_CAST(AudioServer::SpeakerMode)

class AudioBusLayout : public Resource {
	GDCLASS(AudioBusLayout, Resource);

	friend class AudioServer;

	struct Bus {
		StringName name;
		bool solo;
		bool mute;
		bool bypass;

		struct Effect {
			Ref<AudioEffect> effect;
			bool enabled;
		};

		Vector<Effect> effects;

		float volume_db;
		StringName send;

		Bus() {
			solo = false;
			mute = false;
			bypass = false;
			volume_db = 0;
		}
	};

	Vector<Bus> buses;

protected:
	bool _set(const StringName &p_name, const Variant &p_value);
	bool _get(const StringName &p_name, Variant &r_ret) const;
	void _get_property_list(List<PropertyInfo> *p_list) const;

public:
	AudioBusLayout();
};

typedef AudioServer AS;

#endif // AUDIO_SERVER_H


text:
package com.hortonworks.streamline.streams.udf;

import com.hortonworks.streamline.streams.rule.UDF3;

/**
 * Returns the position of the first occurrence of sub string in  a string starting the search from an index.
 * <p>
 * Note: The first position in string is 1 and if substring is not found within string, the function will return 0
 * </p>
 */
public class Position2 implements UDF3<Integer, String, String, Integer> {
    @Override
    public Integer evaluate(String string, String sub, Integer fromIndex) {
        return string.indexOf(sub, fromIndex - 1) + 1;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
<!-- for some information on what you could do (e.g. targets to override). -->
<!-- If you delete this file and reopen the project it will be recreated. -->
<project name="suite_spotbugs" basedir=".">
    <description>Builds the module suite suite.</description>
    <import file="nbproject/build-impl.xml"/>

    <property name="spotbugs.home" value="${basedir}/../libs/spotbugs" />

    <path id="spotbugs.classpath">
        <fileset dir="${spotbugs.home}/lib">
            <include name="**/*.jar" />
        </fileset>
    </path>

    <taskdef name="unionBugs" classname="edu.umd.cs.findbugs.anttask.UnionBugs">
        <classpath refid="spotbugs.classpath" />
    </taskdef>

    <taskdef name="convertXmlToText" classname="edu.umd.cs.findbugs.anttask.ConvertXmlToTextTask">
        <classpath refid="spotbugs.classpath" />
    </taskdef>

    <target name="spotbugs" depends="-init">
        <!-- I define some variable -->
        <property name="output.folder" value="${basedir}/../output" />
        <property name="xml.output" value="${output.folder}/spotbugs.xml" />
        <property name="html.output" value="${output.folder}/spotbugs.html" />

        <!-- I remove the previous files-->
        <delete failonerror="false">
            <fileset dir="${output.folder}" includes="**/*"/>
        </delete>

        <mkdir dir="${output.folder}"  />

        <subant buildpath="${modules.sorted}" target="spotbugs" inheritall="false" inheritrefs="fakse" failonerror="false" />

        <unionBugs to="${xml.output}" >
            <fileset dir="${output.folder}">
                <include name="**/*_spotbugs.xml" />
            </fileset>
        </unionBugs>

        <convertXmlToText
            classpathref="spotbugs.classpath"
            input="${xml.output}"
            outputfile="${html.output}"
            format="html:fancy-hist.xsl"
        />

    </target>

</project>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/// <summary>
/// Task APM helper based on http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx
/// </summary>

// TODO: #3144 - Remove this class and rewrite tests to work directly with TPL.

namespace System.Threading.Tasks
{
    public static class TaskAPMExtensions
    {
        public static Task ToApm(this Task task, AsyncCallback callback, object state)
        {
            if (task.AsyncState == state)
            {
                if (callback != null)
                {
                    task.ContinueWith(delegate { callback(task); },
                        CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
                }
                return task;
            }

            var tcs = new TaskCompletionSource<bool>(state);
            task.ContinueWith(delegate
            {
                if (task.IsFaulted)
                {
                    tcs.TrySetException(task.Exception.InnerExceptions);
                }
                else if (task.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(false);
                }

                if (callback != null)
                {
                    callback(tcs.Task);
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
            return tcs.Task;
        }

        public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback callback, object state)
        {
            if (task.AsyncState == state)
            {
                if (callback != null)
                {
                    task.ContinueWith(delegate { callback(task); },
                        CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
                }

                return task;
            }

            var tcs = new TaskCompletionSource<TResult>(state);
            task.ContinueWith(delegate
            {
                if (task.IsFaulted)
                {
                    tcs.TrySetException(task.Exception.InnerExceptions);
                }
                else if (task.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(task.Result);
                }

                if (callback != null)
                {
                    callback(tcs.Task);
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);

            return tcs.Task;
        }
    }
}


text:
namespace Oasis
{

class Shader;
class Shader;

class OASIS_API Material : public Object
{
public:
    Material();
    ~Material();

    void ApplyToShaderVariant(Shader* variant);

    void ClearParameter(const std::string& name);
    void SetParameter(const std::string& name, const Parameter& value);

    inline void SetInt(const std::string& name, int value) { SetParameter(name, Parameter(value)); }
    inline void SetFloat(const std::string& name, float value) { SetParameter(name, Parameter(value)); }
    inline void SetVector2(const std::string& name, const Vector2& value) { SetParameter(name, Parameter(value)); }
    inline void SetVector3(const std::string& name, const Vector3& value) { SetParameter(name, Parameter(value)); }
    inline void SetVector4(const std::string& name, const Vector4& value) { SetParameter(name, Parameter(value)); }
    inline void SetMatrix3(const std::string& name, const Matrix3& value) { SetParameter(name, Parameter(value)); }
    inline void SetMatrix4(const std::string& name, const Matrix4& value) { SetParameter(name, Parameter(value)); }

    const Parameter* GetParameter(const std::string& name) const;

    Shader* GetShader() { return shader_; }
    void SetShader(Shader* shader);

    void SetKeywords(const std::string& keywords);
    const std::string& GetKeywords() const { return keywords_; }

private:
    Shader* shader_;
    std::unordered_map<std::string, Parameter> parameters_;
    std::string keywords_;
};

}


text:
var fs = require('fs');
var open = require('open');
var path = require('path');
var remote = require('electron').remote;
var BrowserWindow = remote.BrowserWindow;

var moviesList = [];
var magnetLinks = {};
var moviesYears = {};
var moviesIds = {};
var movieYear = 0;
var displayedMovies = 0;
var deletedMoviesFile = path.join(__dirname, "cache/deletedMovies.txt");
var firstMovieLoaded = false;

loadMovies("HD", true);

function loadMovies(moviesQuality, lastList) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    console.log("PB state: " + this.readyState);
    progressBarDoStep();
    if (this.readyState == this.DONE) {
      if (this.status == 200) {
        var doc = $.parseXML(xhttp.response);
        $xml = $(doc);
        $titles = $xml.find("title");
        $links = $xml.find("link");

        try {
          fs.statSync(deletedMoviesFile);
        }
        catch(err) {
          fs.writeFileSync(deletedMoviesFile, "");
        }

        var deletedMovies = fs.readFileSync(deletedMoviesFile);
        for (i = 0; i < $titles.length; i++) {
          if (i == 0) continue;
          $movieName = $titles[i].textContent.toLowerCase();

          // filter low quality movies
          if (moviesQuality == "normal") {
            if (!($movieName.includes("brrip") || $movieName.includes("hdrip") || $movieName.includes("dvdrip") || $movieName.includes("bdrip") || $movieName.includes("webrip") || $movieName.includes("blueray")))
            {
              continue;
            }
          }

          // skip french movies
          if ($movieName.includes("french")) continue;

          // skip hardcoded subtitles
          if ($movieName.includes(".hc.")) continue;
          if ($movieName.includes(" hc ")) continue;
          if ($movieName.includes("korsub")) continue;

          // skip cam
          if ($movieName.includes(".cam.")) continue;
          if ($movieName.includes(" cam ")) continue;

	  if ($movieName.includes(".hdcam.")) continue;
          if ($movieName.includes(" hdcam ")) continue;

		  // skip hdts
		  if ($movieName.includes(".hdts.")) continue;
          if ($movieName.includes(" hdts ")) continue;
          if ($movieName.includes("hd-ts")) continue;
          if ($movieName.includes("hd-tc")) continue;
		  if ($movieName.includes(".hdtc.")) continue;
		  if ($movieName.includes("hdtc")) continue;

          // leave only pure movie name
          $movieName = getMovieName($movieName);

 console.log($movieName);
        // skip empty movies
          if ($movieName == "")  continue;

          // skip deleted movies
          if (deletedMovies.indexOf($movieName) != -1) continue;

          if (!moviesList.includes($movieName)) {
            moviesList.push($movieName);
            magnetLinks[$movieName] = $links[i].textContent;
            if (movieYear > 1900 && movieYear <= new Date().getFullYear()) {
              moviesYears[$movieName] = movieYear;
            }
            else {
              moviesYears[$movieName] = "";
            }
          }
        }
        if (lastList) {
          if (moviesList.length == 0) {
            $("#progress-bar").fadeOut();
            $("#no-movies-container").fadeIn();
          }
          else {
            populateMoviesTable();
          }
        }
      }
      else {
        alert("can't contact the pirate bay :(");
        var window = BrowserWindow.getFocusedWindow();
        window.close();
      }
    }
  };
  if (moviesQuality == "HD") {
    xhttp.open("GET", "https://pirateproxy.live/rss/top100/207", true);
  }
  else if (moviesQuality == "normal") {
    xhttp.open("GET", "https://pirateproxy.live/rss/top100/201", true);
  }
  xhttp.send();
}

function progressBarDoStep() {
  var pBar = document.getElementById('progress-bar');
  pBar.value += 12.5;
}

function fillMoviePoster(movieName, id) {
  var jsonhttp = new XMLHttpRequest();
  jsonhttp.onreadystatechange = function() {
    console.log(id + "/" + (moviesList.length - 1) + "(" + movieName + ") state: " + this.readyState);
    if (this.readyState == this.DONE) {
      if (this.status == 200) {
        var movieInfo = $.parseJSON(jsonhttp.response);

        if (movieInfo["Response"] == "False") {
          console.log("***can't find movie " + movieName + "***");
          fs.appendFile(deletedMoviesFile, movieName + "\n", function (err) {
                        if (err) throw err;
                        });
          return;
        }

        var li = document.createElement("li");
        var rig_cell = document.createElement("div");
        var rig_img = document.createElement('img');
        var rig_overlay = document.createElement("span");
        var rig_text = document.createElement("span");

        moviesIds[movieName] = movieInfo["imdbID"];
        li.setAttribute("id", movieInfo["imdbID"]);
        li.style.display = "none";
        rig_cell.setAttribute("class", "rig-cell");
        rig_img.setAttribute("class", "rig-img");
        rig_overlay.setAttribute("class", "rig-overlay");
        rig_text.setAttribute("class", "rig-text");

        rig_cell.appendChild(rig_img);
        rig_cell.appendChild(rig_overlay);
        rig_cell.appendChild(rig_text);
        li.appendChild(rig_cell);
        document.getElementById("rig").appendChild(li);

        var movieInfoText = "" + movieInfo["Title"] + "

";
        movieInfoText += "Year: " + movieInfo["Year"] + "
";
        movieInfoText += "Genre: " + movieInfo["Genre"] + "
";
        movieInfoText += "Actors: " + movieInfo["Actors"] + "
";
        movieInfoText += "Rating: " + movieInfo["imdbRating"] + "

";

		plotText = movieInfo["Plot"];
		if (plotText.length > 150) {
			plotText = plotText.substring(0,150) + "...";
		}
        movieInfoText += "Plot: " + plotText;

        rig_text.innerHTML = movieInfoText;
        rig_text.addEventListener('click', function() {
          getMovieReviews(movieInfo["imdbID"], movieInfo["Title"]);
        });

        var deleteButton = document.createElement("input");
        var downloadButton = document.createElement("input");

        deleteButton.setAttribute("type", "image");
        deleteButton.src = path.join(__dirname, "img/delete.png");
        deleteButton.setAttribute("class", "delete_button");
        deleteButton.addEventListener('click', function() {
          deleteMovie(movieName);
        });

        downloadButton.setAttribute("type", "image");
        downloadButton.src = path.join(__dirname, "img/download.png");
        downloadButton.setAttribute("class", "download_button");
        downloadButton.addEventListener('click', function() {
          downloadMovie(movieName);
        });

        rig_overlay.appendChild(downloadButton);
        rig_overlay.appendChild(deleteButton);

        // set image source
        if (movieInfo['Poster'] != "N/A") {
            rig_img.src = movieInfo['Poster'];
        }
        else {
            rig_img.src = path.join(__dirname, "img/NA.jpg");
        }

        if (!firstMovieLoaded) {
          firstMovieLoaded = true;
          $("#progress-bar").fadeOut();
        }
        $("#"+movieInfo["imdbID"]).fadeIn(2000);
        displayedMovies++;
        document.getElementById("title").innerText = "Electron Movies Browser - displaying " + (displayedMovies) + " movies";
      }
      else {
        console.log("error: status for " + movieName + " is " + this.status);
      }
    }
  }
  var movieSearchString = movieName.replace(/\s/g, '+');
  movieSearchString = "http://www.omdbapi.com/?apikey=90c2bc1b&t="+movieSearchString+"&y="+moviesYears[movieName]+"&plot=short&r=json";
  jsonhttp.open("GET", movieSearchString, true);
  jsonhttp.send();
}

function getMovieName(movieString) {
  movieYear = 0;
  movieString = movieString.replace(/\./g, ' ');
  movieString = movieString.replace(/:/g, '');
  movieString = movieString.replace(/&/g, 'and');
  movieString = movieString.replace(/;/g, '');
  movieString = movieString.replace(/\//g, '');
  movieString = movieString.replace(/!/g, '');
  var re = /\d{4}/;
  var match = re.exec(movieString);
  if (match != null) {
    movieYear = match[0];
    var yearIndex = movieString.indexOf(match[0]);
    return movieString.substring(0, yearIndex-1).trim();
  }
  else {
    return movieString;
  }
}

function populateMoviesTable() {
  var moviesContainer = document.createElement("ul");
  moviesContainer.setAttribute("id", "rig");
  $("#main-section").append(moviesContainer);
  for (i = 0; i < moviesList.length; i++) {
    fillMoviePoster(moviesList[i], i);
  }
}

function deleteMovie(movieName) {
  fs.appendFile(deletedMoviesFile, movieName + "\n", function (err) {
                        if (err) throw err;
                        });
  $("#"+moviesIds[movieName]).hide('slow', function(){ $("#"+moviesIds[movieName]).remove(); });
  displayedMovies--;
  document.getElementById("title").innerText = "Electron Movies Browser - displaying " + (displayedMovies) + " movies";
}

function downloadMovie(movieName) {
  var link = magnetLinks[movieName];
  open(link);
}

function openImdb(id) {
  open("http://www.imdb.com/title/"+id+"/");
}

function getMovieReviews(movieId, movieName) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
      if (this.status == 200) {
        var reviewsPageText = xhttp.responseText;
        reviewsPageText = stripMovieReviewsGarbage(reviewsPageText);
        document.getElementById("reviews-title").innerText = movieName + " - User Reviews";

        if (reviewsPageText == "") {
          $("#no-reviews-container").fadeIn();
        }

        document.getElementById("reviews").innerHTML = reviewsPageText;
        $("#cover").fadeIn();
        $("#reviews-overlay").fadeIn();
        document.getElementById("reviews").scrollTop = 0;
      }
      else {
        alert("can't contact imdb :(");
      }
    }
  };
  xhttp.open("GET", "http://www.imdb.com/title/"+movieId+"/reviews", true);
  xhttp.send();
}

var reviewsHTML;
function stripMovieReviewsGarbage(reviewsPageText) {

  var titles = [];
  var scores = [];
  var texts = [];
  var helpfuls = [];
  var reviews = "";

  //console.log(reviewsPageText);
  reviewsHTML = reviewsPageText;
  var reviewsHTMLArray = $(reviewsHTML).find('.imdb-user-review').toArray();
  reviewsHTMLArray.forEach(function(review) {
		var reviewScore = $(review).find('.rating-other-user-rating').text().trim();
		if (reviewScore != "") {
	    var reviewTitle = $(review).find('.title').text().trim();
			var reviewText = $(review).find('.text').text().trim();
			var reviewHelpfulness = $(review).find('.actions').text().trim();
			titles.push(reviewTitle);
			scores.push(reviewScore);
			texts.push(reviewText);
			helpfuls.push(reviewHelpfulness);
		}
  });

  for (i = 0; i < titles.length; i++) {
		reviews += "
	" + titles[i] + "
 \
		" + scores[i] + "
 \
		" + texts[i] + "
 \
		" + helpfuls[i].substr(0, helpfuls[i].indexOf('.')) + "

";
  }
  return reviews;
}

// Bind delete/download/min/max/close buttons
(function () {
  function init() {
    document.getElementById("min-btn").addEventListener("click", function (e) {
      var window = BrowserWindow.getFocusedWindow();
      window.minimize();
    });

    document.getElementById("max-btn").addEventListener("click", function (e) {
      var window = BrowserWindow.getFocusedWindow();
      if (!window.isMaximized()) {
        window.maximize();
      } else {
        window.unmaximize();
      }
    });

    document.getElementById("close-btn").addEventListener("click", function (e) {
      var window = BrowserWindow.getFocusedWindow();
      window.close();
    });
  };

  document.getElementById("reviews-close-btn").addEventListener('click', function() {
    $("#no-reviews-container").fadeOut();
    $("#reviews-overlay").fadeOut();
    $("#cover").fadeOut();
  });

  document.onreadystatechange = function () {
    if (document.readyState == "complete") {
      init();
    }
  };
})();


text:
require "tmpdir" unless defined?(Dir.mktmpdir)
require_relative "../cookbook-omnifetch"
require_relative "base"
require_relative "exceptions"

module CookbookOmnifetch
  class GitLocation < BaseLocation
    attr_reader :uri
    attr_reader :branch
    attr_reader :tag
    attr_reader :ref
    attr_reader :revision
    attr_reader :rel

    def initialize(dependency, options = {})
      super

      @uri      = options[:git]
      @branch   = options[:branch]
      @tag      = options[:tag]
      @ref      = options[:ref]
      @revision = options[:revision]
      @rel      = options[:rel]

      # The revision to parse
      @rev_parse = options[:ref] || options[:branch] || options[:tag] || "main"
    end

    # @see BaseLoation#installed?
    def installed?
      (!!revision) && install_path.exist?
    end

    # Install this git cookbook into the cookbook store. This method leverages
    # a cached git copy and a scratch directory to prevent bad cookbooks from
    # making their way into the cookbook store.
    #
    # @see BaseLocation#install
    def install
      scratch_path = Pathname.new(Dir.mktmpdir)

      if cached?
        Dir.chdir(cache_path) do
          git %{fetch --force --tags #{uri} "refs/heads/*:refs/heads/*"}
        end
      else
        git %{clone #{uri} "#{cache_path}" --bare --no-hardlinks}
      end

      Dir.chdir(cache_path) do
        @revision ||= git %{rev-parse #{@rev_parse}}
      end

      # Clone into a scratch directory for validations
      git %{clone --no-checkout "#{cache_path}" "#{scratch_path}"}

      # Make sure the scratch directory is up-to-date and account for rel paths
      Dir.chdir(scratch_path) do
        git %{fetch --force --tags "#{cache_path}"}
        git %{reset --hard #{@revision}}

        if rel
          git %{filter-branch --subdirectory-filter "#{rel}" --force}
        end
      end

      # Validate the scratched path is a valid cookbook
      validate_cached!(scratch_path)

      # If we got this far, we should copy
      FileUtils.rm_rf(install_path) if install_path.exist?
      FileUtils.cp_r(scratch_path, install_path)

      # Remove the git history
      FileUtils.rm_rf(File.join(install_path, ".git"))

      install_path.chmod(0777 & ~File.umask)
    ensure
      # Ensure the scratch directory is cleaned up
      FileUtils.rm_rf(scratch_path) if scratch_path
    end

    # @see BaseLocation#cached_cookbook
    def cached_cookbook
      if installed?
        @cached_cookbook ||= CookbookOmnifetch.cached_cookbook_class.from_path(install_path)
      else
        nil
      end
    end

    def ==(other)
      other.is_a?(GitLocation) &&
        other.uri == uri &&
        other.branch == branch &&
        other.tag == tag &&
        other.shortref == shortref &&
        other.rel == rel
    end

    def to_s
      info = tag || branch || shortref || @rev_parse

      if rel
        "#{uri} (at #{info}/#{rel})"
      else
        "#{uri} (at #{info})"
      end
    end

    def lock_data
      out = {}
      out["git"] = uri
      out["revision"] = revision
      out["ref"] = shortref if shortref
      out["branch"] = branch if branch
      out["tag"] = tag if tag
      out["rel"] = rel if rel
      out
    end

    def to_lock
      out =  "    git: #{uri}\n"
      out << "    revision: #{revision}\n"
      out << "    ref: #{shortref}\n"  if shortref
      out << "    branch: #{branch}\n" if branch
      out << "    tag: #{tag}\n"       if tag
      out << "    rel: #{rel}\n"       if rel
      out
    end

    # The path where this cookbook would live in the store, if it were
    # installed.
    #
    # @return [Pathname, nil]
    def install_path
      CookbookOmnifetch.storage_path
        .join(cache_key)
    end

    def cache_key
      "#{dependency.name}-#{revision}"
    end

    protected

    # The short ref (if one was given).
    #
    # @return [String, nil]
    def shortref
      ref && ref[0...7]
    end

    private

    # Perform a git command.
    #
    # @param [String] command
    #   the command to run
    # @param [Boolean] error
    #   whether to raise error if the command fails
    #
    # @raise [String]
    #   the +$stdout+ from the command
    def git(command, error = true)
      unless CookbookOmnifetch.which("git") || CookbookOmnifetch.which("git.exe") || CookbookOmnifetch.which("git.bat")
        raise GitNotInstalled.new
      end

      response = CookbookOmnifetch.shell_out_class.shell_out(%{git #{command}})

      if error && !response.success?
        raise GitCommandError.new(command, cache_path, response.stderr)
      end

      response.stdout.strip
    end

    # Determine if this git repo has already been downloaded.
    #
    # @return [Boolean]
    def cached?
      cache_path.exist?
    end

    # The path where this git repository is cached.
    #
    # @return [Pathname]
    def cache_path
      Pathname.new(CookbookOmnifetch.cache_path)
        .join(".cache", "git", Digest::SHA1.hexdigest(uri))
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2018 YCSB contributors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You
may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License. See accompanying
LICENSE file.
-->
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yahoo.ycsb</groupId>
        <artifactId>binding-parent</artifactId>
        <version>0.17.0-SNAPSHOT</version>
        <relativePath>../binding-parent</relativePath>
    </parent>

    <artifactId>tablestore-binding</artifactId>
    <name>TableStore DB Binding</name>

    <dependencies>
        <dependency>
            <groupId>com.yahoo.ycsb</groupId>
            <artifactId>core</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>tablestore</artifactId>
            <version>${tablestore.version}</version>
            </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

</project>


text:
.. -*- coding: utf-8 -*-
.. URL: https://docs.docker.com/engine/userguide/containers/usingdocker/
.. SOURCE: https://github.com/docker/docker/blob/master/docs/userguide/containers/usingdocker.md
   doc version: 1.12
      https://github.com/docker/docker/commits/master/docs/userguide/containers/usingdocker.md
.. check date: 2016/06/13
.. Commits on Jan 27, 2016 e310d070f498a2ac494c6d3fde0ec5d6e4479e14
.. ----------------------------------------------------------------------------

.. _usingdocker:

.. Run a simple application

.. _run-a-simple-application:

=======================================
シンプルなアプリケーションの実行
=======================================

.. sidebar:: 目次

   .. contents::
       :depth: 3
       :local:

.. In the "Hello world in a container" you launched your first containers using the docker run command. You ran an interactive container that ran in the foreground. You also ran a detached container that ran in the background. In the process you learned about several Docker commands:

「 :doc:`dockerizing` 」では、``docker run`` コマンドを使い、初めてのコンテナを起動しました。そして、フォアグラウンドで *双方向なコンテナ (interactive container)* を実行しました。また、バックグラウンドで *デタッチド・コンテナ (detached container)* を実行しました。この過程で複数の Docker コマンドを学びました。

..
    docker ps - Lists containers.
    docker logs - Shows us the standard output of a container.
    docker stop - Stops running containers.

* ``docker ps`` - コンテナの一覧を表示。
* ``docker logs`` - コンテナの標準出力を表示。
* ``docker stop`` - 実行中のコンテナを停止。

.. Learn about the Docker client

.. _learn-about-the-docker-client:

Docker クライアントについて学ぶ
===============================

.. If you didn't realize it yet, you've been using the Docker client each time you typed docker in your Bash terminal. The client is a simple command line client also known as a command-line interface (CLI). Each action you can take with the client is a command and each command can take a series of flags and arguments.

気が付いていないかも知れませんが、Bash ターミナル上で毎回 ``docker`` と入力し、既に Docker クライアントを利用していました。クライアントとはシンプルなコマンドライン・クライアントであり、コマンドライン・インターフェース(CLI)とも呼びます。クライアントを使った各種の動作にはコマンド(命令)を使います。各コマンドには一連のフラグや引数を持ちます。

.. code-block:: bash

   # 使い方:  [sudo] docker [サブコマンド] [フラグ] [引数] ..
   # 例:
   $ docker run -i -t ubuntu /bin/bash

.. You can see this in action by using the docker version command to return version information on the currently installed Docker client and daemon.

実際に動作するかどうかは ``docker version`` コマンドを使います。現在インストールしている Docker クライアントとデーモンのバージョン情報を確認できます。

.. code-block:: bash

   $ docker version

.. This command will not only provide you the version of Docker client and daemon you are using, but also the version of Go (the programming language powering Docker).

このコマンドは使用している Docker クライアントとデーモンのバージョンを表示するだけではありません。Go 言語(Docker を動かすプログラミング言語)のバージョンも表示します。

.. code-block:: bash

   Client:
     Version:      1.8.1
     API version:  1.20
     Go version:   go1.4.2
     Git commit:   d12ea79
     Built:        Thu Aug 13 02:35:49 UTC 2015
     OS/Arch:      linux/amd64

   Server:
     Version:      1.8.1
     API version:  1.20
     Go version:   go1.4.2
     Git commit:   d12ea79
     Built:        Thu Aug 13 02:35:49 UTC 2015
     OS/Arch:      linux/amd64

.. Get Docker command help

.. _get-docker-command-help:

Docker コマンドの使い方を表示
=============================

.. You can display the help for specific Docker commands. The help details the options and their usage. To see a list of all the possible commands, use the following:

特定の Docker コマンドに対する使い方も表示できます。help は使い方の詳細を表示します。利用可能なコマンドの一覧を表示するには、次のように実行します:

.. code-block:: bash

   $ docker --help

.. To see usage for a specific command, specify the command with the --help flag:

一般的な使い方は、コマンドラインで ``--help`` フラグを指定します。

.. code-block:: bash

   $ docker attach --help

   Usage: docker attach [OPTIONS] CONTAINER

   Attach to a running container

     --help=false        Print usage
     --no-stdin=false    Do not attach stdin
     --sig-proxy=true    Proxy all received signals to the process

.. Note: For further details and examples of each command, see the command reference in this guide.

.. note::

   各コマンドの更なる詳細や例については、当ガイドの :doc:`コマンド・リファレンス </engine/reference/commandline/cli>` をご覧ください。

.. Running a web application in Docker

.. _running-a-web-application-in-docker:

Docker でウェブ・アプリケーションを実行
=======================================

.. So now you've learned a bit more about the docker client you can move onto the important stuff: running more containers. So far none of the containers you've run did anything particularly useful, so you can change that by running an example web application in Docker.

ここまでは ``docker`` クライアントについて少しだけ学びました。次は多くのコンテナの実行という、より重要なことを学びます。これまで実行したコンテナのほとんどは、いずれも何かに役に立つ処理を行いませんでした。今度は、Docker を使ったウェブ・アプリケーションの実行に移ります。

.. For our web application we're going to run a Python Flask application. Start with a docker run command.

ウェブ・アプリケーションとして、Python の Flask アプリケーションを実行します。``docker run`` コマンドで開始します。

.. code-block:: bash

   $ docker run -d -P training/webapp python app.py

.. Review what the command did. You've specified two flags: -d and -P. You've already seen the -d flag which tells Docker to run the container in the background. The -P flag is new and tells Docker to map any required network ports inside our container to our host. This lets us view our web application.

コマンドの実行内容を精査します。``-d`` と ``-P`` という2つのフラグを指定しました。``-d`` フラグは既出であり、コンテナをバックグラウンドで実行するよう Docker に命令します。``-P`` は新しいフラグで、コンテナ内部のネットワークで必要なポートを、ホスト側にマップする(割り当てる)よう Docker に命令します。これにより、ウェブ・アプリケーションを参照できます。

.. You've specified an image: training/webapp. This image is a pre-built image you've created that contains a simple Python Flask web application.

ここではイメージ ``training/webapp`` を指定しました。このイメージは事前に構築しておいたイメージであり、シンプルな Python Flask ウェブ・アプリケーションが入っています。

.. Lastly, you've specified a command for our container to run: python app.py. This launches our web application.

最後にコンテナに対して ``python app.py`` を実行するコマンドを指定しました。これでウェブ・アプリケーションが起動します。

.. Note: You can see more detail on the docker run command in the command reference and the Docker Run Reference.

.. note::

   ``docker run`` コマンドについて、より詳細を知りたい場合は :doc:`コマンド・リファレンス </engine/reference/commandline/run>` と :doc:`Docker Run リファレンス </engine/reference/run>` をご覧ください。

.. Viewing our web application container

.. viewing-our-web-application-container:

ウェブ・アプリケーションのコンテナを表示
========================================

.. Now you can see your running container using the docker ps command.

さて、``docker ps`` コマンドを使い、実行中のコンテナを表示できます。

.. code-block:: bash

   $ docker ps -l
   CONTAINER ID  IMAGE                   COMMAND       CREATED        STATUS        PORTS                    NAMES
   bc533791f3f5  training/webapp:latest  python app.py 5 seconds ago  Up 2 seconds  0.0.0.0:49155->5000/tcp  nostalgic_morse

.. You can see you've specified a new flag, -l, for the docker ps command. This tells the docker ps command to return the details of the last container started.

``docker ps`` コマンドに新しいフラグ ``-l`` を指定しています。これは、最後に開始したコンテナの詳細を返すよう、``docker ps`` コマンドに命令します。

..    Note: By default, the docker ps command only shows information about running containers. If you want to see stopped containers too use the -a flag.

.. note::

   標準では、``docker ps`` コマンドは実行中のコンテナ情報のみ表示します。停止したコンテナの情報も表示したい場合は、``-a`` フラグを使います。

.. We can see the same details we saw when we first Dockerized a container with one important addition in the PORTS column.

:doc:`初めて Docker 化したコンテナ <dockerizing>` で見てきた詳細に加え、 ``PORTS`` 列に重要な情報が追加されています。

.. code-block:: bash

   PORTS
   0.0.0.0:49155->5000/tcp

.. When we passed the -P flag to the docker run command Docker mapped any ports exposed in our image to our host.

``docker run`` コマンドに ``-P`` フラグを渡したら、Docker はイメージからホスト側に対して、必要なポートを露出 (expose) します。

.. Note: We'll learn more about how to expose ports in Docker images when we learn how to build images.

.. note::

   Docker イメージで露出ポートを指定する方法は、 :doc:`イメージの構築方法 <dockerimages>` で学びます。

.. In this case Docker has exposed port 5000 (the default Python Flask port) on port 49155.

今回の場合、Docker はコンテナのポート 5000 (Python Flask の標準ポート)をホスト上のポート 49115 上に公開しました。

.. Network port bindings are very configurable in Docker. In our last example the -P flag is a shortcut for -p 5000 that maps port 5000 inside the container to a high port (from ephemeral port range which typically ranges from 32768 to 61000) on the local Docker host. We can also bind Docker containers to specific ports using the -p flag, for example:

Docker は、ネットワーク・ポートの割り当て設定を変更可能です。今回の例では、``-P`` フラグは ``-p 5000`` を指定するショートカットにあたります。これは、コンテナの中のポート 5000 を、ローカルの Docker ホスト上のハイポート(典型的な 32768 ~ 61000 の範囲にある一時利用ポート)に割り当てます。あるいは、``-p`` フラグを使うことで、Docker コンテナに割り当てるポートの指定も可能です。例:

.. code-block:: bash

   $ docker run -d -p 80:5000 training/webapp python app.py

.. This would map port 5000 inside our container to port 80 on our local host. You might be asking about now: why wouldn't we just want to always use 1:1 port mappings in Docker containers rather than mapping to high ports? Well 1:1 mappings have the constraint of only being able to map one of each port on your local host.

これはローカルホスト上のポート 80 を、コンテナ内のポート 5000 に割り当てます。もしかすると、次の疑問を持つでしょう。Docker コンテナをハイポートにマッピングするのではなく、常に 1:1 のポート割り当てを使わないのかと。ですが、ローカルホスト上の各ポートに 1:1 で割り当て可能なポートは1つだけだからです。

.. Suppose you want to test two Python applications: both bound to port 5000 inside their own containers. Without Docker's port mapping you could only access one at a time on the Docker host.

例えば、2つの Python アプリケーションを実行したいとします。いずれもコンテナの中でポート 5000 を使うものです。この場合 Docker のホスト上で、ポート 5000 にアクセスできるコンテナは常に1つだけです。

.. So you can now browse to port 49155 in a web browser to see the application.

それではウェブ・ブラウザからポート 49155 を表示してみます。

.. image:: webapp1.png

.. Our Python application is live!

Python アプリケーションが動いています!

.. Note: If you have been using a virtual machine on OS X, Windows or Linux, you'll need to get the IP of the virtual host instead of using localhost. You can do this by running the docker-machine ip your_vm_name from your command line or terminal application, for example:

.. note::

   Mac OS X や Windows または Linux 上の仮想マシンを使っている場合は、ローカルホスト上で仮想マシンが使っている IP アドレスを確認する必要があります。コマンドラインや端末アプリケーションを使い ``docker-machine ip 仮想マシン名`` を実行します。例:

   .. code-block:: bash

      $ docker-machine ip my-docker-vm
      192.168.99.100

   この例では、ブラウザで ``http://192.168.99.100:49155`` を開きます。

.. A network port shortcut

.. _a-network-port-shortcut:

network port でショートカット
=======================================

.. Using the docker ps command to return the mapped port is a bit clumsy so Docker has a useful shortcut we can use: docker port. To use docker port we specify the ID or name of our container and then the port for which we need the corresponding public-facing port.

割り当てたポートを確認するのに ``docker ps`` コマンドを使うのは少々面倒です。そこで、 Docker の ``docker port`` という便利なショートカットを使いましょう。``docker port`` でコンテナ ID や名前を指定したら、公開ポートに割り当てられているポート番号が分かります。

.. code-block:: bash

   $ docker port nostalgic_morse 5000
   0.0.0.0:49155

.. In this case you've looked up what port is mapped externally to port 5000 inside the container.

この例では、コンテナ内のポート 5000 が、外部の何番ポートに割り当てられたか分かります。

.. Viewing the web application's log

.. _viewing-the-web-applications-log:

ウェブ・アプリケーションのログ表示
=======================================

.. You can also find out a bit more about what's happening with our application and use another of the commands you've learned, docker logs.

アプリケーションで何が起こっているのか、より詳しく見てみましょう。これまで学んだ ``docker logs`` コマンドを使います。

.. code-block:: bash

   $ docker logs -f nostalgic_morse
   * Running on http://0.0.0.0:5000/
   10.0.2.2 - - [23/May/2014 20:16:31] "GET / HTTP/1.1" 200 -
   10.0.2.2 - - [23/May/2014 20:16:31] "GET /favicon.ico HTTP/1.1" 404 -

.. This time though you've added a new flag, -f. This causes the docker logs command to act like the tail -f command and watch the container's standard out. We can see here the logs from Flask showing the application running on port 5000 and the access log entries for it.

今回は新しい ``-f`` フラグを使いました。これは ``docker logs`` コマンドに対して ``tail -f`` コマンドのように動作するもので、コンテナの標準出力を見ます。ここではポート 5000 で動作している Flask アプリケーションに対する接続ログを表示します。

.. Looking at our web application container's processes

.. _looking-at-our-web-application-containers-processes:

アプリケーション・コンテナのプロセスを表示
=================================================

.. In addition to the container's logs we can also examine the processes running inside it using the docker top command.

コンテナのログに加え、``docker top`` コマンドを使えば、内部で実行しているプロセスを確認できます。

.. code-block:: bash

   $ docker top nostalgic_morse
   PID                 USER                COMMAND
   854                 root                python app.py

.. Here we can see our python app.py command is the only process running inside the container.

ここでは ``python app.py`` コマンドだけが、コンテナ内のプロセスとして動作していることが分かります。

.. Inspecting our web application container

.. _inspecting-our-web-application-container:

ウェブ・アプリケーション・コンテナの調査
==================================================

.. Lastly, we can take a low-level dive into our Docker container using the docker inspect command. It returns a JSON document containing useful configuration and status information for the specified container.

最後に、Docker コンテナに低レベルでアクセスするには、``docker inspect`` コマンドを使います。指定したコンテナに対する便利な構成情報やステータス情報を、JSON 形式で得られます。

.. code-block:: bash

   $ docker inspect nostalgic_morse

.. You can see a sample of that JSON output.

実行後、次のような JSON 出力例を表示します。

.. code-block:: json

   [{
       "ID": "bc533791f3f500b280a9626688bc79e342e3ea0d528efe3a86a51ecb28ea20",
       "Created": "2014-05-26T05:52:40.808952951Z",
       "Path": "python",
       "Args": [
          "app.py"
       ],
       "Config": {
          "Hostname": "bc533791f3f5",
          "Domainname": "",
          "User": "",
   . . .

.. We can also narrow down the information we want to return by requesting a specific element, for example to return the container's IP address we would:

あるいは、必要となる特定の情報のみ表示するように、情報を絞り込めます。次の例では、コンテナの IP アドレスのみ表示します。

.. code-block:: bash

   $ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nostalgic_morse
   172.17.0.5

.. Stopping our web application container

.. _stopping-our-web-application-container:

ウェブ・アプリケーション・コンテナの停止
==================================================

.. Okay you've seen web application working. Now you can stop it using the docker stop command and the name of our container: nostalgic_morse.

ここまではウェブ・アプリケーションが動作するのを確認しました。次は ``docker stop`` コマンドを使い、``nostalgic_morse`` という名前のコンテナを指定します。

.. code-block:: bash

   $ docker stop nostalgic_morse
   nostalgic_morse

.. We can now use the docker ps command to check if the container has been stopped.

``docker ps`` コマンドを使い、コンテナの停止を確認します。

.. code-block:: bash

   $ docker ps -l

.. Restarting our web application container

.. _restarting-out-web-application-container:

ウェブ・アプリケーション・コンテナの再起動
==================================================

.. Oops! Just after you stopped the container you get a call to say another developer needs the container back. From here you have two choices: you can create a new container or restart the old one. Look at starting your previous container back up.

おっと! コンテナの停止後に、他の開発者がコンテナを元に戻して欲しいと言ってきました。ここでは2つの選択肢があります。新しいコンテナを起動するか、あるいは古いものを再起動するかです。先ほどのコンテナを元に戻してみましょう。

.. code-block:: bash

   $ docker start nostalgic_morse
   nostalgic_morse

.. Now quickly run docker ps -l again to see the running container is back up or browse to the container's URL to see if the application responds.

ここで素早く ``docker ps -l`` を再度実行したら、実行していたコンテナが復帰し、コンテナの URL をブラウザで開けば、アプリケーションが応答します。

..    Note: Also available is the docker restart command that runs a stop and then start on the container.

.. note::

   ``docker restart`` コマンドも利用可能です。こちらはコンテナの停止と起動を行います。

.. Removing our web application container

.. _removing-our-web-application-container:

ウェブ・アプリケーション・コンテナの削除
==================================================

.. Your colleague has let you know that they've now finished with the container and won't need it again. Now, you can remove it using the docker rm command.

同僚は作業を終え、コンテナがもう不要との連絡がありました。これで、``docker rm`` コマンドを使い削除できます。

.. code-block:: bash

   $ docker rm nostalgic_morse
   Error: Impossible to remove a running container, please stop it first or use -f
   2014/05/24 08:12:56 Error: failed to remove one or more containers

.. What happened? We can't actually remove a running container. This protects you from accidentally removing a running container you might need. You can try this again by stopping the container first.

何が起こったのでしょうか? 実行中かもしれないコンテナを間違って削除しないように、保護されているからです。先にコンテナを停止してから、再び実行します。

.. code-block:: bash

   $ docker stop nostalgic_morse
   nostalgic_morse
   $ docker rm nostalgic_morse
   nostalgic_morse

.. And now our container is stopped and deleted.

今度はコンテナを停止し、削除しました。

..    Note: Always remember that removing a container is final!

.. note::

   常に、最後にコンテナを削除するのを忘れないでください。

.. Next steps

次のステップ
====================

.. Until now you've only used images that you've downloaded from Docker Hub. Next, you can get introduced to building and sharing our own images.

ここまでは Docker Hub からダウンロードしたイメージのみを使ってきました。次は、自分でイメージを構築し、共有する方法を紹介します。

.. Go to Working with Docker images.

:doc:`Docker イメージの操作 <dockerimages>` に移動します。

.. seealso::

   Run a simple application
      https://docs.docker.com/engine/userguide/containers/usingdocker/


text:
var https  = require('https')
  , io     = require('socket.io');

var TTPAPI = function () {
    var self      = this;
    this._port    = (typeof arguments[0] === 'number' && arguments[0] % 1 === 0) ? arguments[0] : 80;
    this._options = (Object.prototype.toString.call(arguments[1]) === '[object Object]') ? arguments[1] : {};
    this._io      = io.listen(this._port, this._options);
    this._users   = {};
    this._events  = [];

    this._io.disable('browser client');
    this._io.set('log level', 1);
    this._io.set('transports', ['websocket', 'xhr-polling']);
    this._io.set('authorization', function (data, callback) {
        if (self._options.room_url !== undefined && data.headers.referer.substr(data.headers.referer.lastIndexOf('/') + 1) !== self._options.room_url) {
			callback(null, false);
		} else {
			callback(null, true);
		}
    });

    this._io.sockets.on('connection', function (socket) {
        var id = socket.id,
            x;

        self._users[id] = {
            socket: socket,
            auth:   false,
            userid: null
        };

        socket.on('disconnect', function() {
            delete self._users[id];
        });

        socket.on('auth', function (data, resObj) {
            var authValid;
            if (resObj === undefined) {
                socket.emit('message', {success: false, re: 'auth', error: "You require an update to TT+. Please install - http://turntableplus.fm/downloads/latest.crx", log: true, alert: true});
                socket.disconnect();
                return;
            }
            if (typeof self._options.auth === 'function' && self._options.auth(data.userid) !== true) {
                resObj({success: false, error: "Bot-level authentication failed.", log: true, alert: false});
                socket.disconnect();
                return;
            } else if (typeof data.auth !== "string" || data.auth.length !== 40) {
                resObj({success: false, error: "Auth is not valid.", log: true, alert: false});
                socket.disconnect();
                return;
            }
            https.get({host: "bots.turntableplus.fm", port: 443, path: "/auth/u/" + data.userid + "/a/" + data.auth}, function (authResponse) {
                var json = '';
                authResponse.on('data', function (chunk) {
                    json += chunk.toString();
                });
                authResponse.on('end', function () {
                    try {
                        json = JSON.parse(json);
                        if (json.success === true) {
                            self._users[id].auth = true;
                            self._users[id].userid = data.userid;
                            socket.set('auth', true);
                            socket.set('userid', data.userid);
                            resObj({success: true});
                        } else {
                            json.log = true;
                            json.alert = false;
                            resObj(json);
                            socket.disconnect();
                        }
                    } catch (e) {
                        resObj({success: false, error: "Unknown authentication error.", log: true, alert: false});
                        socket.disconnect();
                    }
                });
            });
        });
    });
};

TTPAPI.prototype.on = function (eventType, listener) {
    this._io.on('connection', function (socket) {
        socket.on(eventType, function () {
            listener.apply(socket, arguments);
        });
    });
};

TTPAPI.prototype.emit = function () {
    var args = [].slice.call(arguments), socket;
    socket = this.getSocket(args.shift());
    if (socket !== null) {
        socket.emit.apply(socket, args);
    }
};

TTPAPI.prototype.broadcast = function () {
    var x, user;
    for (x in this._users) {
        user = this._users[x];
        if (user.hasOwnProperty('auth') === true && user.auth === true) {
            user.socket.emit.apply(user.socket, arguments);
        }
    }
};

TTPAPI.prototype.getSocket = function (userid) {
    var x, user;
    for (x in this._users) {
        user = this._users[x];
        if (user.hasOwnProperty('userid') === true && user.userid === userid && user.hasOwnProperty('auth') === true && user.auth === true) {
            return user.socket;
        }
    }
    return null;
};

TTPAPI.prototype.getUserid = function (socket) {
    if (typeof socket === 'object' && socket.hasOwnProperty('id') === true && this._users[socket.id] !== undefined) {
        return this._users[socket.id].userid;
    } else {
        return false;
    }
}

exports.TTPAPI = TTPAPI;


text:
# Real world projects. Dependency cruised.

## Some popular projects on npm

### Commander

[tj/commander.js](https://github.com/tj/commander.js) - For command line parsing - and cooking command line interfaces.

### Chalk

[chalk/chalk](https://github.com/chalk/chalk) -
For colouring strings in the terminal. A typical _Sorhus style_ micro module that uses other micro modules to accomplish its goals.

### Yarn 2 ('berry')

[yarnpkg/berry](https://github.com/yarnpkg/berry) - package manager.

When your app becomes big, dependency graphs on module level will become
impractical. Dependency-cruiser can consolidate modules (+ their dependencies)
and colour them. Consolidation works out of the box for many repositories,
but can be [configured](./options-reference.md#summarising-collapsepattern-dot-and-archi-reporters)
to your [own liking](./options-reference.md#reporteroptions).

Here's the resulting get high level dependency graph for berry:

[![berry](real-world-samples/berry-high-level-dependencies.svg)](https://sverweij.github.io/dependency-cruiser/assets/berry-high-level-dependencies.html)

howto

To get the above graph we used [berry-dependency-cruiser-config.js](real-world-samples/berry-dependency-cruiser-config.js). To generate it yourself do this in the root of the berry repo:

- `yarn` (with yarn v2 :-))
- `yarn add -D dependency-cruiser`
- `rm -f berry-dependency-cruiser-config.js`
- `wget https://raw.githubusercontent.com/sverweij/dependency-cruiser/develop/doc/real-world-samples/berry-dependency-cruiser-config.js`
- add these two lines to the `scripts` section of the package.json (so don't
  use the globally installed depcruise or even the locally installed one -
  yarn's pnp resolution won't work otherwise:)
  ```
  "dc": "depcruise --version && depcruise --config berry-dependency-cruiser-config.js --output-type err packages",
  "depcruise:archi": "depcruise --version && depcruise --config berry-dependency-cruiser-config.js --output-type archi packages | dot -T svg | tee berry-high-level-dependencies.svg | depcruise-wrap-stream-in-html > berry-high-level-dependencies.html",
  ```
- run `yarn depcruise:archi`

### react

[facebook/react](https://github.com/facebook/react) - "a JavaScript library for building user interfaces".

Also high level:

[![react](real-world-samples/react-high-level-dependencies.svg)](https://sverweij.github.io/dependency-cruiser/assets/react-high-level-dependencies.html)

howto

To get the above graph we used [react-dependency-cruiser-config.js](real-world-samples/react-dependency-cruiser-config.js). To generate it yourself do this in the root of the react repo:

- prepare

```sh
git clone git@github.com:facebook/react.git
cd react
yarn
yarn add -D -W dependency-cruiser
rm -f react-dependency-cruiser-config.js
wget https://raw.githubusercontent.com/sverweij/dependency-cruiser/develop/doc/real-world-samples/react-dependency-cruiser-config.js
```

- Add these run-scripts to the package.json:

  ```
    "dc": "depcruise --version && depcruise --ignore-known --config react-dependency-cruiser-config.js -T err packages/*/{*.js,src}",
    "depcruise:baseline": "depcruise --version && depcruise-baseline packages/*/{*.js,src} --config react-dependency-cruiser-config.js",
    "depcruise:archi": "depcruise --ignore-known --config react-dependency-cruiser-config.js -T archi packages/*/{*.js,src} | dot -T svg | tee react-high-level-dependencies.svg | depcruise-wrap-stream-in-html > react-high-level-dependencies.html
  ```

- `yarn depcruise:baseline`
- `yarn depcruise:archi`

### Safe-regex

[substack/safe-regex](https://github.com/substack/safe-regex) - for sanity checking regular expressions against exponential time errors. For everyone who enables users to input regular expressions in.

![safe-regex](real-world-samples/safe-regex.png)

### Resolve

[substack/node-resolve](https://github.com/substack/node-resolve) - resolves (node) module names to files on disk.

### Yargs

[yargs/yargs](https://github.com/yargs/yargs) - Another library to parse command line options/ cook command line interfaces.

![yargs](real-world-samples/yargs.png)

## TypeScript

It is possible to use dependency-cruiser to infer dependencies of typescript
projects.

We got the picture of tslint by running this in its source folder:

```sh
dependency-cruise -T dot -x node_modules -v -- src/index.ts  | dot -T png > tslint-without-node_modules.png
```

(Yep, that's all - no separate transpilation steps necessary ...)

### tslint

[palantir/tslint](https://github.com/palantir/tslint) - linter for typescript.

The orange lines are warnings for circular dependencies, which occur around two of
tslint's 'barrel' `index.ts` modules:

![tslint](real-world-samples/tslint-without-node_modules.png)

## CoffeeScript

In the same vein dependency-cruiser directly supports CoffeeScript.

In the `src` folder of the CoffeeScript repo run this:

```sh
depcruise -x node_modules -T dot . | dot -T png > coffee-script-coffee-without-node_modules.png
```

### CoffeeScript

[jashkenas/coffeescript](https://github.com/jashkenas/coffeescript) - the
CoffeeScript transpiler:

![coffee-script](real-world-samples/coffee-script-coffee-without-node_modules.png)

(You see one module flagged as _unresolvable_ - this is the parser code
that the CoffeeScript build script generates jison into the folder with
transpiled JavaScript.)

## My own projects

### dependency cruiser

Dependency cruiser used on itself, focusing on internal dependencies only, on three
levels of abstraction - high level, folder and modules. A small
[custom theme](options-reference.md#theme-dot-ddot-and-archi-reporters) in its [configuration](../.dependency-cruiser.json#L243)
colours the various main parts (extract, validate, report) and the dependencies to
them. Click for slightly more interactive versions.

#### high level overview ('archi')

[![dependency cruiser's dependency graph aggregated to its main parts](./real-world-samples/dependency-cruiser-archi-graph.svg)](https://sverweij.github.io/dependency-cruiser/dependency-cruiser-archi-graph.html)

howto

To generate this yourself do this in the root of the dependency-cruiser repo:

```
node ./bin/dependency-cruise.js bin src --config --output-type archi | \
  # format the output with dot. For this specific graph top-down (TD)
  # orientation works best
  dot -T svg -Grankdir=TD | \
  # save the svg
  tee doc/real-world-samples/dependency-cruiser-archi-graph.svg | \
  # process the svg into an interactive html graph
  node bin/wrap-stream-in-html.js > docs/dependency-cruiser-archi-graph.html
```

> the only repository in the world you can't use the commands `depcruise`,
> `depcruise-fmt` or `depcruise-wrap-stream-in-html` is dependency-cruiser's own -
> instead we run the JavaScript files from `bin` directly.
> If you adapt the script for your own use replace
> `node ./bin/dependency-cruise.js` with `depcruise`,
> `node ./bin/wrap-stream-in-html.js` with `depcruise-wrap-stream-in-html`.

#### folder level overview ('ddot')

[![dependency cruiser's dependency graph aggregated to folders](./real-world-samples/dependency-cruiser-dir-graph.svg)](https://sverweij.github.io/dependency-cruiser/dependency-cruiser-dir-graph.html)

howto

To generate this yourself do this in the root of the dependency-cruiser repo:

```
node ./bin/dependency-cruise.js bin src --config --output-type ddot | \
  # format the output with dot. For this specific graph top-down (TD)
  # orientation works best
  dot -T svg -Grankdir=TD | \
  # save the svg
  tee doc/real-world-samples/dependency-cruiser-dir-graph.svg | \
  # process the svg into an interactive html graph
  node bin/wrap-stream-in-html.js > docs/dependency-cruiser-dir-graph.html
```

> the only repository in the world you can't use the commands `depcruise`,
> `depcruise-fmt` or `depcruise-wrap-stream-in-html` is dependency-cruiser's own -
> instead we run the JavaScript files from `bin` directly.
> If you adapt the script for your own use replace
> `node ./bin/dependency-cruise.js` with `depcruise`,
> `node ./bin/wrap-stream-in-html.js` with `depcruise-wrap-stream-in-html`.

#### detailed overview ('dot')

[![dependency cruiser's dependency graph](real-world-samples/dependency-cruiser-without-node_modules.svg)](https://sverweij.github.io/dependency-cruiser/dependency-cruiser-dependency-graph.html)

how to

To generate this yourself do this in the root of the dependency-cruiser repo:

```
# The --prefix will make sure that any links in the report open in vscode
# You can alternatively configure this in your .dependency-cruiser.js
node ./bin/dependency-cruise.js bin src --prefix vscode://file/$(pwd)/ --config --output-type dot | \
  # format the output with dot
  dot -T svg |\
  # process the svg into an interactive html graph
  node ./bin/wrap-stream-in-html.js |\
  # The browser command opens the graph-in-html just produced in your
  # default browser
  browser
```

> the only repository in the world you can't use the commands `depcruise`,
> `depcruise-fmt` or `depcruise-wrap-stream-in-html` is dependency-cruiser's own.
> Instead we run the JavaScript files from `bin` directly. Alternatively, in the
> dependency-cruiser repo you can run a script from package.json to get this
> result as well: `depcruise:graph:view` - which also opens the graph.
> If you adapt the script for your own use replace
> `node ./bin/dependency-cruise.js` with `depcruise`,
> `node ./bin/wrap-stream-in-html.js` with `depcruise-wrap-stream-in-html`.

### state machine cat

[sverweij/state-machine-cat](https://github.com/sverweij/state-machine-cat) - an
interpreter for writing nice state diagrams. Click for a slightly
more interactive version. As you can see this graph does not group modules
from same folders into clusters. Instead it uses only colors for 'grouping'
and notes the folder name in the nodes. It's what the ['flat'](https://github.com/sverweij/dependency-cruiser/blob/develop/doc/cli.md#flat-fdot) graph reporter
does for you. See the _how to_ foldout below to see how to reproduce it.

(For this too: click for a slightly more interactive version)

[![state-machine-cat without external dependencies](https://state-machine-cat.js.org/dependency-cruiser-graph-flat-dot.svg)](https://state-machine-cat.js.org/dependency-cruiser-graph-flat-dot.html)

how to

```sh
git clone git@github.com:sverweij/state-machine-cat.git
cd state-machine-cat
npm install
npx depcruise src bin/smcat --progress \
    --config config/dependency-cruiser-graph.js \
    --output-type flat \
  | dot -Tsvg \
  | tee docs/dependency-cruiser-graph-flat-dot.svg \
  | npx depcruise-wrap-stream-in-html \
  > docs/dependency-cruiser-graph-flat-dot.html
```

### mscgen.js

[mscgenjs/mscgenjs-core](https://github.com/mscgenjs/mscgenjs-core) - an
interpreter library for turning text (in MscGen or two other DSLs) into sequence
charts. Click for a slightly more interactive version.

[![mscgen.js](https://mscgenjs.github.io/mscgenjs-core/dependencygraph.svg)](https://mscgenjs.github.io/mscgenjs-core/dependencygraph.html)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Cartola</logradouro><bairro>Brasília</bairro><cidade>Cascavel</cidade><uf>PR</uf><cep>85815100</cep></feed>


text:
package com.pany.ehcache.integration;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;

import org.ehcache.spi.loaderwriter.CacheLoaderWriter;

/**
 * @author Alex Snaps
 */
public class TestCacheLoaderWriter implements CacheLoaderWriter<Number, String> {

  public static Number lastWrittenKey;

  public static CountDownLatch latch;

  @Override
  public String load(final Number key) throws Exception {
    return key.toString();
  }

  @Override
  public Map<Number, String> loadAll(final Iterable<? extends Number> keys) throws Exception {
    final Map<Number, String> loaded = new HashMap<Number, String>();
    for (Number key : keys) {
      loaded.put(key, load(key));
    }
    return loaded;
  }

  @Override
  public void write(final Number key, final String value) throws Exception {
    lastWrittenKey = key;
    if(latch != null) {
      latch.countDown();
    }
  }

  @Override
  public void writeAll(final Iterable<? extends Map.Entry<? extends Number, ? extends String>> entries) throws Exception {
    for (Entry<? extends Number, ? extends String> entry : entries) {
      lastWrittenKey = entry.getKey();
      if(latch != null) {
        latch.countDown();
      }
    }
  }

  @Override
  public void delete(final Number key) throws Exception {
    throw new UnsupportedOperationException("Implement me!");
  }

  @Override
  public void deleteAll(final Iterable<? extends Number> keys) throws Exception {
    throw new UnsupportedOperationException("Implement me!");
  }
}


text:
var work = function() {
  console.log("working hard!");
};

var dowork = function(f){

  console.log("starting");
  // error handling
  try {
      f();
  }
  catch(ex) {
    console.log(ex);
  }
  console.log("end");
};

// function calling - note: not invoking but passing
dowork(work);


text:
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, initialize_chain_clean, \
    start_node, connect_nodes
from test_framework.mininode import COIN

import time

class PrioritiseTransactionTest (BitcoinTestFramework):

    def setup_chain(self):
        print("Initializing test directory "+self.options.tmpdir)
        initialize_chain_clean(self.options.tmpdir, 4)

    def setup_network(self, split=False):
        self.nodes = []
        # Start nodes with tiny block size of 11kb
        self.nodes.append(start_node(0, self.options.tmpdir, ["-blockprioritysize=7000", "-blockmaxsize=11000", "-maxorphantx=1000", "-relaypriority=true", "-printpriority=1"]))
        self.nodes.append(start_node(1, self.options.tmpdir, ["-blockprioritysize=7000", "-blockmaxsize=11000", "-maxorphantx=1000", "-relaypriority=true", "-printpriority=1"]))
        connect_nodes(self.nodes[1], 0)
        self.is_network_split=False
        self.sync_all()

    def run_test (self):
        # tx priority is calculated: priority = sum(input_value_in_base_units * input_age)/size_in_bytes

        print "Mining 11kb blocks..."
        self.nodes[0].generate(501)

        base_fee = self.nodes[0].getnetworkinfo()['relayfee']

        # 11 kb blocks will only hold about 50 txs, so this will fill mempool with older txs
        taddr = self.nodes[1].getnewaddress()
        for _ in range(900):
            self.nodes[0].sendtoaddress(taddr, 0.1)
        self.nodes[0].generate(1)
        self.sync_all()

        # Create tx of lower value to be prioritized on node 0
        # Older transactions get mined first, so this lower value, newer tx is unlikely to be mined without prioritisation
        priority_tx_0 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)

        # Check that priority_tx_0 is not in block_template() prior to prioritisation
        block_template = self.nodes[0].getblocktemplate()
        in_block_template = False
        for tx in block_template['transactions']:
            if tx['hash'] == priority_tx_0:
                in_block_template = True
                break
        assert_equal(in_block_template, False)

        priority_success = self.nodes[0].prioritisetransaction(priority_tx_0, 1000, int(3 * base_fee * COIN))
        assert(priority_success)

        # Check that prioritized transaction is not in getblocktemplate()
        # (not updated because no new txns)
        in_block_template = False
        block_template = self.nodes[0].getblocktemplate()
        for tx in block_template['transactions']:
            if tx['hash'] == priority_tx_0:
                in_block_template = True
                break
        assert_equal(in_block_template, False)

        # Sending a new transaction will make getblocktemplate refresh within 10s
        self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)

        # Check that prioritized transaction is not in getblocktemplate()
        # (too soon)
        in_block_template = False
        block_template = self.nodes[0].getblocktemplate()
        for tx in block_template['transactions']:
            if tx['hash'] == priority_tx_0:
                in_block_template = True
                break
        assert_equal(in_block_template, False)

        # Check that prioritized transaction is in getblocktemplate()
        # getblocktemplate() will refresh after 1 min, or after 10 sec if new transaction is added to mempool
        # Mempool is probed every 10 seconds. We'll give getblocktemplate() a maximum of 30 seconds to refresh
        block_template = self.nodes[0].getblocktemplate()
        start = time.time();
        in_block_template = False
        while in_block_template == False:
            for tx in block_template['transactions']:
                if tx['hash'] == priority_tx_0:
                    in_block_template = True
                    break
            if time.time() - start > 30:
                raise AssertionError("Test timed out because prioritised transaction was not returned by getblocktemplate within 30 seconds.")
            time.sleep(1)
            block_template = self.nodes[0].getblocktemplate()

        assert(in_block_template)

        # Node 1 doesn't get the next block, so this *shouldn't* be mined despite being prioritized on node 1
        priority_tx_1 = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 0.1)
        self.nodes[1].prioritisetransaction(priority_tx_1, 1000, int(3 * base_fee * COIN))

        # Mine block on node 0
        blk_hash = self.nodes[0].generate(1)
        block = self.nodes[0].getblock(blk_hash[0])
        self.sync_all()

        # Check that priority_tx_0 was mined
        mempool = self.nodes[0].getrawmempool()
        assert_equal(priority_tx_0 in block['tx'], True)
        assert_equal(priority_tx_0 in mempool, False)

        # Check that priority_tx_1 was not mined
        assert_equal(priority_tx_1 in mempool, True)
        assert_equal(priority_tx_1 in block['tx'], False)

        # Mine a block on node 1 and sync
        blk_hash_1 = self.nodes[1].generate(1)
        block_1 = self.nodes[1].getblock(blk_hash_1[0])
        self.sync_all()

        # Check to see if priority_tx_1 is now mined
        mempool_1 = self.nodes[1].getrawmempool()
        assert_equal(priority_tx_1 in mempool_1, False)
        assert_equal(priority_tx_1 in block_1['tx'], True)

if __name__ == '__main__':
    PrioritiseTransactionTest().main()


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\widgets\Select2;
use yii\helpers\ArrayHelper;
/* @var $this yii\web\View */
/* @var $model backend\models\TrainingClass */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
		'id'=>'form-follow-training',
		'action' => ['follow-training','id'=>$activity->id,'class_id'=>$class->id],
		'enableAjaxValidation' => false,
        'enableClientValidation' => true,
	]); ?>
	<?= $form->errorSummary($model) ?>

	<?php echo $form->field($model, 'place_training')->textInput(['value'=>'-'])->label('Tempat'); ?>
	<?php echo $form->field($model, 'day_training')->textInput(['value'=>'1'])->label('Jumlah hari'); ?>
	<?php echo $form->field($model, 'day_hours_training')->textInput(['value'=>'10'])->label('Jamlat per hari'); ?>

	<?php
	$satker_id = Yii::$app->user->identity->employee->satker_id;
	$modelEmployeeSigners = \backend\models\Employee::find()
			->where(
				'
				satker_id=:satker_id
				AND
				organisation_id=:organisation_id
				AND
				chairman = 1
				',
				[
					':satker_id'=>$satker_id,
					':organisation_id'=>[
						387,396,397,398
					],
				]
			)
			->all();

	$employeeSigners = [];
	foreach($modelEmployeeSigners as $modelEmployeeSigner){
		$employeeSigners[$modelEmployeeSigner->person_id]=$modelEmployeeSigner->person->name.' - '.$modelEmployeeSigner->organisation->NM_UNIT_ORG;
	}
	echo $form->field($model, 'employee_id')->widget(Select2::classname(), [
		'data' => $employeeSigners,
		'options' => ['placeholder' => 'Choose employee ...'],
		'pluginOptions' => [
		'allowClear' => true
		],
	])->label('Employee'); ?>

    <?= Html::submitButton(
		' Generate',
		['class' => 'btn btn-success']) ?>

    <?php ActiveForm::end(); ?>

	<?php
	$this->registerJs("
		$('#form-follow-training').on('beforeSubmit', function(event, jqXHR, settings) {
                var form = $(this);
                if(form.find('.has-error').length) {
                     return false;
                }
				$('#modal-heart').modal('hide');
        })"); ?>