text:
package se.simonsoft.cms.indexing.graphics;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;

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

import se.repos.indexing.IndexingDoc;
import se.repos.indexing.IndexingItemHandler;
import se.repos.indexing.item.IndexingItemProgress;

public class HandlerGraphicsResolution implements IndexingItemHandler {

	private static final Logger logger = LoggerFactory.getLogger(HandlerGraphicsResolution.class);

	// #1510 Core 'embd_cms_' prefix included in many reporting queries (use 'embd_cms-themodule_' for specific stuff).
	private static final String FIELD_PREFIX = "embd_cms_";

	private static final Set<String> PNG_FIELDS = new HashSet<String>(Arrays.asList("embd_height", "embd_width", "embd_Dimension_VerticalPixelSize", "embd_Dimension_HorizontalPixelSize"));
	// Require resolution in both directions (otherwise typically not successfully mapped to XMP)
	private static final Set<String> JPG_FIELDS = new HashSet<String>(Arrays.asList("xmp_tiff.ImageLength", "xmp_tiff.ImageWidth", "xmp_tiff.YResolution", "xmp_tiff.XResolution"));
	// Simplest form without calculation.
	private static final Set<String> XMP_FIELDS = new HashSet<String>(Arrays.asList("xmp_tiff.ImageLength", "xmp_tiff.ImageWidth"));

	// JPG interesting fields: "xmp_tiff.ResolutionUnit":"Inch", "xmp_tiff.XResolution":"300.0","xmp_tiff.YResolution":"300.0","xmp_tiff.ImageWidth":"3646","xmp_tiff.ImageLength":"4146"

	@Inject
	public HandlerGraphicsResolution() {}

	@Override
	public void handle(IndexingItemProgress progress) {

		IndexingDoc doc = progress.getFields();

		if (hasFields(doc, PNG_FIELDS)) {
			try {
				doc.addField(FIELD_PREFIX + "css_height", calculateDimensionPixelSize(getInt(doc, "embd_height"), getDouble(doc, "embd_Dimension_VerticalPixelSize")));
				doc.addField(FIELD_PREFIX + "css_width", calculateDimensionPixelSize(getInt(doc, "embd_width"), getDouble(doc, "embd_Dimension_HorizontalPixelSize")));
			} catch (Exception e) {
				// Best effort
				logger.warn("Failed to extract CSS dimensions: {}", e.getMessage(), e);
			}
		} else if (hasFields(doc, JPG_FIELDS)) {
			try {
				if (hasFields(doc, new HashSet<>(Arrays.asList("xmp_tiff.ResolutionUnit")))) {
					Object unit = doc.getFieldValue("xmp_tiff.ResolutionUnit");
					// The only other value should be cm, not sure how Tika represents it.
					if (!"Inch".equals(unit)) {
						throw new RuntimeException("Dimension calculation currently not supported for unit: " + unit);
					}
				}
				doc.addField(FIELD_PREFIX + "css_height", calculateDimensionDpi(getInt(doc, "xmp_tiff.ImageLength"), getDouble(doc, "xmp_tiff.YResolution")));
				doc.addField(FIELD_PREFIX + "css_width", calculateDimensionDpi(getInt(doc, "xmp_tiff.ImageWidth"), getDouble(doc, "xmp_tiff.XResolution")));
			} catch (Exception e) {
				// Best effort
				logger.warn("Failed to extract CSS dimensions: {}", e.getMessage(), e);
			}
		} else if (hasFields(doc, XMP_FIELDS)) {
			try {
				doc.addField(FIELD_PREFIX + "css_height", getInt(doc, "xmp_tiff.ImageLength"));
				doc.addField(FIELD_PREFIX + "css_width", getInt(doc, "xmp_tiff.ImageWidth"));
			} catch (Exception e) {
				// Best effort
				logger.warn("Failed to extract CSS dimensions: {}", e.getMessage(), e);
			}
		}
	}

	String calculateDimensionPixelSize(int pixels, double pixelSize) {
		// CSS pixel is normatively defined as 1/96th of 1 inch
		// https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel

		// PNG:
		// Tika extracts HorizontalPixelSize / VerticalPixelSize in mm.

		double size = (pixels * pixelSize) / 25.4; // image size in inch.
		double css = size*96;

		return Long.toString(Math.round(css));
	}

	String calculateDimensionDpi(int pixels, double dpi) {
		// CSS pixel is normatively defined as 1/96th of 1 inch
		// https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel

		// JPG etc:
		// Tika extracts HorizontalPixelSize / VerticalPixelSize in mm.

		double pixelSize = 25.4 / dpi; // pixel size from dpi
		return calculateDimensionPixelSize(pixels, pixelSize);
	}

	private static int getInt(IndexingDoc doc, String field) {
		String v = doc.getFieldValue(field).toString();
		return Integer.parseInt(v);
	}

	private static double getDouble(IndexingDoc doc, String field) {
		String v = doc.getFieldValue(field).toString();
		return Double.parseDouble(v);
	}

	private static boolean hasFields(IndexingDoc doc, Set<String> fields) {
		for (String f: fields) {
			if (!doc.containsKey(f)) {
				return false;
			}
		}
		return true;
	}

	@Override
	public Set<Class<? extends IndexingItemHandler>> getDependencies() {
		return null;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NYMP</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/paper/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">

NYMP3
                <button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1">Toggle navigation</button>

Home

NYMP3

Super eenvoudig een video van Youtube naar een MP3 omzetten!

                    <form action="/download" method="post" target="_self">

                            URL
                            <input class="form-control" type="text" name="link" placeholder="https://www.youtube.com/watch?v=k4LphhTa_xg">

10%

                        <button class="btn btn-primary" type="submit">Download </button>
                    </form>

2017, Jonas Claes.

redpajama_set_name: RedPajamaGithub


text:
/* $Id$ */
#include "softbot.h"
#include "mp_api.h"
#include "mod_mp/mod_mp.h"
#include "mod_api/udp.h"
#include "mod_api/did_daemon.h"

#include <sched.h>
#include <pthread.h>

#include "mod_did_daemon.h"
#include "mod_did_message.h"

#define NUM_OF_CHILD	1

/******************************************************************************/
static uint32_t DSgetPrefix(char *szKey);
static uint32_t DSgetPrefixWithPrefixBit(char *szKey, int16_t byPrefixBit);

/*static int16_t DSsortDidBK(CDidBK *bucket);*/
static did_slot_t* DSfindDid(char *szKey);
static did_slot_t* DSfindDid_BS ( CDidBK *szBK , char *szKey , int16_t StartPos ,
								int16_t FinishPos );
static CDidBK* DSfindBK ( char *szKey );

static did_slot_t* DSaddDidSL(CDidBK *bucket, did_slot_t slot);
/*static did_slot_t* DSresolveURLfind ( char *szUrl );*/
/*static did_slot_t* DSresolveURLupdate ( char *szUrl , CDidState szState);*/
/*static did_slot_t* DSresolveURLnew (char *szUrl);*/
static did_slot_t* DSnewSL ( char *szUrl , DocId Did );

static int16_t DSdoubleDidBKTable(void);
static int16_t DSpartitionDidBKTable(CDidBK *bucket);

static int16_t DSmd5 ( char* szUrl, char* key );

static void DSsaveData (void);
static void load_data (void);
static did_slot_t* load_slot	(did_slot_t tmpSL);
/******************************************************************************/

static DocId gDidCount;
static int32_t DSsaveCount=0;
static did_slot_t DSsaveSL[MAX_LOAD_BLOCK];

static int slave_thread_num = MAX_PC;
static scoreboard_t scoreboard[] = { THREAD_SCOREBOARD(NUM_OF_CHILD) };

static pthread_mutex_t sock_lock;
static pthread_mutex_t slot_lock;

static int thread_main(slot_t *slot);
static void did_server_kill (int);

/*static int8_t DSDidState;*/
/*static int8_t DSDidOperation;*/
/*static int8_t UDP_LOST_TEST=0;*/

static char m_didSlotPath[256] = DB_PATH"/did/docid.slots";
static char mBindAddr[SHORT_STRING_SIZE] = "127.0.0.1";
static char mBindPort[SHORT_STRING_SIZE] = "";
static int udp_sock;

// internal function definitions
static int isProperProtocol(ClientMsg *msg);
static int executeClientMsg(ServerMsg *svrmsg, ClientMsg *climsg);
static int findId(char* pKey, ServerMsg *msg);
static int makeId(char* pKey, ServerMsg *msg);

static void _do_nothing(int sig);
static void _shutdown(int sig);
static void _graceful_shutdown(int sig);

/*************************** find, make DocId *******************************/
static int findId(char* pKey, ServerMsg *m_svrMsg){
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t *didSlot;

	DSmd5(pKey, tmpKey);
	didSlot = DSfindDid(tmpKey);

	m_svrMsg->result = 0;
	if (didSlot != NULL) {	// if founded
		m_svrMsg->status = DI_OLD_REGISTERED;
		m_svrMsg->result = didSlot->docId;
		return SUCCESS;
	}

	// not found (not registered key)
	m_svrMsg->status = DI_NOT_REGISTERED;
	return FAIL;
}

static int findIdandDelete(char* pKey, ServerMsg *m_svrMsg){
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t *didSlot;

	DSmd5(pKey, tmpKey);
	didSlot = DSfindDid(tmpKey);

	m_svrMsg->result = 0;
	if (didSlot != NULL) {	// if founded
		m_svrMsg->status = DI_OLD_REGISTERED;
		m_svrMsg->result = didSlot->docId;
		memset(didSlot, 0x00, sizeof(did_slot_t));
		return SUCCESS;
	}

	// not found (not registered key)
	m_svrMsg->status = DI_NOT_REGISTERED;
	return FAIL;
}

static int makeId(char *pKey, ServerMsg *m_svrMsg){
	DocId docId=0;
	did_slot_t *pTmpSL;
	char oldregistered=0;

	m_svrMsg->olddid = 0;
	if (findIdandDelete(pKey, m_svrMsg) == SUCCESS) {
		m_svrMsg->olddid = m_svrMsg->result;
		m_svrMsg->status = DI_OLD_REGISTERED;
		oldregistered = 1;
	}

	// Á¦ÀÏ Å« ¼ö´Â ¸¸¾àÀ» À§ÇØ »ç¿ëÇÏÁö ¾Ê´Â´Ù.
	docId = gDidCount+1;
	if (docId == 0) { // id overflow
		m_svrMsg->status = DI_ID_OVERFLOW;
	}
	else {		// if not id overflow ( gDidCount<=2^sizeof(int)-1 )
/*		debug("here !!!! : gDidCount %ld", gDidCount);*/
		docId = gDidCount;
		gDidCount++;
		if (!oldregistered)
			m_svrMsg->status = DI_NEW_REGISTERED;
		m_svrMsg->result = docId;

		pTmpSL = DSnewSL(pKey, docId);
		if (pTmpSL == NULL) {
			return FAIL;
		}

		memcpy(&DSsaveSL[DSsaveCount++] , pTmpSL , sizeof(did_slot_t));

		if (!(DSsaveCount%MAX_LOAD_BLOCK))
		{
			DSsaveData();
			DSsaveCount=0;
		}
	}

	return SUCCESS;
}
/****************************************************************************/

//m_cliMsg.majorVersion == CURRENT_MAJOR_VER (need difinition at the head file)
static int isProperProtocol(ClientMsg *m_cliMsg)
{
	if (strcmp(m_cliMsg->aProtocolId, "DITP") != 0)
		return FALSE;
/*	if (m_cliMsg.majorVersion != 0)*/
/*		return FALSE;*/
/*	if (m_cliMsg.minorVersion != 0)*/
/*		return FALSE;		*/

	return TRUE;
}

// execute the method for which client calls,
// and prepare for the server message
static int executeClientMsg(ServerMsg *m_svrMsg, ClientMsg *m_cliMsg)
{
	char *pKey;
/*	did_slot_t *didSlot;*/

	pKey = m_cliMsg->mesg.aKey;
	if (m_cliMsg->mesg.nKeyLen == MAX_DID_KEY_LEN) {
		pKey[MAX_DID_KEY_LEN-1] = '\0';
	}
	else {
		pKey[m_cliMsg->mesg.nKeyLen] = '\0';
	}
	debug("key: %s",pKey);
	m_svrMsg->nMethod = m_cliMsg->mesg.nMethod;
	m_svrMsg->session = m_cliMsg->session;

	switch (m_cliMsg->mesg.nMethod) {
		case DITP_GET_ID:
			findId(pKey, m_svrMsg);
			debug("method DITP_GET_ID: %ld", m_svrMsg->result);
			break;
		case DITP_GET_NEW_ID:
			makeId(pKey, m_svrMsg);
			debug("method DITP_GET_NEW_ID: %ld", m_svrMsg->result);
			break;
		case DITP_GET_NUM_DOC:
			m_svrMsg->result = gDidCount-1;
			m_svrMsg->status = SUCCESS;
			break;
		default:
			return FAIL;
	}
	return SUCCESS;
}

/*	Daemon main loop
 *	@author gramo @modifier: jiwon, aragorn
 */
static int thread_main(slot_t *slot)
{
	int ret;
	struct sockaddr from;
	socklen_t fromlen = sizeof(struct sockaddr);
	char buf[20];
	char test[30];
	ClientMsg m_cliMsg = {
		/*proctocolId*/"DITP", /*majorVer*/0, /*minorVer*/0, /*check*/0,
		/*ClientRequest*/ { /*key*/"", /*keyLen*/0, /*method*/0 } };
	ServerMsg m_svrMsg = { /*stat*/0, /*method*/0, /*result*/0, /*check*/0 };

	while ( 1 )
	{
		if ( scoreboard->shutdown || scoreboard->graceful_shutdown ) break;

		slot->state = SLOT_WAIT;
		sprintf(test, "i'm slot[%d]", slot->id);

		if ( pthread_mutex_lock(&sock_lock) != 0 ) {
			error("slot[%d]: pthread_mutex_lock: %s",
					slot->id, strerror(errno));
			continue;
		}

		if ( scoreboard->shutdown || scoreboard->graceful_shutdown ) {
			pthread_mutex_unlock(&sock_lock);
			break;
		}

		ret = sb_run_udp_recvfrom(udp_sock,
			(void *)&m_cliMsg, sizeof(ClientMsg),&from, &fromlen, 0);
		pthread_mutex_unlock(&sock_lock);

		/* if graceful_shutdown is on, replying for the request is ok */
		if ( scoreboard->shutdown ) break;

		if (ret <= 0) {      // if packet length is 0 or error occurs,
			info("slot[%d]: UCP_accept() failed", slot->id);
            continue;        // receive again
        }

		if ( inet_ntop(AF_INET,
				(void *)&((struct sockaddr_in *)(&from))->sin_addr, buf, 20)
				== NULL ) {
			error("inet_ntop returned null errno:%s",strerror(errno));
		}
		else{
			debug("slot[%d]: from: %s:%d", slot->id, buf,
					ntohs(((struct sockaddr_in *)(&from))->sin_port));
		}

		slot->state = SLOT_READ;
		time(&(slot->recent_request));

        if (isProperProtocol(&m_cliMsg) < 0) {
			// if protocol signature is wrong,
			info("slot[%d]: wrong procotol signature", slot->id);
			slot->state = SLOT_FINISH;
            continue; // accept another message
        }

		slot->state = SLOT_PROCESS;
		if ( pthread_mutex_lock(&slot_lock) != 0 ) {
			error("slot[%d]: pthread_mutex_lock: %s",
					slot->id, strerror(errno));
			continue;
		}

        if (executeClientMsg(&m_svrMsg, &m_cliMsg) < 0) {
			// if requesting unknown method
			info("slot[%d]: unknown method", slot->id);
			slot->state = SLOT_FINISH;
			pthread_mutex_unlock(&slot_lock);
            continue; // accept another message
        }
		pthread_mutex_unlock(&slot_lock);

		sb_run_udp_sendto(udp_sock,
			&m_svrMsg, sizeof(ServerMsg), &(from), fromlen, UDP_TIMEOUT);

    } // endless while loop

	slot->state = SLOT_FINISH;
	debug("slot[%d] exits", slot->id);
	return SUCCESS;
}

/** get prefix by key.
 *
 *	@author	woosong
 */
static uint32_t DSgetPrefix(char *szKey) {
    uint32_t divisor, remainder;
    uint32_t prefix;
    uint32_t i;

    divisor = gDidBKTable->byPrefixBit / 8;
    remainder = gDidBKTable->byPrefixBit % 8;

	for ( i=0,prefix=0 ;i<divisor; i++ ) {
		prefix = (prefix << 8) + (uint8_t)szKey[i];
	}

	if (remainder) {
		prefix = (prefix << remainder) + (((uint8_t)szKey[i]) >> ( 8 - remainder ));
	}

    return prefix;
}

static uint32_t DSgetPrefixWithPrefixBit(char *szKey, int16_t byPrefixBit) {
	uint32_t divisor, remainder;
	uint32_t prefix;
	uint32_t i;

	divisor = byPrefixBit / 8;
	remainder = byPrefixBit % 8;

    prefix = 0;

	for(i=0; i<divisor; i++) {
		prefix = (prefix << 8) + (uint8_t)szKey[i];
	}

	if (remainder) {
		prefix = (prefix << remainder) + ((uint8_t)szKey[i] >> ( 8 - remainder ));
	}

	return prefix;
}

/**
 *	compare slots with key.
 *	compare function for qsort.
 *
 *	@author woosong
 *	@param	*a	did_slot_t
 *	@param	*b	did_slot_t
 *	@return	memcmp(a->szKey, b->szKey, SYS_DID_KEYSIZE);
 */
static int DScompareSL(const void *a, const void *b) {
    return memcmp(((did_slot_t *)a)->szKey, ((did_slot_t *)b)->szKey, SYS_DID_KEYSIZE);
}

/** sort bucket.

	@author woosong
	@param *bucket	CDidBK
	@return int16_t
	*/
#if 0
static int16_t DSsortDidBK(CDidBK *bucket) {
    qsort(bucket->aDidSL, bucket->nSlotCnt, sizeof(did_slot_t), DScompareSL);
	return SUCCESS;
}
#endif

/**	add a slot to bucket.

    @author woosong
    @param  *bucket CDidBK
    @param  *slot   did_slot_t
    @return NULL - Bucket FULL
    */
static did_slot_t *DSaddDidSL(CDidBK *bucket, did_slot_t slot) {
	int i, j, k;

    if ((bucket) && (uint32_t)((bucket)->nSlotCnt) < MAX_DID_SL) {
		i = 0;

		if ((bucket)->nSlotCnt > 0) {
			k = j = (bucket)->nSlotCnt - 1;
			while (j > i) {
				k = ( i + j ) / 2;
				if (DScompareSL(&((bucket)->aDidSL[k]), &slot)>0)
					j = k;
				else
					i = k + 1;
			}
			if (DScompareSL(&((bucket)->aDidSL[i]), &slot)<0)
				i++;
		}

		j = (bucket)->nSlotCnt;
		if (i != j)
			memmove(&((bucket)->aDidSL[i+1]),
					&((bucket)->aDidSL[i]),
					(j-i) * sizeof(did_slot_t));
        memcpy(&((bucket)->aDidSL[i]), &slot, sizeof(did_slot_t));
        (bucket)->nSlotCnt++;
		return (&((bucket)->aDidSL[i]));
    }
    else {
        return (did_slot_t *)0;
    }
}

/** increases prefixbit by 1 and resets bucket table.

    @author woosong
    @param  void
    @return 0 - OK.
    */
static int16_t DSdoubleDidBKTable(void) {
    int16_t i;
    int8_t byPrefixBit;

    byPrefixBit = (++gDidBKTable->byPrefixBit);

	debug("DSdouble! %d %ld\n", byPrefixBit, gDidCount);

    for(i = (1 << byPrefixBit) - 1; i >= 0; i--)
        gDidBKTable->pDidBK[i] = gDidBKTable->pDidBK[i/2];

    return 0;
}

/** partition Bucket.
	@author	woosong
	@param	*bucket	CDidBK
	@return	0 - OK. 1 - Not partitionable. 2 - memory alloc error.
	*/
static int16_t DSpartitionDidBKTable(CDidBK *bucket) {
	int i, j;
	int depth;
	int8_t byPrefixBit;
	CDidBK *bucket2;

	depth = gDidBKTable->byPrefixBit - bucket->byPrefixBit;

	if (depth <= 0) return 1;

	bucket2 = (CDidBK *)sb_calloc(1, sizeof(CDidBK));
	if(bucket2 == 0x00) {
		crit("cannot allocate for bucket:%s", strerror(errno));
		return 2;
	}

	bucket2->nSlotCnt = 0;
	byPrefixBit = bucket2->byPrefixBit = bucket->byPrefixBit + 1;

	for(i = 0; i < bucket->nSlotCnt; i++)
		if(DSgetPrefixWithPrefixBit(bucket->aDidSL[i].szKey, byPrefixBit) % 2) break;

	j = i;
	for(; i < bucket->nSlotCnt; i++)
	{
		DSaddDidSL(bucket2, bucket->aDidSL[i]);
	}
	bucket->nSlotCnt = j;
	bucket->byPrefixBit++;

	for(i = 0; i < (1 << gDidBKTable->byPrefixBit); i++)
	{
		if (gDidBKTable->pDidBK[i] == bucket)
			if ((i >> (depth - 1)) % 2)
				gDidBKTable->pDidBK[i] = bucket2;
	}
	return 0;
}

/****************************** MD5 related *********************************/
/** url to md5 key of SYS_DID_KEYSIZE.

	@author	woosong
	@param szUrl	url
	@return char*	SYS_DID_KEYSIZE bytes of md5 key digest
	*/
static int16_t DSmd5( char* szUrl, char *key ) {
	MD5_CTX context;
	unsigned char digest[16];
	unsigned int len = strlen(szUrl);

	MD5Init( &context );
	MD5Update( &context, szUrl, len );
	MD5Final( digest, &context );

	memcpy(key, digest, SYS_DID_KEYSIZE);

	return 0;
}
/****************************************************************************/

/** find Did.

        @author gramo
        @param  char* szKey
        @return , *did_slot_t - Success , NULL - Fail
                 */
static did_slot_t* DSfindDid ( char *szKey ) {

        CDidBK *currentBK;

        currentBK = DSfindBK( szKey );

		if (currentBK != 0 )
        	return DSfindDid_BS (currentBK , szKey , 0 , (currentBK)->nSlotCnt);

		return (did_slot_t*)NULL;
}

#if 0
static void printBK(CDidBK *a, int16_t t) {
	int i;
	info("Bucket : %d \n************",t);
	for(i=0;i<((a->nSlotCnt>100) ? 100 : a->nSlotCnt);i++)
		info("slot[%d]:%x %x %x %x %x %x",
				i,
				(unsigned char)a->aDidSL[i].szKey[0],
				(unsigned char)a->aDidSL[i].szKey[1],
				(unsigned char)a->aDidSL[i].szKey[2],
				(unsigned char)a->aDidSL[i].szKey[3],
				(unsigned char)a->aDidSL[i].szKey[4],
				(unsigned char)a->aDidSL[i].szKey[5]);
	info("*************");
}
#endif

/** Find bucket.

    @author gramo
    @param  char* szKey
    @return *CDidBK
 */
static CDidBK* DSfindBK ( char *szKey ) {
        int32_t prefix;

        prefix = DSgetPrefix ( szKey );
		if (prefix >= MAX_DID_BK) {
			crit("prefix[%d] is larger than MAX_DID_BK[%d]",
					prefix, MAX_DID_BK);
			return NULL;
		}

        return (gDidBKTable->pDidBK[prefix]);
}

/**
 *	Bynary Search for did_slot_t
 *	if new then create DID
 *	else find DID
 *
 *	@author gramo
 *	@param CDidBK* szBK
 *	@param char* szKey
 *	@param int16_t StartPos
 *	@param int16_t FinishPos
 *	@return , *did_slot_t - Success , NULL - Fail
 */
static did_slot_t* DSfindDid_BS ( CDidBK *szBK , char *szKey , int16_t StartPos , int16_t FinishPos ) {
	int16_t MiddlePos;
	int16_t flag;
/*	did_slot_t empty;*/

	while (1) {
		MiddlePos = (StartPos + FinishPos) / 2;

		flag = memcmp(szBK->aDidSL[MiddlePos].szKey , szKey, SYS_DID_KEYSIZE);

		if ( ( StartPos == MiddlePos || MiddlePos == FinishPos ) && flag ) {
			return (did_slot_t*)NULL;
		}

		if ( flag < 0 ) {
			StartPos = MiddlePos;
		}
		else if ( flag > 0 ){
			FinishPos = MiddlePos;
		}
		else {
			return &(szBK->aDidSL[MiddlePos]);
		}
	}

	return (did_slot_t*)NULL ;
}

static void DSsaveData (void) {
/*	DocId Did;*/
	FILE *fp;
/*	int16_t i=0;*/
	int32_t size;

	debug("Saving Did slot from [%s]", m_didSlotPath);

	if ( (fp=sb_fopen(m_didSlotPath,"ab")) ==NULL )
		error("fail file open:%s", sys_errlist[errno]);

	if (fseek(fp,0L,SEEK_END))
		error("file file seek:%s", sys_errlist[errno]);

	size = fwrite(DSsaveSL , sizeof(did_slot_t) , MAX_LOAD_BLOCK , fp);

	if (size==MAX_LOAD_BLOCK)
		debug("Sucess!");
	else
		debug("Fail!");

	fclose(fp);
}

static void load_data (void) {
	did_slot_t pTmpSL[MAX_LOAD_BLOCK];
/*	DocId Did;*/
	FILE *fp;
	int i=0;
	int size;

	debug("Loading Did slot from [%s]", m_didSlotPath);
/*	CRIT("Loading Did slot from [%s]", m_didSlotPath);*/

	if ( (fp=sb_fopen(m_didSlotPath,"rb")) == NULL ) {
		info("there is no did database exist");
		debug("Fail file open!");
		return;
	}

	while (!feof(fp)) {
		size = fread(pTmpSL , sizeof(did_slot_t) , MAX_LOAD_BLOCK , fp);

		for (i=0; i<size; i++) {
			load_slot( pTmpSL[i] );
			gDidCount = pTmpSL[i].docId+ 1;

		}
	}
}

/** convert URL into MD5 hash key, and Find slot.
        if don't find slot , create new slot.

                @author gramo
                @param char* szUrl
                @return *did_slot_t
*/
#if 0
static did_slot_t* DSresolveURLnew(char *szUrl) {
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t *pTmpSL;
	DocId Did;

	DSmd5 ( szUrl, tmpKey );

	if ( (pTmpSL=DSfindDid(tmpKey))  ) {
		DSDidState = DID_STATE_OLD;
		return pTmpSL;
	}

	Did = gDidCount++;

	DSDidState = DID_STATE_NEW;
	pTmpSL = DSnewSL( szUrl , Did);

	memcpy(&DSsaveSL[DSsaveCount++] , pTmpSL , sizeof(did_slot_t));

	if (!(DSsaveCount%MAX_LOAD_BLOCK)) {
		DSsaveData();
		DSsaveCount=0;
	}

	return pTmpSL;
}
#endif

/** update slot

	@author gramo
	@param char* szUrl
	@return *did_slot_t
*/
#if 0
static did_slot_t* DSresolveURLupdate ( char *szUrl , CDidState szState) {
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t *pTmpSL;
/*	DocId Did;*/

	DSmd5 ( szUrl, tmpKey );

	if ( (pTmpSL=DSfindDid(tmpKey)) ) {
		DSDidState = DID_STATE_OLD;

		pTmpSL->byState.bDoc = szState.bDoc;
		pTmpSL->byState.bAnc = szState.bAnc;

		return pTmpSL;
	}

	return (did_slot_t*)NULL;
}
#endif

/** convert URL into MD5 hash key, and only Find slot .

                @author gramo
                @param char* szUrl
                @return *did_slot_t
*/
#if 0
static did_slot_t* DSresolveURLfind ( char *szUrl ) {
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t *pTmpSL;
/*	DocId Did;*/

	DSmd5 ( szUrl, tmpKey );

	if ( (pTmpSL=DSfindDid(tmpKey))  ) {
		DSDidState = DID_STATE_OLD;
		return pTmpSL;
	}

	return (did_slot_t*)NULL;
}
#endif

/** create new slot.

	@author gramo
	@param char* szUrl
	@return *did_slot_t
*/
static did_slot_t* DSnewSL ( char *szUrl , DocId Did) {
	CDidBK* pBK;
	char tmpKey[SYS_DID_KEYSIZE];
	did_slot_t tmpSL;
	did_slot_t *pTmpSL;

	DSmd5 ( szUrl, tmpKey );
	pBK = DSfindBK ( tmpKey );
	if (pBK == NULL) {
		crit("pBK(return value of DSfindBK) is NULL! what's up?");
//		return NULL;
	}

	/* create slot */
	memcpy(tmpSL.szKey , tmpKey,SYS_DID_KEYSIZE);
	tmpSL.docId= Did;

	if (!(pTmpSL=DSaddDidSL ( pBK , tmpSL ) ) ) {
		if (!pBK) {
			DSdoubleDidBKTable();
			pBK = DSfindBK(tmpKey);
		} else if ((pBK)->byPrefixBit == gDidBKTable->byPrefixBit)
			DSdoubleDidBKTable();

		if (DSpartitionDidBKTable( pBK ))
			return NULL;

		pBK = DSfindBK ( tmpKey );
		pTmpSL = DSnewSL ( szUrl , Did);
	}

	return pTmpSL;
}

static did_slot_t* load_slot ( did_slot_t tmpSL) {
	CDidBK* pBK;
	did_slot_t *pTmpSL;

	pBK = DSfindBK ( tmpSL.szKey );

	if ( !(pTmpSL=DSaddDidSL(pBK, tmpSL)) ) {
		if ((pBK)->byPrefixBit == gDidBKTable->byPrefixBit)
			DSdoubleDidBKTable();
		if (DSpartitionDidBKTable( pBK ))
			return NULL;
		pBK = DSfindBK ( tmpSL.szKey );
		pTmpSL = load_slot ( tmpSL );
	}
	return pTmpSL;
}

static void private_init()
{
	gDidCount = 1; // will be overriden when loading data from file
	gDidBKTable= (CDidBKTable*)sb_calloc(1,sizeof(CDidBKTable));
	gDidBKTable->pDidBK[0] = (CDidBK*)sb_calloc(1,sizeof(CDidBK));
	gDidBKTable->pDidBK[0]->nSlotCnt = 0;
}

static int module_main(slot_t *slot)
{

	sb_run_set_default_sighandlers(_shutdown, _graceful_shutdown);

	debug("docid server started");
	private_init();
	debug("memory allocation is done.");
	CRIT("start to load_data()...");
	load_data();
	info("load_data() is now done.");
	CRIT("you may register new docs.");

	if ( sb_run_udp_bind(&udp_sock, mBindAddr, mBindPort) != SUCCESS ) {
		error("udp_bind: %s", strerror(errno));
		return 1;
	}

	if ( pthread_mutex_init(&sock_lock, NULL) != 0 ) {
		error("pthread_mutex_init: %s", strerror(errno));
		return 1;
	}
	pthread_mutex_init(&slot_lock, NULL);

	sb_run_init_scoreboard(scoreboard);
	sb_run_spawn_threads(scoreboard, "docid server thread(child)", thread_main);

	scoreboard->period = 20;
	sb_run_monitor_threads(scoreboard);
	did_server_kill(0);

	if ( pthread_mutex_destroy(&sock_lock) != 0 ) {
		error("pthread_mutex_destroy: %s", strerror(errno));
		return 1;
	}

	return 0;
}

static void did_server_kill (int signum) {
	FILE *fp;
	int16_t size;

	debug("saving extra did slot to [%s]", m_didSlotPath);

	if ( (fp=sb_fopen(m_didSlotPath,"ab")) ==NULL ) {
		error("fail file open");
		return;
	}

	if (fseek(fp,0L,SEEK_END)) {
		error("fail file seek");
		return;
	}

	size = fwrite(DSsaveSL , sizeof(did_slot_t) , DSsaveCount , fp);

	if (size==DSsaveCount)
		debug("save extra sucessfully");
	else
		debug("save extra fail");

	fclose(fp);

	return;
}

// XXX -- ¶óÀ̺귯¸®·Î »ç¿ëÇÒ °æ¿ì
/*static void DSinit(int32_t wPort) {*/
/*	gDidCount = 1;*/
/*	gDidBKTable= (CDidBKTable*)sb_calloc(1,sizeof(CDidBKTable));*/
/*	gDidBKTable->pDidBK[0] = (CDidBK*)sb_calloc(1,sizeof(CDidBK));*/
/*	gDidBKTable->pDidBK[0]->nSlotCnt = 0;*/

/*	load_data();*/
/*}*/

/*****************************************************************************/
static void _do_nothing(int sig)
{
	return;
}

static void _shutdown(int sig)
{
	struct sigaction act;

	memset(&act, 0x00, sizeof(act));

//	act.sa_flags = SA_RESTART;
	sigfillset(&act.sa_mask);

	act.sa_handler = _do_nothing;
	sigaction(SIGHUP, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGQUIT, &act, NULL);
	sigaction(SIGTERM, &act, NULL);

	scoreboard->shutdown++;
}

static void _graceful_shutdown(int sig)
{
	struct sigaction act;

	memset(&act, 0x00, sizeof(act));

//	act.sa_flags = SA_RESTART;
	sigfillset(&act.sa_mask);

	act.sa_handler = _do_nothing;
	sigaction(SIGHUP, &act, NULL);
	sigaction(SIGINT, &act, NULL);

	scoreboard->graceful_shutdown++;
}

static int init()
{
	int port=0;
	port = assignSoftBotPort(__FILE__,PORT_ID_DID);
	snprintf(mBindPort,SHORT_STRING_SIZE,"%d",port);
	return SUCCESS;
}

/*************************************************************************/
/* api: same interface with mod_did_client.c */

static int DI_init()
{
	private_init();
	load_data();
	return SUCCESS;
}

static void DI_finish()
{
	did_server_kill(0);
}

static int DI_getId(char *pKey, DocId *docid)
{
	ServerMsg svrMsg;
	svrMsg.nMethod = DITP_GET_ID;
	findId(pKey, &svrMsg);
	*docid = svrMsg.result;
	return (int)svrMsg.status;
}

int DI_getNewId(char *pKey, DocId *docid, DocId *olddocid)
{
	ServerMsg svrMsg;
	svrMsg.nMethod = DITP_GET_NEW_ID;
	makeId(pKey, &svrMsg);
	*docid = svrMsg.result;
	*olddocid = svrMsg.olddid;
	return (int)svrMsg.status;
}

static void register_hooks(void)
{
	sb_hook_local_get_docid(DI_getId,NULL,NULL,HOOK_MIDDLE);
	sb_hook_local_get_new_docid(DI_getNewId,NULL,NULL,HOOK_MIDDLE);
	sb_hook_load_docid_db(DI_init, NULL, NULL, HOOK_MIDDLE);
	sb_hook_unload_docid_db(DI_finish, NULL, NULL, HOOK_MIDDLE);
}

/*************************************************************************/
/* configuration stuff here */

static void set_bind_address(configValue v)
{
	strncpy(mBindAddr, v.argument[0], SHORT_STRING_SIZE);
	mBindAddr[SHORT_STRING_SIZE-1] = '\0';
}

static void get_did_slot_path(configValue v) {
	strncpy(m_didSlotPath, v.argument[0], 256);
}

static void get_slave_thread_num(configValue v) {
	slave_thread_num = atoi(v.argument[0]);
}
/*****************************************************************************/
static config_t config[] = {
	CONFIG_GET("BindIP", set_bind_address, 1, \
		   "IP-address e.g) 192.168.1.1"),
	CONFIG_GET("DidSlotPath",get_did_slot_path, 1, "did slot db local path"),
	CONFIG_GET("SlaveThreadNum",get_slave_thread_num, 1, "slave thread number"),
	{NULL}
};

module did_daemon_module = {
	STANDARD_MODULE_STUFF,
	config,				/* config */
	NULL,				/* registry */
	init,               /* initialize function */
	module_main,		/* child_main */
	scoreboard,			/* scoreboard */
	register_hooks		/* register hook api */
};


text:
css_dir = "css"
sass_dir = "sass"
images_dir = "img"
javascripts_dir = "js"

output_style = :expanded

relative_assets = true
asset_cache_buster = :none

line_comments = false


text:
package info.ineighborhood.cardme.vcard.features;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author George El-Haddad
 *

 * Feb 4, 2010
 *
 *
RFC 2426

 * 3.6.4 REV Type Definition
 *

 *
Type name: REV

 *
Type purpose: To specify revision information about the current vCard.

 *
Type encoding: 8bit

 *
Type value: The default is a single date-time value. Can also be reset to a single date value.

 *
Type special note: The value distinguishes the current revision of the information in this vCard for other renditions of the information.

 *

 *

 */
public interface RevisionFeature extends TypeTools {

	/**
	 *
Returns the revision date.

	 *
	 * @return {@link Calendar}
	 */
	public Calendar getRevision();

	/**
	 *
Sets the revision date.

	 *
	 * @param calendar
	 */
	public void setRevision(Calendar calendar);

	/**
	 *
Sets the revision date.

	 *
	 * @param date
	 */
	public void setRevision(Date date);

	/**
	 *
Clears the revision.

	 */
	public void clearRevision();

	/**
	 *
Returns true if the revision exists.

	 *
	 * @return
	 */
	public boolean hasRevision();

	/**
	 *
Returns a full copy of this object.

	 *
	 * @return {@link RevisionFeature}
	 */
	public RevisionFeature clone();
}


text:
class Observer
  attr_reader :uid
  attr_writer :subject

  def update
    raise "Implement update in subclass"
  end
end

class DashboardService < Observer
  def uid
    self.class.to_s
  end

  def update
    $stdout.print 'Update dashboard'
  end
end

class ReportService < Observer
  def uid
    self.class.to_s
  end

  def update
    $stdout.print 'Generate user statistics PDF document'
  end
end


text:
import codecs,os
def _verify_python_env():
	M='.utf8';L='.utf-8';J=None;I='ascii'
	try:import locale as A;G=codecs.lookup(A.getpreferredencoding()).name
	except Exception:G=I
	if G!=I:return
	B=''
	if os.name=='posix':
		import subprocess as D
		try:C=D.Popen(['locale','-a'],stdout=D.PIPE,stderr=D.PIPE).communicate()[0]
		except OSError:C=b''
		E=set();H=False
		if isinstance(C,bytes):C=C.decode(I,'replace')
		for K in C.splitlines():
			A=K.strip()
			if A.lower().endswith((L,M)):
				E.add(A)
				if A.lower()in('c.utf8','c.utf-8'):H=True
		B+='\n\n'
		if not E:B+='Additional information: on this system no suitable UTF-8 locales were discovered. This most likely requires resolving by reconfiguring the locale system.'
		elif H:B+='This system supports the C.UTF-8 locale which is recommended. You might be able to resolve your issue by exporting the following environment variables:\n\n    export LC_ALL=C.UTF-8\n    export LANG=C.UTF-8'
		else:B+=f"This system lists some UTF-8 supporting locales that you can pick from. The following suitable locales were discovered: {', '.join(sorted(E))}"
		F=J
		for A in (os.environ.get('LC_ALL'),os.environ.get('LANG')):
			if A and A.lower().endswith((L,M)):F=A
			if A is not J:break
		if F is not J:B+=f"\n\nClick discovered that you exported a UTF-8 locale but the locale system could not pick up from it because it does not exist. The exported locale is {F!r} but it is not supported"
	raise RuntimeError(f"Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps.{B}")


text:
package com.mycompany.tmch.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

public class PasswordService {
	private static PasswordService instance;
	public PasswordService(){

	}
	public synchronized String encrypt(String plaintext)throws Exception{
		MessageDigest md=null;
		try{
			md = MessageDigest.getInstance("SHA");

		}catch(NoSuchAlgorithmException e){
			throw new Exception(e.getMessage());
		}

		try{
			md.update(plaintext.getBytes("UTF-8"));
		}catch(UnsupportedEncodingException e){
			throw new Exception(e.getMessage());
		}

		byte raw[] = md.digest();
		String hash=(new Base64().encodeToString(raw));
		return hash;
	}

	public static synchronized PasswordService getInstance(){
		if(instance == null){
			instance = new PasswordService();
		}
		return instance;
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>x2d: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Classes

Files

Class List

Class Hierarchy

Class Members

x2d::util::quadratic_interpolator Member List
This is the complete list of members for x2d::util::quadratic_interpolator, including all inherited members.

calculate() (defined in x2d::util::quadratic_interpolator)	x2d::util::quadratic_interpolator	 [inline, virtual]

elapsed_time_ (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [protected]

quadratic_interpolator(float &v, float min, float mid, float max, float t) (defined in x2d::util::quadratic_interpolator)	x2d::util::quadratic_interpolator	 [inline]

reset() (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [inline, virtual]

time_interpolator(float t) (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [inline]

total_time_ (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [protected]

update(float dt) (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [inline, virtual]

~time_interpolator() (defined in x2d::util::time_interpolator)	x2d::util::time_interpolator	 [inline, virtual]

<address style="text-align: right;">Generated by

 1.6.2 </address>


text:
require 'spec_helper'

describe Gosu::Grid::Cell do

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>Olog Directory Service 2.2.7-SNAPSHOT Reference Package edu.msu.nscl.olog</title>
		<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="style" />

        	edu.msu.nscl.olog

Classes

            	AttachmentManagerTest

            	AttributeManagerTest

            	CompareVersionsTest

            	JPAUtilTest

            	LogManagerTest

            	LogbookManagerTest

            	OlogPerformanceTest

            	OlogPerformanceTestAgainstCode

            	PropertyManagerTest

            	TagManagerTest


text:
#ifndef __MATH
#define __MATH

#define HUGE_VAL 1.79769313486231570000e+308

extern double acos(double);
extern double asin(double);
extern double atan(double);
extern double atan2(double, double);
extern double cos(double);
extern double sin(double);
extern double tan(double);
extern double cosh(double);
extern double sinh(double);
extern double tanh(double);
extern double exp(double);
extern double frexp(double, int *);
extern double ldexp(double, int);
extern double log(double);
extern double log10(double);
extern double modf(double, double *);
extern double pow(double, double);
extern double sqrt(double);
extern double ceil(double);
extern double fabs(double);
extern double floor(double);
extern double fmod(double, double);

#endif /* __MATH */


text:
A Leiningen template for generating a
[Pedestal](https://github.com/pedestal/pedestal) service hosted in an
[Immutant](http://immutant.org/) container.

## Usage

This is a lein project template, and can be used as such.

```sh
$ lein new sonian-pedestal-immutant my-awesome-project
```

## Features provided

The project skeleton sets up a lot of things that are generally useful
for building an http service:

- A `ctl` script and a carousel admin server.
- carousel style modules in general.
- An nrepl listener.
- A `hello world` implementation in Pedestal.
- Unit tests structured properly.
- Unit tests test the `hello world` implementation.
- `only-in-immutant-fixture` is available.

## FAQ

### Where are my logs?

When running Immutant, the logs are in `target/isolated-immutant/standalone/log`

### How do I run a REPL inside Immutant, so I can test things that rely on features it provides?

The :dev profile starts an nrepl listener, and leaves a `.nrepl-port` file in the project directory, which nrepl/cider will pick up automatically when you run `M-x cider`

### My REPL is connected, how can I test?

Use `clojure.test` as usual, i.e. `C-c M-n` to put the REPL into your test's namespace and call `(run-tests)` or `C-c M-,`

Be aware that you must (re)compile anything that you're testing, and that tests that were compiled before are now resident, so commenting them out won't make them stop running until you explicitly remove them. You can do that either by simply restarting the JVM, or with `user/refresh` -- `clojure.tools.namespace.repl` is included in the project for that.

## License

Copyright © 2014 Sonian, Inc.

Distributed under the Apache 2.0 License.


text:
class RefCountedBytes;

namespace history {

// TopSitesCache caches the top sites and thumbnails for TopSites.
class TopSitesCache {
 public:
  TopSitesCache();
  ~TopSitesCache();

  // The top sites.
  void SetTopSites(const MostVisitedURLList& top_sites);
  const MostVisitedURLList& top_sites() const { return top_sites_; }

  // The thumbnails.
  void SetThumbnails(const URLToImagesMap& images);
  const URLToImagesMap& images() const { return images_; }

  // Set a thumbnail.
  void SetPageThumbnail(const GURL& url,
                        RefCountedBytes* thumbnail,
                        const ThumbnailScore& score);

  // Returns the thumbnail as an Image for the specified url. This adds an entry
  // for |url| if one has not yet been added.
  Images* GetImage(const GURL& url);

  // Fetches the thumbnail for the specified url. Returns true if there is a
  // thumbnail for the specified url.
  bool GetPageThumbnail(const GURL& url,
                        scoped_refptr<RefCountedBytes>* bytes);

  // Fetches the thumbnail score for the specified url. Returns true if
  // there is a thumbnail score for the specified url.
  bool GetPageThumbnailScore(const GURL& url, ThumbnailScore* score);

  // Returns the canonical URL for |url|.
  GURL GetCanonicalURL(const GURL& url);

  // Returns true if |url| is known.
  bool IsKnownURL(const GURL& url);

  // Returns the index into |top_sites_| for |url|.
  size_t GetURLIndex(const GURL& url);

  // Removes any thumbnails that are no longer referenced by the top sites.
  void RemoveUnreferencedThumbnails();

 private:
  // The entries in CanonicalURLs, see CanonicalURLs for details. The second
  // argument gives the index of the URL into MostVisitedURLs redirects.
  typedef std::pair<MostVisitedURL*, size_t> CanonicalURLEntry;

  // Comparator used for CanonicalURLs.
  class CanonicalURLComparator {
   public:
    bool operator()(const CanonicalURLEntry& e1,
                    const CanonicalURLEntry& e2) const {
      return e1.first->redirects[e1.second] < e2.first->redirects[e2.second];
    }
  };

  // This is used to map from redirect url to the MostVisitedURL the redirect is
  // from. Ideally this would be map<GURL, size_t> (second param indexing into
  // top_sites_), but this results in duplicating all redirect urls. As some
  // sites have a lot of redirects, we instead use the MostVisitedURL* and the
  // index of the redirect as the key, and the index into top_sites_ as the
  // value. This way we aren't duplicating GURLs. CanonicalURLComparator
  // enforces the ordering as if we were using GURLs.
  typedef std::map<CanonicalURLEntry, size_t,
                   CanonicalURLComparator> CanonicalURLs;

  // Generates the set of canonical urls from |top_sites_|.
  void GenerateCanonicalURLs();

  // Stores a set of redirects. This is used by GenerateCanonicalURLs.
  void StoreRedirectChain(const RedirectList& redirects, size_t destination);

  // Returns the iterator into canconical_urls_ for the specified url.
  CanonicalURLs::iterator GetCanonicalURLsIterator(const GURL& url);

  // The top sites.
  MostVisitedURLList top_sites_;

  // The images. These map from canonical url to image.
  URLToImagesMap images_;

  // Generated from the redirects to and from the most visited pages. See
  // description above typedef for details.
  CanonicalURLs canonical_urls_;

  DISALLOW_COPY_AND_ASSIGN(TopSitesCache);
};

}  // namespace history

#endif  // CHROME_BROWSER_HISTORY_TOP_SITES_CACHE_H_


text:
import { CollectionObject } from './collection-object.model';

export interface Store extends CollectionObject {
  name: string;
  description: string;
  location: YssiLocation;
  createDate: Date;
  updateDate?: Date;
  activities?: string[];
  images?: string[];
  owner?: string;
}

export interface YssiLocation {
  name: string;
  address: string;
  coords: {
    type: 'Point',
    coordinates: [number, number]
  }

}


text:
- `Identical(mixed $value)`

Validates if the input is identical to some value.

```php
v::identical(42)->validate(42); // true
v::identical(42)->validate('42'); // false
```

Message template for this validator includes `{{compareTo}}`.

## Categorization

- Comparisons

## Changelog

Version | Description
--------|-------------
  1.0.0 | Created

***
See also:

- [Contains](Contains.md)
- [Equals](Equals.md)
- [Equivalent](Equivalent.md)


text:
var Ember = require('ember');
var App = require('app');
require('controllers/wizard/step5_controller');
var components = require('data/service_components');

describe('App.WizardStep5Controller', function () {
  var controller = App.WizardStep5Controller.create();
  controller.set('content', {});
  var cpu = 2, memory = 4;
  var schemes = [
    {'description': 'empty condition'},
    {
      'description': 'second host if amount more than 1',
      "else": 1
    },
    {
      'description': 'first host if amount less than 3, third host if amount less than 6, fourth host if amount more than 5',
      "3": 0,
      "6": 2,
      "else": 3
    },
    {
      'description': 'second host if amount less than 3, second host if amount less than 6, third host if amount less than 31, sixth host if amount more than 30',
      "3": 1,
      "6": 1,
      "31": 2,
      "else": 5
    }
  ];
  var test_config = [
    {
      title: '1 host',
      hosts: ['host0'],
      equals: [0, 0, 0, 0]
    },
    {
      title: '2 hosts',
      hosts: ['host0', 'host1'],
      equals: [0, 1, 0, 1]
    },
    {
      title: '3 hosts',
      hosts: ['host0', 'host1', 'host2'],
      equals: [0, 1, 2, 1]
    },
    {
      title: '5 hosts',
      hosts: ['host0', 'host1', 'host2', 'host3', 'host4'],
      equals: [0, 1, 2, 1]
    },
    {
      title: '6 hosts',
      hosts: ['host0', 'host1', 'host2', 'host3', 'host4', 'host6'],
      equals: [0, 1, 3, 2]
    },
    {
      title: '10 hosts',
      hosts: ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9'],
      equals: [0, 1, 3, 2]
    },
    {
      title: '31 hosts',
      hosts: ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9', 'host10', 'host11', 'host12', 'host13', 'host14', 'host15', 'host16', 'host17', 'host18', 'host19', 'host20', 'host21', 'host22', 'host23', 'host24', 'host25', 'host26', 'host27', 'host28', 'host29', 'host30'],
      equals: [0, 1, 3, 5]
    }
  ];

  schemes.forEach(function(scheme, index) {
    describe('#getHostForComponent() condition: ' + scheme.description, function() {

      delete scheme['description'];

      test_config.forEach(function(test) {
        it(test.title, function () {
          controller.get('hosts').clear();
          test.hosts.forEach(function(_host) {
            controller.get('hosts').pushObject(Em.Object.create({
              host_name: _host,
              cpu: cpu,
              memory: memory
            }));
          });
          expect(controller.getHostForComponent(test.hosts.length, scheme).host_name).to.equal(test.hosts[test.equals[index]]);
        });
      });
    });
  });

  describe('#getZooKeeperServer', function() {
    it('should be array with three host names if hosts number more than three', function() {
      var hosts = [
        {host_name: 'host1'},
        {host_name: 'host2'},
        {host_name: 'host3'}
      ];

      controller.set('hosts', hosts);
      expect(controller.getZooKeeperServer(hosts.length)).to.eql(['host1', 'host2', 'host3']);
    });

    it('should be array with one host names if hosts number less than three', function() {
      var hosts = [
        {host_name: 'host1'},
        {host_name: 'host2'}
      ];

      controller.set('hosts', hosts);
      expect(controller.getZooKeeperServer(hosts.length)).to.eql(['host1']);
    });
  });

  describe('#getGangliaServer', function() {
    it('should be host name if one host ', function() {
      var hosts = [
        {host_name: 'host1'}
      ];

      controller.set('hosts', hosts);
      expect(controller.getGangliaServer(hosts.length)).to.eql('host1');
    });

    it('should be host name if hosts number more than one', function() {
      var hosts = [
        {host_name: 'host1'},
        {host_name: 'host2'}
      ];

      controller.set('hosts', hosts);
      expect(controller.getGangliaServer(hosts.length)).to.eql('host1');
    });

    it('should be host name different from localhost if hosts number more than one', function() {
      var hosts = [
        {host_name: ''},
        {host_name: 'host2'}
      ];
      //first host_name is empty string, because of location.hostname = "" in console,
      //to implement current test case

      controller.set('hosts', hosts);
      expect(controller.getGangliaServer(hosts.length)).to.eql('host2');
    });
  });

  controller.set('content', {});

  describe('#isReassignWizard', function() {
    it('true if content.controllerName is reassignMasterController', function() {
      controller.set('content.controllerName', 'reassignMasterController');
      expect(controller.get('isReassignWizard')).to.equal(true);
    });
    it('false if content.controllerName is not reassignMasterController', function() {
      controller.set('content.controllerName', 'mainController');
      expect(controller.get('isReassignWizard')).to.equal(false);
    });
  });

});


text:
(function() {

	window.oChatProps = window.oChatProps? window.oChatProps : {};

    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
	var srcVal = "";
	if('https:' == document.location.protocol) srcVal = "https://127.0.0.1:10643";
	else srcVal = "http://127.0.0.1:10280";
	s.src = srcVal + "/chat/app.js"
    var o = document.getElementsByTagName('script')[0];
    o.parentNode.insertBefore(s, o);
})();

oChatProps["id"] = "123";


text:
<?php

namespace Aerys;

class FilterException extends \Exception {
}


text:
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
SPHINXPROJ    = ExhaleCompanion
SOURCEDIR     = .
BUILDDIR      = _build

# Put it first so that "make" without argument is like "make help".
help:
	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile clean

clean:
	rm -rf doxyoutput/ api/
	# these are specific to the companion site, ignore this rm
	rm -f conf_extensions.rst conf_theme.rst
	@$(SPHINXBUILD) -M clean "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)


text:
<?php

defined('ABSPATH') or die();

/*
Dropin Name: Donate things
Dropin URI: http://simple-history.com/
Author: Pär Thernström
*/

/**
 * Simple History Donate dropin
 * Put some donate messages here and there
 */
class SimpleHistoryDonateDropin
{

    // Simple History instance
    private $sh;

    public function __construct($sh)
    {

        $this->sh = $sh;
        add_action('admin_menu', array( $this, 'add_settings' ), 50);
        add_action('plugin_row_meta', array( $this, 'action_plugin_row_meta' ), 10, 2);
    }

    /**
     * Add link to the donate page in the Plugins » Installed plugins screen
     * Called from filter 'plugin_row_meta'
     */
    public function action_plugin_row_meta($links, $file)
    {

        if ($file == $this->sh->plugin_basename) {
            $links = array_merge(
                $links,
                array( sprintf('%1$s', __('Donate', "simple-history")) )
            );
        }

        return $links;
    }

    public function add_settings()
    {

        $settings_section_id = 'simple_history_settings_section_donate';

        add_settings_section(
            $settings_section_id,
            _x('Donate', 'donate settings headline', 'simple-history'), // No title __("General", "simple-history"),
            array( $this, 'settings_section_output' ),
            SimpleHistory::SETTINGS_MENU_SLUG // same slug as for options menu page
        );

        // Empty section to make more room below
        /*
        add_settings_field(
            "simple_history_settings_donate",
            "", // __("Donate", "simple-history"),
            array($this, "settings_field_donate"),
            SimpleHistory::SETTINGS_MENU_SLUG,
            $settings_section_id
        );
        */
    }

    public function settings_section_output()
    {

        printf(
            __('If you find Simple History useful please donate.', "simple-history"),
            'https://www.paypal.me/eskapism'
        );
    }

    public function settings_field_donate()
    {
    }
}


text:
require File.join(File.dirname(__FILE__), "..", 'stone')
require File.join(File.dirname(__FILE__), 'common_test_case')

class StoneTestCase < BaseTestCase
end

class StoneUnitTestCase < StoneTestCase
  def mock_full_backup_to(stone, expected_backup_file_name)
    partial_mock_stone = flexmock(stone)
    partial_mock_stone.should_receive(:topaz_commands).with(/System startCheckpointSync/).and_return([["", ["[4202 sz:0 cls: 74241 Boolean] true"]], ""]).once.ordered
    partial_mock_stone.should_receive(:topaz_commands).with(/SystemRepository startNewLog/).and_return([["", ["[4202 sz:0 cls: 74241 SmallInteger] 1313"]], ""]).once.ordered
    partial_mock_stone.should_receive(:topaz_commands).with(/System abortTransaction. SystemRepository fullBackupCompressedTo: '#{expected_backup_file_name}'/).once.ordered
  end

  def test_full_backup_to_specific_file
    stone = Stone.create(TEST_STONE_NAME)
    mock_full_backup_to(stone, "/tmp/temporary_backup")
    stone.full_backup("/tmp/temporary_backup")
  end

  def test_full_backup
    stone = Stone.create(TEST_STONE_NAME)
    mock_full_backup_to(stone, "#{stone.backup_directory}/#{stone.name}_#{Date.today.strftime('%F')}.full")
    stone.full_backup
  end

  def test_restore_latest_backup
    stone = Stone.create(TEST_STONE_NAME)
    mock_out_restore_commands(stone, stone.backup_filename_for_today)
    stone.restore_latest_full_backup
  end

  def test_restore_backup_from_named_file
    stone = Stone.create(TEST_STONE_NAME)
    mock_out_restore_commands(stone, "/tmp/koos.backup")
    stone.restore_full_backup_from_named_file("/tmp/koos.backup")
  end

  def test_restore_backup_of_another_stone_on_date
    stone = Stone.create(TEST_STONE_NAME)
    mock_out_restore_commands(stone, "#{stone.backup_directory}/anotherstone_2005-05-13.full.gz")
    stone.restore_full_backup('anotherstone', Date.civil(2005, 5, 13))
  end

  def test_copy_running_stone
    stone = Stone.create(TEST_STONE_NAME)
    flexmock(stone).should_receive(:running?).and_return(true).once
    # Can not copy a running stone
    assert_raises(RuntimeError) { stone.copy_to(nil) }
  end

  def test_copy_stopped_stone
    copy_to_stone_name = "copy_of_#{TEST_STONE_NAME}"
    clear_stone(copy_to_stone_name)

    stone = Stone.create(TEST_STONE_NAME)
    to_stone = Stone.create(copy_to_stone_name)
    partial_mock_stone = flexmock(stone)
    partial_mock_stone.should_receive(:log_sh).with("cp #{stone.extent_filename} #{to_stone.extent_filename}").once
    partial_mock_stone.should_receive(:running?).and_return(false).once
    flexmock(to_stone).should_receive(:running?).and_return(false).once

    stone.copy_to(to_stone)
  end

  def test_run_topaz_file
    stone = Stone.create(TEST_STONE_NAME)
    partial_mock_stone = flexmock(stone)
    partial_mock_stone.should_receive(:topaz_commands).with(["input test.gs", "commit"], true).once.ordered

    stone.input_file("test.gs")
  end

  def test_parse_tranlog_number
    assert(3 == Stone.tranlog_number_from("[18446744073709551610 sz:0 cls: 74241 SmallInteger] 3"))
    assert(-1 == Stone.tranlog_number_from("[18446744073709551610 sz:0 cls: 74241 SmallInteger] -1 == 0xffffffffffffffff"))
  end

  private

  def mock_out_restore_commands(stone, backup_filename)
    partial_mock_stone = flexmock(stone)

    partial_mock_stone.should_receive(:recreate!).once.ordered
    partial_mock_stone.should_receive(:topaz_commands).with(/System abortTransaction. SystemRepository restoreFromBackup: '#{backup_filename}'.*/).once.ordered
    partial_mock_stone.should_receive(:topaz_commands).with(/SystemRepository commitRestore/).and_return('commitRestore succeeded').once.ordered
  end
end

class StoneIntegrationTestCase < StoneTestCase

  def delete_existing_backup(stone)
    File.delete stone.backup_filename_for_today if File.exist? stone.backup_filename_for_today
  end

  def test_full_backup
    stone = Stone.create(TEST_STONE_NAME)
    delete_existing_backup(stone)
    stone.start
    stone.full_backup
    assert File.exist? stone.backup_filename_for_today
  end

  def test_restore
    stone = Stone.create(TEST_STONE_NAME)
    delete_existing_backup(stone)
    stone.start
    random_method_name = add_restore_worked_in_userglobals(stone)
    stone.full_backup
    stone.restore_latest_full_backup
    assert_random_value_present(stone, random_method_name)
  end

  def test_copy_stopped_stone
    copy_to_stone_name = "copy_to_#{TEST_STONE_NAME}"
    clear_stone(copy_to_stone_name)

    stone = Stone.create(TEST_STONE_NAME)
    stone.start
    random_value = add_restore_worked_in_userglobals(stone)
    stone.stop

    copy_to_stone = Stone.create(copy_to_stone_name)
    stone.copy_to(copy_to_stone)
    copy_to_stone.start
    assert_random_value_present(copy_to_stone, random_value)
    clear_stone(copy_to_stone_name)
  end

  def test_netldi
    GemStoneInstallation.current.stopnetldi
    deny GemStoneInstallation.current.netldi_running?
    GemStoneInstallation.current.startnetldi
    assert GemStoneInstallation.current.netldi_running?
    GemStoneInstallation.current.stopnetldi
    deny GemStoneInstallation.current.netldi_running?
  end

  def test_create_new
    assert !GemStoneInstallation.current.stones.include?(TEST_STONE_NAME)
    stone = Stone.create(TEST_STONE_NAME)
    assert GemStoneInstallation.current.stones.include?(TEST_STONE_NAME)
    stone.start
    assert stone.running?
    assert File.directory?(stone.log_directory)
  end

  def test_destroy
    stone = Stone.create(TEST_STONE_NAME)
    stone.start
    assert_raises(RuntimeError) { stone.destroy! }
    stone.stop
    stone.destroy!
    assert ! (File.exist? stone.extent_directory)
  end

  def test_existing_stone_retrieve
    Stone.create TEST_STONE_NAME
    stone = Stone.existing TEST_STONE_NAME
    assert_not_nil stone
    stone.start
    assert stone.running?
  end

  def test_restart
    stone = Stone.create TEST_STONE_NAME
    stone.start
    stone.restart
    assert stone.running?
    # restart can be a nop and this will still pass. How do I test it? Change a config & restart?
    stone.stop
    stone.restart
    assert stone.running?
  end

  def test_stop_not_running
    stone = Stone.create TEST_STONE_NAME
    stone.stop
    assert !stone.running?
    stone.stop
    assert !stone.running?
  end

  def test_start_already_running
    stone = Stone.create TEST_STONE_NAME
    stone.start
    assert stone.running?
    stone.start
    assert stone.running?
  end

  def test_create_config_file
    config_filename = "#{GemStoneInstallation.current.config_directory}/#{TEST_STONE_NAME}.conf"
    assert ! (File.exist? config_filename)

    stone = Stone.new(TEST_STONE_NAME).create_config_file

    assert File.exists? config_filename
    assert GemStoneInstallation.current.stones.include?(TEST_STONE_NAME)

    content = File.open(config_filename).readlines.join
    assert content.include? "DBF_EXTENT_NAMES = #{stone.extent_filename}"
    assert content.include? "DBF_SCRATCH_DIR = #{stone.scratch_directory}"
    assert content.include? "STN_TRAN_LOG_DIRECTORIES = #{stone.tranlog_directories.join(",")}"
  end

  def test_stones_in_different_installations_uses_correct_environment
    fake_previous_stone_name = "#{TEST_STONE_NAME}_previous"
    ln_sf GemStoneInstallation.current.installation_directory, "/tmp/fake_previous"
    clear_stone(fake_previous_stone_name)

    current = GemStoneInstallation.current
    previous = GemStoneInstallation.new('/tmp/fake_previous')
    current_stone = Stone.create(TEST_STONE_NAME)
    previous_stone = Stone.create(fake_previous_stone_name, previous)

    assert current.installation_directory != previous.installation_directory
    assert current_stone.data_directory != previous_stone.data_directory
    assert current_stone.log_directory != previous_stone.log_directory

    current_stone.running?
    assert ENV['GEMSTONE'] == current.installation_directory
    assert ENV['GEMSTONE_DATADIR'] == current_stone.data_directory
    assert ENV['GEMSTONE_LOGDIR'] == current_stone.log_directory

    previous_stone.running?
    assert ENV['GEMSTONE'] == previous.installation_directory
    assert ENV['GEMSTONE_DATADIR'] == previous_stone.data_directory
    assert ENV['GEMSTONE_LOGDIR'] == previous_stone.log_directory
  end

  private

  def assert_random_value_present(stone, random_value)
    assert_nothing_raised { stone.run_topaz_command("UserGlobals at: ##{random_value}") }
  end

  def add_restore_worked_in_userglobals(stone)
    random_key = "restoreWorked#{rand 1000}"
    stone.topaz_commands([
                          ["run",
                           "UserGlobals at: ##{random_key} put: 'yay'",
                           '%', 'commit'].join("\n"),
                          ])
    return random_key
  end
end


text:
package com.goodworkalan.region;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.locks.Lock;

/**
 * A basic writeable implementation that writes its content to disk and marks
 * the entire region as clean in the cleanable used to track dirty bytes.
 *
 * @author Alan Gutierrez
 */
public class BasicWritable extends AbstractRegion implements Writable {
    /** The cleanable interface used to track which bytes are dirty. */
    protected final Cleanable cleanable;

    /**
     * Create a region at the given file position, with the given byte buffer of
     * region content, guarded by the given lock.
     *
     * @param position
     *            The position of the region on disk.
     * @param byteBuffer
     *            The byte buffer of region content.
     * @param lock
     *            A lock used to lock the region for reading and writing.
     * @param cleanable
     *            The cleanable interface used to record dirtyed bytes in the
     *            byte buffer.
     */
    public BasicWritable(long position, ByteBuffer byteBuffer, Lock lock, Cleanable cleanable) {
        super(position, byteBuffer, lock);
        this.cleanable = cleanable;
    }

    /**
     * Return the drityable interface used to record dirtyed bytes in the byte
     * buffer.
     *
     * @return The dirtyable recorder for the byte buffer.
     */
    @Override
    protected Dirtyable getDirtyable() {
        return cleanable;
    }

    /**
     * Write the entire to the given file channel using the given disk at the
     * position of this region offset by the given offset. Marks the entire
     * cleanable used to track dirty bytes as clean.
     *
     * @param fileChannel
     *            The file channel to write to.
     * @param offset
     *            An offset to add to the dirty region map file position.
     * @throws IOException
     *             If an I/O error occurs.
     */
    public void write(FileChannel fileChannel, int offset) throws IOException {
        ByteBuffer bytes = getByteBuffer();
        bytes.clear();
        fileChannel.write(bytes, offset + getPosition());
        cleanable.clean();
    }
}


text:
export default function isObject(input) {
    return Object.prototype.toString.call(input) === '[object Object]';
}


text:
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util';
import {Promise} from 'angular2/src/facade/async';

function waitForElement(selector) {
  var EC = (<any>protractor).ExpectedConditions;
  // Waits for the element with id 'abc' to be present on the dom.
  browser.wait(EC.presenceOf($(selector)), 20000);
}

describe('routing inbox-app', () => {

  afterEach(verifyNoBrowserErrors);

  describe('index view', () => {
    var URL = 'playground/src/routing/';

    it('should list out the current collection of items', () => {
      browser.get(URL);
      waitForElement('.inbox-item-record');
      expect(element.all(by.css('.inbox-item-record')).count()).toEqual(200);
    });

    it('should build a link which points to the detail page', () => {
      browser.get(URL);
      waitForElement('#item-15');
      expect(element(by.css('#item-15')).getAttribute('href')).toMatch(/#\/detail\/15$/);
      element(by.css('#item-15')).click();
      waitForElement('#record-id');
      expect(browser.getCurrentUrl()).toMatch(/\/detail\/15$/);
    });
  });

  describe('drafts view', () => {
    var URL = 'playground/src/routing/#/drafts';

    it('should navigate to the drafts view when the drafts link is clicked', () => {
      browser.get(URL);
      waitForElement('.inbox-item-record');
      element(by.linkText('Drafts')).click();
      waitForElement('.page-title');
      expect(element(by.css('.page-title')).getText()).toEqual('Drafts');
    });

    it('should navigate to email details', () => {
      browser.get(URL);
      element(by.linkText('Drafts')).click();
      waitForElement('.inbox-item-record');
      expect(element.all(by.css('.inbox-item-record')).count()).toEqual(2);
      expect(element(by.css('#item-201')).getAttribute('href')).toMatch(/#\/detail\/201$/);
      element(by.css('#item-201')).click();
      waitForElement('#record-id');
      expect(browser.getCurrentUrl()).toMatch(/\/detail\/201$/);
    });
  });

  describe('detail view', () => {
    var URL = 'playground/src/routing/';

    it('should navigate to the detail view when an email is clicked', () => {
      browser.get(URL);
      waitForElement('#item-10');
      element(by.css('#item-10')).click();
      waitForElement('#record-id');
      var recordId = element(by.css("#record-id"));
      browser.wait(protractor.until.elementTextIs(recordId, "ID: 10"), 5000);
      expect(recordId.getText()).toEqual('ID: 10');
    });

    it('should navigate back to the email inbox page when the back button is clicked', () => {
      browser.get(URL);
      waitForElement('#item-10');
      element(by.css('#item-10')).click();
      waitForElement('.back-button');
      element(by.css('.back-button')).click();
      expect(browser.getCurrentUrl()).toMatch(/\/$/);
    });

    it('should navigate back to index and sort the page items based on the provided querystring param',
       () => {
         browser.get(URL);
         waitForElement('#item-10');
         element(by.css('#item-10')).click();
         waitForElement('.sort-button');
         element(by.css('.sort-button')).click();
         expect(browser.getCurrentUrl()).toMatch(/\/#\?sort=date$/);
         waitForElement('.inbox-item-record');
         expect(element(by.css(".inbox-item-record > a")).getAttribute("id")).toEqual("item-137");
       });
  })
});


text:
package com.ack.adventureandconquer.game.proficiency;

import com.ack.adventureandconquer.game.Proficiency;

/**
 * Created by saskyrar on 02/03/15.
 */
public class Mapping extends Proficiency {
    @Override
    public String getName() {
        return MAPPING;
    }

    @Override
    public String getDescription() {
        return "The character can understand and make maps, even if he cannot read or write. " +
                "With a proficiency throw of 11+, the character can interpret or draft " +
                "complicated layouts or map an area by memory. This proficiency can be " +
                "selected multiple times.";
    }
}


text:
package com.twincoders.twinpush.sdk.demo;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.twincoders.twinpush.sdk.TwinPushSDK;
import com.twincoders.twinpush.sdk.activities.RichNotificationActivity;
import com.twincoders.twinpush.sdk.communications.TwinPushException;
import com.twincoders.twinpush.sdk.communications.TwinRequest;
import com.twincoders.twinpush.sdk.communications.requests.notifications.GetInboxRequest;
import com.twincoders.twinpush.sdk.demo.adapters.DividerItemDecoration;
import com.twincoders.twinpush.sdk.demo.adapters.InboxAdapter;
import com.twincoders.twinpush.sdk.demo.adapters.ItemClickSupport;
import com.twincoders.twinpush.sdk.entities.InboxNotification;
import com.twincoders.twinpush.sdk.logging.Ln;
import com.twincoders.twinpush.sdk.services.NotificationIntentService;

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

/**
 * Example of User Inbox using a Recycler view with InboxAdapter.
 * In this demo, long click over a notification will remove it from the inbox
 */
public class InboxActivity extends ParentActivity implements ItemClickSupport.OnItemClickListener,
        ItemClickSupport.OnItemLongClickListener{

    private RecyclerView mRecyclerView;
    private InboxAdapter mAdapter;

    View progressView;
    View emptyView;

    View displayView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inbox);

        progressView = findViewById(R.id.progress_bar);
        emptyView = findViewById(R.id.empty_view);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new InboxAdapter(this, new ArrayList<InboxNotification>());
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(this);
        ItemClickSupport.addTo(mRecyclerView).setOnItemLongClickListener(this);

        reload(null);
    }

    public void reload(MenuItem object) {
        showProgress();
        TwinPushSDK.getInstance(this).getUserInbox(0, 50, new GetInboxRequest.Listener() {
            @Override
            public void onSuccess(List<InboxNotification> notifications, int totalPages) {
                mAdapter.setNotifications(notifications);
                mAdapter.notifyDataSetChanged();
                if (notifications.isEmpty()) {
                    stopProgress(emptyView);
                } else {
                    stopProgress(mRecyclerView);
                }
            }

            @Override
            public void onError(Exception exception) {
                if (exception instanceof TwinPushException) {
                    TwinPushException twinPushException = (TwinPushException) exception;
                    // Example of obtaining TwinPush API error response info
                    if (twinPushException.getStatusCode() == 404) {
                        Toast.makeText(InboxActivity.this, "Device is not linked with any alias", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(InboxActivity.this, String.format("Error while trying to load notifications: %s", exception.getLocalizedMessage()), Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(InboxActivity.this, String.format("Error while trying to load notifications: %s", exception.getLocalizedMessage()), Toast.LENGTH_LONG).show();
                }
                stopProgress(emptyView);
            }
        });
    }

    @Override
    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
        InboxNotification notification = mAdapter.getNotifications().get(position);
        if (notification.getNotification().isRichNotification()) {
            Intent richIntent = new Intent(this, RichNotificationActivity.class);
            richIntent.putExtra(NotificationIntentService.EXTRA_NOTIFICATION, notification.getNotification());
            startActivity(richIntent);
        }
    }

    @Override
    public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
        InboxNotification notification = mAdapter.getNotifications().get(position);
        TwinPushSDK.getInstance(this).deleteNotification(notification, new TwinRequest.DefaultListener() {
            @Override
            public void onSuccess() {
                reload(null);
            }

            @Override
            public void onError(Exception exception) {
                Ln.e(exception, "Could not delete notification");
            }
        });
        return false;
    }

    private void showProgress() {
        super.showProgress(true, progressView, displayView != null ? displayView : mRecyclerView);
    }

    private void stopProgress(View targetView) {
        this.displayView = targetView;
        super.showProgress(false, progressView, displayView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.inbox_menu, menu);
        return true;
    }
}