text:
/**
 *	BirtNavigationBar
 *	...
 */
BirtNavigationBar = Class.create( );
BirtNavigationBar.prototype = Object.extend( new AbstractUIComponent( ),
{
	_IMAGE_PATH : "birt/images/",
	_IMAGE_EXTENSION : ".gif",
	_IMAGE_FIRST_PAGE : !rtl?"FirstPage":"LastPage",
	_IMAGE_LAST_PAGE : !rtl?"LastPage":"FirstPage",
	_IMAGE_PREVIOUS_PAGE : !rtl?"PreviousPage":"NextPage",
	_IMAGE_NEXT_PAGE : !rtl?"NextPage":"PreviousPage",
	_IMAGE_DISABLED_SUFFIX : "_disabled",

	/**
	 *	Total number of pages.
	 */
	__oTotalPage : null,

	/**
	 *	Current page number.
	 */
	__oPageNumber : null,

	/**
	 *	Initialization routine required by "ProtoType" lib.
	 *	@return, void
	 */
	initialize : function( id )
	{
		this.__initBase( id );
		this.__oPageNumber = $( 'pageNumber' );
		this.__oTotalPage = $( 'totalPage' );
		this.__cb_installEventHandlers( );
	},

	/**
	 *	Binding data to the navigation bar UI. Data includes page number, total
	 *	page number (optional).
	 *
	 *	@data, data DOM tree (Schema TBD)
	 *	@return, void
	 */
	__cb_bind : function( data )
	{
		if ( !data )
		{
			return;
		}

		var oPageNumbers = data.getElementsByTagName( 'PageNumber' );
		if ( !oPageNumbers && !oPageNumbers[0] )
		{
			return;
		}

		this.__oPageNumber.innerHTML = oPageNumbers[0].firstChild.data;

		var oTotalPages = data.getElementsByTagName( 'TotalPage' );
		this.__oTotalPage.innerHTML = ( oTotalPages && oTotalPages[0] )? oTotalPages[0].firstChild.data : '+';

		var pageNumber = parseInt( this.__oPageNumber.firstChild.data );
		var totalPage = ( this.__oTotalPage.firstChild.data == '+' )? '+' : parseInt( this.__oTotalPage.firstChild.data );

		var oImgs = this.__instance.getElementsByTagName( "INPUT" );

		var isFirstPage = !( pageNumber > 1 );
		var isLastPage = !( totalPage == '+' || pageNumber < totalPage );

		oImgs[0].style.cursor = (!isFirstPage)? "pointer" : "default";
		oImgs[1].style.cursor = (!isFirstPage)? "pointer" : "default";
		oImgs[2].style.cursor = (!isLastPage)? "pointer" : "default";
		oImgs[3].style.cursor = (!isLastPage)? "pointer" : "default";

		oImgs[0].src = this._getImageFileName( this._IMAGE_FIRST_PAGE, isFirstPage );
		oImgs[1].src = this._getImageFileName( this._IMAGE_PREVIOUS_PAGE, isFirstPage );
		oImgs[2].src = this._getImageFileName( this._IMAGE_NEXT_PAGE, isLastPage );
		oImgs[3].src = this._getImageFileName( this._IMAGE_LAST_PAGE, isLastPage );
	},

	_getImageFileName : function( base, disabled )
	{
		return this._IMAGE_PATH + base + ( disabled?this._IMAGE_DISABLED_SUFFIX:"" ) + this._IMAGE_EXTENSION;
	},

	/**
	 *	Install native/birt event handlers.
	 *
	 *	@id, navigation bar id (optional since there is only one nav bar)
	 *	@return, void
	 */
	__cb_installEventHandlers : function( )
	{
		var oImgs = this.__instance.getElementsByTagName( 'INPUT' );

		if ( oImgs )
		{
			for ( var i = 0; i < oImgs.length; i++ )
			{
				if ( oImgs[i].type == 'image' )
				{
					Event.observe( oImgs[i], 'click', this.__neh_click.bindAsEventListener( this ), false );
				}
			}
		}

		// Observe "keydown" event
		this.keydown_closure = this.__neh_keydown.bindAsEventListener(this);
		Event.observe($('gotoPage'), 'keydown', this.keydown_closure, false);
	},

	/**
	 *	Handle press "Enter" key.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__neh_keydown: function( event )
	{
		// If press 'Enter' key
		if( event.keyCode == 13 )
		{
			this.__gotoGage( );
			Event.stop( event );
		}
	},

	/**
	 *	Handle clicking 'Goto' event.
	 *
	 *	@return, void
	 */
	__gotoGage : function( )
	{
		var iPageNo = -1;
		var totalPage = ( this.__oTotalPage.firstChild.data == '+' )? '+' : parseInt( this.__oTotalPage.firstChild.data );

		var oGotoPage = $( 'gotoPage' );
		var pageNo = oGotoPage.value;
		if ( pageNo != null && birtUtility.trim( pageNo ).length > 0 )
		{
			iPageNo = parseInt( pageNo );
		}
		if ( iPageNo > 0 && iPageNo <= totalPage )
		{
			birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE, { name : Constants.PARAM_PAGE, value : oGotoPage.value } );
		}
		else
		{
			alert( Constants.error.invalidPageNumber );
			oGotoPage.focus( );
		}
	},

	/**
	 *	Handle native event 'click'.
	 *
	 *	@event, incoming browser native event
	 *	@return, void
	 */
	__neh_click : function( event )
	{
		var pageNumber = parseInt( this.__oPageNumber.firstChild.data );
		var totalPage = ( this.__oTotalPage.firstChild.data == '+' )? '+' : parseInt( this.__oTotalPage.firstChild.data );

		var oBtn = Event.element( event );
		if ( oBtn )
		{
			switch ( oBtn.name )
			{
   				case 'first':
 				{
 					if ( pageNumber > 1 )
 					{
						birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE, { name : Constants.PARAM_PAGE, value : 1 } );
					}
 					break;
 				}
   				case 'previous':
 				{
 					if ( pageNumber > 1 )
 					{
						birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE, { name : Constants.PARAM_PAGE, value : pageNumber - 1 } );
					}
 					break;
 				}
   				case 'next':
 				{
 					if ( totalPage == '+' || pageNumber < totalPage )
 					{
	 					birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE, { name : Constants.PARAM_PAGE, value : pageNumber + 1 } );
 					}
 					break;
 				}
   				case 'last':
 				{
 					if ( totalPage == '+' || pageNumber < totalPage )
 					{
 						birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE, { name : Constants.PARAM_PAGE, value : totalPage } );
 					}
 					break;
 				}
   				case 'goto':
   				{
   					this.__gotoGage( );
   					break;
   				}
				default:
				{
					break;
				}
			}
		}
	},

	__get_current_page : function( )
	{
		return this.__oPageNumber.innerHTML;
	},

	/**
	 * Load current page. Triggered by init.
	 */
	__init_page : function( )
	{
		if( birtParameterDialog.collect_parameter( ) )
		{
			if ( this.__oPageNumber.firstChild )
			{
				var pageNumber = parseInt( this.__oPageNumber.firstChild.data );
				birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE_INIT, { name : Constants.PARAM_PAGE, value : pageNumber } );
			}
			else
			{
				birtEventDispatcher.broadcastEvent( birtEvent.__E_GETPAGE_INIT );
			}
		}
	}
}
);


text:
package com.google.ads.googleads.v10.enums;

public interface ListingGroupTypeEnumOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.enums.ListingGroupTypeEnum)
    com.google.protobuf.MessageOrBuilder {
}

redpajama_set_name: RedPajamaGithub


text:
require 'net/http'
uri = URI("https://bgg-json.azurewebsites.net/collection/edwalter")
@boardgamestring = Net::HTTP.get(uri)
games = JSON.parse(@boardgamestring)
games.each do |each_game|
  Game.create!(title: each_game["name"], thumbnail: each_game["thumbnail"], image: each_game["image"], player_count_min: each_game["minPlayers"], player_count_max: each_game["maxPlayers"], playing_time: each_game["playingTime"])
end

100.times do
  user_info = {
    email: Faker::Internet.email,
    username: Faker::Internet.user_name,
    password: "password",
  }
  User.create!(user_info)
end

5000.times do
  ownership_info = {
    game_id: rand(1..575),
    owner_id: rand(1..100)
  }
  Ownership.create!(ownership_info)
end


text:
package org.twuni.xmppt.xmpp;

import java.util.Collection;

import org.twuni.xmppt.xml.XMLElement;
import org.twuni.xmppt.xml.XMLElementFilter;

public abstract class PacketTransformer implements XMLElementFilter {

	public abstract Object transform( XMLElement element );

	public Object [] transform( Collection<? extends Object> objects ) {
		return transform( objects != null ? objects.toArray() : null );
	}

	public Object [] transform( Object... objects ) {
		int count = objects.length;
		Object [] packets = new Object [count];
		for( int i = 0; i < count; i++ ) {
			Object object = objects[i];
			Object packet = object;
			if( object instanceof XMLElement ) {
				XMLElement item = (XMLElement) object;
				if( matches( item ) ) {
					packet = transform( item );
				}
			}
			packets[i] = packet;
		}
		return packets;
	}

}


text:
package com.hazelcast.client.impl.protocol.task.transaction;

import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.XATransactionCreateCodec;
import com.hazelcast.client.impl.protocol.task.AbstractCallableMessageTask;
import com.hazelcast.instance.Node;
import com.hazelcast.nio.Connection;
import com.hazelcast.security.permission.TransactionPermission;
import com.hazelcast.transaction.TransactionContext;
import com.hazelcast.transaction.impl.xa.TransactionAccessor;
import com.hazelcast.transaction.impl.xa.XAService;

import java.security.Permission;

public class XATransactionCreateMessageTask
        extends AbstractCallableMessageTask<XATransactionCreateCodec.RequestParameters> {

    public XATransactionCreateMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected Object call() throws Exception {
        ClientEndpoint endpoint = getEndpoint();
        XAService xaService = getService(getServiceName());
        String ownerUuid = endpoint.getUuid();
        TransactionContext context = xaService.newXATransactionContext(parameters.xid, ownerUuid, (int) parameters.timeout, true);
        TransactionAccessor.getTransaction(context).begin();
        endpoint.setTransactionContext(context);
        return context.getTxnId();
    }

    @Override
    protected XATransactionCreateCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
        return XATransactionCreateCodec.decodeRequest(clientMessage);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return XATransactionCreateCodec.encodeResponse((String) response);
    }

    @Override
    public String getServiceName() {
        return XAService.SERVICE_NAME;
    }

    @Override
    public String getDistributedObjectName() {
        return null;
    }

    @Override
    public String getMethodName() {
        return null;
    }

    @Override
    public Object[] getParameters() {
        return null;
    }

    @Override
    public Permission getRequiredPermission() {
        return new TransactionPermission();
    }
}


text:
import { upperFirst } from "./index";
export = upperFirst;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/boilerplate_jasmine.iml" filepath="$PROJECT_DIR$/boilerplate_jasmine.iml" />
    </modules>
  </component>
</project>


text:
title: Double-base palindromes
localeTitle: Palíndromos de doble base
---
## Problema 36: palíndromos de doble base

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-36-double-base-palindromes/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
package pl.com.ergosoft.auth.persistence.entity;

import pl.com.ergosoft.auth.persistence.enums.AuthorityName;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;

@Entity
@Table(name = "AUTHORITY")
public class Authority {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "authority_seq")
    @SequenceGenerator(name = "authority_seq", sequenceName = "authority_seq", allocationSize = 1)
    private Long id;

    @Column(name = "NAME", length = 50)
    @NotNull
    @Enumerated(EnumType.STRING)
    private AuthorityName name;

    @ManyToMany(mappedBy = "authorities", fetch = FetchType.LAZY)
    private List<User> users;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public AuthorityName getName() {
        return name;
    }

    public void setName(AuthorityName name) {
        this.name = name;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}


text:
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/dot-luv/jquery-ui.css">

    <link rel="stylesheet" href="codemirror/codemirror.css">
    <link rel="stylesheet" href="codemirror/addon/hint/show-hint.css">

    <link rel="stylesheet" href="css/default.css">

        Template:
        <select name="template" id="template">
          <option value='empty.html'>Empty</option>
          <option value='canvas.html'>Canvas</option>
        </select>

        <button id="insert_template">Insert template</button>

        <textarea id="code" name="code">
        </textarea>


text:
package io.github.josehsantos.hack.lang.psi;

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

public interface HackListAssignmentVariables extends HackPsiElement {

  @NotNull
  HackAssignmentList getAssignmentList();

}


text:
{% extends base_template %}
{% block head %}{{ block.super }}
    {% include "imports/bootstrap.google-prettify.html" %}
{% endblock %}
{% block content %}

Build #{{ app.version }}: {{ app.name }}

See original app for the latest work in progress.

Downloads

            {% url "download_jad" app.domain app.id as url %}CommCare.jad

            {% url "download_jar" app.domain app.id as url %}CommCare.jar

            {% with "download_ccz" as download_ccz_id %}CommCare.ccz

Resource Files

        {% for path, source in files %}

                    {{ path }}

{{ source|force_escape }}

        {% empty %}

No Files

        {% endfor %}

    {% if app.copy_of and not files %}

            This build was made before I knew how to save the files for a specific build.
            To see this view for the current not-yet-built version of this app,
            click here.

    {% endif %}

{% url "download_ccz" app.domain app.id as ccz_url %}
{% include 'app_manager/partials/download_async_modal.html' with element_id=download_ccz_id download_url=ccz_url%}
{% endwith %}
{% endblock %}


text:
class EXPCL_PANDA_NATIVENET Socket_TCP_Listen : public Socket_IP
{
public:
PUBLISHED:
    Socket_TCP_Listen() {};
    ~Socket_TCP_Listen() {};
    inline bool OpenForListen(const Socket_Address & Inaddess, int backlog_size = 1024);
    inline bool GetIncomingConnection(Socket_TCP & newsession, Socket_Address &address);
public:
    inline bool GetIncomingConnection(SOCKET & newsession, Socket_Address &address);

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    Socket_IP::init_type();
    register_type(_type_handle, "Socket_TCP_Listen",
                  Socket_IP::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

////////////////////////////////////////////////////////////////////
// Function name : OpenForListen
// Description   : This function will initialize a listening Socket
////////////////////////////////////////////////////////////////////
inline bool Socket_TCP_Listen::OpenForListen(const Socket_Address & Inaddess, int backlog_size )
{
    ErrorClose();
    _socket = DO_NEWTCP();

    SetReuseAddress();

    if (DO_BIND(_socket, &Inaddess.GetAddressInfo()) != 0) {
      return ErrorClose();
    }

    if (DO_LISTEN(_socket, backlog_size) != 0) {
      return ErrorClose();
    }

    return true;
}
////////////////////////////////////////////////////////////////////
// Function name : GetIncomingConnection
// Description   : This function is used to accept new connections
////////////////////////////////////////////////////////////////////
inline bool Socket_TCP_Listen::GetIncomingConnection(SOCKET & newsession, Socket_Address &address)
{
    newsession = DO_ACCEPT(_socket, &address.GetAddressInfo());
    if (newsession == BAD_SOCKET)
        return false;
    return true;
}

inline bool Socket_TCP_Listen::GetIncomingConnection(Socket_TCP & newsession, Socket_Address &address)
{
    SOCKET sck;
    if(!GetIncomingConnection(sck,address))
        return false;

    newsession.SetSocket(sck);
    return true;
}

#endif //__SOCKET_TCP_LISTEN_H__


text:
from scurve import natural, utils
import tutils

class TestNatural:
    def test_point(self):
        tutils.is_complete(natural.Natural(1, 1))
        tutils.is_complete(natural.Natural(1, 3))
        tutils.is_complete(natural.Natural(2, 3))
        tutils.is_complete(natural.Natural(3, 3))
        tutils.is_complete(natural.Natural(3, 12))
        tutils.is_complete(natural.Natural(4, 3))
        tutils.is_complete(natural.Natural(4, 4))

    def test_index(self):
        tutils.symmetry(natural.Natural(1, 1))
        tutils.symmetry(natural.Natural(2, 3))
        tutils.symmetry(natural.Natural(2, 4))
        tutils.symmetry(natural.Natural(3, 2))
        tutils.symmetry(natural.Natural(3, 12))
        tutils.symmetry(natural.Natural(4, 4))

    def test_fromSize(self):
        z = natural.Natural(2, 3)
        z2 = natural.Natural.fromSize(2, len(z))
        assert z.dimension == z2.dimension
        assert z.size == z2.size

        z = natural.Natural(3, 256)
        z2 = natural.Natural.fromSize(3, len(z))
        assert z.dimension == z2.dimension
        assert z.size == z2.size


text:
package com.github.mvollebregt.wildmock.test.feedback;

import com.github.mvollebregt.wildmock.exceptions.WithClauseNotSatisfiedException;
import com.github.mvollebregt.wildmock.test.helpers.ArbitraryWildcardsMockClass;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static com.github.mvollebregt.wildmock.Wildmock.mock;
import static com.github.mvollebregt.wildmock.Wildmock.verify;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.*;

@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public class WithClauseNotSatisfiedExceptionTest {

    private ArbitraryWildcardsMockClass mock = mock(ArbitraryWildcardsMockClass.class);

    @Test
    public void testOneMatchWithClauseNotSatisfied() {
        // when
        mock.actionA("unexpected input");
        // then
        WithClauseNotSatisfiedException exception = expectThrows(WithClauseNotSatisfiedException.class, () ->
                verify(mock::actionA, String.class).with(wildcard -> wildcard.equals("expected input"))
        );
        assertTrue(exception.getMessage().contains("unexpected input"));
        assertEquals(singletonList(singletonList("unexpected input")),
                exception.getObservedWildcards().stream().map(Arrays::asList).collect(toList()));
    }

    @Test
    public void testTwoMatchesWithClauseNotSatisfied() {
        // when
        mock.actionA("first unexpected input");
        mock.actionA("second unexpected input");
        // then
        WithClauseNotSatisfiedException exception = expectThrows(WithClauseNotSatisfiedException.class, () ->
                verify(mock::actionA, String.class).with(wildcard -> wildcard.equals("expected input"))
        );
        String message = exception.getMessage();
        assertTrue(message.contains("first unexpected input") && message.contains("second unexpected input") &&
                message.contains("2 times"));
        assertEquals(asList(singletonList("first unexpected input"), singletonList("second unexpected input")),
                exception.getObservedWildcards().stream().map(Arrays::asList).collect(toList()));
    }

    @Test
    public void testTwoWildcardsWithClauseNotSatisfied() {
        // when
        mock.actionAB("first unexpected input", "second unexpected input");
        // then
        WithClauseNotSatisfiedException exception = expectThrows(WithClauseNotSatisfiedException.class, () ->
                verify(mock::actionAB, String.class, String.class).
                        with((firstParameter, secondParameter) -> firstParameter.equals("expected input"))
        );
        assertTrue(exception.getMessage().contains("first unexpected input, second unexpected input"));
        assertEquals(singletonList(asList("first unexpected input", "second unexpected input")),
                exception.getObservedWildcards().stream().map(Arrays::asList).collect(toList()));
    }
}


text:
package com.wumbleminky.luxincraft.client.model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.vecmath.Vector3f;

import com.wumbleminky.luxincraft.block.BlockFluid;

import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.client.resources.model.SimpleBakedModel;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraftforge.client.model.ISmartBlockModel;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * The fluid rendering setup associated with this class was originally created by kirderf1 for www.github.com/mraof/minestuck
 * When copying this code, please keep this comment or refer back to the original source in another way, if possible.
 */
@SideOnly(Side.CLIENT)
public class ModelFluidBlock implements ISmartBlockModel{

	static final float RENDER_OFFSET = 0.001F;

    public ModelFluidBlock(){

    }

	@Override
	public List getFaceQuads(EnumFacing facing)	{
		return null;
	}

	@Override
	public List getGeneralQuads(){
		return null;
	}

	@Override
	public boolean isAmbientOcclusion()	{
		return false;
	}

	@Override
	public boolean isGui3d(){
		return false;
	}

	@Override
	public boolean isBuiltInRenderer(){
		return false;
	}

	@Override
	public TextureAtlasSprite getTexture(){
		return null;
	}

	@SuppressWarnings("depcreation")
	@Override
	public ItemCameraTransforms getItemCameraTransforms(){
		return null;
	}

	private final Map<List<Float>, SimpleBakedModel> models = new HashMap<List<Float>, SimpleBakedModel>();

    @SuppressWarnings("deprecation")
	@Override
	public IBakedModel handleBlockState(IBlockState state){
		IExtendedBlockState extState = (IExtendedBlockState) state;
		float heightNW = extState.getValue(BlockFluid.HEIGHT_NW);
		float heightSW = extState.getValue(BlockFluid.HEIGHT_SW);
		float heightSE = extState.getValue(BlockFluid.HEIGHT_SE);
		float heightNE = extState.getValue(BlockFluid.HEIGHT_NE);
		float flow = extState.getValue(BlockFluid.FLOW_DIRECTION);

		return getModel((BlockFluid) state.getBlock(), Arrays.asList(heightSE, heightSW, heightNW, heightNE, flow));
	}

	private SimpleBakedModel getModel(BlockFluid block, List<Float> param){
		SimpleBakedModel model = models.get(param);
		if(model == null){
			model = this.buildModel(block, param);
			models.put(param, model);
		}

		return model;
	}

	private SimpleBakedModel buildModel(BlockFluid block, List<Float> param){

		List<List<BakedQuad>> faceQuads = new ArrayList<List<BakedQuad>>();
		for(int i = 0; i < 6; i++){
			if(i == EnumFacing.DOWN.ordinal())
				faceQuads.add(Arrays.asList(createQuad(new Vector3f(0, 0, 0), new Vector3f(1, 0, 0), new Vector3f(1, 0, 1), new Vector3f(0, 0, 1), block.getFluid().getStillIcon(), EnumFacing.DOWN)));
			else if(i == EnumFacing.UP.ordinal()){
				TextureAtlasSprite sprite = param.get(4) < -999F ? block.getFluid().getStillIcon() : block.getFluid().getFlowingIcon();
				BakedQuad quad1 = createQuad(new Vector3f(0, param.get(2), 0), new Vector3f(0, param.get(1), 1),
						new Vector3f(1, param.get(0), 1), new Vector3f(1, param.get(3), 0), sprite, EnumFacing.UP, param.get(4));
				BakedQuad quad2 = createQuad(new Vector3f(0, param.get(2) - RENDER_OFFSET, 0), new Vector3f(1, param.get(3) - RENDER_OFFSET, 0),
						new Vector3f(1, param.get(0) - RENDER_OFFSET, 1), new Vector3f(0, param.get(1) - RENDER_OFFSET, 1), sprite, EnumFacing.DOWN, param.get(4));
				faceQuads.add(Arrays.asList(quad1, quad2));
			}
			else{
				EnumFacing facing = EnumFacing.values()[i];
				float height1 = param.get(facing.getHorizontalIndex());
				float height2 = param.get((facing.getHorizontalIndex() + 1) % 4);
				int p = facing.getAxisDirection() == EnumFacing.AxisDirection.POSITIVE ? 1 : 0;
				float offset = facing.getAxisDirection().getOffset()*RENDER_OFFSET;

				if(facing.getAxis() == EnumFacing.Axis.X){
					BakedQuad quad1 = createQuad(new Vector3f(p, 0, p), new Vector3f(p, 0, 1-p), new Vector3f(p, height1, 1-p), new Vector3f(p, height2, p), block.getFluid().getFlowingIcon(), facing);
					BakedQuad quad2 = createQuad(new Vector3f(p - offset, 0, p), new Vector3f(p - offset, height2, p), new Vector3f(p - offset, height1, 1-p), new Vector3f(p - offset, 0, 1-p), block.getFluid().getFlowingIcon(), facing.getOpposite());
					faceQuads.add(Arrays.asList(quad1, quad2));
				} else	{
					BakedQuad quad1 = createQuad(new Vector3f(1-p, 0, p), new Vector3f(p, 0, p), new Vector3f(p, height1, p), new Vector3f(1-p, height2, p), block.getFluid().getFlowingIcon(), facing);
					BakedQuad quad2 = createQuad(new Vector3f(1-p, 0, p - offset), new Vector3f(1-p, height2, p - offset), new Vector3f(p, height1, p - offset), new Vector3f(p, 0, p - offset), block.getFluid().getFlowingIcon(), facing.getOpposite());
					faceQuads.add(Arrays.asList(quad1, quad2));
				}
			}
		}

		return new SimpleBakedModel(Collections.emptyList(), faceQuads, false, false, block.getFluid().getStillIcon(), null);
	}

	private BakedQuad createQuad(Vector3f vec1, Vector3f vec2, Vector3f vec3, Vector3f vec4, TextureAtlasSprite sprite, EnumFacing facing){
		return createQuad(vec1, vec2, vec3, vec4, sprite, facing, -1000F);
	}

	private BakedQuad createQuad(Vector3f vec1, Vector3f vec2, Vector3f vec3, Vector3f vec4, TextureAtlasSprite sprite, EnumFacing facing, float flowDir){
		int[] data = new int[28];
		int shade = getShade(facing);

		float xFlow = -1, zFlow = -1;
		if(flowDir > -999F)	{
			xFlow = MathHelper.sin(flowDir) * 0.25F;
			zFlow = MathHelper.cos(flowDir) * 0.25F;
		}

		Vector3f[] vectors = {vec1, vec2, vec3, vec4};
		for(int i = 0; i < 4; i++){
			Vector3f vec = vectors[i];
			int index = i*7;
			data[index] = Float.floatToRawIntBits(vec.x);
			data[index + 1] = Float.floatToRawIntBits(vec.y);
			data[index + 2] = Float.floatToRawIntBits(vec.z);
			data[index + 3] = shade;
			float u = sprite.getMaxU() - sprite.getMinU();
			float v = sprite.getMaxV() - sprite.getMinV();
			if(facing.getAxis() == EnumFacing.Axis.X){
				data[index + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU(vec.z*16F));
				data[index + 5] = Float.floatToRawIntBits(sprite.getInterpolatedV(16F - vec.y*16F));
			} else if(facing.getAxis() == EnumFacing.Axis.Y){
				if(flowDir < -999F)	{
					data[index + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU(vec.x*16F));
					data[index + 5] = Float.floatToRawIntBits(sprite.getInterpolatedV(vec.z*16F));
				} else	{
					data[index + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU(8F + ((vec.z*2-1)*xFlow + (vec.x*2-1)*zFlow)*16F));	//The x and z values here are only expected to be 0 or 1.
					data[index + 5] = Float.floatToRawIntBits(sprite.getInterpolatedV(8F + ((1-2*vec.x)*xFlow + (vec.z*2-1)*zFlow)*16F));
				}
			} else	{
				data[index + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU(vec.x*16F));
				data[index + 5] = Float.floatToRawIntBits(sprite.getInterpolatedV(16F - vec.y*16F));
			}

		}
		return new BakedQuad(data, -1, facing);
	}

	private int getShade(EnumFacing facing) {	//Copied from FaceBakery (Only the end result, and not the process)
		if(facing == EnumFacing.DOWN)
			return -8421505;
		if(facing == EnumFacing.SOUTH || facing == EnumFacing.NORTH)
			return -3355444;
		if(facing == EnumFacing.WEST || facing == EnumFacing.EAST)
			return -6710887;
		else return -1;
	}
}


text:
#ifndef ALIGLAUBERNUCLEON_H
#define ALIGLAUBERNUCLEON_H

////////////////////////////////////////////////////////////////////////////////
//
//  AliGlauberNucleon
//  support class for Glauber MC
//
//  origin: PHOBOS experiment
//  alification: Mikolaj Krzewicki, Nikhef, mikolaj.krzewicki@cern.ch
//
////////////////////////////////////////////////////////////////////////////////

class TNamed;

class AliGlauberNucleon : public TNamed {

private:
   Double32_t fX;            //Position of nucleon
   Double32_t fY;            //Position of nucleon
   Double32_t fZ;            //Position of nucleon
   Bool_t     fInNucleusA;   //=1 from nucleus A, =0 from nucleus B
   Int_t      fNColl;        //Number of binary collisions
   Double32_t fSigNN;        //Interaction cross section of this Nucleon

public:
   AliGlauberNucleon();
   virtual   ~AliGlauberNucleon() {}

   void       Collide()            {fNColl++;}
   Int_t      GetNColl()     const {return fNColl;}
   Double_t   GetSigNN()     const {return fSigNN;}
   Double_t   GetX()         const {return fX;}
   Double_t   GetY()         const {return fY;}
   Double_t   GetZ()         const {return fZ;}
   Bool_t     IsInNucleusA() const {return fInNucleusA;}
   Bool_t     IsInNucleusB() const {return !fInNucleusA;}
   Bool_t     IsSpectator()  const {return !fNColl;}
   Bool_t     IsWounded()    const {return fNColl;}
   void       Reset()              {fNColl=0;}
   void       SetInNucleusA()      {fInNucleusA=1;}
   void       SetInNucleusB()      {fInNucleusA=0;}
   void       SetSigNN(Double_t s) {fSigNN=s;}
   void       SetXYZ(Double_t x, Double_t y, Double_t z) {fX=x; fY=y; fZ=z;}

   ClassDef(AliGlauberNucleon,2)
};

#endif


text:
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/comprehend/model/PiiEntityType.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Comprehend
{
namespace Model
{

  /**
   *
Specifies one of the label or labels that categorize the personally
   * identifiable information (PII) entity being analyzed.

See Also:

   * AWS
   * API Reference

   */
  class AWS_COMPREHEND_API EntityLabel
  {
  public:
    EntityLabel();
    EntityLabel(Aws::Utils::Json::JsonView jsonValue);
    EntityLabel& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The name of the label.

     */
    inline const PiiEntityType& GetName() const{ return m_name; }

    /**
     *
The name of the label.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the label.

     */
    inline void SetName(const PiiEntityType& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the label.

     */
    inline void SetName(PiiEntityType&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the label.

     */
    inline EntityLabel& WithName(const PiiEntityType& value) { SetName(value); return *this;}

    /**
     *
The name of the label.

     */
    inline EntityLabel& WithName(PiiEntityType&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The level of confidence that Amazon Comprehend has in the accuracy of the
     * detection.

     */
    inline double GetScore() const{ return m_score; }

    /**
     *
The level of confidence that Amazon Comprehend has in the accuracy of the
     * detection.

     */
    inline bool ScoreHasBeenSet() const { return m_scoreHasBeenSet; }

    /**
     *
The level of confidence that Amazon Comprehend has in the accuracy of the
     * detection.

     */
    inline void SetScore(double value) { m_scoreHasBeenSet = true; m_score = value; }

    /**
     *
The level of confidence that Amazon Comprehend has in the accuracy of the
     * detection.

     */
    inline EntityLabel& WithScore(double value) { SetScore(value); return *this;}

  private:

    PiiEntityType m_name;
    bool m_nameHasBeenSet = false;

    double m_score;
    bool m_scoreHasBeenSet = false;
  };

} // namespace Model
} // namespace Comprehend
} // namespace Aws


text:
/*                                                 */
/*   The script must be run from the app folder!   */
/*                                                 */

const assert = require("assert");
assert.equal(process.cwd().substr(process.cwd().length - 3), "app", "You must run the test file from where the app.js is located! (cd app; node ../test.js)");
const glob = require("./app/global.js");
const fs = require("fs");
const vm = require("vm");

/* Test nameContainsInvalidChars: */

console.log("Testing nameContainsInvalidChars");

const invalidStrings = ["_", "<", ">", "|", "*", "\\", "/", "!", ":", ";", ".", "&", "Gus      Ek", "GusEk", "5", ];
for (var i = 0; i < invalidStrings.length; ++i) {
        assert.equal(glob.nameContainsInvalidChars(invalidStrings[i]), true, invalidStrings[i]);
}

const validStrings = ["Gus Ek", "Bo Gus Hen Ek", "Bo-Gus Ek", "- -", "gus ek"];
for (var i = 0; i < validStrings.length; ++i) {
        assert.equal(glob.nameContainsInvalidChars(validStrings[i]), false, validStrings[i]);
}

/* Test layoutValid */

console.log("Testing layoutValid");

const content = fs.readFileSync("./models/admin.js", {encoding: "utf-8"});
const func = getFunc(content, "layoutValid");
const sandbox = {JSON: JSON, console: console};
const script = new vm.Script(func);
const context = new vm.createContext(sandbox);
script.runInContext(context);

assert.equal(sandbox.layoutValid('[[{"id": 0, "type": "seat"}]]'), true, "FAILED: layoutValid");
assert.equal(sandbox.layoutValid('[[{"id": "bla", "type": "seat"}]]'), false, "FAILED: layoutValid");
assert.equal(sandbox.layoutValid('[[{"id": 0, "type": "seatasd"}]]'), false, "FAILED: layoutValid");
assert.equal(sandbox.layoutValid('{id: {}}'), false, "FAILED: layoutValid");

/* --------------------------------------------- */

console.log("\nTests succeeded!");

/* --------------------------------------------- */

function getFunc(str, funcName)
{
        var funcIndex = str.indexOf("function " + funcName);

        if (funcIndex === -1) {
                return false;
        } else {
                var clip = str.substring(funcIndex, str.length);

                var funcStartIndex = clip.indexOf("{");
                var funcEndIndex = false;
                var numFound = 0;
                for (var pos = funcStartIndex; pos < clip.length; ++pos) {
                        if (clip[pos] === "{")
                                ++numFound;
                        else if (clip[pos] === "}")
                                --numFound;

                        if (numFound === 0) {
                                funcEndIndex = pos;
                                break;
                        }
                }

                if (funcEndIndex === false)
                        return false;
                else
                        return clip.substring(0, funcEndIndex + 1);
        }
}


text:
<title>RISC-V-Options - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="RISC_002dV_002dDependent.html#RISC_002dV_002dDependent" title="RISC-V-Dependent">
<link rel="next" href="RISC_002dV_002dDirectives.html#RISC_002dV_002dDirectives" title="RISC-V-Directives">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: RISC-V-Directives,
Up: RISC-V-Dependent

9.37.1 RISC-V Options

The following table lists all available RISC-V specific options.

-fpic
-fPIC
Generate position-independent code

-fno-pic
Don't generate position-independent code (default)

-march=ISA
Select the base isa, as specified by ISA.  For example -march=rv32ima.

-mabi=ABI
Selects the ABI, which is either "ilp32" or "lp64", optionally followed
by "f", "d", or "q" to indicate single-precision, double-precision, or
quad-precision floating-point calling convention, or none to indicate
the soft-float calling convention.  Also, "ilp32" can optionally be followed
by "e" to indicate the RVE ABI, which is always soft-float.

-mrelax
Take advantage of linker relaxations to reduce the number of instructions
required to materialize symbol addresses. (default)

-mno-relax
Don't do linker relaxations.


text:
string-functions
================

A utility page for performing a number of text transformations.


text:
package com.hazelcast.aggregation.impl;

import com.hazelcast.aggregation.Aggregator;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;

import java.io.IOException;

public final class IntegerSumAggregator<I> extends AbstractAggregator<I, Integer, Long>
        implements IdentifiedDataSerializable {

    private long sum;

    public IntegerSumAggregator() {
        super();
    }

    public IntegerSumAggregator(String attributePath) {
        super(attributePath);
    }

    @Override
    public void accumulateExtracted(I entry, Integer value) {
        sum += value;
    }

    @Override
    public void combine(Aggregator aggregator) {
        IntegerSumAggregator integerSumAggregator = (IntegerSumAggregator) aggregator;
        this.sum += integerSumAggregator.sum;
    }

    @Override
    public Long aggregate() {
        return sum;
    }

    @Override
    public int getFactoryId() {
        return AggregatorDataSerializerHook.F_ID;
    }

    @Override
    public int getId() {
        return AggregatorDataSerializerHook.INT_SUM;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeUTF(attributePath);
        out.writeLong(sum);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        this.attributePath = in.readUTF();
        this.sum = in.readLong();
    }

}


text:
#ifndef _Sound_h_
#define _Sound_h_

#include "Thing.h"

/*
	A Sound is a structure that can hold the samples of a monaural sound.

	- length
		The number of doubles required to hold the sound.

	- samplingFrequencyInHertz
		The inverse of the time step between consecutive samples.

	- samples
		The doubles that hold the sound. The length of this array is `length`.
*/
typedef struct {
	double *samples;
	int length;
	double samplingFrequencyInHertz;
} Sound;

inline static void Sound_initWithData (Sound *me, double *samples, int length, double samplingFrequencyInHertz) {
	my samples = samples;
	my length = length;
	my samplingFrequencyInHertz = samplingFrequencyInHertz;
}

inline static void Sound_initWithLengthAndSamplingFrequency (Sound *me, int length, double samplingFrequencyInHertz) {
	my samples = (double *) calloc (length, sizeof * my samples);
	if (my samples == NULL) {
		return;
	}
	my length = length;
	my samplingFrequencyInHertz = samplingFrequencyInHertz;
}

inline static bool Sound_isValid (Sound *me) {
	return my samples != NULL;
}

inline static void Sound_initAsSweep (Sound *me, double duration, double samplingFrequency, double endFrequency) {
	Sound_initWithLengthAndSamplingFrequency (me, duration * samplingFrequency, samplingFrequency);
	if (! Sound_isValid (me)) return;
	const double samplingPeriod = 1.0 / samplingFrequency;
	double phase = 0.0;
	for (int isamp = 0; isamp < my length; isamp ++) {
		const double time = (double) isamp / samplingFrequency;
		const double fractionThrough = time / duration;
		const double localFrequency = fractionThrough * endFrequency;
		const double dphase = 2.0 * M_PI * localFrequency * samplingPeriod;
		phase += dphase;
		my samples [isamp] = 0.9 * sin (phase);
	}
}

inline static void Sound_destroy (Sound *me) {
	if (my samples) {
		free (my samples);
		my samples = NULL;
	}
}

inline static void Sound_fillWithNuttallWindow (Sound *me) {
	const double a0 = 0.355768, a1 = -0.487396, a2 = 0.144232, a3 = -0.012604;
	const double fac1 = 2 * M_PI / (my length - 1), fac2 = 2.0 * fac1, fac3 = 3.0 * fac1;
	for (int isamp = 0; isamp < my length; isamp ++) {
		double value = a0 + a1 * cos (fac1 * isamp) + a2 * cos (fac2 * isamp) + a3 * cos (fac3 * isamp);
		my samples [isamp] = value;
		//fprintf (stderr, "window %d %g\n", isamp, my window [isamp]);
	}
}

inline static double Sound_getSum (Sound *me) {
	double sum = 0.0;
	for (int isamp = 0; isamp < my length; isamp ++) {
		sum += my samples [isamp];
	}
	return sum;
}

inline static double Sound_getSumOfSquares (Sound *me) {
	double sumOfSquares = 0.0;
	for (int isamp = 0; isamp < my length; isamp ++) {
		sumOfSquares += my samples [isamp] * my samples [isamp];
	}
	return sumOfSquares;
}

inline static double Sound_getMean (Sound *me) {
	double sum = Sound_getSum (me);
	return sum / my length;
}

inline static void Sound_addConstant (Sound *me, double constant) {
	for (int isamp = 0; isamp < my length; isamp ++) {
		my samples [isamp] += constant;
	}
}

inline static void Sound_multiplyByConstant (Sound *me, double constant) {
	for (int isamp = 0; isamp < my length; isamp ++) {
		my samples [isamp] *= constant;
	}
}

inline static void Sound_subtractMean (Sound *me) {
	double mean = Sound_getMean (me);
	Sound_addConstant (me, - mean);
}

inline static void Sound_normalize (Sound *me) {
	Sound_subtractMean (me);
	double sumOfSquares = Sound_getSumOfSquares (me);
	if (my length < 2) return;
	double stdev = sqrt (sumOfSquares / (my length - 1));
	if (stdev == 0.0) return;
	Sound_multiplyByConstant (me, 1.0 / stdev);
}

/**
	@pre   your length >= my length
*/
inline static void Sound_multiplyByOtherSound (Sound *me, Sound *you) {
	for (int isamp = 0; isamp < my length; isamp ++) {
		my samples [isamp] *= your samples [isamp];
	}
}

/**
	@pre   your length >= my length
	@pre   your samples [1..my length] != 0.0
*/
inline static void Sound_divideByOtherSound (Sound *me, Sound *you) {
	for (int isamp = 0; isamp < my length; isamp ++) {
		my samples [isamp] /= your samples [isamp];
	}
}

inline static int Sound_getBestSpectrumLength (Sound *me) {
	int bestSpectrumLength = 2;
	while (bestSpectrumLength < my length)
		bestSpectrumLength *= 2;
	return bestSpectrumLength;
}

/* End of file Sound.h */
#endif


text:
@interface GCViewController : UIViewController {

}

@end


text:
<?php

namespace Helloworld\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
	private $greetingService;

	public function indexAction()
	{
		/* 发送503错误,用于网站维护
		$resp = new \Zend\Http\PhpEnvironment\Response;
		$resp->setStatusCode(503);
		return $resp;
		*/

		/* 重定向 */
		//$this->redirect()->toUrl('http://www.baidu.com');
		//$this->redirect()->toRoute('sayhello');

		//$url = $this->url()->fromRoute('sayhello', array('a','b'));
		//$test1 = $this->params()->fromHeader();
		//$test2 = $this->params()->fromPost();

		/* 设置layout */
		$this->layout('layout/helloWorldLayout');

		/* flash message */
		$this->flashMessenger()->addMessage('Der Datensatz wurde gelöscht');

		$flashMessenger = $this->flashMessenger();
		if ($flashMessenger->hasMessages()) {
			$return['messages'] = $flashMessenger->getMessages();
		}

		/* P108 widget略 */
		//$widget = $this->forward()
		//				->dispatch('Helloworld\Controller\Widget');

		return new ViewModel(
			array(
				'event' => '吃饭',
				'place' => '柏林',
				'date' => $this->currentDateA(),
				'greeting' => $this->greetingService->getGreeting(),
			)
		);
	}

	public function setGreetingService($service)
	{
		$this->greetingService = $service;
	}
}


text:
package lz4

import (
	"encoding/binary"
	"errors"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"runtime"
	"sync"
	"sync/atomic"
)

// errEndOfBlock is returned by readBlock when it has reached the last block of the frame.
// It is not an error.
var errEndOfBlock = errors.New("end of block")

// Reader implements the LZ4 frame decoder.
// The Header is set after the first call to Read().
// The Header may change between Read() calls in case of concatenated frames.
type Reader struct {
	Header
	Pos      int64 // position within the source
	src      io.Reader
	checksum hash.Hash32    // frame hash
	wg       sync.WaitGroup // decompressing go routine wait group
	data     []byte         // buffered decompressed data
	window   []byte         // 64Kb decompressed data window
}

// NewReader returns a new LZ4 frame decoder.
// No access to the underlying io.Reader is performed.
func NewReader(src io.Reader) *Reader {
	return &Reader{
		src:      src,
		checksum: hashPool.Get(),
	}
}

// readHeader checks the frame magic number and parses the frame descriptoz.
// Skippable frames are supported even as a first frame although the LZ4
// specifications recommends skippable frames not to be used as first frames.
func (z *Reader) readHeader(first bool) error {
	defer z.checksum.Reset()

	for {
		var magic uint32
		if err := binary.Read(z.src, binary.LittleEndian, &magic); err != nil {
			if !first && err == io.ErrUnexpectedEOF {
				return io.EOF
			}
			return err
		}
		z.Pos += 4
		if magic>>8 == frameSkipMagic>>8 {
			var skipSize uint32
			if err := binary.Read(z.src, binary.LittleEndian, &skipSize); err != nil {
				return err
			}
			z.Pos += 4
			m, err := io.CopyN(ioutil.Discard, z.src, int64(skipSize))
			z.Pos += m
			if err != nil {
				return err
			}
			continue
		}
		if magic != frameMagic {
			return fmt.Errorf("lz4.Read: invalid frame magic number: got %x expected %x", magic, frameMagic)
		}
		break
	}

	// header
	var buf [8]byte
	if _, err := io.ReadFull(z.src, buf[:2]); err != nil {
		return err
	}
	z.Pos += 2

	b := buf[0]
	if b>>6 != Version {
		return fmt.Errorf("lz4.Read: invalid version: got %d expected %d", b>>6, Version)
	}
	z.BlockDependency = b>>5&1 == 0
	z.BlockChecksum = b>>4&1 > 0
	frameSize := b>>3&1 > 0
	z.NoChecksum = b>>2&1 == 0
	// 	z.Dict = b&1 > 0

	bmsID := buf[1] >> 4 & 0x7
	bSize, ok := bsMapID[bmsID]
	if !ok {
		return fmt.Errorf("lz4.Read: invalid block max size: %d", bmsID)
	}
	z.BlockMaxSize = bSize

	z.checksum.Write(buf[0:2])

	if frameSize {
		if err := binary.Read(z.src, binary.LittleEndian, &z.Size); err != nil {
			return err
		}
		z.Pos += 8
		binary.LittleEndian.PutUint64(buf[:], z.Size)
		z.checksum.Write(buf[0:8])
	}

	// 	if z.Dict {
	// 		if err := binary.Read(z.src, binary.LittleEndian, &z.DictID); err != nil {
	// 			return err
	// 		}
	// 		z.Pos += 4
	// 		binary.LittleEndian.PutUint32(buf[:], z.DictID)
	// 		z.checksum.Write(buf[0:4])
	// 	}

	// header checksum
	if _, err := io.ReadFull(z.src, buf[:1]); err != nil {
		return err
	}
	z.Pos++
	if h := byte(z.checksum.Sum32() >> 8 & 0xFF); h != buf[0] {
		return fmt.Errorf("lz4.Read: invalid header checksum: got %v expected %v", buf[0], h)
	}

	z.Header.done = true

	return nil
}

// Read decompresses data from the underlying source into the supplied buffer.
//
// Since there can be multiple streams concatenated, Header values may
// change between calls to Read(). If that is the case, no data is actually read from
// the underlying io.Reader, to allow for potential input buffer resizing.
//
// Data is buffered if the input buffer is too small, and exhausted upon successive calls.
//
// If the buffer is large enough (typically in multiples of BlockMaxSize) and there is
// no block dependency, then the data will be decompressed concurrently based on the GOMAXPROCS value.
func (z *Reader) Read(buf []byte) (n int, err error) {
	if !z.Header.done {
		if err = z.readHeader(true); err != nil {
			return
		}
	}

	if len(buf) == 0 {
		return
	}

	// exhaust remaining data from previous Read()
	if len(z.data) > 0 {
		n = copy(buf, z.data)
		z.data = z.data[n:]
		if len(z.data) == 0 {
			z.data = nil
		}
		return
	}

	// Break up the input buffer into BlockMaxSize blocks with at least one block.
	// Then decompress into each of them concurrently if possible (no dependency).
	// In case of dependency, the first block will be missing the window (except on the
	// very first call), the rest will have it already since it comes from the previous block.
	wbuf := buf
	zn := (len(wbuf) + z.BlockMaxSize - 1) / z.BlockMaxSize
	zblocks := make([]block, zn)
	for zi, abort := 0, uint32(0); zi < zn && atomic.LoadUint32(&abort) == 0; zi++ {
		zb := &zblocks[zi]
		// last block may be too small
		if len(wbuf) < z.BlockMaxSize+len(z.window) {
			wbuf = make([]byte, z.BlockMaxSize+len(z.window))
		}
		copy(wbuf, z.window)
		if zb.err = z.readBlock(wbuf, zb); zb.err != nil {
			break
		}
		wbuf = wbuf[z.BlockMaxSize:]
		if !z.BlockDependency {
			z.wg.Add(1)
			go z.decompressBlock(zb, &abort)
			continue
		}
		// cannot decompress concurrently when dealing with block dependency
		z.decompressBlock(zb, nil)
		// the last block may not contain enough data
		if len(zb.data) >= winSize {
			if len(z.window) == 0 {
				z.window = make([]byte, winSize)
			}
			copy(z.window, zb.data[len(zb.data)-winSize:])
		}
	}
	z.wg.Wait()

	// since a block size may be less then BlockMaxSize, trim the decompressed buffers
	for _, zb := range zblocks {
		if zb.err != nil {
			if zb.err == errEndOfBlock {
				return n, z.close()
			}
			return n, zb.err
		}
		bLen := len(zb.data)
		z.checksum.Write(zb.data)
		m := copy(buf[n:], zb.data)
		// buffer the remaining data (this is necessarily the last block)
		if m < bLen {
			z.data = zb.data[m:]
		}
		n += m
	}

	return
}

// readBlock reads an entire frame block from the frame.
// The input buffer is the one that will receive the decompressed data.
// If the end of the frame is detected, it returns the errEndOfBlock error.
func (z *Reader) readBlock(buf []byte, b *block) error {
	var bLen int32
	if err := binary.Read(z.src, binary.LittleEndian, &bLen); err != nil {
		return err
	}
	z.Pos += 4

	switch {
	case bLen == 0:
		return errEndOfBlock
	case bLen > 0:
		b.compressed = true
		b.data = buf
		b.zdata = make([]byte, bLen)
	default:
		b.data = buf[:-bLen]
		b.zdata = buf[:-bLen]
	}
	if _, err := io.ReadFull(z.src, b.zdata); err != nil {
		return err
	}

	if z.BlockChecksum {
		if err := binary.Read(z.src, binary.LittleEndian, &b.checksum); err != nil {
			return err
		}
		xxh := hashPool.Get()
		defer hashPool.Put(xxh)
		xxh.Write(b.zdata)
		if h := xxh.Sum32(); h != b.checksum {
			return fmt.Errorf("lz4.Read: invalid block checksum: got %x expected %x", h, b.checksum)
		}
	}

	return nil
}

// decompressBlock decompresses a frame block.
// In case of an error, the block err is set with it and abort is set to 1.
func (z *Reader) decompressBlock(b *block, abort *uint32) {
	if abort != nil {
		defer z.wg.Done()
	}
	if b.compressed {
		n := len(z.window)
		m, err := UncompressBlock(b.zdata, b.data, n)
		if err != nil {
			if abort != nil {
				atomic.StoreUint32(abort, 1)
			}
			b.err = err
			return
		}
		b.data = b.data[n : n+m]
	}
	z.Pos += int64(len(b.data))
}

// close validates the frame checksum (if any) and checks the next frame (if any).
func (z *Reader) close() error {
	if !z.NoChecksum {
		var checksum uint32
		if err := binary.Read(z.src, binary.LittleEndian, &checksum); err != nil {
			return err
		}
		if checksum != z.checksum.Sum32() {
			return fmt.Errorf("lz4.Read: invalid frame checksum: got %x expected %x", z.checksum.Sum32(), checksum)
		}
	}

	// get ready for the next concatenated frame, but do not change the position
	pos := z.Pos
	z.Reset(z.src)
	z.Pos = pos

	// since multiple frames can be concatenated, check for another one
	return z.readHeader(false)
}

// Reset discards the Reader's state and makes it equivalent to the
// result of its original state from NewReader, but reading from r instead.
// This permits reusing a Reader rather than allocating a new one.
func (z *Reader) Reset(r io.Reader) {
	z.Header = Header{}
	z.Pos = 0
	z.src = r
	z.checksum.Reset()
	z.data = nil
	z.window = nil
}

// WriteTo decompresses the data from the underlying io.Reader and writes it to the io.Writer.
// Returns the number of bytes written.
func (z *Reader) WriteTo(w io.Writer) (n int64, err error) {
	cpus := runtime.GOMAXPROCS(0)
	var buf []byte

	// The initial buffer being nil, the first Read will be only read the compressed frame options.
	// The buffer can then be sized appropriately to support maximum concurrency decompression.
	// If multiple frames are concatenated, Read() will return with no data decompressed but with
	// potentially changed options. The buffer will be resized accordingly, always trying to
	// maximize concurrency.
	for {
		nsize := 0
		// the block max size can change if multiple streams are concatenated.
		// Check it after every Read().
		if z.BlockDependency {
			// in case of dependency, we cannot decompress concurrently,
			// so allocate the minimum buffer + window size
			nsize = len(z.window) + z.BlockMaxSize
		} else {
			// if no dependency, allocate a buffer large enough for concurrent decompression
			nsize = cpus * z.BlockMaxSize
		}
		if nsize != len(buf) {
			buf = make([]byte, nsize)
		}

		m, er := z.Read(buf)
		if er != nil && er != io.EOF {
			return n, er
		}
		m, err = w.Write(buf[:m])
		n += int64(m)
		if err != nil || er == io.EOF {
			return
		}
	}
}


text:
import NoSleep from "nosleep.js";
import playPauseButton from "./components/generic/playPauseButton";
import { setProgress } from "./components/generic/progress";
import bell from "./bell";
import timer from "./components/pages/timer";
import header from "./components/generic/header";
import settings from "./components/pages/settings";
import about from "./components/pages/about";
import home, { HomeTransitionTypes } from "./components/pages/home";
import customTimer, {
  CustomTimerTransitionTypes,
} from "./components/pages/customTimer";

const noSleep = new NoSleep();

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
  k: infer I
) => void
  ? I
  : never;

type ValueOf<T> = T[keyof T];

type State = ValueOf<typeof states>;

const stateMachineObject = {} as UnionToIntersection<State>;

const getState = (): State => Object.getPrototypeOf(stateMachineObject);
const transitionTo = (stateObject: State): UnionToIntersection<State> =>
  Object.setPrototypeOf(stateMachineObject, stateObject);

const data: {
  displayTime?: number;
  totalTime?: number;
} = {};

const startRenderLoop = (startTime: number) =>
  requestAnimationFrame(function renderLoop() {
    if (getState() !== states.timing) return;
    requestAnimationFrame(renderLoop);
    const newDisplayTime = Math.max(
      Math.round((data.totalTime! * 1000 + startTime - Date.now()) / 1000),
      0
    );
    if (newDisplayTime === data.displayTime) return;
    if (!newDisplayTime) stateMachineObject.finishTimer();
    data.displayTime = newDisplayTime;
    setProgress(data.totalTime!, data.displayTime);
  });

const states = {
  about: {
    toHome() {
      transitionTo(states.home);
      history.back();
      header.switchHomeToAbout();
      about.transitionOut();
      home.transitionIn();
    },
  },
  customTimer: {
    toAbout() {
      transitionTo(states.about);
      customTimer.transitionOut(CustomTimerTransitionTypes.left);
      location.replace("#about");
      header.switchAboutToHome();
      about.transitionIn();
    },
    toHome() {
      transitionTo(states.home);
      customTimer.transitionOut(CustomTimerTransitionTypes.zoom);
      home.transitionIn();
    },
    startTimer(timerLengthInSeconds: number) {
      transitionTo(states.timing);
      location.replace("#timer");
      header.hideControls();
      timer.transitionIn();
      customTimer.transitionOut(CustomTimerTransitionTypes.left);
      playPauseButton.enable();
      data.totalTime = timerLengthInSeconds;
      noSleep.enable();
      startRenderLoop(Date.now());
    },
    toSettings() {
      transitionTo(states.settings);
      customTimer.transitionOut(CustomTimerTransitionTypes.right);
      location.replace("#settings");
      header.switchSettingsToHome();
      settings.transitionIn();
    },
  },
  finished: {
    stopTimer() {
      transitionTo(states.home);
      timer.transitionOut();
      home.transitionIn();
      header.showControls();
      history.back();
      noSleep.disable();
      bell.stop();
    },
  },
  home: {
    toAbout() {
      transitionTo(states.about);
      location.hash = "about";
      header.switchAboutToHome();
      home.transitionOut(HomeTransitionTypes.left);
      about.transitionIn();
    },
    toCustomTimer() {
      transitionTo(states.customTimer);
      location.hash = "custom-timer";
      home.transitionOut(HomeTransitionTypes.vertical);
      customTimer.transitionIn();
    },
    toSettings() {
      transitionTo(states.settings);
      location.hash = "settings";
      header.switchSettingsToHome();
      home.transitionOut(HomeTransitionTypes.right);
      settings.transitionIn();
    },
    startTimer(timerLengthInSeconds: number) {
      transitionTo(states.timing);
      location.hash = "timer";
      header.hideControls();
      home.transitionOut(HomeTransitionTypes.left);
      timer.transitionIn();
      playPauseButton.enable();
      data.totalTime = timerLengthInSeconds;
      noSleep.enable();
      startRenderLoop(Date.now());
    },
  },
  paused: {
    resumeTimer() {
      transitionTo(states.timing);
      playPauseButton.enable();
      noSleep.enable();
      startRenderLoop(
        Date.now() - (data.totalTime! - data.displayTime!) * 1000
      );
    },
    stopTimer() {
      transitionTo(states.home);
      timer.transitionOut();
      header.showControls();
      history.back();
      home.transitionIn();
      noSleep.disable();
    },
  },
  settings: {
    toHome() {
      transitionTo(states.home);
      history.back();
      header.switchHomeToSettings();
      settings.transitionOut();
      home.transitionIn();
    },
  },
  timing: {
    pauseTimer() {
      transitionTo(states.paused);
    },
    finishTimer() {
      transitionTo(states.finished);
      timer.finish();
      bell.start();
    },
    stopTimer() {
      transitionTo(states.home);
      history.back();
      timer.transitionOut();
      header.showControls();
      home.transitionIn();
      noSleep.disable();
    },
  },
};

export default transitionTo(states.home);


text:
var request = require('request');
var fs = require('fs');

module.exports = {

  // Write routes object to router file
  writeRoutes: function(routes) {
    fs.writeFileSync('config/routes.js', 'module.exports.routes = ' + JSON.stringify(routes));
  },

  // Write routes object to blueprint config file
  writeBlueprint: function(config) {
    config = {
      blueprints: config
    };
    fs.writeFileSync('config/blueprints.js', 'module.exports = ' + JSON.stringify(config));
  },

  // Starts sails server, makes request, returns response, kills sails server
  testRoute: function(method, options, callback) {

    // Prefix url with domain:port
    if (typeof options === 'string') {
      options = {url: 'http://localhost:1342/' + options};
    } else {
      options.url = 'http://localhost:1342/' + options.url;
    }

    options.method = method == 'del' ? 'delete' : method;

    request(options, function(err, response, body) {
      if (err) return callback(err, response, body);
      callback(null, response, body);
    });

  }
};


text:
<?php
namespace Poll\PollBundle\Entity;

/**
 *
 * @author kadleto2
 */
interface Respondent {

	public function getId();

	public function getImplementation();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.qinghua</groupId>
    <artifactId>fileDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.8.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0.pr3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0.pr3</version>
        </dependency>
    </dependencies>
</project>


text:
namespace System.ComponentModel
{
    /// <summary>
    ///    <para>Specifies whether a property can only be set at
    ///       design time.</para>
    /// </summary>
    [AttributeUsage(AttributeTargets.All)]
    public sealed class DesignOnlyAttribute : Attribute
    {
        /// <summary>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.ComponentModel.DesignOnlyAttribute'/> class.
        ///    </para>
        /// </summary>
        public DesignOnlyAttribute(bool isDesignOnly) => IsDesignOnly = isDesignOnly;

        /// <summary>
        ///    <para>
        ///       Gets a value indicating whether a property can be set only at design time.
        ///    </para>
        /// </summary>
        public bool IsDesignOnly { get; }

        /// <summary>
        ///    <para>
        ///       Specifies that a property can be set only at design time. This <see langword='static '/>field is read-only.
        ///    </para>
        /// </summary>
        public static readonly DesignOnlyAttribute Yes = new DesignOnlyAttribute(true);

        /// <summary>
        ///    <para>
        ///       Specifies that a property can be set at design time or at run time. This <see langword='static '/>field is read-only.
        ///    </para>
        /// </summary>
        public static readonly DesignOnlyAttribute No = new DesignOnlyAttribute(false);

        /// <summary>
        ///    <para>
        ///       Specifies the default value for the <see cref='System.ComponentModel.DesignOnlyAttribute'/>, which is <see cref='System.ComponentModel.DesignOnlyAttribute.No'/>. This <see langword='static'/> field is
        ///       read-only.
        ///    </para>
        /// </summary>
        public static readonly DesignOnlyAttribute Default = No;

        public override bool Equals(object obj)
        {
            if (obj == this)
            {
                return true;
            }

            DesignOnlyAttribute other = obj as DesignOnlyAttribute;
            return other?.IsDesignOnly == IsDesignOnly;
        }

        public override int GetHashCode() => IsDesignOnly.GetHashCode();

        public override bool IsDefaultAttribute() => IsDesignOnly == Default.IsDesignOnly;
    }
}


text:
Clazz.declarePackage ("JSV.api");
Clazz.load (["JSV.api.JSVViewPanel"], "JSV.api.JSVPanel", null, function () {
Clazz.declareInterface (JSV.api, "JSVPanel", JSV.api.JSVViewPanel);
});


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace GestAssoc.Model.Models.Mapping
{
    public class AdherentMap : EntityTypeConfiguration<Adherent>
    {
        public AdherentMap()
        {
            // Primary Key
            this.HasKey(t => t.ID);

            // Properties
            this.Property(t => t.Nom)
                .HasMaxLength(4000);

            this.Property(t => t.Prenom)
                .HasMaxLength(4000);

            this.Property(t => t.Commentaire)
                .HasMaxLength(4000);

            this.Property(t => t.Adresse)
                .HasMaxLength(4000);

            this.Property(t => t.Telephone1)
                .HasMaxLength(4000);

            this.Property(t => t.Telephone2)
                .HasMaxLength(4000);

            this.Property(t => t.Telephone3)
                .HasMaxLength(4000);

            this.Property(t => t.Mail1)
                .HasMaxLength(4000);

            this.Property(t => t.Mail2)
                .HasMaxLength(4000);

            this.Property(t => t.Mail3)
                .HasMaxLength(4000);

            // Table & Column Mappings
            this.ToTable("Adherents");
            this.Property(t => t.ID).HasColumnName("ID");
            this.Property(t => t.Nom).HasColumnName("Nom");
            this.Property(t => t.Prenom).HasColumnName("Prenom");
            this.Property(t => t.DateNaissance).HasColumnName("DateNaissance");
            this.Property(t => t.DateCreation).HasColumnName("DateCreation");
            this.Property(t => t.DateModification).HasColumnName("DateModification");
            this.Property(t => t.Commentaire).HasColumnName("Commentaire");
            this.Property(t => t.Adresse).HasColumnName("Adresse");
            this.Property(t => t.Telephone1).HasColumnName("Telephone1");
            this.Property(t => t.Telephone2).HasColumnName("Telephone2");
            this.Property(t => t.Telephone3).HasColumnName("Telephone3");
            this.Property(t => t.Mail1).HasColumnName("Mail1");
            this.Property(t => t.Mail2).HasColumnName("Mail2");
            this.Property(t => t.Mail3).HasColumnName("Mail3");
            this.Property(t => t.Sexe).HasColumnName("Sexe");
            this.Property(t => t.Ville_ID).HasColumnName("Ville_ID");

            // Relationships
            this.HasOptional(t => t.Ville)
                .WithMany(t => t.Adherents)
                .HasForeignKey(d => d.Ville_ID);

        }
    }
}


text:
<?php

namespace Synapse\Cmf\Framework\Theme\Variation\Entity;

use Majora\Framework\Normalizer\Model\StdNormalizable;

/**
 * Value object for variation condition resolutions.
 */
class VariationContext extends StdNormalizable
{
}


text:
using namespace std;

int main(int argc, char *argv[])
    // fill tree with either arguments or default list of words.
    // print the tree, swap several words, custom sort tree and print.
{
    ex_13_8::Tree tree;
    for(const auto &w:tools::arguments(argc, argv))
        tree.add(w);

    if (tree.empty())
    {
        cout << "no words are given; using default array" << endl;

        // use default list of words
        for(const auto &w:{"Write", "a", "function", "for", "entering", "new",
                           "words", "into", "a", "tree", "of", "Tnodes"})
            tree.add(w);
    }

    cout << tree << endl;

    cout << "-- swap(1, 3)" << endl;
    tree.swap(1, 3);
    cout << tree << endl;

    cout << "-- swap(2, 12)" << endl;
    tree.swap(2, 12);
    cout << tree << endl;

    cout << "-- word sort" << endl;
    tree.sort(ex_13_8::WordCompare{});
    cout << tree << endl;

    cout << "-- count sort" << endl;
    tree.sort(ex_13_8::CountCompare{});
    cout << tree << endl;
}


text:
<?php

namespace Mcwork\Service\Media;

use Contentinum\Service\WebsiteServiceFactory;
use ContentinumComponents\Mapper\Worker;

/**
 * In use media table content
 *
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 */
class InUseServiceFactory extends WebsiteServiceFactory
{

    /**
     * Cache key media table
     *
     * @var string
     */
    const CONTENTINUM_DATABASE = 'mcwork_inuse_medias';

    /**
     * Name cache factory
     *
     * @var string
     */
    const CONTENTINUM_CACHE = 'Mcwork\Cache\Structures';

    /**
     * (non-PHPdoc)
     *
     * @see \Contentinum\Service\WebsiteServiceFactory::queryDbCacheResult()
     */
    protected function queryDbCacheResult($config, $sl)
    {

        $result = array();
        $cache = $sl->get(static::CONTENTINUM_CACHE);
        $key = $config['cache'];
        if (! ($result = $cache->getItem($key))) {
            $worker = new Worker($sl->get($config['entitymanager']));
            $datas = $worker->fetchAll('SELECT * FROM mediainuse');
            $result = array();
            foreach ($datas as $row) {
                $result[$row['mediasid']][] = array(
                    $row['inuseid'],
                    $row['groupname']
                );
            }
            if (isset($config['savecache']) && true === $config['savecache']) {
                $cache->setItem($key, $result);
            }
        }
        return $result;
    }
}


text:
package org.hawkular.metrics.core.impl.cassandra;

import java.util.Map;
import java.util.Optional;

import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.google.common.base.Function;

import org.hawkular.metrics.core.api.Availability;
import org.hawkular.metrics.core.api.AvailabilityMetric;
import org.hawkular.metrics.core.api.Interval;
import org.hawkular.metrics.core.api.MetricId;

/**
 * @author John Sanda
 */
public class AvailabilityMetricMapper implements Function<ResultSet, AvailabilityMetric> {

    private enum ColumnIndex {
        TENANT_ID,
        METRIC_NAME,
        INTERVAL,
        DPART,
        TIME,
        METRIC_TAGS,
        DATA_RETENTION,
        AVAILABILITY,
        TAGS
    }

    @Override
    public AvailabilityMetric apply(ResultSet resultSet) {
        if (resultSet.isExhausted()) {
            return null;
        }
        Row firstRow = resultSet.one();
        AvailabilityMetric metric = getMetric(firstRow);
        metric.addData(new Availability(metric, firstRow.getUUID(ColumnIndex.TIME.ordinal()), firstRow.getBytes(
            ColumnIndex.AVAILABILITY.ordinal()), getTags(firstRow)));

        for (Row row : resultSet) {
            metric.addData(new Availability(metric, row.getUUID(ColumnIndex.TIME.ordinal()), row.getBytes(
                ColumnIndex.AVAILABILITY.ordinal()), getTags(row)));
        }

        return metric;
    }

    private AvailabilityMetric getMetric(Row row) {
        AvailabilityMetric metric = new AvailabilityMetric(row.getString(ColumnIndex.TENANT_ID.ordinal()), getId(row),
            MetricUtils.getTags(row.getMap(ColumnIndex.METRIC_TAGS.ordinal(), String.class, String.class)),
            row.getInt(ColumnIndex.DATA_RETENTION.ordinal()));
        metric.setDpart(row.getLong(ColumnIndex.DPART.ordinal()));

        return metric;
    }

    private MetricId getId(Row row) {
        return new MetricId(row.getString(ColumnIndex.METRIC_NAME.ordinal()), Interval.parse(row.getString(
            ColumnIndex.INTERVAL.ordinal())));
    }

    private Map<String, Optional<String>> getTags(Row row) {
        Map<String, String> map = row.getMap(ColumnIndex.TAGS.ordinal(), String.class, String.class);
        return MetricUtils.getTags(map);
    }
}


text:
package org.apache.reef.vortex.api;

import org.apache.reef.annotations.Unstable;

/**
 * Typed user function. Implement your functions using this interface.
 * Note that Kryo should be able to serialize/deserialize your function and input.
 * Please refer to Kryo project's GitHub repository for how to make Kryo-compatible objects.
 *
 * @param <TInput> input type
 * @param <TOutput> output type
 */
@Unstable
public interface VortexFunction<TInput, TOutput> {
  /**
   * @param input of the function
   * @return output of the function
   * @throws Exception thrown here will bubble up in VortexFuture#get as ExecutionException
   * Exception should be thrown only after all resources are released as they cannot be cleared by Vortex
   * For example if threads are spawned here, shut them down before throwing an exception
   */
  TOutput call(TInput input) throws Exception;
}


text:
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const babel = require('gulp-babel');
const cache = require('gulp-cache');
const concat = require('gulp-concat');
const cssnano = require('gulp-cssnano');
const imagemin = require('gulp-imagemin');
const gulpLoadPlugins = require('gulp-load-plugins');
const ghpages = require('gulp-gh-pages');
const minify = require('gulp-minify-css');
const plumber = require('gulp-plumber');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');

const browserSync = require('browser-sync').create();
const reload = browserSync.reload;
const stream = browserSync.stream;

const del = require('del');
const jshint = require('jshint');
const runSequence = require('run-sequence');
const os = require('os');
const sassdoc = require('sassdoc');

const $ = gulpLoadPlugins; //[FIX]: Not using it at the moment

var port = process.env.SERVER_PORT || 3000;

const paths = {
	source: {
		templates: ['src/*.html'],
		cname: ['CNAME'],
		styles: ['src/assets/styles/**/*.scss'],
		images: ['src/assets/img/**/*.+(png|jpg|gif|svg|jpeg)'],
		scripts: ['src/assets/js/**/*.js'],
		audio: ['src/assets/sounds/**/*.+(wav|mp3)']
	},
	target: {
		all: 'dist/**/*',
		templates: 'dist',
		cname: 'dist',
		styles: 'dist/assets/styles/css',
		sassdoc: 'dist/public/docs',
		images: 'dist/assets/img',
		scripts: 'dist/assets/js',
		audio: 'dist/assets/sounds',
		sourcemaps: 'src/assets/maps'
	}
};

// Html task
gulp.task('html', () => {
	console.log('Running the sass task');
	return gulp.src(paths.source.templates)
	.pipe(gulp.dest(paths.target.templates))
	.pipe(stream());
})

// Sass task
const sassOptions = {
	errLogToConsole: true,
	outputStyle: 'compressed'
}

const autoprefixerOptions = {
	browsers: ['last 2 versions', '> 1%', 'Firefox ESR'],
	cascade: true
}

gulp.task('sass', () => {
	console.log('Running the sass task');
	return gulp.src(paths.source.styles)
		.pipe(plumber())
		.pipe(sourcemaps.init())
		.pipe(sass(sassOptions).on('error', sass.logError))
		.pipe(autoprefixer(autoprefixerOptions))
		.pipe(cssnano())
		.pipe(sourcemaps.write(paths.target.sourcemaps))
		.pipe(gulp.dest(paths.target.styles))
		.pipe(stream());
})

// Sassdoc task
const sassdocOptions = {
	dest: paths.target.sassdoc
}

gulp.task('sassdoc', () => {
	console.log('Running the sassdoc task');
	return gulp.src(paths.source.styles)
		.pipe(sassdoc(sassdocOptions))
		.resume();
})

// Js task
gulp.task('js', () => {
	console.log('Running the js task');
	return gulp.src(paths.source.scripts)
	.pipe(plumber())
	.pipe(sourcemaps.init())
	.pipe(babel())
	.pipe(uglify())
	.pipe(sourcemaps.write(paths.target.sourcemaps))
	.pipe(gulp.dest(paths.target.scripts))
	.pipe(stream());
})

// Image task
const imageOptions = {
	optimizzationLevel: 3,
	progressive: true,
	interlaced: true,
	svgoPlugins: [{cleanupIDs: false}]
}

gulp.task('img', () => {
	console.log('Running the img task');
	return gulp.src(paths.source.images)
	.pipe(cache(imagemin(imageOptions)))
	.pipe(gulp.dest(paths.target.images))
})

// Sound task
gulp.task('sound', () => {
	console.log('Running the sound task');
	return gulp.src(paths.source.audio)
		.pipe(gulp.dest(paths.target.audio))
})

// Clean task
gulp.task('clean:dist', () => {
	console.log('Running the js task');
	return del.sync([paths.target.all])
})

// Cache clear task
gulp.task('cache:clear', (cb) => {
	console.log('Running the cache:clear task');
	return cache.clearAll(cb);
})

// Watch task
gulp.task('watch', ['html', 'sass', 'js', 'img', 'sound'], () => {
	console.log('Running the watch task');
	browserSync.init({
		server: {
			baseDir: 'src'
		}
	})
	gulp.watch(paths.source.styles, ['sass']).on('change', (e) => {
		console.log(`File ${e.path} was ${e.type}, running tasks...`);
	})
	gulp.watch(paths.source.templates, ['html']).on('change', reload);
	gulp.watch(paths.source.scripts, ['js']).on('change', (e) => {
		console.log(`File ${e.path} was ${e.type}, running tasks...`);
	})
	gulp.watch( paths.source.iamges, ['img']).on('change', (e) => {
		console.log(`File ${e.path} was ${e.type}, running tasks...`);
	})
	gulp.watch( paths.source.soundPath, ['sound']).on('change', (e) => {
		console.log(`File ${e.path} was ${e.type}, running tasks...`);
	})
})

// CNAME task
gulp.task('cname', () => {
	console.log('Running the CNAME task');
	return gulp.src(paths.source.cname)
		.pipe(gulp.dest(paths.target.cname))
})

// Build task
gulp.task('build', (cb) => {
	console.log('Running the build task')
	runSequence('clean:dist',
		['html', 'cname', 'sass', 'js', 'img', 'sound', 'sassdoc'],
		cb
	)
})

// Deploy Task
gulp.task('deploy', ['build'], () => {
	console.log('Running the build task')
	return gulp.src(paths.target.all)
	.pipe(ghpages());
})

// Default task
gulp.task('default', (cb) => {
	runSequence(['html', 'sass', 'sassdoc', 'js', 'img', 'sound', 'watch'],
		cb
	)
})


text:
package com.zl.tesseract.scanner.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.zl.tesseract.R;
import com.zl.tesseract.scanner.utils.ScreenUtils;

public final class ScannerFinderView extends RelativeLayout {

    private static final int[] SCANNER_ALPHA = { 0, 64, 128, 192, 255, 192, 128, 64 };
    private static final long ANIMATION_DELAY = 100L;
    private static final int OPAQUE = 0xFF;

    private static final int MIN_FOCUS_BOX_WIDTH = 50;
    private static final int MIN_FOCUS_BOX_HEIGHT = 50;
    private static final int MIN_FOCUS_BOX_TOP = 200;

    private static Point ScrRes;
    private int top;

    private Paint mPaint;
    private int mScannerAlpha;
    private int mMaskColor;
    private int mFrameColor;
    private int mLaserColor;
    private int mTextColor;
    private int mFocusThick;
    private int mAngleThick;
    private int mAngleLength;

    private Rect mFrameRect; //绘制的Rect
    private Rect mRect; //返回的Rect

    public ScannerFinderView(Context context) {
        this(context, null);
    }

    public ScannerFinderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScannerFinderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        Resources resources = getResources();
        mMaskColor = resources.getColor(R.color.finder_mask);
        mFrameColor = resources.getColor(R.color.finder_frame);
        mLaserColor = resources.getColor(R.color.finder_laser);
        mTextColor = resources.getColor(R.color.white);

        mFocusThick = 1;
        mAngleThick = 8;
        mAngleLength = 40;
        mScannerAlpha = 0;
        init(context);
        this.setOnTouchListener(getTouchListener());
    }

    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }
        // 需要调用下面的方法才会执行onDraw方法
        setWillNotDraw(false);

        if (mFrameRect == null) {

            ScrRes = ScreenUtils.getScreenResolution(context);

            int width = ScrRes.x * 3 / 5;
            int height = width;

            width = width == 0
                    ? MIN_FOCUS_BOX_WIDTH
                    : width < MIN_FOCUS_BOX_WIDTH ? MIN_FOCUS_BOX_WIDTH : width;

            height = height == 0
                    ? MIN_FOCUS_BOX_HEIGHT
                    : height < MIN_FOCUS_BOX_HEIGHT ? MIN_FOCUS_BOX_HEIGHT : height;

            int left = (ScrRes.x - width) / 2;
            int top = (ScrRes.y - height) / 5;
            this.top = top; //记录初始距离上方距离

            mFrameRect = new Rect(left, top, left + width, top + height);
            mRect = mFrameRect;
        }
    }

    public Rect getRect() {
        return mRect;
    }

    @Override
    public void onDraw(Canvas canvas) {
        if (isInEditMode()) {
            return;
        }
        Rect frame = mFrameRect;
        if (frame == null) {
            return;
        }
        int width = canvas.getWidth();
        int height = canvas.getHeight();

        // 绘制焦点框外边的暗色背景
        mPaint.setColor(mMaskColor);
        canvas.drawRect(0, 0, width, frame.top, mPaint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, mPaint);
        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, mPaint);
        canvas.drawRect(0, frame.bottom + 1, width, height, mPaint);

        drawFocusRect(canvas, frame);
        drawAngle(canvas, frame);
        drawText(canvas, frame);
        drawLaser(canvas, frame);
    }

    /**
     * 画聚焦框,白色的
     *
     * @param canvas
     * @param rect
     */
    private void drawFocusRect(Canvas canvas, Rect rect) {
        // 绘制焦点框(黑色)
        mPaint.setColor(mFrameColor);
        // 上
        canvas.drawRect(rect.left + mAngleLength, rect.top, rect.right - mAngleLength, rect.top + mFocusThick, mPaint);
        // 左
        canvas.drawRect(rect.left, rect.top + mAngleLength, rect.left + mFocusThick, rect.bottom - mAngleLength,
                mPaint);
        // 右
        canvas.drawRect(rect.right - mFocusThick, rect.top + mAngleLength, rect.right, rect.bottom - mAngleLength,
                mPaint);
        // 下
        canvas.drawRect(rect.left + mAngleLength, rect.bottom - mFocusThick, rect.right - mAngleLength, rect.bottom,
                mPaint);
    }

    /**
     * 画四个角
     *
     * @param canvas
     * @param rect
     */
    private void drawAngle(Canvas canvas, Rect rect) {
        mPaint.setColor(mLaserColor);
        mPaint.setAlpha(OPAQUE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(mAngleThick);
        int left = rect.left;
        int top = rect.top;
        int right = rect.right;
        int bottom = rect.bottom;
        // 左上角
        canvas.drawRect(left, top, left + mAngleLength, top + mAngleThick, mPaint);
        canvas.drawRect(left, top, left + mAngleThick, top + mAngleLength, mPaint);
        // 右上角
        canvas.drawRect(right - mAngleLength, top, right, top + mAngleThick, mPaint);
        canvas.drawRect(right - mAngleThick, top, right, top + mAngleLength, mPaint);
        // 左下角
        canvas.drawRect(left, bottom - mAngleLength, left + mAngleThick, bottom, mPaint);
        canvas.drawRect(left, bottom - mAngleThick, left + mAngleLength, bottom, mPaint);
        // 右下角
        canvas.drawRect(right - mAngleLength, bottom - mAngleThick, right, bottom, mPaint);
        canvas.drawRect(right - mAngleThick, bottom - mAngleLength, right, bottom, mPaint);
    }

    private void drawText(Canvas canvas, Rect rect) {
        int margin = 40;
        mPaint.setColor(mTextColor);
        mPaint.setTextSize(getResources().getDimension(R.dimen.text_size_13sp));
        String text = getResources().getString(R.string.auto_scan_notification);
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;
        float offY = fontTotalHeight / 2 - fontMetrics.bottom;
        float newY = rect.bottom + margin + offY;
        float left = (ScreenUtils.getScreenWidth() - mPaint.getTextSize() * text.length()) / 2;
        canvas.drawText(text, left, newY, mPaint);
    }

    private void drawLaser(Canvas canvas, Rect rect) {
        // 绘制焦点框内固定的一条扫描线
        mPaint.setColor(mLaserColor);
        mPaint.setAlpha(SCANNER_ALPHA[mScannerAlpha]);
        mScannerAlpha = (mScannerAlpha + 1) % SCANNER_ALPHA.length;
        int middle = rect.height() / 2 + rect.top;
        canvas.drawRect(rect.left + 2, middle - 1, rect.right - 1, middle + 2, mPaint);

        mHandler.sendEmptyMessageDelayed(1, ANIMATION_DELAY);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            invalidate();
        }
    };

    private OnTouchListener touchListener;

    private OnTouchListener getTouchListener() {

        if (touchListener == null){
            touchListener = new OnTouchListener() {

                int lastX = -1;
                int lastY = -1;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            lastX = -1;
                            lastY = -1;
                            return true;
                        case MotionEvent.ACTION_MOVE:
                            int currentX = (int) event.getX();
                            int currentY = (int) event.getY();
                            try {
                                Rect rect = mFrameRect;
                                final int BUFFER = 60;
                                if (lastX >= 0) {

                                    boolean currentXLeft = currentX >= rect.left - BUFFER && currentX <= rect.left + BUFFER;
                                    boolean currentXRight = currentX >= rect.right - BUFFER && currentX <= rect.right + BUFFER;
                                    boolean lastXLeft = lastX >= rect.left - BUFFER && lastX <= rect.left + BUFFER;
                                    boolean lastXRight = lastX >= rect.right - BUFFER && lastX <= rect.right + BUFFER;

                                    boolean currentYTop = currentY <= rect.top + BUFFER && currentY >= rect.top - BUFFER;
                                    boolean currentYBottom = currentY <= rect.bottom + BUFFER && currentY >= rect.bottom - BUFFER;
                                    boolean lastYTop = lastY <= rect.top + BUFFER && lastY >= rect.top - BUFFER;
                                    boolean lastYBottom = lastY <= rect.bottom + BUFFER && lastY >= rect.bottom - BUFFER;

                                    boolean XLeft = currentXLeft || lastXLeft;
                                    boolean XRight = currentXRight || lastXRight;
                                    boolean YTop = currentYTop || lastYTop;
                                    boolean YBottom = currentYBottom || lastYBottom;

                                    boolean YTopBottom = (currentY <= rect.bottom && currentY >= rect.top)
                                            || (lastY <= rect.bottom && lastY >= rect.top);

                                    boolean XLeftRight = (currentX <= rect.right && currentX >= rect.left)
                                            || (lastX <= rect.right && lastX >= rect.left);

                                        //右上角
                                    if (XLeft && YTop) {
                                        updateBoxRect(2 * (lastX - currentX), (lastY - currentY), true);
                                        //左上角
                                    } else if (XRight && YTop) {
                                        updateBoxRect(2 * (currentX - lastX), (lastY - currentY), true);
                                        //右下角
                                    } else if (XLeft && YBottom) {
                                        updateBoxRect(2 * (lastX - currentX), (currentY - lastY), false);
                                        //左下角
                                    } else if (XRight && YBottom) {
                                        updateBoxRect(2 * (currentX - lastX), (currentY - lastY), false);
                                        //左侧
                                    } else if (XLeft && YTopBottom) {
                                        updateBoxRect(2 * (lastX - currentX), 0, false);
                                        //右侧
                                    } else if (XRight && YTopBottom) {
                                        updateBoxRect(2 * (currentX - lastX), 0, false);
                                        //上方
                                    } else if (YTop && XLeftRight) {
                                        updateBoxRect(0, (lastY - currentY), true);
                                        //下方
                                    } else if (YBottom && XLeftRight) {
                                        updateBoxRect(0, (currentY - lastY), false);
                                    }
                                }
                            } catch (NullPointerException e) {
                                e.printStackTrace();
                            }
                            v.invalidate();
                            lastX = currentX;
                            lastY = currentY;
                            return true;
                        case MotionEvent.ACTION_UP:
                            //移除之前的刷新
                            mHandler.removeMessages(1);
                            //松手时对外更新
                            mRect = mFrameRect;
                            lastX = -1;
                            lastY = -1;
                            return true;
                        default:

                    }
                    return false;
                }
            };
        }

        return touchListener;
    }

    private void updateBoxRect(int dW, int dH, boolean isUpward) {

        int newWidth = (mFrameRect.width() + dW > ScrRes.x - 4 || mFrameRect.width() + dW < MIN_FOCUS_BOX_WIDTH)
                ? 0 : mFrameRect.width() + dW;

        //限制扫描框最大高度不超过屏幕宽度
        int newHeight = (mFrameRect.height() + dH > ScrRes.x || mFrameRect.height() + dH < MIN_FOCUS_BOX_HEIGHT)
                ? 0 : mFrameRect.height() + dH;

        int leftOffset = (ScrRes.x - newWidth) / 2;

        if (isUpward){
            this.top -= dH;
        }

        int topOffset = this.top;

        if (topOffset < MIN_FOCUS_BOX_TOP){
            this.top = MIN_FOCUS_BOX_TOP;
            return;
        }

        if (topOffset + newHeight > MIN_FOCUS_BOX_TOP + ScrRes.x){
            return;
        }

        if (newWidth < MIN_FOCUS_BOX_WIDTH || newHeight < MIN_FOCUS_BOX_HEIGHT){
            return;
        }

        mFrameRect = new Rect(leftOffset, topOffset, leftOffset + newWidth, topOffset + newHeight);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mHandler.removeMessages(1);
    }
}


text:
package com.microsoft.azure.management.recoveryservices.backup.v2017_07_01.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.recoveryservices.backup.v2017_07_01.ProtectionContainers;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.management.recoveryservices.backup.v2017_07_01.BackupFabricVaultProtectionContainerResource;

class ProtectionContainersImpl extends WrapperImpl<ProtectionContainersInner> implements ProtectionContainers {
    private final RecoveryServicesManager manager;

    ProtectionContainersImpl(RecoveryServicesManager manager) {
        super(manager.inner().protectionContainers());
        this.manager = manager;
    }

    public RecoveryServicesManager manager() {
        return this.manager;
    }

    @Override
    public BackupFabricVaultProtectionContainerResourceImpl define(String name) {
        return wrapModel(name);
    }

    private BackupFabricVaultProtectionContainerResourceImpl wrapModel(ProtectionContainerResourceInner inner) {
        return  new BackupFabricVaultProtectionContainerResourceImpl(inner, manager());
    }

    private BackupFabricVaultProtectionContainerResourceImpl wrapModel(String name) {
        return new BackupFabricVaultProtectionContainerResourceImpl(name, this.manager());
    }

    @Override
    public Completable inquireAsync(String vaultName, String resourceGroupName, String fabricName, String containerName) {
        ProtectionContainersInner client = this.inner();
        return client.inquireAsync(vaultName, resourceGroupName, fabricName, containerName).toCompletable();
    }

    @Override
    public Observable<BackupFabricVaultProtectionContainerResource> getAsync(String vaultName, String resourceGroupName, String fabricName, String containerName) {
        ProtectionContainersInner client = this.inner();
        return client.getAsync(vaultName, resourceGroupName, fabricName, containerName)
        .map(new Func1<ProtectionContainerResourceInner, BackupFabricVaultProtectionContainerResource>() {
            @Override
            public BackupFabricVaultProtectionContainerResource call(ProtectionContainerResourceInner inner) {
                return wrapModel(inner);
            }
       });
    }

    @Override
    public Completable unregisterAsync(String vaultName, String resourceGroupName, String fabricName, String containerName) {
        ProtectionContainersInner client = this.inner();
        return client.unregisterAsync(vaultName, resourceGroupName, fabricName, containerName).toCompletable();
    }

    @Override
    public Completable refreshAsync(String vaultName, String resourceGroupName, String fabricName) {
        ProtectionContainersInner client = this.inner();
        return client.refreshAsync(vaultName, resourceGroupName, fabricName).toCompletable();
    }

}