text:
package smalltalk.vm.primitive;

import smalltalk.vm.VirtualMachine;

/** "The interpreter uses contexts to represent the state of its execution of
 *   CompiledMethods and blocks. A context can be a MethodContext or a
 *   BlockContext. A MethodContext represents the execution of a
 *   CompiledMethod that was invoked by a message." --Bluebook, page 580.
 *   http://stephane.ducasse.free.fr/FreeBooks/BlueBook/Bluebook.pdf
 *
 *  Like Pharo, but unlike the original Smalltalk, we use a single context
 *  object, BlockContext, to represent both block and method context. It's
 *  just simpler. Pharo uses MethodContext but we use BlockContext (after
 *  much deliberation!)
 *
 *  This object represents the execution of a {@link STCompiledBlock} in response
 *  to a message send. This context holds the locals (with arguments first)
 *  and operand stack for computation.  It knows where it is within the method
 *  code block (field ip) and what receiver it's executing the method for.
 *
 *  The VM does not have an explicit invocation stack. The implicit invocation
 *  stack follows the invokingContext chain upwards, just like we
 *  do when resolving symbols.
 *
 *  "A Little SmallTalk" uses Context and (poorly named) Interpreter objects
 *  to represent the execution context of a method. see pdf page 148.
 *  http://sdmeta.gforge.inria.fr/FreeBooks/LittleSmalltalk/ALittleSmalltalk.pdf
 *
 *  This object is not exposed to ST programs as an STObject, as is typical,
 *  for simplicity reasons.
 */
public class BlockContext {
	public static final int INITIAL_STACK_SIZE = 10;

	/** An indicator object that indicates a method has already returned
	 *  so that we can return again later from inside a closure that is
	 *  hanging around somewhere.
	 */
	public static final BlockContext RETURNED = new BlockContext();

	/** In what VM am I executing? */
	public final VirtualMachine vm;

	// ----- STATE OF EXECUTION -----

	/** The context that was active when this context was created; i.e.,
	 *  who invoked me? This is not final because we need to set this to
	 *  RETURNED after this context finishes.
	 */
	public BlockContext invokingContext;

	/** The receiver of the message that resulted in this context */
	public final STObject receiver;

	/** The compiled code associated with this context */
	public final STCompiledBlock compiledBlock;

	/** All arguments and local variables associated with this block */
	public final STObject[] locals;

	/** The instruction pointer that points into compiledBlock.bytcodes */
	public int ip = 0;

	/** The operand stack for this context */
	public STObject[] stack;

	/** The operand stack pointer for this context; points at stack top */
	public int sp = -1;

	// ----- BLOCK CONTEXT INFO -----

	/*  The following two fields are used only by block executions.
	 *
	 *  "A BlockContext represents a block encountered in a CompiledMethod
	 *   [and evaluated]. A BlockContext refers to the MethodContext whose
	 *   CompiledMethod contained the block it represents." -- bluebook p 581 in pdf.
	 *  http://stephane.ducasse.free.fr/FreeBooks/BlueBook/Bluebook.pdf
	 *
	 *  Because blocks are embedded within methods/blocks, this
	 *  object knows which block or method surrounds it and
	 *  also knows the outermost surrounding context: the surrounding
	 *  method. For example, the following method has two embedded
	 *  blocks.
	 *
	 *  foo [
	 *     [ "block 1 starts"
	 *        [^99 "block 2"] value
	 *     ] value
	 *  ]
	 *
	 *  The outermost context is the BlockContext we create for foo when
	 *  it's invoked. Block [[^99] value] has both enclosingContext and
	 *  enclosingMethodContext (both point at the foo context). The
	 *  innermost block, [^99], has:
	 *  	1.  enclosingContext pointing at the (block) BlockContext created
	 *         	during evaluation of block [[^99] value]
	 *      2.  enclosingMethodContext pointing at the foo BlockContext
	 *
	 *  A (block) context object is created from a {@link BlockDescriptor}
	 *  when we hit it with a "value" message to evaluate itself.
	 *
	 *  See bluebook p 580+ in pdf.
	 *  http://stephane.ducasse.free.fr/FreeBooks/BlueBook/Bluebook.pdf
	 *
	 *  See http://pharobooks.gforge.inria.fr/PharoByExampleTwo-Eng/latest/Block.pdf
	 *  See http://sdmeta.gforge.inria.fr/FreeBooks/LittleSmalltalk/ALittleSmalltalk.pdf
	 */

	/** The immediately surrounding/enclosing method or block.
	 *  If this block is a block within the outermost block (i.e., the method),
	 *  the enclosing context is the same as the enclosing method context.
	 *
	 *  This is not the invokingContext, which says who called us.
	 *
	 *  This is called "caller" by bluebook p580 and
	 *  "creator" by little smalltalk p 192 in pdf
	 */
	public BlockContext enclosingContext;

	/** A shortcut up the enclosingContext chain to the method in which the
	 *  block associated with this context is defined.  We need to locate
	 *  the method context that created us so that we can return properly
	 *  upon METHOD_RETURN bytecode. To perform a return, we unwind the
	 *  stack until we reach one level above enclosingMethodContext and
	 *  then push the return result on that context's stack.
	 *
	 *  Smalltalk code can also create a block and pass it as
	 *  a parameter to some distant method's invocation
	 *  context. If the distant method evaluates the block and the
	 *  block has a method return instruction, it's like an
	 *  exception--we must unroll to the method context that
	 *  created the block and then return from it.  Moreover, if
	 *  the enclosingMethodContext has returned when this block
	 *  tries to return, we still a pointer to the method so we
	 *  can respond appropriately with an error.
	 *
	 *  All enclosingMethodContext for blocks defined within method m
	 *  point at m.
	 *
	 *  This is called "home" by bluebook p580
	 */
	public BlockContext enclosingMethodContext;

	// ----- DEBUGGING (dbg instruction) -----
	public String currentFile;
	public int currentLine;
	public int currentCharPos;
	public int prev_ip = -1; // what was the last instruction? ip points at next to execute not currently executing

	private BlockContext() { // used to just to create RETURNED
        this.vm = null;
        this.compiledBlock = null;
        this.receiver = null;
        this.locals = null;
    }

	/** Create a context from a STCompiledBlock and a receiver object */
    public BlockContext(VirtualMachine vm, STCompiledBlock compiledBlock, STObject receiver) {
        this.vm = vm;
        this.compiledBlock = compiledBlock;
        this.receiver = receiver;
        this.locals = new STObject[compiledBlock.nargs+compiledBlock.nlocals];
        for (int i = 0; i < locals.length; i++) {
            locals[i]=vm.nil();
        }
		// probably not the right place to copy args.  It is a "separate concern" and best done by VM not a ctor
        for (int j = compiledBlock.nargs-1; j >= 0; j--){ //in reversed order
            locals[j] = vm.ctx.pop();
        }
        this.stack = new STObject[INITIAL_STACK_SIZE];
        this.enclosingContext  = null;
		this.enclosingMethodContext = this;	// assume method context by default; this context is the method context
    }

	/** Create a BlockContext from a {@link BlockDescriptor} as a
	 *  result of a "value" message sent to force evaluation. The
	 *  descriptor says which block to execute and knows the
	 *  surrounding context.  All of this is copied to the
	 *  BlockContext.
	 *
	 *  To execute "[...] value", we execute BLOCK followed by
	 *  SEND bytecodes. BLOCK creates a descriptor and pushes it
	 *  onto the stack of the currently active context. SEND looks
	 *  up the "value" selector in the BlockDescriptor and finds a
	 *  primitive method.  The VM does the usual thing and creates
	 *  a method context to invoke the primitive method and starts
	 *  executing the "native" java code of the primitive method
	 *  via performPrimitive().
	 *
	 *  The receiver for the value method is the block descriptor.
	 *  The receiver in the block context must be the receiver of
	 *  the enclosing method context (that defined the block).
	 *  This way methods invoked within a block such as "self
	 *  msg."  interpret self as the right object (the receiver of
	 *  the enclosing method).
	 */

	public BlockContext(VirtualMachine vm, BlockDescriptor descriptor) {
		// better to reuse ctor:
		//this(vm, descriptor.compiledBlock, descriptor.receiver);
        this.vm = vm;
        this.compiledBlock = descriptor.block;
        this.receiver = descriptor.receiver;
        this.locals = new STObject[descriptor.block.nargs+descriptor.block.nlocals];
        for (int i = 0; i < locals.length; i++) {
            locals[i]=vm.nil();
        }
        this.stack = new STObject[INITIAL_STACK_SIZE];
        this.enclosingContext = descriptor.enclosingContext;
        this.enclosingMethodContext = descriptor.enclosingMethodContext;
    }

	public void push(STObject o) {
        doubleStackSize(); //if sp == stack.length -1;
        stack[++sp] = o;
	}

    private void doubleStackSize() {
        if(sp == stack.length - 1){
            STObject[] stackDoubled = new STObject[2*stack.length];
            for(int i = 0; i< stack.length; i++)
                stackDoubled[i] = stack[i];
            stack = stackDoubled;

        }
    }

    public STObject pop() {
        return stack[sp--];
    }
	public STObject top() {
        return stack[sp];
    }

	/** If there is no enclosing context, we must be a method. */
	public boolean isBlock() {
        if(this.enclosingContext == null)
            return false;
        else
            return true;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        BlockContext c = this;
        STMetaClassObject enclosingClass = c.compiledBlock.enclosingClass;
        String s;
        if ( enclosingClass!=null ) {
            s = enclosingClass.name + ">>" + c.compiledBlock.name + c.vm.pLocals(c) + c.vm.pContextWorkStack(c);
        }
        else {
            s = c.compiledBlock.qualifiedName + c.vm.pLocals(c) + c.vm.pContextWorkStack(c);
        }
        buf.append(s);
        return buf.toString();
    }
}


text:
package com.samsung.sec.dexter.core.util;

import static org.junit.Assert.*;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.samsung.sec.dexter.core.config.PeerReviewHome;
import com.samsung.sec.dexter.core.config.PeerReviewHomeJson;

public class PeerReviewHomeUtilTest {
	PeerReviewHomeUtil util;

	@Before
	public void setUp() throws Exception {
		util = new PeerReviewHomeUtil(new Gson());
	}

	@Test
	public void loadJson_GivenAReader_loadPeerRevieHomeJson() {
		// given
		Reader reader = createTestJsonStringReader();
		PeerReviewHomeJson testJson = createTestPeerReviewHomeJson();

		// when
		PeerReviewHomeJson homeJson = util.loadJson(reader);

		// then
		assertEquals(testJson, homeJson);
	}

	private PeerReviewHomeJson createTestPeerReviewHomeJson() {
		DexterServerConfig config = new DexterServerConfig("testId", "testPw", "127.0.0.1", 8080);
		PeerReviewHome firstHome = new PeerReviewHome(config, "testProject", "/test", true);
		PeerReviewHome secondHome = new PeerReviewHome(config, "testProject2", "/test2", false);
		List<PeerReviewHome> homeList = new ArrayList<PeerReviewHome>();
		homeList.add(firstHome);
		homeList.add(secondHome);

		return new PeerReviewHomeJson(config, homeList);
	}

	private Reader createTestJsonStringReader() {
		String jsonString = getTestPeerReviewHomeJsonString();

	    return new StringReader(jsonString);
	}

	private String getTestPeerReviewHomeJsonString() {
		return "{" +
		"  \"server\" : {"	+
		"  \"ip\" : \"127.0.0.1\"," +
		"  \"port\" : 8080," +
		"  \"id\" : \"testId\"," +
		"  \"pw\" : \"testPw\"" +
		"  }," +
		"  \"home\" : [{" +
		"    \"projectName\" : \"testProject\"," +
		"    \"sourceDir\": \"/test\"," +
		"    \"active\" : true" +
		"  }, {" +
		"    \"projectName\" : \"testProject2\"," +
		"    \"sourceDir\": \"/test2\"," +
		"    \"active\" : false" +
		"  }]" +
		"}";
	}

	@Test
	public void saveJson_writeJsonStringToFile() {
		// given
		StringWriter strWriter = new StringWriter();
		PeerReviewHomeJson testJson = createTestPeerReviewHomeJson();

		// when
		try {
			util.saveJson(strWriter, testJson);
		} catch (IOException e) {
			fail();
		}

		// then
		assertEquals(getTestPeerReviewHomeJsonString().replaceAll("\\s", ""), strWriter.toString());
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { expect } from 'chai'
import * as sinon from 'sinon'

import ActionRecordStore from '../../../src/extension/private/ActionRecordStore'
import ActionType from '../../../src/tracker/public/ActionType'

import {
  actionsOfJS,
  actionsOfHTML,
  actionsOfMinHTML
} from '../../actions'

describe('ActionRecordStore', () => {
  let store: IActionRecordStore

  beforeEach(() => {
    store = new ActionRecordStore()
  })

  describe('get', () => {
    it('should return [] given non-exsiting trackid', () => {
      expect(store.get(undefined)).to.deep.equal([])
      expect(store.get(null)).to.deep.equal([])
      expect(store.get('-1')).to.deep.equal([])
      expect(store.get('')).to.deep.equal([])
    })
  })

  describe('registerFromActionInfo', () => {
    describe('correctness of parsing record info', () => {
      function register(infos: ActionInfo[]) {
        return Promise.all(
          infos.map((info) => store.registerFromActionInfo(info))
        )
      }
      it('should register action info correctly given javascript source', async () => {
        const infos = actionsOfJS.map((action) => action.info)
        const records = actionsOfJS.map((action) => action.record)

        return register(infos).then(() => {
          const results = store.get('1')

          expect(results).to.have.length(records.length)
          records.map((record) => {
            expect(results).to.include(record)
          })
        })
      })

      it('should register action info correctly given html source', async () => {
        const infos = actionsOfHTML.map((action) => action.info)
        const records = actionsOfHTML.map((action) => action.record)

        return register(infos).then(() => {
          const results = store.get('1')

          expect(results).to.have.length(records.length)
          records.map((record) => {
            expect(results).to.include(record)
          })
        })
      })

      it('should register action info correctly given minified html source', async () => {
        const infos = actionsOfMinHTML.map((action) => action.info)
        const records = actionsOfMinHTML.map((action) => action.record)

        return register(infos).then(() => {
          const results = store.get('1')

          expect(results).to.have.length(records.length)
          records.map((record) => {
            expect(results).to.include(record)
          })
        })
      })

      it('should register repeated action info at the same time correctly', () => {
        const infos = Array(3).fill(actionsOfJS[5].info)
        const record = actionsOfJS[5].record

        return register(infos).then(() => {
          const results = store.get('1')

          expect(results).to.have.length(1)
          expect(results).to.include(record)
        })
      })

      it('should register repeated action info at different time correctly', async () => {
        for (let i = 0; i < 3; i++) {
          await store.registerFromActionInfo(actionsOfJS[5].info)

          const results = store.get('1')

          expect(results).to.have.length(1)
          expect(results).to.include(actionsOfJS[5].record)
        }
      })
    })

    it('should apply FILO on action records transformed from info in trackid group in ActionRecordStore', async () => {
      await store.registerFromActionInfo(actionsOfJS[0].info)
      await store.registerFromActionInfo(actionsOfJS[1].info)

      expect(store.get('1')).to.deep.equal([actionsOfJS[1].record, actionsOfJS[0].record])
    })

    it('should not allow ActionRecordStore to add duplicate (same source.loc) records (registerd from info) to same trackid group', async () => {
      await store.registerFromActionInfo(actionsOfJS[0].info)
      await store.registerFromActionInfo(actionsOfJS[0].info)

      expect(store.get('1')).to.deep.equal([actionsOfJS[0].record])
    })

    it('should allow ActionRecordStore to add duplicate (same source.loc) records (registerd from info) to different trackid group', async () => {
      await store.registerFromActionInfo(actionsOfJS[0].info)
      await store.registerFromActionInfo(
        Object.assign({}, actionsOfJS[0].info, { trackid: '2' })
      )
      expect(store.get('1')).to.deep.equal([actionsOfJS[0].record])
      expect(store.get('2')).to.deep.equal([actionsOfJS[0].record])
    })

    it('should merge trackid group specified in action info \'merge\' field to the front of target group before adding new record', async () => {
      await store.registerFromActionInfo(actionsOfJS[0].info)
      await store.registerFromActionInfo(
        Object.assign({}, actionsOfJS[1].info, { trackid: '2', merge: '1' })
      )
      expect(store.get('1')).to.deep.equal([])
      expect(store.get('2')).to.deep.equal([actionsOfJS[1].record, actionsOfJS[0].record])

      // should avoid duplication after merging
      await store.registerFromActionInfo(
        Object.assign({}, actionsOfJS[0].info, { trackid: '2' })
      )
      expect(store.get('2')).to.deep.equal([actionsOfJS[1].record, actionsOfJS[0].record])

      // should allow adding original records to the merged trackid group
      await store.registerFromActionInfo(actionsOfJS[0].info)

      expect(store.get('1')).to.deep.equal([actionsOfJS[0].record])
    })

    it('should store two info with same loc but different type properly', async () => {
      return Promise.all([
        store.registerFromActionInfo(actionsOfJS[0].info),
        store.registerFromActionInfo(
          Object.assign({}, actionsOfJS[0].info, {
            trackid: '2',
            type: ActionType.Style
          })
        )
      ]).then(() => {
        expect(store.get('1')).to.deep.equal([actionsOfJS[0].record])
        expect(store.get('2')).to.deep.equal([Object.assign({}, actionsOfJS[0].record, { type: ActionType.Style })])
      })
    })

    it('should return true given info added successfully', async () => {
      const shouldSuccess =
        await store.registerFromActionInfo(actionsOfJS[0].info)

      expect(shouldSuccess).to.be.true
    })

    it('should return false given record added has already been in ActionRecordStore', async () => {
      await store.registerFromActionInfo(actionsOfJS[0].info)

      const shouldFail =
        await store.registerFromActionInfo(actionsOfJS[0].info)

      expect(shouldFail).to.be.false
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:gravity="center"
    android:orientation="vertical">

</LinearLayout>


text:
// Copyright [2011] [PagSeguro Internet Ltda.]
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

using Uol.PagSeguro.Exception;

namespace Uol.PagSeguro.Domain
{
    /// <inheritdoc />
    /// <summary>
    /// Identifies a PagSeguro application
    /// </summary>
    public class ApplicationCredentials : Credentials
    {
        private const string AppIdParameterName = "appId";
        private const string AppKeyParameterName = "appKey";
        private const string AuthorizatinCodeParameterName = "authorizationCode";

        /// <summary>
        /// Initializes a new instance of the ApplicationCredentials class
        /// </summary>
        /// <param name="isSandbox"></param>
        /// <param name="appId"></param>
        /// <param name="appKey"></param>
        /// <param name="authorizationCode"></param>
        /// <remarks>
        /// A PagSeguro application is identified by an app identifier and a app key
        /// </remarks>
        public ApplicationCredentials(bool isSandbox, string appId, string appKey, string authorizationCode = null)
        {
            try
            {
                IsSandbox = isSandbox;
                AttributeDictionary[AppIdParameterName] = appId;
                AttributeDictionary[AppKeyParameterName] = appKey;
            }
            catch (PagSeguroServiceException)
            {
                throw new PagSeguroServiceException("Application Credentials not set correctly.");
            }

            AttributeDictionary[AuthorizatinCodeParameterName] = !string.IsNullOrEmpty(authorizationCode) ? authorizationCode : string.Empty;
        }

        /// <summary>
        /// Primary appId associated with this account
        /// </summary>
        // ReSharper disable once UnusedMember.Global
        public string AppId
        {
            get => AttributeDictionary[AppIdParameterName];
            set => AttributeDictionary[AppIdParameterName] = value;
        }

        /// <summary>
        /// PagSeguro app key
        /// </summary>
        // ReSharper disable once UnusedMember.Global
        public string AppKey
        {
            get => AttributeDictionary[AppKeyParameterName];
            set => AttributeDictionary[AppKeyParameterName] = value;
        }

        /// <summary>
        /// PagSeguro authorization code
        /// </summary>
        // ReSharper disable once UnusedMember.Global
        public string AuthorizationCode
        {
            get => AttributeDictionary[AuthorizatinCodeParameterName];
            set => AttributeDictionary[AuthorizatinCodeParameterName] = value;
        }
    }
}


text:
<?php

/**
 * This service monitors CMS Templates
 *
 * @package    Nails
 * @subpackage module-cms
 * @category   Service
 * @author     Nails Dev Team
 */

namespace Nails\Cms\Service\Monitor;

use Nails\Cms\Constants;
use Nails\Cms\Exception\Template\NotFoundException;
use Nails\Common\Exception\FactoryException;
use Nails\Common\Exception\NailsException;
use Nails\Components;
use Nails\Cms\Interfaces;
use Nails\Factory;

/**
 * Class Template
 *
 * @package Nails\Cms\Service\Monitor
 */
class Template
{
    /** @var Interfaces\Monitor\Template[] */
    protected $aMappers;

    // --------------------------------------------------------------------------

    /**
     * Template constructor.
     *
     * @throws NailsException
     */
    public function __construct()
    {
        $this->aMappers = $this->discoverMappers();
    }

    // --------------------------------------------------------------------------

    /**
     * Discovers Template mappers
     *
     * @return Interfaces\Monitor\Template[]
     * @throws NailsException
     */
    protected function discoverMappers(): array
    {
        $aClasses = [];

        foreach (Components::available() as $oComponent) {

            $oClasses = $oComponent
                ->findClasses('Cms\\Monitor')
                ->whichImplement(Interfaces\Monitor\Template::class)
                ->whichCanBeInstantiated();

            foreach ($oClasses as $sClass) {
                $aClasses[] = new $sClass();
            }
        }

        return $aClasses;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns an array of templates and their usages
     *
     * @return \Nails\Cms\Factory\Monitor\Item[]
     * @throws NotFoundException
     * @throws FactoryException
     */
    public function summary(): array
    {
        /** @var \Nails\Cms\Service\Template $oTemplateService */
        $oTemplateService = Factory::service('Template', Constants::MODULE_SLUG);

        $aSummary = [];
        foreach ($oTemplateService->getAvailable() as $oTemplateGroup) {
            foreach ($oTemplateGroup->getTemplates() as $oTemplate) {

                $iUsages = 0;
                foreach ($this->aMappers as $oMapper) {
                    $iUsages += $oMapper->countUsages($oTemplate);
                }

                /** @var \Nails\Cms\Factory\Monitor\Item $oItem */
                $oItem = Factory::factory(
                    'MonitorItem',
                    Constants::MODULE_SLUG,
                    $oTemplate->getSlug(),
                    $oTemplate->getLabel(),
                    $oTemplate->getDescription(),
                    $iUsages,
                    $oTemplate::isDeprecated(),
                );

                $aSummary[] = $oItem;
            }
        }

        arraySortMulti($aSummary, 'label');

        return $aSummary;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns a summary of where a template is used
     *
     * @param Interfaces\Template $oTemplate
     *
     * @return \Nails\Cms\Factory\Monitor\Detail[]
     * @throws FactoryException
     */
    public function summariseItem(Interfaces\Template $oTemplate)
    {
        $aMappers = [];

        foreach ($this->aMappers as $oMapper) {

            $aUsages = $oMapper->getUsages($oTemplate);
            if (!empty($aUsages)) {

                /** @var \Nails\Cms\Factory\Monitor\Detail $oDetail */
                $oDetail = Factory::factory(
                    'MonitorDetail',
                    Constants::MODULE_SLUG,
                    $oMapper->getLabel(),
                    $aUsages
                );

                $aMappers[] = $oDetail;
            }
        }

        return $aMappers;
    }
}


text:
"""
A set of internal utils used by nc and ni scenario.
"""
from avalanche.benchmarks.utils import make_classification_dataset

def train_eval_transforms(dataset_train, dataset_test):
    """
    Internal utility used to create the transform groups from a couple of
    train and test datasets.

    :param dataset_train: The training dataset.
    :param dataset_test: The test dataset.
    :return: The transformations groups.
    """

    if isinstance(dataset_train, make_classification_dataset):
        train_group = dataset_train.get_transforms("train")
    else:
        train_group = (
            getattr(dataset_train, "transform", None),
            getattr(dataset_train, "target_transform", None),
        )

    if isinstance(dataset_test, make_classification_dataset):
        eval_group = dataset_test.get_transforms("eval")
    else:
        eval_group = (
            getattr(dataset_test, "transform", None),
            getattr(dataset_test, "target_transform", None),
        )

    return dict(train=train_group, eval=eval_group)

__all__ = ["train_eval_transforms"]


text:
let _ = require("lodash");
let util = require("../util");

let input = require("fs").readFileSync("./data").toString();

let ingredients = {};

for (let line of input.split("\n")) {
	let name = line.split(": ")[0];

	let ingredientObject = { };
	let properties = line.split(": ")[1].split(", ");

	for (let property of properties) {
		let propertyName = property.split(" ")[0];
		let value = parseInt(property.split(" ")[1], 10);

		ingredientObject[propertyName] = value;
	}

	ingredients[name] = ingredientObject;
}

function getPropertyScore(property, cookieIngredients) {
	return util.sum(
		cookieIngredients.map(ingredient =>
			ingredient[property] * ingredient.value));
}

// cookie = [{ name, properties, amount }...]
function calculateScore(cookieIngredients) {
	let properties = ["capacity", "durability", "flavor", "texture"];

	let propertyScores = properties.map(property => {
		let score = getPropertyScore(property, cookieIngredients);
		return Math.max(0, score);
	});

	let score = propertyScores.reduce((a, b) => a * b);

	let calories = getPropertyScore("calories", cookieIngredients);

	return {score, calories};
}

function addValue(ingredient, value) {
	ingredient.value = value;
	return ingredient;
}

let maxScore = 0;
let keys = Object.keys(ingredients);

for (let i of _.range(1, 100)) {
	for (let j of _.range(1, 100 - i)) {
		for (let k of _.range(1, 100 - i - j)) {
			let h = 100 - i - j - k;

			let scoreInput = [
				addValue(ingredients[keys[0]], i),
				addValue(ingredients[keys[1]], j),
				addValue(ingredients[keys[2]], k),
				addValue(ingredients[keys[3]], h)
			];

			let SC = calculateScore(scoreInput);

			let score = SC.score;
			let calories = SC.calories;

			maxScore = Math.max(maxScore, score);
		}
	}
}

console.log("Part 1:", maxScore);
maxScore = 0;

for (let i of _.range(1, 100)) {
	for (let j of _.range(1, 100 - i)) {
		for (let k of _.range(1, 100 - i - j)) {
			let h = 100 - i - j - k;

			let scoreInput = [
				addValue(ingredients[keys[0]], i),
				addValue(ingredients[keys[1]], j),
				addValue(ingredients[keys[2]], k),
				addValue(ingredients[keys[3]], h)
			];

			let SC = calculateScore(scoreInput);

			let score = SC.score;
			let calories = SC.calories;

			if (calories === 500) maxScore = Math.max(maxScore, score);
		}
	}
}

console.log("Part 2:", maxScore);


text:
package net.floodlightcontroller.packetstreamer;

import net.floodlightcontroller.packetstreamer.thrift.*;

import java.util.List;
import java.util.ArrayList;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The PacketStreamer Sample Client.
 */
public class PacketStreamerClient {
    protected static Logger log = LoggerFactory.getLogger(PacketStreamerClient.class);

    /**
     * Main function entry point;
     * @param args
     */
    public static void main(String [] args) {
        try {
            int serverPort = Integer.parseInt(System.getProperty("net.floodlightcontroller.packetstreamer.port", "9090"));
            TTransport transport;
            transport = new TFramedTransport(new TSocket("localhost", serverPort));
            transport.open();

            TProtocol protocol = new  TBinaryProtocol(transport);
            PacketStreamer.Client client = new PacketStreamer.Client(protocol);

            sendPackets(client, (short)2, OFMessageType.PACKET_IN, true);
            log.debug("Terminate session1");
            client.terminateSession("session1");

            transport.close();
        } catch (TException x) {
            x.printStackTrace();
        }
    }

    /**
     * Send test packets of the given OFMessageType to the packetstreamer server;
     * @param client Packetstreamer client object
     * @param numPackets number of test packets to be sent
     * @param ofType OFMessageType of the test packets
     * @param sync true if send with synchronous interface, false for asynchronous interface
     * @throws TException
     */
    private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync)
    throws TException {
        while (numPackets-- > 0) {
            Message msg = new Message();
            Packet packet = new Packet();

            List<String> sids = new ArrayList<String>();
            sids.add("session1");
            sids.add("session2");
            msg.setSessionIDs(sids);
            packet.setMessageType(ofType);
            long sw_dpid = numPackets/40 + 1;
            packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short)(numPackets - (sw_dpid-1)*40)));

            String strData = "New data, sequence " + numPackets;
            packet.setData(strData.getBytes());
            msg.setPacket(packet);

            try {
                if (sync) {
                      client.pushMessageSync(msg);
                      log.debug("Send packet sync: " + msg.toString());
                } else {
                      client.pushMessageAsync(msg);
                      log.debug("Send packet sync: " + msg.toString());
                }
            } catch (TTransportException e) {
                log.error(e.toString());
            }

            try {
                Thread.sleep(100);
            } catch (Exception e) {}
        }
    }
}


text:
layout: post-no-feature
title: Blackbar
category: articles
tags: [iOS, text, puzzle]
---

* Such a simple idea, but so well executed. Monochromatic visuals without being stark.
* First, tutorial, level is meta, genius.
* Levels interspersed with story really sets the scene. You get some of that from the levels themselves, but the extras provide the real weight.
* Does very clever things with text formatting: does a lot with a little.
* Difficulty curve measured very well: new things introduced at a good pace.

[Blackbar](http://mrgan.com/blackbar/)


text:
.class Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;
.super Ljava/lang/Object;
.source "VirtualKeyboardFragment.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/settings/inputmethod/VirtualKeyboardFragment;->onResume()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/settings/inputmethod/VirtualKeyboardFragment;

.field final synthetic val$activity:Landroid/app/Activity;

.field final synthetic val$context:Landroid/content/Context;

# direct methods
.method constructor <init>(Lcom/android/settings/inputmethod/VirtualKeyboardFragment;Landroid/app/Activity;Landroid/content/Context;)V
    .locals 0

    iput-object p1, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->this$0:Lcom/android/settings/inputmethod/VirtualKeyboardFragment;

    iput-object p2, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->val$activity:Landroid/app/Activity;

    iput-object p3, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->val$context:Landroid/content/Context;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    iget-object v0, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->val$activity:Landroid/app/Activity;

    invoke-virtual {v0}, Landroid/app/Activity;->hasWindowFocus()Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->this$0:Lcom/android/settings/inputmethod/VirtualKeyboardFragment;

    iget-object v1, p0, Lcom/android/settings/inputmethod/VirtualKeyboardFragment$3;->val$context:Landroid/content/Context;

    invoke-static {v0, v1}, Lcom/android/settings/inputmethod/VirtualKeyboardFragment;->-wrap1(Lcom/android/settings/inputmethod/VirtualKeyboardFragment;Landroid/content/Context;)V

    :cond_0
    return-void
.end method


text:
package com.atexpose.dispatcher.channels.tasks;

import com.atexpose.util.watch.IWatch;
import com.atexpose.util.watch.Watch;
import io.schinzel.basicutils.thrower.Thrower;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

/**
 * The purpose of this class is to fire a task at a certain minute each hour.
 *
 * ZoneId is an argument as some time zones like Indian Standard time is not
 * full hours ahead or behind.
 */
public class ScheduledTaskChannelHourly extends ScheduledTaskChannel {

    public ScheduledTaskChannelHourly(String taskName, String request, int minuteOfHour, String zoneId) {
        this(taskName, request, minuteOfHour, zoneId, Watch.create());
    }

    private ScheduledTaskChannelHourly(String taskName, String request, int minuteOfHour, String zoneId, IWatch watch) {
        super(taskName, request, ChronoUnit.HOURS, 1,
                "Every hour at " + minuteOfHour + " minutes",
                getInitialFireTime(minuteOfHour, TaskUtil.getZoneId(zoneId), watch),
                watch);
    }

    /**
     * @param minuteOfHour The minute of the hour
     * @return The argument minute of the hour
     */
    static int validateMinuteOfHour(int minuteOfHour) {
        Thrower.throwIfVarOutsideRange(minuteOfHour, "minutesOfHour", 0, 59);
        return minuteOfHour;
    }

    /**
     *
     * @param minuteOfHour The minute of the hour to start
     * @param zoneId Which time zone this is for
     * @param watch A watch for testing
     * @return The initial time to fire
     */
    static ZonedDateTime getInitialFireTime(int minuteOfHour, ZoneId zoneId, IWatch watch) {
        ZonedDateTime now = watch.getNowAsInstant()
                .atZone(zoneId);
        ZonedDateTime fireTime = now
                .withMinute(minuteOfHour)
                .withSecond(0)
                .withNano(0);
        ZonedDateTime aFewSecondsInTheFuture = now
                .plusSeconds(30);
        // If the fire time is within 30 seconds of now
        return fireTime.isBefore(aFewSecondsInTheFuture)
                // Set fire time to be next hour
                ? fireTime.plusHours(1)
                : fireTime;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>

    <groupId>com.github.hypfvieh</groupId>
    <artifactId>bluez-dbus-parent</artifactId>
    <version>0.1.5-SNAPSHOT</version>

    <name>${project.artifactId}</name>
    <url>https://github.com/hypfvieh/bluez-dbus</url>

    <description>Java native bluetooth library which uses bluez via dbus (linux only)</description>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.8.2</junit.version>
    </properties>

    <modules>
        <module>bluez-dbus</module>
        <module>bluez-dbus-osgi</module>
    </modules>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
            </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-enforcer-plugin</artifactId>
                </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>3.0.0-M1</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>versions-maven-plugin</artifactId>
                    <version>2.8.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-enforcer-plugin</artifactId>
                    <version>3.0.0-M3</version>
                    <executions>
                        <execution>
                            <id>enforce-maven</id>
                            <goals>
                                <goal>enforce</goal>
                            </goals>
                            <configuration>
                                <rules>
                                    <requireMavenVersion>
                                        <version>3.5.0</version>
                                    </requireMavenVersion>
                                    <requireJavaVersion>
                                        <version>${maven.compiler.source}</version>
                                    </requireJavaVersion>
                                    <requireOS>
                                        <family>unix</family>
                                    </requireOS>
                                </rules>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>animal-sniffer-maven-plugin</artifactId>
                    <version>1.20</version>
                    <configuration>
                        <signature>
                            <groupId>org.codehaus.mojo.signature</groupId>
                            <artifactId>java18</artifactId>
                            <version>1.0</version>
                        </signature>
                    </configuration>
                    <executions>
                        <execution>
                            <id>sniffer_check</id>
                            <phase>test</phase>
                            <goals>
                                <goal>check</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.2.0</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>test-jar</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <archive>
                            <manifest>
                                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M5</version>
                    <configuration>
                        <forkCount>1</forkCount>
                        <reuseForks>false</reuseForks>
                        <systemPropertyVariables>
                            <logback.configurationFile>${basedir}/src/test/resources/logback.xml</logback.configurationFile>
                        </systemPropertyVariables>
                    </configuration>
                </plugin>

                <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-release-plugin</artifactId>
                        <version>3.0.0-M1</version>
                        <configuration>
                            <autoVersionSubmodules>true</autoVersionSubmodules>
                            <useReleaseProfile>false</useReleaseProfile>
                            <releaseProfiles>release</releaseProfiles>
                            <pushChanges>false</pushChanges>
                            <goals>deploy</goals>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-source-plugin</artifactId>
                        <version>3.2.1</version>
                        <executions>
                            <execution>
                                <id>attach-sources</id>
                                <goals>
                                    <goal>jar-no-fork</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>3.2.0</version>
                        <configuration>
							<doclint>none</doclint>
                        </configuration>
                        <executions>
                            <execution>
                                <id>attach-javadocs</id>
                                <goals>
                                    <goal>jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                         <groupId>org.apache.maven.plugins</groupId>
                         <artifactId>maven-compiler-plugin</artifactId>
                         <version>3.8.1</version>
                    </plugin>
                    <plugin>
                         <groupId>org.apache.maven.plugins</groupId>
                         <artifactId>maven-site-plugin</artifactId>
                         <version>3.9.1</version>
                    </plugin>
                    <plugin>
                         <groupId>org.apache.maven.plugins</groupId>
                         <artifactId>maven-clean-plugin</artifactId>
                         <version>3.1.0</version>
                    </plugin>
                    <plugin>
                         <groupId>org.apache.maven.plugins</groupId>
                         <artifactId>maven-resources-plugin</artifactId>
                         <version>3.2.0</version>
                    </plugin>
                    <plugin>
                         <groupId>org.apache.maven.plugins</groupId>
                         <artifactId>maven-install-plugin</artifactId>
                         <version>3.0.0-M1</version>
                    </plugin>
            </plugins>
        </pluginManagement>

    </build>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.32</version>
            </dependency>

            <!-- JUnit testing framework. -->
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <version>${junit.version}</version>
            </dependency>

            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-params</artifactId>
                <version>${junit.version}</version>
            </dependency>

            <!-- needed for IDE support -->
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
                <version>${junit.version}</version>
            </dependency>

            <dependency>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-launcher</artifactId>
                <version>1.8.2</version>
            </dependency>

            <dependency>
                <groupId>com.github.hypfvieh</groupId>
                <artifactId>dbus-java</artifactId>
                <version>3.3.1</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <!-- JUnit testing framework. -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- needed for IDE support -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <scm>
        <connection>scm:git:https://github.com/hypfvieh/bluez-dbus.git</connection>
        <developerConnection>scm:git:https://github.com/hypfvieh/bluez-dbus.git</developerConnection>
        <url>https://github.com/hypfvieh/bluez-dbus.git</url>
      <tag>HEAD</tag>
  </scm>

    <licenses>
        <license>
            <name>MIT License</name>
            <url>https://github.com/hypfvieh/bluez-dbus/blob/master/LICENSE</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>hypfvieh</id>
            <name>David M.</name>
            <email>hypfvieh@googlemail.com</email>
        </developer>
    </developers>

    <profiles>
        <profile>
            <id>release</id>
            <properties>
                <gpg.executable>gpg2</gpg.executable>
            </properties>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package net.transitdata.siri;

import java.math.*;
import java.util.GregorianCalendar;

import javax.xml.bind.JAXBContext;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.validation.Schema;

import uk.org.siri.siri_2.*;

public class NewLinesRequest {
	JAXBContext jc;
	DatatypeFactory df = null;
	Schema schema = null;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		NewLinesRequest nlr = new NewLinesRequest();

		Util ut = new Util();

		LinesDeliveryStructure lds = nlr.getLinesDdlivery();
		Siri siri = new Siri();

		siri.setLinesDelivery(lds);

		String xml = ut.getXMLFromObject(siri, true);
		//String json = ut.getJSONFromObject(siri, true);

		System.out.println("XML:\n" + xml );
		//System.out.println("JSON:\n" + json);
		ut.validateXML(xml);

	}

	private LinesDeliveryStructure getLinesDdlivery() {
		LinesDeliveryStructure lds = new LinesDeliveryStructure();

		return lds;
	}

}


text:
[![Build Status](https://travis-ci.org/mgraffg/EvoDAG.svg?branch=master)](https://travis-ci.org/mgraffg/EvoDAG)
[![Build Status](https://travis-ci.org/mgraffg/EvoDAG.svg?branch=develop)](https://travis-ci.org/mgraffg/EvoDAG)
[![Build status](https://ci.appveyor.com/api/projects/status/vx09qqgluff3ko5e?svg=true)](https://ci.appveyor.com/project/mgraffg/evodag)
[![Build status](https://ci.appveyor.com/api/projects/status/vx09qqgluff3ko5e/branch/master?svg=true)](https://ci.appveyor.com/project/mgraffg/evodag/branch/master)
[![Coverage Status](https://coveralls.io/repos/github/mgraffg/EvoDAG/badge.svg?branch=master)](https://coveralls.io/github/mgraffg/EvoDAG?branch=master)
[![Anaconda-Server Badge](https://anaconda.org/ingeotec/evodag/badges/version.svg)](https://anaconda.org/ingeotec/evodag)
[![Anaconda-Server Badge](https://anaconda.org/ingeotec/evodag/badges/latest_release_date.svg)](https://anaconda.org/ingeotec/evodag)
[![Anaconda-Server Badge](https://anaconda.org/ingeotec/evodag/badges/platforms.svg)](https://anaconda.org/ingeotec/evodag)
[![Anaconda-Server Badge](https://anaconda.org/ingeotec/evodag/badges/installer/conda.svg)](https://conda.anaconda.org/ingeotec)
[![PyPI version](https://badge.fury.io/py/EvoDAG.svg)](https://badge.fury.io/py/EvoDAG)
[![Anaconda-Server Badge](https://anaconda.org/ingeotec/evodag/badges/license.svg)](https://anaconda.org/ingeotec/evodag)

# EvoDAG #

Evolving Directed Acyclic Graph (EvoDAG) is a steady-state Genetic Programming system
with tournament selection. The main characteristic of EvoDAG is that
the genetic operation is performed at the root. EvoDAG was inspired
by the geometric semantic crossover proposed by
[Alberto Moraglio](https://scholar.google.com.mx/citations?user=0y4XRI0AAAAJ&hl=en&oi=ao)
_et al._ and the implementation performed by
[Leonardo Vanneschi](https://scholar.google.com.mx/citations?user=uR5K07QAAAAJ&hl=en&oi=ao)
_et al_.

EvoDAG is described in the following conference paper
[EvoDAG: A semantic Genetic Programming Python library](http://ieeexplore.ieee.org/document/7830633/)
Mario Graff, Eric S. Tellez, Sabino Miranda-Jiménez, Hugo Jair Escalante.
2016 IEEE International Autumn Meeting on Power, Electronics and Computing (ROPEC)
pp 1-6. A pre-print version can be download from [here](http://ws.ingeotec.mx/~mgraffg/publications/pdf/ropec2016.pdf).

## Quick Start ##

There are two options to use EvoDAG, one is as a library and the other is using the command line interface.

### Using EvoDAG as library

Let us assume that `X` contains the inputs and `y` contains the
classes. Then in order to train an ensemble of 30 EvoDAG and predict
`X` one uses the following instructions:

```python
# Importing EvoDAG ensemble
from EvoDAG.model import EvoDAGE
# Importing iris dataset from sklearn
from sklearn.datasets import load_iris

# Reading data
data = load_iris()
X = data.data
y = data.target

#train the model
m = EvoDAGE(n_estimators=30, n_jobs=4).fit(X, y)

#predict X using the model
hy = m.predict(X)
```

### Using EvoDAG from the command line

Let us assume one wants to create a classifier of iris dataset. The
first step is to download the dataset from the UCI Machine Learning
Repository

```bash
curl -O https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
```

#### Training EvoDAG

Let us assume, you do not want to optimise the EvoDAG parameters, so the
default parameters are used when flag `-P` is not present, i.e.,

```bash
EvoDAG-train -C -m model.evodag -n 100 -u 4 iris.data
```
`-C` flag indicates that it is a classification problem, and
`-R` is for regression problems; there are different default parameters
for each type of problems.

The performance of EvoDAG without optimising the parameters is
presented in the last column of the performance table.

#### Predict

Once the model is obtained, it is time to use it; given that `iris.data`
was not split into a training and test set, let us assume
that `iris.data` contains some unknown data.
In order to predict `iris.data` one would do:

```bash
EvoDAG-predict -m model.evodag -o iris.predicted iris.data
```

where `-o` indicates the file name used to store the predictions, `-m`
contains the model, and `iris.data` is the test set.

# Performance #

The next table presents the average performance in terms of the
balance error rate (BER) of different classifiers found in
[scikit-learn](http://scikit-learn.org) on nine classification
problems (these benchmarks can be found:
[matlab](http://theoval.cmp.uea.ac.uk/matlab/benchmarks) and [text](http://ws.ingeotec.mx/~mgraffg/classification)).
The best performance among each classification dataset is in
bold face to facilitate the reading. EvoDAG is trained using the
commands describe in Quick Start Section.

|Classifier|Average rank|banana | thyroid | diabetis | heart | ringnorm | twonorm |german| image | waveform|
|-------|------:|------:|-------:|----:|--------:|--------:|------:|-----:|--------:|---------:|
|EvoDAG|2.4|12.0|7.7|**25.0**|**16.1**|1.5|2.3|28.3|3.6|10.8|
|SVC|5.3|11.6|8.1|29.8|17.7|1.8|2.7|33.3|8.9|**10.7**|
|GaussianNB|5.9|41.6|11.5|28.6|16.3|1.4|2.4|30.6|36.7|12.2|
|GradientBoosting|6.1|13.8|8.2|28.5|21.1|6.6|5.7|31.1|2.1|13.6|
|MLP|6.4|18.8|9.3|28.6|18.3|11.0|2.8|32.0|3.4|11.4|
|NearestCentroid|7.4|46.3|22.5|28.2|16.7|24.1|2.3|27.7|37.1|13.0|
|AdaBoost|8.3|28.2|8.7|29.3|22.5|7.0|5.4|31.6|3.2|14.6|
|ExtraTrees|8.7|13.5|6.6|33.0|21.1|8.4|7.8|36.9|2.4|16.5|
|LinearSVC|8.8|50.0|16.9|28.5|16.8|25.2|3.6|32.4|18.6|14.2|
|LogisticRegression|9.1|50.0|20.2|28.3|17.0|25.3|2.9|32.1|18.7|13.7|
|RandomForest|9.1|13.6|7.9|31.9|21.4|9.6|8.9|36.7|2.1|16.9|
|KNeighbors|9.4|11.9|12.1|32.1|18.6|43.7|3.8|36.2|5.3|13.8|
|BernoulliNB|11.6|45.5|32.5|31.9|16.6|28.1|5.8|32.8|39.0|14.3|
|DecisionTree|11.8|15.2|9.3|33.9|27.1|19.2|20.9|36.5|3.4|20.8|
|SGD|14.0|50.3|17.7|34.0|22.2|32.6|3.9|38.5|25.1|17.6|
|PassiveAggressive|14.1|49.0|19.5|34.7|23.3|31.5|3.9|38.7|26.2|17.1|
|Perceptron|14.4|50.2|18.2|34.6|21.6|33.5|3.9|37.5|26.7|19.0|

The predictions of EvoDAG were obtained using the following script:

```bash
dirname=evodag-`EvoDAG-params --version | awk '{print $2}'`
[ ! -d $dirname ] && mkdir $dirname

echo Haciendo `EvoDAG-params --version`

for train in csv/*train_data*.csv;
do
        test=`python -c "import sys; print(sys.argv[1].replace('train', 'test'))" $train`;
        output=`basename ${test} .csv`
        predict=${dirname}/${output}.predict
        model=${dirname}/${output}.model
        if [ ! -f $model ]
        then
            EvoDAG-train -C -u 32 -m $model -t $test $train
        fi
        if [ ! -f $predict ]
        then
            EvoDAG-predict -u 32 -m $model -o $predict $test
        fi
done
```

The predictions sklearn classifiers were obtained using the following
code:

```python
from sklearn.linear_model import LogisticRegression, SGDClassifier, Perceptron
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors.nearest_centroid import NearestCentroid
from sklearn.svm import SVC, LinearSVC
from sklearn.naive_bayes import GaussianNB, BernoulliNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
from glob import glob
import numpy as np

def predict(train, test, alg):
    X = np.loadtxt(train, delimiter=',')
    Xtrain = X[:, :-1]
    ytrain = X[:, -1]
    Xtest = np.loadtxt(test, delimiter=',')
    m = alg().fit(Xtrain, ytrain)
    return m.predict(Xtest)

ALG = [LogisticRegression, SGDClassifier, Perceptron,
       PassiveAggressiveClassifier, SVC, LinearSVC, KNeighborsClassifier, NearestCentroid,
       GaussianNB, BernoulliNB, DecisionTreeClassifier, RandomForestClassifier,
       ExtraTreesClassifier, AdaBoostClassifier, GradientBoostingClassifier, MLPClassifier]

for dataset in ['banana', 'thyroid', 'diabetis', 'heart',
                'ringnorm', 'twonorm', 'german', 'image',
                'waveform']:
    for train in glob('csv/%s_train_data*.csv' % dataset):
        test = train.replace('_train_', '_test_')
        hy_alg = [predict(train, test, alg) for alg in ALG]
```

## Citing EvoDAG ##

If you like EvoDAG, and it is used in a scientific publication, I would
appreciate citations to either the conference paper or the book chapter:

[EvoDAG: A semantic Genetic Programming Python library](http://ieeexplore.ieee.org/document/7830633/)
Mario Graff, Eric S. Tellez, Sabino Miranda-Jiménez, Hugo Jair Escalante.
2016 IEEE International Autumn Meeting on Power, Electronics and Computing (ROPEC)
pp 1-6.
```bibtex
@inproceedings{graff_evodag:_2016,
	title = {{EvoDAG}: {A} semantic {Genetic} {Programming} {Python} library},
	shorttitle = {{EvoDAG}},
	doi = {10.1109/ROPEC.2016.7830633},
	abstract = {Genetic Programming (GP) is an evolutionary algorithm that has received a lot of attention lately due to its success in solving hard real-world problems. Lately, there has been considerable interest in GP's community to develop semantic genetic operators, i.e., operators that work on the phenotype. In this contribution, we describe EvoDAG (Evolving Directed Acyclic Graph) which is a Python library that implements a steady-state semantic Genetic Programming with tournament selection using an extension of our previous crossover operators based on orthogonal projections in the phenotype space. To show the effectiveness of EvoDAG, it is compared against state-of-the-art classifiers on different benchmark problems, experimental results indicate that EvoDAG is very competitive.},
	booktitle = {2016 {IEEE} {International} {Autumn} {Meeting} on {Power}, {Electronics} and {Computing} ({ROPEC})},
	author = {Graff, M. and Tellez, E. S. and Miranda-Jiménez, S. and Escalante, H. J.},
	month = nov,
	year = {2016},
	keywords = {directed graphs, Electronic mail, EvoDAG, evolving directed acyclic graph, Genetic algorithms, GP community, Libraries, semantic genetic operators, semantic genetic programming Python library, Semantics, Sociology, Statistics, Steady-state, steady-state semantic genetic programming, Training},
	pages = {1--6}
}
```

[Semantic Genetic Programming for Sentiment Analysis](http://link.springer.com/chapter/10.1007/978-3-319-44003-3_2)
Mario Graff, Eric S. Tellez, Hugo Jair Escalante, Sabino
Miranda-Jiménez. NEO 2015
Volume 663 of the series Studies in Computational Intelligence pp 43-65.
```bibtex
@incollection{graff_semantic_2017,
	series = {Studies in {Computational} {Intelligence}},
	title = {Semantic {Genetic} {Programming} for {Sentiment} {Analysis}},
	copyright = {©2017 Springer International Publishing Switzerland},
	isbn = {9783319440026 9783319440033},
	url = {http://link.springer.com/chapter/10.1007/978-3-319-44003-3_2},
	abstract = {Sentiment analysis is one of the most important tasks in text mining. This field has a high impact for government and private companies to support major decision-making policies. Even though Genetic Programming (GP) has been widely used to solve real world problems, GP is seldom used to tackle this trendy problem. This contribution starts rectifying this research gap by proposing a novel GP system, namely, Root Genetic Programming, and extending our previous genetic operators based on projections on the phenotype space. The results show that these systems are able to tackle this problem being competitive with other state-of-the-art classifiers, and, also, give insight to approach large scale problems represented on high dimensional spaces.},
	language = {en},
	number = {663},
	urldate = {2016-09-20},
	booktitle = {{NEO} 2015},
	publisher = {Springer International Publishing},
	author = {Graff, Mario and Tellez, Eric S. and Escalante, Hugo Jair and Miranda-Jiménez, Sabino},
	editor = {Schütze, Oliver and Trujillo, Leonardo and Legrand, Pierrick and Maldonado, Yazmin},
	year = {2017},
	note = {DOI: 10.1007/978-3-319-44003-3\_2},
	keywords = {Artificial Intelligence (incl. Robotics), Big Data/Analytics, Computational intelligence, Computer Imaging, Vision, Pattern Recognition and Graphics, Genetic programming, optimization, Semantic Crossover, sentiment analysis, Text mining},
	pages = {43--65}
}
```

## EvoDAG from command line ##

Let us assume one wants to create a classifier of iris dataset. The
first step is to download the dataset from the UCI Machine Learning
Repository

```bash
curl -O https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
```

### Random search on the EvoDAG's parameters space

In order to boost the performance of EvoDAG, it is recommended to optimize the parameters used by
EvoDAG. In order to free the user from this task, EvoDAG can perform a random
search on the parameter space. EvoDAG selects the best configuration found
on the random search. This can be performed as follows:

```bash__
EvoDAG-params -C -P params.evodag -r 734 -u 4 iris.data
```

where `-C` indicates that the task is classification,
`-P` indicates the file name where the parameters sampled are
stored, `-r` specifies the number of samples
(all the experiments presented here sampled 734 points which
corresponded, in early versions, the 0.1% of the search space), `-u` indicates the number of
cpu cores, and `iris.data` is the dataset.

`params.evodag` looks like:

```json
[
    {
        "Add": 30,
        "Cos": false,
        "Div": true,
        "Exp": true,
        "Fabs": true,
        "If": true,
        "Ln": true,
        "Max": 5,
        "Min": 30,
        "Mul": 0,
        "Sigmoid": true,
        "Sin": false,
        "Sq": true,
        "Sqrt": true,
        "classifier": true,
        "early_stopping_rounds": 2000,
        "fitness": [
            0.0,
            0.0,
            0.0
        ],
        "popsize": 500,
        "seed": 0,
        "unique_individuals": true
    },
...
```

where `fitness` is the balance error rate on a validation set, which
is randomly taken from the training set, in this case the 20% of `iris.data`.

### Training EvoDAG

At this point, we are in the position to train a model. Let us assume
one would like to create an ensemble of 10 classifiers on
`iris.data`. The following command performs this action:

```bash
EvoDAG-train -P params.evodag -m model.evodag -n 100 -u 4 iris.data
```

where `-m` specifies the file name used to store the model, `-n` is
the size of the ensemble, `-P` receives EvoDAG's parameters, `-u` is
the number of cpu cores, and `iris.data` is the dataset.

### Predict using EvoDAG model

At this point, EvoDAG has been trained and the model is stored in
`model.evodag`, the next step is to use this model to predict some
unknown data. Given that `iris.data` was not split into a training
and test set, let us assume that `iris.data` contains some unknown
data. In order to predict `iris.data` one would do:

```bash
EvoDAG-predict -m model.evodag -o iris.predicted iris.data
```

where `-o` indicates the file name used to store the predictions, `-m`
contains the model, and `iris.data` has the test set.

`iris.predicted` looks like:

```
Iris-setosa
Iris-setosa
Iris-setosa
Iris-setosa
Iris-setosa
...
```

# Install EvoDAG #

* Install using [conda](https://www.continuum.io)
```bash
conda install -c ingeotec evodag
```
Currently, EvoDAG is available for Python 3.4, 3.5, and 3.6 for
windows-32, windows-64, linux-64 and osx-64

* Install using pip
```bash
pip install EvoDAG
```

## Using source code ##

* Clone the repository
```git clone  https://github.com/mgraffg/EvoDAG.git```
* Install the package as usual
```python setup.py install```
* To install only for the use then
```python setup.py install --user```


text:
package se.callista.oauth.socialmedia.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by magnus on 18/08/14.
 */
@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


text:
Since there is no whitelisting (at least I could not find any traces of
it in the source code for the WDC API or the Simulator) HTTP resources
on the internal network can be secured against smuggling out by setting
up the Same Origin Policy on the target servers (by default servers
should refuse.

### Scenario 2: Malicious connector th on a remote server, badly configured target

Since the Same Origin Policy is applied after the request takes
place (since its implemented on the server side), a server configured
to share embeddable web resources may allow the attacker to both smuggle out
the content and/or trigger actions (URLs having side-effects) on the target
server (both in the Simulator and when using Tableau itself).

### Scenario 2: Malicious connector on the target server

If the malicious party can trick the users to install the connector on
the target server (like a Tomcat WAR package deployed to the companys
internal workgroup server), its Game Over.

The WDC framework cannot protect against compromise.

### Suggestions

- Make all connectors declare their intentions in a non-programmatic
  way before use. For example:

  - A JSON file declaring the name of the connector, some signature data
    to verify its origin and untouched nature, and the url masks it will
    be using (which will be whitelisted for the connector if the user
    accepts them)

  - Before first use, show this data to the user and allow them to
    review the policies of the connector before any of its code is ran.
    (like mobile applications show the required permissions before
    install)

  - If the signature of the connector changes, notify the user and
    let them re-review and re-accept the policies / the connector

# General

## Bugs(?)

- When setting tableau.password or tableau.username before calling
  tableau.submit() the connector works fine in the simulator, but
  accessing tableau.username and tableau.password in the data callback
  they are blank in Tableau.

  We currently work around it by storing the username / password in the
  connectionData in plain text :(

## Things that could make WDC better:

- better communication when using Tableua instead of the Simulator (error and
  log messages are swallowed by Tableau, and we cannot show a meaningful error
  message if the extraction fails after tableau.submit() is called )

- Perheaps a +tableau.encryptedData+ field where we can store
  arbitrary data that wont be stored plain-text in the Tableu file.
  Currently only tableau.password provides this capability.

- The option to turn off showing of the password field in the simulator
  (during demos and more importanty debugging of failed connectors,
  private passwords used to access confidential sources may be leaked
  to the developer or anyone with a plain view of the screen)

- Provide a callback to update some kind of progress meter on the
  Tableau interface during the data extract so the user can see
  the progress when importing a larger number of rows (for example:
  loading 4000 rows in 30 row pages on a throttled HTTP API)


text:
package pl.junit.perf.test;

import org.junit.Test;
import pl.junit.perf.PerformanceTestFrame;
import pl.junit.perf.annotations.ReferenceTest;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by pliszewski on 14.08.2017.
 */
public class DefaultReferenceTest extends PerformanceTestFrame {

    private static final List<Integer> integers;

    static {
        integers = new ArrayList<>();
        Random rand = new Random();
        for (int i = 0; i < 17_000; i++) {
            integers.add(rand.nextInt());
        }
    }

    @Test
    @ReferenceTest(warmupIterations = 10, iterations = 10)
    public void test() {
        BubbleSort.sort(integers);
    }

}


text:
module BugzillaWorkerCommon
  BugNotFoundError = Class.new(StandardError)

  def product
    Settings.bugzilla.product
  end

  def with_bug(bug_id)
    return unless block_given?
    BugzillaService.call do
      output = ActiveBugzilla::Bug.find(:product => product, :id => bug_id)
      raise BugNotFoundError if output.empty?
      bug = output.first
      yield(bug)
    end
  end
end


text:
from django.apps import AppConfig

class SessionProfileConfig(AppConfig):
    name = "sessionprofile"

    def ready(self):
        from . import signals  # noqa


text:
Simple Node, Express and Typescript Starter Kit

### Install following dependencies
```bash
npm install
typings install
```

### Run following command to start Api server
```bash
npm start
```

### Many thanks to @jburger.
https://github.com/jburger/examples#readme

#### I have modified the original code to update Typescript and other dependencies. Restructured the folders.

#### Recommended to use VSCode Editor for NodeJs development. I have added .vscode settings to exclude unnecessary folders from workspace.


text:
package all

import (
	_ "github.com/influxdata/telegraf/plugins/processors/clone"
	_ "github.com/influxdata/telegraf/plugins/processors/converter"
	_ "github.com/influxdata/telegraf/plugins/processors/date"
	_ "github.com/influxdata/telegraf/plugins/processors/dedup"
	_ "github.com/influxdata/telegraf/plugins/processors/defaults"
	_ "github.com/influxdata/telegraf/plugins/processors/enum"
	_ "github.com/influxdata/telegraf/plugins/processors/execd"
	_ "github.com/influxdata/telegraf/plugins/processors/filepath"
	_ "github.com/influxdata/telegraf/plugins/processors/ifname"
	_ "github.com/influxdata/telegraf/plugins/processors/override"
	_ "github.com/influxdata/telegraf/plugins/processors/parser"
	_ "github.com/influxdata/telegraf/plugins/processors/pivot"
	_ "github.com/influxdata/telegraf/plugins/processors/port_name"
	_ "github.com/influxdata/telegraf/plugins/processors/printer"
	_ "github.com/influxdata/telegraf/plugins/processors/regex"
	_ "github.com/influxdata/telegraf/plugins/processors/rename"
	_ "github.com/influxdata/telegraf/plugins/processors/reverse_dns"
	_ "github.com/influxdata/telegraf/plugins/processors/s2geo"
	_ "github.com/influxdata/telegraf/plugins/processors/starlark"
	_ "github.com/influxdata/telegraf/plugins/processors/strings"
	_ "github.com/influxdata/telegraf/plugins/processors/tag_limit"
	_ "github.com/influxdata/telegraf/plugins/processors/template"
	_ "github.com/influxdata/telegraf/plugins/processors/topk"
	_ "github.com/influxdata/telegraf/plugins/processors/unpivot"
)


text:
package gorm_test

import (
	"log"

	"github.com/jinzhu/gorm"
	"github.com/lib/pq"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
	gormtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/jinzhu/gorm"
)

func ExampleOpen() {
	// Register augments the provided driver with tracing, enabling it to be loaded by gormtrace.Open.
	sqltrace.Register("postgres", &pq.Driver{}, sqltrace.WithServiceName("my-service"))

	// Open the registered driver, allowing all uses of the returned *gorm.DB to be traced.
	db, err := gormtrace.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=disable")
	defer db.Close()
	if err != nil {
		log.Fatal(err)
	}

	user := struct {
		gorm.Model
		Name string
	}{}

	// All calls through gorm.DB are now traced.
	db.Where("name = ?", "jinzhu").First(&user)
}


text:
package imagechange

import (
	"fmt"

	"github.com/golang/glog"

	deployapi "github.com/openshift/origin/pkg/deploy/api"
	imageapi "github.com/openshift/origin/pkg/image/api"
)

// ImageChangeController increments the version of a DeploymentConfig which has an image
// change trigger when a tag update to a triggered ImageStream is detected.
//
// Use the ImageChangeControllerFactory to create this controller.
type ImageChangeController struct {
	deploymentConfigClient deploymentConfigClient
}

// fatalError is an error which can't be retried.
type fatalError string

func (e fatalError) Error() string { return "fatal error handling imageRepository: " + string(e) }

// Handle processes image change triggers associated with imageRepo.
func (c *ImageChangeController) Handle(imageRepo *imageapi.ImageStream) error {
	configs, err := c.deploymentConfigClient.listDeploymentConfigs()
	if err != nil {
		return fmt.Errorf("couldn't get list of deploymentConfigs while handling imageRepo %s: %v", labelForRepo(imageRepo), err)
	}

	// Find any configs which should be updated based on the new image state
	configsToUpdate := map[string]*deployapi.DeploymentConfig{}
	for _, config := range configs {
		glog.V(4).Infof("Detecting changed images for deploymentConfig %s", labelFor(config))

		for _, trigger := range config.Triggers {
			params := trigger.ImageChangeParams

			// Only automatic image change triggers should fire
			if trigger.Type != deployapi.DeploymentTriggerOnImageChange || !params.Automatic {
				continue
			}

			// Check if the image repo matches the trigger
			if !triggerMatchesImage(config, params, imageRepo) {
				continue
			}

			// Find the latest tag event for the trigger tag
			latestEvent := imageapi.LatestTaggedImage(imageRepo, params.Tag)
			if latestEvent == nil {
				glog.V(4).Infof("Couldn't find latest tag event for tag %s in imageRepo %s", params.Tag, labelForRepo(imageRepo))
				continue
			}

			// Ensure a change occured
			if len(latestEvent.DockerImageReference) > 0 &&
				latestEvent.DockerImageReference != params.LastTriggeredImage {
				// Mark the config for regeneration
				configsToUpdate[config.Name] = config
			}
		}
	}

	// Attempt to regenerate all configs which may contain image updates
	anyFailed := false
	for _, config := range configsToUpdate {
		err := c.regenerate(config)
		if err != nil {
			anyFailed = true
			glog.Infof("couldn't regenerate depoymentConfig %s: %s", labelFor(config), err)
			continue
		}

		glog.V(4).Infof("Regenerated deploymentConfig %s in response to image change trigger", labelFor(config))
	}

	if anyFailed {
		return fatalError(fmt.Sprintf("couldn't update some deploymentConfigs for trigger on imageRepo %s", labelForRepo(imageRepo)))
	}

	glog.V(4).Infof("Updated all configs for trigger on imageRepo %s", labelForRepo(imageRepo))
	return nil
}

// triggerMatchesImages decides whether a given trigger for config matches the provided image repo.
// When matching:
// - The trigger From field is preferred over the deprecated RepositoryName field.
// - The namespace of the trigger is preferred over the config's namespace.
func triggerMatchesImage(config *deployapi.DeploymentConfig, params *deployapi.DeploymentTriggerImageChangeParams, repo *imageapi.ImageStream) bool {
	if len(params.From.Name) > 0 {
		namespace := params.From.Namespace
		if len(namespace) == 0 {
			namespace = config.Namespace
		}

		return repo.Namespace == namespace && repo.Name == params.From.Name
	}

	// This is an invalid state (as one of From.Name or RepositoryName is required), but
	// account for it anyway.
	if len(params.RepositoryName) == 0 {
		return false
	}

	// If the repo's repository information isn't yet available, we can't assume it'll match.
	return len(repo.Status.DockerImageRepository) > 0 &&
		params.RepositoryName == repo.Status.DockerImageRepository
}

// regenerate calls the generator to get a new config. If the newly generated
// config's version is newer, update the old config to be the new config.
// Otherwise do nothing.
func (c *ImageChangeController) regenerate(config *deployapi.DeploymentConfig) error {
	// Get a regenerated config which includes the new image repo references
	newConfig, err := c.deploymentConfigClient.generateDeploymentConfig(config.Namespace, config.Name)
	if err != nil {
		return fmt.Errorf("error generating new version of deploymentConfig %s: %v", labelFor(config), err)
	}

	// No update occured
	if config.LatestVersion == newConfig.LatestVersion {
		glog.V(4).Infof("No version difference for generated config %s", labelFor(config))
		return nil
	}

	// Persist the new config
	_, err = c.deploymentConfigClient.updateDeploymentConfig(newConfig.Namespace, newConfig)
	if err != nil {
		return err
	}

	glog.Infof("Regenerated depoymentConfig %s for image updates", labelFor(config))
	return nil
}

func labelForRepo(imageRepo *imageapi.ImageStream) string {
	return fmt.Sprintf("%s/%s", imageRepo.Namespace, imageRepo.Name)
}

// labelFor builds a string identifier for a DeploymentConfig.
func labelFor(config *deployapi.DeploymentConfig) string {
	return fmt.Sprintf("%s/%s:%d", config.Namespace, config.Name, config.LatestVersion)
}

// ImageChangeControllerDeploymentConfigClient abstracts access to DeploymentConfigs.
type deploymentConfigClient interface {
	listDeploymentConfigs() ([]*deployapi.DeploymentConfig, error)
	updateDeploymentConfig(namespace string, config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error)
	generateDeploymentConfig(namespace, name string) (*deployapi.DeploymentConfig, error)
}

// ImageChangeControllerDeploymentConfigClientImpl is a pluggable ChangeStrategy.
type deploymentConfigClientImpl struct {
	listDeploymentConfigsFunc    func() ([]*deployapi.DeploymentConfig, error)
	generateDeploymentConfigFunc func(namespace, name string) (*deployapi.DeploymentConfig, error)
	updateDeploymentConfigFunc   func(namespace string, config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error)
}

func (i *deploymentConfigClientImpl) listDeploymentConfigs() ([]*deployapi.DeploymentConfig, error) {
	return i.listDeploymentConfigsFunc()
}

func (i *deploymentConfigClientImpl) generateDeploymentConfig(namespace, name string) (*deployapi.DeploymentConfig, error) {
	return i.generateDeploymentConfigFunc(namespace, name)
}

func (i *deploymentConfigClientImpl) updateDeploymentConfig(namespace string, config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {
	return i.updateDeploymentConfigFunc(namespace, config)
}


text:
package com.streamsets.datacollector.runner;

import com.codahale.metrics.ExponentiallyDecayingReservoir;
import com.google.common.annotations.VisibleForTesting;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.executor.SafeScheduledExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

public class ResourceControlledScheduledExecutor {
  private static final long DELAY_MINIMUM = 5000; // ms
  private static final Logger LOG = LoggerFactory.getLogger(ResourceControlledScheduledExecutor.class);
  private final SafeScheduledExecutorService scheduledExecutorService;
  private final List<Runnable> tasks = new CopyOnWriteArrayList<>();
  public ResourceControlledScheduledExecutor(final float maxCpuConsumption) {
    this(maxCpuConsumption, DELAY_MINIMUM);
  }
  public ResourceControlledScheduledExecutor(final float maxCpuConsumption, final long minimumDelay) {
    Utils.checkArgument(maxCpuConsumption > 0, "Max CPU Consumption cannot be less than zero");
    scheduledExecutorService = new SafeScheduledExecutorService(2, "ResourceControlledScheduledExecutor");
    scheduledExecutorService.scheduleAndForget(new Runnable() {
      private final ExponentiallyDecayingReservoir decayingReservoir =
        new ExponentiallyDecayingReservoir();
      @Override
      public void run() {
        long start = System.currentTimeMillis();
        boolean anyThrewError = false;
        for (Runnable task : tasks) {
          try {
            task.run();
          } catch (Throwable throwable) {
            anyThrewError = true;
            // unfortunately ScheduledExecutorService will eat throwables
            // and then stop scheduling runnables which threw them
            LOG.error("Task " + task + " had error: " + throwable, throwable);
          }
        }
        long delay = minimumDelay;
        if (!tasks.isEmpty()) {
          decayingReservoir.update(System.currentTimeMillis() - start);
          delay = calculateDelay(decayingReservoir.getSnapshot().getMedian(), maxCpuConsumption);
        }
        if (anyThrewError) {
          // if a task fails with an exception it may have failed very quickly in which
          // cause we will spin quite quickly spewing exceptions to the logs. If anything
          // errors then we should proceed with caution
          delay = Math.max(delay, TimeUnit.MINUTES.toMillis(1));
        } else if (delay < minimumDelay) {
          delay = minimumDelay;
        }
        try {
          scheduledExecutorService.scheduleAndForget(this, delay, TimeUnit.MILLISECONDS);
        } catch (RejectedExecutionException e) {
          if (!scheduledExecutorService.isShutdown()) {
            throw e;
          }
        }
      }
    }, 10, TimeUnit.MILLISECONDS);
  }

  public void submit(final Runnable runnable) {
    tasks.add(runnable);
  }

  public void shutdown() {
    scheduledExecutorService.shutdown();
  }

  @VisibleForTesting
  static long calculateDelay(double average, double maxCpuConsumption) {
    return ((long)(average / maxCpuConsumption)) - (long)average;
  }
}


text:
<!DOCTYPE html>

  <title>TEMPLATE PAGE</title>

  <link href="Content/bootstrap.min.css" rel="stylesheet" />
  <link href="Content/Site.css" rel="stylesheet" />
  <link href="Content/pdsa-sidebar.css" rel="stylesheet" />
  <link href="Content/pdsa-summary-block.css" rel="stylesheet" />
  <link href="Content/pdsa-readme-box.css" rel="stylesheet" />
  <link href="Content/pdsa-collapser.css" rel="stylesheet" />

                              LINUX MAX

                                                  Introduccion

                                                ¿Qué es GNU/Linux?
                                                Características del sistema
                                                Distribuciones.
                                               Tipos de software

                                              El proyecto MAX

                                                El entorno de trabajo en KDE.
                                                El escritorio de KDE.
                                                El panel.
                                                Organización de archivos.
                                                Acceso al disco duro, unidad de disquete y CD.

                                              Internet

                                               Internet,Web y Navegadores.
                                                Mozilla y Chromium.

                                              Un recorrido por las aplicaciones educativas

                                               Educativos.
                                               Ciencia y tecnologia

                                              Instalacion y configuracion

                                               Modos de trabajo en MAXs.
                                                Instalación de Linux Max. Guía paso a paso.

                              LIBRE OFFICE WRITER

                                              Exploración del ambiente de Writer

                                                Introducción
                                                Interfaz de usuario
                                                Ortografía y gramática.
                                                Diseño de la vista
                                                Zoom a escala

                                              Trabajando con documentos

                                                Nuevo documento.
                                                Abrir documento.
                                                Guardar documento.
                                                Seleccionar bloques de texto.
                                                Copiar, cortar y pegar texto.
                                                Buscar y reemplazar texto.
                                                Usar Autocorrect.

                                              Formato a documentos.

                                               Uso de estilos.
                                               Formatos a párrafos.
                                               Listas y viñetas.

                                              Formato a páginas

                                               Encabezado y pie de páginas.
                                               Numeración de páginas.
                                               Margen de páginas.
                                               Imprimir desde writer.
                                               Combinar correspondencia.

                              LIBRE OFFICE CALC

                                              Exploración del ambiente de Calc

                                                Exploración al ambiente
                                                Barras
                                                Abrir y guardar un libro.

                                                Empezar un nuevo libro de trabajo.
                                                Conceptos Básicos.
                                                Compaginar dos paginas.
                                                Iniciar y cerrar Calc.

                                              Trabajando con Celdas

                                                Introducir datos.
                                                Modificar datos.
                                                Selección de la celda.
                                                Añadir a la selección.
                                                Borrar celdas.

                                              Formato.

                                               Fuente.
                                               Alineación.
                                               Bordes.
                                               Fondo.
                                               Números.
                                               Alto de fila.
                                               Ancho de columna.
                                               Autoajustar a la selección.
                                               Insertar filas en una hoja.
                                               Insertar columnas en una hoja .
                                               Insertar celdas en una hoja.
                                               Eliminar celdas de una hoja.

                                              Funciones Y Gráficos

                                               Introducir funciones.
                                               Funciones de texto.
                                               Funciones de hojas de calculo.
                                               Crear gráficos.
                                               Modificar la posición y tamaño del grafico.

                              LIBRE OFFICE IMPRESS

                                              Exploración del ambiente de Impress

                                                Introducción
                                                Interfaz de usuario
                                                Vistas del documento.

                                              Trabajando con Presentaciones

                                                Nuevo Presentacion.
                                                Abrir Presentacion.
                                                Guardar Presentacion.

                                              Formato y estilo a presentaciones.

                                               Aplicar formato a presentaciones.
                                               Aplicar estilo a presentaciones.
                                               Crear tablas.
                                               Insertar imágenes, diagrama y otros objetos.

                                              presentaciones

                                               Configurar presentaciones.
                                               Reproducir presentaciones.


text:
import React from 'react';

import {
	Menu,
} from 'semantic-ui-react';

export class MenuStatsComponent extends React.Component {
	public render() {
		return (
			<Menu.Item>
				<Menu.Header>{'stats'}</Menu.Header>
				<Menu.Menu>
					<Menu.Item>
						<span>{'queue count'}</span>
					</Menu.Item>
				</Menu.Menu>
			</Menu.Item>
		);
	}
}


text:
package com.tc.websocket.load.tests;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.tc.websocket.tests.client.NettyTestClient;
import com.tc.websocket.tests.config.NettyClientFactory;
import com.tc.websocket.tests.config.TestConfig;

public class QueueWebSocketLoadTest{

	private static QueueWebSocketLoadTest loader;

	protected static final TestConfig cfg = TestConfig.getInstance();
	protected List<NettyTestClient> clients = new ArrayList<NettyTestClient>();
	private static Scanner scanner;

	/*
	 * make sure the xpages runtime on the target domino server has been initialized (just load an xpage app via browser)
	 * after this class loads, go back to the websocket.nsf and manually invoke the broadcast many agent
	 */
	public static void main(String[] args) throws InterruptedException{
		cfg.overrideProperty("number.of.clients", "2000");
		cfg.overrideProperty("print.on.count", "1000000");

		loader = new QueueWebSocketLoadTest();
		System.out.println("Loaded " + cfg.getNumberOfClients() + " . Run the test agents to broadcast from websocket.nsf");

		scanner = new Scanner(System.in);
		while(scanner.hasNext()){
			String cmd = scanner.next();
			if(cmd.equals("runningcount")){
				System.out.println("Running count is : " + NettyTestClient.counter.get());
			}
			else if(cmd.equals("stop")){
				NettyTestClient.printStats();
				loader.closeClients();
				System.exit(0);
			}else if(cmd.equals("resetcounter")){
				NettyTestClient.resetCounter();
			}else if("gc".equals(cmd)){
				System.gc();
			}
		}

	}

	public QueueWebSocketLoadTest(){

		try{
			NettyClientFactory factory = new NettyClientFactory();
			this.clients.addAll(factory.buildClients(TestConfig.getInstance().getMaxPayload(), false));
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void closeClients() throws InterruptedException{
		for(NettyTestClient client : this.getClients()){
			client.disconnect();
			Thread.sleep(TestConfig.getInstance().getConnectionDelay());
		}
	}

	public List<NettyTestClient> getClients(){
		return clients;
	}

}