text:
/**CFile****************************************************************

  FileName    [abc_global.h]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Global declarations.]

  Synopsis    [Global declarations.]

  Author      [Alan Mishchenko]

  Affiliation [UC Berkeley]

  Date        [Ver. 1.0. Started - Jan 30, 2009.]

  Revision    [$Id: abc_global.h,v 1.00 2009/01/30 00:00:00 alanmi Exp $]

***********************************************************************/

#ifndef ABC__misc__util__abc_global_h
#define ABC__misc__util__abc_global_h

////////////////////////////////////////////////////////////////////////
///                          INCLUDES                                ///
////////////////////////////////////////////////////////////////////////

#include <cstdint>
#ifdef _MSC_VER
//#define inline __inline // compatible with MS VS 6.0
#pragma warning(push)
#pragma warning(disable : 4152) // warning C4152: nonstandard extension, function/data pointer conversion in expression
#pragma warning(disable : 4200) // warning C4200: nonstandard extension used : zero-sized array in struct/union
#pragma warning(disable : 4244) // warning C4244: '+=' : conversion from 'int ' to 'unsigned short ', possible loss of data
#pragma warning(disable : 4302) // warning C4302: 'type cast': truncation from 'void *' to 'pabc::ABC_PTRINT_T'
#pragma warning(disable : 4311) // warning C4311: 'type cast': pointer truncation from 'void *' to 'pabc::ABC_PTRINT_T'
#pragma warning(disable : 4312) // warning C4312: 'type cast': conversion from 'pabc::ABC_PTRINT_T' to 'void *' of greater size
#pragma warning(disable : 4514) // warning C4514: 'Vec_StrPop' : unreferenced inline function has been removed
#pragma warning(disable : 4710) // warning C4710: function 'Vec_PtrGrow' not inlined
//#pragma warning( disable : 4273 )
#endif

#ifdef WIN32
  #ifdef WIN32_NO_DLL
    #define ABC_DLLEXPORT
    #define ABC_DLLIMPORT
  #else
    #define ABC_DLLEXPORT __declspec(dllexport)
    #define ABC_DLLIMPORT __declspec(dllimport)
  #endif
#else  /* defined(WIN32) */
#define ABC_DLLIMPORT
#endif /* defined(WIN32) */

#ifndef ABC_DLL
#define ABC_DLL ABC_DLLIMPORT
#endif

#if !defined(___unused)
#if defined(__GNUC__)
#define ___unused __attribute__ ((__unused__))
#else
#define ___unused
#endif
#endif

/*
#ifdef __cplusplus
#error "C++ code"
#else
#error "C code"
#endif
*/

#include <time.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>

// catch memory leaks in Visual Studio
#ifdef WIN32
  #ifdef _DEBUG
    #define _CRTDBG_MAP_ALLOC
    #include <crtdbg.h>
  #endif
#endif

#ifdef _WIN32
#include <Windows.h>
#endif

#include "abc_namespaces.h"

////////////////////////////////////////////////////////////////////////
///                         PARAMETERS                               ///
////////////////////////////////////////////////////////////////////////

ABC_NAMESPACE_HEADER_START

////////////////////////////////////////////////////////////////////////
///                         BASIC TYPES                              ///
////////////////////////////////////////////////////////////////////////

/**
 * Pointer difference type; replacement for ptrdiff_t.
 * This is a signed integral type that is the same size as a pointer.
 * NOTE: This type may be different sizes on different platforms.
 */
#if       defined(__ccdoc__)
typedef platform_dependent_type ABC_PTRDIFF_T;
#elif     defined(LIN64)
typedef long ABC_PTRDIFF_T;
#elif     defined(NT64)
typedef long long ABC_PTRDIFF_T;
#elif     defined(NT) || defined(LIN) || defined(WIN32)
typedef int ABC_PTRDIFF_T;
#else
   #error unknown platform
#endif /* defined(PLATFORM) */

/**
 * Unsigned integral type that can contain a pointer.
 * This is an unsigned integral type that is the same size as a pointer.
 * NOTE: This type may be different sizes on different platforms.
 */
#if       defined(__ccdoc__)
typedef platform_dependent_type ABC_PTRUINT_T;
#elif     defined(LIN64)
typedef unsigned long ABC_PTRUINT_T;
#elif     defined(NT64)
typedef unsigned long long ABC_PTRUINT_T;
#elif     defined(NT) || defined(LIN) || defined(WIN32)
typedef unsigned int ABC_PTRUINT_T;
#else
   #error unknown platform
#endif /* defined(PLATFORM) */

/**
 * Signed integral type that can contain a pointer.
 * This is a signed integral type that is the same size as a pointer.
 * NOTE: This type may be different sizes on different platforms.
 */
#if       defined(__ccdoc__)
typedef platform_dependent_type ABC_PTRINT_T;
#elif     defined(LIN64)
typedef long ABC_PTRINT_T;
#elif     defined(NT64)
typedef long long ABC_PTRINT_T;
#elif     defined(NT) || defined(LIN) || defined(WIN32)
typedef int ABC_PTRINT_T;
#else
   #error unknown platform
#endif /* defined(PLATFORM) */

/**
 * 64-bit signed integral type.
 */
#if       defined(__ccdoc__)
typedef platform_dependent_type ABC_INT64_T;
#elif     defined(LIN64)
typedef long ABC_INT64_T;
#elif     defined(NT64) || defined(LIN)
typedef long long ABC_INT64_T;
#elif     defined(WIN32) || defined(NT)
typedef signed __int64 ABC_INT64_T;
#else
   #error unknown platform
#endif /* defined(PLATFORM) */

/**
 * 64-bit unsigned integral type.
 */
typedef uint64_t ABC_UINT64_T;

#ifdef LIN
  #define ABC_CONST(number) number ## ULL
#else // LIN64 and windows
  #define ABC_CONST(number) number
#endif

typedef ABC_UINT64_T word;
typedef ABC_INT64_T iword;

////////////////////////////////////////////////////////////////////////
///                      MACRO DEFINITIONS                           ///
////////////////////////////////////////////////////////////////////////

#define ABC_INFINITY    (1000000000)

#define ABC_SWAP(Type, a, b)  { Type t = a; a = b; b = t; }

#define ABC_PRT(a,t)    (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%9.2f sec\n", 1.0*(t)/(CLOCKS_PER_SEC)))
#define ABC_PRTr(a,t)   (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%9.2f sec\r", 1.0*(t)/(CLOCKS_PER_SEC)))
#define ABC_PRTn(a,t)   (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%9.2f sec  ", 1.0*(t)/(CLOCKS_PER_SEC)))
#define ABC_PRTP(a,t,T) (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%9.2f sec (%6.2f %%)\n", 1.0*(t)/(CLOCKS_PER_SEC), (T)? 100.0*(t)/(T) : 0.0))
#define ABC_PRM(a,f)    (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%10.3f MB\n",    1.0*(f)/(1<<20)))
#define ABC_PRMr(a,f)   (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%10.3f MB\r",    1.0*(f)/(1<<20)))
#define ABC_PRMn(a,f)   (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%10.3f MB  ",    1.0*(f)/(1<<20)))
#define ABC_PRMP(a,f,F) (Abc_Print(1, "%s =", (a)), Abc_Print(1, "%10.3f MB (%6.2f %%)\n",  (1.0*(f)/(1<<20)), ((F)? 100.0*(f)/(F) : 0.0) ) )

#define ABC_ALLOC(type, num)     ((type *) malloc(sizeof(type) * (num)))
#define ABC_CALLOC(type, num)    ((type *) calloc((num), sizeof(type)))
#define ABC_FALLOC(type, num)    ((type *) memset(malloc(sizeof(type) * (num)), 0xff, sizeof(type) * (num)))
#define ABC_FREE(obj)            ((obj) ? (free((char *) (obj)), (obj) = 0) : 0)
#define ABC_REALLOC(type, obj, num) \
        ((obj) ? ((type *) realloc((char *)(obj), sizeof(type) * (num))) : \
         ((type *) malloc(sizeof(type) * (num))))

static inline int      Abc_AbsInt( int a        )             { return a < 0 ? -a : a; }
static inline int      Abc_MaxInt( int a, int b )             { return a > b ?  a : b; }
static inline int      Abc_MinInt( int a, int b )             { return a < b ?  a : b; }
static inline word     Abc_MaxWord( word a, word b )          { return a > b ?  a : b; }
static inline word     Abc_MinWord( word a, word b )          { return a < b ?  a : b; }
static inline float    Abc_AbsFloat( float a          )       { return a < 0 ? -a : a; }
static inline float    Abc_MaxFloat( float a, float b )       { return a > b ?  a : b; }
static inline float    Abc_MinFloat( float a, float b )       { return a < b ?  a : b; }
static inline double   Abc_AbsDouble( double a           )    { return a < 0 ? -a : a; }
static inline double   Abc_MaxDouble( double a, double b )    { return a > b ?  a : b; }
static inline double   Abc_MinDouble( double a, double b )    { return a < b ?  a : b; }

static inline int      Abc_Float2Int( float Val )             { union { int x; float y; } v; v.y = Val; return v.x;         }
static inline float    Abc_Int2Float( int Num )               { union { int x; float y; } v; v.x = Num; return v.y;         }
static inline word     Abc_Dbl2Word( double Dbl )             { union { word x; double y; } v; v.y = Dbl; return v.x;       }
static inline double   Abc_Word2Dbl( word Num )               { union { word x; double y; } v; v.x = Num; return v.y;       }
static inline int      Abc_Base2Log( unsigned n )             { int r; if ( n < 2 ) return n; for ( r = 0, n--; n; n >>= 1, r++ ) {}; return r; }
static inline int      Abc_Base10Log( unsigned n )            { int r; if ( n < 2 ) return n; for ( r = 0, n--; n; n /= 10, r++ ) {}; return r; }
static inline int      Abc_Base16Log( unsigned n )            { int r; if ( n < 2 ) return n; for ( r = 0, n--; n; n /= 16, r++ ) {}; return r; }
static inline char *   Abc_UtilStrsav( char * s )             { return s ? strcpy(ABC_ALLOC(char, strlen(s)+1), s) : NULL;  }
static inline int      Abc_BitWordNum( int nBits )            { return (nBits>>5) + ((nBits&31) > 0);                       }
static inline int      Abc_Bit6WordNum( int nBits )           { return (nBits>>6) + ((nBits&63) > 0);                       }
static inline int      Abc_TruthWordNum( int nVars )          { return nVars <= 5 ? 1 : (1 << (nVars - 5));                 }
static inline int      Abc_Truth6WordNum( int nVars )         { return nVars <= 6 ? 1 : (1 << (nVars - 6));                 }
static inline int      Abc_InfoHasBit( unsigned * p, int i )  { return (p[(i)>>5] & (1<<((i) & 31))) > 0;                   }
static inline void     Abc_InfoSetBit( unsigned * p, int i )  { p[(i)>>5] |= (1<<((i) & 31));                               }
static inline void     Abc_InfoXorBit( unsigned * p, int i )  { p[(i)>>5] ^= (1<<((i) & 31));                               }
static inline unsigned Abc_InfoMask( int nVar )               { return (~(unsigned)0) >> (32-nVar);                         }

static inline int      Abc_Var2Lit( int Var, int c )          { assert(Var >= 0 && !(c >> 1)); return Var + Var + c;        }
static inline int      Abc_Lit2Var( int Lit )                 { assert(Lit >= 0); return Lit >> 1;                          }
static inline int      Abc_LitIsCompl( int Lit )              { assert(Lit >= 0); return Lit & 1;                           }
static inline int      Abc_LitNot( int Lit )                  { assert(Lit >= 0); return Lit ^ 1;                           }
static inline int      Abc_LitNotCond( int Lit, int c )       { assert(Lit >= 0); return Lit ^ (int)(c > 0);                }
static inline int      Abc_LitRegular( int Lit )              { assert(Lit >= 0); return Lit & ~01;                         }
static inline int      Abc_Lit2LitV( int * pMap, int Lit )    { assert(Lit >= 0); return Abc_Var2Lit( pMap[Abc_Lit2Var(Lit)], Abc_LitIsCompl(Lit) );      }
static inline int      Abc_Lit2LitL( int * pMap, int Lit )    { assert(Lit >= 0); return Abc_LitNotCond( pMap[Abc_Lit2Var(Lit)], Abc_LitIsCompl(Lit) );   }

static inline int      Abc_Ptr2Int( void * p )                { return (int)(ABC_PTRINT_T)p;      }
static inline void *   Abc_Int2Ptr( int i )                   { return (void *)(ABC_PTRINT_T)i;   }
static inline word     Abc_Ptr2Wrd( void * p )                { return (word)(ABC_PTRUINT_T)p;    }
static inline void *   Abc_Wrd2Ptr( word i )                  { return (void *)(ABC_PTRUINT_T)i;  }

static inline int      Abc_Var2Lit2( int Var, int Att )       { assert(!(Att >> 2)); return (Var << 2) + Att; }
static inline int      Abc_Lit2Var2( int Lit )                { assert(Lit >= 0);    return Lit >> 2;         }
static inline int      Abc_Lit2Att2( int Lit )                { assert(Lit >= 0);    return Lit & 3;          }
static inline int      Abc_Var2Lit3( int Var, int Att )       { assert(!(Att >> 3)); return (Var << 3) + Att; }
static inline int      Abc_Lit2Var3( int Lit )                { assert(Lit >= 0);    return Lit >> 3;         }
static inline int      Abc_Lit2Att3( int Lit )                { assert(Lit >= 0);    return Lit & 7;          }
static inline int      Abc_Var2Lit4( int Var, int Att )       { assert(!(Att >> 4)); return (Var << 4) + Att; }
static inline int      Abc_Lit2Var4( int Lit )                { assert(Lit >= 0);    return Lit >> 4;         }
static inline int      Abc_Lit2Att4( int Lit )                { assert(Lit >= 0);    return Lit & 15;         }

// time counting
typedef ABC_INT64_T abctime;
static inline abctime Abc_Clock()
{
#if (defined(LIN) || defined(LIN64)) && !(__APPLE__ & __MACH__) && !defined(__MINGW32__)
    struct timespec ts;
#ifdef _WIN32
    if ( clock_gettime(0, &ts) < 0 )
        return (abctime)-1;
#else
    if ( clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) < 0 )
        return (abctime)-1;
#endif
    abctime res = ((abctime) ts.tv_sec) * CLOCKS_PER_SEC;
    res += (((abctime) ts.tv_nsec) * CLOCKS_PER_SEC) / 1000000000;
    return res;
#else
    return (abctime) clock();
#endif
}

// bridge communication
#define BRIDGE_NETLIST           106
#define BRIDGE_ABS_NETLIST       107
extern int Gia_ManToBridgeText( FILE * pFile, int Size, unsigned char * pBuffer );
extern int Gia_ManToBridgeAbsNetlist( FILE * pFile, void * p, int pkg_type );

// string printing
extern char * vnsprintf(const char* format, va_list args);
extern char * nsprintf(const char* format, ...);

// misc printing procedures
enum Abc_VerbLevel
{
    ABC_PROMPT   = -2,
    ABC_ERROR    = -1,
    ABC_WARNING  =  0,
    ABC_STANDARD =  1,
    ABC_VERBOSE  =  2
};
static inline void Abc_Print( int level, const char * format, ... )
{
    extern ABC_DLL int Abc_FrameIsBridgeMode();
    va_list args;

    if ( ! Abc_FrameIsBridgeMode() ){
        if ( level == ABC_ERROR )
            printf( "Error: " );
        else if ( level == ABC_WARNING )
            printf( "Warning: " );
    }else{
        if ( level == ABC_ERROR )
            Gia_ManToBridgeText( stdout, (int)strlen("Error: "), (unsigned char*)"Error: " );
        else if ( level == ABC_WARNING )
            Gia_ManToBridgeText( stdout, (int)strlen("Warning: "), (unsigned char*)"Warning: " );
    }

    va_start( args, format );
    if ( Abc_FrameIsBridgeMode() )
    {
        char * tmp = vnsprintf( format, args );
        Gia_ManToBridgeText( stdout, (int)strlen(tmp), (unsigned char*)tmp );
        free( tmp );
    }
    else
        vprintf( format, args );
    va_end( args );
}

static inline void Abc_PrintInt( int i )
{
    double v3 = (double)i/1000;
    double v6 = (double)i/1000000;

    Abc_Print( 1,  "  " );

    if ( i > -1000 && i < 1000 )
        Abc_Print( 1, " %4d", i );

    else if ( v3 > -9.995 && v3 < 9.995 )
        Abc_Print( 1, "%4.2fk", v3 );
    else if ( v3 > -99.95 && v3 < 99.95 )
        Abc_Print( 1, "%4.1fk", v3 );
    else if ( v3 > -999.5 && v3 < 999.5 )
        Abc_Print( 1, "%4.0fk", v3 );

    else if ( v6 > -9.995 && v6 < 9.995 )
        Abc_Print( 1, "%4.2fm", v6 );
    else if ( v6 > -99.95 && v6 < 99.95 )
        Abc_Print( 1, "%4.1fm", v6 );
    else if ( v6 > -999.5 && v6 < 999.5 )
        Abc_Print( 1, "%4.0fm", v6 );
}

static inline void Abc_PrintTime( int level, const char * pStr, abctime time )
{
    ABC_PRT( pStr, time );
}

static inline void Abc_PrintTimeP( int level, const char * pStr, abctime time, abctime Time )
{
    ABC_PRTP( pStr, time, Time );
}

static inline void Abc_PrintMemoryP( int level, const char * pStr, int mem, int Mem )
{
    ABC_PRMP( pStr, mem, Mem );
}

// Returns the next prime >= p
static inline int Abc_PrimeCudd( unsigned int p )
{
    int i,pn;
    p--;
    do {
        p++;
        if (p&1)
        {
            pn = 1;
            i = 3;
            while ((unsigned) (i * i) <= p)
            {
                if (p % i == 0) {
                    pn = 0;
                    break;
                }
                i += 2;
            }
        }
        else
            pn = 0;
    } while (!pn);
    return(p);

} // end of Cudd_Prime

// sorting
extern void   Abc_MergeSort( int * pInput, int nSize );
extern int *  Abc_MergeSortCost( int * pCosts, int nSize );
extern void   Abc_QuickSort1( word * pData, int nSize, int fDecrease );
extern void   Abc_QuickSort2( word * pData, int nSize, int fDecrease );
extern void   Abc_QuickSort3( word * pData, int nSize, int fDecrease );
extern void   Abc_QuickSortCostData( int * pCosts, int nSize, int fDecrease, word * pData, int * pResult );
extern int *  Abc_QuickSortCost( int * pCosts, int nSize, int fDecrease );

ABC_NAMESPACE_HEADER_END

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif

////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


text:
ACCEPTED

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

#### Published in
Annls mycol. 23(3/6): 365 (1925)

#### Original name
Catacauma contractum Syd., 1925

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
/* ListViewController.m
 * IAMenuController
 *
 * Created by Mark Adams on 12/9/11.
 * MIT License
 */

#import "ListViewController.h"
#import "IAMenuController-Swift.h"
#import "MainViewController.h"

@interface NSArray (RandomObject)

- (id)randomObject;

@end

#pragma mark -

@implementation NSArray (RandomObject)

- (id)randomObject {
  NSUInteger randomInteger = (NSUInteger)arc4random_uniform((u_int32_t)self.count);
  return [self objectAtIndex:randomInteger];
}

@end

#pragma mark -

@interface ListViewController ()

@property (nonatomic, strong) NSArray *possibleColors;

@end

#pragma mark -

@implementation ListViewController

@synthesize possibleColors;

- (void)viewDidLoad {
  [super viewDidLoad];
  self.tableView.showsVerticalScrollIndicator = NO;

  self.possibleColors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor cyanColor], [UIColor greenColor],
                         [UIColor lightGrayColor], [UIColor magentaColor], [UIColor brownColor],
                         [UIColor orangeColor], nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];
  mvc.view.backgroundColor = [self.possibleColors randomObject];
  self.menuController.contentViewController = mvc;
}

@end


text:
<?php

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Zend_Xml_SecurityTest::main');
}

/**
 * This is a class that overrides Zend_Xml_Security to mark the heuristicScan()
 * method as public, allowing us to test it.
 *
 * @see Zend_Xml_Security
 */
require_once 'Zend/Xml/TestAsset/Security.php';

require_once 'Zend/Xml/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Xml_Security
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Xml
 * @group      ZF2015-06
 */
class Zend_Xml_MultibyteTest extends PHPUnit_Framework_TestCase
{
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function multibyteEncodings()
    {
        return array(
            'UTF-16LE' => array('UTF-16LE', pack('CC', 0xff, 0xfe), 3),
            'UTF-16BE' => array('UTF-16BE', pack('CC', 0xfe, 0xff), 3),
            'UTF-32LE' => array('UTF-32LE', pack('CCCC', 0xff, 0xfe, 0x00, 0x00), 4),
            'UTF-32BE' => array('UTF-32BE', pack('CCCC', 0x00, 0x00, 0xfe, 0xff), 4),
        );
    }

    public function getXmlWithXXE()
    {
        return <<<XML
<?xml version="1.0" encoding="{ENCODING}"?>
<!DOCTYPE methodCall [
  <!ENTITY pocdata SYSTEM "file:///etc/passwd">
]>
<methodCall>
    <methodName>retrieved: &pocdata;</methodName>
</methodCall>
XML;
    }

    /**
     * Invoke Zend_Xml_Security::heuristicScan with the provided XML.
     *
     * @param string $xml
     * @return void
     * @throws Zend_Xml_Exception
     */
    public function invokeHeuristicScan($xml)
    {
        return Zend_Xml_TestAsset_Security::heuristicScan($xml);
    }

    /**
     * @dataProvider multibyteEncodings
     * @group heuristicDetection
     */
    public function testDetectsMultibyteXXEVectorsUnderFPMWithEncodedStringMissingBOM($encoding, $bom, $bomLength)
    {
        $xml = $this->getXmlWithXXE();
        $xml = str_replace('{ENCODING}', $encoding, $xml);
        $xml = iconv('UTF-8', $encoding, $xml);
        $this->assertNotSame(0, strncmp($xml, $bom, $bomLength));
        $this->setExpectedException('Zend_Xml_Exception', 'ENTITY');
        $this->invokeHeuristicScan($xml);
    }

    /**
     * @dataProvider multibyteEncodings
     */
    public function testDetectsMultibyteXXEVectorsUnderFPMWithEncodedStringUsingBOM($encoding, $bom)
    {
        $xml  = $this->getXmlWithXXE();
        $xml  = str_replace('{ENCODING}', $encoding, $xml);
        $orig = iconv('UTF-8', $encoding, $xml);
        $xml  = $bom . $orig;
        $this->setExpectedException('Zend_Xml_Exception', 'ENTITY');
        $this->invokeHeuristicScan($xml);
    }

    public function getXmlWithoutXXE()
    {
        return <<<XML
<?xml version="1.0" encoding="{ENCODING}"?>
<methodCall>
    <methodName>retrieved: &pocdata;</methodName>
</methodCall>
XML;
    }

    /**
     * @dataProvider multibyteEncodings
     */
    public function testDoesNotFlagValidMultibyteXmlAsInvalidUnderFPM($encoding)
    {
        $xml = $this->getXmlWithoutXXE();
        $xml = str_replace('{ENCODING}', $encoding, $xml);
        $xml = iconv('UTF-8', $encoding, $xml);
        try {
            $result = $this->invokeHeuristicScan($xml);
            $this->assertNull($result);
        } catch (Exception $e) {
            $this->fail('Security scan raised exception when it should not have');
        }
    }

    /**
     * @dataProvider multibyteEncodings
     * @group mixedEncoding
     */
    public function testDetectsXXEWhenXMLDocumentEncodingDiffersFromFileEncoding($encoding, $bom)
    {
        $xml = $this->getXmlWithXXE();
        $xml = str_replace('{ENCODING}', 'UTF-8', $xml);
        $xml = iconv('UTF-8', $encoding, $xml);
        $xml = $bom . $xml;
        $this->setExpectedException('Zend_Xml_Exception', 'ENTITY');
        $this->invokeHeuristicScan($xml);
    }
}

if (PHPUnit_MAIN_METHOD == "Zend_Xml_MultibyteTest::main") {
    Zend_Xml_MultibyteTest::main();
}


text:
layout: page
title: Theme Setup
permalink: /theme-setup/
comments: true
---
## Installation

Minimal Mistakes now requires [Jekyll](http://jekyllrb.com/) 2.2+. Make sure to run `gem update jekyll` if you aren't on the latest version or `gem install jekyll` if this is your first time installing it.

If you are creating a new Jekyll site using Leonids follow these steps:

1. Fork the [Leonids](http://github.com/renyuanz/leonids/fork).
2. Clone the repo you just forked and rename it.
3. Update `config.yml`, add navigation, and replace demo posts and pages with your own. Full details below.

If you want to use Minimal Mistakes with an existing Jekyll site follow these steps:

1. [Download Leonids](https://github.com/renyuanz/leonids/archive/master.zip) and unzip.
2. Rename `leonids-master` to something meaningful ie: `my_blog`
3. Remove demo posts/pages and replace with your own posts, pages, and any other content you want to move over.
4. Update posts' and pages' YAML to match variables used by Leonids. Full details below.
5. Update `_config.yml` and add navigation links. Full details below.

**Pro-tip:** Delete the `gh-pages` branch after cloning and start fresh by branching off `master`. There is a bunch of garbage in `gh-pages` used for the theme's demo site that I'm guessing you won't want.
{: .notice}

---

## Running Jekyll

If `jekyll build` and `jekyll serve` throw errors you may have to run Jekyll with `bundled exec` instead.

> In some cases, running executables without bundle exec may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.
>
>However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.

{% highlight text %}
bundle exec jekyll build

bundle exec jekyll serve
{% endhighlight %}

---

## Scaffolding

How Leonids is organized and what the various files are. All posts, layouts, includes, stylesheets, assets, and whatever else is grouped nicely under the root folder. The compiled Jekyll site outputs to `_site/`.

{% highlight text %}
minimal-mistakes/
├── _includes/
|    ├── disqus.html   # Disqus comments script
|    ├── footer.html            # site footer
|    ├── head.html              # site head
|    ├── sidebar.html           # site sidebar/top navigation
|    ├── social-links.html      # site owner social links management
|    ├── post-section.html      # post section
|    └── js.html                # site javascripts
├── _layouts/
|    ├── default.html            # default layout
|    ├── page.html               # page layout
|    ├── post-index.html         # post index layout
|    └── post.html               # single post layout
├── _posts/                      # MarkDown formatted posts
├── _sass/                       # Sass stylesheets
|    └── pages/                  # Sass stylesheets for specific pages
├── css/                         # compiled stylesheets
├── fonts/                       # fontawesome 4.4.0
├── js/
|    ├── main.js                 # main JavaScript file
|    └── jquery-2.1.4.min.js     # jQuery 2.1.4 min file
├── img/                         # images for posts and pages
├── feed.xml                     # Atom feed template
├── index.md                     # sample homepage.
├── archive.html                 # sample archive page. lists all posts in reverse chronology
├── tags.html                    # sample tags page. lists all tags included in the site
└── theme-setup.md               # theme setup page. safe to remove
{% endhighlight %}

---

## Site Setup

A quick checklist of the files you'll want to edit to get up and running.

### Site Wide Configuration

`_config.yml` is your friend. Open it up and personalize it. Most variables are self explanatory but here's an explanation of each if needed:

#### title

The title of your site... shocker!

Example `title: My Awesome Site`

#### url

Used to generate absolute urls in `sitemap.xml`, `feed.xml`, and for generating canonical URLs in `<head>`. When developing locally either comment this out or use something like `http://localhost:4000` so all assets load properly. *Don't include a trailing `/`*.

Examples:

{% highlight yaml %}
url: http://renyuanz.github.io/leonids
url: http://localhost:4000
url: //cooldude.github.io
url:
{% endhighlight %}

#### Google Analytics and Webmaster Tools

Will be working on it in the future.

### New Post

Just create a markdown file named something like: `year-month-day-your-post-title.md` in the directory `_posts`, and here you go.

### New Page

You can create a page by adding directly a markdown file or html file under the root path or a directory with a index page inside. You can check [this page](http://jekyllrb.com/docs/pages/) for more details.

---

## Layouts and Content

Explanations of the various `_layouts` included with the theme and when to use them.

### Post and Page

These two layouts are very similar. Both have an author sidebar and optional Disqus comments. The only real difference is the post layout includes related posts at the end of the page.

### Post Index Page

A [sample index page]({{ site.url }}/) listing all posts grouped by the year they were published has been provided. The name can be customized to your liking by editing a few references.

### Author Override

By making use of data files you can assign different authors for each post.

Start by modifying `authors.yml` file in the `_data` folder and add your authors using the following format.

{% highlight yaml %}
# Authors

billy_rick:
  name: Billy Rick
  web: http://thewhip.com
  email: billy@rick.com
  bio: "What do you want, jewels? I am a very extravagant man."
  avatar: bio-photo-2.jpg
  twitter: extravagantman
  google:
    plus: +BillyRick

cornelius_fiddlebone:
  name: Cornelius Fiddlebone
  email: cornelius@thewhip.com
  bio: "I ordered what?"
  avatar: bio-photo.jpg
  twitter: rhymeswithsackit
  google:
    plus: +CorneliusFiddlebone
{% endhighlight %}

To assign Billy Rick as an author for our post. We'd add the following YAML front matter to a post:

{% highlight yaml %}
author: billy_rick
{% endhighlight %}

### Social Sharing Links

Social sharing links for Twitter, Facebook, and Google+ are included on posts/pages by default. If you'd like to use different social networks modify `_includes/social-links.html` to your liking. Icons are set using [Font Awesome](http://fontawesome.io).

---

## Further Customization

Jekyll 2.x added support for Sass files making it much easier to modify a theme's fonts and colors. By editing values found in `_sass/variables.scss` you can fine tune the site's colors and typography.

For example if you wanted a red background instead of white you'd change `$text-color: #444;` to `$text-color: $cc0033;`.

---

## Questions?

Found a bug or aren't quite sure how something works? By all means Ping me on Twitter [@mmistakes](http://twitter.com/alittlered3) or [file a GitHub Issue](https://github.com/renyuanz/leonids/issues/new). And if you make something cool with this theme feel free to let me know.

---

## License

This theme is free and open source software, distributed under the MIT License. So feel free to use this Jekyll theme on your site without linking back to me or including a disclaimer.


text:
describe('emp', function() {
  describe('util', function() {
    describe('milstdColorFix', function() {
      it('updates the objects properties with properties.modifiers for lineColor, lineWidth, and fillColor', function() {
        var modifiers = {
          lineColor: '#FFFFFF',
          lineWidth: 4,
          fillColor: '#3E3E3E'
        };

        var feature = {
          format: emp.typeLibrary.featureFormatType.MILSTD,
          properties: {
            modifiers: modifiers
          }
        };

        emp.util.milstdColorFix(feature);

        feature.properties.should.have.property('lineColor', modifiers.lineColor);
        feature.properties.should.have.property('lineWidth', modifiers.lineWidth);
        feature.properties.should.have.property('fillColor', modifiers.fillColor);
      });
    });
  });
});


text:
package eu.inloop.easygcm;

import com.google.android.gms.iid.InstanceIDListenerService;

public class EasyInstanceIDListenerService extends InstanceIDListenerService {

    private static final String TAG = "EasyInstanceIDListenerService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    @Override
    public void onTokenRefresh() {
        EasyGcm.Logger.d("Received token refresh broadcast");

        EasyGcm.removeRegistrationId(getApplicationContext());

        if (GcmUtils.checkCanAndShouldRegister(getApplicationContext())) {
            startService(GcmRegistrationService.createGcmRegistrationIntent(this));
        }
    }
}


text:
<?php

namespace Leguan\LeguanLoder;

use \Leguan\Bootstrap\Leguan;

/**
 * Leguan 内部类加载器
 */
class LeguanLoder
{
	public function __get($name)
	{
		return Leguan::get($name);
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Readtable
{
	public class Table<K, R> where R : IRecord<K>, new ()
	{
		string filename, datfile, binfile;
		Dictionary<K, R> records;

		public Table (string path)
		{
			records = new Dictionary<K, R> ();
			Load (path);
		}

		void Load (string path)
		{
			filename = path;
			if (filename == null || filename == string.Empty || !File.Exists (filename)) {
				return;
			}
			datfile = filename.Replace (".txt", ".dat");
			binfile = filename.Replace (".txt", ".bin");
			Stream stream = File.Open (filename, FileMode.Open);
			TextReader reader = new StreamReader (stream);
			string fields = reader.ReadLine ();
			Logger.D (string.Format ("Load table: {0} \nwith fields: {1}.", filename, fields));
			string table = reader.ReadToEnd ();
			reader.Close();
			stream.Close ();
			string[] strRecords = table.Split (new string[1] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
			foreach (string record in strRecords) {
				R r = new R ();
				if (r.Parse (record)) {
					records [r.Key ()] = r;
				}
			}
		}

		public R Get (K k)
		{
			return records [k];
		}

		public void Serialize ()
		{
			Stream s = File.Open (datfile, FileMode.Create);
			BinaryFormatter formatter = new BinaryFormatter ();
			formatter.Serialize (s, records);
			s.Close ();
		}

		public void Deserialize ()
		{
			records = null;
			Stream s = File.Open (datfile, FileMode.Open);
			BinaryFormatter formatter = new BinaryFormatter ();
			records = formatter.Deserialize (s) as Dictionary<K, R>;
			s.Close ();
		}

		public void SaveBinary ()
		{
			Stream s = File.Open (binfile, FileMode.Create);
			BinaryWriter writer = new BinaryWriter (s);
			int count = records.Count;
			writer.Write (count);
			Dictionary<K, R>.KeyCollection keys = records.Keys;
			foreach (K k in keys) {
				R r = records [k];
				r.Save (ref writer);
			}
			writer.Close ();
			s.Close ();
		}

		public void LoadBinary ()
		{
			records = null;
			records = new Dictionary<K, R> ();
			Stream s = File.Open (binfile, FileMode.Open);
			BinaryReader reader = new BinaryReader (s);
			int count = reader.ReadInt32 ();
			for (int i = 0; i < count; ++i) {
				R r = new R ();
				r.Read (ref reader);
				records [r.Key ()] = r;
			}
			reader.Close ();
			s.Close ();
		}
	}
}


text:
//
//  RPInstantAlphaInstructionsWindowController.h
//  RPInstantAlpha
//
//  Created by Brandon Evans on 2014-05-02.
//  Copyright (c) 2014 Robots and Pencils. All rights reserved.
//

@interface RPInstantAlphaInstructionsWindowController : NSWindowController

/**
 *  Creates a new instruction window controller
 *
 *  @param resetHandler Block called when the reset button is pressed
 *  @param doneHandler  Block called when the done button is pressed
 *
 *  @return A new RPInstantAlphaInstructionsWindowController instance
 */
- (instancetype)initWithReset:(void(^)())resetHandler done:(void(^)())doneHandler;

@end


text: Hello FunctionPrivilegeComponent!


text:
package at.arz.latte.rodeo.scm.restapi;

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

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import at.arz.latte.rodeo.api.RodeoQuery;
import at.arz.latte.rodeo.scm.Scm;
import at.arz.latte.rodeo.scm.ScmLocation;
import at.arz.latte.rodeo.scm.ScmName;
import at.arz.latte.rodeo.scm.ScmType;

public class FindScmRepositories
		implements RodeoQuery<GetScmRepositoriesResult> {
	private enum Order {ASC, DESC};

	private ScmType type;
	private ScmName name;
	private ScmLocation location;
	private String order = "order by o.name asc";

	public void orderByName(Order order) {
		this.order = "order by o.name " + order.name().toLowerCase();
	}

	public void orderByLocation(Order order) {
		this.order = "order by o.location " + order.name().toLowerCase();
	}

	public FindScmRepositories with(ScmName name) {
		this.name = name;
		return this;
	}

	public FindScmRepositories with(ScmLocation location) {
		this.location = location;
		return this;
	}

	public FindScmRepositories with(ScmType type) {
		this.type = type;
		return this;
	}

	@Override
	public GetScmRepositoriesResult execute(EntityManager entityManager) {
		TypedQuery<Scm> query = buildQuery(entityManager);
		setOptionalParam(query, "type", type);
		setOptionalParam(query, "name", name);
		setOptionalParam(query, "location", location);
		List<Scm> list = query.getResultList();
		ArrayList<ScmResult> locations = new ArrayList<ScmResult>();
		for (Scm scm : list) {
			locations.add(new ScmResult(scm.getType(), scm.getName(), scm.getLocation()));
		}
		return new GetScmRepositoriesResult(locations);
	}

	private void setOptionalParam(TypedQuery<Scm> query, String name, Object value) {
		if (value != null) {
			query.setParameter(name, value);
		}
	}

	private TypedQuery<Scm> buildQuery(EntityManager entityManager) {
		if (name == null && type == null && location == null) {
			return entityManager.createNamedQuery(Scm.FIND_ALL, Scm.class);
		}
		StringBuilder builder = new StringBuilder("select o from Scm o where ");
		if (type == null) {
			builder.append(nameQuery());
		} else {
			String nameQuery = nameQuery();
			if (nameQuery.isEmpty()) {
				builder.append("o.type=:type");
			} else {
				builder.append("o.type=:type and (");
				builder.append(nameQuery);
				builder.append(")");
			}
		}
		builder.append(" ");
		builder.append(order);
		return entityManager.createQuery(builder.toString(), Scm.class);

	}

	private String nameQuery() {
		if (name == null) {
			return locationQuery();
		}
		String expression = "o.name like :name";
		String locationQuery = locationQuery();
		return locationQuery.isEmpty() ? expression : expression + " or " + locationQuery;
	}

	private String locationQuery() {
		if (location == null) {
			return "";
		}
		return "o.location like :location";
	}

}


text:
function p = getparameters(pc)

%  Part of the NeuralAnalysis package
%
%  P = GETPARAMETERS(PERIODIC_CURVEOBJ)
%
%  Returns the parameters associated with the PERIODIC_CURVE object PERIODIC_CURVEOBJ.
%
%  See also: PERIODIC_CURVE, PERIODIC_CURVE/SETPARAMETERS

p = pc.PCparams;


text:
namespace Yahoo.Yui.Compressor
{
    public interface ICssCompressor : ICompressor
    {
        bool RemoveComments { get; set; }
    }
}


text:
/* The file is part of Snowman decompiler. */
/* See doc/licenses.asciidoc for the licensing information. */

//
// SmartDec decompiler - SmartDec is a native code to C/C++ decompiler
// Copyright (C) 2015 Alexander Chernov, Katerina Troshina, Yegor Derevenets,
// Alexander Fokin, Sergey Levin, Leonid Tsvetkov
//
// This file is part of SmartDec decompiler.
//
// SmartDec decompiler 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 3 of the License, or
// (at your option) any later version.
//
// SmartDec decompiler 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 SmartDec decompiler.  If not, see <http://www.gnu.org/licenses/>.
//

#include "FunctionPointerType.h"

#include <nc/common/Foreach.h>

namespace nc {
namespace core {
namespace likec {

void FunctionPointerType::print(QTextStream &out) const {
    out << *returnType() << "(*)(";

    bool comma = false;
    foreach (const Type *type, argumentTypes_) {
        if (comma) {
            out << ", ";
        } else {
            comma = true;
        }
        out << *type;
    }

    out << ")";
}

} // namespace likec
} // namespace core
} // namespace nc

/* vim:set et sts=4 sw=4: */


text:
package com.thindeck.agents;

import com.google.common.base.Joiner;
import com.jcabi.matchers.XhtmlMatchers;
import com.jcabi.xml.XML;
import com.jcabi.xml.XMLDocument;
import com.thindeck.api.Agent;
import java.io.IOException;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.xembly.Xembler;

/**
 * Test case for {@link UpdateNginx}.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.5
 */
public final class UpdateNginxTest {

    /**
     * UpdateNginx can update nginx.
     * @throws IOException If fails
     */
    @Test
    public void updatesNginx() throws IOException {
        final Agent agent = new UpdateNginx(
            new Script.Fake("")
        );
        final XML deck = new XMLDocument(
            Joiner.on(' ').join(
                "<deck name='test/test'><containers>",
                " <container type='green' state='alive'><http>80</http>",
                "  <host>localhost</host><name>aaaaaaaa</name>",
                "  <image>ffffffff</image>",
                " </container></containers>",
                "<domains><domain>test.thindeck.com</domain></domains></deck>"
            )
        );
        MatcherAssert.assertThat(
            new XMLDocument(
                new Xembler(agent.exec(deck)).applyQuietly(deck.node())
            ),
            XhtmlMatchers.hasXPaths("/deck")
        );
    }

}


text:
// Copyright 2020 Google LLC
//
// 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.

// [START cloudrun_helloworld_service]
// [START cloud_run_hello_world]
#include <google/cloud/functions/framework.h>
#include <cstdlib>

namespace gcf = ::google::cloud::functions;

auto hello_world_http() {
  return gcf::MakeFunction([](gcf::HttpRequest const& /*request*/) {
    std::string greeting = "Hello ";
    auto const* target = std::getenv("TARGET");
    greeting += target == nullptr ? "World" : target;
    greeting += "\n";

    return gcf::HttpResponse{}
        .set_header("Content-Type", "text/plain")
        .set_payload(greeting);
  });
}

int main(int argc, char* argv[]) {
  return gcf::Run(argc, argv, hello_world_http());
}

// [END cloud_run_hello_world]
// [END cloudrun_helloworld_service]


text:
const Lab = require('lab')
const bunyan = require('bunyan')
const assert = require('power-assert')
const request = require('request-promise')
const req = require('request')
const crc32 = require('crc32')
const {checksumHeader} = require('mini-service-utils')
const BufferList = require('bl')
const {startServer} = require('../')
const utils = require('./test-utils')

const lab = exports.lab = Lab.script()
const {describe, it, before, beforeEach, after, afterEach} = lab

describe('service\'s server', () => {
  let started
  const name = 'test-server'
  const version = '1.0.0'
  const groups = [{
    name: 'sample',
    init: require('./fixtures/sample')
  }, {
    name: 'synchronous',
    init: require('./fixtures/synchronous')
  }]
  const init = async () => ({})

  before(utils.shutdownLogger)

  after(utils.restoreLogger)

  afterEach(async () => {
    if (!started) return
    await started.stop()
  })

  it('should start with default port', async () => {
    const server = await startServer({name, version, init})
    await server.stop()
  })

  it('should handle configuration error', async () => {
    try {
      await startServer({name, version, init, port: -1})
    } catch (err) {
      assert(err instanceof Error)
      assert(err.message.includes('"port" must be larger than or equal to 0'))
      return
    }
    throw new Error('should have failed')
  })

  it('should handle missing name', async () => {
    try {
      await startServer({version, init})
    } catch (err) {
      assert(err instanceof Error)
      assert(err.message.includes('"name" and "version" options'))
      return
    }
    throw new Error('should have failed')
  })

  it('should handle missing version', async () => {
    try {
      await startServer({name, init})
    } catch (err) {
      assert(err instanceof Error)
      assert(err.message.includes('"name" and "version" options'))
      return
    }
    throw new Error('should have failed')
  })

  it('should handle wrong validation object', async () => {
    try {
      await startServer(require('./fixtures/invalid-schema'))
    } catch (err) {
      assert(err instanceof Error)
      assert(err.message.includes('exposed API invalidValidator (from group invalid-schema)'))
      assert(err.message.includes('"validate" must be an array'))
      return
    }
    throw new Error('should have failed')
  })

  it('should handle start error', async () => {
    let err
    // given a started server
    const first = await startServer({name, version, init})
    // when starting another server on the same port
    try {
      const second = await startServer({name, version, init, port: first.info.port})
      await second.stop()
    } catch (threw) {
      err = threw
    }
    await first.stop()
    assert(err instanceof Error)
    assert(err.message.indexOf('EADDRINUSE') >= 0)
  })

  describe('given a started server', () => {
    let server
    const exposedApis = [{
      group: 'sample',
      id: 'ping',
      params: [],
      path: '/api/sample/ping',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'greeting',
      params: ['name'],
      path: '/api/sample/greeting',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'failing',
      params: [],
      path: '/api/sample/failing',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'errored',
      params: [],
      path: '/api/sample/errored',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'getUndefined',
      params: [],
      path: '/api/sample/getUndefined',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'boomError',
      params: [],
      path: '/api/sample/boomError',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'withExoticParameters',
      params: ['param1', 'param2', 'other'],
      path: '/api/sample/withExoticParameters',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'bufferHandling',
      params: ['buffer'],
      path: '/api/sample/bufferHandling',
      hasBufferInput: true,
      hasStreamInput: false
    }, {
      group: 'sample',
      id: 'streamHandling',
      params: ['stream'],
      path: '/api/sample/streamHandling',
      hasBufferInput: false,
      hasStreamInput: true
    }, {
      group: 'synchronous',
      id: 'greeting',
      params: ['name'],
      path: '/api/synchronous/greeting',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'synchronous',
      id: 'getUndefined',
      params: [],
      path: '/api/synchronous/getUndefined',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'synchronous',
      id: 'boomError',
      params: [],
      path: '/api/synchronous/boomError',
      hasBufferInput: false,
      hasStreamInput: false
    }, {
      group: 'synchronous',
      id: 'withExoticParameters',
      params: ['param1', 'param2', 'other'],
      path: '/api/synchronous/withExoticParameters',
      hasBufferInput: false,
      hasStreamInput: false
    }]
    const checksum = crc32(JSON.stringify(exposedApis))

    before(async () => {
      server = await startServer({name, version, groups, openApi: {}})
    })

    after(async () => server.stop())

    it('should list exposed APIs', async () =>
      assert.deepEqual(await request({
        method: 'GET',
        url: `${server.info.uri}/api/exposed`,
        json: true
      }), {
        name,
        version,
        apis: exposedApis
      })
    )

    it('should expose documentation', async () =>
      assert((await request({
        method: 'GET',
        url: `${server.info.uri}/documentation`
      })).includes('/swaggerui/swagger-ui.js'))
    )

    it('should expose openApi descriptor', async () => {
      const descriptor = await request({
        method: 'GET',
        url: `${server.info.uri}/swagger.json`,
        json: true
      })
      assert(descriptor.swagger === '2.0')
      assert(descriptor.basePath === '/api')
      assert.deepStrictEqual(descriptor.info, {title: 'API documentation', version})
    })

    it('should include CRC32 as header for API without parameter', async () => {
      const response = await request({
        method: 'GET',
        url: `${server.info.uri}/api/sample/ping`,
        json: true,
        resolveWithFullResponse: true
      })
      assert(checksum === response.headers[checksumHeader])
    })

    it('should include CRC32 as header for API with parameters', async () => {
      const response = await request({
        method: 'POST',
        url: `${server.info.uri}/api/sample/greeting`,
        body: {
          name: 'John'
        },
        json: true,
        resolveWithFullResponse: true
      })
      assert(response.headers['x-service-crc'] === checksum)
    })

    it('should invoke API without argument', async () => {
      const {time} = await request({
        method: 'GET',
        url: `${server.info.uri}/api/sample/ping`,
        json: true
      })
      assert(typeof time === 'string')
    })

    it('should invoke async API with argument', async () => {
      const greetings = await request({
        method: 'POST',
        url: `${server.info.uri}/api/sample/greeting`,
        body: {
          name: 'John'
        },
        json: true
      })
      assert(greetings === 'Hello John !')
    })

    it('should invoke sync API with argument', async () => {
      const greetings = await request({
        method: 'POST',
        url: `${server.info.uri}/api/synchronous/greeting`,
        body: {
          name: 'John'
        },
        json: true
      })
      assert(greetings === 'Hello John !')
    })

    it('should handle argument validation for async API', async () => {
      try {
        await request({
          method: 'POST',
          url: `${server.info.uri}/api/sample/greeting`,
          body: {
            name: 10
          },
          json: true
        })
      } catch ({error}) {
        assert(error.message.includes('Incorrect parameters for API greeting'))
        assert(error.message.includes('"name" must be a string'))
        assert(error.error === 'Bad Request')
        assert(error.statusCode === 400)
        return
      }
      throw new Error('should have failed')
    })

    it('should handle argument validation for async API', async () => {
      try {
        await request({
          method: 'POST',
          url: `${server.info.uri}/api/synchronous/greeting`,
          body: {
            name: 10
          },
          json: true
        })
      } catch ({error}) {
        assert(error.message.includes('Incorrect parameters for API greeting'))
        assert(error.message.includes('"name" must be a string'))
        assert(error.error === 'Bad Request')
        assert(error.statusCode === 400)
        return
      }
      throw new Error('should have failed')
    })

    it('should handle response validation for async API', async () => {
      let res
      try {
        res = await request({
          method: 'POST',
          url: `${server.info.uri}/api/sample/greeting`,
          body: {
            name: 'boom'
          },
          json: true
        })
      } catch ({error}) {
        assert(error.message.includes('Incorrect response for API greeting'))
        assert(error.message.includes('"greetingResult" must be a string'))
        assert(error.error === 'Bad Response')
        assert(error.statusCode === 512)
        return
      }
      throw new Error(`unexpected result: ${JSON.stringify(res, null, 2)}`)
    })

    it('should handle response validation for sync API', async () => {
      let res
      try {
        res = await request({
          method: 'POST',
          url: `${server.info.uri}/api/synchronous/greeting`,
          body: {
            name: 'boom'
          },
          json: true
        })
      } catch ({error}) {
        assert(error.error === 'Bad Response')
        assert(error.message.includes('Incorrect response for API greeting'))
        assert(error.message.includes('"greetingResult" must be a string'))
        assert(error.statusCode === 512)
        return
      }
      throw new Error(`unexpected result: ${JSON.stringify(res, null, 2)}`)
    })

    it('should handle undefined results from async API', async () => {
      const result = await request({
        method: 'GET',
        url: `${server.info.uri}/api/sample/getUndefined`,
        json: true
      })
      assert(result === undefined)
    })

    it('should handle undefined results from sync API', async () => {
      const result = await request({
        method: 'GET',
        url: `${server.info.uri}/api/synchronous/getUndefined`,
        json: true
      })
      assert(result === undefined)
    })

    it('should handle API asynchronous failure', async () => {
      try {
        await request({
          method: 'GET',
          url: `${server.info.uri}/api/sample/failing`,
          json: true
        })
      } catch ({error}) {
        assert(error.statusCode === 599)
        assert(error.message.includes('Error while calling API failing'))
        assert(error.message.includes('something went really bad'))
        return
      }
      throw new Error('should have failed')
    })

    it('should handle API synchronous failure', async () => {
      try {
        await request({
          method: 'GET',
          url: `${server.info.uri}/api/sample/errored`,
          json: true
        })
      } catch ({error}) {
        assert(error.statusCode === 599)
        assert(error.message.includes('Error while calling API errored'))
        assert(error.message.includes('errored API'))
        return
      }
      throw new Error('should have failed')
    })

    it('should propagate Boom errors from async API', async () => {
      try {
        await request({
          method: 'GET',
          url: `${server.info.uri}/api/sample/boomError`,
          json: true
        })
      } catch ({error}) {
        assert(error.statusCode === 401)
        assert(error.message.includes('Custom authorization error'))
        return
      }
      throw new Error('should have failed')
    })

    it('should propagate Boom errors from sync API', async () => {
      try {
        await request({
          method: 'GET',
          url: `${server.info.uri}/api/synchronous/boomError`,
          json: true
        })
      } catch ({error}) {
        assert(error.statusCode === 401)
        assert(error.message.includes('Custom authorization error'))
        return
      }
      throw new Error('should have failed')
    })

    it('should handle async API with exotic parameters', async () => {
      const result = await request({
        method: 'POST',
        url: `${server.info.uri}/api/sample/withExoticParameters`,
        body: {
          param1: [1, 2],
          param2: {c: {d: 3}},
          other: 4,
          3: 5, // according to arrayToObj(), param0 is 0, param2 is 1, other is 2.
          4: 6
        },
        json: true
      })
      assert.deepStrictEqual(result, [1, 2, 3, 4, 5, 6])
    })

    it('should handle sync API with exotic parameters', async () => {
      const result = await request({
        method: 'POST',
        url: `${server.info.uri}/api/synchronous/withExoticParameters`,
        body: {
          param1: [1, 2],
          param2: {c: {d: 3}},
          other: 4,
          3: 5, // according to arrayToObj(), param0 is 0, param2 is 1, other is 2.
          4: 6
        },
        json: true
      })
      assert.deepStrictEqual(result, [1, 2, 3, 4, 5, 6])
    })

    it('should not complain about big payload', {timeout: 5e3}, async () => {
      const name = Array.from({length: 1024 * 1024 * 10}, () => 'a').join('')
      const greetings = await request({
        method: 'POST',
        url: `${server.info.uri}/api/sample/greeting`,
        body: {name},
        json: true
      })
      assert(greetings)
    })

    it('should send and receive buffers', async () => {
      const response = await request({
        method: 'POST',
        url: `${server.info.uri}/api/sample/bufferHandling`,
        body: Buffer.from(new Uint8Array([1, 2])),
        resolveWithFullResponse: true
      })
      assert(response.headers['content-type'] === 'application/octet-stream')
      assert(response.headers['x-service-crc'] === checksum)
      const result = Buffer.from(response.body)
      assert(Buffer.compare(result, Buffer.from(new Uint8Array([1, 2, 3, 4]))) === 0)
    })

    it('should send and receive streams', async () => {
      const {response, result} = await new Promise((resolve, reject) => {
        let response
        const output = new BufferList()
        const input = new BufferList()

        input.pipe(
          req.post(`${server.info.uri}/api/sample/streamHandling`)
            .on('response', r => {
              response = r
            })
            .on('end', () => {
              resolve({response, result: output.toString()})
            })
        )
          .pipe(output)
          .on('error', reject)

        input.append('here is the message body', 'utf8')
      })
      assert(result === 'here is a prefix -- here is the message body')
      assert(response.headers['x-service-crc'] === checksum)
      assert(response.headers['transfer-encoding'] === 'chunked')
      assert(!response.headers['content-type'])
    })
  })

  describe('server with an ordered list of groups', () => {
    let server
    const initOrder = []
    const ordered = Array.from({length: 3}).map((v, i) => ({
      name: `group-${i}`,
      init: async opts => {
        if (opts.fail) throw new Error(`group ${i} failed to initialize`)
        initOrder.push(i)
        opts.logger.warn(`from group ${i}`)
      }
    }))

    beforeEach(() => {
      server = null
      initOrder.splice(0, initOrder.length)
    })

    afterEach(async () => {
      if (server) {
        await server.stop()
      }
    })

    it('should keep order when registering locally', async () => {
      server = await startServer({name, version, groups: ordered})
      assert.deepEqual(initOrder, [0, 1, 2])
    })

    it('should stop initialisation at first error', async () => {
      try {
        server = await startServer({
          name,
          version,
          groups: ordered,
          groupOpts: {
            'group-1': {fail: true}
          }
        })
      } catch (err) {
        assert(err instanceof Error)
        assert(err.message.includes('group 1 failed to initialize'))
        assert.deepEqual(initOrder, [0])
        return
      }
      throw new Error('should have failed')
    })

    it('should ignore groups that doesn\'t expose an object', async () => {
      server = await startServer({
        name,
        version,
        groups: [{
          name: 'init-string',
          init: () => Promise.resolve('initialized')
        }, {
          name: 'init-boolean',
          init: () => Promise.resolve(true)
        }, {
          name: 'init-array',
          init: () => Promise.resolve([{worked: true}])
        }, {
          name: 'init-empty',
          init: () => Promise.resolve(null)
        }].concat(ordered)
      })
    })

    it('should enforce group name', async () => {
      try {
        server = await startServer({
          name,
          version,
          groups: [{
            init: () => Promise.resolve('initialized')
          }]
        })
      } catch (err) {
        assert(err instanceof Error)
        assert(err.message.indexOf('"name" is required') !== -1)
        return
      }
      throw new Error('should have failed')
    })

    it('should enforce group init function', async () => {
      try {
        server = await startServer({
          name,
          version,
          groups: [{
            name: 'test'
          }]
        })
      } catch (err) {
        assert(err instanceof Error)
        assert(err.message.includes('"init" is required'))
        return
      }
      throw new Error('should have failed')
    })

    it('should manage init function not returning Promise', async () => {
      server = await startServer({
        name,
        version,
        groups: [{
          name: 'test',
          init: () => ({test: () => 'test'})
        }]
      })
    })

    it('should expose logger to groups', async () => {
      const logs = []
      const logger = bunyan.createLogger({name: 'test'})
      logger.warn = msg => logs.push(msg)
      server = await startServer({
        name,
        version,
        logger,
        groups: ordered
      })
      assert.deepEqual(logs, ['from group 0', 'from group 1', 'from group 2'])
    })
  })
})


text:
package md.frolov.legume.client.elastic.model.query;

import java.util.Date;
import java.util.List;
import java.util.Map;

/** @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public interface RangeFacet extends Facet
{
    Map<String, List<RangeDef>> getRange();

    void setRange(Map<String, List<RangeDef>> range);

    interface RangeDef
    {
    }

    interface RangeStr extends RangeDef
    {
        String getFrom();
        void setFrom(String from);
        String getTo();
        void setTo(String to);
    }

    interface RangeInt extends RangeDef
    {
        int getFrom();
        void setFrom(int from);
        int getTo();
        void setTo(int to);
    }

    interface RangeDate extends RangeDef {
        Date getFrom();
        void setFrom(Date from);
        Date getTo();
        void setTo(Date date);
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_places_History_h_
#define mozilla_places_History_h_

#include "mozilla/IHistory.h"
#include "mozilla/Mutex.h"
#include "mozIAsyncHistory.h"
#include "nsIDownloadHistory.h"
#include "Database.h"

#include "mozilla/dom/Link.h"
#include "nsTHashtable.h"
#include "nsString.h"
#include "nsURIHashKey.h"
#include "nsTObserverArray.h"
#include "nsDeque.h"
#include "nsIObserver.h"
#include "mozIStorageConnection.h"

namespace mozilla {
namespace places {

struct VisitData;

#define NS_HISTORYSERVICE_CID \
  {0x0937a705, 0x91a6, 0x417a, {0x82, 0x92, 0xb2, 0x2e, 0xb1, 0x0d, 0xa8, 0x6c}}

// Max size of History::mRecentlyVisitedURIs
#define RECENTLY_VISITED_URI_SIZE 8

class History : public IHistory
              , public nsIDownloadHistory
              , public mozIAsyncHistory
              , public nsIObserver
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_IHISTORY
  NS_DECL_NSIDOWNLOADHISTORY
  NS_DECL_MOZIASYNCHISTORY
  NS_DECL_NSIOBSERVER

  History();

  /**
   * Obtains the statement to use to check if a URI is visited or not.
   */
  mozIStorageAsyncStatement* GetIsVisitedStatement();

  /**
   * Adds an entry in moz_places with the data in aVisitData.
   *
   * @param aVisitData
   *        The visit data to use to populate a new row in moz_places.
   */
  nsresult InsertPlace(const VisitData& aVisitData);

  /**
   * Updates an entry in moz_places with the data in aVisitData.
   *
   * @param aVisitData
   *        The visit data to use to update the existing row in moz_places.
   */
  nsresult UpdatePlace(const VisitData& aVisitData);

  /**
   * Loads information about the page into _place from moz_places.
   *
   * @param _place
   *        The VisitData for the place we need to know information about.
   * @return true if the page was recorded in moz_places, false otherwise.
   */
  bool FetchPageInfo(VisitData& _place);

  /**
   * Get the number of bytes of memory this History object is using,
   * including sizeof(*this))
   */
  size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf);

  /**
   * Obtains a pointer to this service.
   */
  static History* GetService();

  /**
   * Obtains a pointer that has had AddRef called on it.  Used by the service
   * manager only.
   */
  static History* GetSingleton();

  template<int N>
  already_AddRefed<mozIStorageStatement>
  GetStatement(const char (&aQuery)[N])
  {
    mozIStorageConnection* dbConn = GetDBConn();
    NS_ENSURE_TRUE(dbConn, nullptr);
    return mDB->GetStatement(aQuery);
  }

  bool IsShuttingDown() const {
    return mShuttingDown;
  }
  Mutex& GetShutdownMutex() {
    return mShutdownMutex;
  }

  /**
   * Helper function to append a new URI to mRecentlyVisitedURIs. See
   * mRecentlyVisitedURIs.
   */
  void AppendToRecentlyVisitedURIs(nsIURI* aURI);

private:
  virtual ~History();

  /**
   * Obtains a read-write database connection.
   */
  mozIStorageConnection* GetDBConn();

  /**
   * The database handle.  This is initialized lazily by the first call to
   * GetDBConn(), so never use it directly, or, if you really need, always
   * invoke GetDBConn() before.
   */
  nsRefPtr<mozilla::places::Database> mDB;

  /**
   * A read-only database connection used for checking if a URI is visited.
   *
   * @note this should only be accessed by GetIsVisistedStatement and Shutdown.
   */
  nsCOMPtr<mozIStorageConnection> mReadOnlyDBConn;

  /**
   * An asynchronous statement to query if a URI is visited or not.
   *
   * @note this should only be accessed by GetIsVisistedStatement and Shutdown.
   */
  nsCOMPtr<mozIStorageAsyncStatement> mIsVisitedStatement;

  /**
   * Remove any memory references to tasks and do not take on any more.
   */
  void Shutdown();

  static History* gService;

  // Ensures new tasks aren't started on destruction.
  bool mShuttingDown;
  // This mutex guards mShuttingDown. Code running in other threads that might
  // schedule tasks that use the database should grab it and check the value of
  // mShuttingDown. If we are already shutting down, the code must gracefully
  // avoid using the db. If we are not, the lock will prevent shutdown from
  // starting in an unexpected moment.
  Mutex mShutdownMutex;

  typedef nsTObserverArray<mozilla::dom::Link* > ObserverArray;

  class KeyClass : public nsURIHashKey
  {
  public:
    KeyClass(const nsIURI* aURI)
    : nsURIHashKey(aURI)
    {
    }
    KeyClass(const KeyClass& aOther)
    : nsURIHashKey(aOther)
    {
      NS_NOTREACHED("Do not call me!");
    }
    ObserverArray array;
  };

  /**
   * Helper function for nsTHashtable::SizeOfExcludingThis call in
   * SizeOfIncludingThis().
   */
  static size_t SizeOfEntryExcludingThis(KeyClass* aEntry,
                                         nsMallocSizeOfFun aMallocSizeOf,
                                         void*);

  nsTHashtable<KeyClass> mObservers;

  /**
   * mRecentlyVisitedURIs remembers URIs which are recently added to the DB,
   * to avoid saving these locations repeatedly in a short period.
   */
  typedef nsAutoTArray<nsCOMPtr<nsIURI>, RECENTLY_VISITED_URI_SIZE>
          RecentlyVisitedArray;
  RecentlyVisitedArray mRecentlyVisitedURIs;
  RecentlyVisitedArray::index_type mRecentlyVisitedURIsNextIndex;

  bool IsRecentlyVisitedURI(nsIURI* aURI);
};

} // namespace places
} // namespace mozilla

#endif // mozilla_places_History_h_


text:
Pyjobs_web require some OS dependencies (to build project python libs), for a debian-like you can install them with ``apt-get``:

```
# apt-get install python python-dev python-pip git libpq-dev libxml2-dev libxslt1-dev libffi-dev
```

Pyjobs_web also requires an Elasticsearch database to be installed on the server. On a debian-like server you can do the following:

```
# wget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | apt-key add -
# echo "deb https://packages.elastic.co/elasticsearch/2.x/debian stable main" | tee -a /etc/apt/sources.list.d/elasticsearch-2.x.list
```

```
# apt-get update && apt-get install elasticsearch
```

```
# /bin/systemctl daemon-reload
# /bin/systemctl enable elasticsearch.service
```
For other systems (and if you need more details for the installation on debian), you can refer to the official documentation:
https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-repositories.html

If you are not interested in setting up replication on different nodes for Elasticsearch, you might want to consider adding the following line at the end of your ``/etc/elasticsearch/elasticsearch.yml`` file for your pyjobs cluster:

 ```
 index.number_of_replicas: 0
 ```

This will prevent your cluster's health to turn to yellow due to impossible to perform replication on another node (since there are no other node).

### Pyjobs Web

**Note**: For production environment, create ``production.ini`` configuration file from copying ``development.ini.template`` and replace ``development.ini`` by ``production.ini`` in following instructions.

Clone the project:

```
git clone http://gitlab.algoo.fr:10080/algoo/pyjobs_web.git pyjobs_web
```

Move to ``pyjobs_web/pyjobs_web`` directory:

```
mv pyjobs_web/pyjobs_web
```

Install python dependencies:

```
pip install -r requirements.txt
```

Install ``pyjobsweb`` using the setup.py script:

```
python setup.py develop
```

Update config according to your database in ``pyjobs_web/pyjobs_web/development.ini``. Import lines to update are:

* ``debug``: Think to switch at ``False`` if you are in production environment.
* ``session.secret``
* ``session.validate_key``
* ``sqlalchemy.url``: Update it according to your database (MySQL, PostgreSQL, SQLite, [etc](http://docs.sqlalchemy.org/en/latest/core/engines.html).).
* ``elasticsearch.host``: Elasticsearch's address and port (default is localhost:9200)
* ``elasticsearch.project_name``: The name of the project (default is pyjobs)
* ``elasticsearch.instance_name``: The instance of the project (default is dev)
* ``processes.project_name``: The name of the project (default is pyjobs)
* ``processes.instance_name``: The instance of the project (default is dev)

``elasticsearch.project_name`` and ``elasticsearch.instance_name`` will be used as prefix (in the form ``elasticsearch.project_name``_``elasticsearch.instance_name``) for indexes defined in pyjobs. This every indexes for this instance will have the following names: ``elasticsearch.project_name``_``elasticsearch.project_name``_pyjobs_index_name, making it possible for you to run several instances of pyjobs on the same instance of Elasticsearch.

The same applies for ``processes.project_name`` and ``processes.instance_name`` though these are used by interprocesses locks used by pyjobs' background processes.

Create the project PostgreSQL database for any model classes defined, as well as Elasticsearch indexes:

    $ gearbox setup-app -c development.ini

At this point the PostgreSQL database is up and running and Elasticsearch too. Though you will first need to populate the geocompletion index of Elasticsearch for you pyjobs' instance. This is done using the following command:

    $ gearbox populate-elasticsearch -g

At this point the geocompletion data is indexed and ready for search in Elasticsearch. IICIICICICI

### Run PyJobs Web

Start the paste http server::

    $ gearbox serve -c development.ini

While developing you may want the server to reload after changes in package files (or its dependencies) are saved. This can be achieved easily by adding the --reload option::

    $ gearbox serve -c development.ini --reload --debug

Then you are ready to go.

## Update job database with crawls

Run ``gearbox crawl-job-boards`` command. It will be run [PyJobs Crawlers](https://github.com/pyjobs/crawlers) and feed PyJobs Web database.

## Geotagging job offers and companies

You may want to geotag job offers and companies so that they can be filter through geolocation filters (that is if you want the research form to be completely operational).
Pyjobs comes with a command to do just this: ``geotag-jobs-and-companies [-j|--jobs] [-co|--companies]``. This command will perform geotagging operations for job offers or companies depending on the specified parameters. Though you might want to do just one at a time (to not flood the nominatim API, be respectful please :). If some addresses couldn't be geotagged (which might happen for various reasons), you will have to solve theses problems by hand through the admin interface of pyjobs.

## Populate the Elasticsearch database with populate-elasticsearch

Now that we have some data stored in the PostgreSQL database, it is time to index it in Elasticsearch, to make it searchable. To do so, run ``gearbox populate-elasticsearch [-j|--jobs] [-co|--companies] [-g|--geocomplete]`` command. This command, depending on the specified arguments will perform synchronization between the PostgreSQL database and Elasticsearch, or it might have a different behavior when using the -g option. Indeed, when specifying -j or -co, it will perform a synchronization of the job offers stored in PostgreSQL and their corresponding documents in Elasticsearch (the same goes for the companies with -co). But when you specify the -g (or --geocomplete), it will build geocompletion documents based from the static data present in the ``static/geolocations/fr_locations.json`` file, and then index these documents under the geocompletion index. If you run the command:

    $ gearbox populate-elasticsearch -g

several times, it will create duplicates in the Elasticsearch database (which won't happen with -j or -co, which perform synchronization operations!).

This leads us to the next command.

## Purge the Elasticsearch database with purge-elasticsearch

Run ``gearbox purge-elasticsearch [-j|--jobs] [-co|--companies] [-g|--geocomplete]`` command. This command will drop the corresponding index in Elasticsearch (the job, company or geocomplete index based on the argument) and will then re-create it.
This is useful while developing, since it allows you to change the mapping for an index, and then re-index documents corresponding to the with the new mapping with the ``gearbox populate-elasticsearch`` command. It will also reset every synchronization data (stored in PostgreSQL), so that running ``gearbox populate-elasticsearch`` still works after purging an index.

## Publication bots

Pyjobs comes with two different publication bots right now. One of them is customizable, while the other isn't. The command which you can use to start these bots is the following: ``gearbox run-publication-bots [twitter [-n NUMBER] -cf credentials_file.json] [github]``. As stated earlier the Github bot isn't customizable and is likely not to work for you (unless you have the authorization to push on the official https://github.com/pyjobs/annonces.git repository) right now. On the other hand, the Twitter bot will work if you provide it with a .json file, containing your Twitter credentials keys in the following format:

{
    "consumer_key":"consumer_key_value_here",
	"consumer_secret":"consumer_secret_value_here",
	"access_token_key":"access_token_key_value_here",
	"access_token_secret":"access_token_secret_value_here"
}


text:
package wrappers

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	//"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type MockFunc func(ctx APICtx, test map[string]string, h http.Header) (map[string]string, int, http.Header, error)

type apiReq struct {
	Query string
}

type Test struct {
	name string
	fn   interface{}
	err  error
}

type Input struct {
	V string
}

type APICtx struct {
}

func TestWrappers(t *testing.T) {
	tests := []Test{
		{
			"Wraps context input",
			func(ctx APICtx) (Input, error) {
				return Input{V: "test"}, nil
			},
			nil,
		}, {
			"Wraps context + object inputs",
			func(ctx APICtx, test Input) (Input, error) {
				return test, nil
			},
			nil,
		}, {
			"Wraps context + object + header inputs",
			func(ctx APICtx, test Input, h http.Header) (Input, error) {
				return test, nil
			},
			nil,
		}, {
			"Wraps object + error outputs",
			func(ctx APICtx, test Input) (Input, error) {
				return test, nil
			},
			nil,
		}, {
			"Wraps object + status + header outputs",
			func(ctx APICtx, test Input) (Input, int, error) {
				return test, http.StatusOK, nil
			},
			nil,
		}, {
			"Wraps object + status + header + error outputs",
			func(ctx APICtx, test Input) (Input, int, http.Header, error) {
				return test, http.StatusOK, http.Header{}, nil
			},
			nil,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			h, err := BuildEndpoint("post", test.fn)
			if test.err != nil {
				require.NotNil(t, err)
			} else {
				require.EqualValues(t, test.err, err)
			}

			ctx := APICtx{}
			r := Input{V: "test"}
			b, err := json.Marshal(r)
			require.Nil(t, err)

			req, err := http.NewRequest(http.MethodPost, "/", bytes.NewReader(b))
			require.Nil(t, err)
			resp := httptest.NewRecorder()

			h(ctx, resp, req)
		})
	}
}


text:
@interface PodsDummy_Bypass : NSObject
@end
@implementation PodsDummy_Bypass
@end


text:
<?php

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

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),

            new Kimai\Bundle\CoreBundle\KimaiCoreBundle(),
            new Kimai\Bundle\TimeTrackingBundle\KimaiTimeTrackingBundle(),
            new Kimai\Bundle\AuthBundle\KimaiAuthBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>simpla-text</title>

    <link rel="import" href="../../iron-test-helpers/iron-test-helpers.html">
    <link rel="import" href="./test-setup.html">

    <link rel="import" href="../simpla-text.html">

    <test-fixture id="simple">
      <template>
        <simpla-text editable></simpla-text>
      </template>
    </test-fixture>
    <test-fixture id="forced-inline">
      <template>

<simpla-text inline editable></simpla-text>

      </template>
    </test-fixture>
    <test-fixture id="auto-inline">
      <template>

          <simpla-text editable></simpla-text>

      </template>
    </test-fixture>


text:
extern "C" int __attribute__((weak)) weak_undefined_func();

extern "C" int use_weak_undefined_func() {
  if (weak_undefined_func) {
    return weak_undefined_func();
  } else {
    return 6551;
  }
}


text:
<?php

namespace Cerad\Bundle\TournBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CeradTournBundle extends Bundle
{
}


text:
package org.wso2.carbon.apimgt.application.extension;

import feign.FeignException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil;
import org.wso2.carbon.apimgt.integration.client.store.*;
import org.wso2.carbon.apimgt.integration.generated.client.store.model.*;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

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

/**
 * This class represents an implementation of APIManagementProviderService.
 */
public class APIManagementProviderServiceImpl implements APIManagementProviderService {

    private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class);
    private static final String CONTENT_TYPE = "application/json";
    private static final int MAX_API_PER_TAG = 200;
    private static final String APP_TIER_TYPE = "application";

    public boolean isTierLoaded() {
        StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
                .getStoreClient();
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getTenantDomain();
        try {

            storeClient.getIndividualTier().tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER,
                                                                      APP_TIER_TYPE,
                                                                      tenantDomain, CONTENT_TYPE, null, null);
            return true;
        } catch (FeignException e) {
            return false;
        }
    }

    @Override
    public void removeAPIApplication(String applicationName, String username) throws APIManagerException {

        StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
                .getStoreClient();
        ApplicationList applicationList = storeClient.getApplications()
                .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
        if (applicationList.getList() != null && applicationList.getList().size() > 0) {
            ApplicationInfo applicationInfo = applicationList.getList().get(0);
            storeClient.getIndividualApplication().applicationsApplicationIdDelete(applicationInfo.getApplicationId(),
                                                                                null, null);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[],
                                                                String keyType, String username,
                                                                boolean isAllowedAllDomains, String validityTime)
            throws APIManagerException {
        StoreClient storeClient =
                APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
                        .getStoreClient();
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getTenantDomain();
        try {
            ApplicationList applicationList = storeClient.getApplications()
                    .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
            Application application;
            if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) {
                //create application;
                application = new Application();
                application.setName(applicationName);
                application.setSubscriber(username);
                application.setDescription("");
                application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER);
                application.setGroupId("");
                application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE);
            } else {
                ApplicationInfo applicationInfo = applicationList.getList().get(0);
                application = storeClient.getIndividualApplication()
                        .applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null);
            }
            if (application == null) {
                throw new APIManagerException(
                        "Api application creation failed for " + applicationName + " to the user " + username);
            }

            SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet
                    (null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null);
            List<Subscription> needToSubscribe = new ArrayList<>();
            // subscribe to apis.
            if (tags != null && tags.length > 0) {
                for (String tag : tags) {
                    APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag
                            , CONTENT_TYPE, null);
                    if (apiList.getList() == null || apiList.getList().size() == 0) {
                        apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0
                                , MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null);
                    }

                    if (apiList.getList() != null && apiList.getList().size() > 0) {
                        for (APIInfo apiInfo : apiList.getList()) {
                            String id = apiInfo.getProvider().replace("@", "-AT-")
                                    + "-" + apiInfo.getName() + "-" + apiInfo.getVersion();
                            boolean subscriptionExist = false;
                            if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) {
                                for (Subscription subs : subscriptionList.getList()) {
                                    if (subs.getApiIdentifier().equals(id)) {
                                        subscriptionExist = true;
                                        break;
                                    }
                                }
                            }
                            if (!subscriptionExist) {
                                Subscription subscription = new Subscription();
                                //fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0

                                subscription.setApiIdentifier(id);
                                subscription.setApplicationId(application.getApplicationId());
                                subscription.tier(ApiApplicationConstants.DEFAULT_TIER);
                                if (!needToSubscribe.contains(subscription)) {
                                    needToSubscribe.add(subscription);
                                }
                            }
                        }
                    }
                }
            }
            if (!needToSubscribe.isEmpty()) {
                storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE);
            }
            //end of subscription

            List<ApplicationKey> applicationKeys = application.getKeys();
            if (applicationKeys != null) {
                for (ApplicationKey applicationKey : applicationKeys) {
                    if (keyType.equals(applicationKey.getKeyType().toString())) {
                        if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
                            ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
                            apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
                            apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
                            return apiApplicationKey;
                        }
                    }
                }
            }

            ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest();
            List<String> allowedDomains = new ArrayList<>();
            if (isAllowedAllDomains) {
                allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
            } else {
                allowedDomains.add(APIManagerUtil.getTenantDomain());
            }
            applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains);
            applicationKeyGenerateRequest.setCallbackUrl("");
            applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION);
            applicationKeyGenerateRequest.setValidityTime(validityTime);

            ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost(
                    application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null);
            if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
                ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
                apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
                apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
                return apiApplicationKey;
            }
            throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain);
        } catch (FeignException e) {
            throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
        }
    }

}


text:
use pulldown_cmark::{Event, Parser, Tag};

/// Removes all markdown, keeping the text and code blocks
///
/// Currently limited in styling, i.e. no ascii tables or lists
pub(crate) fn remove_markdown(markdown: &str) -> String {
    let mut out = String::new();
    let parser = Parser::new(markdown);

    for event in parser {
        match event {
            Event::Text(text) | Event::Code(text) => out.push_str(&text),
            Event::SoftBreak | Event::HardBreak | Event::Rule | Event::End(Tag::CodeBlock(_)) => {
                out.push('\n')
            }
            _ => {}
        }
    }

    out
}


text:
package poc.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.x.discovery.*;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * This class acts as a facade over the Curator APIs for Service Registration and Discovery.
 * You can register/unregister, discover all services and discover based on name.
 */
public final class ServiceDiscoveryRecipe {

  private final CuratorFramework curatorClient;
  private final ServiceDiscovery<InstanceDetails> serviceDiscovery;
  private final Map<String, ServiceInstance<InstanceDetails>> serviceInstances;

  // tracks all closeables so we can do a clean termination for all of them.
  private final List<Closeable> closeAbles = new ArrayList<>();

  public ServiceDiscoveryRecipe(String zookeeperAddress) throws Exception {
    serviceInstances = new HashMap<>();
    System.out.println("Connecting to ZooKeeper: " + zookeeperAddress);

    // Specify retry mechanism in case of recoverable errors from ZooKeeper.
    curatorClient = CuratorFrameworkFactory.newClient(zookeeperAddress,
        new ExponentialBackoffRetry(1000, 3));

    // Payload Serializer
    final JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<>(InstanceDetails.class);

    // Service Discovery
    serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
        .client(curatorClient)
        .basePath(Config.SERVICES_PATH)
        .serializer(serializer)
        .build();
  }

  public void registerService(String serviceName, int servicePort) throws UnknownHostException, Exception {
    // Scheme, address and port - This will yield an address of form: http://<ip>:port/
    final UriSpec uriSpec = new UriSpec("{scheme}://{address}:{port}");

    final ServiceInstance<InstanceDetails> thisInstance = ServiceInstance.<InstanceDetails>builder().name(serviceName)
        .uriSpec(uriSpec)
        // Pass the IP address the instance is available on
        .address(InetAddress.getLocalHost().getHostAddress())
        // Pass the Port the instance is available on
        .port(servicePort)
        // Pass other Instance details that you want to expose for other services to discover
        .payload(new InstanceDetails(serviceName))
        .build();

    serviceDiscovery.registerService(thisInstance);

    // track it so we can unregister this one.
    serviceInstances.put(serviceName + servicePort, thisInstance);
  }

  public void unregisterService(final String serviceName, final String servicePort) throws Exception {
    final ServiceInstance<InstanceDetails> thisInstance = serviceInstances.get(serviceName + servicePort);
    if (thisInstance != null) {
      serviceDiscovery.unregisterService(thisInstance);
    }
  }

  public void discover(final String serviceName) throws Exception {
    System.out.println("Looking up " + serviceName);
    final Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);

    for (ServiceInstance<InstanceDetails> instance : instances) {
      outputInstance(instance);
    }
  }

  public void discoverAll() throws Exception {
    final Collection<String> serviceNames = serviceDiscovery.queryForNames();

    for (String serviceName : serviceNames) {
      final Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);
      System.out.println("Looking up " + serviceName);
      for (ServiceInstance<InstanceDetails> instance : instances) {
        outputInstance(instance);
      }
    }
  }

  public void start() {
    try {
      curatorClient.start();
      closeAbles.add(curatorClient);
      serviceDiscovery.start();
      // add to top so we can close it first.
      closeAbles.add(0, serviceDiscovery);
    } catch (Exception e) {
      throw new RuntimeException("Error starting Curator Framework/Discovery", e);
    }
  }

  public void close() {
    // Close all
    for (Closeable closeable : closeAbles) {
      CloseableUtils.closeQuietly(closeable);
    }
  }

  private static void outputInstance(ServiceInstance<InstanceDetails> instance) {
    System.out.println("\t" + instance.getPayload().getDescription() + ": " + instance.buildUriSpec());
  }

}


text:
Portalpy
=========
Portalpy is a Python module that allows you to administer Portal for ArcGIS and ArcGIS Online.

## Features
* Designed to be easy.  Most tasks require just a few lines of code.
* Allows user and group management.
* Fully-documented.
* Includes unit tests.

## Requirements
* Python 2.7
* Works with ArcGIS Online and all versions of Portal.

## Resources
* Portalpy.html (reference doc, included in repo)
* http://portalpy.esri.com - this is a running Portal that are used for the unit tests.  It's intended for use in testing with portalpy.

## Issues or new requests?
* We are actively working on implementing functionality for item management.  If you have a request in this area, please wait.
* If you find a bug or have a request for functionality other than item management, please create an item in GitHub.

## Contributing
We really need useful example scripts or modules that use PortalPy.

## Licensing
Copyright 2014 Esri

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

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

[](Esri Tags: ArcGIS-Online Portal-for-ArcGIS Portal Python Tools Library)
[](Esri Language: Python)


text:
namespace System.Drawing.Imaging
{

public sealed class ColorMap
{
	// Internal state.
	private Color newColor;
	private Color oldColor;

	// Constructor.
	public ColorMap() {}

	// Get or set this object's properties.
	public Color NewColor
			{
				get
				{
					return newColor;
				}
				set
				{
					newColor = value;
				}
			}
	public Color OldColor
			{
				get
				{
					return oldColor;
				}
				set
				{
					oldColor = value;
				}
			}

}; // class ColorMap

}; // namespace System.Drawing.Imaging