text:
#include "ogr_db2.h"

CPL_CVSID("$Id: ogrdb2layer.cpp 7d078e0357d2998edfa713422e607cbadf77f9ff 2018-04-08 22:11:28 +0200 Even Rouault $")

/************************************************************************/
/*                        OGRDB2Layer()                        */
/************************************************************************/

OGRDB2Layer::OGRDB2Layer()

{
    m_poDS = nullptr;
    poFeatureDefn = nullptr;
    poDS = nullptr;
    pszGeomColumn = nullptr;
    pszFIDColumn = nullptr;
    bIsIdentityFid = FALSE;
    cGenerated = ' ';
    nLayerStatus = 0;
    panFieldOrdinals = nullptr;
    m_poStmt = nullptr;
    m_poPrepStmt = nullptr;
    iNextShapeId = 0;
    poSRS = nullptr;
    nSRSId = -1; // we haven't even queried the database for it yet.
}

/************************************************************************/
/*                      ~OGRDB2Layer()                         */
/************************************************************************/

OGRDB2Layer::~OGRDB2Layer()

{
    CPLDebug("OGRDB2Layer::~OGRDB2Layer","entering");
    CPLDebug("OGRDB2Layer::~OGRDB2Layer",
             "m_nFeaturesRead: " CPL_FRMT_GIB "; poFeatureDefn: %p",
             m_nFeaturesRead,poFeatureDefn);
    if( m_nFeaturesRead > 0 && poFeatureDefn != nullptr )
    {
        CPLDebug( "OGR_DB2Layer",
                  "%d features read on layer '%s'.",
                  (int) m_nFeaturesRead,
                  poFeatureDefn->GetName() );
    }

    if( m_poStmt )
    {
        delete m_poStmt;
        m_poStmt = nullptr;
    }

    CPLFree( pszGeomColumn );
    CPLFree( pszFIDColumn );
    CPLFree( panFieldOrdinals );

    if( poFeatureDefn )
    {
        poFeatureDefn->Release();
        poFeatureDefn = nullptr;
    }

    if( poSRS )
        poSRS->Release();
    CPLDebug("OGRDB2Layer::~OGRDB2Layer","exiting") ;
}

/************************************************************************/
/*                          BuildFeatureDefn()                          */
/*                                                                      */
/*      Build feature definition from a set of column definitions       */
/*      set on a statement.  Sift out geometry and FID fields.          */
/************************************************************************/

CPLErr OGRDB2Layer::BuildFeatureDefn( const char *pszLayerName,
                                      OGRDB2Statement *poStmt )

{
    poFeatureDefn = new OGRFeatureDefn( pszLayerName );
    int    nRawColumns = poStmt->GetColCount();
    CPLDebug( "OGR_DB2Layer::BuildFeatureDefn",
              "pszLayerName: '%s'; pszGeomColumn: '%s'",
              pszLayerName, pszGeomColumn);
    poFeatureDefn->Reference();

    CPLFree(panFieldOrdinals);
    panFieldOrdinals = (int *) CPLMalloc( sizeof(int) * nRawColumns );

    /* -------------------------------------------------------------------- */
    /*      If we don't already have an FID, check if there is a special    */
    /*      FID named column available.                                     */
    /* -------------------------------------------------------------------- */
    if( pszFIDColumn == nullptr )
    {
        const char *pszOGR_FID = CPLGetConfigOption("DB2SPATIAL_OGR_FID",
                                 "OBJECTID");
        for( int iCol = 0; iCol < nRawColumns; iCol++ )
        {
            if( EQUAL(poStmt->GetColName(iCol),pszOGR_FID) )
            {
                pszFIDColumn = CPLStrdup(pszOGR_FID);
                break;
            }
        }
    }

    if( pszFIDColumn != nullptr )
        CPLDebug( "OGR_DB2Layer::BuildFeatureDefn",
                  "Using column %s as FID for table %s.",
                  pszFIDColumn, poFeatureDefn->GetName() );
    else
        CPLDebug( "OGR_DB2Layer::BuildFeatureDefn",
                  "Table %s has no identified FID column.",
                  poFeatureDefn->GetName() );

    for( int iCol = 0; iCol < nRawColumns; iCol++ )
    {
        if ( pszGeomColumn == nullptr )
        {
            /* need to identify the geometry column */
            if ( EQUAL(poStmt->GetColTypeName( iCol ),
                       "VARCHAR () FOR BIT DATA") )
            {
                pszGeomColumn = CPLStrdup( poStmt->GetColName(iCol) );
                continue;
            }
        }
        else
        {
            if( EQUAL(poStmt->GetColName(iCol),pszGeomColumn) ) {
                continue;
            }
        }
        if( pszFIDColumn != nullptr &&
                EQUAL(poStmt->GetColName(iCol), pszFIDColumn) )
        {
            /* skip FID */
            continue;
        }
        // default field type is string
        OGRFieldDefn    oField( poStmt->GetColName(iCol), OFTString );
        oField.SetWidth( MAX(0,poStmt->GetColSize( iCol )) );

        int colType = poStmt->GetColType(iCol);
        switch( colType )
        {
        case SQL_C_SSHORT:
        case SQL_C_USHORT:
        case SQL_C_SLONG:
        case SQL_C_ULONG:
            oField.SetType( OFTInteger );
            break;

        case SQL_C_SBIGINT:
        case SQL_C_UBIGINT:
            oField.SetType( OFTInteger64 );
            break;

        case SQL_C_BINARY:
            oField.SetType( OFTBinary );
            break;

        case SQL_C_NUMERIC:
            oField.SetType( OFTReal );
            oField.SetPrecision( poStmt->GetColPrecision(iCol) );
            break;

        case SQL_C_FLOAT:
        case SQL_C_DOUBLE:
            oField.SetType( OFTReal );
            oField.SetWidth( 0 );
            break;

        case SQL_C_DATE:
            oField.SetType( OFTDate );
            break;

        case SQL_C_TIME:
            oField.SetType( OFTTime );
            break;

        case SQL_C_TIMESTAMP:
            oField.SetType( OFTDateTime );
            break;

        default:
            /* leave it as OFTString */
            ;
        }

        poFeatureDefn->AddFieldDefn( &oField );
        panFieldOrdinals[poFeatureDefn->GetFieldCount() - 1] = iCol;
    }

    return CE_None;
}

/************************************************************************/
/*                            ResetReading()                            */
/************************************************************************/

void OGRDB2Layer::ResetReading()

{
    iNextShapeId = 0;
    CPLDebug("OGR_DB2Layer::ResetReading","Reset");
}

/************************************************************************/
/*                           GetNextFeature()                           */
/************************************************************************/

OGRFeature *OGRDB2Layer::GetNextFeature()

{
    while( TRUE )
    {
        OGRFeature      *poFeature;

        poFeature = GetNextRawFeature();
        if( poFeature == nullptr )
            return nullptr;
        if( (m_poFilterGeom == nullptr
                || FilterGeometry( poFeature->GetGeometryRef() ) )
                && (m_poAttrQuery == nullptr
                    || m_poAttrQuery->Evaluate( poFeature )) ) {
            return poFeature;
        }

        delete poFeature;
    }
}

/************************************************************************/
/*                         GetNextRawFeature()                          */
/************************************************************************/

OGRFeature *OGRDB2Layer::GetNextRawFeature()

{

    if( GetStatement() == nullptr )
        return nullptr;

    /* -------------------------------------------------------------------- */
    /*      If we are marked to restart then do so, and fetch a record.     */
    /* -------------------------------------------------------------------- */
    if( !m_poStmt->Fetch() )  // fail is normal for final fetch
    {
//      CPLDebug("OGR_DB2Layer::GetNextRawFeature","Fetch failed");
        delete m_poStmt;
        m_poStmt = nullptr;
        return nullptr;
    }
//      CPLDebug("OGR_DB2Layer::GetNextRawFeature","Create feature");
    /* -------------------------------------------------------------------- */
    /*      Create a feature from the current result.                       */
    /* -------------------------------------------------------------------- */
    int         iField;
    OGRFeature *poFeature = new OGRFeature( poFeatureDefn );
    if( pszFIDColumn != nullptr && m_poStmt->GetColId(pszFIDColumn) > -1 )
        poFeature->SetFID(
            atoi(m_poStmt->GetColData(m_poStmt->GetColId(pszFIDColumn))) );
    else
        poFeature->SetFID( iNextShapeId );

    iNextShapeId++;
    m_nFeaturesRead++;

    /* -------------------------------------------------------------------- */
    /*      Set the fields.                                                 */
    /* -------------------------------------------------------------------- */

    for( iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
    {
        if ( poFeatureDefn->GetFieldDefn(iField)->IsIgnored() )
            continue;

        int iSrcField = panFieldOrdinals[iField];
        const char *pszValue = m_poStmt->GetColData( iSrcField );

        if( pszValue == nullptr )
            poFeature->SetFieldNull( iField );
        else if( poFeature->GetFieldDefnRef(iField)->GetType() == OFTBinary )
            poFeature->SetField( iField,
                                 m_poStmt->GetColDataLength(iSrcField),
                                 (GByte *) pszValue );
        else
            poFeature->SetField( iField, pszValue );
    }

    /* -------------------------------------------------------------------- */
    /*      Try to extract a geometry.                                      */
    /* -------------------------------------------------------------------- */

    if( pszGeomColumn != nullptr && !poFeatureDefn->IsGeometryIgnored())
    {
        iField = m_poStmt->GetColId( pszGeomColumn );
        const char *pszGeomText = m_poStmt->GetColData( iField );
        OGRGeometry *poGeom = nullptr;
        OGRErr eErr = OGRERR_NONE;
        if( pszGeomText != nullptr )
        {
            eErr = OGRGeometryFactory::createFromWkt(pszGeomText,
                    nullptr, &poGeom);
        }

        if ( eErr != OGRERR_NONE )
        {
            const char *pszMessage;

            switch ( eErr )
            {
            case OGRERR_NOT_ENOUGH_DATA:
                pszMessage = "Not enough data to deserialize";
                break;
            case OGRERR_UNSUPPORTED_GEOMETRY_TYPE:
                pszMessage = "Unsupported geometry type";
                break;
            case OGRERR_CORRUPT_DATA:
                pszMessage = "Corrupt data";
                break;
            default:
                pszMessage = "Unrecognized error";
            }
            CPLError(CE_Failure, CPLE_AppDefined,
                     "GetNextRawFeature(): %s", pszMessage);
        }

        if( poGeom != nullptr )
        {
            if ( GetSpatialRef() )
                poGeom->assignSpatialReference( poSRS );

            poFeature->SetGeometryDirectly( poGeom );
        }
    }

    return poFeature;
}

/************************************************************************/
/*                             GetFeature()                             */
/************************************************************************/

OGRFeature *OGRDB2Layer::GetFeature( GIntBig nFeatureId )

{
    /* This should be implemented directly! */

    return OGRLayer::GetFeature( nFeatureId );
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int OGRDB2Layer::TestCapability( CPL_UNUSED const char * pszCap )
{
    return FALSE;
}

/************************************************************************/
/*                          StartTransaction()                          */
/************************************************************************/

OGRErr OGRDB2Layer::StartTransaction()

{
    poDS->GetSession()->BeginTransaction();
    return OGRERR_NONE;
}

/************************************************************************/
/*                         CommitTransaction()                          */
/************************************************************************/

OGRErr OGRDB2Layer::CommitTransaction()

{
    poDS->GetSession()->CommitTransaction();
    return OGRERR_NONE;
}

/************************************************************************/
/*                        RollbackTransaction()                         */
/************************************************************************/

OGRErr OGRDB2Layer::RollbackTransaction()

{
    poDS->GetSession()->RollbackTransaction();
    return OGRERR_NONE;
}

/************************************************************************/
/*                           GetSpatialRef()                            */
/************************************************************************/

OGRSpatialReference *OGRDB2Layer::GetSpatialRef()

{
//CPLDebug("OGR_DB2Layer::GetSpatialRef", "nSrsId: %d", nSRSId);
    if( poSRS == nullptr && nSRSId > 0 )
    {
        poSRS = poDS->FetchSRS( nSRSId );
        if( poSRS != nullptr )
            poSRS->Reference();
        else
            nSRSId = 0;
    }

    return poSRS;
}

/************************************************************************/
/*                            GetFIDColumn()                            */
/************************************************************************/

const char *OGRDB2Layer::GetFIDColumn()

{
    GetLayerDefn();

    if( pszFIDColumn != nullptr )
        return pszFIDColumn;
    else
        return "";
}

/************************************************************************/
/*                         GetGeometryColumn()                          */
/************************************************************************/

const char *OGRDB2Layer::GetGeometryColumn()

{
    GetLayerDefn();

    if( pszGeomColumn != nullptr )
        return pszGeomColumn;
    else
        return "";
}

/************************************************************************/
/*                        GByteArrayToHexString()                       */
/************************************************************************/

char* OGRDB2Layer::GByteArrayToHexString( const GByte* pabyData, int nLen)
{
    char* pszTextBuf;
    const size_t nBufLen = nLen*2+3;

    pszTextBuf = (char *) CPLMalloc(nBufLen);

    int  iSrc, iDst=0;

    for( iSrc = 0; iSrc < nLen; iSrc++ )
    {
        if( iSrc == 0 )
        {
            snprintf( pszTextBuf+iDst, nBufLen - iDst, "0x%02x", pabyData[iSrc] );
            iDst += 4;
        }
        else
        {
            snprintf( pszTextBuf+iDst, nBufLen - iDst, "%02x", pabyData[iSrc] );
            iDst += 2;
        }
    }
    pszTextBuf[iDst] = 0;

    return pszTextBuf;
}


text:
<?php
/**
 *
 */

namespace Mvc5\Route\Match\Scheme;

use Mvc5\Route\Definition\Definition;
use Mvc5\Route\Route;

class Scheme
    implements MatchScheme
{
    /**
     * @param Route $route
     * @param Definition $definition
     * @return Route
     */
    public function __invoke(Route $route, Definition $definition)
    {
        return !$definition->scheme() || in_array($route->scheme(), (array) $definition->scheme()) ? $route : null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
FOUNDATION_EXPORT double Pods_Swoxy_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Swoxy_ExampleVersionString[];


text:
module ShouldCompile where

data T a = T a

instance Eq (T a) where
  (==) x y = let v :: a
		 v = undefined
	     in
		v


text:
// -*- C++ -*-
#ifndef EVENT_LCRELATIONNAVIGATORIMPL_H
#define EVENT_LCRELATIONNAVIGATORIMPL_H 1

#include <vector>
#include <map>
#include "EVENT/LCObject.h"
#include "EVENT/LCCollection.h"
#include "LCIOSTLTypes.h"

namespace UTIL {

  /** The LCRelationNavigator makes repeated lookup of relations more conveneient and efficient.
   * The relations are treated symmetrical, i.e. lookup of relations is equally efficient and
   * fast for either direction (from-to and to-from)
   *  at the price of a slower (by a factor of ~2) modification speed.
   *
   * @author gaede
   * @version $Id: LCRelationNavigator.h,v 1.2 2004-09-06 14:35:51 gaede Exp $
   */

  class LCRelationNavigator {

    typedef std::map< EVENT::LCObject* , std::pair< EVENT::LCObjectVec , EVENT::FloatVec > > RelMap ;

  public:

    /** Default constructor
     */
    LCRelationNavigator(const std::string &fromType, const std::string &toType) :
      _from( fromType ),
      _to( toType )  { /* nop */; }

    /**Create the navigator object from an existing collection of relations
     */
    LCRelationNavigator( const EVENT::LCCollection* col ) ;

    /// Destructor.
    virtual ~LCRelationNavigator() { /* nop */; }

    /**The type of the 'from' objects in this relation.
     */
    virtual const std::string & getFromType() const ;

    /**The type of the 'to' objects in this relation.
     */
    virtual const std::string & getToType() const ;

    /** All objects that the given from-object is related to.
     *  LCObjects are of type getToType().
     */
    virtual const EVENT::LCObjectVec & getRelatedToObjects(EVENT::LCObject * from) const ;

    /** All from-objects related to the given object ( the  inverse relationship).
     *  LCObjects are of type getFromType().
     */
    virtual const EVENT::LCObjectVec & getRelatedFromObjects(EVENT::LCObject * to) const ;

    /** The weights of the relations returned by  a call to getRelatedToObjects(from).
     * @see getRelatedToObjects
     */
    virtual const EVENT::FloatVec & getRelatedToWeights(EVENT::LCObject * from) const ;

    /** The weights of the relations returned by  a call to getRelatedFromObjects(to).
     * @see getRelatedFromObjects
     */
    virtual const EVENT::FloatVec & getRelatedFromWeights(EVENT::LCObject * to) const ;

    /** Adds a relation. If there is already an existing relation between the two given objects
     * the weight (or default weight 1.0) is added to that relationship's weight.
     */
    virtual void addRelation(EVENT::LCObject * from, EVENT::LCObject * to, float weight = 1.0) ;

    /** Remove a given relation.
     */
    virtual void removeRelation(EVENT::LCObject * from, EVENT::LCObject * to) ;

    /** Remove a given relation. To reduce the weight of the relationship, call
     *  addRelation( from, to, weight  ) with  weight<0.
     */
    virtual EVENT::LCCollection * createLCCollection() ;

  protected:

    LCRelationNavigator() ;

    virtual void initialize( const EVENT::LCCollection* col ) ;

    void removeRelation(EVENT::LCObject * from, EVENT::LCObject * to, RelMap& map ) ;
    void addRelation(EVENT::LCObject * from, EVENT::LCObject * to, float weight, RelMap& map) ;

    mutable RelMap _map{} ;
    mutable RelMap _rMap{} ;
    std::string _from ;
    std::string _to ;

}; // class
} // namespace EVENT
#endif /* ifndef EVENT_LCRELATIONNAVIGATOR_H */


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Index page » A page » Subpage | A Pelican Blog</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i" />
  <link rel="stylesheet" href="static/m-dark.css" />
  <link rel="canonical" href="subpage.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta property="og:site_name" content="A Pelican Blog" />
  <meta property="og:title" content="Subpage" />
  <meta name="twitter:title" content="Subpage" />
  <meta property="og:url" content="subpage.html" />
  <meta name="twitter:card" content="summary" />
  <meta property="og:type" content="page" />

      A Pelican Blog

            Index page »
            A page »

          Subpage


text:
<%#
 Copyright 2013-2018 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see http://www.jhipster.tech/
 for more information.

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

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse<% if (authenticationType !== 'oauth2') { %>, HttpHeaders<% } %> } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { SERVER_API_URL } from '../../app.constants';

@Injectable()
export class AuthServerProvider {

    constructor(
        private http: HttpClient
    ) {}
<%_ if (authenticationType !== 'oauth2') { _%>

    login(credentials): Observable<any> {
        const data = 'j_username=' + encodeURIComponent(credentials.username) +
            '&j_password=' + encodeURIComponent(credentials.password) +
            '&remember-me=' + credentials.rememberMe + '&submit=Login';
        const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');

        return this.http.post(SERVER_API_URL + 'api/authentication', data, { headers });
    }
<%_ } _%>

    logout(): Observable<any> {
        // logout from the server
        return this.http.post(SERVER_API_URL + 'api/logout', {}, { observe: 'response' }).map((response: HttpResponse<any>) => {
            // to get a new csrf token call the api
            this.http.get(SERVER_API_URL + 'api/account').subscribe(() => {}, () => {});
            return response;
        });
    }
}


text:
#ifndef _PTHREAD_CONDATTR_T
#define _PTHREAD_CONDATTR_T
typedef __darwin_pthread_condattr_t pthread_condattr_t;
#endif /* _PTHREAD_CONDATTR_T */


text:
package com.navercorp.pinpoint.profiler.sender;

import com.navercorp.pinpoint.bootstrap.context.TraceId;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.profiler.context.SpanChunkFactoryV1;
import com.navercorp.pinpoint.profiler.context.id.DefaultTraceRoot;
import com.navercorp.pinpoint.profiler.context.id.DefaultTraceId;
import com.navercorp.pinpoint.profiler.context.Span;
import com.navercorp.pinpoint.profiler.context.SpanChunk;
import com.navercorp.pinpoint.profiler.context.SpanChunkFactory;
import com.navercorp.pinpoint.profiler.context.SpanEvent;
import com.navercorp.pinpoint.profiler.context.id.DefaultTransactionIdEncoder;
import com.navercorp.pinpoint.profiler.context.id.TraceRoot;
import com.navercorp.pinpoint.profiler.context.id.TransactionIdEncoder;
import com.navercorp.pinpoint.thrift.dto.TSpan;
import com.navercorp.pinpoint.thrift.dto.TSpanChunk;
import com.navercorp.pinpoint.thrift.dto.TSpanEvent;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseDeserializer;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseDeserializerFactory;
import com.navercorp.pinpoint.thrift.io.HeaderTBaseSerializerFactory;
import org.apache.thrift.TException;
import org.junit.Assert;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Taejin Koo
 */
public class SpanStreamSendDataSerializerTest {

    private final String agentId = "agentId";
    private final long agentStartTime = System.currentTimeMillis();
    private final TransactionIdEncoder encoder = new DefaultTransactionIdEncoder(agentId, agentStartTime);

    private final SpanChunkFactory spanChunkFactory
            = new SpanChunkFactoryV1("applicationName", agentId, agentStartTime, ServiceType.STAND_ALONE, encoder);

    private TraceRoot newInternalTraceId() {

        TraceId traceId = new DefaultTraceId(agentId, agentStartTime, 100);
        return new DefaultTraceRoot(traceId, agentId, agentStartTime, 100);
    }

    @Test
    public void spanStreamSendDataSerializerTest1() throws InterruptedException, TException {
        int spanEventSize = 10;

        SpanStreamSendDataSerializer serializer = new SpanStreamSendDataSerializer();

        HeaderTBaseSerializerFactory factory = new HeaderTBaseSerializerFactory();

        SpanChunk spanChunk = spanChunkFactory.create(newInternalTraceId(), createSpanEventList(spanEventSize));
        PartitionedByteBufferLocator partitionedByteBufferLocator = serializer.serializeSpanChunkStream(factory.createSerializer(), spanChunk);

        Assert.assertEquals(spanEventSize + 1, partitionedByteBufferLocator.getPartitionedCount());

        HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer();

        for (int i = 0; i < partitionedByteBufferLocator.getPartitionedCount(); i++) {
            ByteBuffer byteBuffer = partitionedByteBufferLocator.getByteBuffer(i);

            byte[] readBuffer = new byte[byteBuffer.remaining()];

            byteBuffer.get(readBuffer);

            Object o = deserializer.deserialize(readBuffer);

            if (o == null) {
                Assert.fail();
            }

            if (i < spanEventSize) {
                Assert.assertTrue(o instanceof TSpanEvent);
            } else {
                Assert.assertTrue(o instanceof TSpanChunk);
            }
        }
    }

    @Test
    public void spanStreamSendDataSerializerTest2() throws InterruptedException, TException {
        int spanEventSize = 10;

        SpanStreamSendDataSerializer serializer = new SpanStreamSendDataSerializer();

        HeaderTBaseSerializerFactory factory = new HeaderTBaseSerializerFactory();

        Span span = createSpan(createSpanEventList(spanEventSize));
        PartitionedByteBufferLocator partitionedByteBufferLocator = serializer.serializeSpanStream(factory.createSerializer(), span);

        Assert.assertEquals(spanEventSize + 1, partitionedByteBufferLocator.getPartitionedCount());

        HeaderTBaseDeserializer deserializer = new HeaderTBaseDeserializerFactory().createDeserializer();

        for (int i = 0; i < partitionedByteBufferLocator.getPartitionedCount(); i++) {
            ByteBuffer byteBuffer = partitionedByteBufferLocator.getByteBuffer(i);

            byte[] readBuffer = new byte[byteBuffer.remaining()];

            byteBuffer.get(readBuffer);

            Object o = deserializer.deserialize(readBuffer);

            if (o == null) {
                Assert.fail();
            }

            if (i < spanEventSize) {
                Assert.assertTrue(o instanceof TSpanEvent);
            } else {
                Assert.assertTrue(o instanceof TSpan);
            }
        }
    }

    private Span createSpan(List<SpanEvent> spanEventList) {
        TraceRoot traceRoot = newInternalTraceId();

        final Span span = new Span(traceRoot);
        for (SpanEvent spanEvent : spanEventList) {
            span.addToSpanEventList(spanEvent);
        }

        span.setAgentId("agentId");
        return span;
    }

    private List<SpanEvent> createSpanEventList(int size) throws InterruptedException {

        TraceRoot traceRoot = newInternalTraceId();

        Span span = new Span(traceRoot);
        List<SpanEvent> spanEventList = new ArrayList<SpanEvent>(size);
        for (int i = 0; i < size; i++) {
            SpanEvent spanEvent = new SpanEvent(traceRoot);
            spanEvent.markStartTime();
            Thread.sleep(1);
            spanEvent.markAfterTime();

            spanEventList.add(spanEvent);
        }

        return spanEventList;
    }

}


text:
package org.kohsuke.stapler;

import java.util.Map;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.HashMap;

/**
 * The stapler version of the {@link ClassLoader} object,
 * that retains some useful cache about a class loader.
 *
 * @author Kohsuke Kawaguchi
 */
public class MetaClassLoader extends TearOffSupport {
    public final MetaClassLoader parent;
    public final ClassLoader loader;

    public MetaClassLoader(ClassLoader loader) {
        this.loader = loader;
        this.parent = get(loader.getParent());
    }

    public static MetaClassLoader get(ClassLoader cl) {
        if(cl ==null)
            return null; // if no parent, delegate to the debug loader if available.

        synchronized(classMap) {
            MetaClassLoader mc = classMap.get(cl);
            if(mc==null) {
                mc = new MetaClassLoader(cl);
                classMap.put(cl,mc);
            }
            return mc;
        }
    }

    /**
     * If non-null, delegate to this classloader.
     */
    public static MetaClassLoader debugLoader = null;

    /**
     * All {@link MetaClass}es.
     *
     * Note that this permanently holds a strong reference to its key, i.e. is a memory leak.
     */
    private static final Map<ClassLoader,MetaClassLoader> classMap = new HashMap<ClassLoader,MetaClassLoader>();

    static {
        try {
            String path = System.getProperty("stapler.resourcePath");
            if(path!=null) {
                String[] tokens = path.split(";");
                URL[] urls = new URL[tokens.length];
                for (int i=0; i<tokens.length; i++)
                    urls[i] = new File(tokens[i]).toURI().toURL();
                debugLoader = new MetaClassLoader(new URLClassLoader(urls));
            }
        } catch (MalformedURLException e) {
            throw new Error(e);
        }
    }
}


text:
module Hackbot
  module Interactions
    class Command < TextConversation
      def self.usage(event, team)
        new(event: event, team: team).usage
      end

      def self.description(event, team)
        new(event: event, team: team).description
      end

      def should_start?
        # We have to use self.class:: to access the constant because of the
        # quirk described in this StackOverflow question:
        #
        # http://stackoverflow.com/q/42779998/1001686
        trigger = self.class::TRIGGER
        mention_regex = Hackbot::Utterances.name(team)

        if in_dm?
          msg =~ /^(#{mention_regex} )?#{trigger}$/ && super
        else
          msg =~ /^#{mention_regex} #{trigger}$/ && super
        end
      end

      def captured
        @_captured ||= self.class::TRIGGER.match(msg)
      end

      def usage
        self.class::USAGE if self.class.const_defined? 'USAGE'
      end

      def description
        self.class::DESCRIPTION if self.class.const_defined? 'DESCRIPTION'
      end
    end
  end
end


text:
#ifndef EGLSURFACE_INCLUDED
#define EGLSURFACE_INCLUDED

#include "egltypedefs.h"
#include "egldisplay.h"

/**
 * "Base" class for device driver surfaces.
 */
struct _egl_surface
{
   /* A surface is a display resource */
   _EGLResource Resource;

   /* The context that is currently bound to the surface */
   _EGLContext *CurrentContext;

   _EGLConfig *Config;

   EGLint Type; /* one of EGL_WINDOW_BIT, EGL_PIXMAP_BIT or EGL_PBUFFER_BIT */

   /* attributes set by attribute list */
   EGLint Width, Height;
   EGLenum TextureFormat;
   EGLenum TextureTarget;
   EGLBoolean MipmapTexture;
   EGLBoolean LargestPbuffer;
   EGLenum RenderBuffer;
   EGLenum VGAlphaFormat;
   EGLenum VGColorspace;

   /* attributes set by eglSurfaceAttrib */
   EGLint MipmapLevel;
   EGLenum MultisampleResolve;
   EGLenum SwapBehavior;

   EGLint HorizontalResolution, VerticalResolution;
   EGLint AspectRatio;

   EGLint SwapInterval;

   /* True if the surface is bound to an OpenGL ES texture */
   EGLBoolean BoundToTexture;
};

PUBLIC EGLBoolean
_eglInitSurface(_EGLSurface *surf, _EGLDisplay *dpy, EGLint type,
                _EGLConfig *config, const EGLint *attrib_list);

extern EGLBoolean
_eglSwapBuffers(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf);

extern EGLBoolean
_eglCopyBuffers(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLNativePixmapType target);

extern EGLBoolean
_eglQuerySurface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLint attribute, EGLint *value);

extern _EGLSurface *
_eglCreateWindowSurface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLConfig *conf, EGLNativeWindowType window, const EGLint *attrib_list);

extern _EGLSurface *
_eglCreatePixmapSurface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLConfig *conf, EGLNativePixmapType pixmap, const EGLint *attrib_list);

extern _EGLSurface *
_eglCreatePbufferSurface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLConfig *conf, const EGLint *attrib_list);

extern EGLBoolean
_eglDestroySurface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf);

extern EGLBoolean
_eglSurfaceAttrib(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLint attribute, EGLint value);

PUBLIC extern EGLBoolean
_eglBindTexImage(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLint buffer);

extern EGLBoolean
_eglReleaseTexImage(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLint buffer);

extern EGLBoolean
_eglSwapInterval(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf, EGLint interval);

#ifdef EGL_VERSION_1_2

extern _EGLSurface *
_eglCreatePbufferFromClientBuffer(_EGLDriver *drv, _EGLDisplay *dpy,
                                  EGLenum buftype, EGLClientBuffer buffer,
                                  _EGLConfig *conf, const EGLint *attrib_list);

#endif /* EGL_VERSION_1_2 */

/**
 * Return true if there is a context bound to the surface.
 *
 * The binding is considered a reference to the surface.  Drivers should not
 * destroy a surface when it is bound.
 */
static INLINE EGLBoolean
_eglIsSurfaceBound(_EGLSurface *surf)
{
   return (surf->CurrentContext != NULL);
}

/**
 * Link a surface to a display and return the handle of the link.
 * The handle can be passed to client directly.
 */
static INLINE EGLSurface
_eglLinkSurface(_EGLSurface *surf, _EGLDisplay *dpy)
{
   _eglLinkResource(&surf->Resource, _EGL_RESOURCE_SURFACE, dpy);
   return (EGLSurface) surf;
}

/**
 * Unlink a linked surface from its display.
 * Accessing an unlinked surface should generate EGL_BAD_SURFACE error.
 */
static INLINE void
_eglUnlinkSurface(_EGLSurface *surf)
{
   _eglUnlinkResource(&surf->Resource, _EGL_RESOURCE_SURFACE);
}

/**
 * Lookup a handle to find the linked surface.
 * Return NULL if the handle has no corresponding linked surface.
 */
static INLINE _EGLSurface *
_eglLookupSurface(EGLSurface surface, _EGLDisplay *dpy)
{
   _EGLSurface *surf = (_EGLSurface *) surface;
   if (!dpy || !_eglCheckResource((void *) surf, _EGL_RESOURCE_SURFACE, dpy))
      surf = NULL;
   return surf;
}

/**
 * Return the handle of a linked surface, or EGL_NO_SURFACE.
 */
static INLINE EGLSurface
_eglGetSurfaceHandle(_EGLSurface *surf)
{
   _EGLResource *res = (_EGLResource *) surf;
   return (res && _eglIsResourceLinked(res)) ?
      (EGLSurface) surf : EGL_NO_SURFACE;
}

/**
 * Return true if the surface is linked to a display.
 *
 * The link is considered a reference to the surface (the display is owning the
 * surface).  Drivers should not destroy a surface when it is linked.
 */
static INLINE EGLBoolean
_eglIsSurfaceLinked(_EGLSurface *surf)
{
   _EGLResource *res = (_EGLResource *) surf;
   return (res && _eglIsResourceLinked(res));
}

#endif /* EGLSURFACE_INCLUDED */


text:
"""Regression test suite for CherryPy.

Run test.py to exercise all tests.
"""


text:
package io.mycat.server.response;

import io.mycat.MycatServer;
import io.mycat.server.ErrorCode;
import io.mycat.server.MySQLFrontConnection;
import io.mycat.server.config.loader.ReloadUtil;
import io.mycat.server.packet.OkPacket;

import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

/**
 * @author mycat
 */
public final class RollbackCallBack {
	private static final Logger LOGGER = Logger.getLogger(RollbackCallBack.class);

	public static void execute(MySQLFrontConnection c) {
		final ReentrantLock lock = MycatServer.getInstance().getConfig().getLock();
		lock.lock();
		try {
			if (ReloadUtil.rollback()) {
				StringBuilder s = new StringBuilder();
				s.append(c).append("Rollback config success by manager");
				LOGGER.warn(s.toString());
				OkPacket ok = new OkPacket();
				ok.packetId = 1;
				ok.affectedRows = 1;
				ok.serverStatus = 2;
				ok.message = "Rollback config success".getBytes();
				ok.write(c);
			} else {
				c.writeErrMessage(ErrorCode.ER_YES, "Rollback config failure");
			}
		} finally {
			lock.unlock();
		}
	}

}


text:
package cn.itdeer.common.security;

import cn.itdeer.modules.admin.security.entity.Role;
import cn.itdeer.modules.admin.security.entity.User;
import cn.itdeer.modules.admin.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

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

/**
 * 描述:自定义用户Service
 * 创建人:Itdeer
 * 创建时间:2017/10/9 21:51
 */

@Service
public class CustomUserService implements UserDetailsService{

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findByUserName(username);
        if(user == null){
            throw new UsernameNotFoundException("登录账户不存在");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

      /* for(Role role : user.getRoles()){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }*/

        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),authorities);
    }
}


text:
package id.ac.tazkia.dosen.dao;

import id.ac.tazkia.dosen.entity.Dosen;
import id.ac.tazkia.dosen.entity.Jabatan;
import id.ac.tazkia.dosen.entity.KategoriKegiatan;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by yogi on 04/05/2017.
 */

@Repository
public interface KategoriKegiatanDao extends PagingAndSortingRepository<KategoriKegiatan, String> {
    KategoriKegiatan findOneByNamaIgnoreCase(String nama);
    Page<KategoriKegiatan> findByNamaContainingIgnoreCase(String nama, Pageable p);
}


text:
module TreeNode
  class ScanItemSet < Node
  end
end


text:
require 'rubygems'
require 'capybara/rspec'
require 'wine_scraper'
require 'fakeweb'

FakeWeb.register_uri(:get, "http://www.thecorkscrew.ie/red-wine.html?limit=all",
                     :body => File.open(File.dirname(__FILE__) + '/support/fixtures/corkscrew-red.html').read,
                     :status => ["200", "Ok"])


text:
static void DeserializeBlockTest(benchmark::State& state)
{
    CDataStream stream(benchmark::data::block2680960, SER_NETWORK, PROTOCOL_VERSION);
    char a = '\0';
    stream.write(&a, 1); // Prevent compaction

    while (state.KeepRunning()) {
        CBlock block;
        stream >> block;
        bool rewound = stream.Rewind(benchmark::data::block2680960.size());
        assert(rewound);
    }
}

static void DeserializeAndCheckBlockTest(benchmark::State& state)
{
    CDataStream stream(benchmark::data::block2680960, SER_NETWORK, PROTOCOL_VERSION);
    char a = '\0';
    stream.write(&a, 1); // Prevent compaction

    SelectParams(CBaseChainParams::MAIN);

    while (state.KeepRunning()) {
        CBlock block; // Note that CBlock caches its checked state, so we need to recreate it here
        stream >> block;
        bool rewound = stream.Rewind(benchmark::data::block2680960.size());
        assert(rewound);

        CValidationState state;
        assert(CheckBlock(block, state));
    }
}

BENCHMARK(DeserializeBlockTest, 130);
BENCHMARK(DeserializeAndCheckBlockTest, 160);


text:
<!doctype html>

	<title>jQuery UI Draggable - Constrain movement</title>
	<link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />

	<link type="text/css" href="../demos.css" rel="stylesheet" />

Constrain movement along an axis:

I can be dragged only vertically

I can be dragged only horizontally

Or to within another DOM element:

I'm contained within the box

I'm contained within the box's parent

I'm contained within my parent

Constrain the movement of each draggable by defining the boundaries of the draggable area. Set the axis option to limit the draggable's path to the x- or y-axis, or use the containment option to specify a parent DOM element or a jQuery selector, like 'document.'


text:
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {EffectsModule} from '@ngrx/effects';
import {StoreModule} from '@ngrx/store';
import {PluginRegistryModule} from '../plugin_registry_module';
import {TextV2DataSourceModule} from './data_source/text_v2_data_source_module';
import {TextEffects} from './effects/text_effects';
import {TEXT_FEATURE_KEY} from './store';
import {reducers} from './store/text_v2_reducers';
import {TextDashboardComponent} from './views/text_dashboard/text_dashboard_component';
import {TextDashboardModule} from './views/text_dashboard/text_dashboard_module';

@NgModule({
  imports: [
    CommonModule,
    TextDashboardModule,
    PluginRegistryModule.forPlugin('text_v2', TextDashboardComponent),
    TextV2DataSourceModule,
    StoreModule.forFeature(TEXT_FEATURE_KEY, reducers),
    EffectsModule.forFeature([TextEffects]),
  ],
  entryComponents: [TextDashboardComponent],
})
export class TextV2Module {}


text:
<!DOCTYPE HTML>

<title>LinearArgument (com.google.ortools:ortools-java 9.4.1874 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package com.google.ortools.sat

Interface LinearArgument

All Known Subinterfaces:

LinearExpr, Literal

All Known Implementing Classes:

AffineExpression, BoolVar, ConstantExpression, IntVar, LinearExprBuilder, NotBoolVar, WeightedSumExpression

public interface LinearArgument

A object that can build a LinearExpr object.

This class is used in all modeling methods of the CpModel class.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method
Description

LinearExpr
build()

Builds a linear expression.

Method Detail

build

LinearExpr build()

Builds a linear expression.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2022. All rights reserved.


text:
package discordbot.command;

/**
 * Indicating that a command has data/cache to clean up after a while
 */
public interface ICommandCleanup {
    /**
     * This method is called in the cleanup service {@see discordbot.service.BotCleanupService}
     * to clean up cached data
     */
    public void cleanup();
}


text:
<!DOCTYPE html>

        <title>Weather popup</title>
        <link rel="stylesheet" href="dist/main.css" type="text/css">

            No location set

                    <button class="units-btn active" data-units="metric" type="button">°C</button>
                    <button class="units-btn" data-units="imperial" type="button">°F</button>
                    <button id="refresh">Refresh</button>

Change location

                    <input id="location-input" type="text" placeholder="e.g. Delhi, IN">
                    <button id="search">

                    </button>

Search for a location and select from those shown below. For increased accuracy, include a two character country code

Please select a location from the menu in the top right corner.

Unable to update data.


text:
package org.opencb.opencga.test.config;

public class Logger {

    private String logLevel;

    public Logger() {
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Logger{\n");
        sb.append("logLevel='").append(logLevel).append('\'').append("\n");
        sb.append("}\n");
        return sb.toString();
    }

    public String getLogLevel() {
        return logLevel;
    }

    public Logger setLogLevel(String logLevel) {
        this.logLevel = logLevel;
        return this;
    }
}


text:
package org.protempa.proposition.value;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;

import junit.framework.TestCase;

/**
 * Test cases for RelativeHourUnit.
 *
 * @author Andrew Post
 */
public class RelativeHourUnitTest extends TestCase {

	@Override
	protected void setUp() throws Exception {
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void testGetDurationInHours() {
		assertEquals(2, Math.round(RelativeHourUnit.HOUR
				.length(2 * 60 * 1000 * 60)));
	}

	public void testSerializable() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(bytes);
		out.writeObject(RelativeHourUnit.HOUR);
		out.close();

		ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
				bytes.toByteArray()));
		Unit unit = (Unit) in.readObject();
		assertEquals(RelativeHourUnit.HOUR, unit);
		in.close();
	}

	public void testReallyLongDuration() {
		assertEquals(596, RelativeHourUnit.HOUR.length(Integer.MAX_VALUE));
	}

	public void testDistanceBetween20Hours() throws ParseException {
		assertEquals(20, RelativeHourGranularity.HOUR.distance(0L,
				20L * 60 * 60 * 1000, RelativeHourGranularity.HOUR,
				RelativeHourUnit.HOUR));
	}
}


text:
package org.keycloak.testsuite.servletauthz;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import org.keycloak.util.JsonSerialization;

/**
 * @author Pedro Igor
 */
public class TestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getRequestURI().endsWith("/body")) {
            Map body = JsonSerialization.readValue(request.getInputStream(), Map.class);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.println(JsonSerialization.writeValueAsString(body));
            writer.flush();
        }
    }

    @Override
    public void destroy() {

    }

}


text: pip install invisibleroads-macros-disk openpyxl pandas


text:
<?php

require_once '../ThumbLib.inc.php';

$thumb = PhpThumbFactory::create('test.jpg');
$thumb->resizePercent(50);
$thumb->show();

?>


text:
ESLINT_RAILS_DIR=$(pwd)
PLUGINS=(yannickcr/eslint-plugin-react) # Add new plugins here.
GIT_URL_PREFIX="git@github.com:"
GIT_URL_SUFFIX=".git"

mkdir -p /tmp/eslint-rails-plugins
cd /tmp/eslint-rails-plugins

for plugin in ${PLUGINS[@]}; do
  git_url=$GIT_URL_PREFIX$plugin$GIT_URL_SUFFIX
  git clone $git_url
  plugin_name=$(basename $git_url .git)
  cd $plugin_name
  npm install
  browserify index.js -o $plugin_name.js
  cp $plugin_name.js $ESLINT_RAILS_DIR/vendor/assets/javascripts/plugins/
done

rm -rf /tmp/eslint-rails-plugins


text:
RCPT="changethis@example.com"

# -----------------------------------------------------------------------
# INIT Logging: we don't know HOME yet, log into tmpfile
# -----------------------------------------------------------------------
LOG="$(mktemp -t gpgmailer)"

exec >>"${LOG}"
exec 2>>"${LOG}"
#set -x

# -----------------------------------------------------------------------
# get USER and HOME as we're going to have an empty environment
# -----------------------------------------------------------------------
OIFS="${IFS}"
IFS=":"
# ensure pathname expansion disabled here (noglob) as the second field
# from passwd will be `*' in most cases!  /bin/sh -f
set -- $(getent passwd $(whoami))
IFS="${OIFS}"
USER="${1}"
HOME="${6}"

# -----------------------------------------------------------------------
# environment done, now set up directories and files
# -----------------------------------------------------------------------
BASEDIR="${HOME}/.gpgmailer/"
INCOMING="${BASEDIR}/incoming/"

LOGDIR=${BASEDIR}/log/
OLDLOG="${LOG}"
LOG="${LOGDIR}/gpgmailer.log"

NOW="$(date "+%Y%m%d%H%M%S")"
HOST="$(hostname -f)"

mkdir -pv "${BASEDIR}" "${LOGDIR}" "${INCOMING}" ||
	exit 128
chmod 700 "${BASEDIR}" "${LOGDIR}" "${INCOMING}"
touch "${LOG}" ||
	exit 128
chmod 600 "${LOG}"

# continue loggin into ${LOG}
exec >>"${LOG}"
exec 2>>"${LOG}"
cat "${OLDLOG}" >> "${LOG}" &&
	rm "${OLDLOG}"

ENC_TMP="$(mktemp "${INCOMING}/${HOST}_${USER}_${NOW}_XXXXXX")"
ENC_FILE="${ENC_TMP}.asc"

test -f "${ENC_TMP}" ||
	{ echo "Cannot create tmpfile ${ENC_TMP}" >&2; exit 128; }

# we need just the temporary filename,
# gpg2 wont override existing files, so remove it here
rm "${ENC_TMP}" ||
	exit 1

# -----------------------------------------------------------------------
# init and logging done, now receive from stdin
# -----------------------------------------------------------------------

/usr/local/bin/gpg --no-secmem-warning --armor --recipient "${RCPT}" --output "${ENC_TMP}" --encrypt &&
	mv -v "${ENC_TMP}" "${ENC_FILE}"


text:
using System;

namespace Orleans.Serialization.TypeSystem
{
    /// <summary>
    /// Type which allows any exception type to be resolved.
    /// </summary>
    public sealed class DefaultTypeFilter : ITypeFilter
    {
        public bool? IsTypeNameAllowed(string typeName, string assemblyName)
        {
            if (assemblyName is { } && assemblyName.Contains("Orleans.Serialization"))
            {
                return true;
            }

            if (typeName.EndsWith(nameof(Exception)))
            {
                return true;
            }

            if (typeName.StartsWith("System."))
            {
                if (typeName.EndsWith("Comparer"))
                {
                    return true;
                }

                if (typeName.StartsWith("System.Collections."))
                {
                    return true;
                }

                if (typeName.StartsWith("System.Net.IP"))
                {
                    return true;
                }
            }

            return null;
        }
    }
}


text:
TEST_CLASS(VariantFilterAnnotations_Test)
{
Q_OBJECT
private slots:

	void no_filter()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters1.txt") + " -out out/VariantFilterAnnotations_out1.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out1.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out1.GSvar"));
	}

	void maxAf()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters2.txt") + " -out out/VariantFilterAnnotations_out2.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out2.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out2.GSvar"));
	}

	void impact_ihdb()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters3.txt") + " -out out/VariantFilterAnnotations_out3.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out3.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out3.GSvar"));
	}

	void class_filters_genoAffected()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters4.txt") + " -out out/VariantFilterAnnotations_out4.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out4.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out4.GSvar"));
	}

	void maxSubAf()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters5.txt") + " -out out/VariantFilterAnnotations_out5.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out5.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out5.GSvar"));
	}

	void multisample_maxAf_dominant()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in_multi.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters6.txt") + " -out out/VariantFilterAnnotations_out6.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out6.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out6.GSvar"));
	}

	void multisample_maxAf_recessive()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in_multi.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters7.txt") + " -out out/VariantFilterAnnotations_out7.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out7.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out7.GSvar"));
	}

	void multisample_notWT()
	{
		EXECUTE("VariantFilterAnnotations", "-in " + TESTDATA("data_in/VariantFilterAnnotations_in_multi.GSvar") + " -filters " + TESTDATA("data_in/VariantFilterAnnotations_filters8.txt") + " -out out/VariantFilterAnnotations_out8.GSvar");
		COMPARE_FILES("out/VariantFilterAnnotations_out8.GSvar", TESTDATA("data_out/VariantFilterAnnotations_out8.GSvar"));
	}

};


text:
describe('touchtap-event', function () {
  'use strict';

  describe('on a page with a abbr single element', function () {
    var elem;

    beforeEach(function () {
      elem = document.createElement('abbr');
      elem.title = 'test';
      document.body.appendChild(elem);
    });

    afterEach(function () {
      document.body.removeChild(elem);
    });

    it('should trigger the alert after a 10ms wait', function (done) {
      elem.addEventListener('touchtap', function (e) {
        expect(e.target).toBe(elem);
        done();
      });

      var event = document.createEvent('TouchEvent');
      event.initUIEvent('touchstart', true, true);
      elem.dispatchEvent(event, {
        pageX: 0,
        pageY: 0
      });

      setTimeout(function () {
        event = document.createEvent('TouchEvent');
        event.initUIEvent('touchend', true, true);
        elem.dispatchEvent(event);
      }, 10);
    });

    it('should trigger the alert after a 150ms wait', function (done) {
      elem.addEventListener('touchtap', function (e) {
        expect(e.target).toBe(elem);
        done();
      });

      var event = document.createEvent('TouchEvent');
      event.initUIEvent('touchstart', true, true);
      elem.dispatchEvent(event, {
        pageX: 0,
        pageY: 0
      });

      setTimeout(function () {
        event = document.createEvent('TouchEvent');
        event.initUIEvent('touchend', true, true);
        elem.dispatchEvent(event);
      }, 150);
    });

    it('should not trigger the alert after a 250ms wait', function (done) {
      elem.addEventListener('touchtap', function () {
        expect(false).toBe(true);
      });

      var event = document.createEvent('TouchEvent');
      event.initUIEvent('touchstart', true, true);
      elem.dispatchEvent(event, {
        pageX: 0,
        pageY: 0
      });

      setTimeout(function () {
        event = document.createEvent('TouchEvent');
        event.initUIEvent('touchend', true, true);
        elem.dispatchEvent(event);
      }, 250);

      // Trigger end of test
      setTimeout(function () {
        done();
      }, 350);
    });

    describe('touching specific coordinates', function () {
      it('should dispatch the event with the coordinates attached', function () {
        elem.addEventListener('touchtap', function (e) {
          expect(e.target).toBe(elem);
          expect(e.customData.touchX).toBe(5);
          expect(e.customData.touchY).toBe(10);
          done();
        });

        var event = document.createEvent('TouchEvent');
        event.initUIEvent('touchstart', true, true);
        elem.dispatchEvent(event, {
          pageX: 5,
          pageY: 10
        });

        setTimeout(function () {
          event = document.createEvent('TouchEvent');
          event.initUIEvent('touchend', true, true);
          elem.dispatchEvent(event);
        }, 10);
      });
    });
  });
});


text:
'use strict';

/**
 * @ngdoc directive
 * @name redditAngularApp.directive:articleDate
 * @description
 * # articleDate
 * Directive for formatted display of article's creation date metadata.
 */
angular.module('redditAngularApp')
  .directive('articleDate', function () {
    return {
      templateUrl: 'views/article-date.html',
      scope: {
        article: '=article'
      },
      restrict: 'E'
    };
  });


text:
<ion-view title="{{'lbl_login' | translate}}" class="login" hide-nav-bar="true">
    <ion-content>

{{'signup_subtitle' | translate}}

{{'signup_title' | translate}}

                <input type="text" placeholder="{{'signup_name'|translate}}" ng-model="user.name">

                <input type="text" placeholder="{{'signup_surname'|translate}}" ng-model="user.surname">

                <input type="email" placeholder="{{'signup_email'|translate}}" ng-model="user.email">

                <input type="password" placeholder="{{'signup_pwd'|translate}}" ng-model="user.password">

              <button class="button button-block login-button-internal" ng-click="register()">

                    {{'signup_signup' | translate}}
              </button>
              <button class="button button-block login-button-signup" ui-sref="app.login">

                  {{'cancel' | translate}}
              </button>

    </ion-content>
</ion-view>


text:
> Yet another store utility for flux.

# Deprecation notice

flux-store-base is superseded by [floox](https://github.com/fatfisz/floox) which, apart form the shorter name, introduces a few new boilerplate reductions and a simple solution for circular dependency of stores.

It won't be maintained anymore.

## Getting Started

Install the package with this command:
```shell
npm install flux-store-base --save
```

Then you can require the package with `require('flux-store-base')`. Once you do that, you get two functions:

### FluxStoreBase.Store

`Store(dispatcher, config)` constructor configures the store using the provided [flux](https://github.com/facebook/flux) dispatcher and `config`, which is an object whose methods and properties will be assigned to the resulting store.
There are also some things going under the hood, but more about that below (see: Features).

### FluxStoreBase.inject

`inject(dispatcher)` returns a constructor which can be used to create stores without passing `dispatcher` every time. The resulting function has only one argument - `config`.

## Example

Action creator:
```js
function createSomeAction(someData) {
  AppDispatcher.dispatchSomeAction(someData);
}
```

Store:
```js
var Store = require('flux-store-base').Store;

var AppDispatcher = require('../dispatcher');

var MyFunkyStore = new Store(AppDispatcher, {

  displayName: 'MyFunkyStore',
  events: ['theChange'],

  getSomething() {
    return this.something;
  },

  onSomeAction(someData) {
    this.something = someData;
    this.emit('theChange');
  },

});

```

Component:
```js
var React = require('react');

var MyFunkyStore = require('./path-to-my-funky-store');

var MyFunkyComponent = React.createClass({

  componentDidMount() {
    MyFunkyStore.on('theChange', this.doSomething);
  },

  componentWillUnmount() {
    MyFunkyStore.off('theChange', this.doSomething);
  },

  doSomething() {
    // Set state or whatever. You know what to do.
  },

});
```

## Pro Tip: Inject the Dispatcher

Create a file (suggested name: `base.js`, contained in the store directory):
```js
var fluxStoreBase = require('flux-store-base');

var AppDispatcher = require('../dispatcher');

var Store = fluxStoreBase.inject(AppDispatcher);

module.exports = Store;
```

Now you can use the module like this, without requiring the dispatcher for each store:
```js
var Store = require('./base');

var MyFunkyStore = new Store({

  ...

});
```

## Features

### Display Name

The property `displayName` is used for errors. If it is absent, `displayName` will be `'anonymous'`.

### Actions

Each method in the `config` which starts with "on" and a capital letter, e. g. "onSomeAction" will be treated as an action handler.
That means:

* The dispatcher will have a new function added for dispatching (in this case "dispatchSomeAction"). The function will have one argument, which will be then passed to the matching "on-" action handlers as a sole argument.

### Dispatch Token

If any action handlers are detected ("on-" methods), the store will be registered in the dispatcher and will have a `dispatchToken` property added. It can be then used like this:

```js
AppDispatcher.waitFor([VeryFineStore.dispatchToken]);
```

### Events

There are two properties on `config` that can be used to configure events to which components can subscribe: `events` and `maxListeners`.
`events` is expected to be an array of strings (but can be left undefined).

Each of those strings is then used to construct three methods for the resulting store: emitter, subscriber and unsubscriber.
For event name `'theChange'` we will get emitter `emitTheChange`, subscriber `addTheChangeListener` and
unsubscriber `removeTheChangeListener`. As you can see, the name of the event is capitalized and incorporated into the new methods' names.

The emitter has no arguments - you should retrieve the data only from the store.
Subscriber and unsubscriber have one argument - event handler.

Also, methods `emit(event)`, `on(event, fn)` and `off(event, fn)` will be added to the store.

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style.

## License
Copyright (c) 2015 FatFisz. Licensed under the MIT license.


text:
using TestFramework.Abot.Core;
using TestFramework.Abot.Poco;
using TestFramework.Abot.Util;
using HtmlAgilityPack;
using System;

namespace TestFramework.WebChecker
{
    public class VideoTabIndexChecker : WebChecker
    {
        public VideoTabIndexChecker()
            : base()
        {
        }

        public VideoTabIndexChecker(CrawlConfiguration crawlConfiguration)
            : base(crawlConfiguration, null, null, null, null, null, null, null, null)
        {
        }

        public VideoTabIndexChecker(CrawlConfiguration crawlConfiguration, ICrawlDecisionMaker crawlDecisionMaker, IThreadManager threadManager, IScheduler scheduler, IPageRequester pageRequester, IHyperLinkParser hyperLinkParser, IMemoryManager memoryManager, IDomainRateLimiter domainRateLimiter, IRobotsDotTextFinder robotsDotTextFinder)
            : base(crawlConfiguration, crawlDecisionMaker, threadManager, scheduler, pageRequester, hyperLinkParser, memoryManager, domainRateLimiter, robotsDotTextFinder)
        {
        }

        protected override void CheckThePage(string uri, HtmlDocument htmlDocument, out string errorSource)
        {
            errorSource = string.Empty;
            try
            {
                foreach (var srcNode in htmlDocument.DocumentNode.SelectNodes("//iframe/@src"))
                {
                    if (srcNode.Attributes["src"].Value.Contains("channel"))
                    {
                        if (srcNode.ParentNode.Attributes["tabindex"] != null)
                        {
                            if (string.IsNullOrEmpty(srcNode.ParentNode.Attributes["tabindex"].Value) || srcNode.ParentNode.Attributes["tabindex"].Value != "0")
                            {
                                errorSource += srcNode.Attributes["src"].Value + ";";
                            }
                        }
                        else
                        {
                            errorSource = srcNode.Attributes["src"].Value + ";";
                        }
                    }
                }

                if (errorSource != string.Empty)
                {
                    _logger.InfoFormat("The following resources have video tab index issue on url {0}\r\n{1}", uri, errorSource.Substring(0, errorSource.Length - 1));
                    errorSource = string.Format("The following resources have video tab index issue on url {0}\r\n{1}\r\n", uri, errorSource.Substring(0, errorSource.Length - 1));
                }
            }
            catch (Exception e)
            {
                _logger.InfoFormat("Exception is thrown when checking video tab index issue on url {0} with message {1}", uri, e.Message);
                errorSource = string.Format("Exception is thrown when checking video tab index issue on url {0} with message {1}\r\n", uri, e.Message);
            }
        }
    }
}


text:
namespace weblayer {

DevToolsManagerDelegateAndroid::DevToolsManagerDelegateAndroid() = default;

DevToolsManagerDelegateAndroid::~DevToolsManagerDelegateAndroid() = default;

std::string DevToolsManagerDelegateAndroid::GetDiscoveryPageHTML() {
  const char html[] =
      ""
      "<title>WebLayer remote debugging</title>"
      "Please use chrome://inspect"
      ""
      "";
  return html;
}

bool DevToolsManagerDelegateAndroid::IsBrowserTargetDiscoverable() {
  return true;
}

}  // namespace weblayer


text:
namespace crnlib
{
   template <typename T>
   struct hasher
   {
      inline size_t operator() (const T& key) const { return static_cast<size_t>(key); }
   };

   template <typename T>
   struct bit_hasher
   {
      inline size_t operator() (const T& key) const { return static_cast<size_t>(fast_hash(&key, sizeof(key))); }
   };

   template <typename T>
   struct equal_to
   {
      inline bool operator()(const T& a, const T& b) const { return a == b;  }
   };

   // Important: The Hasher and Equals objects must be bitwise movable!
   template<typename Key, typename Value = empty_type, typename Hasher = hasher<Key>, typename Equals = equal_to<Key> >
   class hash_map
   {
      friend class iterator;
      friend class const_iterator;

      enum state
      {
         cStateInvalid = 0,
         cStateValid = 1
      };

      enum
      {
         cMinHashSize = 4U
      };

   public:
      typedef hash_map<Key, Value, Hasher, Equals> hash_map_type;
      typedef std::pair<Key, Value> value_type;
      typedef Key                   key_type;
      typedef Value                 referent_type;
      typedef Hasher                hasher_type;
      typedef Equals                equals_type;

      hash_map() :
         m_hash_shift(32), m_num_valid(0), m_grow_threshold(0)
      {
      }

      hash_map(const hash_map& other) :
         m_values(other.m_values),
         m_hash_shift(other.m_hash_shift),
         m_hasher(other.m_hasher),
         m_equals(other.m_equals),
         m_num_valid(other.m_num_valid),
         m_grow_threshold(other.m_grow_threshold)
      {
      }

      hash_map& operator= (const hash_map& other)
      {
         if (this == &other)
            return *this;

         clear();

         m_values = other.m_values;
         m_hash_shift = other.m_hash_shift;
         m_num_valid = other.m_num_valid;
         m_grow_threshold = other.m_grow_threshold;
         m_hasher = other.m_hasher;
         m_equals = other.m_equals;

         return *this;
      }

      inline ~hash_map()
      {
         clear();
      }

      const Equals& get_equals() const { return m_equals; }
            Equals& get_equals()       { return m_equals; }

      void set_equals(const Equals& equals) { m_equals = equals; }

      const Hasher& get_hasher() const { return m_hasher; }
            Hasher& get_hasher()       { return m_hasher; }

      void set_hasher(const Hasher& hasher) { m_hasher = hasher; }

      inline void clear()
      {
         if (!m_values.empty())
         {
            if (CRNLIB_HAS_DESTRUCTOR(Key) || CRNLIB_HAS_DESTRUCTOR(Value))
            {
               node* p = &get_node(0);
               node* p_end = p + m_values.size();

               uint num_remaining = m_num_valid;
               while (p != p_end)
               {
                  if (p->state)
                  {
                     destruct_value_type(p);
                     num_remaining--;
                     if (!num_remaining)
                        break;
                  }

                  p++;
               }
            }

            m_values.clear_no_destruction();

            m_hash_shift = 32;
            m_num_valid = 0;
            m_grow_threshold = 0;
         }
      }

      inline void reset()
      {
         if (!m_num_valid)
            return;

         if (CRNLIB_HAS_DESTRUCTOR(Key) || CRNLIB_HAS_DESTRUCTOR(Value))
         {
            node* p = &get_node(0);
            node* p_end = p + m_values.size();

            uint num_remaining = m_num_valid;
            while (p != p_end)
            {
               if (p->state)
               {
                  destruct_value_type(p);
                  p->state = cStateInvalid;

                  num_remaining--;
                  if (!num_remaining)
                     break;
               }

               p++;
            }
         }
         else if (sizeof(node) <= 32)
         {
            memset(&m_values[0], 0, m_values.size_in_bytes());
         }
         else
         {
            node* p = &get_node(0);
            node* p_end = p + m_values.size();

            uint num_remaining = m_num_valid;
            while (p != p_end)
            {
               if (p->state)
               {
                  p->state = cStateInvalid;

                  num_remaining--;
                  if (!num_remaining)
                     break;
               }

               p++;
            }
         }

         m_num_valid = 0;
      }

      inline uint size()
      {
         return m_num_valid;
      }

      inline uint get_table_size()
      {
         return m_values.size();
      }

      inline bool empty()
      {
         return !m_num_valid;
      }

      inline void reserve(uint new_capacity)
      {
         uint new_hash_size = math::maximum(1U, new_capacity);

         new_hash_size = new_hash_size * 2U;

         if (!math::is_power_of_2(new_hash_size))
            new_hash_size = math::next_pow2(new_hash_size);

         new_hash_size = math::maximum<uint>(cMinHashSize, new_hash_size);

         if (new_hash_size > m_values.size())
            rehash(new_hash_size);
      }

      class const_iterator;

      class iterator
      {
         friend class hash_map<Key, Value, Hasher, Equals>;
         friend class hash_map<Key, Value, Hasher, Equals>::const_iterator;

      public:
         inline iterator() : m_pTable(NULL), m_index(0) { }
         inline iterator(hash_map_type& table, uint index) : m_pTable(&table), m_index(index) { }
         inline iterator(const iterator& other) : m_pTable(other.m_pTable), m_index(other.m_index) { }

         inline iterator& operator= (const iterator& other)
         {
            m_pTable = other.m_pTable;
            m_index = other.m_index;
            return *this;
         }

          // post-increment
         inline iterator operator++(int)
         {
            iterator result(*this);
            ++*this;
            return result;
         }

         // pre-increment
         inline iterator& operator++()
         {
            probe();
            return *this;
         }

         inline value_type& operator*() const { return *get_cur(); }
         inline value_type* operator->() const { return get_cur(); }

         inline bool operator == (const iterator& b) const { return (m_pTable == b.m_pTable) && (m_index == b.m_index); }
         inline bool operator != (const iterator& b) const { return !(*this == b); }
         inline bool operator == (const const_iterator& b) const { return (m_pTable == b.m_pTable) && (m_index == b.m_index); }
         inline bool operator != (const const_iterator& b) const { return !(*this == b); }

      private:
         hash_map_type* m_pTable;
         uint m_index;

         inline value_type* get_cur() const
         {
            CRNLIB_ASSERT(m_pTable && (m_index < m_pTable->m_values.size()));
            CRNLIB_ASSERT(m_pTable->get_node_state(m_index) == cStateValid);

            return &m_pTable->get_node(m_index);
         }

         inline void probe()
         {
            CRNLIB_ASSERT(m_pTable);
            m_index = m_pTable->find_next(m_index);
         }
      };

      class const_iterator
      {
         friend class hash_map<Key, Value, Hasher, Equals>;
         friend class hash_map<Key, Value, Hasher, Equals>::iterator;

      public:
         inline const_iterator() : m_pTable(NULL), m_index(0) { }
         inline const_iterator(const hash_map_type& table, uint index) : m_pTable(&table), m_index(index) { }
         inline const_iterator(const iterator& other) : m_pTable(other.m_pTable), m_index(other.m_index) { }
         inline const_iterator(const const_iterator& other) : m_pTable(other.m_pTable), m_index(other.m_index) { }

         inline const_iterator& operator= (const const_iterator& other)
         {
            m_pTable = other.m_pTable;
            m_index = other.m_index;
            return *this;
         }

         inline const_iterator& operator= (const iterator& other)
         {
            m_pTable = other.m_pTable;
            m_index = other.m_index;
            return *this;
         }

         // post-increment
         inline const_iterator operator++(int)
         {
            const_iterator result(*this);
            ++*this;
            return result;
         }

         // pre-increment
         inline const_iterator& operator++()
         {
            probe();
            return *this;
         }

         inline const value_type& operator*() const { return *get_cur(); }
         inline const value_type* operator->() const { return get_cur(); }

         inline bool operator == (const const_iterator& b) const { return (m_pTable == b.m_pTable) && (m_index == b.m_index); }
         inline bool operator != (const const_iterator& b) const { return !(*this == b); }
         inline bool operator == (const iterator& b) const { return (m_pTable == b.m_pTable) && (m_index == b.m_index); }
         inline bool operator != (const iterator& b) const { return !(*this == b); }

      private:
         const hash_map_type* m_pTable;
         uint m_index;

         inline const value_type* get_cur() const
         {
            CRNLIB_ASSERT(m_pTable && (m_index < m_pTable->m_values.size()));
            CRNLIB_ASSERT(m_pTable->get_node_state(m_index) == cStateValid);

            return &m_pTable->get_node(m_index);
         }

         inline void probe()
         {
            CRNLIB_ASSERT(m_pTable);
            m_index = m_pTable->find_next(m_index);
         }
      };

      inline const_iterator begin() const
      {
         if (!m_num_valid)
            return end();

         return const_iterator(*this, find_next(-1));
      }

      inline const_iterator end() const
      {
         return const_iterator(*this, m_values.size());
      }

      inline iterator begin()
      {
         if (!m_num_valid)
            return end();

         return iterator(*this, find_next(-1));
      }

      inline iterator end()
      {
         return iterator(*this, m_values.size());
      }

      // insert_result.first will always point to inserted key/value (or the already existing key/value).
      // insert_resutt.second will be true if a new key/value was inserted, or false if the key already existed (in which case first will point to the already existing value).
      typedef std::pair<iterator, bool> insert_result;

      inline insert_result insert(const Key& k, const Value& v = Value())
      {
         insert_result result;
         if (!insert_no_grow(result, k, v))
         {
            grow();

            // This must succeed.
            if (!insert_no_grow(result, k, v))
            {
               CRNLIB_FAIL("insert() failed");
            }
         }

         return result;
      }

      inline insert_result insert(const value_type& v)
      {
         return insert(v.first, v.second);
      }

      inline const_iterator find(const Key& k) const
      {
         return const_iterator(*this, find_index(k));
      }

      inline iterator find(const Key& k)
      {
         return iterator(*this, find_index(k));
      }

      inline bool erase(const Key& k)
      {
         int i = find_index(k);

         if (i >= static_cast<int>(m_values.size()))
            return false;

         node* pDst = &get_node(i);
         destruct_value_type(pDst);
         pDst->state = cStateInvalid;

         m_num_valid--;

         for ( ; ; )
         {
            int r, j = i;

            node* pSrc = pDst;

            do
            {
               if (!i)
               {
                  i = m_values.size() - 1;
                  pSrc = &get_node(i);
               }
               else
               {
                  i--;
                  pSrc--;
               }

               if (!pSrc->state)
                  return true;

               r = hash_key(pSrc->first);

            } while ((i <= r && r < j) || (r < j && j < i) || (j < i && i <= r));

            move_node(pDst, pSrc);

            pDst = pSrc;
         }
      }

      inline void swap(hash_map_type& other)
      {
         m_values.swap(other.m_values);
         utils::swap(m_hash_shift,     other.m_hash_shift);
         utils::swap(m_num_valid,      other.m_num_valid);
         utils::swap(m_grow_threshold, other.m_grow_threshold);
         utils::swap(m_hasher,         other.m_hasher);
         utils::swap(m_equals,         other.m_equals);
      }

   private:
      struct node : public value_type
      {
         uint8 state;
      };

      static inline void construct_value_type(value_type* pDst, const Key& k, const Value& v)
      {
         if (CRNLIB_IS_BITWISE_COPYABLE(Key))
            memcpy(&pDst->first, &k, sizeof(Key));
         else
            scalar_type<Key>::construct(&pDst->first, k);

         if (CRNLIB_IS_BITWISE_COPYABLE(Value))
            memcpy(&pDst->second, &v, sizeof(Value));
         else
            scalar_type<Value>::construct(&pDst->second, v);
      }

      static inline void construct_value_type(value_type* pDst, const value_type* pSrc)
      {
         if ((CRNLIB_IS_BITWISE_COPYABLE(Key)) && (CRNLIB_IS_BITWISE_COPYABLE(Value)))
         {
            memcpy(pDst, pSrc, sizeof(value_type));
         }
         else
         {
            if (CRNLIB_IS_BITWISE_COPYABLE(Key))
               memcpy(&pDst->first, &pSrc->first, sizeof(Key));
            else
               scalar_type<Key>::construct(&pDst->first, pSrc->first);

            if (CRNLIB_IS_BITWISE_COPYABLE(Value))
               memcpy(&pDst->second, &pSrc->second, sizeof(Value));
            else
               scalar_type<Value>::construct(&pDst->second, pSrc->second);
         }
      }

      static inline void destruct_value_type(value_type* p)
      {
         scalar_type<Key>::destruct(&p->first);
         scalar_type<Value>::destruct(&p->second);
      }

      // Moves *pSrc to *pDst efficiently.
      // pDst should NOT be constructed on entry.
      static inline void move_node(node* pDst, node* pSrc)
      {
         CRNLIB_ASSERT(!pDst->state);

         if (CRNLIB_IS_BITWISE_COPYABLE_OR_MOVABLE(Key) && CRNLIB_IS_BITWISE_COPYABLE_OR_MOVABLE(Value))
         {
            memcpy(pDst, pSrc, sizeof(node));
         }
         else
         {
            if (CRNLIB_IS_BITWISE_COPYABLE_OR_MOVABLE(Key))
               memcpy(&pDst->first, &pSrc->first, sizeof(Key));
            else
            {
               scalar_type<Key>::construct(&pDst->first, pSrc->first);
               scalar_type<Key>::destruct(&pSrc->first);
            }

            if (CRNLIB_IS_BITWISE_COPYABLE_OR_MOVABLE(Value))
               memcpy(&pDst->second, &pSrc->second, sizeof(Value));
            else
            {
               scalar_type<Value>::construct(&pDst->second, pSrc->second);
               scalar_type<Value>::destruct(&pSrc->second);
            }

            pDst->state = cStateValid;
         }

         pSrc->state = cStateInvalid;
      }

      struct raw_node
      {
         inline raw_node()
         {
            node* p = reinterpret_cast<node*>(this);
            p->state = cStateInvalid;
         }

         inline ~raw_node()
         {
            node* p = reinterpret_cast<node*>(this);
            if (p->state)
               hash_map_type::destruct_value_type(p);
         }

         inline raw_node(const raw_node& other)
         {
            node* pDst = reinterpret_cast<node*>(this);
            const node* pSrc = reinterpret_cast<const node*>(&other);

            if (pSrc->state)
            {
               hash_map_type::construct_value_type(pDst, pSrc);
               pDst->state = cStateValid;
            }
            else
               pDst->state = cStateInvalid;
         }

         inline raw_node& operator= (const raw_node& rhs)
         {
            if (this == &rhs)
               return *this;

            node* pDst = reinterpret_cast<node*>(this);
            const node* pSrc = reinterpret_cast<const node*>(&rhs);

            if (pSrc->state)
            {
               if (pDst->state)
               {
                  pDst->first = pSrc->first;
                  pDst->second = pSrc->second;
               }
               else
               {
                  hash_map_type::construct_value_type(pDst, pSrc);
                  pDst->state = cStateValid;
               }
            }
            else if (pDst->state)
            {
               hash_map_type::destruct_value_type(pDst);
               pDst->state = cStateInvalid;
            }

            return *this;
         }

         uint8 m_bits[sizeof(node)];
      };

      typedef crnlib::vector<raw_node> node_vector;

      node_vector       m_values;
      uint              m_hash_shift;

      Hasher            m_hasher;
      Equals            m_equals;

      uint              m_num_valid;

      uint              m_grow_threshold;

      inline int hash_key(const Key& k) const
      {
         CRNLIB_ASSERT((1U << (32U - m_hash_shift)) == m_values.size());

         uint hash = static_cast<uint>(m_hasher(k));

         // Fibonacci hashing
         hash = (2654435769U * hash) >> m_hash_shift;

         CRNLIB_ASSERT(hash < m_values.size());
         return hash;
      }

      inline const node& get_node(uint index) const
      {
         return *reinterpret_cast<const node*>(&m_values[index]);
      }

      inline node& get_node(uint index)
      {
         return *reinterpret_cast<node*>(&m_values[index]);
      }

      inline state get_node_state(uint index) const
      {
         return static_cast<state>(get_node(index).state);
      }

      inline void set_node_state(uint index, bool valid)
      {
         get_node(index).state = valid;
      }

      inline void grow()
      {
         rehash(math::maximum<uint>(cMinHashSize, m_values.size() * 2U));
      }

      inline void rehash(uint new_hash_size)
      {
         CRNLIB_ASSERT(new_hash_size >= m_num_valid);
         CRNLIB_ASSERT(math::is_power_of_2(new_hash_size));

         if ((new_hash_size < m_num_valid) || (new_hash_size == m_values.size()))
            return;

         hash_map new_map;
         new_map.m_values.resize(new_hash_size);
         new_map.m_hash_shift = 32U - math::floor_log2i(new_hash_size);
         CRNLIB_ASSERT(new_hash_size == (1U << (32U - new_map.m_hash_shift)));
         new_map.m_grow_threshold = UINT_MAX;

         node* pNode = reinterpret_cast<node*>(m_values.begin());
         node* pNode_end = pNode + m_values.size();

         while (pNode != pNode_end)
         {
            if (pNode->state)
            {
               new_map.move_into(pNode);

               if (new_map.m_num_valid == m_num_valid)
                  break;
            }

            pNode++;
         }

         new_map.m_grow_threshold = (new_hash_size + 1U) >> 1U;

         m_values.clear_no_destruction();
         m_hash_shift = 32;

         swap(new_map);
      }

      inline uint find_next(int index) const
      {
         index++;

         if (index >= static_cast<int>(m_values.size()))
            return index;

         const node* pNode = &get_node(index);

         for ( ; ; )
         {
            if (pNode->state)
               break;

            if (++index >= static_cast<int>(m_values.size()))
               break;

            pNode++;
         }

         return index;
      }

      inline uint find_index(const Key& k) const
      {
         if (m_num_valid)
         {
            int index = hash_key(k);
            const node* pNode = &get_node(index);

            if (pNode->state)
            {
               if (m_equals(pNode->first, k))
                  return index;

               const int orig_index = index;

               for ( ; ; )
               {
                  if (!index)
                  {
                     index = m_values.size() - 1;
                     pNode = &get_node(index);
                  }
                  else
                  {
                     index--;
                     pNode--;
                  }

                  if (index == orig_index)
                     break;

                  if (!pNode->state)
                     break;

                  if (m_equals(pNode->first, k))
                     return index;
               }
            }
         }

         return m_values.size();
      }

      inline bool insert_no_grow(insert_result& result, const Key& k, const Value& v = Value())
      {
         if (!m_values.size())
            return false;

         int index = hash_key(k);
         node* pNode = &get_node(index);

         if (pNode->state)
         {
            if (m_equals(pNode->first, k))
            {
               result.first = iterator(*this, index);
               result.second = false;
               return true;
            }

            const int orig_index = index;

            for ( ; ; )
            {
               if (!index)
               {
                  index = m_values.size() - 1;
                  pNode = &get_node(index);
               }
               else
               {
                  index--;
                  pNode--;
               }

               if (orig_index == index)
                  return false;

               if (!pNode->state)
                  break;

               if (m_equals(pNode->first, k))
               {
                  result.first = iterator(*this, index);
                  result.second = false;
                  return true;
               }
            }
         }

         if (m_num_valid >= m_grow_threshold)
            return false;

         construct_value_type(pNode, k, v);

         pNode->state = cStateValid;

         m_num_valid++;
         CRNLIB_ASSERT(m_num_valid <= m_values.size());

         result.first = iterator(*this, index);
         result.second = true;

         return true;
      }

      inline void move_into(node* pNode)
      {
         int index = hash_key(pNode->first);
         node* pDst_node = &get_node(index);

         if (pDst_node->state)
         {
            const int orig_index = index;

            for ( ; ; )
            {
               if (!index)
               {
                  index = m_values.size() - 1;
                  pDst_node = &get_node(index);
               }
               else
               {
                  index--;
                  pDst_node--;
               }

               if (index == orig_index)
               {
                  CRNLIB_ASSERT(false);
                  return;
               }

               if (!pDst_node->state)
                  break;
            }
         }

         move_node(pDst_node, pNode);

         m_num_valid++;
      }
   };

   template<typename Key, typename Value, typename Hasher, typename Equals>
   struct bitwise_movable< hash_map<Key, Value, Hasher, Equals> > { enum { cFlag = true }; };

   template<typename Key, typename Value, typename Hasher, typename Equals>
   inline void swap(hash_map<Key, Value, Hasher, Equals>& a, hash_map<Key, Value, Hasher, Equals>& b)
   {
      a.swap(b);
   }

   extern void hash_map_test();

} // namespace crnlib