text:
//
// as_scriptcode.cpp
//
// A container class for the script code to be compiled
//

#include "as_config.h"
#include "as_scriptcode.h"

BEGIN_AS_NAMESPACE

asCScriptCode::asCScriptCode()
{
	lineOffset = 0;
	code = 0;
	codeLength = 0;
	sharedCode = false;
}

asCScriptCode::~asCScriptCode()
{
	if( !sharedCode && code )
	{
		asDELETEARRAY(code);
	}
}

int asCScriptCode::SetCode(const char *name, const char *code, bool makeCopy)
{
	return SetCode(name, code, 0, makeCopy);
}

int asCScriptCode::SetCode(const char *name, const char *code, size_t length, bool makeCopy)
{
	if( !code ) return asINVALID_ARG;
	this->name = name ? name : "";
	if( !sharedCode && this->code )
		asDELETEARRAY(this->code);

	if( length == 0 )
		length = strlen(code);
	if( makeCopy )
	{
		codeLength = length;
		sharedCode = false;
		this->code = asNEWARRAY(char,length);
		if( this->code == 0 )
			return asOUT_OF_MEMORY;
		memcpy((char*)this->code, code, length);
	}
	else
	{
		codeLength = length;
		this->code = const_cast<char*>(code);
		sharedCode = true;
	}

	// Find the positions of each line
	linePositions.PushLast(0);
	for( size_t n = 0; n < length; n++ )
		if( code[n] == '\n' ) linePositions.PushLast(n+1);
	linePositions.PushLast(length);

	return asSUCCESS;
}

void asCScriptCode::ConvertPosToRowCol(size_t pos, int *row, int *col)
{
	if( linePositions.GetLength() == 0 )
	{
		if( row ) *row = lineOffset;
		if( col ) *col = 1;
		return;
	}

	// Do a binary search in the buffer
	int max = (int)linePositions.GetLength() - 1;
	int min = 0;
	int i = max/2;

	for(;;)
	{
		if( linePositions[i] < pos )
		{
			// Have we found the largest number < programPosition?
			if( min == i ) break;

			min = i;
			i = (max + min)/2;
		}
		else if( linePositions[i] > pos )
		{
			// Have we found the smallest number > programPoisition?
			if( max == i ) break;

			max = i;
			i = (max + min)/2;
		}
		else
		{
			// We found the exact position
			break;
		}
	}

	if( row ) *row = i + 1 + lineOffset;
	if( col ) *col = (int)(pos - linePositions[i]) + 1;
}

bool asCScriptCode::TokenEquals(size_t pos, size_t len, const char *str)
{
	if( pos + len > codeLength ) return false;
	if( strncmp(code + pos, str, len) == 0 && strlen(str) == len )
		return true;
	return false;
}

END_AS_NAMESPACE


text:
namespace dragon {

template <class Context> template <typename T>
void CompareOp<Context>::EqualRunWithType() {
    auto* X1data = input(0).template data<T, Context>();
    auto* X2data = input(1).template data<T, Context>();
    auto* Ydata = output(0)->template mutable_data<T, Context>();
    kernel::Equal<T, Context>(output(0)->count(), X1data, X2data, Ydata);
}

template <class Context>
void CompareOp<Context>::RunOnDevice() {
    CHECK_EQ(input(0).count(), input(1).count())
        << "Both conditioned tensors should have same elements.";
    output(0)->ReshapeLike(input(0));

    if (operation == "EQUAL") {
        if (input(0).template IsType<float>()) EqualRunWithType<float>();
        else LOG(FATAL) << "Unsupported input types.";
    }
    else {
        LOG(FATAL) << "Unsupport operation: [" << operation << "].";
    }
}

DEPLOY_CPU(Compare);
#ifdef WITH_CUDA
DEPLOY_CUDA(Compare);
#endif
OPERATOR_SCHEMA(Compare).NumInputs(2).NumOutputs(1);

NO_GRADIENT(Compare);

}    // namespace dragon

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "em5/command/Command.h"

namespace flo11
{
	/**
	*  @brief Let a vehicle move only on specific status ids.
	*  @author Florian 11-47-1
	*/
	class MoveWithStatusCommand : public em5::Command
	{

	public:
		static const uint32 PLUGINABLE_ID;

	public:
		/**
		*  @brief
		*    Constructor
		*/
		explicit MoveWithStatusCommand(qsf::game::CommandManager* commandManager);
		bool checkCallerWithoutPriority(qsf::Entity& caller);

	public:
		virtual bool checkAvailable() override;
		bool checkCaller(qsf::Entity& caller) override;
		virtual bool checkContext(const qsf::game::CommandContext& context) override;;
		virtual void execute(const qsf::game::CommandContext& context) override;

	protected:

	private:
		static const uint32 ACTION_PRIORITY;
		em5::Command* origCommand;

		QSF_CAMP_RTTI()

	};

}

QSF_CAMP_TYPE_NONCOPYABLE(flo11::MoveWithStatusCommand)


text:
	// WARNING! GL is exposed
#endif


text:
package org.apache.beam.runners.spark.io.hadoop;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.fs.Path;

/**
 * Shard name builder.
 */
public final class ShardNameBuilder {

  private ShardNameBuilder() {
  }

  /**
   * Replace occurrences of uppercase letters 'N' with the given {code}shardCount{code},
   * left-padded with zeros if necessary.
   * @see org.apache.beam.sdk.io.ShardNameTemplate
   * @param template the string template containing uppercase letters 'N'
   * @param shardCount the total number of shards
   * @return a string template with 'N' replaced by the shard count
   */
  public static String replaceShardCount(String template, int shardCount) {
    return replaceShardPattern(template, "N+", shardCount);
  }

  /**
   * Replace occurrences of uppercase letters 'S' with the given {code}shardNumber{code},
   * left-padded with zeros if necessary.
   * @see org.apache.beam.sdk.io.ShardNameTemplate
   * @param template the string template containing uppercase letters 'S'
   * @param shardNumber the number of a particular shard
   * @return a string template with 'S' replaced by the shard number
   */
  public static String replaceShardNumber(String template, int shardNumber) {
    return replaceShardPattern(template, "S+", shardNumber);
  }

  private static String replaceShardPattern(String template, String pattern, int n) {
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(template);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      // replace pattern with a String format string:
      // index 1, zero-padding flag (0), width length of matched pattern, decimal conversion
      m.appendReplacement(sb, "%1\\$0" + m.group().length() + "d");
    }
    m.appendTail(sb);
    return String.format(sb.toString(), n);
  }

  /**
   * @param pathPrefix a relative or absolute path
   * @param template a template string
   * @return the output directory for the given prefix, template and suffix
   */
  public static String getOutputDirectory(String pathPrefix, String template) {
    String out = new Path(pathPrefix + template).getParent().toString();
    if (out.isEmpty()) {
      return "./";
    }
    return out;
  }

  /**
   * @param pathPrefix a relative or absolute path
   * @param template a template string
   * @return the prefix of the output filename for the given path prefix and template
   */
  public static String getOutputFilePrefix(String pathPrefix, String template) {
    String name = new Path(pathPrefix + template).getName();
    if (name.endsWith(template)) {
      return name.substring(0, name.length() - template.length());
    } else {
      return "";
    }
  }

  /**
   * @param pathPrefix a relative or absolute path
   * @param template a template string
   * @return the template for the output filename for the given path prefix and
   * template
   */
  public static String getOutputFileTemplate(String pathPrefix, String template) {
    String name = new Path(pathPrefix + template).getName();
    if (name.endsWith(template)) {
      return template;
    } else {
      return name;
    }
  }
}


text:
#ifndef __GST_MSDKVC1DEC_H__
#define __GST_MSDKVC1DEC_H__

#include "gstmsdkdec.h"

G_BEGIN_DECLS

#define GST_TYPE_MSDKVC1DEC \
  (gst_msdkvc1dec_get_type())
#define GST_MSDKVC1DEC(obj) \
  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_MSDKVC1DEC,GstMsdkVC1Dec))
#define GST_MSDKVC1DEC_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_MSDKVC1DEC,GstMsdkVC1DecClass))
#define GST_IS_MSDKVC1DEC(obj) \
  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_MSDKVC1DEC))
#define GST_IS_MSDKVC1DEC_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_MSDKVC1DEC))

typedef struct _GstMsdkVC1Dec GstMsdkVC1Dec;
typedef struct _GstMsdkVC1DecClass GstMsdkVC1DecClass;

struct _GstMsdkVC1Dec
{
  GstMsdkDec base;
  guint output_order;
};

struct _GstMsdkVC1DecClass
{
  GstMsdkDecClass parent_class;
};

GType gst_msdkvc1dec_get_type (void);

G_END_DECLS

#endif /* __GST_MSDKVC1DEC_H__ */


text:
export function UcFirstFilter () {
  return function (input) {
    if (!input) {
      return null
    }
    return input.substring(0, 1).toUpperCase() + input.substring(1)
  }
}


text:
package com.fasterxml.jackson.core.io;

import java.io.*;

import org.junit.Assert;

import com.fasterxml.jackson.core.util.BufferRecycler;

public class UTF8WriterTest
    extends com.fasterxml.jackson.core.BaseTest
{
    public void testSimple() throws Exception
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        UTF8Writer w = new UTF8Writer(_ioContext(), out);

        String str = "AB\u00A0\u1AE9\uFFFC";
        char[] ch = str.toCharArray();

        // Let's write 3 times, using different methods
        w.write(str);

        w.append(ch[0]);
        w.write(ch[1]);
        w.write(ch, 2, 3);
        w.flush();

        w.write(str, 0, str.length());
        w.close();

        // and thus should have 3 times contents
        byte[] data = out.toByteArray();
        assertEquals(3*10, data.length);
        String act = utf8String(out);
        assertEquals(15, act.length());

        assertEquals(3 * str.length(), act.length());
        assertEquals(str+str+str, act);
    }

    public void testSimpleAscii() throws Exception
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        UTF8Writer w = new UTF8Writer(_ioContext(), out);

        String str = "abcdefghijklmnopqrst\u00A0";
        char[] ch = str.toCharArray();

        w.write(ch, 0, ch.length);
        w.flush(); // trigger different code path for close
        w.close();

        byte[] data = out.toByteArray();
        // one 2-byte encoded char
        assertEquals(ch.length+1, data.length);
        String act = utf8String(out);
        assertEquals(str, act);
    }

    public void testFlushAfterClose() throws Exception
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        UTF8Writer w = new UTF8Writer(_ioContext(), out);

        w.write('X');
        char[] ch = { 'Y' };
        w.write(ch);

        w.close();
        assertEquals(2, out.size());

        // and this ought to be fine...
        w.flush();
        // as well as some more...
        w.close();
        w.flush();
    }

    public void testSurrogatesOk() throws Exception
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        UTF8Writer w = new UTF8Writer(_ioContext(), out);

        // First, valid case, char by char
        w.write(0xD83D);
        w.write(0xDE03);
        w.close();
        assertEquals(4, out.size());
        final byte[] EXP_SURROGATES = new byte[] { (byte) 0xF0, (byte) 0x9F,
               (byte) 0x98, (byte) 0x83 };
        Assert.assertArrayEquals(EXP_SURROGATES, out.toByteArray());

        // and then as String
        out = new ByteArrayOutputStream();
        w = new UTF8Writer(_ioContext(), out);
        w.write("\uD83D\uDE03");
        w.close();
        assertEquals(4, out.size());
        Assert.assertArrayEquals(EXP_SURROGATES, out.toByteArray());
    }

    @SuppressWarnings("resource")
    public void testSurrogatesFail() throws Exception
    {
        BufferRecycler rec = new BufferRecycler();
        ByteArrayOutputStream out;
        UTF8Writer w;

        out = new ByteArrayOutputStream();
        w = new UTF8Writer( _ioContext(rec), out);
        try {
            w.write(0xDE03);
            fail("should not pass");
        } catch (IOException e) {
            verifyException(e, "Unmatched second part");
        }

        out = new ByteArrayOutputStream();
        w = new UTF8Writer(_ioContext(rec), out);
        w.write(0xD83D);
        try {
            w.write('a');
            fail("should not pass");
        } catch (IOException e) {
            verifyException(e, "Broken surrogate pair");
        }

        out = new ByteArrayOutputStream();
        w = new UTF8Writer(_ioContext(rec), out);
        try {
            w.write("\uDE03");
            fail("should not pass");
        } catch (IOException e) {
            verifyException(e, "Unmatched second part");
        }

        out = new ByteArrayOutputStream();
        w = new UTF8Writer(_ioContext(rec), out);
        try {
            w.write("\uD83Da");
            fail("should not pass");
        } catch (IOException e) {
            verifyException(e, "Broken surrogate pair");
        }
    }

    private IOContext _ioContext() {
        return _ioContext(new BufferRecycler());
    }

    private IOContext _ioContext(BufferRecycler br) {
        return new IOContext(br, ContentReference.unknown(), false);
    }
}


text:
@interface GMParticipantsTableViewController : UITableViewController <GMParticipantsChildViewController>

@end


text:
package com.swfarm.biz.product.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.srv.ChainManagementService;
import com.swfarm.biz.oa.bo.ImportResultVoucher;
import com.swfarm.biz.oa.bo.ImportResultVoucherItem;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.oa.srv.SysConfigService;
import com.swfarm.biz.product.bo.StockKeepingUnit;
import com.swfarm.pub.framework.Const;
import com.swfarm.pub.utils.SpringUtils;

public class InitAccecitySkuStockThresholdsController extends
		AbstractController {

	Logger logger = Logger
			.getLogger(InitAccecitySkuStockThresholdsController.class);

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
		Map fileMap = multiRequest.getFileMap();
		if (fileMap.values().size() > 0) {
			MultipartFile file = (MultipartFile) fileMap.values().iterator()
					.next();
			String[] originalNames = file.getOriginalFilename().split("\\.");
			// 默认支持Excel 2003
			String type = "xls";
			if (originalNames.length == 2 && StringUtils.isNotEmpty(originalNames[1])) {
				type = originalNames[1];
			}
			List<StockKeepingUnit> stockKeepingUnits = importSkuStockThresholds(file
					.getInputStream(), type);
			if (CollectionUtils.isNotEmpty(stockKeepingUnits)) {
				Map failedSkuInfos = this
						.importSkuStockThresholds(stockKeepingUnits);
				if (failedSkuInfos.size() > 0) {
					Long importResultVoucherId = this.saveImportResultVoucher(
							multiRequest, file.getOriginalFilename(),
							failedSkuInfos);
					return new ModelAndView(
							"redirect:/admin/importresultvoucher.shtml", "id",
							importResultVoucherId);
				}
			}
		}
		return new ModelAndView(
				"redirect:/product/search_stockkeepingunits.shtml");
	}

	private Object getCellValue(Cell cell) {
		Object cellValue = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			cellValue = cell.getRichStringCellValue().getString();
			break;
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				cellValue = cell.getDateCellValue();
			} else {
				NumberFormat numberFormat = NumberFormat.getNumberInstance();
				numberFormat.setMinimumFractionDigits(0);
				numberFormat.setGroupingUsed(false);
				cellValue = numberFormat.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			cellValue = cell.getBooleanCellValue();
			break;
		case Cell.CELL_TYPE_FORMULA:
			cellValue = cell.getCellFormula();
			break;
		default:
			cellValue = null;
		}
		return cellValue;
	}

	private List<StockKeepingUnit> importSkuStockThresholds(InputStream is, String type) {
		try {
			Sheet sheet = null;
			if ("xlsx".equalsIgnoreCase(type)) {
				XSSFWorkbook xb = new XSSFWorkbook(is);
				sheet = xb.getSheetAt(0);
			} else {
				HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
				sheet = wb.getSheetAt(0);
			}
			List<StockKeepingUnit> stockKeepingUnits = new ArrayList<StockKeepingUnit>();
			int rowIndex = 0;
			for (Row row : sheet) {
				if (rowIndex++ > 0) {
					StockKeepingUnit stockKeepingUnit = new StockKeepingUnit();
					// article number
					Cell articleNumberCell = row.getCell(1);
					if (articleNumberCell != null) {
						Object cellValue = getCellValue(articleNumberCell);
						stockKeepingUnit.setArticleNumber(cellValue.toString());
					}
					// average purchase price
					Cell averagePurchasePriceCell = row.getCell(4);
					if (averagePurchasePriceCell != null) {
						Object cellValue = getCellValue(averagePurchasePriceCell);
						if (cellValue != null) {
							stockKeepingUnit
									.setAveragePurchasePrice(new Double(
											cellValue.toString()));
						}
					}
					// stock threshold sale duration
					Cell stockThresholdSaleDurationCell = row.getCell(9);
					if (stockThresholdSaleDurationCell != null) {
						Object cellValue = getCellValue(stockThresholdSaleDurationCell);
						if (cellValue != null) {
							stockKeepingUnit
									.setStockThresholdSaleDuration(new Double(
											cellValue.toString()));
						}
					}
					// suggest quantity sale duration
					Cell suggestQuantitySaleDurationCell = row.getCell(10);
					if (suggestQuantitySaleDurationCell != null) {
						Object cellValue = getCellValue(suggestQuantitySaleDurationCell);
						if (cellValue != null) {
							stockKeepingUnit
									.setSuggestQuantitySaleDuration(new Double(
											cellValue.toString()));
						}
					}
					// average purchase price
					Cell urchasePriceCell = row.getCell(22);
					if (urchasePriceCell != null) {
						Object cellValue = getCellValue(urchasePriceCell);
						if (cellValue != null) {
							stockKeepingUnit.setPurchasePrice(new Double(
									cellValue.toString()));
						}
					}
					// check article number
					if (StringUtils.isNotEmpty(stockKeepingUnit
							.getArticleNumber())) {
						stockKeepingUnits.add(stockKeepingUnit);
					}
				}
			}
			is.close();
			return stockKeepingUnits;
		} catch (FileNotFoundException e) {
			logger.warn(e.getMessage(), e);
		} catch (IOException e) {
			logger.warn(e.getMessage(), e);
		}
		return null;
	}

	private Map importSkuStockThresholds(
			List<StockKeepingUnit> stockKeepingUnits) {
		ChainManagementService chainManagementService = (ChainManagementService) SpringUtils
				.getBean("chainManagementService");
		Map failedSkuInfos = new HashMap();
		chainManagementService.importSkuStockThresholds(stockKeepingUnits);
		return failedSkuInfos;
	}

	private Long saveImportResultVoucher(HttpServletRequest req,
			String importFileName, Map failedSkuInfos) {
		if (failedSkuInfos.size() > 0) {
			ImportResultVoucher importResultVoucher = new ImportResultVoucher();
			User importUser = (User) req.getSession().getAttribute(
					Const.CREDENTIAL);
			importResultVoucher.setImportUserId(importUser.getId());
			importResultVoucher.setImportFileName(importFileName);
			importResultVoucher.setImportType("initstockkeepingunits");
			importResultVoucher.setImportDate(new Date());
			for (Iterator iter = failedSkuInfos.entrySet().iterator(); iter
					.hasNext();) {
				Map.Entry entry = (Map.Entry) iter.next();
				String[] skuInfo = (String[]) entry.getKey();
				String errorMsg = (String) entry.getValue();
				ImportResultVoucherItem importResultVoucherItem = new ImportResultVoucherItem();
				importResultVoucherItem.setImportItemIdentifier(skuInfo[0]);
				importResultVoucherItem
						.setImportResult(ImportResultVoucher.IMPORT_RESULT_FAILED);
				importResultVoucherItem.setImportMessage(errorMsg);
				importResultVoucher
						.addImportResultVoucherItem(importResultVoucherItem);
			}
			SysConfigService sysConfigService = (SysConfigService) SpringUtils
					.getBean("sysConfigService");
			sysConfigService.saveImportResultVoucher(importResultVoucher);
			return importResultVoucher.getId();
		} else {
			return null;
		}
	}
}


text:
#include "MThemeAdaptor.h"

#include <QVariant>
#include <QGuiApplication>
#include <QPixmap>
#include <QDebug>

MThemeAdaptor* MThemeAdaptor::m_this = 0;
MThemeAdaptor::MThemeAdaptor()
{
    m_currentSkinConfigPath = QGuiApplication::applicationDirPath() + "/theme/default/";
    m_currentSkinConfigName = "default.ini";
    m_settings = new QSettings(m_currentSkinConfigPath + m_currentSkinConfigName,
                               QSettings::IniFormat);
}

MThemeAdaptor *MThemeAdaptor::instance()
{
    if(!m_this) m_this = new MThemeAdaptor;

    return m_this;
}

void MThemeAdaptor::addColor(const QString& name, const QColor &c)
{
    QVariant v = c;
    m_settings->setValue(name, v);
}

QColor MThemeAdaptor::color(const QString& name)
{
    return m_settings->value(name).value<QColor>();
}

//void addPixmap(const QString &);
void MThemeAdaptor::addPixmap(const QString& name, const QString &p)
{
    m_settings->setValue(name, p);
}

QPixmap MThemeAdaptor::pixmap(const QString& name)
{
    QString pixPath = m_currentSkinConfigPath + m_settings->value(name).toString();
    return QPixmap(pixPath);
}

QString MThemeAdaptor::currentSkinConfig()
{
    return m_currentSkinConfigPath + m_currentSkinConfigName;
}


text:
NVAR(int, map_dlight_color, "map directional light color", 0, 0x00FFFFFF, 0x00CCCCCC);
NVAR(float, map_dlight_ambient, "map directional light ambient term", 0.0f, 1.0f, 0.50f);
NVAR(float, map_dlight_diffuse, "map directional light diffuse term", 0.0f, 1.0f, 0.75f);
NVAR(float, map_dlight_directionx, "map directional light direction", -1.0f, 1.0f, 1.0f);
NVAR(float, map_dlight_directiony, "map directional light direction", -1.0f, 1.0f, 1.0f);
NVAR(float, map_dlight_directionz, "map directional light direction", -1.0f, 1.0f, 1.0f);

NVAR(float, map_fog_density, "map fog density", 0.0f, 1.0f, 0.5f);
NVAR(int, map_fog_color, "map fog color", 0, 0x00FFFFFF, 0x00CCCCCC);
NVAR(int, map_fog_equation, "map fog equation", 0, 2, 0);
NVAR(float, map_fog_range_start, "map fog range start (for linear only)", 0.0f, 1.0f, 0.0f);
NVAR(float, map_fog_range_end, "map fog range end (for linear only)", 0.0f, 1.0f, 1.0f);

enum {
    kBillboardJumpPad,
    kBillboardLight,
    kBillboardPlayerStart,
    kBillboardTeleport,
    kBillboardCount
};

void world::unload(bool destroy) {
    // game entities
    for (auto &it : m_mapModels)    delete it;
    for (auto &it : m_playerStarts) delete it;
    for (auto &it : m_jumppads)     delete it;

    // rendering state
    for (auto &it : m_billboards)   delete it;
    for (auto &it : m_pointLights)  delete it;
    for (auto &it : m_spotLights)   delete it;
    for (auto &it : m_models)       delete it.second;
    for (auto &it : m_textures)     delete it.second;

    // release memory backing the containers
    if (destroy) {
        m_map.unload();

        // auxiliaries
        m_entities.destroy();
        m_mapModels.destroy();

        // rendering entities
        m_billboards.destroy();
        m_pointLights.destroy();
        m_spotLights.destroy();

        // game entities
        m_playerStarts.destroy();
        m_teleports.destroy();
        m_jumppads.destroy();
    }
}

world::~world() {
    unload(false);
}

bool world::load(const u::vector<unsigned char> &data) {
    // Unload any loaded ones before loading in the new one
    if (isLoaded())
        unload();
    if (!m_map.load(data))
        return false;
    // light billboard
    m_billboards.resize(1);
    m_billboards[0] = new r::billboard;
    if (!m_billboards[0]->load("textures/icons/light"))
        return false;
    return true;
}

bool world::isLoaded() const {
    return m_map.isLoaded();
}

bool world::load(const u::string &file) {
    if (!m_renderer) return false;
    auto read = u::read(neoGamePath() + "maps/" + file, "rb");
    return read && load(*read) && m_renderer->load(&m_map);
}

bool world::upload(const m::perspective &p) {
    if (!m_renderer) return false;
    return m_renderer->upload(p);
}

void world::render(const r::pipeline &pl) {
    if (!m_renderer) return;
    // a new frame reset world state!
    m_renderer->reset();

    float R = ((map_dlight_color >> 16) & 0xFF) / 255.0f;
    float G = ((map_dlight_color >> 8) & 0xFF) / 255.0f;
    float B = (map_dlight_color & 0xFF) / 255.0f;

    r::directionalLight *directionalLight = m_renderer->getDirectionalLight();
    directionalLight->ambient = map_dlight_ambient;
    directionalLight->diffuse = map_dlight_diffuse;
    directionalLight->color = { R, G, B };
    directionalLight->direction = {
        map_dlight_directionx,
        map_dlight_directiony,
        map_dlight_directionz
    };

    R = ((map_fog_color >> 16) & 0xFF) / 255.0f;
    G = ((map_fog_color >> 8) & 0xFF) / 255.0f;
    B = (map_fog_color & 0xFF) / 255.0f;

    r::fog &fog = m_renderer->getFog();
    fog.color = { R, G, B };
    fog.density = map_fog_density;
    fog.start = map_fog_range_start;
    fog.end = map_fog_range_end;
    fog.equation = map_fog_equation;

    // add all light positions into the billboard
    for (auto *it : m_spotLights)
        m_billboards[0]->add(it->position + m::vec3(0.0f, 5.0f, 0.0f));
    for (auto *it : m_pointLights)
        m_billboards[0]->add(it->position + m::vec3(0.0f, 5.0f, 0.0f));

    // add all lights to the renderer (will ignore adding ones which already exist)
    for (auto *it : m_pointLights)
        m_renderer->addPointLight(it);
    for (auto *it : m_spotLights)
        m_renderer->addSpotLight(it);

    // add all billboards
    for (auto *it : m_billboards)
        m_renderer->addBillboard(it);

    // walk the map models and load new ones on demand (renderer will upload them)
    for (const auto &it : m_mapModels) {
        auto find = m_models.find(it->name);
        if (find == m_models.end()) {
            // a new model
            r::model *model = new r::model;
            if (!model->load(m_textures, it->name))
                neoFatal("Failed to load model %s", it->name);
            m_models.insert({ it->name, model });
            m_renderer->addModel(model, it->highlight, it->position, it->scale, it->rotate);
        } else {
            m_renderer->addModel(find->second, it->highlight, it->position, it->scale, it->rotate);
        }
    }

    m_renderer->render(pl);
}

bool world::trace(const world::trace::query &q, world::trace::hit *h, float maxDistance, bool entities, descriptor *ignore) {
    float min = kMaxTraceDistance;
    m::vec3 position;
    descriptor *ent = nullptr;

    // Note: The following tests all entites in the world.
    // Todo: Use a BIH
    if (entities) {
        for (auto &it : m_entities) {
            // Get position and radius of entity
            float radius = 0.0f;
            if (ignore && (ignore->type == it.type && ignore->index == it.index))
                continue;

            switch (it.type) {
            case entity::kMapModel:
                position = m_mapModels[it.index]->position;
                radius = 10.0f; // TODO: calculate sphere radius from bounding box
                break;
            case entity::kPointLight:
                position = m_pointLights[it.index]->position;
                radius = m_pointLights[it.index]->radius;
                break;
            case entity::kSpotLight:
                position = m_spotLights[it.index]->position;
                radius = m_spotLights[it.index]->radius;
                break;
            case entity::kJumppad:
                position = m_jumppads[it.index]->position;
                radius = 8.0f;
                break;
            case entity::kTeleport:
                position = m_teleports[it.index]->position;
                radius = 8.0f;
                break;
            case entity::kPlayerStart:
                position = m_playerStarts[it.index]->position;
                radius = 8.0f;
                break;
            case entity::kDirectionalLight:
                break;
            }

            // Entity too small or too far away
            if (radius <= 0.0f || (position - q.start).abs() > maxDistance)
                continue;

            float fraction = 0.0f;
            if (!m::vec3::raySphereIntersect(q.start, q.direction, position, radius, &fraction))
                continue;

            if (fraction >= 0.0f && fraction < min) {
                min = fraction;
                ent =
            }
        }
    }

    h->ent = nullptr;
    if (ent) {
        h->position = q.start + min*q.direction;
        h->normal = (h->position - position).normalized();
        h->ent = ent;
        h->fraction = m::clamp(min, 0.0f, 1.0f);
    }

    // Check the level geometry now (assuming one is loaded)
    if (!m_map.isLoaded())
        return ent;

    kdSphereTrace sphereTrace;
    sphereTrace.start = q.start;
    sphereTrace.direction = q.direction * maxDistance;
    sphereTrace.radius = q.radius;
    m_map.traceSphere(&sphereTrace);

    // Update the trace data
    h->fraction = m::clamp(sphereTrace.fraction, 0.0f, 1.0f);
    h->normal = sphereTrace.plane.n;

    // Hit level geometry
    if (h->fraction < 1.0f) {
        const m::vec3 position = sphereTrace.start + sphereTrace.fraction * sphereTrace.direction;
        // Hit an entity earlier
        if (ent) {
            //Only when the object is nearer than the level geometry
            if ((h->position - q.start).abs() < (position - q.start).abs())
                return true;
        }
        h->ent = nullptr;
        h->position = position;
        return true;
    }
    return ent;
}

template <typename T>
static inline T *copy(const T &other) {
    T *o = new T;
    *o = other;
    return o;
}

world::descriptor *world::insert(const r::pointLight &it) {
    const size_t index = m_pointLights.size();
    m_pointLights.push_back(copy(it));
    m_entities.push_back({ entity::kPointLight, index, m_entities.size() });
    return &m_entities.back();
}

world::descriptor *world::insert(const r::spotLight &it) {
    const size_t index = m_spotLights.size();
    m_spotLights.push_back(copy(it));
    m_entities.push_back({ entity::kSpotLight, index, m_entities.size() });
    return &m_entities.back();
}

world::descriptor *world::insert(const mapModel &it) {
    const size_t index = m_mapModels.size();
    m_mapModels.push_back(copy(it));
    m_entities.push_back({ entity::kMapModel, index, m_entities.size() });
    return &m_entities.back();
}

world::descriptor *world::insert(const playerStart &it) {
    const size_t index = m_playerStarts.size();
    m_playerStarts.push_back(copy(it));
    m_entities.push_back({ entity::kPlayerStart, index, m_entities.size() });
    return &m_entities.back();
}

world::descriptor *world::insert(const teleport &it) {
    const size_t index = m_teleports.size();
    m_teleports.push_back(copy(it));
    m_entities.push_back({ entity::kTeleport, index, m_entities.size() });
    return &m_entities.back();
}

world::descriptor *world::insert(const jumppad &it) {
    const size_t index = m_jumppads.size();
    m_jumppads.push_back(copy(it));
    m_entities.push_back({ entity::kJumppad, index, m_entities.size() });
    return &m_entities.back();
}

void world::erase(size_t where) {
    auto &it = m_entities[where];
    size_t index = it.index;
    switch (it.type) {
    case entity::kMapModel:
        delete m_mapModels[index];
        m_mapModels.erase(m_mapModels.begin() + index);
        break;
    case entity::kPlayerStart:
        delete m_playerStarts[index];
        m_playerStarts.erase(m_playerStarts.begin() + index);
        break;
    case entity::kPointLight:
        delete m_pointLights[index];
        m_pointLights.erase(m_pointLights.begin() + index);
        break;
    case entity::kSpotLight:
        delete m_spotLights[index];
        m_spotLights.erase(m_spotLights.begin() + index);
        break;
    case entity::kTeleport:
        delete m_teleports[index];
        m_teleports.erase(m_teleports.begin() + index);
        break;
    case entity::kJumppad:
        delete m_jumppads[index];
        m_jumppads.erase(m_jumppads.begin() + index);
        break;
    default:
        return;
    }
    m_entities.erase(m_entities.begin() + where);
    if (m_entities.size() <= where)
        return;

    // Starting from the entity we just removed. Shift the index down
    // for all others into place
    for (size_t i = where; i < m_entities.size(); ++i) {
        m_entities[i].where--;
        if (m_entities[i].type == it.type) {
            m_entities[i].index = m_entities[i].index
                ? m_entities[i].index - 1 : 0;
        }
    }
}

r::directionalLight *world::getDirectionalLight() {
    return m_renderer ? m_renderer->getDirectionalLight() : nullptr;
}

r::spotLight &world::getSpotLight(size_t index) {
    return *m_spotLights[index];
}

r::pointLight &world::getPointLight(size_t index) {
    return *m_pointLights[index];
}

mapModel &world::getMapModel(size_t index) {
    return *m_mapModels[index];
}

playerStart &world::getPlayerStart(size_t index) {
    return *m_playerStarts[index];
}

teleport &world::getTeleport(size_t index) {
    return *m_teleports[index];
}

jumppad &world::getJumppad(size_t index) {
    return *m_jumppads[index];
}

const u::vector<mapModel*> &world::getMapModels() const {
    return m_mapModels;
}

ColorGrader *world::getColorGrader() {
    return m_renderer ? m_renderer->getColorGrader() : nullptr;
}


text:
'use strict';

//dependencies
var path = require('path');
var storage = require(path.join(__dirname, 'lib', 'storage'));

//export gridfs storage
module.exports = storage;


text:
.ui-galleria-content {
    display: flex;
    flex-direction: column;
}

.ui-galleria-item-wrapper {
    display: flex;
    flex-direction: column;
    position: relative;
}

.ui-galleria-item-container {
    position: relative;
    display: flex;
    height: 100%;
}

.ui-galleria-item-nav {
    position: absolute;
    top: 50%;
    margin-top: -.5rem;
    display: inline-flex;
    justify-content: center;
    align-items: center;
}

.ui-galleria-item-prev {
    left: 0;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.ui-galleria-item-next {
    right: 0;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.ui-galleria-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 100%;
}

.ui-galleria-item-nav-onhover .ui-galleria-item-nav {
    pointer-events: none;
    opacity: 0;
    transition: opacity .2s ease-in-out;
}

.ui-galleria-item-nav-onhover .ui-galleria-item-wrapper:hover .ui-galleria-item-nav {
    pointer-events: all;
    opacity: 1;
}

.ui-galleria-item-nav-onhover .ui-galleria-item-wrapper:hover .ui-galleria-item-nav.ui-state-disabled {
    pointer-events: none;
}

.ui-galleria-caption {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
}

/* Thumbnails */
.ui-galleria-thumbnail-wrapper {
    display: flex;
    flex-direction: column;
    overflow: auto;
    flex-shrink: 0;
}

.ui-galleria-thumbnail-prev,
.ui-galleria-thumbnail-next {
    align-self: center;
    flex: 0 0 auto;
    display: flex;
    justify-content: center;
	align-items: center;
}

.ui-galleria-thumbnail-prev span,
.ui-galleria-thumbnail-next span {
    display: flex;
    justify-content: center;
    align-items: center;
}

.ui-galleria-thumbnail-container {
    display: flex;
    flex-direction: row;
}

.ui-galleria-thumbnail-items-container {
    overflow: hidden;
}

.ui-galleria-thumbnail-items {
    display: flex;
}

.ui-galleria-thumbnail-item {
    overflow: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: .5;
    transition: opacity .3s;
}

.ui-galleria-thumbnail-item:hover,
.ui-galleria-thumbnail-item-current {
    opacity: 1;
}

/* Positions */
/* Thumbnails */
.ui-galleria-thumbnails-left .ui-galleria-content,
.ui-galleria-thumbnails-right .ui-galleria-content {
    flex-direction: row;
}

.ui-galleria-thumbnails-left .ui-galleria-item-wrapper,
.ui-galleria-thumbnails-right .ui-galleria-item-wrapper {
    flex-direction: row;
}

.ui-galleria-thumbnails-left .ui-galleria-item-wrapper,
.ui-galleria-thumbnails-top .ui-galleria-item-wrapper {
    order: 2;
}

.ui-galleria-thumbnails-left .ui-galleria-thumbnail-wrapper,
.ui-galleria-thumbnails-top .ui-galleria-thumbnail-wrapper {
    order: 1;
}

.ui-galleria-thumbnails-left .ui-galleria-thumbnail-wrapper,
.ui-galleria-thumbnails-right .ui-galleria-thumbnail-wrapper {
    height: 100%;
}

.ui-galleria-thumbnails-left .ui-galleria-thumbnail-container,
.ui-galleria-thumbnails-right .ui-galleria-thumbnail-container {
    flex-direction: column;
    flex-grow: 1;
}

.ui-galleria-thumbnails-left .ui-galleria-thumbnail-items,
.ui-galleria-thumbnails-right .ui-galleria-thumbnail-items {
    flex-direction: column;
    height: 100%;
}

/* Indicators */
.ui-galleria-indicators {
    display: flex;
    align-items: center;
    justify-content: center;
}

.ui-galleria-indicator > button {
    display: inline-flex;
    align-items: center;
}

.ui-galleria-indicators-left .ui-galleria-item-wrapper,
.ui-galleria-indicators-right .ui-galleria-item-wrapper {
    flex-direction: row;
    align-items: center;
}

.ui-galleria-indicators-left .ui-galleria-item-container,
.ui-galleria-indicators-top .ui-galleria-item-container {
    order: 2;
}

.ui-galleria-indicators-left .ui-galleria-indicators,
.ui-galleria-indicators-top .ui-galleria-indicators {
    order: 1;
}

.ui-galleria-indicators-left .ui-galleria-indicators,
.ui-galleria-indicators-right .ui-galleria-indicators {
    flex-direction: column;
}

.ui-galleria-indicator-onitem .ui-galleria-indicators {
    position: absolute;
    display: flex;
}

.ui-galleria-indicator-onitem.ui-galleria-indicators-top .ui-galleria-indicators {
    top: 0;
    left: 0;
    width: 100%;
    align-items: flex-start;
}

.ui-galleria-indicator-onitem.ui-galleria-indicators-right .ui-galleria-indicators {
    right: 0;
    top: 0;
    height: 100%;
    align-items: flex-end;
}

.ui-galleria-indicator-onitem.ui-galleria-indicators-bottom .ui-galleria-indicators {
    bottom: 0;
    left: 0;
    width: 100%;
    align-items: flex-end;
}

.ui-galleria-indicator-onitem.ui-galleria-indicators-left .ui-galleria-indicators {
    left: 0;
    top: 0;
    height: 100%;
    align-items: flex-start;
}

/* FullScreen */
.ui-galleria-mask {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
}

.ui-galleria-close {
    position: absolute;
    top: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.ui-galleria-mask .ui-galleria-item-nav {
    position: fixed;
    top: 50%;
    margin-top: -.5rem;
}

/* Keyboard Support */
.ui-items-hidden .ui-galleria-thumbnail-item {
    visibility: hidden;
}

.ui-items-hidden .ui-galleria-thumbnail-item.ui-galleria-thumbnail-item-active {
    visibility: visible;
}


text:
package org.apache.jsieve.exception;

/**
 * Class LookupException indicates an exceptional condition encountered while
 * locating a Sieve resource.
 */
@SuppressWarnings("serial")
public class LookupException extends SieveException {

    /**
     * Constructor for LookupException.
     */
    public LookupException() {
        super();
    }

    /**
     * Constructor for LookupException.
     *
     * @param message
     */
    public LookupException(String message) {
        super(message);
    }

    /**
     * Constructor for LookupException.
     *
     * @param message
     * @param cause
     */
    public LookupException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructor for LookupException.
     *
     * @param cause
     */
    public LookupException(Throwable cause) {
        super(cause);
    }

}


text:
class Reports::BaseController < ApplicationController
  before_filter :set_info

  private

  def set_info
    @month = requested_month
    @year = requested_year
    if requested_year && requested_month
      @month_as_date = Date.new(requested_year, requested_month)
    end
    @requested_teams = requested_teams
    @users = requested_users
    @teams = accessible_teams
  end

  def accessible_teams
    Team.accessible_by(current_ability)
  end

  def accessible_users
    User.only_active.accessible_by(current_ability)
  end

  def requested_teams
    # accessible_by filters by id, a subsequent where(id: id) will replace the first one
    # (cf. rails activerecord/lib/active_record/relation/query_methods.rb, line 132)
    return accessible_teams unless params[:team_ids].present?
    accessible_teams.where('id IN (?)', params[:team_ids].map(&:to_i))
  end

  def requested_user
    accessible_users.where('id = ?', params[:user_id]).first unless params[:user_id].blank?
  end

  def requested_month
    params[:month].present? ? params[:month].to_i : nil
  end

  def requested_year
    params[:year].present? ? params[:year].to_i : nil
  end

  def requested_users
    case
    when requested_user
      [requested_user]
    when requested_teams
      accessible_users.in_teams(requested_teams)
    else
      accessible_users
    end
  end
end


text:
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace nFact.SpecFlow
{
    class UnZip
    {
        public static string Exec(string archiveFilenameIn, string outFolder)
        {
            using (FileStream fs = File.OpenRead(archiveFilenameIn))
            {
                string fileName = null;
                var zf = new ZipFile(fs);
                try
                {
                    foreach (ZipEntry zipEntry in zf)
                    {
                        if (!zipEntry.IsFile)
                        {
                            continue;           // Ignore directories
                        }
                        fileName = zipEntry.Name;
                        // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                        // Optionally match entrynames against a selection list here to skip as desired.
                        // The unpacked length is available in the zipEntry.Size property.

                        byte[] buffer = new byte[4096];     // 4K is optimum
                        Stream zipStream = zf.GetInputStream(zipEntry);

                        // Manipulate the output filename here as desired.
                        String fullZipToPath = Path.Combine(outFolder, fileName);
                        string directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                            Directory.CreateDirectory(directoryName);

                        // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                        // of the file, but does not waste memory.
                        // The "using" will close the stream even if an exception occurs.
                        using (FileStream streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                }

                finally
                {
                    if (zf != null)
                    {
                        zf.IsStreamOwner = true;
                        zf.Close(); // Ensure we release resources
                    }
                }
                return fileName;
            }
        }
    }
}


text:
namespace node {
namespace crypto {

inline ClientHelloParser::ClientHelloParser()
    : state_(kEnded),
      onhello_cb_(nullptr),
      onend_cb_(nullptr),
      cb_arg_(nullptr),
      session_size_(0),
      session_id_(nullptr),
      servername_size_(0),
      servername_(nullptr),
      ocsp_request_(0),
      tls_ticket_size_(0),
      tls_ticket_(nullptr) {
  Reset();
}

inline void ClientHelloParser::Reset() {
  frame_len_ = 0;
  body_offset_ = 0;
  extension_offset_ = 0;
  session_size_ = 0;
  session_id_ = nullptr;
  tls_ticket_size_ = -1;
  tls_ticket_ = nullptr;
  servername_size_ = 0;
  servername_ = nullptr;
  ocsp_request_ = 0;
}

inline void ClientHelloParser::Start(ClientHelloParser::OnHelloCb onhello_cb,
                                     ClientHelloParser::OnEndCb onend_cb,
                                     void* onend_arg) {
  if (!IsEnded())
    return;
  Reset();

  CHECK_NE(onhello_cb, nullptr);

  state_ = kWaiting;
  onhello_cb_ = onhello_cb;
  onend_cb_ = onend_cb;
  cb_arg_ = onend_arg;
}

inline void ClientHelloParser::End() {
  if (state_ == kEnded)
    return;
  state_ = kEnded;
  if (onend_cb_ != nullptr) {
    onend_cb_(cb_arg_);
    onend_cb_ = nullptr;
  }
}

inline bool ClientHelloParser::IsEnded() const {
  return state_ == kEnded;
}

inline bool ClientHelloParser::IsPaused() const {
  return state_ == kPaused;
}

}  // namespace crypto
}  // namespace node

#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#endif  // SRC_NODE_CRYPTO_CLIENTHELLO_INL_H_


text:
package org.carbon.copy.data.structures;

import co.paralleluniverse.galaxy.Store;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

import static org.carbon.copy.data.structures.DataStructure.TIMEOUT_SECS;

/**
 * Galaxy only provides inter-node synchronization. The application (us) needs to implement intra-node synchronization.
 * Today we create a new Txn object for each transaction we want to open. We map from data structures to byte[] ids
 * and the transaction itself only thinks in terms of ids. It pins, releases, and rolls back those ids instead of data structures.
 * I got around to implement a bookkeeping structure that let's us figure out whether a block has been locked locally already.
 * This way we're a) able to run multiple independent transactions concurrently and b) introduce a blocking call only when
 * a transaction wants a block that has been locked already.
 */
class TxnManagerImpl implements TxnManager {
    private static Logger logger = LoggerFactory.getLogger(TxnManagerImpl.class);
    // this contains the node-wide set of blocks that are engaged in a transaction
    // if a transaction tries to pin a block that is already in this set,
    // the transaction steps on somebody else's foot
    private static final ConcurrentHashMap<Long, LocalLock> blocksToLocalLocks = new ConcurrentHashMap<>(16, 0.75f, 8);

    private final Store store;

    @Inject
    TxnManagerImpl(Store store) {
        this.store = store;
    }

    public void doTransactionally(Consumer<Txn> lambda) throws IOException {
        Txn txn = beginTransaction();
        try {
            lambda.accept(txn);
            txn.commit();
        } catch (Exception xcp) {
            txn.rollback();
            throw new IOException(xcp);
        }
    }

    public Txn beginTransaction() {
        return new Txn(store, this);
    }

    // this is a blocking call!
    // getting a lock on a block in carbon-copy is a two-phase affair
    // there is a local lock that coordinates multiple threads inside the same node / JVM
    // and then there's the remote lock that is a galaxy feature ensuring that only one node in the cluster
    // has ownership of the block and is allowed to change it
    void lock(long blockId) {
        LocalLock ll = tryGetLocalLock(blockId);
        Future<byte[]> remoteFuture = tryGetRemoteLock(blockId);

        try {
            if (ll == null || ll.amIHoldingTheLock()) {
                // there was no previous local lock that means we have it
                remoteFuture.get(TIMEOUT_SECS, TimeUnit.SECONDS);
            } else {
                // somebody else is holding a lock on this block
                // that means we play the waiting game
                Future<Void> f = new LocalAndRemoteLockFuture(remoteFuture, ll);
                waitFor(f);
                // recursive call into myself in order to attempt
                lock(blockId);
            }
        } catch (InterruptedException | ExecutionException | TimeoutException xcp) {
            throw new RuntimeException(xcp);
        }
    }

    // visible for testing
    protected void waitFor(Future f) throws InterruptedException, ExecutionException, TimeoutException {
        f.get(TIMEOUT_SECS, TimeUnit.SECONDS);
    }

    private LocalLock tryGetLocalLock(long blockId) {
        return blocksToLocalLocks.putIfAbsent(blockId, new LocalLock(blockId));
    }

    private Future<byte[]> tryGetRemoteLock(long blockId) {
        return store.getxAsync(blockId, null);
    }

    // this method releases the local lock a thread has
    // that will enable other threads to grab the local lock and more changes to the
    // block that was previously locked
    // this implementation gives preference to other threads on this node who want to make updates
    // meaning before releasing the remote lock as well, we check whether other threads want the lock as well
    // if so, we pass on the local lock while retaining the remote lock
    void release(long blockId) {
        // release local lock first
        LocalLock ll = releaseLocalLock(blockId);
        // find out whether there's a waitlist for this block
        // we might piggy back on this remote lock while we have it
        if (!ll.hasThreadsWaiting()) {
            // release remote lock
            releaseRemoteLock(blockId);
        }
    }

    private LocalLock releaseLocalLock(long blockId) {
        LocalLock ll = blocksToLocalLocks.remove(blockId);
        ll.release();
        return ll;
    }

    private void releaseRemoteLock(long blockId) {
        store.release(blockId);
    }

    /**
     * Convenience class around a ReentrantLock. It practically makes the lock feel like a future.
     */
    private static class LocalLock {
        private final ReentrantLock innerLock = new ReentrantLock();
        private final long blockId;

        LocalLock(long blockId) {
            this.blockId = blockId;
            innerLock.lock();
        }

        boolean amIHoldingTheLock() {
            return innerLock.isHeldByCurrentThread();
        }

        boolean hasThreadsWaiting() {
            return innerLock.hasQueuedThreads();
        }

        String getCurrentLockOwner() {
            return blockId + " - " + innerLock.toString() + " - " + innerLock.getHoldCount();
        }

        void lock(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            boolean haveLock = innerLock.tryLock(timeout, unit);
            // try to behave like a future
            if (!haveLock) {
                throw new TimeoutException("Couldn't acquire lock from " + getCurrentLockOwner());
            }
            if (innerLock.getHoldCount() > 1) {
                logger.warn("LocalLock {} is being acquired more than once", getCurrentLockOwner());
            }
        }

        void lock() throws InterruptedException, ExecutionException {
            innerLock.lockInterruptibly();
        }

        void release() {
            if (amIHoldingTheLock()) {
                innerLock.unlock();
                if (innerLock.getHoldCount() > 0) {
                    logger.warn("LocalLock {} is still being held more than once", getCurrentLockOwner());
                }
            } else {
                throw new IllegalStateException("Can't release a lock you don't own: " + getCurrentLockOwner());
            }
        }
    }

    /**
     * A convenience future that warps around a local lock and a remote lock.
     * It hugs both the remote future and the local lock and tries to provide an easier to use interface.
     * Looks like a future, behaves like a future, is a future.
     */
    private static class LocalAndRemoteLockFuture implements Future<Void> {
        private final Future<byte[]> remoteLockingFuture;
        private final LocalLock localLock;

        LocalAndRemoteLockFuture(Future<byte[]> remoteLockingFuture, LocalLock localLock) {
            this.remoteLockingFuture = remoteLockingFuture;
            this.localLock = localLock;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return remoteLockingFuture.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return remoteLockingFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return remoteLockingFuture.isDone();
        }

        @Override
        public Void get() throws InterruptedException, ExecutionException {
            localLock.lock();
            remoteLockingFuture.get();
            return null;
        }

        @Override
        public Void get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            long before = System.currentTimeMillis();
            localLock.lock(timeout, unit);

            // lots of math in order to find out how much time is still left on the timeout
            // however we want to at least wait five more milliseconds though
            // maybe the remote future finished already and we can proceed and salvage the transaction
            long stillToWait = Math.max(
                    unit.toMillis(timeout) - (System.currentTimeMillis() - before),
                    5
            );

            remoteLockingFuture.get(stillToWait, TimeUnit.MILLISECONDS);
            return null;
        }
    }
}


text:
import {Container, SpecificContainer, UniversalContainer} from "../Container";
import {RowContainer} from "../universal/Row";
import {Street, Shape, House, Highway} from "../../components/Shapes";
import {PlatformContainer} from "../universal/Platform";

interface HouseSegmentContainer {
    segments: string[];
    segmented: { [index: string]: Shape[] };
    left: { [index: string]: UniversalContainer };
    right: { [index: string]: UniversalContainer };
}

interface BranchSegmentContainer {
    segments: string[];
    segmented: { [index: string]: Shape[] };
    left: { [index: string]: SpecificContainer };
    right: { [index: string]: SpecificContainer };
}

type distributionFunction = (s: Shape) => number;
type distributionString = "left" | "right" | "default";
type distributionMethod = distributionString | distributionFunction;

type containerFunction = (key: string, mirror: boolean) => UniversalContainer;

export interface StreetContainerOptions extends AttributeContainer {
    "spacer.initial"?: number;
    "spacer.branches"?: number;
    "spacer.terranullius"?: number;
    "spacer.conclusive"?: number;

    "road.trim"?: boolean;

    "house.container"?: containerFunction;
    "house.distribution"?: distributionMethod;
    "house.segmentation"?: (s: Shape) => string;
    "house.segmentorder"?: (a: string, b: string) => number;
    "house.platforms"?: null | ShapeAttributes;
    "house.path"?: null | ShapeAttributes;

    "branch.container"?: containerFunction;
    "branch.distribution"?: distributionMethod;
    "branch.segmentation"?: (s: Shape) => string;
    "branch.segmentorder"?: (a: string, b: string) => number;
}

/**
 * Create an Evostreet Layout City Container
 */
export class StreetContainer extends SpecificContainer {
    private leftBranchSpacer: number;
    private rightBranchSpacer: number;
    private road: Street | null;
    private houses: HouseSegmentContainer;
    private branches: BranchSegmentContainer;

    constructor(key: string, options: StreetContainerOptions = {}) {
        super(key, options);

        const natSort = (a: string, b: string) => a === b ? 0 : (a > b ? 1 : -1);
        const defaults: StreetContainerOptions = {
            "spacer.initial": 20,
            "spacer.branches": 15,
            "spacer.terranullius": 20,
            "spacer.conclusive": 0,

            "house.container": (s: string, m: boolean) => new RowContainer(s, m),
            "house.distribution": "default",
            "house.segmentation": (s: Shape) => "default",
            "house.segmentorder": natSort,
            "house.platforms": null,
            "house.path": null,

            "branch.container": (s: string, m: boolean) => new RowContainer(s, m),
            "branch.distribution": "default",
            "branch.segmentation": (s: Shape) => "default",
            "branch.segmentorder": natSort
        };
        this.setDefaults(defaults);

        this.leftBranchSpacer = 0;
        this.rightBranchSpacer = 0;

        this.road = null;

        this.houses = {
            segments: [],
            segmented: {},
            left: {},
            right: {}
        };

        this.branches = {
            segments: [],
            segmented: {},
            left: {},
            right: {}
        };
    }

    public setBranchSpacingLeft(spacing: number): void {
        this.leftBranchSpacer = spacing;
    }

    public setBranchSpacingRight(spacing: number): void {
        this.rightBranchSpacer = spacing;
    }

    public add(shape: Shape) {
        if (shape instanceof StreetContainer) {
            this.addBranch(shape);
        } else if (shape instanceof House) {
            this.addHouse(shape);
        } else if (shape instanceof Street) {
            if (this.road !== null) {
                throw new Error("StreetContainer can only have one road.");
            }
            this.road = shape;
        } else {
            throw new Error("Unknown Shape-Type: " + shape);
        }
    }

    public finalize(): void {
        if (this.road === null) {
            throw new Error("StreetContainer requires a primary street");
        }
        const mainRoad = this.road;
        let branchCount = 0;
        let houseCount = 0;

        this.prepareSegments();
        this.addHousesToStructure();
        this.addBranchesToStructure();
        this.putHousesOnPlatforms();
        this.updateDimensions();

        let containersBottom = this.getOption("spacer.initial") - (this.dimensions.width / 2);
        const halfTheRoadLength = (mainRoad.displayDimensions.length / 2);
        const middleOfTheRoad = (this.dimensions.length / 2) - this.getRightBlockLength() - halfTheRoadLength;

        mainRoad.dimensions.width = this.dimensions.width;
        mainRoad.position.x = middleOfTheRoad;
        mainRoad.position.y = 0;
        super.add(mainRoad);

        // Place Branches, Segment by Segment
        for (const bSeg of this.branches.segments) {
            const bKey = String(bSeg);
            const leftBranch = this.branches.left[bKey];
            const rightBranch = this.branches.right[bKey];

            if (leftBranch.size) {
                leftBranch.position.x = middleOfTheRoad - halfTheRoadLength - leftBranch.centroid.x;
                leftBranch.position.y = containersBottom + leftBranch.centroid.y;
                super.add(leftBranch);
                branchCount++;
            }

            if (rightBranch.size) {
                rightBranch.position.x = middleOfTheRoad + halfTheRoadLength + rightBranch.centroid.x;
                rightBranch.position.y = containersBottom + rightBranch.centroid.y;
                super.add(rightBranch);
                branchCount++;
            }

            containersBottom += Math.max(leftBranch.displayDimensions.width, rightBranch.displayDimensions.width);
        }

        // Add Terra Nullius (if required)
        if (this.branches.segments.length) {
            containersBottom += this.getOption("spacer.terranullius");
        }

        // Place Houses, Segment by Segment
        for (const hSeg of this.houses.segments) {
            const hKey = String(hSeg);
            const leftHouses = this.houses.left[hKey];
            const rightHouses = this.houses.right[hKey];

            if (leftHouses.size) {
                leftHouses.position.x = middleOfTheRoad - halfTheRoadLength - leftHouses.centroid.x;
                leftHouses.position.y = containersBottom + leftHouses.centroid.y;
                super.add(leftHouses);
                houseCount++;
            }

            if (rightHouses.size) {
                rightHouses.position.x = middleOfTheRoad + halfTheRoadLength + rightHouses.centroid.x;
                rightHouses.position.y = containersBottom + rightHouses.centroid.y;
                super.add(rightHouses);
                houseCount++;
            }

            containersBottom += Math.max(leftHouses.displayDimensions.width, rightHouses.displayDimensions.width);
        }

        if (this.getOption("road.trim") && !houseCount) {
            this.trimMainRoad(mainRoad);
        }
    }

    public getRoad(): Street | null {
        return this.road;
    }

    private addHouse(shape: House) {
        const segmentFunc = this.getOption("house.segmentation") as (s: Shape) => string;
        const segmentIndex = String(segmentFunc(shape));

        if (this.houses.segments.indexOf(segmentIndex) < 0) {
            const houseContainer: containerFunction = this.getOption("house.container");
            this.houses.segments.push(segmentIndex);
            this.houses.segmented[segmentIndex] = [];
            this.houses.left[segmentIndex]  = houseContainer(this.key + "_" + segmentIndex + "_hl", false);
            this.houses.right[segmentIndex] = houseContainer(this.key + "_" + segmentIndex + "_hr", true);
            this.houses.left[segmentIndex].rotate(-90);
            this.houses.right[segmentIndex].rotate(-90);
        }

        this.houses.segmented[segmentIndex].push(shape);
    }

    private addBranch(shape: StreetContainer): void {
        const segmentFunc = this.getOption("branch.segmentation") as (s: Shape) => string;
        const segmentIndex = String(segmentFunc(shape));

        if (this.branches.segments.indexOf(segmentIndex) < 0) {
            const branchContainer: containerFunction = this.getOption("branch.container");
            this.branches.segments.push(segmentIndex);
            this.branches.segmented[segmentIndex] = [];
            this.branches.left[segmentIndex]  = branchContainer(this.key + "_" + segmentIndex + "_bl", false);
            this.branches.right[segmentIndex] = branchContainer(this.key + "_" + segmentIndex + "_br", true);
            this.branches.left[segmentIndex].rotate(-90);
            this.branches.right[segmentIndex].rotate(-90);
        }

        this.branches.segmented[segmentIndex].push(shape);
    }

    private updateDimensions(): void {
        this.dimensions.length = this.getContainerLength();
        this.dimensions.width  = this.getContainerWidth() + this.getOption("spacer.conclusive");
    }

    private putHousesOnPlatforms(): void {
        const platformOptions = this.getOption("house.platforms");
        const pathOptions = this.getOption("house.path");
        if (!platformOptions) {
            return;
        }

        const wrap = (c: UniversalContainer): UniversalContainer => {
            if (!c.size) {
                return c;
            }

            const hContainer = new PlatformContainer(this.key, c.isMirrored);
            hContainer.setOptions(platformOptions);
            hContainer.add(c);

            if (pathOptions) {
                const path = new Street(this.key);
                path.updateAttributes(pathOptions);
                hContainer.add(path);
            }

            return hContainer;
        };

        for (const hSeg of this.houses.segments) {
            const hKey = String(hSeg);
            this.houses.left[hKey] = wrap(this.houses.left[hKey]);
            this.houses.right[hKey] = wrap(this.houses.right[hKey]);
        }

        return;
    }

    private prepareSegments(): void {
        const houseOrder = this.getOption("house.segmentorder");
        const branchOrder = this.getOption("branch.segmentorder");

        this.houses.segments.sort(houseOrder);
        this.branches.segments.sort(branchOrder);
    }

    private addHousesToStructure(): void {
        for (const segment of this.houses.segments) {
            const key = String(segment);

            this.distributeShapes(
                this.houses.segmented[key],
                this.getOption("house.distribution"),
                this.houses.left[key],
                this.houses.right[key]
            );
        }
    }

    private addBranchesToStructure(): void {
        const branchSpacer: number = this.getOption("spacer.branches");
        let initialLeft = true;
        let initialRight = true;

        const addSpacerLeft = (s: StreetContainer): void => {
            if (initialLeft) {
                initialLeft = false;
            } else {
                s.setBranchSpacingLeft(branchSpacer);
            }
        };

        const addSpacerRight = (s: StreetContainer): void => {
            if (initialRight) {
                initialRight = false;
            } else {
                s.setBranchSpacingRight(branchSpacer);
            }
        };

        for (const segment of this.branches.segments) {
            const key = String(segment);

            this.distributeShapes(
                this.branches.segmented[key],
                this.getOption("branch.distribution"),
                this.branches.left[key],
                this.branches.right[key]
            );

            this.branches.left[key].shapes.forEach(addSpacerLeft);
            this.branches.right[key].shapes.forEach(addSpacerRight);
        }
    }

    private distributeShapes(shapes: Shape[], method: distributionMethod, left: Container, right: Container): void {
        if (typeof method === "string") {
            if (method === "left") {
                this.distributeShapesToContainer(shapes, left);
            } else if (method === "right") {
                this.distributeShapesToContainer(shapes, right);
            } else {
                this.distributeShapesInDefaultOrder(shapes, left, right);
            }
        } else {
            this.distributeShapesEquallyByAttribute(shapes, method, left, right);
        }
    }

    private distributeShapesToContainer(shapes: Shape[], container: Container): void {
        for (const s of shapes) {
            container.add(s);
        }
    }

    private distributeShapesInDefaultOrder(shapes: Shape[], left: Container, right: Container): void {
        for (let i: number = 0; i < shapes.length; i++) {
            if (shapes.hasOwnProperty(i)) {
                const c = (i % 2) ? left : right;
                c.add(shapes[i]);
            }
        }
    }

    private distributeShapesEquallyByAttribute(
        shapes: Shape[],
        attr: distributionFunction,
        left: Container,
        right: Container
    ): void {
        shapes.sort((a: Shape, b: Shape) => attr(b) - attr(a));
        let diff = 0;
        for (const s of shapes) {
            if (diff <= 0) {
                left.add(s);
                diff += attr(s);
            } else {
                right.add(s);
                diff -= attr(s);
            }
        }
    }

    private getContainerWidth(): number {
        const houseWidth = this.getHousesBlockTotalWidth();
        const branchWidth = this.getBranchesBlockTotalWidth();
        const containerMargin = (branchWidth && houseWidth) ? this.getOption("spacer.terranullius") : 0;
        return houseWidth + branchWidth + this.getOption("spacer.initial") + containerMargin;
    }

    private getHousesBlockTotalWidth(): number {
        let maxLeftHouses = 0;
        let maxRightHouses = 0;
        let tmp: number;

        for (const l in this.houses.left) {
            if (!this.houses.left.hasOwnProperty(l)) {
                continue;
            }

            tmp = this.houses.left[l].displayDimensions.width;
            if (maxLeftHouses < tmp) {
                maxLeftHouses = tmp;
            }
        }

        for (const r in this.houses.right) {
            if (!this.houses.right.hasOwnProperty(r)) {
                continue;
            }

            tmp = this.houses.right[r].displayDimensions.width;
            if (maxRightHouses < tmp) {
                maxRightHouses = tmp;
            }
        }

        return Math.max(maxLeftHouses, maxRightHouses);
    }

    private getBranchesBlockTotalWidth(): number {
        let maxLeftBranches = 0;
        let maxRightBranches = 0;
        let tmp: number;

        for (const l in this.branches.left) {
            if (!this.branches.left.hasOwnProperty(l)) {
                continue;
            }

            tmp = this.branches.left[l].displayDimensions.width;
            if (maxLeftBranches < tmp) {
                maxLeftBranches = tmp;
            }
        }

        for (const r in this.branches.right) {
            if (!this.branches.right.hasOwnProperty(r)) {
                continue;
            }

            tmp = this.branches.right[r].displayDimensions.width;
            if (maxRightBranches < tmp) {
                maxRightBranches = tmp;
            }
        }

        return Math.max(maxLeftBranches, maxRightBranches);
    }

    private getContainerLength(): number {
        const leftLength  = this.getLeftBlockLength();
        const rightLength = this.getRightBlockLength();
        const road = this.road as Street;

        return leftLength + road.displayDimensions.length + rightLength;
    }

    private getLeftBlockLength(): number {
        let maxLeftHouses = 0;
        let maxLeftBranches = 0;
        let tmp: number;

        for (const h in this.houses.left) {
            if (!this.houses.left.hasOwnProperty(h)) {
                continue;
            }

            tmp = this.houses.left[h].displayDimensions.length;
            if (maxLeftHouses < tmp) {
                maxLeftHouses = tmp;
            }
        }

        for (const b in this.branches.left) {
            if (!this.branches.left.hasOwnProperty(b)) {
                continue;
            }

            tmp = this.branches.left[b].displayDimensions.length;
            if (maxLeftBranches < tmp) {
                maxLeftBranches = tmp;
            }
        }

        return Math.max(maxLeftHouses, maxLeftBranches) + this.leftBranchSpacer;
    }

    private getRightBlockLength(): number {
        let maxRightHouses = 0;
        let maxRightBranches = 0;
        let tmp: number;

        for (const h in this.houses.right) {
            if (!this.houses.right.hasOwnProperty(h)) {
                continue;
            }

            tmp = this.houses.right[h].displayDimensions.length;
            if (maxRightHouses < tmp) {
                maxRightHouses = tmp;
            }
        }

        for (const b in this.branches.right) {
            if (!this.branches.right.hasOwnProperty(b)) {
                continue;
            }

            tmp = this.branches.right[b].displayDimensions.length;
            if (maxRightBranches < tmp) {
                maxRightBranches = tmp;
            }
        }

        return Math.max(maxRightHouses, maxRightBranches) + this.rightBranchSpacer;
    }

    private trimMainRoad(mainRoad: Street): void {
        let furthestStreetPosition = -Infinity;
        const xPos = this.dimensions.width / 2;
        for (const s of this.shapes) {
            if (!(s instanceof UniversalContainer)) {
                continue;
            }

            const containerPos = s.rotation ? s.position.y : -s.position.y;
            furthestStreetPosition = (s as UniversalContainer)
                .shapes
                .reduce(
                    (carry: number, shape: Shape) => {
                        const roadBlock = shape as StreetContainer;
                        const road: Street = roadBlock.getRoad() as Street;
                        if (!road) {
                            return carry;
                        }

                        const roadsEnd = roadBlock.rotation ? -road.position.x : road.position.x;
                        const roadWidth = (road.dimensions.length / 2);

                        return Math.max(
                            containerPos + roadBlock.position.x + roadsEnd + roadWidth,
                            carry
                        );
                    },
                    furthestStreetPosition
                );
        }

        furthestStreetPosition = this.dimensions.width - furthestStreetPosition - xPos;

        if (mainRoad instanceof Highway) {
            furthestStreetPosition -= this.getOption("spacer.initial") * .5;
        }

        if (0 < furthestStreetPosition && furthestStreetPosition < mainRoad.dimensions.width) {
            mainRoad.dimensions.width -= furthestStreetPosition;
            mainRoad.position.y -= (furthestStreetPosition / 2);
        }
    }
}


text:
// AjaxReload
function ajaxReload(url){
	$.ajax({
		url:url,
		async:false,
		success:function(data){
			// do nothings
		}
	});
	window.location.reload();
	return false;
}

// base_web.js

/**
 * mabetle javascript lib
 */
function addBookmark(title,url) {
	try{
		window.external.AddFavorite( url, title);
	}catch (e){
		try{
			window.sidebar.addPanel(title, url,"");
		}catch(e2){
			alert("加入收藏失败,请使用Ctrl+D进行添加!");
		}
	}
}
function setHomepage(url){
	if (document.all){
		document.body.style.behavior  = 'url(#default#homepage)' ;
		document.body.setHomePage(url);
	}	else if  (window.sidebar)	{
		if (window.netscape)		{
			try {
				netscape.security.PrivilegeManager.enablePrivilege( " UniversalXPConnect " );
			}catch (e) {
				alert( " 该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true " );
			}
		}
		var prefs  =  Components.classes[ ' @mozilla.org/preferences-service;1 ' ].getService(Components.interfaces.nsIPrefBranch);
		prefs.setCharPref( ' browser.startup.homepage ' ,  url );
	}
}

// calc.js

function add(a,b){
	return a + b;
}

// checkboxAll set checkbox checked.
// target: checkbox name
// b: true or false
function checkboxAll(target, b){
	var checkboxes = document.getElementsByName(target);
	for (var i=0; i<checkboxes.length; i++)  {
		checkboxes[i].checked = b;
	}
}

// toggleCheckbox toggle checkbox
// source: from checkbox
// target: checkbox name
function toggleCheckbox(source,target){
	var d = document,
	items=d.getElementsByName(target),
	len = items.length;
	for(var i=0;i<len;i++){
		items[i].checked=source.checked;
	}
}

// toggleCheckboxByClass
function toggleCheckboxClass(source,className){
	var d = document,
	items=d.getElementsByClass(className),
	len = items.length;
	for(var i=0;i<len;i++){
		items[i].checked=source.checked;
	}
}

// reverseCheckbox reverse checkbox
// target: checkbox name
function reverseCheckbox(target){
	var checkboxes = document.getElementsByName(target);
	for (var i = 0; i < checkboxes.length ;i++) {
		var b = checkboxes[i].checked;
		checkboxes[i].checked = !b;
	}
}

//
// define in package.json
//

// one json data keys
function jsonKeys(data){
	var cols = [];
	for (var key in data) {
		cols.push(key);
	}
	return cols;
}

function isInArray(col, cols){
	if (cols === "") {
		return false;
	}
	if (cols.length === 0) {
		return false;
	}
	for (var i = 0, len = cols.length; i < len; i++) {
		if (col === cols[i]){
			return true;
		}
	}
	return false;
}

function isNotInArraay(col,cols){
	return !isInArray(col,cols)
}

// get used columns
// cols: all cols
// include: include cols, comma seperate string
// exclude: exclude cols, comma seperate string
function getUsedCols(cols,include,exclude){
	var result = [];
	var includeArray = include.split(",");
	var excludeArray = exclude.split(",");

	//console.log("include array:", includeArray)

	if ((includeArray.length === 0) || (includeArray.length === 1 && includeArray[0] === "")) {
		includeArray = cols;
		//console.log("put cols to include, include array:", includeArray);
	}

	for (var i = 0, len = cols.length; i < len; i++) {
		var col = cols[i];
		// skip some special columns
		if (col === "Id") {
			continue;
		}
		if (isInArray(col,includeArray) && isNotInArraay(col,excludeArray)){
			result.push(col);
		}
	}
	return result;
}

function isHasKey(key,options) {
	for (col in options){
		if (col === key ) {
			return true;
		}
	}
	return false;
}

function getExclude(options) {
	var exclude = getOption("exclude",options);
	if (exclude === ""){
		return "Id"
	}
	return exclude
}

function getOption(name,options) {
	for (var key in options){
		if (name === key) {
			return options[key];
		}
	}
	return "";
}

// jsonToTable
function jsonToTable(rows,options){
	if (rows.length === 0) {
		return "No results.";
	}

	var table="

";

	var include = getOption("include",options);
	var exclude = getOption("exclude",options);

	var allCols = jsonKeys(rows[0]);
	var cols = getUsedCols(allCols,include,exclude);

	// add head
	table = table + colsHead(cols);
	table = table + "

";
	table = table + "
";
	//add body
	table = table + jsonTableBody(rows,cols);
	table= table + "

";
	return table;
}

function colsHead(cols){
	var table = "";
	for (var i = 0; i < cols.length; i++) {
		table = table + "" + cols[i] + "	";
	}
	return table;
}

function jsonTableBody(rows,cols){
	var table = "";
	for (var row = 0; row < rows.length; row++) {
		table = table + "
"
		for (var col = 0; col < cols.length; col++) {
			var key = cols[col];
			table = table + "" + rows[row][key] + "	";
		}
		table = table + "
"
	}
	return table;
}

function parseJsonTable(url){
	$.getJSON(url, function(data) {
		var table = jsonToTable(data);
		$("#zone").html(table);
		zoneDialog();
	});
}

// switchLangEn
function switchLangEn(){
	var url = "/Lang/ChangeLang?lang=en-US";
	AjaxReload(url);
	return false;
}

// switchLangZh
function switchLangZh(){
	var url = "/Lang/ChangeLang?lang=zh-CN";
	AjaxReload(url);
	return false;
}

// Nav
$(document).ready(function(){
	$(".nav").accessibleDropDown();
});

$.fn.accessibleDropDown = function (){
	var el = $(this);
	/* Setup dropdown menus for IE 6 */
	$("li", el).mouseover(function() {
		$(this).addClass("hover");
	}).mouseout(function() {
		$(this).removeClass("hover");
	});

	/* Make dropdown menus keyboard accessible */
	$("a", el).focus(function() {
		$(this).parents("li").addClass("hover");
	}).blur(function() {
		$(this).parents("li").removeClass("hover");
	});
};

document.getElementByClass = function (classname) {
	var elements = [];
	var alltags = document.all ? document.all : document.getElementsByTagName("*");

	for (var i=0; i<alltags.length; i++) {
		var classNames = alltags[i].className.split(" ");
		if (classNames.contain(classname))
			elements[elements.length] = alltags[i];
	}
	return elements;
}

function tableToJson(table) {
	var data = [];
	// first row needs to be headers
	var headers = [];
	for (var i=0; i<table.rows[0].cells.length; i++) {
		headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
	}
	// go through cells
	for (var i=1; i<table.rows.length; i++) {
		var tableRow = table.rows[i];
		var rowData = {};
		for (var j=0; j<tableRow.cells.length; j++) {
			rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
		}
		data.push(rowData);
	}
	return data;
}

// zoneDialog show zone in dialog mode
function zoneDialog(){
	$("#zone").dialog({
		minWidth:800,
		width:'auto',
		colseOnEscape:true,
		modal: true,
		buttons: {
			关闭: function() {
				$( this).dialog( "close" );
			}
		}
	});
	// update zone height to adapt content.
	$("#zone").css({
		width: 'auto',
		minWidth:800,
		height: 'auto'
	});

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ExportableFileTemplateSettings">
    <includes_templates>
      <template name="C File Header.h" reformat="true" live-template-enabled="false" enabled="false" />
      <template name="File Header.java" reformat="true" live-template-enabled="true" enabled="true" />
    </includes_templates>
  </component>
</project>


text:
google-plugins
================

See the [component page](http://scarygami.github.io/google-plugins) for more information.


text:
import React from 'react'

export const SelectedKey = () => {
  return

KEY

    <button>C Major</button>

}

export default SelectedKey


text:
export const BEFORE = "before"
export const PRIMARY = "primary"
export const AFTER = "after"


text:
'use strict';

function Enum() {
  var _this = this;

  if (!(this instanceof Enum)) return new (Function.prototype.bind.apply(Enum, [null].concat(Array.prototype.slice.call(arguments))))();
  Array.from(arguments).forEach(function (arg) {
    _this[arg] = Symbol(arg);
  });
}

module.exports = Enum;


text:
\documentclass{article}

\usepackage{lmodern}
\usepackage{my-package}

\begin{document}

\end{document}


text:
<?php
/*
 * (c) Pekin Denis <dpekin@armd.ru>
 */

namespace Armd\DCXBundle\Exception;

/**
 * Thrown whenever a DCXParser process fails.
 */
class ParserException extends RuntimeException
{
    protected $message;

    public function __construct($xml){
        $errors = libxml_get_errors();
        foreach ($errors as $error) {
            $this->message .= $this->xml_error($error, $xml);
        }
        libxml_clear_errors();
        parent::__construct($this->message);
    }

    private function xml_error($error, $xml){
        $err  = $xml[$error->line - 1] . "\n";
        $err .= str_repeat('-', $error->column) . "^\n";

        switch ($error->level) {
            case LIBXML_ERR_WARNING:
                $err .= "Warning $error->code: ";
                break;
             case LIBXML_ERR_ERROR:
                $err .= "Error $error->code: ";
                break;
            case LIBXML_ERR_FATAL:
                $err .= "Fatal Error $error->code: ";
                break;
        }

        $err .= trim($error->message) .
                   "\n  Line: $error->line" .
                   "\n  Column: $error->column";

        if ($error->file) {
            $err .= "\n  File: $error->file";
        }
        return $err;
    }
}


text:
basedir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
. $basedir/utils.sh

# Make sure we kill the entire process tree when exiting
trap 'kill 0' SIGINT SIGTERM

function run_test_retry(){
    local tests_file=$1
    local tmp_log_file=$2
    local i=0
    local exit_code=0

    pushd . > /dev/null
    cd $tests_dir

    while : ; do
        > $tmp_log_file
        testr run --subunit --load-list=$tests_file > $tmp_log_file 2>&1
        subunit-stats $tmp_log_file > /dev/null
        exit_code=$?
        ((i++))
        ( [ $exit_code -eq 0 ] || [ $i -ge $max_attempts ] ) && break
        echo "Test $tests_file failed. Retrying count: $i"
    done

    popd > /dev/null

    echo $exit_code
}

function get_tests_range() {
    local i=$1
    if [ $i -lt ${#tests[@]} ]; then
        local test=${tests[$i]}
        local test_class=${test%.*}
        local j=$i
        if [ $run_isolated -eq 0 ]; then
            for test in ${tests[@]:$((i+1))}; do
                local test_class_match=${test%.*}
                if [ "$test_class" == "$test_class_match" ]; then
                    ((j++))
                else
                    break
                fi
            done
        fi

        echo $i $j
    fi
}

function get_next_test_idx_range() {
   (
        flock -x 200
        local test_idx=$(<$cur_test_idx_file)
        local test_idx_range=( $(get_tests_range $test_idx) )

        if [ ${#test_idx_range[@]} -gt 0 ]; then
            test_idx=${test_idx_range[1]}
            ((test_idx++))
            echo $test_idx > $cur_test_idx_file
            echo ${test_idx_range[@]}
        fi
   ) 200>$lock_file_1
}

function parallel_test_runner() {
    local runner_id=$1
    while : ; do
        local test_idx_range=( $(get_next_test_idx_range) )

        if [ ${#test_idx_range[@]} -eq 0 ]; then
            break
        fi

        local range_start=${test_idx_range[0]}
        local range_end=${test_idx_range[1]}
        local tmp_tests_file=$(tempfile)
        local l=$((range_end-range_start+1))

        for test in ${tests[@]:$range_start:$l}; do
            echo $test >> $tmp_tests_file
        done

        local tmp_log_file="$tmp_log_file_base"_"$range_start"

        echo `timestamp` "Test runner $runner_id is starting tests from $((range_start+1)) to $((range_end+1)) out of ${#tests[@]}:"
        cat $tmp_tests_file
        echo

        local test_exit_code=$(run_test_retry $tmp_tests_file $tmp_log_file)
        rm $tmp_tests_file

        echo `timestamp` "Test runner $runner_id finished tests from $((range_start+1)) to $((range_end+1)) out of ${#tests[@]} with exit code: $test_exit_code"
    done
}

tests_file=$1
tests_dir=$2
log_file=$3
max_parallel_tests=${4:-10}
max_attempts=${5:-5}
run_isolated=${6:-0}

tests=(`awk '{print}' $tests_file`)

cur_test_idx_file=$(tempfile)
echo 0 > $cur_test_idx_file

lock_file_1=$(tempfile)
tmp_log_file_base=$(tempfile)

pids=()
for i in $(seq 1 $max_parallel_tests); do
    parallel_test_runner $i &
    pids+=("$!")
done

for pid in ${pids[@]}; do
    wait $pid
done

rm $cur_test_idx_file

> $log_file
for i in $(seq 0 $((${#tests[@]}-1))); do
    tmp_log_file="$tmp_log_file_base"_"$i"
    if [ -f "$tmp_log_file" ]; then
        cat $tmp_log_file >> $log_file
        rm $tmp_log_file
    fi
done

rm $tmp_log_file_base
rm $lock_file_1

echo "Test execution completed in $SECONDS seconds."

subunit-stats $log_file > /dev/null
exit $?


text:
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six

from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources import wait_condition as wc_base
from heat.engine import support

LOG = logging.getLogger(__name__)

class HeatWaitCondition(resource.Resource):
    """Resource for handling signals received by WaitConditionHandle.

    Resource takes WaitConditionHandle and starts to create. Resource is in
    CREATE_IN_PROGRESS status until WaitConditionHandle doesn't receive
    sufficient number of successful signals (this number can be specified with
    count property) and successfully creates after that, or fails due to
    timeout.
    """

    support_status = support.SupportStatus(version='2014.2')

    PROPERTIES = (
        HANDLE, TIMEOUT, COUNT,
    ) = (
        'handle', 'timeout', 'count',
    )

    ATTRIBUTES = (
        DATA,
    ) = (
        'data',
    )

    properties_schema = {
        HANDLE: properties.Schema(
            properties.Schema.STRING,
            _('A reference to the wait condition handle used to signal this '
              'wait condition.'),
            required=True
        ),
        TIMEOUT: properties.Schema(
            properties.Schema.NUMBER,
            _('The number of seconds to wait for the correct number of '
              'signals to arrive.'),
            required=True,
            constraints=[
                constraints.Range(1, 43200),
            ]
        ),
        COUNT: properties.Schema(
            properties.Schema.INTEGER,
            _('The number of success signals that must be received before '
              'the stack creation process continues.'),
            constraints=[
                constraints.Range(min=1),
            ],
            default=1,
            update_allowed=True
        ),
    }

    attributes_schema = {
        DATA: attributes.Schema(
            _('JSON string containing data associated with wait '
              'condition signals sent to the handle.'),
            cache_mode=attributes.Schema.CACHE_NONE,
            type=attributes.Schema.STRING
        ),
    }

    def _get_handle_resource(self):
        return self.stack.resource_by_refid(self.properties[self.HANDLE])

    def _validate_handle_resource(self, handle):
        if handle is not None and isinstance(
                handle, wc_base.BaseWaitConditionHandle):
            return
        LOG.debug("Got %r instead of wait condition handle", handle)
        hn = handle.name if handle else self.properties[self.HANDLE]
        msg = _('%s is not a valid wait condition handle.') % hn
        raise ValueError(msg)

    def _wait(self, handle, started_at, timeout_in):
        if timeutils.is_older_than(started_at, timeout_in):
            exc = wc_base.WaitConditionTimeout(self, handle)
            LOG.info('%(name)s Timed out (%(timeout)s)',
                     {'name': str(self), 'timeout': str(exc)})
            raise exc

        handle_status = handle.get_status()

        if any(s != handle.STATUS_SUCCESS for s in handle_status):
            failure = wc_base.WaitConditionFailure(self, handle)
            LOG.info('%(name)s Failed (%(failure)s)',
                     {'name': str(self), 'failure': str(failure)})
            raise failure

        if len(handle_status) >= self.properties[self.COUNT]:
            LOG.info("%s Succeeded", str(self))
            return True
        return False

    def handle_create(self):
        handle = self._get_handle_resource()
        self._validate_handle_resource(handle)
        started_at = timeutils.utcnow()
        return handle, started_at, float(self.properties[self.TIMEOUT])

    def check_create_complete(self, data):
        return self._wait(*data)

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        if prop_diff:
            self.properties = json_snippet.properties(self.properties_schema,
                                                      self.context)

        handle = self._get_handle_resource()
        started_at = timeutils.utcnow()
        return handle, started_at, float(self.properties[self.TIMEOUT])

    def check_update_complete(self, data):
        return self._wait(*data)

    def handle_delete(self):
        handle = self._get_handle_resource()
        if handle:
            handle.metadata_set({})

    def _resolve_attribute(self, key):
        handle = self._get_handle_resource()
        if handle is None:
            return ''
        if key == self.DATA:
            meta = handle.metadata_get(refresh=True)
            res = {k: meta[k][handle.DATA] for k in meta}
            LOG.debug('%(name)s.GetAtt(%(key)s) == %(res)s'
                      % {'name': self.name,
                         'key': key,
                         'res': res})

            return six.text_type(jsonutils.dumps(res))

def resource_mapping():
    return {
        'OS::Heat::WaitCondition': HeatWaitCondition,
    }


text:
require 'spec_helper'
require 'stack'

describe StackMachine do
	it "checks to see if string is present" do
		stack = StackMachine.new("")
		stack.should_receive(:puts).with("Sorry, you didn't enter a value")
		stack.stack_machine_emulator
	end

	it "should fail if string does not have a digit or + or *" do
		stack = StackMachine.new("123g+45*")
		stack.should_receive(:puts).with(false)
		stack.stack_machine_emulator
	end

	it "should fail if first character is not a digit" do
		stack = StackMachine.new("h34")
		stack.should_receive(:puts).with(false)
		stack.stack_machine_emulator
	end

	it "first 2 characters should be digits and returns topmost value" do
		stack = StackMachine.new("12")
		stack.should_receive(:puts).with("2")
		stack.stack_machine_emulator
	end

	it "should fail if 2 or more consecitive additions" do
		stack = StackMachine.new("123++")
		stack.should_receive(:puts).with(false)
		stack.stack_machine_emulator
	end

	it "should fail if 2 or more consecitive multiplication" do
		stack = StackMachine.new("123**")
		stack.should_receive(:puts).with(false)
		stack.stack_machine_emulator
	end

	it "should fail if string is '11++'" do
		stack = StackMachine.new("11++")
		stack.should_receive(:puts).with(false)
		stack.stack_machine_emulator
	end

	it "should return 76 if string is '13+62*7+*'" do
		stack = StackMachine.new("13+62*7+*")
		stack.should_receive(:puts).with("76")
		stack.stack_machine_emulator
	end
end


text:
require "rails_helper"

describe "replicating questions with tags" do
  let(:mission) { create(:mission) }
  let(:orig_tag1) { create(:tag, name: "a", mission: orig_mission) }
  let(:orig_tag2) { create(:tag, name: "b", mission: orig_mission) }
  let(:orig_q) do
    create(:question, mission: orig_mission, qtype_name: "text", tags: [orig_tag1, orig_tag2])
  end

  describe "to_mission" do
    let(:orig_mission) { nil }
    let(:copy_q) { orig_q.replicate(mode: :to_mission, dest_mission: mission) }

    context "basic" do
      it "should replicate tag when replicates a standard library question to a mission" do
        orig_q.reload
        expect(orig_q.id).not_to eq(copy_q.id)
        expect(copy_q.tags.count).to eq(2)
        [orig_tag1, orig_tag2].each do |orig_tag|
          new_tag = find_tag_by_name(copy_q, orig_tag.name)
          expect(new_tag.id).not_to eq(orig_tag.id)
          expect(new_tag.name).to eq(orig_tag.name)
          expect(new_tag.mission).to eq(mission)
        end
      end
    end

    context "conflicting tag exists in mission" do
      let!(:pre_existing_tag) { Tag.create!(name: "a", mission: mission) }
      let(:a_tag_for_copy) { find_tag_by_name(copy_q, "a") }
      let(:b_tag_for_copy) { find_tag_by_name(copy_q, "b") }

      it "should use the existing tag" do
        expect(orig_q.id).not_to eq(copy_q.id)
        expect(Tag.count).to eq(4) # 2 original ones, pre-existing_tag, new 'b' tag made in replication
        expect(copy_q.tags.count).to eq(2)

        expect(a_tag_for_copy.id).to eq(pre_existing_tag.id)

        expect(b_tag_for_copy.id).not_to eq(orig_tag2.id)
        expect(b_tag_for_copy.name).to eq(orig_tag2.name)
        expect(b_tag_for_copy.mission).to eq(mission)
      end
    end
  end

  describe "promote" do
    let(:orig_mission) { mission }
    let(:std) { orig_q.replicate(mode: :promote) }

    context "basic" do
      it "should create new tag with mission nil" do
        orig_q.reload
        expect(orig_q.id).not_to eq(std.id)
        expect(std.tags.count).to eq(2)
        [orig_tag1, orig_tag2].each do |orig_tag|
          new_tag = find_tag_by_name(std, orig_tag.name)
          expect(new_tag.id).not_to eq(orig_tag.id)
          expect(new_tag.name).to eq(orig_tag.name)
          expect(new_tag.mission).to be_nil
        end
      end
    end

    context "conflicting standard tag exists" do
      let!(:pre_existing_tag) { Tag.create!(name: "a", mission: nil) }
      let(:a_tag_for_std) { find_tag_by_name(std, "a") }
      let(:b_tag_for_std) { find_tag_by_name(std, "b") }

      it "should use the existing tag" do
        orig_q.reload
        expect(orig_q.id).not_to eq(std.id)
        expect(Tag.count).to eq(4) # 2 original ones, pre-existing_tag, new 'b' tag made in promotion

        expect(std.tags.count).to eq(2)

        expect(a_tag_for_std.id).to eq(pre_existing_tag.id)

        expect(b_tag_for_std.id).not_to eq(orig_tag2.id)
        expect(b_tag_for_std.name).to eq(orig_tag2.name)
        expect(b_tag_for_std.mission).to be_nil
      end
    end
  end

  describe "clone" do
    let(:orig_mission) { mission }
    let(:copy_q) { orig_q.replicate(mode: :clone) }

    it "should use the existing tag in the mission" do
      orig_q.reload
      expect(orig_q.id).not_to eq(copy_q.id)
      expect(Tag.count).to eq(2) # only the two original ones, to be reused in copy_q
      expect(copy_q.tags.count).to eq(2)
      [orig_tag1, orig_tag2].each do |orig_tag|
        new_tag = find_tag_by_name(copy_q, orig_tag.name)
        expect(new_tag.id).to eq(orig_tag.id)
        expect(new_tag.name).to eq(orig_tag.name)
        expect(new_tag.mission).to eq(mission)
      end
    end
  end

  def find_tag_by_name(question, name)
    question.tags.find_by(name: name)
  end
end


text:
package org.pkaq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Description:     应用配置启动入口.
 * @FileName:         Booter.java
 * @Author:            S.PKAQ
 * @Version:          1.0
 * @Date:              2016年4月7日 上午9:28:07
 */
@SpringBootApplication
@Slf4j
public class Booter implements CommandLineRunner {
    /**
     * 入口函数.
     * @param args args
     */
    @Autowired
    public static void main(String[] args) {
        SpringApplication.run(Booter.class, args);
    }

    public void run(String... args) throws Exception {
        log.info("  --- --- --- [ web started ] --- --- ---  ");
    }
}