text:
package org.opencb.biodata.tools.variant.converters.proto;

import org.junit.Before;
import org.junit.Test;
import org.opencb.biodata.models.variant.*;
import org.opencb.biodata.models.variant.avro.FileEntry;
import org.opencb.biodata.models.variant.protobuf.VcfMeta;
import org.opencb.biodata.models.variant.protobuf.VcfSliceProtos;
import org.opencb.biodata.tools.variant.converters.proto.VariantToProtoVcfRecord;
import org.opencb.biodata.tools.variant.converters.proto.VcfRecordProtoToVariantConverter;

import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**
 * Created on 05/11/15
 *
 * @author Jacobo Coll <jacobo167@gmail.com>
 */
public class VcfRecordProtoToVariantConverterTest {

    private VcfRecordProtoToVariantConverter converter;
    private VcfMeta meta;
    private VcfSliceProtos.Fields fields;

    @Before
    public void setUp() throws Exception {
        meta = new VcfMeta(new VariantSource("1", "chr1", "study1", "5"));

        meta.getVariantSource().setSamples(Arrays.asList("sample1", "sample2", "sample3", "sample4"));
        meta.setFormatDefault(Arrays.asList("GT", "DP"));
        meta.setInfoDefault(Collections.singletonList("Key"));
        meta.setFilterDefault("PASS");
        meta.setIdDefault(".");

        LinkedHashMap<String, Integer> samplePositions = new LinkedHashMap<>();
        samplePositions.put("sample1", 0);
        samplePositions.put("sample2", 1);
        samplePositions.put("sample3", 2);
        samplePositions.put("sample4", 3);

        fields = VcfSliceProtos.Fields.newBuilder()
                .addFormats("GT:DP")
                .addFormats("GT")
                .addFilters("PASS")
                .addFilters("nopass")
                .addInfoKeys("Key")
                .addInfoKeys("Key1")
                .addInfoKeys("Key2")
                .addDefaultInfoKeys(0)
                .addGts("0|0")
                .addGts("0|1")
                .addGts("1|0")
                .addGts("1|1")
                .build();

        converter = new VcfRecordProtoToVariantConverter(fields, samplePositions, meta.getVariantSource().getFileId(), meta.getVariantSource().getStudyId());

    }

    @Test
    public void testConvert() throws Exception {

        VariantToProtoVcfRecord toProto = new VariantToProtoVcfRecord();
        toProto.updateMeta(fields);

        Variant variant = new Variant("1", 5000, "A", "C");
        StudyEntry studyEntry = new StudyEntry();
        studyEntry.setFormat(Collections.singletonList("GT"));
        studyEntry.setStudyId(meta.getVariantSource().getStudyId());
        studyEntry.setSamplesData(Arrays.asList(
                Arrays.asList("0|0"),
                Arrays.asList("0|1"),
                Arrays.asList("1|0"),
                Arrays.asList("1|1")));
        Map<String, String> attributes = new HashMap<>();
        attributes.put(StudyEntry.FILTER, "nopass");
        attributes.put(StudyEntry.QUAL, "50");
        attributes.put("Key1", "V1");
        attributes.put("Key2", "V2");

        studyEntry.setFiles(Collections.singletonList(new FileEntry(meta.getVariantSource().getFileId(), "5:A:C:0", attributes)));
        variant.setStudies(Collections.singletonList(studyEntry));

        VcfSliceProtos.VcfRecord vcfRecord = toProto.convert(variant);
        assertNotEquals(0, vcfRecord.getFormatIndex());
        assertNotEquals("", vcfRecord.getFilterIndex());
        assertEquals(2, vcfRecord.getInfoKeyIndexCount());
        Variant convertedVariant = converter.convert(vcfRecord, "1", 0);

        assertEquals(variant, convertedVariant);
    }

    @Test
    public void testConvertDefaultValues() throws Exception {

        VariantToProtoVcfRecord toProto = new VariantToProtoVcfRecord();
        toProto.updateMeta(fields);

        Variant variant = new Variant("1", 5, "A", "C");
        StudyEntry studyEntry = new StudyEntry();
        studyEntry.setFormat(Arrays.asList("GT", "DP"));
        studyEntry.setStudyId("study1");
        studyEntry.setSamplesData(Arrays.asList(
                Arrays.asList("0|0", "10"),
                Arrays.asList("0|1", "20"),
                Arrays.asList("1|0", "30"),
                Arrays.asList("1|1", "40")));
        Map<String, String> attributes = new HashMap<>();
        attributes.put(StudyEntry.FILTER, "PASS");
        attributes.put(StudyEntry.QUAL, "57");
        attributes.put("Key", "Value");

        studyEntry.setFiles(Collections.singletonList(new FileEntry("chr1", "5:A:C:0", attributes)));
        variant.setStudies(Collections.singletonList(studyEntry));

        VcfSliceProtos.VcfRecord vcfRecord = toProto.convert(variant, 100);
        assertEquals(0, vcfRecord.getFormatIndex());
        assertEquals(0, vcfRecord.getFilterIndex());
        assertEquals(0, vcfRecord.getInfoKeyIndexCount());
        assertEquals(5, vcfRecord.getRelativeStart());
        Variant convertedVariant = converter.convert(vcfRecord, "1", 0);

        assertEquals(variant, convertedVariant);
    }

}


text:
require 'active_support/concern'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/inflector'
require 'embeddable/version'
require 'embeddable/engine' if defined?(Rails)
require 'embeddable/default_services'

module Embeddable
  extend ActiveSupport::Concern

  included do
    @embeddables = []
  end

  module ClassMethods
    attr_reader :embeddables

    def embeddable(name, options = {})
      source = options.fetch :from

      define_method name do
        url = send(source)
        return if url.blank?
        Service.find(url)
      end

      define_method "#{name}_type" do
        service = send(name)
        return unless service
        service.class.type.intern
      end

      define_method "#{name}_id" do
        send(name).try(:id)
      end

      define_method "#{name}?" do
        !!send("#{name}_id")
      end

      Embeddable::Service.all.each do |service|

        define_method "#{name}_on_#{service.type}?" do
          send("#{name}_type") == service.type.intern
        end

      end

      define_method "#{name}_source" do
        source
      end

      @embeddables << name
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

namespace Custom
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{*pathInfo}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


text:
/*global define*/

define([
    'underscore',
    'parse',
    'models/answer'
], function (_, Parse, AnswerModel) {
    'use strict';

    var AnswerList = Parse.Collection.extend({
        model: AnswerModel
    });

    return AnswerList;
});


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("DynamicMenu.DataLayer.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynamicMenu.DataLayer.Tests")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("40f5e461-a102-4712-81ba-29a50f23fc40")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
const func = require('../src/construct-binary-tree-from-preorder-inorder');
const assert = require('assert');
const TreeNode = require('../src/_utils/tree-node');
describe('construct-binary-tree-from-preorder-inorder', function () {
    describe('#buildTree()', function () {
        it('should return 1(2(4,5),3) when preorder is [1,2,4,5,3] and inorder is [4,2,5,1,3]', function () {
            let ret = func([1, 2, 4, 5, 3], [4, 2, 5, 1, 3]);
            assert.equal(ret.val, 1);
            assert.equal(ret.left.val, 2);
            assert.equal(ret.right.val, 3);
            assert.equal(ret.left.left.val, 4);
            assert.equal(ret.left.right.val, 5);
        });
    });
});


text:
		<fieldset id="description" pui-fieldset style="margin-bottom:20px">
			<legend>Description</legend>
			Tabbed panel component featuring client side tabs
		</fieldset>
		<fieldset id="supports" pui-fieldset style="margin-bottom:20px">
			<legend>Supports</legend>

Themeable panel components

Title can be on top or on the left, also definable by angular expressions

Tabs can be removed

Programmatic setting the active tab

User callback when tab is selected

Panel can be in an included file.

Support for changing number of tabs dynamically

puiPanel can be used to define the panel

		</fieldset>
		<fieldset id="issues" pui-fieldset style="margin-bottom:20px">
			<legend>Known issues</legend>
		</fieldset>
        <fieldset id="fixes" pui-fieldset style="margin-bottom:20px">
            <legend>History</legend>

0.3

Support for tab panels from included files

Number of tabs can be changed dynamically

puiPanel can be used to define the panel

        </fieldset>
		<fieldset id="planned" pui-fieldset style="margin-bottom:20px">
			<legend>Planned</legend>

Support of effects

Lazy loading

		</fieldset>

		<fieldset id="Configuration" pui-fieldset style="margin-bottom:20px">
			<legend>Configuration</legend>

                    Type
                    Default
                    Description

                    Array of String
                    null
                    URL's of the included files as panel

            When directive points to an object

					Name
					Type
					Default
					Description

					orientation
					String
					top
					Orientation of tab headers, "top" or "left"

					closeable
					Boolean
					false
					Can a tab be closed by the end user

					callback
					function(index)
					undefined
					Callback function when user activate a tab.

					activeElement
					int
					0
					The active tab in the view.

                    urls
                    Array of String
                    null
                    URL's of the included files as tab

		</fieldset>


text:
'use strict';

let angular = require('angular');

module.exports = angular.module('spinnaker.serverGroup.configure.gce.loadBalancer', [])
  .controller('gceServerGroupLoadBalancersCtrl', function(modalWizardService) {
    modalWizardService.getWizard().markClean('load-balancers');
    modalWizardService.getWizard().markComplete('load-balancers');

  }).name;


text:
/* eslint-env node, mocha */
/* global $database, $pg_database */
import expect from 'unexpected';

import cleanDB from '../dbCleaner';
import { getSingleton } from '../../app/app';
import { PubSub } from '../../app/models';
import { PubSubAdapter } from '../../app/support/PubSubAdapter';

import {
  authHeaders,
  createAndReturnPost,
  createCommentAsync,
  createTestUsers,
  deletePostAsync,
  goPrivate,
  goPublic,
  performJSONRequest,
  removeCommentAsync,
  updateCommentAsync,
  updatePostAsync,
} from './functional_test_helper';
import Session from './realtime-session';

describe('Backlinks in API output', () => {
  let luna, mars;
  let lunaPostId, marsPostId;

  before(async () => {
    await cleanDB($pg_database);
    [luna, mars] = await createTestUsers(['luna', 'mars']);

    ({ id: lunaPostId } = await createAndReturnPost(luna, 'Luna post'));
    ({ id: marsPostId } = await createAndReturnPost(
      mars,
      `As Luna said, example.com/${lunaPostId}`,
    ));
  });

  it(`should return Luna post with 1 backlink`, async () => {
    const resp = await performJSONRequest('GET', `/v2/posts/${lunaPostId}`);
    expect(resp, 'to satisfy', { posts: { backlinksCount: 1 } });
  });

  it(`should return Mars post by Luna post's UUID search`, async () => {
    const resp = await performJSONRequest('GET', `/v2/search?qs=${encodeURIComponent(lunaPostId)}`);
    expect(resp, 'to satisfy', { posts: [{ id: marsPostId }] });
  });

  describe('Mars becomes private', () => {
    before(() => goPrivate(mars));
    after(() => goPublic(mars));

    it(`should return Luna post with 0 backlinks to anonymous`, async () => {
      const resp = await performJSONRequest('GET', `/v2/posts/${lunaPostId}`);
      expect(resp, 'to satisfy', { posts: { backlinksCount: 0 } });
    });

    it(`should return Luna post with 0 backlinks to Luna`, async () => {
      const resp = await performJSONRequest(
        'GET',
        `/v2/posts/${lunaPostId}`,
        null,
        authHeaders(luna),
      );
      expect(resp, 'to satisfy', { posts: { backlinksCount: 0 } });
    });

    it(`should return Luna post with 1 backlink to Mars`, async () => {
      const resp = await performJSONRequest(
        'GET',
        `/v2/posts/${lunaPostId}`,
        null,
        authHeaders(mars),
      );
      expect(resp, 'to satisfy', { posts: { backlinksCount: 1 } });
    });
  });
});

describe('Backlinks in realtime', () => {
  let luna, mars;
  let lunaSession;

  before(async () => {
    await cleanDB($pg_database);
    const app = await getSingleton();
    const port = process.env.PEPYATKA_SERVER_PORT || app.context.config.port;
    const pubsubAdapter = new PubSubAdapter($database);
    PubSub.setPublisher(pubsubAdapter);

    [luna, mars] = await createTestUsers(['luna', 'mars']);
    lunaSession = await Session.create(port, 'Luna session');
    await lunaSession.sendAsync('auth', { authToken: luna.authToken });

    // Luna subscribed to her timeline
    const lunaTimeline = await luna.user.getPostsTimeline();
    await lunaSession.sendAsync('subscribe', { timeline: [lunaTimeline.id] });

    // Luna created post
    luna.post = await createAndReturnPost(luna, 'Luna post');
  });

  describe('Mars is public', () => {
    it(`should deliver 'post:update' to the Luna when Mars creates post with her post ID`, async () => {
      const test = lunaSession.receiveWhile(
        'post:update',
        async () =>
          (mars.post = await createAndReturnPost(
            mars,
            `As Luna said, example.com/${luna.post.id}`,
          )),
      );
      await expect(test, 'when fulfilled', 'to satisfy', {
        posts: { id: luna.post.id, backlinksCount: 1 },
      });
    });

    it(`should not deliver 'post:update' to the Luna when Mars updates post keeping her post ID`, async () => {
      const test = lunaSession.notReceiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, again, example.com/${luna.post.id}` }),
      );
      await expect(test, 'to be fulfilled');
    });

    it(`should deliver 'post:update' to the Luna when Mars updates post and removes her post ID`, async () => {
      const test = lunaSession.receiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, hmm...` }),
      );
      await expect(test, 'when fulfilled', 'to satisfy', {
        posts: { id: luna.post.id, backlinksCount: 0 },
      });
    });

    it(`should deliver 'post:update' to the Luna when Mars updates post and returns her post ID`, async () => {
      const test = lunaSession.receiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, again, example.com/${luna.post.id}` }),
      );
      await expect(test, 'when fulfilled', 'to satisfy', {
        posts: { id: luna.post.id, backlinksCount: 1 },
      });
    });

    it(`should deliver 'post:update' to the Luna when Mars removes post with her post ID`, async () => {
      const test = lunaSession.receiveWhile('post:update', () =>
        deletePostAsync(mars, mars.post.id),
      );
      await expect(test, 'when fulfilled', 'to satisfy', {
        posts: { id: luna.post.id, backlinksCount: 0 },
      });
    });
  });

  describe('Mars is private', () => {
    before(() => goPrivate(mars));
    after(() => goPublic(mars));

    it(`should not deliver 'post:update' to the Luna when Mars creates post with her post ID`, async () => {
      const test = lunaSession.notReceiveWhile(
        'post:update',
        async () =>
          (mars.post = await createAndReturnPost(
            mars,
            `As Luna said, example.com/${luna.post.id}`,
          )),
      );
      await expect(test, 'to be fulfilled');
    });

    it(`should not deliver 'post:update' to the Luna when Mars updates post keeping her post ID`, async () => {
      const test = lunaSession.notReceiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, again, example.com/${luna.post.id}` }),
      );
      await expect(test, 'to be fulfilled');
    });

    it(`should not deliver 'post:update' to the Luna when Mars updates post and removes her post ID`, async () => {
      const test = lunaSession.notReceiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, hmm...` }),
      );
      await expect(test, 'to be fulfilled');
    });

    it(`should not deliver 'post:update' to the Luna when Mars updates post and returns her post ID`, async () => {
      const test = lunaSession.notReceiveWhile('post:update', () =>
        updatePostAsync(mars, { body: `As Luna said, again, example.com/${luna.post.id}` }),
      );
      await expect(test, 'to be fulfilled');
    });

    it(`should not deliver 'post:update' to the Luna when Mars removes post with her post ID`, async () => {
      const test = lunaSession.notReceiveWhile('post:update', () =>
        deletePostAsync(mars, mars.post.id),
      );
      await expect(test, 'to be fulfilled');
    });
  });

  describe('Backlinks in comments', () => {
    before(async () => (mars.post = await createAndReturnPost(mars, `Just a post`)));
    after(() => deletePostAsync(mars, mars.post.id));

    describe('Mars is public', () => {
      it(`should deliver 'post:update' to the Luna when Mars creates comment with her post ID`, async () => {
        const test = lunaSession.receiveWhile(
          'post:update',
          async () =>
            ({ comments: mars.comment } = await createCommentAsync(
              mars,
              mars.post.id,
              `As Luna said, example.com/${luna.post.id}`,
            ).then((r) => r.json())),
        );
        await expect(test, 'when fulfilled', 'to satisfy', {
          posts: { id: luna.post.id, backlinksCount: 1 },
        });
      });

      it(`should not deliver 'post:update' to the Luna when Mars updates comment keeping her post ID`, async () => {
        const test = lunaSession.notReceiveWhile('post:update', () =>
          updateCommentAsync(
            mars,
            mars.comment.id,
            `As Luna said, again, example.com/${luna.post.id}`,
          ),
        );
        await expect(test, 'to be fulfilled');
      });

      it(`should deliver 'post:update' to the Luna when Mars updates comment and removes her post ID`, async () => {
        const test = lunaSession.receiveWhile('post:update', () =>
          updateCommentAsync(mars, mars.comment.id, `As Luna said, hmm...`),
        );
        await expect(test, 'when fulfilled', 'to satisfy', {
          posts: { id: luna.post.id, backlinksCount: 0 },
        });
      });

      it(`should deliver 'post:update' to the Luna when Mars updates comment and returns her post ID`, async () => {
        const test = lunaSession.receiveWhile('post:update', () =>
          updateCommentAsync(
            mars,
            mars.comment.id,
            `As Luna said, again, example.com/${luna.post.id}`,
          ),
        );
        await expect(test, 'when fulfilled', 'to satisfy', {
          posts: { id: luna.post.id, backlinksCount: 1 },
        });
      });

      it(`should deliver 'post:update' to the Luna when Mars removes comment with her post ID`, async () => {
        const test = lunaSession.receiveWhile('post:update', () =>
          removeCommentAsync(mars, mars.comment.id),
        );
        await expect(test, 'when fulfilled', 'to satisfy', {
          posts: { id: luna.post.id, backlinksCount: 0 },
        });
      });
    });

    describe('Mars is private', () => {
      before(() => goPrivate(mars));
      after(() => goPublic(mars));

      it(`should not deliver 'post:update' to the Luna when Mars creates comment with her post ID`, async () => {
        const test = lunaSession.notReceiveWhile(
          'post:update',
          async () =>
            ({ comments: mars.comment } = await createCommentAsync(
              mars,
              mars.post.id,
              `As Luna said, example.com/${luna.post.id}`,
            ).then((r) => r.json())),
        );
        await expect(test, 'to be fulfilled');
      });

      it(`should not deliver 'post:update' to the Luna when Mars updates comment keeping her post ID`, async () => {
        const test = lunaSession.notReceiveWhile('post:update', () =>
          updateCommentAsync(
            mars,
            mars.comment.id,
            `As Luna said, again, example.com/${luna.post.id}`,
          ),
        );
        await expect(test, 'to be fulfilled');
      });

      it(`should not deliver 'post:update' to the Luna when Mars updates comment and removes her post ID`, async () => {
        const test = lunaSession.notReceiveWhile('post:update', () =>
          updateCommentAsync(mars, mars.comment.id, `As Luna said, hmm...`),
        );
        await expect(test, 'to be fulfilled');
      });

      it(`should not deliver 'post:update' to the Luna when Mars updates comment and returns her post ID`, async () => {
        const test = lunaSession.notReceiveWhile('post:update', () =>
          updateCommentAsync(
            mars,
            mars.comment.id,
            `As Luna said, again, example.com/${luna.post.id}`,
          ),
        );
        await expect(test, 'to be fulfilled');
      });

      it(`should not deliver 'post:update' to the Luna when Mars removes comment with her post ID`, async () => {
        const test = lunaSession.notReceiveWhile('post:update', () =>
          removeCommentAsync(mars, mars.comment.id),
        );
        await expect(test, 'to be fulfilled');
      });
    });
  });
});


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

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>HierarchyDynamicMBean xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
17
18  package org.apache.log4j.jmx;
19
20
21  import org.apache.log4j.Appender;
22  import org.apache.log4j.Category;
23  import org.apache.log4j.Level;
24  import org.apache.log4j.LogManager;
25  import org.apache.log4j.Logger;
26  import org.apache.log4j.helpers.OptionConverter;
27  import org.apache.log4j.spi.HierarchyEventListener;
28  import org.apache.log4j.spi.LoggerRepository;
29
30  import javax.management.Attribute;
31  import javax.management.AttributeNotFoundException;
32  import javax.management.InvalidAttributeValueException;
33  import javax.management.JMException;
34  import javax.management.ListenerNotFoundException;
35  import javax.management.MBeanAttributeInfo;
36  import javax.management.MBeanConstructorInfo;
37  import javax.management.MBeanException;
38  import javax.management.MBeanInfo;
39  import javax.management.MBeanNotificationInfo;
40  import javax.management.MBeanOperationInfo;
41  import javax.management.MBeanParameterInfo;
42  import javax.management.Notification;
43  import javax.management.NotificationBroadcaster;
44  import javax.management.NotificationBroadcasterSupport;
45  import javax.management.NotificationFilter;
46  import javax.management.NotificationFilterSupport;
47  import javax.management.NotificationListener;
48  import javax.management.ObjectName;
49  import javax.management.ReflectionException;
50  import javax.management.RuntimeOperationsException;
51  import java.lang.reflect.Constructor;
52  import java.util.Vector;
53
54  public class HierarchyDynamicMBean extends AbstractDynamicMBean
55                                     implements HierarchyEventListener,
56                                                NotificationBroadcaster {
57
58    static final String ADD_APPENDER = "addAppender.";
59    static final String THRESHOLD = "threshold";
60
61    private MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
62    private MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
63
64    private Vector vAttributes = new Vector();
65    private String dClassName = this.getClass().getName();
66    private String dDescription =
67       "This MBean acts as a management facade for org.apache.log4j.Hierarchy.";
68
69    private NotificationBroadcasterSupport nbs = new NotificationBroadcasterSupport();
70
71
72    private LoggerRepository hierarchy;
73
74    private static Logger log = Logger.getLogger(HierarchyDynamicMBean.class);
75
76    public HierarchyDynamicMBean() {
77      hierarchy = LogManager.getLoggerRepository();
78      buildDynamicMBeanInfo();
79    }
80
81    private
82    void buildDynamicMBeanInfo() {
83      Constructor[] constructors = this.getClass().getConstructors();
84      dConstructors[0] = new MBeanConstructorInfo(
85           "HierarchyDynamicMBean(): Constructs a HierarchyDynamicMBean instance",
86  	 constructors[0]);
87
88      vAttributes.add(new MBeanAttributeInfo(THRESHOLD,
89  					   "java.lang.String",
90  					   "The \"threshold\" state of the hiearchy.",
91  					   true,
92  					   true,
93  					   false));
94
95      MBeanParameterInfo[] params = new MBeanParameterInfo[1];
96      params[0] = new MBeanParameterInfo("name", "java.lang.String",
97  				       "Create a logger MBean" );
98      dOperations[0] = new MBeanOperationInfo("addLoggerMBean",
99  				    "addLoggerMBean(): add a loggerMBean",
100 				    params ,
101 				    "javax.management.ObjectName",
102 				    MBeanOperationInfo.ACTION);
103   }
104
105
106   public
107   ObjectName addLoggerMBean(String name) {
108     Logger cat = LogManager.exists(name);
109
110     if(cat != null) {
111       return addLoggerMBean(cat);
112     } else {
113       return null;
114     }
115   }
116
117   ObjectName addLoggerMBean(Logger logger) {
118     String name = logger.getName();
119     ObjectName objectName = null;
120     try {
121       LoggerDynamicMBean loggerMBean = new LoggerDynamicMBean(logger);
122       objectName = new ObjectName("log4j", "logger", name);
123
124       if (!server.isRegistered(objectName)) {
125         registerMBean(loggerMBean, objectName);
126         NotificationFilterSupport nfs = new NotificationFilterSupport();
127         nfs.enableType(ADD_APPENDER + logger.getName());
128         log.debug("---Adding logger [" + name + "] as listener.");
129         nbs.addNotificationListener(loggerMBean, nfs, null);
130         vAttributes.add(new MBeanAttributeInfo("logger=" + name, "javax.management.ObjectName",
131                 "The " + name + " logger.", true, true, // this makes the object
132                 // clickable
133                 false));
134
135       }
136
137     } catch(JMException e) {
138       log.error("Could not add loggerMBean for ["+name+"].", e);
139     } catch(RuntimeException e) {
140       log.error("Could not add loggerMBean for ["+name+"].", e);
141     }
142     return objectName;
143   }
144
145   public
146   void addNotificationListener(NotificationListener listener,
147 			       NotificationFilter filter,
148 			       java.lang.Object handback) {
149     nbs.addNotificationListener(listener, filter, handback);
150   }
151
152   protected
153   Logger getLogger() {
154     return log;
155   }
156
157   public
158   MBeanInfo getMBeanInfo() {
159     //cat.debug("getMBeanInfo called.");
160
161     MBeanAttributeInfo[] attribs = new MBeanAttributeInfo[vAttributes.size()];
162     vAttributes.toArray(attribs);
163
164     return new MBeanInfo(dClassName,
165 			 dDescription,
166 			 attribs,
167 			 dConstructors,
168 			 dOperations,
169 			 new MBeanNotificationInfo[0]);
170   }
171
172   public
173   MBeanNotificationInfo[] getNotificationInfo(){
174     return nbs.getNotificationInfo();
175   }
176
177   public
178   Object invoke(String operationName,
179 		Object params[],
180 		String signature[]) throws MBeanException,
181                                            ReflectionException {
182
183     if (operationName == null) {
184       throw new RuntimeOperationsException(
185         new IllegalArgumentException("Operation name cannot be null"),
186 	"Cannot invoke a null operation in " + dClassName);
187     }
188     // Check for a recognized operation name and call the corresponding operation
189
190     if(operationName.equals("addLoggerMBean")) {
191       return addLoggerMBean((String)params[0]);
192     } else {
193       throw new ReflectionException(
194 	    new NoSuchMethodException(operationName),
195 	    "Cannot find the operation " + operationName + " in " + dClassName);
196     }
197
198   }
199
200
201   public
202   Object getAttribute(String attributeName) throws AttributeNotFoundException,
203                                                     MBeanException,
204                                                     ReflectionException {
205
206     // Check attributeName is not null to avoid NullPointerException later on
207     if (attributeName == null) {
208       throw new RuntimeOperationsException(new IllegalArgumentException(
209 			"Attribute name cannot be null"),
210        "Cannot invoke a getter of " + dClassName + " with null attribute name");
211     }
212
213     log.debug("Called getAttribute with ["+attributeName+"].");
214
215     // Check for a recognized attributeName and call the corresponding getter
216     if (attributeName.equals(THRESHOLD)) {
217       return hierarchy.getThreshold();
218     } else if(attributeName.startsWith("logger")) {
219       int k = attributeName.indexOf("%3D");
220       String val = attributeName;
221       if(k > 0) {
222 	val = attributeName.substring(0, k)+'='+ attributeName.substring(k+3);
223       }
224       try {
225 	return new ObjectName("log4j:"+val);
226       } catch(JMException e) {
227 	    log.error("Could not create ObjectName" + val);
228       } catch(RuntimeException e) {
229 	    log.error("Could not create ObjectName" + val);
230       }
231     }
232
233
234
235     // If attributeName has not been recognized throw an AttributeNotFoundException
236     throw(new AttributeNotFoundException("Cannot find " + attributeName +
237 					 " attribute in " + dClassName));
238
239   }
240
241
242   public
243   void addAppenderEvent(Category logger, Appender appender) {
244     log.debug("addAppenderEvent called: logger="+logger.getName()+
245 	      ", appender="+appender.getName());
246     Notification n = new Notification(ADD_APPENDER+logger.getName(), this, 0);
247     n.setUserData(appender);
248     log.debug("sending notification.");
249     nbs.sendNotification(n);
250   }
251
252  public
253   void removeAppenderEvent(Category cat, Appender appender) {
254     log.debug("removeAppenderCalled: logger="+cat.getName()+
255 	      ", appender="+appender.getName());
256   }
257
258   public
259   void postRegister(java.lang.Boolean registrationDone) {
260     log.debug("postRegister is called.");
261     hierarchy.addHierarchyEventListener(this);
262     Logger root = hierarchy.getRootLogger();
263     addLoggerMBean(root);
264   }
265
266   public
267   void removeNotificationListener(NotificationListener listener)
268                                          throws ListenerNotFoundException {
269     nbs.removeNotificationListener(listener);
270   }
271
272   public
273   void setAttribute(Attribute attribute) throws AttributeNotFoundException,
274                                                 InvalidAttributeValueException,
275                                                 MBeanException,
276                                                 ReflectionException {
277
278     // Check attribute is not null to avoid NullPointerException later on
279     if (attribute == null) {
280       throw new RuntimeOperationsException(
281                   new IllegalArgumentException("Attribute cannot be null"),
282 	  "Cannot invoke a setter of "+dClassName+" with null attribute");
283     }
284     String name = attribute.getName();
285     Object value = attribute.getValue();
286
287     if (name == null) {
288       throw new RuntimeOperationsException(
289                new IllegalArgumentException("Attribute name cannot be null"),
290 	       "Cannot invoke the setter of "+dClassName+
291 	       " with null attribute name");
292     }
293
294     if(name.equals(THRESHOLD)) {
295       Level l = OptionConverter.toLevel((String) value,
296 					   hierarchy.getThreshold());
297       hierarchy.setThreshold(l);
298     }
299
300
301   }
302 }

This page was automatically generated by Maven


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Manish Bisht">
    <link rel="icon" href="images/Logo.jpg">

    <title>Profile Reader by Manish Bisht</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/cover.css" rel="stylesheet">

ProfileReader

           <form class="form-horizontal" action="search.html" method="get">

                 <input type="text" name="user" id="user" class="form-control input-lg" placeholder="Enter the name of any person">

                    <input type="submit" value="Search" class="btn btn-primary btn-block btn-lg">

                    <input type="reset" value="Reset" class="btn btn-primary btn-block btn-lg">

           </form>

NOTE : We currently supports the profiles that are uploaded on Wikipedia

Designed, Developed and Maintained by Manish Bisht


text:
// Licensed to .NET HTTP Abstractions (the "Project") under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The Project licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using Taco.Helpers.Utils;

namespace Taco.Helpers {
    public class Response {
        readonly Action<int, IDictionary<string, string>, IObservable<Cargo<ArraySegment<byte>>>> _result;

        int _status = 200;
        readonly IDictionary<string, string> _headers = new Dictionary<string, string>();
        readonly Body _body = new Body();

        public Response(Action<int, IDictionary<string, string>, IObservable<Cargo<ArraySegment<byte>>>> result) {
            _result = result;
        }

        public int Status {
            get { return _status; }
            set { _status = value; }
        }

        public string ContentType {
            get { return GetHeader("Content-Type"); }
            set { SetHeader("Content-Type", value); }
        }

        string GetHeader(string name) {
            string value;
            return _headers.TryGetValue(name, out value) ? value.Replace("\r\n", ",") : null;
        }

        public void SetHeader(string name, string value) {
            _headers.Remove(name);
            AddHeader(name, value);
        }

        public void AddHeader(string name, string value) {
            var sanitized = (value ?? "").Replace("\r", "").Replace("\n", "");
            if (string.IsNullOrWhiteSpace(sanitized))
                return;

            string existing;
            _headers[name] = _headers.TryGetValue(name, out existing) ? existing + "\r\n" + sanitized : sanitized;
        }

        public Response Write(object data) {
            _body.Write(data);
            return this;
        }

        public void Finish() {
            _result(Status, _headers, _body.Attach((fault, complete) => {
                complete();
                return () => { };
            }));
        }

        public void Finish(Action<Action<Exception>, Action> block) {
            _result(Status, _headers, _body.Attach((fault, complete) => {
                block(fault, complete);
                return () => { };
            }));
        }

        public void Finish(Action block) {
            _result(Status, _headers, _body.Attach((fault, complete) => {
                block();
                complete();
                return () => { };
            }));
        }

        public void Finish(Func<Action<Exception>, Action, Action> block) {
            _result(Status, _headers, _body.Attach(block));
        }

        public void Finish(IObservable<Cargo<ArraySegment<byte>>> body) {
            _result(Status, _headers, _body.Attach(body.Subscribe));
        }

        public void Finish(Func<Action<Cargo<ArraySegment<byte>>>, Action<Exception>, Action, IDisposable> subscribe) {
            _result(Status, _headers, _body.Attach(subscribe));
        }

        class Body : IObservable<Cargo<ArraySegment<byte>>> {
            readonly IList<object> _body = new List<object>();
            Func<Action<Cargo<ArraySegment<byte>>>, Action<Exception>, Action, IDisposable> _subscribe;

            public Body() {
                Write = _body.Add;
            }

            public Action<object> Write;

            public IObservable<Cargo<ArraySegment<byte>>> Attach(Func<Action<Exception>, Action, Action> block) {
                return Attach((next, fault, complete) => new Disposable(block(fault, complete)));
            }

            public IObservable<Cargo<ArraySegment<byte>>> Attach(Func<Action<Cargo<ArraySegment<byte>>>, Action<Exception>, Action, IDisposable> subscribe) {
                _subscribe = subscribe;
                return this;
            }

            public IDisposable Subscribe(IObserver<Cargo<ArraySegment<byte>>> observer) {
                try {
                    Write = data => observer.OnNext(Cargo.From(Normalize(data)));
                    foreach (var piece in _body) {
                        observer.OnNext(Cargo.From(Normalize(piece)));
                    }
                    return _subscribe(observer.OnNext, observer.OnError, observer.OnCompleted);
                }
                catch (Exception ex) {
                    observer.OnError(ex);
                    return Disposable.Noop;
                }
            }

            ArraySegment<byte> Normalize(object data) {
                if (data is ArraySegment<byte>)
                    return (ArraySegment<byte>)data;
                if (data is byte[])
                    return new ArraySegment<byte>((byte[])data);

                //todo: have response encoding in environment?
                return new ArraySegment<byte>(Encoding.Default.GetBytes(Convert.ToString(data)));
            }
        }
    }
}


text:
enum
{
    LINE_SPACE = 40,
    kItemTagBasic = 1000,
};

static struct
{
	const char *name;
	std::function<void(Ref* sender)> callback;
}
g_guisTests[] =
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    {
        "VideoPlayerTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIVideoPlayerTest);
            sceneManager->setMinUISceneId(kUIVideoPlayerTest);
            sceneManager->setMaxUISceneId(kUIVideoPlayerTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
    },
#endif
    {
        "focus test",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(KUIFocusTest_HBox);
            sceneManager->setMinUISceneId(KUIFocusTest_HBox);
            //TODO: improve ListView focus
            sceneManager->setMaxUISceneId(KUIFocusTest_NestedLayout3);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
    },
	{

        "ButtonTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIButtonTest);
            sceneManager->setMinUISceneId(kUIButtonTest);
            sceneManager->setMaxUISceneId(kUIButtonTest_Title);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "CheckBoxTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUICheckBoxTest);
            sceneManager->setMinUISceneId(kUICheckBoxTest);
            sceneManager->setMaxUISceneId(kUICheckBoxTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
	{
        "SliderTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUISliderTest);
            sceneManager->setMinUISceneId(kUISliderTest);
            sceneManager->setMaxUISceneId(kUISliderTest_Scale9);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "ImageViewTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIImageViewTest);
            sceneManager->setMinUISceneId(kUIImageViewTest);
            sceneManager->setMaxUISceneId(kUIImageViewTest_Scale9);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "LoadingBarTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUILoadingBarTest_Left);
            sceneManager->setMinUISceneId(kUILoadingBarTest_Left);
            sceneManager->setMaxUISceneId(kUILoadingBarTest_Right_Scale9);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "TextAtalsTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUITextAtlasTest);
            sceneManager->setMinUISceneId(kUITextAtlasTest);
            sceneManager->setMaxUISceneId(kUITextAtlasTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "TextTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUITextTest);
            sceneManager->setMinUISceneId(kUITextTest);
            sceneManager->setMaxUISceneId(kUITextTest_TTF);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "TextBMFontTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUITextBMFontTest);
            sceneManager->setMinUISceneId(kUITextBMFontTest);
            sceneManager->setMaxUISceneId(kUITextBMFontTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "TextFieldTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUITextFieldTest);
            sceneManager->setMinUISceneId(kUITextFieldTest);
            sceneManager->setMaxUISceneId(kUITextFieldTest_TrueTypeFont);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "LayoutTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUILayoutTest);
            sceneManager->setMinUISceneId(kUILayoutTest);
            sceneManager->setMaxUISceneId(kUILayoutTest_Layout_Relative_Location);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "ScrollViewTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIScrollViewTest_Vertical);
            sceneManager->setMinUISceneId(kUIScrollViewTest_Vertical);
            sceneManager->setMaxUISceneId(kUIScrollViewTest_ScrollToPercentBothDirection_Bounce);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "PageViewTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIPageViewTest);
            sceneManager->setMinUISceneId(kUIPageViewTest);
            sceneManager->setMaxUISceneId(kUIPageViewButtonTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "ListViewTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIListViewTest_Vertical);
            sceneManager->setMinUISceneId(kUIListViewTest_Vertical);
            sceneManager->setMaxUISceneId(kUIListViewTest_Horizontal);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "WidgetAddNodeTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIWidgetAddNodeTest);
            sceneManager->setMinUISceneId(kUIWidgetAddNodeTest);
            sceneManager->setMaxUISceneId(kUIWidgetAddNodeTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},
    {
        "RichTextTest",
        [](Ref* sender)
        {
            UISceneManager* sceneManager = UISceneManager::sharedUISceneManager();
            sceneManager->setCurrentUISceneId(kUIRichTextTest);
            sceneManager->setMinUISceneId(kUIRichTextTest);
            sceneManager->setMaxUISceneId(kUIRichTextTest);
            Scene* scene = sceneManager->currentUIScene();
            Director::getInstance()->replaceScene(scene);
        }
	},

};

static const int g_maxTests = sizeof(g_guisTests) / sizeof(g_guisTests[0]);

static Vec2 s_tCurPos = Vec2::ZERO;

////////////////////////////////////////////////////////
//
// CocosGUITestMainLayer
//
////////////////////////////////////////////////////////
void CocosGUITestMainLayer::onEnter()
{
    Layer::onEnter();

    auto s = Director::getInstance()->getWinSize();

    _itemMenu = Menu::create();
    _itemMenu->setPosition( s_tCurPos );
    MenuItemFont::setFontName("fonts/arial.ttf");
    MenuItemFont::setFontSize(24);
    for (int i = 0; i < g_maxTests; ++i)
    {
        auto pItem = MenuItemFont::create(g_guisTests[i].name, g_guisTests[i].callback);
        pItem->setPosition(Vec2(s.width / 2, s.height - (i + 1) * LINE_SPACE));
        _itemMenu->addChild(pItem, kItemTagBasic + i);
    }

    auto listener = EventListenerTouchAllAtOnce::create();
    listener->onTouchesBegan = CC_CALLBACK_2(CocosGUITestMainLayer::onTouchesBegan, this);
    listener->onTouchesMoved = CC_CALLBACK_2(CocosGUITestMainLayer::onTouchesMoved, this);

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    addChild(_itemMenu);
}

void CocosGUITestMainLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event  *event)
{
    auto touch = static_cast<Touch*>(touches[0]);

    _beginPos = touch->getLocation();
}

void CocosGUITestMainLayer::onTouchesMoved(const std::vector<Touch*>& touches, Event  *event)
{
    auto touch = static_cast<Touch*>(touches[0]);

    auto touchLocation = touch->getLocation();
    float nMoveY = touchLocation.y - _beginPos.y;

    auto curPos  = _itemMenu->getPosition();
    auto nextPos = Vec2(curPos.x, curPos.y + nMoveY);

    if (nextPos.y < 0.0f)
    {
        _itemMenu->setPosition(Vec2::ZERO);
        return;
    }

    if (nextPos.y > ((g_maxTests + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))
    {
        _itemMenu->setPosition(Vec2(0, ((g_maxTests + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)));
        return;
    }

    _itemMenu->setPosition(nextPos);
    _beginPos = touchLocation;
    s_tCurPos   = nextPos;
}

////////////////////////////////////////////////////////
//
// CocosGUITestScene
//
////////////////////////////////////////////////////////

void CocosGUITestScene::onEnter()
{
    Scene::onEnter();

    auto label = Label::createWithTTF("Back", "fonts/arial.ttf", 20);
    //#endif
    auto pMenuItem = MenuItemLabel::create(label, CC_CALLBACK_1(CocosGUITestScene::BackCallback, this));

    Menu* pMenu =Menu::create(pMenuItem, nullptr);

    pMenu->setPosition( Vec2::ZERO );
    pMenuItem->setPosition( Vec2( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) );

    addChild(pMenu, 1);
}

void CocosGUITestScene::runThisTest()
{
    auto layer = new CocosGUITestMainLayer();
    addChild(layer);
    layer->release();

    Director::getInstance()->replaceScene(this);
}

void CocosGUITestScene::BackCallback(Ref* pSender)
{
    CocoStudioGUITestScene* pScene = new CocoStudioGUITestScene();
    pScene->runThisTest();
    pScene->release();
}


text:
import constants from '../constants';
import { getCardIndex } from '../cardUtils'
import update from 'react-addons-update';

const initialState = [];
const initialAction = { type: 'initial state'}

const cards = (state = initialState, action = initialAction) => {
    switch (action.type) {
      case constants.FETCH_CARDS_SUCCESS:
        return action.payload.response;
      /*
       * Card Creation
       */
      case constants.CREATE_CARD:
        return update(state, {$push: [action.payload.card] })

      case constants.CREATE_CARD_SUCCESS:
        cardIndex = getCardIndex(state, action.payload.card.id);
        return update(state, {
          [cardIndex]: {
            id: { $set: action.payload.response.id }
          }
        });

      case constants.CREATE_CARD_ERROR:
        cardIndex = getCardIndex(state, action.payload.card.id);
        return update(state, { $splice:[[cardIndex, 1]]});

      /*
       * Card Status Toggle
       */
      case constants.TOGGLE_CARD_DETAILS:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            showDetails: { $apply: (currentValue) => (currentValue !== false)? false : true }
          }
        });

      /*
       * Card Update
       */
      case constants.UPDATE_CARD:
        cardIndex = getCardIndex(state, action.payload.card.id);
        return update(state, {
          [cardIndex]: {
            $set: action.payload.draftCard
          }
        });

      case constants.UPDATE_CARD_ERROR:
        cardIndex = getCardIndex(state, action.payload.card.id);
        return update(state, {
          [cardIndex]: {
            $set: action.payload.card
          }
        });

      /*
       * Card Drag'n Drop
       */
      case constants.UPDATE_CARD_POSITION:
        if(action.payload.cardId !== action.payload.afterId) {
          cardIndex = getCardIndex(state, action.payload.cardId);
          let card = state[cardIndex]
          let afterIndex = getCardIndex(state, action.payload.afterId);
          return update(state, {
            $splice: [
              [cardIndex, 1],
              [afterIndex, 0, card]
            ]
          });
        }

      case constants.UPDATE_CARD_STATUS:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            status: { $set: action.payload.listId }
          }
        });

      case constants.PERSIST_CARD_DRAG_ERROR:
        cardIndex = getCardIndex(state, action.payload.cardProps.id);
        return update(state, {
          [cardIndex]: {
            status: { $set: action.cardProps.status }
          }
        });

      /*
       * Task Creation
       */
      case constants.CREATE_TASK:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            tasks: {$push: [action.payload.task] }
          }
        });

      case constants.CREATE_TASK_SUCCESS:
        cardIndex = getCardIndex(state, action.payload.cardId);
        taskIndex = state[cardIndex].tasks.findIndex((task)=>(
          task.id == action.payload.task.id
        ));
        return update(state, {
          [cardIndex]: {
            tasks: {
              [taskIndex]: {
                id: { $set: action.payload.response.id }
              }
            }
          }
        });

      case constants.CREATE_TASK_ERROR:
        let cardIndex = getCardIndex(state, action.payload.cardId);
        let taskIndex = state[cardIndex].tasks.findIndex((task)=>(
          task.id == action.payload.task.id
        ));
        return update(state, {
          [cardIndex]: {
            tasks: {
              $splice:[[taskIndex, 1]]
            }
          }
        });

      /*
       * Task Deletion
       */
      case constants.DELETE_TASK:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            tasks: {$splice: [[action.payload.taskIndex,1]] }
          }
        });

      case constants.DELETE_TASK_ERROR:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            tasks: {$splice: [[action.payload.taskIndex, 0, action.payload.task]] }
          }
        });

      /*
       * Task Toggling
       */
      case constants.TOGGLE_TASK:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            tasks: {
              [action.payload.taskIndex]: { done: { $apply: (done) => !done }}
            }
          }
        });

      case constants.TOGGLE_TASK_ERROR:
        cardIndex = getCardIndex(state, action.payload.cardId);
        return update(state, {
          [cardIndex]: {
            tasks: {
              [action.payload.taskIndex]: { done: { $apply: (done) => !done }}
            }
          }
        });

      default:
        return state;
    }
}

export default cards;


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by fedotk on 3/2/2016.
 */
public class ContactDeletionTests extends TestBase {
  @BeforeMethod
  public void ensurePreconditions() {
    app.goTo().homePage();
    if (app.db().contacts().size() == 0) {
      app.contact().create(new ContactData().withFirstname("Name1").withLastname("Name2"));
    }
  }

  @Test(enabled = true)
  public void testContactDeletion() {
    app.goTo().homePage();
    Contacts before = app.db().contacts();
//    Contacts before = app.contact().all(); //создаем список контактов до
    ContactData deletedContact = before.iterator().next();
    app.contact().delete(deletedContact);
//    app.goTo().homePage();
    assertThat(app.contact().count(), equalTo(before.size() - 1));
    Contacts after = app.db().contacts();
//    Contacts after = app.contact().all(); //создаем список контакто после
//    Assert.assertEquals(after.size(), before.size() - 1);
    assertThat(after, equalTo(before.without(deletedContact)));
    verifyGroupListInUI();
  }

}


text:
	union array ## __ ## name { struct array arr; array_type const *const *v; array_type **v_modifiable; }
#define ARRAY_TYPE(name) \
	union array ## __ ## name

struct array {
	buffer_t *buffer;
	size_t element_size;
};

ARRAY_DEFINE_TYPE(string, char *);
ARRAY_DEFINE_TYPE(const_string, const char *);
ARRAY_DEFINE_TYPE(uint32_t, uint32_t);
ARRAY_DEFINE_TYPE(uint, unsigned int);
ARRAY_DEFINE_TYPE(void_array, void *);

#endif


text: <input type="radio" value="{{option.option_value}}" ng-model="field.field_value" ng-disabled="!field.field_disabled" />


text:
define( "JBrowse/View/FileDialog", [
            'dojo/_base/declare',
            'dojo/_base/array',
            'dojo/aspect',
            'dojo/on',
            'dijit/focus',
            'dijit/form/Button',
            'dijit/form/RadioButton',
            'dojo/dom-construct',
            'dijit/Dialog',
            'dojox/form/Uploader',
            'dojox/form/uploader/plugins/IFrame',
            './FileDialog/TrackList/BAMDriver',
            './FileDialog/TrackList/BigWigDriver',
            './FileDialog/TrackList/GFF3Driver',
            './FileDialog/TrackList/GTFDriver',
            './FileDialog/TrackList/VCFTabixDriver',
            './FileDialog/ResourceList',
            './FileDialog/TrackList',
            'JBrowse/Util'
        ],
        function(
            declare,
            array,
            aspect,
            on,
            dijitFocus,
            Button,
            RadioButton,
            dom,
            Dialog,
            Uploaded,
            IFramePlugin,
            BAMDriver,
            BigWigDriver,
            GFF3Driver,
            GTFDriver,
            VCFTabixDriver,
            ResourceList,
            TrackList,
            Util
        ) {

return declare( null, {

    constructor: function( args ) {
        this.browser = args.browser;
        this.config = dojo.clone( args.config || {} );
        this.browserSupports = {
            dnd: 'draggable' in document.createElement('span')
        };

        this._fileTypeDrivers = [ new BAMDriver(), new BigWigDriver(), new GFF3Driver(), new GTFDriver(), new VCFTabixDriver() ];
    },

    addFileTypeDriver: function( d ) {
        this._fileTypeDrivers.unshift( d );
    },
    getFileTypeDrivers: function() {
        return this._fileTypeDrivers.slice();
    },

    _makeActionBar: function( openCallback, cancelCallback ) {
        var actionBar = dom.create(
            'div', {
                className: 'dijitDialogPaneActionBar'
            });

        var disChoices = this.trackDispositionChoice = [
            new RadioButton({ id: 'openImmediately',
                              value: 'openImmediately',
                              checked: true
                            }),
            new RadioButton({ id: 'addToTrackList',
                              value: 'addToTrackList'
                            })
        ];

        var aux = dom.create('div',{className:'aux'},actionBar);
        disChoices[0].placeAt(aux);
        dom.create('label', { "for": 'openImmediately', innerHTML: 'Open immediately' }, aux ),
        disChoices[1].placeAt(aux);
        dom.create('label', { "for": 'addToTrackList', innerHTML: 'Add to tracks' }, aux );

        new Button({ iconClass: 'dijitIconDelete', label: 'Cancel',
                     onClick: dojo.hitch( this, function() {
                                              cancelCallback && cancelCallback();
                                              this.dialog.hide();
                                          })
                   })
            .placeAt( actionBar );
        new Button({ iconClass: 'dijitIconFolderOpen',
                     label: 'Open',
                     onClick: dojo.hitch( this, function() {
                         openCallback && openCallback({
                             trackConfs: this.trackList.getTrackConfigurations(),
                             trackDisposition: this.trackDispositionChoice[0].checked ? this.trackDispositionChoice[0].value :
                                               this.trackDispositionChoice[1].checked ? this.trackDispositionChoice[1].value :
                                                                                undefined
                         });
                         this.dialog.hide();
                     })
                   })
            .placeAt( actionBar );

        return { domNode: actionBar };
    },

    show: function( args ) {
        var dialog = this.dialog = new Dialog(
            { title: "Open files", className: 'fileDialog' }
            );

        var localFilesControl   = this._makeLocalFilesControl();
        var remoteURLsControl   = this._makeRemoteURLsControl();
        var resourceListControl = this._makeResourceListControl();
        var trackListControl    = this._makeTrackListControl();
        var actionBar           = this._makeActionBar( args.openCallback, args.cancelCallback );

        // connect the local files control to the resource list
        if( !Util.isElectron() ) {
            dojo.connect( localFilesControl.uploader, 'onChange', function() {
                resourceListControl.addLocalFiles( localFilesControl.uploader._files );
            });
        }
        else {
            on( localFilesControl.uploader, 'click', function() {
                var remote = electronRequire('remote');
                var app = remote.require('app');
                var dialog = remote.require('dialog');
                var ret = dialog.showOpenDialog({ properties: [ 'openFile','multiSelections' ]});
                if( ret ) {
                    var paths = array.map( ret, function(replace) { return Util.replacePath(replace); });
                    resourceListControl.addURLs( paths );
                }
            });
        }

        // connect the remote URLs control to the resource list
        dojo.connect( remoteURLsControl, 'onChange', function( urls ) {
            resourceListControl.clearURLs();
            resourceListControl.addURLs( urls );
        });

        // connect the resource list to the track list
        dojo.connect( resourceListControl, 'onChange', function( resources ) {
            trackListControl.update( resources );
        });

        var div = function( attr, children ) {
            var d = dom.create('div', attr );
            array.forEach( children, dojo.hitch( d, 'appendChild' ));
            return d;
        };
        var content = [
                dom.create( 'div', { className: 'intro', innerHTML: args.introMsg||'Add any combination of data files and URLs, and JBrowse will automatically suggest tracks to display their contents.' } ),
                div( { className: 'resourceControls' },
                     [ localFilesControl.domNode, remoteURLsControl.domNode ]
                   ),
                resourceListControl.domNode,
                trackListControl.domNode,
                actionBar.domNode
        ];
        dialog.set( 'content', content );
        dialog.show();

        aspect.after( dialog, 'hide', dojo.hitch( this, function() {
                              dijitFocus.curNode && dijitFocus.curNode.blur();
                              setTimeout( function() { dialog.destroyRecursive(); }, 500 );
                      }));
    },

    _makeLocalFilesControl: function() {
        var container = dom.create('div', { className: 'localFilesControl' });

        dom.create('h3', { innerHTML: 'Local files' }, container );

        var dragArea = dom.create('div', { className: 'dragArea' }, container );
        var fileBox;
        if( Util.isElectron() ) {
            fileBox = dom.create('input', { type: 'button', value: 'Select files...', id: 'openFile' }, dragArea );
        }
        else {
            fileBox = new dojox.form.Uploader({
                multiple: true
            });
            fileBox.placeAt( dragArea );
            if( this.browserSupports.dnd ) {
                // let the uploader process any files dragged into the dialog
                fileBox.addDropTarget( this.dialog.domNode );

                // add a message saying you can drag files in
                dom.create(
                    'div', {
                        className: 'dragMessage',
                        innerHTML: 'Select or drag files here.'
                    }, dragArea
                );
            }
        }

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return { domNode: container, uploader: fileBox };
    },

    _makeRemoteURLsControl: function() {
        var container = dom.create('div', { className: 'remoteURLsControl' });

        // make the input elements
        dom.create('h3', { innerHTML: 'Remote URLs - <smaller>one per line</smaller>' }, container );

        // the onChange here will be connected to by the other parts
        // of the dialog to propagate changes to the text in the box
        var self = { domNode: container,
                     onChange: function(urls) {
                         //console.log('urls changed');
                     }
                   };
        self.input = dom.create( 'textarea', {
                                     className: 'urlInput',
                                     placeHolder: "http://paste.urls.here/example.bam",
                                     cols: 25,
                                     rows: 5,
                                     spellcheck: false
                                 }, container );

        // set up the handlers to propagate changes
        var realChange = function() {
            var text = dojo.trim( self.input.value );
            var urls = text.length ? text.split( /\s+/ ) : [];
            self.onChange( urls );
        };
        // watch the input text for changes.  just do it every 900ms
        // because there are many ways that text can get changed (like
        // pasting), not all of which fire the same events.  not using
        // the onchange event, because that doesn't fire until the
        // textarea loses focus.
        var previousText = '';
        var checkFrequency = 900;
        var checkForChange = function() {
            // compare with all whitespace changed to commas so that
            // we are insensitive to changes in whitespace
            if( self.input.value.replace(/\s+/g,',') != previousText ) {
                realChange();
                previousText = self.input.value.replace(/\s+/g,',');
            }
            window.setTimeout( checkForChange, checkFrequency );
        };
        window.setTimeout( checkForChange, checkFrequency );

        // little elements used to show pipeline-like connections between the controls
        dom.create( 'div', { className: 'connector', innerHTML: ' '}, container );

        return self;
    },

    _makeResourceListControl: function () {
        var rl = new ResourceList({ dialog: this });
        return rl;
    },
    _makeTrackListControl: function() {
        var tl = new TrackList({ browser: this.browser, fileDialog: this });
        this.trackList = tl;
        return tl;
    }
});
});


text:
package com.seguim.example.controllers;

import com.seguim.Controller;
import com.seguim.controllers.AbstractController;
import com.sun.net.httpserver.HttpExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * Date: 12/12/14.
 * Time: 14:21
 */
@Controller("/index")
public class IndexController extends AbstractController {

	@Override
	public Map get(Map data, HttpExchange t) {
		System.out.println("Called /index with GET method.");
		System.out.println(" data = " + data);
		Map<String, String> map = new HashMap<String, String>();
		map.put("Hello", "World!");
		return map;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Request version="1.0">
  <Header>
    <Security sender="{{sender}}"/>
  </Header>
  <Transaction channel="{{channel}}" mode="CONNECTOR_TEST">
    <User pwd="{{pwd}}" login="{{login}}"/>
    <Identification>
      <TransactionID>42</TransactionID>
      <ShopperID>customerid123456</ShopperID>
    </Identification>
    <Payment code="VA.PA">
      <Presentation>
        <Amount>359.98</Amount>
        <Usage>Cart Trx 42</Usage>
        <Currency>EUR</Currency>
      </Presentation>
    </Payment>
    <Customer>
      <Contact>
        <Email>whitelist-test@payolution.com</Email>
        <Ip>192.168.0.1</Ip>
      </Contact>
      <Address>
        <Street>Spengergasse 37</Street>
        <Zip>1050</Zip>
        <City>Wien</City>
        <Country>AT</Country>
      </Address>
      <Name>
        <Given>Max</Given>
        <Family>Mustermann</Family>
        <Sex>M</Sex>
        <Birthdate>1970-01-30</Birthdate>
      </Name>
    </Customer>
    <Account>
      <Brand>PAYOLUTION_INVOICE</Brand>
    </Account>
    <Analysis>
      <Criterion name="PAYOLUTION_PRE_CHECK">TRUE</Criterion>
      <Criterion name="PAYOLUTION_CUSTOMER_LANGUAGE">de</Criterion>
      <Criterion name="PAYOLUTION_CUSTOMER_REGISTRATION_LEVEL">0</Criterion>
      <Criterion name="PAYOLUTION_TAX_AMOUNT">50.98</Criterion>
      <Criterion name="PAYOLUTION_REQUEST_SYSTEM_VENDOR">CustomSystemName_ProgrammingLanguage_XML</Criterion>
      <Criterion name="PAYOLUTION_REQUEST_SYSTEM_VERSION">CustomSystemVersion</Criterion>
      <Criterion name="PAYOLUTION_REQUEST_SYSTEM_TYPE">Webshop</Criterion>
      <Criterion name="PAYOLUTION_WEBSHOP_URL">www.shop.example.com</Criterion>
      <Criterion name="PAYOLUTION_MODULE_NAME">PaymentModuleName</Criterion>
      <Criterion name="PAYOLUTION_MODULE_VERSION">PaymentModuleVersion</Criterion>
      <Criterion name="PAYOLUTION_ITEM_DESCR_1">Phone</Criterion>
      <Criterion name="PAYOLUTION_ITEM_PRICE_1">349.99</Criterion>
      <Criterion name="PAYOLUTION_ITEM_TAX_1">49.99</Criterion>
      <Criterion name="PAYOLUTION_ITEM_DESCR_2">Cover</Criterion>
      <Criterion name="PAYOLUTION_ITEM_PRICE_2">9.99</Criterion>
      <Criterion name="PAYOLUTION_ITEM_TAX_2">0.99</Criterion>
      <Criterion name="PAYOLUTION_CUSTOMER_NUMBER">customerid123456</Criterion>
      <Criterion name="PAYOLUTION_CUSTOMER_GROUP">TOP</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_GIVEN">Max</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_FAMILY">Mustermann</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_COUNTRY">AT</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_CITY">Graz</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_ZIP">1060</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_STREET">Spengergasse 38</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_COMPANY">Payolution Company</Criterion>
      <Criterion name="PAYOLUTION_SHIPPING_TYPE">ALTERNATIVE_SHIPPING_ADDRESS</Criterion>
      <Criterion name="PAYOLUTION_TRX_TYPE">B2B</Criterion>
      <Criterion name="PAYOLUTION_COMPANY_NAME">Payolution Company</Criterion>
      <Criterion name="PAYOLUTION_COMPANY_UID">ATU4514545</Criterion>
      <Criterion name="PAYOLUTION_COMPANY_TYPE">COMPANY</Criterion>
      <Criterion name="PAYOLUTION_SESSION_ID">payolution_de_827ccb0eea8a706c4c34a16891f84e7b</Criterion>
    </Analysis>
  </Transaction>
</Request>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class HomePageProvider extends CI_Controller {

	public function __construct()
    {
        parent::__construct();
    }

    public function send_confirmation_requirements($lang = NULL, $email = NULL)
    {
    	$this->load->library('email');
        $this->email->from('product.development@pwex.co', 'Pwex');
		$this->email->to($email);
    	if ($lang == 'es') {
	        $this->email->subject('Hemos recibido tu información');
	        $this->email->message('

Ya estas un paso más cerca del creciente mercado del continente Americano. En los próximos días te estaremos contactando.

¿Tienes alguna pregunta?

Escribenos a: product.development@pwex.co

O llamanos a: 210-828-5555

El equipo de

	        ');
    	} else {
    		$this->email->subject('We have received your information');
	        $this->email->message('

You are already one step closer to the growing market of the American continent. In the coming days we will be contacting you.

Do you have any question?

Write to: product.development@pwex.co

Or call us: 210-828-5555

The  Team

	        ');
    	}
        $this->email->send();
        if ($lang == 'es') {
	        redirect('http://pwex.org/?lang=es');
        } else {
	        redirect('http://pwex.org/');
        }
    }

}


text:
module ApiV3
  module Plugin
    class PluginInfoRepresenter < BaseRepresenter

      REPRESENTER_FOR_PLUGIN_INFO_TYPE = {
        com.thoughtworks.go.server.ui.plugins.AuthenticationPluginInfo => AuthenticationPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.AuthorizationPluginInfo => AuthorizationPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.NotificationPluginInfo => NotificationPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.PackageRepositoryPluginInfo => PackageRepositoryPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.PluggableTaskPluginInfo => PluggableTaskPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.SCMPluginInfo => SCMPluginInfoRepresenter,
        com.thoughtworks.go.server.ui.plugins.ElasticPluginInfo => ElasticPluginInfoRepresenter,
      }

      class <<self
        def new(plugin)
          representer_for_type(plugin.class).new(plugin)
        end

        def representer_for_type(type)
          REPRESENTER_FOR_PLUGIN_INFO_TYPE[type] || (raise UnprocessableEntity, "Invalid plugin type '#{type}'. It has to be one of '#{REPRESENTER_FOR_PLUGIN_INFO_TYPE.keys.join(', ')}.'")
        end
      end
    end
  end
end


text:
package pro.taskana.common.test;

import static java.time.temporal.ChronoUnit.SECONDS;

import java.time.Duration;
import java.util.Optional;
import javax.sql.DataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.testcontainers.containers.Db2Container;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;
import org.testcontainers.utility.DockerImageName;

import pro.taskana.common.internal.configuration.DB;

public class DockerContainerCreator {

  private DockerContainerCreator() {
    throw new IllegalStateException("Utility class");
  }

  public static Optional<JdbcDatabaseContainer<?>> createDockerContainer(DB db) {
    switch (db) {
      case DB2:
        return Optional.of(
            new Db2Container(
                    DockerImageName.parse("taskana/db2:11.5")
                        .asCompatibleSubstituteFor("ibmcom/db2"))
                .waitingFor(
                    new LogMessageWaitStrategy()
                        .withRegEx(".*DB2START processing was successful.*")
                        .withStartupTimeout(Duration.of(60, SECONDS)))
                .withUsername("db2inst1")
                .withPassword("db2inst1-pwd")
                .withDatabaseName("TSKDB"));
      case POSTGRES:
        return Optional.of(
            new PostgreSQLContainer<>(DockerImageName.parse("postgres:10"))
                .withUsername("postgres")
                .withPassword("postgres")
                .withDatabaseName("postgres")
                .withCommand(
                    "/bin/sh",
                    "-c",
                    "localedef -i de_DE -c -f UTF-8 -A /usr/share/locale/locale.alias de_DE.UTF-8 "
                        + "&& export LANG=de_DE.UTF-8 "
                        + "&& ./docker-entrypoint.sh postgres -c fsync=off")
                .waitingFor(
                    new LogMessageWaitStrategy()
                        .withRegEx(".*Datenbanksystem ist bereit, um Verbindungen anzunehmen.*\\s")
                        .withTimes(2)
                        .withStartupTimeout(Duration.of(60, SECONDS))));
      default:
        return Optional.empty();
    }
  }

  public static DataSource createDataSource(JdbcDatabaseContainer<?> container) {
    PooledDataSource ds =
        new PooledDataSource(
            Thread.currentThread().getContextClassLoader(),
            container.getDriverClassName(),
            container.getJdbcUrl(),
            container.getUsername(),
            container.getPassword());
    ds.setPoolTimeToWait(50);
    ds.forceCloseAll(); // otherwise, the MyBatis pool is not initialized correctly
    return ds;
  }
}


text: java $JAVA_OPTS -jar /opt/jenkins/jenkins.war $JENKINS_OPTS


text:
package org.scalaide.ui.internal.editor.spelling

import org.eclipse.core.runtime.AssertionFailedException
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.jdt.internal.ui.text.spelling.JavaSpellingProblem
import org.eclipse.jdt.internal.ui.text.spelling.SpellCheckEngine
import org.eclipse.jdt.internal.ui.text.spelling.SpellCheckIterator
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEvent
import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellEventListener
import org.eclipse.jdt.ui.PreferenceConstants
import org.eclipse.jdt.ui.text.IJavaPartitions._
import org.eclipse.jface.text.BadLocationException
import org.eclipse.jface.text.IDocument
import org.eclipse.jface.text.IRegion
import org.eclipse.jface.text.TextUtilities
import org.eclipse.ui.texteditor.spelling.ISpellingEngine
import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector
import org.eclipse.ui.texteditor.spelling.SpellingContext
import org.scalaide.core.lexical.ScalaPartitions._

/**
 * Checks Scala files for spelling mistakes.
 */
class ScalaSpellingEngine extends ISpellingEngine {

  override def check(document: IDocument, regions: Array[IRegion], context: SpellingContext, collector: ISpellingProblemCollector, monitor: IProgressMonitor): Unit = {
    val engine = SpellCheckEngine.getInstance()
    val checker = engine.getSpellChecker()

    if (checker != null) {
      try check(document, regions, checker, collector, monitor)
      catch {
        case _: BadLocationException | _: AssertionFailedException =>
        // Ignore: the document has been changed in another thread and will be checked again
      }
    }
  }

  private def check(document: IDocument, regions: Array[IRegion], checker: ISpellChecker, collector: ISpellingProblemCollector, monitor: IProgressMonitor): Unit = {
    val spellCheckablePartitionTypes = getSpellCheckablePartitionTypes
    val listener = new SpellEventListener(collector, document)

    for {
      region <- regions
      partition <- TextUtilities.computePartitioning(document, JAVA_PARTITIONING, region.getOffset, region.getLength, false)
      if spellCheckablePartitionTypes contains partition.getType
    } {
      if (monitor != null && monitor.isCanceled || listener.isProblemsThresholdReached)
        return
      checker.execute(listener, new SpellCheckIterator(document, partition, checker.getLocale))
    }
  }

  private def getSpellCheckablePartitionTypes = {
    val ignoreStrings = PreferenceConstants.getPreferenceStore.getBoolean(PreferenceConstants.SPELLING_IGNORE_JAVA_STRINGS)
    Set(JAVA_DOC, JAVA_MULTI_LINE_COMMENT, JAVA_SINGLE_LINE_COMMENT) ++
      (if (ignoreStrings) Set() else Set(JAVA_STRING, SCALA_MULTI_LINE_STRING))
  }

  private class SpellEventListener(collector: ISpellingProblemCollector, document: IDocument) extends ISpellEventListener {
    val problemsThreshold = PreferenceConstants.getPreferenceStore.getInt(PreferenceConstants.SPELLING_PROBLEMS_THRESHOLD)
    var problemCount = 0

    override def handle(event: ISpellEvent) =
      if (problemCount < problemsThreshold) {
        problemCount += 1
        collector.accept(new JavaSpellingProblem(event, document))
      }

    def isProblemsThresholdReached() = problemCount >= problemsThreshold
  }

}


text:
package io.datarouter.util;

public class Base16ByteStringCodec{

	public static final Base16ByteStringCodec INSTANCE = new Base16ByteStringCodec();

	public String encode(byte[] bytes){
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for(byte word : bytes){
			String hex = Integer.toHexString(word & 0xff);
			if(hex.length() == 1){
				sb.append("0");
			}
			sb.append(hex);
		}
		return sb.toString();
	}

}


text:
import unittest
import os
import tempfile

# internal modules:
from yotta.lib.folders import globalInstallDirectory

from yotta.test.cli import cli
from yotta.test.cli import util

Test_Target = 'x86-linux-native'

class TestCLILink(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.prefix_dir = tempfile.mkdtemp()
        os.environ['YOTTA_PREFIX'] = cls.prefix_dir

    @classmethod
    def tearDownClass(cls):
        util.rmRf(cls.prefix_dir)
        cls.prefix_dir = None

    def testLink(self):
        linked_in_module = util.writeTestFiles(util.Test_Trivial_Lib, True)

        stdout, stderr, statuscode = cli.run(['-t', Test_Target, '--plain', 'link'], cwd=linked_in_module)
        self.assertEqual(statuscode, 0)
        self.assertTrue(os.path.exists(os.path.join(globalInstallDirectory(), 'test-trivial-lib')))

        test_module = util.writeTestFiles(util.Test_Testing_Trivial_Lib_Dep, True)
        stdout, stderr, statuscode = cli.run(['-t', Test_Target, '--plain', 'list'], cwd=test_module)
        self.assertIn('missing', stdout+stderr)

        stdout, stderr, statuscode = cli.run(['-t', Test_Target, '--plain', 'link', 'test-trivial-lib'], cwd=test_module)
        self.assertEqual(statuscode, 0)
        self.assertNotIn('broken', stdout+stderr)

        stdout, stderr, statuscode = cli.run(['-t', Test_Target, '--plain', 'list'], cwd=test_module)
        self.assertNotIn('missing', stdout+stderr)

        util.rmRf(test_module)
        util.rmRf(linked_in_module)

    @unittest.skipIf(not util.canBuildNatively(), "can't build natively on this platform yet")
    def testLinkedBuild(self):
        linked_in_module = util.writeTestFiles(util.Test_Trivial_Lib, True)
        test_module = util.writeTestFiles(util.Test_Testing_Trivial_Lib_Dep, True)

        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'link'], cwd=linked_in_module)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'link', 'test-trivial-lib'], cwd=test_module)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'build'], cwd=test_module)
        self.assertEqual(statuscode, 0)

        util.rmRf(test_module)
        util.rmRf(linked_in_module)

    @unittest.skipIf(not util.canBuildNatively(), "can't build natively on this platform yet")
    def testLinkedReBuild(self):
        # test that changing which module is linked triggers a re-build
        linked_in_module_1 = util.writeTestFiles(util.Test_Trivial_Lib, True)
        linked_in_module_2 = util.writeTestFiles(util.Test_Trivial_Lib, True)
        test_module = util.writeTestFiles(util.Test_Testing_Trivial_Lib_Dep, True)

        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'link'], cwd=linked_in_module_1)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'link', 'test-trivial-lib'], cwd=test_module)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'build'], cwd=test_module)
        self.assertEqual(statuscode, 0)

        # check that rebuild is no-op
        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'build'], cwd=test_module)
        self.assertIn('no work to do', stdout+stderr)
        self.assertEqual(statuscode, 0)

        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'link'], cwd=linked_in_module_2)
        self.assertEqual(statuscode, 0)

        stdout, stderr, statuscode = cli.run(['-t', util.nativeTarget(), '--plain', 'build'], cwd=test_module)
        self.assertNotIn('no work to do', stdout+stderr)
        self.assertEqual(statuscode, 0)

        util.rmRf(test_module)
        util.rmRf(linked_in_module_1)
        util.rmRf(linked_in_module_2)

    @unittest.skipIf(not util.canBuildNatively(), "can't build natively on this platform yet")
    def testTargetLinkedBuild(self):
        linked_in_target = util.writeTestFiles(util.getNativeTargetDescription(), True)
        test_module = util.writeTestFiles(util.Test_Testing_Trivial_Lib_Dep_Preinstalled, True)

        stdout, stderr, statuscode = cli.run(['-t', 'test-native-target', '--plain', 'link-target'], cwd=linked_in_target)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', 'test-native-target', '--plain', 'link-target', 'test-native-target'], cwd=test_module)
        self.assertEqual(statuscode, 0)
        stdout, stderr, statuscode = cli.run(['-t', 'test-native-target', '--plain', 'build'], cwd=test_module)
        self.assertEqual(statuscode, 0)

        util.rmRf(test_module)
        util.rmRf(linked_in_target)


text:
import {LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';
import {ConventionalViewStrategy} from 'aurelia-framework';

/**
 *
 */
LogManager.addAppender(new ConsoleAppender());
LogManager.setLevel(LogManager.logLevel.error);

/**
 *
 */
export function configure(aurelia)
{
  aurelia.use
    .defaultBindingLanguage()
    .defaultResources()
    .history()
    .router()
    .eventAggregator();
  aurelia.start().then(a => a.setRoot('config/bootstrap', document.body));
}

/**
 *
 */
ConventionalViewStrategy.convertModuleIdToViewUrl = function(moduleId){
  var id = (moduleId.endsWith('.js') || moduleId.endsWith('.ts')) ? moduleId.substring(0, moduleId.length - 3) : moduleId;

  //
  // TODO
  // Fix a better solution...
  //
  if (id.endsWith('bootstrap')) {
	  return 'src/Template/Layout/default.html';
  }

  return id + '.html';
}


text:
/* eslint-disable import/no-commonjs */

const path = require('path');
const { ErrorWithStack } = require('jest-util');
const JSDOMEnvironment = require('jest-environment-jsdom');

const ROOT_PATH = path.resolve(__dirname, '../..');

class CustomEnvironment extends JSDOMEnvironment {
  constructor(config, context) {
    super(config, context);

    Object.assign(context.console, {
      error(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.error() with:\n\n${args.join(', ')}`,
          this.error,
        );
      },

      warn(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.warn() with:\n\n${args.join(', ')}`,
          this.warn,
        );
      },
    });

    const { testEnvironmentOptions } = config;
    const { IS_EE } = testEnvironmentOptions;
    this.global.gon = {
      ee: IS_EE,
    };

    this.rejectedPromises = [];

    this.global.promiseRejectionHandler = error => {
      this.rejectedPromises.push(error);
    };

    this.global.fixturesBasePath = `${ROOT_PATH}/tmp/tests/frontend/fixtures${IS_EE ? '-ee' : ''}`;
    this.global.staticFixturesBasePath = `${ROOT_PATH}/spec/frontend/fixtures`;

    // Not yet supported by JSDOM: https://github.com/jsdom/jsdom/issues/317
    this.global.document.createRange = () => ({
      setStart: () => {},
      setEnd: () => {},
      commonAncestorContainer: {
        nodeName: 'BODY',
        ownerDocument: this.global.document,
      },
    });
  }

  async teardown() {
    await new Promise(setImmediate);

    if (this.rejectedPromises.length > 0) {
      throw new ErrorWithStack(
        `Unhandled Promise rejections: ${this.rejectedPromises.join(', ')}`,
        this.teardown,
      );
    }

    await super.teardown();
  }
}

module.exports = CustomEnvironment;