text:
module SynologyDownloadStation
  module Response

    class LoginError < StandardError; end

    # {"login_success"=>true, "id"=>"FsEr6MGnWj59o", "success"=>true}
    class Login < Base

      def parse_response
        raise LoginError.new(response.inspect) unless login_success
      end

      def login_success
        response[:login_success] || false
      end

      def id
        response[:id]
      end
      alias :token :id

    end

  end
end


text:
package org.ovirt.engine.api.restapi.resource;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.ws.rs.core.Response;

import org.ovirt.engine.api.common.util.DetailHelper;
import org.ovirt.engine.api.model.Agent;
import org.ovirt.engine.api.model.Certificate;
import org.ovirt.engine.api.model.Cluster;
import org.ovirt.engine.api.model.Host;
import org.ovirt.engine.api.model.HostedEngine;
import org.ovirt.engine.api.model.Hosts;
import org.ovirt.engine.api.model.Statistic;
import org.ovirt.engine.api.model.Statistics;
import org.ovirt.engine.api.resource.HostResource;
import org.ovirt.engine.api.resource.HostsResource;
import org.ovirt.engine.api.restapi.types.FenceAgentMapper;
import org.ovirt.engine.api.utils.LinkHelper;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdsOperationActionParameters;
import org.ovirt.engine.core.common.action.hostdeploy.AddVdsActionParameters;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.businessentities.pm.FenceAgent;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.NameQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BackendHostsResource extends AbstractBackendCollectionResource<Host, VDS> implements
        HostsResource {

    private static final Logger log = LoggerFactory.getLogger(BackendHostsResource.class);
    private static final String DEFAULT_NAME = "Default";
    static final String[] SUB_COLLECTIONS = { "storage", "nics", "numanodes", "tags", "permissions", "statistics",
        "hooks", "fenceagents", "katelloerrata", "devices", "networkattachments", "unmanagednetworks", "storageconnectionextensions" };
    static final String GLUSTERONLY_MODE_COLLECTIONS_TO_HIDE = "storage";

    public BackendHostsResource() {
        super(Host.class, VDS.class, SUB_COLLECTIONS);
    }

    @Override
    public Hosts list() {
        ApplicationMode appMode = getCurrent().getApplicationMode();
        if (appMode == ApplicationMode.GlusterOnly) {
            return listGlusterOnly();
        }
        else {
            return listAll();
        }
    }

    private Hosts listGlusterOnly() {
        if (isFiltered()) {
            return mapGlusterOnlyCollection(getBackendCollection(VdcQueryType.GetAllHosts,
                    new VdcQueryParametersBase()));
        }
        else {
            return mapGlusterOnlyCollection(getBackendCollection(SearchType.VDS));
        }
    }

    private Hosts listAll() {
        if (isFiltered()) {
            return mapCollection(getBackendCollection(VdcQueryType.GetAllHosts,
                    new VdcQueryParametersBase()));
        }
        else {
            return mapCollection(getBackendCollection(SearchType.VDS));
        }
    }

    @Override
    public HostResource getHostSubResource(String id) {
        return inject(new BackendHostResource(id, this));
    }

    @Override
    public Response add(Host host) {
        validateEnums(Host.class, host);
        validateParameters(host, "name", "address");
        VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null);
        staticHost.setVdsGroupId(getClusterId(host));
        staticHost.setDisablePowerManagementPolicy(true);
        AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword());
        if (host.isSetOverrideIptables()) {
            addParams.setOverrideFirewall(host.isOverrideIptables());
        }
        if (host.isSetRebootAfterInstallation()) {
            addParams.setRebootAfterInstallation(host.isRebootAfterInstallation());
        }
        if (host.isSetPowerManagement() && host.getPowerManagement().isSetAgents()) {
            List<FenceAgent> agents = new LinkedList<>();
            for (Agent agent : host.getPowerManagement().getAgents().getAgents()) {
                agents.add(FenceAgentMapper.map(agent, null));
            }
            addParams.setFenceAgents(agents);
        }
        addParams = (AddVdsActionParameters) getMapper
            (Host.class, VdsOperationActionParameters.class).map(host, addParams);
        return performCreate(VdcActionType.AddVds,
                               addParams,
                               new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class));
    }

    @Override
    protected Host doPopulate(Host model, VDS entity) {
        Host host = addHostedEngineIfConfigured(model, entity);
        return host;
    }

    @Override
    protected Host deprecatedPopulate(Host model, VDS entity) {
        Set<String> details = DetailHelper.getDetails(httpHeaders, uriInfo);
        if (details.contains("statistics")) {
            addStatistics(model, entity);
        }
        addCertificateInfo(model);
        return model;
    }

    public void addStatistics(Host model, VDS entity) {
        model.setStatistics(new Statistics());
        HostStatisticalQuery query = new HostStatisticalQuery(newModel(model.getId()));
        List<Statistic> statistics = query.getStatistics(entity);
        for (Statistic statistic : statistics) {
            LinkHelper.addLinks(uriInfo, statistic, query.getParentType());
        }
        model.getStatistics().getStatistics().addAll(statistics);
    }

    private Hosts mapCollection(List<VDS> entities) {
        Hosts collection = new Hosts();
        for (VDS entity : entities) {
            collection.getHosts().add(addLinks(populate(map(entity), entity)));
        }
        return collection;
    }

    //TODO: REVISIT when backend expose CertificateSubject in vds
    public Host addCertificateInfo(Host host) {
        VdcQueryReturnValue result =
            runQuery(VdcQueryType.GetVdsCertificateSubjectByVdsId,
                    new IdQueryParameters(asGuid(host.getId())));

        if (result != null
            && result.getSucceeded()
            && result.getReturnValue() != null) {
            String subject = result.getReturnValue().toString();
            if (subject != null){
                host.setCertificate(new Certificate());
                host.getCertificate().setSubject(subject);
                host.getCertificate().setOrganization(subject.split(",")[0].replace("O=", ""));
            }
        }
        else {
            log.error("Could not fetch certificate info for host '{}'", host.getId());
        }
        return host;
    }

    private Hosts mapGlusterOnlyCollection(List<VDS> entities) {
        Hosts collection = new Hosts();
        for (VDS entity : entities) {
            collection.getHosts().add(addLinks(populate(map(entity), entity), GLUSTERONLY_MODE_COLLECTIONS_TO_HIDE));
        }
        return collection;
    }

    private Guid getClusterId(Host host) {
        if (host.isSetCluster()) {
            Cluster cluster = host.getCluster();
            if (cluster.isSetId()) {
                return asGuid(cluster.getId());
            }
            if (cluster.isSetName()) {
                return getClusterIdByName(cluster.getName());
            }
        }
        return getClusterIdByName(DEFAULT_NAME);
    }

    private Guid getClusterIdByName(String name) {
        return getEntity(VDSGroup.class,
                VdcQueryType.GetVdsGroupByName,
                new NameQueryParameters(name),
                "Cluster: name=" + name).getId();
    }

    Host addHostedEngineIfConfigured(Host host, VDS entity) {
        /* Add entity data only if the hosted engine agent is configured on this host */
        if (entity.getHighlyAvailableIsConfigured()) {
            HostedEngine hostedEngine = getMapper(VDS.class, HostedEngine.class).map(entity, null);
            host.setHostedEngine(hostedEngine);
        }
        return host;
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation UIColor (FLColor)

+ (UIColor *)FLTabBarTitleColor {

    return [UIColor colorWithHexString:@"#ED4C38"];
}

@end


text:
define([
  'underscore',
  'backbone',
], function( _, Backbone ){

  var townCollection = Backbone.Collection.extend({

    url: 'measure',
    initialize : function() {

    }

  });

  return townCollection;

});


text:
real-world-haskell
==================

Codes tests when I am reading "Real World Haskell"


text:
package com.daimajia.easing.quad;

import com.daimajia.easing.BaseEasingMethod;

public class QuadEaseInOut extends BaseEasingMethod{
    public QuadEaseInOut(float duration) {
        super(duration);
    }

    @Override
    public Float calculate(float t, float b, float c, float d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    }
}


text:
import Processor from '../base/view_model';

export class Remove extends Processor {
  constructor(processorId) {
    super(processorId, 'remove', 'Remove');
    this.sourceField = '';
  }

  get description() {
    const source = this.sourceField || '?';
    return `[${source}]`;
  }

  get model() {
    return {
      processorId: this.processorId,
      typeId: this.typeId,
      sourceField: this.sourceField || ''
    };
  }
};


text:
<?php
/**
 * A password strategy that uses bcrypt.
 * The default implementation uses a work factor of 12, you should adjust
 * this based on your security requirements
 * @author Charles Pick
 * @package packages.passwordStrategy
 */
class ABcryptPasswordStrategy extends APasswordStrategy
{
	/**
	 * The work factor used when hashing passwords.
	 * The higher the work factor the more computationally expensive
	 * it is to encode and validate passwords. So it makes your passwords
	 * harder to crack, but it can also be a burden on your own server.
	 *
	 * @var integer
	 */
	public $workFactor = 12;
	/**
	 * Generates a random salt.
	 * @return string the generated salt
	 */
	protected function generateSalt()
	{
		$salt = '$2a$'.str_pad($this->workFactor,2,'0',STR_PAD_LEFT).'$';
		$salt .= substr(strtr(base64_encode($this->getRandomBytes(16)),'+','.'),0,22);
		return $salt;
	}
	/**
	 * Gets a number of random bytes
	 * @param integer $count the number of bytes to return
	 * @return bool|string
	 */
	protected function getRandomBytes($count = 16)
	{
		$bytes = "";
		if (function_exists("openssl_random_pseudo_bytes") && strtoupper(substr(PHP_OS,0,3)) !== "WIN") {
			$bytes = openssl_random_pseudo_bytes($count);
		}
		else if(
			$bytes == ""
			&& is_readable("/dev/urandom")
			&& ($handle = fopen("/dev/urandom", "rb")) !== false
		) {
			$bytes = fread($handle,$count);
			fclose($handle);
		}

		if (strlen($bytes) < $count) {
			$key = uniqid(Yii::app()->name, true);

			// we need to pad with some pseudo random bytes
			while(strlen($bytes) < $count) {
				$value = $bytes;
				for($i = 0; $i < 12; $i++) {
                    if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
                        $value = hash_hmac('sha1',microtime().$value,$key,true);
                    } else {
                        $value = hash_hmac('salsa20',microtime().$value,$key,true);
                    }
					usleep(10); // make sure microtime() returns a new value
				}
				$bytes = substr($value,0,$count);
			}
		}
		return $bytes;
	}

	/**
	 * Encode a plain text password.
	 * Child classes should implement this method and do their encoding here
	 * @param string $password the plain text password to encode
	 * @return string the encoded password
	 */
	public function encode($password)
	{
		return crypt($password,$this->getSalt());
	}

}


text:
package org.apache.log4j.net;

import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Test;

import org.apache.log4j.*;
import org.apache.log4j.util.*;

import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.apache.log4j.xml.XLevel;

/**
   @author  Ceki Gülcü
*/
public class SocketServerTestCase extends TestCase {

  static String TEMP = "output/temp";
  static String FILTERED = "output/filtered";

  // %5p %x [%t] %c %m%n
  // DEBUG T1 [main] org.apache.log4j.net.SocketAppenderTestCase Message 1
  static String PAT1 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[main]\\ "
                       + ".* Message \\d{1,2}";

  // DEBUG T2 [main] ? (?:?) Message 1
  static String PAT2 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[main]\\ "
                       + "\\? \\(\\?:\\?\\) Message \\d{1,2}";

  // DEBUG T3 [main] org.apache.log4j.net.SocketServerTestCase (SocketServerTestCase.java:121) Message 1
  static String PAT3 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[main]\\ "
                       + "org.apache.log4j.net.SocketServerTestCase "
                       + "\\(SocketServerTestCase.java:\\d{3}\\) Message \\d{1,2}";

  // DEBUG some T4 MDC-TEST4 [main] SocketAppenderTestCase - Message 1
  // DEBUG some T4 MDC-TEST4 [main] SocketAppenderTestCase - Message 1
  static String PAT4 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[main]\\"
                       + " (root|SocketServerTestCase) - Message \\d{1,2}";

  static String PAT5 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[main]\\"
                       + " (root|SocketServerTestCase) - Message \\d{1,2}";

  static String PAT6 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6"
                       + " \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}";

  static String PAT7 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7"
                       + " \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}";

  // DEBUG some8 T8 shortSocketServer MDC-TEST7 [main] SocketServerTestCase - Message 1
  static String PAT8 = "^(TRACE|DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer"
                       + " MDC-TEST8 \\[main]\\ (root|SocketServerTestCase) - Message \\d{1,2}";

  static String EXCEPTION1 = "java.lang.Exception: Just testing";
  static String EXCEPTION2 = "\\s*at .*\\(.*\\)";
  static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)";
  static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)";
  static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)";

  static Logger logger = Logger.getLogger(SocketServerTestCase.class);
  static public final int PORT = 12345;
  static Logger rootLogger = Logger.getRootLogger();
  SocketAppender socketAppender;

  public SocketServerTestCase(String name) {
    super(name);
  }

  public void setUp() {
    System.out.println("Setting up test case.");
  }

  public void tearDown() {
    System.out.println("Tearing down test case.");
    socketAppender = null;
    rootLogger.removeAllAppenders();
  }

  /**
   * The pattern on the server side: %5p %x [%t] %c %m%n
   *
   * We are testing NDC functionality across the wire.
   */
  public void test1() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    rootLogger.addAppender(socketAppender);
    common("T1", "key1", "MDC-TEST1");
    delay(1);
    ControlFilter cf = new ControlFilter(new String[]{PAT1, EXCEPTION1,
						       EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

    Transformer.transform(
      TEMP, FILTERED,
      new Filter[] { cf, new LineNumberFilter(),
          new JunitTestRunnerFilter(),
          new SunReflectFilter() });

    assertTrue(Compare.compare(FILTERED, "witness/socketServer.1"));
  }

  /**
   * The pattern on the server side: %5p %x [%t] %C (%F:%L) %m%n
   *
   * We are testing NDC across the wire. Localization is turned off by
   * default so it is not tested here even if the conversion pattern
   * uses localization. */
  public void test2() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    rootLogger.addAppender(socketAppender);

    common("T2", "key2", "MDC-TEST2");
    delay(1);
    ControlFilter cf = new ControlFilter(new String[]{PAT2, EXCEPTION1,
						       EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

    Transformer.transform(
      TEMP, FILTERED,
      new Filter[] { cf, new LineNumberFilter(),
          new JunitTestRunnerFilter(),
          new SunReflectFilter() });

    assertTrue(Compare.compare(FILTERED, "witness/socketServer.2"));
  }

  /**
   *  The pattern on the server side: %5p %x [%t] %C (%F:%L) %m%n
   *  meaning that we are testing NDC and locatization functionality
   *  across the wire.  */
  public void test3() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    rootLogger.addAppender(socketAppender);

    common("T3", "key3", "MDC-TEST3");
    delay(1);
    ControlFilter cf = new ControlFilter(new String[]{PAT3, EXCEPTION1,
						       EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

    Transformer.transform(
      TEMP, FILTERED,
      new Filter[] { cf, new LineNumberFilter(),
          new JunitTestRunnerFilter(),
          new SunReflectFilter() });

    assertTrue(Compare.compare(FILTERED, "witness/socketServer.3"));
  }

  /**
   *  The pattern on the server side: %5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n
   *  meaning that we are testing NDC, MDC and localization functionality across
   *  the wire.
  */
  public void test4() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    rootLogger.addAppender(socketAppender);

    NDC.push("some");
    common("T4", "key4", "MDC-TEST4");
    NDC.pop();
    delay(1);
    //
    //  These tests check MDC operation which
    //    requires JDK 1.2 or later
    if(!System.getProperty("java.version").startsWith("1.1.")) {

        ControlFilter cf = new ControlFilter(new String[]{PAT4, EXCEPTION1,
						           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
        Transformer.transform(
          TEMP, FILTERED,
          new Filter[] { cf, new LineNumberFilter(),
              new JunitTestRunnerFilter(),
              new SunReflectFilter() });

        assertTrue(Compare.compare(FILTERED, "witness/socketServer.4"));
    }
  }

  /**
   * The pattern on the server side: %5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n
   *
   * The test case uses wraps an AsyncAppender around the
   * SocketAppender. This tests was written specifically for bug
   * report #9155.

   * Prior to the bug fix the output on the server did not contain the
   * MDC-TEST5 string because the MDC clone operation (in getMDCCopy
   * method) operation is performed twice, once from the main thread
   * which is correct, and a second time from the AsyncAppender's
   * dispatch thread which is incrorrect.

   */
  public void test5() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    AsyncAppender asyncAppender = new AsyncAppender();
    asyncAppender.setLocationInfo(true);
    asyncAppender.addAppender(socketAppender);
    rootLogger.addAppender(asyncAppender);

    NDC.push("some5");
    common("T5", "key5", "MDC-TEST5");
    NDC.pop();
    delay(2);
    //
    //  These tests check MDC operation which
    //    requires JDK 1.2 or later
    if(!System.getProperty("java.version").startsWith("1.1.")) {
        ControlFilter cf = new ControlFilter(new String[]{PAT5, EXCEPTION1,
						           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

        Transformer.transform(
          TEMP, FILTERED,
          new Filter[] { cf, new LineNumberFilter(),
              new JunitTestRunnerFilter(),
              new SunReflectFilter() });

        assertTrue(Compare.compare(FILTERED, "witness/socketServer.5"));
    }
  }

  /**
   * The pattern on the server side: %5p %x %X{hostID}${key6} [%t] %c{1} - %m%n
   *
   * This test checks whether client-side MDC overrides the server side.
   * It uses an AsyncAppender encapsulating a SocketAppender
   */
  public void test6() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    AsyncAppender asyncAppender = new AsyncAppender();
    asyncAppender.setLocationInfo(true);
    asyncAppender.addAppender(socketAppender);
    rootLogger.addAppender(asyncAppender);

    NDC.push("some6");
    MDC.put("hostID", "client-test6");
    common("T6", "key6", "MDC-TEST6");
    NDC.pop();
    MDC.remove("hostID");
    delay(2);
    //
    //  These tests check MDC operation which
    //    requires JDK 1.2 or later
    if(!System.getProperty("java.version").startsWith("1.1.")) {
        ControlFilter cf = new ControlFilter(new String[]{PAT6, EXCEPTION1,
						           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

        Transformer.transform(
          TEMP, FILTERED,
          new Filter[] { cf, new LineNumberFilter(),
              new JunitTestRunnerFilter(),
              new SunReflectFilter() });

        assertTrue(Compare.compare(FILTERED, "witness/socketServer.6"));
    }
  }

  /**
   * The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n
   *
   * This test checks whether client-side MDC overrides the server side.
   */
  public void test7() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    rootLogger.addAppender(socketAppender);

    NDC.push("some7");
    MDC.put("hostID", "client-test7");
    common("T7", "key7", "MDC-TEST7");
    NDC.pop();
    MDC.remove("hostID");
    delay(2);
    //
    //  These tests check MDC operation which
    //    requires JDK 1.2 or later
    if(!System.getProperty("java.version").startsWith("1.1.")) {
        ControlFilter cf = new ControlFilter(new String[]{PAT7, EXCEPTION1,
						           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

        Transformer.transform(
          TEMP, FILTERED,
          new Filter[] { cf, new LineNumberFilter(),
              new JunitTestRunnerFilter(),
              new SunReflectFilter() });
        assertTrue(Compare.compare(FILTERED, "witness/socketServer.7"));
    }
  }

  /**
   * The pattern on the server side: %5p %x %X{hostID} ${key8} [%t] %c{1} - %m%n
   *
   * This test checks whether server side MDC works.
   */
  public void test8() throws Exception {
    socketAppender = new SocketAppender("localhost", PORT);
    socketAppender.setLocationInfo(true);
    rootLogger.addAppender(socketAppender);

    NDC.push("some8");

    //
    //   The test has relied on the receiving code to
    //      combine the sent MDC with the receivers MDC
    //      (which contains a value for hostID).
    //      The mechanism of how that happens is not clear
    //      and it does not work with Apache Harmony.
    //      Unclear if it is a Harmony issue.
    if (System.getProperty("java.vendor").indexOf("Apache") != -1) {
        MDC.put("hostID", "shortSocketServer");
    }

    common("T8", "key8", "MDC-TEST8");
    NDC.pop();
    delay(2);
    //
    //  These tests check MDC operation which
    //    requires JDK 1.2 or later
    if(!System.getProperty("java.version").startsWith("1.1.")) {
        ControlFilter cf = new ControlFilter(new String[]{PAT8, EXCEPTION1,
						           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});

        Transformer.transform(
          TEMP, FILTERED,
          new Filter[] { cf, new LineNumberFilter(),
              new JunitTestRunnerFilter(),
              new SunReflectFilter() });
        assertTrue(Compare.compare(FILTERED, "witness/socketServer.8"));
    }
  }

  static
  void common(String dc, String key, Object o) {
    String oldThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("main");

    int i = -1;
    NDC.push(dc);
    MDC.put(key, o);
    Logger root = Logger.getRootLogger();

    logger.setLevel(Level.DEBUG);
    rootLogger.setLevel(Level.DEBUG);

    logger.log(XLevel.TRACE, "Message " + ++i);

    logger.setLevel(Level.TRACE);
    rootLogger.setLevel(Level.TRACE);

    logger.trace("Message " + ++i);
    root.trace("Message " + ++i);
    logger.debug("Message " + ++i);
    root.debug("Message " + ++i);
    logger.info("Message " + ++i);
    logger.warn("Message " + ++i);
    logger.log(XLevel.LETHAL, "Message " + ++i); //5

    Exception e = new Exception("Just testing");
    logger.debug("Message " + ++i, e);
    root.error("Message " + ++i, e);
    NDC.pop();
    MDC.remove(key);

    Thread.currentThread().setName(oldThreadName);
  }

  public void delay(int secs) {
    try {Thread.sleep(secs*1000);} catch(Exception e) {}
  }

  public static Test suite() {
    TestSuite suite = new TestSuite();
    suite.addTest(new SocketServerTestCase("test1"));
    suite.addTest(new SocketServerTestCase("test2"));
    suite.addTest(new SocketServerTestCase("test3"));
    suite.addTest(new SocketServerTestCase("test4"));
    suite.addTest(new SocketServerTestCase("test5"));
    suite.addTest(new SocketServerTestCase("test6"));
    suite.addTest(new SocketServerTestCase("test7"));
    suite.addTest(new SocketServerTestCase("test8"));
    return suite;
  }
}


text:
package org.apache.synapse.config.xml.endpoints;

import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.xml.XMLConfigConstants;
import org.apache.synapse.endpoints.Template;

import javax.xml.namespace.QName;
import java.util.Iterator;
import java.util.Properties;

public class TemplateFactory {

    public static final Log log = LogFactory.getLog(TemplateFactory.class);

    public Template createEndpointTemplate(OMElement element, Properties properties) {
        Template template = new Template();

        OMAttribute nameAttribute = element.getAttribute(
                new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));

        if (nameAttribute != null) {
            template.setName(nameAttribute.getAttributeValue());
        } else {
            handleException("Error loading the configuration from endpointTemplate, '" +
                    "name' attribute missing");
        }

        Iterator paramItr = element.getChildrenWithName(
                new QName(SynapseConstants.SYNAPSE_NAMESPACE, "parameter"));
        while (paramItr.hasNext()) {
            OMElement paramElement = (OMElement) paramItr.next();
            OMAttribute paramName = paramElement.getAttribute(new QName("name"));
            if (paramName == null) {
                handleException("parameter name should be present");
            }
            assert paramName != null;
            template.addParameter(paramName.getAttributeValue().trim());
        }

        if (!template.getParameters().contains("name")) {
            template.addParameter("name");
        }
        if (!template.getParameters().contains("uri")) {
            template.addParameter("uri");
        }

        OMElement endpointElement = element.getFirstChildWithName(
                new QName(SynapseConstants.SYNAPSE_NAMESPACE, "endpoint"));
        if (endpointElement == null) {
            handleException("endpoint element is required in an endpoint template");
        }
        template.setElement(endpointElement);

        return template;
    }

    protected void handleException(String message) {
        log.error(message);
        throw new SynapseException(message);
    }
}


text:
'use strict';

var babelHelpers = require('./util/babelHelpers.js');

var _react = require('react');

var _react2 = babelHelpers.interopRequireDefault(_react);

var _domHelpersStyle = require('dom-helpers/style');

var _domHelpersStyle2 = babelHelpers.interopRequireDefault(_domHelpersStyle);

var _domHelpersQueryHeight = require('dom-helpers/query/height');

var _domHelpersQueryHeight2 = babelHelpers.interopRequireDefault(_domHelpersQueryHeight);

var _utilConfiguration = require('./util/configuration');

var _utilConfiguration2 = babelHelpers.interopRequireDefault(_utilConfiguration);

var _classnames = require('classnames');

var _classnames2 = babelHelpers.interopRequireDefault(_classnames);

var _utilCompat = require('./util/compat');

var _utilCompat2 = babelHelpers.interopRequireDefault(_utilCompat);

var transform = _utilConfiguration2['default'].animate.transform;

function properties(prop, value) {
  var _ref, _ref2;

  var TRANSLATION_MAP = _utilConfiguration2['default'].animate.TRANSLATION_MAP;

  if (TRANSLATION_MAP && TRANSLATION_MAP[prop]) return (_ref = {}, _ref[transform] = TRANSLATION_MAP[prop] + '(' + value + ')', _ref);

  return (_ref2 = {}, _ref2[prop] = value, _ref2);
}

var PopupContent = _react2['default'].createClass({
  displayName: 'PopupContent',

  render: function render() {
    var child = this.props.children;

    if (!child) return _react2['default'].createElement('span', { className: 'rw-popup rw-widget' });

    child = _react2['default'].Children.only(this.props.children);

    return _react.cloneElement(child, {
      className: _classnames2['default'](child.props.className, 'rw-popup rw-widget')
    });
  }
});

module.exports = _react2['default'].createClass({

  displayName: 'Popup',

  propTypes: {
    open: _react2['default'].PropTypes.bool,
    dropUp: _react2['default'].PropTypes.bool,
    duration: _react2['default'].PropTypes.number,

    onRequestClose: _react2['default'].PropTypes.func.isRequired,
    onClosing: _react2['default'].PropTypes.func,
    onOpening: _react2['default'].PropTypes.func,
    onClose: _react2['default'].PropTypes.func,
    onOpen: _react2['default'].PropTypes.func
  },

  getInitialState: function getInitialState() {
    return {};
  },

  getDefaultProps: function getDefaultProps() {
    return {
      duration: 200,
      open: false,
      onClosing: function onClosing() {},
      onOpening: function onOpening() {},
      onClose: function onClose() {},
      onOpen: function onOpen() {}
    };
  },

  // componentDidMount(){
  //   !this.props.open && this.close(0)
  // },
  componentWillMount: function componentWillMount() {
    !this.props.open && (this._initialPosition = true);
  },

  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
    this.setState({
      contentChanged: childKey(nextProps.children) !== childKey(this.props.children)
    });
  },

  componentDidUpdate: function componentDidUpdate(pvProps) {
    var closing = pvProps.open && !this.props.open,
        opening = !pvProps.open && this.props.open,
        open = this.props.open;

    if (opening) this.open();else if (closing) this.close();else if (open) this.height();
  },

  render: function render() {
    var _props = this.props;
    var className = _props.className;
    var open = _props.open;
    var dropUp = _props.dropUp;
    var props = babelHelpers.objectWithoutProperties(_props, ['className', 'open', 'dropUp']);
    var display = open ? 'block' : void 0;

    if (this._initialPosition) {
      display = 'none';
    }

    return _react2['default'].createElement(
      'div',
      babelHelpers._extends({}, props, {
        style: babelHelpers._extends({
          display: display,
          height: this.state.height
        }, props.style),
        className: _classnames2['default'](className, 'rw-popup-container', { 'rw-dropup': dropUp })
      }),
      _react2['default'].createElement(
        PopupContent,
        { ref: 'content' },
        this.props.children
      )
    );
  },

  reset: function reset() {
    var container = _utilCompat2['default'].findDOMNode(this),
        content = _utilCompat2['default'].findDOMNode(this.refs.content),
        style = { display: 'block', overflow: 'hidden' };

    _domHelpersStyle2['default'](container, style);
    this.height();
    _domHelpersStyle2['default'](content, properties('top', this.props.dropUp ? '100%' : '-100%'));
  },

  height: function height() {
    var el = _utilCompat2['default'].findDOMNode(this),
        content = _utilCompat2['default'].findDOMNode(this.refs.content),
        margin = parseInt(_domHelpersStyle2['default'](content, 'margin-top'), 10) + parseInt(_domHelpersStyle2['default'](content, 'margin-bottom'), 10);

    var height = _domHelpersQueryHeight2['default'](content) + (isNaN(margin) ? 0 : margin);

    if (this.state.height !== height) {
      el.style.height = height + 'px';
      this.setState({ height: height });
    }
  },

  open: function open() {
    var self = this,
        anim = _utilCompat2['default'].findDOMNode(this),
        el = _utilCompat2['default'].findDOMNode(this.refs.content);

    this.ORGINAL_POSITION = _domHelpersStyle2['default'](el, 'position');
    this._isOpening = true;

    if (this._initialPosition) {
      this._initialPosition = false;
      this.reset();
    } else this.height();

    this.props.onOpening();

    anim.className += ' rw-popup-animating';
    el.style.position = 'absolute';

    _utilConfiguration2['default'].animate(el, { top: 0 }, self.props.duration, 'ease', function () {
      if (!self._isOpening) return;

      anim.className = anim.className.replace(/ ?rw-popup-animating/g, '');

      el.style.position = self.ORGINAL_POSITION;
      anim.style.overflow = 'visible';
      self.ORGINAL_POSITION = null;

      self.props.onOpen();
    });
  },

  close: function close(dur) {
    var self = this,
        el = _utilCompat2['default'].findDOMNode(this.refs.content),
        anim = _utilCompat2['default'].findDOMNode(this);

    this.ORGINAL_POSITION = _domHelpersStyle2['default'](el, 'position');

    this._isOpening = false;
    this.height();
    this.props.onClosing();

    anim.style.overflow = 'hidden';
    anim.className += ' rw-popup-animating';
    el.style.position = 'absolute';

    _utilConfiguration2['default'].animate(el, { top: this.props.dropUp ? '100%' : '-100%' }, dur === undefined ? this.props.duration : dur, 'ease', function () {
      if (self._isOpening) return;

      el.style.position = self.ORGINAL_POSITION;
      anim.className = anim.className.replace(/ ?rw-popup-animating/g, '');

      anim.style.display = 'none';
      self.ORGINAL_POSITION = null;
      self.props.onClose();
    });
  }

});

function childKey(children) {
  var nextChildMapping = _react2['default'].Children.map(children, function (c) {
    return c;
  });
  for (var key in nextChildMapping) return key;
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.LogConsistency;
using Orleans.Runtime;
using Orleans.Storage;
using Orleans.MultiCluster;
using Orleans.EventSourcing.Common;

namespace Orleans.EventSourcing.CustomStorage
{
    /// <summary>
    /// A log consistency adaptor that uses the user-provided storage interface <see cref="ICustomStorageInterface{T,E}"/>.
    /// This interface must be implemented by any grain that uses this log view adaptor.
    /// </summary>
    /// <typeparam name="TLogView">log view type</typeparam>
    /// <typeparam name="TLogEntry">log entry type</typeparam>
    internal class CustomStorageAdaptor<TLogView, TLogEntry> : PrimaryBasedLogViewAdaptor<TLogView, TLogEntry, SubmissionEntry<TLogEntry>>
        where TLogView : class, new()
        where TLogEntry : class
    {
        /// <summary>
        /// Initialize a new instance of CustomStorageAdaptor class
        /// </summary>
        public CustomStorageAdaptor(ILogViewAdaptorHost<TLogView, TLogEntry> host, TLogView initialState,
            ILogConsistencyProtocolServices services, string primaryCluster)
            : base(host, initialState, services)
        {
            if (!(host is ICustomStorageInterface<TLogView, TLogEntry>))
                throw new BadProviderConfigException("Must implement ICustomStorageInterface<TLogView,TLogEntry> for CustomStorageLogView provider");
            this.primaryCluster = primaryCluster;
        }

        private string primaryCluster;

        private const int slowpollinterval = 10000;

        private TLogView cached;
        private int version;

        /// <inheritdoc/>
        protected override TLogView LastConfirmedView()
        {
            return cached;
        }

        /// <inheritdoc/>
        protected override int GetConfirmedVersion()
        {
            return version;
        }

        /// <inheritdoc/>
        protected override void InitializeConfirmedView(TLogView initialstate)
        {
            cached = initialstate;
            version = 0;
        }

        /// <inheritdoc/>
        protected override bool SupportSubmissions
        {
            get
            {
                return MayAccessStorage();
            }
        }

        private bool MayAccessStorage()
        {
            return (!Services.MultiClusterEnabled)
                   || string.IsNullOrEmpty(primaryCluster)
                   || primaryCluster == Services.MyClusterId;
        }

        /// <inheritdoc/>
        protected override SubmissionEntry<TLogEntry> MakeSubmissionEntry(TLogEntry entry)
        {
           // no special tagging is required, thus we create a plain submission entry
           return new SubmissionEntry<TLogEntry>() { Entry = entry };
        }

        [Serializable]
        private class ReadRequest : ILogConsistencyProtocolMessage
        {
            public int KnownVersion { get; set; }
        }
        [Serializable]
        private class ReadResponse<ViewType> : ILogConsistencyProtocolMessage
        {
            public int Version { get; set; }

            public ViewType Value { get; set; }
        }

        /// <inheritdoc/>
        protected override Task<ILogConsistencyProtocolMessage> OnMessageReceived(ILogConsistencyProtocolMessage payload)
        {
            var request = (ReadRequest) payload;

            if (! MayAccessStorage())
                throw new ProtocolTransportException("message destined for primary cluster ended up elsewhere (inconsistent configurations?)");

            var response = new ReadResponse<TLogView>() { Version = version };

            // optimization: include value only if version is newer
            if (version > request.KnownVersion)
                response.Value = cached;

            return Task.FromResult<ILogConsistencyProtocolMessage>(response);
        }

        /// <inheritdoc/>
        protected override async Task ReadAsync()
        {
            enter_operation("ReadAsync");

            while (true)
            {
                try
                {
                    if (MayAccessStorage())
                    {
                        // read from storage
                        var result = await ((ICustomStorageInterface<TLogView, TLogEntry>)Host).ReadStateFromStorage();
                        version = result.Key;
                        cached = result.Value;
                    }
                    else
                    {
                        // read from primary cluster
                        var request = new ReadRequest() { KnownVersion = version };
                        if (!Services.MultiClusterConfiguration.Clusters.Contains(primaryCluster))
                            throw new ProtocolTransportException("the specified primary cluster is not in the multicluster configuration");
                        var response =(ReadResponse<TLogView>) await Services.SendMessage(request, primaryCluster);
                        if (response.Version > request.KnownVersion)
                        {
                            version = response.Version;
                            cached = response.Value;
                        }
                    }

                    Services.Log(LogLevel.Debug, "read success v{0}", version);

                    LastPrimaryIssue.Resolve(Host, Services);

                    break; // successful
                }
                catch (Exception e)
                {
                    // unwrap inner exception that was forwarded - helpful for debugging
                    if ((e as ProtocolTransportException)?.InnerException != null)
                        e = ((ProtocolTransportException)e).InnerException;

                    LastPrimaryIssue.Record(new ReadFromPrimaryFailed() { Exception = e }, Host, Services);
                }

                Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue);

                await LastPrimaryIssue.DelayBeforeRetry();
            }

            exit_operation("ReadAsync");
        }

        /// <inheritdoc/>
        protected override async Task<int> WriteAsync()
        {
            enter_operation("WriteAsync");

            var updates = GetCurrentBatchOfUpdates().Select(submissionentry => submissionentry.Entry).ToList();
            bool writesuccessful = false;
            bool transitionssuccessful = false;

            try
            {
                writesuccessful = await ((ICustomStorageInterface<TLogView,TLogEntry>) Host).ApplyUpdatesToStorage(updates, version);

                LastPrimaryIssue.Resolve(Host, Services);
            }
            catch (Exception e)
            {
                // unwrap inner exception that was forwarded - helpful for debugging
                if ((e as ProtocolTransportException)?.InnerException != null)
                    e = ((ProtocolTransportException)e).InnerException;

                LastPrimaryIssue.Record(new UpdatePrimaryFailed() { Exception = e }, Host, Services);
            }

            if (writesuccessful)
            {
                Services.Log(LogLevel.Debug, "write ({0} updates) success v{1}", updates.Count, version + updates.Count);

                // now we update the cached state by applying the same updates
                // in case we encounter any exceptions we will re-read the whole state from storage
                try
                {
                    foreach (var u in updates)
                    {
                        version++;
                        Host.UpdateView(this.cached, u);
                    }

                    transitionssuccessful = true;
                }
                catch (Exception e)
                {
                    Services.CaughtUserCodeException("UpdateView", nameof(WriteAsync), e);
                }
            }

            if (!writesuccessful || !transitionssuccessful)
            {
                Services.Log(LogLevel.Debug, "{0} failed {1}", writesuccessful ? "transitions" : "write", LastPrimaryIssue);

                while (true) // be stubborn until we can re-read the state from storage
                {
                    await LastPrimaryIssue.DelayBeforeRetry();

                    try
                    {
                        var result = await ((ICustomStorageInterface<TLogView, TLogEntry>)Host).ReadStateFromStorage();
                        version = result.Key;
                        cached = result.Value;

                        Services.Log(LogLevel.Debug, "read success v{0}", version);

                        LastPrimaryIssue.Resolve(Host, Services);

                        break;
                    }
                    catch (Exception e)
                    {
                        // unwrap inner exception that was forwarded - helpful for debugging
                        if ((e as ProtocolTransportException)?.InnerException != null)
                            e = ((ProtocolTransportException)e).InnerException;

                        LastPrimaryIssue.Record(new ReadFromPrimaryFailed() { Exception = e }, Host, Services);
                    }

                    Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue);
                }
            }

            // broadcast notifications to all other clusters
            // TODO: send state instead of updates, if smaller
            if (writesuccessful)
                BroadcastNotification(new UpdateNotificationMessage()
                   {
                       Version = version,
                       Updates = updates,
                   });

            exit_operation("WriteAsync");

            return writesuccessful ? updates.Count : 0;
        }

        /// <summary>
        /// Describes a connection issue that occurred when updating the primary storage.
        /// </summary>
        [Serializable]
        public class UpdatePrimaryFailed : PrimaryOperationFailed
        {
            /// <inheritdoc/>
            public override string ToString()
            {
                return $"update primary failed: caught {Exception.GetType().Name}: {Exception.Message}";
            }
        }

        /// <summary>
        /// Describes a connection issue that occurred when reading from the primary storage.
        /// </summary>
        [Serializable]
        public class ReadFromPrimaryFailed : PrimaryOperationFailed
        {
            /// <inheritdoc/>
            public override string ToString()
            {
                return $"read from primary failed: caught {Exception.GetType().Name}: {Exception.Message}";
            }
        }

        /// <summary>
        /// A notification message that is sent to remote instances of this grain after the primary has been
        /// updated, to let them know the latest version. Contains all the updates that were applied.
        /// </summary>
        [Serializable]
        protected class UpdateNotificationMessage : INotificationMessage
        {
            /// <inheritdoc/>
            public int Version { get; set; }

            /// <summary> The list of updates that were applied. </summary>
            public List<TLogEntry> Updates { get; set; }

            /// <summary>
            /// A representation of this notification message suitable for tracing.
            /// </summary>
            public override string ToString()
            {
                return string.Format("v{0} ({1} updates)", Version, Updates.Count);
            }
        }

        private SortedList<long, UpdateNotificationMessage> notifications = new SortedList<long,UpdateNotificationMessage>();

        /// <inheritdoc/>
        protected override void OnNotificationReceived(INotificationMessage payload)
        {
           var um = payload as UpdateNotificationMessage;
            if (um != null)
                notifications.Add(um.Version - um.Updates.Count, um);
            else
                base.OnNotificationReceived(payload);
        }

        /// <inheritdoc/>
        protected override void ProcessNotifications()
        {

            // discard notifications that are behind our already confirmed state
            while (notifications.Count > 0 && notifications.ElementAt(0).Key < version)
            {
                Services.Log(LogLevel.Debug, "discarding notification {0}", notifications.ElementAt(0).Value);
                notifications.RemoveAt(0);
            }

            // process notifications that reflect next global version
            while (notifications.Count > 0 && notifications.ElementAt(0).Key == version)
            {
                var updatenotification = notifications.ElementAt(0).Value;
                notifications.RemoveAt(0);

                // Apply all operations in pending
                foreach (var u in updatenotification.Updates)
                    try
                    {
                        Host.UpdateView(cached, u);
                    }
                    catch (Exception e)
                    {
                        Services.CaughtUserCodeException("UpdateView", nameof(ProcessNotifications), e);
                    }

                version = updatenotification.Version;

                Services.Log(LogLevel.Debug, "notification success ({0} updates) v{1}", updatenotification.Updates.Count, version);
            }

            Services.Log(LogLevel.Trace, "unprocessed notifications in queue: {0}", notifications.Count);

            base.ProcessNotifications();

        }

        [Conditional("DEBUG")]
        private void enter_operation(string name)
        {
            Services.Log(LogLevel.Trace, "/-- enter {0}", name);
        }

        [Conditional("DEBUG")]
        private void exit_operation(string name)
        {
            Services.Log(LogLevel.Trace, "\\-- exit {0}", name);
        }

    }
}


text:
$(document).ready(function() {
    $(".selectTags").select2({
        placeholder: "Select a tag",
        tags: true,
        createTag: function(newTag) {
            return {
                id: 'new:' + newTag.term,
                text: newTag.term + ' (new)'
            };
        },
        maximumSelectionLength: 5
    });
    var editor_config = {
        path_absolute : '/',
        selector: '.editor',
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
        toolbar2: "print preview media | forecolor backcolor emoticons",
        image_advtab: true,
        image_class_list: [
            {title: 'None', value: ''},
            {title: 'Image Responsive', value: 'img-responsive'}
        ],
        templates: [
            {title: 'one column', content: '

text goes here

'},
            {title: 'two column', content: '

text goes here

text goes here

'},
            {title: 'two column left bigger', content: '

text goes here

text goes here

'},
            {title: 'two column right bigger', content: '

text goes here

text goes here

'}
        ],
        file_browser_callback : function(field_name, url, type, win) {
            var w = window,
                d = document,
                e = d.documentElement,
                g = d.getElementsByTagName('body')[0],
                x = w.innerWidth || e.clientWidth || g.clientWidth,
                y = w.innerHeight|| e.clientHeight|| g.clientHeight;

            var cmsURL = editor_config.path_absolute + 'laravel-filemanager?field_name=' + field_name;

            if (type == 'image') {
                cmsURL = cmsURL + "&type=Images";
            } else {
                cmsURL = cmsURL + "&type=Files";
            }

            tinyMCE.activeEditor.windowManager.open({
                file : cmsURL,
                title : 'Filemanager',
                width : x * 0.8,
                height : y * 0.8,
                resizable : "yes",
                close_previous : "no"
            });

        }
    };
    tinymce.init(editor_config);

});


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFE" />
    <stroke android:width="6dip" android:color="@color/colorBlack" />
</shape>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * History event Schema
 */
var HistoryEventSchema = new Schema({
	dateOfOccurrence: {
		type: Date,
		default: Date.now
	},
    type: {
        type: Number,
        default: 0
    },
	description: {
		type: String,
		default: '',
		trim: true
	},
});

mongoose.model('HistoryEvent', HistoryEventSchema);

/**
 * Dog Schema
 */
var DogSchema = new Schema({
	created: {
		type: Date,
		default: Date.now
	},
	name: {
		type: String,
		default: '',
		trim: true,
		required: 'Name cannot be blank'
	},
	dateOfBirth: {
		type: Date,
		default: Date.now,
		trim: true
	},
	breed: {
		type: String,
		default: 'Mieszaniec',
		trim: true
	},
	registrationNumber: {
		type: String,
		default: '',
		trim: true
	},
	description: {
		type: String,
		default: '',
		trim: true
	},
	dateOfAdmission: {
		type: Date,
		default: Date.now,
		trim: true
	},
    typeOfAdmission: {
        type: Number,
        default: 0
    },
	sex: {
		type: String,
		enum: ['male', 'female'],
		default: 'male'
	},
	commune: {
		type: String,
		default: '',
		trim: true
	},
	weight: {
		type: Number,
		default: 0,
		trim: true
	},
	height: {
		type: Number,
		default: 0,
		trim: true
	},
	color: {
		type: String,
		default: '',
		trim: true
	},
    typeOfHairInt: {
        type: Number,
        default: 0
    },
	chipId: {
		type: String,
		default: '',
		trim: true
	},
	dateOfLeaveFromShelter: {
		type: Date,
		default: Date.now,
		trim: true
	},
    typeOfLeaveFromShelter: {
        type: Number,
        default: 0
    },
	presentInTheShelter: {
		type: Boolean,
		default: true,
		trim: true
	},
	presentInTemporaryHouse: {
		type: Boolean,
		default: false,
		trim: true
	},
	photos: {
		type: String,
		default: '',
		trim: true
	},
    history: [HistoryEventSchema]

	/*
	shelterId: {
		type: Schema.ObjectId,
		ref: 'Shelter'
	},
	*/
});

mongoose.model('Dog', DogSchema);


text:
module Processors
  class Base

    attr_reader :xml, :result

    def initialize(xml, result)
      @xml    = xml
      @result = result
    end

    def process
      raise "Please implement me"
    end

    def cleanup
      # nothing
    end

    # lower priority execute sooner
    def self.priority
      50
    end

    def self.dependencies
     nil
    end

  end
end


text:
import React, { FC } from 'react';
import { useFetch } from '../../hooks/useFetch';
import { LabelsTable } from './LabelsTable';
import { DroppedTarget, Labels, Target } from '../targets/target';

import { withStatusIndicator } from '../../components/withStatusIndicator';
import { mapObjEntries } from '../../utils';
import { usePathPrefix } from '../../contexts/PathPrefixContext';
import { API_PATH } from '../../constants/constants';

interface ServiceMap {
  activeTargets: Target[];
  droppedTargets: DroppedTarget[];
}

export interface TargetLabels {
  discoveredLabels: Labels;
  labels: Labels;
  isDropped: boolean;
}

export const processSummary = (
  activeTargets: Target[],
  droppedTargets: DroppedTarget[]
): Record<string, { active: number; total: number }> => {
  const targets: Record<string, { active: number; total: number }> = {};

  // Get targets of each type along with the total and active end points
  for (const target of activeTargets) {
    const { scrapePool: name } = target;
    if (!targets[name]) {
      targets[name] = {
        total: 0,
        active: 0,
      };
    }
    targets[name].total++;
    targets[name].active++;
  }
  for (const target of droppedTargets) {
    const { job: name } = target.discoveredLabels;
    if (!targets[name]) {
      targets[name] = {
        total: 0,
        active: 0,
      };
    }
    targets[name].total++;
  }

  return targets;
};

export const processTargets = (activeTargets: Target[], droppedTargets: DroppedTarget[]): Record<string, TargetLabels[]> => {
  const labels: Record<string, TargetLabels[]> = {};

  for (const target of activeTargets) {
    const name = target.scrapePool;
    if (!labels[name]) {
      labels[name] = [];
    }
    labels[name].push({
      discoveredLabels: target.discoveredLabels,
      labels: target.labels,
      isDropped: false,
    });
  }

  for (const target of droppedTargets) {
    const { job: name } = target.discoveredLabels;
    if (!labels[name]) {
      labels[name] = [];
    }
    labels[name].push({
      discoveredLabels: target.discoveredLabels,
      isDropped: true,
      labels: {},
    });
  }

  return labels;
};

export const ServiceDiscoveryContent: FC<ServiceMap> = ({ activeTargets, droppedTargets }) => {
  const targets = processSummary(activeTargets, droppedTargets);
  const labels = processTargets(activeTargets, droppedTargets);

  return (
    <>

Service Discovery

        {mapObjEntries(targets, ([k, v]) => (

              {k} ({v.active} / {v.total} active targets)

        ))}

      {mapObjEntries(labels, ([k, v]) => {
        return <LabelsTable value={v} name={k} key={k} />;
      })}
    </>
  );
};
ServiceDiscoveryContent.displayName = 'ServiceDiscoveryContent';

const ServicesWithStatusIndicator = withStatusIndicator(ServiceDiscoveryContent);

const ServiceDiscovery: FC = () => {
  const pathPrefix = usePathPrefix();
  const { response, error, isLoading } = useFetch<ServiceMap>(`${pathPrefix}/${API_PATH}/targets`);
  return (
    <ServicesWithStatusIndicator
      {...response.data}
      error={error}
      isLoading={isLoading}
      componentTitle="Service Discovery information"
    />
  );
};

export default ServiceDiscovery;


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c">
    <page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        document.onreadystatechange = function(){
            if(document.readyState === 'complete') {
                redirect();
            }
        };
        function redirect(){
            document.location = '/carAll';
        }
    </script>
<body>
</body>
</html>


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author olamedia
 */
interface yIFormControlValidator{
    public function validate($control){

    }
}


text:
package org.ppwcode.metainfo_I;

import static org.ppwcode.metainfo_I.License.Type.APACHE_V2;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.ppwcode.metainfo_I.vcs.SvnInfo;

/**
 * Annotation for copyright information. By using this annotation,
 * the copyright information is available in the code.
 *
 * Usage pattern:
 * <pre>
 * ATCopyright("2007 - $Date: 2007-05-08 16:33:08 +0200 (Tue, 08 May 2007) $, PeopleWare n.v.")
 * public class ... {
 *  ...
 * }
 * </pre>
 *
 * @author    Jan Dockx
 */
@Copyright("2007 - $Date: 2007-05-08 16:33:08 +0200 (Tue, 08 May 2007) $, PeopleWare n.v.")
@License(APACHE_V2)
@SvnInfo(revision = "$Revision: 857 $",
         date     = "$Date: 2007-05-08 16:33:08 +0200 (Tue, 08 May 2007) $")
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Copyright {

  /**
   * The copyright notice. This should start with the period in which the contents
   * (the authored expression) if the file was created (e.g., <var>start year - end year</var>),
   * and the name of the copyright holder.
   */
  String value();

}


text:
package madgik.exareme.master.queryProcessor.graph;

import madgik.exareme.common.optimizer.OperatorBehavior;
import org.junit.Test;

import java.util.PriorityQueue;

import static org.junit.Assert.assertEquals;

/**
 * @author heraldkllapi
 */
public class ConcreteOperatorTest {

    public ConcreteOperatorTest() {
    }

    @Test public void testOrdering() {
        PriorityQueue<ConcreteOperator> readyOps = new PriorityQueue<>();
        readyOps.offer(new ConcreteOperator("A", 10, 0, 0, OperatorBehavior.store_and_forward));
        readyOps.offer(new ConcreteOperator("B", 20, 0, 0, OperatorBehavior.store_and_forward));
        readyOps.offer(new ConcreteOperator("C", 5, 0, 0, OperatorBehavior.store_and_forward));

        assertEquals("B", readyOps.poll().operatorName);
        assertEquals("A", readyOps.poll().operatorName);
        assertEquals("C", readyOps.poll().operatorName);
    }
}


text:
function Cat(name, breed) {
	this.name = name;
	this.breed = breed;
}

var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");

Cat.prototype.meow = function() {
	return this.name + " Meow!!!";
}

alert(cheshire.meow() + gary.meow());


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.camunda.bpm</groupId>
	<artifactId>mail-printer-connector</artifactId>
	<name>camunda BPM - example - coffee</name>
	<version>1.0.0-SNAPSHOT</version>

	<properties>
		<version.camunda>7.7.0</version.camunda>
		<spring.version>4.3.3.RELEASE</spring.version>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.camunda.bpm</groupId>
				<artifactId>camunda-bom</artifactId>
				<version>${version.camunda}</version>
				<scope>import</scope>
				<type>pom</type>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-framework-bom</artifactId>
				<version>${spring.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>

		<dependency>
			<groupId>org.camunda.bpm</groupId>
			<artifactId>camunda-engine</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.camunda.bpm</groupId>
			<artifactId>camunda-engine-spring</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.camunda.bpm.extension</groupId>
			<artifactId>camunda-bpm-mail-core</artifactId>
			<version>1.0.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.camunda.bpm</groupId>
			<artifactId>camunda-engine-plugin-connect</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.camunda.template-engines</groupId>
			<artifactId>camunda-template-engines-freemarker</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.4.190</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.10.19</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-core</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.assertj</groupId>
			<artifactId>assertj-core</artifactId>
			<version>3.4.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.icegreen</groupId>
			<artifactId>greenmail</artifactId>
			<version>1.5.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.7</version>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<packaging>war</packaging>
</project>