text:
/*	$NetBSD: aml_memman.c,v 1.3 2009/01/18 09:46:59 lukem Exp $	*/

/*-
 * Copyright (c) 1999, 2000 Mitsuru IWASAKI <iwasaki@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	Id: aml_memman.c,v 1.10 2000/08/09 14:47:43 iwasaki Exp
 *	$FreeBSD: src/usr.sbin/acpi/amldb/aml/aml_memman.c,v 1.2 2000/11/09 06:24:45 iwasaki Exp $
 */
#include <sys/cdefs.h>
__RCSID("$NetBSD: aml_memman.c,v 1.3 2009/01/18 09:46:59 lukem Exp $");

/*
 * Generic Memory Management
 */

#include <sys/param.h>

#include <aml/aml_memman.h>

#ifndef _KERNEL
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#else /* _KERNEL */
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/malloc.h>
MALLOC_DEFINE(M_MEMMAN, "memman", "Generic and Simple Memory Management");
#endif /* !_KERNEL */

unsigned int	memid_unkown = 255;

static int		 manage_block(struct memman *memman, unsigned int id,
				      void *block, unsigned static_mem,
				      unsigned entries);
static int		 blockman_init(struct memman *memman, unsigned int id);
static void		 memman_flexsize_add_histogram(struct memman *memman,
						       size_t size,
						       int tolerance);
static int		 memman_comp_histogram_size(const void *a,
						    const void *b);
static void		 memman_sort_histogram_by_size(struct memman *memman);
static unsigned int	 memman_guess_memid(struct memman *memman, void *chunk);
static void		 memman_statistics_fixedsize(struct memman *memman);
static void		 memman_statistics_flexsize(struct memman *memman);

static int
manage_block(struct memman *memman, unsigned int id, void *block,
    unsigned static_mem, unsigned entries)
{
	unsigned int	i;
	size_t	alloc_size;
	void	*tmp, *realblock;
	struct	memman_blockman	*bmp;
	struct	memman_block *memblock;
	struct	memman_node *memnodes;

	bmp = &memman->blockman[id];
	alloc_size = MEMMAN_BLOCKNODE_SIZE(entries);

	if (static_mem) {
		tmp = (void *)block;
		realblock = (char *)block + alloc_size;
	} else {
		tmp = MEMMAN_SYSMALLOC(alloc_size);
		if (!tmp) {
			return (-1);
		}
		realblock = block;

		memman->allocated_mem += alloc_size;
		memman->salloc_called++;
	}

	memblock = (struct memman_block *)tmp;
	memnodes = (struct memman_node *)((char *)tmp + sizeof(struct memman_block));

	memblock->block = realblock;
	memblock->static_mem = static_mem;
	memblock->allocated = entries;
	memblock->available = entries;
	if (!static_mem) {
		alloc_size += roundup(bmp->size * entries, ROUNDUP_UNIT);
	}
	memblock->allocated_mem = alloc_size;
	LIST_INSERT_HEAD(&bmp->block_list, memblock, links);

	for (i = 0; i < entries; ++i) {
		memnodes[i].node = ((char *)realblock + (i * (bmp->size)));
		memnodes[i].memblock = memblock;
		LIST_INSERT_HEAD(&bmp->free_node_list, &memnodes[i], links);
	}
	bmp->available = entries;

	return (0);
}

static int
blockman_init(struct memman *memman, unsigned int id)
{
	int	status;
	struct	memman_blockman *bmp;

	bmp = &memman->blockman[id];
	bmp->initialized = 1;
	LIST_INIT(&bmp->block_list);
	LIST_INIT(&bmp->free_node_list);
	LIST_INIT(&bmp->occupied_node_list);
	status = manage_block(memman, id, bmp->initial_block,
	    1, MEMMAN_INITIAL_SIZE);
	return (status);
}

void *
memman_alloc(struct memman *memman, unsigned int id)
{
	size_t	alloc_size;
	void	*chunk, *block;
	struct	memman_blockman *bmp;
	struct	memman_node *memnode;

	if (memman->max_memid <= id) {
		printf("memman_alloc: invalid memory type id\n");
		return (NULL);
	}
	bmp = &memman->blockman[id];
	if (!bmp->initialized) {
		if (blockman_init(memman, id)) {
			goto malloc_fail;
		}
	}
	memman->alloc_called++;

	if (bmp->available == 0) {
		alloc_size = roundup(bmp->size * MEMMAN_INCR_SIZE,
		    ROUNDUP_UNIT);
		block = MEMMAN_SYSMALLOC(alloc_size);
		if (!block) {
			goto malloc_fail;
		}
		memman->required_mem += bmp->size * MEMMAN_INCR_SIZE;
		memman->allocated_mem += alloc_size;
		memman->salloc_called++;

		if (manage_block(memman, id, block, 0, MEMMAN_INCR_SIZE)) {
			goto malloc_fail;
		}
	}
	memnode = LIST_FIRST(&bmp->free_node_list);
	LIST_REMOVE(memnode, links);
	chunk = memnode->node;
	LIST_INSERT_HEAD(&bmp->occupied_node_list, memnode, links);
	memnode->memblock->available--;
	bmp->available--;

	return (chunk);

malloc_fail:
	printf("memman_alloc: could not allocate memory\n");
	return (NULL);
}

static void
memman_flexsize_add_histogram(struct memman *memman, size_t size,
    int tolerance)
{
	unsigned int i;
	int	gap;

	if (size == 0) {
		return;
	}
	for (i = 0; i < memman->flex_mem_histogram_ptr; i++) {
		gap = memman->flex_mem_histogram[i].mem_size - size;
		if (gap >= (tolerance * -1) && gap <= tolerance) {
			memman->flex_mem_histogram[i].count++;
			if (memman->flex_mem_histogram[i].mem_size < size) {
				memman->flex_mem_histogram[i].mem_size = size;
			}
			return;
		}
	}

	if (memman->flex_mem_histogram_ptr == MEMMAN_HISTOGRAM_SIZE) {
		memman_flexsize_add_histogram(memman, size, tolerance + 1);
		return;
	}
	i = memman->flex_mem_histogram_ptr;
	memman->flex_mem_histogram[i].mem_size = size;
	memman->flex_mem_histogram[i].count = 1;
	memman->flex_mem_histogram_ptr++;
}

static int
memman_comp_histogram_size(const void *a, const void *b)
{
	int	delta;

	delta = ((const struct memman_histogram *)a)->mem_size -
	    ((const struct memman_histogram *)b)->mem_size;
	return (delta);
}

static void
memman_sort_histogram_by_size(struct memman *memman)
{
	qsort(memman->flex_mem_histogram, memman->flex_mem_histogram_ptr,
	    sizeof(struct memman_histogram), memman_comp_histogram_size);
}

void *
memman_alloc_flexsize(struct memman *memman, size_t size)
{
	void	*mem;
	struct	memman_flexmem_info *info;

	if (size == 0) {
		return (NULL);
	}
	if ((mem = MEMMAN_SYSMALLOC(size)) != NULL) {	/* XXX */

		info = MEMMAN_SYSMALLOC(sizeof(struct memman_flexmem_info));
		if (info) {
			if (!memman->flex_mem_initialized) {
				LIST_INIT(&memman->flexmem_info_list);
				bzero(memman->flex_mem_histogram,
				    sizeof(struct memman_histogram));
				memman->flex_mem_initialized = 1;
			}
			info->addr = mem;
			info->mem_size = size;
			LIST_INSERT_HEAD(&memman->flexmem_info_list, info, links);
		}
		memman->flex_alloc_called++;
		memman->flex_salloc_called++;
		memman->flex_required_mem += size;
		memman->flex_allocated_mem += size;
		if (memman->flex_mem_size_min == 0 ||
		    memman->flex_mem_size_min > size) {
			memman->flex_mem_size_min = size;
		}
		if (memman->flex_mem_size_max < size) {
			memman->flex_mem_size_max = size;
		}
		if (memman->flex_peak_mem_usage <
		    (memman->flex_allocated_mem - memman->flex_reclaimed_mem)) {
			memman->flex_peak_mem_usage =
			    (memman->flex_allocated_mem - memman->flex_reclaimed_mem);
		}
		memman_flexsize_add_histogram(memman, size,
		    memman->flex_mem_histogram_initial_tolerance);
	}
	return (mem);
}

static unsigned int
memman_guess_memid(struct memman *memman, void *chunk)
{
	unsigned int	id;
	struct	memman_blockman *bmp;
	struct	memman_node *memnode;

	for (id = 0; id < memman->max_memid; id++) {
		bmp = &memman->blockman[id];
		if (!bmp->initialized) {
			if (blockman_init(memman, id)) {
				printf("memman_free: could not initialized\n");
			}
		}
		LIST_FOREACH(memnode, &bmp->occupied_node_list, links) {
			if (memnode->node == chunk) {
				return (id);	/* got it! */
			}
		}
	}
	return (memid_unkown);	/* gave up */
}

void
memman_free(struct memman *memman, unsigned int memid, void *chunk)
{
	unsigned int	id;
	unsigned	found;
	void	*block;
	struct	memman_blockman *bmp;
	struct	memman_block *memblock;
	struct	memman_node *memnode;

	id = memid;
	if (memid == memid_unkown) {
		id = memman_guess_memid(memman, chunk);
	}
	if (memman->max_memid <= id) {
		printf("memman_free: invalid memory type id\n");
		MEMMAN_SYSABORT();
		return;
	}
	bmp = &memman->blockman[id];
	if (!bmp->initialized) {
		if (blockman_init(memman, id)) {
			printf("memman_free: could not initialized\n");
		}
	}
	found = 0;
	LIST_FOREACH(memnode, &bmp->occupied_node_list, links) {
		if (memnode->node == chunk) {
			found = 1;
			break;
		}
	}
	if (!found) {
		printf("memman_free: invalid address\n");
		return;
	}
	memman->free_called++;

	LIST_REMOVE(memnode, links);
	memblock = memnode->memblock;
	memblock->available++;
	LIST_INSERT_HEAD(&bmp->free_node_list, memnode, links);
	bmp->available++;

	if (!memblock->static_mem &&
	    memblock->available == memblock->allocated) {
		LIST_FOREACH(memnode, &bmp->free_node_list, links) {
			if (memnode->memblock != memblock) {
				continue;
			}
			LIST_REMOVE(memnode, links);
			bmp->available--;
		}
		block = memblock->block;
		MEMMAN_SYSFREE(block);
		memman->sfree_called++;

		LIST_REMOVE(memblock, links);
		memman->sfree_called++;
		memman->reclaimed_mem += memblock->allocated_mem;
		MEMMAN_SYSFREE(memblock);
	}
}

void
memman_free_flexsize(struct memman *memman, void *chunk)
{
	struct	memman_flexmem_info *info;

	LIST_FOREACH(info, &memman->flexmem_info_list, links) {
		if (info->addr == chunk) {
			memman->flex_reclaimed_mem += info->mem_size;
			LIST_REMOVE(info, links);
			MEMMAN_SYSFREE(info);
			break;
		}
	}
	/* XXX */
	memman->flex_free_called++;
	memman->flex_sfree_called++;
	MEMMAN_SYSFREE(chunk);
}

void
memman_freeall(struct memman *memman)
{
	unsigned int id;
	void	*chunk;
	struct	memman_blockman *bmp;
	struct	memman_node *memnode;
	struct	memman_block *memblock;
	struct	memman_flexmem_info *info;

	for (id = 0; id < memman->max_memid; id++) {
		bmp = &memman->blockman[id];

		while ((memnode = LIST_FIRST(&bmp->occupied_node_list))) {
			chunk = memnode->node;
			printf("memman_freeall: fixed size (id = %u)\n", id);
			memman_free(memman, id, chunk);
		}
		while ((memblock = LIST_FIRST(&bmp->block_list))) {
			LIST_REMOVE(memblock, links);
			if (!memblock->static_mem) {
				memman->sfree_called++;
				memman->reclaimed_mem += memblock->allocated_mem;
				MEMMAN_SYSFREE(memblock);
			}
		}
		bmp->initialized = 0;
	}

	LIST_FOREACH(info, &memman->flexmem_info_list, links) {
		printf("memman_freeall: flex size (size = %zd, addr = %p)\n",
		    info->mem_size, info->addr);
		memman_free_flexsize(memman, info->addr);
	}
}

static void
memman_statistics_fixedsize(struct memman *memman)
{
	printf("  fixed size memory blocks\n");
	printf("    alloc():		%d times\n", memman->alloc_called);
	printf("    system malloc():	%d times\n", memman->salloc_called);
	printf("    free():		%d times\n", memman->free_called);
	printf("    system free():	%d times\n", memman->sfree_called);
	printf("    required memory:	%zd bytes\n", memman->required_mem);
	printf("    allocated memory:	%zd bytes\n", memman->allocated_mem);
	printf("    reclaimed memory:	%zd bytes\n", memman->reclaimed_mem);
}

static void
memman_statistics_flexsize(struct memman *memman)
{
	unsigned int	i;

	printf("  flexible size memory blocks\n");
	printf("    alloc():		%d times\n", memman->flex_alloc_called);
	printf("    system malloc():	%d times\n", memman->flex_salloc_called);
	printf("    free():		%d times\n", memman->flex_free_called);
	printf("    system free():	%d times\n", memman->flex_sfree_called);
	printf("    required memory:	%zd bytes\n", memman->flex_required_mem);
	printf("    allocated memory:	%zd bytes\n", memman->flex_allocated_mem);
	printf("    reclaimed memory:	%zd bytes\n", memman->flex_reclaimed_mem);
	printf("    peak memory usage:	%zd bytes\n", memman->flex_peak_mem_usage);
	printf("    min memory size:	%zd bytes\n", memman->flex_mem_size_min);
	printf("    max memory size:	%zd bytes\n", memman->flex_mem_size_max);
	printf("    avg memory size:	%zd bytes\n",
	    (memman->flex_alloc_called) ?
	    memman->flex_allocated_mem / memman->flex_alloc_called : 0);

	printf("    memory size histogram (%d entries):\n",
	    memman->flex_mem_histogram_ptr);
	printf("	size	count\n");
	memman_sort_histogram_by_size(memman);
	for (i = 0; i < memman->flex_mem_histogram_ptr; i++) {
		printf("	%zu	%d\n",
		    memman->flex_mem_histogram[i].mem_size,
		    memman->flex_mem_histogram[i].count);
	}
}

void
memman_statistics(struct memman *memman)
{
	printf("memman: reporting statistics\n");
	memman_statistics_fixedsize(memman);
	memman_statistics_flexsize(memman);
}

size_t
memman_memid2size(struct memman *memman, unsigned int id)
{
	if (memman->max_memid <= id) {
		printf("memman_alloc: invalid memory type id\n");
		return (0);
	}
	return (memman->blockman[id].size);
}


text:
const test = require('tape')
const nlp = require('./_lib')

test('acronyms', function (t) {
  let doc = nlp(`mr. and Mrs. Smith are in the FBI and the c.i.a.`)
  doc.acronyms().stripPeriods()
  t.equal(doc.text(), 'mr. and Mrs. Smith are in the FBI and the cia', 'no-periods')

  doc.acronyms().addPeriods().addPeriods().addPeriods().addPeriods()
  t.equal(doc.text(), 'mr. and Mrs. Smith are in the F.B.I. and the c.i.a.', 'one-period')

  t.end()
})

test('acronyms-more', function (t) {
  let doc = nlp('i work for the F.B.I. in Kansas.')
  doc.acronyms().stripPeriods()
  t.equal(doc.text(), 'i work for the FBI in Kansas.', 'strip-period')

  doc.acronyms().addPeriods()
  t.equal(doc.text(), 'i work for the F.B.I. in Kansas.', 'add-period')
  t.end()
})

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RodneCislo = RodneCislo;
exports.rodnecislo = rodnecislo;
// rodnecislo.js
// authors : Jakub Podlaha
// license : MIT
// repo: github.com/kub1x/rodnecislo
var GENDER = {
  MALE: 'MALE',
  FEMALE: 'FEMALE'
};
var MONTH_OFFSET = 1;
var DEFAULT_ADULTHOOD = 18;
var AGE_WHEN_BORN = 0;

function RodneCislo(value) {
  var _this = this;

  // PIN parts and Parsed birthdate
  var _yy, _mm, _dd, _xxx, _D, _M, _YYYY; // Gender

  var _gender = GENDER.MALE; // PIN attributes

  var _longFormat = false; // Validation

  var _error = null;

  this.year = function () {
    return _YYYY;
  };

  this.month = function () {
    return _M;
  };

  this.day = function () {
    return _D;
  };

  this.birthDate = function () {
    return new Date(_YYYY, _M, _D);
  };

  this.birthDateAsString = function () {
    return "".concat(_D, ".").concat(_M + MONTH_OFFSET, ".").concat(_YYYY);
  };

  this.dic = function () {
    return "CZ".concat(_yy).concat(_mm).concat(_dd).concat(_xxx);
  };

  this.gender = function () {
    return _gender;
  };

  this.isMale = function () {
    return _gender === GENDER.MALE;
  };

  this.isFemale = function () {
    return _gender === GENDER.FEMALE;
  };

  this.isValid = function () {
    return !_error && _this.age() >= AGE_WHEN_BORN;
  };

  this.isPossible = function () {
    return !_error;
  };

  this.error = function () {
    return _error;
  };

  this.isAdult = function () {
    var adulthood = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_ADULTHOOD;
    return _this.age() >= adulthood;
  };

  this.age = function () {
    // Current date parsed (ignoring +1 timezone)
    var now = new Date();
    var CYYYY = now.getFullYear();
    var CM = now.getMonth();
    var CD = now.getDate();
    var age = CYYYY - _YYYY;

    if (CM > _M) {
      return age;
    }

    if (CM < _M) {
      return --age;
    } // We're on the MONTH of the bday.
    // NOTE In Czech you reach certain age at the beginning of your birthday.

    return CD >= _D ? age : --age;
  };
  /**
   * with OR without slash '/' between date part and distinction part
   * with 3 OR 4 digits of distinction part
   */

  var RODNECISLO_RE = /^(\d\d)(\d\d)(\d\d)\/?(\d\d\d\d?)$/;
  var MATCH_YY = 1;
  var MATCH_MM = 2;
  var MATCH_DD = 3;
  var MATCH_XX = 4;
  var LONG_XX_LENGTH = 4;
  var BEGIN = 0;
  var LAST = -1;
  var MODULO = 11;
  var MODULO_RESULT = 0;
  var MODULO_EXCEPTION_VALUE = 10;
  var MODULO_EXCEPTION_CHECK = 0;

  function parseRawInput(inputText) {
    var match = RODNECISLO_RE.exec(inputText);

    if (!match) {
      _error = 'Didn\'t match RegEx';
      return false;
    }

    _longFormat = match[MATCH_XX].length === LONG_XX_LENGTH;
    var whole, test, check;

    try {
      // Birth date parsed
      _yy = match[MATCH_YY];
      _mm = match[MATCH_MM];
      _dd = match[MATCH_DD];
      _xxx = match[MATCH_XX];

      if (_longFormat) {
        whole = "".concat(match[MATCH_YY]).concat(match[MATCH_MM]).concat(match[MATCH_DD]).concat(match[MATCH_XX]);
        test = +whole.slice(BEGIN, LAST); // all but last

        check = +whole.slice(LAST); // the last digit

        whole = +whole; // all of it
      }
    } catch (e) {
      _error = 'Failed to parse input string';
      return false;
    }

    if (_longFormat) {
      if (whole % MODULO === MODULO_RESULT) {// good old classic
      } else if (test % MODULO === MODULO_EXCEPTION_VALUE && check === MODULO_EXCEPTION_CHECK) {// the rare 1000 cases
      } else {
        _error = 'Failed the modulo condition';
        return false;
      }
    }

    return true;
  }

  var YEAR53 = 53;
  var CENT19 = 1900;
  var CENT20 = 2000;
  var YEAR2004 = 2004;
  var WOMAN_MM_ADDITION = 50;
  var EXTRA_MM_ADDITION = 20;

  function parseBirthYear() {
    _YYYY = +_yy;

    if (!_longFormat && _YYYY <= YEAR53) {
      // since ever - 31.12.1953
      _YYYY += CENT19;
    } else if (_longFormat && _YYYY > YEAR53) {
      // 1.1.1954 - 31.12.1999
      _YYYY += CENT19;
    } else if (_longFormat && _YYYY <= YEAR53) {
      // 1.1.2000 - 31.12.2053
      _YYYY += CENT20;
    } else {
      // NOTE This never happends as it would be the same as for 1954-2000
      // 1.1.2054 - until ever
      _error = 'We didn\'t think about this yet...';
      return false;
    }

    return true;
  }

  function parseBirthMonth() {
    // Month and Gender
    _M = +_mm; // Women have month + 50

    if (_M > WOMAN_MM_ADDITION) {
      _gender = GENDER.FEMALE;
      _M %= WOMAN_MM_ADDITION;
    } // Sometimes men/women get extra month + 20

    if (_M > EXTRA_MM_ADDITION) {
      if (_YYYY >= YEAR2004) {
        _M %= EXTRA_MM_ADDITION;
      } else {
        // NOTE
        _error = 'Addition of month+20 is allowed for year >= 2004 only.';
        return false;
      }
    } // Ok

    _M -= MONTH_OFFSET;
    _D = +_dd;
    return true;
  }

  function doesBirthdateExist() {
    var date = new Date(_YYYY, _M, _D);
    var convertedDate = "".concat(date.getFullYear(), "-").concat(date.getMonth(), "-").concat(date.getDate());
    var givenDate = "".concat(_YYYY, "-").concat(_M, "-").concat(_D); // Final birthdate validation

    if (givenDate !== convertedDate) {
      _error = 'Invalid birth date';
      return false;
    }

    return true;
  }

  function parseBirthDate() {
    return parseBirthYear() && parseBirthMonth() && doesBirthdateExist();
  }

  parseRawInput(value);
  parseBirthDate();
  return this;
} // RodneCislo

function rodnecislo(value) {
  return new RodneCislo(value);
}


text:
package org.apache.hadoop.hbase.regionserver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;

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

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CoordinatedStateManager;
import org.apache.hadoop.hbase.CoordinatedStateManagerFactory;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.Server;
import org.apache.hadoop.hbase.SmallTests;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.wal.HLog;
import org.apache.hadoop.hbase.regionserver.wal.HLogFactory;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.zookeeper.KeeperException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;

import com.google.common.collect.ImmutableList;

/**
 * Test the {@link RegionMergeTransaction} class against two HRegions (as
 * opposed to running cluster).
 */
@Category(SmallTests.class)
public class TestRegionMergeTransaction {
  private final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private final Path testdir = TEST_UTIL.getDataTestDir(this.getClass()
      .getName());
  private HRegion region_a;
  private HRegion region_b;
  private HRegion region_c;
  private HLog wal;
  private FileSystem fs;
  // Start rows of region_a,region_b,region_c
  private static final byte[] STARTROW_A = new byte[] { 'a', 'a', 'a' };
  private static final byte[] STARTROW_B = new byte[] { 'g', 'g', 'g' };
  private static final byte[] STARTROW_C = new byte[] { 'w', 'w', 'w' };
  private static final byte[] ENDROW = new byte[] { '{', '{', '{' };
  private static final byte[] CF = HConstants.CATALOG_FAMILY;

  @Before
  public void setup() throws IOException {
    this.fs = FileSystem.get(TEST_UTIL.getConfiguration());
    this.fs.delete(this.testdir, true);
    this.wal = HLogFactory.createHLog(fs, this.testdir, "logs",
        TEST_UTIL.getConfiguration());
    this.region_a = createRegion(this.testdir, this.wal, STARTROW_A, STARTROW_B);
    this.region_b = createRegion(this.testdir, this.wal, STARTROW_B, STARTROW_C);
    this.region_c = createRegion(this.testdir, this.wal, STARTROW_C, ENDROW);
    assert region_a != null && region_b != null && region_c != null;
    TEST_UTIL.getConfiguration().setBoolean("hbase.testing.nocluster", true);
  }

  @After
  public void teardown() throws IOException {
    for (HRegion region : new HRegion[] { region_a, region_b, region_c }) {
      if (region != null && !region.isClosed()) region.close();
      if (this.fs.exists(region.getRegionFileSystem().getRegionDir())
          && !this.fs.delete(region.getRegionFileSystem().getRegionDir(), true)) {
        throw new IOException("Failed deleting of "
            + region.getRegionFileSystem().getRegionDir());
      }
    }
    if (this.wal != null)
      this.wal.closeAndDelete();
    this.fs.delete(this.testdir, true);
  }

  /**
   * Test straight prepare works. Tries to merge on {@link #region_a} and
   * {@link #region_b}
   * @throws IOException
   */
  @Test
  public void testPrepare() throws IOException {
    prepareOnGoodRegions();
  }

  private RegionMergeTransaction prepareOnGoodRegions() throws IOException {
    RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_b,
        false);
    RegionMergeTransaction spyMT = Mockito.spy(mt);
    doReturn(false).when(spyMT).hasMergeQualifierInMeta(null,
        region_a.getRegionName());
    doReturn(false).when(spyMT).hasMergeQualifierInMeta(null,
        region_b.getRegionName());
    assertTrue(spyMT.prepare(null));
    return spyMT;
  }

  /**
   * Test merging the same region
   */
  @Test
  public void testPrepareWithSameRegion() throws IOException {
    RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a,
        this.region_a, true);
    assertFalse("should not merge the same region even if it is forcible ",
        mt.prepare(null));
  }

  /**
   * Test merging two not adjacent regions under a common merge
   */
  @Test
  public void testPrepareWithRegionsNotAdjacent() throws IOException {
    RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a,
        this.region_c, false);
    assertFalse("should not merge two regions if they are adjacent except it is forcible",
        mt.prepare(null));
  }

  /**
   * Test merging two not adjacent regions under a compulsory merge
   */
  @Test
  public void testPrepareWithRegionsNotAdjacentUnderCompulsory()
      throws IOException {
    RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_c,
        true);
    RegionMergeTransaction spyMT = Mockito.spy(mt);
    doReturn(false).when(spyMT).hasMergeQualifierInMeta(null,
        region_a.getRegionName());
    doReturn(false).when(spyMT).hasMergeQualifierInMeta(null,
        region_c.getRegionName());
    assertTrue("Since focible is true, should merge two regions even if they are not adjacent",
        spyMT.prepare(null));
  }

  /**
   * Pass a reference store
   */
  @Test
  public void testPrepareWithRegionsWithReference() throws IOException {
    HStore storeMock = Mockito.mock(HStore.class);
    when(storeMock.hasReferences()).thenReturn(true);
    when(storeMock.getFamily()).thenReturn(new HColumnDescriptor("cf"));
    when(storeMock.close()).thenReturn(ImmutableList.<StoreFile>of());
    this.region_a.stores.put(Bytes.toBytes(""), storeMock);
    RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a,
        this.region_b, false);
    assertFalse(
        "a region should not be mergeable if it has instances of store file references",
        mt.prepare(null));
  }

  @Test
  public void testPrepareWithClosedRegion() throws IOException {
    this.region_a.close();
    RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a,
        this.region_b, false);
    assertFalse(mt.prepare(null));
  }

  /**
   * Test merging regions which are merged regions and has reference in hbase:meta all
   * the same
   */
  @Test
  public void testPrepareWithRegionsWithMergeReference() throws IOException {
    RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_b,
        false);
    RegionMergeTransaction spyMT = Mockito.spy(mt);
    doReturn(true).when(spyMT).hasMergeQualifierInMeta(null,
        region_a.getRegionName());
    doReturn(true).when(spyMT).hasMergeQualifierInMeta(null,
        region_b.getRegionName());
    assertFalse(spyMT.prepare(null));
  }

  @Test
  public void testWholesomeMerge() throws IOException, InterruptedException {
    final int rowCountOfRegionA = loadRegion(this.region_a, CF, true);
    final int rowCountOfRegionB = loadRegion(this.region_b, CF, true);
    assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0);
    assertEquals(rowCountOfRegionA, countRows(this.region_a));
    assertEquals(rowCountOfRegionB, countRows(this.region_b));

    // Start transaction.
    RegionMergeTransaction mt = prepareOnGoodRegions();

    // Run the execute. Look at what it returns.
    TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0);
    CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager(
      TEST_UTIL.getConfiguration());
    Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp);
    HRegion mergedRegion = mt.execute(mockServer, null);
    // Do some assertions about execution.
    assertTrue(this.fs.exists(mt.getMergesDir()));
    // Assert region_a and region_b is closed.
    assertTrue(region_a.isClosed());
    assertTrue(region_b.isClosed());

    // Assert mergedir is empty -- because its content will have been moved out
    // to be under the merged region dirs.
    assertEquals(0, this.fs.listStatus(mt.getMergesDir()).length);
    // Check merged region have correct key span.
    assertTrue(Bytes.equals(this.region_a.getStartKey(),
        mergedRegion.getStartKey()));
    assertTrue(Bytes.equals(this.region_b.getEndKey(),
        mergedRegion.getEndKey()));
    // Count rows. merged region are already open
    try {
      int mergedRegionRowCount = countRows(mergedRegion);
      assertEquals((rowCountOfRegionA + rowCountOfRegionB),
          mergedRegionRowCount);
    } finally {
      HRegion.closeHRegion(mergedRegion);
    }
    // Assert the write lock is no longer held on region_a and region_b
    assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread());
    assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread());
  }

  @Test
  public void testRollback() throws IOException, InterruptedException {
    final int rowCountOfRegionA = loadRegion(this.region_a, CF, true);
    final int rowCountOfRegionB = loadRegion(this.region_b, CF, true);
    assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0);
    assertEquals(rowCountOfRegionA, countRows(this.region_a));
    assertEquals(rowCountOfRegionB, countRows(this.region_b));

    // Start transaction.
    RegionMergeTransaction mt = prepareOnGoodRegions();

    when(mt.createMergedRegionFromMerges(region_a, region_b,
        mt.getMergedRegionInfo())).thenThrow(
        new MockedFailedMergedRegionCreation());

    // Run the execute. Look at what it returns.
    boolean expectedException = false;
    TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0);
    CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager(
      TEST_UTIL.getConfiguration());
    Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp);
    try {
      mt.execute(mockServer, null);
    } catch (MockedFailedMergedRegionCreation e) {
      expectedException = true;
    }
    assertTrue(expectedException);
    // Run rollback
    assertTrue(mt.rollback(null, null));

    // Assert I can scan region_a and region_b.
    int rowCountOfRegionA2 = countRows(this.region_a);
    assertEquals(rowCountOfRegionA, rowCountOfRegionA2);
    int rowCountOfRegionB2 = countRows(this.region_b);
    assertEquals(rowCountOfRegionB, rowCountOfRegionB2);

    // Assert rollback cleaned up stuff in fs
    assertTrue(!this.fs.exists(HRegion.getRegionDir(this.testdir,
        mt.getMergedRegionInfo())));

    assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread());
    assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread());

    // Now retry the merge but do not throw an exception this time.
    assertTrue(mt.prepare(null));
    HRegion mergedRegion = mt.execute(mockServer, null);
    // Count rows. daughters are already open
    // Count rows. merged region are already open
    try {
      int mergedRegionRowCount = countRows(mergedRegion);
      assertEquals((rowCountOfRegionA + rowCountOfRegionB),
          mergedRegionRowCount);
    } finally {
      HRegion.closeHRegion(mergedRegion);
    }
    // Assert the write lock is no longer held on region_a and region_b
    assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread());
    assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread());
  }

  @Test
  public void testFailAfterPONR() throws IOException, KeeperException, InterruptedException {
    final int rowCountOfRegionA = loadRegion(this.region_a, CF, true);
    final int rowCountOfRegionB = loadRegion(this.region_b, CF, true);
    assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0);
    assertEquals(rowCountOfRegionA, countRows(this.region_a));
    assertEquals(rowCountOfRegionB, countRows(this.region_b));

    // Start transaction.
    RegionMergeTransaction mt = prepareOnGoodRegions();
    Mockito.doThrow(new MockedFailedMergedRegionOpen())
        .when(mt)
        .openMergedRegion((Server) Mockito.anyObject(),
            (RegionServerServices) Mockito.anyObject(),
            (HRegion) Mockito.anyObject());

    // Run the execute. Look at what it returns.
    boolean expectedException = false;
    TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0);
    CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager(
      TEST_UTIL.getConfiguration());
    Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp);
    try {
      mt.execute(mockServer, null);
    } catch (MockedFailedMergedRegionOpen e) {
      expectedException = true;
    }
    assertTrue(expectedException);
    // Run rollback returns false that we should restart.
    assertFalse(mt.rollback(null, null));
    // Make sure that merged region is still in the filesystem, that
    // they have not been removed; this is supposed to be the case if we go
    // past point of no return.
    Path tableDir = this.region_a.getRegionFileSystem().getRegionDir()
        .getParent();
    Path mergedRegionDir = new Path(tableDir, mt.getMergedRegionInfo()
        .getEncodedName());
    assertTrue(TEST_UTIL.getTestFileSystem().exists(mergedRegionDir));
  }

  @Test
  public void testMeregedRegionBoundary() {
    TableName tableName =
        TableName.valueOf("testMeregedRegionBoundary");
    byte[] a = Bytes.toBytes("a");
    byte[] b = Bytes.toBytes("b");
    byte[] z = Bytes.toBytes("z");
    HRegionInfo r1 = new HRegionInfo(tableName);
    HRegionInfo r2 = new HRegionInfo(tableName, a, z);
    HRegionInfo m = RegionMergeTransaction.getMergedRegionInfo(r1, r2);
    assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey())
        && Bytes.equals(m.getEndKey(), r1.getEndKey()));

    r1 = new HRegionInfo(tableName, null, a);
    r2 = new HRegionInfo(tableName, a, z);
    m = RegionMergeTransaction.getMergedRegionInfo(r1, r2);
    assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey())
        && Bytes.equals(m.getEndKey(), r2.getEndKey()));

    r1 = new HRegionInfo(tableName, null, a);
    r2 = new HRegionInfo(tableName, z, null);
    m = RegionMergeTransaction.getMergedRegionInfo(r1, r2);
    assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey())
        && Bytes.equals(m.getEndKey(), r2.getEndKey()));

    r1 = new HRegionInfo(tableName, a, z);
    r2 = new HRegionInfo(tableName, z, null);
    m = RegionMergeTransaction.getMergedRegionInfo(r1, r2);
    assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey())
      && Bytes.equals(m.getEndKey(), r2.getEndKey()));

    r1 = new HRegionInfo(tableName, a, b);
    r2 = new HRegionInfo(tableName, b, z);
    m = RegionMergeTransaction.getMergedRegionInfo(r1, r2);
    assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey())
      && Bytes.equals(m.getEndKey(), r2.getEndKey()));
  }

  /**
   * Exception used in this class only.
   */
  @SuppressWarnings("serial")
  private class MockedFailedMergedRegionCreation extends IOException {
  }

  @SuppressWarnings("serial")
  private class MockedFailedMergedRegionOpen extends IOException {
  }

  private HRegion createRegion(final Path testdir, final HLog wal,
      final byte[] startrow, final byte[] endrow)
      throws IOException {
    // Make a region with start and end keys.
    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("table"));
    HColumnDescriptor hcd = new HColumnDescriptor(CF);
    htd.addFamily(hcd);
    HRegionInfo hri = new HRegionInfo(htd.getTableName(), startrow, endrow);
    HRegion a = HRegion.createHRegion(hri, testdir,
        TEST_UTIL.getConfiguration(), htd);
    HRegion.closeHRegion(a);
    return HRegion.openHRegion(testdir, hri, htd, wal,
        TEST_UTIL.getConfiguration());
  }

  private int countRows(final HRegion r) throws IOException {
    int rowcount = 0;
    InternalScanner scanner = r.getScanner(new Scan());
    try {
      List<Cell> kvs = new ArrayList<Cell>();
      boolean hasNext = true;
      while (hasNext) {
        hasNext = scanner.next(kvs);
        if (!kvs.isEmpty())
          rowcount++;
      }
    } finally {
      scanner.close();
    }
    return rowcount;
  }

  /**
   * Load region with rows from 'aaa' to 'zzz', skip the rows which are out of
   * range of the region
   * @param r Region
   * @param f Family
   * @param flush flush the cache if true
   * @return Count of rows loaded.
   * @throws IOException
   */
  private int loadRegion(final HRegion r, final byte[] f, final boolean flush)
      throws IOException {
    byte[] k = new byte[3];
    int rowCount = 0;
    for (byte b1 = 'a'; b1 <= 'z'; b1++) {
      for (byte b2 = 'a'; b2 <= 'z'; b2++) {
        for (byte b3 = 'a'; b3 <= 'z'; b3++) {
          k[0] = b1;
          k[1] = b2;
          k[2] = b3;
          if (!HRegion.rowIsInRange(r.getRegionInfo(), k)) {
            continue;
          }
          Put put = new Put(k);
          put.add(f, null, k);
          if (r.getLog() == null)
            put.setDurability(Durability.SKIP_WAL);
          r.put(put);
          rowCount++;
        }
      }
      if (flush) {
        r.flushcache();
      }
    }
    return rowCount;
  }

}


text:
import {copy} from 'cerebral/operators'

export default [
  copy('input:title', 'state:app.newTodoTitle')
]


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class clusternodegroup_nslimitidentifier_binding(base_resource) :
	""" Binding class showing the nslimitidentifier that can be bound to clusternodegroup.
	"""
	def __init__(self) :
		self._identifiername = ""
		self._name = ""
		self.___count = 0

	@property
	def name(self) :
		"""Name of the nodegroup to which you want to bind a cluster node or an entity.
Minimum length =  1.
		"""
		try :
			return self._name
		except Exception as e:
			raise e

	@name.setter
	def name(self, name) :
		"""Name of the nodegroup to which you want to bind a cluster node or an entity.
Minimum length =  1
		"""
		try :
			self._name = name
		except Exception as e:
			raise e

	@property
	def identifiername(self) :
		"""stream identifier  and rate limit identifier that need to be bound to this nodegroup.
		"""
		try :
			return self._identifiername
		except Exception as e:
			raise e

	@identifiername.setter
	def identifiername(self, identifiername) :
		"""stream identifier  and rate limit identifier that need to be bound to this nodegroup.
		"""
		try :
			self._identifiername = identifiername
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(clusternodegroup_nslimitidentifier_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.clusternodegroup_nslimitidentifier_binding
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.name) :
				return str(self.name)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				updateresource = clusternodegroup_nslimitidentifier_binding()
				updateresource.name = resource.name
				updateresource.identifiername = resource.identifiername
				return updateresource.update_resource(client)
			else :
				if resource and len(resource) > 0 :
					updateresources = [clusternodegroup_nslimitidentifier_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						updateresources[i].name = resource[i].name
						updateresources[i].identifiername = resource[i].identifiername
				return cls.update_bulk_request(client, updateresources)
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		try :
			if resource and type(resource) is not list :
				deleteresource = clusternodegroup_nslimitidentifier_binding()
				deleteresource.name = resource.name
				deleteresource.identifiername = resource.identifiername
				return deleteresource.delete_resource(client)
			else :
				if resource and len(resource) > 0 :
					deleteresources = [clusternodegroup_nslimitidentifier_binding() for _ in range(len(resource))]
					for i in range(len(resource)) :
						deleteresources[i].name = resource[i].name
						deleteresources[i].identifiername = resource[i].identifiername
				return cls.delete_bulk_request(client, deleteresources)
		except Exception as e :
			raise e

	@classmethod
	def get(cls, service, name) :
		""" Use this API to fetch clusternodegroup_nslimitidentifier_binding resources.
		"""
		try :
			obj = clusternodegroup_nslimitidentifier_binding()
			obj.name = name
			response = obj.get_resources(service)
			return response
		except Exception as e:
			raise e

	@classmethod
	def get_filtered(cls, service, name, filter_) :
		""" Use this API to fetch filtered set of clusternodegroup_nslimitidentifier_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = clusternodegroup_nslimitidentifier_binding()
			obj.name = name
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			return response
		except Exception as e:
			raise e

	@classmethod
	def count(cls, service, name) :
		""" Use this API to count clusternodegroup_nslimitidentifier_binding resources configued on NetScaler.
		"""
		try :
			obj = clusternodegroup_nslimitidentifier_binding()
			obj.name = name
			option_ = options()
			option_.count = True
			response = obj.get_resources(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

	@classmethod
	def count_filtered(cls, service, name, filter_) :
		""" Use this API to count the filtered set of clusternodegroup_nslimitidentifier_binding resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = clusternodegroup_nslimitidentifier_binding()
			obj.name = name
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(service, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e:
			raise e

class clusternodegroup_nslimitidentifier_binding_response(base_response) :
	def __init__(self, length=1) :
		self.clusternodegroup_nslimitidentifier_binding = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.clusternodegroup_nslimitidentifier_binding = [clusternodegroup_nslimitidentifier_binding() for _ in range(length)]


text:
package com.emc.storageos.model.tenant;

import com.emc.storageos.model.NamedRelatedResourceRep;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name = "subtenants")
public class TenantOrgList {
    private List<NamedRelatedResourceRep> subtenants;

    public TenantOrgList() {
    }

    public TenantOrgList(List<NamedRelatedResourceRep> subtenants) {
        this.subtenants = subtenants;
    }

    /**
     * List of this tenant's subtenants.
     *
     * @return List of NamedRelatedResourceRep
     */
    @XmlElement(name = "subtenant")
    public List<NamedRelatedResourceRep> getSubtenants() {
        if (subtenants == null) {
            subtenants = new ArrayList<NamedRelatedResourceRep>();
        }
        return subtenants;
    }

    public void setSubtenants(List<NamedRelatedResourceRep> subtenants) {
        this.subtenants = subtenants;
    }
}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_NULLARY_FUNCTORS_H
#define EIGEN_NULLARY_FUNCTORS_H

namespace Eigen {

namespace internal {

template<typename Scalar>
struct scalar_constant_op {
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE scalar_constant_op(const scalar_constant_op& other) : m_other(other.m_other) { }
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE scalar_constant_op(const Scalar& other) : m_other(other) { }
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() () const { return m_other; }
  template<typename PacketType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const PacketType packetOp() const { return internal::pset1<PacketType>(m_other); }
  const Scalar m_other;
};
template<typename Scalar>
struct functor_traits<scalar_constant_op<Scalar> >
{ enum { Cost = 0 /* as the constant value should be loaded in register only once for the whole expression */,
         PacketAccess = packet_traits<Scalar>::Vectorizable, IsRepeatable = true }; };

template<typename Scalar> struct scalar_identity_op {
  EIGEN_EMPTY_STRUCT_CTOR(scalar_identity_op)
  template<typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (IndexType row, IndexType col) const { return row==col ? Scalar(1) : Scalar(0); }
};
template<typename Scalar>
struct functor_traits<scalar_identity_op<Scalar> >
{ enum { Cost = NumTraits<Scalar>::AddCost, PacketAccess = false, IsRepeatable = true }; };

template <typename Scalar, typename Packet, bool IsInteger> struct linspaced_op_impl;

template <typename Scalar, typename Packet>
struct linspaced_op_impl<Scalar,Packet,/*IsInteger*/false>
{
  linspaced_op_impl(const Scalar& low, const Scalar& high, Index num_steps) :
    m_low(low), m_high(high), m_size1(num_steps==1 ? 1 : num_steps-1), m_step(num_steps==1 ? Scalar() : (high-low)/Scalar(num_steps-1)),
    m_interPacket(plset<Packet>(0)),
    m_flip(std::abs(high)<std::abs(low))
  {}

  template<typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (IndexType i) const {
    if(m_flip)
      return (i==0)? m_low : (m_high - (m_size1-i)*m_step);
    else
      return (i==m_size1)? m_high : (m_low + i*m_step);
  }

  template<typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(IndexType i) const
  {
    // Principle:
    // [low, ..., low] + ( [step, ..., step] * ( [i, ..., i] + [0, ..., size] ) )
    if(m_flip)
    {
      Packet pi = padd(pset1<Packet>(Scalar(i-m_size1)),m_interPacket);
      Packet res = padd(pset1<Packet>(m_high), pmul(pset1<Packet>(m_step), pi));
      if(i==0)
        res = pinsertfirst(res, m_low);
      return res;
    }
    else
    {
      Packet pi = padd(pset1<Packet>(Scalar(i)),m_interPacket);
      Packet res = padd(pset1<Packet>(m_low), pmul(pset1<Packet>(m_step), pi));
      if(i==m_size1-unpacket_traits<Packet>::size+1)
        res = pinsertlast(res, m_high);
      return res;
    }
  }

  const Scalar m_low;
  const Scalar m_high;
  const Index m_size1;
  const Scalar m_step;
  const Packet m_interPacket;
  const bool m_flip;
};

template <typename Scalar, typename Packet>
struct linspaced_op_impl<Scalar,Packet,/*IsInteger*/true>
{
  linspaced_op_impl(const Scalar& low, const Scalar& high, Index num_steps) :
    m_low(low),
    m_multiplier((high-low)/convert_index<Scalar>(num_steps<=1 ? 1 : num_steps-1)),
    m_divisor(convert_index<Scalar>(num_steps+high-low)/(high-low+1)),
    m_use_divisor((high-low+1)<num_steps)
  {}

  template<typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
  const Scalar operator() (IndexType i) const
  {
    if(m_use_divisor) return m_low + convert_index<Scalar>(i)/m_divisor;
    else              return m_low + convert_index<Scalar>(i)*m_multiplier;
  }

  const Scalar m_low;
  const Scalar m_multiplier;
  const Scalar m_divisor;
  const bool m_use_divisor;
};

// ----- Linspace functor ----------------------------------------------------------------

// Forward declaration (we default to random access which does not really give
// us a speed gain when using packet access but it allows to use the functor in
// nested expressions).
template <typename Scalar, typename PacketType> struct linspaced_op;
template <typename Scalar, typename PacketType> struct functor_traits< linspaced_op<Scalar,PacketType> >
{
  enum
  {
    Cost = 1,
    PacketAccess =   (!NumTraits<Scalar>::IsInteger) && packet_traits<Scalar>::HasSetLinear && packet_traits<Scalar>::HasBlend,
                  /*&& ((!NumTraits<Scalar>::IsInteger) || packet_traits<Scalar>::HasDiv),*/ // <- vectorization for integer is currently disabled
    IsRepeatable = true
  };
};
template <typename Scalar, typename PacketType> struct linspaced_op
{
  linspaced_op(const Scalar& low, const Scalar& high, Index num_steps)
    : impl((num_steps==1 ? high : low),high,num_steps)
  {}

  template<typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (IndexType i) const { return impl(i); }

  template<typename Packet,typename IndexType>
  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(IndexType i) const { return impl.packetOp(i); }

  // This proxy object handles the actual required temporaries and the different
  // implementations (integer vs. floating point).
  const linspaced_op_impl<Scalar,PacketType,NumTraits<Scalar>::IsInteger> impl;
};

// Linear access is automatically determined from the operator() prototypes available for the given functor.
// If it exposes an operator()(i,j), then we assume the i and j coefficients are required independently
// and linear access is not possible. In all other cases, linear access is enabled.
// Users should not have to deal with this structure.
template<typename Functor> struct functor_has_linear_access { enum { ret = !has_binary_operator<Functor>::value }; };

// For unreliable compilers, let's specialize the has_*ary_operator
// helpers so that at least built-in nullary functors work fine.
#if !( (EIGEN_COMP_MSVC>1600) || (EIGEN_GNUC_AT_LEAST(4,8)) || (EIGEN_COMP_ICC>=1600))
template<typename Scalar,typename IndexType>
struct has_nullary_operator<scalar_constant_op<Scalar>,IndexType> { enum { value = 1}; };
template<typename Scalar,typename IndexType>
struct has_unary_operator<scalar_constant_op<Scalar>,IndexType> { enum { value = 0}; };
template<typename Scalar,typename IndexType>
struct has_binary_operator<scalar_constant_op<Scalar>,IndexType> { enum { value = 0}; };

template<typename Scalar,typename IndexType>
struct has_nullary_operator<scalar_identity_op<Scalar>,IndexType> { enum { value = 0}; };
template<typename Scalar,typename IndexType>
struct has_unary_operator<scalar_identity_op<Scalar>,IndexType> { enum { value = 0}; };
template<typename Scalar,typename IndexType>
struct has_binary_operator<scalar_identity_op<Scalar>,IndexType> { enum { value = 1}; };

template<typename Scalar, typename PacketType,typename IndexType>
struct has_nullary_operator<linspaced_op<Scalar,PacketType>,IndexType> { enum { value = 0}; };
template<typename Scalar, typename PacketType,typename IndexType>
struct has_unary_operator<linspaced_op<Scalar,PacketType>,IndexType> { enum { value = 1}; };
template<typename Scalar, typename PacketType,typename IndexType>
struct has_binary_operator<linspaced_op<Scalar,PacketType>,IndexType> { enum { value = 0}; };

template<typename Scalar,typename IndexType>
struct has_nullary_operator<scalar_random_op<Scalar>,IndexType> { enum { value = 1}; };
template<typename Scalar,typename IndexType>
struct has_unary_operator<scalar_random_op<Scalar>,IndexType> { enum { value = 0}; };
template<typename Scalar,typename IndexType>
struct has_binary_operator<scalar_random_op<Scalar>,IndexType> { enum { value = 0}; };
#endif

} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_NULLARY_FUNCTORS_H


text:
/**
 * Created by dd on 11/24/14.
 */

isNumber = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
};

strToId = function(raw) {
    return raw.replace(/[^\w\s]|_/g, "").replace(/\s+/g, "-");
};

setValuePath = function(object, path, value) {
    var a = path.split('.');
    var o = object;
    for (var i = 0; i < a.length - 1; i++) {
        var n = a[i];
        if (n in o) {
            o = o[n];
        } else {
            o[n] = {};
            o = o[n];
        }
    }
    o[a[a.length - 1]] = value;
};

getValuePath = function(object, path) {
    var o = object;
    path = path.replace(/\[(\w+)\]/g, '.$1');
    path = path.replace(/^\./, '');
    var a = path.split('.');
    while (a.length) {
        var n = a.shift();
        if (n in o) {
            o = o[n];
        } else {
            return;
        }
    }
    return o;
};

yyyymmdd = function(date) {
    var yyyy = date.getFullYear().toString();
    var mm = (date.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = date.getDate().toString();
    return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};

yyyy_mm_dd = function(date) {
    var yyyy = date.getFullYear().toString();
    var mm = (date.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = date.getDate().toString();
    return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};

searchIsabel = function() {
    var patientDiagnoses = Session.get("patientDiagnoses");
    var diagnosisList = "";
    for (var di in patientDiagnoses) {
        var dx = patientDiagnoses[di];
        if (diagnosisList.length > 0) diagnosisList += "|";
        diagnosisList += dx.objName;
    }
    console.log("searchIsabel: " + diagnosisList);
    var pt = Session.get("patient");
    var dob = yyyymmdd(getValuePath(pt, "data['id/dob']").startDate);
    var sex = getValuePath(pt, "data['id/sex']").text;
    var pregnant = "false";
    Meteor.call("isabel", dob, sex, pregnant, 12, diagnosisList, function(error, result){
        if (error) {
            return console.error("ERROR calling Isabel: " + error);
        }
        console.log("Received response from Isabel: " + JSON.stringify(result, null, "  "));
        var contentString = result.content.substring(7, result.content.length - 2);
        var content = JSON.parse(contentString);
        console.log("Received RESULT from Isabel: " + JSON.stringify(content, null, "  "));
        Session.set("isabel", content.Diagnosis_checklist)
    });
};

getPatientDiagnoses = function(patientId) {
    if (! patientId) return;
    return Facts.find({pred: "diagnosis", subj: patientId, valid: 1 });
};

getPatientFlags = function(patientId) {
    if (! patientId) return;
    return Facts.find({pred: "flag", subj: patientId, valid: 1 });
};

getPatientMeds = function(patientId) {
    if (! patientId) return;
    return Facts.find({pred: "medication", subj: patientId, valid: 1 });
};

//TODO filter out any questions that need not be asked
getPatientQuestions = function(flags) {
    if (! patientId) return;
    return Questions.find(
        {
            valid: 1,
            $or: [ flags ]
        }
    );
};

//TODO support users being permitted to handle other patients
getUserPatients = function(userid) {
    if (! userid) return;
    return Entities.find({etypes: "patient", owners: userid, valid: 1 });
};


text:
import json
import time

from nose.tools import eq_
from rest_framework.test import APIClient

from django.conf import settings

from kitsune.search.tests.test_es import ElasticTestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.questions.tests import QuestionFactory, AnswerFactory
from kitsune.products.tests import ProductFactory
from kitsune.wiki.tests import DocumentFactory, RevisionFactory

class SuggestViewTests(ElasticTestCase):
    client_class = APIClient

    # TODO: This should probably be a subclass of QuestionFactory
    def _make_question(self, solved=True, **kwargs):
        defaults = {
            'title': 'Login to website comments disabled ' + str(time.time()),
            'content': """
                readersupportednews.org, sends me emails with a list of
                articles to read.

                The links to the articles work as normal, except that I
                cannot login from the linked article - as required - to
                send my comments.

                I see a javascript activity statement at the bottom left
                corner of my screen while the left button is depressed
                on the Login button. it is gone when I release the left
                button, but no results.

                I have the latest (7) version of java enabled, on an XP
                box.

                Why this inability to login to this website commentary?
                """,
        }
        defaults.update(kwargs)
        q = QuestionFactory(**defaults)
        if solved:
            a = AnswerFactory(question=q)
            q.solution = a
        # Trigger a reindex for the question.
        q.save()
        return q

    # TODO: This should probably be a subclass of DocumentFactory
    def _make_document(self, **kwargs):
        defaults = {
            'title': 'How to make a pie from scratch with email ' + str(time.time()),
            'category': 10,
        }

        defaults.update(kwargs)
        d = DocumentFactory(**defaults)
        RevisionFactory(document=d, is_approved=True)
        d.save()
        return d

    def test_invalid_product(self):
        res = self.client.get(reverse('search.suggest'), {'product': 'nonexistant', 'q': 'search'})
        eq_(res.status_code, 400)
        eq_(res.data, {'product': [u'Could not find product with slug "nonexistant".']})

    def test_invalid_locale(self):
        res = self.client.get(reverse('search.suggest'), {'locale': 'bad-medicine', 'q': 'search'})
        eq_(res.status_code, 400)
        eq_(res.data, {'locale': [u'Could not find locale "bad-medicine".']})

    def test_invalid_fallback_locale_none_case(self):
        # Test the locale -> locale case.
        non_none_locale_fallback_pairs = [
            (key, val) for key, val in sorted(settings.NON_SUPPORTED_LOCALES.items())
            if val is not None
        ]
        locale, fallback = non_none_locale_fallback_pairs[0]

        res = self.client.get(reverse('search.suggest'), {'locale': locale, 'q': 'search'})
        eq_(res.status_code, 400)
        error_message = (u'"{0}" is not supported, but has fallback locale "{1}".'
                         .format(locale, fallback))
        eq_(res.data, {'locale': [error_message]})

    def test_invalid_fallback_locale_non_none_case(self):
        # Test the locale -> None case which falls back to WIKI_DEFAULT_LANGUAGE.
        has_none_locale_fallback_pairs = [
            (key, val) for key, val in sorted(settings.NON_SUPPORTED_LOCALES.items())
            if val is None
        ]
        locale, fallback = has_none_locale_fallback_pairs[0]

        res = self.client.get(reverse('search.suggest'), {'locale': locale, 'q': 'search'})
        eq_(res.status_code, 400)
        error_message = (u'"{0}" is not supported, but has fallback locale "{1}".'
                         .format(locale, settings.WIKI_DEFAULT_LANGUAGE))
        eq_(res.data, {'locale': [error_message]})

    def test_invalid_numbers(self):
        res = self.client.get(reverse('search.suggest'), {
            'max_questions': 'a',
            'max_documents': 'b',
            'q': 'search',
        })
        eq_(res.status_code, 400)
        eq_(res.data, {
            'max_questions': [u'A valid integer is required.'],
            'max_documents': [u'A valid integer is required.'],
        })

    def test_q_required(self):
        res = self.client.get(reverse('search.suggest'))
        eq_(res.status_code, 400)
        eq_(res.data, {'q': [u'This field is required.']})

    def test_it_works(self):
        q1 = self._make_question()
        d1 = self._make_document()
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        eq_([q['id'] for q in req.data['questions']], [q1.id])
        eq_([d['title'] for d in req.data['documents']], [d1.title])

    def test_filters_in_postdata(self):
        q1 = self._make_question()
        d1 = self._make_document()
        self.refresh()

        data = json.dumps({'q': 'emails'})
        # Note: Have to use .generic() because .get() will convert the
        # data into querystring params and then it's clownshoes all
        # the way down.
        req = self.client.generic(
            'GET', reverse('search.suggest'), data=data,
            content_type='application/json')
        eq_(req.status_code, 200)
        eq_([q['id'] for q in req.data['questions']], [q1.id])
        eq_([d['title'] for d in req.data['documents']], [d1.title])

    def test_both_querystring_and_body_raises_error(self):
        self._make_question()
        self._make_document()
        self.refresh()

        data = json.dumps({'q': 'emails'})
        # Note: Have to use .generic() because .get() will convert the
        # data into querystring params and then it's clownshoes all
        # the way down.
        req = self.client.generic(
            'GET', reverse('search.suggest') + '?max_documents=3', data=data,
            content_type='application/json')
        eq_(req.status_code, 400)
        eq_(req.data,
            {u'detail': 'Put all parameters either in the querystring or the HTTP request body.'})

    def test_questions_max_results_0(self):
        self._make_question()
        self.refresh()

        # Make sure something matches the query first.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        eq_(len(req.data['questions']), 1)

        # If we specify "don't give me any" make sure we don't get any.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_questions': '0'})
        eq_(len(req.data['questions']), 0)

    def test_questions_max_results_non_0(self):
        self._make_question()
        self._make_question()
        self._make_question()
        self._make_question()
        self._make_question()
        self.refresh()

        # Make sure something matches the query first.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        eq_(len(req.data['questions']), 5)

        # Make sure we get only 3.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_questions': '3'})
        eq_(len(req.data['questions']), 3)

    def test_documents_max_results_0(self):
        self._make_document()
        self.refresh()

        # Make sure something matches the query first.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        eq_(len(req.data['documents']), 1)

        # If we specify "don't give me any" make sure we don't get any.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_documents': '0'})
        eq_(len(req.data['documents']), 0)

    def test_documents_max_results_non_0(self):
        self._make_document()
        self._make_document()
        self._make_document()
        self._make_document()
        self._make_document()
        self.refresh()

        # Make sure something matches the query first.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        eq_(len(req.data['documents']), 5)

        # Make sure we get only 3.
        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'max_documents': '3'})
        eq_(len(req.data['documents']), 3)

    def test_product_filter_works(self):
        p1 = ProductFactory()
        p2 = ProductFactory()
        q1 = self._make_question(product=p1)
        self._make_question(product=p2)
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'product': p1.slug})
        eq_([q['id'] for q in req.data['questions']], [q1.id])

    def test_locale_filter_works_for_questions(self):
        q1 = self._make_question(locale='fr')
        self._make_question(locale='en-US')
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'locale': 'fr'})
        eq_([q['id'] for q in req.data['questions']], [q1.id])

    def test_locale_filter_works_for_documents(self):
        d1 = self._make_document(slug='right-doc', locale='fr')
        self._make_document(slug='wrong-doc', locale='en-US')
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails', 'locale': 'fr'})
        eq_([d['slug'] for d in req.data['documents']], [d1.slug])

    def test_serializer_fields(self):
        """Test that fields from the serializer are included."""
        self._make_question()
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        # Check that a field that is only available from the DB is in the response.
        assert 'metadata' in req.data['questions'][0]

    def test_only_solved(self):
        """Test that only solved questions are suggested."""
        q1 = self._make_question(solved=True)
        q2 = self._make_question(solved=False)
        self.refresh()

        req = self.client.get(reverse('search.suggest'), {'q': 'emails'})
        ids = [q['id'] for q in req.data['questions']]
        assert q1.id in ids
        assert q2.id not in ids
        eq_(len(ids), 1)


text:
package com.commonsware.android.tablayout;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
  private SampleAdapter adapter;
  private TabLayout tabs;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ViewPager pager=(ViewPager)findViewById(R.id.pager);

    adapter=new SampleAdapter(this, getSupportFragmentManager());
    pager.setAdapter(adapter);

    tabs=(TabLayout)findViewById(R.id.tabs);
    tabs.setupWithViewPager(pager);
    tabs.setTabMode(TabLayout.MODE_FIXED);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actions, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.fixed) {
      item.setChecked(!item.isChecked());

      if (item.isChecked()) {
        adapter.setPageCount(3);
        tabs.setTabMode(TabLayout.MODE_FIXED);
      }
      else {
        adapter.setPageCount(10);
        tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
      }

      adapter.notifyDataSetChanged();
      tabs.setTabsFromPagerAdapter(adapter);

      return(true);
    }

    return(super.onOptionsItemSelected(item));
  }
}


text:
package de.hpi.bpmn2xpdl;

import java.util.ArrayList;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmappr.Element;
import org.xmappr.RootElement;

@RootElement("Lanes")
public class XPDLLanes extends XMLConvertible {

	@Element("Lane")
	protected ArrayList<XPDLLane> lanes;

	public void add(XPDLLane newLane) {
		initializeLanes();

		getLanes().add(newLane);
	}

	public ArrayList<XPDLLane> getLanes() {
		return lanes;
	}

	public void readJSONlanesunknowns(JSONObject modelElement) {
		readUnknowns(modelElement, "lanesunknowns");
	}

	public void setLanes(ArrayList<XPDLLane> lanes) {
		this.lanes = lanes;
	}

	public void writeJSONchildShapes(JSONObject modelElement) throws JSONException {
		ArrayList<XPDLLane> lanesList = getLanes();
		if (lanesList != null) {
			initializeChildShapes(modelElement);

			JSONArray childShapes = modelElement.getJSONArray("childShapes");
			for (int i = 0; i < lanesList.size(); i++) {
				JSONObject newLane = new JSONObject();
				lanesList.get(i).write(newLane);
				childShapes.put(newLane);
			}
		}
	}

	public void writeJSONlanesunknowns(JSONObject modelElement) throws JSONException {
		writeUnknowns(modelElement, "lanesunknowns");
	}

	protected void initializeChildShapes(JSONObject modelElement) throws JSONException {
		if (modelElement.optJSONArray("childShapes") == null) {
			modelElement.put("childShapes", new JSONArray());
		}
	}

	protected void initializeLanes() {
		if (getLanes() == null) {
			setLanes(new ArrayList<XPDLLane>());
		}
	}

	public void createAndDistributeMapping(Map<String, XPDLThing> mapping) {
		if (getLanes() != null) {
			for (XPDLThing thing : getLanes()) {
				thing.setResourceIdToObject(mapping);
				mapping.put(thing.getResourceId(), thing);
			}
		}
	}
}


text:
copyright:
  years: 2016

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:pre: .pre}

# Informazioni su Trajectory Pattern Analysis
{: #tp_iotdriverinsights_overview}
Ultimo aggiornamento: 16 giugno 2016
{: .last-updated}

La API Trajectory Pattern Analysis è un servizio fornito da {{site.data.keyword.iotdriverinsights_full}} che puoi utilizzare per analizzare gli schemi O/D (Origine/Destinazione) e di rotta dei viaggi in auto dai dati di analisi degli autoveicoli.

{:shortdesc}

## Analisi degli schemi di traiettoria delle rotte
{: #tpa}

Puoi identificare e analizzare schemi O/D e di rotta per più viaggi in auto.
Il seguente diagramma mostra un semplice esempio degli schemi O/D e di rotta di un veicolo (veicolo-1) presi da più viaggi. In questo esempio, Trajectory Pattern Analysis identifica due schemi O/D:
- Uno schema O/D da Casa (Origine1) a Ufficio (Destinazione1) che ha due schemi di rotta
- Uno schema O/D da Casa (Origine1) a Negozio (Destinazione2) che ha uno schema di rotta.

![esempio di rotta O/D](images/tp_odroute_example.png "Esempio di schema O/D e di rotta")

Trajectory Pattern Analysis calcola anche alcune metriche di diversità nella guida per ciascun veicolo come elencato nella seguente tabella. Puoi utilizzare queste metriche per giudicare le caratteristiche di guida di un guidatore.

|Nome metrica|Descrizione|
|:---|:---|
|Rapporto O/D unico|Il rapporto tra il numero di viaggi che non sono coperti da schemi O/D e il numero totali di viaggi immessi.|
|Rapporto chilometraggio unico|Il rapporto del chilometraggio che non è coperto da schemi di rotta e il chilometraggio totale dei viaggi immessi.|
|Rapporto viaggio unico|Il rapporto del numero di viaggi che non sono coperti dagli schemi di rotta e il numero totale di viaggi immessi.|

## API REST
{: #rest_api}

La API REST Trajectory Pattern Analysis fornisce le richieste che puoi usare per personalizzare e sviluppare le tue applicazioni {{site.data.keyword.Bluemix_notm}}:

 1. Comandi dei dati degli autoveicoli:
   - `sendCarProbeData` invia i dati di analisi degli autoveicoli da analizzare
   - `getCarProbeDataListAsDate` restituisce l'elenco di dati di analisi degli autoveicoli in base alla data
   - `deleteCarProbeDataListByDate` elimina i dati di analisi degli autoveicoli
 2. Comandi dei lavori di analisi:
   - `sendJobRequest` invia la richiesta di lavoro di analisi degli schemi di traiettoria
   - `getJobInfo` restituisce le informazioni del lavoro specificato
   - `getJobInfoList` restituisce l'elenco di informazioni sul lavoro
 3. Comandi dei risultati dell'analisi:
   - `getResultSummary` restituisce le informazioni di riepilogo analizzate dell'analisi degli schemi di traiettoria
   - `getAnalyzedODDetail` restituisce le informazioni dettagliate dello schema O/D analizzato specificato
   - `getRouteGPSList` restituisce l'elenco di informazioni GPS dello schema di rotta analizzata specificato
   - `getODList` restituisce l'elenco di informazioni sugli schemi O/D degli argomenti specificati
   - `deleteJobResult` elimina tutti i risultati analizzati correlati a un lavoro

Per ulteriori informazioni, consulta la documentazione della [API {{site.data.keyword.iotdriverinsights_short}}](http://ibm.biz/IoTDriverBehavior_APIdoc){:new_window}.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Popover - Standalone</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <button id="basic" onclick="presentPopover({ component: 'profile-page', ev: event })">Show Popover</button>
  <button onclick="presentPopover({ component: 'translucent-page', ev: event, translucent: true })">Show Translucent Popover</button>
  <button color="secondary" onclick="presentPopover({ component: 'list-page', ev: event })">Show Long List Popover</button>
  <button color="danger" onclick="presentPopover({ component: 'profile-page' })">No Event Popover</button>

  <ion-popover-controller></ion-popover-controller>


text:
local usage = [====[

safe-guild-transform
====================
Wrapper for transform, used by Masterwork for the purpose of providing safe
unit transformations for guild mod purposes.  Removes the need to check the
gender of the unit prior to sending them to be transformed.  This script
provides the necessary remedies to that issue.  Guild castes tokens should be
written with _MALE and _FEMALE appended to the end of the file.

This Wrapper will also check for "race compliance", to keep non dwarves from
being turned into dwarves.

Arguments::

    -unit id
        set the target unit
    -guild
        guild name as written in caste minus _MALE and _FEMALE
    -race
        race name

]====]
local utils=require 'utils'

validArgs = validArgs or utils.invert ({
 'help',
 'unit',
 'guild',
 'race'
})

local args = utils.processArgs({...}, validArgs)

if not ... or args.help then
  print(usage)
  return
end

if not args.unit then
  error 'specify a unit'
end

if not args.race or not args.guild then
  error 'Specficy a target form.'
end

local unit = df.unit.find(tonumber(args.unit))

if args.race == tostring(df.global.world.raws.creatures.all[unit.race].creature_id) then

  local suffix
  if unit.sex == 1 then
    suffix = "_MALE"
  else
    suffix = "_FEMALE"
  end

  args.guild=args.guild..suffix

  dfhack.run_script('modtools/transform-unit', '-unit', unit.id, '-race', args.race, '-caste', args.guild, '-keepInventory', 1)

else
  error 'attempted to change the race of a unit, reject transformation.'
end


text:
package org.apache.beam.runners.direct;

import static java.util.Arrays.asList;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.concurrent.GuardedBy;
import org.apache.beam.runners.core.metrics.DistributionData;
import org.apache.beam.runners.core.metrics.GaugeData;
import org.apache.beam.runners.core.metrics.MetricFiltering;
import org.apache.beam.runners.core.metrics.MetricKey;
import org.apache.beam.runners.core.metrics.MetricUpdates;
import org.apache.beam.runners.core.metrics.MetricUpdates.MetricUpdate;
import org.apache.beam.runners.core.metrics.MetricsMap;
import org.apache.beam.sdk.metrics.DistributionResult;
import org.apache.beam.sdk.metrics.GaugeResult;
import org.apache.beam.sdk.metrics.MetricName;
import org.apache.beam.sdk.metrics.MetricQueryResults;
import org.apache.beam.sdk.metrics.MetricResult;
import org.apache.beam.sdk.metrics.MetricResults;
import org.apache.beam.sdk.metrics.MetricsFilter;

/**
 * Implementation of {@link MetricResults} for the Direct Runner.
 */
class DirectMetrics extends MetricResults {

  // TODO: (BEAM-723) Create a shared ExecutorService for maintenance tasks in the DirectRunner.
  private static final ExecutorService COUNTER_COMMITTER =
      Executors.newCachedThreadPool(
          new ThreadFactoryBuilder()
              .setThreadFactory(MoreExecutors.platformThreadFactory())
              .setDaemon(true)
              .setNameFormat("direct-metrics-counter-committer")
              .build());

  private interface MetricAggregation<UpdateT, ResultT> {
    UpdateT zero();
    UpdateT combine(Iterable<UpdateT> updates);
    ResultT extract(UpdateT data);
  }

  /**
   * Implementation of a metric in the direct runner.
   *
   * @param <UpdateT> The type of raw data received and aggregated across updates.
   * @param <ResultT> The type of result extracted from the data.
   */
  private static class DirectMetric<UpdateT, ResultT> {
    private final MetricAggregation<UpdateT, ResultT> aggregation;

    private final AtomicReference<UpdateT> finishedCommitted;

    private final Object attemptedLock = new Object();
    @GuardedBy("attemptedLock")
    private volatile UpdateT finishedAttempted;
    @GuardedBy("attemptedLock")
    private final ConcurrentMap<CommittedBundle<?>, UpdateT> inflightAttempted =
        new ConcurrentHashMap<>();

    public DirectMetric(MetricAggregation<UpdateT, ResultT> aggregation) {
      this.aggregation = aggregation;
      finishedCommitted = new AtomicReference<>(aggregation.zero());
      finishedAttempted = aggregation.zero();
    }

    /**
     * Add the given {@code tentativeCumulative} update to the physical aggregate.
     *
     * @param bundle The bundle receiving an update.
     * @param tentativeCumulative The new cumulative value for the given bundle.
     */
    public void updatePhysical(CommittedBundle<?> bundle, UpdateT tentativeCumulative) {
      // Add (or update) the cumulatiev value for the given bundle.
      inflightAttempted.put(bundle, tentativeCumulative);
    }

    /**
     * Commit a physical value for the given {@code bundle}.
     *
     * @param bundle The bundle being committed.
     * @param finalCumulative The final cumulative value for the given bundle.
     */
    public void commitPhysical(final CommittedBundle<?> bundle, final UpdateT finalCumulative) {
      // To prevent a query from blocking the commit, we perform the commit in two steps.
      // 1. We perform a non-blocking write to the uncommitted table to make the new vaule
      //    available immediately.
      // 2. We submit a runnable that will commit the update and remove the tentative value in
      //    a synchronized block.
      inflightAttempted.put(bundle, finalCumulative);
      COUNTER_COMMITTER.submit(new Runnable() {
        @Override
        public void run() {
          synchronized (attemptedLock) {
            finishedAttempted = aggregation.combine(asList(finishedAttempted, finalCumulative));
            inflightAttempted.remove(bundle);
          }
        }
      });
    }

    /** Extract the latest values from all attempted and in-progress bundles. */
    public ResultT extractLatestAttempted() {
      ArrayList<UpdateT> updates = new ArrayList<>(inflightAttempted.size() + 1);
      // Within this block we know that will be consistent. Specifically, the only change that can
      // happen concurrently is the addition of new (larger) values to inflightAttempted.
      synchronized (attemptedLock) {
        updates.add(finishedAttempted);
        updates.addAll(inflightAttempted.values());
      }
      return aggregation.extract(aggregation.combine(updates));
    }

    /**
     * Commit a logical value for the given {@code bundle}.
     *
     * @param bundle The bundle being committed.
     * @param finalCumulative The final cumulative value for the given bundle.
     */
    public void commitLogical(final CommittedBundle<?> bundle, final UpdateT finalCumulative) {
      UpdateT current;
      do {
        current = finishedCommitted.get();
      } while (!finishedCommitted.compareAndSet(current,
          aggregation.combine(asList(current, finalCumulative))));
    }

    /** Extract the value from all successfully committed bundles. */
    public ResultT extractCommitted() {
      return aggregation.extract(finishedCommitted.get());
    }
  }

  private static final MetricAggregation<Long, Long> COUNTER =
      new MetricAggregation<Long, Long>() {
    @Override
    public Long zero() {
      return 0L;
    }

    @Override
    public Long combine(Iterable<Long> updates) {
      long value = 0;
      for (long update : updates) {
        value += update;
      }
      return value;
    }

    @Override
    public Long extract(Long data) {
      return data;
    }
  };

  private static final MetricAggregation<DistributionData, DistributionResult> DISTRIBUTION =
      new MetricAggregation<DistributionData, DistributionResult>() {
        @Override
        public DistributionData zero() {
          return DistributionData.EMPTY;
        }

        @Override
        public DistributionData combine(Iterable<DistributionData> updates) {
          DistributionData result = DistributionData.EMPTY;
          for (DistributionData update : updates) {
            result = result.combine(update);
          }
          return result;
        }

        @Override
        public DistributionResult extract(DistributionData data) {
          return data.extractResult();
        }
      };

  private static final MetricAggregation<GaugeData, GaugeResult> GAUGE =
      new MetricAggregation<GaugeData, GaugeResult>() {
        @Override
        public GaugeData zero() {
          return GaugeData.empty();
        }

        @Override
        public GaugeData combine(Iterable<GaugeData> updates) {
          GaugeData result = GaugeData.empty();
          for (GaugeData update : updates) {
            result = result.combine(update);
          }
          return result;
        }

        @Override
        public GaugeResult extract(GaugeData data) {
          return data.extractResult();
        }
      };

  /** The current values of counters in memory. */
  private MetricsMap<MetricKey, DirectMetric<Long, Long>> counters =
      new MetricsMap<>(new MetricsMap.Factory<MetricKey, DirectMetric<Long, Long>>() {
        @Override
        public DirectMetric<Long, Long> createInstance(MetricKey unusedKey) {
          return new DirectMetric<>(COUNTER);
        }
      });
  private MetricsMap<MetricKey, DirectMetric<DistributionData, DistributionResult>> distributions =
      new MetricsMap<>(
          new MetricsMap.Factory<MetricKey, DirectMetric<DistributionData, DistributionResult>>() {
        @Override
        public DirectMetric<DistributionData, DistributionResult> createInstance(
            MetricKey unusedKey) {
          return new DirectMetric<>(DISTRIBUTION);
        }
      });
  private MetricsMap<MetricKey, DirectMetric<GaugeData, GaugeResult>> gauges =
      new MetricsMap<>(
          new MetricsMap.Factory<MetricKey, DirectMetric<GaugeData, GaugeResult>>() {
            @Override
            public DirectMetric<GaugeData, GaugeResult> createInstance(
                MetricKey unusedKey) {
              return new DirectMetric<>(GAUGE);
            }
          });

  @AutoValue
  abstract static class DirectMetricQueryResults implements MetricQueryResults {
    public static MetricQueryResults create(
        Iterable<MetricResult<Long>> counters,
        Iterable<MetricResult<DistributionResult>> distributions,
        Iterable<MetricResult<GaugeResult>> gauges) {
      return new AutoValue_DirectMetrics_DirectMetricQueryResults(counters, distributions, gauges);
    }
  }

  @AutoValue
  abstract static class DirectMetricResult<T> implements MetricResult<T> {
    // need to define these here so they appear in the correct order
    // and the generated constructor is usable and consistent
    public abstract MetricName name();
    public abstract String step();
    public abstract T committed();
    public abstract T attempted();

    public static <T> MetricResult<T> create(MetricName name, String scope,
        T committed, T attempted) {
      return new AutoValue_DirectMetrics_DirectMetricResult<T>(
          name, scope, committed, attempted);
    }
  }

  @Override
  public MetricQueryResults queryMetrics(MetricsFilter filter) {
    ImmutableList.Builder<MetricResult<Long>> counterResults = ImmutableList.builder();
    for (Entry<MetricKey, DirectMetric<Long, Long>> counter : counters.entries()) {
      maybeExtractResult(filter, counterResults, counter);
    }
    ImmutableList.Builder<MetricResult<DistributionResult>> distributionResults =
        ImmutableList.builder();
    for (Entry<MetricKey, DirectMetric<DistributionData, DistributionResult>> distribution
        : distributions.entries()) {
      maybeExtractResult(filter, distributionResults, distribution);
    }
    ImmutableList.Builder<MetricResult<GaugeResult>> gaugeResults =
        ImmutableList.builder();
    for (Entry<MetricKey, DirectMetric<GaugeData, GaugeResult>> gauge
        : gauges.entries()) {
      maybeExtractResult(filter, gaugeResults, gauge);
    }

    return DirectMetricQueryResults.create(counterResults.build(), distributionResults.build(),
        gaugeResults.build());
  }

  private <ResultT> void maybeExtractResult(
      MetricsFilter filter,
      ImmutableList.Builder<MetricResult<ResultT>> resultsBuilder,
      Map.Entry<MetricKey, ? extends DirectMetric<?, ResultT>> entry) {
    if (MetricFiltering.matches(filter, entry.getKey())) {
      resultsBuilder.add(DirectMetricResult.create(
          entry.getKey().metricName(),
          entry.getKey().stepName(),
          entry.getValue().extractCommitted(),
          entry.getValue().extractLatestAttempted()));
    }
  }

  /** Apply metric updates that represent physical counter deltas to the current metric values. */
  public void updatePhysical(CommittedBundle<?> bundle, MetricUpdates updates) {
    for (MetricUpdate<Long> counter : updates.counterUpdates()) {
      counters.get(counter.getKey()).updatePhysical(bundle, counter.getUpdate());
    }
    for (MetricUpdate<DistributionData> distribution : updates.distributionUpdates()) {
      distributions.get(distribution.getKey())
          .updatePhysical(bundle, distribution.getUpdate());
    }
    for (MetricUpdate<GaugeData> gauge : updates.gaugeUpdates()) {
      gauges.get(gauge.getKey())
          .updatePhysical(bundle, gauge.getUpdate());
    }
  }

  public void commitPhysical(CommittedBundle<?> bundle, MetricUpdates updates) {
    for (MetricUpdate<Long> counter : updates.counterUpdates()) {
      counters.get(counter.getKey()).commitPhysical(bundle, counter.getUpdate());
    }
    for (MetricUpdate<DistributionData> distribution : updates.distributionUpdates()) {
      distributions.get(distribution.getKey())
          .commitPhysical(bundle, distribution.getUpdate());
    }
    for (MetricUpdate<GaugeData> gauge : updates.gaugeUpdates()) {
      gauges.get(gauge.getKey())
          .commitPhysical(bundle, gauge.getUpdate());
    }
  }

  /** Apply metric updates that represent new logical values from a bundle being committed. */
  public void commitLogical(CommittedBundle<?> bundle, MetricUpdates updates) {
    for (MetricUpdate<Long> counter : updates.counterUpdates()) {
      counters.get(counter.getKey()).commitLogical(bundle, counter.getUpdate());
    }
    for (MetricUpdate<DistributionData> distribution : updates.distributionUpdates()) {
      distributions.get(distribution.getKey())
          .commitLogical(bundle, distribution.getUpdate());
    }
    for (MetricUpdate<GaugeData> gauge : updates.gaugeUpdates()) {
      gauges.get(gauge.getKey())
          .commitLogical(bundle, gauge.getUpdate());
    }
  }
}


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

namespace Twitter.Models
{
    class Tweet
    {
    }
}