text:
/* 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.
 */
package org.activiti.standalone.testing;

import org.activiti.engine.test.ActivitiRule;
import org.activiti.engine.test.Deployment;
import org.activiti.engine.test.mock.ActivitiMockSupport;
import org.activiti.engine.test.mock.MockServiceTask;
import org.activiti.engine.test.mock.MockServiceTasks;
import org.activiti.engine.test.mock.NoOpServiceTasks;
import org.activiti.standalone.testing.helpers.ServiceTaskTestMock;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

/**
 * @author Joram Barrez
 */
public class MockSupportWithActivitiRuleTest {

  @Rule
  public ActivitiRule activitiRule = new ActivitiRule() {

    protected void configureProcessEngine() {
      ServiceTaskTestMock.CALL_COUNT.set(0);

      activitiRule.mockSupport().mockServiceTaskWithClassDelegate("com.yourcompany.delegate", ServiceTaskTestMock.class);
      activitiRule.mockSupport().mockServiceTaskWithClassDelegate("com.yourcompany.anotherDelegate", "org.activiti.standalone.testing.helpers.ServiceTaskTestMock");
    }

  };

  @Test
  @Deployment
  public void testClassDelegateMockSupport() {
    Assert.assertEquals(0, ServiceTaskTestMock.CALL_COUNT.get());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(1, ServiceTaskTestMock.CALL_COUNT.get());
  }

  @Test
  @Deployment
  public void testClassDelegateStringMockSupport() {
    Assert.assertEquals(0, ServiceTaskTestMock.CALL_COUNT.get());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(1, ServiceTaskTestMock.CALL_COUNT.get());
  }

  @Test
  @Deployment
  @MockServiceTask(originalClassName = "com.yourcompany.delegate", mockedClassName = "org.activiti.standalone.testing.helpers.ServiceTaskTestMock")
  public void testMockedServiceTaskAnnotation() {
    Assert.assertEquals(0, ServiceTaskTestMock.CALL_COUNT.get());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(1, ServiceTaskTestMock.CALL_COUNT.get());
  }

  @Test
  @Deployment(resources = { "org/activiti/standalone/testing/MockSupportWithActivitiRuleTest.testMockedServiceTaskAnnotation.bpmn20.xml" })
  @MockServiceTask(id = "serviceTask", mockedClassName = "org.activiti.standalone.testing.helpers.ServiceTaskTestMock")
  public void testMockedServiceTaskByIdAnnotation() {
    Assert.assertEquals(0, ServiceTaskTestMock.CALL_COUNT.get());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(1, ServiceTaskTestMock.CALL_COUNT.get());
  }

  @Test
  @Deployment
  @MockServiceTasks({ @MockServiceTask(originalClassName = "com.yourcompany.delegate1", mockedClassName = "org.activiti.standalone.testing.helpers.ServiceTaskTestMock"),
      @MockServiceTask(originalClassName = "com.yourcompany.delegate2", mockedClassName = "org.activiti.standalone.testing.helpers.ServiceTaskTestMock") })
  public void testMockedServiceTasksAnnotation() {
    Assert.assertEquals(0, ServiceTaskTestMock.CALL_COUNT.get());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(2, ServiceTaskTestMock.CALL_COUNT.get());
  }

  @Test
  @Deployment
  @NoOpServiceTasks
  public void testNoOpServiceTasksAnnotation() {
    Assert.assertEquals(0, activitiRule.mockSupport().getNrOfNoOpServiceTaskExecutions());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(5, activitiRule.mockSupport().getNrOfNoOpServiceTaskExecutions());

    for (int i = 1; i <= 5; i++) {
      Assert.assertEquals("com.yourcompany.delegate" + i, activitiRule.mockSupport().getExecutedNoOpServiceTaskDelegateClassNames().get(i - 1));
    }
  }

  @Test
  @Deployment(resources = { "org/activiti/standalone/testing/MockSupportWithActivitiRuleTest.testNoOpServiceTasksAnnotation.bpmn20.xml" })
  @NoOpServiceTasks(ids = { "serviceTask1", "serviceTask3", "serviceTask5" }, classNames = { "com.yourcompany.delegate2", "com.yourcompany.delegate4" })
  public void testNoOpServiceTasksWithIdsAnnotation() {
    ActivitiMockSupport mockSupport = activitiRule.getMockSupport();
    Assert.assertEquals(0, mockSupport.getNrOfNoOpServiceTaskExecutions());
    activitiRule.getRuntimeService().startProcessInstanceByKey("mockSupportTest");
    Assert.assertEquals(5, mockSupport.getNrOfNoOpServiceTaskExecutions());

    for (int i = 1; i <= 5; i++) {
      Assert.assertEquals("com.yourcompany.delegate" + i, mockSupport.getExecutedNoOpServiceTaskDelegateClassNames().get(i - 1));
    }
  }

}


text:
import sys, time

def get_data():
    numcases = int(sys.stdin.readline())
    for case in range(1,numcases+1):
        N, M = [int(v) for v in sys.stdin.readline().strip().split()]
        data = []
        for line_number in range(N):
            line = sys.stdin.readline().strip().split()
            data.append([int(i) for i in line])
        yield (case, data)

def below_max_height(lawn, max_height = 100):
  for line in lawn:
    if any(field < 1 or field > max_height for field in line):
      return "NO"
  return "YES"

def solve(lawn):
  # Take highest setting as pattern
  heights = [sum(int(i) for i in line) for line in lawn]
  max_line = heights.index(max(heights))
  pattern = lawn[max_line]

  # Check all other lines against this pattern
  other_lines = lawn[:max_line] + lawn[max_line+1:]
  for line in other_lines:
    if line != pattern:
      setting = max(line)
      trimmed = [min(setting, p) for p in pattern]
      if line != trimmed:
        return "NO"
  return below_max_height(lawn)

def main():
    for case, data in get_data():
      print "Case #" + repr(case) + ":", solve(data)
      """
      for line in data:
        print " ".join([str(i) for i in line])
      print
      """

if __name__ == "__main__":
  main()

redpajama_set_name: RedPajamaGithub


text:
/** Class: DragAndDropStrategy
 *
 * Inherits from:
 *     - <MouseStrategy>
 */
define(function(require, exports, module) {

	var MouseStrategy = require('./MouseStrategy');
	var DefaultStrategy = require('./DefaultStrategy');

	/** Constructor: DragAndDropStrategy()
	 * Creates a new instance of <DragAndDropStrategy>
	 */
	var DragAndDropStrategy = function DragAndDropStrategy(canvasWrapper) {
		var _self = this;

		/** PrivateMember: _data
		 * Data to transfer from the initiatior the a potential drop target.
		 */
		var _data;

		/** PrivateMember: _initiator
		 * The <Widget> which initiated the drag and drop process.
		 */
		var _initiator;

		var _mouseOverWidgets = [];

		var _dragging = false;

		MouseStrategy.call(this, canvasWrapper);

		/** Function: dragStarted(absolutePosition)
		 * Called by the <CanvasWrapper>, this method looks for the deepest
		 * <Widget> on the given absolute position and sends a native_dragStart
		 * event.
		 * The <Widget> itself can use the events *acceptCallback* to start
		 * a drag and drop sequence.
		 *
		 * Parameters:
		 *     (Object) absolutePosition - {left: ?, top: ?}
		 */
		_self.dragStarted = function dragStarted(absolutePosition) {
			var acceptCallback = handleAcceptDrag;
			var cancelCallback = stopDrag;
			var initiatorCandidate = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);
			initiatorCandidate.dispatchEvent('mouse:dragstart', {absolutePosition: absolutePosition, acceptCallback: acceptCallback, cancelCallback: cancelCallback });
		};

		/** Function: mouseMoved(absolutePosition)
		 *
		 * Parameters:
		 *     (Object) absolutePosition - {left: ?, top: ?}
		 */
		_self.mouseMoved = function mouseMoved(absolutePosition) {
			if(_dragging) {
				var canvasWrapper = _self.getCanvasWrapper();
				var deepestWidget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

				if(deepestWidget) {
					deepestWidget.dispatchEvent('mouse:drag', {absolutePosition:absolutePosition});

					if(_mouseOverWidgets.indexOf(deepestWidget) === -1) {
						_mouseOverWidgets.push(deepestWidget);
						deepestWidget.dispatchEvent('mouse:dragenter', {absolutePosition: absolutePosition});
					}
				}

				canvasWrapper.searchWidgetsOnPosition(absolutePosition,undefined
					,function notFound(widget) {
						var index = _mouseOverWidgets.indexOf(widget);
						if(widget !== deepestWidget && index > -1) {
							_mouseOverWidgets.splice(index,1);
							widget.dispatchEvent('mouse:dragexit', {absolutePosition: absolutePosition});
						}
					}
				);
			}

		};

		/** Function: mouseButtonReleased(button, absolutePosition)
		 * As soon as the mouse button was released during a drag and drop process,
		 * the process itself gets stopped.
		 * The initiating and possbile targeted <Widget> get informed with
		 * a native_dragStop event.
		 *
		 * Parameters:
		 *     (int) button - Number of the pressed button
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		_self.mouseButtonReleased = function mouseButtonReleased(button, absolutePosition) {
			var canvasWrapper = _self.getCanvasWrapper();
			var dropTarget = canvasWrapper.searchDeepestWidgetOnPosition(absolutePosition);

			if(_initiator) _initiator.dispatchEvent('mouse:dragstop',{absolutePosition:absolutePosition});
			if(dropTarget) dropTarget.dispatchEvent('mouse:drop',{absolutePosition:absolutePosition});
			stopDrag(absolutePosition);
		};

		_self.mouseButtonPressed = function mouseButtonPressed(button, absolutePosition) { };
		_self.mouseButtonClicked = function mouseButtonClicked(button, absolutePosition) { };

		/** PrivateFunction: handleAcceptDrag(widget, date)
		 * Used as callback when emitting a native_dragStart event to a potential
		 * drag and drop initiator.
		 *
		 * Parameters:
		 *     (Widget) widget - <Widget> which accepted the dnd
		 *     (Object) data
		 */
		function handleAcceptDrag(widget, data) {
			_initiator = widget;
			_data = data;
			_dragging = true;
		}

		/** PrivateFunction: stopDrag(absolutePosition)
		 * Stops the drag and drop process on the given absolute position.
		 *
		 * Parameters:
		 *     (Object) absolutePosition - { left: ?, top: ? }
		 */
		function stopDrag(absolutePosition) {
			_dragging = false;

			/** Event: stopDrag
			 * Informs (most commonly) the <CanvasWrapper> that a drag and
			 * drop process has finished.
			 *
			 * Parameters:
			 *     (Object) absolutePosition - { left: ?, top: ? } describing
			 *                                 the location where DnD has
			 *                                 stopped.
			 */
			_self.emit('draganddropstrategy:stopdrag', absolutePosition);
		}

	};

	DragAndDropStrategy.prototype = Object.create(MouseStrategy.prototype);
	DragAndDropStrategy.prototype.constructor = DragAndDropStrategy;

	return DragAndDropStrategy;
});


text:
oils-plugin-auth
================

Authentication plugin for oils

Installation:

```npm install oils-plugin-auth```


text:
import numpy as np
from windowModel import WindowModel
from utils import softmaxLossAndGrads, relu, drelu

class PositionDependentVectorModel(WindowModel):
    def __init__(self, keywords, winSize=100, stepsize=0.05, reg=0.01,
                 wdim=32):
        super(PositionDependentVectorModel, self).__init__(keywords, winSize,
                                                           stepsize, reg)
        # dimension of each wordvector
        self.wdim = wdim
        # initialize random parameters for weights
        totalToks = len(self.keywordList) + self.winSize
        self.add_param('W', (self.wdim*self.winSize, totalToks+1))
        self.add_param('wvec', (totalToks, self.wdim))

    def lossAndGrads(self, batchAndTargets, computeGrads=True):
        nb = len(batchAndTargets)
        ctxtoks = [ctxtok for ctxtok,tgt in batchAndTargets]
        tgts = [tgt for ctxtok,tgt in batchAndTargets]
        context = self.wvec[ctxtoks,:].reshape((nb,-1))
        scores = np.dot(context, self.W)
        preds = np.argmax(scores, axis=1)

        loss, probs, dscores = softmaxLossAndGrads(scores, tgts)
        if not computeGrads:
            return preds, probs, loss

        dW = np.dot(context.T, dscores)
        dcontext = np.dot(dscores, self.W.T).reshape((nb,-1,self.wdim))
        dwvec = np.zeros_like(self.wvec)
        for b,ctxtok in enumerate(ctxtoks):
            for w,tok in enumerate(ctxtok):
                dwvec[tok] += dcontext[b,w]
        grads = {}
        grads['W'] = dW + self.reg * self.W
        grads['wvec'] = dwvec + self.reg * self.wvec * (dwvec != 0)

        return preds, probs, loss, grads

class NonLinearVectorModel(WindowModel):
    def __init__(self, keywords, winSize=100, stepsize=0.05, reg=0.01,
                 wdim=32, zdim=512):
        super(NonLinearVectorModel, self).__init__(keywords, winSize,
                                                   stepsize, reg)
        # dimension of each wordvector
        self.wdim = wdim
        self.zdim = zdim
        # initialize random parameters for weights
        totalToks = len(self.keywordList) + self.winSize
        self.add_param('Wz', (self.wdim*self.winSize, self.zdim))
        self.add_param('Wa', (self.zdim, totalToks+1))
        self.add_param('wvec', (totalToks, self.wdim))

    def lossAndGrads(self, batchAndTargets, computeGrads=True):
        nb = len(batchAndTargets)
        ctxtoks = [ctxtok for ctxtok,tgt in batchAndTargets]
        tgts = [tgt for ctxtok,tgt in batchAndTargets]
        context = self.wvec[ctxtoks,:].reshape((nb,-1))
        z = np.dot(context, self.Wz)
        a = relu(z)
        scores = np.dot(a, self.Wa)
        preds = np.argmax(scores, axis=1)

        loss, probs, dscores = softmaxLossAndGrads(scores, tgts)
        if not computeGrads:
            return preds, probs, loss

        dWa = np.dot(a.T, dscores)
        da = np.dot(dscores, self.Wa.T)

        dz = drelu(da, a)

        dWz = np.dot(context.T, dz)
        dcontext = np.dot(dz, self.Wz.T).reshape((nb,-1,self.wdim))
        dwvec = np.zeros_like(self.wvec)
        for b,ctxtok in enumerate(ctxtoks):
            for w,tok in enumerate(ctxtok):
                dwvec[tok] += dcontext[b,w]
        grads = {}
        grads['Wa'] = dWa + self.reg * self.Wa
        grads['Wz'] = dWz + self.reg * self.Wz
        grads['wvec'] = dwvec + self.reg * self.wvec * (dwvec != 0)

        return preds, probs, loss, grads

class ConstantAttentionVectorModel(WindowModel):
    def __init__(self, keywords, winSize=100, stepsize=0.05, reg=0.01,
                 wdim=32):
        super(ConstantAttentionVectorModel, self).__init__(keywords, winSize,
                                                           stepsize, reg)
        # dimension of each wordvector
        self.wdim = wdim
        # initialize random parameters for weights
        totalToks = len(self.keywordList) + self.winSize
        self.add_param('attn', (self.winSize,), 1.)
        self.add_param('W', (self.wdim, totalToks+1))
        self.add_param('wvec', (totalToks, self.wdim))

    def lossAndGrads(self, batchAndTargets, computeGrads=True):
        nb = len(batchAndTargets)
        ctxtoks = [ctxtok for ctxtok,tgt in batchAndTargets]
        tgts = [tgt for ctxtok,tgt in batchAndTargets]

        context = np.transpose(self.wvec[ctxtoks,:], (0,2,1))
        attnvec = context.dot(self.attn)
        scores = np.dot(attnvec, self.W)
        preds = np.argmax(scores, axis=1)

        loss, probs, dscores = softmaxLossAndGrads(scores, tgts)
        if not computeGrads:
            return preds, probs, loss

        dW = np.dot(attnvec.T, dscores)
        dattnvec = np.dot(dscores, self.W.T)

        dattn = np.tensordot(context, dattnvec, axes=([0,1],[0,1]))
        dcontext = dattnvec[...,None]*self.attn

        dwvec = np.zeros_like(self.wvec)
        for b,ctxtok in enumerate(ctxtoks):
            for w,tok in enumerate(ctxtok):
                dwvec[tok] += dcontext[b,:,w]
        grads = {}
        grads['W'] = dW + self.reg * self.W
        grads['attn'] = dattn + self.reg * self.attn
        grads['wvec'] = dwvec + self.reg * self.wvec * (dwvec != 0)

        return preds, probs, loss, grads


text:
var isFunction = require("is_function"),
    evaluate;

module.exports = evaluate_list;

evaluate = require("./index");

function evaluate_list(input, context) {
    var first = input.first(),
        list;

    if (input.size() > 0) {
        if (context.has_special_form(first)) {
            return context.get_special_form(first)(input, context);
        } else if (context.has_macro(first)) {
            return context.get_macro(first)(input);
        }
    }

    list = input.map(function each(value) {
        return evaluate(value, context);
    });

    first = list.first();

    if (isFunction(first)) {
        return first(list.shift());
    } else {
        return list;
    }
}


text:
package org.qifu.vo;

import org.qifu.base.model.BaseValueObj;

public class SysBeanHelpExprVO extends BaseValueObj implements java.io.Serializable {
	private static final long serialVersionUID = 7730143312476877752L;
	private String oid;
	private String helpOid;
	private String exprId;
	private String exprSeq;
	private String runType;

	public SysBeanHelpExprVO() {

	}

	public SysBeanHelpExprVO(String oid, String helpOid,
			String exprId, String exprSeq, String runType) {
		this.oid = oid;
		this.helpOid = helpOid;
		this.exprId = exprId;
		this.exprSeq = exprSeq;
		this.runType = runType;
	}

	@Override
	public String getOid() {
		return this.oid;
	}

	public void setOid(String oid) {
		this.oid = oid;
	}

	public String getHelpOid() {
		return helpOid;
	}

	public void setHelpOid(String helpOid) {
		this.helpOid = helpOid;
	}

	public String getExprId() {
		return exprId;
	}

	public void setExprId(String exprId) {
		this.exprId = exprId;
	}

	public String getExprSeq() {
		return exprSeq;
	}

	public void setExprSeq(String exprSeq) {
		this.exprSeq = exprSeq;
	}

	public String getRunType() {
		return runType;
	}

	public void setRunType(String runType) {
		this.runType = runType;
	}

}


text:
package gov.va.vinci.leo.cr;

import gov.va.vinci.leo.SampleService;
import gov.va.vinci.leo.types.CSI;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.resource.ResourceInitializationException;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;

import static org.junit.Assert.*;

public class FileCollectionReaderTest {

    /**
     * Array of File objects being processed.
     */
    protected ArrayList<File> mFileCollection = null;
    private static String RESULTS = "this is a test";
    String rootDirectory = "";

    @Before
    public void setTestString() throws IOException {
        String path = new File(".").getCanonicalPath();
        if (!path.endsWith("client")) {
            rootDirectory = "client/";
        }
    }

    @Test
    public void testEmptyConstructor() {
        FileCollectionReader fsr = new FileCollectionReader();
        assertNotNull(fsr);
    }

    @Test
    public void testConstructor() {
        FileCollectionReader fsr = new FileCollectionReader(new File(rootDirectory + "src/test/resources/inputDirectory"), true);
        assertNotNull(fsr);
    }

    @Test
    public void testRecurseFlag() throws Exception {
        FileCollectionReader fsr =
                (FileCollectionReader) new FileCollectionReader(new File(rootDirectory + "src/test/resources/inputDirectory"), false)
                        .produceCollectionReader();
        assertNotNull(fsr);
        assertTrue(fsr.getCollectionSize() == 1);
        FileCollectionReader fsr2 =
                (FileCollectionReader) new FileCollectionReader(new File(rootDirectory + "src/test/resources/inputDirectory"), true)
                        .produceCollectionReader();
        assertNotNull(fsr);
        assertTrue(fsr2.getCollectionSize() == 2);
    }

    @Test
    public void testInitialize() throws IllegalAccessException, ResourceInitializationException {
        FileCollectionReader fileCollectionReader =
                (FileCollectionReader) new FileCollectionReader(new File(rootDirectory + "src/test/resources/inputDirectory"), true)
                        .produceCollectionReader();
        assertEquals(1, fileCollectionReader.getCollectionSize(), 2);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEmptyFilePathConstructor() throws Exception {
        FileCollectionReader fsr = new FileCollectionReader(null, true);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testBadConstructor() throws Exception {
        FileCollectionReader fsr = new FileCollectionReader(new File(rootDirectory + "src/test/resources/badDirectory"), true);
    }

    @Test
    public void testGetNext() throws Exception {
        FileCollectionReader fsr =
                (FileCollectionReader) new FileCollectionReader(new File(rootDirectory + "src/test/resources/inputDirectory"), true)
                        .setEncoding(Charset.defaultCharset().displayName())
                        .setRecurseFlag(false)
                        .produceCollectionReader();
        assertNotNull(fsr);
        assertEquals(Charset.defaultCharset().displayName(), fsr.getEncoding());
        assertEquals(new File(rootDirectory + "src/test/resources/inputDirectory").getAbsolutePath(), fsr.getInputDirectory().getAbsolutePath());
        FilenameFilter filenameFilter = fsr.getFilenameFilter();
        assertTrue(filenameFilter instanceof SuffixFileFilter);
        assertFalse(fsr.mRecurse);

        AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(SampleService
                .simpleServiceDefinition()
                .getAnalysisEngineDescription());
        CAS mockCas = ae.newCAS();
        assertTrue(fsr.hasNext());
        fsr.getNext(mockCas);
        assertEquals(1, fsr.getCurrentIndex());
        FSIterator<AnnotationFS> csiIterator = mockCas.getAnnotationIndex(mockCas.getTypeSystem().getType(CSI.class.getCanonicalName())).iterator();
        assertTrue(csiIterator.hasNext());
        CSI csi = (CSI) csiIterator.next();
        assertTrue("text1.txt".equals(csi.getID()));
        assertTrue(csi.getLocator().endsWith("client/src/test/resources/inputDirectory/text1.txt"));
        assertNull(csi.getPropertiesKeys());
        assertNull(csi.getRowData());
        assertTrue(RESULTS.equals(mockCas.getDocumentText()));
    }

}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Proto
{
    public partial class PID
    {
        private Process _p;

        public PID(string address, string id)
        {
            Address = address;
            Id = id;
        }

        internal Process Ref
        {
            get
            {
                var p = _p;
                if (p != null)
                {
                    if (p is LocalProcess lp && lp.IsDead)
                    {
                        _p = null;
                    }
                    return _p;
                }

                var reff = ProcessRegistry.Instance.Get(this);
                if (!(reff is DeadLetterProcess))
                {
                    _p = reff;
                }

                return _p;
            }
        }

        public void Tell(object message)
        {
            var reff = Ref ?? ProcessRegistry.Instance.Get(this);
            reff.SendUserMessage(this, message, null);
        }

        public void SendSystemMessage(object sys)
        {
            var reff = Ref ?? ProcessRegistry.Instance.Get(this);
            reff.SendSystemMessage(this, sys);
        }

        public void Request(object message, PID sender)
        {
            var reff = Ref ?? ProcessRegistry.Instance.Get(this);
            reff.SendUserMessage(this, message, sender);
        }

        public Task<T> RequestAsync<T>(object message, TimeSpan timeout)
            => RequestAsync(message, new FutureProcess<T>(timeout));

        public Task<T> RequestAsync<T>(object message, CancellationToken cancellationToken)
            => RequestAsync(message, new FutureProcess<T>(cancellationToken));

        public Task<T> RequestAsync<T>(object message)
            => RequestAsync(message, new FutureProcess<T>());

        private Task<T> RequestAsync<T>(object message, FutureProcess<T> future)
        {
            Request(message, future.PID);
            return future.Task;
        }

        public void Stop()
        {
            var reff = ProcessRegistry.Instance.Get(this);
            reff.Stop(this);
        }

        public string ToShortString()
        {
            return Address + "/" + Id;
        }
    }
}


text:
照片选择工具

这是一个搬运工项目,项目作者是 https://github.com/donglua/PhotoPicker 很赞的一个工具, 感谢原作者,将会在原作者的基础上做一些美化和功能的增加

1. 支持gradle中引用
2. 美化
3. 优化

使用方法:

1. gradle 引用

compile 'com.zhaisoft.lib.photopicker:android-photo-picker:0.0.1'

2. 使用方法,请参考此activity

调用

 PhotoPickerIntent intent = new PhotoPickerIntent(Activity_UploadImage.this);
                intent.setPhotoCount(9);
                startActivityForResult(intent, REQUEST_CODE);

回调
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        List<String> photos = null;
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {

                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }


text:
Style files are the standalone files that ArcGIS uses to store reusable symbology and drawing information.  Style files store this information independently of the geographic features to be drawn, so a common set of symbol, label placement, drawing rule, color definition, and other bits of cartographic rendering information can be consistently applied to multiple datasets, quickly and easily.

Style files with the .style extension are used in ArcGIS Desktop (ArcMap/ArcCatalog/ArcGlobe) and are in fact Microsoft Access databases.  In ArcGIS Runtime these style files have a .dat extension and are SQLite databases.  ArcGIS Pro uses the same SQLite database format but uses a .stylx filename extension instead.

The application in this repository is designed to automate the use of data provided by the [Joint Military Symbology XML (JMSML)](https://github.com/Esri/joint-military-symbology-xml) repository with the tools and techniques available and documented in the style file utility section of the [Military Features Data](https://github.com/Esri/military-features-data) repository.

The stylx file creation procedures outlined in the Military Features Data repository are lengthy, complicated, somewhat cumbersome, and could lead to user frustration and error, particularly if the need arises to perform those operations repeatedly.

In the interest of streamlining and automating the process of going from raw MIL-STD-2525D JMSML data to finished ArcGIS Pro ready military symbology stylx files, we've built this repository to simplify the work required.

Strict dependence on the JMSML and Military Features Data repositories exist here, so if anything significant changes, in terms of the data, procedures, or execution requirements documented in those repositories, amendments to the contents of this repository may be required.

![Image of Stylx Manager]( screen.png )

## Features

* Converts DISA's svg files (as managed by JMSML) to an equivalent set of EMF files, according to the procedures and using the tools documented [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/image-conversion-utilities).

* Creates military symbology style files from the aforementioned EMF files and the CSV image name category tag information exported from JMSML, according to the procedures and using the tools documented [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/image-conversion-utilities).

* Launches ArcGIS Pro, loading a specified project file, so the user can import one or more of the aforementioned style files, which converts their contents to stylx.

* Merges the all-icon stylx file, created in the aforementioned step, with the manually managed drawing-and-label-rule stylx file, according to the procedures and using the tools documented [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/merge-stylx-utilities).

## Sections

* [Requirements](#requirements)
* [Instructions](#instructions)
* [Other Documentation](#documentation)
* [Resources](#resources)
* [Issues](#issues)
* [Contributing](#contributing)
* [Licensing](#licensing)

## Requirements

* A text editor of your choice for viewing and/or editing the configuration file (if desired).
* To build the .NET Solution source you will need:
    * Visual Studio 2012 or later.
* This application makes use of the tools in the following GitHub repositories (these repositories need to be downloaded or cloned to your computer and the requirements outlined [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities) also need to be met):
	* [joint-military-symbology-xml](https://github.com/Esri/joint-military-symbology-xml)
	* [military-features-data](https://github.com/Esri/military-features-data)
* Image file conversion requires a copy of Inkscape, installed to a location whose fully qualified path is devoid of spaces.  Install it from [here](https://inkscape.org/en/).
* Creating the style files requires a built version of the CSV-to-Style application source located [here](https://github.com/csmoore/csv2ArcGISStyle).  A fully built deployment of this can also be found [here](https://github.com/Esri/military-features-data/blob/master/data/mil2525d/utilities/style-utilities/style-file-utilities/csv2ArcGISStyleDeployment.zip).
* Creating the stylx files requires a copy of ArcGIS Pro 1.1 or greater.
* Merging stylx files together requires a command line version of SQLite3.  A version of this can be downloaded from [here](http://www.sqlite.org/).

## Instructions

### General Help
[New to Github? Get started here.](http://htmlpreview.github.com/?https://github.com/Esri/esri.github.com/blob/master/help/esri-getting-to-know-github.html)

### Getting Started with the solution
* Open and build the Visual Studio Solution at manage-military-styles.sln
* Run the solution to see a form appear, which you can use to execute the aforementioned features.
* The config.xml file in the solution's executable folder will be used to initialize the paths to all of the above required data and tools.  Specifically, when this application is run and the form first appears, enter or browse to the following locations (default locations from the config file will initialize the appropriate text boxes):

	* **Manager Home** - The location of this local repository (a folder).
	* **Military Features Data** - The location of your local military-features-data repository (a folder).
	* **JMSML** - The location of your local joint-military-symbology-xml repository (a folder).
	* **Graphics** - The location, devoid of spaces, of the folder on your machine where graphics will be copied and converted (a folder).
	* **Inkscape** - The path, devoid of spaces, where your copy of Inkscape.com is installed (a file).
	* **CSV to Style** - The location of your local copy of the CSV to Style generation application (a folder).
	* **ArcGIS Pro** - The path to your installed instance of the ArcGIS Pro executable (a file).
	* **Symbol Project** - The path to the ArcGIS Pro project (aprx) file you wish to open, when launching ArcGIS Pro.
	* **Stylx** - The path to the stylx file you created when you used ArcGIS Pro to import the style file for all icons/symbols (a file).
	* **SQLite** - The path to your installed instance of SQLite (a file).

General execution of the various steps of the stylx generation process is from left to right, on the main form, with each preceding step required to complete successfully before moving on to the next step.

**1. Convert Graphics** - This automagically follows the procedures outlined [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/image-conversion-utilities), first copying to your specified location all of the current JMSML SVG files, and then using Inkscape to convert those files to EMF.  When completed, Notepad is used to open up a log of the conversion process, so you can confirm its success.

**2. Create Style Files** - This automagically follows the procedures outlined [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/style-file-utilities), to modify a copy of the image name category tag CSV files in the JMSML samples folder.  It then repeatedly runs the standalone CSV-to-Style creation process, that uses the contents of the CSVs and the associated EMFs created in the previous step to build new ArcGIS Desktop (ArcMap) style files.  When completed, Notepad is used to open up a log of the creation process, so you can confirm its success.

**3. Import into Pro** - This quite simply starts up your instance of ArcGIS Pro, with the project file you specified.  Once ArcGIS Pro has started, you will need to use the desktop tools to import the **Military 2525Delta All.style** file into your project, which will convert it to an ArcGIS Pro stylx file.

**4. Merge Stylx** - This automagically follows the procedures outlined [here](https://github.com/Esri/military-features-data/tree/master/data/mil2525d/utilities/style-utilities/merge-stylx-utilities) to modify a copy of the military features data SQLite script file, and then it uses that to merge the stylx file created in step three above (which contains points only) with the line, areas, and label information contained in the manually managed file [here](https://github.com/Esri/military-features-data/blob/master/data/mil2525d/core_data/stylxfiles/mil2525d-lines-areas-labels-base-template.stylx).  When completed, Notepad is used to open up a log of the merge process, so you can confirm its success.

**Final Results** - When all four steps are successfully completed, you should find several finished style and one new stylx file in the StyleOutputData folder of this repository.

## Documentation

- To learn more about the Joint Military Symbology XML GitHub repository, go [here](https://github.com/Esri/joint-military-symbology-xml).
- To learn more about the Military Features Data GitHub repository, go [here](https://github.com/Esri/military-features-data).

## Resources

* Learn more about Esri's [ArcGIS for Defense maps and apps](http://resources.arcgis.com/en/communities/defense-and-intelligence/).

## Issues

Find a bug or want to request a new feature?  Please let us know by submitting an issue.

## Contributing

Esri welcomes contributions from anyone and everyone. Please see our [guidelines for contributing](https://github.com/esri/contributing).

## Licensing

Copyright 2015 Esri

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.

A copy of the license is available in the repository's
[license.txt](license.txt) file.

[](Esri Tags: ArcGIS Defense and Intelligence Joint Military Symbology XML ArcGISSolutions)
[](Esri Language: XML)


text:
package com.android.manifmerger;

import com.android.common.SdkConstants;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.common.ide.common.blame.SourceFile;
import com.android.common.ide.common.blame.SourcePosition;
import com.android.common.ide.common.res2.MergingException;
import com.android.common.utils.ILogger;
import com.android.common.utils.SdkUtils;
import com.android.common.utils.XmlUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Xml {@link Element} which is mergeable.
 *
 * A mergeable element can contains 3 types of children :
 *

 *
a child element, which itself may or may not be mergeable.

 *
xml attributes which are related to the element.

 *
tools oriented attributes to trigger specific behaviors from the merging tool

 *

 *
 * The two main responsibilities of this class is to be capable of comparing itself against
 * another instance of the same type as well as providing XML element merging capabilities.
 */
public class XmlElement extends OrphanXmlElement {

    @NonNull
    private final XmlDocument mDocument;

    @Nullable
    private final NodeOperationType mNodeOperationType;

    // list of non tools related attributes.
    @NonNull
    private final ImmutableList<XmlAttribute> mAttributes;

    // map of all tools related attributes keyed by target attribute name
    @NonNull
    private final Map<NodeName, AttributeOperationType> mAttributesOperationTypes;

    // list of mergeable children elements.
    @NonNull
    private final ImmutableList<XmlElement> mMergeableChildren;

    // optional selector declared on this xml element.
    @Nullable
    private final Selector mSelector;

    // optional list of libraries that we should ignore the minSdk version
    @NonNull
    private final List<Selector> mOverrideUsesSdkLibrarySelectors;

    public XmlElement(@NonNull Element xml, @NonNull XmlDocument document) {
        super(xml);

        mDocument = Preconditions.checkNotNull(document);
        Selector selector = null;
        List<Selector> overrideUsesSdkLibrarySelectors = ImmutableList.of();

        ImmutableMap.Builder<NodeName, AttributeOperationType> attributeOperationTypeBuilder =
                ImmutableMap.builder();
        ImmutableList.Builder<XmlAttribute> attributesListBuilder = ImmutableList.builder();
        NamedNodeMap namedNodeMap = getXml().getAttributes();
        NodeOperationType lastNodeOperationType = null;
        for (int i = 0; i < namedNodeMap.getLength(); i++) {
            Node attribute = namedNodeMap.item(i);
            if (SdkConstants.TOOLS_URI.equals(attribute.getNamespaceURI())) {
                String instruction = attribute.getLocalName();
                if (instruction.equals(NodeOperationType.NODE_LOCAL_NAME)) {
                    // should we flag an error when there are more than one operation type on a node ?
                    lastNodeOperationType = NodeOperationType.valueOf(
                            SdkUtils.camelCaseToConstantName(
                                    attribute.getNodeValue()));
                } else if (instruction.equals(Selector.SELECTOR_LOCAL_NAME)) {
                    selector = new Selector(attribute.getNodeValue());
                } else if (instruction.equals(NodeOperationType.OVERRIDE_USES_SDK)) {
                    String nodeValue = attribute.getNodeValue();
                    ImmutableList.Builder<Selector> builder = ImmutableList.builder();
                    for (String selectorValue : Splitter.on(',').split(nodeValue)) {
                        builder.add(new Selector(selectorValue.trim()));
                    }
                    overrideUsesSdkLibrarySelectors = builder.build();
                } else {
                    AttributeOperationType attributeOperationType;
                    try {
                        attributeOperationType =
                                AttributeOperationType.valueOf(
                                        SdkUtils.xmlNameToConstantName(instruction));
                    } catch (IllegalArgumentException e) {
                        try {
                            // is this another tool's operation type that we do not care about.
                            OtherOperationType.valueOf(instruction);
                            break;
                        } catch (IllegalArgumentException e1) {

                            String errorMessage =
                                    String.format("Invalid instruction '%1$s', "
                                                    + "valid instructions are : %2$s",
                                            instruction,
                                            Joiner.on(',').join(AttributeOperationType.values())
                                    );
                            throw new RuntimeException(MergingException.wrapException(e)
                                    .withMessage(errorMessage)
                                    .withFile(mDocument.getSourceFile())
                                    .withPosition(XmlDocument.getNodePosition(xml)).build());
                        }
                    }
                    for (String attributeName : Splitter.on(',').trimResults()
                            .split(attribute.getNodeValue())) {
                        if (attributeName.indexOf(XmlUtils.NS_SEPARATOR) == -1) {
                            String toolsPrefix = XmlUtils
                                    .lookupNamespacePrefix(getXml(), SdkConstants.TOOLS_URI,
                                            SdkConstants.ANDROID_NS_NAME, false);
                            // automatically provide the prefix.
                            attributeName = toolsPrefix + XmlUtils.NS_SEPARATOR + attributeName;
                        }
                        NodeName nodeName = XmlNode.fromXmlName(attributeName);
                        attributeOperationTypeBuilder.put(nodeName, attributeOperationType);
                    }
                }
            }
        }
        mAttributesOperationTypes = attributeOperationTypeBuilder.build();
        for (int i = 0; i < namedNodeMap.getLength(); i++) {
            Node attribute = namedNodeMap.item(i);
            XmlAttribute xmlAttribute = new XmlAttribute(
                    this, (Attr) attribute, getType().getAttributeModel(XmlNode.fromXmlName(
                            ((Attr) attribute).getName())));
            attributesListBuilder.add(xmlAttribute);
        }
        mNodeOperationType = lastNodeOperationType;
        mAttributes = attributesListBuilder.build();
        mMergeableChildren = initMergeableChildren();
        mSelector = selector;
        mOverrideUsesSdkLibrarySelectors = overrideUsesSdkLibrarySelectors;
    }

    /**
     * Returns the owning {@link com.android.manifmerger.XmlDocument}
     */
    @NonNull
    public XmlDocument getDocument() {
        return mDocument;
    }

    /**
     * Returns the list of attributes for this xml element.
     */
    public List<XmlAttribute> getAttributes() {
        return mAttributes;
    }

    /**
     * Returns the {@link com.android.manifmerger.XmlAttribute} for an attribute present on this
     * xml element, or {@link com.google.common.base.Optional#absent} if not present.
     * @param attributeName the attribute name.
     */
    public Optional<XmlAttribute> getAttribute(NodeName attributeName) {
        for (XmlAttribute xmlAttribute : mAttributes) {
            if (xmlAttribute.getName().equals(attributeName)) {
                return Optional.of(xmlAttribute);
            }
        }
        return Optional.absent();
    }

    /**
     * Get the node operation type as optionally specified by the user. If the user did not
     * explicitly specify how conflicting elements should be handled, a
     * {@link com.android.manifmerger.NodeOperationType#MERGE} will be returned.
     */
    @NonNull
    public NodeOperationType getOperationType() {
        return mNodeOperationType != null
                ? mNodeOperationType
                : NodeOperationType.MERGE;
    }

    /**
     * Get the attribute operation type as optionally specified by the user. If the user did not
     * explicitly specify how conflicting attributes should be handled, a
     * {@link AttributeOperationType#STRICT} will be returned.
     */
    @NonNull
    public AttributeOperationType getAttributeOperationType(NodeName attributeName) {
        return mAttributesOperationTypes.containsKey(attributeName)
                ? mAttributesOperationTypes.get(attributeName)
                : AttributeOperationType.STRICT;
    }

    @NonNull
    public Collection<Map.Entry<NodeName, AttributeOperationType>> getAttributeOperations() {
        return mAttributesOperationTypes.entrySet();
    }

    @NonNull
    public List<Selector> getOverrideUsesSdkLibrarySelectors() {
        return mOverrideUsesSdkLibrarySelectors;
    }

    @NonNull
    @Override
    public SourcePosition getPosition() {
        return XmlDocument.getNodePosition(this);
    }

    @NonNull
    @Override
    public SourceFile getSourceFile() {
        return mDocument.getSourceFile();
    }

    /**
     * Merge this xml element with a lower priority node.
     *
     * For now, attributes will be merged. If present on both xml elements, a warning will be
     * issued and the attribute merge will be rejected.
     *
     * @param lowerPriorityNode lower priority Xml element to merge with.
     * @param mergingReport the merging report to log errors and actions.
     */
    public void mergeWithLowerPriorityNode(
            @NonNull XmlElement lowerPriorityNode,
            @NonNull MergingReport.Builder mergingReport) {

        if (mSelector != null && !mSelector.isResolvable(getDocument().getSelectors())) {
            mergingReport.addMessage(getSourceFilePosition(),
                    MergingReport.Record.Severity.ERROR,
                    String.format("'tools:selector=\"%1$s\"' is not a valid library identifier, "
                            + "valid identifiers are : %2$s",
                            mSelector.toString(),
                            Joiner.on(',').join(mDocument.getSelectors().getKeys())));
            return;

        }
        mergingReport.getLogger().info("Merging " + getId()
                + " with lower " + lowerPriorityNode.printPosition());

        // workaround for 0.12 release and overlay treatment of manifest entries. This will
        // need to be expressed in the model instead.
        MergeType mergeType = getType().getMergeType();
        // if element we are merging in is not a library (an overlay or an application),  we should
        // always merge the <manifest> attributes otherwise, we do not merge the libraries
        // <manifest> attributes.
        if (isA(ManifestModel.NodeTypes.MANIFEST)
                && lowerPriorityNode.getDocument().getFileType() != XmlDocument.Type.LIBRARY) {
            mergeType = MergeType.MERGE;
        }

        if (mergeType != MergeType.MERGE_CHILDREN_ONLY) {
            // make a copy of all the attributes metadata, it will eliminate elements from this
            // list as it finds them explicitly defined in the lower priority node.
            // At the end of the explicit attributes processing, the remaining elements of this
            // list will need to be checked for default value that may clash with a locally
            // defined attribute.
            List<AttributeModel> attributeModels =
                    new ArrayList<AttributeModel>(lowerPriorityNode.getType().getAttributeModels());

            // merge explicit attributes from lower priority node.
            for (XmlAttribute lowerPriorityAttribute : lowerPriorityNode.getAttributes()) {
                lowerPriorityAttribute.mergeInHigherPriorityElement(this, mergingReport);
                if (lowerPriorityAttribute.getModel() != null) {
                    attributeModels.remove(lowerPriorityAttribute.getModel());
                }
            }
            // merge implicit default values from lower priority node when we have an explicit
            // attribute declared on this node.
            for (AttributeModel attributeModel : attributeModels) {
                if (attributeModel.getDefaultValue() != null) {
                    Optional<XmlAttribute> myAttribute = getAttribute(attributeModel.getName());
                    if (myAttribute.isPresent()) {
                        myAttribute.get().mergeWithLowerPriorityDefaultValue(
                                mergingReport, lowerPriorityNode);
                    }
                }
            }
        }
        // are we supposed to merge children ?
        if (mNodeOperationType != NodeOperationType.MERGE_ONLY_ATTRIBUTES) {
            mergeChildren(lowerPriorityNode, mergingReport);
        } else {
            // record rejection of the lower priority node's children .
            for (XmlElement lowerPriorityChild : lowerPriorityNode.getMergeableElements()) {
                mergingReport.getActionRecorder().recordNodeAction(this,
                        Actions.ActionType.REJECTED,
                        lowerPriorityChild);
            }
        }
    }

    @NonNull
    public ImmutableList<XmlElement> getMergeableElements() {
        return mMergeableChildren;
    }

    /**
     * Returns a child of a particular type and a particular key.
     * @param type the requested child type.
     * @param keyValue the requested child key.
     * @return the child of {@link com.google.common.base.Optional#absent()} if no child of this
     * type and key exist.
     */
    @NonNull
    public Optional<XmlElement> getNodeByTypeAndKey(
            ManifestModel.NodeTypes type,
            @Nullable String keyValue) {

        for (XmlElement xmlElement : mMergeableChildren) {
            if (xmlElement.isA(type) &&
                    (keyValue == null || keyValue.equals(xmlElement.getKey()))) {
                return Optional.of(xmlElement);
            }
        }
        return Optional.absent();
    }

    /**
     * Returns all immediate children of this node for a particular type, irrespective of their
     * key.
     * @param type the type of children element requested.
     * @return the list (potentially empty) of children.
     */
    @NonNull
    public ImmutableList<XmlElement> getAllNodesByType(ManifestModel.NodeTypes type) {
        ImmutableList.Builder<XmlElement> listBuilder = ImmutableList.builder();
        for (XmlElement mergeableChild : initMergeableChildren()) {
            if (mergeableChild.isA(type)) {
                listBuilder.add(mergeableChild);
            }
        }
        return listBuilder.build();
    }

    // merge this higher priority node with a lower priority node.
    public void mergeChildren(@NonNull XmlElement lowerPriorityNode,
            @NonNull MergingReport.Builder mergingReport) {

        // read all lower priority mergeable nodes.
        // if the same node is not defined in this document merge it in.
        // if the same is defined, so far, give an error message.
        for (XmlElement lowerPriorityChild : lowerPriorityNode.getMergeableElements()) {

            if (shouldIgnore(lowerPriorityChild, mergingReport)) {
                continue;
            }
            mergeChild(lowerPriorityChild, mergingReport);
        }
    }

    /**
     * Returns true if this element supports having a tools:selector decoration, false otherwise.
     */
    public boolean supportsSelector() {
        return getOperationType().isSelectable();
    }

    // merge a child of a lower priority node into this higher priority node.
    private void mergeChild(@NonNull XmlElement lowerPriorityChild, @NonNull MergingReport.Builder mergingReport) {

        ILogger logger = mergingReport.getLogger();

        // If this a custom element, we just blindly merge it in.
        if (lowerPriorityChild.getType() == ManifestModel.NodeTypes.CUSTOM) {
            handleCustomElement(lowerPriorityChild, mergingReport);
            return;
        }

        Optional<XmlElement> thisChildOptional =
                getNodeByTypeAndKey(lowerPriorityChild.getType(),lowerPriorityChild.getKey());

        // only in the lower priority document ?
        if (!thisChildOptional.isPresent()) {
            addElement(lowerPriorityChild, mergingReport);
            return;
        }
        // it's defined in both files.
        logger.verbose(lowerPriorityChild.getId() + " defined in both files...");

        XmlElement thisChild = thisChildOptional.get();
        switch (thisChild.getType().getMergeType()) {
            case CONFLICT:
                addMessage(mergingReport, MergingReport.Record.Severity.ERROR, String.format(
                        "Node %1$s cannot be present in more than one input file and it's "
                                + "present at %2$s and %3$s",
                        thisChild.getType(),
                        thisChild.printPosition(),
                        lowerPriorityChild.printPosition()
                ));
                break;
            case ALWAYS:

                // no merging, we consume the lower priority node unmodified.
                // if the two elements are equal, just skip it.

                // but check first that we are not supposed to replace or remove it.
                @NonNull NodeOperationType operationType =
                        calculateNodeOperationType(thisChild, lowerPriorityChild);
                if (operationType == NodeOperationType.REMOVE ||
                        operationType == NodeOperationType.REPLACE) {
                    mergingReport.getActionRecorder().recordNodeAction(thisChild,
                            Actions.ActionType.REJECTED, lowerPriorityChild);
                    break;
                }

                if (thisChild.getType().areMultipleDeclarationAllowed()) {
                    mergeChildrenWithMultipleDeclarations(lowerPriorityChild, mergingReport);
                } else {
                    if (!thisChild.isEquals(lowerPriorityChild)) {
                        addElement(lowerPriorityChild, mergingReport);
                    }
                }
                break;
            default:
                // 2 nodes exist, some merging need to happen
                handleTwoElementsExistence(thisChild, lowerPriorityChild, mergingReport);
                break;
        }
    }

    /**
     * Handles presence of custom elements (elements not part of the android or tools
     * namespaces). Such elements are merged unchanged into the resulting document, and
     * optionally, the namespace definition is added to the merged document root element.
     * @param customElement the custom element present in the lower priority document.
     * @param mergingReport the merging report to log errors and actions.
     */
    private void handleCustomElement(@NonNull XmlElement customElement,
            @NonNull MergingReport.Builder mergingReport) {
        addElement(customElement, mergingReport);

        // add the custom namespace to the document generation.
        String nodeName = customElement.getXml().getNodeName();
        if (!nodeName.contains(":")) {
            return;
        }
        @NonNull String prefix = nodeName.substring(0, nodeName.indexOf(':'));
        String namespace = customElement.getDocument().getRootNode()
                .getXml().getAttribute(SdkConstants.XMLNS_PREFIX + prefix);

        if (namespace != null) {
            getDocument().getRootNode().getXml().setAttributeNS(
                    SdkConstants.XMLNS_URI, SdkConstants.XMLNS_PREFIX + prefix, namespace);
        }
    }

    /**
     * Merges two children when this children's type allow multiple elements declaration with the
     * same key value. In that case, we only merge the lower priority child if there is not already
     * an element with the same key value that is equal to the lower priority child. Two children
     * are equals if they have the same attributes and children declared irrespective of the
     * declaration order.
     *
     * @param lowerPriorityChild the lower priority element's child.
     * @param mergingReport the merging report to log errors and actions.
     */
    private void mergeChildrenWithMultipleDeclarations(
            @NonNull XmlElement lowerPriorityChild,
            @NonNull MergingReport.Builder mergingReport) {

        Preconditions.checkArgument(lowerPriorityChild.getType().areMultipleDeclarationAllowed());
        if (lowerPriorityChild.getType().areMultipleDeclarationAllowed()) {
            for (XmlElement sameTypeChild : getAllNodesByType(lowerPriorityChild.getType())) {
                if (sameTypeChild.getId().equals(lowerPriorityChild.getId()) &&
                        sameTypeChild.isEquals(lowerPriorityChild)) {
                    return;
                }
            }
        }
        // if we end up here, we never found a child of this element with the same key and strictly
        // equals to the lowerPriorityChild so we should merge it in.
        addElement(lowerPriorityChild, mergingReport);
    }

    /**
     * Determine if we should completely ignore a child from any merging activity.
     * There are 2 situations where we should ignore a lower priority child :
     *

     *

     *
The associate {@link com.android.manifmerger.ManifestModel.NodeTypes} is
     *     annotated with {@link com.android.manifmerger.MergeType#IGNORE}

     *
This element has a child of the same type with no key that has a '
     *     tools:node="removeAll' attribute.

     *

     * @param lowerPriorityChild the lower priority child we should determine eligibility for
     *                           merging.
     * @return true if the element should be ignored, false otherwise.
     */
    private boolean shouldIgnore(
            @NonNull XmlElement lowerPriorityChild,
            @NonNull MergingReport.Builder mergingReport) {

        if (lowerPriorityChild.getType().getMergeType() == MergeType.IGNORE) {
            return true;
        }

        // do we have an element of the same type of that child with no key ?
        Optional<XmlElement> thisChildElementOptional =
                getNodeByTypeAndKey(lowerPriorityChild.getType(), null /* keyValue */);
        if (!thisChildElementOptional.isPresent()) {
            return false;
        }
        XmlElement thisChild = thisChildElementOptional.get();

        // are we supposed to delete all occurrences and if yes, is there a selector defined to
        // filter which elements should be deleted.
        boolean shouldDelete = thisChild.mNodeOperationType == NodeOperationType.REMOVE_ALL
                && (thisChild.mSelector == null
                        || thisChild.mSelector.appliesTo(lowerPriorityChild));
        // if we should discard this child element, record the action.
        if (shouldDelete) {
            mergingReport.getActionRecorder().recordNodeAction(thisChildElementOptional.get(),
                    Actions.ActionType.REJECTED,
                    lowerPriorityChild);
        }
        return shouldDelete;
    }

    /**
     * Handle 2 elements (of same identity) merging.
     * higher priority one has a tools:node="remove", remove the low priority one
     * higher priority one has a tools:node="replace", replace the low priority one
     * higher priority one has a tools:node="strict", flag the error if not equals.
     * default or tools:node="merge", merge the two elements.
     * @param higherPriority the higher priority node.
     * @param lowerPriority the lower priority element.
     * @param mergingReport the merging report to log errors and actions.
     */
    private void handleTwoElementsExistence(
            @NonNull XmlElement higherPriority,
            @NonNull XmlElement lowerPriority,
            @NonNull MergingReport.Builder mergingReport) {

        @NonNull NodeOperationType operationType = calculateNodeOperationType(higherPriority, lowerPriority);
        // 2 nodes exist, 3 possibilities :
        //  higher priority one has a tools:node="remove", remove the low priority one
        //  higher priority one has a tools:node="replace", replace the low priority one
        //  higher priority one has a tools:node="strict", flag the error if not equals.
        switch(operationType) {
            case MERGE:
            case MERGE_ONLY_ATTRIBUTES:
                // record the action
                mergingReport.getActionRecorder().recordNodeAction(higherPriority,
                        Actions.ActionType.MERGED, lowerPriority);
                // and perform the merge
                higherPriority.mergeWithLowerPriorityNode(lowerPriority, mergingReport);
                break;
            case REMOVE:
            case REPLACE:
                // so far remove and replace and similar, the post validation will take
                // care of removing this node in the case of REMOVE.

                // just don't import the lower priority node and record the action.
                mergingReport.getActionRecorder().recordNodeAction(higherPriority,
                        Actions.ActionType.REJECTED, lowerPriority);
                break;
            case STRICT:
                Optional<String> compareMessage = higherPriority.compareTo(lowerPriority);
                if (compareMessage.isPresent()) {
                    // flag error.
                    addMessage(mergingReport, MergingReport.Record.Severity.ERROR, String.format(
                            "Node %1$s at %2$s is tagged with tools:node=\"strict\", yet "
                                    + "%3$s at %4$s is different : %5$s",
                            higherPriority.getId(),
                            higherPriority.printPosition(),
                            lowerPriority.getId(),
                            lowerPriority.printPosition(),
                            compareMessage.get()
                    ));
                }
                break;
            default:
                mergingReport.getLogger().error(null /* throwable */,
                        "Unhandled node operation type %s", higherPriority.getOperationType());
                break;
        }
    }

    /**
     * Calculate the effective node operation type for a higher priority node when a lower priority
     * node is queried for merge.
     * @param higherPriority the higher priority node which may have a {@link NodeOperationType}
     *                       declaration and may also have a {@link Selector} declaration.
     * @param lowerPriority the lower priority node that is elected for merging with the higher
     *                      priority node.
     * @return the effective {@link NodeOperationType} that should be used to affect higher and
     * lower priority nodes merging.
     */
    @NonNull
    private static NodeOperationType calculateNodeOperationType(
            @NonNull XmlElement higherPriority,
            @NonNull XmlElement lowerPriority) {

        @NonNull NodeOperationType operationType = higherPriority.getOperationType();
        // if the operation's selector exists and the lower priority node is not selected,
        // we revert to default operation type which is merge.
        if (higherPriority.supportsSelector()
                && higherPriority.mSelector != null
                && !higherPriority.mSelector.appliesTo(lowerPriority)) {
            operationType = NodeOperationType.MERGE;
        }
        return operationType;
    }

    /**
     * Add an element and its leading comments as the last sub-element of the current element.
     * @param elementToBeAdded xml element to be added to the current element.
     * @param mergingReport the merging report to log errors and actions.
     */
    private void addElement(
            @NonNull XmlElement elementToBeAdded, @NonNull MergingReport.Builder mergingReport) {

        List<Node> comments = getLeadingComments(elementToBeAdded.getXml());
        // record all the actions before the node is moved from the library document to the main
        // merged document.
        mergingReport.getActionRecorder().recordDefaultNodeAction(elementToBeAdded);

        // only in the new file, just import it.
        Node node = getXml().getOwnerDocument().adoptNode(elementToBeAdded.getXml());
        getXml().appendChild(node);

        // also adopt the child's comments if any.
        for (Node comment : comments) {
            Node newComment = getXml().getOwnerDocument().adoptNode(comment);
            getXml().insertBefore(newComment, node);
        }

        mergingReport.getLogger().verbose("Adopted " + node);
    }

    public boolean isEquals(XmlElement otherNode) {
        return !compareTo(otherNode).isPresent();
    }

    /**
     * Returns a potentially null (if not present) selector decoration on this element.
     */
    @Nullable
    public Selector getSelector() {
        return mSelector;
    }

    /**
     * Compares this element with another {@link XmlElement} ignoring all attributes belonging to
     * the {@link SdkConstants#TOOLS_URI} namespace.
     *
     * @param other the other element to compare against.
     * @return a {@link String} describing the differences between the two XML elements or
     * {@link Optional#absent()} if they are equals.
     */
    @NonNull
    public Optional<String> compareTo(Object other) {

        if (!(other instanceof XmlElement)) {
            return Optional.of("Wrong type");
        }
        XmlElement otherNode = (XmlElement) other;

        // compare element names
        if (getXml().getNamespaceURI() != null) {
            if (!getXml().getLocalName().equals(otherNode.getXml().getLocalName())) {
                return Optional.of(
                        String.format("Element names do not match: %1$s versus %2$s",
                                getXml().getLocalName(),
                                otherNode.getXml().getLocalName()));
            }
            // compare element ns
            String thisNS = getXml().getNamespaceURI();
            String otherNS = otherNode.getXml().getNamespaceURI();
            if ((thisNS == null && otherNS != null)
                    || (thisNS != null && !thisNS.equals(otherNS))) {
                return Optional.of(
                        String.format("Element namespaces names do not match: %1$s versus %2$s",
                                thisNS, otherNS));
            }
        } else {
            if (!getXml().getNodeName().equals(otherNode.getXml().getNodeName())) {
                return Optional.of(String.format("Element names do not match: %1$s versus %2$s",
                        getXml().getNodeName(),
                        otherNode.getXml().getNodeName()));
            }
        }

        // compare attributes, we do it twice to identify added/missing elements in both lists.
        Optional<String> message = checkAttributes(this, otherNode);
        if (message.isPresent()) {
            return message;
        }
        message = checkAttributes(otherNode, this);
        if (message.isPresent()) {
            return message;
        }

        // compare children
        @NonNull List<Node> expectedChildren = filterUninterestingNodes(getXml().getChildNodes());
        @NonNull List<Node> actualChildren = filterUninterestingNodes(otherNode.getXml().getChildNodes());
        if (expectedChildren.size() != actualChildren.size()) {

            if (expectedChildren.size() > actualChildren.size()) {
                // missing some.
                @NonNull List<String> missingChildrenNames =
                        Lists.transform(expectedChildren, NODE_TO_NAME);
                missingChildrenNames.removeAll(Lists.transform(actualChildren, NODE_TO_NAME));
                return Optional.of(String.format(
                        "%1$s: Number of children do not match up: "
                                + "expected %2$d versus %3$d at %4$s, missing %5$s",
                        getId(),
                        expectedChildren.size(),
                        actualChildren.size(),
                        otherNode.printPosition(),
                        Joiner.on(",").join(missingChildrenNames)));
            } else {
                // extra ones.
                @NonNull List<String> extraChildrenNames = Lists.transform(actualChildren, NODE_TO_NAME);
                extraChildrenNames.removeAll(Lists.transform(expectedChildren, NODE_TO_NAME));
                return Optional.of(String.format(
                        "%1$s: Number of children do not match up: "
                                + "expected %2$d versus %3$d at %4$s, extra elements found : %5$s",
                        getId(),
                        expectedChildren.size(),
                        actualChildren.size(),
                        otherNode.printPosition(),
                        Joiner.on(",").join(expectedChildren)));
            }
        }
        for (Node expectedChild : expectedChildren) {
            if (expectedChild.getNodeType() == Node.ELEMENT_NODE) {
                @NonNull XmlElement expectedChildNode = new XmlElement((Element) expectedChild, mDocument);
                message = findAndCompareNode(otherNode, actualChildren, expectedChildNode);
                if (message.isPresent()) {
                    return message;
                }
            }
        }
        return Optional.absent();
    }

    private Optional<String> findAndCompareNode(
            @NonNull XmlElement otherElement,
            @NonNull List<Node> otherElementChildren,
            @NonNull XmlElement childNode) {

        Optional<String> message = Optional.absent();
        for (Node potentialNode : otherElementChildren) {
            if (potentialNode.getNodeType() == Node.ELEMENT_NODE) {
                @NonNull XmlElement otherChildNode = new XmlElement((Element) potentialNode, mDocument);
                if (childNode.getType() == otherChildNode.getType()) {
                    // check if this element uses a key.
                    if (childNode.getType().getNodeKeyResolver().getKeyAttributesNames()
                            .isEmpty()) {
                        // no key... try all the other elements, if we find one equal, we are done.
                        message = childNode.compareTo(otherChildNode);
                        if (!message.isPresent()) {
                            return Optional.absent();
                        }
                    } else {
                        // key...
                        if (childNode.getKey() == null) {
                            // other key MUST also be null.
                            if (otherChildNode.getKey() == null) {
                                return childNode.compareTo(otherChildNode);
                            }
                        } else {
                            if (childNode.getKey().equals(otherChildNode.getKey())) {
                                return childNode.compareTo(otherChildNode);
                            }
                        }
                    }
                }
            }
        }
        return message.isPresent()
                ? message
                : Optional.of(String.format("Child %1$s not found in document %2$s",
                        childNode.getId(),
                        otherElement.printPosition()));
    }

    @NonNull
    private static List<Node> filterUninterestingNodes(@NonNull NodeList nodeList) {
        List<Node> interestingNodes = new ArrayList<Node>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.TEXT_NODE) {
                Text t = (Text) node;
                if (!t.getData().trim().isEmpty()) {
                    interestingNodes.add(node);
                }
            } else if (node.getNodeType() != Node.COMMENT_NODE) {
                interestingNodes.add(node);
            }

        }
        return interestingNodes;
    }

    private static Optional<String> checkAttributes(
            @NonNull XmlElement expected,
            @NonNull XmlElement actual) {

        for (XmlAttribute expectedAttr : expected.getAttributes()) {
            XmlAttribute.NodeName attributeName = expectedAttr.getName();
            if (attributeName.isInNamespace(SdkConstants.TOOLS_URI)) {
                continue;
            }
            Optional<XmlAttribute> actualAttr = actual.getAttribute(attributeName);
            if (actualAttr.isPresent()) {
                if (!expectedAttr.getValue().equals(actualAttr.get().getValue())) {
                    return Optional.of(
                            String.format("Attribute %1$s do not match: %2$s versus %3$s at %4$s",
                                    expectedAttr.getId(),
                                    expectedAttr.getValue(),
                                    actualAttr.get().getValue(),
                                    actual.printPosition()));
                }
            } else {
                return Optional.of(String.format("Attribute %1$s not found at %2$s",
                        expectedAttr.getId(), actual.printPosition()));
            }
        }
        return Optional.absent();
    }

    @SuppressWarnings("SpellCheckingInspection")
    private ImmutableList<XmlElement> initMergeableChildren() {
        ImmutableList.Builder<XmlElement> mergeableNodes = new ImmutableList.Builder<XmlElement>();
        NodeList nodeList = getXml().getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                XmlElement xmlElement = new XmlElement((Element) node, mDocument);
                mergeableNodes.add(xmlElement);
            }
        }
        return mergeableNodes.build();
    }

    /**
     * Returns all leading comments in the source xml before the node to be adopted.
     * @param nodeToBeAdopted node that will be added as a child to this node.
     */
    static List<Node> getLeadingComments(@NonNull Node nodeToBeAdopted) {
        @NonNull ImmutableList.Builder<Node> nodesToAdopt = new ImmutableList.Builder<Node>();
        Node previousSibling = nodeToBeAdopted.getPreviousSibling();
        while (previousSibling != null
                && (previousSibling.getNodeType() == Node.COMMENT_NODE
                || previousSibling.getNodeType() == Node.TEXT_NODE)) {
            // we really only care about comments.
            if (previousSibling.getNodeType() == Node.COMMENT_NODE) {
                nodesToAdopt.add(previousSibling);
            }
            previousSibling = previousSibling.getPreviousSibling();
        }
        return nodesToAdopt.build().reverse();
    }

    void addMessage(@NonNull MergingReport.Builder mergingReport,
            @NonNull MergingReport.Record.Severity severity,
            @NonNull String message) {
        mergingReport.addMessage(getSourceFilePosition(),
                severity,
                message);
    }
}


text:
interface IEvent {
    commandName: string
    name: string;
    correlationId: Object;
    payload: Object;
}


text:
BEGIN_HYPERDEX_NAMESPACE

class datatype_int64 : public datatype_info
{
    public:
        datatype_int64();
        virtual ~datatype_int64() throw ();

    public:
        virtual hyperdatatype datatype();
        virtual bool validate(const e::slice& value);
        virtual bool check_args(const funcall& func);
        virtual uint8_t* apply(const e::slice& old_value,
                               const funcall* funcs, size_t funcs_sz,
                               uint8_t* writeto);

    public:
        virtual bool hashable();
        virtual uint64_t hash(const e::slice& value);
        virtual bool indexable();

    public:
        virtual bool containable();
        virtual bool step(const uint8_t** ptr,
                          const uint8_t* end,
                          e::slice* elem);
        virtual uint8_t* write(uint8_t* writeto,
                               const e::slice& elem);
        virtual bool comparable();
        virtual int compare(const e::slice& lhs, const e::slice& rhs);
        virtual compares_less compare_less();
};

END_HYPERDEX_NAMESPACE

#endif // hyperdex_common_datatype_int64_h_


text:
/**
 * animal
 *
 * @author Pierre Master Bioinfo
 *
 */
import java.io.*;
import java.util.*;

public class Animalerie {
    public static void printArray(Vector<Animal> anArray) {
        System.out.print("\n");
        for (int i = 0; i < anArray.size(); i++) {
            anArray.get(i).affiche();
        }
        System.out.println(" ");
    }

    public static void clearScreen() {
        System.out.print("\033[H\033[2J");
        System.out.flush();
    }

    public static boolean saisie_boolean() {
        String temp = saisie_chaine();
        boolean bvar = Boolean.parseBoolean(temp);
        return bvar;
    }

    public static String saisie_chaine() {
        try {
            BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
            String chaine = buff.readLine();
            return chaine;
        } catch (IOException e) {
            System.out.println(" impossible de travailler" + e);
            return null;
        }
    }

    public static int saisie_entier() {
        try {
            BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
            String chaine = buff.readLine();
            int num = Integer.parseInt(chaine);
            return num;
        } catch (IOException e) {
            return 0;
        }
    }

    public void saveanimals(BufferedWriter buff) throws IOException{
            for (int i = 0; i < tab.size(); i++) {
                tab.get(i).save(buff);
            }
    }

    private String nom;
    public static Vector<Animal> tab = new Vector<Animal>();
    public static int compteur = 0;

    public void setNom_animalerie(String id) {
        nom = id;
    }

    public String getNom_animalerie() {
        return nom;
    }

    public static void menu() {
        clearScreen();
        System.out.println("NATACHA VETERINAIRE BONJOUUUUUUR...");
        System.out.println("\n[1] Rentrer le nom des animaux");
        System.out.println("[2] Afficher les infos des animaux");
        System.out.println("[3] Afficher les infos d'un animal");
        System.out.println("\n[4] Saisir l'état d'un animal");
        System.out.println("[5] Vieillir tous les animaux");
        System.out.println("[6] Vieillir un animal");
        System.out.println("\n[0] Quitter\n");
        int option = saisie_entier();

        switch (option) {
        case 1:
            clearScreen();
            tab = saisie_animal();
            clearScreen();
            menu();
            break;
        case 2:
            clearScreen();
            printArray(tab);
            saisie_chaine();
            menu();
            break;
        case 3:
            clearScreen();
            System.out.println("Quel est le nom de l'animal ?: ");
            String nom = saisie_chaine();
            afficher_lui(tab, nom);
            saisie_chaine();
            menu();
            break;
        case 4:
            clearScreen();
            System.out.println("Quel est le nom de l'animal ?: ");
            nom = saisie_chaine();
            passer_en_revue(nom);
            saisie_chaine();
            menu();
            break;
        case 5:
            clearScreen();
            le_temps_qui_passe();
            saisie_chaine();
            menu();
            break;
        case 6:
            clearScreen();
            System.out.println("Quel est le nom de l'animal ?: ");
            String nomduvieux = saisie_chaine();
            vieux_crouton(nomduvieux);
            saisie_chaine();
            menu();
            break;
        case 0:
            gerer_animalerie.menuanimalerie();
            break;
        default:
            menu();
            break;
        }
    }

    public static Animal Avis_de_recherche(Vector<Animal> tab, String nom) {
        for (int j = 0; j < compteur; j++) {
            if (tab.get(j).getId().equals(nom)) {
                return tab.get(j);
            }
        }
        return null;
    }

    public static void afficher_lui(Vector<Animal> tab, String nom) {
        Animal found = Avis_de_recherche(tab, nom);
        System.out.println("\nid: " + found.getId());
        System.out.println("Age: " + found.getAge() + " mois");
        System.out.println("Encore en vie: " + found.getStatus() + "\n");
    }

    public static void le_temps_qui_passe() {
        for (int j = 0; j < compteur; j++) {
            int newage = tab.get(j).getAge() + 1;
            tab.get(j).setAge(newage);
        }
    }

    public static void vieux_crouton(String nom) {
        Animal found = Avis_de_recherche(tab, nom);
        int newage = found.getAge() + 1;
        found.setAge(newage);
    }

    public static boolean prouve_que_tu_existe(Vector<Animal> tab, String nom) {
        if (compteur == 0) {
            return false;
        }
        Animal found = Avis_de_recherche(tab, nom);
        if (found != null) {
            System.out.println("\nNom déjà existant, rentrez en un autre: ");
            return true;
        }
        return false;
    }

    public static Vector<Animal> saisie_animal() {
        System.out.println("\nCombien voulez-vous ajouter d'animaux ? : ");
        int nombre = saisie_entier();
        //agrandir_tableau(tab,nombre);
        Vector<Animal> tab = new Vector<Animal>();//[nombre];
        for (int i = 0; i < nombre; i++) {

            System.out.println("\nDonnez un nom: ");
            String nom = saisie_chaine();
            while (prouve_que_tu_existe(tab, nom) == true) {
                nom = saisie_chaine();
            }

            System.out.println("\nDonnez un age: ");
            int age = saisie_entier();
            boolean vivant = true;
            afficheChoix();
            int reponse = saisie_entier();
            Animal item = null;
            switch (reponse) {
            case 1:
                item = new chat(nom, age, vivant);
                break;
            case 2:
                item = new canari(nom, age, vivant);
                break;
            case 3:
                item = new souris(nom, age, vivant);
                break;
            default:
                System.out.println("Option inexistante recommencez");
                i--;
            }
            if (item != null) {
                tab.add(item);
                compteur = compteur + 1;
            }
        }
        clearScreen();
        return tab;
    }

    static void afficheChoix() {
        System.out.println("\nQuel est l'espèce de l'animal ?");
        System.out.println("[1]\t Gros matou");
        System.out.println("[2]\t Canari de Mémé");
        System.out.println("[3]\t Grosse Souris");

    }

    public static Vector<Animal> passer_en_revue(String nom) {
        for (int i = 0; i < tab.size(); i++) {
            if (tab.get(i).getId().equals(nom)) {
                System.out.println("\n" + tab.get(i).getId() + " est-il encore en vie ? (True/False): ");
                boolean boule = saisie_boolean();
                int age = tab.get(i).getAge();
                Animal item = new Animal(nom, age, boule);
                tab.set(i, item);
            }
        }
        return tab;
    }

    public Animalerie(String chaine) {
        nom=chaine;
        tab=new Vector();
    }

    public static void main(String[] arg) {
        menu();
    }

}


text:
/* */
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
  for (var p in b)
    if (b.hasOwnProperty(p))
      d[p] = b[p];
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var OuterSubscriber_1 = require('../OuterSubscriber');
var subscribeToResult_1 = require('../util/subscribeToResult');
function withLatestFrom() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i - 0] = arguments[_i];
  }
  var project;
  if (typeof args[args.length - 1] === 'function') {
    project = args.pop();
  }
  var observables = args;
  return this.lift(new WithLatestFromOperator(observables, project));
}
exports.withLatestFrom = withLatestFrom;
var WithLatestFromOperator = (function() {
  function WithLatestFromOperator(observables, project) {
    this.observables = observables;
    this.project = project;
  }
  WithLatestFromOperator.prototype.call = function(subscriber, source) {
    return source._subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
  };
  return WithLatestFromOperator;
}());
var WithLatestFromSubscriber = (function(_super) {
  __extends(WithLatestFromSubscriber, _super);
  function WithLatestFromSubscriber(destination, observables, project) {
    _super.call(this, destination);
    this.observables = observables;
    this.project = project;
    this.toRespond = [];
    var len = observables.length;
    this.values = new Array(len);
    for (var i = 0; i < len; i++) {
      this.toRespond.push(i);
    }
    for (var i = 0; i < len; i++) {
      var observable = observables[i];
      this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
    }
  }
  WithLatestFromSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
    this.values[outerIndex] = innerValue;
    var toRespond = this.toRespond;
    if (toRespond.length > 0) {
      var found = toRespond.indexOf(outerIndex);
      if (found !== -1) {
        toRespond.splice(found, 1);
      }
    }
  };
  WithLatestFromSubscriber.prototype.notifyComplete = function() {};
  WithLatestFromSubscriber.prototype._next = function(value) {
    if (this.toRespond.length === 0) {
      var args = [value].concat(this.values);
      if (this.project) {
        this._tryProject(args);
      } else {
        this.destination.next(args);
      }
    }
  };
  WithLatestFromSubscriber.prototype._tryProject = function(args) {
    var result;
    try {
      result = this.project.apply(this, args);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(result);
  };
  return WithLatestFromSubscriber;
}(OuterSubscriber_1.OuterSubscriber));


text:
package org.fest.assertions.internal;

import static org.fest.assertions.error.ShouldBeLowerCase.shouldBeLowerCase;
import static org.fest.assertions.test.ExpectedException.none;
import static org.fest.assertions.test.FailureMessages.actualIsNull;
import static org.fest.assertions.test.TestData.someInfo;
import static org.fest.assertions.test.TestFailures.expectedAssertionErrorNotThrown;
import static org.mockito.Mockito.*;

import org.fest.assertions.core.AssertionInfo;
import org.fest.assertions.test.ExpectedException;
import org.junit.*;

/**
 * Tests for <code>{@link Characters#assertLowerCase(AssertionInfo, Character)}</code>.
 *
 * @author Yvonne Wang
 */
public class Characters_assertLowerCase_Test {

  @Rule public ExpectedException thrown = none();

  private Failures failures;
  private Characters characters;

  @Before public void setUp() {
    failures = spy(new Failures());
    characters = new Characters();
    characters.failures = failures;
  }

  @Test public void should_fail_if_actual_is_null() {
    thrown.expectAssertionError(actualIsNull());
    characters.assertLowerCase(someInfo(), null);
  }

  @Test public void should_pass_if_actual_is_lowercase() {
    characters.assertLowerCase(someInfo(), 'a');
  }

  @Test public void should_fail_if_actual_is_not_lowercase() {
    AssertionInfo info = someInfo();
    try {
      characters.assertLowerCase(info, 'A');
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldBeLowerCase('A'));
      return;
    }
    throw expectedAssertionErrorNotThrown();
  }
}


text:
const stream = fc.randomFinancial().stream();
const data = stream.take(110);

function renderChart() {
    // add a new datapoint and remove an old one
    data.push(stream.next());
    data.shift();

    // Create and apply the bollinger algorithm
    const bollingerAlgorithm = fc.indicatorBollingerBands().value(d => d.close);
    const bollingerData = bollingerAlgorithm(data);
    const mergedData = data.map((d, i) => ({
        ...d,
        bollinger: bollingerData[i]
    }));

    // Offset the range to include the full bar for the latest value
    const DAY_MS = 1000 * 60 * 60 * 24;
    const xExtent = fc
        .extentDate()
        .accessors([d => d.date])
        .padUnit('domain')
        .pad([DAY_MS * -bollingerAlgorithm.period()(mergedData), DAY_MS]);

    // ensure y extent includes the bollinger bands
    const yExtent = fc
        .extentLinear()
        .accessors([
            d => d.bollinger.upper,
            d => d.high,
            d => d.bollinger.lower,
            d => d.low
        ]);

    // create a chart
    const chart = fc
        .chartCartesian(d3.scaleTime(), d3.scaleLinear())
        .xDomain(xExtent(mergedData))
        .yDomain(yExtent(mergedData))
        .chartLabel('Streaming Idempotent Chart');

    // Create the gridlines and series
    const gridlines = fc.annotationSvgGridline();
    const candlestick = fc.seriesSvgCandlestick();

    const bollingerBands = function() {
        const area = fc
            .seriesSvgArea()
            .mainValue(d => d.bollinger.upper)
            .baseValue(d => d.bollinger.lower)
            .crossValue(d => d.date);

        const upperLine = fc
            .seriesSvgLine()
            .mainValue(d => d.bollinger.upper)
            .crossValue(d => d.date);

        const averageLine = fc
            .seriesSvgLine()
            .mainValue(d => d.bollinger.average)
            .crossValue(d => d.date);

        const lowerLine = fc
            .seriesSvgLine()
            .mainValue(d => d.bollinger.lower)
            .crossValue(d => d.date);

        const bollingerMulti = fc
            .seriesSvgMulti()
            .series([area, upperLine, lowerLine, averageLine])
            .decorate(g => {
                g.enter().attr(
                    'class',
                    (_, i) =>
                        'multi bollinger ' +
                        ['area', 'upper', 'lower', 'average'][i]
                );
            });

        return bollingerMulti;
    };

    // add them to the chart via a multi-series
    const multi = fc
        .seriesSvgMulti()
        .series([gridlines, bollingerBands(), candlestick]);

    chart.svgPlotArea(multi);

    d3.select('#streaming-chart')
        .datum(mergedData)
        .call(chart);
}

// re-render the chart every 200ms
renderChart();
setInterval(renderChart, 200);


text:
<?php
namespace App;

use App\BancoPersonal;
use App\LaboratorioPersonal;
use \Illuminate\Database\Eloquent\Model;

class Usuario extends Model {
    protected $table = 'usuarios';

    //Ejemplo de definir campos
    //protected $fillable = ['username','email','password'];
	public function banco_personal()
	{
		return $this->hasOne(BancoPersonal::class, 'usuario_id','id');
	}

	public function laboratorio_personal()
	{
		return $this->hasOne(LaboratorioPersonal::class, 'usuario_id','id');
	}
}


text:
System.register(["aurelia-binding", "node-emoji"], function (exports_1, context_1) {
    "use strict";
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __moduleName = context_1 && context_1.id;
    var aurelia_binding_1, node_emoji_1, Emoji;
    return {
        setters: [
            function (aurelia_binding_1_1) {
                aurelia_binding_1 = aurelia_binding_1_1;
            },
            function (node_emoji_1_1) {
                node_emoji_1 = node_emoji_1_1;
            }
        ],
        execute: function () {
            Emoji = (function () {
                function Emoji() {
                }
                Emoji.prototype.toView = function (val) {
                    if (!val || val === '' || typeof val !== 'string') {
                        return val;
                    }
                    return node_emoji_1.emojify(val);
                };
                return Emoji;
            }());
            Emoji = __decorate([
                aurelia_binding_1.valueConverter('emoji')
            ], Emoji);
            exports_1("Emoji", Emoji);
        }
    };
});
//# sourceMappingURL=emoji-value-converter.js.map


text:
using System;
using System.Web;

/// <summary>
/// Summary description for PasswordSetting
/// </summary>
public class PasswordSetting
{
	public PasswordSetting()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    //password age , 80, 180, 360 days
    public int Duration { get; set; }

    //password minimum length
    public int MinLength { get; set; }

    //password maximum length
    public int MaxLength { get; set; }

    //password Numbers length
    public int NumsLength { get; set; }

    //password Upper letter length
    public int UpperLength { get; set; }

    //password Special character length
    public int SpecialLength { get; set; }

    //password valid special characters
    public string SpecialChars { get; set; }

    //password Special character length
    public int MaxConsecutiveRepeatedChars { get; set; }

}