text:
package com.gopivotal.pig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import org.apache.pig.ResourceSchema;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema;

import org.joda.time.DateTime;

import com.pivotal.hawq.mapreduce.HAWQException;
import com.pivotal.hawq.mapreduce.HAWQRecord;
import com.pivotal.hawq.mapreduce.datatype.HAWQBox;
import com.pivotal.hawq.mapreduce.datatype.HAWQCircle;
import com.pivotal.hawq.mapreduce.datatype.HAWQLseg;
import com.pivotal.hawq.mapreduce.datatype.HAWQPath;
import com.pivotal.hawq.mapreduce.datatype.HAWQPoint;
import com.pivotal.hawq.mapreduce.datatype.HAWQPolygon;
import com.pivotal.hawq.mapreduce.schema.HAWQPrimitiveField.PrimitiveType;
import com.pivotal.hawq.mapreduce.schema.HAWQSchema;
import com.pivotal.hawq.mapreduce.schema.HAWQField;

/**
 * A utility for converting HAWQ column definitions and data to their related
 * counterparts for Pig.
 */
public class HawqPigDataConverter {

	private static final Logger LOG = Logger
			.getLogger(HawqPigDataConverter.class);
	private static final Map<PrimitiveType, Byte> hawqToPigType = new HashMap<PrimitiveType, Byte>();
	private static TupleFactory TF = TupleFactory.getInstance();
	private static BagFactory BF = BagFactory.getInstance();

	public static FieldSchema toPigField(HAWQField hField)
			throws FrontendException {

		// Create a few objects that are re-used in the below switch statement
		List<FieldSchema> ptFields = new ArrayList<FieldSchema>();
		ptFields.add(new FieldSchema("x", DataType.DOUBLE));
		ptFields.add(new FieldSchema("y", DataType.DOUBLE));

		List<FieldSchema> boxFields = new ArrayList<FieldSchema>();
		boxFields.add(new FieldSchema("pt1", new Schema(ptFields)));
		boxFields.add(new FieldSchema("pt2", new Schema(ptFields)));

		// Convert the HAWQ field to the pig data type
		byte pigType = getPigDataType(hField.asPrimitive().getType());

		// Based on the HAWQ type, create the associated schema. Complex types
		// are commonly tuples containing other fields. Simple types are
		// trivially converted.
		FieldSchema fSchema = null;
		switch (hField.asPrimitive().getType()) {
		case BOX:
			fSchema = new FieldSchema(hField.getName(), new Schema(boxFields));
			break;
		case CIRCLE:
			List<FieldSchema> circleFields = new ArrayList<FieldSchema>();

			circleFields.add(new FieldSchema("x", DataType.DOUBLE));
			circleFields.add(new FieldSchema("y", DataType.DOUBLE));
			circleFields.add(new FieldSchema("r", DataType.DOUBLE));

			fSchema = new FieldSchema(hField.getName(),
					new Schema(circleFields));
			break;
		case LSEG:
			List<FieldSchema> lsegFields = new ArrayList<FieldSchema>();

			lsegFields.add(new FieldSchema("pt1", new Schema(ptFields)));
			lsegFields.add(new FieldSchema("pt2", new Schema(ptFields)));

			fSchema = new FieldSchema(hField.getName(), new Schema(lsegFields));
			break;
		case PATH:
			List<FieldSchema> pathFields = new ArrayList<FieldSchema>();

			pathFields.add(new FieldSchema("open", DataType.BOOLEAN));
			pathFields.add(new FieldSchema("pts", new Schema(ptFields),
					DataType.BAG));

			fSchema = new FieldSchema(hField.getName(), new Schema(pathFields));
			break;
		case POINT:
			fSchema = new FieldSchema(hField.getName(), new Schema(ptFields));
			break;
		case POLYGON:
			List<FieldSchema> polygonFields = new ArrayList<FieldSchema>();
			polygonFields.add(new FieldSchema("pts", new Schema(ptFields),
					DataType.BAG));

			polygonFields.add(new FieldSchema("bbox", new Schema(boxFields)));

			fSchema = new FieldSchema(hField.getName(), new Schema(
					polygonFields));
			break;
		default:
			// All the types that are not complex, i.e. the ones above
			fSchema = new FieldSchema(hField.getName(), pigType);
			break;
		}

		return fSchema;
	}

	/**
	 * Convert a HAWQSchema to a ResourceSchema.
	 *
	 * @param schema
	 * @return The Pig schema or null if an exception was thrown
	 */
	public static synchronized ResourceSchema toPigSchema(HAWQSchema schema) {

		List<HAWQField> hawqFields = schema.getFields();
		List<FieldSchema> pigFields = new ArrayList<FieldSchema>();

		try {
			// For each field, convert it to a big type
			for (HAWQField hField : hawqFields) {
				if (hField.isPrimitive()) {
					pigFields.add(toPigField(hField));
				} else if (hField.isArray()) {
					throw new UnsupportedOperationException(
							"Array types are not supported");
				}
			}
		} catch (FrontendException e) {
			LOG.error("Error processing Pig schema", e);
			return null;
		}

		return new ResourceSchema(new Schema(pigFields));
	}

	/**
	 * Converts the field, retrieved from the given record at the given index,
	 * into a Pig value, expressed as an object. Inspects the field's type for
	 * proper conversion
	 *
	 * @param record
	 *            The record to get the field from
	 * @param idx
	 *            The index of the field
	 * @return The Pig object or null on error
	 */
	public static synchronized Object toPigValue(HAWQRecord record, int idx) {
		Object retval = null;
		PrimitiveType hawqType = record.getSchema().getField(idx).asPrimitive()
				.getType();
		try {
			switch (hawqType) {
			case BIT:
				return record.getBit(idx).toString();
			case BOOL:
				return record.getBoolean(idx);
			case BOX:
				HAWQBox box = record.getBox(idx);
				HAWQPoint pt1 = box.getPoint1();
				HAWQPoint pt2 = box.getPoint2();

				Tuple pigBox = TF.newTuple(2);
				Tuple tPt1 = TF.newTuple(2);
				Tuple tPt2 = TF.newTuple(2);

				tPt1.set(0, pt1.getX());
				tPt1.set(1, pt1.getY());
				tPt2.set(0, pt2.getX());
				tPt2.set(1, pt2.getY());

				pigBox.set(0, tPt1);
				pigBox.set(1, tPt2);

				return pigBox;
			case BPCHAR:
				return record.getString(idx);
			case BYTEA:
				return new DataByteArray(record.getBytes(idx));
			case CHAR:
				// this case will never get called cause CHAR -> BPCHAR
				return (char) record.getChar(idx);
			case CIDR:
				return record.getCidr(idx).toString();
			case CIRCLE:
				HAWQCircle cirle = record.getCircle(idx);
				Tuple tCircle = TF.newTuple(3);

				tCircle.set(0, cirle.getCenter().getX());
				tCircle.set(1, cirle.getCenter().getY());
				tCircle.set(2, cirle.getRadius());

				return tCircle;
			case DATE:
				return new DateTime(record.getDate(idx).getTime());
			case FLOAT4:
				return record.getFloat(idx);
			case FLOAT8:
				return record.getDouble(idx);
			case INET:
				return record.getInet(idx).toString();
			case INT2:
				return record.getShort(idx);
			case INT4:
				return record.getInt(idx);
			case INT8:
				return record.getLong(idx);
			case INTERVAL:
				return record.getInterval(idx).toString();
			case LSEG:
				HAWQLseg lseg = record.getLseg(idx);
				pt1 = lseg.getPoint1();
				pt2 = lseg.getPoint2();

				Tuple tLSeg = TF.newTuple(2);
				tPt1 = TF.newTuple(2);
				tPt2 = TF.newTuple(2);

				tPt1.set(0, pt1.getX());
				tPt1.set(1, pt1.getY());
				tPt2.set(0, pt2.getX());
				tPt2.set(1, pt2.getY());

				tLSeg.set(0, tPt1);
				tLSeg.set(1, tPt2);
				return tLSeg;
			case MACADDR:
				return record.getMacaddr(idx).toString();
			case NUMERIC:
				return record.getBigDecimal(idx);
			case PATH:
				HAWQPath path = record.getPath(idx);
				List<Tuple> points = new ArrayList<Tuple>();

				for (HAWQPoint p : path.getPoints()) {
					Tuple tPoint = TF.newTuple(2);
					tPoint.set(0, p.getX());
					tPoint.set(1, p.getY());
					points.add(tPoint);
				}

				Tuple tPath = TF.newTuple(2);

				tPath.set(0, path.isOpen());
				tPath.set(1, BF.newDefaultBag(points));

				return tPath;
			case POINT:
				HAWQPoint pt = record.getPoint(idx);
				Tuple tPoint = TF.newTuple(2);
				tPoint.set(0, pt.getX());
				tPoint.set(1, pt.getY());
				return tPoint;
			case POLYGON:
				Tuple tPoly = TF.newTuple(2);

				HAWQPolygon poly = record.getPolygon(idx);
				points = new ArrayList<Tuple>();

				for (HAWQPoint p : poly.getPoints()) {
					tPoint = TF.newTuple(2);
					tPoint.set(0, p.getX());
					tPoint.set(1, p.getY());
					points.add(tPoint);
				}

				box = poly.getBoundbox();
				pt1 = box.getPoint1();
				pt2 = box.getPoint2();

				pigBox = TF.newTuple(2);
				tPt1 = TF.newTuple(2);
				tPt2 = TF.newTuple(2);

				tPt1.set(0, pt1.getX());
				tPt1.set(1, pt1.getY());
				tPt2.set(0, pt2.getX());
				tPt2.set(1, pt2.getY());

				pigBox.set(0, tPt1);
				pigBox.set(1, tPt2);

				tPoly.set(0, BF.newDefaultBag(points));
				tPoly.set(1, pigBox);

				return tPoly;
			case TEXT:
				return record.getString(idx);
			case TIME:
			case TIMETZ:
				return new DateTime(record.getTime(idx).getTime());
			case TIMESTAMP:
			case TIMESTAMPTZ:
				return new DateTime(record.getTimestamp(idx).getTime());
			case VARBIT:
				return record.getVarbit(idx).toString();
			case VARCHAR:
				return record.getString(idx);
			case XML:
				return record.getString(idx);
			default:
				break;

			}
		} catch (HAWQException | ExecException e) {
			LOG.error("Error when converting object", e);
			return null;
		}

		return retval;
	}

	/**
	 * Gets the Pig data type from the primitive HAWQ type. O(1)
	 *
	 * @param hawqType
	 *            The HAWQ Type
	 * @return The Pig type or null if not found in the internal map
	 */
	public static synchronized byte getPigDataType(PrimitiveType hawqType) {
		return hawqToPigType.get(hawqType);
	}

	/**
	 * Gets the HAWQ data type from from the given Pig {@link DataType}. O(n)
	 *
	 * @param pigType
	 *            The Pig type
	 * @return The HAWQ type or null if not found
	 */
	public static synchronized PrimitiveType getHawqDataType(byte pigType) {

		for (Entry<PrimitiveType, Byte> entry : hawqToPigType.entrySet()) {
			if (entry.getValue() == pigType) {
				return entry.getKey();
			}
		}

		return null;
	}

	static {
		// A bunch of mappings that I selfishly chose
		hawqToPigType.put(PrimitiveType.BIT, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.BOOL, DataType.BOOLEAN);
		hawqToPigType.put(PrimitiveType.BOX, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.BPCHAR, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.BYTEA, DataType.BYTEARRAY);
		hawqToPigType.put(PrimitiveType.CHAR, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.CIDR, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.CIRCLE, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.DATE, DataType.DATETIME);
		hawqToPigType.put(PrimitiveType.FLOAT4, DataType.FLOAT);
		hawqToPigType.put(PrimitiveType.FLOAT8, DataType.DOUBLE);
		hawqToPigType.put(PrimitiveType.INET, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.INT2, DataType.INTEGER);
		hawqToPigType.put(PrimitiveType.INT4, DataType.INTEGER);
		hawqToPigType.put(PrimitiveType.INT8, DataType.LONG);
		hawqToPigType.put(PrimitiveType.INTERVAL, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.LSEG, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.MACADDR, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.NUMERIC, DataType.BIGDECIMAL);
		hawqToPigType.put(PrimitiveType.PATH, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.POINT, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.POLYGON, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.TEXT, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.TIME, DataType.DATETIME);
		hawqToPigType.put(PrimitiveType.TIMESTAMP, DataType.DATETIME);
		hawqToPigType.put(PrimitiveType.TIMESTAMPTZ, DataType.DATETIME);
		hawqToPigType.put(PrimitiveType.TIMETZ, DataType.DATETIME);
		hawqToPigType.put(PrimitiveType.VARBIT, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.VARCHAR, DataType.CHARARRAY);
		hawqToPigType.put(PrimitiveType.XML, DataType.CHARARRAY);
	}
}


text:
package hello1;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/springapp-servlet.xml")
@WebAppConfiguration
public class HelloControllerTest {
    private MockMvc mockMvc;

    @Autowired
    protected WebApplicationContext wac;

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
    }

    @Test
    public void htmlView() throws Exception {
        this.mockMvc.perform(get("/hello"))
        .andExpect(view().name(containsString("hello")))
        .andExpect(model().attribute("msg", "Spring mvc"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace backend\controllers;

use common\models\base\asset\Info;
use frontend\actions\sina;
use frontend\actions\sinapay;
use Yii;
use common\models\sinapay\SinaWithdraw;
use common\models\sinapay\SinaWithdrawSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\sinapay\SinaInvest;

/**
 * SinawithdrawController implements the CRUD actions for SinaWithdraw model.
 */
class SinawithdrawController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all SinaWithdraw models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SinaWithdrawSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SinaWithdraw model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SinaWithdraw model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SinaWithdraw();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing SinaWithdraw model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SinaWithdraw model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SinaWithdraw model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SinaWithdraw the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SinaWithdraw::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 用户退款
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionRefund(){
        if (\App::$app->request->post()) {

            $uid =  \App::$app->request->post()['Code']['uid'];
            $orig_outer_trade_no = \App::$app->request->post()['Code']['out_trade_no'];
            $refund_amount = \App::$app->request->post()['Code']['money'];
            $summary = \App::$app->request->post()['Code']['msg'];
            //获取新浪的账户余额
            $sina_balance = sinapay::querySinaBalance($uid);
            if($sina_balance['errorNum'] == '0'){
                $available_balance = $sina_balance['data']['available_balance'];
            }
            //获取网站的账户信息
            $balance = Info::findOne(['member_id' => $uid]);
            $site_balabce = $balance['balance'];
            //调用新浪退款接口
            $sina = new sina();
            $out_trade_no =  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $refund = $sina->create_hosting_refund($out_trade_no,$orig_outer_trade_no,$refund_amount,$summary);
            if(!$refund){
                throw new NotFoundHttpException('新浪接口错误');
            }
            if($refund['response_code'] == "APPLY_SUCCESS"){
                //提交信息成功
                if($refund['refund_status'] == 'SUCCESS' || $refund['refund_status'] == 'PAY_FINISHED'){
                    //更新账户信息
                    $sina_balance = sinapay::querySinaBalance($uid);
                    if($sina_balance['errorNum'] == '0'){
                        $available_balance_now = $sina_balance['data']['available_balance'];
                    }
                    //获取网站的账户信息
                    $balance = Info::findOne(['member_id' => $uid]);
                    $site_balabce_now = $balance['balance'];
                    //返回数据
                    $data = array(
                        'available_balance' => $available_balance,
                        'site_balabce' => $site_balabce,
                        'available_balance_now' => $available_balance_now,
                        'site_balabce_now' => $site_balabce_now
                    );
                    return $this->render('import',compact("data"));

                }else{
                    throw new NotFoundHttpException($refund['response_message']);
                }
            }else{
                throw new NotFoundHttpException($refund['response_message']);

            }
        } else {
            $data = array(
                'available_balance' => '-1',
                'site_balabce' => '-2',
                'available_balance_now' => '-3',
                'site_balabce_now' => '-4'
            );
            return $this->render('import',compact("data"));
        }
    }
}


text:
require("data/scripts/3rdparty/bit")
require("data/scripts/gui/group")

GUI = { _widgets = {}, _groups = {} }
GUI.__index = GUI

function GUI:loadGroup(name)
	local func = nil
	if name ~= nil then
		func = self["widgets_" .. name]
	end
	if type(func) == "function" then
		func(self, char)
	end
end

function GUI:widgets_game()
	-- Creation
	self:getWidget('fps', nil, "widget_fps_5452434", constants.wtText, {
		align = bit.bor(constants.waLEFT, constants.waBOTTOM), y = 0, x = 10,
		text = {
			base = "FPS: ", align = constants.waLEFT,
			face = "./DejaVuSans.ttf", size = 20, color = {80,80,80},
	}}, {'game'})
	self:getWidget('time', nil, "widget_time_493245", constants.wtText, {
		image = "sprite_widget_time_768888", width = 263, height = 70,
		align = bit.bor(constants.waRIGHT, constants.waTOP),
		text = { y = 8, face = "./LiberationSerif-Regular.ttf", size = 26, }
	}, {'game'})
	self:getWidget('stats', nil, "widget_stats_98072", constants.wtBlank, {
		image = "sprite_widget_stats_909956", width = 200, height = 300,
		align = bit.bor(constants.waLEFT, constants.waTOP),
		bgposx = 265, bgimage = "misc.png",
	}, {'game', 'stats'})
	self:getWidget('plevel', 'stats', "textwidget_plevel_152271", constants.wtText, {
		y = 15, x = -30, align = bit.bor(constants.waRIGHT, constants.waTOP),
		text = { size = 18, align = constants.waLEFT,
			face = "./LiberationSerif-Regular.ttf", base = "Level: ", },
	}, {'game', 'stats'})
	self:getWidget('pdays', 'stats', "textwidget_pdays_353161", constants.wtText, {
		x = -30, y = 45, align = bit.bor(constants.waRIGHT, constants.waTOP),
		text = {
			face = "./LiberationSerif-Regular.ttf", base = "Age: ",
			size = 18, align = constants.waLEFT,
		}
	}, {'game', 'stats'})
	local hpbar = self:getWidget('hpbar', 'stats', "barwidget_phpbar_121678",
		constants.wtBar, {
		width = 146, height = 20, y = 80, align = constants.waTOP,
		text = { base = "HP: ", size = 18, align = constants.waLEFT,
			face = "./LiberationSerif-Regular.ttf",
		},
		bar = { color = {255,0,0}, width = 133, height = 8, y = -5 },
		top = { x = -7, y = -5, width = 145, height = 17,
				image = "sprite_bar_cover_693493" }
	}, {'game', 'stats'})
	local fedbar = self:getWidget('fedbar', 'stats', "barwidget_pfedbar_655231",
		constants.wtBar, {
		width = 146, height = 20, y = 125, align = constants.waTOP,
		text = { base = "Fed: ", size = 18, align = constants.waLEFT,
			face = "./LiberationSerif-Regular.ttf",
		},
		bar = { color = {0,0,255}, width = 133, height = 8, y = -5 },
		top = { x = -7, y = -5, width = 145, height = 17, image = "sprite_bar_cover_693493" }
	}, {'game', 'stats'})
	local expbar = self:getWidget('expbar', 'stats', "barwidget_pexpbar_361877",
		constants.wtBar, {
		width = 146, height = 20, y = 170, align = constants.waTOP,
		text = { base = "Exp: ", size = 18, align = constants.waLEFT,
			face = "./LiberationSerif-Regular.ttf",
		},
		bar = { color = {0,255,0}, width = 133, height = 8, y = -5 },
		top = { x = -7, y = -5, width = 145, height = 17, image = "sprite_bar_cover_693493" }
	}, {'game', 'stats'})

	self:getWidget('minimap_container', nil, 'widget_minimap_bg', constants.wtBlank, {
 		width = 600, height = 600, depth = 3, bgcolor = {255, 255, 255}
 	}, {'game', 'map'})
	self:getWidget('minimap', 'minimap_container', 'widget_minimap', constants.wtBlank, {
 		width = 600, height = 600, image = Map.imageName()
 	}, {'game', 'map'})

	-- Bindings
	self:bindWidget('fps', nil, constants.gbpFPS)
	self:bindWidget('plevel', Player, constants.uBaseLevel)
	self:bindWidget('pdays', Player, constants.uBaseAge)
	self:bindWidget('hpbar', Player, constants.uStateHP)
	self:bindWidget('fedbar', Player, constants.uStateFed)
	self:bindWidget('expbar', Player, constants.uStateExp)

	hpbar:bindBarMaxValue(Player, constants.uParamHP)
	fedbar:BarSize(100)
	expbar:bindBarMaxValue(Player, constants.uParamExp)
end

function GUI:getWidget(name, parent, wname, wtype, wparams, groups)
	local widget = self._widgets[name]
	if widget == nil and (wname and wtype and wparams) then
		local parent = self._widgets[parent]
		if parent ~= nil then
			self._widgets[name] = Interface.addChild(parent, wname, wtype, wparams)
		else
			self._widgets[name] = Interface.createWidget(wname, wtype, wparams)
		end
		widget = self._widgets[name]
	end
	if groups ~= nil then
		for i, group in ipairs(groups) do
			self:addToGroup(group, widget)
		end
	end
	return widget
end

function GUI:getGroup( name )
	if self._groups[name] == nil then
		self._groups[name] = WidgetGroup:create()
	end
	return self._groups[name]
end

function GUI:addToGroup( name, widget )
	local group = self:getGroup(name)
	group:add(widget)
end

function GUI:bindWidget(name, target, location)
	if self._widgets[name] ~= nil then
		self._widgets[name]:bindParam(target, location)
	end
end


text:
import type {EslintContext, CallExpression} from './types';

/* $FlowFixMe */
const describeAliases = Object.assign(Object.create(null), {
  describe: true,
  'describe.only': true,
  'describe.skip': true,
  fdescribe: true,
  xdescribe: true,
});

/* $FlowFixMe */
const testCaseNames = Object.assign(Object.create(null), {
  fit: true,
  it: true,
  'it.only': true,
  'it.skip': true,
  test: true,
  'test.only': true,
  'test.skip': true,
  xit: true,
  xtest: true,
});

const getNodeName = node => {
  if (node.type === 'MemberExpression') {
    return node.object.name + '.' + node.property.name;
  }
  return node.name;
};

const isDescribe = node =>
  node &&
  node.type === 'CallExpression' &&
  describeAliases[getNodeName(node.callee)];

const isTestCase = node =>
  node &&
  node.type === 'CallExpression' &&
  testCaseNames[getNodeName(node.callee)];

const newDescribeContext = () => ({
  describeTitles: [],
  testTitles: [],
});

const handleTestCaseTitles = (context, titles, node, title) => {
  if (isTestCase(node)) {
    if (titles.indexOf(title) !== -1) {
      context.report({
        message: 'Test title is used multiple times in the same test suite.',
        node,
      });
    }
    titles.push(title);
  }
};

const handleTestSuiteTitles = (context, titles, node, title) => {
  if (!isDescribe(node)) {
    return;
  }
  if (titles.indexOf(title) !== -1) {
    context.report({
      message: 'Test suite title is used multiple times.',
      node,
    });
  }
  titles.push(title);
};

const isFirstArgLiteral = node =>
  node.arguments && node.arguments[0] && node.arguments[0].type === 'Literal';

module.exports = (context: EslintContext) => {
  const contexts = [newDescribeContext()];
  return {
    CallExpression(node: CallExpression) {
      const currentLayer = contexts[contexts.length - 1];
      if (isDescribe(node)) {
        contexts.push(newDescribeContext());
      }
      if (!isFirstArgLiteral(node)) {
        return;
      }

      const title = node.arguments[0].value;
      handleTestCaseTitles(context, currentLayer.testTitles, node, title);
      handleTestSuiteTitles(context, currentLayer.describeTitles, node, title);
    },
    'CallExpression:exit'(node: CallExpression) {
      if (isDescribe(node)) {
        contexts.pop();
      }
    },
  };
};


text:
This is my ugly, hacked up script that lets you download a set of user resources
(comments, submissions, etc) from a reddit user and save it to a json file. You can also delete those resources from reddit with this script if your logged in as them.

Go see how to setup a reddit app with praw / prawoauth2.   I would set this up as a personal script.
Or see https://www.reddit.com/prefs/apps/

**LIMITATIONS:**

Since you can only fetch 1000 items of a type from reddit, you can only download your latest
1000 items of each type.  Maybe deleting them and then trying again will let you get the next 1000?

This 1000 item limit is a reddit server limitation, not a limit of this script.  The script maybe could get around it by
getting the oldest item of each type, and then doing a search for all items by user x before time y, if
that is possible. (TODO)

**DOES NOT DOWNLOAD YOUR INBOX / PMs**  (TODO Should do this one day)

**Why did I make it?**

1. There is nothing like google takeout in reddit, so you cannot export all of your data as a user.
2. When you press the delete user button, you do not delete your comments or your submissions, you just remove your username tag from them.  And whats worse, once you have done that, you cannot go back and remove your actual content.


text:
#include <xdispatch/dispatch>
#include "cxx_tests.h"

#include <iostream>

#define RUN_TIMES 20

/*
 Little tests mainly checking the correct mapping of the Qt api
 to the underlying C Api
 */

extern "C" void cxx_dispatch_queue_blocks(){
    MU_BEGIN_TEST(cxx_dispatch_queue_blocks);

	uintptr_t* worker = new uintptr_t;
	*worker = 0;

    xdispatch::queue q = xdispatch::global_queue(xdispatch::HIGH);
    MU_ASSERT_NOT_NULL(q.native());

    q.apply(RUN_TIMES, ^(size_t i){
        dispatch_atomic_inc(worker);
    });

    xdispatch::global_queue(xdispatch::LOW).async(^{
        MU_ASSERT_EQUAL(*worker,RUN_TIMES);
        MU_PASS("Queue executed");
    });

    xdispatch::exec();
	MU_END_TEST;
}


text:
VERSION := $(shell sh -c 'git describe --always --tags')
ifdef GOBIN
PATH := $(GOBIN):$(PATH)
else
PATH := $(subst :,/bin:,$(GOPATH))/bin:$(PATH)
endif

# Standard Telegraf build
default: prepare build

# Windows build
windows: prepare-windows build-windows

# Only run the build (no dependency grabbing)
build:
	go install -ldflags "-X main.version=$(VERSION)" ./...

build-windows:
	GOOS=windows GOARCH=amd64 go build -o telegraf.exe -ldflags \
		"-X main.version=$(VERSION)" \
		./cmd/telegraf/telegraf.go

build-for-docker:
	CGO_ENABLED=0 GOOS=linux go build -installsuffix cgo -o telegraf -ldflags \
					"-s -X main.version=$(VERSION)" \
					./cmd/telegraf/telegraf.go

# run package script
package:
	./scripts/build.py --package --version="$(VERSION)" --platform=linux --arch=all --upload

# Get dependencies and use gdm to checkout changesets
prepare:
	go get github.com/sparrc/gdm
	gdm restore

# Use the windows godeps file to prepare dependencies
prepare-windows:
	go get github.com/sparrc/gdm
	gdm restore
	gdm restore -f Godeps_windows

# Run all docker containers necessary for unit tests
docker-run:
	docker run --name aerospike -p "3000:3000" -d aerospike/aerospike-server:3.9.0
	docker run --name kafka \
		-e ADVERTISED_HOST=localhost \
		-e ADVERTISED_PORT=9092 \
		-p "2181:2181" -p "9092:9092" \
		-d spotify/kafka
	docker run --name mysql -p "3306:3306" -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -d mysql
	docker run --name memcached -p "11211:11211" -d memcached
	docker run --name postgres -p "5432:5432" -d postgres
	docker run --name rabbitmq -p "15672:15672" -p "5672:5672" -d rabbitmq:3-management
	docker run --name redis -p "6379:6379" -d redis
	docker run --name nsq -p "4150:4150" -d nsqio/nsq /nsqd
	docker run --name mqtt -p "1883:1883" -d ncarlier/mqtt
	docker run --name riemann -p "5555:5555" -d blalor/riemann
	docker run --name snmp -p "31161:31161/udp" -d titilambert/snmpsim

# Run docker containers necessary for CircleCI unit tests
docker-run-circle:
	docker run --name aerospike -p "3000:3000" -d aerospike/aerospike-server:3.9.0
	docker run --name kafka \
		-e ADVERTISED_HOST=localhost \
		-e ADVERTISED_PORT=9092 \
		-p "2181:2181" -p "9092:9092" \
		-d spotify/kafka
	docker run --name nsq -p "4150:4150" -d nsqio/nsq /nsqd
	docker run --name mqtt -p "1883:1883" -d ncarlier/mqtt
	docker run --name riemann -p "5555:5555" -d blalor/riemann
	docker run --name snmp -p "31161:31161/udp" -d titilambert/snmpsim

# Kill all docker containers, ignore errors
docker-kill:
	-docker kill nsq aerospike redis rabbitmq postgres memcached mysql kafka mqtt riemann snmp
	-docker rm nsq aerospike redis rabbitmq postgres memcached mysql kafka mqtt riemann snmp

# Run full unit tests using docker containers (includes setup and teardown)
test: vet docker-kill docker-run
	# Sleeping for kafka leadership election, TSDB setup, etc.
	sleep 60
	# SUCCESS, running tests
	go test -race ./...

# Run "short" unit tests
test-short: vet
	go test -short ./...

vet:
	go vet ./...

.PHONY: test test-short vet build default


text:
#include "slicertsi.h"
#include "shared/slicer/slicer.h"
#include "amffiletsi.h"
#include "slicestacktsi.h"
#include "amfregiontsi.h"

SlicerTSI::SlicerTSI(QScriptEngine& engine, SlicerProgressCallback* callback)
    : ToolScriptInterface(engine),
      slicer_(new Slicer()),
      callback_(callback) {
}
//
//SliceStack* SlicerTSI::doSlicing(AMFRegion* region) {
//  if (!slicer_->doSlicing(region, callback_)) {
//    throwError("Slicer failed: " + slicer_->getLastErrorString());
//    return 0;
//  }
//  return new SliceStack(slicer_->getSliceStack());
//}

void SlicerTSI::setSliceHeight(double v) {
  //jlz27 - Does not work in Qt 4.6.2
    /*if (!_finite(v) || _isnan(v)) {
    throwError("Invalid slice height");
  }*/

  slicer_->setSliceHeight((FAHFloat)v);
}

void SlicerTSI::alignTray() {
  slicer_->setAlignment(Slicer::kAlignTray);
}

void SlicerTSI::alignTop() {
  slicer_->setAlignment(Slicer::kAlignTop);
}

void SlicerTSI::alignBottom() {
  slicer_->setAlignment(Slicer::kAlignBottom);
}

void SlicerTSI::alignCenter() {
  slicer_->setAlignment(Slicer::kAlignCenter);
}

void SlicerTSI::doSlicing(QScriptValue amf_region) {
  AMFRegionTSI* argument = (AMFRegionTSI*)castTo(amf_region, "AMFRegionTSI");

  if (!argument) {
    throwError("Invalid object passed to slicer's doSlicing()");
    return;
  }

  if (!slicer_->doSlicing(argument->region(), callback_)) {
    throwError("Unable to perform slicing:  " + slicer_->getLastErrorString());
    return;
  }

  argument->setSlices(new SliceStack(slicer_->getSliceStack()));
//
//  AMFFileTSI* argument = (AMFFileTSI*)castTo(amf_object, "AMFFileTSI");
//
//  if (!argument) {
//    return throwError("Invalid object passed to slicer's doSlicing()");
//  }
//
//  if (!slicer_->doSlicing(argument->amf(), callback_)) {
//    return throwError("Unable to perform slicing:  " + slicer_->getLastErrorString());
//  }
//
//  return newQObject(new SliceStackTSI(engine(), slicer_));
}


text:
// -*- C++ -*-

// Copyright (C) 2005, 2006, 2007, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3.  If not see
// <http://www.gnu.org/licenses/>.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file trie_dna_example.cpp
 * An example showing how to use a trie for storing DNA strings.
 */

/**
 * This example shows how to use a PATRICIA trie for storing
 DNA strings. The main point is writing element-access traits
 for these strings.
*/

#include <cassert>
#include <iostream>
#include <cstdlib>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/trie_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

// DNA is represented by a string.
typedef string dna_t;

// Following is an element access traits for a DNA string.
struct dna_string_access_traits
{
public:
  typedef size_t size_type;
  typedef dna_t key_type;
  typedef const key_type& key_const_reference;
  typedef char e_type;
  typedef string::const_iterator const_iterator;

  enum
    {
      // Number of distinct elements. This is 4 = |{'A', 'C', 'G', 'T'}|
      max_size = 4
    };

  // Returns a const_iterator to the firstelement of r_key.
  inline static const_iterator
  begin(key_const_reference r_key)
  { return r_key.begin(); }

  // Returns a const_iterator to the after-lastelement of r_key.
  inline static const_iterator
  end(key_const_reference r_key)
  { return r_key.end(); }

  // Maps an element to a position.
  inline static size_t
  e_pos(e_type e)
  {
    switch(e)
      {
      case 'A':
	return 0;
      case 'C':
	return 1;
      case 'G':
	return 2;
      case 'T':
	return 3;
      default:
	std::abort();
      };
  }
};

// A PATRICIA trie with DNA string element-access traits.
typedef dna_string_access_traits traits_type;
typedef trie<dna_t, string, traits_type> trie_type;

int main()
{
  trie_type t;

  // Now map some DNAs to diseases in namespace STD.
  t["ACCGGTTACTGGTA"] = "gonorrhea";
  t["CCGTTATCGGTA"] = "syphlis";

  // Check gonorrhea already contracted.
  assert(t.find("ACCGGTTACTGGTA") != t.end());

  return 0;
}


text:
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-MaterialSpinner-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1720)

Spinner with Material Design - Down to API 9

This library provides you a Spinner with the Material style. You can use it like any regular Spinner.
Add floating label text, hint and error messages.

## Screenshots
![MaterialSpinner](./screenshots/screenshot.gif)

## Gradle Dependency
Use this dependency in your build.gradle file to reference this library in your project

```groovy
compile 'com.github.ganfra:material-spinner:1.1.1'
```

If you use other libraries requiring nineoldandroids and appcompat-v7 like [MaterialEditText](https://github.com/rengwuxian/MaterialEditText/) make sure to exclude them :
```groovy
compile ('com.github.ganfra:material-spinner:1.1.1'){
        exclude group: 'com.nineoldandroids', module: 'library'
        exclude group: 'com.android.support', module: 'appcompat-v7'
}
```

## Usages

In the xml :

```xml
<fr.ganfra.materialspinner.MaterialSpinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:ms_multiline="false"
        app:ms_hint="hint"
        app:ms_enableFloatingLabel="false"
        app:ms_enableErrorLabel="false"
        app:ms_floatingLabelText="floating label"
        app:ms_baseColor="@color/base"
        app:ms_highlightColor="@color/highlight"
        app:ms_errorColor="@color/error"
        app:ms_typeface="typeface.ttf"
        app:ms_thickness="2dp"
        app:ms_hintColor="@color/hint"
        app:ms_arrowColor="@color/arrow"
        app:ms_arrowSize="16dp"
        app:ms_alignLabels="false"
        app:ms_floatingLabelColor="@color/floating_label"/>
```
You can set a hint and a floating label text. If no floating label text is provided, the hint will be set instead.

Java side, you use it like a regular spinner, setting an adapter to it.
```java
 String[] ITEMS = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"};
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ITEMS);
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spinner = (MaterialSpinner) findViewById(R.id.spinner);
 spinner.setAdapter(adapter);
```

If you need to set an error message, you can do it the same way than with an EditText :
```java
 //Activate
 spinner.setError("Error");
 //Desactivate
 spinner.setError(null);
```
You can choose to have a scrolling animation or to set the error message on multiple lines with the "ms_multiline" attribute in xml (default is true).

## License

    Copyright 2015 François Ganard

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
<!--

    Copyright 2007-2016, Kaazing Corporation. All rights reserved.

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
Base class for implementing transport based on active polling strategies like NIO select call, or any API
based on I/O polling system calls (epoll, poll, select, kqueue, etc). Know implementations are <tt>org.apache.mina.transport.socket.nio</tt>
and <tt>org.apache.mina.transport.socket.apr</tt>.
</body>
</html>


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SessionController implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function welcomeAction(Request $request, $name = null)
    {
        $session = $request->getSession();

        // new session case
        if (!$session->has('name')) {
            if (!$name) {
                return new Response('You are new here and gave no name.');
            }

            // remember name
            $session->set('name', $name);

            return new Response(sprintf('Hello %s, nice to meet you.', $name));
        }

        // existing session
        $name = $session->get('name');

        return new Response(sprintf('Welcome back %s, nice to meet you.', $name));
    }

    public function logoutAction(Request $request)
    {
        $request->getSession()->invalidate();

        return new Response('Session cleared.');
    }

    public function setFlashAction(Request $request, $message)
    {
        $session = $request->getSession();
        $session->getFlashBag()->set('notice', $message);

        return new RedirectResponse($this->container->get('router')->generate('session_showflash'));
    }

    public function showFlashAction(Request $request)
    {
        $session = $request->getSession();

        if ($session->getFlashBag()->has('notice')) {
            list($output) = $session->getFlashBag()->get('notice');
        } else {
            $output = 'No flash was set.';
        }

        return new Response($output);
    }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using Autofac.Builder;
using Autofac.Core;
using Autofac.Features.ResolveAnything;
using Moq;

namespace Autofac.Extras.Moq
{
    /// <summary>
    /// Wrapper around <see cref="Autofac"/> and <see cref="Moq"/>
    /// </summary>
    [SecurityCritical]
    public class AutoMock : IDisposable
    {
        private bool _disposed;

        /// <summary>
        /// <see cref="MockRepository"/> instance responsible for expectations and mocks.
        /// </summary>
        public MockRepository MockRepository { [SecurityCritical]get; [SecurityCritical]private set; }

        /// <summary>
        /// <see cref="IContainer"/> that handles the component resolution.
        /// </summary>
        public IContainer Container { get; private set; }

        private AutoMock(MockBehavior behavior)
            : this(new MockRepository(behavior))
        {
        }

        private AutoMock(MockRepository repository)
        {
            MockRepository = repository;
            var builder = new ContainerBuilder();
            builder.RegisterInstance(MockRepository);
            builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
            builder.RegisterSource(new MoqRegistrationHandler());
            Container = builder.Build();
            VerifyAll = false;
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="AutoMock"/> class.
        /// </summary>
        [SecuritySafeCritical]
        ~AutoMock()
        {
            Dispose(false);
        }

        /// <summary>
        /// Create new <see cref="AutoMock"/> instance with loose mock behavior.
        /// </summary>
        /// <seealso cref="MockRepository"/>
        /// <returns>Container initialized for loose behavior.</returns>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static AutoMock GetLoose()
        {
            return new AutoMock(MockBehavior.Loose);
        }

        /// <summary>
        /// Create new <see cref="AutoMock"/> instance with strict mock behavior.
        /// </summary>
        /// <seealso cref="MockRepository"/>
        /// <returns>Container initialized for loose behavior.</returns>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public static AutoMock GetStrict()
        {
            return new AutoMock(MockBehavior.Strict);
        }

        /// <summary>
        /// Create new <see cref="AutoMock"/> instance that will create mocks with behavior defined by <c>repository</c>.
        /// </summary>
        /// <param name="repository"></param>
        /// <returns></returns>
        public static AutoMock GetFromRepository(MockRepository repository)
        {
            return new AutoMock(repository);
        }

        /// <summary>
        /// Verifies mocks and disposes internal container.
        /// </summary>
        [SecuritySafeCritical]
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Handles disposal of managed and unmanaged resources.
        /// </summary>
        /// <param name="disposing">
        /// <see langword="true" /> to dispose of managed resources (during a manual execution
        /// of <see cref="Autofac.Extras.Moq.AutoMock.Dispose()"/>); or
        /// <see langword="false" /> if this is getting run as part of finalization where
        /// managed resources may have already been cleaned up.
        /// </param>
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // We can only verify things with the mock
                    // repository if it hasn't already been garbage
                    // collected during finalization.
                    try
                    {
                        if (VerifyAll)
                        {
                            MockRepository.VerifyAll();
                        }
                        else
                        {
                            MockRepository.Verify();
                        }
                    }
                    finally
                    {
                        Container.Dispose();
                    }
                }
                _disposed = true;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether all mocks are verified.
        /// </summary>
        /// <value><c>true</c> to verify all mocks. <c>false</c> (default) to verify only mocks marked Verifiable.</value>
        public bool VerifyAll { get; set; }

        /// <summary>
        /// Finds (creating if needed) the actual mock for the provided type
        /// </summary>
        /// <typeparam name="T">Type to mock</typeparam>
        /// <param name="parameters">Optional parameters</param>
        /// <returns>Mock</returns>
        public Mock<T> Mock<T>(params Parameter[] parameters) where T : class
        {
            var obj = (IMocked<T>)Create<T>(parameters);
            return obj.Mock;
        }

        /// <summary>
        /// Resolve the specified type in the container (register it if needed)
        /// </summary>
        /// <typeparam name="T">Service</typeparam>
        /// <param name="parameters">Optional parameters</param>
        /// <returns>The service.</returns>
        public T Create<T>(params Parameter[] parameters)
        {
            return Container.Resolve<T>(parameters);
        }

        /// <summary>
        /// Resolve the specified type in the container (register it if needed)
        /// </summary>
        /// <typeparam name="TService">Service</typeparam>
        /// <typeparam name="TImplementation">The implementation of the service.</typeparam>
        /// <param name="parameters">Optional parameters</param>
        /// <returns>The service.</returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The component registry is responsible for registration disposal.")]
        public TService Provide<TService, TImplementation>(params Parameter[] parameters)
        {
            Container.ComponentRegistry.Register(
                RegistrationBuilder.ForType<TImplementation>().As<TService>().InstancePerLifetimeScope().CreateRegistration());

            return Container.Resolve<TService>(parameters);
        }

        /// <summary>
        /// Resolve the specified type in the container (register specified instance if needed)
        /// </summary>
        /// <typeparam name="TService">Service</typeparam>
        /// <returns>The instance resolved from container.</returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The component registry is responsible for registration disposal.")]
        public TService Provide<TService>(TService instance)
            where TService : class
        {
            Container.ComponentRegistry.Register(
                RegistrationBuilder.ForDelegate((c, p) => instance).InstancePerLifetimeScope().CreateRegistration());

            return Container.Resolve<TService>();
        }
    }
}


text:
package io.v.vdl.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface VdlStructOrUnionType extends VdlType {

  @NotNull
  List<VdlFieldDeclaration> getFieldDeclarationList();

  @Nullable
  PsiElement getLbrace();

  @Nullable
  PsiElement getRbrace();

  @Nullable
  PsiElement getStruct();

  @Nullable
  PsiElement getUnion();

}


text:
swift-hn
========

This is the swift version of my hacker news feed


text:
using System;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;

namespace QuantConnect.Tests.Common.Securities
{
    [TestFixture]
    public class AccountCurrencyImmediateSettlementModelTests
    {
        private static readonly DateTime Noon = new DateTime(2014, 6, 24, 12, 0, 0);
        private static readonly TimeKeeper TimeKeeper = new TimeKeeper(Noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });

        [Test]
        public void FundsAreSettledImmediately()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(null, securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            var model = new AccountCurrencyImmediateSettlementModel();
            var config = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
            );

            portfolio.SetCash(1000);
            Assert.AreEqual(1000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            var timeUtc = Noon.ConvertToUtc(TimeZones.NewYork);
            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, 1000);

            Assert.AreEqual(2000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, -500);

            Assert.AreEqual(1500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, 1000);

            Assert.AreEqual(2500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }

        [Test]
        public void FundsAreSettledInAccountCurrency()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(null, securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            var model = new AccountCurrencyImmediateSettlementModel();
            portfolio.SetCash(1000);
            portfolio.SetCash("EUR", 0, 1.1m);

            var config = CreateTradeBarConfig(Symbols.DE30EUR);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                portfolio.CashBook["EUR"],
                SymbolProperties.GetDefault("EUR"),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
            );

            Assert.AreEqual(1000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            var timeUtc = Noon.ConvertToUtc(TimeZones.NewYork);
            model.ApplyFunds(portfolio, security, timeUtc, "EUR", 1000);

            // 1000 + 1000 * 1.1 = 2100
            Assert.AreEqual(2100, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, "EUR", -500);

            // 2100 - 500 * 1.1 = 1550
            Assert.AreEqual(1550, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, "EUR", 1000);

            // 1550 + 1000 * 1.1 = 2650
            Assert.AreEqual(2650, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }

        private SubscriptionDataConfig CreateTradeBarConfig(Symbol symbol)
        {
            return new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
        }
    }
}


text:
/* global define */
// Note that we use the global require here because we need to
// update the global confirmation.

import {tryPromise} from "./kb_lib/Utils";
import {
    PluginConfig, PluginDefinition, PluginLoadConfig,
    PluginServiceDefinition, Runtime, Service, AMDRequire
} from "./types";

// TODO: a hack to override the node require definition built into TS
// TODO: there may be a compiler option to allow using AMD require?
declare var require: AMDRequire;

interface IframeInstallerConfig {
    usingSourceModules: boolean;
    root: string;
    iframePath: string;
}

interface LegacyInstallerConfig {
    usingSourceModules: boolean;
    root: string;
    moduleRoot: string;
    resourcesRoot: string;
}

interface PluginManagerConstructorParams {
    runtime: Runtime;
    moduleBase: string;
}

export class PluginManager {
    runtime: Runtime;
    moduleBase: string;
    services: Map<string, Service<any>>;

    constructor({runtime, moduleBase}: PluginManagerConstructorParams) {
        this.runtime = runtime;
        this.moduleBase = moduleBase || '/modules';
        this.services = new Map<string, Service<any>>();
    }

    installIntoService(
        pluralTypeName: string,
        serviceDefinition: PluginServiceDefinition,
        pluginDef: PluginDefinition,
        pluginConfig: PluginConfig
    ) {
        return tryPromise(() => {
            // weird, perhaps, way to strip off a terminal "s".
            const nameMatch = pluralTypeName.match(/(.*?)(:?(s)|($))$/);
            if (!nameMatch) {
                return;
            }
            const typeName = nameMatch[1];
            if (!this.runtime.hasService(typeName)) {
                console.error('missing service', typeName, serviceDefinition, pluginConfig);
                throw {
                    name: 'MissingService',
                    message: 'The requested service "' + typeName + '" was not registered in the plugin manager',
                    suggestion: 'This is a web app configuration issue, not a user error'
                };
            }

            // NB to avoid an empty call to installIntoService, just omit the
            // service from the install section.
            if (serviceDefinition) {
                const service = this.runtime.service(typeName);
                if (service.pluginHandler) {
                    return service.pluginHandler(serviceDefinition, pluginDef, pluginConfig);
                }
            }
        });
    }

    installLegacyPlugin(pluginLoadConfig: PluginLoadConfig, pluginConfig: PluginConfig) {
        // build up a list of modules and add them to the require config.
        return tryPromise(() => {
            const sourcePath = pluginLoadConfig.directory;

            let usingSourceModules = false;

            const installerConfig: LegacyInstallerConfig = {
                usingSourceModules,
                root: sourcePath,
                moduleRoot: sourcePath + '/modules',
                resourcesRoot: this.moduleBase + '/' + sourcePath + '/resources'
            };

            // Now install any ui service configuration.
            const serviceConfigs = pluginConfig.services || pluginConfig.install;
            if (!serviceConfigs) {
                return null;
            }

            return Promise.all(Object.entries(serviceConfigs)
                .map(([serviceName, serviceConfig]) => {
                    return this.installIntoService(serviceName, serviceConfig, installerConfig, pluginConfig);
                }));
        });

    }

    cacheBusterKey(buildInfo: any, developMode: boolean) {
        // NB developMode not implemented yet, so always defaults
        // to the gitCommitHash
        if (developMode) {
            return String(new Date().getTime());
        } else {
            return buildInfo.git.commitHash;
        }
    }

    cacheBuster() {
        // TODO: get develop mode from runtime
        return '?cb=' + this.cacheBusterKey(this.runtime.config('buildInfo'), false);
    }

    installIFramePlugin(pluginLoadConfig: PluginLoadConfig, pluginConfig: PluginConfig) {
        // build up a list of modules and add them to the require config.
        return tryPromise(() => {
            const pluginInstallerConfig: IframeInstallerConfig = {
                usingSourceModules: false,
                root: pluginLoadConfig.directory,
                iframePath: `${pluginLoadConfig.directory}/iframe_root/index.html` + this.cacheBuster()
            };

            // This overrides the plugin's own concept of plugin name with
            // the one provided in kbase-ui's name for the plugin, which is deri ved
            // from plugins.yml
            // This allows us to support loading the same plugin twice under different
            // names. This has very limited utility ... but is very useful when needed.
            // E.g. to load different versions of the same plugin for side by side
            // evaluation
            // TODO: come up with a better way of doing this!
            pluginConfig.package.name = pluginLoadConfig.name;

            // Now install any ui service configuration.
            const serviceConfigs = pluginConfig.services || pluginConfig.install;
            if (!serviceConfigs) {
                return null;
            }

            return Promise.all(Object.entries(serviceConfigs)
                .map(([serviceName, serviceConfig]) => {
                    return this.installIntoService(serviceName, serviceConfig, pluginInstallerConfig, pluginConfig);
                }));
        });
    }

    installPlugin(pluginLoadConfig: PluginLoadConfig, pluginConfig: PluginConfig) {
        // build up a list of modules and add them to the require config.
        return tryPromise(() => {
            // Plugin type - legacy or iframe.
            const pluginType = pluginConfig.package.type || 'iframe';

            switch (pluginType) {
                case 'legacy':
                    return this.installLegacyPlugin(pluginLoadConfig, pluginConfig);
                case 'iframe':
                    return this.installIFramePlugin(pluginLoadConfig, pluginConfig);
                default:
                    throw new Error('Unsupported plugin type: ' + pluginType);
            }
        });
    }

    /**
     *
     * @param {type} pluginDef
     * @returns {Promise}
     */
    loadPlugin(pluginLoadConfig: PluginLoadConfig) {
        if (pluginLoadConfig.disabled) {
            return;
        }
        return new Promise((resolve, reject) => {
            require([`yaml!${pluginLoadConfig.directory}/config.yml`], (pluginConfig: PluginConfig) => {
                this.installPlugin(pluginLoadConfig, pluginConfig)
                    .then(() => {
                        resolve(pluginLoadConfig);
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        });
    }

    installPlugins(pluginLoadConfigs: Map<string, PluginLoadConfig>) {
        const loaders = Array.from(pluginLoadConfigs, ([_pluginName, pluginLoadConfig]) => {
            return this.loadPlugin(pluginLoadConfig);
        });
        return Promise.all(loaders);
    }
}


text:
var CUI = CUI ? CUI : {};
CUI.Login = {};

$(document).ready(function() {

    CUI.Login.Events.register();

    $('#password_link').click(function(e){
        e.preventDefault();
        $('.card#password_reset').animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
    });
    $('#username_link').click(function(e){
        e.preventDefault();
        $('.card#username_recovery').animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
    });
    $('#password_reset_return_link').click(function(e){
        e.preventDefault();
        $('.card#password_reset').animate({ 'left' : '-360px' }, 'slow', function(){
            $(this).css('z-index', -1);
        });
    });
    $('#username_recovery_return_link').click(function(e){
        e.preventDefault();
        $('.card#username_recovery').animate({ 'left' : '-360px' }, 'slow', function(){
            $(this).css('z-index', -1);
        });
    });
    $('#login_btn').click(function(){
      CUI.Login.Actions.toggleSpinner();
    });
    $(document).bind("ajax:complete",
          function(evt, data, status, xhr){
            if(status == "success") {
              $('form .spinner').fadeOut('fast');
            }
          }
    );
    $('#username').focus();
});

CUI.Login.Actions = (function($){
    var show_password = function(input_field, input_reveal_field, show){
            var password;

            if( show ){
                password = input_field.val();
                input_field.hide();
                input_reveal_field.val(password).show();
            } else {
                password = input_reveal_field.val();
                input_reveal_field.hide();
                input_field.val(password).show();
            }
        },
        add_hash_input = function(parent){
            if (window.location.hash != "") {
                $('<input>').attr({
                    type: 'hidden',
                    id: 'hash_anchor',
                    name: 'hash_anchor',
                    value: window.location.hash
                }).appendTo(parent);
            }
        },
        interstitial_switcher_animation = function(num_orgs, redir_path){
          if(parseInt(num_orgs, 10) > 1){
            $('#interstitial').trigger({type:'login'});
          } else if(redir_path){
            CUI.Login.Actions.toggleSpinner();
            window.location.href = redir_path;
          } else {
            window.location.reload();
          }
        },
        toggleSpinner = function(){
          $('#login_form .spinner').fadeToggle('fast');
        },
        redirecter = function(url){
          if ($.browser.msie){
            window.location = url;
          } else {
            window.location.href = url;
          }
        };

    return {
        show_password   : show_password,
        add_hash_input  : add_hash_input,
        interstitial_switcher_animation : interstitial_switcher_animation,
        redirecter : redirecter,
        toggleSpinner : toggleSpinner
    };

})(jQuery);

CUI.Login.Events = (function($, actions){
    var register = function(){
            $('#reveal').change(function(){
                actions.show_password($('#password-input'), $('#password-input-reveal'), $(this).is(':checked'));
            });
            $('#login_form').live('submit', function(e) {
                actions.add_hash_input(this);
            });
            //if you have an #interstitial container for an interstitial, this will function. otherwise it won't.
            // this is for alchemy
            var interstitial = $('#interstitial');
            if (interstitial.length){
              $('#interstitial').bind('login', function(event){
                CUI.Login.Actions.toggleSpinner();
                interstitial.animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
              });
            }
        };
    return {
        register    : register
    }

})(jQuery, CUI.Login.Actions);


text:
require File.expand_path('../spec_helper', __FILE__)
require 'git-feats'
require 'faraday'

describe GitFeats::API do
  let(:klass) { GitFeats::API }
  subject { klass }

  describe ".upload_feats" do
    let(:meth)  { :upload_feats }
    subject     { klass.method(meth) }
    its(:arity) { should eq(-1) }

    # request mocks with faraday
    stubs = Faraday::Adapter::Test::Stubs.new do |stub|
      stub.post('/api/feats') {[200, {}, '{"message":"OK"}']}
    end

    test = Faraday.new do |builder|
      builder.adapter :test, stubs
    end

    it "display success if response is 200" do
      response = test.post('/api/feats')
    end
  end
end


text:
package v1

import (
	"fmt"
	"strings"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"kpt.dev/configsync/pkg/api/configmanagement"
)

// These comments must remain outside the package docstring.
// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// ClusterConfig is the top-level object for the config data definition.
//
// It holds a config defined for a single org unit (namespace).
type ClusterConfig struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// The actual object definition, per K8S object definition style.
	// +optional
	Spec ClusterConfigSpec `json:"spec,omitempty"`

	// The current status of the object, per K8S object definition style.
	// +optional
	Status ClusterConfigStatus `json:"status,omitempty"`
}

// ClusterConfigSpec defines the configs that will exist at the cluster level.
type ClusterConfigSpec struct {
	// Token indicates the version of the ClusterConfig last imported from the source of truth.
	// +optional
	Token string `json:"token,omitempty"`

	// ImportTime is the timestamp of when the ClusterConfig was updated by the Importer.
	// +optional
	ImportTime metav1.Time `json:"importTime,omitempty"`

	// Resources contains namespace scoped resources that are synced to the API server.
	// +optional
	Resources []GenericResources `json:"resources,omitempty"`
}

// ClusterConfigStatus contains fields that define the status of a ClusterConfig.
type ClusterConfigStatus struct {
	// Token indicates the version of the config that the Syncer last attempted to update from.
	// +optional
	Token string `json:"token,omitempty"`

	// SyncErrors contains any errors that occurred during the last attempt the Syncer made to update
	// resources from the ClusterConfig specs. This field will be empty on success.
	// +optional
	SyncErrors []ConfigManagementError `json:"syncErrors,omitempty"`

	// SyncTime is the timestamp of when the config resources were last updated by the Syncer.
	// +optional
	SyncTime metav1.Time `json:"syncTime,omitempty"`

	// SyncState is the current state of the config resources (eg synced, stale, error).
	// +optional
	SyncState ConfigSyncState `json:"syncState,omitempty"`

	// ResourceConditions contains health status of cluster-scope resources
	// +optional
	ResourceConditions []ResourceCondition `json:"resourceConditions,omitempty"`
}

// +kubebuilder:object:root=true

// ClusterConfigList holds a list of cluster level configs, returned as response to a List call on
// the cluster config hierarchy.
type ClusterConfigList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of configs that apply.
	Items []ClusterConfig `json:"items"`
}

// These comments must remain outside the package docstring.
// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// NamespaceConfig is the top-level object for the config data definition.
//
// It holds a config defined for a single org unit (namespace).
type NamespaceConfig struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata. The Name field of the config must match the namespace name.
	// +optional
	metav1.ObjectMeta `json:"metadata"`

	// The actual object definition, per K8S object definition style.
	// +optional
	Spec NamespaceConfigSpec `json:"spec,omitempty"`

	// The current status of the object, per K8S object definition style.
	// +optional
	Status NamespaceConfigStatus `json:"status,omitempty"`
}

// NamespaceConfigSpec contains all the information about a config linkage.
type NamespaceConfigSpec struct {
	// Token indicates the version of the NamespaceConfig last imported from the source of truth.
	// +optional
	Token string `json:"token,omitempty"`

	// ImportTime is the timestamp of when the NamespaceConfig was updated by the Importer.
	// +optional
	ImportTime metav1.Time `json:"importTime,omitempty"`

	// Resources contains namespace scoped resources that are synced to the API server.
	// +optional
	Resources []GenericResources `json:"resources,omitempty"`

	// DeleteSyncedTime is the time at which the importer identified the intent to delete
	// the corresponding Namespace
	// +optional
	DeleteSyncedTime metav1.Time `json:"deleteSyncedTime,omitempty"`
}

// NamespaceConfigStatus contains fields that define the status of a NamespaceConfig.
type NamespaceConfigStatus struct {
	// Token indicates the version of the config that the Syncer last attempted to update from.
	// +optional
	Token string `json:"token,omitempty"`

	// SyncErrors contains any errors that occurred during the last attempt the Syncer made to update
	// resources from the NamespaceConfig specs. This field will be empty on success.
	// +optional
	SyncErrors []ConfigManagementError `json:"syncErrors,omitempty"`

	// SyncTime is the timestamp of when the config resources were last updated by the Syncer.
	// +optional
	SyncTime metav1.Time `json:"syncTime,omitempty"`

	// SyncState is the current state of the config resources (eg synced, stale, error).
	// +optional
	SyncState ConfigSyncState `json:"syncState,omitempty"`

	// ResourceConditions contains health status of namespaced resources
	// +optional
	ResourceConditions []ResourceCondition `json:"resourceConditions,omitempty"`
}

// +kubebuilder:object:root=true

// NamespaceConfigList holds a list of NamespaceConfigs, as response to a List call on the config
// hierarchy API.
type NamespaceConfigList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of configs that apply.
	Items []NamespaceConfig `json:"items"`
}

// GenericResources contains API objects of a specified Group and Kind.
type GenericResources struct {
	// Group is the Group for all resources contained within
	// +optional
	Group string `json:"group,omitempty"`

	// Kind is the Kind for all resources contained within.
	Kind string `json:"kind"`

	// Versions is a list Versions corresponding to the Version for this Group and Kind.
	Versions []GenericVersionResources `json:"versions"` // Per version information.
}

// GenericVersionResources holds a set of resources of a single version for a Group and Kind.
type GenericVersionResources struct {
	// Version is the version of all objects in Objects.
	Version string `json:"version"`

	// Objects is the list of objects of a single Group Version and Kind.
	Objects []runtime.RawExtension `json:"objects"`
}

// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// ClusterSelector specifies a LabelSelector applied to clusters that exist within a
// cluster registry.
type ClusterSelector struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ObjectMeta `json:"metadata"`

	// The actual object definition, per K8S object definition style.
	Spec ClusterSelectorSpec `json:"spec"`
}

// ClusterSelectorSpec contains spec fields for ClusterSelector.
type ClusterSelectorSpec struct {
	// Selects clusters.
	// This field is NOT optional and follows standard label selector semantics. An empty selector
	// matches all clusters.
	Selector metav1.LabelSelector `json:"selector"`
}

// +kubebuilder:object:root=true

// ClusterSelectorList holds a list of ClusterSelector resources.
type ClusterSelectorList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of selectors.
	Items []ClusterSelector `json:"items"`
}

// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// NamespaceSelector specifies a LabelSelector applied to namespaces that exist within a
// NamespaceConfig hierarchy.
type NamespaceSelector struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata. The Name field of the config must match the namespace name.
	// +optional
	metav1.ObjectMeta `json:"metadata"`

	// The actual object definition, per K8S object definition style.
	Spec NamespaceSelectorSpec `json:"spec"`
}

// NamespaceSelectorSpec contains spec fields for NamespaceSelector.
type NamespaceSelectorSpec struct {
	// Selects namespaces.
	// This field is NOT optional and follows standard label selector semantics. An empty selector
	// matches all namespaces.
	Selector metav1.LabelSelector `json:"selector"`
}

// +kubebuilder:object:root=true

// NamespaceSelectorList holds a list of NamespaceSelector resources.
type NamespaceSelectorList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of NamespaceSelectors.
	Items []NamespaceSelector `json:"items"`
}

// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// Sync is used for configuring sync of generic resources.
type Sync struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata. The Name field of the config must match the namespace name.
	// +optional
	metav1.ObjectMeta `json:"metadata"`

	// Spec is the standard spec field.
	Spec SyncSpec `json:"spec"`

	// Status is the status for the sync declaration.
	Status SyncStatus `json:"status,omitempty"`
}

// NewSync creates a sync object for consumption by the syncer, this will only populate the
// group and kind as those are the only fields the syncer presently consumes.
func NewSync(gk schema.GroupKind) *Sync {
	var name string
	if gk.Group == "" {
		name = strings.ToLower(gk.Kind)
	} else {
		name = fmt.Sprintf("%s.%s", strings.ToLower(gk.Kind), gk.Group)
	}
	return &Sync{
		TypeMeta: metav1.TypeMeta{
			APIVersion: SchemeGroupVersion.String(),
			Kind:       configmanagement.SyncKind,
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Spec: SyncSpec{
			Group: gk.Group,
			Kind:  gk.Kind,
		},
	}
}

// SyncSpec specifies the sync declaration which corresponds to an API Group and contained
// kinds and versions.
type SyncSpec struct {
	// Group is the group, for example configmanagement.gke.io or rbac.authorization.k8s.io
	Group string `json:"group"` // group, eg configmanagement.gke.io
	// Kind is the string that represents the Kind for the object as given in TypeMeta, for example
	// ClusterRole, Namespace or Deployment.
	Kind string `json:"kind"`
	// HierarchyMode specifies how the object is treated when it appears in an abstract namespace.
	// The default is "inherit", meaning objects are inherited from parent abstract namespaces.
	// If set to "none", the type is not allowed in Abstract Namespaces.
	// +optional
	HierarchyMode HierarchyModeType `json:"hierarchyMode,omitempty"`
}

// SyncStatus represents the status for a sync declaration
type SyncStatus struct {
	// Status indicates the state of the sync.  One of "syncing", or "error".  If "error" is specified
	// then Error will be populated with a message regarding the error.
	Status SyncState `json:"status"`
	// Message indicates a message associated with the status.
	// +optional
	Message string `json:"message,omitempty"`
}

// +kubebuilder:object:root=true

// SyncList holds a list of Sync resources.
type SyncList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of sync declarations.
	Items []Sync `json:"items"`
}

// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// Repo holds configuration and status about the Nomos source of truth.
type Repo struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// +optional
	Spec RepoSpec `json:"spec,omitempty"`

	// +optional
	Status RepoStatus `json:"status,omitempty"`
}

// RepoSpec contains spec fields for Repo.
type RepoSpec struct {
	// Repo version string, corresponds to how the config importer should handle the directory
	// structure (implicit assumptions).
	Version string `json:"version"`
}

// RepoStatus contains status fields for Repo.
type RepoStatus struct {
	// +optional
	Source RepoSourceStatus `json:"source,omitempty"`

	// +optional
	Import RepoImportStatus `json:"import,omitempty"`

	// +optional
	Sync RepoSyncStatus `json:"sync,omitempty"`
}

// RepoSourceStatus contains status fields for the Repo's source of truth.
type RepoSourceStatus struct {
	// Most recent version token seen in the source of truth (eg the repo). This token is updated as
	// soon as the config importer sees a new change in the repo.
	// +optional
	Token string `json:"token,omitempty"`

	// Errors is a list of any errors that occurred while reading from the source of truth.
	// +optional
	Errors []ConfigManagementError `json:"errors,omitempty"`
}

// RepoImportStatus contains status fields for the import of the Repo.
type RepoImportStatus struct {
	// Most recent version token imported from the source of truth into Nomos CRs. This token is
	// updated once the importer finishes processing a change, whether or not there were errors
	// during the import.
	// +optional
	Token string `json:"token,omitempty"`

	// LastUpdate is the timestamp of when this status was updated by the Importer.
	// +optional
	LastUpdate metav1.Time `json:"lastUpdate,omitempty"`

	// Errors is a list of any errors that occurred while performing the most recent import indicated
	// by Token.
	// +optional
	Errors []ConfigManagementError `json:"errors,omitempty"`
}

// RepoSyncStatus contains status fields for the sync of the Repo.
type RepoSyncStatus struct {
	// LatestToken is the most recent version token synced from the source of truth to managed K8S
	// resources. This token is updated as soon as the syncer starts processing a new change, whether
	// or not it has finished processing or if there were errors during the sync.
	// +optional
	LatestToken string `json:"latestToken,omitempty"`

	// LastUpdate is the timestamp of when this status was updated by the Importer.
	// +optional
	LastUpdate metav1.Time `json:"lastUpdate,omitempty"`

	// InProgress is a list of changes that are currently being synced. Each change may or may not
	// have associated errors.
	// +optional
	InProgress []RepoSyncChangeStatus `json:"inProgress,omitempty"`

	ResourceConditions []ResourceCondition `json:"resourceConditions,omitempty"`
}

// ResourceCondition represents the sync status of the resource
type ResourceCondition struct {
	GroupVersion   string                 `json:"groupVersion,omitempty"`
	Kind           string                 `json:"kind,omitempty"`
	NamespacedName string                 `json:"namespacedName,omitempty"`
	ResourceState  ResourceConditionState `json:"resourceState,omitempty"`
	Token          string                 `json:"token,omitempty"`

	// These fields match the proposed conditions/annotations for status.
	ReconcilingReasons []string `json:"reconcilingReasons,omitempty"`
	Errors             []string `json:"errors,omitempty"`
}

// RepoSyncChangeStatus represents the status of a single change being synced in the Repo.
type RepoSyncChangeStatus struct {
	// Token is the version token for the change being synced from the source of truth to managed K8S
	// resources.
	// +optional
	Token string `json:"token,omitempty"`

	// Errors is a list of any errors that occurred while syncing the resources changed for the
	// version token above.
	// +optional
	Errors []ConfigManagementError `json:"errors,omitempty"`
}

// ConfigManagementError represents an error that occurs during the management of configs. It is
// typically produced when processing the source of truth, importing a config, or syncing a K8S
// resource.
type ConfigManagementError struct {
	// ErrorResource is unused and should be removed when we uprev the API version.
	ErrorResource `json:",inline"`

	// Code is the error code of this particualr error.  Error codes are numeric strings,
	// like "1012".
	// +optional
	Code string `json:"code"`

	// ErrorMessage describes the error that occurred.
	// +optional
	ErrorMessage string `json:"errorMessage,omitempty"`

	// ErrorResourcs describes the resources associated with this error, if any.
	ErrorResources []ErrorResource `json:"errorResources,omitempty"`
}

// ErrorResource contains the identification bits of a single resource that is involved in
// a resource error.
type ErrorResource struct {
	// SourcePath is the repo-relative slash path to where the config is defined. This field may be
	// empty for errors that are not associated with a specific config file.
	// +optional
	SourcePath string `json:"sourcePath,omitempty"`

	// ResourceName is the name of the affected K8S resource. This field may be empty for errors that
	// are not associated with a specific resource.
	// +optional
	ResourceName string `json:"resourceName,omitempty"`

	// ResourceNamespace is the namespace of the affected K8S resource. This field may be empty for
	// errors that are associated with a cluster-scoped resource or not associated with a specific
	// resource.
	// +optional
	ResourceNamespace string `json:"resourceNamespace,omitempty"`

	// ResourceGVK is the GroupVersionKind of the affected K8S resource. This field may be empty for
	// errors that are not associated with a specific resource.
	// +optional
	ResourceGVK schema.GroupVersionKind `json:"resourceGVK"`
}

// +kubebuilder:object:root=true

// RepoList holds a list of Repo resources.
type RepoList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of Repo declarations.
	Items []Repo `json:"items"`
}

// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true

// HierarchyConfig is used for configuring the HierarchyModeType for managed resources.
type HierarchyConfig struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata. The Name field of the config must match the namespace name.
	// +optional
	metav1.ObjectMeta `json:"metadata"`

	// Spec is the standard spec field.
	Spec HierarchyConfigSpec `json:"spec"`
}

// +kubebuilder:object:root=true

// HierarchyConfigList holds a list of HierarchyConfig resources.
type HierarchyConfigList struct {
	metav1.TypeMeta `json:",inline"`

	// Standard object's metadata.
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`

	// Items is a list of HierarchyConfigs.
	Items []HierarchyConfig `json:"items"`
}

// HierarchyConfigSpec specifies the HierarchyConfigResources.
type HierarchyConfigSpec struct {
	Resources []HierarchyConfigResource `json:"resources"`
}

// HierarchyConfigResource specifies the HierarchyModeType based on the matching Groups and Kinds enabled.
type HierarchyConfigResource struct {
	// Group is the name of the APIGroup that contains the resources.
	// +optional
	Group string `json:"group,omitempty"`
	// Kinds is a list of kinds this rule applies to.
	// +optional
	Kinds []string `json:"kinds,omitempty"`
	// HierarchyMode specifies how the object is treated when it appears in an abstract namespace.
	// The default is "inherit", meaning objects are inherited from parent abstract namespaces.
	// If set to "none", the type is not allowed in Abstract Namespaces.
	// +optional
	HierarchyMode HierarchyModeType `json:"hierarchyMode,omitempty"`
}


text:
/*
  **********************************************************
  * OPAQUE NAVBAR SCRIPT
  **********************************************************
  */

  // Toggle tranparent navbar when the user scrolls the page

  $(window).scroll(function() {
    if($(this).scrollTop() > 450)  /*height in pixels when the navbar becomes non opaque*/
    {
        $('.opaque-navbar').addClass('opaque');
    } else {
        $('.opaque-navbar').removeClass('opaque');
    }
});

$(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});

/**
 * Automatically executed if DOM is ready
 */
$(function() {
    $('a[href*=#]').anchor({
        transitionDuration : 1200
    });
});

/**
 * anchor.js - jQuery Plugin
 * Jump to a specific section smoothly
 *
 * @dependencies	jQuery v1.5.0 http://jquery.com
 * @author			Cornel Boppart <cornel@bopp-art.com>
 * @copyright		Author

 * @version		1.0.5 (02/11/2014)
 */

;(function ($) {

	window.anchor = {

		/**
		 * Default settings
		 *
		 */
		settings: {
			transitionDuration: 2000,
			transitionTimingFunction: 'swing',
			labels: {
				error: 'Couldn\'t find any section'
			}
		},

		/**
		 * Initializes the plugin
		 *
		 * @param	{object}	options	The plugin options (Merged with default settings)
		 * @return	{object}	this	The current element itself
		 */
		init: function (options) {
			// Apply merged settings to the current object
			$(this).data('settings', $.extend(anchor.settings, options));

			return this.each(function () {
				var $this = $(this);

				$this.unbind('click').click(function (event) {
					event.preventDefault();
					anchor.jumpTo(
						anchor.getTopOffsetPosition($this),
						$this.data('settings')
					);
				});
			});
		},

		/**
		 * Gets the top offset position
		 *
		 * @param	{object}	$object				The root object to get sections position from
		 * @return	{int}		topOffsetPosition	The top offset position
		 */
		getTopOffsetPosition: function ($object) {
			var href = $object.attr('href'),
				$section = $($(href).get(0)),
				documentHeight = $(document).height(),
				browserHeight = $(window).height();

			if (!$section || $section.length < 1) {
				throw new ReferenceError(anchor.settings.labels.error);
			}

			if (($section.offset().top + browserHeight) > documentHeight) {
				return documentHeight - browserHeight;
			} else {
				return $section.offset().top;
			}
		},

		/**
		 * Jumps to the specific position
		 *
		 * @param	{int}		topOffsetPosition	The top offset position
		 * @param	{object}	settings			The object specific settings
		 * @return	{void}
		 */
		jumpTo: function (topOffsetPosition, settings) {
			var $viewport = $('html, body');

			$viewport.animate(
				{scrollTop: topOffsetPosition},
				settings.transitionDuration,
				settings.transitionTimingFunction
			);

				// Stop the animation immediately, if a user manually scrolls during the animation.
			$viewport.bind('scroll mousedown DOMMouseScroll mousewheel keyup', function(event){
				if (event.which > 0 || event.type === 'mousedown' || event.type === 'mousewheel') {
					$viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
				}
			});
		}

	};

	$.fn.anchor = function (method) {
			// Method calling logic
		if (anchor[method]) {
			return anchor[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return anchor.init.apply(this, arguments);
		} else {
			return $.error('Method ' + method + ' does not exist on jQuery.anchor');
		}
	};

})(jQuery);

//auto expand textarea
function adjust_textarea(h) {
    h.style.height = "20px";
    h.style.height = (h.scrollHeight)+"px";
}

//for map
var myCenter=new google.maps.LatLng(27.703466,85.3111983);
function initialize()
{
var mapProp = {
  center:myCenter,
  zoom:15,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };

var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

var marker=new google.maps.Marker({
  position:myCenter,
  animation:google.maps.Animation.BOUNCE
  });

marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);


text:
package org.apache.samza.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

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

import org.apache.samza.Partition;
import org.apache.samza.system.SystemStreamPartition;
import org.apache.samza.system.SystemStreamMetadata;
import org.junit.Test;

public class TestSinglePartitionWithoutOffsetsSystemAdmin {
  @Test
  public void testShouldGetASinglePartition() {
    SinglePartitionWithoutOffsetsSystemAdmin admin = new SinglePartitionWithoutOffsetsSystemAdmin();
    Set<String> streamNames = new HashSet<String>();
    streamNames.add("a");
    streamNames.add("b");

    Map<String, SystemStreamMetadata> metadata = admin.getSystemStreamMetadata(streamNames);
    assertEquals(2, metadata.size());
    SystemStreamMetadata metadata1 = metadata.get("a");
    SystemStreamMetadata metadata2 = metadata.get("b");

    assertEquals(1, metadata1.getSystemStreamPartitionMetadata().size());
    assertEquals(1, metadata2.getSystemStreamPartitionMetadata().size());
    assertNull(metadata.get(new SystemStreamPartition("test-system", "c", new Partition(0))));
  }
}


text:
<resources>

    <!-- Application theme. -->
    <style name="AppTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#FC4C02</item>
        <item name="android:titleTextStyle">@style/myTheme.ActionBar.Text</item>
    </style>

    <style name="myTheme.ActionBar.Text" parent="@android:style/TextAppearance">
        <item name="android:textColor">#FFFFFF</item>
    </style>

</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="darkGray">#979797</color>
    <color name="coolRed">#F15369</color>
    <color name="transCoolRed">#00F15369</color>
    <color name="lightGray">#F8F7F3</color>
    <color name="offBlack">#101820</color>
    <color name="offWhite">#FAFAFA</color>
</resources>


text:
@extends('selmarinel_admin::admin.layouts.edit')
@section('title_name', 'Проекта')

@section('form_body')

        Аватар

 Выбрать обложку

            <input type="file" name="cover" class="hidden" id="selectCover">
            getCover()}}" style="width:250px" class="img-rounded">

        Название
        <input name="title" type="text" value="{{$model->title}}" class="form-control">

        Описание
        <textarea name="description" class="form-control" id="edit">{{$model->description}}</textarea>

Добавить Галерею

                    @foreach($model->files as $file)

id}}' class='elementPhoto col-md-2 col-sm-4 col-xs-6 panel grid-item'>
                            getCover()}}' class='img-responsive'>

                                         Удалить фото

                            <input class='form-control' name='photo_ids[]' type='hidden' value='{{$file->id}}'>

                    @endforeach

                     Добавить фото

                        {!! Form::file('file_photo', ['class' => 'hidden', 'id' => 'coverInput']) !!}

@endsection

@section('script')
    <link href="{{$app['selmarinel_admin.assets']->getPath('js/lib/froala_editor/css/froala_editor.min.css')}}" rel="stylesheet" type="text/css">
    <link href="{{$app['selmarinel_admin.assets']->getPath('js/lib/froala_editor/css/froala_style.min.css')}}" rel="stylesheet" type="text/css">
    <link href="{{$app['selmarinel_admin.assets']->getPath('js/lib/froala_editor/css/themes/gray.min.css')}}" rel="stylesheet" type="text/css">

@endsection