text:
export default function makeActionCreator(type, ...argNames) {
    return function(...args) {
        let action = { type }
        argNames.forEach((arg, index) => {
            action[argNames[index]] = args[index]
        })
        return action
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Mopsis\Contracts\Traits;

use Mopsis\Core\App;
use Mopsis\Core\Auth;

trait LoggableTrait
{
    public function logChanges($message = null)
    {
        if ($this->exists && !count($this->getDirty())) {
            return $this;
        }

        $event = App::make('Event', [
            'message' => $message ?: $this->traceAction(),
            'values'  => json_encode($this->getDiff())
        ]);

        $event->user()->associate(Auth::user());
        $this->events()->save($event);

        return $this;
    }

    protected function getDiff()
    {
        $diff = [];

        foreach ($this->getDirty() as $field => $newValue) {
            $oldValue = $this->getOriginal($field);

            if ($oldValue !== $newValue) {
                $diff[$field] = $newValue;
            }
        }

        /**
         * @noinspection PhpUndefinedClassConstantInspection
         */
        return array_diff_key($diff, array_fill_keys([
            $this->getKeyName(),
            static::CREATED_AT,
            static::UPDATED_AT,
            static::DELETED_AT
        ], null));
    }

    protected function traceAction()
    {
        foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) {
            if (preg_match('/^Controllers\\\\(\w+)/', $frame['class'], $m)) {
                return $m[1] . '.' . $frame['function'];
            }
        }

        return;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HTML5 event manager</title>
    <meta name="description" content="A simple HTML5 event manager widget for 3WEB Supinfo courses" />
    <link rel="stylesheet" href="style.css"/>

HTML5 event manager

            <fieldset>
                <legend>Create a new event</legend>

                <form action="." method="get" id="event-form">

Name: <input type="text" name="name" required/>

Start date: <input type="date" name="startDate" required/>

End date: <input type="date" name="endDate" required/>

City: <input type="text" name="city" required/>

Postal code: <input type="text" name="postalCode" required/>

Box number: <input type="number" name="boxNumber" required/>

Street: <input type="text" name="street" required/>

<input type="submit" value="Create"/>

                </form>
            </fieldset>

            <fieldset>
                <legend id="hd">Confirm event</legend>

                <form action="." method="get" id="confirm">

Event summary

Event name

Start date: <time datetime="2016-04-21" itemprop="startDate" content="2016-04-21T20:00">2016-04-21</time>

End date : <time datetime="2016-04-22" itemprop="endDate" content="2016-04-22T20:00">2016-04-22</time>

                                Mountain View,
                                94043
                                2
                                1600 Amphitheatre Pkwy

                        <input type="submit" value="Confirm" />

                </form>
            </fieldset>


text:
aggregators Package
===================

:mod:`base` Module
------------------

.. automodule:: stream_framework.aggregators.base
    :members:
    :undoc-members:
    :show-inheritance:


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'ruboty/kihon'


text:
package com.micmiu.framework.web.v1.base.vo;

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

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * 分页查询对象
 *
 * @param <T>
 * @author Michael Sun
 */
public abstract class AbstractPagedQuery<T> {

	/**
	 * 查询条件:查询起始纪录位置.
	 */
	private int page = 1;
	/**
	 * 分页条件:一页的记录条数.
	 */
	private int rows = DEFAULT_ITEMS_PERPAGE;

	/**
	 * 排序字段
	 */
	private String sortName;

	/**
	 * 默认一页显示的记录数.
	 */
	private static final int DEFAULT_ITEMS_PERPAGE = 15;

	/**
	 * 查询的结果集合.
	 */
	private List<T> queryResults;

	/**
	 * 查询结果,总共条目个数.
	 */
	private long totalCount = -1;

	/**
	 * @return the rp
	 */
	public int getRp() {
		return rows;
	}

	/**
	 * @param rp the rp to set
	 */
	public void setRows(int rp) {
		this.rows = rp;
	}

	/**
	 * @return the page
	 */
	public int getPage() {
		return page;
	}

	/**
	 * @param page the page to set
	 */
	public void setPage(int page) {
		this.page = page;
	}

	/**
	 * @return the start 起始记录
	 */
	public int getStart() {
		return (page - 1) * rows;
	}

	public int getEnd() {
		return page * rows;
	}

	/**
	 * @return Returns the queryResults.
	 */
	public List<T> getQueryResults() {
		return queryResults;
	}

	/**
	 * @param pQueryResults The queryResults to set.
	 */
	public void setQueryResults(List<T> pQueryResults) {
		this.queryResults = pQueryResults;
	}

	/**
	 * @return Returns the totalCount.
	 */
	public long getTotalCount() {
		return totalCount;
	}

	/**
	 * @param pTotalCount The totalCount to set.
	 */
	public void setTotalCount(long pTotalCount) {
		this.totalCount = pTotalCount;
	}

	public Query buildQuery(Session session, boolean isQueryTotalCount) {
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(buildSQL(queryParams,
				isQueryTotalCount));

		Query query = session.createQuery(sql.toString());
		// 设置查询参数
		for (Entry<String, Object> entry : queryParams.entrySet()) {
			query.setParameter(entry.getKey(), queryParams.get(entry.getKey()));
		}
		return query;

	}

	/**
	 * 构造分页查询语句
	 *
	 * @param queryParams
	 * @param isQueryTotalCount
	 * @return
	 */
	public abstract String buildSQL(HashMap<String, Object> queryParams,
									boolean isQueryTotalCount);

	public String getSortName() {
		return sortName;
	}

	public void setSortName(String sortName) {
		this.sortName = sortName;
	}

	/**
	 * 根据pageSize与rp计算总页数, 默认值为-1.
	 */
	public long getTotalPages() {
		if (totalCount < 0) {
			return -1;
		}

		long count = totalCount / rows;
		if (totalCount % rows > 0) {
			count++;
		}
		return count;
	}

	/**
	 * 是否还有下一页.
	 */
	public boolean isHasNext() {
		return (page + 1 <= getTotalPages());
	}

	/**
	 * 取得下页的页号, 序号从1开始. 当前页为尾页时仍返回尾页序号.
	 */
	public int getNextPage() {
		if (isHasNext()) {
			return page + 1;
		} else {
			return page;
		}
	}

	/**
	 * 是否还有上一页.
	 */
	public boolean isHasPre() {
		return (page - 1 >= 1);
	}

	/**
	 * 取得上页的页号, 序号从1开始. 当前页为首页时返回首页序号.
	 */
	public int getPrePage() {
		if (isHasPre()) {
			return page - 1;
		} else {
			return page;
		}
	}

}


text:
namespace FFHelper.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ModifiedTeamDropDownAgain : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed" >

    <LinearLayout
        android:id="@+id/ll_emoji_type_container"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignParentBottom="true"
        android:divider="@drawable/widget_divider"
        android:orientation="horizontal"
        android:background="#ccced2"
        android:showDividers="middle" >

        <TextView
            android:id="@+id/btn_default"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:background="#ededed"
            android:text="@string/widget_emoji_default"
            android:textColor="#686868"
            android:textSize="14sp" />

        <View
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:background="@drawable/widget_divider" />
        <TextView
            android:id="@+id/btn_text_emoji"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:button="@null"
            android:gravity="center"
            android:background="#ccced2"
            android:text="颜表情"
            android:textColor="#686868"
            android:textSize="14sp" />

        <View
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="3"/>
    </LinearLayout>

    <View
        android:id="@+id/view_divider_bottom"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_above="@id/ll_emoji_type_container"
        android:background="@drawable/widget_divider" />

    <LinearLayout
        android:id="@+id/ll_dots"
        android:layout_width="match_parent"
        android:layout_height="24dip"
        android:layout_above="@id/view_divider_bottom"
        android:gravity="center"
        android:orientation="horizontal" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_contains"
        android:paddingTop="20dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:layout_above="@id/ll_dots"/>
    <android.support.v4.view.ViewPager
        android:id="@+id/text_vp_contains"
        android:visibility="gone"
        android:paddingTop="20dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:layout_above="@id/ll_dots"/>

</RelativeLayout>


text:
package com.tesco.bootcamp.orderreview;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class WebApplicationConfiguration {

    @Value("${customerAPI.url}")
    private String customerServiceURL;

    @Bean(name = "customerServiceURL")
    public String customerServiceURLMethod(){
        return customerServiceURL;
    }

    @Value("${orderAPI.url}")
    private String orderServiceURL;

    @Bean(name = "orderServiceURL")
    public String orderServiceURLMethod(){
        return orderServiceURL;
    }

    @Value("${orderStatusAPI.url}")
    private String orderStatusServiceURL;

    @Bean(name = "orderStatusServiceURL")
    public String orderStatusServiceURLMethod(){
        return orderStatusServiceURL;
    }

    @SuppressWarnings("SameReturnValue")
    @Bean(name = "dummy")
    @Primary
    public String dummy(){
        return "";
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(clientHttpRequestFactory());
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(5000);
        return factory;
    }

}


text:
@interface CTNavigationController : UINavigationController

@end


text:
/**
 * The sample illustrates rules to resolve conflicts between inheritance
 * candidates with default methods. There are two simple rules:
 *

 *
Class wins. If the superclass has a concrete or abstract declaration of
 * this method, then it is preferred over all defaults.

 *
Subtype wins. If an interface extends another interface, and both provide
 * a default, then the more specific interface wins.

 *

 */
public class Inheritance {

    /**
     * The behavior of an creature that can swim
     */
    public interface Swimable {

        /**
         * Return string representation of the swim action for a creature that
         * can swim
         *
         * @return string representation of the swim action for a creature
         * that can swim
         */
        default String swim() {
            return "I can swim.";
        }
    }

    /**
     * The abstract class that overrides {@link #swim} method
     */
    public abstract static class Fish implements Swimable {

        /**
         * Return string representation of the swim action for a fish
         *
         * @return string representation of the swim action for a fish
         */
        @Override
        public String swim() {
            return this.getClass().getSimpleName() + " swims under water";
        }
    }

    /**
     * This class is used for the illustration rule of 1. See the source code
     * of the {@link #main} method.
     *

     *      System.out.println(new Tuna().swim()); //"Tuna swims under water" output is suspected here
     *

     */
    public static class Tuna extends Fish implements Swimable {
    }

    /**
     * The behavior of an creature that can dive: the interface that overrides
     * {@link #swim} method (subtype of {@link Swimable})
     */
    public interface Diveable extends Swimable {

        /**
         * Return string representation of the swim action for a creature that
         * can dive
         *
         * @return string representation of the swim action for a creature
         * that can dive
         */
        @Override
        default String swim() {
            return "I can swim on the surface of the water.";
        }

        /**
         * Return string representation of the dive action for a creature that
         * can dive
         *
         * @return string representation of the dive action for a creature
         * that can dive
         */
        default String dive() {
            return "I can dive.";
        }
    }

    /**
     * This class is used for the illustration of rule 2. See the source code
     * of the {@link #main} method
     *

     *      //"I can swim on the surface of the water." output is suspected here
     *      System.out.println(new Duck().swim());
     *

     */
    public static class Duck implements Swimable, Diveable {
    }

    /**
     * Illustrate behavior of the classes: {@link Tuna} and {@link Duck}
     *
     * @param args command line arguments
     */
    public static void main(final String[] args) {
        // Illustrates rule 1. The Fish.swim() implementation wins
        //"Tuna swims under water" is output
        System.out.println(new Tuna().swim());

        // Illustrates rule 2. The Diveable.swim() implementation wins
        //"I can swim on the surface of the water." is output
        System.out.println(new Duck().swim());
    }
}


text:
// FastNBT.h

// Interfaces to the fast NBT parser and writer

/*
The fast parser parses the data into a vector of cFastNBTTag structures. These structures describe the NBT tree,
but themselves are allocated in a vector, thus minimizing reallocation.
The structures have a minimal constructor, setting all member "pointers" to "invalid".

The fast writer doesn't need a NBT tree structure built beforehand, it is commanded to open, append and close tags
(just like XML); it keeps the internal tag stack and reports errors in usage.
It directly outputs a string containing the serialized NBT data.
*/

#pragma once

#include "../Endianness.h"

enum eTagType
{
	TAG_Min       = 0,  // The minimum value for a tag type
	TAG_End       = 0,
	TAG_Byte      = 1,
	TAG_Short     = 2,
	TAG_Int       = 3,
	TAG_Long      = 4,
	TAG_Float     = 5,
	TAG_Double    = 6,
	TAG_ByteArray = 7,
	TAG_String    = 8,
	TAG_List      = 9,
	TAG_Compound  = 10,
	TAG_IntArray  = 11,
	TAG_Max       = 11,  // The maximum value for a tag type
} ;

/** This structure is used for all NBT tags.
It contains indices to the parent array of tags, building the NBT tree this way.
Also contains indices into the data stream being parsed, used for values;
NO dynamically allocated memory is used!
Structure (all with the tree structure it describes) supports moving in memory (std::vector reallocation)
*/
struct cFastNBTTag
{
public:

	eTagType m_Type;

	// The following members are indices into the data stream. m_DataLength == 0 if no data available
	// They must not be pointers, because the datastream may be copied into another AString object in the meantime.
	int m_NameStart;
	int m_NameLength;
	int m_DataStart;
	int m_DataLength;

	// The following members are indices into the array returned; -1 if not valid
	// They must not be pointers, because pointers would not survive std::vector reallocation
	int m_Parent;
	int m_PrevSibling;
	int m_NextSibling;
	int m_FirstChild;
	int m_LastChild;

	cFastNBTTag(eTagType a_Type, int a_Parent) :
		m_Type(a_Type),
		m_NameLength(0),
		m_DataLength(0),
		m_Parent(a_Parent),
		m_PrevSibling(-1),
		m_NextSibling(-1),
		m_FirstChild(-1),
		m_LastChild(-1)
	{
	}

	cFastNBTTag(eTagType a_Type, int a_Parent, int a_PrevSibling) :
		m_Type(a_Type),
		m_NameLength(0),
		m_DataLength(0),
		m_Parent(a_Parent),
		m_PrevSibling(a_PrevSibling),
		m_NextSibling(-1),
		m_FirstChild(-1),
		m_LastChild(-1)
	{
	}
} ;

/** Parses and contains the parsed data
Also implements data accessor functions for tree traversal and value getters
The data pointer passed in the constructor is assumed to be valid throughout the object's life. Care must be taken not to initialize from a temporary.
The parser decomposes the input data into a tree of tags that is stored as an array of cFastNBTTag items,
and accessing the tree is done by using the array indices for tags. Each tag stores the indices for its parent,
first child, last child, prev sibling and next sibling, a value of -1 indicates that the indice is not valid.
Each primitive tag also stores the length of the contained data, in bytes.
*/
class cParsedNBT
{
public:
	cParsedNBT(const char * a_Data, int a_Length);

	bool IsValid(void) const {return m_IsValid; }

	/** Returns the root tag of the hierarchy. */
	int GetRoot(void) const {return 0; }

	/** Returns the first child of the specified tag, or -1 if none / not applicable. */
	int GetFirstChild (int a_Tag) const { return m_Tags[(size_t)a_Tag].m_FirstChild; }

	/** Returns the last child of the specified tag, or -1 if none / not applicable. */
	int GetLastChild  (int a_Tag) const { return m_Tags[(size_t)a_Tag].m_LastChild; }

	/** Returns the next sibling of the specified tag, or -1 if none. */
	int GetNextSibling(int a_Tag) const { return m_Tags[(size_t)a_Tag].m_NextSibling; }

	/** Returns the previous sibling of the specified tag, or -1 if none. */
	int GetPrevSibling(int a_Tag) const { return m_Tags[(size_t)a_Tag].m_PrevSibling; }

	/** Returns the length of the tag's data, in bytes.
	Not valid for Compound or List tags! */
	int GetDataLength (int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type != TAG_List);
		ASSERT(m_Tags[(size_t)a_Tag].m_Type != TAG_Compound);
		return m_Tags[(size_t)a_Tag].m_DataLength;
	}

	/** Returns the data stored in this tag.
	Not valid for Compound or List tags! */
	const char * GetData(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type != TAG_List);
		ASSERT(m_Tags[(size_t)a_Tag].m_Type != TAG_Compound);
		return m_Data + m_Tags[(size_t)a_Tag].m_DataStart;
	}

	/** Returns the direct child tag of the specified name, or -1 if no such tag. */
	int FindChildByName(int a_Tag, const AString & a_Name) const
	{
		return FindChildByName(a_Tag, a_Name.c_str(), a_Name.length());
	}

	/** Returns the direct child tag of the specified name, or -1 if no such tag. */
	int FindChildByName(int a_Tag, const char * a_Name, size_t a_NameLength = 0) const;

	/** Returns the child tag of the specified path (Name1\Name2\Name3...), or -1 if no such tag. */
	int FindTagByPath(int a_Tag, const AString & a_Path) const;

	eTagType GetType(int a_Tag) const { return m_Tags[(size_t)a_Tag].m_Type; }

	/** Returns the children type for a List tag; undefined on other tags. If list empty, returns TAG_End. */
	eTagType GetChildrenType(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_List);
		return (m_Tags[(size_t)a_Tag].m_FirstChild < 0) ? TAG_End : m_Tags[(size_t)m_Tags[(size_t)a_Tag].m_FirstChild].m_Type;
	}

	/** Returns the value stored in a Byte tag. Not valid for any other tag type. */
	inline unsigned char GetByte(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Byte);
		return (unsigned char)(m_Data[(size_t)m_Tags[(size_t)a_Tag].m_DataStart]);
	}

	/** Returns the value stored in a Short tag. Not valid for any other tag type. */
	inline Int16 GetShort(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Short);
		return GetBEShort(m_Data + m_Tags[(size_t)a_Tag].m_DataStart);
	}

	/** Returns the value stored in an Int tag. Not valid for any other tag type. */
	inline Int32 GetInt(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Int);
		return GetBEInt(m_Data + m_Tags[(size_t)a_Tag].m_DataStart);
	}

	/** Returns the value stored in a Long tag. Not valid for any other tag type. */
	inline Int64 GetLong(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Long);
		return NetworkToHostLong8(m_Data + m_Tags[(size_t)a_Tag].m_DataStart);
	}

	/** Returns the value stored in a Float tag. Not valid for any other tag type. */
	inline float GetFloat(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Float);

		// Cause a compile-time error if sizeof(float) != 4
		// If your platform produces a compiler error here, you'll need to add code that manually decodes 32-bit floats
		char Check1[5 - sizeof(float)];  // Fails if sizeof(float) > 4
		char Check2[sizeof(float) - 3];  // Fails if sizeof(float) < 4
		UNUSED(Check1);
		UNUSED(Check2);

		Int32 i = GetBEInt(m_Data + m_Tags[(size_t)a_Tag].m_DataStart);
		float f;
		memcpy(&f, &i, sizeof(f));
		return f;
	}

	/** Returns the value stored in a Double tag. Not valid for any other tag type. */
	inline double GetDouble(int a_Tag) const
	{
		// Cause a compile-time error if sizeof(double) != 8
		// If your platform produces a compiler error here, you'll need to add code that manually decodes 64-bit doubles
		char Check1[9 - sizeof(double)];  // Fails if sizeof(double) > 8
		char Check2[sizeof(double) - 7];  // Fails if sizeof(double) < 8
		UNUSED(Check1);
		UNUSED(Check2);

		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_Double);
		return NetworkToHostDouble8(m_Data + m_Tags[(size_t)a_Tag].m_DataStart);
	}

	/** Returns the value stored in a String tag. Not valid for any other tag type. */
	inline AString GetString(int a_Tag) const
	{
		ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_String);
		AString res;
		res.assign(m_Data + m_Tags[(size_t)a_Tag].m_DataStart, m_Tags[(size_t)a_Tag].m_DataLength);
		return res;
	}

	/** Returns the tag's name. For tags that are not named, returns an empty string. */
	inline AString GetName(int a_Tag) const
	{
		AString res;
		res.assign(m_Data + m_Tags[(size_t)a_Tag].m_NameStart, m_Tags[(size_t)a_Tag].m_NameLength);
		return res;
	}

protected:
	const char *             m_Data;
	int                      m_Length;
	std::vector<cFastNBTTag> m_Tags;
	bool                     m_IsValid;  // True if parsing succeeded

	// Used while parsing:
	int m_Pos;

	bool Parse(void);
	bool ReadString(int & a_StringStart, int & a_StringLen);  // Reads a simple string (2 bytes length + data), sets the string descriptors
	bool ReadCompound(void);  // Reads the latest tag as a compound
	bool ReadList(eTagType a_ChildrenType);  // Reads the latest tag as a list of items of type a_ChildrenType
	bool ReadTag(void);       // Reads the latest tag, depending on its m_Type setting
} ;

class cFastNBTWriter
{
public:
	cFastNBTWriter(const AString & a_RootTagName = "");

	void BeginCompound(const AString & a_Name);
	void EndCompound(void);

	void BeginList(const AString & a_Name, eTagType a_ChildrenType);
	void EndList(void);

	void AddByte     (const AString & a_Name, unsigned char a_Value);
	void AddShort    (const AString & a_Name, Int16 a_Value);
	void AddInt      (const AString & a_Name, Int32 a_Value);
	void AddLong     (const AString & a_Name, Int64 a_Value);
	void AddFloat    (const AString & a_Name, float a_Value);
	void AddDouble   (const AString & a_Name, double a_Value);
	void AddString   (const AString & a_Name, const AString & a_Value);
	void AddByteArray(const AString & a_Name, const char * a_Value, size_t a_NumElements);
	void AddIntArray (const AString & a_Name, const int *  a_Value, size_t a_NumElements);

	void AddByteArray(const AString & a_Name, const AString & a_Value)
	{
		AddByteArray(a_Name, a_Value.data(), a_Value.size());
	}

	const AString & GetResult(void) const {return m_Result; }

	void Finish(void);

protected:

	struct sParent
	{
		int m_Type;   // TAG_Compound or TAG_List
		int m_Pos;    // for TAG_List, the position of the list count
		int m_Count;  // for TAG_List, the element count
		eTagType m_ItemType;  // for TAG_List, the element type
	} ;

	static const int MAX_STACK = 50;  // Highly doubtful that an NBT would be constructed this many levels deep

	// These two fields emulate a stack. A raw array is used due to speed issues - no reallocations are allowed.
	sParent m_Stack[MAX_STACK];
	int     m_CurrentStack;

	AString m_Result;

	bool IsStackTopCompound(void) const { return (m_Stack[m_CurrentStack].m_Type == TAG_Compound); }

	void WriteString(const char * a_Data, short a_Length);

	inline void TagCommon(const AString & a_Name, eTagType a_Type)
	{
		// If we're directly inside a list, check that the list is of the correct type:
		ASSERT((m_Stack[m_CurrentStack].m_Type != TAG_List) || (m_Stack[m_CurrentStack].m_ItemType == a_Type));

		if (IsStackTopCompound())
		{
			// Compound: add the type and name:
			m_Result.push_back((char)a_Type);
			WriteString(a_Name.c_str(), (short)a_Name.length());
		}
		else
		{
			// List: add to the counter
			m_Stack[m_CurrentStack].m_Count++;
		}
	}
} ;


text:
package au.gov.amsa.geo.adhoc;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

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

import com.github.davidmoten.grumpy.core.Position;

import au.gov.amsa.geo.Eez;
import au.gov.amsa.geo.ShapefileUtil;
import au.gov.amsa.geo.TimedPosition;
import au.gov.amsa.geo.distance.OperatorEffectiveSpeedChecker;
import au.gov.amsa.geo.model.SegmentOptions;
import au.gov.amsa.gt.Shapefile;
import au.gov.amsa.risky.format.BinaryFixes;
import au.gov.amsa.risky.format.BinaryFixesFormat;
import au.gov.amsa.risky.format.Downsample;
import au.gov.amsa.risky.format.Fix;
import au.gov.amsa.util.identity.MmsiValidator2;
import rx.Observable;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;

public class DistanceTravelledInEezMain {

    private static final int MIN_DISTANCE_KM_TO_ESTIMATE_TIME = 1;
    private static final Logger log = LoggerFactory.getLogger(DistanceTravelledInEezMain.class);

    private enum Location {
        IN, OUT, UNKNOWN;
    }

    private static final class State {

        private static final long HOUR_MILLIS = TimeUnit.HOURS.toMillis(1);

        String date;

        int mmsi;
        Fix fix;
        Location location;
        double distanceKm;

        double totalTimeMs;

        public double totalTimeHours() {
            return totalTimeMs / HOUR_MILLIS;
        }

        public String formattedDate() {
            return DistanceTravelledInEezMain.formattedDate(date);
        }

    }

    static String formattedDate(String date) {
        SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
        sdfIn.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            Date d = sdfIn.parse(date);
            // Sabine's preferred date format for importing into SPSS
            SimpleDateFormat sdfOut = new SimpleDateFormat("dd-MMM-yyyy");
            sdfOut.setTimeZone(TimeZone.getTimeZone("UTC"));
            return sdfOut.format(d);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        System.out.println("running");

        File tracks = new File("/home/dxm/combinedSortedTracks");
        long t = System.currentTimeMillis();
        List<File> files = Arrays.asList(tracks.listFiles());
        files.sort((a, b) -> a.getName().compareTo(b.getName()));
        try (PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("target/output.csv")))) {
            out.println(Vessel.headings());
            Observable //
                    .from(files) //
                    .filter(x -> x.getName().endsWith(".track.gz")) //
                    .filter(x -> x.getName().startsWith("2017")) //
                    .flatMap(file -> {
                        log.info(file.toString());

                        // Note that the Shapefile objects are not thread-safe so we make new one for
                        // each file to enable parallel processing

                        // used for intersections with eez boundary
                        Shapefile eezLine = Eez.loadEezLine();

                        // used for contains tests
                        Shapefile eezPolygon = Eez.loadEezPolygon();
                        long startTime = Util.getStartTime(file);
                        long endTime = startTime + TimeUnit.HOURS.toMillis(24);
                        return BinaryFixes //
                                .from(file, true, BinaryFixesFormat.WITH_MMSI) //
                                .subscribeOn(Schedulers.computation()) //
                                .filter(f -> MmsiValidator2.INSTANCE.isValid(f.mmsi())) //
                                .filter(f -> f.time() >= startTime && f.time() <= endTime) //
                                .groupBy(fix -> fix.mmsi()) //
                                .flatMap(o -> calculateDistance(file, eezLine, eezPolygon, o));
                    }, Runtime.getRuntime().availableProcessors()) //
                    .filter(x -> x.state.fix != null) //
                    .toBlocking() //
                    .forEach(x -> out.println(x.line()));
        }
        System.out.println((System.currentTimeMillis() - t) + "ms");
    }

    private static Observable<? extends Vessel> calculateDistance(File file, Shapefile eezLine, Shapefile eezPolygon,
            GroupedObservable<Integer, Fix> o) {
        return Observable.defer(() -> {
            State state = new State();
            state.date = file.getName().substring(0, file.getName().indexOf(".track.gz"));
            state.mmsi = o.getKey();
            state.location = Location.UNKNOWN;
            return o //
                    .compose(Downsample.minTimeStep(5, TimeUnit.MINUTES)) //
                    .lift(new OperatorEffectiveSpeedChecker(
                            SegmentOptions.builder().acceptAnyFixHours(480L).maxSpeedKnots(50).build()))
                    .filter(check -> check.isOk()) //
                    .map(check -> check.fix()) //
                    .doOnNext(fix -> {
                        //TODO unit test
                        boolean inside = eezPolygon.contains(fix.lat(), fix.lon());
                        Location location = inside ? Location.IN : Location.OUT;
                        if (state.location != Location.UNKNOWN) {
                            boolean crossed = state.location != location;
                            if (crossed) {
                                TimedPosition point = ShapefileUtil.findRegionCrossingPoint(eezLine, state.fix, fix);
                                final double distance;
                                if (location == Location.IN) {
                                    distance = distanceKm(fix.lat(), fix.lon(), point.lat, point.lon);
                                } else {
                                    distance = distanceKm(state.fix.lat(), state.fix.lon(), point.lat, point.lon);
                                }
                                state.distanceKm += distance;
                                double d = distanceKm(state.fix.lat(), state.fix.lon(), fix.lat(), fix.lon());
                                if (d >= MIN_DISTANCE_KM_TO_ESTIMATE_TIME) {
                                    // we ensure that d is not close to zero so that the time estimate does not get
                                    // blown out by instability in the division.
                                    state.totalTimeMs += distance / d * (fix.time() - state.fix.time());
                                }
                            } else if (location == Location.IN) {
                                state.distanceKm += distanceKm(state.fix.lat(), state.fix.lon(), fix.lat(), fix.lon());
                                state.totalTimeMs += fix.time() - state.fix.time();
                            }
                        }
                        state.fix = fix;
                        state.location = location;
                    }) //
                    .count() //
                    .map(count -> new Vessel(count, state));
        });
    }

    static final class Vessel {
        final long count;

        State state;

        double totalTimeHours() {
            return state.totalTimeMs / TimeUnit.HOURS.toMillis(1);
        }

        Vessel(long count, State state) {
            this.count = count;
            this.state = state;
        }

        static String headings() {
            return "dateUTC,mmsi,aisClass,numReports,distanceNmInEEZ,elapsedTimeHoursInEEZ";
        }

        String line() {
            DecimalFormat df = new DecimalFormat("0.000");
            return String.format("%s,%s,%s,%s,%s,%s", //
                    state.formattedDate(), //
                    state.mmsi, //
                    state.fix.aisClass(), //
                    count, //
                    df.format(state.distanceKm / 1.852), //
                    df.format(state.totalTimeHours()));
        }

    }

    private static double distanceKm(double lat, double lon, double lat2, double lon2) {
        return Position.create(lat, lon).getDistanceToKm(Position.create(lat2, lon2));
    }

}


text:
<?php
/**
 * Loco locale utilities
 */

/**
 * Match locale to code at end of string.
 * @param string e.g. "something-fr_FR"
 * @return LocoLocale
 */
function loco_locale_resolve( $s ){
    $lc = '';
    $cc = '';
    if( preg_match('/(?:^|\W)([a-z]{2,3})(?:(?:-|_)([a-z]{2}))?$/i', $s, $r ) ){
        $lc = strtolower($r[1]);
        if( isset($r[2]) ){
            $cc = strtoupper($r[2]);
            // handle situation when short domain part looks like language
            if( ! LocoLocale::is_known_language($lc) && LocoLocale::is_known_language($cc) ){
                $lc = strtolower($cc);
                $cc = '';
            }
        }
    }
    return LocoLocale::init( $lc, $cc );
}

/**
 * Locale object
 */
final class LocoLocale {

    private $lang;
    private $region;
    private $label;
    private $plurals = array('one','other');
    private $nplurals = 2;
    private $pluraleq = 'n != 1';

    private function __construct( $lc, $cc ){
        $lc and $this->lang = strtolower($lc);
        $cc and $this->region = strtoupper($cc);
    }

    public function export(){
        $data = get_object_vars($this);
        $this->region or $data['region'] = self::default_region($this->lang);
        $data['icon'] = $this->icon_class();
        return $data;
    }

    public function __toString(){
        $str = $this->get_name();
        if( $code = $this->get_code() ){
            $str = $code.', '.$str;
        }
        return $str;
    }

    public function get_code(){
        return $this->lang && $this->region ? $this->lang.'_'.$this->region : ( $this->lang ? $this->lang : '' ) ;
    }

    public function icon_class(){
        $cc = $this->region or $cc = self::default_region($this->lang);
        if( $cc ){
            return 'flag flag-'.strtolower($cc).' lang-'.$this->lang;
        }
        return 'lang lang-'.$this->lang;
    }

    public function get_name(){
        return empty($this->label) ? Loco::__('Unknown language') : $this->label;
    }

    public function equal_to( LocoLocale $locale ){
        return $this->get_code() === $locale->get_code();
    }

    public function preg( $delimiter = '/' ){
        $lc = preg_quote( $this->lang, $delimiter );
        $cc = preg_quote( $this->region, $delimiter );
        return $lc.'(?:[\-_]'.$cc.')?';
    }

    /**
     * @return LocoLocale
     */
    public static function init( $lc, $cc ){
        extract( self::data() );
        if( ! $cc ){
            if( self::is_regionless($lc) ){
                // WordPress expects this locale to be regionless
                $cc = '';
            }
            else {
                $cc = self::default_region($lc);
            }
        }
        $label = '';
        $locale = new LocoLocale( $lc, $cc );
        // get locale name from official WordPress list
        if( isset($locales[$lc][$cc]) ){
            $locale->label = $locales[$lc][$cc];
        }
        // get plural rules from iso 639 language and set label if common locale wasn't known
        if( isset($langs[$lc]) ){
            list( $label, $pluraleq, $plurals ) = $langs[$lc];
            $locale->pluraleq = $pluraleq;
            $locale->plurals = $plurals;
            $locale->nplurals = count( $plurals );
        }
        // get country just for label if not already applied from common locale combo
        if( ! $locale->label ){
            if( $cc ){
                if( isset($regions[$cc]) ){
                    $label = $label ? $label.' ('.$regions[$cc].')' : $regions[$cc];
                }
                else {
                    $label = $label ? $label.' ('.$cc.')' : '';
                }
            }
            $locale->label = $label;
        }
        return $locale;
    }

    /**
     * @return array
     */
    private static function data(){
        static $data;
        if( ! isset($data) ){
            // this must be the first include of this file to ensure it returns
            $data = loco_require('build/locales-compiled');
        }
        return $data;
    }

    /**
     * Get names of all common locales indexed by xx_YY code
     * @return array
     */
    public static function get_names(){
        static $names = array();
        if( ! $names ){
            $data = self::data();
            foreach( $data['locales'] as $lc => $regions ){
                foreach( $regions as $cc => $label ){
                    if( '' === $cc ){
                        $names[$lc] = $label;
                    }
                    else {
                        $names[$lc.'_'.$cc] = $label;
                    }
                }
            }
            asort($names,SORT_ASC|SORT_STRING);
        }
        return $names;
    }

    /**
     * Test whether a language code is considered regionless by WordPress core.
     * example: Thai is not "th_TH" but only "th"
     */
    public static function is_regionless( $lc ){
        $data = self::data();
        return isset($data['locales'][$lc]['']);
    }

    /**
     * Alias to loco_language_country
     */
    public static function default_region( $lang ){
        self::data();
        if( 'en' === $lang ){
            return 'US';
        }
        return loco_language_country( $lang );
    }

    /**
     * Test if locale code is strictly a valid WordPress locale
     */
    public static function is_valid_wordpress( $code ){
        if( ! preg_match('/^[a-z]{2,3}(?:_[A-Z]{2})?$/', $code, $r ) ){
            return false;
        }
        $names = self::get_names();
        return isset( $names[$r[0]] );
    }

    /**
     * Test if code is a valid language code
     * This includes all two character languages in ISO-639, plus any three character codes used by WordPress
     */
    public static function is_known_language( $code ){
        $data = self::data();
        $code = strtolower($code);
        return isset($data['langs'][$code]);
    }

    /**
     * Test if code is a known region
     * This includes all two character languages in ISO-3166
     */
    public static function is_known_region( $code ){
        $data = self::data();
        $code = strtoupper($code);
        return isset($data['regions'][$code]);
    }

}


text:
"use strict";

/*
 * Our controller for creating and populating our modules
 */
angular.module('de.isnow.myApp').controller('MainController',
		['$location', '$rootScope', 'resourceService', '$http', 'userService',
		 'sessionTimeout', '$log',
          function($location, $rootScope, resourceService, $http,
                   userService, sessionTimeout, $log) {

	var model = this;
	$log.info ('Instantiating de.isnow.myApp.');

	sessionTimeout.setTimer();

	model.userinfo = {};

	model.onViewChange = function(){
		sessionTimeout.tickle();
		var q = userService.stillLoggedIn();
		q.promise.then(
			function(data) {
				console.log (data);
				if ((!data) || (!data.uid))
					$location.path('/login');
				else
					model.userinfo = data;
			});

	};

	model.logIn = function(){
		model.userinfo = userService.doLogIn(model.realm, model.username, model.password).promise.then(
			// successfully logged in
			function(data) {
				if (null == data.uid) {
					$location.path('/login');
				} else {
					model.userinfo = data;
					$location.path('/home');
				}
			},
			// failed to log in
			function(err) {
				alert("Maintenance, please try again in a couple of minutes");
				model.userinfo = undefined;
				$location.path('/login');
			}
		);
	};

	model.loggedIn = function(){
		return userService.loggedIn;
	};

	model.logOut = function(){
		userService.doLogOut();
		$location.path('/login');
	};

	resourceService.teams('short').all(
	   function(data) {
		   model.teams= data;
   });

	/*resourceService.settings().get(function (data){
		model.systemSettings = data;
		if (data) {
			if ((data.instance == "DEV") || (data.instance == "TEST")) {
				//set jersey tracing for $resource calls
				$http.defaults.headers.common['X-Jersey-Tracing-Accept']="ALL";
			}
		}
	});*/
}]);


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p163;

import org.gradle.test.performance.mediummonolithicjavaproject.p159.Production3195;
import org.gradle.test.performance.mediummonolithicjavaproject.p161.Production3235;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test3276 {
    Production3276 objectUnderTest = new Production3276();

    @Test
    public void testProperty0() {
        Production3195 value = new Production3195();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production3235 value = new Production3235();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production3275 value = new Production3275();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
package com.selluv.android.common.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.selluv.android.R;

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

/**
 * Created by wdkim on 2016. 12. 27..
 * https://github.com/zhonghanwen/ColorTextView
 */

public class SLVColorTextView extends AppCompatTextView {

    private List<String> mColorTexts = new ArrayList<>();
    private List<String> mColors = new ArrayList<>();
    private int size;
    private String mCurrentText;

    public SLVColorTextView(Context context) {
        super(context);
    }

    public SLVColorTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public SLVColorTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        TypedArray attrsArray = getContext().obtainStyledAttributes(attrs, R.styleable.ColorTextView, 0, 0);
        String colorTexts = attrsArray.getString(R.styleable.ColorTextView_color_texts);
        String colors = attrsArray.getString(R.styleable.ColorTextView_color_arrays);
        attrsArray.recycle();

        initData(colorTexts, colors);

        setHtmlText();
    }

    public void initData(String colorTexts, String colors) {
        try {
            if (!TextUtils.isEmpty(colorTexts)) {
                String[] texts = colorTexts.split("\\|");
                for (int i = 0; i < texts.length; i++) {
                    mColorTexts.add(texts[i]);
                }
            }

            if (!TextUtils.isEmpty(colors)) {
                String[] texts = colors.split("\\|");
                for (int i = 0; i < texts.length; i++) {
                    mColors.add(texts[i]);
                }
            }
            size = Math.min(mColors.size(), mColorTexts.size());
            mCurrentText = getText().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setHtmlText() {
        try {
            if (!TextUtils.isEmpty(mCurrentText)) {
                for (int i = 0; i < size; i++) {
                    mCurrentText = mCurrentText.replace(mColorTexts.get(i), color(mColors.get(i), mColorTexts.get(i)));
                }
            }
            if (!TextUtils.isEmpty(mCurrentText)) {
                setText(Html.fromHtml(mCurrentText));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SLVColorTextView findAndSetStrColor(String str, String color) {
        try {
            if (!TextUtils.isEmpty(mCurrentText)) {
                mCurrentText = mCurrentText.replaceAll(str, color(color, str));
            }
            if (!TextUtils.isEmpty(mCurrentText)) {
                setText(Html.fromHtml(mCurrentText));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    public String color(String colorCode, String str) {
        return "" + str + "";
    }

}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..",".."))

Puppet::Type.newtype(:jboss_exec) do
  @doc = "Executes an arbitrary command within a JBoss container"
  feature :treetop, "Treetop gem for parsing"

  #non-isomorphic types can have multiple instances with the same namevar
  @isomorphic = false

  newparam(:server) do
    desc "The Server instance that this resource should be managed in"
  end

  newparam(:command, :namevar=>true) do
    desc "The command to execute, given in CLI format"
  end

  newparam(:expected_output) do
    desc "The hash output from the command should contain a super set of the provided values."
    defaultto({"outcome"=>"success"})
  end

  newparam(:arguments) do
    desc "Arguments to be appended to the command"
  end

  newparam(:unless) do
    desc "If specified, the command is only executed when this evaluates to false"
  end

  newparam(:onlyif) do
    desc "If specified, the command is only executed when this evaluates to true"
  end

  newparam(:refreshonly) do
    desc "If true, this command will only be executed when refreshed"
    defaultto false
    newvalues true, false
  end

  newparam(:logoutput) do
    desc 'Whether to log command output in addition to logging the exit code. Defaults to `on_failure`, which only logs the output when the command has an exit code that does not match any value specified by the returns attribute. As with any resource type, the log level can be controlled with the loglevel metaparameter.'

    defaultto :on_failure
    newvalues true, false, :on_failure
  end

  newparam(:tries) do
    desc "The number of times execution of the command should be tried.
          Defaults to '1'. This many attempts will be made to execute
          the command until the command does not return a failure.
          Note that the timeout paramater applies to each try rather than
          to the complete set of tries."

    munge do |value|
      if value.is_a?(String)
        unless value =~ /^[\d]+$/
          raise ArgumentError, "Tries must be an integer"
        end
        value = Integer(value)
      end
      raise ArgumentError, "Tries must be an integer >= 1" if value < 1
      value
    end

    defaultto 1
  end

  newparam(:try_sleep) do
    desc "The time to sleep in seconds between 'tries'."

    munge do |value|
      if value.is_a?(String)
        unless value =~ /^[-\d.]+$/
          raise ArgumentError, "try_sleep must be a number"
        end
        value = Float(value)
      end
      raise ArgumentError, "try_sleep cannot be a negative number" if value < 0
      value
    end

    defaultto 0
  end

  def server_reference
    catalog.resource("Jboss_admin::Server[#{self[:server]}]")
  end

  newproperty(:executed, :boolean => true) do
    defaultto true

    def retrieve
      not @resource.should_execute?
    end

    def sync
      tries = self.resource[:tries]
      try_sleep = self.resource[:try_sleep]

      output = nil
      last_error = nil

      # attempt toe CLI command for each try
      tries.times do |try|
        begin
          # Only add debug messages for tries > 1 to reduce log spam.
          debug("Exec try #{try+1}/#{tries}") if tries > 1

          # run the command
          output = provider.execute_command(resource[:command], resource[:arguments])

          # break the try loop if command was a success
          break if (resource[:expected_output].to_a - output.to_a).empty?

          # sleep before next attempt
          if try_sleep > 0 and tries > 1
            debug("Sleeping for #{try_sleep} seconds between tries")
            sleep try_sleep
          end
        rescue => e
          last_error = e
        end
      end

      if (!output)
        self.fail("Error executing CLI command `#{resource[:command]}`: #{last_error}")
      end

      # determine if the execution was a success
      success = (resource[:expected_output].to_a - output.to_a).empty?

      # log output if required
      if (resource[:logoutput] == :true || (!success && resource[:logoutput] == :on_failure))
        self.send(@resource[:loglevel], output.inspect)
      end

      # fail if CLI command failed
      if !success
        self.fail("Error executing CLI command `#{resource[:command]}`: #{output['failure-description']}")
      end
    end
  end

  def should_execute?(refreshing=false)
    require 'puppet/util/cli_parser'
    require 'puppet/util/path_generator'

    return false if self[:refreshonly] && !refreshing

    parser = CliParser.new
    if self[:onlyif]
      check = parser.parse_condition self[:onlyif]
      check_command = PathGenerator.format_command check[1][0], check[1][1], check[1][2]
      data = provider.execute_command check_command
      result = check[0].call data

      return false if !result
    end
    if self[:unless]
      check = parser.parse_condition self[:unless]
      check_command = PathGenerator.format_command check[1][0], check[1][1], check[1][2]
      data = provider.execute_command check_command
      result = check[0].call data

      return false if result
    end
    true
  end

  def refresh
    if should_execute? true
      self.property(:executed).sync
    end
  end

  autorequire(:jboss_resource) do
    require 'puppet/util/cli_parser'
    require 'puppet/util/path_generator'

    parser = CliParser.new
    resource_path = parser.parse_command value(:command)
    raise "Could not parse command #{value(:command)}, autorequire will fail" unless resource_path

    command_dependencies = PathGenerator.ancestors_and_self resource_path[0]
    unless_dependencies  = []
    onlyif_dependencies  = []

    if value(:onlyif)
      resource_path = parser.parse_condition value(:onlyif)
      raise "Could not parse condition #{value(:onlyif)}, autorequire will fail" unless resource_path
      onlyif_dependencies = PathGenerator.ancestors_and_self resource_path[1][0]
    end

    if value(:unless)
      resource_path = parser.parse_condition value(:unless)
      raise "Could not parse condition #{value(:unless)}, autorequire will fail" unless resource_path
      unless_dependencies = PathGenerator.ancestors_and_self resource_path[1][0]
    end

    command_dependencies | onlyif_dependencies | unless_dependencies
  end

  autorequire(:anchor) do
    ["Jboss_admin::Server[#{self[:server]}] End"]
  end
end


text:
<?php

namespace RESTfm\BackendPdo;

/**
 * PdoResponseException class.
 */
class PdoResponseException extends \RESTfm\ResponseException {

    /**
     * Override superclass constructor.
     *
     * @param \PDOException $e
     *   The exception object as returned from the failed PDO command.
     */
    function __construct(\PDOException $e) {

        $code = 500;                // Default status code. Overridden below.
        $reason = '';

        $pdoCode = $e->getCode();
        $pdoMessage = $e->getMessage();

        if ($pdoCode == 1045) {
            // 1045: "Access denied for user"
            //      Note: same with or without password being used.
            $code = \RESTfm\ResponseException::UNAUTHORIZED;
        }

        /* -- Code below from FileMakerResponseException, kept as reference --
        $fmCode = $fileMakerError->getCode();
        $fmMessage = $fileMakerError->getMessage();
        if ($fmCode == 101 || $fmCode == 104 || $fmCode == 105) {
            // 101: Record is missing
            // 104: Script is missing
            // 105: Layout is missing
            $code = \RESTfm\ResponseException::NOTFOUND;
        } elseif ($fmCode == 22 && stripos($fmMessage, 'password') !== FALSE) {
            // FileMaker Server 11 authorisation required response.
            // "Communication Error: (22) The requested URL returned error:
            //  401 - This can be due to an invalid username or password,
            //  or if the FMPHP privilege is not enabled for that user."
            $code = \RESTfm\ResponseException::UNAUTHORIZED;
        } elseif ($fmCode == 18 && stripos($fmMessage, 'account') !== FALSE) {
            // FileMaker Server 12 authorisation required response.
            // "Client must provide account information to proceed"
            $code = \RESTfm\ResponseException::UNAUTHORIZED;
        } elseif ($fmCode == 9 && stripos($fmMessage, 'privileges') !== FALSE) {
            // FileMaker Server 12 - Sometimes occurs when user account is
            //  correct, but with incorrect password. Does _not_ occur when
            //  trying to write record with read only access.
            // "Insufficient privileges"
            $code = \RESTfm\ResponseException::UNAUTHORIZED;
        }
        */

        // Additional headers for this exception.
        $this->addHeader('X-RESTfm-PDO-Status', $pdoCode);
        $this->addHeader('X-RESTfm-PDO-Reason', $pdoMessage);

        // Set a generic PDO reason for status 500 if not already set.
        if ($code == 500 && empty($reason)) {
            $reason = 'PDO Error';
        }

        // Finally call superclass constructor.
        parent::__construct($reason, $code, $e);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.chariotinstruments.markets.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <EditText
            android:id="@+id/symbolEditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:inputType="text"
            android:hint="Enter Ticker Symbol" />

        <Button
            android:id="@+id/startButton"
            android:text="Start"
            android:onClick="startProcess"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_toRightOf="@+id/symbolEditText"/>

        <Button
            android:id="@+id/stopButton"
            android:text="Stop"
            android:onClick="stopProcess"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:layout_toRightOf="@+id/startButton"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <Button
            android:id="@+id/getSymbolDataButton"
            android:text="Get Symbol"
            android:onClick="getSymbolData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:layout_below="@+id/symbolEditText"/>

        <Button
            android:id="@+id/accountDataButton"
            android:text="Account"
            android:onClick="getAccountData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/getSymbolDataButton"
            android:layout_below="@+id/symbolEditText"/>

        <Button
            android:id="@+id/prefsButton"
            android:text="Prefs"
            android:onClick="getPrefsActivity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/accountDataButton"
            android:layout_below="@+id/symbolEditText"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2">

        <EditText
            android:id="@+id/currentTextBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/getSymbolDataButton"
            android:hint="v5-19-2016"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3">
        <TextView
            android:id="@+id/dataTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/currentTextBox"
            android:text="Hello World!"
            android:scrollbars="vertical"/>

    </LinearLayout>
</LinearLayout>


text:
Simple script which performs an encrypted backup of the root FS using duplicity and GPG. The backup is then uploaded to a WebDAV(S) server. Can be used to perform either an incremental or full backup. Sends an email upon completion.

#### Backup and recovery has been tested with:
* FreeBSD 10.2 RELEASE
* gpg 1.4.20 and 2.1.11
* duplicity 0.7.06 and 0.7.07.1
* stackstorage.com for WebDAV endpoint

#### How to use
Use *-f* flag for a full backup, and *-i* for incremental. That's all there is to it.

#### Get it into production
1. Make sure you've installed duplicity and gpg. Note that when using GPG > 2.0, you'll need "pinentry-mode loopback" in your *.gnupg/gpg.conf*.
2. Create/import a GPG keypair dedicated for backups. Write the key's password to */root/.gpg.pwd*

    ```
    PASSPHRASE=""
    ```
3. Store your WebDAV user's password in */root/duplicity.pwd*

    ```
    WEBDAVPWD=""
    ```
4. Change ownership of above .pwd file to root:wheel, and set file permissions to 500.
5. Copy backup.sh to */usr/local/bin/backup*. Adjust it to your needs and make sure to fill in all $VARS.
6. Test. Test. Test.
7. Add a cronjob. The example below performs a daily incremental backup and a weekly full backup.

    ```
    0 23 * * * /usr/local/bin/backup -i
    0 8 * * 6 /usr/local/bin/backup -f
    ```


text:
<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
 */

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
    $api->get('/v1/codelist', 'App\Api\V1\Controllers\OnixCodelistController@index');
    $api->get('/v1/codelist/{number}', 'App\Api\V1\Controllers\OnixCodelistController@show');
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
	<TextView
	    android:id="@+id/tv_toast"
	    android:background="@drawable/call_locate_white"
	    android:text="电话来了"
	    android:gravity="center"
	    android:drawableLeft="@android:drawable/ic_menu_call"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content">
	</TextView>
</LinearLayout>


text:
'use strict';

describe('Hours E2E Tests:', function () {
  describe('Test hours page', function () {
    it('Should report missing credentials', function () {
      browser.get('http://localhost:3001/hours');
      expect(element.all(by.repeater('hour in hours')).count()).toEqual(0);
    });
  });
});


text:
// Video decode demo using MMAL

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <interface/mmal/mmal.h>
#include <interface/mmal/util/mmal_util.h>
#include <interface/mmal/util/mmal_default_components.h>
#include <interface/mmal/util/mmal_util_params.h>
#include <interface/mmal/mmal_parameters_video.h>

#include "bcm_host.h"
#include "ilclient.h"

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
typedef enum {false, true} bool;
typedef void CMMALVideoBuffer;

#define CLASSNAME "video_decode"
enum { LOGERROR, LOGWARNING, LOGDEBUG };
static void Log(int priority, const char *format, ...)
{
  char str[1024];
  va_list args;
  va_start(args, format);
  vsnprintf(str, sizeof str, format, args);
  va_end(args);
  puts(str);
}

#define LogF(priority, format, ...) Log(priority, "%12s::%4d:%-20s " format, CLASSNAME, __LINE__, __FUNCTION__, ##__VA_ARGS__)
#define LogD(format, ...) LogF(LOGDEBUG, format, ##__VA_ARGS__)
#define LogE(format, ...) LogF(LOGERROR, format, ##__VA_ARGS__)
#define LogS(status, format, ...) if (status == MMAL_SUCCESS) {} else LogE(format " (status=0x%x %s)", ##__VA_ARGS__, status, mmal_status_to_string(status))

typedef struct {
  int m_decoded_width;
  int m_decoded_height;
  MMAL_ES_FORMAT_T *m_es_format;
  MMAL_COMPONENT_T *m_dec;
  MMAL_PORT_T *m_dec_input;
  MMAL_PORT_T *m_dec_output;
  MMAL_POOL_T *m_dec_input_pool;
  MMAL_POOL_T *m_dec_output_pool;
  MMAL_POOL_T *m_vout_input_pool;
  MMAL_QUEUE_T *m_queue;
  float m_fps;
} decoder_state_t;

typedef struct {
  int extrasize;
  int fpsrate;
  int fpsscale;
  void *extradata;
  MMAL_FOURCC_T m_codingType;
  MMAL_FOURCC_T m_encoding;
} stream_info_t;

static int GetAllowedReferences() { return 5; }

static void PortSettingsChanged(decoder_state_t *state, MMAL_BUFFER_HEADER_T *buffer)
{
  MMAL_STATUS_T status;
  MMAL_EVENT_FORMAT_CHANGED_T *fmt = mmal_event_format_changed_get(buffer);
  mmal_format_copy(state->m_es_format, fmt->format);

  if (state->m_es_format->es->video.crop.width && state->m_es_format->es->video.crop.height)
  {
    float m_aspect_ratio = 1.0f;
    if (state->m_es_format->es->video.par.num && state->m_es_format->es->video.par.den)
      m_aspect_ratio = (float)(state->m_es_format->es->video.par.num * state->m_es_format->es->video.crop.width) / (state->m_es_format->es->video.par.den * state->m_es_format->es->video.crop.height);
    state->m_decoded_width = state->m_es_format->es->video.crop.width;
    state->m_decoded_height = state->m_es_format->es->video.crop.height;
    LogD("format changed: %dx%d %.2f", state->m_decoded_width, state->m_decoded_height, m_aspect_ratio);
  }
  else
    LogE("format changed: Unexpected %dx%d", state->m_es_format->es->video.crop.width, state->m_es_format->es->video.crop.height);

  mmal_format_copy(state->m_dec_output->format, state->m_es_format);

  status = mmal_port_parameter_set_boolean(state->m_dec_output, MMAL_PARAMETER_ZERO_COPY,  MMAL_TRUE);
  LogS(status, "Failed to enable zero copy mode on %s", state->m_dec_output->name);

  status = mmal_port_format_commit(state->m_dec_output);
  LogS(status, "Failed to commit decoder output port");

  LogD("Output %dx%d (%dx%d) encoding %4.4s", state->m_es_format->es->video.width, state->m_es_format->es->video.height, state->m_es_format->es->video.crop.width, state->m_es_format->es->video.crop.height, &state->m_dec_output->format->encoding);

  if (!state->m_dec_output_pool)
  {
    LogD("create output pool: %d x %d, (min:%d recommended:%d)", state->m_dec_output->buffer_num, state->m_dec_output->buffer_size, state->m_dec_output->buffer_size_min, state->m_dec_output->buffer_num_recommended);
    state->m_dec_output_pool = mmal_port_pool_create(state->m_dec_output, state->m_dec_output->buffer_num, state->m_dec_output->buffer_size);
    if (!state->m_dec_output_pool)
      LogE("Failed to create pool for decoder output port");
    // prime decoder output buffers
    MMAL_BUFFER_HEADER_T *buffer;
    while (buffer = mmal_queue_get(state->m_dec_output_pool->queue), buffer)
    {
      LogD("Sending buffer:%p to dec_output", buffer);
      mmal_buffer_header_reset(buffer);
      buffer->cmd = 0;
      status = mmal_port_send_buffer(state->m_dec_output, buffer);
      if (status != MMAL_SUCCESS)
      {
        mmal_buffer_header_release(buffer);
        LogE("Failed to return buffer to dec_output");
        return;
      }
    }
  }
}

static void dec_control_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
  decoder_state_t *state = (decoder_state_t *)port->userdata;
  LogD("port:%p buffer %p, len %d cmd:%4.4s", port, buffer, buffer->length, &buffer->cmd);
  mmal_queue_put(state->m_queue, buffer);
}

static void dec_input_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
  //decoder_state_t *state = (decoder_state_t *)port->userdata;
  LogD("port:%p buffer %p, len %d cmd:%4.4s", port, buffer, buffer->length, &buffer->cmd);
  mmal_buffer_header_release(buffer);
}

static void dec_output_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
{
  decoder_state_t *state = (decoder_state_t *)port->userdata;
  LogD("port:%p buffer %p, len %d cmd:%4.4s", port, buffer, buffer->length, &buffer->cmd);
  mmal_queue_put(state->m_queue, buffer);
}

bool SendCodecConfigData(decoder_state_t *state, stream_info_t m_hints)
{
  MMAL_STATUS_T status;
  if (!state->m_dec_input_pool || !m_hints.extrasize)
    return true;
  // send codec config data
  MMAL_BUFFER_HEADER_T *buffer = mmal_queue_timedwait(state->m_dec_input_pool->queue, 500);
  if (!buffer)
  {
    LogE("mmal_queue_get failed");
    return false;
  }

  mmal_buffer_header_reset(buffer);
  buffer->cmd = 0;
  buffer->length = min(m_hints.extrasize, buffer->alloc_size);
  memcpy(buffer->data, m_hints.extradata, buffer->length);
  buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END | MMAL_BUFFER_HEADER_FLAG_CONFIG;
  LogD("%-8p %-6d flags:%x", buffer, buffer->length, buffer->flags);
  status = mmal_port_send_buffer(state->m_dec_input, buffer);
  LogS(status, "Failed send buffer to decoder input port");
  return true;
}

static int test_mmal_setup(decoder_state_t *state, stream_info_t m_hints)
{
  MMAL_STATUS_T status;

  // initialize mmal.
  status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &state->m_dec);
  LogS(status, "Failed to create MMAL decoder component %s", MMAL_COMPONENT_DEFAULT_VIDEO_DECODER);

  state->m_dec->control->userdata = (struct MMAL_PORT_USERDATA_T *)state;
  status = mmal_port_enable(state->m_dec->control, dec_control_port_cb);
  LogS(status, "Failed to enable decoder control port %s", MMAL_COMPONENT_DEFAULT_VIDEO_DECODER);

  state->m_dec_input = state->m_dec->input[0];

  state->m_dec_input->format->type = MMAL_ES_TYPE_VIDEO;
  state->m_dec_input->format->encoding = m_hints.m_codingType;
  if (m_hints.fpsrate > 0 && m_hints.fpsscale > 0)
  {
    state->m_dec_input->format->es->video.frame_rate.num = m_hints.fpsrate;
    state->m_dec_input->format->es->video.frame_rate.den = m_hints.fpsscale;
    state->m_fps = m_hints.fpsrate / m_hints.fpsscale;
  }
  else
    state->m_fps = 0.0f;
  //state->m_dec_input->format->flags |= MMAL_ES_FORMAT_FLAG_FRAMED;

  status = mmal_port_parameter_set_boolean(state->m_dec_input, MMAL_PARAMETER_VIDEO_DECODE_ERROR_CONCEALMENT, MMAL_FALSE);
  LogS(status, "Failed to disable error concealment on %s", state->m_dec_input->name);

  status = mmal_port_parameter_set_uint32(state->m_dec_input, MMAL_PARAMETER_EXTRA_BUFFERS, GetAllowedReferences());
  LogS(status, "Failed to enable extra buffers on %s", state->m_dec_input->name);

  status = mmal_port_parameter_set_uint32(state->m_dec_input, MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS, 1);
  LogS(status, "Failed to disable interpolate timestamps mode on %s", state->m_dec_input->name);

  status = mmal_port_format_commit(state->m_dec_input);
  LogS(status, "Failed to commit format for decoder input port %s", state->m_dec_input->name);

  state->m_dec_input->buffer_size = state->m_dec_input->buffer_size_recommended;
  state->m_dec_input->buffer_num = state->m_dec_input->buffer_num_recommended;

  state->m_dec_input->userdata = (struct MMAL_PORT_USERDATA_T *)state;
  status = mmal_port_enable(state->m_dec_input, dec_input_port_cb);
  LogS(status, "Failed to enable decoder input port %s", state->m_dec_input->name);

  state->m_dec_output = state->m_dec->output[0];

  // set up initial decoded frame format - will likely change from this
  state->m_dec_output->format->encoding = state->m_dec_output->format->encoding_variant = m_hints.m_encoding;
  state->m_es_format = mmal_format_alloc();
  mmal_format_copy(state->m_es_format, state->m_dec_output->format);

  status = mmal_port_parameter_set_boolean(state->m_dec_output, MMAL_PARAMETER_ZERO_COPY,  MMAL_TRUE);
  LogS(status, "Failed to enable zero copy mode on %s", state->m_dec_output->name);

  status = mmal_port_format_commit(state->m_dec_output);
  LogS(status, "Failed to commit decoder output format");

  LogD("Output %dx%d (%dx%d) encoding %4.4s", state->m_es_format->es->video.width, state->m_es_format->es->video.height, state->m_es_format->es->video.crop.width, state->m_es_format->es->video.crop.height, &state->m_dec_output->format->encoding);

  state->m_dec_output->buffer_size = state->m_dec_output->buffer_size_min;
  state->m_dec_output->buffer_num = max(GetAllowedReferences(), state->m_dec_output->buffer_num_recommended);
  state->m_dec_output->userdata = (struct MMAL_PORT_USERDATA_T *)state;
  status = mmal_port_enable(state->m_dec_output, dec_output_port_cb);
  LogS(status, "Failed to enable decoder output port");

  status = mmal_component_enable(state->m_dec);
  LogS(status, "Failed to enable decoder component %s", state->m_dec->name);

  LogD("create input pool: %d x %d, (min:%d recommended:%d)", state->m_dec_input->buffer_num, state->m_dec_input->buffer_size, state->m_dec_input->buffer_size_min, state->m_dec_input->buffer_num_recommended);
  state->m_dec_input_pool = mmal_port_pool_create(state->m_dec_input, state->m_dec_input->buffer_num, state->m_dec_input->buffer_size);
  LogS(status, "Failed to create pool for decoder input port");

  if (!SendCodecConfigData(state, m_hints))
    return -1;

  state->m_queue = mmal_queue_create();
  if (!state->m_queue)
  {
    LogE("Failed to create mmal queue");
    return -1;
  }
  return status;
}

static int test_mmal_decode(decoder_state_t *state, stream_info_t m_hints, const char *filename, const char *outfilename)
{
  MMAL_STATUS_T status;
  FILE *in, *out = NULL;
  if((in = fopen(filename, "rb")) == NULL)
    return -2;
  if (outfilename && (out = fopen(outfilename, "wb")) == NULL)
    return -2;

  while (1)
  {
    MMAL_BUFFER_HEADER_T *buffer = mmal_queue_timedwait(state->m_dec_input_pool->queue, 10);
    if (buffer)
    {
      buffer->length = fread(buffer->data, 1, buffer->alloc_size, in);
      if (buffer->length < 0)
      {
        LogE("fread returned %d", buffer->length);
        return -4;
      }
      else if (buffer->length > 0)
      {
        buffer->flags = MMAL_BUFFER_HEADER_FLAG_USER0;
        if (feof(in))
          buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;

        LogD("Sending buffer:%p to dec_input length:%d/%d flags:%x", buffer, buffer->length, buffer->alloc_size, buffer->flags);
        status = mmal_port_send_buffer(state->m_dec_input, buffer);
        LogS(status, "mmal_port_send_buffer failed");
      }
    }
    buffer = mmal_queue_timedwait(state->m_queue, 10);
    if (buffer)
    {
      assert(!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_TRANSMISSION_FAILED));
      if (buffer->cmd == MMAL_EVENT_ERROR)
      {
        status = (MMAL_STATUS_T)*(uint32_t *)buffer->data;
        LogS(status, "Error");
      }
      else if (buffer->cmd == 0)
      {
        assert(!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_DECODEONLY));
        if (!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_CORRUPTED))
        {
          int eos = buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS;
          LogD("got decoded buffer:%p buffer_size(%u) dts:%.3f pts:%.3f flags:%x:%x",
             buffer, buffer->length, buffer->dts*1e-6, buffer->pts*1e-6, buffer->flags, buffer->type->video.flags);

          if (out && m_hints.m_encoding == MMAL_ENCODING_I420)
            fwrite(buffer->data, 1, buffer->length, out);

          mmal_buffer_header_reset(buffer);
          buffer->cmd = 0;
          LogD("Sending buffer:%p to dec_output", buffer);
          status = mmal_port_send_buffer(state->m_dec_output, buffer);
          LogS(status, "Failed to return buffer to dec_output");
          buffer = NULL;// don't want to release it
          if (eos)
          {
            LogD("stream complete!");
            break;
          }
        }
      }
      else if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED)
      {
        PortSettingsChanged(state, buffer);
      }
      if (buffer)
        mmal_buffer_header_release(buffer);
    }
  }
  fclose(in);
  if (out)
    fclose(out);
  return 0;
}

static void test_mmal_destroy(decoder_state_t *state, stream_info_t m_hints)
{
  if (state->m_queue)
    mmal_queue_destroy(state->m_queue);

  if (state->m_dec && state->m_dec->control && state->m_dec->control->is_enabled)
    mmal_port_disable(state->m_dec->control);

  if (state->m_dec_input && state->m_dec_input->is_enabled)
    mmal_port_disable(state->m_dec_input);

  if (state->m_dec_output && state->m_dec_output->is_enabled)
    mmal_port_disable(state->m_dec_output);
  state->m_dec_output = NULL;

  if (state->m_dec && state->m_dec->is_enabled)
    mmal_component_disable(state->m_dec);

  if (state->m_dec_input_pool)
    mmal_port_pool_destroy(state->m_dec_input, state->m_dec_input_pool);
  state->m_dec_input_pool = NULL;
  state->m_dec_input = NULL;

  if (state->m_dec)
    mmal_component_destroy(state->m_dec);
  state->m_dec = NULL;

  mmal_format_free(state->m_es_format);
}

int main(int argc, char **argv)
{
  decoder_state_t decoder_state = {};
  stream_info_t m_hints = {};
  m_hints.m_codingType = MMAL_ENCODING_H264;
  m_hints.m_encoding = MMAL_ENCODING_I420;
  //m_hints.m_encoding = MMAL_ENCODING_OPAQUE;
  if (argc < 2)
  {
     printf("Usage: %s <filename>\n", argv[0]);
     exit(1);
  }
  bcm_host_init();
  test_mmal_setup(&decoder_state, m_hints);
  test_mmal_decode(&decoder_state, m_hints, argv[1], argc >=3 ? argv[2]:NULL);
  test_mmal_destroy(&decoder_state, m_hints);
  return 0;
}


text:
package generator

import (
	"strings"
	"text/template"
)

var packageFuncs = template.FuncMap{
	"ToLower":  strings.ToLower,
	"UnExport": unexport,
	"Replace":  strings.Replace,
	"Generate": func(suffix string) string { return suffix + ":generate" }, // yes, this seems insane but ensures that we can use `go generate ./...` from the main package
}

const packageTemplate string = `{{.Header}}// Code generated by counterfeiter. DO NOT EDIT.
package {{.DestinationPackage}}

import (
	{{- range $index, $import := .Imports.ByAlias}}
	{{$import}}
	{{- end}}
)

//{{Generate "go"}} go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//{{Generate "counterfeiter"}} . {{.Name}}

// {{.Name}} is a generated interface representing the exported functions
// in the {{.TargetPackage}} package.
type {{.Name}} interface {
  {{- range .Methods}}
  {{.Name}}({{.Params.AsNamedArgsWithTypes}}) {{.Returns.AsReturnSignature}}
  {{- end}}
}

type {{.Name}}Shim struct {}

{{- range .Methods}}
func (p *{{$.Name}}Shim) {{.Name}}({{.Params.AsNamedArgsWithTypes}}) {{.Returns.AsReturnSignature}} {
  {{if .Returns.HasLength}}return {{end}}{{$.TargetAlias}}.{{.Name}}({{.Params.AsNamedArgsForInvocation}})
}
{{end}}
var _ {{.Name}} = new({{.Name}}Shim)
`


text:
package org.apache.hyracks.storage.am.lsm.common.api;

/**
 * This interface generates component Ids for LSM components (both memory and disk components).
 */
public interface ILSMComponentIdGenerator {

    /**
     * @return An Id for LSM component
     */
    public ILSMComponentId getId();

    /**
     * Refresh the component Id generator to generate the next Id.
     * {@link #getId()} would always return the same Id before this method is called.
     */
    public void refresh();

}


text:
@echo off
echo Press any key to publish
pause
".nuget\NuGet.exe" push TimeyWimey.1.0.0.nupkg -Source https://www.nuget.org/api/v2/package
pause


text:
class CreateCalendarLocations < ActiveRecord::Migration

  def up
    create_table :refinery_calendar_locations do |t|

      t.string :name

      t.integer :position

      t.timestamps
    end

    add_column :refinery_calendar_events, :location_id, :integer
    add_index :refinery_calendar_events, :location_id
  end

end

def down
  if defined?(::Refinery::UserPlugin)
    ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-calendar"})
  end

  drop_table :refinery_calendar_locations

  remove_column :refinery_calendar_events, :location_id
  remove_index :refinery_calendar_events, :category_id

end


text:
from indico.modules.events.management.views import WPEventManagement

class WPManagePersons(WPEventManagement):
    template_prefix = 'events/persons/'
    sidemenu_option = 'persons'
    bundles = ('module_events.persons.js',)


text:
<?xml version="1.0" encoding="utf-8"?>

<merge xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/icon"
            android:id="@+id/upload_preview_image"
            android:layout_centerInParent="true"
            />
    <TextView
            android:layout_below="@+id/upload_preview_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="正在上传..."
            />
</merge>


text: export { default } from './Contribute'


text:
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace Falcor.Router
{
    public class RouteResolver: IRouteResolver
    {
        private readonly List<Route> _routes;

        public RouteResolver(IEnumerable<Route> routes)
        {
            _routes = routes.ToList();
        }

        public IEnumerable<Route> FindRoutes(IPath path)
        {
            return _routes.Where(i => Match(path.Items, i.Items));
        }

        private static bool Match(IList<IPathItem> input, IList<IRoutePathItem> definition)
        {
            if (input.Count < definition.Count)
            {
                return false;
            }

            var result = definition.Zip(input, (def, inp) => MatchComponent(def.Item, inp)).All(i => i);
            return result;
        }

        private static bool MatchComponent(IPathItem definition, IPathItem input)
        {
            var keysInput = input as Keys;
            var indexInput = input as Integers;

            var keysDefinition = definition as Keys;

            if (keysDefinition != null)
            {
                if (keysInput == null)
                {
                    if (indexInput != null && indexInput.Values.Count == 1)
                    {
                        keysInput = new Keys(indexInput.Values[0].ToString());
                    }
                    else
                    {
                        return false;
                    }
                }

                return keysDefinition.Values.Count == 0
                    || keysDefinition.Values.Any(i => keysInput.Values.Any(j => string.Compare(j, i, true, CultureInfo.InvariantCulture) == 0));
            }

            var rangeInput = input as Range;
            var rangeDefinition = definition as Range;
            if (rangeDefinition != null)
            {
                return rangeInput != null;
            }

            var indexDefinition = definition as Integers;
            return indexInput != null && indexDefinition != null;
        }
    }
}


text:
#include "platform/CCCommon.h"
#include "CCStdC.h"
#include "CCWinRTUtils.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
#include "ModalLayer.h"
#include "CCEGLView.h"
#endif

#if defined(VLD_DEBUG_MEMORY)
#include <vld.h>
#endif

NS_CC_BEGIN

#define MAX_LEN         (cocos2d::kMaxLogLen + 1)

void CCLog(const char * pszFormat, ...)
{
#if defined(COCOS2D_DEBUG)
    char szBuf[MAX_LEN];

    va_list ap;
    va_start(ap, pszFormat);
    vsnprintf_s(szBuf, MAX_LEN, MAX_LEN, pszFormat, ap);
    va_end(ap);

    WCHAR wszBuf[MAX_LEN] = {0};
    MultiByteToWideChar(CP_UTF8, 0, szBuf, -1, wszBuf, sizeof(wszBuf));
    OutputDebugStringW(wszBuf);
    OutputDebugStringW(L"\n");

    WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), szBuf, sizeof(szBuf), NULL, FALSE);
    printf("%s\n", szBuf);
#endif
}

void CCMessageBox(const char * pszMsg, const char * pszTitle)
{

#if defined(VLD_DEBUG_MEMORY)
	VLDReportLeaks();
#endif

    // Create the message dialog and set its content
    Platform::String^ message = ref new Platform::String(CCUtf8ToUnicode(pszMsg, -1).c_str());
    Platform::String^ title = ref new Platform::String(CCUtf8ToUnicode(pszTitle, -1).c_str());
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	Windows::UI::Popups::MessageDialog^ msg = ref new Windows::UI::Popups::MessageDialog(message, title);
    // Set the command to be invoked when a user presses 'ESC'
    msg->CancelCommandIndex = 1;

    // Show the message dialog
    msg->ShowAsync();
#else

    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
    if(!pEGLView->ShowMessageBox(title, message))
    {
	    ModalLayer *messageBox = ModalLayer::create();
	    messageBox->setMessage(pszMsg);
	    CCDirector::sharedDirector()->getRunningScene()->addChild(messageBox);
    }
#endif

}

void CCLuaLog(const char *pszMsg)
{
#if defined(COCOS2D_DEBUG)
    int bufflen = MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, NULL, 0);
    WCHAR* widebuff = new WCHAR[bufflen + 1];
    memset(widebuff, 0, sizeof(WCHAR) * (bufflen + 1));
    MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, widebuff, bufflen);

    OutputDebugStringW(widebuff);
    OutputDebugStringA("\n");

	bufflen = WideCharToMultiByte(CP_ACP, 0, widebuff, -1, NULL, 0, NULL, NULL);
	char* buff = new char[bufflen + 1];
	memset(buff, 0, sizeof(char) * (bufflen + 1));
	WideCharToMultiByte(CP_ACP, 0, widebuff, -1, buff, bufflen, NULL, NULL);
	puts(buff);

	delete[] widebuff;
	delete[] buff;
#endif
}

NS_CC_END


text:
export function increment() {
	return {
		type: 'INCREMENT_VALUE'
	}
}

export function decrement() {
	return {
		type: 'DECREMENT_VALUE'
	}
}

export function incrementAsync() {
	return {
		type: 'INCREMENT_ASYNC'
	}
}

export function decrementAsync() {
	return {
		type: 'DECREMENT_ASYNC'
	}
}


text:
//// [privateAccessInSubclass1.ts]
class Base {
  private options: any;
}

class D extends Base {
  myMethod() {
    this.options;
  }
}

//// [privateAccessInSubclass1.js]
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Base = /** @class */ (function () {
    function Base() {
    }
    return Base;
}());
var D = /** @class */ (function (_super) {
    __extends(D, _super);
    function D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    D.prototype.myMethod = function () {
        this.options;
    };
    return D;
}(Base));


text:
<title>Majority Wins</title>

Majority Wins (with self)

A model of decision making where a person makes their current opinion
match the majority of their neighbors' opinions (including their own opinion).  For example, a cell (or person) will decide to
join a particular political party only if that party is in the majority (among their neighbors).
If two neighbors are colored blue, six neighbors are colored red, and the cell
itself is colored red, then the
cell will decide to join the majority red party (7 out of 9 are red). In other words the cell will turn red. If there is a tie, the party is picked randomly.

Simulations with this rule will quickly come to a steady state with obvious
clusters of each opinion.
This simulation is not quite as interesting as the strict
Majority Wins rule which excludes the opinion of the cell from the decision
making.  In that case, the cell is entirely influenced by its neighbors, and
its own opinion matters not at all.  Simulations with
the Majority Wins rule have more dynamic boundaries than this rule (where the cell cannot quite
make up its mind).

This is one of a class of so-called voter models that have simple rules but
surprisingly complex behavior.  These voter models have been used to simulate
gawking behavior, jury decision making, rioting, herding, flocking, phase transitions (like
water to ice), and a host of applications in particle physics where molecules check their
neighboring molecules before moving.


text:
package org.hisp.dhis.tracker.preheat.supplier.strategy;

import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.query.QueryService;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.tracker.preheat.cache.PreheatCacheService;
import org.hisp.dhis.tracker.preheat.mappers.CategoryOptionMapper;
import org.springframework.stereotype.Component;

/**
 * @author Luciano Fiandesio
 */
@Component
@StrategyFor( value = CategoryOption.class, mapper = CategoryOptionMapper.class, cache = true, ttl = 30, capacity = 5 )
public class CatOptionStrategy extends AbstractSchemaStrategy
{
    public CatOptionStrategy( SchemaService schemaService, QueryService queryService,
        IdentifiableObjectManager manager, PreheatCacheService cacheService )
    {
        super( schemaService, queryService, manager, cacheService );
    }
}


text:
title: "Tuesday, 26 July 2016"
date: "2016-07-26"
excerpt: "Just another day at the office"
header:
    image:  beer-eggs-sausages-bachelor-breakfast.jpg
    teaser: beer-eggs-sausages-bachelor-breakfast.jpg
meals:
    - name: "Breakfast"
      notes: "No time to eat at home. Oops."
      foods:
          - food: "Sausage, Egg & Cheese Croissant Sandwich"
            quantity: 1
            calories: 380
    - name: "Lunch"
      notes: "Good thing I thought to prep lunch on Sunday night. Now I just have to remember to bring it with me."
      foods:
          - food: "Giant Store-brand Sausage, 1 link"
            quantity: 2
            calories: 210
          - food: "Pasta, 1 cup (57g)"
            quantity: .64
            calories: 210
          - food: "Sticky Fingers BBQ Sauce, 1tbsp"
            quantity: 1
            calories: 20
    - name: "Dinner"
      notes: "Chicken tonight (sung to the tune of Yngwie Malmsteen's "Heaven tonight")"
      foods:
          - food: "Wegmans Vegetable Bow Tie Pasta, 1oz"
            quantity: 3
            calories: 100
          - food: "Wegmans Italian Marinade Chicken Breast Cutlets, 1oz"
            quantity: 7.07
            calories: 27.5
          - food: "Kraft 100% Grated Parmesan Cheese, 1tbsp"
            quantity: 2
            calories: 10
          - food: "Schleppes Ginger Ale, 1oz"
            quantity: 4
            calories: 12
---


text:
package castalia

import castalia.model.Model.{ResponseConfig, DefaultResponseConfig, StubConfig}

object StubConfigParser {

  def parseStubConfig(jsonFile: String): StubConfig = {
    val initialConfig = JsonConverter.parseJson[StubConfig](jsonFile)
    (initialConfig.default) match {
      case (Some(default)) =>
        initialConfig.responses match {
          case None =>
            initialConfig
          case Some(initialResponses) => StubConfig(
            initialConfig.endpoint,
            initialConfig.default,
            Some(addDefaults(default, initialResponses)),
            initialConfig.responseprovider)
        }
      case _ => initialConfig
    }

  }

  def parseStubConfigs(jsonFiles: List[String]): List[StubConfig] = {
    jsonFiles.map(parseStubConfig(_))
  }

  private def addDefaults(default: DefaultResponseConfig, responses: List[ResponseConfig]): List[ResponseConfig] =
    (responses) match {
      case (Nil) => Nil
      case (first :: rest) => mix(default, first) :: addDefaults(default, rest)
    }

  private def mix(default: DefaultResponseConfig, response: ResponseConfig) = {
    val delayOption = (default.delay, response.delay) match {
      case (_, Some(delay)) => Some(delay)
      case (default, _) => default
    }
    // future extension: httpStatusCode and response in ResponseConfig become Option, and default can be mixed in

    ResponseConfig(response.ids, delayOption, response.httpStatusCode, response.response)
  }
}


text:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Xml.EventSpec (spec) where

import Lastfm
import Lastfm.Event
import Test.Hspec
import Text.Xml.Lens

import SpecHelper

spec :: Spec
spec = do
  it "attend" $
    shouldHaveXml_ . privately $
      attend <*> event 3142549 <*> status Attending

  it "share" $
    shouldHaveXml_ . privately $
      share <*> event 3142549 <*> recipient "liblastfm" <* message "Just listen!"

  it "getAttendees" $
    publicly (getAttendees <*> event 3142549 <* limit 2)
   `shouldHaveXml`
    root.node "attendees".node "user".node "name".text

  it "getInfo" $
    publicly (getInfo <*> event 3142549)
   `shouldHaveXml`
    root.node "event".node "venue".node "location".node "country".text

  it "getShouts" $
    publicly (getShouts <*> event 3142549 <* limit 1)
   `shouldHaveXml`
    root.node "shouts".node "shout".node "body".text


text:
package com.ctrip.framework.cs.component.defaultComponents;

import com.ctrip.framework.cs.annotation.ComponentStatus;
import com.ctrip.framework.cs.util.JMXQuery;

import java.util.ArrayList;
import java.util.Map;

/**
 * Created by jiang.j on 2016/6/3.
 */
@ComponentStatus(id = "vi.memorypoolinfo",name = "jvm memory pool info",description = "jvm内存池监控",custom = true)
public class MemoryPoolInfo extends ArrayList<Map<String,Object>> {

    public MemoryPoolInfo(){
        JMXQuery jmxQuery = new JMXQuery();
        this.addAll(jmxQuery.query(JMXQuery.JAVALANG,"MemoryPool",new String[]{"Name","Usage"}));
    }
}


text:
//
//  ClotheshorseStatus.h
//  HomeMate
//
//  Created by Air on 15/11/18.
//  Copyright © 2017年 Air. All rights reserved.
//

#import "HMBaseModel+Extension.h"

typedef enum {
    /**
     *  风干
     */
    KStatusTypeWindDry,
    /**
     *  烘干
     */
    KStatusTypeHeatDry,
    /**
     *  照明
     */
    KStatusTypeLight,
    /**
     *  消毒
     */
    KStatusTypeSterilize,
    /**
     *  总控
     */
    KStatusTypeMainCtrl,

}KStatusType;

@interface HMClotheshorseStatus : HMBaseModel

@property (nonatomic, strong) NSString *       deviceId;
@property (nonatomic, strong) NSString *       motorState;
@property (nonatomic, strong) NSString *       motorStateTime;

/**
 *  0:上升到顶部
   100:下降到底部
   其余0~100之间的数值为中间位置

 */
@property (nonatomic, assign) NSInteger       motorPosition;
@property (nonatomic, strong) NSString *       motorPositionTime;
@property (nonatomic, strong) NSString *       lightingState;
@property (nonatomic, strong) NSString *       lightingStateTime;
@property (nonatomic, strong) NSString *       sterilizingState;
@property (nonatomic, strong) NSString *       sterilizingStateTime;
@property (nonatomic, strong) NSString *       heatDryingState;
@property (nonatomic, strong) NSString *       heatDryingStateTime;
@property (nonatomic, strong) NSString *       windDryingState;
@property (nonatomic, strong) NSString *       windDryingStateTime;
@property (nonatomic, strong) NSString *       mainSwitchState;
@property (nonatomic, strong) NSString *       mainSwitchStateTime;
@property (nonatomic, strong) NSString *       exceptionInfo;
@property (nonatomic, strong) NSString *       exceptionInfoTime;

+ (HMClotheshorseStatus *)objectWithDeviceId:(NSString *)deviceId;

/**
 *  改变对应设备的状态
 *
 *  @param type     状态类型
 *  @param ctrlTime 控制时间
 *  @param status   功能状态: 1表示开,0 表示关
 *  @param deviceId 设备Id
 */
+ (BOOL)updateStatusType:(KStatusType)type ctrlTime:(NSString *)ctrlTime status:(int)status deviceId:(NSString *)deviceId;
@end


text:
static NSString  * const bannerCellIdentifier = @"bannerCellIdentifier";
static NSString  * const typeOneCellIdentifier = @"typeOneCellIdentifier";
static NSString  * const collectionCell1Identifier = @"HomePageTypeOneCollectionViewCell";
static NSString  * const collectionHeaderIndentifier = @"typeOneHeaderIndentifier";

@implementation HomeTypeOneTableViewCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (void)setModel:(ListItemModel *)model{
    _model =model;
    [self.myCollectionView reloadData];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _model.theme_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomePageTypeOneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCell1Identifier forIndexPath:indexPath];
    cell.model =_model.theme_list[indexPath.row];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    ListItemCollectionReusableView *view = (ListItemCollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collectionHeaderIndentifier forIndexPath:indexPath];
    view.headerTitleLabel.text = _model.groupName;
    return view;
}

@end