text:
import moment from 'moment'
import React, { PropTypes } from 'react'

moment.locale(
  'en-short',
  {
    relativeTime: {
      d: "1d",
      dd: "%dd",
      future: "%s",
      h: "1h",
      hh: "%dh",
      m: "1m",
      M: "1M",
      mm: "%dm",
      MM: "%dM",
      past: "%s",
      s: "now",
      y: "1y",
      yy: "%dy"
    }
  }
);

export default class Time extends React.Component {
  componentDidMount() {
    this.intervalId = setInterval(this.update.bind(this), 1000 * 60);
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  getRelativeTime() {
    return this.getMomentTime().locale('en-short').fromNow();
  }

  getAbsoluteTime() {
    return this.getMomentTime().format('YYYY-MM-DD HH:mm');
  }

  getHumanReadableTime() {
    if (this.getIsBefore24HoursAgo()) {
      return this.getAbsoluteTime();
    } else {
      return this.getRelativeTime();
    }
  }

  getIsBefore24HoursAgo() {
    return this.getMomentTime().isBefore(moment.duration(24, 'hours'));
  }

  getMachineReadableTime() {
    return this.getMomentTime().format('YYYY-MM-DDTHH:mm:ssZ');
  }

  getMomentTime() {
    return moment(new Date(this.props.time));
  }

  render() {
    return(
      <time {...this.props} dateTime={this.getMachineReadableTime()} title={this.getAbsoluteTime()}>
        {this.getHumanReadableTime()}
      </time>
    );
  }

  update() {
    this.forceUpdate();
  }
}


text:
void MetaData_Fill_FieldDef(tMD_TypeDef *pParentType, tMD_FieldDef *pFieldDef, U32 memOffset, tMD_TypeDef **ppClassTypeArgs) {
	U32 sigLength;
	PTR sig;
	tMetaData *pMetaData;

	pFieldDef->pParentType = pParentType;

	sig = MetaData_GetBlob(pFieldDef->signature, &sigLength);

	MetaData_DecodeSigEntry(&sig); // First entry always 0x06
	pFieldDef->pType = Type_GetTypeFromSig(pFieldDef->pMetaData, &sig, ppClassTypeArgs, NULL);
	if (pFieldDef->pType == NULL) {
		// If the field is a core generic type definition, then we can't do anything more
		return;
	}
	MetaData_Fill_TypeDef(pFieldDef->pType, NULL, NULL);
	// A check for 0 is done so if a type has a field of it's own type it is handled correctly.
	pFieldDef->memSize = (pFieldDef->pType->stackSize>0)?pFieldDef->pType->stackSize:sizeof(void*);
	pFieldDef->memOffset = memOffset;
	pFieldDef->pFieldDef = pFieldDef;

	pMetaData = pFieldDef->pMetaData;
	if (FIELD_HASFIELDRVA(pFieldDef)) {
		U32 i, top;

		// Field has RVA, so load it from FieldRVA
		top = pMetaData->tables.numRows[MD_TABLE_FIELDRVA];
		for (i=1; i<=top; i++) {
			tMD_FieldRVA *pFieldRVA;

			pFieldRVA = (tMD_FieldRVA*)MetaData_GetTableRow(pMetaData, MAKE_TABLE_INDEX(MD_TABLE_FIELDRVA, i));
			if (pFieldRVA->field == pFieldDef->tableIndex) {
				pFieldDef->pMemory = (PTR)pFieldRVA->rva;
				break;
			}
		}
	} else if (FIELD_ISLITERAL(pFieldDef)) {
		// Field is literal, so make pMemory point to the value signature
		U32 i, top;

		top = pMetaData->tables.numRows[MD_TABLE_CONSTANT];
		for (i=1; i<=top; i++) {
			tMD_Constant *pConst;
			pConst = (tMD_Constant*)MetaData_GetTableRow(pMetaData, MAKE_TABLE_INDEX(MD_TABLE_CONSTANT, i));
			if (pConst->parent == pFieldDef->tableIndex) {
				// Found the field
				pFieldDef->pMemory = (PTR)pConst;
				break;
			}
		}
	}
}

void MetaData_Fill_MethodDef(tMD_TypeDef *pParentType, tMD_MethodDef *pMethodDef, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs) {
	SIG sig;
	U32 i, entry, totalSize;

	pMethodDef->pParentType = pParentType;
	pMethodDef->pMethodDef = pMethodDef;
	pMethodDef->isFilled = 1;

	if (pMethodDef->isGenericDefinition) {
		// Generic definition method, so can't do any more.
		//log_f("Method<>: %s.%s.%s()\n", pParentType->nameSpace, pParentType->name, pMethodDef->name);
		return;
	}

	sig = MetaData_GetBlob(pMethodDef->signature, NULL);
	entry = MetaData_DecodeSigEntry(&sig);
	if (entry & SIG_METHODDEF_GENERIC) {
		// Has generic parameters. Read how many, but don't care about the answer
		MetaData_DecodeSigEntry(&sig);
	}
	pMethodDef->numberOfParameters = MetaData_DecodeSigEntry(&sig) + (METHOD_ISSTATIC(pMethodDef)?0:1);
	pMethodDef->pReturnType = Type_GetTypeFromSig(pMethodDef->pMetaData, &sig, ppClassTypeArgs, ppMethodTypeArgs);
	if (pMethodDef->pReturnType != NULL) {
		MetaData_Fill_TypeDef(pMethodDef->pReturnType, NULL, NULL);
	}
	pMethodDef->pParams = (tParameter*)malloc(pMethodDef->numberOfParameters * sizeof(tParameter));
	totalSize = 0;
	if (!METHOD_ISSTATIC(pMethodDef)) {
		// Fill in parameter info for the 'this' pointer
		pMethodDef->pParams->offset = 0;
		if (pParentType->isValueType) {
			// If this is a value-type then the 'this' pointer is actually an IntPtr to the value-type's location
			pMethodDef->pParams->size = 4;
			pMethodDef->pParams->pTypeDef = types[TYPE_SYSTEM_INTPTR];
		} else {
			pMethodDef->pParams->size = 4;
			pMethodDef->pParams->pTypeDef = pParentType;
		}
		totalSize = 4;
	}
	for (i=totalSize>>2; i<pMethodDef->numberOfParameters; i++) {
		tMD_TypeDef *pTypeDef;
		U32 size;

		pTypeDef = Type_GetTypeFromSig(pMethodDef->pMetaData, &sig, ppClassTypeArgs, ppMethodTypeArgs);
		//if (pTypeDef != NULL) {
			MetaData_Fill_TypeDef(pTypeDef, NULL, NULL);
			size = pTypeDef->stackSize;
		//} else {
		//	// If this method has generic-type-argument arguments, then we can't do anything very sensible yet
		//	size = 0;
		//}
		pMethodDef->pParams[i].pTypeDef = pTypeDef;
		pMethodDef->pParams[i].offset = totalSize;
		pMethodDef->pParams[i].size = size;
		totalSize += size;
	}
	pMethodDef->parameterStackSize = totalSize;
}

// Find the method that has been overridden by pMethodDef.
// This is to get the correct vTable offset for the method.
// This must search the MethodImpl table to see if the default inheritence rules are being overridden.
// Return NULL if this method does not override anything.
static tMD_MethodDef* FindVirtualOverriddenMethod(tMD_TypeDef *pTypeDef, tMD_MethodDef *pMethodDef) {
	U32 i;

	do {
		// Search MethodImpl table
		for (i=pTypeDef->pMetaData->tables.numRows[MD_TABLE_METHODIMPL]; i>0; i--) {
			tMD_MethodImpl *pMethodImpl;

			pMethodImpl = (tMD_MethodImpl*)MetaData_GetTableRow(pTypeDef->pMetaData, MAKE_TABLE_INDEX(MD_TABLE_METHODIMPL, i));
			if (pMethodImpl->class_ == pTypeDef->tableIndex) {
				tMD_MethodDef *pMethodDeclDef;

				pMethodDeclDef = MetaData_GetMethodDefFromDefRefOrSpec(pTypeDef->pMetaData, pMethodImpl->methodDeclaration, pTypeDef->ppClassTypeArgs, pMethodDef->ppMethodTypeArgs);
				if (pMethodDeclDef->tableIndex == pMethodDef->tableIndex) {
					IDX_TABLE methodToken;
					tMD_MethodDef *pMethod;

					methodToken = pMethodImpl->methodBody;
					pMethod = (tMD_MethodDef*)MetaData_GetTableRow(pTypeDef->pMetaData, methodToken);
					return pMethod;
				}
			}
		}

		// Use normal inheritence rules
		// It must be a virtual method that's being overridden.
		for (i=pTypeDef->numVirtualMethods - 1; i != 0xffffffff; i--) {
			if (MetaData_CompareNameAndSig(pMethodDef->name, pMethodDef->signature, pMethodDef->pMetaData, pMethodDef->pParentType->ppClassTypeArgs, pMethodDef->ppMethodTypeArgs, pTypeDef->pVTable[i], pTypeDef->ppClassTypeArgs, NULL)) {
				return pTypeDef->pVTable[i];
			}
		}
		pTypeDef = pTypeDef->pParent;
	} while (pTypeDef != NULL);

	return NULL;
}

void MetaData_Fill_TypeDef_(tMD_TypeDef *pTypeDef, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs) {
	IDX_TABLE firstIdx, lastIdx, token;
	U32 instanceMemSize, staticMemSize, virtualOfs, i, j;
	tMetaData *pMetaData;
	tMD_TypeDef *pParent;

	pMetaData = pTypeDef->pMetaData;
	pTypeDef->isFilled = 1;
	pTypeDef->pTypeDef = pTypeDef;

	pTypeDef->pParent = MetaData_GetTypeDefFromDefRefOrSpec(pMetaData, pTypeDef->extends, ppClassTypeArgs, ppMethodTypeArgs);
	pParent = pTypeDef->pParent;

	if (pParent != NULL) {
		MetaData_Fill_TypeDef(pParent, NULL, NULL);
		virtualOfs = pParent->numVirtualMethods;
	} else {
		virtualOfs = 0;
	}
	pTypeDef->isValueType = (U8)Type_IsValueType(pTypeDef);

	// If not primed, then work out how many methods & fields there are.
	if (!pTypeDef->isPrimed) {
		// Methods
		lastIdx = (pTypeDef->isLast)?
			MAKE_TABLE_INDEX(MD_TABLE_METHODDEF, pTypeDef->pMetaData->tables.numRows[MD_TABLE_METHODDEF]):
			(pTypeDef[1].methodList - 1);
		pTypeDef->numMethods = lastIdx - pTypeDef->methodList + 1;
		// Fields
		lastIdx = (pTypeDef->isLast)?
			MAKE_TABLE_INDEX(MD_TABLE_FIELDDEF, pTypeDef->pMetaData->tables.numRows[MD_TABLE_FIELDDEF]):
			(pTypeDef[1].fieldList - 1);
		pTypeDef->numFields = lastIdx - pTypeDef->fieldList + 1;
	}

	// Must create the virtual method table BEFORE any other type resolution is done
	// Note that this must not do ANY filling of types or methods.
	// This is to ensure that the parent object(s) in any type inheritance hierachy are allocated
	// their virtual method offset before derived types.
	firstIdx = pTypeDef->methodList;
	lastIdx = firstIdx + pTypeDef->numMethods - 1;
	// This only needs to be done for non-generic types, or for generic types that are not a definition
	// I.e. Fully instantiated generic types
	if (!pTypeDef->isGenericDefinition) {
		for (token = firstIdx; token <= lastIdx; token++) {
			tMD_MethodDef *pMethodDef;

			pMethodDef = MetaData_GetMethodDefFromDefRefOrSpec(pMetaData, token, ppClassTypeArgs, ppMethodTypeArgs);

			// This is needed, so array resolution can work correctly and FindVirtualOverriddenMethod() can work.
			pMethodDef->pParentType = pTypeDef;

			if (METHOD_ISVIRTUAL(pMethodDef)) {
				if (METHOD_ISNEWSLOT(pMethodDef) || pTypeDef->pParent == NULL) {
					// Allocate a new vTable slot if method is explicitly marked as NewSlot, or
					// this is of type Object.
					pMethodDef->vTableOfs = virtualOfs++;
				} else {
					tMD_MethodDef *pVirtualOveriddenMethod;

					pVirtualOveriddenMethod = FindVirtualOverriddenMethod(pTypeDef->pParent, pMethodDef);
					Assert(pVirtualOveriddenMethod != NULL);
					pMethodDef->vTableOfs = pVirtualOveriddenMethod->vTableOfs;
				}
			} else {
				// Dummy value - make it obvious it's not valid!
				pMethodDef->vTableOfs = 0xffffffff;
			}

		}
		// Create the virtual method table
		pTypeDef->numVirtualMethods = virtualOfs;

		// Resolve fields, members, interfaces.
		// Only needs to be done if it's not a generic definition type

		// It it's not a value-type and the stack-size is not preset, then set it up now.
		// It needs to be done here as non-static fields in non-value types can point to the containing type
		if (pTypeDef->stackSize == 0 && !pTypeDef->isValueType) {
			pTypeDef->stackType = EVALSTACK_O;
			pTypeDef->stackSize = sizeof(void*);
		}
		// Resolve all fields - instance ONLY at this point,
		// because static fields in value-types can be of the containing type, and the size is not yet known.
		firstIdx = pTypeDef->fieldList;
		lastIdx = firstIdx + pTypeDef->numFields - 1;
		staticMemSize = 0;
		if (pTypeDef->numFields > 0) {
			pTypeDef->ppFields = mallocForever(pTypeDef->numFields * sizeof(tMD_FieldDef*));
		}
		instanceMemSize = (pTypeDef->pParent == NULL)?0:pTypeDef->pParent->instanceMemSize;
		for (token = firstIdx, i=0; token <= lastIdx; token++, i++) {
			tMD_FieldDef *pFieldDef;

			pFieldDef = MetaData_GetFieldDefFromDefOrRef(pMetaData, token, ppClassTypeArgs, ppMethodTypeArgs);
			if (!FIELD_ISSTATIC(pFieldDef)) {
				// Only handle non-static fields at the moment
				if (pTypeDef->pGenericDefinition != NULL) {
					// If this is a generic instantiation type, then all field defs need to be copied,
					// as there will be lots of different instantiations.
					tMD_FieldDef *pFieldCopy = TMALLOCFOREVER(tMD_FieldDef);
					memcpy(pFieldCopy, pFieldDef, sizeof(tMD_FieldDef));
					pFieldDef = pFieldCopy;
				}
				if (FIELD_ISLITERAL(pFieldDef) || FIELD_HASFIELDRVA(pFieldDef)) {
					// If it's a literal, then analyse the field, but don't include it in any memory allocation
					// If is has an RVA, then analyse the field, but don't include it in any memory allocation
					MetaData_Fill_FieldDef(pTypeDef, pFieldDef, 0, ppClassTypeArgs);
				} else {
					MetaData_Fill_FieldDef(pTypeDef, pFieldDef, instanceMemSize, ppClassTypeArgs);
					instanceMemSize += pFieldDef->memSize;
				}
				pTypeDef->ppFields[i] = pFieldDef;
			}
		}
		if (pTypeDef->instanceMemSize == 0) {
			pTypeDef->instanceMemSize = instanceMemSize;
		}

		// Sort out stack type and size.
		// Note that this may already be set, as some basic types have this preset;
		// or if it's not a value-type it'll already be set
		if (pTypeDef->stackSize == 0) {
			// if it gets here then it must be a value type
			pTypeDef->stackType = EVALSTACK_VALUETYPE;
			pTypeDef->stackSize = pTypeDef->instanceMemSize;
		}
		// Sort out array element size. Note that some basic types will have this preset.
		if (pTypeDef->arrayElementSize == 0) {
			pTypeDef->arrayElementSize = pTypeDef->stackSize;
		}

		// Handle static fields
		for (token = firstIdx, i=0; token <= lastIdx; token++, i++) {
			tMD_FieldDef *pFieldDef;

			pFieldDef = MetaData_GetFieldDefFromDefOrRef(pMetaData, token, ppClassTypeArgs, ppMethodTypeArgs);
			if (FIELD_ISSTATIC(pFieldDef)) {
				// Only handle static fields here
				if (pTypeDef->pGenericDefinition != NULL) {
					// If this is a generic instantiation type, then all field defs need to be copied,
					// as there will be lots of different instantiations.
					tMD_FieldDef *pFieldCopy = TMALLOCFOREVER(tMD_FieldDef);
					memcpy(pFieldCopy, pFieldDef, sizeof(tMD_FieldDef));
					pFieldDef = pFieldCopy;
				}
				if (FIELD_ISLITERAL(pFieldDef) || FIELD_HASFIELDRVA(pFieldDef)) {
					// If it's a literal, then analyse the field, but don't include it in any memory allocation
					// If is has an RVA, then analyse the field, but don't include it in any memory allocation
					MetaData_Fill_FieldDef(pTypeDef, pFieldDef, 0, ppClassTypeArgs);
				} else {
					MetaData_Fill_FieldDef(pTypeDef, pFieldDef, staticMemSize, ppClassTypeArgs);
					staticMemSize += pFieldDef->memSize;
				}
				pTypeDef->ppFields[i] = pFieldDef;
			}
		}
		if (staticMemSize > 0) {
			pTypeDef->pStaticFields = mallocForever(staticMemSize);
			memset(pTypeDef->pStaticFields, 0, staticMemSize);
			// Set the field addresses (->pMemory) of all static fields
			for (i = 0; i<pTypeDef->numFields; i++) {
				tMD_FieldDef *pFieldDef;

				pFieldDef = pTypeDef->ppFields[i];
				if (FIELD_ISSTATIC(pFieldDef) && pFieldDef->pMemory == NULL) {
					// Only set it if it isn't already set. It will be already set if this field has an RVA
					pFieldDef->pMemory = pTypeDef->pStaticFields + pFieldDef->memOffset;
				}
			}
			pTypeDef->staticFieldSize = staticMemSize;
		}

		// Resolve all members
		firstIdx = pTypeDef->methodList;
		lastIdx = firstIdx + pTypeDef->numMethods - 1;
		pTypeDef->ppMethods = mallocForever(pTypeDef->numMethods * sizeof(tMD_MethodDef*));
		pTypeDef->pVTable = mallocForever(pTypeDef->numVirtualMethods * sizeof(tMD_MethodDef*));
		// Copy initial vTable from parent
		if (pTypeDef->pParent != NULL) {
			memcpy(pTypeDef->pVTable, pTypeDef->pParent->pVTable, pTypeDef->pParent->numVirtualMethods * sizeof(tMD_MethodDef*));
		}
		for (token = firstIdx, i = 0; token <= lastIdx; token++, i++) {
			tMD_MethodDef *pMethodDef;

			pMethodDef = MetaData_GetMethodDefFromDefRefOrSpec(pMetaData, token, ppClassTypeArgs, ppMethodTypeArgs);
			if (pTypeDef->pGenericDefinition != NULL) {
				// If this is a generic instantiation type, then all method defs need to be copied,
				// as there will be lots of different instantiations.
				tMD_MethodDef *pMethodCopy = TMALLOCFOREVER(tMD_MethodDef);
				memcpy(pMethodCopy, pMethodDef, sizeof(tMD_MethodDef));
				pMethodDef = pMethodCopy;
			}
			if (METHOD_ISSTATIC(pMethodDef) && strcmp(pMethodDef->name, ".cctor") == 0) {
				// This is a static constructor
				pTypeDef->pStaticConstructor = pMethodDef;
			}
			if (!METHOD_ISSTATIC(pMethodDef) && pTypeDef->pParent != NULL &&
				strcmp(pMethodDef->name, "Finalize") == 0) {
				// This is a Finalizer method, but not for Object.
				// Delibrately miss out Object's Finalizer because it's empty and will cause every object
				// of any type to have a Finalizer which will be terrible for performance.
				pTypeDef->pFinalizer = pMethodDef;
			}
			if (METHOD_ISVIRTUAL(pMethodDef)) {
				// This is a virtual method, so enter it in the vTable
				pTypeDef->pVTable[pMethodDef->vTableOfs] = pMethodDef;
			}
			pTypeDef->ppMethods[i] = pMethodDef;
		}
		// Find inherited Finalizer, if this type doesn't have an explicit Finalizer, and if there is one
		if (pTypeDef->pFinalizer == NULL) {
			tMD_TypeDef *pInheritedType = pTypeDef->pParent;
			while (pInheritedType != NULL) {
				if (pInheritedType->pFinalizer != NULL) {
					pTypeDef->pFinalizer = pInheritedType->pFinalizer;
					break;
				}
				pInheritedType = pInheritedType->pParent;
			}
		}
		// Fill all method definitions for this type
		for (i=0; i<pTypeDef->numMethods; i++) {
			MetaData_Fill_MethodDef(pTypeDef, pTypeDef->ppMethods[i], ppClassTypeArgs, ppMethodTypeArgs);
		}

		// Map all interface method calls. This only needs to be done for Classes, not Interfaces
		// And is not done for generic definitions.
		if (!TYPE_ISINTERFACE(pTypeDef)) {
			firstIdx = 0;
			if (pTypeDef->pParent != NULL) {
				j = pTypeDef->numInterfaces = pTypeDef->pParent->numInterfaces;
			} else {
				j = 0;
			}
			// TODO: Better to do this once during file load (the bit in this for loop)
			for (i=1; i<=pMetaData->tables.numRows[MD_TABLE_INTERFACEIMPL]; i++) {
				tMD_InterfaceImpl *pInterfaceImpl;

				pInterfaceImpl = (tMD_InterfaceImpl*)MetaData_GetTableRow(pMetaData, MAKE_TABLE_INDEX(MD_TABLE_INTERFACEIMPL, i));
				if (pInterfaceImpl->class_ == pTypeDef->tableIndex) {
					// count how many interfaces are implemented
					pTypeDef->numInterfaces++;
					if (firstIdx == 0) {
						firstIdx = MAKE_TABLE_INDEX(MD_TABLE_INTERFACEIMPL, i);
					}
					lastIdx = MAKE_TABLE_INDEX(MD_TABLE_INTERFACEIMPL, i);
				}
			}
			if (pTypeDef->numInterfaces > 0 && !pTypeDef->isGenericDefinition) {
				U32 mapNum;

				pTypeDef->pInterfaceMaps = (tInterfaceMap*)mallocForever(pTypeDef->numInterfaces * sizeof(tInterfaceMap));
				// Copy interface maps from parent type
				if (j > 0) {
					memcpy(pTypeDef->pInterfaceMaps, pTypeDef->pParent->pInterfaceMaps, j * sizeof(tInterfaceMap));
				}
				mapNum = j;
				if (firstIdx > 0) {
					for (token=firstIdx; token<=lastIdx; token++, mapNum++) {
						tMD_InterfaceImpl *pInterfaceImpl;

						pInterfaceImpl = (tMD_InterfaceImpl*)MetaData_GetTableRow(pMetaData, token);
						if (pInterfaceImpl->class_ == pTypeDef->tableIndex) {
							tMD_TypeDef *pInterface;
							tInterfaceMap *pMap;

							// Get the interface that this type implements
							pInterface = MetaData_GetTypeDefFromDefRefOrSpec(pMetaData, pInterfaceImpl->interface_, ppClassTypeArgs, ppMethodTypeArgs);
							MetaData_Fill_TypeDef(pInterface, NULL, NULL);
							pMap = &pTypeDef->pInterfaceMaps[mapNum];
							pMap->pInterface = pInterface;
							pMap->pVTableLookup = (U32*)mallocForever(pInterface->numVirtualMethods * sizeof(U32));
							pMap->ppMethodVLookup = NULL;
							// Discover interface mapping for each interface method
							for (i=0; i<pInterface->numVirtualMethods; i++) {
								tMD_MethodDef *pInterfaceMethod, *pOverriddenMethod;

								pInterfaceMethod = pInterface->pVTable[i];
								pOverriddenMethod = FindVirtualOverriddenMethod(pTypeDef, pInterfaceMethod);
								Assert(pOverriddenMethod != NULL);
								pMap->pVTableLookup[i] = pOverriddenMethod->vTableOfs;
							}
						} else {
							Crash("Problem with interface class");
						}
					}
				}
			}
		}

		// If this is an enum type, then pretend its stack type is its underlying type
		if (pTypeDef->pParent == types[TYPE_SYSTEM_ENUM]) {
			pTypeDef->stackType = EVALSTACK_INT32;
		}
	}

	// If this is a nested type, then find the namespace of it
	if (pTypeDef->pNestedIn != NULL) {
		tMD_TypeDef *pRootTypeDef = pTypeDef->pNestedIn;
		while (pRootTypeDef->pNestedIn != NULL) {
			pRootTypeDef = pRootTypeDef->pNestedIn;
		}
		pTypeDef->nameSpace = pRootTypeDef->nameSpace;
	}

	log_f(2, "Type:  %s.%s\n", pTypeDef->nameSpace, pTypeDef->name);
}

redpajama_set_name: RedPajamaGithub


text:
title: Binding to ASP DataSource components
page_title: Binding to ASP DataSource components | RadComboBox for ASP.NET AJAX Documentation
description: Binding to ASP DataSource components
slug: combobox/data-binding/binding-to-asp-datasource-components
tags: binding,to,asp,datasource,components
published: True
position: 3
---

# Binding to ASP DataSource components

**RadComboBox** supports binding to all ASP.NET 2.0 DataSource components, including:

* AccessDataSource

* SqlDataSource

* XmlDataSource

* ObjectDataSource

* SiteMapDataSource

* LinqDataSource

To bind to a DataSource component, all you need to do is set the **DataSourceID** property of RadComboBox to the ID of the DataSource component. You should also set the **DataTextField** and **DataValueField** properties of RadComboBox to map the **Text** and **Value** properties of the items to the respective columns / fields from the data source.

If you need to map additional columns from the data source to properties of RadComboBox items, you can use the **ItemDataBound** event. The event arguments passed to the event, **e.Item** and **e.Item.DataItem**, hold the instance of RadComboBox item being bound and the **DataItem** to which it is bound. You can map a property from the **DataItem** to the corresponding property of RadComboBox item. Be sure to cast the **DataItem** object to the proper data type first.

````C#

protected void RadComboBox1_ItemDataBound(object o, RadComboBoxItemEventArgs e)
{
	DataRowView dataSourceRow = (DataRowView)e.Item.DataItem;
	e.Item.Enabled = (bool)dataSourceRow["Enabled"];
	e.Item.Attributes["customAttribute"] = dataSourceRow["CustomAttribute"].ToString();
}

````
````VB.NET

Protected Sub RadComboBox1_ItemDataBound(ByVal o As Object, ByVal e As
RadComboBoxItemEventArgs) Handles RadComboBox1.ItemDataBound

	Dim dataSourceRow As DataRowView = DirectCast(e.Item.DataItem, DataRowView)
	e.Item.Enabled = DirectCast(dataSourceRow("Enabled"), Boolean)
	e.Item.Attributes("customAttribute") = dataSourceRow("CustomAttribute").ToString()
End Sub

````

## AccessDataSource

````ASPNET
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/Data/Combo.mdb"
	SelectCommand="SELECT * FROM [Links]">
</asp:AccessDataSource>
<telerik:radcombobox
	id="RadComboBox2"
	runat="server"
	datatextfield="Text"
	datavaluefield="Value"
	datasourceid="AccessDataSource1"
	onitemdatabound="RadComboBox2_ItemDataBound" />
````

## SqlDataSource

````ASPNET
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComboConnectionString %>"
	SelectCommand="SELECT * FROM [Links]"></asp:SqlDataSource>
<telerik:radcombobox
	id="RadComboBox1"
	runat="server"
	datatextfield="Text"
	datavaluefield="Value"
	datasourceid="SqlDataSource1"
	onitemdatabound="RadComboBox1_ItemDataBound" />
````

## XmlDataSource

````ASPNET

<telerik:radcombobox
		id="RadComboBox1"
		runat="server"
		datasourceid="XmlDataSource1"
		datatextfield="Text"
		datavaluefield="Value">
</telerik:radcombobox>

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/ContentFile.xml"></asp:XmlDataSource>

````

When using an **XmlDataSource**, the XML file should have the format shown below:

````XML

<items>
 <Item Text="New York" Value="1" />
 <Item Text="Paris" Value="2" />
 <Item Text="London" Value="3" />
</items>

````

>note You can also [load the XML file directly]({%slug combobox/radcombobox-items/loading-items-from-xml%}), rather than using a DataSource component as an intermediary.
>

## ObjectDataSource

````ASPNET
<telerik:radcombobox
	id="RadComboBox1"
	runat="server"
	datavaluefield="ID"
	datatextfield="Text"
	datasourceid="ObjectDataSource1">
</telerik:radcombobox>
<asp:ObjectDataSource ID="ObjectDataSource1" TypeName="ComboObjectData" SelectMethod="GetItems"
	runat="server"></asp:ObjectDataSource>
````

````C#

public class ComboObjectData
{
	public ComboObjectData() { }
	public static List<ComboDataItem> GetItems()
	{
		List<ComboDataItem> itemsList = new List<ComboDataItem>();
		itemsList.Add(new ComboDataItem(1, "item 1"));
		itemsList.Add(new ComboDataItem(2, "item 2"));
		itemsList.Add(new ComboDataItem(3, "item 3"));
		return itemsList;
	}
	public class ComboDataItem
	{
		private string _text;
		private int _id;
		public string Text
		{
			get
			{
				return _text;
			}
			set
			{
				_text = value;
			}
		}
		public int ID
		{
			get
			{
				return _id;
			}
			set
			{
				_id = value;
			}
		}
		public ComboDataItem(int id, string text)
		{
			_id = id;
			_text = text;
		}
	}
}

````
````VB.NET

Public Class ComboObjectData
	Public Sub New()
	End Sub
	Public Shared Function GetItems() As List(Of ComboDataItem)
		Dim itemsList As New List(Of ComboDataItem)()
		itemsList.Add(New ComboDataItem(1, "item 1"))
		itemsList.Add(New ComboDataItem(2, "item 2"))
		itemsList.Add(New ComboDataItem(3, "item 3"))
		Return itemsList
	End Function
	Public Class ComboDataItem
		Private _text As String
		Private _id As Integer
		Public Property Text() As String
			Get
				Return _text
			End Get
			Set(ByVal value As String)
				_text = value
			End Set
		End Property
		Public Property ID() As Integer
			Get
				Return _id
			End Get
			Set(ByVal value As Integer)
				_id = value
			End Set
		End Property

		Public Sub New(ByVal id As Integer, ByVal text As String)
			_id = id
			_text = text
		End Sub
	End Class
End Class

````


text:
'use strict';

// Equipments controller
angular.module('equipments').controller('EquipmentsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Equipments',
	function($scope, $stateParams, $location, Authentication, Equipments) {
		$scope.authentication = Authentication;

		// Create new Equipment
		$scope.create = function() {
			// Create new Equipment object
			var equipment = new Equipments ({
				name: this.name
			});

			// Redirect after save
			equipment.$save(function(response) {
				$location.path('equipments/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Equipment
		$scope.remove = function(equipment) {
			if ( equipment ) {
				equipment.$remove();

				for (var i in $scope.equipments) {
					if ($scope.equipments [i] === equipment) {
						$scope.equipments.splice(i, 1);
					}
				}
			} else {
				$scope.equipment.$remove(function() {
					$location.path('equipments');
				});
			}
		};

		// Update existing Equipment
		$scope.update = function() {
			var equipment = $scope.equipment;

			equipment.$update(function() {
				$location.path('equipments/' + equipment._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Equipments
		$scope.find = function() {
			$scope.equipments = Equipments.query();
		};

		// Find existing Equipment
		$scope.findOne = function() {
			$scope.equipment = Equipments.get({
				equipmentId: $stateParams.equipmentId
			});
		};
	}
]);


text:
layout: post
title: Caveblazers
date-added: 2017-02-26
game-url: http://www.rupeck.com/caveblazers
game-publisher: http://www.rupeck.com/
game-image: UefYawD.jpg
game-published: Apr 1, 2016
game-status: EARLY ACCESS
score-random: 5
score-progression: 4
score-platforming: 5
score-permadeath: 4
score-exploration: 4
score-controller: 1
catagory: fit
year-added: 2016
---

Really close fit with some very interesting companion mechanics.  Bosses are really tough in this one and don't have a ton of variety.


text:
Angular Material
SKIP TO CONTENT
Documentation Version

LATEST RELEASE (1.1.0-RC.5)
TOGGLE COLLAPSED
GETTING STARTED

DEMOS
TOGGLE EXPANDED
Autocomplete
Bottom Sheet
Button
Card
Checkbox
Chips
Colors
Content
Datepicker
Dialog
Divider
FAB Speed Dial
FAB Toolbar
Grid List
Icon
Input
List
Menu
Menu Bar current page
Nav Bar
Panel
Progress Circular
Progress Linear
Radio Button
Select
Sidenav
Slider
Subheader
Swipe
Switch
Tabs
Toast
Toolbar
Tooltip
Virtual Repeat
Whiteframe
Customization

CSS
TOGGLE COLLAPSED

THEMING
TOGGLE COLLAPSED
API Reference

LAYOUT
TOGGLE COLLAPSED

SERVICES
TOGGLE COLLAPSED

TYPES
TOGGLE COLLAPSED

DIRECTIVES
TOGGLE COLLAPSED
CONTRIBUTORS
Demos -  Menu Bar
Basic Usage

HTMLJSCSSHTMLJSCSS
angular
  .module('menuBarDemoBasic', ['ngMaterial'])
  .config(function($mdIconProvider) {
    $mdIconProvider
      .defaultIconSet('img/icons/sets/core-icons.svg', 24);
  })
  .filter('keyboardShortcut', function($window) {
    return function(str) {
      if (!str) return;
      var keys = str.split('-');
      var isOSX = /Mac OS X/.test($window.navigator.userAgent);
      var seperator = (!isOSX || keys.length > 2) ? '+' : '';
      var abbreviations = {
        M: isOSX ? '⌘' : 'Ctrl',
        A: isOSX ? 'Option' : 'Alt',
        S: 'Shift'
      };
      return keys.map(function(key, index) {
        var last = index == keys.length - 1;
        return last ? key : abbreviations[key];
      }).join(seperator);
    };
  })
  .controller('DemoBasicCtrl', function DemoCtrl($mdDialog) {
    this.settings = {
      printLayout: true,
      showRuler: true,
      showSpellingSuggestions: true,
      presentationMode: 'edit'
    };
    this.sampleAction = function(name, ev) {
      $mdDialog.show($mdDialog.alert()
        .title(name)
        .textContent('You triggered the "' + name + '" action')
        .ok('Great')
        .targetEvent(ev)
      );
    };
  });
Untitled document
File   Edit   View   Format
Untitled document

Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum. Nulla vitae elit libero, a pharetra augue. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.

Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Vestibulum id ligula porta felis euismod semper. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Nulla vitae elit libero, a pharetra augue. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.

Etiam porta sem malesuada magna mollis euismod. Maecenas faucibus mollis interdum. Maecenas sed diam eget risus varius blandit sit amet non magna. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

Powered by Google ©2014–2016. Code licensed under the MIT License. Documentation licensed under CC BY 4.0.


text:
layout: post
title: Analysis of RocsksDB code
subtitle: about benchmark tool's source code
category: DataBase
tags: [rocksdb, facebook]
permalink: /2016/04/08/Rocks_DB_Bench_Tool_source/
---

rocksDB/tools/db_bench_too.cc is file to analyze "./db_bench" utility code.

facebook tests performance of rocksdb as configured by default.

now, I will test rocksDB in centos 7.2 , linux basic version(of cetnos 7.1), and rocksDB 4.3.1 release version

the following is set up environment of facebook's rocksDB test to compare levelDB to rocksDB performance, and XFS filesystem is important for me to think.

    Operating System Linux 2.6.38.4

    total database size is 800GB, stored on XFS filesystem with TRIM support

from now on, I will start source analyzation of rocksDB for rocksDB bench market tool.

above all, the following is the summarization of db_bench_tool terms & way to test rocksDB.

```c++
DEFINE_string(benchmarks,
              "fillseq,"
              "fillsync,"
              "fillrandom,"
              "overwrite,"
              "readrandom,"
              "newiterator,"
              "newiteratorwhilewriting,"
              "seekrandom,"
              "seekrandomwhilewriting,"
              "seekrandomwhilemerging,"
              "readseq,"
              "readreverse,"
              "compact,"
              "readrandom,"
              "multireadrandom,"
              "readseq,"
              "readtocache,"
              "readreverse,"
              "readwhilewriting,"
              "readwhilemerging,"
              "readrandomwriterandom,"
              "updaterandom,"
              "randomwithverify,"
              "fill100K,"
              "crc32c,"
              "xxhash,"
              "compress,"
              "uncompress,"
              "acquireload,"
              "fillseekseq,"
              "randomtransaction,"
              "randomreplacekeys",

              "Comma-separated list of operations to run in the specified"
              " order. Available benchmarks:\n"
              "\tfillseq       -- write N values in sequential key"
              " order in async mode\n"
              "\tfillrandom    -- write N values in random key order in async"
              " mode\n"
              "\toverwrite     -- overwrite N values in random key order in"
              " async mode\n"
              "\tfillsync      -- write N/100 values in random key order in "
              "sync mode\n"
              "\tfill100K      -- write N/1000 100K values in random order in"
              " async mode\n"
              "\tdeleteseq     -- delete N keys in sequential order\n"
              "\tdeleterandom  -- delete N keys in random order\n"
              "\treadseq       -- read N times sequentially\n"
              "\treadtocache   -- 1 thread reading database sequentially\n"
              "\treadreverse   -- read N times in reverse order\n"
              "\treadrandom    -- read N times in random order\n"
              "\treadmissing   -- read N missing keys in random order\n"
              "\treadwhilewriting      -- 1 writer, N threads doing random "
              "reads\n"
              "\treadwhilemerging      -- 1 merger, N threads doing random "
              "reads\n"
              "\treadrandomwriterandom -- N threads doing random-read, "
              "random-write\n"
              "\tprefixscanrandom      -- prefix scan N times in random order\n"
              "\tupdaterandom  -- N threads doing read-modify-write for random "
              "keys\n"
              "\tappendrandom  -- N threads doing read-modify-write with "
              "growing values\n"
              "\tmergerandom   -- same as updaterandom/appendrandom using merge"
              " operator. "
              "Must be used with merge_operator\n"
              "\treadrandommergerandom -- perform N random read-or-merge "
              "operations. Must be used with merge_operator\n"
              "\tnewiterator   -- repeated iterator creation\n"
              "\tseekrandom    -- N random seeks, call Next seek_nexts times "
              "per seek\n"
              "\tseekrandomwhilewriting -- seekrandom and 1 thread doing "
              "overwrite\n"
              "\tseekrandomwhilemerging -- seekrandom and 1 thread doing "
              "merge\n"
              "\tcrc32c        -- repeated crc32c of 4K of data\n"
              "\txxhash        -- repeated xxHash of 4K of data\n"
              "\tacquireload   -- load N*1000 times\n"
              "\tfillseekseq   -- write N values in sequential key, then read "
              "them by seeking to each key\n"
              "\trandomtransaction     -- execute N random transactions and "
              "verify correctness\n"
              "\trandomreplacekeys     -- randomly replaces N keys by deleting "
              "the old version and putting the new version\n\n"
              "Meta operations:\n"
              "\tcompact     -- Compact the entire DB\n"
              "\tstats       -- Print DB stats\n"
              "\tlevelstats  -- Print the number of files and bytes per level\n"
              "\tsstables    -- Print sstable info\n"
              "\theapprofile -- Dump a heap profile (if supported by this"
              " port)\n");

the texts above is way to benchmark rocksDB.

the following is the way to configure variable for benchmark.

DEFINE_int64(num, 1000000, "Number of key/values to place in database");

DEFINE_int64(numdistinct, 1000,
             "Number of distinct keys to use. Used in RandomWithVerify to "
             "read/write on fewer keys so that gets are more likely to find the"
             " key and puts are more likely to update the same key");

```

## while analyzing source code, I committed to rocksdb open source.

![](/)

## get started (based on rocksdb 4.6 version source, I looked into the source)

**First, source analyzation get started in directory (/rocksDB/tools/db_benc.cc file)**

    - keywords : rocksdb::db_bench_tool(argc, argv);

```c++
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#ifndef GFLAGS
#include <cstdio>
int main() {
  fprintf(stderr, "Please install gflags to run rocksdb tools\n");
  return 1;
}
#else
#include <rocksdb/db_bench_tool.h>
int main(int argc, char** argv) { rocksdb::db_bench_tool(argc, argv); }
#endif  // GFLAGS

```

**Second, db_bench_tool function in rocksdb/tools/db_bench_tool.cc file**

    - keywords : rocksdb::Benchmark benchmark;, rocksdb::Benchmark benchmark;, FLAGS_db

```c++
int db_bench_tool(int argc, char** argv) {
  rocksdb::port::InstallStackTraceHandler();
  SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) +
                  " [OPTIONS]...");
  ParseCommandLineFlags(&argc, &argv, true);

  FLAGS_compaction_style_e = (rocksdb::CompactionStyle) FLAGS_compaction_style;
  if (FLAGS_statistics) {
    dbstats = rocksdb::CreateDBStatistics();
  }
  FLAGS_compaction_pri_e = (rocksdb::CompactionPri)FLAGS_compaction_pri;

  std::vector<std::string> fanout = rocksdb::StringSplit(
      FLAGS_max_bytes_for_level_multiplier_additional, ',');
  for (size_t j = 0; j < fanout.size(); j++) {
    FLAGS_max_bytes_for_level_multiplier_additional_v.push_back(
#ifndef CYGWIN
        std::stoi(fanout[j]));
#else
        stoi(fanout[j]));
#endif
  }

  FLAGS_compression_type_e =
    StringToCompressionType(FLAGS_compression_type.c_str());

  if (!FLAGS_hdfs.empty()) {
    FLAGS_env  = new rocksdb::HdfsEnv(FLAGS_hdfs);
  }

  if (!strcasecmp(FLAGS_compaction_fadvice.c_str(), "NONE"))
    FLAGS_compaction_fadvice_e = rocksdb::Options::NONE;
  else if (!strcasecmp(FLAGS_compaction_fadvice.c_str(), "NORMAL"))
    FLAGS_compaction_fadvice_e = rocksdb::Options::NORMAL;
  else if (!strcasecmp(FLAGS_compaction_fadvice.c_str(), "SEQUENTIAL"))
    FLAGS_compaction_fadvice_e = rocksdb::Options::SEQUENTIAL;
  else if (!strcasecmp(FLAGS_compaction_fadvice.c_str(), "WILLNEED"))
    FLAGS_compaction_fadvice_e = rocksdb::Options::WILLNEED;
  else {
    fprintf(stdout, "Unknown compaction fadvice:%s\n",
            FLAGS_compaction_fadvice.c_str());
  }

  FLAGS_rep_factory = StringToRepFactory(FLAGS_memtablerep.c_str());

  // The number of background threads should be at least as much the
  // max number of concurrent compactions.
  FLAGS_env->SetBackgroundThreads(FLAGS_max_background_compactions);
  FLAGS_env->SetBackgroundThreads(FLAGS_max_background_flushes,
                                  rocksdb::Env::Priority::HIGH);

  // Choose a location for the test database if none given with --db=<path>
  if (FLAGS_db.empty()) {
    std::string default_db_path;
    rocksdb::Env::Default()->GetTestDirectory(&default_db_path);
    default_db_path += "/dbbench";
    FLAGS_db = default_db_path;
  }

  if (FLAGS_stats_interval_seconds > 0) {
    // When both are set then FLAGS_stats_interval determines the frequency
    // at which the timer is checked for FLAGS_stats_interval_seconds
    FLAGS_stats_interval = 1000;
  }

  //so far, rocksdb option setting

  rocksdb::Benchmark benchmark;   // from now on, benchmark go newly
  benchmark.Run();                // Run() function is next target for source analyzation.
  return 0;
}
```

**third, Run() function /rocksdb/tools/db_bench_tool.cc**

    - keywords : PrintHeader();, Open(&open_options_);, RunBenchmark(num_threads, name, method);

```c++
void Run() {
    if (!SanityCheck()) {
      exit(1);
    }
    PrintHeader();
    Open(&open_options_);
    std::stringstream benchmark_stream(FLAGS_benchmarks);
    std::string name;
    while (std::getline(benchmark_stream, name, ',')) {
      // Sanitize parameters
      num_ = FLAGS_num;
      reads_ = (FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads);
      writes_ = (FLAGS_writes < 0 ? FLAGS_num : FLAGS_writes);
      value_size_ = FLAGS_value_size;
      key_size_ = FLAGS_key_size;
      entries_per_batch_ = FLAGS_batch_size;
      write_options_ = WriteOptions();
      read_random_exp_range_ = FLAGS_read_random_exp_range;
      if (FLAGS_sync) {
        write_options_.sync = true;
      }
      write_options_.disableWAL = FLAGS_disable_wal;

      void (Benchmark::*method)(ThreadState*) = nullptr;
      void (Benchmark::*post_process_method)() = nullptr;

      bool fresh_db = false;
      int num_threads = FLAGS_threads;

      if (name == "fillseq") {
        fresh_db = true;
        method = &Benchmark::WriteSeq;
      } else if (name == "fillbatch") {
        fresh_db = true;
        entries_per_batch_ = 1000;
        method = &Benchmark::WriteSeq;
      } else if (name == "fillrandom") {
        fresh_db = true;
        method = &Benchmark::WriteRandom;
      } else if (name == "filluniquerandom") {
        fresh_db = true;
        if (num_threads > 1) {
          fprintf(stderr,
                  "filluniquerandom multithreaded not supported"
                  ", use 1 thread");
          num_threads = 1;
        }
        method = &Benchmark::WriteUniqueRandom;
      } else if (name == "overwrite") {
        method = &Benchmark::WriteRandom;
      } else if (name == "fillsync") {
        fresh_db = true;
        num_ /= 1000;
        write_options_.sync = true;
        method = &Benchmark::WriteRandom;
      } else if (name == "fill100K") {
        fresh_db = true;
        num_ /= 1000;
        value_size_ = 100 * 1000;
        method = &Benchmark::WriteRandom;
      } else if (name == "readseq") {
        method = &Benchmark::ReadSequential;
      } else if (name == "readtocache") {
        method = &Benchmark::ReadSequential;
        num_threads = 1;
        reads_ = num_;
      } else if (name == "readreverse") {
        method = &Benchmark::ReadReverse;
      } else if (name == "readrandom") {
        method = &Benchmark::ReadRandom;
      } else if (name == "readrandomfast") {
        method = &Benchmark::ReadRandomFast;
      } else if (name == "multireadrandom") {
        fprintf(stderr, "entries_per_batch = %" PRIi64 "\n",
                entries_per_batch_);
        method = &Benchmark::MultiReadRandom;
      } else if (name == "readmissing") {
        ++key_size_;
        method = &Benchmark::ReadRandom;
      } else if (name == "newiterator") {
        method = &Benchmark::IteratorCreation;
      } else if (name == "newiteratorwhilewriting") {
        num_threads++;  // Add extra thread for writing
        method = &Benchmark::IteratorCreationWhileWriting;
      } else if (name == "seekrandom") {
        method = &Benchmark::SeekRandom;
      } else if (name == "seekrandomwhilewriting") {
        num_threads++;  // Add extra thread for writing
        method = &Benchmark::SeekRandomWhileWriting;
      } else if (name == "seekrandomwhilemerging") {
        num_threads++;  // Add extra thread for merging
        method = &Benchmark::SeekRandomWhileMerging;
      } else if (name == "readrandomsmall") {
        reads_ /= 1000;
        method = &Benchmark::ReadRandom;
      } else if (name == "deleteseq") {
        method = &Benchmark::DeleteSeq;
      } else if (name == "deleterandom") {
        method = &Benchmark::DeleteRandom;
      } else if (name == "readwhilewriting") {
        num_threads++;  // Add extra thread for writing
        method = &Benchmark::ReadWhileWriting;
      } else if (name == "readwhilemerging") {
        num_threads++;  // Add extra thread for writing
        method = &Benchmark::ReadWhileMerging;
      } else if (name == "readrandomwriterandom") {
        method = &Benchmark::ReadRandomWriteRandom;
      } else if (name == "readrandommergerandom") {
        if (FLAGS_merge_operator.empty()) {
          fprintf(stdout, "%-12s : skipped (--merge_operator is unknown)\n",
                  name.c_str());
          exit(1);
        }
        method = &Benchmark::ReadRandomMergeRandom;
      } else if (name == "updaterandom") {
        method = &Benchmark::UpdateRandom;
      } else if (name == "appendrandom") {
        method = &Benchmark::AppendRandom;
      } else if (name == "mergerandom") {
        if (FLAGS_merge_operator.empty()) {
          fprintf(stdout, "%-12s : skipped (--merge_operator is unknown)\n",
                  name.c_str());
          exit(1);
        }
        method = &Benchmark::MergeRandom;
      } else if (name == "randomwithverify") {
        method = &Benchmark::RandomWithVerify;
      } else if (name == "fillseekseq") {
        method = &Benchmark::WriteSeqSeekSeq;
      } else if (name == "compact") {
        method = &Benchmark::Compact;
      } else if (name == "crc32c") {
        method = &Benchmark::Crc32c;
      } else if (name == "xxhash") {
        method = &Benchmark::xxHash;
      } else if (name == "acquireload") {
        method = &Benchmark::AcquireLoad;
      } else if (name == "compress") {
        method = &Benchmark::Compress;
      } else if (name == "uncompress") {
        method = &Benchmark::Uncompress;
#ifndef ROCKSDB_LITE
      } else if (name == "randomtransaction") {
        method = &Benchmark::RandomTransaction;
        post_process_method = &Benchmark::RandomTransactionVerify;
#endif  // ROCKSDB_LITE
      } else if (name == "randomreplacekeys") {
        fresh_db = true;
        method = &Benchmark::RandomReplaceKeys;
      } else if (name == "stats") {
        PrintStats("rocksdb.stats");
      } else if (name == "levelstats") {
        PrintStats("rocksdb.levelstats");
      } else if (name == "sstables") {
        PrintStats("rocksdb.sstables");
      } else if (!name.empty()) {  // No error message for empty name
        fprintf(stderr, "unknown benchmark '%s'\n", name.c_str());
        exit(1);
      }

      if (fresh_db) {
        if (FLAGS_use_existing_db) {
          fprintf(stdout, "%-12s : skipped (--use_existing_db is true)\n",
                  name.c_str());
          method = nullptr;
        } else {
          if (db_.db != nullptr) {
            db_.DeleteDBs();
            DestroyDB(FLAGS_db, open_options_);
          }
          for (size_t i = 0; i < multi_dbs_.size(); i++) {
            delete multi_dbs_[i].db;
            DestroyDB(GetDbNameForMultiple(FLAGS_db, i), open_options_);
          }
          multi_dbs_.clear();
        }
        Open(&open_options_);  // use open_options for the last accessed
      }

      if (method != nullptr) {
        fprintf(stdout, "DB path: [%s]\n", FLAGS_db.c_str());
        RunBenchmark(num_threads, name, method);
      }
      if (post_process_method != nullptr) {
        (this->*post_process_method)();
      }
    }
    if (FLAGS_statistics) {
     fprintf(stdout, "STATISTICS:\n%s\n", dbstats->ToString().c_str());
    }
  }
```

** fourth, PrintHeader() function in rocksDB/tools/db_bench_tool.cc file**

    - keywords : there is no keyword. just print function

```c++
void PrintHeader() {
    PrintEnvironment();
    fprintf(stdout, "Keys:       %d bytes each\n", FLAGS_key_size);
    fprintf(stdout, "Values:     %d bytes each (%d bytes after compression)\n",
            FLAGS_value_size,
            static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
    fprintf(stdout, "Entries:    %" PRIu64 "\n", num_);
    fprintf(stdout, "Prefix:    %d bytes\n", FLAGS_prefix_size);
    fprintf(stdout, "Keys per prefix:    %" PRIu64 "\n", keys_per_prefix_);
    fprintf(stdout, "RawSize:    %.1f MB (estimated)\n",
            ((static_cast<int64_t>(FLAGS_key_size + FLAGS_value_size) * num_)
             / 1048576.0));
    fprintf(stdout, "FileSize:   %.1f MB (estimated)\n",
            (((FLAGS_key_size + FLAGS_value_size * FLAGS_compression_ratio)
              * num_)
             / 1048576.0));
    fprintf(stdout, "Write rate: %" PRIu64 " bytes/second\n",
            FLAGS_benchmark_write_rate_limit);
    if (FLAGS_enable_numa) {
      fprintf(stderr, "Running in NUMA enabled mode.\n");
#ifndef NUMA
      fprintf(stderr, "NUMA is not defined in the system.\n");
      exit(1);
#else
      if (numa_available() == -1) {
        fprintf(stderr, "NUMA is not supported by the system.\n");
        exit(1);
      }
#endif
    }

    auto compression = CompressionTypeToString(FLAGS_compression_type_e);
    fprintf(stdout, "Compression: %s\n", compression.c_str());

    switch (FLAGS_rep_factory) {
      case kPrefixHash:
        fprintf(stdout, "Memtablerep: prefix_hash\n");
        break;
      case kSkipList:
        fprintf(stdout, "Memtablerep: skip_list\n");
        break;
      case kVectorRep:
        fprintf(stdout, "Memtablerep: vector\n");
        break;
      case kHashLinkedList:
        fprintf(stdout, "Memtablerep: hash_linkedlist\n");
        break;
      case kCuckoo:
        fprintf(stdout, "Memtablerep: cuckoo\n");
        break;
    }
    fprintf(stdout, "Perf Level: %d\n", FLAGS_perf_level);

    PrintWarnings(compression.c_str());
    fprintf(stdout, "------------------------------------------------\n");
  }
```

**fifth, PrintEnvironment() function in rocksDB/tools/db_bench_tool.cc file**

    - keywords : there is no keywords, just print process

```c+
void PrintEnvironment() {
    fprintf(stderr, "RocksDB:    version %d.%d\n",
            kMajorVersion, kMinorVersion);

#if defined(__linux)
    time_t now = time(nullptr);
    char buf[52];
    // Lint complains about ctime() usage, so replace it with ctime_r(). The
    // requirement is to provide a buffer which is at least 26 bytes.
    fprintf(stderr, "Date:       %s",
            ctime_r(&now, buf));  // ctime_r() adds newline

    FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
    if (cpuinfo != nullptr) {
      char line[1000];
      int num_cpus = 0;
      std::string cpu_type;
      std::string cache_size;
      while (fgets(line, sizeof(line), cpuinfo) != nullptr) {
        const char* sep = strchr(line, ':');
        if (sep == nullptr) {
          continue;
        }
        Slice key = TrimSpace(Slice(line, sep - 1 - line));
        Slice val = TrimSpace(Slice(sep + 1));
        if (key == "model name") {
          ++num_cpus;
          cpu_type = val.ToString();
        } else if (key == "cache size") {
          cache_size = val.ToString();
        }
      }
      fclose(cpuinfo);
      fprintf(stderr, "CPU:        %d * %s\n", num_cpus, cpu_type.c_str());
      fprintf(stderr, "CPUCache:   %s\n", cache_size.c_str());
    }
#endif
  }
```

**sixth, Open(options * opts) in rocksdb/tools/db_bench_tool.cc **

    - keywords : this just configure option

```c++
void Open(Options* opts) {
    Options& options = *opts;

    assert(db_.db == nullptr);

    options.create_if_missing = !FLAGS_use_existing_db;
    options.create_missing_column_families = FLAGS_num_column_families > 1;
    options.db_write_buffer_size = FLAGS_db_write_buffer_size;
    options.write_buffer_size = FLAGS_write_buffer_size;
    options.max_write_buffer_number = FLAGS_max_write_buffer_number;
    options.min_write_buffer_number_to_merge =
      FLAGS_min_write_buffer_number_to_merge;
    options.max_write_buffer_number_to_maintain =
        FLAGS_max_write_buffer_number_to_maintain;
    options.max_background_compactions = FLAGS_max_background_compactions;
    options.max_subcompactions = static_cast<uint32_t>(FLAGS_subcompactions);
    options.max_background_flushes = FLAGS_max_background_flushes;
    options.compaction_style = FLAGS_compaction_style_e;
    options.compaction_pri = FLAGS_compaction_pri_e;
    if (FLAGS_prefix_size != 0) {
      options.prefix_extractor.reset(
          NewFixedPrefixTransform(FLAGS_prefix_size));
    }
    if (FLAGS_use_uint64_comparator) {
      options.comparator = test::Uint64Comparator();
      if (FLAGS_key_size != 8) {
        fprintf(stderr, "Using Uint64 comparator but key size is not 8.\n");
        exit(1);
      }
    }
    options.memtable_prefix_bloom_bits = FLAGS_memtable_bloom_bits;
    options.bloom_locality = FLAGS_bloom_locality;
    options.max_open_files = FLAGS_open_files;
    options.max_file_opening_threads = FLAGS_file_opening_threads;
    options.new_table_reader_for_compaction_inputs =
        FLAGS_new_table_reader_for_compaction_inputs;
    options.compaction_readahead_size = FLAGS_compaction_readahead_size;
    options.random_access_max_buffer_size = FLAGS_random_access_max_buffer_size;
    options.writable_file_max_buffer_size = FLAGS_writable_file_max_buffer_size;
    options.statistics = dbstats;
    if (FLAGS_enable_io_prio) {
      FLAGS_env->LowerThreadPoolIOPriority(Env::LOW);
      FLAGS_env->LowerThreadPoolIOPriority(Env::HIGH);
    }
    if (FLAGS_disable_flashcache_for_background_threads &&
        cachedev_fd_ == -1) {
      // Avoid creating the env twice when an use_existing_db is true
      cachedev_fd_ = open(FLAGS_flashcache_dev.c_str(), O_RDONLY);
      if (cachedev_fd_ < 0) {
        fprintf(stderr, "Open flash device failed\n");
        exit(1);
      }
      flashcache_aware_env_ = NewFlashcacheAwareEnv(FLAGS_env, cachedev_fd_);
      if (flashcache_aware_env_.get() == nullptr) {
        fprintf(stderr, "Failed to open flashcache device at %s\n",
                FLAGS_flashcache_dev.c_str());
        std::abort();
      }
      options.env = flashcache_aware_env_.get();
    } else {
      options.env = FLAGS_env;
    }
    options.disableDataSync = FLAGS_disable_data_sync;
    options.use_fsync = FLAGS_use_fsync;
    options.wal_dir = FLAGS_wal_dir;
    options.num_levels = FLAGS_num_levels;
    options.target_file_size_base = FLAGS_target_file_size_base;
    options.target_file_size_multiplier = FLAGS_target_file_size_multiplier;
    options.max_bytes_for_level_base = FLAGS_max_bytes_for_level_base;
    options.level_compaction_dynamic_level_bytes =
        FLAGS_level_compaction_dynamic_level_bytes;
    options.max_bytes_for_level_multiplier =
        FLAGS_max_bytes_for_level_multiplier;
    options.filter_deletes = FLAGS_filter_deletes;
    if (FLAGS_row_cache_size) {
      if (FLAGS_cache_numshardbits >= 1) {
        options.row_cache =
            NewLRUCache(FLAGS_row_cache_size, FLAGS_cache_numshardbits);
      } else {
        options.row_cache = NewLRUCache(FLAGS_row_cache_size);
      }
    }
    if ((FLAGS_prefix_size == 0) && (FLAGS_rep_factory == kPrefixHash ||
                                     FLAGS_rep_factory == kHashLinkedList)) {
      fprintf(stderr, "prefix_size should be non-zero if PrefixHash or "
                      "HashLinkedList memtablerep is used\n");
      exit(1);
    }
    switch (FLAGS_rep_factory) {
      case kSkipList:
        options.memtable_factory.reset(new SkipListFactory(
            FLAGS_skip_list_lookahead));
        break;
#ifndef ROCKSDB_LITE
      case kPrefixHash:
        options.memtable_factory.reset(
            NewHashSkipListRepFactory(FLAGS_hash_bucket_count));
        break;
      case kHashLinkedList:
        options.memtable_factory.reset(NewHashLinkListRepFactory(
            FLAGS_hash_bucket_count));
        break;
      case kVectorRep:
        options.memtable_factory.reset(
          new VectorRepFactory
        );
        break;
      case kCuckoo:
        options.memtable_factory.reset(NewHashCuckooRepFactory(
            options.write_buffer_size, FLAGS_key_size + FLAGS_value_size));
        break;
#else
      default:
        fprintf(stderr, "Only skip list is supported in lite mode\n");
        exit(1);
#endif  // ROCKSDB_LITE
    }
    if (FLAGS_use_plain_table) {
#ifndef ROCKSDB_LITE
      if (FLAGS_rep_factory != kPrefixHash &&
          FLAGS_rep_factory != kHashLinkedList) {
        fprintf(stderr, "Waring: plain table is used with skipList\n");
      }
      if (!FLAGS_mmap_read && !FLAGS_mmap_write) {
        fprintf(stderr, "plain table format requires mmap to operate\n");
        exit(1);
      }

      int bloom_bits_per_key = FLAGS_bloom_bits;
      if (bloom_bits_per_key < 0) {
        bloom_bits_per_key = 0;
      }

      PlainTableOptions plain_table_options;
      plain_table_options.user_key_len = FLAGS_key_size;
      plain_table_options.bloom_bits_per_key = bloom_bits_per_key;
      plain_table_options.hash_table_ratio = 0.75;
      options.table_factory = std::shared_ptr<TableFactory>(
          NewPlainTableFactory(plain_table_options));
#else
      fprintf(stderr, "Plain table is not supported in lite mode\n");
      exit(1);
#endif  // ROCKSDB_LITE
    } else if (FLAGS_use_cuckoo_table) {
#ifndef ROCKSDB_LITE
      if (FLAGS_cuckoo_hash_ratio > 1 || FLAGS_cuckoo_hash_ratio < 0) {
        fprintf(stderr, "Invalid cuckoo_hash_ratio\n");
        exit(1);
      }
      rocksdb::CuckooTableOptions table_options;
      table_options.hash_table_ratio = FLAGS_cuckoo_hash_ratio;
      table_options.identity_as_first_hash = FLAGS_identity_as_first_hash;
      options.table_factory = std::shared_ptr<TableFactory>(
          NewCuckooTableFactory(table_options));
#else
      fprintf(stderr, "Cuckoo table is not supported in lite mode\n");
      exit(1);
#endif  // ROCKSDB_LITE
    } else {
      BlockBasedTableOptions block_based_options;
      if (FLAGS_use_hash_search) {
        if (FLAGS_prefix_size == 0) {
          fprintf(stderr,
              "prefix_size not assigned when enable use_hash_search \n");
          exit(1);
        }
        block_based_options.index_type = BlockBasedTableOptions::kHashSearch;
      } else {
        block_based_options.index_type = BlockBasedTableOptions::kBinarySearch;
      }
      if (cache_ == nullptr) {
        block_based_options.no_block_cache = true;
      }
      block_based_options.cache_index_and_filter_blocks =
          FLAGS_cache_index_and_filter_blocks;
      block_based_options.pin_l0_filter_and_index_blocks_in_cache =
          FLAGS_pin_l0_filter_and_index_blocks_in_cache;
      block_based_options.block_cache = cache_;
      block_based_options.block_cache_compressed = compressed_cache_;
      block_based_options.block_size = FLAGS_block_size;
      block_based_options.block_restart_interval = FLAGS_block_restart_interval;
      block_based_options.filter_policy = filter_policy_;
      block_based_options.skip_table_builder_flush =
          FLAGS_skip_table_builder_flush;
      block_based_options.format_version = 2;
      options.table_factory.reset(
          NewBlockBasedTableFactory(block_based_options));
    }
    if (FLAGS_max_bytes_for_level_multiplier_additional_v.size() > 0) {
      if (FLAGS_max_bytes_for_level_multiplier_additional_v.size() !=
          (unsigned int)FLAGS_num_levels) {
        fprintf(stderr, "Insufficient number of fanouts specified %d\n",
                (int)FLAGS_max_bytes_for_level_multiplier_additional_v.size());
        exit(1);
      }
      options.max_bytes_for_level_multiplier_additional =
        FLAGS_max_bytes_for_level_multiplier_additional_v;
    }
    options.level0_stop_writes_trigger = FLAGS_level0_stop_writes_trigger;
    options.level0_file_num_compaction_trigger =
        FLAGS_level0_file_num_compaction_trigger;
    options.level0_slowdown_writes_trigger =
      FLAGS_level0_slowdown_writes_trigger;
    options.compression = FLAGS_compression_type_e;
    options.compression_opts.level = FLAGS_compression_level;
    options.WAL_ttl_seconds = FLAGS_wal_ttl_seconds;
    options.WAL_size_limit_MB = FLAGS_wal_size_limit_MB;
    options.max_total_wal_size = FLAGS_max_total_wal_size;

    if (FLAGS_min_level_to_compress >= 0) {
      assert(FLAGS_min_level_to_compress <= FLAGS_num_levels);
      options.compression_per_level.resize(FLAGS_num_levels);
      for (int i = 0; i < FLAGS_min_level_to_compress; i++) {
        options.compression_per_level[i] = kNoCompression;
      }
      for (int i = FLAGS_min_level_to_compress;
           i < FLAGS_num_levels; i++) {
        options.compression_per_level[i] = FLAGS_compression_type_e;
      }
    }
    options.soft_rate_limit = FLAGS_soft_rate_limit;
    options.hard_rate_limit = FLAGS_hard_rate_limit;
    options.soft_pending_compaction_bytes_limit =
        FLAGS_soft_pending_compaction_bytes_limit;
    options.hard_pending_compaction_bytes_limit =
        FLAGS_hard_pending_compaction_bytes_limit;
    options.delayed_write_rate = FLAGS_delayed_write_rate;
    options.allow_concurrent_memtable_write =
        FLAGS_allow_concurrent_memtable_write;
    options.enable_write_thread_adaptive_yield =
        FLAGS_enable_write_thread_adaptive_yield;
    options.write_thread_max_yield_usec = FLAGS_write_thread_max_yield_usec;
    options.write_thread_slow_yield_usec = FLAGS_write_thread_slow_yield_usec;
    options.rate_limit_delay_max_milliseconds =
      FLAGS_rate_limit_delay_max_milliseconds;
    options.table_cache_numshardbits = FLAGS_table_cache_numshardbits;
    options.max_grandparent_overlap_factor =
      FLAGS_max_grandparent_overlap_factor;
    options.disable_auto_compactions = FLAGS_disable_auto_compactions;
    options.source_compaction_factor = FLAGS_source_compaction_factor;

    // fill storage options
    options.allow_os_buffer = FLAGS_bufferedio;
    options.allow_mmap_reads = FLAGS_mmap_read;
    options.allow_mmap_writes = FLAGS_mmap_write;
    options.advise_random_on_open = FLAGS_advise_random_on_open;
    options.access_hint_on_compaction_start = FLAGS_compaction_fadvice_e;
    options.use_adaptive_mutex = FLAGS_use_adaptive_mutex;
    options.bytes_per_sync = FLAGS_bytes_per_sync;
    options.wal_bytes_per_sync = FLAGS_wal_bytes_per_sync;

    // merge operator options
    options.merge_operator = MergeOperators::CreateFromStringId(
        FLAGS_merge_operator);
    if (options.merge_operator == nullptr && !FLAGS_merge_operator.empty()) {
      fprintf(stderr, "invalid merge operator: %s\n",
              FLAGS_merge_operator.c_str());
      exit(1);
    }
    options.max_successive_merges = FLAGS_max_successive_merges;
    options.compaction_measure_io_stats = FLAGS_compaction_measure_io_stats;

    // set universal style compaction configurations, if applicable
    if (FLAGS_universal_size_ratio != 0) {
      options.compaction_options_universal.size_ratio =
        FLAGS_universal_size_ratio;
    }
    if (FLAGS_universal_min_merge_width != 0) {
      options.compaction_options_universal.min_merge_width =
        FLAGS_universal_min_merge_width;
    }
    if (FLAGS_universal_max_merge_width != 0) {
      options.compaction_options_universal.max_merge_width =
        FLAGS_universal_max_merge_width;
    }
    if (FLAGS_universal_max_size_amplification_percent != 0) {
      options.compaction_options_universal.max_size_amplification_percent =
        FLAGS_universal_max_size_amplification_percent;
    }
    if (FLAGS_universal_compression_size_percent != -1) {
      options.compaction_options_universal.compression_size_percent =
        FLAGS_universal_compression_size_percent;
    }
    options.compaction_options_universal.allow_trivial_move =
        FLAGS_universal_allow_trivial_move;
    if (FLAGS_thread_status_per_interval > 0) {
      options.enable_thread_tracking = true;
    }
    if (FLAGS_rate_limiter_bytes_per_sec > 0) {
      options.rate_limiter.reset(
          NewGenericRateLimiter(FLAGS_rate_limiter_bytes_per_sec));
    }

#ifndef ROCKSDB_LITE
    if (FLAGS_readonly && FLAGS_transaction_db) {
      fprintf(stderr, "Cannot use readonly flag with transaction_db\n");
      exit(1);
    }
#endif  // ROCKSDB_LITE

    if (FLAGS_num_multi_db <= 1) {
      OpenDb(options, FLAGS_db, &db_);
    } else {
      multi_dbs_.clear();
      multi_dbs_.resize(FLAGS_num_multi_db);
      for (int i = 0; i < FLAGS_num_multi_db; i++) {
        OpenDb(options, GetDbNameForMultiple(FLAGS_db, i), &multi_dbs_[i]);
      }
    }
    if (FLAGS_min_level_to_compress >= 0) {
      options.compression_per_level.clear();
    }
  }
```

**seventh, After I looked into FLAGS_db variable in rocksDB/tools/db_bench_too.cc file, I tested about creating Database.**

the following is results :

```shell
[hyunyoung.lee@localhost ~]$ cd rocksdb-4.3.1/
[hyunyoung.lee@localhost rocksdb-4.3.1]$ ./db_bench
LevelDB:    version 4.3
Date:       Wed Apr 13 10:53:18 2016
CPU:        4 * Intel(R) Core(TM) i3-0000 CPU @ 3.40GHz
CPUCache:   3072 KB
Keys:       16 bytes each
Values:     100 bytes each (50 bytes after compression)
Entries:    1000000
Prefix:    0 bytes
Keys per prefix:    0
RawSize:    110.6 MB (estimated)
FileSize:   62.9 MB (estimated)
Writes per second: 0
Compression: Snappy
Memtablerep: skip_list
Perf Level: 0
WARNING: Assertions are enabled; benchmarks unnecessarily slow
------------------------------------------------
DB path: [/tmp/rocksdbtest-1000/dbbench]
fillseq      :       1.293 micros/op 773175 ops/sec;   85.5 MB/s
DB path: [/tmp/rocksdbtest-1000/dbbench]
fillsync     :       2.868 micros/op 348677 ops/sec;   38.6 MB/s (1000 ops)
DB path: [/tmp/rocksdbtest-1000/dbbench]
fillrandom   :       2.800 micros/op 357188 ops/sec;   39.5 MB/s
DB path: [/tmp/rocksdbtest-1000/dbbench]
overwrite    :       2.858 micros/op 349954 ops/sec;   38.7 MB/s
DB path: [/tmp/rocksdbtest-1000/dbbench]
readrandom   :       8.079 micros/op 123782 ops/sec;   13.7 MB/s (1000000 of 1000000 found)

DB path: [/tmp/rocksdbtest-1000/dbbench]
newiterator  :       0.814 micros/op 1228303 ops/sec;
DB path: [/tmp/rocksdbtest-1000/dbbench]
newiteratorwhilewriting :       1.891 micros/op 528781 ops/sec;
DB path: [/tmp/rocksdbtest-1000/dbbench]
seekrandom   :      10.043 micros/op 99569 ops/sec; (816350 of 1000000 found)

DB path: [/tmp/rocksdbtest-1000/dbbench]
seekrandomwhilewriting :      51.014 micros/op 19602 ops/sec; (917578 of 1000000 found)

DB path: [/tmp/rocksdbtest-1000/dbbench]
put or merge error: Not implemented: Provide a merge_operator when opening DB
pure virtual method called
pure virtual method called
terminate called without an active exception
terminate called without an active exception
Received signal 6 (Aborted)
Aborted
[hyunyoung.lee@localhost rocksdb-4.3.1]$ ./db_bench --db=/dev/nvme0n1
LevelDB:    version 4.3
Date:       Wed Apr 13 10:56:58 2016
CPU:        4 * Intel(R) Core(TM) i3-0000 CPU @ 3.40GHz
CPUCache:   3072 KB
Keys:       16 bytes each
Values:     100 bytes each (50 bytes after compression)
Entries:    1000000
Prefix:    0 bytes
Keys per prefix:    0
RawSize:    110.6 MB (estimated)
FileSize:   62.9 MB (estimated)
Writes per second: 0
Compression: Snappy
Memtablerep: skip_list
Perf Level: 0
WARNING: Assertions are enabled; benchmarks unnecessarily slow
------------------------------------------------
open error: IO error: `/dev/nvme0n1' exists but is not a directory
```

after source analyzation of db_bench_tools.cc, rocksDB relies on filesystem as levelDB.

if you know more about it, please refer to <a href ="https://github.com/facebook/rocksdb/issues/1016">this site</a>


text:
Universitas Pardede merupakan sebuah universitas baru yang berfokus pada Ilmu
Komputer Aplikatif, yang diantaranya mengajari Dasar-Dasar Powerpoint,
Photoshop: Seni dan Desain, Pengembangan Pengoperasian Warnet, dsb.

Suatu hari, Univ. Pardede kewalahan karena management mahasiswanya masih
belum dibuat, sehingga UP mengadakan sayembara yang bernama "PLS BUILD OUR
DATABASE 2K17", Benny sebagai mahasiswa Ilmu Komputer merasa tertarik mengikuti
lomba ini bukan karena tertantang kemampuan programmingnya, namun karena
hadiahnya yang berupa stok mie instan untuk 4 tahun. Oleh karena itu Benny
mengajak anda, mahasiswa Ilmu Komputer UI yang berdedikasi di dunia
programming, untuk membantunya membuat program sederhana untuk management data
mahasiswa Universitas Pardede.

**Tugas:**

Membuat program yang berguna untuk memasukkan data berupa matkul dan
pesertanya, serta beberapa operasi terkait matkul-matkul tersebut.

### Format masukkan:

1. `tambah <matkul> <npm1> <npm2> . . . <npmX>`
   Menambahkan matkul baru dengan nama `<matkul>`, yang beranggotakan
   mahasiswa yang direpresentasikan dengan NPM, dari `<npm1>` hingga `<npmX>`.

2. `gabungan <matkul1> <matkul2>`
   Mencetak NPM-NPM mahasiswa yang mengambil `<matkul1>` **ATAU** `<matkul2>`.

3. `pengambil <matkul1> <matkul2>`
   Mencetak NPM-NPM mahasiswa yang mengambil `<matkul1>` **DAN** `<matkul2>`.

4. `hanya <matkul1> <matkul2>`
   Mencetak NPM-NPM mahasiswa yang mengambil `<matkul1>` tetapi **TIDAK**
   mengambil `<matkul2>`.

5. `cetak <matkul>`
   Mencetak NPM-NPM mahasiswa yang mengambil `<matkul>`.

6. `cetak matkul`
   Mencetak NPM-NPM mahasiswa terdaftar di semua matkul yang ada.

7. `selesai`
   Memberhentikan / keluar dari program

### Format Keluaran :

1. `tambah`:
   `<matkul> berhasil ditambahkan!`

2. `gabungan`/`pengambil`/`hanya`:
   **Ket : cetak NPM-NPM nya saja yang sesuai dengan kriteria perintahnya**

3. `cetak <matkul>`:
   `<matkul> : <NPM tiap tiap peserta>`

4. `cetak matkul`:
   **Ket : Untuk setiap matkul, print dengan format :**
   `<matkul> : <NPM tiap-tiap peserta>`

5. `selesai`:
   `Program berhenti!`

**Untuk lebih mengerti input dan output, coba lihat contoh di bawah.
Contoh Jalannya Program:**

```
tambah DDP 12345 14045 15680 12345 65789
DDP berhasil ditambahkan!

cetak DDP
DDP : {15680, 12345, 14045, 65789}

tambah PPW 48224 12345 16898 14045
PPW berhasil ditambahkan!

tambah PSD 55668
PSD berhasil ditambahkan!

cetak matkul
DDP : {15680, 12345, 14045, 65789}
PPW : {48224, 12345, 16898, 14045}
PSD : {55668}

gabungan DDP PSD
{15680, 55668, 12345, 14045, 65789}

pengambil DDP PPW
{12345, 14045}

hanya DDP PPW
{15680, 65789}

hanya PPW DDP
{48224, 16898}

selesai
Program berhenti!
```

Dibawah ini disediakan *template* code untuk membantu kalian.
**PERHATIAN : Penggunaan template ini tidak wajib, jika kalian memiliki solusi
sendiri yang lebih kalian mengerti, gunakan solusi kalian sendiri.**

```python
def main():
    matkul =  # Buat sebuah dictionary
    while  # Buat agar meminta input terus :
        masukan = input(">>> ")
        '''
        Buat agar program berhenti saat masukan adalah "selesai"
        '''

    masukan_split = masukan.split(" ")

    if masukan_split[0] == "tambah":
        nama_matkul = masukan_split[1]
        npm_semua = masukan_split[2:]
        # Buat sebuah set untuk menampung NPM-NPM diatas
        # Masukan ke dictionary yang telah dibuat diatas
        print(masukan_split[1],"berhasil ditambahkan!")

    # Gunakan method yang dimiliki set untuk melakukan 3 operasi di bawah ini
    elif masukan_split[0] == "gabungan":

    elif masukan_split[0] == "pengambil":

    elif masukan_split[0] == "hanya":

    # ------------------------------------------------------
    elif masukan_split[0] == "cetak":
        # Lakukan selection, apakah cetak salah satu matkul, atau semuanya
        # dan lakukan operasi print sesuai format
    else:
        print("Perintah salah !")

main()
```

<br>

**FDL IF PDD SAT**

---

Diambil dari `Soal Tutorial Lab 7 - Kelas C.pdf` (Tutorial Lab 7 DDP1 C
\-- 30 Oktober 2017)


text:
var Foo =
/*#__PURE__*/
function (_Bar) {
  "use strict";

  function Foo() {
    var _this;

    babelHelpers.classCallCheck(this, Foo);
    if (eval("false")) _this = babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this));
    return babelHelpers.possibleConstructorReturn(_this);
  }

  babelHelpers.inherits(Foo, _Bar);
  return Foo;
}(Bar);


text:
<?php
/**
* Snippet Polish lexicon topic
*
* @language pl
* @package modx
* @subpackage lexicon
*/

#$_lang['snippet'] = 'Snippet';
$_lang['snippet'] = 'Snippet';

#$_lang['snippets_available'] = 'Snippets available for you to include in your page';
$_lang['snippets_available'] = 'Snippets available for you to include in your page';

#$_lang['snippet_code'] = 'Snippet code (php)';
$_lang['snippet_code'] = 'Snippet code (php)';

#$_lang['snippet_delete_confirm'] = 'Are you sure you want to delete this snippet?';
$_lang['snippet_delete_confirm'] = 'Are you sure you want to delete this snippet?';

#$_lang['snippet_desc'] = 'Description';
$_lang['snippet_desc'] = 'Description';

#$_lang['snippet_duplicate_confirm'] = 'Are you sure you want to duplicate this snippet?';
$_lang['snippet_duplicate_confirm'] = 'Are you sure you want to duplicate this snippet?';

#$_lang['snippet_duplicate_error'] = 'An error occurred while duplicating the snippet.';
$_lang['snippet_duplicate_error'] = 'An error occurred while duplicating the snippet.';

#$_lang['snippet_err_create'] = 'An error occurred while creating the snippet.';
$_lang['snippet_err_create'] = 'An error occurred while creating the snippet.';

#$_lang['snippet_err_delete'] = 'An error occured while trying to delete the snippet.';
$_lang['snippet_err_delete'] = 'An error occured while trying to delete the snippet.';

#$_lang['snippet_err_duplicate'] = 'An error occured while trying to duplicate the snippet.';
$_lang['snippet_err_duplicate'] = 'An error occured while trying to duplicate the snippet.';

#$_lang['snippet_err_exists_name'] = 'A snippet already exists with the name "[[+name]]".';
$_lang['snippet_err_exists_name'] = 'A snippet already exists with the name "[[+name]]".';

#$_lang['snippet_err_invalid_name'] = 'Snippet name is invalid.';
$_lang['snippet_err_invalid_name'] = 'Snippet name is invalid.';

#$_lang['snippet_err_locked'] = 'This snippet is locked for editing.';
$_lang['snippet_err_locked'] = 'This snippet is locked for editing.';

#$_lang['snippet_err_nf'] = 'Snippet not found!';
$_lang['snippet_err_nf'] = 'Snippet not found!';

#$_lang['snippet_err_ns'] = 'Snippet not specified.';
$_lang['snippet_err_ns'] = 'Snippet not specified.';

#$_lang['snippet_err_ns_name'] = 'Please specify a name for the snippet.';
$_lang['snippet_err_ns_name'] = 'Please specify a name for the snippet.';

#$_lang['snippet_err_remove'] = 'An error occurred while remove the snippet.';
$_lang['snippet_err_remove'] = 'An error occurred while remove the snippet.';

#$_lang['snippet_err_save'] = 'An error occurred while saving the snippet.';
$_lang['snippet_err_save'] = 'An error occurred while saving the snippet.';

#$_lang['snippet_execonsave'] = 'Execute snippet after saving.';
$_lang['snippet_execonsave'] = 'Execute snippet after saving.';

#$_lang['snippet_lock'] = 'Lock snippet for editing';
$_lang['snippet_lock'] = 'Lock snippet for editing';

#$_lang['snippet_lock_msg'] = 'Users must have the edit_locked attribute in order to can edit this snippet.';
$_lang['snippet_lock_msg'] = 'Users must have the edit_locked attribute in order to can edit this snippet.';

#$_lang['snippet_management_msg'] = 'Here you can choose which snippet you wish to edit.';
$_lang['snippet_management_msg'] = 'Here you can choose which snippet you wish to edit.';

#$_lang['snippet_msg'] = 'Here you can add/edit snippets. Remember, snippets are \'raw\' PHP code, and if you expect the output of the snippet to be shown at a certain point within the template, you need to return a value from within the snippet.';
$_lang['snippet_msg'] = 'Here you can add/edit snippets. Remember, snippets are \'raw\' PHP code, and if you expect the output of the snippet to be shown at a certain point within the template, you need to return a value from within the snippet.';

#$_lang['snippet_name'] = 'Snippet name';
$_lang['snippet_name'] = 'Snippet name';

#$_lang['snippet_new'] = 'New Snippet';
$_lang['snippet_new'] = 'New Snippet';

#$_lang['snippet_properties'] = 'Default Properties';
$_lang['snippet_properties'] = 'Default Properties';

#$_lang['snippet_title'] = 'Create/edit snippet';
$_lang['snippet_title'] = 'Create/edit snippet';

#$_lang['snippet_untitled'] = 'Untitled snippet';
$_lang['snippet_untitled'] = 'Untitled snippet';

#$_lang['snippets'] = 'Snippets';
$_lang['snippets'] = 'Snippets';


text:
package org.apache.rya.indexing.pcj.fluo.integration;

import static org.junit.Assert.assertEquals;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.apache.accumulo.core.client.Connector;
import org.apache.fluo.api.client.FluoClient;
import org.apache.fluo.api.client.FluoFactory;
import org.apache.log4j.Logger;
import org.apache.rya.indexing.pcj.fluo.api.CreateFluoPcj;
import org.apache.rya.indexing.pcj.storage.PrecomputedJoinStorage;
import org.apache.rya.indexing.pcj.storage.PrecomputedJoinStorage.CloseableIterator;
import org.apache.rya.indexing.pcj.storage.accumulo.AccumuloPcjStorage;
import org.apache.rya.pcj.fluo.test.base.RyaExportITBase;
import org.junit.Test;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.query.BindingSet;

public class StreamingTestIT extends RyaExportITBase {

	private static final Logger log = Logger.getLogger(StreamingTestIT.class);

	@Test
	public void testRandomStreamingIngest() throws Exception {
	    final String sparql =
	            "select ?name ?uuid where { " +
                    "?uuid <http://pred1> ?name ; "  +
                    "<http://pred2> \"literal\"." +
                "}";

	    try (FluoClient fluoClient = FluoFactory.newClient(super.getFluoConfiguration())) {
	        // Create the PCJ table.
	        final Connector accumuloConn = super.getAccumuloConnector();
	        final PrecomputedJoinStorage pcjStorage = new AccumuloPcjStorage(accumuloConn, getRyaInstanceName());
	        final String pcjId = pcjStorage.createPcj(sparql);

	        // Task the Fluo app with the PCJ.
	        new CreateFluoPcj().withRyaIntegration(pcjId, pcjStorage, fluoClient, accumuloConn, getRyaInstanceName());

	        // Add Statements to the Fluo app.
	        log.info("Adding Join Pairs...");
	        addRandomQueryStatementPairs(100);

	        super.getMiniFluo().waitForObservers();

	        int resultCount = 0;
	        try(CloseableIterator<BindingSet> resultsIt = pcjStorage.listResults(pcjId)) {
	            while(resultsIt.hasNext()) {
	                resultCount++;
	                resultsIt.next();
	            }
	        }

	        // Show the correct number of Binding Sets were created for the PCJ.
	        assertEquals(100, resultCount);
	    }
	}

	private void addRandomQueryStatementPairs(final int numPairs) throws Exception {
		final Set<Statement> statementPairs = new HashSet<>();
		for (int i = 0; i < numPairs; i++) {
			final String uri = "http://uuid_" + UUID.randomUUID().toString();
			final Statement statement1 = new StatementImpl(new URIImpl(uri), new URIImpl("http://pred1"),
					new LiteralImpl("number_" + (i + 1)));
			final Statement statement2 = new StatementImpl(new URIImpl(uri), new URIImpl("http://pred2"), new LiteralImpl("literal"));
			statementPairs.add(statement1);
			statementPairs.add(statement2);
		}
		super.getRyaSailRepository().getConnection().add(statementPairs, new Resource[0]);
		super.getMiniFluo().waitForObservers();
	}
}


text:
"""Various functions for creating and returning various data to be used
by the ``acsql`` web application.

This module contains functions to obtains image and proposal metadata
for use by the ``acsql`` web application.  See the ``acsql_webapp``
module for further information about the web application.

Authors
-------

    - Matthew Bourque
    - Meredith Durbin

Use
---

    This module is intended to be imported and used by ``acsql_webapp``
    as such:
    ::

        from acsql.website.data_containers import get_view_image_dict
        from acsql.website.data_containers import get_view_proposal_dict

        image_dict = get_view_image_dict(proposal, filename, fits_type)
        proposal_dict = get_view_proposal_dict(proposal)

Dependencies
------------

    - ``acsql``
"""

import glob
import html
import os
import requests

from acsql.database import database_interface
from acsql.database.database_interface import Master
from acsql.utils.utils import SETTINGS

def _get_image_lists(data_dict, fits_type):
    """Add a list of JPEG and Thumbnail paths to the ``data_dict``
    dictionary.

    Parameters
    ----------
    data_dict : dict
        A dictionary containing data used to render a webpage.
    fits_type : str
        The FITS type.  Can either be ``raw``, ``flt``, or ``flc``.

    Returns
    -------
    data_dict : dict
        A dictionary containing data used to render a webpage.
    """

    jpeg_proposal_path = os.path.join('static/img/jpegs/', data_dict['proposal_id'])
    thumb_proposal_path = os.path.join('static/img/thumbnails/', data_dict['proposal_id'])

    data_dict['jpegs'] = sorted(glob.glob(os.path.join(jpeg_proposal_path, '*flt.jpg')))
    data_dict['thumbs'] = sorted(glob.glob(os.path.join(thumb_proposal_path, '*flt.thumb')))

    return data_dict

def _get_metadata_from_database(data_dict):
    """Add observation metadata (e.g. ``aperture``, ``exptime``, etc.)
    to the ``data_dict`` by querying the ``acsql`` database.

    Parameters
    ----------
    data_dict : dict
        A dictionary containing data used to render a webpage.

    Returns
    -------
    data_dict : dict
        A dictionary containing data used to render a webpage.
    """

    session = getattr(database_interface, 'session')

    results = []
    for rootname in data_dict['rootnames']:

        detector = session.query(Master.detector)\
            .filter(Master.rootname == rootname).one()[0]

        table = getattr(database_interface, '{}_raw_0'.format(detector))
        result = session.query(
            table.aperture, table.exptime, table.filter1, table.filter2,
            table.targname, table.date_obs, table.time_obs, table.expstart,
            table.expflag, table.quality, table.ra_targ, table.dec_targ,
            table.pr_inv_f, table.pr_inv_l).filter(table.rootname == rootname).one()
        result = [item for item in result]
        result.append(detector)
        results.append(result)

    session.close()

    # Parse the results
    data_dict['detectors'] = [detector for item in results]
    data_dict['apertures'] = [item[0] for item in results]
    data_dict['exptimes'] = [item[1] for item in results]
    data_dict['filter1s'] = [item[2] for item in results]
    data_dict['filter2s'] = [item[3] for item in results]
    data_dict['targnames'] = [item[4] for item in results]
    data_dict['dateobss'] = [item[5] for item in results]
    data_dict['timeobss'] = [item[6] for item in results]
    data_dict['expstarts'] = [item[7] for item in results]
    data_dict['expflags'] = [item[8] for item in results]
    data_dict['qualitys'] = [item[9] for item in results]
    data_dict['ras'] = [item[10] for item in results]
    data_dict['decs'] = [item[11] for item in results]
    data_dict['pi_firsts'] = [item[12] for item in results]
    data_dict['pi_lasts'] = [item[13] for item in results]

    return data_dict

def _get_buttons_dict(data_dict):
    """Add data used for various buttons on the ``/archive/<proposal>``
    page or ``/database/results/`` page to the ``data_dict``.

    Parameters
    ----------
    data_dict : dict
        A dictionary containing data for the given
        ``/archive/<proposal>`` or ``/database/results/`` page, such as
        ``visits`` and ``targnames``

    Returns
    -------
    data_dict : dict
        A dictionary containing data for the given
        ``/archive/<proposal>`` or ``/database/results/`` page, such as
        ``visits`` and ``targnames``
    """

    data_dict['buttons'] = {}
    data_dict['buttons']['detector'] = sorted(set(data_dict['detectors']))
    data_dict['buttons']['visit'] = sorted(set(data_dict['visits']))
    data_dict['buttons']['target'] = sorted(set(data_dict['targnames']))
    data_dict['buttons']['filter'] = sorted(set([
        '{}/{}'.format(filter1, filter2)
        for filter1, filter2
        in zip(data_dict['filter1s'], data_dict['filter2s'])]))

    return data_dict

def _get_proposal_status(data_dict):
    """Add proposal status information (e.g. ``proposal_title``,
    ``cycle``, etc.) to the ``data_dict``.

    The proposal status information is scraped from the proposal
    status webpage.

    Parameters
    ----------
    data_dict : dict
        A dictionary containing data used to render a webpage.

    Returns
    -------
    data_dict : dict
        A dictionary containing data used to render a webpage.
    """

    data_dict['status_page'] = (
        'http://www.stsci.edu/cgi-bin/get-proposal-info?id={}'
        '&submit=Go&observatory=HST').format(data_dict['proposal_id'])

    req = requests.get(data_dict['status_page'], timeout=3)

    if req.ok:

        status_string = req.content.decode()
        data_dict['proposal_title'] = html.unescape(status_string.\
            split('Title: ')[1].\
            split('
')[0])
        data_dict['cycle'] = html.unescape(status_string.\
            split('Cycle: ')[1].\
            split('
')[0])
        data_dict['schedule'] = html.unescape(status_string.\
            split('/proposal-help-HST.html#')[2].\
            split('">')[0])

    else:
        print('Request failed: {}'.format(data_dict['status_page']))
        data_dict['proposal_title'] = 'proposal title unavailable'
        data_dict['cycle'] = None
        data_dict['schedule'] = None

    return data_dict

def _initialize_data_dict(proposal, fits_type='flt'):
    """Create and return a dictionary containing commonly used data
    amongst ``/archive/<proposal>/`` and
    ``/archive/<proposal>/<filename>`` webpages.

    Parameters
    ----------
    proposal : str
        The proposal number (e.g. ``12345``).
    fits_type : str
        The FITS type.  Can be ``raw``, ``flt``, or ``flc``.

    Returns
    -------
    data_dict : dict
        A dictionary containing data used to render a webpage.
    """

    data_dict = {}
    data_dict['proposal_id'] = proposal
    data_dict = _get_image_lists(data_dict, fits_type)
    data_dict['rootnames'] = [os.path.basename(item).split('_')[0][:-1] for item in data_dict['jpegs']]
    data_dict['filenames'] = [os.path.basename(item).split('_')[0] for item in data_dict['jpegs']]
    data_dict['num_images'] = len(data_dict['jpegs'])
    data_dict = _get_proposal_status(data_dict)

    return data_dict

# def get_view_header_dict(filename, fits_type='flt'):
#     """
#     """

#     header_dict = {}
#     header_dict['filename'] = filename
#     header_dict['fits_type'] = fits_type.upper

#     return header_dict

def get_view_image_dict(proposal, filename, fits_type='flt'):
    """Return a dictionary containing data used for the
    ``/archive/<proposal>/<filename>/`` webpage.

    Parameters
    ----------
    proposal : str
        The proposal number (e.g. ``12345``).
    filename : str
        The 9-character IPPPSSOOT rootname (e.g. ``jcye04zsq``.)
    fits_type : str
        The JPEG FITS type to view. Can either be ``raw``, ``flt``, or
        ``flc``.

    Returns
    -------
    image_dict : dict
        A dictionary containing data used for the
        ``/archive/<proposal>/<filename>`` webpage.
    """

    image_dict = _initialize_data_dict(proposal, fits_type)
    image_dict['fits_type'] = fits_type.upper()
    image_dict['filename'] = filename
    image_dict['rootname'] = filename[:-1]
    image_dict = _get_metadata_from_database(image_dict)
    image_dict['index'] = image_dict['filenames'].index(image_dict['filename'])
    image_dict['page'] = image_dict['index'] + 1
    image_dict['expstart'] = image_dict['expstarts'][image_dict['index']]
    image_dict['filter1'] = image_dict['filter1s'][image_dict['index']]
    image_dict['filter2'] = image_dict['filter2s'][image_dict['index']]
    image_dict['aperture'] = image_dict['apertures'][image_dict['index']]
    image_dict['exptime'] = image_dict['exptimes'][image_dict['index']]
    image_dict['expflag'] = image_dict['expflags'][image_dict['index']]
    image_dict['quality'] = image_dict['qualitys'][image_dict['index']]
    image_dict['ra'] = image_dict['ras'][image_dict['index']]
    image_dict['dec'] = image_dict['decs'][image_dict['index']]
    image_dict['targname'] = image_dict['targnames'][image_dict['index']]
    image_dict['pi_first_name'] = image_dict['pi_firsts'][image_dict['index']]
    image_dict['pi_last_name'] = image_dict['pi_lasts'][image_dict['index']]
    image_dict['view_url'] = 'archive/{}/{}/{}'.format(image_dict['proposal_id'], image_dict['filename'], fits_type)
    image_dict['fits_links'] = {}
    image_dict['first'] = image_dict['index'] == 0
    image_dict['last'] = image_dict['index'] == image_dict['num_images'] - 1

    # Determine path to JPEG
    jpeg_path = '/static/img/jpegs/{}/{}_{}.jpg'.format(image_dict['proposal_id'], image_dict['filename'], fits_type)
    jpeg_path_abs = os.path.join(SETTINGS['jpeg_dir'], image_dict['proposal_id'], '{}_{}.jpg'.format(image_dict['filename'], fits_type))
    if os.path.exists(jpeg_path_abs):
        image_dict['image'] = jpeg_path
    else:
        image_dict['image'] = None

    # Determine next and previous images, if possible
    if not image_dict['last']:
        image_dict['next'] = {'proposal': image_dict['proposal_id'], 'filename': image_dict['filenames'][image_dict['index'] + 1], 'fits_type': fits_type}
    if not image_dict['first']:
        image_dict['prev'] = {'proposal': image_dict['proposal_id'], 'filename': image_dict['filenames'][image_dict['index'] - 1], 'fits_type': fits_type}

    # Determine other available JPEGs for given observation
    jpeg_types = glob.glob(jpeg_path_abs.replace('{}.jpg'.format(fits_type), '*.jpg'))
    jpeg_types = [os.path.basename(item).split('_')[-1].split('.')[0] for item in jpeg_types]
    jpeg_types = [item for item in jpeg_types if item.upper() != image_dict['fits_type']]
    image_dict['available_jpegs'] = {}
    for jpeg_type in jpeg_types:
        image_dict['available_jpegs'][jpeg_type] = image_dict['view_url'].replace(fits_type, jpeg_type)

    # For downloading the files
    # image_dict['proposal_name'] = image_dict['filename'][0:4]
    # image_dict['fits_links']['FLT'] = os.path.join(
    #                                       SETTINGS['filesystem'],
    #                                       image_dict['proposal_name'],
    #                                       image_dict['filename'],
    #                                       '{}_flt.fits'.format(image_dict['filename']))

    return image_dict

def get_view_proposal_dict(proposal):
    """Return a dictionary containing data used for the
    ``/archive/<proposal>/` webpage.

    Parameters
    ----------
    proposal : str
        The proposal number (e.g. ``12345``).

    Returns
    -------
    proposal_dict : dict
        A dictionary containing data used for the
        ``/archive/<proposal>/`` webpage.
    """

    proposal_dict = _initialize_data_dict(proposal)
    proposal_dict['visits'] = [os.path.basename(item).split('_')[0][4:6].upper() for item in proposal_dict['jpegs']]
    proposal_dict['num_visits'] = len(set(proposal_dict['visits']))
    proposal_dict = _get_metadata_from_database(proposal_dict)
    proposal_dict = _get_buttons_dict(proposal_dict)
    proposal_dict['viewlinks'] = ['/archive/{}/{}/'.format(proposal_dict['proposal_id'], filename) for filename in proposal_dict['filenames']]

    return proposal_dict

def get_view_query_results_dict(query_results_dict):
    """Return a dictionary containing data used for the
    ``/database/results/`` webpage.

    Parameters
    ----------
    query_results_dict : dict
        A dictionary containing the results of the query performed
        through the ``/database/`` webpage, along with some additional
        metadata.

    Returns
    -------
    thumbnail_dict : dict
        A dictionary containing data used for the ``/database/results/``
        webpage.
    """

    query_results = query_results_dict['query_results']

    thumbnail_dict = {}
    thumbnail_dict['num_images'] = query_results_dict['num_results']
    thumbnail_dict['rootnames'] = [item[3] for item in query_results]
    thumbnail_dict['filenames'] = [item[4].split('_')[0] for item in query_results]
    thumbnail_dict['detectors'] = [item[5] for item in query_results]
    thumbnail_dict['expstarts'] = [item[6] for item in query_results]
    thumbnail_dict['filter1s'] = [item[7] for item in query_results]
    thumbnail_dict['filter2s'] = [item[8] for item in query_results]
    thumbnail_dict['exptimes'] = [item[9] for item in query_results]
    thumbnail_dict['targnames'] = [item[10] for item in query_results]
    thumbnail_dict['proposal_ids'] = [item[11] for item in query_results]
    thumbnail_dict['visits'] = [item[4:6] for item in thumbnail_dict['rootnames']]
    thumbnail_dict = _get_buttons_dict(thumbnail_dict)
    thumbnail_dict['thumbs'] = ['static/img/thumbnails/{}/{}_flt.thumb'.format(proposid, filename)
        for proposid, filename in zip(thumbnail_dict['proposal_ids'], thumbnail_dict['filenames'])]
    thumbnail_dict['viewlinks'] = ['/archive/{}/{}/'.format(proposid, filename)
        for proposid, filename in zip(thumbnail_dict['proposal_ids'], thumbnail_dict['filenames'])]

    return thumbnail_dict


text:
typedef NS_ENUM(NSUInteger, SPPersonalClubInfoUpdateViewControllerStyle) {
    SPPersonalClubInfoUpdateViewControllerStyleUpdateClubName  = 1,
    SPPersonalClubInfoUpdateViewControllerStyleUpdateClubEvent = 2,
    SPPersonalClubInfoUpdateViewControllerStyleUpdateClubOther = 3
};

@protocol SPPersonalClubInfoUpdateViewControllerProtocol <NSObject>

- (void)finishedUpdateClubNameAction:(NSString *)clubName;
- (void)finishedUpdateClubEventAction:(NSString *)clubEventString clubEventNum:(NSString *)clubEventNum;

@end

@interface SPPersonalClubInfoUpdateViewController : SPBaseViewController

@property (weak) id <SPPersonalClubInfoUpdateViewControllerProtocol> delegate;

- (instancetype)initWithStyle:(SPPersonalClubInfoUpdateViewControllerStyle)style
                 sourceString:(NSString *)sourceString
                       clubId:(NSString *)clubId;

@end