text:
#ifndef CYGONCE_INFRA_CYG_TYPE_H
#define CYGONCE_INFRA_CYG_TYPE_H

//==========================================================================
//
//      cyg_type.h
//
//      Standard types, and some useful coding macros.
//
//==========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####
// -------------------------------------------
// This file is part of eCos, the Embedded Configurable Operating System.
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2009 Free Software Foundation, Inc.
//
// eCos is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 or (at your option) any later
// version.
//
// eCos is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with eCos; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
// As a special exception, if other files instantiate templates or use
// macros or inline functions from this file, or you compile this file
// and link it with other works to produce a work based on this file,
// this file does not by itself cause the resulting work to be covered by
// the GNU General Public License. However the source code for this file
// must still be made available in accordance with section (3) of the GNU
// General Public License v2.
//
// This exception does not invalidate any other reasons why a work based
// on this file might be covered by the GNU General Public License.
// -------------------------------------------
// ####ECOSGPLCOPYRIGHTEND####
//==========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s):   nickg from an original by hmt
// Contributors:  nickg
// Date:        1997-09-08
// Purpose:     share unambiguously sized types.
// Description: we typedef [cyg_][u]int8,16,32 &c for general use.
// Usage:       #include "cyg/infra/cyg_type.h"
//              ...
//              cyg_int32 my_32bit_integer;
//
//####DESCRIPTIONEND####
//

#include <stddef.h>           // Definition of NULL from the compiler

// -------------------------------------------------------------------------
// Some useful macros. These are defined here by default.

// __externC is used in mixed C/C++ headers to force C linkage on an external
// definition. It avoids having to put all sorts of ifdefs in.

#ifdef __cplusplus
# define __externC extern "C"
#else
# define __externC extern
#endif
// Also define externC for now - but it is deprecated
#define externC __externC

// Compiler version.
#ifdef __GNUC__
# if defined(__GNU_PATCHLEVEL__)
#  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                             + __GNUC_MINOR__ * 100 \
                             + __GNUC_PATCHLEVEL__)
# else
#  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                             + __GNUC_MINOR__ * 100)
# endif
#endif

// -------------------------------------------------------------------------
// The header <basetype.h> defines the base types used here. It is
// supplied either by the target architecture HAL, or by the host
// porting kit. They are all defined as macros, and only those that
// make choices other than the defaults given below need be defined.

#define CYG_LSBFIRST 1234
#define CYG_MSBFIRST 4321

#include <cyg/hal/basetype.h>

#if (CYG_BYTEORDER != CYG_LSBFIRST) && (CYG_BYTEORDER != CYG_MSBFIRST)
# error You must define CYG_BYTEORDER to equal CYG_LSBFIRST or CYG_MSBFIRST
#endif

#ifndef CYG_DOUBLE_BYTEORDER
#define CYG_DOUBLE_BYTEORDER CYG_BYTEORDER
#endif

#ifndef cyg_halint8
# define cyg_halint8 char
#endif
#ifndef cyg_halint16
# define cyg_halint16 short
#endif
#ifndef cyg_halint32
# define cyg_halint32 int
#endif
#ifndef cyg_halint64
# define cyg_halint64 long long
#endif

#ifndef cyg_halcount8
# define cyg_halcount8 int
#endif
#ifndef cyg_halcount16
# define cyg_halcount16 int
#endif
#ifndef cyg_halcount32
# define cyg_halcount32 int
#endif
#ifndef cyg_halcount64
# define cyg_halcount64 long long
#endif

#ifndef cyg_haladdress
# define cyg_haladdress cyg_uint32
#endif
#ifndef cyg_haladdrword
# define cyg_haladdrword cyg_uint32
#endif

#ifndef cyg_halbool
# define cyg_halbool int
#endif

#ifndef cyg_halatomic
# define cyg_halatomic cyg_halint8
#endif

// -------------------------------------------------------------------------
// Provide a default architecture alignment
// This may be overridden in basetype.h if necessary.
// These should be straightforward numbers to allow use in assembly.

#ifndef CYGARC_ALIGNMENT
# define CYGARC_ALIGNMENT 8
#endif
// And corresponding power of two alignment
#ifndef CYGARC_P2ALIGNMENT
# define CYGARC_P2ALIGNMENT 3
#endif
#if (CYGARC_ALIGNMENT) != (1 << CYGARC_P2ALIGNMENT)
# error "Inconsistent CYGARC_ALIGNMENT and CYGARC_P2ALIGNMENT values"
#endif

// -------------------------------------------------------------------------
// The obvious few that compilers may define for you.
// But in case they don't:

#ifndef NULL
# define NULL 0
#endif

#ifndef __cplusplus

typedef cyg_halbool bool;

# ifndef false
#  define false 0
# endif

# ifndef true
#  define true (!false)
# endif

#endif

// -------------------------------------------------------------------------
// Allow creation of procedure-like macros that are a single statement,
// and must be followed by a semi-colon

#define CYG_MACRO_START do {
#define CYG_MACRO_END   } while (0)

#define CYG_EMPTY_STATEMENT CYG_MACRO_START CYG_MACRO_END

#define CYG_UNUSED_PARAM( _type_, _name_ ) CYG_MACRO_START      \
  _type_ __tmp1 = (_name_);                                     \
  _type_ __tmp2 = __tmp1;                                       \
  __tmp1 = __tmp2;                                              \
CYG_MACRO_END

//----------------------------------------------------------------------------
// The unused attribute stops the compiler warning about the variable
// not being used.
// The used attribute prevents the compiler from optimizing it away.

#define CYG_REFERENCE_OBJECT(__object__)                            \
    CYG_MACRO_START                                                 \
    static const void*  __cygvar_discard_me__                       \
    __attribute__ ((unused, used)) = (const void*)&(__object__);    \
    CYG_MACRO_END

// -------------------------------------------------------------------------
// Define basic types for using integers in memory and structures;
// depends on compiler defaults and CPU type.

typedef unsigned cyg_halint8    cyg_uint8  ;
typedef   signed cyg_halint8    cyg_int8   ;

typedef unsigned cyg_halint16   cyg_uint16 ;
typedef   signed cyg_halint16   cyg_int16  ;

typedef unsigned cyg_halint32   cyg_uint32 ;
typedef   signed cyg_halint32   cyg_int32  ;

typedef unsigned cyg_halint64   cyg_uint64 ;
typedef   signed cyg_halint64   cyg_int64  ;

typedef  cyg_halbool            cyg_bool   ;

// -------------------------------------------------------------------------
// Define types for using integers in registers for looping and the like;
// depends on CPU type, choose what it is most comfortable with, with at
// least the range required.

typedef unsigned cyg_halcount8  cyg_ucount8  ;
typedef   signed cyg_halcount8  cyg_count8   ;

typedef unsigned cyg_halcount16 cyg_ucount16 ;
typedef   signed cyg_halcount16 cyg_count16  ;

typedef unsigned cyg_halcount32 cyg_ucount32 ;
typedef   signed cyg_halcount32 cyg_count32  ;

typedef unsigned cyg_halcount64 cyg_ucount64 ;
typedef   signed cyg_halcount64 cyg_count64  ;

// -------------------------------------------------------------------------
// Define a type to be used for atomic accesses. This type is guaranteed
// to be read or written in a single uninterruptible operation. This type
// is at least a single byte.

typedef volatile unsigned cyg_halatomic  cyg_atomic;
typedef volatile unsigned cyg_halatomic  CYG_ATOMIC;

// -------------------------------------------------------------------------
// Define types for access plain, on-the-metal memory or devices.

typedef cyg_uint32  CYG_WORD;
typedef cyg_uint8   CYG_BYTE;
typedef cyg_uint16  CYG_WORD16;
typedef cyg_uint32  CYG_WORD32;
typedef cyg_uint64  CYG_WORD64;

typedef cyg_haladdress  CYG_ADDRESS;
typedef cyg_haladdrword CYG_ADDRWORD;

// -------------------------------------------------------------------------
// Number of elements in a (statically allocated) array.

#define CYG_NELEM(a) (sizeof(a) / sizeof((a)[0]))

// -------------------------------------------------------------------------
// Constructor ordering macros.  These are added as annotations to all
// static objects to order the constuctors appropriately.

#if defined(__cplusplus) && defined(__GNUC__) && \
    !defined(CYGBLD_ATTRIB_INIT_PRI)
# define CYGBLD_ATTRIB_INIT_PRI( _pri_ ) __attribute__((init_priority(_pri_)))
#elif !defined(CYGBLD_ATTRIB_INIT_PRI)
// FIXME: should maybe just bomb out if this is attempted anywhere else?
// Not sure
# define CYGBLD_ATTRIB_INIT_PRI( _pri_ )
#endif

// The following will be removed eventually as it doesn't allow the use of
// e.g. pri+5 format
#define CYG_INIT_PRIORITY( _pri_ ) CYGBLD_ATTRIB_INIT_PRI( CYG_INIT_##_pri_ )

#define CYGBLD_ATTRIB_INIT_BEFORE( _pri_ ) CYGBLD_ATTRIB_INIT_PRI(_pri_-100)
#define CYGBLD_ATTRIB_INIT_AFTER( _pri_ )  CYGBLD_ATTRIB_INIT_PRI(_pri_+100)

#if defined(__GNUC__) && !defined(__cplusplus) && (__GNUC_VERSION__ >= 40300)
// Equivalents of the above for C functions, available from gcc 4.3 onwards.
# define CYGBLD_ATTRIB_C_INIT_PRI( _pri_)       __attribute__((constructor (_pri_)))
# define CYGBLD_ATTRIB_C_INIT_BEFORE( _pri_ )   __attribute__((constructor (_pri_-100)))
# define CYGBLD_ATTRIB_C_INIT_AFTER( _pri_ )    __attribute__((constructor (_pri_+100)))
#endif

// Start with initializing everything inside the cpu and the main memory.
#define CYG_INIT_HAL                    10000
#define CYG_INIT_SCHEDULER              11000
#define CYG_INIT_IDLE_THREAD            11100
#define CYG_INIT_INTERRUPTS             12000
#define CYG_INIT_CLOCK                  14000
#define CYG_INIT_THREADS                16000
#define CYG_INIT_KERNEL                 19000
#define CYG_INIT_MEMALLOC               20000
// Now move on to I/O subsystems and device drivers. These can make use of
// kernel and HAL functionality, and can dynamically allocate memory if
// absolutely needed. For now they can also assume that diag_printf()
// functionality is available, but that may change in future.
//
// Primary buses are ones very closely tied to the processor, e.g. PCI.
#define CYG_INIT_BUS_PRIMARY            30000
// Not yet: on some targets cyg_pci_init() has to be called very early
// on for HAL diagnostics to work.
// #define CYG_INIT_BUS_PCI                CYG_INIT_BUS_PRIMARY
//
// Secondary buses may hang off primary buses, e.g. USB host.
#define CYG_INIT_BUS_SECONDARY          31000
// Tertiary buses are everything else.
#define CYG_INIT_BUS_TERTIARY           32000
#define CYG_INIT_BUS_I2C                CYG_INIT_BUS_TERTIARY
#define CYG_INIT_BUS_SPI                CYG_INIT_BUS_TERTIARY
//
// In future HAL diag initialization may happen at this point.
//
// Watchdogs and wallclocks often hang off a tertiary bus but
// have no dependencies
#define CYG_INIT_DEV_WATCHDOG           35000
#define CYG_INIT_DEV_WALLCLOCK          36000
// A primary block configuration can be initialized with no need
// for per-unit configuration information.
#define CYG_INIT_DEV_BLOCK_PRIMARY      37000
#define CYG_INIT_DEV_FLASH              CYG_INIT_DEV_BLOCK_PRIMARY
// Per-unit configuration data extracted from primary storage.
// NOTE: for future use, not implemented yet.
#define CYG_INIT_CONFIG                 38000
// Secondary block devices may use per-unit configuration data
// for e.g. interpreting partition layout. Few devices are expected
// to fall into this category. Note that these devices, as well as
// some char devices, may not actually be usable until interrupts
// are enabled.
#define CYG_INIT_DEV_BLOCK_SECONDARY    40000
// Char devices are everything else: serial, ethernet, CAN, ...
#define CYG_INIT_DEV_CHAR               41000
// For backwards compatibility. Subject to change in future so
// a CYG_INIT_DEV_ priority should be used instead.
#define CYG_INIT_DRIVERS                48000
// CYG_INIT_IO and CYG_INIT_IO_FS are poorly defined at present,
// and may get reorganized in future.
#define CYG_INIT_IO                     49000
#define CYG_INIT_IO_FS                  50000
// The I/O subsystems and device drivers have been initialized.
#define CYG_INIT_LIBC                   56000
#define CYG_INIT_COMPAT                 58000
#define CYG_INIT_APPLICATION            60000
#define CYG_INIT_PREDEFAULT             65534
#define CYG_INIT_DEFAULT                65535

// -------------------------------------------------------------------------
// Label name macros. Some toolsets generate labels with initial
// underscores and others don't. CYG_LABEL_NAME should be used on
// labels in C/C++ code that are defined in assembly code or linker
// scripts. CYG_LABEL_DEFN is for use in assembly code and linker
// scripts where we need to manufacture labels that can be used from
// C/C++.
// These are default implementations that should work for most targets.
// They may be overridden in basetype.h if necessary.

#ifndef CYG_LABEL_NAME

#define CYG_LABEL_NAME(_name_) _name_

#endif

#ifndef CYG_LABEL_DEFN

#define CYG_LABEL_DEFN(_label) _label

#endif

// -------------------------------------------------------------------------
// COMPILER-SPECIFIC STUFF

#ifdef __GNUC__
// Force a 'C' routine to be called like a 'C++' contructor
# if !defined(CYGBLD_ATTRIB_CONSTRUCTOR)
#  define CYGBLD_ATTRIB_CONSTRUCTOR __attribute__((constructor))
# endif

// Define a compiler-specific rune for saying a function doesn't return
# if !defined(CYGBLD_ATTRIB_NORET)
#  define CYGBLD_ATTRIB_NORET __attribute__((noreturn))
# endif

// How to define weak symbols - this is only relevant for ELF and a.out,
// but that won't be a problem for eCos
# if !defined(CYGBLD_ATTRIB_WEAK)
#  define CYGBLD_ATTRIB_WEAK __attribute__ ((weak))
# endif

// How to define alias to symbols. Just pass in the symbol itself, not
// the string name of the symbol
# if !defined(CYGBLD_ATTRIB_ALIAS)
#  define CYGBLD_ATTRIB_ALIAS(__symbol__) \
        __attribute__ ((alias (#__symbol__)))
# endif

// This effectively does the reverse of the previous macro. It defines
// a name that the attributed variable or function will actually have
// in assembler.
# if !defined(CYGBLD_ATTRIB_ASM_ALIAS)
#  define __Str(x) #x
#  define __Xstr(x) __Str(x)
#  define CYGBLD_ATTRIB_ASM_ALIAS(__symbol__) \
             __asm__ ( __Xstr( CYG_LABEL_DEFN( __symbol__ ) ) )
# endif

// Shows that a function returns the same value when given the same args, but
// note this can't be used if there are pointer args
# if !defined(CYGBLD_ATTRIB_CONST)
#  define CYGBLD_ATTRIB_CONST __attribute__((const))
#endif

// Assign a defined variable to a specific section
# if !defined(CYGBLD_ATTRIB_SECTION)
#  define CYGBLD_ATTRIB_SECTION(__sect__) __attribute__((section (__sect__)))
# endif

// Give a type or object explicit minimum alignment
# if !defined(CYGBLD_ATTRIB_ALIGN)
#  define CYGBLD_ATTRIB_ALIGN(__align__) __attribute__((aligned(__align__)))
# endif

# if !defined(CYGBLD_ATTRIB_ALIGN_MAX)
#  define CYGBLD_ATTRIB_ALIGN_MAX __attribute__((aligned))
# endif

# if !defined(CYGBLD_ATTRIB_ALIGNOFTYPE)
#  define CYGBLD_ATTRIB_ALIGNOFTYPE( _type_ ) \
     __attribute__((aligned(__alignof__( _type_ ))))
# endif

// Teach compiler how to check format of printf-like functions
# define CYGBLD_ATTRIB_PRINTF_FORMAT(__format__, __args__) \
        __attribute__((format (printf, __format__, __args__)))

// Teach compiler how to check format of scanf-like functions
# define CYGBLD_ATTRIB_SCANF_FORMAT(__format__, __args__) \
        __attribute__((format (scanf, __format__, __args__)))

// Teach compiler how to check format of strftime-like functions
# define CYGBLD_ATTRIB_STRFTIME_FORMAT(__format__, __args__) \
        __attribute__((format (strftime, __format__, __args__)))

// Tell the compiler not to throw away a variable or function. Only known
// available on 3.3.2 or above. Old version's didn't throw them away,
// but using the unused attribute should stop warnings.
# if !defined(CYGBLD_ATTRIB_USED)
#  if __GNUC_VERSION__ >= 30302
#   define CYGBLD_ATTRIB_USED __attribute__((used))
#  else
#   define CYGBLD_ATTRIB_USED __attribute__((unused))
#  endif
# endif
#else // non-GNU

# define CYGBLD_ATTRIB_CONSTRUCTOR

# define CYGBLD_ATTRIB_NORET
    // This intentionally gives an error only if we actually try to
    // use it.  #error would give an error if we simply can't.
// FIXME: Had to disarm the bomb - the CYGBLD_ATTRIB_WEAK macro is now
//        (indirectly) used in host tools.
# define CYGBLD_ATTRIB_WEAK /* !!!-- Attribute weak not defined --!!! */

# define CYGBLD_ATTRIB_ALIAS(__x__) !!!-- Attribute alias not defined --!!!

# define CYGBLD_ATTRIB_ASM_ALIAS(__symbol__) !!!-- Asm alias not defined --!!!

# define CYGBLD_ATTRIB_CONST

# define CYGBLD_ATTRIB_ALIGN(__align__) !!!-- Alignment alias not defined --!!!

# define CYGBLD_ATTRIB_ALIGN_MAX !!!-- Alignment alias not defined --!!!

# define CYGBLD_ATTRIB_ALIGNOFTYPE( _type_ ) !!!-- Alignment alias not defined --!!!

# define CYGBLD_ATTRIB_PRINTF_FORMAT(__format__, __args__)

# define CYGBLD_ATTRIB_SCANF_FORMAT(__format__, __args__)

# define CYGBLD_ATTRIB_STRFTIME_FORMAT(__format__, __args__)

#endif

// How to define weak aliases. Currently this is simply a mixture of the
// above

# define CYGBLD_ATTRIB_WEAK_ALIAS(__symbol__) \
        CYGBLD_ATTRIB_WEAK CYGBLD_ATTRIB_ALIAS(__symbol__)

#ifdef __cplusplus
# define __THROW throw()
#else
# define __THROW
#endif

// -------------------------------------------------------------------------
// Variable annotations
// These annotations may be added to various static variables in the
// HAL and kernel to indicate which component they belong to. These
// are used by some targets to optimize memory placement of these
// variables.

#ifndef CYGBLD_ANNOTATE_VARIABLE_HAL
#define CYGBLD_ANNOTATE_VARIABLE_HAL
#endif
#ifndef CYGBLD_ANNOTATE_VARIABLE_SCHED
#define CYGBLD_ANNOTATE_VARIABLE_SCHED
#endif
#ifndef CYGBLD_ANNOTATE_VARIABLE_CLOCK
#define CYGBLD_ANNOTATE_VARIABLE_CLOCK
#endif
#ifndef CYGBLD_ANNOTATE_VARIABLE_INTR
#define CYGBLD_ANNOTATE_VARIABLE_INTR
#endif

// -------------------------------------------------------------------------
// Various "flavours" of memory regions that can be described by the
// Memory Layout Tool (MLT).

#define CYGMEM_REGION_ATTR_R  0x01  // Region can be read
#define CYGMEM_REGION_ATTR_W  0x02  // Region can be written

#if defined (__GNUC__)
#elif defined (MSVC)
#define __inline__ __inline
#define inline __inline
#else
#endif
// -------------------------------------------------------------------------
#endif // CYGONCE_INFRA_CYG_TYPE_H multiple inclusion protection
// EOF cyg_type.h


text:
import { MotionPollMethod } from 'app/shared/models/motions/motion-poll';
import { MajorityMethod, PercentBase, PollState, PollType } from 'app/shared/models/poll/base-poll';
import { MotionTitleInformation } from 'app/site/motions/models/view-motion';
import { BasePollSlideData } from 'app/slides/polls/base-poll-slide-data';

export interface MotionPollSlideData extends BasePollSlideData {
    motion: MotionTitleInformation;
    poll: {
        title: string;
        type: PollType;
        pollmethod: MotionPollMethod;
        state: PollState;
        onehundred_percent_base: PercentBase;
        majority_method: MajorityMethod;

        options: {
            yes?: number;
            no?: number;
            abstain?: number;
        }[];

        // optional for published polls:
        votesvalid: number;
        votesinvalid: number;
        votescast: number;
    };
}

redpajama_set_name: RedPajamaGithub


text:
package tests.api.java.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;

public class FileReaderTest extends junit.framework.TestCase {

	FileReader br;

	BufferedWriter bw;

	FileInputStream fis;

	File f;

	/**
	 * @tests java.io.FileReader#FileReader(java.io.File)
	 */
	public void test_ConstructorLjava_io_File() {
		// Test for method java.io.FileReader(java.io.File)
		try {
			bw = new BufferedWriter(new FileWriter(f.getPath()));
			bw.write(" After test string", 0, 18);
			bw.close();
			br = new FileReader(f);
			char[] buf = new char[100];
			int r = br.read(buf);
			br.close();
			assertEquals("Failed to read correct chars", " After test string", new String(buf, 0, r)
					);
		} catch (Exception e) {
			fail("Exception during Constructor test " + e.toString());
		}
	}

	/**
	 * @tests java.io.FileReader#FileReader(java.io.FileDescriptor)
	 */
	public void test_ConstructorLjava_io_FileDescriptor() {
		// Test for method java.io.FileReader(java.io.FileDescriptor)
		try {
			bw = new BufferedWriter(new FileWriter(f.getPath()));
			bw.write(" After test string", 0, 18);
			bw.close();
			FileInputStream fis = new FileInputStream(f.getPath());
			br = new FileReader(fis.getFD());
			char[] buf = new char[100];
			int r = br.read(buf);
			br.close();
			fis.close();
			assertEquals("Failed to read correct chars", " After test string", new String(buf, 0, r)
					);
		} catch (Exception e) {
			fail("Exception during Constructor test " + e.toString());
		}
	}

	/**
	 * @tests java.io.FileReader#FileReader(java.lang.String)
	 */
	public void test_ConstructorLjava_lang_String() {
		// Test for method java.io.FileReader(java.lang.String)
		try {
			bw = new BufferedWriter(new FileWriter(f.getPath()));
			bw.write(" After test string", 0, 18);
			bw.close();
			br = new FileReader(f.getPath());
			char[] buf = new char[100];
			int r = br.read(buf);
			br.close();
			assertEquals("Failed to read correct chars", " After test string", new String(buf, 0, r)
					);
		} catch (Exception e) {
			fail("Exception during Constructor test " + e.toString());
		}
	}

	/**
	 * Sets up the fixture, for example, open a network connection. This method
	 * is called before a test is executed.
	 */
	protected void setUp() {

		f = new File(System.getProperty("user.home"), "reader.tst");

		if (f.exists()) {
			if (!f.delete()) {
				fail("Unable to delete test file");
			}
		}
	}

	/**
	 * Tears down the fixture, for example, close a network connection. This
	 * method is called after a test is executed.
	 */
	protected void tearDown() {

		try {
			bw.close();
			br.close();
		} catch (Exception e) {
		}

		try {
			if (fis != null)
				fis.close();
		} catch (Exception e) {
		}
		f.delete();
	}
}


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

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:padding="5dp"
                android:textSize="15dp"
                android:maxLines="1"
                android:textColor="@color/primaryText"
                android:text="Sample"
                android:layout_alignParentTop="true"/>

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>


text:
/**
 * Module dependencies
 */

var cli = module.exports
var fs = require('fs')
var path = require('path')
var yargs = require('yargs')
var pkg = require(path.join(__dirname, '../../package.json'))
var usage = fs.readFileSync(path.join(__dirname, 'docs/usage.txt'), 'utf8')

yargs
  .usage(usage)
  // version
  .alias('v', 'version')
  .describe('v', 'Show version')
  // help
  .alias('h', 'help')
  .describe('h', 'Show usage')
  // environment
  .alias('e', 'environment')
  .describe('e', 'Set environment')
  // client (apply the operation to a client instead of a user)
  .boolean('c')

/**
 * Help
 */

cli.help = function () {
  yargs.showHelp()
  process.exit()
}

/**
 * Version
 */

cli.version = function () {
  console.log('Anvil Connect v%s', pkg.version)
  process.exit()
}

/**
 * Symbol table
 */

cli.symbols = {
  // commands and subcommands
  init: { type: 'command' },
  migrate: { type: 'command' },
  deployment: { type: 'subcommand' },
  db: { type: 'subcommand' },
  assign: { type: 'command' },
  revoke: { type: 'command' },
  permit: { type: 'command' },
  forbid: { type: 'command' },
  config: { type: 'command' },
  copy: { type: 'command' },
  signup: { type: 'command' },
  uri: { type: 'command' },
  serve: { type: 'command' },
  token: { type: 'command' },
  decode: { type: 'command' },

  // models
  role: { type: 'model', value: 'Role' },
  scope: { type: 'model', value: 'Scope' },
  client: { type: 'model', value: 'Client' },
  user: { type: 'model', value: 'User' },

  // methods
  ls: { type: 'method', value: 'list' },
  get: { type: 'method', value: 'get' },
  add: { type: 'method', value: 'insert' },
  update: { type: 'method', value: 'patch' },
  rm: { type: 'method', value: 'delete' }
}

/**
 * Command Parser
 */

cli.parse = function parse (tokens, options) {
  tokens = [].concat(tokens) // copy this and leave argv intact
  var command = {}
  var token
  var symbol

  // consume the tokens
  while (tokens.length > 0) {
    token = tokens.shift()
    symbol = cli.symbols[token]

    // the token has a symbol
    if (symbol) {
      switch (symbol.type) {
        case 'command':
          command.name = token
          break

        case 'subcommand':
          if (!command.name) { throw new Error('Unknown command') }
          command.name += '-' + token
          break

        case 'model':
          command.model = symbol.value
          break

        case 'method':
          command.method = symbol.value
          break

        default:
          throw new Error('Unrecognized symbol type')
      }

    // the token is a parameter
    } else if (!command.name) {
      // parse json into "data"
      if (token.indexOf('{') !== -1) {
        try {
          command.data = JSON.parse(token)
        } catch (e) {
          console.log(e)
          process.exit()
        }

      // treat the value as an identifier
      } else {
        command.identifier = token
      }
    }
  }

  return command
}

/**
 * Execute
 */

cli.exec = function exec (command, argv, done) {
  var cmd = command.name
  var model = command.model
  var method = command.method
  var identifier = command.identifier
  var data = command.data

  if (!cmd && !model) {
    cli.help()
  }

  // execute a simple command (and exit)
  if (cmd) {
    return require(path.join(__dirname, cmd))(argv)
  }

  // use email for identifier
  if (model === 'User' && identifier && identifier.indexOf('@') !== -1) {
    require(path.join(__dirname, '..', '..', 'models', model))
      .getByEmail(identifier, function (err, user) {
        if (err) { return done(err) }
        command.identifier = user._id
        exec(command, argv, done)
      })

  // invoke a model method
  } else if (!cmd) {
    if (!method) { throw new Error('Unknown method') }

    model = path.join(__dirname, '..', '..', 'models', model)

    if (model && method && identifier && data) {
      return require(model)[method](identifier, data, done)
    }

    if (model && method && identifier) {
      return require(model)[method](identifier, done)
    }

    if (model && method && data) {
      return require(model)[method](data, done)
    }

    if (model && method) {
      return require(model)[method](done)
    } else {
      done()
    }
  }
}

/**
 * Run
 */

cli.run = function () {
  var argv = yargs.argv
  var env = argv.e || argv.environment
  var tokens = [].concat(argv._)
  var command = cli.parse(tokens)

  if (argv.v || argv.version || command.name === 'version') {
    cli.version()
  }

  if (!command || argv.h || argv.help || command.name === 'help') {
    cli.help()
  }

  if (env && ['development', 'production'].indexOf(env) !== -1) {
    process.env.NODE_ENV = env
  }

  if (argv.production) {
    process.env.NODE_ENV = 'production'
  }

  try {
    cli.exec(command, argv, function (err, result) {
      if (err) { throw err }
      console.log(JSON.stringify(result, null, 2))
      process.exit()
    })
  } catch (e) {
    console.log(e)
    e.stack && console.log(e.stack)
    process.exit()
  }
}


text:
<?php

namespace CmsMediaForce\Fixture;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;

use CmsMediaForce\Entity\ArquivoTexto,
    CmsMediaForce\Entity\DadosCadConteudo;

use CmsBase\Helper\SlugHelper;

class LoadArquivoTexto extends AbstractFixture implements OrderedFixtureInterface {

    public function load(ObjectManager $manager) {

        $dirArquivos = 'public/files/formularios/';

        $endereco = 'files/formularios/';

        $scanDir = scandir($dirArquivos);

        $notToRead = array(
          '.',
          '..',
          '_'
        );

        foreach($scanDir as $file) {
            $file = utf8_decode($file);
            if (!in_array($file, $notToRead)) {
                $endereco = $endereco . $file;

                $ext = pathinfo($file, PATHINFO_EXTENSION);

                $titulo = basename($file, ".".$ext);

                $arquivo = new ArquivoTexto;

                $arquivo->setTitulo($titulo)
                    ->setEndereco($endereco);

                $formulario = $manager->getReference('CmsMediaForce\Entity\Categoria', 3);

                $arthurAdmin = $manager->getReference('CmsMediaForce\Entity\User', 1);

                $dadosCad = new DadosCadConteudo;

                $dadosCad->setSlug(SlugHelper::slug($arquivo->getTitulo()))
                    ->setCategoria($formulario)
                    ->setCriadoPor($arthurAdmin);

                $manager->persist($dadosCad);

                $arquivo->setDadosCad($dadosCad);

                $manager->persist($arquivo);

            }
        }

       /* $dirFormularios = 'public/arquivos/circulares/';

        $endereco = 'arquivos/circulares/';

        $scanDir = scandir($dirFormularios);

        foreach($scanDir as $file) {
            if (!in_array($file, $notToRead)) {
                $endereco = $endereco . $file;

                $ext = pathinfo($file, PATHINFO_EXTENSION);

                $titulo = basename($file, ".".$ext);

                $arquivo = new ArquivoTexto;

                $arquivo->setTitulo($titulo)
                    ->setEndereco($endereco);

                $circular = $manager->getReference('CmsMediaForce\Entity\Categoria', 4);

                $arthurAdmin = $manager->getReference('CmsMediaForce\Entity\User', 4);

                $dadosCad = new DadosCadConteudo;

                $dadosCad->setSlug(SlugHelper::slug($arquivo->getTitulo()))
                    ->setCategoria($circular)
                    ->setCriadoPor($arthurAdmin);

                $manager->persist($dadosCad);

                $arquivo->setDadosCad($dadosCad);

                $manager->persist($arquivo);

            }
        }*/

        $manager->flush();
    }

    public function getOrder() {
        return 3;
    }
}


text:
About Psyrun

Easy parameter space evaluation and serial farming.


text:
-- DROP TABLE action_template;

CREATE TABLE action_template
(
  id bigint NOT NULL,
  task_template_id bigint NOT NULL, -- Link to task_templates table.
  sequence integer NOT NULL, -- Sequence number of the action in selected task template.
  type_id integer NOT NULL, -- Type of the action. Move,Alter,Give or Take
  object_template_id bigint DEFAULT 0, -- Link to a template object. 0 if not applicable.
  instrument_template_id bigint DEFAULT 0, -- Link to instrument template table. 0 if not applicable.
  manner_template_id bigint DEFAULT 0, -- Link to manner table. 0 if not applicable
  duration bigint DEFAULT 0, -- Estimated duration of the action in ms. 0 If not applicable.
  location_template_id bigint DEFAULT 0, -- Link to object template table. 0 if not applicable
  ontology_id bigint, -- Ontological name of the template action. Link to ontology table.
  end_state integer,
  CONSTRAINT action_template_pk PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE action_template
  OWNER TO test;
COMMENT ON TABLE action_template
  IS 'Acions related to task templates';
COMMENT ON COLUMN action_template.task_template_id IS 'Link to task_templates table. ';
COMMENT ON COLUMN action_template.sequence IS 'Sequence number of the action in selected task template.';
COMMENT ON COLUMN action_template.type_id IS 'Type of the action. Move,Alter,Give or Take';
COMMENT ON COLUMN action_template.object_template_id IS 'Link to a template object. 0 if not applicable. ';
COMMENT ON COLUMN action_template.instrument_template_id IS 'Link to instrument template table. 0 if not applicable. ';
COMMENT ON COLUMN action_template.manner_template_id IS 'Link to manner table. 0 if not applicable';
COMMENT ON COLUMN action_template.duration IS 'Estimated duration of the action in ms. 0 If not applicable. ';
COMMENT ON COLUMN action_template.location_template_id IS 'Link to object template table. 0 if not applicable';
COMMENT ON COLUMN action_template.ontology_id IS 'Ontological name of the template action. Link to ontology table.';


text:
package com.spotify.styx.util;

import com.spotify.styx.model.Event;
import com.spotify.styx.model.EventVisitor;
import com.spotify.styx.model.ExecutionDescription;
import com.spotify.styx.model.TriggerParameters;
import com.spotify.styx.model.WorkflowInstance;
import com.spotify.styx.serialization.Json;
import com.spotify.styx.state.Message;
import com.spotify.styx.state.Trigger;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Utility for getting information about {@link Event}s
 */
public final class EventUtil {

  private EventUtil() {
    throw new UnsupportedOperationException();
  }

  public static String name(Event event) {
    return event.accept(EventNameVisitor.INSTANCE);
  }

  public static String info(Event event) {
    return event.accept(EventInfoVisitor.INSTANCE);
  }

  /**
   * An {@link EventVisitor} for extracting the info of an {@link Event}.
   */
  private enum EventInfoVisitor implements EventVisitor<String> {
    INSTANCE;

    @Override
    public String timeTrigger(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String triggerExecution(WorkflowInstance workflowInstance, Trigger trigger,
        TriggerParameters parameters) {
      return String.format("Trigger id: %s, Parameters: %s", TriggerUtil.triggerId(trigger),
          Json.deterministicStringUnchecked(parameters));
    }

    @Override
    public String info(WorkflowInstance workflowInstance, Message message) {
      return message.line();
    }

    @Override
    public String created(WorkflowInstance workflowInstance, String executionId, String dockerImage) {
      return String.format("Execution id: %s, Docker image: %s", executionId, dockerImage);
    }

    @Override
    public String dequeue(WorkflowInstance workflowInstance, Set<String> resourceIds) {
      return "";
    }

    @Override
    public String started(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String terminate(WorkflowInstance workflowInstance, Optional<Integer> exitCode) {
      return "Exit code: " + exitCode.map(String::valueOf).orElse("-");
    }

    @Override
    public String runError(WorkflowInstance workflowInstance, String message) {
      return "Error message: " + message;
    }

    @Override
    public String success(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String retryAfter(WorkflowInstance workflowInstance, long delayMillis) {
      return String.format("Delay (seconds): %d", TimeUnit.MILLISECONDS.toSeconds(delayMillis));
    }

    @Override
    public String retry(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String stop(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String timeout(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String halt(WorkflowInstance workflowInstance) {
      return "";
    }

    @Override
    public String submit(WorkflowInstance workflowInstance, ExecutionDescription executionDescription,
        String executionId) {
      return String.format("Execution description: %s, id: %s", executionDescription, executionId);
    }

    @Override
    public String submitted(WorkflowInstance workflowInstance, String executionId, String runnerId) {
      return String.format("Execution id: %s, runner id: %s", executionId, runnerId);
    }
  }

  /**
   * An {@link EventVisitor} for extracting the name of an {@link Event}.
   */
  private enum EventNameVisitor implements EventVisitor<String> {
    INSTANCE;

    @Override
    public String timeTrigger(WorkflowInstance workflowInstance) {
      return "timeTrigger";
    }

    @Override
    public String triggerExecution(WorkflowInstance workflowInstance, Trigger trigger,
        TriggerParameters parameters) {
      return "triggerExecution";
    }

    @Override
    public String info(WorkflowInstance workflowInstance, Message message) {
      return "info";
    }

    @Override
    public String dequeue(WorkflowInstance workflowInstance, Set<String> resourceIds) {
      return "dequeue";
    }

    @Override
    public String created(WorkflowInstance workflowInstance, String executionId,
        String dockerImage) {
      return "created";
    }

    @Override
    public String started(WorkflowInstance workflowInstance) {
      return "started";
    }

    @Override
    public String terminate(WorkflowInstance workflowInstance, Optional<Integer> exitCode) {
      return "terminate";
    }

    @Override
    public String runError(WorkflowInstance workflowInstance, String message) {
      return "runError";
    }

    @Override
    public String success(WorkflowInstance workflowInstance) {
      return "success";
    }

    @Override
    public String retryAfter(WorkflowInstance workflowInstance, long delayMillis) {
      return "retryAfter";
    }

    @Override
    public String retry(WorkflowInstance workflowInstance) {
      return "retry";
    }

    @Override
    public String stop(WorkflowInstance workflowInstance) {
      return "stop";
    }

    @Override
    public String timeout(WorkflowInstance workflowInstance) {
      return "timeout";
    }

    @Override
    public String halt(WorkflowInstance workflowInstance) {
      return "halt";
    }

    @Override
    public String submit(WorkflowInstance workflowInstance, ExecutionDescription executionDescription,
        String executionId) {
      return "submit";
    }

    @Override
    public String submitted(WorkflowInstance workflowInstance, String executionId, String runnerId) {
      return "submitted";
    }
  }
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Loader;

require_once __DIR__ . '/AppKernel.php';

class _Kernel extends AppKernel
{
    /**
     * @var \Closure
     */
    private $kernelModifier = null;

    public function boot()
    {
        parent::boot();

        if ($kernelModifier = $this->kernelModifier) {
            $kernelModifier($this);
            $this->kernelModifier = null;
        };
    }

    public function setKernelModifier(\Closure $kernelModifier)
    {
        $this->kernelModifier = $kernelModifier;

        // We force the kernel to shutdown to be sure the next request will boot it
        $this->shutdown();
    }
}


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

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.fest.assertions.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.Response.Status;

import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition;
import org.camunda.bpm.engine.repository.DecisionRequirementsDefinitionQuery;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mockito;

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

public class DecisionRequirementsDefinitionRestServiceQueryTest extends AbstractRestServiceTest {

  @ClassRule
  public static TestContainerRule rule = new TestContainerRule();

  protected static final String DECISION_REQUIREMENTS_DEFINITION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/decision-requirements-definition";
  protected static final String DECISION_REQUIREMENTS_DEFINITION_COUNT_QUERY_URL = DECISION_REQUIREMENTS_DEFINITION_QUERY_URL + "/count";

  private DecisionRequirementsDefinitionQuery mockedQuery;

  @Before
  public void setUpRuntime() {
    DecisionRequirementsDefinition mockDecisionRequirementsDefinition = MockProvider.createMockDecisionRequirementsDefinition();
    mockedQuery = createMockQuery(Collections.singletonList(mockDecisionRequirementsDefinition));
  }

  private DecisionRequirementsDefinitionQuery createMockQuery(List<DecisionRequirementsDefinition> mockedDefinitions) {
    DecisionRequirementsDefinitionQuery query = mock(DecisionRequirementsDefinitionQuery.class);

    when(query.list()).thenReturn(mockedDefinitions);
    when(query.count()).thenReturn((long) mockedDefinitions.size());
    when(processEngine.getRepositoryService().createDecisionRequirementsDefinitionQuery()).thenReturn(query);

    return query;
  }

  @Test
  public void testEmptyQuery() {
    given()
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).list();
  }

  @Test
  public void testInvalidNumericParameter() {
    String anInvalidIntegerQueryParam = "aString";

    given()
      .queryParam("version", anInvalidIntegerQueryParam)
      .then()
        .expect()
          .statusCode(Status.BAD_REQUEST.getStatusCode())
          .contentType(ContentType.JSON)
          .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
          .body("message", equalTo("Cannot set query parameter 'version' to value 'aString': "
            + "Cannot convert value aString to java type java.lang.Integer"))
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);
  }

  @Test
  public void testInvalidBooleanParameter() {
    String anInvalidBooleanQueryParam = "neitherTrueNorFalse";

    given().queryParam("latestVersion", anInvalidBooleanQueryParam)
      .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON)
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo("Cannot set query parameter 'latestVersion' to value 'neitherTrueNorFalse': "
          + "Cannot convert value neitherTrueNorFalse to java type java.lang.Boolean"))
      .when().get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);
  }

  @Test
  public void testInvalidSortingOptions() {
    executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST);
    executeAndVerifySorting("id", "anInvalidSortOrderOption", Status.BAD_REQUEST);
  }

  @Test
  public void testSortByParameterOnly() {
    given()
      .queryParam("sortBy", "id")
      .then()
        .expect()
          .statusCode(Status.BAD_REQUEST.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);
  }

  @Test
  public void testSortOrderParameterOnly() {
    given()
      .queryParam("sortOrder", "asc")
      .then()
        .expect()
          .statusCode(Status.BAD_REQUEST.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);
  }

  protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) {
    given()
      .queryParam("sortBy", sortBy)
      .queryParam("sortOrder", sortOrder)
    .then()
      .expect()
        .statusCode(expectedStatus.getStatusCode())
    .when()
      .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);
  }

  @Test
  public void testSortingParameters() {
    // asc
    InOrder inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("id", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionId();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("name", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionName();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("version", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionVersion();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("key", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("category", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionCategory();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("deploymentId", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByDeploymentId();
    inOrder.verify(mockedQuery).asc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("tenantId", "asc", Status.OK);
    inOrder.verify(mockedQuery).orderByTenantId();
    inOrder.verify(mockedQuery).asc();

    // desc
    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("id", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionId();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("name", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionName();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("version", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionVersion();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("key", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("category", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionCategory();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("deploymentId", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByDeploymentId();
    inOrder.verify(mockedQuery).desc();

    inOrder = Mockito.inOrder(mockedQuery);
    executeAndVerifySorting("tenantId", "desc", Status.OK);
    inOrder.verify(mockedQuery).orderByTenantId();
    inOrder.verify(mockedQuery).desc();
  }

  @Test
  public void testSuccessfulPagination() {
    int firstResult = 0;
    int maxResults = 10;

    given()
      .queryParam("firstResult", firstResult)
      .queryParam("maxResults", maxResults)
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).listPage(firstResult, maxResults);
  }

  /**
   * If parameter "firstResult" is missing, we expect 0 as default.
   */
  @Test
  public void testMissingFirstResultParameter() {
    int maxResults = 10;

    given()
      .queryParam("maxResults", maxResults)
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).listPage(0, maxResults);
  }

  /**
   * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default.
   */
  @Test
  public void testMissingMaxResultsParameter() {
    int firstResult = 10;

    given()
      .queryParam("firstResult", firstResult)
      .then()
        .expect()
          .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE);
  }

  @Test
  public void testDecisionRequirementsDefinitionRetrieval() {
    Response response = given()
        .then()
          .expect()
            .statusCode(Status.OK.getStatusCode())
        .when()
          .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    // assert query invocation
    InOrder inOrder = Mockito.inOrder(mockedQuery);
    inOrder.verify(mockedQuery).list();

    String content = response.asString();
    List<Map<String, String>> decisionRequirementsDefinitions = from(content).getList("");

    assertThat(decisionRequirementsDefinitions).hasSize(1);
    assertThat(decisionRequirementsDefinitions.get(0)).isNotNull();

    String returnedId = from(content).getString("[0].id");
    String returnedKey = from(content).getString("[0].key");
    String returnedCategory = from(content).getString("[0].category");
    String returnedName = from(content).getString("[0].name");
    int returnedVersion = from(content).getInt("[0].version");
    String returnedResource = from(content).getString("[0].resource");
    String returnedDeploymentId = from(content).getString("[0].deploymentId");
    String returnedTenantId = from(content).getString("[0].tenantId");

    assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID);
    assertThat(returnedKey).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY);
    assertThat(returnedCategory).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY);
    assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME);
    assertThat(returnedVersion).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION);
    assertThat(returnedResource).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME);
    assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_DEPLOYMENT_ID);
    assertThat(returnedTenantId).isEqualTo(null);
  }

  @Test
  public void testDecisionRequirementsDefinitionRetrievalByList() {
    mockedQuery = createMockQuery(MockProvider.createMockTwoDecisionRequirementsDefinitions());

    Response response = given()
      .queryParam("decisionRequirementsDefinitionIdIn", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID_LIST)
      .then().expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    // assert query invocation
    InOrder inOrder = Mockito.inOrder(mockedQuery);
    inOrder.verify(mockedQuery).decisionRequirementsDefinitionIdIn(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID);
    inOrder.verify(mockedQuery).list();

    String content = response.asString();
    List<String> definitions = from(content).getList("");
    assertThat(definitions).hasSize(2);

    String returnedDefinitionId1 = from(content).getString("[0].id");
    String returnedDefinitionId2 = from(content).getString("[1].id");

    assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID);
    assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID);
  }

  @Test
  public void testDecisionRequirementsDefinitionRetrievalByEmptyList() {
    given()
      .queryParam("decisionRequirementsDefinitionIdIn", "")
      .then().expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    // assert query invocation
    InOrder inOrder = Mockito.inOrder(mockedQuery);
    inOrder.verify(mockedQuery, never()).decisionRequirementsDefinitionIdIn(Matchers.<String[]>anyVararg());
    inOrder.verify(mockedQuery).list();
  }

  @Test
  public void testAdditionalParameters() {
    Map<String, String> queryParameters = getCompleteQueryParameters();

    given()
      .queryParams(queryParameters)
      .expect()
        .statusCode(Status.OK.getStatusCode())
      .when()
        .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    // assert query invocation
    verify(mockedQuery).decisionRequirementsDefinitionId(queryParameters.get("decisionRequirementsDefinitionId"));
    verify(mockedQuery).decisionRequirementsDefinitionCategory(queryParameters.get("category"));
    verify(mockedQuery).decisionRequirementsDefinitionCategoryLike(queryParameters.get("categoryLike"));
    verify(mockedQuery).decisionRequirementsDefinitionName(queryParameters.get("name"));
    verify(mockedQuery).decisionRequirementsDefinitionNameLike(queryParameters.get("nameLike"));
    verify(mockedQuery).decisionRequirementsDefinitionKey(queryParameters.get("key"));
    verify(mockedQuery).decisionRequirementsDefinitionKeyLike(queryParameters.get("keyLike"));
    verify(mockedQuery).decisionRequirementsDefinitionVersion(Integer.parseInt(queryParameters.get("version")));
    verify(mockedQuery).latestVersion();
    verify(mockedQuery).decisionRequirementsDefinitionResourceName(queryParameters.get("resourceName"));
    verify(mockedQuery).decisionRequirementsDefinitionResourceNameLike(queryParameters.get("resourceNameLike"));
    verify(mockedQuery).deploymentId(queryParameters.get("deploymentId"));
    verify(mockedQuery).list();
  }

  @Test
  public void testDecisionRequirementDefinitionTenantIdList() {
    List<DecisionRequirementsDefinition> decisionRequirementsDefinitions = Arrays.asList(
        MockProvider.mockDecisionRequirementsDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(),
        MockProvider.createAnotherMockDecisionRequirementsDefinition());
    mockedQuery = createMockQuery(decisionRequirementsDefinitions);

    Response response = given()
      .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
    verify(mockedQuery).list();

    String content = response.asString();
    List<String> definitions = from(content).getList("");
    assertThat(definitions).hasSize(2);

    String returnedTenantId1 = from(content).getString("[0].tenantId");
    String returnedTenantId2 = from(content).getString("[1].tenantId");

    assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
    assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
  }

  @Test
  public void testDecisionRequirementsDefinitionWithoutTenantId() {
    Response response = given()
      .queryParam("withoutTenantId", true)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).withoutTenantId();
    verify(mockedQuery).list();

    String content = response.asString();
    List<String> definitions = from(content).getList("");
    assertThat(definitions).hasSize(1);

    String returnedTenantId1 = from(content).getString("[0].tenantId");
    assertThat(returnedTenantId1).isEqualTo(null);
  }

  @Test
  public void testDecisionRequirementsDefinitionTenantIdIncludeDefinitionsWithoutTenantid() {
    List<DecisionRequirementsDefinition> decisionDefinitions = Arrays.asList(
        MockProvider.mockDecisionRequirementsDefinition().tenantId(null).build(),
        MockProvider.mockDecisionRequirementsDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build());
    mockedQuery = createMockQuery(decisionDefinitions);

    Response response = given()
      .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID)
      .queryParam("includeDecisionRequirementsDefinitionsWithoutTenantId", true)
    .then().expect()
      .statusCode(Status.OK.getStatusCode())
    .when()
      .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL);

    verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID);
    verify(mockedQuery).includeDecisionRequirementsDefinitionsWithoutTenantId();
    verify(mockedQuery).list();

    String content = response.asString();
    List<String> definitions = from(content).getList("");
    assertThat(definitions).hasSize(2);

    String returnedTenantId1 = from(content).getString("[0].tenantId");
    String returnedTenantId2 = from(content).getString("[1].tenantId");

    assertThat(returnedTenantId1).isEqualTo(null);
    assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
  }

  @Test
  public void testQueryCount() {
    expect().statusCode(Status.OK.getStatusCode())
      .body("count", equalTo(1))
      .when().get(DECISION_REQUIREMENTS_DEFINITION_COUNT_QUERY_URL);

    verify(mockedQuery).count();
  }

  private Map<String, String> getCompleteQueryParameters() {
    Map<String, String> parameters = new HashMap<String, String>();

    parameters.put("decisionRequirementsDefinitionId", "anId");
    parameters.put("category", "cat");
    parameters.put("categoryLike", "catlike");
    parameters.put("name", "name");
    parameters.put("nameLike", "namelike");
    parameters.put("key", "key");
    parameters.put("keyLike", "keylike");
    parameters.put("version", "1");
    parameters.put("latestVersion", "true");
    parameters.put("resourceName", "res");
    parameters.put("resourceNameLike", "resLike");
    parameters.put("deploymentId", "depId");

    return parameters;
  }

}


text:
\n
static inline void __iomem *ndrd_get_flush_wpq(struct nd_region_data *ndrd, int dimm, int hint)
static inline void ndrd_set_flush_wpq(struct nd_region_data *ndrd, int dimm, int hint, void __iomem *flush)
static inline struct nd_namespace_index *to_namespace_index( struct nvdimm_drvdata *ndd, int i)
static inline struct nd_namespace_index *to_current_namespace_index( struct nvdimm_drvdata *ndd)
static inline struct nd_namespace_index *to_next_namespace_index( struct nvdimm_drvdata *ndd)
static inline unsigned nd_inc_seq(unsigned seq)
int nd_integrity_init(struct gendisk *disk, unsigned long meta_size)
; void wait_nvdimm_bus_probe_idle(struct device *dev)
; void nd_device_register(struct device *dev)
; void nd_device_unregister(struct device *dev, enum nd_async_mode mode)
; void nd_device_notify(struct device *dev, enum nvdimm_event event)
; int nd_uuid_store(struct device *dev, u8 **uuid_out, const char *buf, size_t len)
; ssize_t nd_size_select_show(unsigned long current_size, const unsigned long *supported, char *buf)
; ssize_t nd_size_select_store(struct device *dev, const char *buf, unsigned long *current_size, const unsigned long *supported)
; int __init nvdimm_init(void)
; int __init nd_region_init(void)
; int __init nd_label_init(void)
; void nvdimm_exit(void)
; void nd_region_exit(void)
; struct nvdimm; struct nvdimm_drvdata *to_ndd(struct nd_mapping *nd_mapping)
; int nvdimm_check_config_data(struct device *dev)
; int nvdimm_init_nsarea(struct nvdimm_drvdata *ndd)
; int nvdimm_init_config_data(struct nvdimm_drvdata *ndd)
; int nvdimm_get_config_data(struct nvdimm_drvdata *ndd, void *buf, size_t offset, size_t len)
; int nvdimm_set_config_data(struct nvdimm_drvdata *ndd, size_t offset, void *buf, size_t len)
; long nvdimm_clear_poison(struct device *dev, phys_addr_t phys, unsigned int len)
; void nvdimm_set_aliasing(struct device *dev)
; void nvdimm_set_locked(struct device *dev)
; void nvdimm_clear_locked(struct device *dev)
; int nvdimm_security_setup_events(struct device *dev)
; int nvdimm_security_unlock(struct device *dev)
; static inline int nvdimm_security_unlock(struct device *dev)
u64 nd_sb_checksum(struct nd_gen_sb *sb)
; int nd_btt_probe(struct device *dev, struct nd_namespace_common *ndns)
; bool is_nd_btt(struct device *dev)
; struct device *nd_btt_create(struct nd_region *nd_region)
; static inline int nd_btt_probe(struct device *dev, struct nd_namespace_common *ndns)
static inline bool is_nd_btt(struct device *dev)
static inline struct device *nd_btt_create(struct nd_region *nd_region)
int nd_pfn_probe(struct device *dev, struct nd_namespace_common *ndns)
; bool is_nd_pfn(struct device *dev)
; struct device *nd_pfn_create(struct nd_region *nd_region)
; struct device *nd_pfn_devinit(struct nd_pfn *nd_pfn, struct nd_namespace_common *ndns)
; int nd_pfn_validate(struct nd_pfn *nd_pfn, const char *sig)
; extern struct attribute_group nd_pfn_attribute_group; static inline int nd_pfn_probe(struct device *dev, struct nd_namespace_common *ndns)
static inline bool is_nd_pfn(struct device *dev)
static inline struct device *nd_pfn_create(struct nd_region *nd_region)
static inline int nd_pfn_validate(struct nd_pfn *nd_pfn, const char *sig)
struct nd_dax *to_nd_dax(struct device *dev)
; int nd_dax_probe(struct device *dev, struct nd_namespace_common *ndns)
; bool is_nd_dax(struct device *dev)
; struct device *nd_dax_create(struct nd_region *nd_region)
; static inline int nd_dax_probe(struct device *dev, struct nd_namespace_common *ndns)
static inline bool is_nd_dax(struct device *dev)
static inline struct device *nd_dax_create(struct nd_region *nd_region)
int nd_region_to_nstype(struct nd_region *nd_region)
; int nd_region_register_namespaces(struct nd_region *nd_region, int *err)
; u64 nd_region_interleave_set_cookie(struct nd_region *nd_region, struct nd_namespace_index *nsindex)
; u64 nd_region_interleave_set_altcookie(struct nd_region *nd_region)
; void nvdimm_bus_lock(struct device *dev)
; void nvdimm_bus_unlock(struct device *dev)
; bool is_nvdimm_bus_locked(struct device *dev)
; int nvdimm_revalidate_disk(struct gendisk *disk)
; void nvdimm_drvdata_release(struct kref *kref)
; void put_ndd(struct nvdimm_drvdata *ndd)
; int nd_label_reserve_dpa(struct nvdimm_drvdata *ndd)
; void nvdimm_free_dpa(struct nvdimm_drvdata *ndd, struct resource *res)
; struct resource *nvdimm_allocate_dpa(struct nvdimm_drvdata *ndd, struct nd_label_id *label_id, resource_size_t start, resource_size_t n)
; resource_size_t nvdimm_namespace_capacity(struct nd_namespace_common *ndns)
; bool nvdimm_namespace_locked(struct nd_namespace_common *ndns)
; struct nd_namespace_common *nvdimm_namespace_common_probe(struct device *dev)
; int nvdimm_namespace_attach_btt(struct nd_namespace_common *ndns)
; int nvdimm_namespace_detach_btt(struct nd_btt *nd_btt)
; const char *nvdimm_namespace_disk_name(struct nd_namespace_common *ndns, char *name)
; unsigned int pmem_sector_size(struct nd_namespace_common *ndns)
; void nvdimm_badblocks_populate(struct nd_region *nd_region, struct badblocks *bb, const struct resource *res)
; int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
; int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
; void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
; static inline int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
int nd_region_to_nstype(struct nd_region *nd_region)
; int nd_region_register_namespaces(struct nd_region *nd_region, int *err)
; u64 nd_region_interleave_set_cookie(struct nd_region *nd_region, struct nd_namespace_index *nsindex)
; u64 nd_region_interleave_set_altcookie(struct nd_region *nd_region)
; void nvdimm_bus_lock(struct device *dev)
; void nvdimm_bus_unlock(struct device *dev)
; bool is_nvdimm_bus_locked(struct device *dev)
; int nvdimm_revalidate_disk(struct gendisk *disk)
; void nvdimm_drvdata_release(struct kref *kref)
; void put_ndd(struct nvdimm_drvdata *ndd)
; int nd_label_reserve_dpa(struct nvdimm_drvdata *ndd)
; void nvdimm_free_dpa(struct nvdimm_drvdata *ndd, struct resource *res)
; struct resource *nvdimm_allocate_dpa(struct nvdimm_drvdata *ndd, struct nd_label_id *label_id, resource_size_t start, resource_size_t n)
; resource_size_t nvdimm_namespace_capacity(struct nd_namespace_common *ndns)
; bool nvdimm_namespace_locked(struct nd_namespace_common *ndns)
; struct nd_namespace_common *nvdimm_namespace_common_probe(struct device *dev)
; int nvdimm_namespace_attach_btt(struct nd_namespace_common *ndns)
; int nvdimm_namespace_detach_btt(struct nd_btt *nd_btt)
; const char *nvdimm_namespace_disk_name(struct nd_namespace_common *ndns, char *name)
; unsigned int pmem_sector_size(struct nd_namespace_common *ndns)
; void nvdimm_badblocks_populate(struct nd_region *nd_region, struct badblocks *bb, const struct resource *res)
; int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
; int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
; void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
; static inline int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
return -ENXIO; } static inline int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
int nd_region_to_nstype(struct nd_region *nd_region)
; int nd_region_register_namespaces(struct nd_region *nd_region, int *err)
; u64 nd_region_interleave_set_cookie(struct nd_region *nd_region, struct nd_namespace_index *nsindex)
; u64 nd_region_interleave_set_altcookie(struct nd_region *nd_region)
; void nvdimm_bus_lock(struct device *dev)
; void nvdimm_bus_unlock(struct device *dev)
; bool is_nvdimm_bus_locked(struct device *dev)
; int nvdimm_revalidate_disk(struct gendisk *disk)
; void nvdimm_drvdata_release(struct kref *kref)
; void put_ndd(struct nvdimm_drvdata *ndd)
; int nd_label_reserve_dpa(struct nvdimm_drvdata *ndd)
; void nvdimm_free_dpa(struct nvdimm_drvdata *ndd, struct resource *res)
; struct resource *nvdimm_allocate_dpa(struct nvdimm_drvdata *ndd, struct nd_label_id *label_id, resource_size_t start, resource_size_t n)
; resource_size_t nvdimm_namespace_capacity(struct nd_namespace_common *ndns)
; bool nvdimm_namespace_locked(struct nd_namespace_common *ndns)
; struct nd_namespace_common *nvdimm_namespace_common_probe(struct device *dev)
; int nvdimm_namespace_attach_btt(struct nd_namespace_common *ndns)
; int nvdimm_namespace_detach_btt(struct nd_btt *nd_btt)
; const char *nvdimm_namespace_disk_name(struct nd_namespace_common *ndns, char *name)
; unsigned int pmem_sector_size(struct nd_namespace_common *ndns)
; void nvdimm_badblocks_populate(struct nd_region *nd_region, struct badblocks *bb, const struct resource *res)
; int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
; int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
; void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
; static inline int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
return -ENXIO; } static inline int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
return -ENXIO; } static inline void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
int nd_region_to_nstype(struct nd_region *nd_region)
; int nd_region_register_namespaces(struct nd_region *nd_region, int *err)
; u64 nd_region_interleave_set_cookie(struct nd_region *nd_region, struct nd_namespace_index *nsindex)
; u64 nd_region_interleave_set_altcookie(struct nd_region *nd_region)
; void nvdimm_bus_lock(struct device *dev)
; void nvdimm_bus_unlock(struct device *dev)
; bool is_nvdimm_bus_locked(struct device *dev)
; int nvdimm_revalidate_disk(struct gendisk *disk)
; void nvdimm_drvdata_release(struct kref *kref)
; void put_ndd(struct nvdimm_drvdata *ndd)
; int nd_label_reserve_dpa(struct nvdimm_drvdata *ndd)
; void nvdimm_free_dpa(struct nvdimm_drvdata *ndd, struct resource *res)
; struct resource *nvdimm_allocate_dpa(struct nvdimm_drvdata *ndd, struct nd_label_id *label_id, resource_size_t start, resource_size_t n)
; resource_size_t nvdimm_namespace_capacity(struct nd_namespace_common *ndns)
; bool nvdimm_namespace_locked(struct nd_namespace_common *ndns)
; struct nd_namespace_common *nvdimm_namespace_common_probe(struct device *dev)
; int nvdimm_namespace_attach_btt(struct nd_namespace_common *ndns)
; int nvdimm_namespace_detach_btt(struct nd_btt *nd_btt)
; const char *nvdimm_namespace_disk_name(struct nd_namespace_common *ndns, char *name)
; unsigned int pmem_sector_size(struct nd_namespace_common *ndns)
; void nvdimm_badblocks_populate(struct nd_region *nd_region, struct badblocks *bb, const struct resource *res)
; int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
; int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
; void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
; static inline int nvdimm_setup_pfn(struct nd_pfn *nd_pfn, struct dev_pagemap *pgmap)
return -ENXIO; } static inline int devm_nsio_enable(struct device *dev, struct nd_namespace_io *nsio)
return -ENXIO; } static inline void devm_nsio_disable(struct device *dev, struct nd_namespace_io *nsio)
}endif int nd_blk_region_init(struct nd_region *nd_region)
; int nd_region_activate(struct nd_region *nd_region)
; void __nd_iostat_start(struct bio *bio, unsigned long *start)
; static inline bool nd_iostat_start(struct bio *bio, unsigned long *start)
*start = jiffies;generic_start_io_acct(disk->queue, bio_op(bio)
, bio_sectors(bio)
, &disk->part0)
;return true; } static inline void nd_iostat_end(struct bio *bio, unsigned long start)
generic_end_io_acct(disk->queue, bio_op(bio)
, &disk->part0, start)
; } static inline bool is_bad_pmem(struct badblocks *bb, sector_t sector, unsigned int len)
\n
     56 struct device *dev
     28 struct nd_region *nd_region
     27 struct nd_namespace_common *ndns
     23 struct nvdimm_drvdata *ndd
     13 struct nd_namespace_io *nsio
     11 struct nd_pfn *nd_pfn
      8 struct dev_pagemap *pgmap
      5 void
      5 struct gendisk *disk
      5 struct badblocks *bb
      4 struct resource *res
      4 struct nd_namespace_index *nsindex
      4 struct nd_label_id *label_id
      4 struct nd_btt *nd_btt
      4 struct kref *kref
      4 resource_size_t start
      4 resource_size_t n
      4 int *err
      4 const struct resource *res
      4 char *name
      3 struct bio *bio
      3 size_t len
      2 void *buf
      2 unsigned long *start
      2 unsigned int len
      2 struct nd_region_data *ndrd
      2 size_t offset
      2 int hint
      2 int dimm
      2 disk->queue
      2 const unsigned long *supported
      2 const char *sig
      2 const char *buf
      2 bio_opbio
      1 void __iomem *flush
      1 unsigned seq
      1 unsigned long start
      1 unsigned long meta_size
      1 unsigned long current_size
      1 unsigned long *current_size
      1 u8 **uuid_out
      1 struct nd_mapping *nd_mapping
      1 struct nd_gen_sb *sb
      1 sector_t sector
      1 phys_addr_t phys
      1 int i
      1 enum nvdimm_event event
      1 enum nd_async_mode mode
      1 char *buf
      1 bio


text:
module Azure::DevTestLabs::Mgmt::V2016_05_15
  module Models
    #
    # Defines values for HostCachingOptions
    #
    module HostCachingOptions
      None = "None"
      ReadOnly = "ReadOnly"
      ReadWrite = "ReadWrite"
    end
  end
end


text:
package smile.classification;

import java.io.Serializable;
import java.util.Arrays;
import smile.math.Math;
import smile.math.distance.Distance;
import smile.math.distance.EuclideanDistance;
import smile.math.distance.Metric;
import smile.neighbor.CoverTree;
import smile.neighbor.KDTree;
import smile.neighbor.KNNSearch;
import smile.neighbor.LinearSearch;
import smile.neighbor.Neighbor;

/**
 * K-nearest neighbor classifier. The k-nearest neighbor algorithm (k-NN) is
 * a method for classifying objects by a majority vote of its neighbors,
 * with the object being assigned to the class most common amongst its k
 * nearest neighbors (k is a positive integer, typically small).
 * k-NN is a type of instance-based learning, or lazy learning where the
 * function is only approximated locally and all computation
 * is deferred until classification.
 *

 * The best choice of k depends upon the data; generally, larger values of
 * k reduce the effect of noise on the classification, but make boundaries
 * between classes less distinct. A good k can be selected by various
 * heuristic techniques, e.g. cross-validation. In binary problems, it is
 * helpful to choose k to be an odd number as this avoids tied votes.
 *

 * A drawback to the basic majority voting classification is that the classes
 * with the more frequent instances tend to dominate the prediction of the
 * new object, as they tend to come up in the k nearest neighbors when
 * the neighbors are computed due to their large number. One way to overcome
 * this problem is to weight the classification taking into account the
 * distance from the test point to each of its k nearest neighbors.
 *

 * Often, the classification accuracy of k-NN can be improved significantly
 * if the distance metric is learned with specialized algorithms such as
 * Large Margin Nearest Neighbor or Neighborhood Components Analysis.
 *

 * Nearest neighbor rules in effect compute the decision boundary in an
 * implicit manner. It is also possible to compute the decision boundary
 * itself explicitly, and to do so in an efficient manner so that the
 * computational complexity is a function of the boundary complexity.
 *

 * The nearest neighbor algorithm has some strong consistency results. As
 * the amount of data approaches infinity, the algorithm is guaranteed to
 * yield an error rate no worse than twice the Bayes error rate (the minimum
 * achievable error rate given the distribution of the data). k-NN is
 * guaranteed to approach the Bayes error rate, for some value of k (where k
 * increases as a function of the number of data points).
 *
 * @author Haifeng Li
 */
public class KNN<T> implements SoftClassifier<T>, Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * The data structure for nearest neighbor search.
     */
    private KNNSearch<T, T> knn;
    /**
     * The labels of training samples.
     */
    private int[] y;
    /**
     * The number of neighbors for decision.
     */
    private int k;
    /**
     * The number of classes.
     */
    private int c;

    /**
     * Trainer for KNN classifier.
     */
    public static class Trainer<T> extends ClassifierTrainer<T> {
        /**
         * The number of neighbors.
         */
        private int k;
        /**
         * The distance functor.
         */
        private Distance<T> distance;

        /**
         * Constructor.
         *
         * @param distance the distance metric functor.
         * @param k the number of neighbors.
         */
        public Trainer(Distance<T> distance, int k) {
            if (k < 1) {
                throw new IllegalArgumentException("Invalid k of k-NN: " + k);
            }

            this.distance = distance;
            this.k = k;
        }

        @Override
        public KNN<T> train(T[] x, int[] y) {
            return new KNN<T>(x, y, distance, k);
        }
    }

    /**
     * Constructor.
     * @param knn k-nearest neighbor search data structure of training instances.
     * @param y training labels in [0, c), where c is the number of classes.
     * @param k the number of neighbors for classification.
     */
    public KNN(KNNSearch<T, T> knn, int[] y, int k) {
        this.knn = knn;
        this.k = k;
        this.y = y;

        // class label set.
        int[] labels = Math.unique(y);
        Arrays.sort(labels);

        for (int i = 0; i < labels.length; i++) {
            if (labels[i] < 0) {
                throw new IllegalArgumentException("Negative class label: " + labels[i]);
            }

            if (i > 0 && labels[i] - labels[i-1] > 1) {
                throw new IllegalArgumentException("Missing class: " + labels[i]+1);
            }
        }

        c = labels.length;
        if (c < 2) {
            throw new IllegalArgumentException("Only one class.");
        }
    }

    /**
     * Constructor. By default, this is a 1-NN classifier.
     * @param x training samples.
     * @param y training labels in [0, c), where c is the number of classes.
     * @param distance the distance measure for finding nearest neighbors.
     */
    public KNN(T[] x, int[] y, Distance<T> distance) {
        this(x, y, distance, 1);
    }

    /**
     * Learn the K-NN classifier from data of any generalized type with a given
     * distance definition.
     * @param k the number of neighbors for classification.
     * @param x training samples.
     * @param y training labels in [0, c), where c is the number of classes.
     * @param distance the distance measure for finding nearest neighbors.
     */
    public KNN(T[] x, int[] y, Distance<T> distance, int k) {
        if (x.length != y.length) {
            throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
        }

        if (k < 1) {
            throw new IllegalArgumentException("Illegal k = " + k);
        }

        // class label set.
        int[] labels = Math.unique(y);
        Arrays.sort(labels);

        for (int i = 0; i < labels.length; i++) {
            if (labels[i] < 0) {
                throw new IllegalArgumentException("Negative class label: " + labels[i]);
            }

            if (i > 0 && labels[i] - labels[i-1] > 1) {
                throw new IllegalArgumentException("Missing class: " + labels[i]+1);
            }
        }

        c = labels.length;
        if (c < 2) {
            throw new IllegalArgumentException("Only one class.");
        }

        this.y = y;
        this.k = k;
        if (distance instanceof Metric) {
            knn = new CoverTree<T>(x, (Metric<T>) distance);
        } else {
            knn = new LinearSearch<T>(x, distance);
        }
    }

    /**
     * Learn the 1-NN classifier from data of type double[].
     * @param x the training samples.
     * @param y training labels in [0, c), where c is the number of classes.
     */
    public static KNN<double[]> learn(double[][] x, int[] y) {
        return learn(x, y, 1);
    }

    /**
     * Learn the K-NN classifier from data of type double[].
     * @param k the number of neighbors for classification.
     * @param x training samples.
     * @param y training labels in [0, c), where c is the number of classes.
     */
    public static KNN<double[]> learn(double[][] x, int[] y, int k) {
        if (x.length != y.length) {
            throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
        }

        if (k < 1) {
            throw new IllegalArgumentException("Illegal k = " + k);
        }

        KNNSearch<double[], double[]> knn = null;
        if (x[0].length < 10) {
            knn = new KDTree<double[]>(x, x);
        } else {
            knn = new CoverTree<double[]>(x, new EuclideanDistance());
        }

        return new KNN<double[]>(knn, y, k);
    }

    @Override
    public int predict(T x) {
        return predict(x, null);
    }

    @Override
    public int predict(T x, double[] posteriori) {
        if (posteriori != null && posteriori.length != c) {
            throw new IllegalArgumentException(String.format("Invalid posteriori vector size: %d, expected: %d", posteriori.length, c));
        }

        Neighbor<T,T>[] neighbors = knn.knn(x, k);
        if (k == 1) {
            return y[neighbors[0].index];
        }

        int[] count = new int[c];
        for (int i = 0; i < k; i++) {
            count[y[neighbors[i].index]]++;
        }

        if (posteriori != null) {
            for (int i = 0; i < c; i++) {
                posteriori[i] = (double) count[i] / k;
            }
        }

        int max = 0;
        int idx = 0;
        for (int i = 0; i < c; i++) {
            if (count[i] > max) {
                max = count[i];
                idx = i;
            }
        }

        return idx;
    }
}


text:
package com.nibado.example.spark.loader;

import com.nibado.example.spark.analyse.WordList;

import java.io.*;

/**
 * Loader for 'condensed' word lists. The file in the repo is a sentiwordnet file with redundant information stripped out
 * to bring down the size by quite a large margin.
 */
public class CondensedLoader implements WordListLoader {
    @Override
    public void load(WordList list, InputStream stream) throws IOException {
        try(BufferedReader ins = new BufferedReader(new InputStreamReader(stream))) {
            String line;
            while((line = ins.readLine()) != null) {
                addLine(list, line);
            }
        }
    }

    private void addLine(WordList list, String line) {
        String[] parts = line.split(",");
        list.add(parts[0], Double.parseDouble(parts[1]), Double.parseDouble(parts[2]));
    }
}


text:
import random
from Queue import Queue
import timeit
import subprocess
import sys
import os

class Leaf(object):
    '''Create leaf.'''
    def __init__(self, key, left=None, right=None, parent=None):
        self.left = left
        self.key = key
        self.right = right
        self.parent = parent

    def __repr__(self):
        if self.parent:
            parent = self.parent.key
        else:
            parent = None
        if self.left:
            left = self.left.key
        else:
            left = None
        if self.right:
            right = self.right.key
        else:
            right = None
        return "parent = {}, left = {} , right = {}".format(parent, left, right)

    def _get_dot(self):
        """recursively prepare a dot graph entry for this node."""
        if self.parent is not None:
            yield "\t%s -> %s;" % (self.key, self.parent.key)
        if self.left is not None:
            yield "\t%s -> %s;" % (self.key, self.left.key)
            for i in self.left._get_dot():
                yield i
        elif self.right is not None:
            r = random.randint(0, 1e9)
            yield "\tnull%s [shape=point];" % r
            yield "\t%s -> null%s;" % (self.key, r)
        if self.right is not None:
            yield "\t%s -> %s;" % (self.key, self.right.key)
            for i in self.right._get_dot():
                yield i
        elif self.left is not None:
            r = random.randint(0, 1e9)
            yield "\tnull%s [shape=point];" % r
            yield "\t%s -> null%s;" % (self.key, r)

class Tree(object):
    '''Create tree'''

    def __init__(self, root=None):
        self.root = root

    def _contains(self, key, leaf):
        if leaf is None or leaf.key == key:
            return leaf
        elif key < leaf.key:
            return self._contains(key, leaf.left)
        else:
            return self._contains(key, leaf.right)

    def contains(self, key):
        return bool(self._contains(key, self.root))

    def insert(self, key):
        if not self.root:
            self.root = Leaf(key)
        else:
            self._insert(key, self.root)

    def _insert(self, key, leaf):
        if key == leaf.key:
            return leaf
        elif key < leaf.key:
            if leaf.left:
                return self._insert(key, leaf.left)
            else:
                leaf.left = Leaf(key, parent=leaf)
                return leaf.left
        else:
            if leaf.right:
                return self._insert(key, leaf.right)
            else:
                leaf.right = Leaf(key, parent=leaf)
                return leaf.right

    def _find_replacement(self, leaf):
        current = leaf
        while current.right:
            current = current.right
        return current

    def _remove_node(self, leaf, replacement_leaf=None):
        if leaf.parent:
            if leaf.parent.left == leaf:
                leaf.parent.left = leaf.left
            else:
                leaf.parent.right = leaf.right
        if replacement_leaf:
            replacement_leaf.parent = leaf.parent

    def delete(self, target):
        self._delete(target, self.root)

    def _delete(self, target, start):
        leaf = self._contains(target, start)
        if leaf:
            if leaf.left and leaf.right:
                successor = self._find_replacement(leaf.left)
                leaf.key = successor.key
                self._delete(successor.key, successor)
            elif leaf.left:
                self._remove_node(leaf, leaf.left)
            elif leaf.right:
                self._remove_node(leaf, leaf.right)
            else:
                self._remove_node(leaf)

    def size(self):
        if not self.root:
            return 0
        else:
            return self._size(self.root, 1)

    def _size(self, leaf, count):
        if leaf.left:
            count += 1
            count = self._size(leaf.left, count)
        if leaf.right:
            count += 1
            count = self._size(leaf.right, count)
        return count

    def depth(self):
        if not self.root:
            return 0
        else:
            return self._depth(self.root)[0]

    def _depth(self, leaf):
        if leaf is None:
            return 0, 0, 0
        else:
            depthL = self._depth(leaf.left)[0]
            depthR = self._depth(leaf.right)[0]
        return max([depthL, depthR]) + 1, depthL, depthR

    def balance(self, start=None):
        if not start:
            return self._balance(self.root)
        else:
            return self._balance(start)

    def _balance(self, leaf):
        depthL, depthR = self._depth(leaf)[1:3]
        return depthL - depthR

    def in_order(self):
        return self._in_order(self.root)

    def _in_order(self, leaf):
        if leaf is None:
            return
        for val in self._in_order(leaf.left):
            yield val
        yield leaf.key
        for val in self._in_order(leaf.right):
            yield val

    def pre_order(self):
        return self._pre_order(self.root)

    def _pre_order(self, leaf):
        if leaf is None:
            return
        yield leaf.key
        for val in self._pre_order(leaf.left):
            yield val
        for val in self._pre_order(leaf.right):
            yield val

    def post_order(self):
        return self._post_order(self.root)

    def _post_order(self, leaf):
        if leaf is None:
            return
        for val in self._post_order(leaf.left):
            yield val
        for val in self._post_order(leaf.right):
            yield val
        yield leaf.key

    def breadth_first_traversal(self):
        q = Queue()
        q.put(self.root)
        while not q.empty():
            leaf = q.get()
            yield leaf.key
            if leaf.left:
                q.put(leaf.left)
            if leaf.right:
                q.put(leaf.right)

    def get_dot(self):
        """return the tree with root 'self' as a dot graph for visualization"""
        return "digraph G{\n%s}" % ("" if self.root.key is None else (
            "\t%s;\n%s\n" % (
                self.root.key,
                "\n".join(self.root._get_dot())
            )
        ))

    def graph(self, file_name):
        t = subprocess.Popen(["dot", "-Tpng"],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        png_data = t.communicate(self.get_dot())
        with open('{}.png'.format(file_name), 'w') as png_file:
            png_file.write(png_data[0])
        os.system('open {}.png'.format(file_name))

    def nuclear_option(self):
        generator = self.in_order()
        num = []
        while True:
            try:
                num.append(generator.next())
            except StopIteration:
                self.root = self._nuclear_option(num, 0, len(num)-1, None)
                return

    def _nuclear_option(self, num, begin, end, parent):
        if begin > end:
            return None
        midPoint = (begin+end)//2
        root = Leaf(num[midPoint], parent=parent)
        root.left = self._nuclear_option(num, begin, midPoint-1, root)
        root.right = self._nuclear_option(num, midPoint+1, end, root)
        return root

    def avl_insert(self, key):
        if not self.root:
            self.root = Leaf(key)
        else:
            self._insert(key, self.root)
            # self.graph('1_Pre_AVL_Balance')
            bal = self.balance(self.root)
            if bal > 1 or bal < -1:
                self._avl_balance(self.root, bal)

    def _avl_balance(self, current, bal):
        while not (bal == 1 or bal == -1):
            if bal > 1:
                current = current.left
                bal = self.balance(current)
            else:
                current = current.right
                bal = self.balance(current)
        parent = current.parent

        while parent:
            if current is parent.left:
                if self._balance(parent) == 2:
                    if self._balance(current) == -1:
                        self._rotate_left(current)
                        # self.graph('2_Left_Left')
                    self._rotate_right(parent)
                    # self.graph('3_Left_Right')

                    return
                if self._balance(parent) == -1:
                    return
            else:
                if self._balance(parent) == -2:
                    if self._balance(current) == 1:
                        self._rotate_right(current)
                        # self.graph('4_Right_Right')

                    self._rotate_left(parent)
                    # self.graph('5_Right_Left')

                    return
                if self._balance(parent) == 1:
                    return
            current, parent = parent, parent.parent

    def _rotate_left(self, leaf):
        leaf.right.parent = leaf.parent
        try:
            if leaf is leaf.parent.left:
                leaf.parent.left = leaf.right
            else:
                leaf.parent.right = leaf.right
        except:
            self.root = leaf.right
        leaf.right.left, leaf.right, leaf.parent = leaf, leaf.right.left, leaf.right
        try:
            leaf.right.parent = leaf
        except:
            pass

    def _rotate_right(self, leaf):
        leaf.left.parent = leaf.parent
        try:
            if leaf is leaf.parent.right:
                leaf.parent.right = leaf.left
            else:
                leaf.parent.left = leaf.left
        except:
            self.root = leaf.left
        leaf.left.right, leaf.left, leaf.parent = leaf, leaf.left.right, leaf.left
        try:
            leaf.left.parent = leaf
        except:
            pass

if __name__ == '__main__':

    def makeBalancedTree(num):
        return makeBalance(num, 0, len(num)-1)

    def makeBalance(num, begin, end):
        if begin > end:
            return None
        midPoint = (begin+end)//2
        root = Leaf(num[midPoint])
        root.left = makeBalance(num, begin, midPoint-1)
        root.right = makeBalance(num, midPoint+1, end)
        return root

    if len(sys.argv) > 1:
        if sys.argv[1] == 'con':
            nums = []
            nums.append(range(0, 5))
            nums.append(range(0, 50))
            nums.append(range(0, 500))

            for num in nums:
                T_easy = Tree(makeBalancedTree(num))
                T_hard = Tree()
                for i in num:
                    T_hard.insert(i)

                def test_contains_easy():
                    T_easy.contains(num[-1])

                def test_contains_hard():
                    T_hard.contains(num[-1])

                best_case = '{:10.10f}s :Best Case,  Balanced,   Leaves {},  Depth {}'
                worst_case = '{:10.10f}s :Worst Case, Unbalanced, Leaves {},  Depth {}'
                time_easy = timeit.Timer(
                    "test_contains_easy()",
                    setup="from __main__ import test_contains_easy").timeit(
                    number=10000)
                time_hard = timeit.Timer(
                    "test_contains_hard()",
                    setup="from __main__ import test_contains_hard").timeit(
                    number=10000)

                print(best_case.format(time_easy, len(num), T_easy.depth()))
                print(worst_case.format(time_hard, len(num), T_hard.depth()))
                print('{} times slower'.format(float(time_hard)/float(time_easy)))
                print('\n')
        elif sys.argv[1] == 'avl':
            nums = []
            nums.append(range(0, 5))
            nums.append(range(0, 50))
            nums.append(range(0, 500))

            for num in nums:
                T = Tree()

                def test_avl_insert():
                    for i in num:
                        T.avl_insert(i)

                case = '{:10.10f}s : Leaves {}'
                time = timeit.Timer(
                    "test_avl_insert()",
                    setup="from __main__ import test_avl_insert").timeit(
                    number=100)

                print(case.format(time, len(num)))
                print('\n')