text:
require "shellwords"

#
# Tests, setup, and teardown common to the application and plugin generator suites.
#
module SharedGeneratorTests
  def setup
    Rails.application = TestApp::Application
    super
    Rails::Generators::AppGenerator.instance_variable_set("@desc", nil)

    Kernel.silence_warnings do
      Thor::Base.shell.attr_accessor :always_force
      @shell = Thor::Base.shell.new
      @shell.always_force = true
    end
  end

  def teardown
    super
    Rails::Generators::AppGenerator.instance_variable_set("@desc", nil)
    Rails.application = TestApp::Application.instance
  end

  def application_path
    destination_root
  end

  def test_skeleton_is_created
    run_generator

    default_files.each { |path| assert_file path }
  end

  def test_plugin_new_generate_pretend
    run_generator ["testapp", "--pretend"]
    default_files.each { |path| assert_no_file File.join("testapp", path) }
  end

  def test_invalid_database_option_raises_an_error
    content = capture(:stderr) { run_generator([destination_root, "-d", "unknown"]) }
    assert_match(/Invalid value for --database option/, content)
  end

  def test_test_files_are_skipped_if_required
    run_generator [destination_root, "--skip-test"]
    assert_no_file "test"
  end

  def test_name_collision_raises_an_error
    reserved_words = %w[application destroy plugin runner test]
    reserved_words.each do |reserved|
      content = capture(:stderr) { run_generator [File.join(destination_root, reserved)] }
      assert_match(/Invalid \w+ name #{reserved}\. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n/, content)
    end
  end

  def test_name_raises_an_error_if_name_already_used_constant
    %w{ String Hash Class Module Set Symbol }.each do |ruby_class|
      content = capture(:stderr) { run_generator [File.join(destination_root, ruby_class)] }
      assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use\. Please choose another \w+ name\.\n/, content)
    end
  end

  def test_shebang_is_added_to_rails_file
    run_generator [destination_root, "--ruby", "foo/bar/baz", "--full"]
    assert_file "bin/rails", /#!foo\/bar\/baz/
  end

  def test_shebang_when_is_the_same_as_default_use_env
    run_generator [destination_root, "--ruby", Thor::Util.ruby_command, "--full"]
    assert_file "bin/rails", /#!\/usr\/bin\/env/
  end

  def test_template_raises_an_error_with_invalid_path
    quietly do
      content = capture(:stderr) { run_generator([destination_root, "-m", "non/existent/path"]) }

      assert_match(/The template \[.*\] could not be loaded/, content)
      assert_match(/non\/existent\/path/, content)
    end
  end

  def test_template_is_executed_when_supplied_an_https_path
    url = "https://gist.github.com/josevalim/103208/raw/"
    generator([destination_root], template: url)

    applied = nil
    apply_stub = -> (path, *) { applied = path }

    generator.stub(:apply, apply_stub) do
      run_generator_instance
    end

    assert_equal url, applied
  end

  def test_skip_git
    run_generator [destination_root, "--skip-git", "--full"]
    assert_no_file(".gitignore")
    assert_no_directory(".git")
  end

  def test_skip_keeps
    run_generator [destination_root, "--skip-keeps", "--full"]

    assert_file ".gitignore" do |content|
      assert_no_match(/\.keep/, content)
    end
    assert_directory("app/assets/images")
    assert_no_file("app/models/concerns/.keep")
  end

  def test_default_frameworks_are_required_when_others_are_removed
    run_generator [
      destination_root,
      "--skip-active-record",
      "--skip-active-storage",
      "--skip-action-mailer",
      "--skip-action-mailbox",
      "--skip-action-text",
      "--skip-action-cable"
    ]

    assert_file "#{application_path}/config/application.rb", /^require\s+["']rails["']/
    assert_file "#{application_path}/config/application.rb", /^require\s+["']active_model\/railtie["']/
    assert_file "#{application_path}/config/application.rb", /^require\s+["']active_job\/railtie["']/
    assert_file "#{application_path}/config/application.rb", /^# require\s+["']active_record\/railtie["']/
    assert_file "#{application_path}/config/application.rb", /^# require\s+["']active_storage\/engine["']/
    assert_file "#{application_path}/config/application.rb", /^require\s+["']action_controller\/railtie["']/
    assert_file "#{application_path}/config/application.rb", /^# require\s+["']action_mailer\/railtie["']/
    unless generator_class.name == "Rails::Generators::PluginGenerator"
      assert_file "#{application_path}/config/application.rb", /^# require\s+["']action_mailbox\/engine["']/
      assert_file "#{application_path}/config/application.rb", /^# require\s+["']action_text\/engine["']/
    end
    assert_file "#{application_path}/config/application.rb", /^require\s+["']action_view\/railtie["']/
    assert_file "#{application_path}/config/application.rb", /^# require\s+["']action_cable\/engine["']/
    assert_file "#{application_path}/config/application.rb", /^require\s+["']rails\/test_unit\/railtie["']/
  end

  def test_generator_without_skips
    run_generator
    assert_file "#{application_path}/config/application.rb", /\s+require\s+["']rails\/all["']/
    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_match(/config\.action_mailer\.raise_delivery_errors = false/, content)
    end
    assert_file "#{application_path}/config/environments/test.rb" do |content|
      assert_match(/config\.action_mailer\.delivery_method = :test/, content)
    end
    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_match(/# config\.action_mailer\.raise_delivery_errors = false/, content)
      assert_match(/^  # config\.require_master_key = true/, content)
    end
  end

  def test_gitignore_when_sqlite3
    run_generator

    assert_file ".gitignore" do |content|
      assert_match(/sqlite3/, content)
    end
  end

  def test_gitignore_when_non_sqlite3_db
    run_generator([destination_root, "-d", "mysql"])

    assert_file ".gitignore" do |content|
      assert_no_match(/sqlite/i, content)
    end
  end

  def test_generator_if_skip_active_record_is_given
    run_generator [destination_root, "--skip-active-record"]
    assert_no_directory "#{application_path}/db/"
    assert_no_file "#{application_path}/config/database.yml"
    assert_no_file "#{application_path}/app/models/application_record.rb"
    assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
    assert_file "test/test_helper.rb" do |helper_content|
      assert_no_match(/fixtures :all/, helper_content)
    end
    assert_file "#{application_path}/bin/setup" do |setup_content|
      assert_no_match(/db:prepare/, setup_content)
    end
    assert_file ".gitignore" do |content|
      assert_no_match(/sqlite/i, content)
    end
  end

  def test_generator_for_active_storage
    run_generator([destination_root])

    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/test.rb" do |content|
      assert_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/storage.yml"
    assert_directory "#{application_path}/storage"
    assert_directory "#{application_path}/tmp/storage"

    assert_file ".gitignore" do |content|
      assert_match(/\/storage\//, content)
    end
  end

  def test_generator_if_skip_active_storage_is_given
    run_generator [destination_root, "--skip-active-storage"]

    assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']active_storage\/engine["']/

    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/test.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_no_file "#{application_path}/config/storage.yml"
    assert_no_directory "#{application_path}/storage"
    assert_no_directory "#{application_path}/tmp/storage"

    assert_file ".gitignore" do |content|
      assert_no_match(/\/storage\//, content)
    end
  end

  def test_generator_does_not_generate_active_storage_contents_if_skip_active_record_is_given
    run_generator [destination_root, "--skip-active-record"]

    assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']active_storage\/engine["']/

    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_file "#{application_path}/config/environments/test.rb" do |content|
      assert_no_match(/config\.active_storage/, content)
    end

    assert_no_file "#{application_path}/config/storage.yml"
    assert_no_directory "#{application_path}/storage"
    assert_no_directory "#{application_path}/tmp/storage"

    assert_file ".gitignore" do |content|
      assert_no_match(/\/storage\//, content)
    end
  end

  def test_generator_if_skip_action_mailer_is_given
    run_generator [destination_root, "--skip-action-mailer"]
    assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_mailer\/railtie["']/
    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_no_match(/config\.action_mailer/, content)
    end
    assert_file "#{application_path}/config/environments/test.rb" do |content|
      assert_no_match(/config\.action_mailer/, content)
    end
    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_no_match(/config\.action_mailer/, content)
    end
    assert_no_directory "#{application_path}/app/mailers"
    assert_no_directory "#{application_path}/test/mailers"
  end

  def test_generator_if_skip_action_cable_is_given
    run_generator [destination_root, "--skip-action-cable", "--webpack"]
    assert_file "#{application_path}/config/application.rb", /#\s+require\s+["']action_cable\/engine["']/
    assert_no_file "#{application_path}/config/cable.yml"
    assert_no_file "#{application_path}/app/javascript/consumer.js"
    assert_no_directory "#{application_path}/app/javascript/channels"
    assert_no_directory "#{application_path}/app/channels"
    assert_file "Gemfile" do |content|
      assert_no_match(/"redis"/, content)
    end
  end

  def test_generator_when_sprockets_is_not_used
    run_generator [destination_root, "-a", "none"]

    assert_no_file "#{application_path}/config/initializers/assets.rb"
    assert_no_file "#{application_path}/app/assets/config/manifest.js"

    assert_file "Gemfile" do |content|
      assert_no_match(/sass-rails/, content)
    end

    assert_file "#{application_path}/config/environments/development.rb" do |content|
      assert_no_match(/config\.assets\.debug/, content)
    end

    assert_file "#{application_path}/config/environments/production.rb" do |content|
      assert_no_match(/config\.assets\.digest/, content)
      assert_no_match(/config\.assets\.css_compressor/, content)
      assert_no_match(/config\.assets\.compile/, content)
    end
  end

  def test_dev_option
    run_generator_using_prerelease [destination_root, "--dev"]
    rails_path = File.expand_path("../../..", Rails.root)
    assert_file "Gemfile", %r{^gem ["']rails["'], path: ["']#{Regexp.escape rails_path}["']$}
  end

  def test_edge_option
    Rails.stub(:gem_version, Gem::Version.new("2.1.0")) do
      run_generator_using_prerelease [destination_root, "--edge"]
    end
    assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']2-1-stable["']$}
  end

  def test_edge_option_during_alpha
    Rails.stub(:gem_version, Gem::Version.new("2.1.0.alpha")) do
      run_generator_using_prerelease [destination_root, "--edge"]
    end
    assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
  end

  def test_main_option
    run_generator_using_prerelease [destination_root, "--main"]
    assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
  end

  def test_master_option
    run_generator_using_prerelease [destination_root, "--master"]
    assert_file "Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
  end

  def test_target_rails_prerelease_with_relative_app_path
    run_generator_using_prerelease ["myproject", "--main"]
    assert_file "myproject/Gemfile", %r{^gem ["']rails["'], github: ["']rails/rails["'], branch: ["']main["']$}
  end

  private
    def run_generator_instance
      @bundle_commands = []
      @bundle_command_stub ||= -> (command, *) { @bundle_commands << command }

      generator.stub(:bundle_command, @bundle_command_stub) do
        super
      end
    end

    def run_generator_using_prerelease(args)
      option_args, positional_args = args.partition { |arg| arg.start_with?("--") }
      project_path = File.expand_path(positional_args.first, destination_root)
      expected_args = [project_path, *positional_args.drop(1), *option_args]

      generator(positional_args, option_args)

      rails_gem_pattern = /^gem ["']rails["'], .+/
      bundle_command_rails_gems = []
      @bundle_command_stub = -> (command, *) do
        @bundle_commands << command
        assert_file File.expand_path("Gemfile", project_path) do |gemfile|
          bundle_command_rails_gems << gemfile[rails_gem_pattern]
        end
      end

      # run target_rails_prerelease on exit to mimic re-running generator
      generator.stub :exit, generator.method(:target_rails_prerelease) do
        run_generator_instance
      end

      assert_file File.expand_path("Gemfile", project_path) do |gemfile|
        assert_equal "install", @bundle_commands[0]
        assert_equal gemfile[rails_gem_pattern], bundle_command_rails_gems[0]

        assert_match %r"^exec rails (?:plugin )?new #{Regexp.escape Shellwords.join(expected_args)}", @bundle_commands[1]
        assert_equal gemfile[rails_gem_pattern], bundle_command_rails_gems[1]
      end
    end

    def assert_gem(name, constraint = nil)
      constraint_pattern = /, #{Regexp.escape constraint}/ if constraint
      assert_file "Gemfile", %r/^\s*gem ["']#{name}["']#{constraint_pattern}/
    end

    def assert_no_gem(name)
      assert_file "Gemfile" do |content|
        assert_no_match %r/gem ["']#{name}["']/, content
      end
    end
end


text:
		<title>Member List</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">

				Main Page
				Class Hierarchy
				Compound List
				Compound Members

PxVehicleClutchData Member List

This is the complete list of members for PxVehicleClutchData, including all inherited members.

isValid() const 	PxVehicleClutchData	private

mAccuracyMode	PxVehicleClutchData

mEstimateIterations	PxVehicleClutchData

mPad	PxVehicleClutchData	private

mStrength	PxVehicleClutchData

PxVehicleClutchData()	PxVehicleClutchData	inline

PxVehicleClutchData(const PxEMPTY &)	PxVehicleClutchData	inline

PxVehicleDriveSimData class	PxVehicleClutchData	friend

Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. www.nvidia.com

redpajama_set_name: RedPajamaGithub


text:
show_help () {
  cat <<EOF
${0##*/}, version %version%
This script is a wrapper to convert a potential to gromacs

Usage: ${0##*/} [options] input output

Allowed options:
    --help       show this help
    --clean      remove all intermediate temp files
    --no-r2d     do not converts rad to degree (scale x axis with 180/3.1415)
                 for angle and dihedral
                 Note: VOTCA calcs in rad, but gromacs in degree
    --no-shift   do not shift the potential
    --step XXX   use XXX as step for the interaction
EOF
}

clean=
do_shift="yes"
r2d="57.2957795"
step=

### begin parsing options
shopt -s extglob
while [[ ${1#-} != $1 ]]; do
 if [[ ${1#--} = $1 && -n ${1:2} ]]; then
    #short opt with arguments here: o
    if [[ ${1#-[o]} != ${1} ]]; then
       set -- "${1:0:2}" "${1:2}" "${@:2}"
    else
       set -- "${1:0:2}" "-${1:2}" "${@:2}"
    fi
 fi
 case $1 in
   --r2d) #default now
    shift ;;
   --no-r2d)
    r2d=1
    shift ;;
   --clean)
    clean="yes"
    shift ;;
   --no-shift)
    do_shift="no"
    shift ;;
   --step)
    step="$2"
    shift 2;;
   -h | --help)
    show_help
    exit 0;;
  *)
   die "Unknown option '$1'";;
 esac
done
### end parsing options

[[ -z $1 || -z $2 ]] && die "${0##*/}: missing argument"
input="$1"
trunc=${1##*/}
trunc="${trunc%%.*}"
[[ -f $input ]] || die "${0##*/}: Could not find input file '$input'"
output="$2"
echo "Convert $input to $output"

#special if calling from csg_call
xvgtype="$(csg_get_interaction_property bondtype)"
[[ $xvgtype = "C6" || $xvgtype = "C12" || $xvgtype = "CB" ]] && tabtype="non-bonded" || tabtype="$xvgtype"

zero=0
if [[ $tabtype = "non-bonded" ]]; then
  tablend="$(csg_get_property --allow-empty cg.inverse.gromacs.table_end)"
  mdp="$(csg_get_property cg.inverse.gromacs.mdp)"
  if [[ -f ${mdp} ]]; then
    echo "Found setting file '$mdp' now trying to check options in there"
    rlist=$(get_simulation_setting rlist)
    tabext=$(get_simulation_setting "table[-_]extension")
    # if we have all 3 numbers do this checks
    tabl=$(csg_calc "$rlist" + "$tabext")
    [[ -n $tablend  ]] &&  csg_calc "$tablend" "<" "$tabl" && \
      die "${0##*/}: Error table is shorter then what mdp file ($mdp) needs, increase cg.inverse.gromacs.table_end in setting file.\nrlist ($rlist) + tabext ($tabext) > cg.inverse.gromacs.table_end ($tablend)"
    max="$(csg_get_interaction_property max)"
    rvdw="$(get_simulation_setting rvdw)"
    csg_calc "$max" ">" "$rvdw" && die "${0##*/}: rvdw ($rvdw) is smaller than max ($max)"
    [[ -z $tablend ]] && tablend=$(csg_calc "$rlist" + "$tabext")
  elif [[ -z $tablend ]]; then
    die "${0##*/}: cg.inverse.gromacs.table_end was not defined in xml seeting file"
  fi
elif [[ $tabtype = "bond" ]]; then
  tablend="$(csg_get_property cg.inverse.gromacs.table_end)"
elif [[ $tabtype = "angle" ]]; then
  tablend=180
elif [[ $tabtype = "dihedral" ]]; then
  zero="-180"
  tablend=180
else
  die "${0##*/}: Unknown interaction type $tabtype"
fi

[[ $step ]] || step=$(csg_get_interaction_property step)
gromacs_bins="$(csg_get_property cg.inverse.gromacs.table_bins)"
comment="$(get_table_comment $input)"

if [[ $tabtype = "angle" || $tabtype = "dihedral" ]] && [[ $r2d != 1 ]]; then
  scale="$(critical mktemp ${trunc}.pot.scale.XXXXX)"
  do_external table linearop --on-x "${input}" "${scale}" "$r2d" "0"
  step=$(csg_calc $r2d "*" $step)
else
  scale="${input}"
fi

if [[ $tabtype = "dihedral" ]]; then
  csg_resample_opts=( "--boundaries" "periodic")
fi

#keep the grid for now, so that extrapolate can calculate the right mean
smooth="$(critical mktemp ${trunc}.pot.smooth.XXXXX)"
critical csg_resample --in "${scale}" --out "$smooth" --grid "${zero}:${step}:${tablend}" "${csg_resample_opts[@]}"

extrapol="$(critical mktemp ${trunc}.pot.extrapol.XXXXX)"
do_external potential extrapolate ${clean:+--clean} --type "$tabtype" "${smooth}" "${extrapol}"

interpol="$(critical mktemp ${trunc}.pot.interpol.XXXXX)"
critical csg_resample --in "${extrapol}" --out "$interpol" --grid "${zero}:${gromacs_bins}:${tablend}" "${csg_resample_opts[@]}" --comment "$comment"

if [[ $do_shift = "yes" ]]; then
  tshift="$(critical mktemp ${trunc}.pot.shift.XXXXX)"
  do_external potential shift --type "$tabtype" "${interpol}" "${tshift}"
else
  tshift="$interpol"
fi

potmax="$(csg_get_property --allow-empty cg.inverse.gromacs.pot_max)"
do_external convert_potential xvg ${potmax:+--max} ${potmax} --type "${xvgtype}" "${tshift}" "${output}"
if [[ $clean ]]; then
  rm -f "${smooth}" "${interpol}" "${extrapol}" "${tshift}"
  [[ ${input} = ${scale} ]] || rm -f "${scale}"
fi


text:
<!DOCTYPE HTML>
<html>
<head>
  <title>Media test: append source child</title>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
  <script type="text/javascript" src="manifest.js"></script>
</head>
<body>
<video id="v1"></video>
<audio id="a1"></audio>
<pre id="test">
<script class="testbody" type="text/javascript">
var v1 = document.getElementById("v1");
var a1 = document.getElementById("a1");

is(v1.src, "", "src should be null");
is(a1.src, "", "src should be null");
is(v1.currentSrc, "", "currentSrc should be null");
is(a1.currentSrc, "", "currentSrc should be null");
is(v1.childNodes.length, 0, "should have no children");
is(a1.childNodes.length, 0, "should have no children");

function newSource(filter) {
  var test = null;
  var candidates = gSmallTests.filter(function(x){return filter.test(x.type);});
  var e = document.createElement("source");
  e.type = candidates[0].type;
  e.src = candidates[0].name;
  return e;
}

var audioLoaded = false;
var videoLoaded = false;

function loaded(e) {
  var media = e.target;
  ok(media.networkState > 0, "networkState should be > 0");
  is(media.childNodes.length, 1, "should have 1 child");
  var sourceFile = media.currentSrc.substring(media.currentSrc.lastIndexOf('/')+1);
  var resource = media.firstChild.src.substring(media.firstChild.src.lastIndexOf('/')+1);
  is(sourceFile, resource, "loaded wrong resource!");
  if (media == a1)
    audioLoaded = true;
  else if (media == v1)
    videoLoaded = true;
  if (audioLoaded && videoLoaded) {
    SimpleTest.finish();
  }
}

v1.addEventListener('loadeddata', loaded, false);
a1.addEventListener('loadeddata', loaded, false);

var videoSource = newSource(/^video/);
if (videoSource) {
  v1.appendChild(videoSource);
  v1.load();
} else {
  // No video backends? Don't test anything.
  videoLoaded = true;
}

var audioSource = newSource(/^audio/);
if (audioSource) {
  a1.appendChild(audioSource);
  a1.load();
} else {
  audioLoaded = true;
}

if (!audioLoaded && !videoLoaded) {
  SimpleTest.waitForExplicitFinish();
} else {
  todo(false, "No types supported");
}

</script>
</pre>
</body>
</html>


text:
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@TestFile

//@Require('Class')
//@Require('Obj')
//@Require('Stack')
//@Require('bugmeta.BugMeta')
//@Require('bugunit.TestTag')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var Class       = bugpack.require('Class');
    var Obj         = bugpack.require('Obj');
    var Stack       = bugpack.require('Stack');
    var BugMeta     = bugpack.require('bugmeta.BugMeta');
    var TestTag     = bugpack.require('bugunit.TestTag');

    //-------------------------------------------------------------------------------
    // Simplify References
    //-------------------------------------------------------------------------------

    var bugmeta     = BugMeta.context();
    var test        = TestTag.test;

    //-------------------------------------------------------------------------------
    // Declare Tests
    //-------------------------------------------------------------------------------

    var stackConstructorTest = {

        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function() {
            this.array = ["how's", "it", "going?"];
        },

        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            this.stackZero     = new Stack();
            this.stackOne      = new Stack(["hello", "Brian"]);
            this.stackTwo      = new Stack(this.array);
            this.stackThree    = new Stack(this.stackOne);

            test.assertEqual(this.stackZero.getCount(), 0,
                "Assert Stack does not add arguments when none are given at construction time");

            test.assertEqual(this.stackTwo.containsAll(this.array), true,
                "Assert Stack accepts an Array as an argument at construction time and adds the array values to the Stack");
            test.assertEqual(this.stackTwo.getCount(), 3,
                "Assert stackTwo contains 3 items");

            test.assertEqual(this.stackOne.contains("hello"), true,
                "Assert Stack added value from array in to Stack");
            test.assertEqual(this.stackOne.contains("Brian"), true,
                "Assert Stack added value from array in to Stack");
            test.assertEqual(this.stackOne.getCount(), 2,
                "Assert stackOne contains 2 items");

            test.assertEqual(this.stackThree.containsAll(this.stackOne), true,
                "Assert collection accepts a Stack as an argument at construction time and adds the Stack values to the new Stack");
            test.assertEqual(this.stackThree.getCount(), 2,
                "Assert stackThree contains 2 items");
        }
    };

    /**
     * This tests
     * 1) Instantiate a simple Stack
     */
    var stackInstantiationTest = {

        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function() {
            this.testStack = new Stack();
        },

        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            test.assertTrue(this.testStack.isEmpty(),
                "Assert that the Stack is empty");
            test.assertTrue(Class.doesExtend(this.testStack, Stack),
                "Assert that the testStack extends Stack");
        }
    };

    /**
     * This tests
     * 1) creates a shallow clone of the Stack
     */
    var stackShallowCloneTest = {

        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function() {
            this.testStack = new Stack();
            this.testObject = {};
            this.testStack.add(this.testObject);
            this.testStackClone = this.testStack.clone();
        },

        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            test.assertTrue(this.testStack.contains(this.testObject),
                "Assert that the Stack contains the testObject");
            test.assertTrue(this.testStackClone.contains(this.testObject),
                "Assert that the cloned Stack contains the testObject");
        }
    };

    /**
     * This tests
     * 1) creates a deep clone of the Stack
     */
    var stackDeepCloneTest = {

        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function() {
            this.testStack = new Stack();
            this.testObject = {
                key: "value"
            };
            this.testStack.add(this.testObject);
            this.testStackClone = this.testStack.clone(true);
        },

        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            var testObjectClone = this.testStackClone.toArray()[0];
            test.assertTrue(this.testStack.contains(this.testObject),
                "Assert that the Stack contains the testObject");
            test.assertFalse(this.testStack.contains(testObjectClone),
                "Assert that the Stack does not contain the cloned object");
            test.assertTrue(this.testStackClone.contains(testObjectClone),
                "Assert that the cloned Stack contains the testObjectClone");
            test.assertFalse(this.testStackClone.contains(this.testObject),
                "Assert that the cloned Stack contains the testObjectClone");
            test.assertEqual(testObjectClone.key, "value",
                "Assert that the cloned object has key:'value'");
        }
    };

    /**
     * This tests
     * 1) Adding as simple string to a set
     * 2) Adding a second simple string to a set
     */
    var stackAddTest = {

        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function() {
            this.testValue1     = "value1";
            this.testValue2     = "value2";
            this.stack          = new Stack();
        },

        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            var result1 = this.stack.add(this.testValue1);
            test.assertTrue(this.stack.contains(this.testValue1),
                "Assert first item added to the Stack is contained within the Stack.");
            test.assertEqual(this.stack.getCount(), 1,
                "Assert count is 1 after adding 1 item.");
            test.assertTrue(result1,
                "Assert that true was returned when adding value1");

            var result2 = this.stack.add(this.testValue2);
            test.assertTrue(this.stack.contains(this.testValue1),
                "Assert first item added to the Stack is still contained within the Stack after adding a second item.");
            test.assertTrue(this.stack.contains(this.testValue2),
                "Assert second item added to the Stack is contained within the Stack.");
            test.assertEqual(this.stack.getCount(), 2,
                "Assert count is 2 after adding 2 items.");
            test.assertTrue(result2,
                "Assert that true was returned when adding value2");
        }
    };

    //-------------------------------------------------------------------------------
    // BugMeta
    //-------------------------------------------------------------------------------

    bugmeta.tag(stackConstructorTest).with(
        test().name("Stack - constructor test")
    );
    bugmeta.tag(stackInstantiationTest).with(
        test().name("Stack - instantiation test")
    );
    bugmeta.tag(stackShallowCloneTest).with(
        test().name("Stack - shallow clone test")
    );
    bugmeta.tag(stackDeepCloneTest).with(
        test().name("Stack - deep clone test")
    );
    bugmeta.tag(stackAddTest).with(
        test().name("Stack - add test")
    );
});


text:
@section('title', 'Login')

@section('content')

Login

                    @if(Session::get('login_errors'))

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

E-mail or password was incorrect, please try again

                    @endif

                    @if(Session::has('password_reset'))

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

Your password has been reset, please log in

                    @endif

                    {{ Form::open(['route' => 'auth.login']) }}

                            {{ Form::label('username', 'Username', [ 'class' => 'control-label' ]) }}
                            {{ Form::text('username', null, ['class'=>'form-control', 'placeholder' => 'Username...'])}}

                            {{ Form::label('password', 'Password', [ 'class' => 'control-label' ]) }}
                            {{ Form::password('password', ['class'=>'form-control', 'placeholder'=>'Password...'])}}

                                {{ Form::checkbox('remember') }} Remember me

                            <button type="submit" class="btn btn-primary btn-block btn-login">Login</button>

                    {{ Form::close() }}

OR

                     Login with Github

Forgot your password?

Don't have an account yet?

@stop


text:
package com.twigsntwines.daterangepicker;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import java.util.Calendar;

public class DatePickerFragment1 extends Fragment implements DatePicker.OnDateChangedListener {

    public DatePickerFragment1(){}

    @Override
    public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) {
        FromDatePickedListener listener = (FromDatePickedListener) getParentFragment();
        listener.OnFromDatePicked(i,i1,i2);
    }

    interface FromDatePickedListener{
        void OnFromDatePicked(int year, int month, int day);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_date_picker,container,false);

        DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
        Calendar cal = Calendar.getInstance();
        datePicker.init(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH),this);

        return view;
    }
}


text:
name: I want to file a bug or feature request about Flutter's CI infrastructure
about: As a contributor, you want to file an issue about the build/test/release
  infra, e.g. dashboards (http://flutter-dashboard.appspot.com), devicelab,
  LUCI (https://ci.chromium.org/p/flutter) etc.
title: ''
labels: 'team: infra'
assignees: ''

---

<!--  Thank you for contributing to Flutter!

      If you are filing a bug, please add the steps to reproduce, expected and actual results.

      If you are filing a feature request, please describe the use case and a proposal.

      If you are requesting a small infra task with P0 or P1 priority, please add it to the
      "Infra Ticket Queue" project with "New" column, explain why the task is needed and what
      actions need to perform (if you happen to know). No need to set an assignee; the infra oncall
      will triage and process the infra ticket queue.
-->


text:
<?php

$l['archive_fullversion'] = "Versión completa:";
$l['archive_replies'] = "Respuestas";
$l['archive_reply'] = "Respuesta";
$l['archive_pages'] = "Páginas:";
$l['archive_note'] = "Actualmente estas viendo una versión simplificada de nuestro contenido. Ver la versión completa con el formato correcto.";
$l['archive_reference_urls'] = "URLs de referencia";
$l['archive_nopermission'] = "Lo sentimos, pero no tienes permiso de acceder este recurso.";
$l['error_nothreads'] = "Actualmente no hay temas en este foro.";
$l['archive_not_found'] = "
404 No encontrado

El documento especificado no se ha encontrado en este servidor.
";
?>


text:
@import XCTest;

@interface JSZUnmockedTestCase : XCTestCase

@end

@implementation JSZUnmockedTestCase

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testSimpleNoMockingNetworkCall {
    [self performSimpleVerifiedNetworkCall:nil];
}

- (void)testSimpleNoMockingPerformanceNetworkCall {
    __weak typeof(self) wself = self;
    [self measureBlock:^{
        __strong typeof(wself) sself = wself;
        if (!sself) {
            return;
        }
        [sself performSimpleVerifiedNetworkCall:nil];
    }];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/pocket_money"
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:background="@color/colorPrimary"
                android:gravity="center"
                android:textColor="@color/white"
                android:textSize="32sp"
                tools:text="4500 iroha" />

            <android.support.v4.widget.ContentLoadingProgressBar
                android:id="@+id/progress_bar"
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:visibility="gone" />

            <ListView
                android:id="@+id/transaction_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <LinearLayout
                android:id="@+id/empty_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="vertical"
                tools:visibility="visible">

                <TextView
                    android:id="@+id/empty_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp"
                    android:gravity="center"
                    android:text="@string/transaction_history_not_found" />
            </LinearLayout>

        </LinearLayout>

    </android.support.v4.widget.SwipeRefreshLayout>
</layout>


text:
package org.apache.felix.framework.cache;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.*;

import org.apache.felix.framework.Logger;
import org.apache.felix.framework.util.SecureAction;
import org.apache.felix.framework.util.WeakZipFileFactory;
import org.osgi.framework.Constants;

/**
 *

 * This class, combined with <tt>BundleArchive</tt>, and concrete
 * <tt>BundleRevision</tt> subclasses, implement the Felix bundle cache.
 * It is possible to configure the default behavior of this class by
 * passing properties into Felix' constructor. The configuration properties
 * for this class are (properties starting with "<tt>felix</tt>" are specific
 * to Felix, while those starting with "<tt>org.osgi</tt>" are standard OSGi
 * properties):
 *

 *

 *
<tt>felix.cache.filelimit</tt> - The integer value of this string
 *       sets an upper limit on how many files the cache will open. The default
 *       value is zero, which means there is no limit.
 *

 *
<tt>org.osgi.framework.storage</tt> - Sets the directory to use as
 *       the bundle cache; by default bundle cache directory is
 *       <tt>felix-cache</tt> in the current working directory. The value
 *       should be a valid directory name. The directory name can be either absolute
 *       or relative. Relative directory names are relative to the current working
 *       directory. The specified directory will be created if it does
 *       not exist.
 *

 *
<tt>felix.cache.rootdir</tt> - Sets the root directory to use to
 *       calculate the bundle cache directory for relative directory names. If
 *       <tt>org.osgi.framework.storage</tt> is set to a relative name, by
 *       default it is relative to the current working directory. If this
 *       property is set, then it will be calculated as being relative to
 *       the specified root directory.
 *

 *
<tt>felix.cache.locking</tt> - Enables or disables bundle cache locking,
 *       which is used to prevent concurrent access to the bundle cache. This is
 *       enabled by default, but on older/smaller JVMs file channel locking is
 *       not available; set this property to <tt>false</tt> to disable it.
 *

 *
<tt>felix.cache.bufsize</tt> - Sets the buffer size to be used by
 *       the cache; the default value is 4096. The integer value of this
 *       string provides control over the size of the internal buffer of the
 *       disk cache for performance reasons.
 *

 *

 * For specific information on how to configure the Felix framework, refer
 * to the Felix framework usage documentation.
 *

 * @see org.apache.felix.framework.cache.BundleArchive
**/
public class BundleCache
{
    public static final String CACHE_BUFSIZE_PROP = "felix.cache.bufsize";
    public static final String CACHE_ROOTDIR_PROP = "felix.cache.rootdir";
    public static final String CACHE_LOCKING_PROP = "felix.cache.locking";
    public static final String CACHE_FILELIMIT_PROP = "felix.cache.filelimit";
    // TODO: CACHE - This should eventually be removed along with the code
    //       supporting the old multi-file bundle cache format.
    public static final String CACHE_SINGLEBUNDLEFILE_PROP = "felix.cache.singlebundlefile";

    protected static transient int BUFSIZE = 4096;

    private static transient final String CACHE_DIR_NAME = "felix-cache";
    private static transient final String CACHE_ROOTDIR_DEFAULT = ".";
    private static transient final String CACHE_LOCK_NAME = "cache.lock";
    static transient final String BUNDLE_DIR_PREFIX = "bundle";

    private static final SecureAction m_secureAction = new SecureAction();

    private final Logger m_logger;
    private final Map m_configMap;
    private final WeakZipFileFactory m_zipFactory;
    private final Object m_lock;

    public BundleCache(Logger logger, Map configMap)
        throws Exception
    {
        m_logger = logger;
        m_configMap = configMap;

        int limit = 0;
        String limitStr = (String) m_configMap.get(CACHE_FILELIMIT_PROP);
        if (limitStr != null)
        {
            try
            {
                limit = Integer.parseInt(limitStr);
            }
            catch (NumberFormatException ex)
            {
                limit = 0;
            }
        }
        m_zipFactory = new WeakZipFileFactory(limit);

        // Create the cache directory, if it does not exist.
        File cacheDir = determineCacheDir(m_configMap);
        if (!getSecureAction().fileExists(cacheDir))
        {
            if (!getSecureAction().mkdirs(cacheDir))
            {
                m_logger.log(
                    Logger.LOG_ERROR,
                    "Unable to create cache directory: " + cacheDir);
                throw new RuntimeException("Unable to create cache directory.");
            }
        }

        Object locking = m_configMap.get(CACHE_LOCKING_PROP);
        locking = (locking == null)
            ? Boolean.TRUE.toString()
            : locking.toString().toLowerCase();
        if (((String) locking).equals(Boolean.TRUE.toString()))
        {
            File lockFile = new File(cacheDir, CACHE_LOCK_NAME);
            FileChannel fc = null;
            FileOutputStream fos = null;
            try
            {
                if (!getSecureAction().fileExists(lockFile))
                {
                    fos = getSecureAction().getFileOutputStream(lockFile);
                    fc = fos.getChannel();
                }
                else
                {
                    fos = getSecureAction().getFileOutputStream(lockFile);
                    fc = fos.getChannel();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (fos != null) fos.close();
                    if (fc != null) fc.close();
                }
                catch (Exception ex2)
                {
                    // Ignore.
                }
                throw new Exception("Unable to create bundle cache lock file: " + ex);
            }
            try
            {
                m_lock = fc.tryLock();
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to lock bundle cache: " + ex);
            }
        }
        else
        {
            m_lock = null;
        }
    }

    public synchronized void release()
    {
        if (m_lock != null)
        {
            try
            {
                ((FileLock) m_lock).release();
                ((FileLock) m_lock).channel().close();
            }
            catch (Exception ex)
            {
                // Not much we can do here, just log it.
                m_logger.log(
                    Logger.LOG_WARNING,
                    "Exception releasing bundle cache.", ex);
            }
        }
    }

    /* package */ static SecureAction getSecureAction()
    {
        return m_secureAction;
    }

    public synchronized void delete() throws Exception
    {
        // Delete the cache directory.
        File cacheDir = determineCacheDir(m_configMap);
        deleteDirectoryTree(cacheDir);
    }

    public BundleArchive[] getArchives()
        throws Exception
    {
        // Get buffer size value.
        try
        {
            String sBufSize = (String) m_configMap.get(CACHE_BUFSIZE_PROP);
            if (sBufSize != null)
            {
                BUFSIZE = Integer.parseInt(sBufSize);
            }
        }
        catch (NumberFormatException ne)
        {
            // Use the default value.
        }

        // Create the existing bundle archives in the directory, if any exist.
        File cacheDir = determineCacheDir(m_configMap);
        List archiveList = new ArrayList();
        File[] children = getSecureAction().listDirectory(cacheDir);
        for (int i = 0; (children != null) && (i < children.length); i++)
        {
            // Ignore directories that aren't bundle directories or
            // is the system bundle directory.
            if (children[i].getName().startsWith(BUNDLE_DIR_PREFIX) &&
                !children[i].getName().equals(BUNDLE_DIR_PREFIX + Long.toString(0)))
            {
                // Recreate the bundle archive.
                try
                {
                    archiveList.add(
                        new BundleArchive(
                            m_logger, m_configMap, m_zipFactory, children[i]));
                }
                catch (Exception ex)
                {
                    // Log exception and remove bundle archive directory.
                    m_logger.log(Logger.LOG_ERROR,
                        "Error reloading cached bundle, removing it: " + children[i], ex);
                    deleteDirectoryTree(children[i]);
                }
            }
        }

        return (BundleArchive[])
            archiveList.toArray(new BundleArchive[archiveList.size()]);
    }

    public BundleArchive create(long id, int startLevel, String location, InputStream is)
        throws Exception
    {
        File cacheDir = determineCacheDir(m_configMap);

        // Construct archive root directory.
        File archiveRootDir =
            new File(cacheDir, BUNDLE_DIR_PREFIX + Long.toString(id));

        try
        {
            // Create the archive and add it to the list of archives.
            BundleArchive ba =
                new BundleArchive(
                    m_logger, m_configMap, m_zipFactory, archiveRootDir,
                    id, startLevel, location, is);
            return ba;
        }
        catch (Exception ex)
        {
            if (m_secureAction.fileExists(archiveRootDir))
            {
                if (!BundleCache.deleteDirectoryTree(archiveRootDir))
                {
                    m_logger.log(
                        Logger.LOG_ERROR,
                        "Unable to delete the archive directory: "
                            + archiveRootDir);
                }
            }
            throw ex;
        }
    }

    /**
     * Provides the system bundle access to its private storage area; this
     * special case is necessary since the system bundle is not really a
     * bundle and therefore must be treated in a special way.
     * @param fileName the name of the file in the system bundle's private area.
     * @return a <tt>File</tt> object corresponding to the specified file name.
     * @throws Exception if any error occurs.
    **/
    public File getSystemBundleDataFile(String fileName)
        throws Exception
    {
        // Make sure system bundle directory exists.
        File sbDir = new File(determineCacheDir(m_configMap), BUNDLE_DIR_PREFIX + Long.toString(0));

        // If the system bundle directory exists, then we don't
        // need to initialize since it has already been done.
        if (!getSecureAction().fileExists(sbDir))
        {
            // Create system bundle directory, if it does not exist.
            if (!getSecureAction().mkdirs(sbDir))
            {
                m_logger.log(
                    Logger.LOG_ERROR,
                    "Unable to create system bundle directory.");
                throw new IOException("Unable to create system bundle directory.");
            }
        }

        // Do some sanity checking.
        if ((fileName.length() > 0) && (fileName.charAt(0) == File.separatorChar))
            throw new IllegalArgumentException("The data file path must be relative, not absolute.");
        else if (fileName.indexOf("..") >= 0)
            throw new IllegalArgumentException("The data file path cannot contain a reference to the \"..\" directory.");

        // Return the data file.
        return new File(sbDir, fileName);
    }

    //
    // Static file-related utility methods.
    //

    /**
     * This method copies an input stream to the specified file.
     * @param is the input stream to copy.
     * @param outputFile the file to which the input stream should be copied.
    **/
    static void copyStreamToFile(InputStream is, File outputFile)
        throws IOException
    {
        OutputStream os = null;

        try
        {
            os = getSecureAction().getFileOutputStream(outputFile);
            os = new BufferedOutputStream(os, BUFSIZE);
            byte[] b = new byte[BUFSIZE];
            int len = 0;
            while ((len = is.read(b)) != -1)
            {
                os.write(b, 0, len);
            }
        }
        finally
        {
            if (is != null) is.close();
            if (os != null) os.close();
        }
    }

    static boolean deleteDirectoryTree(File target)
    {
        if (!deleteDirectoryTreeRecursive(target))
        {
            // We might be talking windows and native libs -- hence,
            // try to trigger a gc and try again. The hope is that
            // this releases the classloader that loaded the native
            // lib and allows us to delete it because it then
            // would not be used anymore.
            System.gc();
            System.gc();
            return deleteDirectoryTreeRecursive(target);
        }
        return true;
    }

    //
    // Private methods.
    //

    private static File determineCacheDir(Map configMap)
    {
        File cacheDir;

        // Check to see if the cache directory is specified in the storage
        // configuration property.
        String cacheDirStr = (String) configMap.get(Constants.FRAMEWORK_STORAGE);
        // Get the cache root directory for relative paths; the default is ".".
        String rootDirStr = (String) configMap.get(CACHE_ROOTDIR_PROP);
        rootDirStr = (rootDirStr == null) ? CACHE_ROOTDIR_DEFAULT : rootDirStr;
        if (cacheDirStr != null)
        {
            // If the specified cache directory is relative, then use the
            // root directory to calculate the absolute path.
            cacheDir = new File(cacheDirStr);
            if (!cacheDir.isAbsolute())
            {
                cacheDir = new File(rootDirStr, cacheDirStr);
            }
        }
        else
        {
            // If no cache directory was specified, then use the default name
            // in the root directory.
            cacheDir = new File(rootDirStr, CACHE_DIR_NAME);
        }

        return cacheDir;
    }

    private static boolean deleteDirectoryTreeRecursive(File target)
    {
    	if (!getSecureAction().fileExists(target))
        {
            return true;
        }

        if (getSecureAction().isFileDirectory(target))
        {
            File[] files = getSecureAction().listDirectory(target);
            if (files != null)
            {
                for (int i = 0; i < files.length; i++)
                {
                    deleteDirectoryTreeRecursive(files[i]);
                }
            }
        }

        return getSecureAction().deleteFile(target);
    }
}


text:
FOUNDATION_EXPORT double XcodeVersionNumber;

//! Project version string for Xcode.
FOUNDATION_EXPORT const unsigned char XcodeVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Xcode/PublicHeader.h>


text:
This plugin allows Radargun to run performance tests against Couchbase server using the Couchbase Java SDK (version 2.7.4).

## Creating a Cluster

### Docker

Couchbase server can be setup and configured using Docker, with official images available on [DockerHub](https://hub.docker.com/_/couchbase). Instructions on how to start the container are available on there too.

### Manual install

Couchbase server can also be installed using a direct download available from [Couchbase.com/downloads](https://www.couchbase.com/downloads). Download and install instructions are available on the website.

## Setting up the Cluster

Once you have a running cluster, you need to setup the cluster before it can service requests. This is done by opening the web UI at [localhost:8091](http://localhost:8091) and following create new cluster forms (only the KV service is required to run Radargun tests).

## Creating the 'default' bucket

By default, the plugin expects to use a bucket called _default_ to store and retrieve values from. You can create a bucket using the *bucket* tab and selecting _new bucket_.


text:
from collections import defaultdict
import operator
import re
from math import log
import random
import os
from os import listdir
from os.path import isfile, join, isdir
from os import walk
import pandas
import filereader as fr

filename = 'distinctive_words.txt'

"""
This function prints the top 10 words associated with each of the 20 topics into the file "distinctive_words.txt".
It is used only in the part2 of this assignment. Input is

all_words - the word count data structure created by train() function
"""
def top10(all_words):
	if os.path.exists(filename):
		os.remove(filename)

	output = open(filename, 'w')
	for topic in all_words:
		output.write('-'*50 + "\n")
		output.write("Top 10 words for " + topic + "\n")
		output.write('-'*50 + "\n")
		top_words = sorted(((k, v) for k,v in all_words[topic].iteritems()), key=lambda tup: tup[1], reverse=True)
		for word in top_words[:10]:
			output.write(str(word[0]) + " - " + str(int(word[1])) + "\n")

	output.close()
	print "Output written to file", filename

"""
This function prints the top 10 words associated with spam and non-spam.
It also prints the last 10 words associated with spam - this is because I found the requirement of part1 a little ambiguous.
The input is

all_words - the word count data structure created by train() function
"""
def spamwords(all_words):
	if 'spam' not in all_words and 'notspam' not in all_words:
		print "This model is not for spam classification"
	else:
		top_words = sorted(((k, v) for k,v in all_words['spam'].iteritems()), key=lambda tup: tup[1], reverse=True)
		print '-'*50
		print "Top 10 words associated with spam"
		print '-'*50
		for word in top_words[:10]:
			print word[0], "-", int(word[1])

		print ""

		print '-'*50
		print "Last 10 words associated with spam"
		print '-'*50
		for word in top_words[-10:]:
			print word[0], "-", int(word[1])

		print ""

		top_words = sorted(((k, v) for k,v in all_words['notspam'].iteritems()), key=lambda tup: tup[1], reverse=True)
		print '-'*50
		print "Top 10 words associated with notspam"
		print '-'*50
		for word in top_words[:10]:
			print word[0], "-", int(word[1])

		print ""

		print '-'*50
		print "Last 10 words associated with notspam"
		print '-'*50
		for word in top_words[-10:]:
			print word[0], "-", int(word[1])

		print ""

def defaultvalue():
	return 0.0000000001

def defaultcollection():
	return defaultdict(defaultvalue)

"""
Function to train the Bayes model. This function is common for the part1 (spam, non-spam) and part2 (topics) case.
For part2 it implements the EM algorithm when the fraction is < 1. The number of iterations for EM are kept to 3 through experimental results for
different values on this dataset. The idea of EM algorithm is pretty simple
E step - assumes the topic assignment for each document is fixed and then calculates the word likelihood ie. P(W|T) over all topics
M step - assumes the word likelihoods are fixed and then calculates the posterior i.e P(T|w1 w2 .. wn) where w1 .. wn belong to a document D.
This is done for all documents D in the train dataset.

The input arguments for it are in the form of

train_data - this is the data structure returned by the readdata() method in filereader module
fraction - is the fraction input by the user. This is applicable only for part2 and for part1 it takes on its default assignment of 1
part - for which part of the assignment is the function being called viz. "part1" or "part2"
featuretype - can take values of "binary" or "frequency". It mainly controls how the feature vectors are implemented
"""
def train(train_data, part, featuretype="frequency", fraction=1):
	topics = train_data['topics']
	document_topics = defaultdict(lambda: topics[0])

	model = {}

	iterations = 3 if fraction < 1 else 1
	for i in range(iterations):
		all_words = defaultdict(defaultcollection)

		topic_likelihood = defaultdict(float)
		topicwise_counts = defaultdict(float)

		# if fraction == 1 no need to run the EM algorithm as we know all the labels
		if fraction < 1:
			print "E step for iteration", i+1

		for doc in train_data['docs']:
			for word in doc:
				if word != "class_name" and word != "document_name":

					if i == 0:
						# This is the part which does the initial assignment of topics to document based on the value of a randomly generated number
						# from a uniform probability distribution
						current_topic = random.choice(topics) if random.random() > fraction else doc['class_name']
						document_topics[doc['document_name']] = current_topic
					else:
						current_topic = document_topics[doc['document_name']]

					if featuretype == "frequency":
						topic_likelihood[current_topic] += 1
						all_words[current_topic][word] += 1
						topicwise_counts[current_topic] += 1
					elif featuretype == "binary":
						all_words[current_topic][word] = 1

		if featuretype == "binary":
			for t in topics:
				topic_likelihood[t] += len(all_words[t])
				topicwise_counts[t] += len(all_words[t])

		total = sum(topic_likelihood.itervalues(), 0.0)
		topic_likelihood = {k: v / total for k, v in topic_likelihood.iteritems()}

		# if fraction == 1 no need to run the EM algorithm as we know all the labels. Thus the M step is redundant and is skipped
		if fraction < 1:
			correct = 0.0
			total = 0.0

			print "M step for iteration", i+1
			for doc in train_data['docs']:
				total += 1
				topic_assignment = defaultdict(lambda: 0.0)
				for word in doc:
					if word != "class_name" and word != "document_name":
						for candidate in topics:
							topic_assignment[candidate] += log((all_words[candidate][word] / topicwise_counts[candidate]), 2)

				for topic in topics:
					topic_assignment[topic] += log(topic_likelihood[candidate], 2)

				document_topics[doc['document_name']] = max(topic_assignment.iteritems(), key=operator.itemgetter(1))[0]

				if max(topic_assignment.iteritems(), key=operator.itemgetter(1))[0] == doc['class_name']:
					correct += 1

			print "Accuracy in iteration", i+1, "is", str(int(correct)) + "/" + str(int(total)), str(round(((correct / total) * 100), 2)) + "%"

	top10(all_words) if part == "part2" else spamwords(all_words)

	# final structure contained in the dictionary to be pickled
	model['words'] = all_words
	model['topic_likelihood'] = topic_likelihood
	model['topicwise_counts'] = topicwise_counts
	model['topics'] = topics
	return model

"""
This function tests the trained Naive Bayes model on the data contained in test_dir.

model - the trained model returned by the train() function
test_dir - directory which contains test documents organized into directories corresponding to actual topic names
"""
def test(model, test_dir, stopwords):
	topic_likelihood = model['topic_likelihood']
	topics = model['topics']
	all_words = model['words']
	topicwise_counts = model['topicwise_counts']

	print sum(len(v) for k,v in all_words.iteritems()), "words present in the vocabulary"

	confusion_matrix = [[0]*len(topics) for i in range(len(topics))]

	average = 0.0
	average_total = 0.0
	for t in topics:
		correct = 0.0
		total = 0.0
		for f in listdir(join(os.getcwd(), test_dir, t)):
			total += 1
			topic_assignment = defaultdict(lambda: 0.0)
			for line in open(join(os.getcwd(), test_dir, t, f)):
				for word in line.split():
					word = fr.cleanword(word)

					if word and word not in stopwords:
						for candidate in topics:
							topic_assignment[candidate] += log((all_words[candidate][word] / topicwise_counts[candidate]), 2)

			for topic in topics:
				topic_assignment[topic] += log(topic_likelihood[candidate], 2)

			predicted_topic = max(topic_assignment.iteritems(), key=operator.itemgetter(1))[0]
			if predicted_topic == t:
				correct += 1
			confusion_matrix[topics.index(t)][topics.index(predicted_topic)] += 1

		average_total += total
		average += correct
		print "Accuracy for", t, "is", str(int(correct)) + "/" + str(int(total)), str(round(((correct / total) * 100), 2)) + "%"

	print "Average accuracy is", str(round(((average / average_total) * 100), 2)) + "%"

	print "\n", "Here is the confusion matrix"
	matrix = pandas.DataFrame(confusion_matrix, topics, topics)
	print matrix


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

namespace IronJS.Runtime
{
    public static class BoxFields
    {
        public const string Bool = "Bool";
        public const string Number = "Number";
        public const string Clr = "Clr";
        public const string Undefined = "Clr";
        public const string String = "String";
        public const string SuffixString = "SuffixString";
        public const string Object = "Object";
        public const string Function = "Func";
    }
}


text:
package org.apache.camel.spring;

import javax.management.ObjectName;

import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Test that verifies JMX can be disabled via Spring.
 *
 *
 */
public class DisableJmxAgentTest extends DefaultJMXAgentTest {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/spring/disableJmxConfig.xml");
    }

    @Override
    @Test
    public void testQueryMbeans() throws Exception {
        // whats the numbers before, because the JVM can have left overs when unit testing
        int before = mbsc.queryNames(new ObjectName("org.apache.camel" + ":type=consumers,*"), null).size();

        // start route should enlist the consumer to JMX if JMX was enabled
        context.getRouteController().startRoute("foo");

        int after = mbsc.queryNames(new ObjectName("org.apache.camel" + ":type=consumers,*"), null).size();

        assertEquals("Should not have added consumer to JMX", before, after);
    }

}


text:
class IgnitionLaunch6 < Formula
  desc "Launch libraries for robotics applications"
  homepage "https://github.com/ignitionrobotics/ign-launch"
  url "https://github.com/ignitionrobotics/ign-launch.git", branch: "main"
  version "5.999.999~0~20211227"
  license "Apache-2.0"

  depends_on "cmake" => :build
  depends_on "pkg-config" => :build

  depends_on "ignition-cmake2"
  depends_on "ignition-common5"
  depends_on "ignition-gazebo7"
  depends_on "ignition-gui7"
  depends_on "ignition-msgs9"
  depends_on "ignition-plugin1"
  depends_on "ignition-tools"
  depends_on "ignition-transport12"
  depends_on "qt@5"
  depends_on "tinyxml2"

  def install
    system "cmake", ".", *std_cmake_args
    system "make", "install"
  end

  test do
    ENV["IGN_CONFIG_PATH"] = "#{opt_share}/ignition"
    system "ign", "launch", "--versions"
    # check for Xcode frameworks in bottle
    cmd_not_grep_xcode = "! grep -rnI 'Applications[/]Xcode' #{prefix}"
    system cmd_not_grep_xcode
  end
end


text:
# Bare Conductive Touch Board GPIO Inverter Example

A GPIO inverter written using the MPR121 as a GPIO extender on the [Bare Conductive Touch Board](http://www.bareconductive.com/touch-board). Reads an MPR121 electrode and outputs the inverse to drive an LED connected to another electrode.

Needs an LED with a series current limiting resistor connected between E11 and ground. 470 ohms is good for most LEDs. E10 is set as a digital input with an internal pullup. Leaving E10 unconnected turns the LED off. Connecting E10 to ground turns the LED on.

##### TODO: diagram

## Requirements

* [Arduino](http://arduino.cc/en/Main/Software) 1.0.5 or 1.5.6+ (1.5.6+ is strongly preferred).

* Arduino's instructions for installing libraries are available [here](http://arduino.cc/en/Guide/Libraries)

* [Bare Conductive MPR121 library](https://github.com/BareConductive/mpr121/)

## Install

This is normally installed as an example within the MPR121 library, but if you want to manually install it into your Arduino sketchbook, here is how to do it.

1. Close the Arduino IDE if you have it open.
1. Download the [.zip](https://github.com/BareConductive/mpr121/archive/public.zip) or clone the repository to your local machine - if downloading the .zip, extract the contents somewhere that suits you.
1. Take the **GPIOinverter** folder and move it to **Arduino Sketchbook Folder**. This will be different for each operating system:

	**Windows**

	Libraries\\Documents\\Arduino

	or

	My Documents\\Arduino

	**Mac**

	Documents/Arduino

	**Linux (Ubuntu)**

	Home/Arduino

	If this folder does not exist, create it first.
1. Reopen the Arduino IDE - you should now be able to open the sketch in the **File -> Sketchbook** menu.


text:
/* Generated code */

interface ResourceLink {

	uri?: string;
}

export default ResourceLink;


text:
file(REMOVE_RECURSE
  "CMakeFiles/03_Insertion_Sort.dir/main.cpp.obj"
  "03_Insertion_Sort.pdb"
  "03_Insertion_Sort.exe"
  "03_Insertion_Sort.exe.manifest"
  "lib03_Insertion_Sort.dll.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/03_Insertion_Sort.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
package org.sewas.domain.model;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

/**
 * Created by sebastian on 21/05/17.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE,
        setterVisibility=JsonAutoDetect.Visibility.NONE, creatorVisibility=JsonAutoDetect.Visibility.NONE)
public class MatchResult {

    @JsonProperty("PointsTeam1")
    private int PointsTeam1;

    @JsonProperty("PointsTeam2")
    private int PointsTeam2;

    @JsonProperty("ResultDescription")
    private String ResultDescription;

    @JsonProperty("ResultID")
    private int ResultID;

    @JsonProperty("ResultName")
    private String ResultName;

    @JsonProperty("ResultOrderID")
    private int ResultOrderID;

    @JsonProperty("ResultTypeID")
    private int ResultTypeID;

    public int getPointsTeam1() {
        return PointsTeam1;
    }

    public void setPointsTeam1(int pointsTeam1) {
        PointsTeam1 = pointsTeam1;
    }

    public int getPointsTeam2() {
        return PointsTeam2;
    }

    public void setPointsTeam2(int pointsTeam2) {
        PointsTeam2 = pointsTeam2;
    }

    public String getResultDescription() {
        return ResultDescription;
    }

    public void setResultDescription(String resultDescription) {
        ResultDescription = resultDescription;
    }

    public int getResultID() {
        return ResultID;
    }

    public void setResultID(int resultID) {
        ResultID = resultID;
    }

    public String getResultName() {
        return ResultName;
    }

    public void setResultName(String resultName) {
        ResultName = resultName;
    }

    public int getResultOrderID() {
        return ResultOrderID;
    }

    public void setResultOrderID(int resultOrderID) {
        ResultOrderID = resultOrderID;
    }

    public int getResultTypeID() {
        return ResultTypeID;
    }

    public void setResultTypeID(int resultTypeID) {
        ResultTypeID = resultTypeID;
    }
}


text:
namespace console {;

void whoami(Ogre::StringVector&);
void version(Ogre::StringVector&);
void make(Ogre::StringVector& vec);
void sudo(Ogre::StringVector& vec);

}	// namespace console


text:
//
//  ZXNavTitleView.m
//  ZXNavigationBar
//
//  Created by 李兆祥 on 2020/3/12.
//  Copyright © 2020 ZXLee. All rights reserved.
//  https://github.com/SmileZXLee/ZXNavigationBar
//  V1.4.1

#import "ZXNavTitleView.h"

@implementation ZXNavTitleView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
package com.kurukurupapa.pffsimu.test;

public interface SlowTests {

}


text:
import unittest

from project.util import BaseTestCase

class TestMainViews(BaseTestCase):

    def test_main_route_does_not_require_login(self):
        # Ensure main route requres a logged in user.
        response = self.client.get('/', follow_redirects=True)
        self.assertTrue(response.status_code == 200)
        self.assertTemplateUsed('main/index.html')

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


text:
var kue = require('kue');
var cluster = require('cluster');

var through2 = require('through2');
var graft = require('graft')();
var spdy = require('graft/spdy');  // Buggy ByteStream on Windows
var ws = require('graft/ws');  // ByteStream Ok on Windows

var fs = require('fs');
var path = require('path');
var zlib = require('zlib');
var domain = require('domain');

var Mailer = require('./lib/mailer');

/* Config-variables */

var config = require('./config');
var clusterWorkerSize = 1;

/* System variables */

// Nodemailer Transporter to smtp-relay.gmail.com
var mailout = new Mailer(config.mailoutOptions);

// Mailin will store jobs to Microservices (retry with backoff)
var jobs = kue.createQueue({ redis: config.redisOptions });
jobs.on('error', function(err) { console.log( 'Oops... ', err ); });  // Must be bound or will crash
process.once( 'uncaughtException', function(err){
  console.error( 'Something bad happened, uncaughtException:', err );
  jobs.shutdown( 1000, function(err2){
    console.error( 'Kue shutdown result: ', err2||'OK' );
    process.exit( 0 );
  });
});

// Build job processing function with seperate graft streams (so they don't block on each other)
var buildProcessGraftJob = function(graft) {
  /* Function called when a pending kue job needs to be processed. */
  return (function processGraftJob(job, ctx, done) {
    console.log("Job %d processing...", job.id);

    var d = domain.create();
    d.on('error', function(err) {
      done(err);
    });

    d.run(function() {
      // Get persisted graftMessage from job data
      var msg = job.data.graftMessage;
      if (msg) { job.progress(1, 8); }

      // Convert filePaths into filestreams that can be sent via graft jschan
      if (msg.filePaths) {
        var fileStreams = {};
        msg.filePaths.forEach(function(filePath) {
          var fileName = path.basename(filePath);
          var fileStream = fs.createReadStream(filePath);

          fileStream.on('open', function() { console.log('open event in origin file'); });
          fileStream.on('error', function() { console.log('error event in origin file'); });
          fileStream.on('end', function() { console.log('end event in origin file'); });
          fileStream.on('close', function() { console.log('close event in origin file'); });
          //fileStream.push(null);

          fileStreams[fileName] = fileStream;
          job.progress(2, 8, 'files-some-ready');
          job.log("File ready: %s", fileName);
        });
        msg.fileStreams = fileStreams;
        job.progress(3, 8, 'files-all-ready');
      }

      // Reply from microservice (Warning: might not receive any reply on returnChannel)
      var results = [];
      var isError = false;
      msg.returnChannel = graft.ReadChannel();
      msg.returnChannel.pipe(through2.obj(function(msg, enc, cb) {
        console.dir(msg);
        job.progress(6, 8, 'channel-returning-data');

        if (msg.error) {
          isError = true;
          done(msg.error);
        } else if ('log' in msg) {
          if ( Array.isArray(msg.log) ) {
            job.log.apply(job, msg.log);
          } else if ('length' in msg.log ) {
            job.log.apply(job, Array.prototype.slice.call(msg.log));
          }
        } else if ('result' in msg) {
          results.push(msg.result);
          job.log("Result: %s", JSON.stringify(msg.result) );
        }

        cb();
      }));
      msg.returnChannel.on('unpipe', function() {
        job.progress(7, 8, 'channel-ended');
        job.log("Microservice response ended with %d results.", results.length);

        if (!isError) {
          if (results.length === 0) {
            done(new Error("Graft returnChannel ended with no results. Likely timeout issue."));
          } else {
            done(null, results);
          }
        }
      });

      // Send Request to microservices
      job.progress(4, 8, 'request-sending');
      job.log("Sending request to Microservice");
      graft.write(msg);  // Note: Request message dispatched by graft.where() pattern-matching
      job.progress(5, 8, 'request-sent');
      job.log("Sent request to Microservice");
    });
  });
};

if (cluster.isMaster) {
  /* Master Logic */

  /* Event emitted when a pending kue job has completed. */
  jobs.on('job complete', function(id, result) {
    console.log("Job %d completed.", id);
    kue.Job.get(id, function(err, job) {
      if (err) { console.error(err); return; }

      // Store the result in Kue db
      //job.data.success = true;
      //job.set('data', JSON.stringify(job.data));

      // Send the result back to the email sender.
      // Email balik hasil nya ke pengirim email.
      if (job.data.sourceMail) { mailout.replyToEmail(job.data.sourceMail, "Job " + job.id + " Completed: \n" + result); }
    });
  });

  /* Event emitted when a pending kue job has failed an attempt. */
  //jobs.on('job failed attempt', function(id, errorMsg, attempts) {});
  //  console.log("Job %d failed attempt %d on queue...", id, attempts);
  //  if (job.data.sourceMail) { mailout.replyToEmail(job.data.sourceMail, "Job " + job.id + " Retry due to: \n" + errorMsg); }
  //});

  /* Event emitted when a pending kue job has failed with no further attempts left. */
  jobs.on('job failed', function(id, errorMsg) {
    console.log("Job %d failed all attempts on queue.", id);
    kue.Job.get(id, function(err, job) {
      if (err) { console.error(err); return; }

      // Send the result back to the email sender.
      // Email balik hasil nya ke pengirim email.
      if (job.data.sourceMail) { mailout.replyToEmail(job.data.sourceMail, "Job " + job.id + " Failed: \n" + errorMsg); }
    });
  });

  // Fork workers in cluster that will process jobs
  for (var i = 0; i < clusterWorkerSize; i++) {
    cluster.fork();
  }

  // Recover all stuck active jobs
  jobs.active( function( err, ids ) {
    ids.forEach( function( id ) {
      kue.Job.get( id, function( err, job ) {
        // Your application should check if job is a stuck one
        job.inactive();
      });
    });
  });

} else {
  /* Worker Logic */
  var processGraftJob = buildProcessGraftJob(graft);

  // RENE Microservice Instance
  //var CpsRene = require('./lib/cps-rene');
  //var rene = new CpsRene(config.cpsReneOptions);
  //var reneSrv = rene.getService();

  var reneSrv = ws.client({ host: '10.0.4.15', port: 6001, reconnectTimeout: 1000 });
  reneSrv.on('ready', function() { console.log("ready event on rene microservice"); });
  reneSrv.session.on('error', function() { console.log("error event on rene microservice"); });
  reneSrv.session.on('close', function() { console.log("close event on rene microservice"); });

  if (config.cpsReneOptions.targets !== null && typeof config.cpsReneOptions.targets === 'object') {
    Object.keys(config.cpsReneOptions.targets).forEach(function(target, idx) {
      // Route graft jobs to relevant microservice
      graft.where({ systemId: target }, reneSrv);
      // Register event handler such that pending kue job will be processed
      reneSrv.once('ready', function() {
        jobs.process(target, 1, function(job, ctx, done) {
          if (!ctx.isMicroservicePauseBinded && reneSrv.session) {
            var resume = function() { console.log("resuming %s", target); ctx.resume(); };
            var pause = function() { console.log("pausing %s", target); reneSrv.once('ready', resume); ctx.pause(); };

            reneSrv.session.on('error', pause);
            reneSrv.session.on('close', pause);
            ctx.isMicroservicePauseBinded = true;
          }

          if (Object.keys(job.data).length > 1) {
            processGraftJob(job, ctx, done);
          } else {
            done();
          }
        });

        // Create initial job to initialize worker context
        jobs.create(target, { title: "Ready" }).save();
      });
    });
  }

  // Accurate Microservice Instance
  //var CpsAccurate = require('./lib/cps-accurate');
  //var accurate = new CpsAccurate(config.cpsAccurateOptions);
  //var accurateSrv = accurate.getService();

  var accurateSrv = ws.client({ host: '10.0.4.15', port: 6002, reconnectTimeout: 1000 });
  accurateSrv.on('ready', function() { console.log("ready event on accurate microservice"); });
  accurateSrv.session.on('error', function() { console.log("error event on accurate microservice"); });
  accurateSrv.session.on('close', function() { console.log("close event on accurate microservice"); });

  if (config.cpsAccurateOptions.targets !== null && typeof config.cpsAccurateOptions.targets === 'object') {
    Object.keys(config.cpsAccurateOptions.targets).forEach(function(target, idx) {
      // Route graft jobs to relevant microservice
      graft.where({ systemId: target }, accurateSrv);
      // Register event handler such that pending kue job will be processed
      accurateSrv.once('ready', function() {
        jobs.process(target, 1, function(job, ctx, done) {
          if (!ctx.isMicroservicePauseBinded && accurateSrv.session) {
            var resume = function() { console.log("resuming %s", target); ctx.resume(); };
            var pause = function() { console.log("pausing %s", target); accurateSrv.once('ready', resume); ctx.pause(); };

            accurateSrv.session.on('error', pause);
            accurateSrv.session.on('close', pause);
            ctx.isMicroservicePauseBinded = true;
          }

          if (Object.keys(job.data).length > 1) {
            processGraftJob(job, ctx, done);
          } else {
            done();
          }
        });

        // Create initial job to initialize worker context
        jobs.create(target, { title: "Ready" }).save();
      });
    });
  }

  console.log("Worker %s ready to process graft jobs.", cluster.worker.id);
}


text:
@interface AsyncCanceler : NSObject<Cancelable> {
	NSObject<Cancelable>* cancelable;
}
@property (nonatomic,retain) NSObject<Cancelable>* cancelable;

+(AsyncCanceler*)cancelerFor:(NSObject<Cancelable>*)cancelable;

@end


text:
package com.github.yoskhdia.sqscala

import com.amazonaws.handlers.AsyncHandler
import com.amazonaws.services.sqs.model._
import com.github.yoskhdia.sqscala.serializer.MessageSerializer

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.concurrent.{Future, Promise}
import scala.language.postfixOps

trait SqsQueue {

  def name: QueueName

  def url: QueueUrl

  protected def client: SqsClient

  def receive[T](waitTime: Option[FiniteDuration] = None, visibilityTimeout: Option[FiniteDuration] = None)(implicit serializer: MessageSerializer[T]): Future[Option[Message[T]]] = {
    val request = new ReceiveMessageRequest()
      .withQueueUrl(url.simplified)
      .withMaxNumberOfMessages(1)
    waitTime.foreach(d => request.withWaitTimeSeconds(d.toSeconds.toInt))
    visibilityTimeout.foreach(d => request.withVisibilityTimeout(d.toSeconds.toInt))

    val p = Promise[Option[Message[T]]]()
    client.awsClient.receiveMessageAsync(request, new AsyncHandler[ReceiveMessageRequest, ReceiveMessageResult] {
      override def onError(exception: Exception): Unit = p.failure(exception)

      override def onSuccess(request: ReceiveMessageRequest, result: ReceiveMessageResult): Unit = {
        result.getMessages.asScala.headOption.fold(p.success(None)) { message =>
          p.success(Some(
            Message(
              MessageId(message.getMessageId),
              serializer.deserialize(message.getBody),
              ReceiptHandle(message.getReceiptHandle),
              message.getAttributes.asScala.toMap,
              message.getMessageAttributes.asScala.toMap
            )
          ))
        }
      }
    })
    p.future
  }

  def send[T](message: T, delay: Option[FiniteDuration] = None, messageAttributes: Map[String, MessageAttributeValue] = Map.empty[String, MessageAttributeValue])(implicit serializer: MessageSerializer[T]): Future[MessageId] = {
    val request = new SendMessageRequest()
      .withQueueUrl(url.simplified)
      .withMessageBody(serializer.serialize(message))
    messageAttributes.foreach { case (key, value) =>
      request.addMessageAttributesEntry(key, value)
    }
    delay.foreach(d => request.withDelaySeconds(d.toSeconds.toInt))

    val p = Promise[MessageId]()
    client.awsClient.sendMessageAsync(request, new AsyncHandler[SendMessageRequest, SendMessageResult] {
      override def onError(exception: Exception): Unit = p.failure(exception)

      override def onSuccess(request: SendMessageRequest, result: SendMessageResult): Unit = p.success(MessageId(result.getMessageId))
    })
    p.future
  }

  def delete(receiptHandle: ReceiptHandle): Future[Unit] = {
    val request = new DeleteMessageRequest()
      .withQueueUrl(url.simplified)
      .withReceiptHandle(receiptHandle.value)

    val p = Promise[Unit]()
    client.awsClient.deleteMessageAsync(request, new AsyncHandler[DeleteMessageRequest, DeleteMessageResult] {
      override def onError(exception: Exception): Unit = p.failure(exception)

      override def onSuccess(request: DeleteMessageRequest, result: DeleteMessageResult): Unit = p.success(Unit)
    })
    p.future
  }
}