text:
package middleware

import (
	"fmt"
	"log"
	"net/http"
	"runtime/debug"
	// "strings"
	"runtime"

	"github.com/getsentry/raven-go"
)

/*
Middleware that catches panics, and:
	- logs them
	- optionally reports them to sentry - pass in "" if you don't want this
	- sends a 500 response
You can also use ThrowError() to raise an error that this middleware will catch, for example
if you want an error to be reported to sentry
*/
func BuildErrorCatcher(sentryClient *raven.Client) func(h http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		handler := func(w http.ResponseWriter, r *http.Request) {

			defer func() {
				err := recover()
				if err == nil {
					return
				}
				if sentryClient != nil {
					// Send the error to sentry
					const size = 1 << 12
					buf := make([]byte, size)
					n := runtime.Stack(buf, false)
					sentryClient.CaptureMessage(fmt.Sprintf("%v\nStacktrace:\n%s", err, buf[:n]), sentryClient.Tags)
				}

				switch err := err.(type) {
				case HttpError:
					log.Printf("Return response for error %s", err.Message)
					err.WriteResponse(w)
					return
				default:
					log.Printf("Panic: %v\n", err)
					debug.PrintStack()
					http.Error(w, http.StatusText(500), 500)
					return
				}
			}()

			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(handler)
	}
}

/*
An error that encapsulates an HTTP status code and message.
Use ThrowError() to build an HttpError and raise it as a panic
*/
type HttpError struct {
	StatusCode int
	Message    string
}

func (h HttpError) Error() string {
	return h.Message
}

func (h HttpError) WriteResponse(w http.ResponseWriter) {
	http.Error(w, h.Message, h.StatusCode)
}

func MakeError(statusCode int, format string, params ...interface{}) error {
	return HttpError{statusCode, fmt.Sprintf(format, params...)}
}

func ThrowError(statusCode int, format string, params ...interface{}) {
	panic(MakeError(statusCode, format, params...))
}


text:
package com.btmura.android.reddit.app;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.content.Loader;

import com.btmura.android.reddit.content.RelatedSubredditLoader;
import com.btmura.android.reddit.widget.RelatedSubredditAdapter;

class RelatedSubredditListController implements SubredditListController<RelatedSubredditAdapter> {

  static final String EXTRA_ACCOUNT_NAME = "accountName";
  static final String EXTRA_SIDEBAR_SUBREDDIT = "sidebarSubreddit";
  static final String EXTRA_SELECTED_SUBREDDIT = "selectedSubreddit";
  static final String EXTRA_SINGLE_CHOICE = "singleChoice";

  private final Context ctx;
  private final String accountName;
  private final String sidebarSubreddit;
  private final RelatedSubredditAdapter adapter;

  // TODO(btmura): use arguments instead of bundle
  RelatedSubredditListController(Context ctx, Bundle args) {
    this.ctx = ctx;
    this.accountName = getAccountNameExtra(args);
    this.sidebarSubreddit = getSidebarSubredditExtra(args);
    this.adapter = new RelatedSubredditAdapter(ctx, getSingleChoiceExtra(args));
  }

  @Override
  public void restoreInstanceState(Bundle savedInstanceState) {
    setSelectedSubreddit(getSelectedSubredditExtra(savedInstanceState));
  }

  @Override
  public void saveInstanceState(Bundle outState) {
    outState.putString(EXTRA_SELECTED_SUBREDDIT, getSelectedSubreddit());
  }

  // Loader related methods

  @Override
  public Loader<Cursor> createLoader() {
    return new RelatedSubredditLoader(ctx, accountName, sidebarSubreddit);
  }

  @Override
  public void swapCursor(Cursor cursor) {
    adapter.swapCursor(cursor);
  }

  // Getters

  @Override
  public RelatedSubredditAdapter getAdapter() {
    return adapter;
  }

  @Override
  public String getSelectedSubreddit() {
    return adapter.getSelectedSubreddit();
  }

  @Override
  public boolean isSingleChoice() {
    return adapter.isSingleChoice();
  }

  // Setters

  @Override
  public String setSelectedPosition(int position) {
    return adapter.setSelectedPosition(position);
  }

  @Override
  public void setSelectedSubreddit(String selectedSubreddit) {
    adapter.setSelectedSubreddit(selectedSubreddit);
  }

  // Getters for extras.

  private static String getAccountNameExtra(Bundle extras) {
    return extras.getString(EXTRA_ACCOUNT_NAME);
  }

  private static String getSidebarSubredditExtra(Bundle extras) {
    return extras.getString(EXTRA_SIDEBAR_SUBREDDIT);
  }

  private static String getSelectedSubredditExtra(Bundle extras) {
    return extras.getString(EXTRA_SELECTED_SUBREDDIT);
  }

  private static boolean getSingleChoiceExtra(Bundle extras) {
    return extras.getBoolean(EXTRA_SINGLE_CHOICE);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package scavlink.link.command

import scavlink.link.command.CommandTestData.CommandResponses
import scavlink.message.enums.{MavCmd, MavResult}

import scala.concurrent.duration._

object CommandTestData {
  type CommandResponses = Map[MavCmd.Value, (FiniteDuration, MavResult.Value)]

}

trait CommandTestData {
  // predefined results for various commands

  val navResponses: CommandResponses = Map[MavCmd.Value, (FiniteDuration, MavResult.Value)](
    MavCmd.COMPONENT_ARM_DISARM -> (2.seconds, MavResult.ACCEPTED),
    MavCmd.NAV_WAYPOINT -> (0.seconds, MavResult.ACCEPTED),
    MavCmd.NAV_RETURN_TO_LAUNCH -> (0.seconds, MavResult.ACCEPTED),
    MavCmd.DO_FENCE_ENABLE -> (3.seconds, MavResult.TEMPORARILY_REJECTED),
    MavCmd.DO_JUMP -> (0.seconds, MavResult.DENIED),
    MavCmd.DO_PARACHUTE -> (10.seconds, MavResult.FAILED)
  ).withDefaultValue((0.seconds, MavResult.UNSUPPORTED))
}


text:
@implementation MQMessageFormInputModel

-(instancetype)init {
    if(self = [super init]) {
        self.tip = @"";
        self.placeholder = @"";
        self.key = @"";
        self.text = @"";
        self.isRequired = NO;
        self.isSingleLine = YES;
        self.inputModelType = InputModelTypeText;
        self.metainfo = @[];
    }
    return self;
}

@end


text:
#include <NdbApi.hpp>
#include <NdbSchemaCon.hpp>
#include <NdbMutex.h>
#include <NdbOut.hpp>
#include <NdbSleep.h>
#include <NdbThread.h>
#include <NdbTick.h>
#include <NdbMain.h>
#include <NdbTest.hpp>
#include <random.h>

//#define TRACE
#define DEBUG
//#define RELEASE
#define NODE_REC // epaulsa: introduces pointer checks to help 'acid' keep core
// during node recovery

#ifdef TRACE

#define VerifyMethodInt(c, m) (ReportMethodInt(c->m, c, #c, #m, __FILE__, __LINE__))
#define VerifyMethodPtr(v, c, m) (v=ReportMethodPtr(c->m, c, #v, #c, #m, __FILE__, __LINE__))
#define VerifyMethodVoid(c, m) (c->m, ReportMethodVoid(c, #c, #m, __FILE__, __LINE__))

int ReportMethodInt(int iRes, NdbConnection* pNdbConnection, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  ndbout << szFile << "(" << iLine << ") : ";
  ndbout << szClass << "->" << szMethod << " return " << iRes << " : ";
  ndbout << pNdbConnection->getNdbError();
  NdbOperation* pNdbOperation = pNdbConnection->getNdbErrorOperation();
  if(pNdbOperation) {
    ndbout << " : " << pNdbOperation->getNdbError();
  }
  ndbout << " : " << pNdbConnection->getNdbErrorLine();
  ndbout << endl;
  return iRes;
}

template <class C>
int ReportMethodInt(int iRes, C* pC, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  ndbout << szFile << "(" << iLine << ") : ";
  ndbout << szClass << "->" << szMethod << " return " << iRes << " : ";
  ndbout << pC->getNdbError();
  ndbout << endl;
  return iRes;
}

template <class R, class C>
R* ReportMethodPtr(R* pR, C* pC, const char* szVariable, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  ndbout << szFile << "(" << iLine << ") : ";
  ndbout << szVariable << " = " << szClass << "->" << szMethod << " return " << (long)(void*)pR << " : ";
  ndbout << pC->getNdbError();
  ndbout << endl;
  return pR;
}

template <class C>
void ReportMethodVoid(C* pC, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  ndbout << szFile << "(" << iLine << ") : ";
  ndbout << szClass << "->" << szMethod << " : ";
  ndbout << pC->getNdbError();
  ndbout << endl;
}
#endif /* TRACE */

#ifdef DEBUG

#define VerifyMethodInt(c, m) (ReportMethodInt(c->m, c, #c, #m, __FILE__, __LINE__))
#define VerifyMethodPtr(v, c, m) (v=ReportMethodPtr(c->m, c, #v, #c, #m, __FILE__, __LINE__))
#define VerifyMethodVoid(c, m) (c->m, ReportMethodVoid(c, #c, #m, __FILE__, __LINE__))

int ReportMethodInt(int iRes, NdbConnection* pNdbConnection, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  if(iRes<0) {
    ndbout << szFile << "(" << iLine << ") : ";
    ndbout << szClass << "->" << szMethod << " return " << iRes << " : ";
    ndbout << pNdbConnection->getNdbError();
    NdbOperation* pNdbOperation = pNdbConnection->getNdbErrorOperation();
    if(pNdbOperation) {
      ndbout << " : " << pNdbOperation->getNdbError();
    }
    ndbout << " : " << pNdbConnection->getNdbErrorLine();
    ndbout << " : ";
    ndbout << endl;
  }
  return iRes;
}

template <class C>
int ReportMethodInt(int iRes, C* pC, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  if(iRes<0) {
    ndbout << szFile << "(" << iLine << ") : ";
    ndbout << szClass << "->" << szMethod << " return " << iRes << " : ";
    ndbout << pC->getNdbError();
    ndbout << endl;
  }
  return iRes;
}

template <class R, class C>
R* ReportMethodPtr(R* pR, C* pC, const char* szVariable, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  if(!pR) {
    ndbout << szFile << "(" << iLine << ") : ";
    ndbout << szVariable << " = " << szClass << "->" << szMethod << " return " << " : ";
    ndbout << pC->getNdbError();
    ndbout << endl;
  }
  return pR;
}

template <class C>
void ReportMethodVoid(C* pC, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  if(pC->getNdbError().code) {
    ndbout << szFile << "(" << iLine << ") : ";
    ndbout << szClass << "->" << szMethod << " : ";
    ndbout << pC->getNdbError();
    ndbout << endl;
  }
}

#endif /* DEBUG */

#ifdef RELEASE

#define VerifyMethodInt(c, m) (c->m)
#define VerifyMethodPtr(v, c, m) (v=(c->m))
#define VerifyMethodVoid(c, m) (c->m)

int ReportMethodInt(int iRes, NdbConnection* pNdbConnection, const char* szClass, const char* szMethod, const char* szFile, const int iLine)
{
  if(iRes<0) {
    ndbout << szFile << "(" << iLine << ") : ";
    ndbout << szClass << "->" << szMethod << " return " << iRes << " : ";
    ndbout << pNdbConnection->getNdbError();
    NdbOperation* pNdbOperation = pNdbConnection->getNdbErrorOperation();
    if(pNdbOperation) {
      ndbout << " : " << pNdbOperation->getNdbError();
    }
    ndbout << " : " << pNdbConnection->getNdbErrorLine();
    ndbout << endl;
  }
  return iRes;
}

#endif /* RELEASE */

// epaulsa =>
#ifndef NODE_REC
#define CHK_TR(p)
#else
#define CHK_TR(p) if(!p){													\
			ndbout <<"startTransaction failed, returning now." << endl ;	\
			delete pNdb ;													\
			pNdb = NULL ;													\
			return 0 ;														\
		}
#endif // NODE_REC
// <= epaulsa

const char* c_szWarehouse = "WAREHOUSE";
const char* c_szWarehouseNumber = "W_ID";
const char* c_szWarehouseSum = "W_SUM";
const char* c_szWarehouseCount = "W_CNT";
const char* c_szDistrict = "DISTRICT";
const char* c_szDistrictWarehouseNumber = "D_W_ID";
const char* c_szDistrictNumber = "D_ID";
const char* c_szDistrictSum = "D_SUM";
const char* c_szDistrictCount = "D_CNT";

Uint32 g_nWarehouseCount = 10;
Uint32 g_nDistrictPerWarehouse = 10;
Uint32 g_nThreadCount = 1;
NdbMutex* g_pNdbMutex = 0;

extern "C" void* NdbThreadFuncInsert(void* pArg)
{
  myRandom48Init((long int)NdbTick_CurrentMillisecond());
  unsigned nSucc = 0;
  unsigned nFail = 0;
  Ndb* pNdb = NULL ;
  pNdb = new Ndb("TEST_DB");
  VerifyMethodInt(pNdb, init());
  VerifyMethodInt(pNdb, waitUntilReady());

  while(NdbMutex_Trylock(g_pNdbMutex)) {
    Uint32 nWarehouse = myRandom48(g_nWarehouseCount);
    NdbConnection* pNdbConnection = NULL ;
    VerifyMethodPtr(pNdbConnection, pNdb, startTransaction());
    CHK_TR(pNdbConnection);
    NdbOperation* pNdbOperationW = NULL ;
    VerifyMethodPtr(pNdbOperationW, pNdbConnection, getNdbOperation(c_szWarehouse));
    VerifyMethodInt(pNdbOperationW, insertTuple());
    VerifyMethodInt(pNdbOperationW, equal(c_szWarehouseNumber, nWarehouse));
    VerifyMethodInt(pNdbOperationW, setValue(c_szWarehouseCount, Uint32(1)));
    Uint32 nWarehouseSum = 0;
    for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
      NdbOperation* pNdbOperationD = NULL ;
      VerifyMethodPtr(pNdbOperationD, pNdbConnection, getNdbOperation(c_szDistrict));
      VerifyMethodInt(pNdbOperationD, insertTuple());
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictWarehouseNumber, nWarehouse));
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictNumber, nDistrict));
      VerifyMethodInt(pNdbOperationD, setValue(c_szDistrictCount, Uint32(1)));
      Uint32 nDistrictSum = myRandom48(100);
      nWarehouseSum += nDistrictSum;
      VerifyMethodInt(pNdbOperationD, setValue(c_szDistrictSum, nDistrictSum));
    }
    VerifyMethodInt(pNdbOperationW, setValue(c_szWarehouseSum, nWarehouseSum));
    int iExec = pNdbConnection->execute(Commit);
    int iError = pNdbConnection->getNdbError().code;

    if(iExec<0 && iError!=0 && iError!=266 && iError!=630) {
      ReportMethodInt(iExec, pNdbConnection, "pNdbConnection", "execute(Commit)", __FILE__, __LINE__);
    }
    if(iExec==0) {
      ++nSucc;
    } else {
      ++nFail;
    }
    VerifyMethodVoid(pNdb, closeTransaction(pNdbConnection));
  }
  ndbout << "insert: " << nSucc << " succeeded, " << nFail << " failed " << endl;
  NdbMutex_Unlock(g_pNdbMutex);
  delete pNdb;
  pNdb = NULL ;
  return NULL;
}

extern "C" void* NdbThreadFuncUpdate(void* pArg)
{
  myRandom48Init((long int)NdbTick_CurrentMillisecond());
  unsigned nSucc = 0;
  unsigned nFail = 0;
  Ndb* pNdb = NULL ;
  pNdb = new Ndb("TEST_DB");
  VerifyMethodInt(pNdb, init());
  VerifyMethodInt(pNdb, waitUntilReady());

  while(NdbMutex_Trylock(g_pNdbMutex)) {
    Uint32 nWarehouse = myRandom48(g_nWarehouseCount);
    NdbConnection* pNdbConnection = NULL ;
    VerifyMethodPtr(pNdbConnection, pNdb, startTransaction());
    CHK_TR(pNdbConnection) ; // epaulsa
    NdbOperation* pNdbOperationW = NULL ;
    VerifyMethodPtr(pNdbOperationW, pNdbConnection, getNdbOperation(c_szWarehouse));
    VerifyMethodInt(pNdbOperationW, interpretedUpdateTuple());
    VerifyMethodInt(pNdbOperationW, equal(c_szWarehouseNumber, nWarehouse));
    VerifyMethodInt(pNdbOperationW, incValue(c_szWarehouseCount, Uint32(1)));
    Uint32 nWarehouseSum = 0;
    for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
      NdbOperation* pNdbOperationD = NULL ;
      VerifyMethodPtr(pNdbOperationD, pNdbConnection, getNdbOperation(c_szDistrict));
      VerifyMethodInt(pNdbOperationD, interpretedUpdateTuple());
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictWarehouseNumber, nWarehouse));
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictNumber, nDistrict));
      VerifyMethodInt(pNdbOperationD, incValue(c_szDistrictCount, Uint32(1)));
      Uint32 nDistrictSum = myRandom48(100);
      nWarehouseSum += nDistrictSum;
      VerifyMethodInt(pNdbOperationD, setValue(c_szDistrictSum, nDistrictSum));
    }
    VerifyMethodInt(pNdbOperationW, setValue(c_szWarehouseSum, nWarehouseSum));
    int iExec = pNdbConnection->execute(Commit);
    int iError = pNdbConnection->getNdbError().code;

    if(iExec<0 && iError!=0 && iError!=266 && iError!=626) {
      ReportMethodInt(iExec, pNdbConnection, "pNdbConnection", "execute(Commit)", __FILE__, __LINE__);
    }
    if(iExec==0) {
      ++nSucc;
    } else {
      ++nFail;
    }
    VerifyMethodVoid(pNdb, closeTransaction(pNdbConnection));
  }
  ndbout << "update: " << nSucc << " succeeded, " << nFail << " failed " << endl;
  NdbMutex_Unlock(g_pNdbMutex);
  delete pNdb;
  pNdb = NULL ;
  return NULL;
}

extern "C" void* NdbThreadFuncDelete(void* pArg)
{
  myRandom48Init((long int)NdbTick_CurrentMillisecond());
  unsigned nSucc = 0;
  unsigned nFail = 0;
  Ndb* pNdb = NULL ;
  pNdb = new Ndb("TEST_DB");
  VerifyMethodInt(pNdb, init());
  VerifyMethodInt(pNdb, waitUntilReady());

  while(NdbMutex_Trylock(g_pNdbMutex)) {
    Uint32 nWarehouse = myRandom48(g_nWarehouseCount);
    NdbConnection* pNdbConnection = NULL ;
    VerifyMethodPtr(pNdbConnection, pNdb, startTransaction());
    CHK_TR(pNdbConnection) ; // epaulsa
    NdbOperation* pNdbOperationW = NULL ;
    VerifyMethodPtr(pNdbOperationW, pNdbConnection, getNdbOperation(c_szWarehouse));
    VerifyMethodInt(pNdbOperationW, deleteTuple());
    VerifyMethodInt(pNdbOperationW, equal(c_szWarehouseNumber, nWarehouse));
    for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
      NdbOperation* pNdbOperationD = NULL ;
      VerifyMethodPtr(pNdbOperationD, pNdbConnection, getNdbOperation(c_szDistrict));
      VerifyMethodInt(pNdbOperationD, deleteTuple());
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictWarehouseNumber, nWarehouse));
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictNumber, nDistrict));
    }
    int iExec = pNdbConnection->execute(Commit);
    int iError = pNdbConnection->getNdbError().code;

    if(iExec<0 && iError!=0 && iError!=266 && iError!=626) {
      ReportMethodInt(iExec, pNdbConnection, "pNdbConnection", "execute(Commit)", __FILE__, __LINE__);
    }
    if(iExec==0) {
      ++nSucc;
    } else {
      ++nFail;
    }
    VerifyMethodVoid(pNdb, closeTransaction(pNdbConnection));
  }
  ndbout << "delete: " << nSucc << " succeeded, " << nFail << " failed " << endl;
  NdbMutex_Unlock(g_pNdbMutex);
  delete pNdb;
  pNdb = NULL ;
  return NULL;
}

extern "C" void* NdbThreadFuncRead(void* pArg)
{
  myRandom48Init((long int)NdbTick_CurrentMillisecond());
  unsigned nSucc = 0;
  unsigned nFail = 0;
  NdbRecAttr** ppNdbRecAttrDSum = new NdbRecAttr*[g_nDistrictPerWarehouse];
  NdbRecAttr** ppNdbRecAttrDCnt = new NdbRecAttr*[g_nDistrictPerWarehouse];
  Ndb* pNdb = NULL ;
  pNdb = new Ndb("TEST_DB");
  VerifyMethodInt(pNdb, init());
  VerifyMethodInt(pNdb, waitUntilReady());

  while(NdbMutex_Trylock(g_pNdbMutex)) {
    Uint32 nWarehouse = myRandom48(g_nWarehouseCount);
    NdbConnection* pNdbConnection = NULL ;
    VerifyMethodPtr(pNdbConnection, pNdb, startTransaction());
    CHK_TR(pNdbConnection) ; // epaulsa
    NdbOperation* pNdbOperationW = NULL ;
    VerifyMethodPtr(pNdbOperationW, pNdbConnection, getNdbOperation(c_szWarehouse));
    VerifyMethodInt(pNdbOperationW, readTuple());
    VerifyMethodInt(pNdbOperationW, equal(c_szWarehouseNumber, nWarehouse));
    NdbRecAttr* pNdbRecAttrWSum;
    VerifyMethodPtr(pNdbRecAttrWSum, pNdbOperationW, getValue(c_szWarehouseSum, 0));
    NdbRecAttr* pNdbRecAttrWCnt;
    VerifyMethodPtr(pNdbRecAttrWCnt, pNdbOperationW, getValue(c_szWarehouseCount, 0));
    for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
      NdbOperation* pNdbOperationD = NULL ;
      VerifyMethodPtr(pNdbOperationD, pNdbConnection, getNdbOperation(c_szDistrict));
      VerifyMethodInt(pNdbOperationD, readTuple());
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictWarehouseNumber, nWarehouse));
      VerifyMethodInt(pNdbOperationD, equal(c_szDistrictNumber, nDistrict));
      VerifyMethodPtr(ppNdbRecAttrDSum[nDistrict], pNdbOperationD, getValue(c_szDistrictSum, 0));
      VerifyMethodPtr(ppNdbRecAttrDCnt[nDistrict], pNdbOperationD, getValue(c_szDistrictCount, 0));
    }
    int iExec = pNdbConnection->execute(Commit);
    int iError = pNdbConnection->getNdbError().code;

    if(iExec<0 && iError!=0 && iError!=266 && iError!=626) {
      ReportMethodInt(iExec, pNdbConnection, "pNdbConnection", "execute(Commit)", __FILE__, __LINE__);
    }
    if(iExec==0) {
      Uint32 nSum = 0;
      Uint32 nCnt = 0;
      for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
        nSum += ppNdbRecAttrDSum[nDistrict]->u_32_value();
        nCnt += ppNdbRecAttrDCnt[nDistrict]->u_32_value();
      }
      if(nSum!=pNdbRecAttrWSum->u_32_value()
         || nCnt!=g_nDistrictPerWarehouse*pNdbRecAttrWCnt->u_32_value()) {
        ndbout << "INCONSISTENT!" << endl;
        ndbout << "iExec==" << iExec << endl;
        ndbout << "iError==" << iError << endl;
        ndbout << endl;
        ndbout << c_szWarehouseSum << "==" << pNdbRecAttrWSum->u_32_value() << ", ";
        ndbout << c_szWarehouseCount << "==" << pNdbRecAttrWCnt->u_32_value() << endl;
        ndbout << "nSum==" << nSum << ", nCnt=" << nCnt << endl;
        for(Uint32 nDistrict=0; nDistrict<g_nDistrictPerWarehouse; ++nDistrict) {
          ndbout << c_szDistrictSum << "[" << nDistrict << "]==" << ppNdbRecAttrDSum[nDistrict]->u_32_value() << ", ";
          ndbout << c_szDistrictCount << "[" << nDistrict << "]==" << ppNdbRecAttrDCnt[nDistrict]->u_32_value() << endl;
        }
        VerifyMethodVoid(pNdb, closeTransaction(pNdbConnection));
        delete pNdb; pNdb = NULL ;
        delete[] ppNdbRecAttrDSum; ppNdbRecAttrDSum = NULL ;
        delete[] ppNdbRecAttrDCnt; ppNdbRecAttrDCnt = NULL ;
        NDBT_ProgramExit(NDBT_FAILED);
      }
      ++nSucc;
    } else {
      ++nFail;
    }
    VerifyMethodVoid(pNdb, closeTransaction(pNdbConnection));
  }
  ndbout << "read: " << nSucc << " succeeded, " << nFail << " failed " << endl;
  NdbMutex_Unlock(g_pNdbMutex);
  delete pNdb; pNdb = NULL ;
  delete[] ppNdbRecAttrDSum; ppNdbRecAttrDSum = NULL ;
  delete[] ppNdbRecAttrDCnt; ppNdbRecAttrDCnt = NULL ;
  return NULL;
}

NDB_COMMAND(acid, "acid", "acid", "acid", 65535)
{
  ndb_init();
  long nSeconds = 60;
  int rc = NDBT_OK;

  for(int i=1; i<argc; ++i) {
    if(argv[i][0]=='-' || argv[i][0]=='/') {
      switch(argv[i][1]) {
      case 'w': g_nWarehouseCount=atol(argv[i]+2); break;
      case 'd': g_nDistrictPerWarehouse=atol(argv[i]+2); break;
      case 's': nSeconds=atol(argv[i]+2); break;
      case 't': g_nThreadCount=atol(argv[i]+2); break;
      default: ndbout << "invalid option" << endl; return 1;
      }
    } else {
      ndbout << "invalid operand" << endl;
      return 1;
    }
  }
  ndbout << argv[0];
  ndbout << " -w" << g_nWarehouseCount;
  ndbout << " -d" << g_nDistrictPerWarehouse;
  ndbout << " -s" << (int)nSeconds;
  ndbout << " -t" << g_nThreadCount;
  ndbout << endl;

  Ndb* pNdb = NULL ;
  pNdb = new Ndb("TEST_DB");
  VerifyMethodInt(pNdb, init());
  VerifyMethodInt(pNdb, waitUntilReady());

  NdbSchemaCon* pNdbSchemaCon= NdbSchemaCon::startSchemaTrans(pNdb);
  if(!pNdbSchemaCon){
    ndbout <<"startSchemaTransaction failed, exiting now" << endl ;
    delete pNdb ;
    NDBT_ProgramExit(NDBT_FAILED) ;
  }
  NdbSchemaOp* pNdbSchemaOp = NULL ;
  VerifyMethodPtr(pNdbSchemaOp, pNdbSchemaCon, getNdbSchemaOp());
  VerifyMethodInt(pNdbSchemaOp, createTable(
                                            c_szWarehouse,
                                            (4+4+4+12)*1.02*g_nWarehouseCount/1024+1,
                                            TupleKey,
                                            (4+14)*g_nWarehouseCount/8/1024+1));

  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szWarehouseNumber, TupleKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szWarehouseSum, NoKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szWarehouseCount, NoKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaCon, execute());
  NdbSchemaCon::closeSchemaTrans(pNdbSchemaCon);

  pNdbSchemaCon= NdbSchemaCon::startSchemaTrans(pNdb);
  VerifyMethodPtr(pNdbSchemaOp, pNdbSchemaCon, getNdbSchemaOp());
  VerifyMethodInt(pNdbSchemaOp, createTable(
                                            c_szDistrict,
                                            (4+4+4+4+12)*1.02*g_nWarehouseCount*g_nDistrictPerWarehouse/1024+1,
                                            TupleKey,
                                            (4+4+14)*g_nWarehouseCount*g_nDistrictPerWarehouse/8/1024+1));

  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szDistrictWarehouseNumber, TupleKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szDistrictNumber, TupleKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szDistrictSum, NoKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaOp, createAttribute(c_szDistrictCount, NoKey, 32, 1, UnSigned, MMBased, false));
  VerifyMethodInt(pNdbSchemaCon, execute());
  NdbSchemaCon::closeSchemaTrans(pNdbSchemaCon);
  g_pNdbMutex = NdbMutex_Create();
  NdbMutex_Lock(g_pNdbMutex);

  NdbThread** ppNdbThread = new NdbThread*[g_nThreadCount*4];
  for(Uint32 nThread=0; nThread<g_nThreadCount; ++nThread) {
    ppNdbThread[nThread*4+0] = NdbThread_Create(NdbThreadFuncInsert, 0, 65535, "insert",
                                                NDB_THREAD_PRIO_LOW);
    ppNdbThread[nThread*4+1] = NdbThread_Create(NdbThreadFuncUpdate, 0, 65535, "update",
                                                NDB_THREAD_PRIO_LOW);
    ppNdbThread[nThread*4+2] = NdbThread_Create(NdbThreadFuncDelete, 0, 65535, "delete",
                                                NDB_THREAD_PRIO_LOW);
    ppNdbThread[nThread*4+3] = NdbThread_Create(NdbThreadFuncRead, 0, 65535, "read",
                                                NDB_THREAD_PRIO_LOW);
  }

  NdbSleep_SecSleep(nSeconds);
  NdbMutex_Unlock(g_pNdbMutex);

  void* pStatus;
  for(Uint32 nThread=0; nThread<g_nThreadCount; ++nThread) {
    NdbThread_WaitFor(ppNdbThread[nThread*4+0], &pStatus);
    NdbThread_WaitFor(ppNdbThread[nThread*4+1], &pStatus);
    NdbThread_WaitFor(ppNdbThread[nThread*4+2], &pStatus);
    NdbThread_WaitFor(ppNdbThread[nThread*4+3], &pStatus);
  }

  NdbMutex_Destroy(g_pNdbMutex);
  delete[] ppNdbThread;
  delete pNdb;
  return NDBT_ProgramExit(rc);
}


text:
VERSION=$(mvn -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive exec:exec -q)

function main {
    #DIR_NAME="$(dirname $(dirname $0))"
    local cli_jar="$PWD/target/java-cli-${VERSION}-jar-with-dependencies.jar"

    [[ ! -f  "$cli_jar" ]] && echo "File not found: $cli_jar" && exit 1

    #JYTHON_JAR="$HOME/jython/jython/jython-standalone-2.7.0.jar"

    if [[ ! -f  "$JYTHON_JAR" ]]; then
        echo "Requires Jython stand-alone Jar file, from http://www.jython.org/downloads.html download the latest Jython stand-alone jar and create an environment variable by the name JYTHON_JAR" \
        && exit 1
    fi

    CLASSPATH="$JYTHON_JAR:$cli_jar"

    echo java -cp "$CLASSPATH" org.python.util.jython "$PWD/scripts/delete_tests.py" "$@"
    java -cp "$CLASSPATH" org.python.util.jython "$PWD/scripts/delete_tests.py" "$@"

}

main  "$@"


text:
from ..rest import RestClient

class Tickets(object):
    """Auth0 tickets endpoints

    Args:
        domain (str): Your Auth0 domain, e.g: 'username.auth0.com'

        token (str): Management API v2 Token

        telemetry (bool, optional): Enable or disable Telemetry
            (defaults to True)

        timeout (float or tuple, optional): Change the requests
            connect and read timeout. Pass a tuple to specify
            both values separately or a float to set both to it.
            (defaults to 5.0 for both)

        rest_options (RestClientOptions): Pass an instance of
            RestClientOptions to configure additional RestClient
            options, such as rate-limit retries.
            (defaults to None)
    """

    def __init__(
        self,
        domain,
        token,
        telemetry=True,
        timeout=5.0,
        protocol="https",
        rest_options=None,
    ):
        self.domain = domain
        self.protocol = protocol
        self.client = RestClient(
            jwt=token, telemetry=telemetry, timeout=timeout, options=rest_options
        )

    def _url(self, action):
        return "{}://{}/api/v2/tickets/{}".format(self.protocol, self.domain, action)

    def create_email_verification(self, body):
        """Create an email verification ticket.

        Args:
            body (dict): attributes to set on the email verification request.

        See: https://auth0.com/docs/api/v2#!/Tickets/post_email_verification
        """
        return self.client.post(self._url("email-verification"), data=body)

    def create_pswd_change(self, body):
        """Create password change ticket.

        Args:
            body (dict): attributes to set on the password change request.

        See: https://auth0.com/docs/api/v2#!/Tickets/post_password_change
        """
        return self.client.post(self._url("password-change"), data=body)


text:
package io.github.suxil.service.service.zyj;

import io.github.suxil.service.domain.zyj.ZyjSixtyFourGua;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 * 六十四卦 服务类
 * </p>
 *
 * @author generate
 * @since 2019-11-17
 */
public interface IZyjSixtyFourGuaService extends IService<ZyjSixtyFourGua> {

}


text:
package com.thoughtworks.go.util.command;

public class CommandTimeoutException extends RuntimeException {
    public CommandTimeoutException(String message) {
        super(message);
    }
}


text:
/********************************************************************
	created:	2014/11/03
	created:	3:11:2014   16:13
	filename: 	SIPAddressCtrl.h
	author:		±ù

	purpose:	SOUI°æµÄIP¿Ø¼þ
*********************************************************************/
#pragma once

namespace SOUI
{

	class SEditIP;

	class SIPAddressCtrl :
		public SWindow
	{
		SOUI_CLASS_NAME(SIPAddressCtrl,L"ipctrl")
	public:
		SIPAddressCtrl(void);
		~SIPAddressCtrl(void);

		BOOL IsBlank() const;
		void ClearAddress();
		int GetAddress(_Out_ BYTE& nField0,_Out_  BYTE& nField1,_Out_  BYTE& nField2,_Out_  BYTE& nField3) const;
		int GetAddress(_Out_ DWORD& dwAddress) const;

		void SetAddress(_In_ DWORD dwAddress);
		void SetAddress(_In_ BYTE nField0,_In_ BYTE nField1,_In_ BYTE nField2,_In_ BYTE nField3);

		void SetFieldFocus(WORD nField);
		void SetFieldRange(int nField, BYTE nLower, BYTE nUpper);
	protected:
		void OnPaint(IRenderTarget *pRT);
		LRESULT OnCreate(LPVOID);
		void OnSize( UINT nType, CSize size );

		SOUI_MSG_MAP_BEGIN()
		    MSG_WM_CREATE(OnCreate)
			MSG_WM_SIZE(OnSize)
			MSG_WM_PAINT_EX(OnPaint)
		SOUI_MSG_MAP_END()
	private:
		SEditIP * m_editFields[4];
	};
}


text:
import { getHighlightEditStyle } from 'binary-ui-styles';
import styled from 'styled-components';

export default styled.View`
  background-color: #ffffff;
  justify-content: space-between;
  flex-direction: row;
  ${props => (
    getHighlightEditStyle(
      props.isEdit,
      props.isValid,
      props.isTypingHighlight,
      props.styleBorderColor
    )
  )}
`;


text:
package edu.sjtu.jsearcher.balance;

import java.util.*;

public class ConsistentHash<T> {
	private final HashFunction hashFunction;
	private final int numberOfReplicas;// number of virtual nodes
	// mapping: virtual node -> physical node
	private final SortedMap<Long, T> circle = new TreeMap<Long, T>();

	/**
	 *
	 * @param hashFunction
	 * @param numberOfReplicas
	 * @param nodes : physical nodes
	 */
	public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
			Collection<T> nodes) {
		this.hashFunction = hashFunction;
		this.numberOfReplicas = numberOfReplicas;
		for (T node : nodes) {
			add(node);
		}
	}

	/**
	 * add a physical node
	 * @param node
	 */
	public void add(T node) {
		for (int i = 0; i < numberOfReplicas; i++) {
			circle.put(hashFunction.hash(node.toString() + i), node);
		}
	}

	/**
	 * remove a physical node
	 * @param node
	 */
	public void remove(T node) {
		for (int i = 0; i < numberOfReplicas; i++) {
			circle.remove(hashFunction.hash(node.toString() + i));
		}
	}

	/**
	 * given the input, get target physical node
	 * @param key
	 * @return
	 */
	public T get(Object key) {
		if (circle.isEmpty()) {
			return null;
		}
		// 计算hash值
		long hash = hashFunction.hash(key);
		// 如果不包括这个hash值
		if (!circle.containsKey(hash)) {
			SortedMap<Long, T> tailMap = circle.tailMap(hash);
			hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
		}

		return circle.get(hash);
	}

	public static void main(String args[]) {
		List<Node> nodes = new ArrayList<Node>();
		nodes.add(new Node("A", "192.168.0.1"));
		//nodes.add(new Node("B", "192.168.0.2"));
		//nodes.add(new Node("C", "192.168.0.3"));

		ConsistentHash<Node> ch = new ConsistentHash<Node>(new HashFunction(), 3, nodes);

		List<String> keys = new ArrayList<String>();
		keys.add("https://leetcode.com/problems/perfect-rectangle/");
		keys.add("https://leetcode.com/problems/ransom-note/");
		keys.add("https://leetcode.com/problems/super-ugly-number/");
		keys.add("https://leetcode.com/contest/");
		keys.add("https://leetcode.com/");

		for(String key : keys) {
			System.out.println(ch.get(key));
		}
	}
}


text:
package org.apache.ignite.internal;

import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.Ignite;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.P2;
import org.apache.ignite.messaging.MessagingListenActor;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonTest;

/**
 * Test for {@link org.apache.ignite.IgniteCluster}.
 */
@GridCommonTest(group = "Kernal Self")
public class GridSelfTest extends ClusterGroupAbstractTest {
    /** Nodes count. */
    private static final int NODES_CNT = 4;

    /** {@inheritDoc} */
    @SuppressWarnings({"ConstantConditions"})
    @Override protected void beforeTestsStarted() throws Exception {
        assert NODES_CNT > 2;

        for (int i = 0; i < NODES_CNT; i++)
            startGrid(i);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopAllGrids();
    }

    /** {@inheritDoc} */
    @Override protected ClusterGroup projection() {
        return grid(0).cluster();
    }

    /** {@inheritDoc} */
    @Override protected UUID localNodeId() {
        return grid(0).localNode().id();
    }

    /** {@inheritDoc} */
    @Override protected Collection<UUID> remoteNodeIds() {
        return F.nodeIds(grid(0).cluster().forRemotes().nodes());
    }

    /** {@inheritDoc} */
    @Override public void testRemoteNodes() throws Exception {
        int size = remoteNodeIds().size();

        String name = "oneMoreGrid";

        try {
            Ignite g = startGrid(name);

            UUID joinedId = g.cluster().localNode().id();

            assert projection().forRemotes().nodes().size() == size + 1;

            assert F.nodeIds(projection().forRemotes().nodes()).contains(joinedId);
        }
        finally {
            stopGrid(name);
        }
    }

    /** {@inheritDoc} */
    @Override public void testRemoteProjection() throws Exception {
        ClusterGroup remotePrj = projection().forRemotes();

        int size = remotePrj.nodes().size();

        String name = "oneMoreGrid";

        try {
            Ignite g = startGrid(name);

            UUID joinedId = g.cluster().localNode().id();

            assert remotePrj.nodes().size() == size + 1;

            assert F.nodeIds(remotePrj.nodes()).contains(joinedId);
        }
        finally {
            stopGrid(name);
        }
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings({"TooBroadScope"})
    public void testAsyncListen() throws Exception {
        final String hello = "HELLO!";

        final String bye = "BYE!";

        final Ignite g = grid(0);

        final UUID locNodeId = g.cluster().localNode().id();

        g.message().remoteListen(null, new MessagingListenActor<String>() {
            @Override protected void receive(UUID nodeId, String rcvMsg) throws Throwable {
                if (hello.equals(rcvMsg)) {
                    assertEquals(locNodeId, nodeId);
                    assertEquals(hello, rcvMsg);

                    stop(bye);
                }
            }
        });

        final AtomicInteger cnt = new AtomicInteger();

        g.message().localListen(null, new P2<UUID, String>() {
            @Override public boolean apply(UUID nodeId, String msg) {
                if (msg.equals(bye))
                    cnt.incrementAndGet();

                return true;
            }
        });

        g.message().send(null, hello);

        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return cnt.get() == g.cluster().nodes().size();
            }
        }, 5000);

        assertEquals(cnt.get(), g.cluster().nodes().size());
    }

    /**
     * @throws Exception If failed.
     */
    public void testForOthers() throws Exception {
        ClusterNode node0 = grid(0).localNode();
        ClusterNode node1 = grid(1).localNode();
        ClusterNode node2 = grid(2).localNode();
        ClusterNode node3 = grid(3).localNode();

        ClusterGroup p1 = grid(0).cluster().forOthers(node0);

        assertEquals(3, p1.nodes().size());

        assertEquals(2, p1.forOthers(node1).nodes().size());

        assertEquals(1, p1.forOthers(node1, node2).nodes().size());

        assertEquals(1, grid(0).cluster().forOthers(node1, node2, node3).nodes().size());
    }
}


text:
package ru.job4j.iteratorconverter;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Class converts Iterator<Iterator<Integer>> to Iterator<Integer>.
 * @author Artem Prokopov
 * @since 19/10/2017
 * @version 1.0
 */
public class Converter {
    /**
     * Method converts Iterator<Iterator<Integer>> to Iterator<Integer>.
     * @param it parameter method type Iterator<Iterator<Integer>>.
     * @return iterator Iterator<Integer>.
     */
    Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {
        return new Iterator<Integer>() {
            private Iterator<Integer>  current = it.next();
            @Override
            public boolean hasNext() {
                return it.hasNext() || current.hasNext();
            }

            @Override
            public Integer next() {
                if (!current.hasNext() && !it.hasNext()) {
                    throw new NoSuchElementException("No such element.");
                }
                if (!current.hasNext() && it.hasNext()) {
                    current = it.next();
                }
                return current.next();
            }
        };
    }
}


text:
cd .. && mvn -Dcheckstyle.skip=true -Dmaven.test.skip=true -Dmaven.javadoc.skip=true package && cd examples
echo "Basic"
javac -cp "../target/*" Basic.java && java -cp ../target/*:. Basic
echo
echo "Running CompressionResults"
javac -cp "../target/*" CompressionResults.java && java -cp ../target/*:. CompressionResults
echo
echo "Running SerializeToByteBufferExample"
javac -cp "../target/*" SerializeToByteBufferExample.java && java -cp ../target/*:. SerializeToByteBufferExample
echo
echo "Running ImmutableRoaringBitmapExample"
javac -cp "../target/*" ImmutableRoaringBitmapExample.java && java -cp ../target/*:. ImmutableRoaringBitmapExample
echo
echo "Running MemoryMappingExample"
javac -cp "../target/*" MemoryMappingExample.java && java -cp ../target/*:. MemoryMappingExample
echo
echo "Serializing to byte array"
javac -cp "../target/*":. SerializeToByteArrayExample.java && java -cp ../target/*:. SerializeToByteArrayExample
echo
echo "ForEach example"
javac -cp "../target/*":. ForEachExample.java && java -cp ../target/*:. ForEachExample
echo
echo "Very large example"
javac -cp "../target/*":. VeryLargeBitmap.java && java -cp ../target/*:. VeryLargeBitmap
echo
echo "Serializing to file "
javac -cp "../target/*" SerializeToDiskExample.java &&  java -cp ../target/*:. SerializeToDiskExample
rm bitmapwithoutruns.bin  bitmapwithruns.bin
rm *.class


text:
<?php

namespace Auth\Mapper;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class AbstractMapper implements ServiceLocatorAwareInterface
{
    protected $service_manager;
	protected $Config;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->service_manager = $serviceLocator;
    }

    public function getServiceLocator()
    {
        return $this->service_manager;
    }

    /**
     * Uses sha1 security to create a hash of a string $val
     *
     * @param $val string
     * @param $key string
     * @return string
     */
    public function createHash($val,$key)
    {
        $hash   =   hash_hmac('sha512', $val, $key);
        return $hash;
    }

    /**
     *
     * Encrypt/Decrypt function
     * Note strings should already hashed, salted and md5ed or sha1ed before even thinking of using this
     *
     * @param           $mode 'e'|'d' ==> encrypt|decrypt
     * @param           $string_to_convert
     * @param           $key
     *
     * @return array|bool|string
     */
    public function twoWayCrypt($mode, $string_to_convert, $key)
    {
        $encryptionMethod   =   "AES-256-CBC";
        $raw_output         =   FALSE;

        if($mode === "e")
        {
            // Encrypt
            $iv             =   mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC), MCRYPT_RAND);
            return  $iv . ":ntz:" . openssl_encrypt($string_to_convert, $encryptionMethod, $key, $raw_output, $iv);
        }
        elseif($mode === "d")
        {
            // Decrypt
            $expld          =   explode(':ntz:', $string_to_convert);
            return  openssl_decrypt($expld[1], $encryptionMethod, $key, $raw_output, $expld[0]);
        }
        else
        {
            return FALSE;
        }
    }

    public function _writeLog($priority='info', $message)
    {
        $this->getServiceLocator()->get('Zend\Log\Auth')->$priority($message);
    }

    protected function getConfig()
    {
        if (!$this->Config)
        {
            $this->Config   =   $this->getServiceLocator()->get('config');
        }

        return $this->Config;
    }

    public function areExceptionsAllowed()
    {
        $domainSegments     =   explode(".", $_SERVER['SERVER_NAME']);
        return $domainSegments[0] == 'www' ? FALSE : TRUE;
    }
}


text:
package org.mindinformatics.gwt.domeo.plugins.resource.pmcimages.service;

/**
 * @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
 */
public interface IPmcImagesConnector {

	public void retrievePmcImagesData(IPmcImagesRequestCompleted completionCallback,
			String pmid, String pmcid, String doi) throws IllegalArgumentException;
}


text:
package com.cloud.api.command.user.autoscale;

import com.cloud.acl.RoleType;
import com.cloud.acl.SecurityChecker.AccessType;
import com.cloud.api.ACL;
import com.cloud.api.APICommand;
import com.cloud.api.ApiCommandJobType;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.BaseAsyncCustomIdCmd;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.AutoScaleVmProfileResponse;
import com.cloud.api.response.TemplateResponse;
import com.cloud.api.response.UserResponse;
import com.cloud.context.CallContext;
import com.cloud.event.EventTypes;
import com.cloud.network.as.AutoScaleVmProfile;
import com.cloud.user.Account;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@APICommand(name = "updateAutoScaleVmProfile", description = "Updates an existing autoscale vm profile.", responseObject = AutoScaleVmProfileResponse.class, entityType =
        {AutoScaleVmProfile.class},
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCustomIdCmd {
    public static final Logger s_logger = LoggerFactory.getLogger(UpdateAutoScaleVmProfileCmd.class.getName());

    private static final String s_name = "updateautoscalevmprofileresponse";

    // ///////////////////////////////////////////////////
    // ////////////// API parameters /////////////////////
    // ///////////////////////////////////////////////////

    @ACL(accessType = AccessType.OperateEntry)
    @Parameter(name = ApiConstants.ID,
            type = CommandType.UUID,
            entityType = AutoScaleVmProfileResponse.class,
            required = true,
            description = "the ID of the autoscale vm profile")
    private Long id;

    @Parameter(name = ApiConstants.TEMPLATE_ID,
            type = CommandType.UUID,
            entityType = TemplateResponse.class,
            description = "the template of the auto deployed virtual machine")
    private Long templateId;

    @Parameter(name = ApiConstants.AUTOSCALE_VM_DESTROY_TIME,
            type = CommandType.INTEGER,
            description = "the time allowed for existing connections to get closed before a vm is destroyed")
    private Integer destroyVmGraceperiod;

    @Parameter(name = ApiConstants.COUNTERPARAM_LIST,
            type = CommandType.MAP,
            description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161")
    private Map counterParamList;

    @Parameter(name = ApiConstants.AUTOSCALE_USER_ID,
            type = CommandType.UUID,
            entityType = UserResponse.class,
            description = "the ID of the user used to launch and destroy the VMs")
    private Long autoscaleUserId;

    @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the profile to the end user or not", since =
            "4.4", authorized = {RoleType.Admin})
    private Boolean display;

    // ///////////////////////////////////////////////////
    // ///////////// API Implementation///////////////////
    // ///////////////////////////////////////////////////

    @Override
    public void execute() {
        CallContext.current().setEventDetails("AutoScale Policy Id: " + getId());
        final AutoScaleVmProfile result = _autoScaleService.updateAutoScaleVmProfile(this);
        if (result != null) {
            final AutoScaleVmProfileResponse response = _responseGenerator.createAutoScaleVmProfileResponse(result);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update autoscale vm profile");
        }
    }

    // ///////////////////////////////////////////////////
    // ///////////////// Accessors ///////////////////////
    // ///////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        final AutoScaleVmProfile vmProfile = _entityMgr.findById(AutoScaleVmProfile.class, getId());
        if (vmProfile != null) {
            return vmProfile.getAccountId();
        }
        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are
        // tracked
    }

    public Long getTemplateId() {
        return templateId;
    }

    public Map getCounterParamList() {
        return counterParamList;
    }

    public Long getAutoscaleUserId() {
        return autoscaleUserId;
    }

    public Integer getDestroyVmGraceperiod() {
        return destroyVmGraceperiod;
    }

    public Boolean getDisplay() {
        return display;
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_AUTOSCALEVMPROFILE_UPDATE;
    }

    @Override
    public String getEventDescription() {
        return "Updating AutoScale Vm Profile. Vm Profile Id: " + getId();
    }

    @Override
    public ApiCommandJobType getInstanceType() {
        return ApiCommandJobType.AutoScaleVmProfile;
    }

    @Override
    public void checkUuid() {
        if (getCustomId() != null) {
            _uuidMgr.checkUuid(getCustomId(), AutoScaleVmProfile.class);
        }
    }
}


text:
border : 3px solid blue;
height :100px;
overflow:scroll;
display : none;
}
#anim{
height : 400px;
border : 3px solid red;
display : block;
width : 800px;
  margin : auto;
}

#twin-form {
  margin: 20px;
  padding: 15px;
  border: 1px solid #9999ff;
  background-color: #ddddff;
  width : 800px;
  margin : auto;
}

@font-face {
    font-family: digital;
    src: url(digital.ttf);
}


text:
<!DOCTYPE html>

  <title data-ng-bind="root.htmlTitle">fadeit - software udviklingsvirksomhed</title>
  <meta name="prerender-status-code" content="{{responseStatus}}">

  <meta charset="utf-8">
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <link ng-if="otherLang" rel="alternate" hreflang="{{otherLang}}" href="{{otherLangURL}}" />
  <base href="/">
  <meta name="fragment" content="!">

  <meta name="description" content="{{root.pageDesc}}">
  <meta name="author" content="fadeit ApS">
  <meta name="keywords" content="fadeit, software, udvikling, design, mobil, web, applikationer, systemer, development, aarhus, denmark">

  <meta property="og:site_name" content="fadeit">
  <meta property="og:author" content="fadeit ApS">
  <meta property="og:title" content="{{root.htmlTitle}}">
  <meta property="og:description" content="{{root.pageDesc}}">
  <meta property="og:url" content="{{root.pageURL}}">

  <meta property="og:image" content="https://fadeit.dk/{{img.slug}}/{{img.id}}/{{img.image}}" ng-repeat="img in root.pageImages">
  <meta property="og:image" content="https://fadeit.dk/src/assets/img/brand/fadeit_logo_square.png">
  <meta property="og:type" content="website">

  <meta name="twitter:title" content="{{root.htmlTitle}}">
  <meta name="twitter:description" content="{{root.pageDesc}}">
  <meta name="twitter:url" content="{{root.pageURL}}">

  <meta name="twitter:image" content="https://fadeit.dk/{{img.slug}}/{{img.id}}/{{img.image}}" ng-repeat="img in root.pageImages">
  <meta name="twitter:image" content="https://fadeit.dk/src/assets/img/brand/fadeit_logo_square.png">

  <link href="/src/assets/img/brand/favicon/favicon.ico" rel="shortcut icon" type="image/x-icon">
  <link rel="apple-touch-icon" sizes="57x57" href="/src/assets/img/brand/favicon/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/src/assets/img/brand/favicon/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/src/assets/img/brand/favicon/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/src/assets/img/brand/favicon/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/src/assets/img/brand/favicon/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/src/assets/img/brand/favicon/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/src/assets/img/brand/favicon/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/src/assets/img/brand/favicon/apple-touch-icon-152x152.png">
  <link rel="icon" type="image/png" href="/src/assets/img/brand/favicon/favicon-196x196.png" sizes="196x196">
  <link rel="icon" type="image/png" href="/src/assets/img/brand/favicon/favicon-160x160.png" sizes="160x160">
  <link rel="icon" type="image/png" href="/src/assets/img/brand/favicon/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/src/assets/img/brand/favicon/favicon-16x16.png" sizes="16x16">
  <link rel="icon" type="image/png" href="/src/assets/img/brand/favicon/favicon-32x32.png" sizes="32x32">
  <meta name="msapplication-TileColor" content="#2d89ef">
  <meta name="msapplication-TileImage" content="/src/assets/img/brand/favicon/mstile-144x144.png">

  <link rel="stylesheet" type="text/css" href="/src/assets/css/app.min.css?<%= Date.now() %>" />

            Our website uses JavaScript to render content. Please return once you've enabled it!

            Sorry! Here's a penguin to cheer you up :(

          Phone
           81100810 ·
          info@fadeit.dk ·
          Thorsagervej 11-13, 8550 Ryomgård · CVR 35527192

<%
  //#Scripts are automatically added using grunt, you should not touch this part.

  if(typeof scripts !== 'undefined'){
    scripts.forEach(function (script){
      %><%
    });
  } else {
      %><%
  }
%>


text:
FROM centos/s2i-core-centos7

ENV SUMMARY="MongoDB NoSQL database server" \
    DESCRIPTION="MongoDB (from humongous) is a free and open-source \
cross-platform document-oriented database program. Classified as a NoSQL \
database program, MongoDB uses JSON-like documents with schemas. This \
container image contains programs to run mongod server."

LABEL summary="$SUMMARY" \
      description="$DESCRIPTION" \
      io.k8s.description="$DESCRIPTION" \
      io.k8s.display-name="MongoDB 3.2" \
      io.openshift.expose-services="27017:mongodb" \
      io.openshift.tags="database,mongodb,rh-mongodb32" \
      com.redhat.component="rh-mongodb32-docker" \
      name="centos/mongodb-32-centos7" \
      usage="docker run -d -e MONGODB_ADMIN_PASSWORD=my_pass centos/mongodb-32-centos7" \
      version="3.2" \
      maintainer="SoftwareCollections.org <sclorg@redhat.com>"

ENV MONGODB_VERSION=3.2 \
    # Set paths to avoid hard-coding them in scripts.
    APP_DATA=/opt/app-root/src \
    HOME=/var/lib/mongodb \
    CONTAINER_SCRIPTS_PATH=/usr/share/container-scripts/mongodb \
    # Incantations to enable Software Collections on `bash` and `sh -i`.
    ENABLED_COLLECTIONS=rh-mongodb32 \
    BASH_ENV="\${CONTAINER_SCRIPTS_PATH}/scl_enable" \
    ENV="\${CONTAINER_SCRIPTS_PATH}/scl_enable" \
    PROMPT_COMMAND=". \${CONTAINER_SCRIPTS_PATH}/scl_enable"

EXPOSE 27017

ENTRYPOINT ["container-entrypoint"]
CMD ["run-mongod"]

RUN yum install -y centos-release-scl && \
    INSTALL_PKGS="bind-utils gettext iproute rsync tar shadow-utils rh-mongodb32-mongodb rh-mongodb32 rh-mongodb32-mongo-tools groff-base" && \
    yum install -y --setopt=tsflags=nodocs $INSTALL_PKGS && \
    rpm -V $INSTALL_PKGS && \
    yum clean all

COPY s2i/bin/ $STI_SCRIPTS_PATH

COPY root /

# Container setup
RUN touch /etc/mongod.conf && \
    mkdir -p ${HOME}/data && \
    # Set owner 'mongodb:0' and 'g+rw(x)' permission - to avoid problems running container with arbitrary UID
    /usr/libexec/fix-permissions /etc/mongod.conf ${CONTAINER_SCRIPTS_PATH}/mongod.conf.template \
    ${HOME} ${APP_DATA}/.. && \
    usermod -a -G root mongodb && \
    rpm-file-permissions

VOLUME ["/var/lib/mongodb/data"]

USER 184


text:
/*----------------------------------------------------------------------*
 * Arduino Button Library v1.0                                          *
 * Jack Christensen May 2011, published Mar 2012                        *
 *                                                                      *
 * Library for reading momentary contact switches like tactile button   *
 * switches. Intended for use in state machine constructs.              *
 * Use the read() function to read all buttons in the main loop,        *
 * which should execute as fast as possible.                            *
 *                                                                      *
 * This work is licensed under the Creative Commons Attribution-        *
 * ShareAlike 3.0 Unported License. To view a copy of this license,     *
 * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a       *
 * letter to Creative Commons, 171 Second Street, Suite 300,            *
 * San Francisco, California, 94105, USA.                               *
 *----------------------------------------------------------------------*/

#include "Button.h"

/*----------------------------------------------------------------------*
 * Button(pin, puEnable, invert, dbTime) instantiates a button object.  *
 * pin      Is the Arduino pin the button is connected to.              *
 * puEnable Enables the AVR internal pullup resistor if != 0 (can also  *
 *          use true or false).                                         *
 * invert   If invert == 0, interprets a high state as pressed, low as  *
 *          released. If invert != 0, interprets a high state as        *
 *          released, low as pressed  (can also use true or false).     *
 * dbTime   Is the debounce time in milliseconds.                       *
 *                                                                      *
 * (Note that invert cannot be implied from puEnable since an external  *
 *  pullup could be used.)                                              *
 *----------------------------------------------------------------------*/
setup(struct Button* btn, unsigned char pin, unsigned char puEnable, unsigned char invert, unsigned int dbTime) {
    btn->pin = pin;
    btn->puEnable = puEnable;
    btn->invert = invert;
    btn->dbTime = dbTime;
    if (btn->puEnable != 0)
        pinMode(btn->pin, INPUT_PULLUP);    //enable pullup resistor
    else
        pinMode(btn->pin, INPUT);
    btn->state = digitalRead(btn->pin);
    if (btn->invert != 0) btn->state = !btn->state;
    btn->time = millis();
    btn->lastState = btn->state;
    btn->changed = 0;
    btn->lastChange = btn->time;
}

/*----------------------------------------------------------------------*
 * read() returns the state of the button, 1==pressed, 0==released,     *
 * does debouncing, captures and maintains times, previous states, etc. *
 *----------------------------------------------------------------------*/
unsigned char read(struct Button* btn) {
    static unsigned int ms;
    static unsigned char pinVal;

    ms = millis();
    pinVal = digitalRead(_pin);
    if (btn->invert != 0) pinVal = !pinVal;
    if (ms - btn->lastChange < btn->dbTime) {
        btn->time = ms;
        btn->changed = 0;
        return btn->state;
    }
    else {
        btn->lastState = btn->state;
        btn->state = pinVal;
        btn->time = ms;
        if (btn->state != btn->lastState)   {
            btn->lastChange = ms;
            btn->changed = 1;
        }
        else {
            btn->changed = 0;
        }
        return btn->state;
    }
}

/*----------------------------------------------------------------------*
 * isPressed() and isReleased() check the button state when it was last *
 * read, and return false (0) or true (!=0) accordingly.                *
 * These functions do not cause the button to be read.                  *
 *----------------------------------------------------------------------*/
unsigned char isPressed(struct Button* btn) {
    return btn->state == 0 ? 0 : 1;
}

unsigned char isReleased(struct Button* btn) {
    return btn->state == 0 ? 1 : 0;
}

/*----------------------------------------------------------------------*
 * wasPressed() and wasReleased() check the button state to see if it   *
 * changed between the last two reads and return false (0) or           *
 * true (!=0) accordingly.                                              *
 * These functions do not cause the button to be read.                  *
 *----------------------------------------------------------------------*/
unsigned char wasPressed(struct Button* btn) {
    return btn->state && btn->changed;
}

unsigned char wasReleased(struct Button* btn) {
    return !btn->state && btn->changed;
}

/*----------------------------------------------------------------------*
 * pressedFor(ms) and releasedFor(ms) check to see if the button is     *
 * pressed (or released), and has been in that state for the specified  *
 * time in milliseconds. Returns false (0) or true (1) accordingly.     *
 * These functions do not cause the button to be read.                  *
 *----------------------------------------------------------------------*/
unsigned char pressedFor(struct Button* btn, unsigned int ms) {
    return (btn->state == 1 && btn->time - btn->lastChange >= ms) ? 1 : 0;
}

unsigned char releasedFor(struct Button* btn, unsigned int ms) {
    return (btn->state == 0 && btn->time - btn->lastChange >= ms) ? 1 : 0;
}

/*----------------------------------------------------------------------*
 * lastChange() returns the time the button last changed state,         *
 * in milliseconds.                                                     *
 *----------------------------------------------------------------------*/
unsigned int lastChange(struct Button* btn) {
    return btn->lastChange;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.titan</groupId>
	<artifactId>Pantheon</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>Pantheon Maven Webapp</name>

	<properties>
		<spring.version>3.1.1.RELEASE</spring.version>
		<hibernate.version>3.6.9.Final</hibernate.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<build>
		<sourceDirectory>src/main/java</sourceDirectory>
		<resources>
			<resource>
				<directory>src/conf</directory>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<finalName>Pantheon</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<compilerVersion>${jdk-compiler-version}</compilerVersion>
					<source>${jdk-source-version}</source>
					<target>${jdk-target-version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.4</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warName>${project.artifactId}</warName>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<includes>
						<include>**/*Test*.java</include>
					</includes>
					<argLine>-Xmx256M</argLine>
					<parallel>methods</parallel>
					<threadCount>10</threadCount>
				</configuration>
			</plugin>

			<!-- <plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>1.8</version>
				<executions>
					<execution>
						<id>add-source</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>add-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>src/test</source>
							</sources>
						</configuration>
					</execution>
				</executions>
			</plugin> -->
		</plugins>

	</build>

	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.22</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.0.4.RELEASE</version>
		</dependency>
		<!-- log -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>

		<!-- test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
	</dependencies>
</project>


text:
require "spec_helper"

describe Mongoid::Extensions::Symbol::Inflections do

  describe "invert" do

    context "when :asc" do

      it "returns :desc" do
        :asc.invert.should eq(:desc)
      end
    end

    context "when :ascending" do

      it "returns :descending" do
        :ascending.invert.should eq(:descending)
      end
    end

    context "when :desc" do

      it "returns :asc" do
        :desc.invert.should eq(:asc)
      end
    end

    context "when :descending" do

      it "returns :ascending" do
        :descending.invert.should eq(:ascending)
      end
    end
  end

  describe "#gt" do

    it 'returns :"foo $gt"' do
      ret = :foo.gt
      ret.key.should eq(:foo)
      ret.operator.should eq("gt")
    end
  end

  describe "#near" do

    it 'returns :"foo $near"' do
      ret = :foo.near
      ret.key.should eq(:foo)
      ret.operator.should eq("near")
    end
  end

  describe "#not" do

    it 'returns :"foo $not"' do
      ret = :foo.not
      ret.key.should eq(:foo)
      ret.operator.should eq("not")
    end
  end

  describe "#within" do

    it "returns :foo $within" do
      ret = :foo.within
      ret.key.should eq(:foo)
      ret.operator.should eq("within")
    end
  end
end


text:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'concrete');


text:
import Texture2D from "../Resource/Texture2D";

export default class TextureSizeCalculator {
  public static getPow2Size(width: number, height: number): { width: number, height: number } {
    const nw = Math.pow(2, Math.ceil(Math.log2(width))); // largest 2^n integer that does not exceed s
    const nh = Math.pow(2, Math.ceil(Math.log2(height))); // largest 2^n integer that does not exceed s
    return {
      width: Math.max(1, Math.min(nw, Texture2D.maxTextureSize)),
      height: Math.max(1, Math.min(nh, Texture2D.maxTextureSize)),
    };
  }
}


text:
window.UserEventListView = Backbone.View.extend({
    tagName: 'div',
    initialize: function() {
        this.model.bind('reset', this.render, this);
        this.model.bind('change', this.render, this);
    },
    render: function() {
        _.each(this.model.models, function(event) {
            $(this.el).attr('class', 'event-list').append(new UserEventListItemView({model: event}).render().el);
        }, this);
        return this;
    }
});

window.UserEventListItemView = Backbone.View.extend({
    tagName: 'div',
    template: _.template($('#user-event-list-tpl').html()),
    render: function() {
        $(this.el).attr('class', 'user-event').html(this.template(this.model.toJSON()));
        return this;
    },
    events: {
        "click .delete-event": "deleteEvent",
    },
    initialize: function() {
        this.model.bind("destroy", this.close, this);
        this.model.bind('change', this.render, this);
    },
    deleteEvent: function() {
        this.model.url = 'api/logged/account/1/events/' + this.model.get('id');
        this.model.destroy();
    }
});


text:
<?php
/**
 * Hook Component
 *
 * Loads DebugKit.Toolbar component in ALL controllers.
 */
    Croogo::hookComponent('*', 'DebugKit.Toolbar');
?>


text:
using System.Web.Mvc;
using Site.Models;

namespace Site
{
    public class SessionAuthorize : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Session["User"] as Users == null)
            {
                context.Result = new RedirectResult("/Login");
            }
        }
    }

    public class AdminAuthorize : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            Users user = context.HttpContext.Session["User"] as Users;
            if (user == null || user.RoleID != 1)
            {
                context.Result = new RedirectResult("/Shop");
            }
        }
    }
}


text:
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';

const metadata = new ChartMetadata({
  category: t('Table'),
  name: t('Time-series Table'),
  description: t(
    'Compare multiple time series charts (as sparklines) and related metrics quickly.',
  ),
  tags: [
    t('Advanced-Analytics'),
    t('Multi-Variables'),
    t('Comparison'),
    t('Legacy'),
    t('Percentages'),
    t('Tabular'),
    t('Text'),
    t('Trend'),
  ],
  thumbnail,
  useLegacyApi: true,
});

export default class TimeTableChartPlugin extends ChartPlugin {
  constructor() {
    super({
      metadata,
      transformProps,
      loadChart: () => import('./TimeTable.jsx'),
    });
  }
}


text:
#ifndef S60_NAV_TASK_GUI_COMMAND_HANDLER_H
#define S60_NAV_TASK_GUI_COMMAND_HANDLER_H

#include "NavTaskGuiHandler.h"

class CS60NavTaskGuiCommandHandler : public CNavTaskGuiCommandHandler
{
   CS60NavTaskGuiCommandHandler(class CWayFinderAppUi* appUi)
      : iAppUi(appUi), iEditCommand(0), iConfirmCommand(0) {}
   void ConstructL();
public:
   static class CS60NavTaskGuiCommandHandler* NewL(class CWayFinderAppUi* appUi);

   ~CS60NavTaskGuiCommandHandler();

private:
   /* Convenience method for sending GuiProtFileMess. */
   virtual void SendFileOperationL(class isab::GuiFileOperation* op);

   /* Show no files error popup */
   virtual void ShowNoFilesErrorDialog();

   /* Convenience method for creating an array from a location vector */
   void InitArrayFromLocationVector(CDesCArrayFlat* aArray,
         const isab::LocationVector* loc);

   /* Show select file list */
   TInt ShowSelectList(const isab::LocationVector* loc,
         TInt lastUsedIndex);

   /* Show save file edit box popup */
   TBool ShowFileNameEditBox(char *defaultName);

   /* Show confirm overwrite popup */
   TBool ShowOverwriteConfirmPopup(char *additional);

   /* Show confirm delte popup */
   TBool ShowDeleteConfirmPopup(char *additional);

   /* Handle select operation */
   virtual void HandleGuiFileOperationSelect(isab::GuiFileOperationSelect* op);

   /* Handle confirm operation */
   virtual void HandleGuiFileOperationConfirm(isab::GuiFileOperationConfirm* op);

public:
   /* Handle callbacks. */
   void GenerateEvent(enum TNTCommandEvent aEvent);
   void HandleGeneratedEventL(enum TNTCommandEvent aEvent);

private:

   /* Pointer to AppUi for sending messages. */
   class CWayFinderAppUi* iAppUi;

   /* Saved data for editbox callback. */
   class CEditFileNameOperation* iEditCommand;

   /* Saved data for confirmbox callback. */
   class CConfirmCommandOperation* iConfirmCommand;

   /* Event generator. */
   typedef CEventGenerator<CS60NavTaskGuiCommandHandler, enum TNTCommandEvent>
      CTNTEventGenerator;
   CTNTEventGenerator* iEventGenerator;

};

#endif


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.api;

import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;

/**
 * Represents a Groovy lambda expression body in a block form.
 */
public interface GrBlockLambdaBody extends GrLambdaBody, GrCodeBlock {
}


text:
package array;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Q997FindTheTownJudge {

    //Difficulty: Easy
    //TAG: array

    /**
     * 997. Find the Town Judge
     * In a town, there are N people labelled from 1 to N.  There is a rumor that one of these people is secretly the town judge.
     *
     * If the town judge exists, then:
     *
     * The town judge trusts nobody.
     * Everybody (except for the town judge) trusts the town judge.
     * There is exactly one person that satisfies properties 1 and 2.
     * You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
     *
     * If the town judge exists and can be identified, return the label of the town judge.  Otherwise, return -1.
     *
     *
     *
     * Example 1:
     *
     * Input: N = 2, trust = [[1,2]]
     * Output: 2
     * Example 2:
     *
     * Input: N = 3, trust = [[1,3],[2,3]]
     * Output: 3
     * Example 3:
     *
     * Input: N = 3, trust = [[1,3],[2,3],[3,1]]
     * Output: -1
     * Example 4:
     *
     * Input: N = 3, trust = [[1,2],[2,3]]
     * Output: -1
     * Example 5:
     *
     * Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
     * Output: 3
     *
     *
     * Note:
     *
     * 1 <= N <= 1000
     * trust.length <= 10000
     * trust[i] are all different
     * trust[i][0] != trust[i][1]
     * 1 <= trust[i][0], trust[i][1] <= N
     */

    /*
    Solution 1:
    record all people -> trusts in a map
    intersect all sets together find public trust people
    check if there is this kind of person and the person trust nobody by !map.containsKey(judge)

    Time: O(n)
    Space: O(n)
     */

    public int findJudge(int N, int[][] trust) {
        if (N <= 0 || trust == null) return -1;
        if (N == 1 && trust.length == 0) return 1;
        Map<Integer, Set<Integer>> map = new HashMap<>();
        Set<Integer> judgeSet = new HashSet<>();
        for (int[] arr: trust) {
            map.putIfAbsent(arr[0], new HashSet<>());
            map.get(arr[0]).add(arr[1]);
            judgeSet.add(arr[1]);
        }
        for (Set<Integer> set: map.values()) {
            judgeSet.retainAll(set);
        }
        if (judgeSet.size() == 0) return -1;
        int judge = judgeSet.iterator().next();
        return map.containsKey(judge) ? -1 : judge;
    }

    /*
    Solution 2:
    Similar to 277, loop once add count of current person by:
    trust someone else, count--
    been trusted, count++

    finally the one has trust with N - 1 became the judge

    Time: O(n)
    Space: O(n)
     */

    public int findJudge2(int N, int[][] trust) {
        int[] count = new int[N+1];
        for (int[] t: trust) {
            count[t[0]]--;
            count[t[1]]++;
        }
        for (int i = 1; i <= N; ++i) {
            if (count[i] == N - 1) return i;
        }
        return -1;
    }

}


text:
type: post
category: fe
---
Web UI Security matters
Read 51 penetration test and Front-End-Checklist first.

1. Reverse tab nabbing
CRITICALITY:

An attacker might use this technique to silently load other pages on the parent tab which can be used for malicious operations such as phishing attacks.

SUGGESTED FIX:

Please ensure that user-controlled (anchor tag with target="_blank") links have the following attribute set:

Copy
rel="noopener noreferrer"
More about the fix: https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#tabnabbing

2. Content security policy
CRITICALITY:
An attacker may inject scripts into the HTML files to steal user's information, such as Cookie, JWT token. If the CSP header is not offered, the browser will use same-origin policy standard, attackers can do XSS attack by injecting <img/> tags or <script/> tags.

SUGGESTED FIX:
Currently we have two kinds of projects:

S3 bucket project: The CI uploads webpack compiled static files to AWS S3 bucket,  the server is served by AWS cloud front.
Node project: The project has one node server to serve itself.
For S3 bucket project
Most of the CSP directives can be added using <meta/> tags.

install csp-html-webpack-plugin into the projectyarn add -D csp-html-webpack-plugin

you can use the configuration in admin.aftership.com, including reCAPTCHA, Newrelic Browser & google-analytics.

Some directives such as frame-ancestors can not be added by <meta/> tag. A response header is needed to add to the website.

You cannot add frame-ancestors directive using <meta/>

add  frame-ancestor _and _X-Frame-Options _in AWS cloudfront _to avoid click jacking attack.

Validations

You can check your CSP content in [CSP Evaluator](https://csp-evaluator.withgoogle.com/).

3. Subresource Integrity
#
CRITICALITY
Attackers can inject arbitrary malicious content info files on the CDN.

SUGGESTED FIX
For files from CDN add integrity & crossorigin field in script and link  tags, you can calculate the hash by using SRI Hash Generator.

Copy
<script src="https://example.com/example-framework.js"
        integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
        crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
        rel="stylesheet"
        integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
        crossorigin="anonymous"/>

If the project is a S3 bucket project, the following webpack plugin can add integrity for the compiled statics.

webpack-subresource-integrity

You need to set output.crossOriginLoading to anonymous in webpack.config.js.

不推荐用SRI,因为integrity会加上用户的UA


text:
"use strict";

describe("defaults: change default plugin options", function() {

	var defaults = $.extend({}, $.fn.intlTelInput.defaults);

	beforeEach(function() {
		intlSetup();
		input = $("<input>");
	});

	afterEach(function() {
		input.intlTelInput("destroy");
		input = null;
		$.fn.intlTelInput.defaults = defaults;
	});

	it("set default option initialCountry=ru", function() {
		$.fn.intlTelInput.defaults.initialCountry = "ru";
		input.intlTelInput();
		expect(input.intlTelInput("getSelectedCountryData").iso2).toEqual("ru");
	});

});


text:
import Users from 'meteor/vulcan:users';

const membersActions = [
  "posts.upvote",
  "posts.cancelUpvote",
  "posts.downvote",
  "posts.cancelDownvote",
  "comments.upvote",
  "comments.cancelUpvote",
  "comments.downvote",
  "comments.cancelDownvote"
];
Users.groups.members.can(membersActions);


text:
{% extends "base.html" %}
{% block first_column %}

Search Results '{{ search_term }}'

Loading...

{% endblock %}


text:
<resources>
    <string name="app_name">GLFFT Test and Bench Suite</string>
    <string name="action_run_test_suite">Run Test Suite</string>
</resources>