text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Tags on Hadrien Mary</title>
    <link>https://hadim.fr/tags/</link>
    <description>Recent content in Tags on Hadrien Mary</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>

	<atom:link href="https://hadim.fr/tags/index.xml" rel="self" type="application/rss+xml" />

  </channel>
</rss>


text:
@implementation LSFormSwitchCell

- (void)onInitWithLabel:(NSString *)label value:(id)value andRule:(NSDictionary *)rule{
    self.textLabel.text = label;
    _switchView = [[UISwitch alloc] init];
    [self addSubview:_switchView];
    _switchView.left = self.width - 20 - _switchView.width;
    _switchView.top   = 6;
    [_switchView addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
}
- (CGFloat)cellHeight{
    return 44;
}
- (void)setData:(NSString *)data{
    if ([data boolValue]) {
        _switchView.on = [data boolValue];
    }
    _data = @([data boolValue]);
}
- (id)data{
    _data = @(_switchView.on);
    return _data;
}
- (void)valueChanged:(id)switchView{
    _data = @(_switchView.isSelected);
    if ([self.delegate respondsToSelector:@selector(cell:valuedChanged:)]) {
        [self.delegate cell:self valuedChanged:_data];
    }
}

+ (NSDictionary *)mapperWithCellName:(NSString *)cellName keyName:(NSString *)keyName andLabel:(NSString *)label{
    return [LSFormCell mapperWithClassName:@"Switch" cellName:cellName keyName:keyName   label:label value:nil andRule:nil];
}

@end

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../helper', __FILE__)

class TestMab < ActionDispatch::IntegrationTest
  test "normal view" do
    get "application/normal"
    assert_response :success
    assert_template "application/normal"
    assert_template "layouts/application"
    assert_html "
Hello Mab!
"
  end

  test "no layout" do
    get "application/no_layout"
    assert_response :success
    assert_template "application/normal"
    assert_equal "
Hello Mab!
", @response.body
  end

  test "variables" do
    get "application/variables"
    assert_response :success
    assert_template "application/variables"
    assert_template "layouts/application"
    assert_html "
Hello world!
"
  end

  test "content for" do
    get "application/content_for"
    assert_response :success
    assert_template "application/content_for"
    assert_template "layouts/application"
    assert_html "
Sub
", :heading => "
Heading
"
  end

  def assert_html(expected, options = {})
    expected = "<!DOCTYPE html><title>Dummy</title>#{options[:heading]}
#{expected}
" unless options[:skip_layout]
    assert_equal expected, @response.body
  end
end


text:
TL;DR

| go test flags | Description                              |
|---------------|------------------------------------------|
| `-debug`      | Enable debug mode for the test           |
| `-goldens`    | Update the golden files of the run tests |
| `-cassettes`  | Update the cassettes of the run tests    |

### Objectives of the test suite

- Ensure that we got no new regression when we merge new code
- Avoid leaking credentials when doing integration testing with Scaleway APIs

### Solution

#### Interaction Recording: Golden & Cassettes files

A **cassette** file contains all the interactions of the Scaleway APIs that a CLI must produce when a given test run.
A **golden** file contains the output that the CLI must produce when a given interaction recorded by a cassette occurs.

Having golden ensure that any change in a command output will be noticed if the behavior of the CLI change for a given interaction.
Having cassette ensure that we can replay interactions without actually doing the calls.

Warning, if you choose to record a new cassette, you will create real resources on your organization and will be billed accordingly.
Be sure to check out the resource you create in each test and remember to delete them once you need them anymore.

#### Metadata

When running a test, you might need information such as ID that you cannot know in advance (such as ID of resources).
The `core.Test` uses different helpers to pass useful information around.

One of them is the [`core.testMetadata`](https://github.com/scaleway/scaleway-cli/blob/master/internal/core/testing.go#L80).
It is designed to store information such as ID or object describing a resource during a test.
This metadata can use the `render` method to provide helpful golang templating features to have commands arguments computed dynamically.

#### BeforeFunc and AfterFunc

Usually, you might need to set up and teardown resources when you are running a test for testing a specific command.
For that you can use [`BeforeFunc`](https://github.com/scaleway/scaleway-cli/blob/master/internal/core/testing.go#L100) and [`AfterFunc`](https://github.com/scaleway/scaleway-cli/blob/master/internal/core/testing.go#L102).
Those types allow you to execute code before (`BeforeFunc`) or after (`AfterFunc`) the main command you want to test.
Those functions can access the metadata to change dynamically their behavior.

#### Logging and debug mode

When you are running CLI commands, you can use the `-D` to access the user logs.
You can activate the debug mode by passing the `-debug` flag when running the `go test` command.
For instance:

```
go test ./internal/namespaces/init -debug
```

When you are developing tests, you can also use the `Logger` field that is available in the different contexts to write your own logs.

#### Targeting specific tests

The test suite is design to run quickly, but when you are recording interactions you probably don't want to record interactions for all the tests in the test suite.
You can filter the test you want to run using the native filtering features of the go test command.

So let's suppose you would like to run the test `Test_InstallServer` in the baremetal package, you would use:

`go test ./internal/namespaces/baremetal/v1 -run Test_InstallServer`

Keep in mind that running a single file is NOT equivalent to run the test for a package.
Always run the test on the whole package (here the "baremetal" package stored in the folder "./internal/namespaces/baremetal/v1") and use the `-run` to target specific tests.

### Adding new tests

We welcome contributions!
If you want to contribute new tests you should have the following:

1. Setup your dev environment:
    - Install go for your platform
    - Install your credentials, preferably in a configuration file (run `scw init`)
        - Keep in mind that if you record interaction, the resource you will instantiate will be delivered and billed.
        - Clean up the resource you don't use once the recording is over.


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 10.4.3-1-2-s
description: this is not coerced to an object in strict mode (string)
flags: [noStrict]
includes: [runTestCase.js]
---*/

function testcase() {

  function foo()
  {
    'use strict';
    return typeof(this);
  }

  function bar()
  {
    return typeof(this);
  }

  return foo.call('1') === 'string' && bar.call('1') === 'object';
 }
runTestCase(testcase);


text:
require 'spec_helper'

provider_class = Puppet::Type.type(:file_line).provider(:ruby)
#  These tests fail on windows when run as part of the rake task. Individually they pass
describe provider_class, unless: Puppet::Util::Platform.windows? do
  include PuppetlabsSpec::Files

  let :tmpfile do
    tmpfilename('file_line_test')
  end
  let :content do
    ''
  end
  let :params do
    {}
  end
  let :resource do
    Puppet::Type::File_line.new({
      name: 'foo',
      path: tmpfile,
      line: 'foo',
    }.merge(params))
  end
  let :provider do
    provider_class.new(resource)
  end

  before :each do
    File.open(tmpfile, 'w') do |fh|
      fh.write(content)
    end
  end

  describe '#create' do
    context 'when adding' do
      pending('To be added.')
    end
    context 'when replacing' do
      let :params do
        {
          line: 'foo = bar',
          match: '^foo\s*=.*$',
          replace: false,
        }
      end
      let(:content) { "foo1\nfoo=blah\nfoo2\nfoo3" }

      it "providor 'be_exists'" do
        expect(provider).to be_exists
      end
      it 'does not replace the matching line' do
        provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo=blah\nfoo2\nfoo3")
      end
      it 'appends the line if no matches are found' do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") }
        expect(provider.exists?).to be false
        provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar")
      end
      it 'raises an error with invalid values' do
        expect {
          @resource = Puppet::Type::File_line.new(
            name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', replace: 'asgadga',
          )
        }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.})
      end
    end
  end
  describe '#destroy' do
    pending('To be added?')
  end
  context 'when matching' do
    # rubocop:disable RSpec/InstanceVariable : replacing before with let breaks the tests, variables need to be altered within it block : multi
    before :each do
      @resource = Puppet::Type::File_line.new(
        name: 'foo',
        path: tmpfile,
        line: 'foo = bar',
        match: '^foo\s*=.*$',
      )
      @provider = provider_class.new(@resource)
    end
    describe 'using match' do
      it 'raises an error if more than one line matches, and should not have modified the file' do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") }
        expect { @provider.create }.to raise_error(Puppet::Error, %r{More than one line.*matches})
        expect(File.read(tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz")
      end

      it 'replaces all lines that matches' do
        @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: true)
        @provider = provider_class.new(@resource)
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") }
        @provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar")
      end

      it 'replaces all lines that match, even when some lines are correct' do
        @resource = Puppet::Type::File_line.new(name: 'neil', path: tmpfile, line: "\thard\tcore\t0\n", match: '^[ \t]hard[ \t]+core[ \t]+.*', multiple: true)
        @provider = provider_class.new(@resource)
        File.open(tmpfile, 'w') { |fh| fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") }
        @provider.create
        expect(File.read(tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0")
      end

      it 'raises an error with invalid values' do
        expect {
          @resource = Puppet::Type::File_line.new(
            name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: 'asgadga',
          )
        }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.})
      end

      it 'replaces a line that matches' do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2") }
        @provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2")
      end
      it 'adds a new line if no lines match' do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") }
        @provider.create
        expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n")
      end
      it 'does nothing if the exact line already exists' do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = bar\nfoo2") }
        @provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2")
      end
    end
    describe 'using match+append_on_no_match - when there is a match' do
      it 'replaces line' do
        @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false)
        @provider = provider_class.new(@resource)
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") }
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz")
      end
    end
    describe 'using match+append_on_no_match - when there is no match' do
      it 'does not add line after no matches found' do
        @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false)
        @provider = provider_class.new(@resource)
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") }
        expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz")
      end
    end
  end
  context 'when match+replace+append_on_no_match' do
    pending('to do')
  end
  context 'when after' do
    let :resource do
      Puppet::Type::File_line.new(
        name: 'foo',
        path: tmpfile,
        line: 'inserted = line',
        after: '^foo1',
      )
    end

    let :provider do
      provider_class.new(resource)
    end

    context 'when match and after set' do
      shared_context 'when resource_create' do
        let(:match) { '^foo2$' }
        let(:after) { '^foo1$' }
        let(:resource) do
          Puppet::Type::File_line.new(
            name: 'foo',
            path: tmpfile,
            line: 'inserted = line',
            after: after,
            match: match,
          )
        end
      end
      before :each do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nfoo = baz") }
      end
      describe 'inserts at match' do
        include_context 'resource_create'
        it {
          provider.create
          expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz")
        }
      end
      describe 'inserts a new line after when no match' do
        include_context 'resource_create' do
          let(:match) { '^nevergoingtomatch$' }
        end
        it {
          provider.create
          expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz")
        }
      end
      describe 'append to end of file if no match for both after and match' do
        include_context 'resource_create' do
          let(:match) { '^nevergoingtomatch$' }
          let(:after) { '^stillneverafter' }
        end
        it {
          provider.create
          expect(File.read(tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line")
        }
      end
    end
    context 'with one line matching the after expression' do
      before :each do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") }
      end

      it 'inserts the specified line after the line matching the "after" expression' do
        provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz")
      end
    end
    context 'with multiple lines matching the after expression' do
      before :each do
        File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") }
      end

      it 'errors out stating "One or no line must match the pattern"' do
        expect { provider.create }.to raise_error(Puppet::Error, %r{One or no line must match the pattern})
      end

      it 'adds the line after all lines matching the after expression' do
        @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', after: '^foo1$', multiple: true)
        @provider = provider_class.new(@resource)
        @provider.create
        expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz")
      end
    end
    context 'with no lines matching the after expression' do
      let :content do
        "foo3\nfoo = blah\nfoo2\nfoo = baz\n"
      end

      before :each do
        File.open(tmpfile, 'w') { |fh| fh.write(content) }
      end

      it 'appends the specified line to the file' do
        provider.create
        expect(File.read(tmpfile)).to eq(content << resource[:line] << "\n")
      end
    end
  end
  context 'when removing with a line' do
    before :each do
      # TODO: these should be ported over to use the PuppetLabs spec_helper
      #  file fixtures once the following pull request has been merged:
      # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files
      @resource = Puppet::Type::File_line.new(
        name: 'foo',
        path: tmpfile,
        line: 'foo',
        ensure: 'absent',
      )
      @provider = provider_class.new(@resource)
    end
    it 'removes the line if it exists' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2")
    end
    it 'removes the line without touching the last new line' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\n") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\n")
    end
    it 'removes any occurence of the line' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\n")
    end
    it 'example in the docs' do
      @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128')
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n")
    end
  end
  context 'when removing with a match' do
    before :each do
      @resource = Puppet::Type::File_line.new(
        name: 'foo',
        path: tmpfile,
        line: 'foo2',
        ensure: 'absent',
        match: 'o$',
        match_for_absence: true,
      )
      @provider = provider_class.new(@resource)
    end

    it 'finds a line to match' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      expect(@provider.exists?).to be true
    end

    it 'removes one line if it matches' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2")
    end

    it 'the line parameter is actually not used at all but is silently ignored if here' do
      @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'supercalifragilisticexpialidocious', ensure: 'absent', match: 'o$', match_for_absence: true)
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2")
    end

    it 'and may not be here and does not need to be here' do
      @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, ensure: 'absent', match: 'o$', match_for_absence: true)
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2")
    end

    it 'raises an error if more than one line matches' do
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") }
      expect { @provider.destroy }.to raise_error(Puppet::Error, %r{More than one line})
    end

    it 'removes multiple lines if :multiple is true' do
      @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', multiple: true, match_for_absence: true)
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\n")
    end

    it 'ignores the match if match_for_absence is not specified' do
      @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$')
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo\n")
    end

    it 'ignores the match if match_for_absence is false' do
      @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', match_for_absence: false)
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo\n")
    end

    it 'example in the docs' do
      @resource = Puppet::Type::File_line.new(
        name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
        match: '^export\ HTTP_PROXY\=', match_for_absence: true
      )
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n")
    end

    it 'example in the docs showing line is redundant' do
      @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, match: '^export\ HTTP_PROXY\=', match_for_absence: true)
      @provider = provider_class.new(@resource)
      File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") }
      @provider.destroy
      expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n")
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST AnimatedGif" />
  <property name="jnlp.Name"     value="AnimatedGif" />
  <property name="jnlp.name"     value="animatedgif" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/animatedgif/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/AnimatedGif.html" />
</project>


text:
<?xml version="1.0"?>

<project name="library" default="usage" basedir=".">
	<import id="toplevel" file="../build.xml" />

	<target name="create-distfile" depends="compile,dist.prepare" description="Create library jar file.">
		<jar jarfile="${dist.dir}/${project.name}.jar" index="true" basedir="${target.classes.dir}" manifest="${project.manifest}">
			<manifest>
			    <attribute name="Built-By" value="${user.name}"/>
			    <section name="${project.package}">
			        <attribute name="Specification-Title" value="${project.title}"/>
			        <attribute name="Specification-Version" value="${project.version}"/>
			        <attribute name="Specification-Vendor" value="${company.name}"/>
			        <attribute name="Implementation-Vendor-Id" value="${company.package.prefix}"/>
			        <attribute name="Implementation-Title" value="${project.title}"/>
			        <attribute name="Implementation-Version" value="${project.version} ${TODAY}"/>
			        <attribute name="Implementation-Vendor" value="${company.name}"/>
				    <attribute name="sealed" value="true"/>
			    </section>
			</manifest>
		</jar>
	</target>

</project>


text:
class CreateNeighborhoods < ActiveRecord::Migration
  def change
    create_table :neighborhoods do |t|
      t.string :name
      t.string :borough
      t.timestamps
    end
  end
end


text: """OpenSearch v1 mappings."""


text:
<?php

/**
 * Replace regular expression case insensitive
 *
 * @phpstub
 *
 * @param string $pattern
 * @param string $replacement
 * @param string $string
 *
 * @return string The modified string is returned. If no matches are found in
 *                , then it will be returned unchanged.
 */
function eregi_replace($pattern, $replacement, $string)
{
}


text:
function subscriptionResults = getSubscriptionResults(loopID)
%getSubscriptionResults Get the subscription results for the last time step.
%   subscriptionResults = getSubscriptionResults(LOOPID) Returns the
%   subscription results for the last time step and the given induction loop. If no
%   induction loop id is given, all subscription results are returned in a
%   containers.Map data structure.
%   If the induction loop id is unknown or the subscription did for any reason return
%   no data, 'None' is returned.
%   It is not possible to retrieve older subscription results than the ones
%   from the last time step.

%   Copyright 2019 Universidad Nacional de Colombia,
%   Politecnico Jaime Isaza Cadavid.
%   Authors: Andres Acosta, Jairo Espinosa, Jorge Espinosa.
%   $Id: getSubscriptionResults.m 48 2018-12-26 15:35:20Z afacostag $

global loopSubscriptionResults
if isempty(loopSubscriptionResults)
    throw(MException('traci:FatalTraCIError',...
        'You have to subscribe to the variable'));
end
if nargin < 1
    loopID = 'None';
end

subscriptionResults = loopSubscriptionResults.get(loopID);


text:
var Checker = function (config) {
  var EventEmitter = require('events').EventEmitter,
    http = require('http');

  var log4js = require('log4js');
  log4js.loadAppender('file');
  log4js.addAppender(log4js.appenders.file('logs/local.log'), 'local');
  for (var i in config.central) {
    log4js.addAppender(log4js.appenders.file('logs/' + config.central[i].id + '.log'), config.central[i].id);
  }
  var logger = {
    local: log4js.getLogger('local')
  }
  for (var i in config.central) {
    logger[config.central[i].id] = log4js.getLogger(config.central[i].id);
  }

  var urlConcat = function () {
    var array = [];

    for (var i in arguments) {
      array[i] = arguments[i].replace(/\/$/, '').replace(/^\//, '');
    }

    return array.join('/');
  };

  return function (requestParam) {
    var req = requestParam;

    function check(serverConfig) {
      var eventEmitter = new EventEmitter();

      var urlToRequest = urlConcat(serverConfig.url, req.url);

      logger[serverConfig.id].debug('GET ' + urlToRequest);

      var startTime = new Date();
      http.get(urlToRequest,function (response) {
        var time = (new Date() - startTime);
        if (time < 100) {
          logger[serverConfig.id].debug('Response in %s ms for %s', time, urlToRequest);
        } else if (time < 500) {
          logger[serverConfig.id].info('Response in %s ms for %s', time, urlToRequest);
        } else {
          logger[serverConfig.id].warn('Response in %s ms for %s', time, urlToRequest);
        }

        eventEmitter.emit('response', null, response);
      }).on('error', function (error) {
          eventEmitter.emit('response', error, null);
        });

      return eventEmitter;
    }

    return {
      check: check
    };
  };
}

module.exports = Checker;


text:
require 'mysql2'
require "bank_routing/storage/sql"

class RoutingNumber

  class MySQLStore < SQLStore

    DefaultOptions = {
      table_name: 'routing_numbers',
      connection_class: Mysql2::Client,
      connection_method: :new,
      string_escape_method: :escape
    }

    def create_table_statement
      "CREATE TABLE IF NOT EXISTS #{ options[ :table_name ] } (id integer PRIMARY KEY AUTO_INCREMENT, #{ Schema.map {|(field,type)| "#{field.to_s} #{ TypeMap[type] }" }.join( ', ' ) })"
    end

  end

  Stores[:mysql] = MySQLStore

end


text:
module Virtus
  class Attribute

    # Attribute extension which raises CoercionError when coercion failed
    #
    module Strict

      # @see [Attribute#coerce]
      #
      # @raises [CoercionError] when coercer failed
      #
      # @api public
      def coerce(*)
        output = super

        if value_coerced?(output) || !required? && output.nil?
          output
        else
          raise CoercionError.new(output, primitive)
        end
      end

    end # Strict

  end # Attribute
end # Virtus


text:
package net.kemitix.ldapmanager.navigation.events;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import net.kemitix.ldapmanager.domain.User;
import net.kemitix.ldapmanager.navigation.UserNavigationItem;

/**
 * Raised when the user presses Enter or Space on a {@link UserNavigationItem}.
 *
 * @author Paul Campbell (pcampbell@kemitix.net)
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class NavigationItemUserActionEvent {

    @Getter
    private final User user;

    /**
     * Create a new ApplicationEvent for when the User is opened.
     *
     * @param user The user
     *
     * @return the event
     */
    public static NavigationItemUserActionEvent of(@NonNull final User user) {
        return new NavigationItemUserActionEvent(user);
    }
}


text:
/*jshint node:true, mocha:true*/
/**
 * @author pmeijer / https://github.com/pmeijer
 */

var testFixture = require('./globals');

describe('NodeWorker', function () {
    'use strict';

    var Q = testFixture.Q,
        path = testFixture.path,
        fs = testFixture.fs,
        httpProxy = require('http-proxy'),
        rimraf = testFixture.rimraf,
        childProcess = testFixture.childProcess,
        should = testFixture.should,
        ExecutorClient = testFixture.ExecutorClient,
        BlobClient = testFixture.BlobClient,
        logger = testFixture.Logger.create('node_worker:test', {
            //patterns: ['gme:test:*cache'],
            transports: [{
                transportType: 'Console',
                options: {
                    level: 'error',
                    colorize: true,
                    timestamp: true,
                    prettyPrint: true,
                    //handleExceptions: true, // ignored by default
                    //exitOnError: false,
                    depth: 4,
                    debugStdout: true
                }
            }]
        }, false),
        executorClient,
        blobClient,
        server,
        nodeWorkerProcess,
        proxyServer,
        port;

    function startServer(gmeConfig, workerNonce, useHttpsProxy, callback) {
        proxyServer = null;
        port = null;

        Q.nfcall(rimraf, './test-tmp/blob-local-storage')
            .then(function () {
                return Q.nfcall(rimraf, './test-tmp/executor-tmp');
            })
            .then(function () {
                return Q.nfcall(rimraf, './test-tmp/worker_config.json');
            })
            .then(function () {
                server = testFixture.WebGME.standaloneServer(gmeConfig);
                return Q.nfcall(server.start);
            })
            .then(function () {
                var workerConfig = {},
                    clientsParam = {};

                useHttpsProxy = useHttpsProxy === true;
                if (useHttpsProxy) {
                    port = gmeConfig.server.port - 1;
                    proxyServer = new httpProxy.createServer({
                        target: {
                            host: 'localhost',
                            port: gmeConfig.server.port
                        },
                        ssl: {
                            key: fs.readFileSync(path.join(__dirname,
                                'certificates',
                                'sample-key.pem'), 'utf8'),
                            cert: fs.readFileSync(path.join(__dirname,
                                'certificates',
                                'sample-cert.pem'), 'utf8')
                        }
                    });

                } else {
                    port = gmeConfig.server.port;
                }

                clientsParam.serverPort = port;
                clientsParam.sessionId = 'testingNodeWorker';
                clientsParam.server = '127.0.0.1';
                clientsParam.httpsecure = useHttpsProxy;
                clientsParam.executorNonce = gmeConfig.executor.nonce;

                clientsParam.logger = logger.fork('NodeWorker:ExecClient');
                executorClient = new ExecutorClient(clientsParam);

                clientsParam.logger = logger.fork('NodeWorker:BlobClient');
                blobClient = new BlobClient(clientsParam);
                workerConfig[server.getUrl()] = workerNonce ? {executorNonce: workerNonce} : {};
                return Q.nfcall(fs.writeFile, 'test-tmp/worker_config.json', JSON.stringify(workerConfig));
            })
            .then(function () {
                if (proxyServer) {
                    var deferred = Q.defer();
                    proxyServer.listen(port, function (err) {
                        if (err) {
                            deferred.reject(err);
                        } else {
                            deferred.resolve();
                        }
                    });
                    return deferred.promise;
                } else {
                    return;
                }
            })
            .then(function () {
                var deferred = Q.defer(),
                    stderr = '',
                    stdout = '',
                    args = ['node_worker.js', 'test-tmp/worker_config.json',
                        'test-tmp/executor-tmp'],
                    timeoutId = setTimeout(function () {
                        deferred.reject('Worker did not respond in time, stderr: ' + stderr + ' stdout: ' + stdout);
                    }, 3000);

                nodeWorkerProcess = childProcess.spawn('node', args,
                    {cwd: path.join(__dirname, '..')});
                nodeWorkerProcess.stderr.on('data', function (data) {
                    stderr += data.toString();
                });
                nodeWorkerProcess.stdout.on('data', function (data) {
                    var str = data.toString();
                    stdout += str;
                    if (str.indexOf('Connected to') > -1) {
                        clearTimeout(timeoutId);
                        deferred.resolve({connected: true, stdout: stdout, stderr: stderr});
                    } else if (str.indexOf('Server returned 403') > -1) {
                        clearTimeout(timeoutId);
                        deferred.resolve({connected: false, stdout: stdout, stderr: stderr});
                    } else if (str.indexOf('Error connecting to') > -1) {
                        clearTimeout(timeoutId);
                        deferred.resolve({connected: false, stdout: stdout, stderr: stderr});
                    }
                });

                // nodeWorkerProcess.on('close', function (code, signal) {
                //     console.log('close', code, signal);
                // });
                // nodeWorkerProcess.on('error', function (err) {
                //     console.log('error', err);
                // });

                return deferred.promise;
            })
            .catch(function (err) {
                throw new Error(err);
            })
            .nodeify(callback);
    }

    describe('[nonce not set]', function () {

        before(function (done) {
            var gmeConfig = testFixture.getGmeConfig();
            this.timeout(5000);
            gmeConfig.executor.enable = true;
            gmeConfig.executor.nonce = null;

            startServer(gmeConfig, null, false, function (err, result) {
                if (err) {
                    done(err);
                    return;
                }
                if (result.connected) {
                    done();
                } else {
                    done(new Error('Worker did not attach, stdout: ' + result.stdout + ', stderr: ' +
                        result.stderr));
                }
            });
        });

        after(function (done) {
            nodeWorkerProcess.on('close', function (/*code*/) {
                setTimeout(function () {
                    server.stop(function (err) {
                        if (proxyServer) {
                            proxyServer.close(function (err1) {
                                done(err || err1);
                            });
                        } else {
                            done(err);
                        }
                    });
                }, 200); // Allow some time for initiated POST /worker
            });

            nodeWorkerProcess.kill('SIGINT');
        });

        it('getWorkersInfo should return one worker', function (done) {
            executorClient.getWorkersInfo(function (err, res) {
                var keys = Object.keys(res);
                if (err) {
                    done(err);
                    return;
                }
                should.equal(typeof res, 'object', 'getWorkersInfo return object');
                should.equal(keys.length > 0, true, 'workers attached');
                done();
            });
        });

        it('createJob with cmd node -h should return SUCCESS', function (done) {
            this.timeout(20000);
            var executorConfig = {
                    cmd: 'node',
                    args: ['-h'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig)
                };

            artifact.addFiles(filesToAdd)
                .then(function () {
                    return artifact.save();
                })
                .then(function (hash) {
                    return executorClient.createJob({hash: hash});
                })
                .then(function (jobInfo) {
                    var intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash, function (err, res) {
                            if (err) {
                                clearInterval(intervalId);
                                done(err);
                                return;
                            }

                            if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                // The job is still running..
                                return;
                            }
                            clearInterval(intervalId);
                            should.equal(res.status, 'SUCCESS');
                            done();
                        });
                    }, 1000);
                })
                .catch(done);
        });

        it('createJob and cancelJob when it is running and return with status CANCELED', function (done) {
            this.timeout(20000);
            var executorConfig = {
                    cmd: 'node',
                    args: ['longRunning.js'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                    'longRunning.js': 'setTimeout(function (){ process.exit(1); }, 10000);'
                };

            artifact.addFiles(filesToAdd)
                .then(function () {
                    return artifact.save();
                })
                .then(function (hash) {
                    return executorClient.createJob({hash: hash});
                })
                .then(function (jobInfo) {
                    var secret = jobInfo.secret,
                        cancelSent = false,
                        intervalId;

                    intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash, function (err, res) {
                            if (err) {
                                clearInterval(intervalId);
                                done(err);
                                return;
                            }

                            if (res.status === 'CREATED') {
                                // The job was created..
                                return;
                            } else if (res.status === 'RUNNING') {
                                if (cancelSent === false) {
                                    cancelSent = true;
                                    executorClient.cancelJob(jobInfo, secret, function (err) {
                                        if (err) {
                                            clearInterval(intervalId);
                                            done(err);
                                        }
                                    });
                                }
                                return;
                            }

                            clearInterval(intervalId);
                            should.equal(res.status, 'CANCELED');
                            done();
                        });
                    }, 100);
                })
                .catch(done);
        });

        it('createJob and cancelJob right away and return with status CANCELED', function (done) {
            this.timeout(20000);
            var executorConfig = {
                    cmd: 'node',
                    args: ['longRunning2.js'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                    'longRunning2.js': 'setTimeout(function (){ process.exit(1); }, 10000);'
                };

            artifact.addFiles(filesToAdd)
                .then(function () {
                    return artifact.save();
                })
                .then(function (hash) {
                    return executorClient.createJob({hash: hash});
                })
                .then(function (jobInfo) {
                    var secret = jobInfo.secret;
                    var intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash, function (err, res) {
                            if (err) {
                                clearInterval(intervalId);
                                done(err);
                                return;
                            }

                            if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                // The job was created or is running..
                                return;
                            }

                            clearInterval(intervalId);
                            should.equal(res.status, 'CANCELED');
                            done();
                        });
                    }, 100);

                    return executorClient.cancelJob(jobInfo, secret);
                })
                .catch(done);
        });

        it('createJob and cancelJob after SUCCESS should not do anything', function (done) {
            this.timeout(20000);
            var executorConfig = {
                    cmd: 'node',
                    args: ['--version'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig)
                };

            artifact.addFiles(filesToAdd)
                .then(function () {
                    return artifact.save();
                })
                .then(function (hash) {
                    return executorClient.createJob({hash: hash});
                })
                .then(function (jobInfo) {
                    var intervalId,
                        secret = jobInfo.secret,
                        deferred = Q.defer();

                    intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash)
                            .then(function (res) {
                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }

                                clearInterval(intervalId);
                                should.equal(res.status, 'SUCCESS');

                                executorClient.cancelJob(jobInfo, secret)
                                    .then(function () {
                                        return executorClient.getInfo(jobInfo.hash);
                                    })
                                    .then(function (info) {
                                        should.equal(info.status, 'SUCCESS');
                                        deferred.resolve();
                                    })
                                    .catch(deferred.reject);
                            })
                            .catch(function (err) {
                                clearInterval(intervalId);
                                deferred.reject(err);
                            });
                    }, 100);

                    return deferred.promise;
                })
                .nodeify(done);
        });

        it('createJob and cancelJob and createJob and cancelJob', function (done) {
            this.timeout(20000);
            var executorConfig = {
                    cmd: 'node',
                    args: ['longRunning3.js'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                    'longRunning3.js': 'setTimeout(function (){ process.exit(1); }, 10000);'
                };

            artifact.addFiles(filesToAdd)
                .then(function () {
                    return artifact.save();
                })
                .then(function (hash) {
                    return executorClient.createJob({hash: hash});
                })
                .then(function (jobInfo) {
                    var deferred = Q.defer(),
                        intervalId;

                    intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash, function (err, res) {
                            if (err) {
                                clearInterval(intervalId);
                                deferred.reject(err);
                                return;
                            }

                            if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                // The job was created or is running..
                                return;
                            }

                            clearInterval(intervalId);
                            should.equal(res.status, 'CANCELED');
                            deferred.resolve(jobInfo);
                        });
                    }, 100);

                    executorClient.cancelJob(jobInfo, jobInfo.secret);

                    return deferred.promise;
                })
                .then(function (jobInfo) {
                    return executorClient.createJob({hash: jobInfo.hash});
                })
                .then(function (jobInfo) {
                    var deferred = Q.defer(),
                        intervalId;

                    intervalId = setInterval(function () {
                        executorClient.getInfo(jobInfo.hash, function (err, res) {
                            if (err) {
                                clearInterval(intervalId);
                                deferred.reject(err);
                                return;
                            }

                            if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                // The job was created or is running..
                                return;
                            }

                            clearInterval(intervalId);
                            should.equal(res.status, 'CANCELED');
                            deferred.resolve(jobInfo);
                        });
                    }, 100);

                    executorClient.cancelJob(jobInfo, jobInfo.secret);

                    return deferred.promise;
                })
                .nodeify(done);
        });
    });

    describe('[nonce match]', function () {
        before(function (done) {
            var gmeConfig = testFixture.getGmeConfig();
            this.timeout(5000);
            gmeConfig.executor.enable = true;
            gmeConfig.executor.nonce = 'aReallyLongSecret';

            startServer(gmeConfig, 'aReallyLongSecret', false, function (err, result) {
                if (err) {
                    done(err);
                    return;
                }
                if (result.connected) {
                    done();
                } else {
                    done(new Error('Worker did not attach, stdout: ' + result.stdout + ', stderr: ' +
                        result.stderr));
                }
            });
        });

        after(function (done) {
            nodeWorkerProcess.on('close', function (/*code*/) {
                setTimeout(function () {
                    server.stop(function (err) {
                        if (proxyServer) {
                            proxyServer.close(function (err1) {
                                done(err || err1);
                            });
                        } else {
                            done(err);
                        }
                    });
                }, 200); // Allow some time for initiated POST /worker
            });

            nodeWorkerProcess.kill('SIGINT');
        });

        it('getWorkersInfo should return at least one worker', function (done) {
            executorClient.getWorkersInfo(function (err, res) {
                var keys = Object.keys(res);
                if (err) {
                    done(err);
                    return;
                }
                should.equal(typeof res, 'object', 'getWorkersInfo return object');
                should.equal(keys.length > 0, true, 'worker attached');
                done();
            });
        });

        it('createJob with cmd node -h should return SUCCESS', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['-h'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig)
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'SUCCESS');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with node fail.js should return FAILED_TO_EXECUTE', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['fail.js'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                    'fail.js': 'process.exit(1)'
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_TO_EXECUTE');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with invalid hash should return FAILED_TO_GET_SOURCE_METADATA', function (done) {
            executorClient.createJob({hash: '911'}, function (err, jobInfo) {
                var intervalId;
                if (err) {
                    done(new Error(err));
                    return;
                }
                intervalId = setInterval(function () {
                    executorClient.getInfo(jobInfo.hash, function (err, res) {
                        if (err) {
                            clearInterval(intervalId);
                            done(err);
                            return;
                        }

                        if (res.status === 'CREATED' || res.status === 'RUNNING') {
                            // The job is still running..
                            return;
                        }
                        clearInterval(intervalId);
                        should.equal(res.status, 'FAILED_TO_GET_SOURCE_METADATA');
                        done();
                    });
                }, 100);
            });
        });

        it('createJob with without executor_config.json should return FAILED_EXECUTOR_CONFIG', function (done) {
            var artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'fail.js': 'process.exit(1)'
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with missing cmd should return FAILED_EXECUTOR_CONFIG', function (done) {
            var executorConfig = {
                    ccmd: 'node',
                    args: ['-h'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with missing resultArtifacts should return FAILED_EXECUTOR_CONFIG', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['-h']
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });
    });

    describe('[nonce not matching]', function () {
        it('worker should not attach', function (done) {
            var gmeConfig = testFixture.getGmeConfig();
            this.timeout(5000);
            gmeConfig.executor.enable = true;
            gmeConfig.executor.nonce = 'aReallyLongSecret';

            startServer(gmeConfig, 'notMatching', false, function (err, result) {
                if (err) {
                    done(err);
                    return;
                }
                if (result.connected) {
                    done(new Error('Worker did attach when should not, stdout: ' + result.stdout + ', stderr: ' +
                        result.stderr));
                } else {
                    done();
                }
            });
        });

        after(function (done) {
            nodeWorkerProcess.on('close', function (/*code*/) {
                setTimeout(function () {
                    server.stop(function (err) {
                        if (proxyServer) {
                            proxyServer.close(function (err1) {
                                done(err || err1);
                            });
                        } else {
                            done(err);
                        }
                    });
                }, 200); // Allow some time for initiated POST /worker
            });

            nodeWorkerProcess.kill('SIGINT');
        });
    });

    describe('[https nonce match]', function () {
        var nodeTLSRejectUnauthorized;

        nodeTLSRejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED;

        before(function (done) {
            var gmeConfig = testFixture.getGmeConfig();
            this.timeout(5000);
            gmeConfig.executor.enable = true;
            gmeConfig.executor.nonce = 'aReallyLongSecret';

            process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
            startServer(gmeConfig, 'aReallyLongSecret', true, function (err, result) {
                if (err) {
                    done(err);
                    return;
                }
                if (result.connected) {
                    done();
                } else {
                    done(new Error('Worker did not attach, stdout: ' + result.stdout + ', stderr: ' +
                        result.stderr));
                }
            });
        });

        after(function (done) {
            process.env.NODE_TLS_REJECT_UNAUTHORIZED = nodeTLSRejectUnauthorized;
            nodeWorkerProcess.on('close', function (/*code*/) {
                setTimeout(function () {
                    server.stop(function (err) {
                        if (proxyServer) {
                            proxyServer.close(function (err1) {
                                done(err || err1);
                            });
                        } else {
                            done(err);
                        }
                    });
                }, 200); // Allow some time for initiated POST /worker
            });

            nodeWorkerProcess.kill('SIGINT');
        });

        it('getWorkersInfo should return at least one worker', function (done) {
            executorClient.getWorkersInfo(function (err, res) {
                var keys = Object.keys(res);
                if (err) {
                    done(err);
                    return;
                }
                should.equal(typeof res, 'object', 'getWorkersInfo return object');
                should.equal(keys.length > 0, true, 'worker attached');
                done();
            });
        });

        it('createJob with cmd node -h should return SUCCESS', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['-h'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig)
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'SUCCESS');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with node fail.js should return FAILED_TO_EXECUTE', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['fail.js'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                    'fail.js': 'process.exit(1)'
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_TO_EXECUTE');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with invalid hash should return FAILED_TO_GET_SOURCE_METADATA', function (done) {
            executorClient.createJob({hash: '911'}, function (err, jobInfo) {
                var intervalId;
                if (err) {
                    done(new Error(err));
                    return;
                }
                intervalId = setInterval(function () {
                    executorClient.getInfo(jobInfo.hash, function (err, res) {
                        if (err) {
                            clearInterval(intervalId);
                            done(err);
                            return;
                        }

                        if (res.status === 'CREATED' || res.status === 'RUNNING') {
                            // The job is still running..
                            return;
                        }
                        clearInterval(intervalId);
                        should.equal(res.status, 'FAILED_TO_GET_SOURCE_METADATA');
                        done();
                    });
                }, 100);
            });
        });

        it('createJob with without executor_config.json should return FAILED_EXECUTOR_CONFIG', function (done) {
            var artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'fail.js': 'process.exit(1)'
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with missing cmd should return FAILED_EXECUTOR_CONFIG', function (done) {
            var executorConfig = {
                    ccmd: 'node',
                    args: ['-h'],
                    resultArtifacts: [{name: 'all', resultPatterns: []}]
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });

        it('createJob with missing resultArtifacts should return FAILED_EXECUTOR_CONFIG', function (done) {
            var executorConfig = {
                    cmd: 'node',
                    args: ['-h']
                },
                artifact = blobClient.createArtifact('execFiles'),
                filesToAdd = {
                    'executor_config.json': JSON.stringify(executorConfig),
                };
            artifact.addFiles(filesToAdd, function (err/*, hashes*/) {
                if (err) {
                    done(err);
                    return;
                }
                artifact.save(function (err, hash) {
                    if (err) {
                        done(err);
                        return;
                    }
                    executorClient.createJob({hash: hash}, function (err, jobInfo) {
                        var intervalId;
                        if (err) {
                            done(new Error(err));
                            return;
                        }
                        intervalId = setInterval(function () {
                            executorClient.getInfo(jobInfo.hash, function (err, res) {
                                if (err) {
                                    clearInterval(intervalId);
                                    done(err);
                                    return;
                                }

                                if (res.status === 'CREATED' || res.status === 'RUNNING') {
                                    // The job is still running..
                                    return;
                                }
                                clearInterval(intervalId);
                                should.equal(res.status, 'FAILED_EXECUTOR_CONFIG');
                                done();
                            });
                        }, 100);
                    });
                });
            });
        });
    });
});


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

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Hello SyntaxHighlighter</title>

	<link type="text/css" rel="stylesheet" href="styles/shCoreEclipse.css"/>

Hello SyntaxHighlighter

// LoginForm has two attributes: username and password
class LoginForm extends \yii\base\Model
{
    public $username;
    public $password;

    public function attributeLabels()
    {
        return [
            'username' => 'Your name',
            'password' => 'Your password',
        ];
    }
}

class EmployeeController extends \yii\web\Controller
{
    public function actionCreate($id = null)
    {
        // 第一种方法
        $employee = new Employee(['scenario' => 'managementPanel']);

        // 第二种方法
        $employee = new Employee();
        $employee->scenario = 'managementPanel';

        // 第三种方法
        $employee = Employee::find()->where('id = :id', [':id' => $id])->one();
        if ($employee !== null) {
            $employee->scenario = 'managementPanel';
        }
    }
}


text:
package org.apereo.cas.support.saml.web.idp.profile.sso.request;

import org.apereo.cas.audit.AuditActionResolvers;
import org.apereo.cas.audit.AuditResourceResolvers;
import org.apereo.cas.audit.AuditableActions;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.shibboleth.utilities.java.support.xml.ParserPool;
import org.apache.commons.lang3.tuple.Pair;
import org.apereo.inspektr.audit.annotation.Audit;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.decoder.servlet.BaseHttpServletRequestXMLMessageDecoder;
import org.opensaml.saml.common.SignableSAMLObject;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * This is {@link DefaultSSOSamlHttpRequestExtractor}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@Slf4j
@RequiredArgsConstructor
@Getter
public class DefaultSSOSamlHttpRequestExtractor implements SSOSamlHttpRequestExtractor {
    /**
     * The Parser pool.
     */
    private final ParserPool parserPool;

    @Audit(action = AuditableActions.SAML2_REQUEST,
        actionResolverName = AuditActionResolvers.SAML2_REQUEST_ACTION_RESOLVER,
        resourceResolverName = AuditResourceResolvers.SAML2_REQUEST_RESOURCE_RESOLVER)
    @Override
    @SneakyThrows
    public Optional<Pair<? extends SignableSAMLObject, MessageContext>> extract(final HttpServletRequest request,
                                                                                final BaseHttpServletRequestXMLMessageDecoder decoder,
                                                                                final Class<? extends SignableSAMLObject> clazz) {
        LOGGER.trace("Received SAML profile request [{}]", request.getRequestURI());
        decoder.setHttpServletRequest(request);
        decoder.setParserPool(this.parserPool);
        decoder.initialize();
        decoder.decode();

        val messageContext = decoder.getMessageContext();
        LOGGER.trace("Locating SAML object from message context...");
        val object = (SignableSAMLObject) messageContext.getMessage();
        if (object == null) {
            LOGGER.debug("SAML object cannot be determined from the decoder [{}]", decoder.getClass().getSimpleName());
            return Optional.empty();
        }

        if (!clazz.isAssignableFrom(object.getClass())) {
            LOGGER.debug("SAML object [{}] type does not match [{}]", object.getClass().getName(), clazz);
            return Optional.empty();
        }

        LOGGER.debug("Decoded SAML object [{}] from http request", object.getElementQName());
        return Optional.of(Pair.of(object, messageContext));
    }
}


text:
package rapture.dsl.serfun;

import java.util.List;
import java.util.Queue;

import rapture.common.Hose;
import rapture.common.SeriesValue;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class MavgHose extends SimpleHose {
    private int range = 0;
    private double sum = 0.0;
    private String col;
    private Queue<SeriesValue> window = Lists.newLinkedList();

    public MavgHose(HoseArg input, int range) {
        super(input);
        this.range = range;
    }

    @Override
    public String getName() { return "mavg()"; }

    public static class Factory implements HoseFactory {
        @Override
        public Hose make(List<HoseArg> args) {
            Preconditions.checkArgument(args.size() == 2, "Wrong number of arguments to mavg()");
            HoseArg input = args.get(0);
            int range = args.get(1).tryInt("Bad argument to mavg(stream, range) -- range must be an Integer");
            Hose result = new MavgHose(input, range);
            return result;
        }
    }

    @Override
    public SeriesValue pullValue() {
        while(window.size() < range) {
            SeriesValue v = pullFromUpstream();
            if (v == null) {
                return null;
            }
            sum += v.asDouble();
            col = v.getColumn();
            window.add(v);
        }
        SeriesValue result = new DecimalSeriesValue(sum / range, col);
        SeriesValue dead = window.poll();
        sum -= dead.asLong();
        return result;
    }

    @Override
    public void pushValue(SeriesValue v) {
        sum += v.asDouble();
        col = v.getColumn();
        window.add(v);
        if(window.size() > range) {
            SeriesValue dead = window.poll();
            sum -= dead.asDouble();
        }
        if(window.size() == range) {
            pushValue(new DecimalSeriesValue(sum / range, col));
        }
    }
}


text:
#import "TiBase.h"

#ifdef USE_TI_UIIPADSPLITWINDOW

#import "TiViewProxy.h"

@interface TiUIiPadSplitWindowButtonProxy : TiViewProxy {
@private
	UIBarButtonItem *button;
}

-(id)initWithButton:(UIBarButtonItem*)button pageContext:(id<TiEvaluator>)pageContext;

@end

#endif


text:
<?php

namespace Ustream\Arr;

use PHPUnit_Framework_Assert;
use PHPUnit_Framework_Constraint;
use PHPUnit_Framework_Constraint_IsEqual;
use PHPUnit_Framework_TestCase;
use Ustream\Option\None;
use Ustream\Option\Option;
use Ustream\Option\Some;

/**
 * Holds the CompositeExtractorTest class
 */
class CompositeExtractorTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldExtractAllFieldPathPairsFromDataMap()
    {
        $inputData = array('foo' => array('bar' => 'baz'));
        $firstResult = array('bar' => 'baz');
        $secondResult = 'baz';

        $firstExtractor = new TestExtractor($inputData, new Some($firstResult));
        $secondExtractor = new TestExtractor($firstResult, new Some($secondResult));
        $extractor = new CompositeExtractor($firstExtractor, $secondExtractor);

        $this->assertEquals($secondResult, $extractor->extract($inputData)->getOrElse(null));
        $firstExtractor->assertCalled();
        $secondExtractor->assertCalled();
    }

    /**
     * @test
     */
    public function shouldReturnNoneIfAnyExtractorReturnsNone()
    {
        $firstExtractor = new TestExtractor($this->anything(), None::create());
        $secondExtractor = new TestExtractor($this->anything(), null);
        $extractor = new CompositeExtractor($firstExtractor, $secondExtractor);

        $this->assertEquals(None::create(), $extractor->extract(array()));
        $firstExtractor->assertCalled();
        $secondExtractor->assertNotCalled();

        $firstExtractor = new TestExtractor($this->anything(), new Some(array()));
        $secondExtractor = new TestExtractor($this->anything(), None::create());
        $extractor = new CompositeExtractor($firstExtractor, $secondExtractor);

        $this->assertEquals(None::create(), $extractor->extract(array()));
        $firstExtractor->assertCalled();
        $secondExtractor->assertCalled();
    }
}

class TestExtractor implements Extractor
{
    private $input, $output;
    private $called = false;

    /**
     * @param mixed $input
     * @param mixed $output
     */
    public function __construct($input, $output)
    {
        $this->input = $input;
        $this->output = $output;
    }

    /**
     * @param array $data
     * @return Option
     */
    public function extract($data)
    {
        $expected = $this->input instanceof PHPUnit_Framework_Constraint
            ? $this->input
            : new PHPUnit_Framework_Constraint_IsEqual($this->input);
        PHPUnit_Framework_Assert::assertThat($data, $expected);
        $this->called = true;
        return $this->output;
    }

    public function assertCalled()
    {
        PHPUnit_Framework_Assert::assertTrue($this->called);
    }

    public function assertNotCalled()
    {
        PHPUnit_Framework_Assert::assertFalse($this->called);
    }
}


text:
<!DOCTYPE html>

Click me
<button inert id="button">Click me</button>

Click meeee

Click me


text:
package pl.nn44.battleship.util;

public interface IdGenerator {

  String nextId();
}


text:
package org.bizzle.astar

import
  org.bizzle.pathfinding.{ coordinate, pathingmap, PathingStatus },
    coordinate.{ BadCoordinate2D, Coordinate2D },
    pathingmap.PathingMapString

import
  base.{ AStarBase, HeuristicLib }

/**
 * Created by IntelliJ IDEA.
 * User: Jason
 * Date: 12/4/11
 * Time: 10:40 PM
 */

// Basically, runs two AStar processes asychronously, and they pass each other their updated beenThere arrays and current locations.
// If one reaches a location that the other has reached, or if the current locations are next to each other, it returns.
object BiDirAStar extends AStarBase[BiDirStepData](0.8, HeuristicLib.manhattanDistance) {

  override def apply(mapString: PathingMapString) : PathingStatus[BiDirStepData] = {
    val stepData = BiDirStepData(mapString)
    execute(primeStepData(stepData), calculateMaxIters(stepData.pathingMap.colCount, stepData.pathingMap.rowCount))
  }

  override protected def execute(stepData: BiDirStepData, maxIters: Int) : PathingStatus[BiDirStepData] = {

    val (stgStepData, stgCrumbs) = step(stepData.clone())
    val (gtsStepData, gtsCrumbs) = step(stepData.cloneForBiBackwards())

    stgStepData.assimilateBreadcrumbs(gtsCrumbs)
    gtsStepData.assimilateBreadcrumbs(stgCrumbs)

    val director = new BiDirDirector(decide(_: BiDirStepData, maxIters), step)    // decide() gets partially applied
    director.direct(stgStepData, gtsStepData)

  }

  override protected def goalIsFound(stepData: BiDirStepData, freshLoc: Coordinate2D) =
    (freshLoc overlaps stepData.goal) || (stepData hasInOthersBreadcrumbs freshLoc)

  override protected def makeNewStepData(stepData: BiDirStepData, freshLoc: Coordinate2D = BadCoordinate2D, isIncingIters: Boolean = false) =
    BiDirStepData(freshLoc, stepData, isIncingIters)

}


text: Dialog for choosing from a list of items


text:
package com.github.stephenc.intellij.plugin.generateserializationhelpers;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.generation.actions.BaseGenerateAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiAnonymousClass;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;

public class GenerateMethodAction extends BaseGenerateAction {
    public GenerateMethodAction(CodeInsightActionHandler handler) {
        super(handler);
    }

    protected PsiClass getTargetClass(Editor editor, PsiFile file) {
      final PsiClass targetClass = super.getTargetClass(editor, file);
      if (targetClass == null || targetClass instanceof PsiAnonymousClass ||
          targetClass.isEnum()) return null;
      return targetClass;
    }
}