text:
package org.springframework.boot.actuate.scheduling;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.FixedDelayTask;
import org.springframework.scheduling.config.FixedRateTask;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskHolder;
import org.springframework.scheduling.config.Task;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.scheduling.support.ScheduledMethodRunnable;

/**
 * {@link Endpoint} to expose information about an application's scheduled tasks.
 *
 * @author Andy Wilkinson
 * @since 2.0.0
 */
@Endpoint(id = "scheduledtasks")
public class ScheduledTasksEndpoint {

	private final Collection<ScheduledTaskHolder> scheduledTaskHolders;

	public ScheduledTasksEndpoint(Collection<ScheduledTaskHolder> scheduledTaskHolders) {
		this.scheduledTaskHolders = scheduledTaskHolders;
	}

	@ReadOperation
	public ScheduledTasksReport scheduledTasks() {
		Map<TaskType, List<TaskDescription>> descriptionsByType = this.scheduledTaskHolders
				.stream().flatMap((holder) -> holder.getScheduledTasks().stream())
				.map(ScheduledTask::getTask).map(TaskDescription::of)
				.filter(Objects::nonNull)
				.collect(Collectors.groupingBy(TaskDescription::getType));
		return new ScheduledTasksReport(descriptionsByType);
	}

	/**
	 * A report of an application's scheduled {@link Task Tasks}, primarily intended for
	 * serialization to JSON.
	 */
	public static final class ScheduledTasksReport {

		private final List<TaskDescription> cron;

		private final List<TaskDescription> fixedDelay;

		private final List<TaskDescription> fixedRate;

		private ScheduledTasksReport(
				Map<TaskType, List<TaskDescription>> descriptionsByType) {
			this.cron = descriptionsByType.getOrDefault(TaskType.CRON,
					Collections.emptyList());
			this.fixedDelay = descriptionsByType.getOrDefault(TaskType.FIXED_DELAY,
					Collections.emptyList());
			this.fixedRate = descriptionsByType.getOrDefault(TaskType.FIXED_RATE,
					Collections.emptyList());
		}

		public List<TaskDescription> getCron() {
			return this.cron;
		}

		public List<TaskDescription> getFixedDelay() {
			return this.fixedDelay;
		}

		public List<TaskDescription> getFixedRate() {
			return this.fixedRate;
		}

	}

	/**
	 * Base class for descriptions of a {@link Task}.
	 */
	public abstract static class TaskDescription {

		private static final Map<Class<? extends Task>, Function<Task, TaskDescription>> DESCRIBERS = new LinkedHashMap<>();

		static {
			DESCRIBERS.put(FixedRateTask.class,
					(task) -> new FixedRateTaskDescription((FixedRateTask) task));
			DESCRIBERS.put(FixedDelayTask.class,
					(task) -> new FixedDelayTaskDescription((FixedDelayTask) task));
			DESCRIBERS.put(CronTask.class,
					(task) -> new CronTaskDescription((CronTask) task));
			DESCRIBERS.put(TriggerTask.class,
					(task) -> describeTriggerTask((TriggerTask) task));
		}

		private final TaskType type;

		private final RunnableDescription runnable;

		private static TaskDescription of(Task task) {
			return DESCRIBERS.entrySet().stream()
					.filter((entry) -> entry.getKey().isInstance(task))
					.map((entry) -> entry.getValue().apply(task)).findFirst()
					.orElse(null);
		}

		private static TaskDescription describeTriggerTask(TriggerTask triggerTask) {
			Trigger trigger = triggerTask.getTrigger();
			if (trigger instanceof CronTrigger) {
				return new CronTaskDescription(triggerTask, (CronTrigger) trigger);
			}
			if (trigger instanceof PeriodicTrigger) {
				PeriodicTrigger periodicTrigger = (PeriodicTrigger) trigger;
				if (periodicTrigger.isFixedRate()) {
					return new FixedRateTaskDescription(triggerTask, periodicTrigger);
				}
				return new FixedDelayTaskDescription(triggerTask, periodicTrigger);
			}
			return null;
		}

		protected TaskDescription(TaskType type, Runnable runnable) {
			this.type = type;
			this.runnable = new RunnableDescription(runnable);
		}

		private TaskType getType() {
			return this.type;
		}

		public final RunnableDescription getRunnable() {
			return this.runnable;
		}

	}

	/**
	 * A description of an {@link IntervalTask}.
	 */
	public static class IntervalTaskDescription extends TaskDescription {

		private final long initialDelay;

		private final long interval;

		protected IntervalTaskDescription(TaskType type, IntervalTask task) {
			super(type, task.getRunnable());
			this.initialDelay = task.getInitialDelay();
			this.interval = task.getInterval();
		}

		protected IntervalTaskDescription(TaskType type, TriggerTask task,
				PeriodicTrigger trigger) {
			super(type, task.getRunnable());
			this.initialDelay = trigger.getInitialDelay();
			this.interval = trigger.getPeriod();
		}

		public long getInitialDelay() {
			return this.initialDelay;
		}

		public long getInterval() {
			return this.interval;
		}

	}

	/**
	 * A description of a {@link FixedDelayTask} or a {@link TriggerTask} with a
	 * fixed-delay {@link PeriodicTrigger}.
	 */
	public static final class FixedDelayTaskDescription extends IntervalTaskDescription {

		private FixedDelayTaskDescription(FixedDelayTask task) {
			super(TaskType.FIXED_DELAY, task);
		}

		private FixedDelayTaskDescription(TriggerTask task, PeriodicTrigger trigger) {
			super(TaskType.FIXED_DELAY, task, trigger);
		}

	}

	/**
	 * A description of a {@link FixedRateTask} or a {@link TriggerTask} with a fixed-rate
	 * {@link PeriodicTrigger}.
	 */
	public static final class FixedRateTaskDescription extends IntervalTaskDescription {

		private FixedRateTaskDescription(FixedRateTask task) {
			super(TaskType.FIXED_RATE, task);
		}

		private FixedRateTaskDescription(TriggerTask task, PeriodicTrigger trigger) {
			super(TaskType.FIXED_RATE, task, trigger);
		}

	}

	/**
	 * A description of a {@link CronTask} or a {@link TriggerTask} with a
	 * {@link CronTrigger}.
	 */
	public static final class CronTaskDescription extends TaskDescription {

		private final String expression;

		private CronTaskDescription(CronTask task) {
			super(TaskType.CRON, task.getRunnable());
			this.expression = task.getExpression();
		}

		private CronTaskDescription(TriggerTask task, CronTrigger trigger) {
			super(TaskType.CRON, task.getRunnable());
			this.expression = trigger.getExpression();
		}

		public String getExpression() {
			return this.expression;
		}

	}

	/**
	 * A description of a {@link Task Task's} {@link Runnable}.
	 *
	 * @author Andy Wilkinson
	 */
	public static final class RunnableDescription {

		private final String target;

		private RunnableDescription(Runnable runnable) {
			if (runnable instanceof ScheduledMethodRunnable) {
				Method method = ((ScheduledMethodRunnable) runnable).getMethod();
				this.target = method.getDeclaringClass().getName() + "."
						+ method.getName();
			}
			else {
				this.target = runnable.getClass().getName();
			}
		}

		public String getTarget() {
			return this.target;
		}

	}

	private enum TaskType {

		CRON, FIXED_DELAY, FIXED_RATE;

	}

}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base.test.util;

import junit.framework.TestCase;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.model.FrameworkMethod;
import org.robolectric.annotation.Config;

import org.chromium.base.test.BaseRobolectricTestRunner;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.List;

/** Unit tests for SkipCheck. */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class SkipCheckTest {
    private static class TestableSkipCheck extends SkipCheck {
        public static <T extends Annotation> List<T> getAnnotationsForTesting(
                AnnotatedElement element, Class<T> annotationClass) {
            return AnnotationProcessingUtils.getAnnotations(element, annotationClass);
        }

        @Override
        public boolean shouldSkip(FrameworkMethod m) {
            return false;
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    private @interface TestAnnotation {}

    @TestAnnotation
    private class AnnotatedBaseClass {
        public void unannotatedMethod() {}
        @TestAnnotation public void annotatedMethod() {}
    }

    private class ExtendsAnnotatedBaseClass extends AnnotatedBaseClass {
        public void anotherUnannotatedMethod() {}
    }

    private class ExtendsTestCaseClass extends TestCase {
        public ExtendsTestCaseClass(String name) {
            super(name);
        }
        public void testMethodA() {}
    }

    private class UnannotatedBaseClass {
        public void unannotatedMethod() {}
        @TestAnnotation public void annotatedMethod() {}
    }

    @Test
    public void getAnnotationsForClassNone() {
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                UnannotatedBaseClass.class, TestAnnotation.class);
        Assert.assertEquals(0, annotations.size());
    }

    @Test
    public void getAnnotationsForClassOnClass() {
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                AnnotatedBaseClass.class, TestAnnotation.class);
        Assert.assertEquals(1, annotations.size());
    }

    @Test
    public void getAnnotationsForClassOnSuperclass() {
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                ExtendsAnnotatedBaseClass.class, TestAnnotation.class);
        Assert.assertEquals(1, annotations.size());
    }

    @Test
    public void getAnnotationsForMethodNone() throws NoSuchMethodException {
        Method testMethod = UnannotatedBaseClass.class.getMethod("unannotatedMethod",
                (Class[]) null);
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                testMethod, TestAnnotation.class);
        Assert.assertEquals(0, annotations.size());
    }

    @Test
    public void getAnnotationsForMethodOnMethod() throws NoSuchMethodException {
        Method testMethod = UnannotatedBaseClass.class.getMethod("annotatedMethod",
                (Class[]) null);
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                testMethod, TestAnnotation.class);
        Assert.assertEquals(1, annotations.size());
    }

    @Test
    public void getAnnotationsForMethodOnClass() throws NoSuchMethodException {
        Method testMethod = AnnotatedBaseClass.class.getMethod("unannotatedMethod",
                (Class[]) null);
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                testMethod, TestAnnotation.class);
        Assert.assertEquals(1, annotations.size());
    }

    @Test
    public void getAnnotationsForMethodOnSuperclass() throws NoSuchMethodException {
        Method testMethod = ExtendsAnnotatedBaseClass.class.getMethod("unannotatedMethod",
                (Class[]) null);
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                testMethod, TestAnnotation.class);
        Assert.assertEquals(1, annotations.size());
    }

    @Test
    public void getAnnotationsOverlapping() throws NoSuchMethodException {
        Method testMethod = AnnotatedBaseClass.class.getMethod("annotatedMethod",
                (Class[]) null);
        List<TestAnnotation> annotations = TestableSkipCheck.getAnnotationsForTesting(
                testMethod, TestAnnotation.class);
        Assert.assertEquals(2, annotations.size());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.virtualinfinity.emulation.ui;

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

/**
 * @author Daniel Pitts
 */
public class PresentationComponentLine implements PresentationLine, AttributedCharacterLine {
    private final PresentationComponentModel parent;
    private final List<Position> positions = new ArrayList<>();

    public PresentationComponentLine(PresentationComponentModel parent) {
        this.parent = parent;
    }

    public void deleteCharacters(int position, int count) {
        existingPositions(position, count).clear();
        parent.updated();
    }

    private int bound(int position) {
        return Math.max(0, Math.min(position, positions.size()));
    }

    public void setCodePoint(int column, int codePoint, DisplayAttribute attribute) {
        positions.addAll(Collections.nCopies(Math.max(0, column - positions.size() + 1), null));
        positions.set(column, new Position(codePoint, attribute));
        parent.updated();
    }

    @Override
    public void eraseAll() {
        positions.clear();
        parent.updated();
    }

    @Override
    public void eraseTo(int column) {
        eraseSection(0, column + 1);
    }

    private List<Position> existingPositions(int start, int count) {
        return positions.subList(bound(start), bound(start +count));
    }

    @Override
    public void eraseFrom(int column) {
        eraseSection(column, positions.size());
    }

    @Override
    public void eraseSection(int start, int count) {
        existingPositions(start, count).replaceAll(p -> null);
        parent.updated();
    }

    @Override
    public void insert(int start, int count) {
        if (positions.size() <= start) {
            return;
        }

        positions.addAll(start, Collections.nCopies(count, null));
        parent.updated();
    }

    public void scrollLeft(int count) {
        existingPositions(0, count).clear();
        parent.updated();
    }

    public void scrollRight(int count) {
        insert(0, count);
        parent.updated();
    }

    @Override
    public int numPositions() {
        return positions.size();
    }

    @Override
    public DisplayAttribute attribute(int col) {
        return read(col).attribute;
    }

    private Position read(int col) {
        final Position position = positions.size() > col ? positions.get(col) : null;
        if (position == null) {
            return new Position(0, null);
        }
        return position;
    }

    @Override
    public int codePoint(int col) {
        return read(col).codePoint;
    }

    private static class Position {
        final int codePoint;
        final DisplayAttribute attribute;

        public Position(int codePoint, DisplayAttribute attribute) {
            this.codePoint = codePoint == 0 ? 32 : codePoint;
            this.attribute = attribute;
        }

        public int codePoint() {
            return codePoint;
        }

        public DisplayAttribute attribute() {
            return attribute;
        }
    }

    @Override
    public String toString() {
        return positions.stream().mapToInt(value -> value == null ? ' ' : value.codePoint).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
    }
}


text:
package maths;

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

import gui.Workspace;
import javafx.scene.image.Image;
import util.ImgUtils;

/**
 * An expression whose value is unknown, but may be found in the heap.
 *
 * @author jkunimune
 */
public class Variable extends Expression {

	private final String name;

	public Variable(String s) {
		name = s;
	}

	@Override
	public int[] shape() {
		final int[] out = {1,1};
		return out;
	}

	@Override
	protected Expression getComponent(int i, int j) {
		return this; //TODO: variables can be vectors, too, right?
	}

	@Override
	public List<String> getInputs(Workspace heap) {
		if (heap != null && heap.containsKey(name)){
			return heap.get(name).getInputs(heap);
		}
		else {
			List<String> list = new ArrayList<String>();
			list.add(name);
			return list;
		}
	}

	@Override
	public Expression replaced(String[] oldStrs, String[] newStrs) {
		for (int i = 0; i < oldStrs.length; i ++)
			if (oldStrs[i].equals(name))
				return new Variable(newStrs[i]);
		return this;
	}

	@Override
	public Expression simplified(Workspace heap) {
		if (heap != null && heap.containsKey(name))
			return heap.get(name).simplified(heap);
		else
			return this;
	}

	@Override
	public Image toImage() {
		return ImgUtils.horzCat(ImgUtils.drawString(name.substring(0, 1), true),
				ImgUtils.subS(ImgUtils.drawString(name.substring(1))));
	}

	@Override
	public String toString() {
		return name;
	}

}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Collections.Generic.List`1<UnityEngine.UIVertex>
struct List_1_t1317283468;

#include "codegen/il2cpp-codegen.h"

// System.Void UnityEngine.UI.ListPool`1<UnityEngine.UIVertex>::.cctor()
extern "C"  void ListPool_1__cctor_m3740250016_gshared (Il2CppObject * __this /* static, unused */, const MethodInfo* method);
#define ListPool_1__cctor_m3740250016(__this /* static, unused */, method) ((  void (*) (Il2CppObject * /* static, unused */, const MethodInfo*))ListPool_1__cctor_m3740250016_gshared)(__this /* static, unused */, method)
// System.Collections.Generic.List`1<T> UnityEngine.UI.ListPool`1<UnityEngine.UIVertex>::Get()
extern "C"  List_1_t1317283468 * ListPool_1_Get_m3130095824_gshared (Il2CppObject * __this /* static, unused */, const MethodInfo* method);
#define ListPool_1_Get_m3130095824(__this /* static, unused */, method) ((  List_1_t1317283468 * (*) (Il2CppObject * /* static, unused */, const MethodInfo*))ListPool_1_Get_m3130095824_gshared)(__this /* static, unused */, method)
// System.Void UnityEngine.UI.ListPool`1<UnityEngine.UIVertex>::Release(System.Collections.Generic.List`1<T>)
extern "C"  void ListPool_1_Release_m2709067242_gshared (Il2CppObject * __this /* static, unused */, List_1_t1317283468 * ___toRelease0, const MethodInfo* method);
#define ListPool_1_Release_m2709067242(__this /* static, unused */, ___toRelease0, method) ((  void (*) (Il2CppObject * /* static, unused */, List_1_t1317283468 *, const MethodInfo*))ListPool_1_Release_m2709067242_gshared)(__this /* static, unused */, ___toRelease0, method)
// System.Void UnityEngine.UI.ListPool`1<UnityEngine.UIVertex>::<s_ListPool>m__14(System.Collections.Generic.List`1<T>)
extern "C"  void ListPool_1_U3Cs_ListPoolU3Em__14_m3908991543_gshared (Il2CppObject * __this /* static, unused */, List_1_t1317283468 * ___l0, const MethodInfo* method);
#define ListPool_1_U3Cs_ListPoolU3Em__14_m3908991543(__this /* static, unused */, ___l0, method) ((  void (*) (Il2CppObject * /* static, unused */, List_1_t1317283468 *, const MethodInfo*))ListPool_1_U3Cs_ListPoolU3Em__14_m3908991543_gshared)(__this /* static, unused */, ___l0, method)


text:
using AbstractSyntax.Expression;
using AbstractSyntax.SpecialSymbol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractSyntax.Symbol
{
    [Serializable]
    public class AttributeSymbol : Scope
    {
        public AttributeType AttributeType { get; private set; }
        public AttributeTargets ValidOn { get; private set; }
        public bool IsAllowMultiple { get; private set; }
        public bool IsInheritable { get; private set; }

        public AttributeSymbol(AttributeType type, string name = null)
        {
            Name = name;
            AttributeType = type;
            ValidOn = AttributeTargets.All;
        }
    }

    //todo 単純なフラグ管理で属性を扱うようにリファクタリングする。
    public enum AttributeType
    {
        Unknown,
        Custom,
        Contravariant,
        Covariant,
        ConstructorConstraint,
        ValueConstraint,
        ReferenceConstraint,
        Variadic,
        Optional,
        GlobalScope,
        Abstract,
        Virtual,
        Final,
        Static,
        Public,
        Internal,
        Protected,
        Private,
    }
}


text:
/*
 * 作者:钟勋 (e-mail:zhongxunking@163.com)
 */

/*
 * 修订记录:
 * @author 钟勋 2019-09-05 23:31 创建
 */
package org.antframework.configcenter.facade.result;

import lombok.Getter;
import lombok.Setter;
import org.antframework.common.util.facade.AbstractResult;
import org.antframework.configcenter.facade.info.PropertyChange;

/**
 * 计算分支合并result
 */
@Getter
@Setter
public class ComputeBranchMergenceResult extends AbstractResult {
    // 配置变动
    private PropertyChange propertyChange;
}


text:
class TrackTransformer
  include Transformers::Base

  def self.matches?(subject)
    subject.class == Track
  end
end


text:
package org.apache.hadoop.hdfs.server.namenode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.net.Node;

public class TestReplicationPolicy extends TestCase {
  private static final int BLOCK_SIZE = 1024;
  private static final int NUM_OF_DATANODES = 6;
  private static final Configuration CONF = new Configuration();
  private static final NetworkTopology cluster;
  private static final NameNode namenode;
  private static final ReplicationTargetChooser replicator;
  private static final DatanodeDescriptor dataNodes[] =
    new DatanodeDescriptor[] {
      new DatanodeDescriptor(new DatanodeID("h1:5020"), "/d1/r1"),
      new DatanodeDescriptor(new DatanodeID("h2:5020"), "/d1/r1"),
      new DatanodeDescriptor(new DatanodeID("h3:5020"), "/d1/r2"),
      new DatanodeDescriptor(new DatanodeID("h4:5020"), "/d1/r2"),
      new DatanodeDescriptor(new DatanodeID("h5:5020"), "/d2/r3"),
      new DatanodeDescriptor(new DatanodeID("h6:5020"), "/d2/r3")
    };

  private final static DatanodeDescriptor NODE =
    new DatanodeDescriptor(new DatanodeID("h7:5020"), "/d2/r4");

  static {
    try {
      FileSystem.setDefaultUri(CONF, "hdfs://localhost:0");
      CONF.set("dfs.http.address", "0.0.0.0:0");
      NameNode.format(CONF);
      namenode = new NameNode(CONF);
    } catch (IOException e) {
      e.printStackTrace();
      throw (RuntimeException)new RuntimeException().initCause(e);
    }
    FSNamesystem fsNamesystem = FSNamesystem.getFSNamesystem();
    replicator = fsNamesystem.replicator;
    cluster = fsNamesystem.clusterMap;
    // construct network topology
    for(int i=0; i<NUM_OF_DATANODES; i++) {
      cluster.add(dataNodes[i]);
    }
    for(int i=0; i<NUM_OF_DATANODES; i++) {
      dataNodes[i].updateHeartbeat(
          2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
          2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0);
    }
  }

  /**
   * In this testcase, client is dataNodes[0]. So the 1st replica should be
   * placed on dataNodes[0], the 2nd replica should be placed on
   * different rack and third should be placed on different node
   * of rack chosen for 2nd node.
   * The only excpetion is when the <i>numOfReplicas</i> is 2,
   * the 1st is on dataNodes[0] and the 2nd is on a different rack.
   * @throws Exception
   */
  public void testChooseTarget1() throws Exception {
    dataNodes[0].updateHeartbeat(
        2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
        FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 4); // overloaded

    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertEquals(targets[0], dataNodes[0]);

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertEquals(targets[0], dataNodes[0]);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      3, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    assertEquals(targets[0], dataNodes[0]);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]));

    targets = replicator.chooseTarget(
                                     4, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 4);
    assertEquals(targets[0], dataNodes[0]);
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]) ||
               cluster.isOnSameRack(targets[2], targets[3]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[2]));

    dataNodes[0].updateHeartbeat(
        2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
        FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0);
  }

  /**
   * In this testcase, client is dataNodes[0], but the dataNodes[1] is
   * not allowed to be chosen. So the 1st replica should be
   * placed on dataNodes[0], the 2nd replica should be placed on a different
   * rack, the 3rd should be on same rack as the 2nd replica, and the rest
   * should be placed on a third rack.
   * @throws Exception
   */
  public void testChooseTarget2() throws Exception {
    List<Node> excludedNodes;
    DatanodeDescriptor[] targets;

    excludedNodes = new ArrayList<Node>();
    excludedNodes.add(dataNodes[1]);
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], excludedNodes, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    excludedNodes.clear();
    excludedNodes.add(dataNodes[1]);
    targets = replicator.chooseTarget(
                                      1, dataNodes[0], excludedNodes, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertEquals(targets[0], dataNodes[0]);

    excludedNodes.clear();
    excludedNodes.add(dataNodes[1]);
    targets = replicator.chooseTarget(
                                      2, dataNodes[0], excludedNodes, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertEquals(targets[0], dataNodes[0]);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    excludedNodes.clear();
    excludedNodes.add(dataNodes[1]);
    targets = replicator.chooseTarget(
                                      3, dataNodes[0], excludedNodes, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    assertEquals(targets[0], dataNodes[0]);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]));

    excludedNodes.clear();
    excludedNodes.add(dataNodes[1]);
    targets = replicator.chooseTarget(
                                      4, dataNodes[0], excludedNodes, BLOCK_SIZE);
    assertEquals(targets.length, 4);
    assertEquals(targets[0], dataNodes[0]);
    for(int i=1; i<4; i++) {
      assertFalse(cluster.isOnSameRack(targets[0], targets[i]));
    }
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]) ||
               cluster.isOnSameRack(targets[2], targets[3]));
    assertFalse(cluster.isOnSameRack(targets[1], targets[3]));
  }

  /**
   * In this testcase, client is dataNodes[0], but dataNodes[0] is not qualified
   * to be chosen. So the 1st replica should be placed on dataNodes[1],
   * the 2nd replica should be placed on a different rack,
   * the 3rd replica should be placed on the same rack as the 2nd replica,
   * and the rest should be placed on the third rack.
   * @throws Exception
   */
  public void testChooseTarget3() throws Exception {
    // make data node 0 to be not qualified to choose
    dataNodes[0].updateHeartbeat(
        2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
        (FSConstants.MIN_BLOCKS_FOR_WRITE-1)*BLOCK_SIZE, 0); // no space

    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertEquals(targets[0], dataNodes[1]);

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertEquals(targets[0], dataNodes[1]);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      3, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    assertEquals(targets[0], dataNodes[1]);
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      4, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 4);
    assertEquals(targets[0], dataNodes[1]);
    for(int i=1; i<4; i++) {
      assertFalse(cluster.isOnSameRack(targets[0], targets[i]));
    }
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]) ||
               cluster.isOnSameRack(targets[2], targets[3]));
    assertFalse(cluster.isOnSameRack(targets[1], targets[3]));

    dataNodes[0].updateHeartbeat(
        2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
        FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0);
  }

  /**
   * In this testcase, client is dataNodes[0], but none of the nodes on rack 1
   * is qualified to be chosen. So the 1st replica should be placed on either
   * rack 2 or rack 3.
   * the 2nd replica should be placed on a different rack,
   * the 3rd replica should be placed on the same rack as the 1st replica,
   * @throws Exception
   */
  public void testChoooseTarget4() throws Exception {
    // make data node 0 & 1 to be not qualified to choose: not enough disk space
    for(int i=0; i<2; i++) {
      dataNodes[i].updateHeartbeat(
          2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
          (FSConstants.MIN_BLOCKS_FOR_WRITE-1)*BLOCK_SIZE, 0);
    }

    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertFalse(cluster.isOnSameRack(targets[0], dataNodes[0]));

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertFalse(cluster.isOnSameRack(targets[0], dataNodes[0]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      3, dataNodes[0], null, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    for(int i=0; i<3; i++) {
      assertFalse(cluster.isOnSameRack(targets[i], dataNodes[0]));
    }
    assertTrue(cluster.isOnSameRack(targets[0], targets[1]) ||
               cluster.isOnSameRack(targets[1], targets[2]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[2]));

    for(int i=0; i<2; i++) {
      dataNodes[i].updateHeartbeat(
          2*FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
          FSConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0);
    }
  }
  /**
   * In this testcase, client is is a node outside of file system.
   * So the 1st replica can be placed on any node.
   * the 2nd replica should be placed on a different rack,
   * the 3rd replica should be placed on the same rack as the 2nd replica,
   * @throws Exception
   */
  public void testChooseTarget5() throws Exception {
    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, NODE, null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, NODE, null, BLOCK_SIZE);
    assertEquals(targets.length, 1);

    targets = replicator.chooseTarget(
                                      2, NODE, null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      3, NODE, null, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    assertTrue(cluster.isOnSameRack(targets[1], targets[2]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));
  }

  /**
   * This testcase tests re-replication, when dataNodes[0] is already chosen.
   * So the 1st replica can be placed on random rack.
   * the 2nd replica should be placed on different node by same rack as
   * the 1st replica. The 3rd replica can be placed randomly.
   * @throws Exception
   */
  public void testRereplicate1() throws Exception {
    List<DatanodeDescriptor> chosenNodes = new ArrayList<DatanodeDescriptor>();
    chosenNodes.add(dataNodes[0]);
    DatanodeDescriptor[] targets;

    targets = replicator.chooseTarget(
                                      0, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertFalse(cluster.isOnSameRack(dataNodes[0], targets[0]));

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertTrue(cluster.isOnSameRack(dataNodes[0], targets[0]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[1]));

    targets = replicator.chooseTarget(
                                      3, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 3);
    assertTrue(cluster.isOnSameRack(dataNodes[0], targets[0]));
    assertFalse(cluster.isOnSameRack(targets[0], targets[2]));
  }

  /**
   * This testcase tests re-replication,
   * when dataNodes[0] and dataNodes[1] are already chosen.
   * So the 1st replica should be placed on a different rack than rack 1.
   * the rest replicas can be placed randomly,
   * @throws Exception
   */
  public void testRereplicate2() throws Exception {
    List<DatanodeDescriptor> chosenNodes = new ArrayList<DatanodeDescriptor>();
    chosenNodes.add(dataNodes[0]);
    chosenNodes.add(dataNodes[1]);

    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertFalse(cluster.isOnSameRack(dataNodes[0], targets[0]));

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertFalse(cluster.isOnSameRack(dataNodes[0], targets[0]));
    assertFalse(cluster.isOnSameRack(dataNodes[0], targets[1]));
  }

  /**
   * This testcase tests re-replication,
   * when dataNodes[0] and dataNodes[2] are already chosen.
   * So the 1st replica should be placed on the rack that the writer resides.
   * the rest replicas can be placed randomly,
   * @throws Exception
   */
  public void testRereplicate3() throws Exception {
    List<DatanodeDescriptor> chosenNodes = new ArrayList<DatanodeDescriptor>();
    chosenNodes.add(dataNodes[0]);
    chosenNodes.add(dataNodes[2]);

    DatanodeDescriptor[] targets;
    targets = replicator.chooseTarget(
                                      0, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 0);

    targets = replicator.chooseTarget(
                                      1, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertTrue(cluster.isOnSameRack(dataNodes[0], targets[0]));
    assertFalse(cluster.isOnSameRack(dataNodes[2], targets[0]));

    targets = replicator.chooseTarget(
                               1, dataNodes[2], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 1);
    assertTrue(cluster.isOnSameRack(dataNodes[2], targets[0]));
    assertFalse(cluster.isOnSameRack(dataNodes[0], targets[0]));

    targets = replicator.chooseTarget(
                                      2, dataNodes[0], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertTrue(cluster.isOnSameRack(dataNodes[0], targets[0]));

    targets = replicator.chooseTarget(
                               2, dataNodes[2], chosenNodes, null, BLOCK_SIZE);
    assertEquals(targets.length, 2);
    assertTrue(cluster.isOnSameRack(dataNodes[2], targets[0]));
  }

  /**
   * This testcase tests whether the value returned by
   * DFSUtil.getInvalidateWorkPctPerIteration() is positive
   */
  public void testGetInvalidateWorkPctPerIteration() {
    Configuration conf = new Configuration();
    float blocksInvalidateWorkPct = DFSUtil.getInvalidateWorkPctPerIteration(conf);
    assertTrue(blocksInvalidateWorkPct > 0);

    conf.set(DFSConfigKeys.DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION, "0.0");
    try {
      blocksInvalidateWorkPct = DFSUtil.getInvalidateWorkPctPerIteration(conf);
      fail("Should throw IllegalArgumentException.");
    } catch (IllegalArgumentException e) {
      // expected
    }

    conf.set(DFSConfigKeys.DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION, "0.5f");
    blocksInvalidateWorkPct = DFSUtil.getInvalidateWorkPctPerIteration(conf);
    assertEquals(blocksInvalidateWorkPct, 0.5f);
  }

  /**
   * This testcase tests whether the value returned by
   * DFSUtil.getReplWorkMultiplier() is positive
   */
  public void testGetReplWorkMultiplier() {
    Configuration conf = new Configuration();
    int blocksReplWorkMultiplier = DFSUtil.getReplWorkMultiplier(conf);
    assertTrue(blocksReplWorkMultiplier > 0);

    conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION, "-1");
    try {
      blocksReplWorkMultiplier = DFSUtil.getReplWorkMultiplier(conf);
      fail("Should throw IllegalArgumentException.");
    } catch (IllegalArgumentException e) {
      // expected
    }

    conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION, "3");
    blocksReplWorkMultiplier = DFSUtil.getReplWorkMultiplier(conf);
    assertEquals(blocksReplWorkMultiplier, 3);
  }

}


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

public class Program
{
    public static void Main()
    {
        bool canContinue = true;

        var playerScoresList = new Dictionary<string, int>();
        var playerCardsDrawn = new Dictionary<string, string>();

        while (canContinue)
        {
            var input = Console.ReadLine().Split(':');

            var name = input[0];

            if (name == "JOKER")
            {
                canContinue = false;
                break;
            }

            var currentCardsDrawn = input[1];

            if (!playerCardsDrawn.ContainsKey(name))
            {
                playerCardsDrawn[name] = string.Empty;
            }

            playerCardsDrawn[name] += currentCardsDrawn;
        }

        foreach (var playerCardsPair in playerCardsDrawn)
        {
            var currentPlayerName = playerCardsPair.Key;
            var currentPlayerAllCardsDrawnRaw = playerCardsPair.Value;
            var currentPlayerTotalScore = 0;

            var separators = new char[] { ',', ' ' };
            var currentPlayerAllCardsDrawn = currentPlayerAllCardsDrawnRaw.Split(separators, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();

            foreach (var card in currentPlayerAllCardsDrawn)
            {
                currentPlayerTotalScore += GetHandScore(card);
            }

            playerScoresList[currentPlayerName] = currentPlayerTotalScore;
        }

        foreach (var playerTotalScorePair in playerScoresList)
        {
            var currentPlayerName = playerTotalScorePair.Key;
            var currentPlayerTotalScore = playerTotalScorePair.Value;

            Console.WriteLine($"{currentPlayerName}: {currentPlayerTotalScore}");
        }
    }

    private static int GetHandScore(string card)
    {
        string power = card[0].ToString();
        string type = card[card.Length - 1].ToString();

        if (power == "1")
        {
            power = "10";
        }

        int powerAsNumber = 0;
        int typeAsNumber = 0;
        bool numberPower = int.TryParse(power, out powerAsNumber);

        if (!numberPower)
        {
            switch (power)
            {
                case "J":
                    powerAsNumber = 11;
                    break;
                case "Q":
                    powerAsNumber = 12;
                    break;
                case "K":
                    powerAsNumber = 13;
                    break;
                case "A":
                    powerAsNumber = 14;
                    break;
            }
        }

        switch (type)
        {
            case "S":
                typeAsNumber = 4; break;
            case "H":
                typeAsNumber = 3; break;
            case "D":
                typeAsNumber = 2; break;
            case "C":
                typeAsNumber = 1; break;
        }

        int cardPoints = powerAsNumber * typeAsNumber;
        return cardPoints;
    }
}


text:
var messageHandler;
if (typeof jQuery === 'undefined') jQuery = {};

// detect HTML5 slideshow type, set message handler
if      (typeof jQuery.deck !== 'undefined')        messageHandler = updateDeckJS;
else if (typeof Reveal !== 'undefined')             messageHandler = updateReveal;
else if (typeof impress !== 'undefined')            messageHandler = updateImpress;
else if (typeof jQuery.jmpress !== 'undefined')     messageHandler = updateJmpress;
else if (typeof jQuery.scrolldeck !== 'undefined')  messageHandler = updateScrollDeck;
else if (typeof Flowtime !== 'undefined')  			messageHandler = updateFlowtime;
else    messageHandler = updateGeneric;

// separated in case we want to differentiate in the future
function updateDeckJS(message) {
    console.log('updateDeckJS '+message);
    var e = jQuery.Event('keydown');
    e.which = parseInt(message,10);
    $(document).trigger(e);
}
function updateReveal(message) {
    console.log('updateReveal '+message);
    if      (message === '37')      Reveal.navigateLeft();
    else if (message === '38')      Reveal.navigateUp();
    else if (message === '39')      Reveal.navigateRight();
    else if (message === '40')      Reveal.navigateDown();
    else if (message === '27')      Reveal.toggleOverview();
    else if (message === 'goto:0')  Reveal.slide(0,0);
}
function updateImpress(message) {
    console.log('updateImpress '+message);
    if      (message === '37')   impress().prev();
    else if (message === '39')   impress().next();
    else if (message.indexOf('goto') !== -1) {
        if      (message === 'goto:0') impress().goto(0);
        else    impress().goto(message.replace('goto:',''));
    }
}
function updateJmpress(message) {
    console.log('updateJmpress '+message);
    var e = jQuery.Event('keydown');
    e.which = e.keyCode = parseInt(message,10);
    $(document).trigger(e);
}
function updateScrollDeck(message) {
    console.log('updateScrollDeck '+message);
    var e = jQuery.Event('keydown');
    e.which = e.keyCode = parseInt(message,10);
    $(document).trigger(e);
}
function updateGeneric(message) {
    console.log('updateGeneric '+message);
    var e = jQuery.Event('keydown');
    e.which = e.keyCode = parseInt(message,10);
    $(document).trigger(e);
}

var iosocket = io.connect();

iosocket.on('connect', function () {
    console.log('connected');
});

iosocket.on('message', function(message) {
    messageHandler(message);
});

iosocket.on('key down', function(data) {
    messageHandler("" +data.keyCode, data.shiftKey, data.altKey, data.ctrlKey, data.metaKey);
});

iosocket.on('key up', function(data) {
    messageHandler("" + data.keyCode, data.shiftKey, data.altKey, data.ctrlKey, data.metaKey);
});

iosocket.on('disconnect', function() {
    console.log('disconnected');
});


text:
package org.apache.hyracks.control.cc;

import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.hyracks.api.application.ICCApplication;
import org.apache.hyracks.api.application.IServiceContext;
import org.apache.hyracks.api.config.IConfigManager;
import org.apache.hyracks.api.config.Section;
import org.apache.hyracks.api.job.resource.DefaultJobCapacityController;
import org.apache.hyracks.api.job.resource.IJobCapacityController;
import org.apache.hyracks.control.common.controllers.CCConfig;
import org.apache.hyracks.control.common.controllers.ControllerConfig;
import org.apache.hyracks.control.common.controllers.NCConfig;

public class BaseCCApplication implements ICCApplication {
    private static final Logger LOGGER = Logger.getLogger(BaseCCApplication.class.getName());
    public static final ICCApplication INSTANCE = new BaseCCApplication();

    protected BaseCCApplication() {
    }

    @Override
    public void start(IServiceContext serviceCtx, String[] args) throws Exception {
        if (args.length > 0) {
            throw new IllegalArgumentException("Unrecognized argument(s): " + Arrays.toString(args));
        }
    }

    @Override
    public void stop() throws Exception {
        // no-op
    }

    @Override
    public void startupCompleted() throws Exception {
        // no-op
    }

    @Override
    public IJobCapacityController getJobCapacityController() {
        return DefaultJobCapacityController.INSTANCE;
    }

    @Override
    public void registerConfig(IConfigManager configManager) {
        configManager.addIniParamOptions(ControllerConfig.Option.CONFIG_FILE, ControllerConfig.Option.CONFIG_FILE_URL);
        configManager.addCmdLineSections(Section.CC, Section.COMMON);
        configManager.setUsageFilter(getUsageFilter());
        configManager.register(ControllerConfig.Option.class, CCConfig.Option.class, NCConfig.Option.class);
    }

    @Override
    public Object getApplicationContext() {
        return null;
    }

    protected void configureLoggingLevel(Level level) {
        LOGGER.info("Setting Hyracks log level to " + level);
        Logger.getLogger("org.apache.hyracks").setLevel(level);
    }

}


text:
var Browser, GmailDeleter, Unterproto, async, events;

Browser = require('zombie');

Unterproto = require('unterproto');

async = require('async');

events = require('events');

GmailDeleter = Unterproto.inherits({
  initialize: function(username, password) {
    this.browser = new Browser();
    this.username = username;
    return this.password = password;
  },
  emitInfo: function(message) {
    return this.emit('info', message);
  },
  getTitle: function() {
    return this.browser.query('title').innerHTML;
  },
  run: function(callback) {
    var _this = this;
    if (callback == null) {
      callback = function() {};
    }
    return async.series([this.logIn.bind(this), this.deleteAll.bind(this)], function(err, results) {
      if (err) {
        _this.emit('error', err);
      }
      return callback();
    });
  },
  logIn: function(callback) {
    var _this = this;
    return this.browser.visit('http://gmail.com', function(err) {
      var logInSiteTitle;
      if (err) {
        throw err;
      }
      logInSiteTitle = _this.getTitle();
      _this.browser.fill('Email', _this.username);
      _this.browser.fill('Passwd', _this.password);
      return _this.browser.pressButton('#signIn', function() {
        if (_this.getTitle() === logInSiteTitle) {
          callback(new Error('Login failed'));
          return;
        }
        _this.emitInfo('Login successful');
        return callback();
      });
    });
  },
  createWait: function(ms) {
    return function(callback) {
      this.emitInfo("Waiting for " + ms + " ms");
      return setTimeout(callback, ms);
    };
  },
  deleteAll: function(callback) {
    var deleteLoop, messagesDeleted,
      _this = this;
    messagesDeleted = 0;
    this.on('messagesDeleted', function(num) {
      messagesDeleted += num;
      return process.stdout.write('.');
    });
    deleteLoop = function(loopCallback) {
      return _this.deleteAllOnActivePage(function(err, res) {
        if (err) {
          return loopCallback(err);
        } else if (res) {
          return deleteLoop(callback);
        } else {
          return loopCallback();
        }
      });
    };
    this.emitInfo('Deleting (it will take a while)');
    return deleteLoop(function(err) {
      console.log('');
      _this.emitInfo("Messages deleted: " + messagesDeleted);
      return callback(err);
    });
  },
  deleteAllOnActivePage: function(callback) {
    var checkbox, checkboxes, messagesNum, _i, _len,
      _this = this;
    checkboxes = this.getMessageCheckboxes();
    messagesNum = checkboxes.length;
    if (!messagesNum) {
      callback(null, false);
      return;
    }
    for (_i = 0, _len = checkboxes.length; _i < _len; _i++) {
      checkbox = checkboxes[_i];
      checkbox.checked = true;
    }
    return this.browser.pressButton('input[type=submit][name=nvp_a_tr]', function() {
      _this.emit('messagesDeleted', messagesNum);
      return callback(null, true);
    });
  },
  getMessageCheckboxes: function() {
    return this.browser.document.querySelectorAll('form[name="f"] tr input[type=checkbox]');
  }
});

module.exports = GmailDeleter.inherits(Object.getPrototypeOf(new events.EventEmitter()));


text:
`client1.js` starts `admin` CA that publishes messages. It also subscribes to them.

`client2.js` starts `ca1` CA that subscribes to them.

When the client times out, and then we retry after a while, the pending notifications are not lost. They have been collected by the CA, and pushed to the client when it reconnects. See `caf_session` for details.


text:
<?php

/**
 * Admin general export manager.
 */
class GenExport_Main extends DynExportBase
{

    /**
     * Export class name
     *
     * @var string
     */
    public $sClassDo = "genExport_do";

    /**
     * Export ui class name
     *
     * @var string
     */
    public $sClassMain = "genExport_main";

    /**
     * Current class template name.
     *
     * @var string
     */
    protected $_sThisTemplate = "dyn_exportdefault.tpl";

    /**
     * Creates shop object, passes shop data to Smarty engine and returns name of
     * template file
     *
     * @return string
     */
    public function render()
    {
        $this->createMainExportView();

        return parent::render();
    }
}


text:
This software visualizes the breadth-first search or depth-first search for a triangular lattice or square lattice.

![Lattice Screenshot](/Lattice/Screenshot/TriangularBfs.jpg?raw=true "Lattice Screenshot")


text:
////////////////////////////////
// JsonResult : traitement réponse AJAX
////////////////////////////////

// var parsJson = function(json) {
// 	var rep = eval('(' + json + ')');
// 	ConsoleResult("######## Message retour (parsJson) : ", rep.result, true);
// 	return rep;
// }

var JsonResult = function(json) {
	ResponseArray = new Array();
	if(parseInt(json.status) != 200) {
		ConsoleResult('Erreur ', parseInt(json.status), true);
		ResponseArray["html"] = "
BAD RETURN "+parseInt(json.status)+"!!!
";
		return ResponseArray;
	} else ConsoleResult('Statut Retour ', parseInt(json.status), true);
	if(typeof json.responseText != "undefined") {
		ResponseArray = $.parseJSON(json.responseText);
		CR = new ConsoleResult();
		CR.add("Résultat : ", ResponseArray["result"]);
		CR.add("Message : ", ResponseArray["message"]);
		CR.add("Retour html : ", ResponseArray["html"].length);
		CR.show();
		return ResponseArray;
	} else {
		ResponseArray["html"] = "
BAD RETURN !!! json.responseText = undefined
";
		return ResponseArray;
	}
}

var modedev = false;
if(($("#modedev").val() == "dev") || ($("#modedev").val() == "test")) modedev = true;

// Affichage en console (uniquement en mode dev ou test)
// libelle :			libellé de l'information
// texte :				texte de l'information
// afficheToutDeSuite : affiche l'information aussitôt (sans appeler "show()")
// force :				affiche sans condition de mode (même si modedev=false)
var ConsoleResult = function(libelle, texte, afficheToutDeSuite, force) {
	var objCRparent = this;
	this.lib = Array();
	this.tx = Array();
	this.cpt = 0;
	this.frc = force;
	this.show = function(force) {
		if((modedev == true || objCRparent.frc == true || force == true) && objCRparent.lib.length > 0)
		for(i in objCRparent.lib) {
			console.log(objCRparent.lib[i],objCRparent.tx[i]);
		}
	}
	this.add = function(libelle, texte) {
		if(libelle && (texte != null)) {
			if(texte == false) texte = "(boolean) false";
			if(texte == true) texte = "(boolean) true";
			objCRparent.lib[objCRparent.cpt] = libelle+"";
			objCRparent.tx[objCRparent.cpt] = texte+"";
			objCRparent.cpt++;
		}
		return this.objCRparent;
	}
	if(libelle && texte) this.add(libelle, texte);
	if(afficheToutDeSuite == true) this.show();
}

ConsoleResult("mode DEV : ", modedev, true);

$.fn.tagName = function() {
	return this.get(0).tagName.toLowerCase();
}

/* **************************************************** */
/* MISES A JOUR BLOCS avec majZone
/* **************************************************** */
var majZone = function(zone) {
	// alert("Mise à jour "+zone);
	var nomZone = zone.replace("groupe", "");
	var $groupe = $('.'+"groupe"+nomZone);
	$groupe.each(function(){
		if($(this).hasClass("majZone")) { // il faut que la zone contienne la classe "majZone" !!!
			var $target = $(this).parent();
			var data = new Object();
			proto = $(this).attr('data-prototype').split("__");
			url = proto[0];
			data["methode"] = proto[1];
			$("input", $(this)).each(function() {
				nom = $(this).attr('class').replace(nomZone+"_", "");
				// alert(nom+" = "+$(this).val());
				data[nom] = $(this).val();
			});
			ConsoleResult("data send : ", data, true);
			$.ajax({
				type: "POST",
				url: url,
				data: data,
				error: function() {
					ConsoleResult("Désolé : ", "une erreur est survenue. Veuillez recommencer s.v.p.", true);
				}
			}).done( function(data) {
				ConsoleResult("Retour majZone : ", data, true);
				retour = $.parseJSON(data);
				if(retour.result == true) $target.html(retour.html);
			});
		}
	});
}

jQuery(document).ready(function($) {

	////////////////////////////////
	// personnalisation select   //
	// Chosen                   //
	/////////////////////////////
	$("select").attr("data-placeholder", "Selectionner...");
	$("select").chosen({
		no_results_text:'Aucun élément trouvé…',
		allow_single_deselect:true,
		disable_search_threshold:10,
		allow_single_deselect: true
	});

	////////////////////////////////
	// Formulaires dynammiques   //
	//////////////////////////////
	// $("body").on("change", ".dynform select, .dynform input", function() {
	// 	alert("Formulaire modifié");
	// });

	////////////////////////////////
	// Formulaires dynammiques   //
	//////////////////////////////
	// $("body").on("change", ".dynform select, .dynform input", function() {
	// 	alert("Formulaire modifié");
	// });

	$( ".datepicker" ).datepicker({
		// dates : futures uniquement et jusqu'à -1 mois
		minDate: "-1M",
		// minDate: 0,
		dateFormat: "dd-mm-yy"
	});

	$( ".datepicker2" ).datepicker({
		// dates : min - 1 mois / max + 1 mois et 10 jours
		minDate: "-1M",
		maxDate: "+1M +10D",
		dateFormat: "dd-mm-yy"
	});

	$( ".datepickerAll" ).datepicker({
		// toutes dates
		dateFormat: "dd-mm-yy"
	});

	// Initialisation du chemin
	tinyMCE.baseURL = $("#hiddenStuffs input#homepath").val().replace("app_dev.php/", "") + "bundles/acmegrouplabo/js/tinymce";
	tinyMCE.init({
		language : 'fr_FR',
		selector: 'form .richtexts',
		plugins: [
		    "advlist autolink lists link image charmap print preview anchor",
		    "searchreplace visualblocks code fullscreen",
		    "insertdatetime media table contextmenu paste"
		],
		toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
	});

	/* **************************************************** */
	/* Liens externes -> dans une nouvelle fenêtre
	/* **************************************************** */
	$(".URLext").on("click", function(event) {
		URL = $(this).attr("href");
		if(URL == undefined) URL = $(">a", this).first().attr("href");
		// alert(URL);
		window.open(URL);
		event.preventDefault();
		return false;
	});

	// Désactivation des liens sur les
	$("a").each(function() {
		if($(this).attr('href') == "#") {
			// $(this).css('cursor', 'default');
			$(this).addClass('disabled');
		}
	});
	// Désactivation des liens "disabled"
	$("body").on("click", ".disabled", function(event) {
		event.preventDefault();
		return false;
	});
	// Liens javascript:history.back();
	$("body").on("click", ".backpage", function() { history.back(); })
	$("body").on("click", ".homepage", function() {
		var homepath = $("#homepath").val();
		document.location = homepath;
	});

	/* **************************************************** */
	/* FANCYBOX
	/* **************************************************** */

	// FOND MODALES : légèrement bleuté
	var backgroundFCY = 'rgba(220, 240, 255, 0.60)';

	$('.fancybox').fancybox({
		openEffect	: 'fade',
		closeEffect	: 'fade',
        padding     : 6,
		helpers : {
			overlay : {
				css : {'background' : backgroundFCY}
			}
		}
	});

	$(".various").fancybox({
		// fitToView	: true,
		// closeBtn	: false,
		maxWidth	: 640,
		width		: 640,
		// height		: '50%',
		// autoSize	: true,
		closeClick	: false,
		openEffect	: 'fade',
		closeEffect	: 'fade',
		title 		: false,
        padding     : 6,
		helpers : {
			overlay : {
				css : {'background' : backgroundFCY}
			}
		}
	}).trigger('click');

	$(".youtubeFancy").fancybox({
		maxWidth	: 800,
		maxHeight	: 600,
		fitToView	: true,
		// width		: '70%',
		// height		: '70%',
		autoSize	: true,
		closeClick	: false,
		openEffect	: 'fade',
		closeEffect	: 'fade',
        padding     : 6,
		helpers : {
			overlay : {
				css : {'background' : backgroundFCY}
			}
		}
	});

	$("a.fancymd").fancybox({
		hideOnContentClick		: true,
		padding					: 4,
		// overlayColor			:'#00FF00',
		// overlayOpacity		: 0.7,
		transitionIn			:'elastic',
		transitionOut			:'elastic',
		zoomSpeedIn				: 300,
		zoomSpeedOut			: 300,
		minWidth				: 400,
		minHeight				: 300,
		maxWidth				: 800,
		maxHeight				: 600,
		fitToView				: true,
		// width				: 600,
		// height				: 400,
		type					:'ajax',
		helpers : {
			overlay : {
				css : {'background' : backgroundFCY}
			}
		}
	});

	/* **************************************************** */
	/* TINYMCE --> directeditor richtext
	/* **************************************************** */

	// Initialisation du chemin --> fait plus haut (pour formulaires)
	// tinyMCE.baseURL = $("#hiddenStuffs input#homepath").val().replace("app_dev.php/", "") + "bundles/acmegrouplabo/js/tinymce";

	// Sauvegarde son propore contenu
	var saveHtml = function(elem) {
		// CR = new ConsoleResult();
		// CR.add(elem.id, $("#"+elem.id).html());
		// CR.add(elem.id, $("#"+elem.id).attr('data-prototype'));
		// CR.show();
		$("#"+elem.id).data("texte", tinyMCE.html.Entities.decode($("#"+elem.id).html()));
		path = $("#"+elem.id).attr('data-prototype').split("___");
		$("#"+elem.id).data("pathSend", path[0]);
		$("#"+elem.id).data("pathShort", path[1]);
		$("#"+elem.id).data("pathGet", path[2]);
		$("#"+elem.id).removeAttr('data-prototype');
	}

	var saveTinyChanges = function(elem) {
		texte = tinyMCE.html.Entities.decode(elem.getContent());
		ConsoleResult("Path : ", $("#"+elem.id).data("pathSend"), true);
		ConsoleResult("Changement POST", elem.id + " : " + texte, true);
		// $("#"+elem.id).data("texte", tinyMCE.html.Entities.decode(elem.getContent()));
		$.ajax({
			type: "POST",
			url: $("#"+elem.id).data("pathSend"),
			data: {'data': texte},
			error: function() {
				ConsoleResult("Erreur : ", "changement", true);
			},
			success: function() {
				ConsoleResult("Succès : ", "chargement", true);
			}
		}).done( function(data) {
			retour = eval('('+data+')');
			ConsoleResult("Retour enregistrement : ", data, true);
			$("#"+elem.id).load($("#"+elem.id).data("pathShort"));
		});
	}

	tinyMCE.init({
		// language : 'fr_FR',
		selector: ".editableRich",
		inline: true,
		plugins: [
			"advlist autolink lists link image charmap print preview anchor",
			"searchreplace visualblocks code fullscreen",
			"insertdatetime media table contextmenu paste"
		],
		toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		// toolbar: "undo redo | styleselect | bold italic "
		setup : function(ed){
			saveHtml(ed);
			ed.on('blur', function(e) {
				if($("#"+ed.id).data("texte") != tinyMCE.html.Entities.decode(ed.getContent())) saveTinyChanges(ed);
			}).on('focus', function(e) {
				$("#"+ed.id).load($("#"+ed.id).data("pathGet"))
			}).on('click', function(e) {
				e.preventDefault();
				return false;
			});
		}
	});

	tinyMCE.init({
		selector: ".editable",
		inline: true,
		plugins: ["insertdatetime media contextmenu"],
		toolbar: "undo redo",
		menubar: false,
		setup : function(ed){
			saveHtml(ed);
			ed.on('blur', function(e) {
				if($("#"+ed.id).data("texte") != tinyMCE.html.Entities.decode(ed.getContent())) saveTinyChanges(ed);
			}).on('focus', function(e) {
				$("#"+ed.id).load($("#"+ed.id).data("pathGet"))
			}).on('click', function(e) {
				e.preventDefault();
				return false;
			});;
		}
	});

	tinyMCE.init({
		selector: ".editablePrix",
		inline: true,
		plugins: ["insertdatetime media contextmenu"],
		toolbar: false,
		menubar: false,
		setup : function(ed){
			saveHtml(ed);
			ed.on('blur', function(e) {
				if($("#"+ed.id).data("texte") != tinyMCE.html.Entities.decode(ed.getContent())) saveTinyChanges(ed);
			}).on('focus', function(e) {
				$("#"+ed.id).load($("#"+ed.id).data("pathGet"))
			}).on('click', function(e) {
				e.preventDefault();
				return false;
			});;
		}
	});

	var col = "#5F5"; // couleur highlight
	var clignote = function(elem) {
		// bgcol = $(elem).css("backgroundColor");
		bgcol = "transparent";
		$(elem)
			.animate({backgroundColor: col}, 200)
			.delay(200).animate({backgroundColor: bgcol}, 200)
			.delay(100).animate({backgroundColor: col}, 30)
			.delay(50).animate({backgroundColor: bgcol}, 50)
			.delay(50).animate({backgroundColor: col}, 30)
			.delay(50).animate({backgroundColor: bgcol}, 50);
	}
	var highlight = function(elem) {
		// bgcol = $(elem).css("backgroundColor");
		bgcol = "transparent";
		$(elem)
			.animate({backgroundColor: col}, 100)
			.delay(200)
			.animate({backgroundColor: bgcol}, 300);
	}

	// mémorise les données texte pour comparaison lors de changements
	$(".editable, .editableRich, .editablePrix").each(function() {
		// html = $(this).html();
		// if(html == null) html = "";
		// $(this).data("texte", html);
		clignote(this);
	});

	$("body").on("mouseenter", ".editable, .editableRich, .editablePrix", function() {
		highlight(this);
	});

	// $("body").on("focusout", ".editable, .editableRich, .editablePrix", function() {
	// 	if(!$(this).hasClass("mce-edit-focus")) {
	// 		newhtml = $(this).html();
	// 		if(newhtml == null) newhtml = "";
	// 		if(newhtml != $(this).data("texte")) {
	// 			// Le texte a été modifié : on le persiste en base de données
	// 			highlight(this);
	// 			alert("Texte modifié : \n" + $(this).data("texte") + "\ndevient\n" + newhtml);
	// 		}
	// 	}
	// });

	/* **************************************************** */
	/* ACTIONS SUR ENTITÉS
	/* **************************************************** */
	$('body').on("click", '.LaboAction', function(event) {
		test = $(this).attr("data-prototype").split("__");
		alert("Action : "+test[0]+" "+test[2]+" d'id = "+test[1]);
		event.preventDefault();
	});

	/* **************************************************** */
	/* GESTION DES MESSAGES EN POP-IN / MODALES
	/* **************************************************** */
	if($(".messages >p").length) {
		$(".messages").dialog({
			autoOpen: true,
			width: 380,
			height: "auto",
			minHeight: 120,
			maxHeight: 500,
			modal: true,
			closeText: 'Fermer',
			draggable: true,
			resizable: false,
			dialogClass: "testss",
			position: ["center", 250],
			// dialogClass: "RedTitleStuff",
			buttons: {
				"Fermer": function() {
					$(this).dialog("close");
				}
			}
		});
		setTimeout(function() { $(".messages").dialog('close'); }, 6000);
		$(".messages").bind('clickoutside', function(e) {
			$target = $(e.target);
			if (!$target.filter('.hint').length && !$target.filter('.hintclickicon').length) {
				$(this).dialog('close');
			}
		});
	}

});


text:
if [ -f "/home/vagrant/.provisioned_gridengine_execd" ]; then
  echo "[PROVISIONING] Already provisioned gridengine_execd..."
  exit 0
fi

######
######
######

# set provisioning checkpoint
touch /home/vagrant/.provisioned_gridengine_execd


text:
require "spec_helper"

describe Mongoid::Contexts::Enumerable do

  let(:person) do
    Person.new(:title => "Sir").tap do |person|
      10.times do |n|
        post_code = n % 3 == 0 ? 32250 : 60661
        person.addresses << Address.new(:number => n, :post_code => post_code, :street => "Upper Street #{n}")
      end
    end
  end

  describe "#limit" do

    it "returns the specified number of documents" do
      person.addresses.criteria.limit(5).size.should == 5
    end

  end

  describe "#paginate" do

    it "paginates the embedded documents" do
      addresses = person.addresses.paginate(:page => nil, :per_page => 5)
      addresses.current_page.should == 1
      addresses.size.should == 5
    end

  end

  describe "#order_by" do

    context "ascending" do
      it "sorts by a simple key" do
        person.addresses.order_by(:number.asc).
          map(&:number).should == (0..9).to_a
      end

      it "sorts by a compound key" do
        person.addresses.order_by(:post_code.asc, :number.asc).
          map(&:number).should == [0, 3, 6, 9, 1, 2, 4, 5, 7, 8]
      end
    end

    context "descending" do
      it "sorts by a simple key" do
        person.addresses.order_by(:number.desc).
          map(&:number).should == (0..9).to_a.reverse
      end

      it "sorts by a compound key" do
        person.addresses.order_by(:post_code.desc, :number.desc).
          map(&:number).should == [0, 3, 6, 9, 1, 2, 4, 5, 7, 8].reverse
      end
    end

    context "with ascending and descending" do
      it "sorts by ascending first" do
        person.addresses.order_by(:post_code.asc, :number.desc).
          map(&:number).should == [9, 6, 3, 0, 8, 7, 5, 4, 2, 1]
      end

      it "sorts by descending first" do
        person.addresses.order_by(:post_code.desc, :number.asc).
          map(&:number).should == [1, 2, 4, 5, 7, 8, 0, 3, 6, 9]
      end
    end

  end

  describe "#shift" do
    it "returns the first element" do
      person.addresses.criteria.shift.number.should == 0
    end

    it "skips to the next value" do
      criteria = person.addresses.criteria
      criteria.shift
      criteria.shift
      criteria.first.number.should == 2
    end
  end

  describe "#skip" do

    it "excludes the specified number of document" do
      person.addresses.criteria.skip(5).limit(10).
        map(&:number).should == [5, 6, 7, 8, 9]
    end

  end

end


text:
@interface NSXMLElement (Extensions)

- (NSXMLElement *)elementForName:(NSString *)name attributeName:(NSString *)attribute value:(NSString *)value;

@end


text:
<?php

$lang['welcome_title'] = "Accueil";

/* End of file upload_lang.php */
/* Location: ./system/language/french/welcome_lang.php */


text:
#ifndef _LIBTUI_PROGRESSBAR_HH_
#define _LIBTUI_PROGRESSBAR_HH_

#include "widget.hh"
#include "window.hh"
#include "tui.hh"

#include <chrono>
#include <mutex>
#include <thread>

namespace tui {
  class ProgressBar : public Widget {
  public:
    ProgressBar(Application *app);
    ~ProgressBar() {
      set_unknown_progress(false);
    }

    void set_locator(Locator locator) {
      this->locator = locator;
    }

  protected:
    virtual void draw() {
      WINDOW * cwin = this->get_window()->get_curses_window();
      if(unknown) {
        ::wmove(cwin, position.y, position.x);
        for(int i = 0; i < size.w; i++) {
          ::waddch(cwin, ' ');
        }
        std::lock_guard<std::mutex> lock(this->mutex);
        int sbw = size.w *mq_width/100;
        if(this->shift < 0) {
          ::wmove(cwin, position.y, position.x);
          for(int i = 0; i < sbw + shift; i++) {
            ::waddch(cwin, '#');
          }
        } else {
          if(shift + sbw > size.w) {
            ::wmove(cwin, position.y, position.x);
            for(int i = 0; i < (sbw + shift) - size.w; i++) {
              ::waddch(cwin, '#');
            }
          }
          ::wmove(cwin, position.y, position.x + shift);
          for(int i = shift; i < std::min(size.w, shift + sbw); i++) {
            ::waddch(cwin, '#');
          }
        }
      } else {
        // TODO - print progress bar
      }
    }
    virtual void parent_resize(Rectangle parent) {
      std::lock_guard<std::mutex> lock(this->mutex);
      std::tie(position, size) = locator(parent);
      ms_per_shift = 1000*100/(size.w * velocity);
    }

  public:
    void set_unknown_progress(bool is_unknown);

    void clock_procedure() {
      using ticker = std::chrono::steady_clock;
      auto tp = ticker::now();
      while(1) {
        {
          std::lock_guard<std::mutex> lock(this->mutex);
          if(this->unknown == false) return;
          this->shift++;
          if(this->shift >= size.w) this->shift -= size.w;
          tp += std::chrono::milliseconds(ms_per_shift);
        }
        app->call([this](){if(this->get_window()) this->get_window()->refresh();});
        std::this_thread::sleep_until(tp);
      }
    }
  protected:
    std::string text = "";
    std::string overflow_text = "...";
    int shift = 0;
    int value = 0;
    int maxvalue = 100;
    int velocity = 40;  // % paska na sekundę
    int mq_width = 30;  // % paska
    int ms_per_shift;
    bool unknown = false;
    Point position;
    Size size;
    Locator locator;
    std::mutex mutex;
    std::thread clock;
  };
}

#endif /* end of include guard: _LIBTUI_PROGRESSBAR_HH_ */


text:
USING_NS_CC;

#pragma mark - Public Interface

bool GameplayLayer::init() {
  if (!Layer::init()) {
    return false;
  }

  this->setName(PLAYER_TURN_GAMEPLAY_LAYER);
  this->setVisible(false);

  this->_setupChildren();
  this->_setupEventHandlers();

  return true;
}

void GameplayLayer::migrateDicesAndShow() {
  for (auto dice : Game::getInstance()->getActionDices()) {
    auto sprite = (ActionDiceSprite*) dice->getSprite();
    CC_SAFE_RETAIN(sprite);
    auto position = sprite->getParent()->getPosition();
    sprite->removeFromParent();

    auto newPosition = sprite->getPosition() + position;
    sprite->setPosition(newPosition);
    sprite->setOriginalPosition(newPosition);

    this->addChild(sprite);
    CC_SAFE_RELEASE(sprite);
  }

  this->runAction(Show::create());
}

void GameplayLayer::resetFreeBootUsed() {
  this->_getFreeBootSprite()->resetFreeBootUsed();
}

void GameplayLayer::resetDockableNodes() {
  this->_getDockableContainer()->resetDockableNodes();
}

void GameplayLayer::dockActionDice(ActionDiceSprite *actionDiceSprite) {
  Node* dockableNode;

  auto dockableNodes = this->_getDockableContainer()->getDockableNodes();
  dockableNodes.reverse();
  for (auto node : dockableNodes) {
    if (node->getChildren().size() == 0) {
      dockableNode = node;
      break;
    }
  }

  auto dispatcher = Director::getInstance()->getEventDispatcher();

  actionDiceSprite->dockOnNode(dockableNode);
  dispatcher->dispatchCustomEvent(EVT_ACTION_DICE_SPENT,
                                  actionDiceSprite->getDice());
}

#pragma mark - Private Interface

void GameplayLayer::_setupChildren() {
  this->addChild(this->_createFreeBootSprite());
  this->addChild(this->_createDockableContainer());
  this->addChild(this->_createFinalizarButton());
}

void GameplayLayer::_setupEventHandlers() {
  auto dispatcher = Director::getInstance()->getEventDispatcher();

  auto diceDragStartedCallback = CC_CALLBACK_1(GameplayLayer::_handleActionDiceDragStarted, this);
  this->setDiceDragStartedListener(
    dispatcher->addCustomEventListener(EVT_ACTION_DICE_DRAG_STARTED, diceDragStartedCallback)
  );

  auto diceDragMovedCallback = CC_CALLBACK_1(GameplayLayer::_handleActionDiceDragMoved, this);
  this->setDiceDragMovedListener(
    dispatcher->addCustomEventListener(EVT_ACTION_DICE_DRAG_MOVED, diceDragMovedCallback)
  );

  auto diceDragEndedCallback = CC_CALLBACK_1(GameplayLayer::_handleActionDiceDragEnded, this);
  this->setDiceDragEndedListener(
    dispatcher->addCustomEventListener(EVT_ACTION_DICE_DRAG_ENDED, diceDragEndedCallback)
  );
}

Sprite* GameplayLayer::_createFreeBootSprite() {
  auto sprite = FreeBootSprite::create();

  auto size = sprite->getContentSize() / 2;
  auto x = DOCK_MARGIN + size.width;
  auto y = this->getContentSize().height - (DOCK_MARGIN + size.height);

  sprite->setPosition(Vec2(x, y));

  return sprite;
}

DockableContainer* GameplayLayer::_createDockableContainer() {
  auto dockableContainer = DockableContainer::create();

  auto bootSprite = this->getChildByName(FREE_BOOT_SPRITE_NAME);
  auto bootSize = bootSprite->getContentSize();

  auto dockX = bootSprite->getPosition().x;
  auto dockY = bootSprite->getPosition().y - dockableContainer->getContentSize().height;

  dockableContainer->setPosition(Vec2(dockX, dockY));

  return dockableContainer;
}

Node* GameplayLayer::_createFinalizarButton() {
  auto button = EndTurnButton::create();

  auto size = button->getContentSize() / 2;
  auto x = this->getContentSize().width - (END_TURN_MARGIN + size.width);
  auto y = this->getContentSize().height - (END_TURN_MARGIN + size.height);

  button->setPosition(Vec2(x, y));

  return button;
}

FreeBootSprite* GameplayLayer::_getFreeBootSprite() {
  return (FreeBootSprite*) this->getChildByName(FREE_BOOT_SPRITE_NAME);
}

DockableContainer* GameplayLayer::_getDockableContainer() {
  return (DockableContainer*) this->getChildByName(DOCK_CONTAINER_NODE_NAME);
}

#pragma mark - Event Handlers

void GameplayLayer::_handleActionDiceDragStarted(EventCustom* event) {
  auto data = (ActionDiceDragData*) event->getUserData();
  auto sprite = data->getSprite();
  auto dice = sprite->getDice();

  sprite->startDragging();

  auto room = Game::getInstance()->getRoomForCharacterCoordinate();
  auto hasMonstersInRoom = room->getMonsters().size() > 0;

  auto handler = DiceDragHandlerFactory::getHandler(dice);
  handler->dragStarted(data, this, this->_getDockableContainer());
}

void GameplayLayer::_handleActionDiceDragMoved(EventCustom* event) {
  auto data = (ActionDiceDragData*) event->getUserData();
  auto sprite = data->getSprite();
  auto touch = data->getTouch();
  auto dice = sprite->getDice();

  auto touchLocation = this->convertTouchToNodeSpace(touch);
  sprite->setPosition(touchLocation);

  auto handler = DiceDragHandlerFactory::getHandler(dice);
  handler->dragMoved(data, this, this->_getDockableContainer());
}

void GameplayLayer::_handleActionDiceDragEnded(EventCustom* event) {
  auto data = (ActionDiceDragData*) event->getUserData();
  auto sprite = data->getSprite();
  auto dice = sprite->getDice();

  sprite->setLocalZOrder(sprite->getLocalZOrder() - DRAG_Z_ORDER_DELTA);

  OverlayUtil::removeOverlay(this);

  auto handler = DiceDragHandlerFactory::getHandler(dice);
  bool docked = handler->dragEnded(data, this, this->_getDockableContainer());

  if (!docked) {
    sprite->restoreOriginalPosition();
  }
}


text:
BlockImagePicker
=========

This BlockImagePickerController Class inherits form UIImagePickerController using blocks instead of delegate methods.

How To Use It
-------------

```objective-c

#import "BlockImagePickerController.h"

...

{
	...

	void (^finishingBlock)(UIImagePickerController *picker, NSDictionary *info, UIImage *originalImage, UIImage *editedImage) = ^(UIImagePickerController *picker, NSDictionary *info, UIImage *originalImage, UIImage *editedImage)
    {
        /*
        	Same as - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
        	but providing [info objectForKey:UIImagePickerControllerOriginalImage] as originalImage and [info objectForKey:UIImagePickerControllerEditedImage] as editedImage to make it easier to use
        */
    };
    void (^cancelingBlock)(UIImagePickerController *picker) = ^(UIImagePickerController *picker)
    {
    	/*
			Same as - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    	*/
    };
    BlockImagePickerController *blockImagePickerController = [[BlockImagePickerController alloc] initWithCameraSourceType:UIImagePickerControllerSourceTypeCamera
                                                                                onFinishingBlock:finishingBlock
                                                                                onCancelingBlock:cancelingBlock];

    void (^completionBlock)() = ^()
    {

    };
    [self presentViewController:blockImagePickerController animated:YES completion:completionBlock];

    ...
}

...

```


text:
App.UsersWidget = App.DataWidget.extend({

  className: 'users',

  url: '/users/count',

  tmpl: '
{{count}} users
'

});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syn. meth. fung. (Göttingen) 1: 135 (1801)

#### Original name
Geastrum hygrometricum Pers., 1801

### Remarks
null