text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v11/errors/audience_error.proto

namespace Google\Ads\GoogleAds\V11\Errors\AudienceErrorEnum;

use UnexpectedValueException;

/**
 * Enum describing possible audience errors.
 *
 * Protobuf type google.ads.googleads.v11.errors.AudienceErrorEnum.AudienceError
 */
class AudienceError
{
    /**
     * Enum unspecified.
     *
     * Generated from protobuf enum UNSPECIFIED = 0;
     */
    const UNSPECIFIED = 0;
    /**
     * The received error code is not known in this version.
     *
     * Generated from protobuf enum UNKNOWN = 1;
     */
    const UNKNOWN = 1;
    /**
     * An audience with this name already exists.
     *
     * Generated from protobuf enum NAME_ALREADY_IN_USE = 2;
     */
    const NAME_ALREADY_IN_USE = 2;
    /**
     * A dimension within the audience definition is not valid.
     *
     * Generated from protobuf enum DIMENSION_INVALID = 3;
     */
    const DIMENSION_INVALID = 3;
    /**
     * One of the audience segment added is not found.
     *
     * Generated from protobuf enum AUDIENCE_SEGMENT_NOT_FOUND = 4;
     */
    const AUDIENCE_SEGMENT_NOT_FOUND = 4;
    /**
     * One of the audience segment type is not supported.
     *
     * Generated from protobuf enum AUDIENCE_SEGMENT_TYPE_NOT_SUPPORTED = 5;
     */
    const AUDIENCE_SEGMENT_TYPE_NOT_SUPPORTED = 5;
    /**
     * The same segment already exists in this audience.
     *
     * Generated from protobuf enum DUPLICATE_AUDIENCE_SEGMENT = 6;
     */
    const DUPLICATE_AUDIENCE_SEGMENT = 6;
    /**
     * Audience can't have more than allowed number segments.
     *
     * Generated from protobuf enum TOO_MANY_SEGMENTS = 7;
     */
    const TOO_MANY_SEGMENTS = 7;
    /**
     * Audience can't have multiple dimensions of same type.
     *
     * Generated from protobuf enum TOO_MANY_DIMENSIONS_OF_SAME_TYPE = 8;
     */
    const TOO_MANY_DIMENSIONS_OF_SAME_TYPE = 8;
    /**
     * The audience cannot be removed, because it is currently used in an
     * ad group criterion or asset group signal in an (enabled or paused)
     * ad group or campaign.
     *
     * Generated from protobuf enum IN_USE = 9;
     */
    const IN_USE = 9;

    private static $valueToName = [
        self::UNSPECIFIED => 'UNSPECIFIED',
        self::UNKNOWN => 'UNKNOWN',
        self::NAME_ALREADY_IN_USE => 'NAME_ALREADY_IN_USE',
        self::DIMENSION_INVALID => 'DIMENSION_INVALID',
        self::AUDIENCE_SEGMENT_NOT_FOUND => 'AUDIENCE_SEGMENT_NOT_FOUND',
        self::AUDIENCE_SEGMENT_TYPE_NOT_SUPPORTED => 'AUDIENCE_SEGMENT_TYPE_NOT_SUPPORTED',
        self::DUPLICATE_AUDIENCE_SEGMENT => 'DUPLICATE_AUDIENCE_SEGMENT',
        self::TOO_MANY_SEGMENTS => 'TOO_MANY_SEGMENTS',
        self::TOO_MANY_DIMENSIONS_OF_SAME_TYPE => 'TOO_MANY_DIMENSIONS_OF_SAME_TYPE',
        self::IN_USE => 'IN_USE',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AudienceError::class, \Google\Ads\GoogleAds\V11\Errors\AudienceErrorEnum_AudienceError::class);


text:
#include "DumpHandler.h"

#pragma warning(disable : 4091)
#include <DbgHelp.h>
#pragma warning(default : 4091)

namespace dump
{

DumpHandler::DumpHandler( void )
{
    memset( &_ExceptionInfo, 0x00, sizeof( _ExceptionInfo ) );

    // Create new thread to ensure dump creation in case of stack overflow exception
    _hWatchThd = CreateThread( NULL, 0, &DumpHandler::WatchdogProc, this, 0, NULL );
}

DumpHandler::~DumpHandler( void )
{
    DisableWatchdog();

    _active = false;
    if (_hWatchThd)
    {
        WaitForSingleObject( _hWatchThd, INFINITE );
        _hWatchThd = NULL;
    }
}

/// <summary>
/// Get singleton instance
/// </summary>
/// <returns>Instance</returns>
DumpHandler& DumpHandler::Instance()
{
    static DumpHandler instance;
    return instance;
}

/// <summary>
/// Setup unhanded exception filter
/// </summary>
/// <param name="dumpRoot">Crash dump root dolder</param>
/// <param name="flags">Dump flags</param>
/// <param name="pDump">User crash callback routine</param>
/// <param name="pFilter">Unused</param>
/// <param name="pContext">User context to pass into crash callback</param>
/// <returns>true on success, false if already installed</returns>
bool DumpHandler::CreateWatchdog(
    const std::wstring& dumpRoot,
    eDumpFlags flags,
    fnCallback pDump /*= nullptr*/,
    fnCallback pFilter /*= nullptr*/,
    void* pContext /*= nullptr*/
    )
{
    // Prevent multiple assignment
    if (_pPrevFilter == nullptr)
    {
        _flags = flags;
        _pUserContext = pContext;
        _dumpRoot = dumpRoot;
        _pDumpProc = pDump;

        _pPrevFilter = SetUnhandledExceptionFilter( &DumpHandler::UnhandledExceptionFilter );

        return true;
    }

    return false;
}

/// <summary>
/// Remove unhanded exception filter
/// </summary>
void DumpHandler::DisableWatchdog()
{
    if (_pPrevFilter)
    {
        SetUnhandledExceptionFilter( (LPTOP_LEVEL_EXCEPTION_FILTER)_pPrevFilter );
        _pPrevFilter = nullptr;
    }
}

/// <summary>
/// Unhanded exception filter
/// </summary>
/// <param name="ExceptionInfo">Exception information</param>
/// <returns>Exception handling status</returns>
LONG CALLBACK DumpHandler::UnhandledExceptionFilter( PEXCEPTION_POINTERS ExceptionInfo )
{
    auto& inst = Instance();

    inst._ExceptionInfo = ExceptionInfo;
    inst._FailedThread = GetCurrentThreadId();

    if (Instance()._hWatchThd == NULL)
        ExitProcess( 0x1338 );

    // Wait for dump generation reasonable amount of time (3 min)
    WaitForSingleObject( inst._hWatchThd, 3 * 60 * 1000 );

    return EXCEPTION_CONTINUE_SEARCH;
}

/// <summary>
/// Crash watcher
/// </summary>
/// <param name="lpParam">DumpHandler pointer</param>
/// <returns>Error code</returns>
DWORD CALLBACK DumpHandler::WatchdogProc( LPVOID lpParam )
{
    DumpHandler* pClass = reinterpret_cast<DumpHandler*>(lpParam);

    // Wait for crashed thread id
    while (pClass && pClass->_FailedThread == 0)
    {
        if (pClass->_active)
            Sleep( 5 );
        else
            return ERROR_SUCCESS;
    }

    if (pClass)
        pClass->ExceptionHandler();

    return ERROR_SUCCESS;
}

/// <summary>
/// Actual exception handler
/// </summary>
void DumpHandler::ExceptionHandler()
{
    std::wstring strFullDump, strMiniDump;

    int dumpFlags = MiniDumpWithIndirectlyReferencedMemory |
                    MiniDumpWithDataSegs |
                    MiniDumpWithHandleData |
                    MiniDumpWithFullMemory;

    GenDumpFilenames( strFullDump, strMiniDump );

    // Create full memory dump
    if (_flags & CreateFullDump)
        CreateDump( strFullDump, dumpFlags );

    // Create mini dump
    if (_flags & CreateMinidump)
        CreateDump( strMiniDump, MiniDumpNormal );

    // Call user routine
    if (_pDumpProc)
        _pDumpProc( strFullDump.c_str(), _pUserContext, _ExceptionInfo, true );

    // Prevent dtor deadlock
    _hWatchThd = NULL;
    ExitProcess( 0x1337 );
}

/// <summary>
/// Write crash dump
/// </summary>
/// <param name="strFilePath">Output file</param>
/// <param name="flags">flags</param>
void DumpHandler::CreateDump( const std::wstring& strFilePath, int flags )
{
    MINIDUMP_EXCEPTION_INFORMATION aMiniDumpInfo = { 0 };

    HANDLE hFile = CreateFile( strFilePath.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );

    aMiniDumpInfo.ThreadId = _FailedThread;
    aMiniDumpInfo.ExceptionPointers = _ExceptionInfo;
    aMiniDumpInfo.ClientPointers = TRUE;

    if (hFile != INVALID_HANDLE_VALUE)
    {
        MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)flags, &aMiniDumpInfo, NULL, NULL );

        FlushFileBuffers( hFile );
        CloseHandle( hFile );
    }
}

/// <summary>
/// Generate crash dump file names
/// </summary>
/// <param name="strFullDump">Full dump name</param>
/// <param name="strMiniDump">Mini dump name</param>
/// <returns>true on success</returns>
bool DumpHandler::GenDumpFilenames( std::wstring& strFullDump, std::wstring& strMiniDump )
{
    wchar_t tFullName[MAX_PATH] = { 0 };
    wchar_t tMiniName[MAX_PATH] = { 0 };
    wchar_t tImageName[MAX_PATH] = { 0 };

    SYSTEMTIME time = { 0 };

    // Current time
    GetLocalTime( &time );

    // Image name
    GetModuleFileName( NULL, tImageName, ARRAYSIZE( tImageName ) );
    std::wstring modulename( tImageName );
    modulename = modulename.substr( modulename.rfind( L"\\" ) + 1 );

    // File name based on current time
    swprintf_s( tFullName, sizeof( tFullName ) / sizeof( wchar_t ), L"%s\\%s_%d.%.2d.%.2d.%.2d.%.2d.%.2d.dmp",
                _dumpRoot.c_str(), modulename.c_str(), time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond );

    swprintf_s( tMiniName, sizeof( tFullName ) / sizeof( wchar_t ), L"%s\\%s_%d.%.2d.%.2d.%.2d.%.2d.%.2d.mdmp",
                _dumpRoot.c_str(), modulename.c_str(), time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond );

    strFullDump = tFullName;
    strMiniDump = tMiniName;

    return true;
}
}

redpajama_set_name: RedPajamaGithub


text:
rem ##################################
rem ### 1. Options for all batches ###
rem ##################################

rem Note:
rem 1. Any options can be moved down to the per batch section
rem 2. These "BATCH" options override any settings in configlocal.cmd

rem If you want to override configlocal.cmd/version.cmd
rem -------------------------------------------------
rem set EXO_BATCH_MAJOR_VER=
rem set EXO_BATCH_MINOR_VER=
rem set EXO_BATCH_MICRO_VER=
rem set EXO_BATCH_BUILD_VER=

rem Usually set per batch in section 4.x below
rem ------------------------------------------
rem set BATCH_TARGET_CPU=
rem set BATCH_CONFIGURATION=

rem Commonly only one toolset etc installed so best defined in
rem configlocal.cmd but can be defined here per batch if multiple
rem tools etc are available
rem -------------------------------------------------------------
rem set EXO_BATCH_TOOLSET=
rem set EXO_BATCH_POSTGRES_VER=
rem set EXO_BATCH_BOOST_VER=
rem set EXO_BATCH_BOOSTPRO=
rem set EXO_BATCH_BUILD_ROOT=
rem set EXO_BATCH_PROGRAMFILES_ROOT=

rem ##########################################
rem ### 2. Change the default batch stages ###
rem ##########################################
rem *=default, un-remark the alternative if desired

rem set EXO_BATCH_CLEAN=NO*
rem set EXO_BATCH_CLEAN=YES

rem set EXO_BATCH_MAKE=YES*
rem set EXO_BATCH_MAKE=NO

rem set EXO_BATCH_PACK=YES*
rem set EXO_BATCH_PACK=NO

rem set EXO_BATCH_UPLOAD=NO*
rem set EXO_BATCH_UPLOAD=YES

rem ################################
rem ### 3. Standard Preparation ####
rem ################################

rem ----------------------------
rem --- clean the batch logs ---
rem ----------------------------
    if exist batch.log del batch.log
    if exist batch.err del batch.err

rem ######################
rem #### 4.x Do a batch ##
rem ######################

    set BATCH_TARGET_CPU=x64
    set BATCH_CONFIGURATION=Release
    call batchone

rem ######################
rem #### 4.x Do a batch ##
rem ######################

    set BATCH_TARGET_CPU=x86
    set BATCH_CONFIGURATION=Release
    call batchone

rem ##########################################
rem #### 5. Store and/or email the results ###
rem ##########################################
pause


text:
#ifdef __GNUC__
#define FATAL __attribute__((noreturn))
#else
#define FATAL
#endif

typedef uint8_t byte;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef long long vlong;
typedef unsigned long long uvlong;

typedef struct Htab Htab;
typedef struct Bitset Bitset;
typedef struct Optctx Optctx;
typedef struct Str Str;
typedef struct Strbuf Strbuf;

struct Htab {
	size_t nelt;
	size_t ndead;
	size_t sz;
	ulong (*hash)(void *k);
	int (*cmp)(void *a, void *b);
	void **keys;
	void **vals;
	ulong *hashes;
	char *dead;
};

struct Bitset {
	size_t nchunks;
	size_t *chunks;
};

struct Optctx {
	/* public exports */
	char *optarg;
	char **args;
	size_t nargs;

	/* internal state */
	char *optstr;
	char **optargs;
	size_t noptargs;
	size_t argidx;
	int optdone; /* seen -- */
	int finished;
	char *curarg;
};

struct Str {
	size_t len;
	char *buf;
};

struct Strbuf {
	char *buf;
	size_t sz;
	size_t len;
};

/* string buffer */
Strbuf *mksb();
char *sbfin(Strbuf *sb);
void sbputs(Strbuf *sb, char *s);
void sbputb(Strbuf *sb, char b);

/* bit sets */
ulong bshash(Bitset *bs);
Bitset *mkbs(void);
void bsfree(Bitset *bs);
Bitset *bsdup(Bitset *bs);
Bitset *bsclear(Bitset *bs);
void delbs(Bitset *bs);
void bsput(Bitset *bs, size_t elt);
void bsdel(Bitset *bs, size_t elt);
void bsunion(Bitset *a, Bitset *b);
void bsintersect(Bitset *a, Bitset *b);
void bsdiff(Bitset *a, Bitset *b);
int bseq(Bitset *a, Bitset *b);
int bsissubset(Bitset *set, Bitset *sub);
int bsisempty(Bitset *set);
int bsiter(Bitset *bs, size_t *elt);
size_t bsmax(Bitset *bs);
size_t bscount(Bitset *bs);

/* inline for speed */
static inline int bshas(Bitset *bs, size_t elt)
{
	size_t eltidx, eltshift;

	if (elt >= bs->nchunks * 8 * sizeof(size_t))
		return 0;
	eltidx = elt / (8 * sizeof(size_t));
	eltshift = elt % (8 * sizeof(size_t));
	return (bs->chunks[eltidx] & (1ULL << eltshift)) != 0;
}

/* hash tables */
Htab *mkht(ulong (*hash)(void *key), int (*cmp)(void *k1, void *k2));
void htfree(Htab *ht);
int htput(Htab *ht, void *k, void *v);
void htdel(Htab *ht, void *k);
void *htget(Htab *ht, void *k);
int hthas(Htab *ht, void *k);
void **htkeys(Htab *ht, size_t *nkeys);
ulong strhash(void *key);
int streq(void *a, void *b);
ulong strlithash(void *key);
int strliteq(void *a, void *b);
ulong ptrhash(void *key);
int ptreq(void *a, void *b);
ulong inthash(uint64_t key);
int inteq(uint64_t a, uint64_t b);
ulong murmurhash2(void *buf, size_t sz);

/* util functions */
void *zalloc(size_t size);
void *xalloc(size_t size);
void *zrealloc(void *p, size_t oldsz, size_t size);
void *xrealloc(void *p, size_t size);
void die(char *msg, ...) FATAL;
char *strdupn(char *s, size_t len);
char *xstrdup(char *s);
char *strjoin(char *u, char *v);
void *memdup(void *mem, size_t len);
size_t bprintf(char *buf, size_t len, char *fmt, ...);

/* indented printf */
void indentf(int depth, char *fmt, ...);
void findentf(FILE *fd, int depth, char *fmt, ...);
void vfindentf(FILE *fd, int depth, char *fmt, va_list ap);

/* serializing/unserializing */
void be64(vlong v, byte buf[8]);
vlong host64(byte buf[8]);
void be32(long v, byte buf[4]);
long host32(byte buf[4]);
static inline intptr_t ptoi(void *p) { return (intptr_t)p; }
static inline void *itop(intptr_t i) { return (void *)i; }

void wrbuf(FILE *fd, void *buf, size_t sz);
void rdbuf(FILE *fd, void *buf, size_t sz);
char rdbyte(FILE *fd);
void wrbyte(FILE *fd, char val);
char rdbyte(FILE *fd);
void wrint(FILE *fd, long val);
long rdint(FILE *fd);
void wrstr(FILE *fd, char *val);
char *rdstr(FILE *fd);
void wrlenstr(FILE *fd, Str str);
void rdlenstr(FILE *fd, Str *str);
void wrflt(FILE *fd, double val);
double rdflt(FILE *fd);
void wrbool(FILE *fd, int val);
int rdbool(FILE *fd);

size_t max(size_t a, size_t b);
size_t min(size_t a, size_t b);
size_t align(size_t sz, size_t a);

/* list funcs */
/* hack; nl is void* b/c void*** is incompatible with T*** */
void lappend( void *l, size_t *len, void *n);
void lcat(void *dst, size_t *ndst, void *src, size_t nsrc);
void linsert(void *l, size_t *len, size_t idx, void *n);
void *lpop(void *l, size_t *len);
void ldel(void *l, size_t *len, size_t idx);
void lfree(void *l, size_t *len);

/* suffix replacement */
char *swapsuffix(char *buf, size_t sz, char *s, char *suf, char *swap);


text:
<?xml version="1.0" encoding="UTF-8"?>
<jboss xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:jee="http://java.sun.com/xml/ns/javaee"
	xmlns:mdb="urn:resource-adapter-binding" xmlns:security="urn:security">

	<jee:assembly-descriptor>
		<mdb:resource-adapter-binding>
			<jee:ejb-name>FSWatcherMDB</jee:ejb-name>
			<mdb:resource-adapter-name>test.ear#fswatcher.rar</mdb:resource-adapter-name>
		</mdb:resource-adapter-binding>
	</jee:assembly-descriptor>
</jboss>


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cencode.h"

void b64enc(char **enc, char *str)
{
	size_t length = strlen(str);
        /*
         * BASE64 needs 4 * ceil(n / 3) bytes, including padding
         * rather than linking in the math library or trying to
         * implement a celing function, just pessimistically round
         * up by 3
         * and add 1 for the NULL terminator
         */
        size_t enc_length = ((4 * length) / 3) + 3 + 1;
	char *encstring = malloc(enc_length);
        if (!encstring)
        {
                // TODO handle error
                return;
        }
        memset(encstring, 0, enc_length);

	base64_encodestate state;
	base64_init_encodestate(&state);
	length = base64_encode_block(str, length, encstring, &state);
	base64_encode_blockend(encstring + length, &state);
	*enc = encstring;
}


text:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from. models import BiblioUser
from django.utils.translation import ugettext_lazy as _

class BiblioUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('Additional_Info'), {'fields': ('avatar', 'phone')})
    )

admin.site.register(BiblioUser, BiblioUserAdmin)


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

namespace Groups.Derived
{
    internal class ProductGroupElement : GroupElement<(GroupElement g1, GroupElement g2)>
    {
        public override GroupElement Identity => new ProductGroupElement((g1.Identity, g2.Identity));

        private GroupElement g1;
        private GroupElement g2;

        public ProductGroupElement((GroupElement g1, GroupElement g2) val) : base(val)
        {
            g1 = val.g1;
            g2 = val.g2;
        }

        protected override int ComputeOrder()
        {
            return Arithmetic.Lcm(g1.Order, g2.Order);
        }

        public override bool Equals(object obj)
        {
            if (obj is ProductGroupElement g)
            {
                return g1.Equals(g.g1) && g2.Equals(g.g2);
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            return g1.GetHashCode() + g2.GetHashCode();
        }

        public override GroupElement Invert()
        {
            return new ProductGroupElement((g1.Invert(), g2.Invert()));
        }

        protected override GroupElement Multiply(GroupElement h)
        {
            if (h is null)
            {
                throw new ArgumentNullException(nameof(h));
            }
            else if (h is ProductGroupElement hp)
            {
                return new ProductGroupElement((g1 * hp.g1, g2 * hp.g2));
            }
            else
            {
                throw new ArgumentException(nameof(h), Error_ParentGroupsIncompatible);
            }
        }
    }
}


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \file DTK_MeshContainer.cpp
 * \author Stuart R. Slattery
 * \brief Mesh container explicit template instantiations.
 */
//---------------------------------------------------------------------------//

#include "DTK_MeshContainer.hpp"

namespace DataTransferKit
{

template class MeshContainer<char>;

template class MeshContainer<unsigned short int>;
template class MeshContainer<short int>;

template class MeshContainer<unsigned int>;
template class MeshContainer<int>;

template class MeshContainer<long unsigned int>;
template class MeshContainer<long int>;

template class MeshContainer<long long unsigned int>;
template class MeshContainer<long long int>;

} // end namespace DataTransferKit

//---------------------------------------------------------------------------//
// end DTK_MeshContainer.cpp
//---------------------------------------------------------------------------//


text:
/**
 * FreeIMU calibration header. Automatically generated by FreeIMU_GUI.
 * Do not edit manually unless you know what you are doing.
*/

#define CALIBRATION_H

const int acc_off_x = -13;
const int acc_off_y = -7;
const int acc_off_z = -14;
const float acc_scale_x = 252.551548;
const float acc_scale_y = 260.244190;
const float acc_scale_z = 250.523972;

const int magn_off_x = 8;
const int magn_off_y = -85;
const int magn_off_z = 38;
const float magn_scale_x = 525.072503;
const float magn_scale_y = 492.829055;
const float magn_scale_z = 489.613078;


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/miCompose"
        android:icon="@drawable/ic_action_compose"
        android:showAsAction="ifRoom"
        android:onClick="onCompose"
        android:title="@string/compose_title">
    </item>

    <item
        android:id="@+id/miProfile"
        android:icon="@drawable/ic_action_profile"
        android:showAsAction="ifRoom"
        android:onClick="onProfileView"
        android:title="@string/profile_title">
    </item>
</menu>


text:
package org.wso2.carbon.registry.rest.api.exception;

public class RestApiBasicAuthenticationException extends Exception {

    public RestApiBasicAuthenticationException()
    {
    }

    public RestApiBasicAuthenticationException(String message)
    {
        super(message);
    }

    public RestApiBasicAuthenticationException(Throwable cause)
    {
        super(cause);
    }

    public RestApiBasicAuthenticationException(String message, Throwable cause)
    {
        super(message, cause);
    }
}


text:
package swatches

import (
	"github.com/corestoreio/pkg/config/element"
	"github.com/corestoreio/pkg/store/scope"
)

// ConfigStructure global configuration structure for this package.
// Used in frontend and backend. See init() for details.
var ConfigStructure element.Sections

func init() {
	ConfigStructure = element.MustMakeSectionsValidate(
		element.Section{
			ID:        "catalog",
			SortOrder: 40,
			Scopes:    scope.PermStore,
			Groups: element.MakeGroups(
				element.Group{
					ID:        "frontend",
					SortOrder: 100,
					Scopes:    scope.PermStore,
					Fields: element.MakeFields(
						element.Field{
							// Path: catalog/frontend/swatches_per_product
							ID:        "swatches_per_product",
							Label:     `Swatches per Product`,
							Type:      element.TypeText,
							SortOrder: 300,
							Visible:   element.VisibleYes,
							Scopes:    scope.PermStore,
							Default:   16,
						},
					),
				},
			),
		},

		// Hidden Configuration, may be visible somewhere else ...
		element.Section{
			ID: "general",
			Groups: element.MakeGroups(
				element.Group{
					ID: "validator_data",
					Fields: element.MakeFields(
						element.Field{
							// Path: general/validator_data/input_types
							ID:      `input_types`,
							Type:    element.TypeHidden,
							Visible: element.VisibleNo,
							Default: `{"swatch_visual":"swatch_visual","swatch_text":"swatch_text"}`,
						},
					),
				},
			),
		},
	)
	Backend = NewBackend(ConfigStructure)
}


text:
var fs = require('fs');
var selectors;

function writeIconCSS() {
        fs.appendFile('config/custom.css', selectors);
}

exports.commands = {
        seticon: function (target, room, user) {
        if (!this.can('eval')) return this.errorReply("Access denied.");

                var args = target.split(',');
                if (args.length < 3) return this.parse('/help seticon');
                var username = toId(args.shift());
                var image = 'background: rgba(244, 244, 244, 0.8) url("' + args.shift().trim() + '") right no-repeat;';
                selectors = '\n\n' + '  #' + toId(args.shift()) + '-userlist-user-' + username;
                args.forEach(function (room) {
                        selectors += ', #' + toId(room) + '-userlist-user-' + username;
                });
                selectors += ' { \n' + '    ' + image +  '\n  }';

                this.privateModCommand("(" + user.name + " has set an icon to " + username + ")");
                writeIconCSS();
        },
        seticonhelp: ["/seticon [username], [image], [room 1], [room 2], etc. - Sets an icon to a user in chosen rooms. Credits goes to Master Float in this."]
};


text:
require 'test_helper'
require File.join File.dirname(__FILE__), '..', '..', 'lib', 'docomo_css', 'filter'

class DocomoCss::FilterTest < Test::Unit::TestCase
  def setup
    @filter = DocomoCss::Filter.new
  end

  def test_invalid_response_content_type
    response = mock("invalid_response") do
      expects(:content_type).returns('text/html').once
      expects(:body).never
    end
    controller = stub("invalid_controller", :response => response)
    @filter.after(controller)
  end

  def test_escape_numeric_character_reference
    assert_equal "HTMLCSSINLINERESCAPE123456789::::::::", @filter.escape_numeric_character_reference("&#123456789;")
    assert_equal "HTMLCSSINLINERESCAPEx123def::::::::", @filter.escape_numeric_character_reference("�")
  end

  def test_unescape_numeric_character_reference
    assert_equal "&#123456789;", @filter.unescape_numeric_character_reference("HTMLCSSINLINERESCAPE123456789::::::::")
    assert_equal "�", @filter.unescape_numeric_character_reference("HTMLCSSINLINERESCAPEx123def::::::::")
  end

  def test_pseudo_selectors
    css = TinyCss.new.read_string(<<-CSS)
a:visited { color: FF00FF; }
    CSS
    assert_equal ["a:visited"], @filter.pseudo_selectors(css)

    css = TinyCss.new.read_string(<<-CSS)
.purple { color: FF00FF; }
    CSS
    assert_equal [], @filter.pseudo_selectors(css)
  end

  def test_stylesheet_link_node
    doc = Nokogiri::HTML(<<-HTML)
<link href="a.css"/>
<link href="b.css" rel="stylesheet"/>
    HTML

    @filter.stylesheet_link_node(doc).each do |node|
      assert_equal 'b.css', node['href']
    end
  end

  def test_extract_pseudo_style
    css = TinyCss.new.read_string <<-CSS
a:link    { color: red; }
a:focus   { color: green; }
a:visited { color: blue; }
div.title { background-color: #999 }
    CSS

    pseudo_style = @filter.extract_pseudo_style css
    assert_equal('red', pseudo_style.style['a:link']['color'])
    assert_equal('green', pseudo_style.style['a:focus']['color'])
    assert_equal('blue', pseudo_style.style['a:visited']['color'])
    assert_equal('#999', css.style['div.title']['background-color'])
  end

  def test_embed_pseudo_style
    css = TinyCss.new
    assert_equal nil, @filter.embed_pseudo_style(nil, css)

    css = TinyCss.new.read_string <<-CSS
a:link    { color: red; }
a:focus   { color: green; }
a:visited { color: blue; }
    CSS

    doc = Nokogiri::HTML <<-HTML

    HTML
    doc = @filter.embed_pseudo_style doc, css
    assert_match %r'


text:
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  filter_parameter_logging :password, :password_confirmation
end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class TextStyle</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />

 TextStyle

Description

					Description |
															Methods (details)

The TextStyle defines the color, size and font name of a text element.

			Located in /googlecharttools/view/options/TextStyle.class.php (line 36)

OptionStorage
   |
   --TextStyle

Method Summary

			Description |
												Methods (details)

											TextStyle
										__construct
											([string $color = null], [string $fontName = null], [int $fontSize = null])

											void
										setColor
											(string $color)

											void
										setFontName
											(int $name)

											void
										setFontSize
											(int $size)

Methods

			Description |
																Methods (details)

		Constructor __construct (line 49)

Creates a new TextStyle option-set.

access: public

		TextStyle

			__construct

					([string $color = null], [string $fontName = null], [int $fontSize = null])

				string
				$color: The text-color. Any valid HTML/CSS color definition               (e. g. "white", #FFF, #123456).

				string
				$fontName: The font type's name.

				int
				$fontSize: The font size in pixels.

		setColor (line 64)

Sets the font's color.

Any valid HTML/CSS color definition can be used (e. g. "white", #FFF, #123456).

access: public

		void

			setColor

					(string $color)

				string
				$color: HTML color string. If set to null, the default color               assigned to the outer element will be used.

		setFontName (line 75)

Sets the font-type.

access: public

		void

			setFontName

					(int $name)

				int
				$name: The font type's name. If set to null, the default font               assigned to the outer element will be used.

		setFontSize (line 86)

Sets the font's size.

access: public

		void

			setFontSize

					(int $size)

				int
				$size: The font size in pixels. If set to null, the default size               assigned to the outer element will be used.

Inherited Methods

Inherited From OptionStorage

							OptionStorage::encodeOptions()

							OptionStorage::getOption()

							OptionStorage::setOption()

							OptionStorage::setOptionArray()

							OptionStorage::setOptionBoolean()

							OptionStorage::setOptionNumeric()

		Documentation generated on Mon, 01 Oct 2012 16:45:07 +0200 by phpDocumentor 1.4.4


text:
package org.hisp.dhis.android.core.trackedentity.internal;

import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter;
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.NameableWithStyleStatementBinder;
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementBinder;
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementWrapper;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.db.stores.internal.StoreFactory;
import org.hisp.dhis.android.core.arch.helpers.UidsHelper;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeTableInfo;

import androidx.annotation.NonNull;

public final class TrackedEntityAttributeStore {

    private TrackedEntityAttributeStore() {}

    private static StatementBinder<TrackedEntityAttribute> BINDER =
            new NameableWithStyleStatementBinder<TrackedEntityAttribute>() {

        @Override
        public void bindToStatement(@NonNull TrackedEntityAttribute o, @NonNull StatementWrapper w) {
            super.bindToStatement(o, w);
            w.bind(13, o.pattern());
            w.bind(14, o.sortOrderInListNoProgram());
            w.bind(15, UidsHelper.getUidOrNull(o.optionSet()));
            w.bind(16, o.valueType());
            w.bind(17, o.expression());
            w.bind(18, o.programScope());
            w.bind(19, o.displayInListNoProgram());
            w.bind(20, o.generated());
            w.bind(21, o.displayOnVisitSchedule());
            w.bind(22, o.orgUnitScope());
            w.bind(23, o.unique());
            w.bind(24, o.inherit());
            w.bind(25, o.formName());
            w.bind(26, o.displayFormName());
            w.bind(27, o.fieldMask());
            w.bind(28, o.aggregationType());
        }
    };

    public static IdentifiableObjectStore<TrackedEntityAttribute> create(DatabaseAdapter databaseAdapter) {
        return StoreFactory.objectWithUidStore(databaseAdapter,
                TrackedEntityAttributeTableInfo.TABLE_INFO, BINDER, TrackedEntityAttribute::create);
    }
}


text:
This is a Facebook Messenger chatbot intended for group chats that supports creating small, impromptu events. Once an event is created with EventNotify, the participants will receive reminders through Messenger private messages. The bot supports Natural Language Processing through Wit.ai, so you can talk to it in plain English. See usage examples below!

## Usage

To use this bot with your Messenger group, you must add the bot's Facebook profile as a friend: <https://www.facebook.com/eventnotify>
Then simply add the bot to your group chat. To ensure your friends get event notifications properly, they should add the bot as a friend as well.

To invoke the bot, use the prefix "EventNotify" followed by your event and participants. If no participants are specified, all members of the group chat will be auto-added.
Examples:
```
"EventNotify Invite @aakash @sai to hackathon Sunday 7pm at my place"
"EventNotify Basketball in Warren at 8 pm"
```

Just say ```EventNotify``` to the bot to see your current group events and ```EventNotify help``` for further assistance.

## Installation for Development

To configure EventNotify for development, clone this repository and install the required npm packages with ```npm install```.

You then need to create a ```credentials.json``` file in the ```eventnotify``` folder. See the ```eventnotify/sample-credentials.json``` file for a template. This file includes the login for your target Facebook account and the Wit.ai server token you can get from your Wit account.

You need PostgreSQL installed locally to run the database in your development environment. If you are on UNIX, you can run the ```mac-install.sh``` shell script to install and configure PostgreSQL. You must now change the name in ```postgres/pgquery.js``` to your name in your Postgres settings.

Now code away (start at ```eventnotify/launch.js```), pull requests are welcomed! If you have any questions or comments you can contact chatboteventnotify@gmail.com.

## Built With

 * Node.js
 * Postgres
 * [Facebook Chat API by Schmavery](https://github.com/Schmavery/facebook-chat-api)
 * Wit.ai

## Contributors
Made at UCSD with ❤

Contributors alphabetically:

 * Sai Annam
 * Tejas Badadare
 * Pramukh Govindaraju
 * Aakash Kesavarapu
 * Archit Mishra
 * Chirag Toprani


text:
package org.apache.kerby.kerberos.kerb.client.request;

import org.apache.kerby.kerberos.kerb.KrbErrorCode;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.PkinitOption;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.common.KrbUtil;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.HostAddress;
import org.apache.kerby.kerberos.kerb.type.base.HostAddresses;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.kdc.AsReq;
import org.apache.kerby.kerberos.kerb.type.kdc.EncAsRepPart;
import org.apache.kerby.kerberos.kerb.type.kdc.EncKdcRepPart;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;

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

public class AsRequest extends KdcRequest {

    private PrincipalName clientPrincipal;
    private EncryptionKey clientKey;

    public AsRequest(KrbContext context) {
        super(context);

        setServerPrincipal(makeTgsPrincipal());
    }

    public PrincipalName getClientPrincipal() {
        return clientPrincipal;
    }

    public void setClientPrincipal(PrincipalName clientPrincipal) {
        this.clientPrincipal = clientPrincipal;
    }

    public void setClientKey(EncryptionKey clientKey) {
        this.clientKey = clientKey;
    }

    @Override
    public EncryptionKey getClientKey() throws KrbException {
        return clientKey;
    }

    @Override
    public void process() throws KrbException {
        super.process();

        KdcReqBody body = getReqBody();

        AsReq asReq = new AsReq();
        asReq.setReqBody(body);
        asReq.setPaData(getPreauthContext().getOutputPaData());

        setKdcReq(asReq);
    }

    @Override
    public void processResponse(KdcRep kdcRep) throws KrbException  {
        setKdcRep(kdcRep);

        PrincipalName clientPrincipal = getKdcRep().getCname();
        String clientRealm = getKdcRep().getCrealm();
        clientPrincipal.setRealm(clientRealm);

        if (!(getRequestOptions().contains(PkinitOption.USE_ANONYMOUS)
                && KrbUtil.pricipalCompareIgnoreRealm(clientPrincipal, getClientPrincipal()))
                && !getRequestOptions().contains(TokenOption.USER_ID_TOKEN)
                && !clientPrincipal.equals(getClientPrincipal())) {
            throw new KrbException(KrbErrorCode.KDC_ERR_CLIENT_NAME_MISMATCH);
        }

        byte[] decryptedData = decryptWithClientKey(getKdcRep().getEncryptedEncPart(),
                KeyUsage.AS_REP_ENCPART);
        if ((decryptedData[0] & 0x1f) == 26) {
            decryptedData[0] = (byte) (decryptedData[0] - 1);
        }
        EncKdcRepPart encKdcRepPart = new EncAsRepPart();
        try {
            encKdcRepPart.decode(decryptedData);
        } catch (IOException e) {
            throw new KrbException("Failed to decode EncAsRepPart", e);
        }
        getKdcRep().setEncPart(encKdcRepPart);

        if (getChosenNonce() != encKdcRepPart.getNonce()) {
            throw new KrbException("Nonce didn't match");
        }

        PrincipalName returnedServerPrincipal = encKdcRepPart.getSname();
        returnedServerPrincipal.setRealm(encKdcRepPart.getSrealm());
        PrincipalName requestedServerPrincipal = getServerPrincipal();
        if (requestedServerPrincipal.getRealm() == null) {
            requestedServerPrincipal.setRealm(getContext().getKrbSetting().getKdcRealm());
        }
        if (!returnedServerPrincipal.equals(requestedServerPrincipal)) {
            throw new KrbException(KrbErrorCode.KDC_ERR_SERVER_NOMATCH);
        }

        HostAddresses hostAddresses = getHostAddresses();
        if (hostAddresses != null) {
            List<HostAddress> requestHosts = hostAddresses.getElements();
            if (!requestHosts.isEmpty()) {
                List<HostAddress> responseHosts = encKdcRepPart.getCaddr().getElements();
                for (HostAddress h : requestHosts) {
                    if (!responseHosts.contains(h)) {
                        throw new KrbException("Unexpected client host");
                    }
                }
            }
        }
    }

    public TgtTicket getTicket() {
        TgtTicket tgtTicket = new TgtTicket(getKdcRep().getTicket(),
                (EncAsRepPart) getKdcRep().getEncPart(), getKdcRep().getCname());
        return tgtTicket;
    }

    private PrincipalName makeTgsPrincipal() {
        return KrbUtil.makeTgsPrincipal(getContext().getKrbSetting().getKdcRealm());
    }

    protected CredentialCache resolveCredCache(File ccacheFile) throws IOException {
        CredentialCache cc = new CredentialCache();
        cc.load(ccacheFile);

        return cc;
    }

}


text:
/** @file

    @brief

(c) 2016, stefan.berke@modular-audio-graphics.com

All rights reserved

created 1/12/2016

*/

#ifndef GENERATE_INPUT_H
#define GENERATE_INPUT_H

#include <cassert>
#include <vector>
#include "mnn/function.h"

template <typename Float>
class GenerateInput
{
public:

    GenerateInput(Float rndMin, Float rndMax)
        : error_    (-1.)
        , rndMin_   (rndMin)
        , rndMax_   (rndMax)
    { }

    const Float* input() const { return &inputBest_[0]; }
    const Float* output() const { return &outputBest_[0]; }
    Float error() const { return error_; }
    Float errorWorst() const { return errorWorst_; }

    void setExpectedOutput(const Float* v, size_t num);

    void initializeInput();
    void mutateInput();

    template <class Net>
    void approximateInput(Net& net, size_t numSteps);

    /** Find input that minimizes cd error */
    template <class Rbm>
    void approximateInputRbm(Rbm& net, size_t numSteps, size_t cdSteps);

    std::vector<Float>
        input_, inputBest_,
        output_, outputBest_, outputExpect_;
    Float error_, errorWorst_,
        rndMin_, rndMax_;
};

template <typename Float>
void GenerateInput<Float>::setExpectedOutput(const Float *v, size_t num)
{
    output_.resize(num);
    outputExpect_.resize(num);
    outputBest_.resize(num);
    for (auto& o : outputExpect_)
        o = *v++;
}

template <typename Float>
void GenerateInput<Float>::initializeInput()
{
    for (auto& v : input_)
        v = MNN::rnd(rndMin_, rndMax_);
    error_ = -1.;
}

template <typename Float>
void GenerateInput<Float>::mutateInput()
{
    for (auto& i : input_)
        if (MNN::rnd(0., 1.) < 0.3)
            i = std::max(-1., std::min(1.,
                    i + MNN::rnd(-1., 1.) * MNN::rnd(0., .002)
                                     ));
}

template <typename Float>
template <class Net>
void GenerateInput<Float>::approximateInput(Net& net, size_t numSteps)
{
    // resize/reinit if necessary
    if (input_.size() != net.numIn())
    {
        input_.resize(net.numIn());
        inputBest_.resize(input_.size());
        initializeInput();
    }

    assert(output_.size() == net.numOut() && outputExpect_.size() == net.numOut() );

    errorWorst_ = 0.;

    for (size_t step = 0; step < numSteps; ++step)
    {
        net.fprop(&input_[0], &output_[0]);

        // get error
        Float e = 0.;
        for (size_t i = 0; i < output_.size(); ++i)
            e += std::abs(outputExpect_[i] - output_[i]);
        e = e / output_.size() * 100.;

        errorWorst_ = std::max(errorWorst_, e);

        // made progress?
        if (error_ < 0. || e < error_)
        {
            error_ = e;
            inputBest_ = input_;
            outputBest_ = output_;
        }
        // otherwise reverse mutation
        else
            input_ = inputBest_;

        mutateInput();
    }
}

template <typename Float>
template <class Rbm>
void GenerateInput<Float>::approximateInputRbm(Rbm& net, size_t numSteps, size_t cdSteps)
{
    // resize/reinit if necessary
    if (input_.size() != net.numIn())
    {
        input_.resize(net.numIn());
        inputBest_.resize(input_.size());
        initializeInput();
    }

    errorWorst_ = 0.;

    for (size_t step = 0; step < numSteps; ++step)
    {
        // get error
        Float e = net.cd(&input_[0], cdSteps, 0.);

        errorWorst_ = std::max(errorWorst_, e);

        // made progress?
        if (e > 0. && (error_ < 0. || e < error_))
        {
            error_ = e;
            inputBest_ = input_;
        }
        // otherwise reverse mutation
        else
            input_ = inputBest_;

        mutateInput();
    }
}

#endif // GENERATE_INPUT_H


text:
SET DIR=%~dp0
:: /MD is link against msvcrt.dll
@cl /nologo /I%DIR%..\testlib test_ctest.c
:: link /MD test_vector.obj /out:test_vector.exe


text:
/*
 *
 * SettingsPage
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { bindRoutineCreators } from 'redux-saga-routines';
import { createStructuredSelector } from 'reselect';
import Loader from 'react-loader-advanced';
import moment from 'moment';
import { groupBy, sortBy } from 'lodash';

import Alert from 'components/Alert';
import Spinner from 'components/Spinner';
import RowHeader from 'components/RowHeader';
import { togglePrinting } from 'containers/App/actions';
import { makeSelectOnboarded, makeSelectPrinting } from 'containers/App/selectors';
import { isClosedYear } from 'utils/generic-validators';
import { userContext } from 'hocs';
import { asPdfWrapper, exportToCsv } from 'utils/generic-helpers';

import { setComponent, setSelectedYear } from './actions';
import { fetchAllEmploymentData, fetchAllElementsData, submitProfile, submitElement, createEmployment, editEmployment, deleteEmployment } from './routines';
import makeSelectSettingsPage from './selectors';
import EmploymentTab from './EmploymentTab';
import ElementsTab from './ElementsTab';
import TableElements from './TableElements';
import TableEmployment from './TableEmployment';

@userContext
export class SettingsPage extends React.PureComponent {

  constructor(props) {
    super(props);

    this.renderEmploymentTab = this.renderEmploymentTab.bind(this);
    this.renderElementsTab = this.renderElementsTab.bind(this);
    this.handleOnDownloadIconClick = this.handleOnDownloadIconClick.bind(this);
  }

  componentWillMount() {
    if (this.props.printing) {
      this.props.togglePrinting();
    }

    if (this.props.Settings.component === 'employment') {
      this.props.fetchAllEmploymentData.trigger();
    } else if (this.props.Settings.component === 'elements') {
      this.props.fetchAllElementsData.trigger();
    }
  }

  componentWillReceiveProps(nextProps) {
    const thisComponent = this.props.Settings.component;
    const nextComponent = nextProps.Settings.component;
    const thisSelectedYear = this.props.Settings.selectedYear;
    const nextSelectedYear = nextProps.Settings.selectedYear;

    if (nextComponent === 'employment') {
      if (thisComponent !== 'employment' || thisSelectedYear !== nextSelectedYear) {
        this.props.fetchAllEmploymentData.trigger();
      }
    } else if (nextComponent === 'elements') {
      if (thisComponent !== 'elements' || thisSelectedYear !== nextSelectedYear) {
        this.props.fetchAllElementsData.trigger();
      }
    }
  }

  handleOnDownloadIconClick(format) {
    const prefix = this.props.Settings.component === 'employment' ? 'Anstellung' : 'Leistungselemente';
    const filename = `${prefix} ${this.props.firstName} ${this.props.lastName}`;
    const rows = [];

    if (format === 'csv') {
      const title = `${filename} / ${this.props.Settings.selectedYear}`;

      if (this.props.Settings.component === 'employment') {
        const emptyRow = [null, null, null];
        rows.push([title, null, null]);
        rows.push(emptyRow);
        rows.push(['Arbeitspensum', 'Von', 'Bis']);
        this.props.Settings.employments.forEach((employment) => {
          const hours = ((employment.scope / 100) * 8.4).toFixed(2);
          rows.push([
            `${employment.scope}% (${hours}h)`,
            moment(employment.start).format('DD.MM.YYYY'),
            employment.end ? moment(employment.end).format('DD.MM.YYYY') : 'unbefristed',
          ]);
        });

        rows.push(emptyRow);
        rows.push(['Geplante Abwesenheiten', 'Tage', 'Stunden']);
        rows.push(['Ferien', this.props.Settings.profile.plannedVacations.toFixed(2), null]);
        rows.push(['Militär und Diverses', this.props.Settings.profile.plannedMixed.toFixed(2), null]);
        rows.push(['Bewilligte Nachqual.', null, this.props.Settings.profile.plannedQuali.toFixed(2)]);
        rows.push(['Treueprämien', this.props.Settings.profile.plannedPremiums.toFixed(2), null]);

        rows.push(emptyRow);
        rows.push(['Überträge aus dem Vorjahr', 'Tage', 'Stunden']);
        rows.push(['Totale Jahresarbeitszeit letztes Jahr', null, this.props.Settings.profile.transferTotalLastYear.toFixed(2)]);
        rows.push(['Überzeit (maximum 1%)', null, this.props.Settings.profile.transferOvertime.toFixed(2)]);
        rows.push(['bewilligte Ferien', this.props.Settings.profile.transferGrantedVacations.toFixed(2), null]);
        rows.push(['bewilligte Überzeit', null, this.props.Settings.profile.transferGrantedOvertime.toFixed(2)]);
      } else {
        const emptyRow = [null, null, null, null];
        rows.push([title, null, null, null]);

        const groupedRecords = groupBy(this.props.Settings.elements.filter((e) => e.project !== 'Default'), 'project');
        Object.keys(groupedRecords).forEach((projectName) => {
          rows.push(emptyRow);
          rows.push([projectName, 'Soll [L]', 'Soll [h]', 'Ist [h]']);

          sortBy(groupedRecords[projectName], 'label').forEach((element) => {
            const targetL = element.setpoint && element.setpoint.value && element.unit === 'l' ? element.setpoint.value.toFixed(2) || '0.00' : '';
            const targetH = element.setpoint && element.setpoint.value ? (element.factor * element.setpoint.value).toFixed(2) : '';
            rows.push([
              element.label,
              targetL,
              targetH,
              element.actual,
            ]);
          });
        });
      }

      exportToCsv(filename, rows);
    } else {
      asPdfWrapper(this.props.togglePrinting, filename);
    }
  }

  renderEmploymentTab() {
    if (this.props.printing) {
      return (
        <TableEmployment
          employments={this.props.Settings.employments}
          profile={this.props.Settings.profile}
          selectedYear={this.props.Settings.selectedYear}
          firstName={this.props.firstName}
          lastName={this.props.lastName}
        />
      );
    }

    const isClosed = this.props.Settings.profile.closed || isClosedYear(this.props.Settings.selectedYear);

    return (
      <EmploymentTab
        isClosed={isClosed}
        employments={this.props.Settings.employments}
        profile={this.props.Settings.profile}
        submitProfile={this.props.submitProfile}
        renderComponent={this.props.Settings.component}
        setComponent={this.props.setComponent}
        record={this.props.Settings.record}
        createEmployment={this.props.createEmployment}
        editEmployment={this.props.editEmployment}
        deleteEmployment={this.props.deleteEmployment}
        isImpersonated={this.props.isImpersonated}
        isTeamleader={this.props.isTeamleader}
      />
    );
  }

  renderElementsTab() {
    if (this.props.printing) {
      return (
        <TableElements
          elements={this.props.Settings.elements}
          selectedYear={this.props.Settings.selectedYear}
          firstName={this.props.firstName}
          lastName={this.props.lastName}
        />
      );
    }

    const isClosed = isClosedYear(this.props.Settings.selectedYear);
    return (
      <ElementsTab
        isClosed={isClosed}
        selectedYear={this.props.Settings.selectedYear}
        elements={this.props.Settings.elements}
        submitElement={this.props.submitElement}
        isImpersonated={this.props.isImpersonated}
      />
    );
  }

  render() {
    const tabs = [
      { label: 'Anstellung', value: 'employment', handleOnActive: () => this.props.setComponent({ component: 'employment', record: {} }) },
      { label: 'Leistungselemente', value: 'elements', handleOnActive: () => this.props.setComponent({ component: 'elements', record: {} }) },
    ];

    const hasDownloadIcon = this.props.Settings.component !== 'form';

    return (
      <Loader
        show={this.props.Settings.loading}
        message={<Spinner />}
        contentBlur={0.5}
        backgroundStyle={{ backgroundColor: 'rgab(255,255,255,0.4)' }}
      >
        { <RowHeader
          title="Einstellungen"
          tabs={tabs}
          tabsValue={this.props.Settings.component}
          selectedYear={this.props.Settings.selectedYear}
          selectableYears={4}
          onYearSelect={this.props.setSelectedYear}
          hasDownloadIcon={hasDownloadIcon}
          downloadFormats={['pdf', 'csv']}
          onDownloadIconClick={this.handleOnDownloadIconClick}
        /> }
        { !this.props.onboarded &&
          <Alert
            msg="Bitte hinterlege ein Arbeitspensum in deinen Einstellungen"
            type="info"
            time={0}
          />
        }
        <div>
          { this.props.Settings.component === 'employment' ? this.renderEmploymentTab() : null }
          { this.props.Settings.component === 'form' ? this.renderEmploymentTab() : null }
          { this.props.Settings.component === 'elements' ? this.renderElementsTab() : null }
        </div>
      </Loader>
    );
  }
}

SettingsPage.defaultProps = {
  isTeamleader: false,
};

SettingsPage.propTypes = {
  // properties
  Settings: PropTypes.shape({
    component: PropTypes.oneOf(['employment', 'elements', 'form']),
    elements: PropTypes.array.isRequired,
    employments: PropTypes.array.isRequired,
    selectedYear: PropTypes.number.isRequired,
    profile: PropTypes.shape({
      plannedVacations: PropTypes.number.isRequired,
      plannedMixed: PropTypes.number.isRequired,
      plannedQuali: PropTypes.number.isRequired,
      plannedPremiums: PropTypes.number.isRequired,
      transferTotalLastYear: PropTypes.number.isRequired,
      transferOvertime: PropTypes.number.isRequired,
      transferGrantedVacations: PropTypes.number.isRequired,
      transferGrantedOvertime: PropTypes.number.isRequired,
      closed: PropTypes.bool.isRequired,
    }).isRequired,
    record: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
  }).isRequired,
  isImpersonated: PropTypes.bool,
  isTeamleader: PropTypes.bool.isRequired,
  onboarded: PropTypes.bool,
  firstName: PropTypes.string,
  lastName: PropTypes.string,
  printing: PropTypes.bool.isRequired,
  // actions
  setComponent: PropTypes.func.isRequired,
  setSelectedYear: PropTypes.func.isRequired,
  togglePrinting: PropTypes.func.isRequired,
  // routines
  fetchAllEmploymentData: PropTypes.func.isRequired,
  fetchAllElementsData: PropTypes.func.isRequired,
  submitProfile: PropTypes.func.isRequired,
  submitElement: PropTypes.func.isRequired,
  createEmployment: PropTypes.func.isRequired,
  editEmployment: PropTypes.func.isRequired,
  deleteEmployment: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  Settings: makeSelectSettingsPage(),
  onboarded: makeSelectOnboarded(),
  printing: makeSelectPrinting(),
});

function mapDispatchToProps(dispatch) {
  return {
    setComponent: bindActionCreators(setComponent, dispatch),
    setSelectedYear: bindActionCreators(setSelectedYear, dispatch),
    togglePrinting: bindActionCreators(togglePrinting, dispatch),
    ...bindRoutineCreators({ fetchAllEmploymentData }, dispatch),
    ...bindRoutineCreators({ fetchAllElementsData }, dispatch),
    ...bindRoutineCreators({ submitProfile }, dispatch),
    ...bindRoutineCreators({ submitElement }, dispatch),
    ...bindRoutineCreators({ createEmployment }, dispatch),
    ...bindRoutineCreators({ editEmployment }, dispatch),
    ...bindRoutineCreators({ deleteEmployment }, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SettingsPage);


text:
/**
 * Chromecast receiver functionality.
 * @class
 */
var receiver = function() {};

/**
 * @const {string}
 * @private
 */
receiver.MESSAGE_NAMESPACE_ = 'urn:x-cast:com.shaka.cast.messages';

/**
 * @type {cast.receiver.CastReceiverManager}
 * @private
 */
receiver.castReceiverManager_ = null;

/**
 * @type {cast.receiver.CastMessageBus}
 * @private
 */
receiver.messageBus_ = null;  // custom message bus

/**
 * @const {number} The ms to remain idle before killing the receiver app.
 * @private
 */
receiver.IDLE_TIMEOUT_ = 1000 * 60 * 5; // 5 minutes

/**
 * @type {?number} Id of the idle timer.
 * @private
 */
receiver.idleTimer_ = null;

/**
 * Initializes the receiver.
 */
receiver.initialize = function() {

  receiver.castReceiverManager_ =
      cast.receiver.CastReceiverManager.getInstance();

  receiver.castReceiverManager_.onSenderDisconnected = function(event) {
    if (receiver.castReceiverManager_.getSenders().length == 0) {
      if (event.reason ==
          cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER) {
        window.close();
      }
    }
  };

  receiver.messageBus_ = receiver.castReceiverManager_.getCastMessageBus(
      receiver.MESSAGE_NAMESPACE_);
  /**
   * Handles messages from the sender. event.data will be objects with a
   * type and value.
   * @param {Event} event The message event.
   */
  receiver.messageBus_.onMessage = function(event) {
    var message = JSON.parse(event['data']);
    switch (message['type']) {
      case 'loadStream':
        receiverApp.loadDashStream(message['value']);
        break;
      case 'play':
        receiverApp.play();
        break;
      case 'pause':
        receiverApp.pause();
        break;
      case 'setCurrentTime':
        receiverApp.setCurrentTime(message['value']);
        break;
      case 'mute':
        receiverApp.mute(message['value']);
        break;
      case 'setVolume':
        receiverApp.setVolume(message['value']);
    }
  };

  receiver.castReceiverManager_.start();
  receiver.setIdleTimeout(receiver.IDLE_TIMEOUT_);
};

/**
 * Sets an idle timeout.
 * @param {number} timeout Time in milliseconds before the idle player
 *    terminates.
 */
receiver.setIdleTimeout = function(timeout) {
  // If starts playing before timeout, the timer will be cancelled.
  if (receiver.idleTimer) {
    window.clearTimeout(receiver.idleTimer);
  }
  receiver.idleTimer = window.setTimeout(function() {
    window.close();
  }, timeout);
};

/**
 * Cancels idle timeout.
 */
receiver.cancelIdleTimeout = function() {
  if (receiver.idleTimer) {
    window.clearTimeout(receiver.idleTimer);
  }
  receiver.IdleTimeout = null;
};

/**
 * Broadcast message to all senders via custom message channel.
 * @param {string} type The type of message.
 * @param {*} value The value of the message.
 */
receiver.broadcast = function(type, value) {
  receiver.messageBus_.broadcast(
      JSON.stringify({'type': type, 'value': value}));
};


text:
"""
SQS Message Processing
===============

"""
import base64
import json
import logging
import traceback
import zlib

from .email_delivery import EmailDelivery
from .sns_delivery import SnsDelivery

from c7n_mailer.utils import kms_decrypt

DATA_MESSAGE = "maidmsg/1.0"

class MailerSqsQueueIterator:
    # Copied from custodian to avoid runtime library dependency
    msg_attributes = ['sequence_id', 'op', 'ser']

    def __init__(self, aws_sqs, queue_url, logger, limit=0, timeout=10):
        self.aws_sqs = aws_sqs
        self.queue_url = queue_url
        self.limit = limit
        self.logger = logger
        self.timeout = timeout
        self.messages = []

    # this and the next function make this object iterable with a for loop
    def __iter__(self):
        return self

    def __next__(self):
        if self.messages:
            return self.messages.pop(0)
        response = self.aws_sqs.receive_message(
            QueueUrl=self.queue_url,
            WaitTimeSeconds=self.timeout,
            MaxNumberOfMessages=3,
            MessageAttributeNames=self.msg_attributes,
            AttributeNames=['SentTimestamp']
        )

        msgs = response.get('Messages', [])
        self.logger.debug('Messages received %d', len(msgs))
        for m in msgs:
            self.messages.append(m)
        if self.messages:
            return self.messages.pop(0)
        raise StopIteration()

    next = __next__  # python2.7

    def ack(self, m):
        self.aws_sqs.delete_message(
            QueueUrl=self.queue_url,
            ReceiptHandle=m['ReceiptHandle'])

class MailerSqsQueueProcessor:

    def __init__(self, config, session, logger, max_num_processes=16):
        self.config = config
        self.logger = logger
        self.session = session
        self.max_num_processes = max_num_processes
        self.receive_queue = self.config['queue_url']
        self.endpoint_url = self.config.get('endpoint_url', None)
        if self.config.get('debug', False):
            self.logger.debug('debug logging is turned on from mailer config file.')
            logger.setLevel(logging.DEBUG)

    """
    Cases
    - aws resource is tagged CreatorName: 'milton', ldap_tag_uids has CreatorName,
        we do an ldap lookup, get milton's email and send him an email
    - you put an email in the to: field of the notify of your policy, we send an email
        for all resources enforce by that policy
    - you put an sns topic in the to: field of the notify of your policy, we send an sns
        message for all resources enforce by that policy
    - an lambda enforces a policy based on an event, we lookup the event aws username, get their
        ldap email and send them an email about a policy enforcement (from lambda) for the event
    - resource-owners has a list of tags, SupportEmail, OwnerEmail, if your resources
        include those tags with valid emails, we'll send an email for those resources
        any others
    - resource-owners has a list of tags, SnSTopic, we'll deliver an sns message for
        any resources with SnSTopic set with a value that is a valid sns topic.
    """
    def run(self, parallel=False):
        self.logger.info("Downloading messages from the SQS queue.")
        aws_sqs = self.session.client('sqs', endpoint_url=self.endpoint_url)
        sqs_messages = MailerSqsQueueIterator(aws_sqs, self.receive_queue, self.logger)

        sqs_messages.msg_attributes = ['mtype', 'recipient']
        # lambda doesn't support multiprocessing, so we don't instantiate any mp stuff
        # unless it's being run from CLI on a normal system with SHM
        if parallel:
            import multiprocessing
            process_pool = multiprocessing.Pool(processes=self.max_num_processes)
        for sqs_message in sqs_messages:
            self.logger.debug(
                "Message id: %s received %s" % (
                    sqs_message['MessageId'], sqs_message.get('MessageAttributes', '')))
            msg_kind = sqs_message.get('MessageAttributes', {}).get('mtype')
            if msg_kind:
                msg_kind = msg_kind['StringValue']
            if not msg_kind == DATA_MESSAGE:
                warning_msg = 'Unknown sqs_message or sns format %s' % (sqs_message['Body'][:50])
                self.logger.warning(warning_msg)
            if parallel:
                process_pool.apply_async(self.process_sqs_message, args=sqs_message)
            else:
                self.process_sqs_message(sqs_message)
            self.logger.debug('Processed sqs_message')
            sqs_messages.ack(sqs_message)
        if parallel:
            process_pool.close()
            process_pool.join()
        self.logger.info('No sqs_messages left on the queue, exiting c7n_mailer.')
        return

    # This function when processing sqs messages will only deliver messages over email or sns
    # If you explicitly declare which tags are aws_usernames (synonymous with ldap uids)
    # in the ldap_uid_tags section of your mailer.yml, we'll do a lookup of those emails
    # (and their manager if that option is on) and also send emails there.
    def process_sqs_message(self, encoded_sqs_message):
        body = encoded_sqs_message['Body']
        try:
            body = json.dumps(json.loads(body)['Message'])
        except ValueError:
            pass
        sqs_message = json.loads(zlib.decompress(base64.b64decode(body)))

        self.logger.debug("Got account:%s message:%s %s:%d policy:%s recipients:%s" % (
            sqs_message.get('account', 'na'),
            encoded_sqs_message['MessageId'],
            sqs_message['policy']['resource'],
            len(sqs_message['resources']),
            sqs_message['policy']['name'],
            ', '.join(sqs_message['action'].get('to'))))

        # get the map of email_to_addresses to mimetext messages (with resources baked in)
        # and send any emails (to SES or SMTP) if there are email addresses found
        email_delivery = EmailDelivery(self.config, self.session, self.logger)
        to_addrs_to_email_messages_map = email_delivery.get_to_addrs_email_messages_map(sqs_message)
        for email_to_addrs, mimetext_msg in to_addrs_to_email_messages_map.items():
            email_delivery.send_c7n_email(sqs_message, list(email_to_addrs), mimetext_msg)

        # this sections gets the map of sns_to_addresses to rendered_jinja messages
        # (with resources baked in) and delivers the message to each sns topic
        sns_delivery = SnsDelivery(self.config, self.session, self.logger)
        sns_message_packages = sns_delivery.get_sns_message_packages(sqs_message)
        sns_delivery.deliver_sns_messages(sns_message_packages, sqs_message)

        # this section sends a notification to the resource owner via Slack
        if any(e.startswith('slack') or e.startswith('https://hooks.slack.com/')
                for e in sqs_message.get('action', ()).get('to', []) +
                sqs_message.get('action', ()).get('owner_absent_contact', [])):
            from .slack_delivery import SlackDelivery

            if self.config.get('slack_token'):
                self.config['slack_token'] = \
                    kms_decrypt(self.config, self.logger, self.session, 'slack_token')

            slack_delivery = SlackDelivery(self.config, self.logger, email_delivery)
            slack_messages = slack_delivery.get_to_addrs_slack_messages_map(sqs_message)
            try:
                slack_delivery.slack_handler(sqs_message, slack_messages)
            except Exception:
                traceback.print_exc()
                pass

        # this section gets the map of metrics to send to datadog and delivers it
        if any(e.startswith('datadog') for e in sqs_message.get('action', ()).get('to')):
            from .datadog_delivery import DataDogDelivery
            datadog_delivery = DataDogDelivery(self.config, self.session, self.logger)
            datadog_message_packages = datadog_delivery.get_datadog_message_packages(sqs_message)

            try:
                datadog_delivery.deliver_datadog_messages(datadog_message_packages, sqs_message)
            except Exception:
                traceback.print_exc()
                pass

        # this section sends the full event to a Splunk HTTP Event Collector (HEC)
        if any(
            e.startswith('splunkhec://')
            for e in sqs_message.get('action', ()).get('to')
        ):
            from .splunk_delivery import SplunkHecDelivery
            splunk_delivery = SplunkHecDelivery(self.config, self.session, self.logger)
            splunk_messages = splunk_delivery.get_splunk_payloads(
                sqs_message, encoded_sqs_message['Attributes']['SentTimestamp']
            )

            try:
                splunk_delivery.deliver_splunk_messages(splunk_messages)
            except Exception:
                traceback.print_exc()
                pass


text:
export const environment = {
  production: true,
  version: '%VERSION%',
  buildtime: '%BUILDTIME%',
  base_href: '%BASE_HREF%',
  googletranslate_api_key: null,
  googletranslate_provoke_failures: false,
  github_api_key: null,
  github_provoke_failures: false,
};


text:
<?php

namespace Nz\CrawlerBundle\Admin;

use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Nz\CrawlerBundle\Model\LinkManagerInterface;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Form\CallbackTransformer;

class LinkAdmin extends Admin
{

    /**
     * @var LinkManagerInterface
     */
    protected $linkManager;
    protected $maxPerPage = 300;
    protected $parentAssociationMapping = 'profile';

    /**
     * Default values to the datagrid.
     *
     * @var array
     */
    protected $datagridValues = array(
        '_page' => 1,
        '_per_page' => 320,
        '_sort_order' => 'DESC',
    );

    protected function configureRoutes(RouteCollection $collection)
    {
        // on top
        $collection->add('crawl-indexes', 'crawl-indexes');
        $collection->add('crawl-links', 'crawl-links');
        $collection->add('crawl-url', 'crawl-url');
        // on list
        $collection->add('crawl-link', $this->getRouterIdParameter() . '/crawl');
    }

    /**
     * {@inheritdoc}
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('id')
            ->add('url')
            ->add('processed')
            ->add('error')
            ->add('skip')
            ->add('notes')
            ->add('crawledAt')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('Option', array(
                'class' => 'col-md-8',
            ))
            ->add('name')
            ->add('url', 'url')
            ->add('processed')
            ->add('error')
            ->add('skip')
            ->add('crawledAt')
            ->add('notes')
            ->add('profile')
            ->end()
        ;
        /*
          $formMapper->getFormBuilder()->get('notes')
          ->addModelTransformer(new CallbackTransformer(
          function ($dbNotes) {
          $json = json_encode($dbNotes);
          return $json;
          }, function ($formNotes) {

          if (empty($formNotes)) {
          return [];
          }

          $array = json_decode($formNotes, true);
          return $array;
          }
          ))
          ;
         */
    }

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);

        if ($this->getParent()) {
            return $query;
        }

        if ($this->getRequest()->get('filter')) {
            return $query;
        }

        $query->andWhere(
            $query->getRootAliases()[0] . '.profile is NULL'
        );
        return $query;
        /* d($this->getRequest()); */
        /* dd($query); */
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {

        $listMapper
            ->addIdentifier('url', null, array(
                'template' => 'NzCrawlerBundle:CRUD:list__link_identifier.html.twig'
            ))
            ->add('processed', null)
            ->add('error', null, array('editable' => true))
            ->add('skip', null, array('editable' => true))
        /*       custom actions
          ->add('_action', 'crawl', array(
          'actions' => array(
          'Crawl' => array(
          'template' => 'NzCrawlerBundle:CRUD:list__link_action.html.twig'
          )
          )
          ))
         */

        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {

        $datagridMapper
            ->add('url')
            ->add('processed')
            ->add('error')
            ->add('skip')
        ;

        if ($this->getParent()) {
            return;
        }
        //if not in parent add by profile filter
        $datagridMapper
            /*
             */
            ->add('profile', null, array(), 'entity', array(
                'class' => 'Nz\CrawlerBundle\Entity\Profile',
                'property' => 'name',
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        $request = $this->getRequest();

        $persist = $this->getRequest()->get('persist', false);
        $uri = $this->generateUrl($action, array_merge($request->attributes->get('_route_params'), array('persist' => !$persist)));
        $style = 'background-color:%s';
        $menu->addChild($persist ? $this->trans('sidemenu.link_persisting') : $this->trans('sidemenu.link_testing'), [
            'uri' => $uri,
            'attributes' => array(
                'style' => sprintf($style, $persist ? 'orangered' : 'greenyellow')
            )
        ]);

        if ('list' === $action) {
            $menu->addChild($this->trans('sidemenu.link_crawl_indexes'), [
                'uri' => $this->generateUrl('crawl-indexes'),
            ]);
            /* $admin = $this->isChild() ? $this->getParent() : $this; */

            $menu->addChild($this->trans('sidemenu.link_crawl_links'), [
                'uri' => $this->generateUrl('crawl-links'),
            ]);
        }
    }

    public function getPersistentParameters()
    {
        if (!$this->getRequest()) {
            return array();
        }
        return array(
            'persist' => $this->getRequest()->get('persist', false)
        );
    }

    /**
     */
    public function setLinkManager(LinkManagerInterface $linkManager)
    {
        $this->linkManager = $linkManager;
    }
}


text:
package aws

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"sort"
	"strings"
	"time"
)

var b64 = base64.StdEncoding

type Client struct {
	Key, Secret string
}

var Debug = os.Getenv("DEBUG") == "true"

func (client *Client) Debug(format string, i ...interface{}) {
	if Debug {
		fmt.Printf(format+"\n", i...)
	}
}

func NewFromEnv() *Client {
	client := &Client{}
	client.Key, client.Secret = os.Getenv(ENV_AWS_ACCESS_KEY), os.Getenv(ENV_AWS_SECRET_KEY)

	if client.Key == "" || client.Secret == "" {
		abortWith(fmt.Sprintf("%s and %s must be set in ENV", ENV_AWS_ACCESS_KEY, ENV_AWS_SECRET_KEY))
	}
	return client
}

type Response struct {
	StatusCode int
	Content    []byte
}

func QueryPrefix(version, action string) string {
	return "Version=" + version + "&Action=" + action
}

type ErrorResponse struct {
	XMLName   xml.Name `xml:"ErrorResponse"`
	RequestID string   `xml:"RequestID"`
	Errors    []*Error `xml:"Error"`
}

type Error struct {
	Code    string `xml:"Code"`
	Message string `xml:"Message"`
}

func (er *ErrorResponse) ErrorStrings() string {
	out := []string{}
	for _, e := range er.Errors {
		out = append(out, fmt.Sprintf("%s: %s", e.Code, e.Message))
	}
	return strings.Join(out, ", ")
}

func ExtractError(b []byte) error {
	rsp := &ErrorResponse{}
	e := xml.Unmarshal(b, rsp)
	if e == nil {
		return fmt.Errorf(rsp.ErrorStrings())
	}
	return nil
}

// list of endpoints
func (client *Client) DoSignedRequest(method string, endpoint, action string, extraAttributes map[string]string) (rsp *Response, e error) {
	request, e := http.NewRequest(method, endpoint+"?"+action, nil)
	client.SignAwsRequestV2(request, time.Now())
	raw, e := http.DefaultClient.Do(request)
	if e != nil {
		return rsp, e
	}
	defer raw.Body.Close()
	rsp = &Response{
		StatusCode: raw.StatusCode,
	}
	rsp.Content, e = ioutil.ReadAll(raw.Body)
	if e != nil {
		return rsp, e
	}
	return rsp, e
}

func (client *Client) signPayload(payload string) string {
	hash := hmac.New(sha256.New, []byte(client.Secret))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum(nil))
	return string(signature)
}

func (client *Client) SignAwsRequest(req *http.Request) {
	date := time.Now().UTC().Format(http.TimeFormat)
	token := "AWS3-HTTPS AWSAccessKeyId=" + client.Key + ",Algorithm=HmacSHA256,Signature=" + client.signPayload(date)
	req.Header.Set("X-Amzn-Authorization", token)
	req.Header.Set("x-amz-date", date)
	return
}

func (client *Client) v2PayloadAndQuery(req *http.Request) (payload, rawQuery string) {
	values := req.URL.Query()
	if len(values["AWSAccessKeyId"]) == 0 {
		values.Add("AWSAccessKeyId", client.Key)
	}

	if len(values["SignatureVersion"]) == 0 {
		values.Add("SignatureVersion", "2")
	}

	if len(values["SignatureMethod"]) == 0 {
		values.Add("SignatureMethod", "HmacSHA256")
	}

	if len(values["Timestamp"]) == 0 {
		values.Add("Timestamp", time.Now().UTC().Format(time.RFC3339))
	}

	var keys, sarray []string
	for k, _ := range values {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		sarray = append(sarray, Encode(k)+"="+Encode(values[k][0]))
	}

	joined := strings.Join(sarray, "&")
	path := "/"
	if req.URL.Path != "" {
		path = req.URL.Path
	}

	return strings.Join([]string{
		req.Method,
		req.URL.Host,
		path,
		joined,
	}, "\n"), joined
}

func (client *Client) SignAwsRequestV2(req *http.Request, t time.Time) {
	values := req.URL.Query()
	if len(values["Timestamp"]) == 0 {
		values.Add("Timestamp", t.UTC().Format(time.RFC3339))
	}
	req.URL.RawQuery = values.Encode()
	payload, query := client.v2PayloadAndQuery(req)
	query += "&Signature=" + Encode(client.signPayload(payload))
	req.URL.RawQuery = query
}

// authentication:	http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html
// upload:			http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
func (client *Client) SignS3Request(req *http.Request) {
	time := time.Now()
	date := time.Format(http.TimeFormat)
	payloadParts := []string{
		req.Method,
		req.Header.Get(CONTENT_MD5),
		req.Header.Get(CONTENT_TYPE),
		date,
	}
	amzHeaders := []string{}
	for k, v := range req.Header {
		value := strings.ToLower(k) + ":" + strings.Join(v, ",")
		if strings.HasPrefix(value, "x-amz") {
			amzHeaders = append(amzHeaders, value)
		}
	}
	sort.Strings(amzHeaders)
	payloadParts = append(payloadParts, amzHeaders...)
	payloadParts = append(payloadParts, req.URL.Path)
	payload := strings.Join(payloadParts, "\n")
	req.Header.Add("Date", date)
	req.Header.Add("Authorization", "AWS "+client.Key+":"+client.signPayload(payload))
}


text:
from unittest import TestCase

import geopandas as gpd
import numpy as np
import pandas as pd
import shapely.geometry
import shapely.wkt
from shapely.geometry import Point

from cate.core.types import GeoDataFrameProxy
from cate.core.types import ValidationError
from cate.ops.data_frame import data_frame_min, data_frame_max, data_frame_query, data_frame_find_closest, \
    great_circle_distance, data_frame_aggregate, data_frame_subset

test_point = 'POINT (597842.4375881671 5519903.13366397)'

test_poly_4326 = 'POLYGON ((-80 -40, -70 -40, ' \
                 '-70 -45, -80 -45, ' \
                 '-80 -40))'

class TestDataFrameOps(TestCase):
    df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6],
                       'B': ['a', 'b', 'c', 'x', 'y', 'z'],
                       'C': [False, False, True, False, True, True],
                       'D': [0.4, 0.5, 0.3, 0.3, 0.1, 0.4]})

    gdf = gpd.GeoDataFrame({'A': [1, 2, 3, 4, 5, 6],
                            'B': ['a', 'b', 'c', 'x', 'y', 'z'],
                            'C': [False, False, True, False, True, True],
                            'D': [0.4, 0.5, 0.3, 0.3, 0.1, 0.4],
                            'geometry': gpd.GeoSeries([
                                shapely.wkt.loads('POINT(10 10)'),
                                shapely.wkt.loads('POINT(10 20)'),
                                shapely.wkt.loads('POINT(10 30)'),
                                shapely.wkt.loads('POINT(20 30)'),
                                shapely.wkt.loads('POINT(20 20)'),
                                shapely.wkt.loads('POINT(20 10)'),
                            ])})

    gdf_32718 = gpd.GeoDataFrame({'A': [1]},
                                 crs={'init': 'epsg:32718'},
                                 geometry=[shapely.wkt.loads(test_point)])

    test_region_4326 = shapely.wkt.loads(test_poly_4326)

    gdfp = GeoDataFrameProxy.from_features(gdf.__geo_interface__['features'])

    def test_data_frame_min(self):
        df2 = data_frame_min(TestDataFrameOps.df, 'D')
        self.assertIsInstance(df2, pd.DataFrame)
        self.assertEqual(len(df2), 1)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D'])
        self.assertEqual(df2.iloc[0, 0], 5)
        self.assertEqual(df2.iloc[0, 1], 'y')
        self.assertEqual(df2.iloc[0, 2], True)
        self.assertEqual(df2.iloc[0, 3], 0.1)

    def test_data_frame_max(self):
        df2 = data_frame_max(TestDataFrameOps.df, 'D')
        self.assertIsInstance(df2, pd.DataFrame)
        self.assertEqual(len(df2), 1)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D'])
        self.assertEqual(df2.iloc[0, 0], 2)
        self.assertEqual(df2.iloc[0, 1], 'b')
        self.assertEqual(df2.iloc[0, 2], False)
        self.assertEqual(df2.iloc[0, 3], 0.5)

    def test_data_frame_query(self):
        df2 = data_frame_query(TestDataFrameOps.df, "D >= 0.4 and B != 'b'")
        self.assertIsInstance(df2, pd.DataFrame)
        self.assertEqual(len(df2), 2)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D'])
        self.assertEqual(df2.iloc[0, 0], 1)
        self.assertEqual(df2.iloc[0, 1], 'a')
        self.assertEqual(df2.iloc[0, 2], False)
        self.assertEqual(df2.iloc[0, 3], 0.4)
        self.assertEqual(df2.iloc[1, 0], 6)
        self.assertEqual(df2.iloc[1, 1], 'z')
        self.assertEqual(df2.iloc[1, 2], True)
        self.assertEqual(df2.iloc[1, 3], 0.4)

    def test_data_frame_query_with_geom(self):
        self._test_data_frame_query_with_geom(TestDataFrameOps.gdf)
        # Skipped due to new behaviour of from_features
        # self._test_data_frame_query_with_geom(TestDataFrameOps.gdfp)

    def _test_data_frame_query_with_geom(self, gdf):
        df2 = data_frame_query(gdf, "not C and @almost_equals('10,10')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        df2 = data_frame_query(gdf, "not C and @contains('10,10')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        df2 = data_frame_query(gdf, "not C and @crosses('10,10')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 0)
        df2 = data_frame_query(gdf, "not C and @disjoint('10,10')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 2)
        df2 = data_frame_query(gdf, "not C and @intersects('19, 9, 21, 31')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        df2 = data_frame_query(gdf, "not C and @touches('10, 10, 20, 30')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 3)
        df2 = data_frame_query(gdf, "@within('19, 9, 21, 31')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 3)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D', 'geometry'])
        self.assertEqual(df2.iloc[0, 0], 4)
        self.assertEqual(df2.iloc[1, 0], 5)
        self.assertEqual(df2.iloc[2, 0], 6)
        self.assertEqual(df2.iloc[0, 1], 'x')
        self.assertEqual(df2.iloc[1, 1], 'y')
        self.assertEqual(df2.iloc[2, 1], 'z')
        self.assertEqual(df2.iloc[0, 2], False)
        self.assertEqual(df2.iloc[1, 2], True)
        self.assertEqual(df2.iloc[2, 2], True)
        self.assertEqual(df2.iloc[0, 3], 0.3)
        self.assertEqual(df2.iloc[1, 3], 0.1)
        self.assertEqual(df2.iloc[2, 3], 0.4)
        df2 = data_frame_query(gdf, "not C and @within('19, 9, 21, 31')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D', 'geometry'])
        self.assertEqual(df2.iloc[0, 0], 4)
        self.assertEqual(df2.iloc[0, 1], 'x')
        self.assertEqual(df2.iloc[0, 2], False)
        self.assertEqual(df2.iloc[0, 3], 0.3)
        df2 = data_frame_query(gdf, "not C and geometry.within(@from_wkt('19, 9, 21, 31'))")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        self.assertEqual(list(df2.columns), ['A', 'B', 'C', 'D', 'geometry'])
        self.assertEqual(df2.iloc[0, 0], 4)
        self.assertEqual(df2.iloc[0, 1], 'x')
        self.assertEqual(df2.iloc[0, 2], False)
        self.assertEqual(df2.iloc[0, 3], 0.3)

    def test_data_frame_subset(self):
        df2 = data_frame_subset(TestDataFrameOps.gdf,
                                region='POLYGON((-10 0, 25 0, 25 30, -10 0))')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 3)
        self.assertIn('A', df2)
        self.assertIn('B', df2)
        self.assertIn('C', df2)
        self.assertIn('D', df2)
        self.assertIn('geometry', df2)

        df2 = data_frame_subset(TestDataFrameOps.gdf,
                                var_names="A,C",
                                region='POLYGON((-10 0, 25 0, 25 30, -10 0))')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 3)
        self.assertIn('A', df2)
        self.assertNotIn('B', df2)
        self.assertIn('C', df2)
        self.assertNotIn('D', df2)
        self.assertIn('geometry', df2)

        df2 = data_frame_subset(TestDataFrameOps.gdf,
                                var_names="A,C",
                                region='POLYGON((30 30, 40 30, 40 40, 30 30))')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 0)

    def test_data_frame_failures(self):
        df2 = data_frame_query(TestDataFrameOps.gdf_32718, "@within('" + test_poly_4326 + "')")
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)

        df2 = data_frame_subset(TestDataFrameOps.gdf_32718,
                                var_names='A',
                                region=TestDataFrameOps.test_region_4326)
        self.assertEqual(len(df2), 1)

    def test_data_frame_find_closest(self):
        df2 = data_frame_find_closest(TestDataFrameOps.gdf, 'POINT(20 30)',
                                      dist_col_name='dist')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 1)
        self.assertIn('A', df2)
        self.assertIn('B', df2)
        self.assertIn('C', df2)
        self.assertIn('D', df2)
        self.assertIn('geometry', df2)
        self.assertIn('dist', df2)
        self.assertEqual(1, len(df2['dist']))
        self.assertEqual(0.0, df2['dist'].iloc[0])
        self.assertEqual(shapely.wkt.loads('POINT(20 30)'), df2['geometry'].iloc[0])

        df2 = data_frame_find_closest(TestDataFrameOps.gdf, 'POINT(21 28)',
                                      max_results=3, dist_col_name='dist')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 3)
        self.assertIn('A', df2)
        self.assertIn('B', df2)
        self.assertIn('C', df2)
        self.assertIn('D', df2)
        self.assertIn('geometry', df2)
        self.assertIn('dist', df2)
        np.testing.assert_approx_equal(2.1828435, df2['dist'].iloc[0])
        np.testing.assert_approx_equal(8.0518568, df2['dist'].iloc[1])
        np.testing.assert_approx_equal(9.8221713, df2['dist'].iloc[2])
        self.assertEqual(shapely.wkt.loads('POINT(20 30)'), df2['geometry'].iloc[0])
        self.assertEqual(shapely.wkt.loads('POINT(20 20)'), df2['geometry'].iloc[1])
        self.assertEqual(shapely.wkt.loads('POINT(10 30)'), df2['geometry'].iloc[2])

        df2 = data_frame_find_closest(TestDataFrameOps.gdf, 'POINT(21 28)',
                                      max_dist=9.0, max_results=3, dist_col_name='dist')
        self.assertIsInstance(df2, gpd.GeoDataFrame)
        self.assertEqual(len(df2), 2)
        self.assertIn('A', df2)
        self.assertIn('B', df2)
        self.assertIn('C', df2)
        self.assertIn('D', df2)
        self.assertIn('geometry', df2)
        self.assertIn('dist', df2)
        np.testing.assert_approx_equal(2.1828435, df2['dist'].iloc[0])
        np.testing.assert_approx_equal(8.0518568, df2['dist'].iloc[1])
        self.assertEqual(shapely.wkt.loads('POINT(20 30)'), df2['geometry'].iloc[0])
        self.assertEqual(shapely.wkt.loads('POINT(20 20)'), df2['geometry'].iloc[1])

    def test_data_frame_aggregate(self):
        # Generate mock data
        data = {'name': ['A', 'B', 'C'],
                'lat': [45, 46, 47.5],
                'lon': [-120, -121.2, -122.9]}

        df = pd.DataFrame(data)
        # needs to be a copy
        gdf_empty_geo = gpd.GeoDataFrame(df).copy()
        gdf = gpd.GeoDataFrame(df, geometry=[Point(xy) for xy in zip(df['lon'], df['lat'])])

        var_names_not_agg = 'name, lat, lon'
        var_names_not_in = 'asdc, lat, lon'
        var_names_valid = ['lat', 'lon']
        aggregations = ["count", "mean", "median", "sum", "std", "min", "max"]

        # Assert that a Validation exception is thrown if the df is None
        with self.assertRaises(ValidationError):
            data_frame_aggregate(df=None)

        # Assert that a Validation exception is thrown if the var_names contain non-existing fields in the df
        with self.assertRaises(ValidationError):
            data_frame_aggregate(df=df, var_names=var_names_not_in)

        # Assert that a Validation exception is thrown if the var_names contain non-aggregatable fields
        with self.assertRaises(ValidationError):
            data_frame_aggregate(df=df, var_names=var_names_not_agg)

        # Assert that a Validation exception is thrown if the GeoDataFrame does not have a geometry
        with self.assertRaises(ValidationError):
            data_frame_aggregate(df=gdf_empty_geo, var_names=None)

        with self.assertRaises(ValidationError):
            data_frame_aggregate(df=gdf_empty_geo, var_names='lat')

        # assert that a input and output types for df are the same
        rdf = data_frame_aggregate(df=gdf, var_names=var_names_valid)
        self.assertEqual(len(rdf), 1)

        # assert that columns are return if var_names = None for a DataFrame
        rdf = data_frame_aggregate(df=df, var_names=None)
        self.assertEqual(len(rdf.columns), len(aggregations) * len(var_names_valid))

        # assert that columns are return if var_names = None for a GeoDataFrame
        rdf = data_frame_aggregate(df=gdf, var_names=None, aggregate_geometry=True)
        self.assertEqual(len(rdf.columns), len(aggregations) * len(var_names_valid) + 1)

        # assert that geometry union is created
        rdf = data_frame_aggregate(df=gdf, var_names=var_names_valid, aggregate_geometry=True)
        self.assertIsNotNone(rdf.geometry)

class GreatCircleDistanceTest(TestCase):
    def test_great_circle_distance(self):
        dist = great_circle_distance(Point(20, 20), Point(20, 20))
        self.assertIsNotNone(dist)
        np.testing.assert_approx_equal(0.0, dist)
        dist = great_circle_distance(Point(20, 0), Point(20, 30))
        np.testing.assert_approx_equal(30.0, dist)
        dist = great_circle_distance(Point(-20, 0), Point(20, 0))
        np.testing.assert_approx_equal(40.0, dist)
        dist = great_circle_distance(Point(-155, 0), Point(155, 0))
        np.testing.assert_approx_equal(50.0, dist)
        dist = great_circle_distance(Point(0, 0), Point(0, 90))
        np.testing.assert_approx_equal(90.0, dist)
        dist = great_circle_distance(Point(0, -90), Point(0, 90))
        np.testing.assert_approx_equal(180.0, dist)
        dist = great_circle_distance(Point(0, 180), Point(0, 0))
        np.testing.assert_approx_equal(180.0, dist)
        dist = great_circle_distance(Point(0, 0), Point(1, 1))
        np.testing.assert_approx_equal(1.4141777, dist)


text:
This project creates a working snap of `leafpad`.

To get this done, we need to do the following:
 - uses the launcher from the `desktop-gtk2` part.
 - use the `leafpad` git tree (https://github.com/oluc/leafpad)

## Current state

Working features:
 - it generally works


text:
module ActionGuard
  class Role
    attr_reader :level
    def initialize(value, level)
      @value = value
      @level = level
    end

    def >=(other)
      level <= other.level
    end

    def < (other)
      level > other.level
    end

    def to_s
      "Role(:#{@value})"
    end
  end
end


text:
export function isElement(a: any): a is Element {
    return a instanceof Element;
}


text:
import React from 'react';
import PropTypes from 'prop-types';

import { Link } from 'react-router-dom';
import isEmpty from 'ramda/src/isEmpty';
import not from 'ramda/src/not';

import { capitalize } from '../utils';

/* eslint-disable react/prop-types */
const ChangeAnswerColumn = ({
  question,
  changeAnswerLink,
  withChangeAnswer,
  tableHasChangeAnswers,
}) => {
  if (withChangeAnswer) {
    return (

        <Link href={false} to={changeAnswerLink} data-element-id="change-answer-link">
          Change {question}
        </Link>

    );
  }

  if (tableHasChangeAnswers) {
    return ;
  }

  return null;
};

// eslint-disable-next-line
const QuestionAnswerRow = ({
  question,
  answer,
  dataTags,
  changeAnswerLink,
  withChangeAnswer,
  tableHasChangeAnswers,
}) => not(isEmpty(answer)) ? (

    {question}

{capitalize(answer.answer)}

      {answer[`reasons-${answer.answer}`] && (

"{capitalize(answer[`reasons-${answer.answer}`])}"

      )}
      {answer['reasons-for-answer'] && (

"{capitalize(answer['reasons-for-answer'])}"

      )}

    <ChangeAnswerColumn
      {...{
 withChangeAnswer, question, changeAnswerLink, tableHasChangeAnswers,
}}
    />

) : null;

QuestionAnswerRow.propTypes = {
  question: PropTypes.string,
  changeAnswerLink: PropTypes.string,
  answer: PropTypes.shape({
    answer: PropTypes.string,
  }),
  dataTags: PropTypes.objectOf(PropTypes.string),
};

QuestionAnswerRow.defaultProps = {
  question: '',
  answer: {},
  dataTags: {},
  changeAnswerLink: '',
};

export default QuestionAnswerRow;