text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
          <token id="1">
            <word>A</word>
            <lemma>a</lemma>
            <CharacterOffsetBegin>0</CharacterOffsetBegin>
            <CharacterOffsetEnd>1</CharacterOffsetEnd>
            <POS>DT</POS>
          </token>
          <token id="2">
            <word>section</word>
            <lemma>section</lemma>
            <CharacterOffsetBegin>2</CharacterOffsetBegin>
            <CharacterOffsetEnd>9</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="3">
            <word>of</word>
            <lemma>of</lemma>
            <CharacterOffsetBegin>10</CharacterOffsetBegin>
            <CharacterOffsetEnd>12</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="4">
            <word>the</word>
            <lemma>the</lemma>
            <CharacterOffsetBegin>13</CharacterOffsetBegin>
            <CharacterOffsetEnd>16</CharacterOffsetEnd>
            <POS>DT</POS>
          </token>
          <token id="5">
            <word>line</word>
            <lemma>line</lemma>
            <CharacterOffsetBegin>17</CharacterOffsetBegin>
            <CharacterOffsetEnd>21</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="6">
            <word>downstream</word>
            <lemma>downstream</lemma>
            <CharacterOffsetBegin>22</CharacterOffsetBegin>
            <CharacterOffsetEnd>32</CharacterOffsetEnd>
            <POS>RB</POS>
          </token>
          <token id="7">
            <word>from</word>
            <lemma>from</lemma>
            <CharacterOffsetBegin>33</CharacterOffsetBegin>
            <CharacterOffsetEnd>37</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="8">
            <word>Monbulk</word>
            <lemma>Monbulk</lemma>
            <CharacterOffsetBegin>38</CharacterOffsetBegin>
            <CharacterOffsetEnd>45</CharacterOffsetEnd>
            <POS>NNP</POS>
          </token>
          <token id="9">
            <word>Creek</word>
            <lemma>Creek</lemma>
            <CharacterOffsetBegin>46</CharacterOffsetBegin>
            <CharacterOffsetEnd>51</CharacterOffsetEnd>
            <POS>NNP</POS>
          </token>
          <token id="10">
            <word>mill</word>
            <lemma>mill</lemma>
            <CharacterOffsetBegin>52</CharacterOffsetBegin>
            <CharacterOffsetEnd>56</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
        </tokens>
        <parse>(ROOT (S (NP (NP (DT A) (NN section)) (PP (IN of) (NP (DT the) (NN line)))) (ADJP (RB downstream) (PP (IN from) (NP (NNP Monbulk) (NNP Creek) (NN mill)))))) </parse>
        <dependencies type="basic-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="6">downstream</dependent>
          </dep>
          <dep type="det">
            <governor idx="2">section</governor>
            <dependent idx="1">A</dependent>
          </dep>
          <dep type="dep">
            <governor idx="6">downstream</governor>
            <dependent idx="2">section</dependent>
          </dep>
          <dep type="prep">
            <governor idx="2">section</governor>
            <dependent idx="3">of</dependent>
          </dep>
          <dep type="det">
            <governor idx="5">line</governor>
            <dependent idx="4">the</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="3">of</governor>
            <dependent idx="5">line</dependent>
          </dep>
          <dep type="prep">
            <governor idx="6">downstream</governor>
            <dependent idx="7">from</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="8">Monbulk</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="9">Creek</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="7">from</governor>
            <dependent idx="10">mill</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="6">downstream</dependent>
          </dep>
          <dep type="det">
            <governor idx="2">section</governor>
            <dependent idx="1">A</dependent>
          </dep>
          <dep type="dep">
            <governor idx="6">downstream</governor>
            <dependent idx="2">section</dependent>
          </dep>
          <dep type="det">
            <governor idx="5">line</governor>
            <dependent idx="4">the</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="2">section</governor>
            <dependent idx="5">line</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="8">Monbulk</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="9">Creek</dependent>
          </dep>
          <dep type="prep_from">
            <governor idx="6">downstream</governor>
            <dependent idx="10">mill</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-ccprocessed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="6">downstream</dependent>
          </dep>
          <dep type="det">
            <governor idx="2">section</governor>
            <dependent idx="1">A</dependent>
          </dep>
          <dep type="dep">
            <governor idx="6">downstream</governor>
            <dependent idx="2">section</dependent>
          </dep>
          <dep type="det">
            <governor idx="5">line</governor>
            <dependent idx="4">the</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="2">section</governor>
            <dependent idx="5">line</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="8">Monbulk</dependent>
          </dep>
          <dep type="nn">
            <governor idx="10">mill</governor>
            <dependent idx="9">Creek</dependent>
          </dep>
          <dep type="prep_from">
            <governor idx="6">downstream</governor>
            <dependent idx="10">mill</dependent>
          </dep>
        </dependencies>
      </sentence>
    </sentences>
  </document>
</root>

redpajama_set_name: RedPajamaGithub


text:
package rocserv

import (
	"context"
	"errors"
	"io"
	"sync"
	"time"

	"gitlab.pri.ibanyu.com/middleware/seaweed/xlog"
	xprom "gitlab.pri.ibanyu.com/middleware/seaweed/xstat/xmetric/xprometheus"
	"gitlab.pri.ibanyu.com/middleware/seaweed/xtime"
	"gitlab.pri.ibanyu.com/middleware/seaweed/xutil/pool"
	"gitlab.pri.ibanyu.com/middleware/seaweed/xutil/sync2"
)

const (
	getConnTimeout = time.Second * 1
	statTick       = time.Second * 10
)

var (
	ErrConnectionPoolClosed = errors.New("connection pool is closed")
)

type rpcClientConn interface {
	Close() error
	SetTimeout(timeout time.Duration) error
	GetServiceClient() interface{}
}

// ConnectionPool connection pool corresponding to the addr
type ConnectionPool struct {
	calleeServiceKey string

	rpcType     string
	rpcFactory  func(addr string) (rpcClientConn, error)
	addr        string
	idle        int // count of idle connection
	active      int // count of established connection, sometime active will bigger than idle, then the conn will be closed
	idleTimeout time.Duration

	mu          sync.Mutex
	closed      sync2.AtomicBool
	connections *pool.List // 对应地址的连接池
}

// NewConnectionPool constructor of ConnectionPool
func NewConnectionPool(addr string, idle, active int, idleTimeout time.Duration, rpcFactory func(addr string) (rpcClientConn, error), calleeServiceKey string) *ConnectionPool {
	cp := &ConnectionPool{addr: addr, idle: idle, active: active, idleTimeout: idleTimeout, rpcFactory: rpcFactory, calleeServiceKey: calleeServiceKey, closed: sync2.NewAtomicBool(false)}
	return cp
}

func (cp *ConnectionPool) Open() {
	if cp.idle == 0 {
		cp.idle = defaultMaxIdle
	}
	if cp.active == 0 {
		cp.active = defaultMaxActive
	}
	if cp.idle > cp.active {
		cp.idle = cp.active
	}
	if cp.active < defaultMaxActive {
		cp.active = defaultMaxActive
	}
	cp.mu.Lock()
	defer cp.mu.Unlock()
	cp.connections = pool.NewList(&pool.Config{Active: cp.active, Idle: cp.idle, IdleTimeout: xtime.Duration(cp.idleTimeout), WaitTimeout: xtime.Duration(time.Second), Wait: true})
	cp.connections.New = func(ctx context.Context) (io.Closer, error) {
		return cp.rpcFactory(cp.addr)
	}
	cp.stat()
	return
}

func (cp *ConnectionPool) stat() {
	tickC := time.Tick(statTick)
	go func() {
		count := int64(0)
		for !cp.closed.Get() {
			count++
			select {
			case <-tickC:
				if cp.closed.Get() {
					return
				}
				confActive, confIdle, active, idle := cp.connections.Stat()
				if count % 10 == 0 {
					// 减少日志为原来的十分之一
					xlog.Infof(context.Background(), "caller: %s, callee: %s, callee_addr: %s, conf_active: %d, conf_idle: %d, active: %d, idle: %d", GetServName(), cp.calleeServiceKey, cp.addr, confActive, confIdle, active, idle)
				}
				group, service := GetGroupAndService()
				_metricRPCConnectionPool.With(xprom.LabelGroupName, group,
					xprom.LabelServiceName, service,
					xprom.LabelCalleeService, cp.calleeServiceKey,
					calleeAddr, cp.addr,
					connectionPoolStatType, confActiveType).Set(float64(confActive))
				_metricRPCConnectionPool.With(xprom.LabelGroupName, group,
					xprom.LabelServiceName, service,
					xprom.LabelCalleeService, cp.calleeServiceKey,
					calleeAddr, cp.addr,
					connectionPoolStatType, activeType).Set(float64(active))
				_metricRPCConnectionPool.With(xprom.LabelGroupName, group,
					xprom.LabelServiceName, service,
					xprom.LabelCalleeService, cp.calleeServiceKey,
					calleeAddr, cp.addr,
					connectionPoolStatType, confIdleType).Set(float64(confIdle))
				_metricRPCConnectionPool.With(xprom.LabelGroupName, group,
					xprom.LabelServiceName, service,
					xprom.LabelCalleeService, cp.calleeServiceKey,
					calleeAddr, cp.addr,
					connectionPoolStatType, idleType).Set(float64(idle))
			}
		}
		xlog.Infof(context.Background(), "caller: %s, callee: %s, callee_addr: %s exit stat", GetServName(), cp.calleeServiceKey, cp.addr)
	}()
}

func (cp *ConnectionPool) pool() (p *pool.List) {
	cp.mu.Lock()
	p = cp.connections
	cp.mu.Unlock()
	return p
}

// Close close connection pool
func (cp *ConnectionPool) Close() {
	cp.closed.Set(true)
	p := cp.pool()
	if p == nil {
		return
	}
	p.Close()
	cp.mu.Lock()
	cp.connections = nil
	cp.mu.Unlock()
	return
}

// Addr return addr of connection pool
func (cp *ConnectionPool) Addr() string {
	return cp.addr
}

// Get return a connection, you should call PooledConnection's Recycle once done
func (cp *ConnectionPool) Get(ctx context.Context) (rpcClientConn, error) {
	p := cp.pool()
	if p == nil {
		return nil, ErrConnectionPoolClosed
	}

	getCtx, cancel := context.WithTimeout(ctx, getConnTimeout)
	defer cancel()
	r, err := p.Get(getCtx)
	if err != nil {
		return nil, err
	}

	return r.(rpcClientConn), nil
}

// Put recycle a connection into the pool
func (cp *ConnectionPool) Put(conn rpcClientConn, forceClose bool) {
	p := cp.pool()
	if p == nil {
		panic(ErrConnectionPoolClosed)
	}
	p.Put(context.TODO(), conn, forceClose)
}


text:
#ifndef __INET_DSR_OMNETPP_H
#define __INET_DSR_OMNETPP_H

#ifndef OMNETPP
#define OMNETPP
#endif

// #include <endian.h>
#include "inet/routing/extras/base/compatibility_dsr.h"
#include "dsr-uu/dsr-opt.h"

#ifdef MobilityFramework
#include "NetwPkt_m.h"
#ifndef IPv4Address
#define IPv4Address int
#endif
#define IPv4Datagram NetwPkt
#else
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/networklayer/common/IPProtocolId_m.h"
#endif

#ifdef MobilityFramework

#ifndef IPv4Datagram
#define IPv4Datagram NetwPkt
#endif

#ifndef IPv4Address
#define IPv4Address int

#endif

#endif

namespace inet {

namespace inetmanet {

class EtxCost
{
  public:
    IPv4Address address;
    double cost;
    ~EtxCost() {}
};

class DSRPkt : public IPv4Datagram
{

  protected:
    struct dsr_opt_hdr *options;
    IPProtocolId encap_protocol;
    IPv4Address previous;
    IPv4Address next;
    EtxCost  *costVector;
    unsigned int costVectorSize;
    int dsr_ttl;

  private:
    void copy(const DSRPkt& other);
    void clean();

  public:
    explicit DSRPkt(const char *name=NULL) : IPv4Datagram(name) {costVector=NULL; options=NULL; costVectorSize=0; dsr_ttl=0;}
    ~DSRPkt ();
    DSRPkt (const DSRPkt  &m);
    DSRPkt (struct dsr_pkt *dp,int interface_id);
    DSRPkt &    operator= (const DSRPkt &m);
    virtual DSRPkt *dup() const {return new DSRPkt(*this);}
    //void addOption();
    //readOption();
#ifdef MobilityFramework
    void setTimeToLive (int ttl) {setTtl(ttl);}
    int getTimeToLive() {return getTtl();}
#endif
    void    ModOptions (struct dsr_pkt *p,int);
    void setEncapProtocol(IPProtocolId procotol) {encap_protocol = procotol;}
    IPProtocolId getEncapProtocol() {return encap_protocol;}
#ifdef MobilityFramework
    const IPv4Address& prevAddress() const {return previous;}
    void setPrevAddress(const IPv4Address& address_var) {previous = address_var;}
    const IPv4Address& nextAddress() const {return next;}
    void setNextAddress(const IPv4Address& address_var) {next = address_var;}
#else
    const IPv4Address prevAddress() const {return previous;}
    void setPrevAddress(const IPv4Address address_var) {previous = address_var;}
    const IPv4Address nextAddress() const {return next;}
    void setNextAddress(const IPv4Address address_var) {next = address_var;}
#endif
    struct dsr_opt_hdr * getOptions() const {return options;}
    void  setOptions(dsr_opt_hdr * op) {if (options !=NULL) free(options);  options=op;}
    virtual std::string detailedInfo() const;

    void resetCostVector();
    virtual void getCostVector(EtxCost &cost,int &size); // Copy
    virtual EtxCost* getCostVector() {return ((costVectorSize>0)?costVector:NULL);}

    virtual void setCostVector(EtxCost &cost, int size);
    virtual void setCostVector(EtxCost *cost,int size);

    virtual unsigned getCostVectorSize() const {return costVectorSize;}

    virtual void setCostVectorSize(unsigned n);
    virtual void setCostVectorSize(EtxCost);
    virtual void setCostVectorSize(u_int32_t addr, double cost);
};

class EtxList
{
  public:
    IPv4Address address;
    double delivery;// the simulation suppose that the code use a u_int32_t
};

class DSRPktExt: public IPv4Datagram
{
  protected:
    EtxList *extension;
    int size;

  private:
    void copy(const DSRPktExt& other);
    void clean() { clearExtension(); }

  public:
    explicit DSRPktExt(const char *name=NULL) : IPv4Datagram(name) {size=0; extension=NULL;}
    ~DSRPktExt ();
    DSRPktExt (const DSRPktExt  &m);
    DSRPktExt &     operator= (const DSRPktExt &m);
    void clearExtension();
    EtxList * addExtension(int len);
    EtxList * delExtension(int len);
    EtxList * getExtension() {return extension;}
    int getSizeExtension () {return size;}
    virtual DSRPktExt *dup() const {return new DSRPktExt(*this);}

};

} // namespace inetmanet

} // namespace inet

#endif              /* _DSR_PKT_H */


text:
package com.example.air.weather;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.example.air.weather.db.*;
import com.example.air.weather.util.*;
import org.litepal.crud.*;
import java.io.*;
import java.util.*;
import okhttp3.*;

    /**
     * Created by Air on 2017/4/10.
     *      遍历省市县数据
     */

    public class Choose_AreaFragment extends Fragment{
        public static final int LEVEL_PROVINCE = 0;
        public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private Button backButton;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();

    private List<Province> provinceList;//省列表
    private List<City> cityList;//市列表
    private List<County> countyList;//县列表
    private Province selectedProvince;//选中的省份
    private City selectedCity;//选中的城市
    private int currentLevel;//当前选中的级别

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                if (currentLevel == LEVEL_PROVINCE){
                    selectedProvince = provinceList.get(position);
                    queryCities();
                }
            }
        });
        backButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (currentLevel == LEVEL_COUNTY){
                    queryCities();
                }
            }
        });
        queryProvinces();
    }

    /**
     * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
     */
    private void queryProvinces() {
        titleText.setText("中国");
        backButton.setVisibility(View.GONE);
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address, "province");
        }
    }

    /**
     * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。
     */
    private void queryCities() {
        titleText.setText(selectedProvince.getProvinceName());
        backButton.setVisibility(View.VISIBLE);
        cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address, "city");
        }
    }

    /**
     * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。
     */
    private void queryCounties() {
        titleText.setText(selectedCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    /**
     * 根据传入的地址和类型从服务器上查询省市县数据。
     */
    private void queryFromServer(String address, final String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                boolean result = false;
                if ("province".equals(type)) {
                    result = UTILity.handleProvinceResponse(responseText);
                } else if ("city".equals(type)) {
                    result = UTILity.handleCityResponse(responseText, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = UTILity.handleCountyResponse(responseText, selectedCity.getId());
                }
                if (result) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCounties();
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 通过runOnUiThread()方法回到主线程处理逻辑
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

}


text:
class AddMissingIndexes < ActiveRecord::Migration
  def change
    add_index :taggings, :tag_id
    add_index :taggings, :taggable_id
    add_index :taggings, :taggable_type
    add_index :taggings, :tagger_id
    add_index :taggings, :context

    add_index :taggings, [:tagger_id, :tagger_type]
    add_index :taggings, [:taggable_id, :taggable_type, :tagger_id, :context], name: 'taggings_idy'
  end
end


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

		<item value="322" key="DIALOG_WIDTH"/>
		<item value="1|Ubuntu|11.0|0|GTK|1|" key="DIALOG_FONT_NAME"/>
		<item value="379" key="DIALOG_HEIGHT"/>

		<item value="800" key="DIALOG_WIDTH"/>
		<item value="1|Ubuntu|11.0|0|GTK|1|" key="DIALOG_FONT_NAME"/>
		<item value=", " key="org.eclipse.debug.ui.EXPANDED_NODES"/>
		<item value="762" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_2"/>
		<item value="640" key="DIALOG_HEIGHT"/>
		<item value="237" key="org.eclipse.debug.ui.DIALOG_SASH_WEIGHTS_1"/>


text:
default: basic_image basic_text 2d_transforms 2d_shapes screen_entities screen_sprites basic_lighting advanced_lighting 3d_audio skeletal_animation

basic_image:
	g++ -g `freetype-config --cflags` -IBasicImage -lPolyCore BasicImage/HelloPolycodeApp.cpp main.cpp -o basic_image
basic_text:
	g++ -g `freetype-config --cflags` -IBasicText -lPolyCore BasicText/HelloPolycodeApp.cpp main.cpp -o basic_text
2d_transforms:
	g++ -g `freetype-config --cflags` -I2DTransforms -lPolyCore 2DTransforms/HelloPolycodeApp.cpp main.cpp -o 2d_transforms
2d_shapes:
	g++ -g `freetype-config --cflags` -I2DShapes -lPolyCore 2DShapes/HelloPolycodeApp.cpp main.cpp -o 2d_shapes
screen_entities:
	g++ -g `freetype-config --cflags` -IScreenEntities -lPolyCore ScreenEntities/HelloPolycodeApp.cpp main.cpp -o screen_entities
screen_sprites:
	g++ -g `freetype-config --cflags` -IScreenSprites -lPolyCore ScreenSprites/HelloPolycodeApp.cpp main.cpp -o screen_sprites
basic_lighting:
	g++ -g `freetype-config --cflags` -IBasicLighting -lPolyCore BasicLighting/HelloPolycodeApp.cpp main.cpp -o basic_lighting
advanced_lighting:
	g++ -g `freetype-config --cflags` -IAdvancedLighting -lPolyCore AdvancedLighting/HelloPolycodeApp.cpp main.cpp -o advanced_lighting
3d_audio:
	g++ -g `freetype-config --cflags` -I3DAudio -lPolyCore 3DAudio/HelloPolycodeApp.cpp main.cpp -o 3d_audio
skeletal_animation:
	g++ -g `freetype-config --cflags` -ISkeletalAnimation -lPolyCore SkeletalAnimation/HelloPolycodeApp.cpp main.cpp -o skeletal_animation
clean:
	rm basic_image basic_text 2d_transforms 2d_shapes screen_entities screen_sprites basic_lighting advanced_lighting 3d_audio skeletal_animation


text:
"""
Copyright 2015 SmartBear Software

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

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

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

    Ref: https://github.com/swagger-api/swagger-codegen
"""

from pprint import pformat
from six import iteritems

class ApGpsSyncChanged(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self):
        """
        ApGpsSyncChanged - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'sys_time': 'datetime',
            'sync_state': 'str',
            'reason': 'str',
            'mac_address': 'str',
            'type': 'str'
        }

        self.attribute_map = {
            'sys_time': 'sysTime',
            'sync_state': 'syncState',
            'reason': 'reason',
            'mac_address': 'macAddress',
            'type': 'type'
        }

        self._sys_time = None
        self._sync_state = None
        self._reason = None
        self._mac_address = None
        self._type = None

    @property
    def sys_time(self):
        """
        Gets the sys_time of this ApGpsSyncChanged.
        Time of notification

        :return: The sys_time of this ApGpsSyncChanged.
        :rtype: datetime
        """
        return self._sys_time

    @sys_time.setter
    def sys_time(self, sys_time):
        """
        Sets the sys_time of this ApGpsSyncChanged.
        Time of notification

        :param sys_time: The sys_time of this ApGpsSyncChanged.
        :type: datetime
        """
        self._sys_time = sys_time

    @property
    def sync_state(self):
        """
        Gets the sync_state of this ApGpsSyncChanged.
        GPS synchronization state

        :return: The sync_state of this ApGpsSyncChanged.
        :rtype: str
        """
        return self._sync_state

    @sync_state.setter
    def sync_state(self, sync_state):
        """
        Sets the sync_state of this ApGpsSyncChanged.
        GPS synchronization state

        :param sync_state: The sync_state of this ApGpsSyncChanged.
        :type: str
        """
        allowed_values = ["sync", "lost"]
        if sync_state not in allowed_values:
            raise ValueError(
                "Invalid value for `sync_state`, must be one of {0}"
                .format(allowed_values)
            )
        self._sync_state = sync_state

    @property
    def reason(self):
        """
        Gets the reason of this ApGpsSyncChanged.
        Reason for the loss of GPS synchronization

        :return: The reason of this ApGpsSyncChanged.
        :rtype: str
        """
        return self._reason

    @reason.setter
    def reason(self, reason):
        """
        Sets the reason of this ApGpsSyncChanged.
        Reason for the loss of GPS synchronization

        :param reason: The reason of this ApGpsSyncChanged.
        :type: str
        """
        allowed_values = ["", "none", "gpsLost", "ppsLost"]
        if reason not in allowed_values:
            raise ValueError(
                "Invalid value for `reason`, must be one of {0}"
                .format(allowed_values)
            )
        self._reason = reason

    @property
    def mac_address(self):
        """
        Gets the mac_address of this ApGpsSyncChanged.
        MAC address of the AP mote

        :return: The mac_address of this ApGpsSyncChanged.
        :rtype: str
        """
        return self._mac_address

    @mac_address.setter
    def mac_address(self, mac_address):
        """
        Sets the mac_address of this ApGpsSyncChanged.
        MAC address of the AP mote

        :param mac_address: The mac_address of this ApGpsSyncChanged.
        :type: str
        """
        self._mac_address = mac_address

    @property
    def type(self):
        """
        Gets the type of this ApGpsSyncChanged.
        Notification type

        :return: The type of this ApGpsSyncChanged.
        :rtype: str
        """
        return self._type

    @type.setter
    def type(self, type):
        """
        Sets the type of this ApGpsSyncChanged.
        Notification type

        :param type: The type of this ApGpsSyncChanged.
        :type: str
        """
        allowed_values = ["netStarted", "pathStateChanged", "pathAlert", "moteStateChanged", "joinFailed", "pingResponse", "invalidMIC", "dataPacketReceived", "ipPacketReceived", "packetSent", "cmdFinished", "configChanged", "configLoaded", "alarmOpened", "alarmClosed", "deviceHealthReport", "neighborHealthReport", "discoveryHealthReport", "rawMoteNotification", "serviceChanged", "apStateChanged", "managerStarted", "managerStopping", "optPhase", "pathAlert", "moteTrace", "frameCapacity", "apGpsSyncChanged"]
        if type not in allowed_values:
            raise ValueError(
                "Invalid value for `type`, must be one of {0}"
                .format(allowed_values)
            )
        self._type = type

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
@implementation ViewController {
    Firebase *firebase;
    Firebase *myself;
    Firebase *myPosition;

    NSMutableDictionary *markers;
    NSMutableDictionary *radices;

    NSString *myRoomId;
    NSString *myUserName;

    NSDateFormatter *formatter;
    NSUserDefaults *prefs;
}

- (void)awakeFromNib {

    NSLog(@"Awake from nib");

    formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy HH:mm"];

    prefs = [NSUserDefaults standardUserDefaults];

    myUserName = [prefs stringForKey:PREF_NAME];
    if(!myUserName) {
        myUserName = [[UIDevice currentDevice] name];
        [prefs setObject:myUserName forKey:PREF_NAME];
        [prefs synchronize];
    }
}

- (void)viewDidLoad
{
    NSLog(@"View did load");

    [super viewDidLoad];

    // Delegate for the map events
    self.mapView.delegate = self;

    // Register to get claled when the user clicks a link
    NSNotificationCenter *nsCenter = [NSNotificationCenter defaultCenter];
    [nsCenter addObserver:self selector:@selector(openNewRoom:) name:OPEN_NOTIFICATION object:nil];

    [self prepareMap];
}

- (void)openNewRoom:(NSNotification *)notification {

    NSLog(@"Got notification: %@", notification);

    NSString *roomName = [notification.userInfo objectForKey:OPEN_NOTIFICATION];

    [self prepareMapWithRoomName:roomName];
}

- (void)prepareMap {
    [self prepareMapWithRoomName:nil];
}

- (void)prepareMapWithRoomName:(NSString *)roomName {

    NSLog(@"Preparing map with: >%@<", roomName);

    [self cleanMapIfNeeded];

    markers = [NSMutableDictionary dictionary];
    radices = [NSMutableDictionary dictionary];

    NSString *firebaseBaseUrl = [FB_URL stringByAppendingString:PROTOCOL_VERSION];
    Firebase *roomsFirebase = [[Firebase alloc] initWithUrl:firebaseBaseUrl];

    if(roomName.length > 0) {
        firebase = [roomsFirebase childByAppendingPath:roomName];
    } else {
        firebase = [roomsFirebase childByAutoId];
        roomName = firebase.name;
    }

    myRoomId = [prefs stringForKey:roomName];

    if(myRoomId) {
        myself = [firebase childByAppendingPath:myRoomId];
    } else {
        myself = [firebase childByAutoId];
        myRoomId = [myself name];
        [prefs setObject:myRoomId forKey:roomName];
        [prefs synchronize];
    }

    [[myself childByAppendingPath:FB_NAME] setValue:myUserName];
    myPosition = [myself childByAppendingPath:FB_POSITION];

    [firebase observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
        [self personAddedWithSnapshot:snapshot];
    }];

    [firebase observeEventType:FEventTypeChildRemoved withBlock:^(FDataSnapshot *snapshot) {
        [self personRemovedWithSnapshot:snapshot];
    }];

    // Follow the user (until he moves the map manually)
    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}

- (void)cleanMapIfNeeded {
    if(firebase) {
        NSLog(@"Cleaning map");

        [firebase removeAllObservers];
        [self.mapView removeAnnotations:[markers allValues]];
    }
}

- (void)personAddedWithSnapshot:(FDataSnapshot *)snapshot {
    NSString *snapshotName = snapshot.name;

    // Do not capture myself
    if([snapshotName isEqualToString:myRoomId]) {
        return;
    }

    NSDictionary *value = snapshot.value;

    NSString *guyName = [value objectForKey:FB_NAME];

    NSLog(@"New user %@", guyName);

    Firebase *positionRef = [[snapshot ref] childByAppendingPath:FB_POSITION];

    [positionRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
        [self positionChangedWithName:guyName andSnapshot:snapshot];
    }];
}

- (void)personRemovedWithSnapshot:(FDataSnapshot *)snapshot {
    NSString *snapshotName = snapshot.name;

    NSLog(@"User removed %@", snapshotName);

    MKPointAnnotation *marker = [markers objectForKey:snapshotName];
    if(marker) {
        [self.mapView removeAnnotation:marker];
        [markers removeObjectForKey:snapshotName];
    }

    MKCircle *radix = [radices objectForKey:snapshotName];
    if(radix) {
        [self.mapView removeOverlay:radix];
        [radices removeObjectForKey:snapshotName];
    }

    [snapshot.ref removeAllObservers];
}

- (void) positionChangedWithName:(NSString *)guyName andSnapshot:(FDataSnapshot *)snapshot {
    NSDictionary *position = snapshot.value;

    if([position isKindOfClass:[NSNull class]]) {
        return;
    }

    Firebase *ref = [snapshot ref];
    Firebase *parent = [ref parent];
    NSString *parentName = [parent name];

    NSLog(@"Position changed for %@: %@", parentName, position);

    CLLocationCoordinate2D zoomLocation;
    zoomLocation.latitude = [[position objectForKey:FB_LAT] doubleValue];
    zoomLocation.longitude = [[position objectForKey:FB_LONG] doubleValue];

    double accuracy = [[position objectForKey:FB_ACCURACY] doubleValue];
    if(accuracy > MAX_ACCURACY) {
        accuracy = MAX_ACCURACY;
    }

    NSNumber *dateTimestamp = [position objectForKey:FB_DATETIME];
    NSTimeInterval interval = [dateTimestamp doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSString *dateString = [formatter stringFromDate:date];

    MKPointAnnotation *marker = [markers objectForKey:parentName];
    if(marker) {
        marker.coordinate = zoomLocation;
        marker.subtitle = dateString;

    } else {
        marker = [[MKPointAnnotation alloc] init];
        marker.coordinate = zoomLocation;
        marker.title = guyName;
        marker.subtitle = dateString;

        [self.mapView addAnnotation:marker];

        [markers setValue:marker forKey:parentName];
    }

    MKCircle *radix = [radices objectForKey:parentName];
    if(radix) {
        [self.mapView removeOverlay:radix];
    }

    // We cannot move an overlay, so we remove it if needed then re-add it
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:zoomLocation radius:accuracy];
    [self.mapView addOverlay:circle];
    [radices setValue:circle forKey:parentName];
}

// Used to show the radius
- (MKOverlayView *)mapView:(MKMapView *)map viewForOverlay:(id <MKOverlay>)overlay
{
    MKCircleView *circleView = [[MKCircleView alloc] initWithOverlay:overlay];
    circleView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.8];
    circleView.lineWidth = 2;
    circleView.fillColor = [[UIColor blueColor] colorWithAlphaComponent:0.3];
    return circleView;
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {

    NSLog(@"User updated his position: %@", userLocation);

    NSMutableDictionary *newPos = [NSMutableDictionary dictionary];
    [newPos setValue:[NSNumber numberWithDouble:userLocation.coordinate.latitude] forKey:FB_LAT];
    [newPos setValue:[NSNumber numberWithDouble:userLocation.coordinate.longitude] forKey:FB_LONG];
    [newPos setValue:[NSNumber numberWithDouble:userLocation.location.horizontalAccuracy] forKey:FB_ACCURACY];

    NSNumber *date = [NSNumber numberWithDouble:([[NSDate date] timeIntervalSince1970] * 1000)];
    NSString *numStr = [NSString stringWithFormat:@"%llu", [date unsignedLongLongValue]];

    [newPos setValue:numStr forKey:FB_DATETIME];

    [myPosition setValue:newPos];
}

- (IBAction)shareButton:(id)sender {
    NSString *shareText = NSLocalizedString(@"SHARE_TEXT", @"Text used when sharing the WAY url");
    NSString *shareUrl = [BASE_URL stringByAppendingString:firebase.name];
    NSString *shareComplete = [NSString stringWithFormat:shareText, shareUrl];

    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:shareComplete];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"SHARE_ALERT_TITLE", @"Title of the alert when sharing the WAY url")
                                                    message:NSLocalizedString(@"SHARE_ALERT_CONTENT", @"Content of the alert when sharing the WAY url")
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"SHARE_ALERT_BUTTON", @"OK Button when sharing the WAY url")
                                          otherButtonTitles:nil];

    [alert show];

    NSLog(@"Sharing URL: %@", shareComplete);
}

- (IBAction)gpsButton:(id)sender {
    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}

- (IBAction)cancel:(UIStoryboardSegue *)segue {

    if([segue.identifier isEqualToString:@"CancelInput"]) {
        // We don't do anything if the user cancelled

        NSLog(@"User dismissed the settings");

        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (IBAction)done:(UIStoryboardSegue *)segue {

    if([segue.identifier isEqualToString:@"DoneInput"]) {

        NSLog(@"User submitted the settings");

        myUserName = [prefs stringForKey:PREF_NAME];
        [[myself childByAppendingPath:FB_NAME] setValue:myUserName];

        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

@end


text:
package org.apache.dubbo.common.serialize.protobuf.support;

import org.apache.dubbo.common.serialize.protobuf.support.model.GooglePB;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class GenericProtobufJsonObjectOutputTest {
    private ByteArrayOutputStream byteArrayOutputStream;
    private GenericProtobufJsonObjectOutput genericProtobufObjectOutput;
    private GenericProtobufJsonObjectInput genericProtobufObjectInput;
    private ByteArrayInputStream byteArrayInputStream;

    @BeforeEach
    public void setUp() {
        this.byteArrayOutputStream = new ByteArrayOutputStream();
        this.genericProtobufObjectOutput = new GenericProtobufJsonObjectOutput(byteArrayOutputStream);
    }

    @Test
    public void testWriteObjectNull() throws IOException {
        assertThrows(IllegalArgumentException.class, () -> {
            this.genericProtobufObjectOutput.writeObject(null);
        });
    }

    @Test
    public void testWriteGooglePbObject() throws IOException {
        Random random = new Random();
        final int bound = 100000;
        List<GooglePB.PhoneNumber> phoneNumberList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            phoneNumberList.add(GooglePB.PhoneNumber.newBuilder().setNumber(random.nextInt(bound) + "").setType(GooglePB.PhoneType.forNumber(random.nextInt(GooglePB.PhoneType.values().length - 1))).build());
        }

        Map<String, GooglePB.PhoneNumber> phoneNumberMap = new HashMap<>();
        for (int i = 0; i < 5; i++) {
            phoneNumberMap.put("phoneNumber" + i, GooglePB.PhoneNumber.newBuilder().setNumber(random.nextInt(bound) + "").setType(GooglePB.PhoneType.forNumber(random.nextInt(GooglePB.PhoneType.values().length - 1))).build());
        }
        GooglePB.PBRequestType request = GooglePB.PBRequestType.newBuilder()
                .setAge(15).setCash(10).setMoney(16.0).setNum(100L)
                .addAllPhone(phoneNumberList).putAllDoubleMap(phoneNumberMap).build();

        this.genericProtobufObjectOutput.writeObject(request);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readObject(GooglePB.PBRequestType.class), is(request));
    }

    @Test
    public void testWriteBoolean() throws IOException {
        boolean random = new Random().nextBoolean();
        this.genericProtobufObjectOutput.writeBool(random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readBool(), is(random));
    }

    @Test
    public void testWriteByte() throws IOException {
        int random = new Random().nextInt();
        this.genericProtobufObjectOutput.writeByte((byte) random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readByte(), is((byte) random));
    }

    @Test
    public void testWriteShort() throws IOException {
        int random = new Random().nextInt();
        this.genericProtobufObjectOutput.writeShort((short) random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readShort(), is((short) random));
    }

    @Test
    public void testWriteInt() throws IOException {
        int random = new Random().nextInt();
        this.genericProtobufObjectOutput.writeInt(random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readInt(), is(random));
    }

    @Test
    public void testWriteFloat() throws IOException {
        float random = new Random().nextFloat();
        this.genericProtobufObjectOutput.writeFloat(random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readFloat(), is(random));
    }

    @Test
    public void testWriteDouble() throws IOException {
        double random = new Random().nextDouble();
        this.genericProtobufObjectOutput.writeDouble(random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readDouble(), is(random));
    }

    @Test
    public void testWriteString() throws IOException {
        byte[] bytes = new byte[new Random().nextInt(100)];
        new Random().nextBytes(bytes);

        this.genericProtobufObjectOutput.writeUTF(new String(bytes));
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readUTF(), is(new String(bytes)));
    }

    @Test
    public void testWriteBytes() throws IOException {
        byte[] bytes = new byte[new Random().nextInt(100)];
        new Random().nextBytes(bytes);
        this.genericProtobufObjectOutput.writeBytes(bytes);
        this.flushToInput();
        final byte[] bytes1 = genericProtobufObjectInput.readBytes();
        assertThat(bytes1, is(bytes));
    }

    @Test
    public void testWriteBytesSpecLength() throws IOException {
        final int length = new Random().nextInt(100);
        byte[] bytes = new byte[length];
        new Random().nextBytes(bytes);
        this.genericProtobufObjectOutput.writeBytes(bytes, 0, length);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readBytes(), is(bytes));
    }

    @Test
    public void testWriteLong() throws IOException {
        long random = new Random().nextLong();
        this.genericProtobufObjectOutput.writeLong(random);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readLong(), is(random));
    }

    @Test
    public void testWriteMap() throws IOException, ClassNotFoundException {
        Map<String, Object> map = new HashMap<>();
        map.put("key", "hello");
        map.put("value", "dubbo");
        this.genericProtobufObjectOutput.writeAttachments(map);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readAttachments(), is(map));
    }

    @Test
    void testWriteMultiType() throws IOException, ClassNotFoundException {
        long random = new Random().nextLong();
        this.genericProtobufObjectOutput.writeLong(random);
        Map<String, Object> map = new HashMap<>();
        map.put("key", "hello");
        map.put("value", "world");
        this.genericProtobufObjectOutput.writeAttachments(map);
        final int length = new Random().nextInt(100);
        byte[] bytes = new byte[length];
        new Random().nextBytes(bytes);
        this.genericProtobufObjectOutput.writeBytes(bytes, 0, length);
        int randomShort = new Random().nextInt();
        this.genericProtobufObjectOutput.writeShort((short) randomShort);
        this.flushToInput();
        assertThat(genericProtobufObjectInput.readLong(), is(random));
        assertThat(genericProtobufObjectInput.readAttachments(), is(map));
        assertThat(genericProtobufObjectInput.readBytes(), is(bytes));
        assertThat(genericProtobufObjectInput.readShort(), is((short) randomShort));
    }

    private void flushToInput() {
        this.genericProtobufObjectOutput.flushBuffer();
        this.byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        this.genericProtobufObjectInput = new GenericProtobufJsonObjectInput(byteArrayInputStream);
    }
}


text:
require 'spec_helper'

describe Storey, '.create_plain_schema' do
  context 'when there is no suffix set' do
    it 'should create a schema without a suffix' do
      Storey.create_plain_schema 'dun'
      expect(Storey.schemas(suffix: true)).to include('dun')
    end
  end

  context 'when there is a suffix set' do
    before do
      Storey.configuration.suffix = '_lop'
    end

    it 'should create a schema with the suffix' do
      Storey.create_plain_schema 'dun'
      expect(Storey.schemas(suffix: true)).to include('dun_lop')
    end
  end
end


text:
<?php
/**
 * @apiGroup           Storage
 * @apiName            downloadFile
 *
 * @api                {GET} /v1/storage/{folder_name}/{resource_name} Download File
 * @apiDescription     Download a file from server's public folder
 *
 * @apiVersion         1.0.0
 * @apiPermission      none
 *
 * @apiSuccessExample  {json}       Success-Response:
 * HTTP/1.1 202 OK
 */

$router->get('storage/{id}/{resource_name}', [
    'as' => 'api_storage_download_file',
    'uses'  => 'Controller@downloadFile',
]);


text:
FOUNDATION_EXPORT double KSGeographyVersionNumber;
FOUNDATION_EXPORT const unsigned char KSGeographyVersionString[];


text:
require 'spec_helper'

RSpec.describe 'GlobalID extensions' do
  describe 'GlobalID::Locator.locate' do
    it 'invokes GlobalIdUtils::Locator.locate' do
      str = 'gid://fish/NeonTetra/1'

      expect(GlobalIdUtils::Locator).to receive(:locate).with(str, [])
      GlobalID::Locator.locate(str)
    end
  end

  describe 'GlobalID::Locator.locate_many' do
    it 'invokes GlobalIdUtils::Locator.locate_many' do
      strs = ['gid://fish/NeonTetra/1', 'gid://fish/SiameseFighting/1']

      expect(GlobalIdUtils::Locator).to receive(:locate_many).with(strs, {})
      GlobalID::Locator.locate_many(strs)
    end
  end

  describe 'GlobalID.find!' do
    it 'raises if gid is invalid' do
      expect { GlobalID.find!('//bogus') }.to raise_error(URI::BadURIError)
    end

    it 'delegates to GlobalID.find if gid is valid' do
      str = 'gid://fish/NeonTetra/1'
      gid = GlobalID.new(str)

      expect(GlobalID).to receive(:find).with(gid, {})
      GlobalID.find!(str)
    end
  end

  describe 'GlobalID.find_many' do
    it 'invokes GlobalID::Locator.locate_many with options' do
      strs = ['gid://fish/NeonTetra/1', 'gid://fish/SiameseFighting/1']
      gids = strs.map { |str| GlobalID.parse(str) }

      expect(GlobalID::Locator).to receive(:locate_many).with(gids, ignore_missing: true)
      GlobalID.find_many(strs, ignore_missing: true)
    end
  end

  describe 'GlobalID.find_many!' do
    it 'raises if any gid is invalid' do
      strs = ['gid://fish/NeonTetra/1', '//bogus']

      expect { GlobalID.find_many!(strs) }.to raise_error(URI::BadURIError)
    end

    it 'invokes GlobalID.find_many with options if gids are valid' do
      strs = ['gid://fish/NeonTetra/1', 'gid://fish/SiameseFighting/1']
      gids = strs.map { |str| GlobalID.new(str) }

      expect(GlobalID).to receive(:find_many).with(gids, ignore_missing: true)
      GlobalID.find_many!(strs, ignore_missing: true)
    end
  end

  describe 'GlobalID.scoped_find' do
    let!(:model_class) do
      module Fish
        class NeonTetra < Base
        end
      end

      ::Fish::NeonTetra
    end

    before { GlobalID.app = 'testapp' }
    after { Fish.send(:remove_const, 'NeonTetra') if Fish.const_defined?('NeonTetra') }

    context 'when called with scope objects' do
      it 'evaluates multiple scopes' do
        with_name_scope = ::GlobalIdUtils::Scope.new(:with_name, 'Nemo')
        with_fins_scope = ::GlobalIdUtils::Scope.new(:with_fins)

        expect(model_class).to receive(:with_name).with('Nemo').and_return(model_class)
        expect(model_class).to receive(:with_fins).and_return(model_class)
        expect(model_class).to receive(:find_by!).with(id: '1').and_return(double)

        GlobalID.scoped_find('gid://fish/NeonTetra/1', [with_name_scope, with_fins_scope])
      end

      it 'evaluates a single scope' do
        with_name_scope = ::GlobalIdUtils::Scope.new(:with_name, 'Nemo')

        expect(model_class).to receive(:with_name).with('Nemo').and_return(model_class)
        expect(model_class).to receive(:find_by!).with(id: '1').and_return(double)

        GlobalID.scoped_find('gid://fish/NeonTetra/1', with_name_scope)
      end
    end

    context 'when called with scope name symbols' do
      it 'evaluates multiple scopes' do
        expect(model_class).to receive(:with_eyes).and_return(model_class)
        expect(model_class).to receive(:with_fins).and_return(model_class)
        expect(model_class).to receive(:find_by!).with(id: '1').and_return(double)

        GlobalID.scoped_find('gid://fish/NeonTetra/1', [:with_eyes, :with_fins])
      end

      it 'evaluates a single scope' do
        expect(model_class).to receive(:with_fins).and_return(model_class)
        expect(model_class).to receive(:find_by!).with(id: '1').and_return(double)

        GlobalID.scoped_find('gid://fish/NeonTetra/1', :with_fins)
      end
    end

    context 'when called with scope name strings' do
      it 'evaluates the scope' do
        expect(model_class).to receive(:with_fins).and_return(model_class)
        expect(model_class).to receive(:find_by!).with(id: '1').and_return(double)

        GlobalID.scoped_find('gid://fish/NeonTetra/1', 'with_fins')
      end
    end
  end
end


text:
package storm.kafka;

import backtype.storm.spout.Scheme;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class StringScheme implements Scheme {

    public List<Object> deserialize(byte[] bytes) {
        try {
            return new Values(new String(bytes, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public Fields getOutputFields() {
        return new Fields("str");
    }
}


text:
package org.robolectric.shadows;

import android.content.Context;
import android.app.DatePickerDialog;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import static org.robolectric.bytecode.RobolectricInternals.*;

@Implements(DatePickerDialog.class)
public class ShadowDatePickerDialog extends ShadowAlertDialog {

  @RealObject protected DatePickerDialog realDatePickerDialog;
  private int year;
  private int monthOfYear;
  private int dayOfMonth;

  public void __constructor__(Context context, int theme, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    this.year = year;
    this.monthOfYear = monthOfYear;
    this.dayOfMonth = dayOfMonth;

    getConstructor(DatePickerDialog.class, realDatePickerDialog, Context.class, int.class,
        DatePickerDialog.OnDateSetListener.class, int.class, int.class, int.class)
        .invoke(context, theme, callBack, year, monthOfYear, dayOfMonth);
  }

  public int getYear() {
    return year;
  }

  public int getMonthOfYear() {
    return monthOfYear;
  }

  public int getDayOfMonth() {
    return dayOfMonth;
  }
}


text:
import { expect } from 'chai';
import * as sinon from 'sinon';
import path from 'path';
import proxyquire from 'proxyquire';

import { the, when, should,
         getStubApp, getStubContainer,
         assertWasCalled, assertParameter, assertInstance } from '../../testing/src';

the('appBuilder', () => {

  const stubConfig = {};
  const stubLogger = { logStream: {} };
  const stubContainer = getStubContainer(stubConfig, stubLogger);
  const stubApp = getStubApp();
  const stubPassport = {};
  const stubInitialiseContent = sinon.spy();
  const stubInitialiseDataParsers = sinon.spy();
  const stubInitialiseErrorHandlers = sinon.spy();
  const stubInitialiseRequestLogger = sinon.spy();
  const stubInitialiseRoutes = sinon.spy();
  const stubInitialiseSecurity = sinon.spy();
  const stubInitialiseAuthentication = sinon.stub().returns(stubPassport);
  const stubGetRootPath = sinon.stub().returns('somepath');

  let AppBuilder;
  let builder;

  before(() => {

    proxyquire.noCallThru();

    const mocks = {

      './content': stubInitialiseContent,
      './dataParsers': stubInitialiseDataParsers,
      './errorHandlers': stubInitialiseErrorHandlers,
      './logging': stubInitialiseRequestLogger,
      './routes': stubInitialiseRoutes,
      './security': stubInitialiseSecurity,
      './authentication': stubInitialiseAuthentication,
      '../core/utilities': { getRootPath: stubGetRootPath }
    };

    AppBuilder = proxyquire('../src/middleware/appBuilder', mocks).default;
    builder = AppBuilder.create(stubContainer, stubApp);
  });

  when('created', () => {

    should('return a new AppBuilder instance', () => {

      assertInstance(builder, AppBuilder);
    });

    should('store config and logger instances from the container', () => {

      expect(builder._config).to.equal(stubConfig);
      expect(builder._logger).to.equal(stubLogger);
    });
  });

  when('useEjs called', () => {

    let setMethodSpy;
    let result;

    before(() => {

      setMethodSpy = sinon.spy(stubApp, 'set');
      result = builder.useEjs();
    });

    should('set views path to app views directory', () => {

      const firstSetCall = setMethodSpy.getCall(0);

      expect(firstSetCall.args[0]).to.equal('views');
      expect(firstSetCall.args[1]).to.equal(path.join('somepath', 'views'));
    });

    should('set view engine to ejs', () => {

      const secondSetCall = setMethodSpy.getCall(1);

      expect(secondSetCall.args[0]).to.equal('view engine');
      expect(secondSetCall.args[1]).to.equal('ejs');
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('logRequests called', () => {

    let result;

    before(() => {

      result = builder.logRequests();
    });

    should('initialise the request logger', () => {

      assertWasCalled(stubInitialiseRequestLogger);
      assertParameter(stubInitialiseRequestLogger, 0, stubApp);
      assertParameter(stubInitialiseRequestLogger, 1, stubConfig);
      assertParameter(stubInitialiseRequestLogger, 2, stubLogger.logStream);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('useDataParsers called', () => {

    let result;

    before(() => {

      result = builder.useDataParsers();
    });

    should('initialise the data parsers', () => {

      assertWasCalled(stubInitialiseDataParsers, stubApp);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('defaultContent called', () => {

    let result;

    before(() => {

      result = builder.defaultContent();
    });

    should('initialise the default content options (serve static & compress)', () => {

      assertWasCalled(stubInitialiseContent, stubApp);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('secure called', () => {

    let result;

    before(() => {

      result = builder.secure();
    });

    should('initialise security measures (HTTP headers via helmet)', () => {

      assertWasCalled(stubInitialiseSecurity, stubApp);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('useAuthentication called', () => {

    let result;

    before(() => {

      result = builder.useAuthentication();
    });

    should('initialise the authentication middleware', () => {

      assertWasCalled(stubInitialiseAuthentication);
      assertParameter(stubInitialiseAuthentication, 0, stubApp);
      assertParameter(stubInitialiseAuthentication, 1, stubContainer);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('useRoutes called', () => {

    const stubRoutes = {};
    let result;

    before(() => {

      result = builder.useRoutes(stubRoutes);
    });

    should('initialise the app routes', () => {

      assertWasCalled(stubInitialiseRoutes);
      assertParameter(stubInitialiseRoutes, 0, stubApp);
      assertParameter(stubInitialiseRoutes, 1, stubContainer);
      assertParameter(stubInitialiseRoutes, 2, stubRoutes);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('handleErrors called', () => {

    let result;

    before(() => {

      result = builder.handleErrors();
    });

    should('initialise the error handlers', () => {

      assertWasCalled(stubInitialiseErrorHandlers);
      assertParameter(stubInitialiseErrorHandlers, 0, stubApp);
      assertParameter(stubInitialiseErrorHandlers, 1, stubConfig);
      assertParameter(stubInitialiseErrorHandlers, 2, stubLogger);
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('trustProxy called', () => {

    let enableMethodSpy;
    let result;

    before(() => {

      enableMethodSpy = sinon.spy(stubApp, 'enable');
      result = builder.trustProxy();
    });

    should('enable \'trust proxy\' setting', () => {

      assertWasCalled(enableMethodSpy, 'trust proxy');
    });

    should('return the builder instance', () => {

      expect(result).to.equal(builder);
    });
  });

  when('result requested', () => {

    let r;

    before(() => {

      r = builder.result;
    });

    should('return the app (express) instance', () => {

      expect(r).to.equal(stubApp);
    });
  });
});


text:
local Command	= require("obj.Command")

--- test command
local Test		= Command:clone()
Test.name = "Test"
Test.keywords	= {"test"}

--- Execute the command
function Test:execute(input,user)
	print('test')
end

return Test


text:
// CHECKSTYLE:OFF
// Checkstyle is disabled because in test 'testUploadBigFileAndCompareChecksum'
// there is a needed while loop without a statement inside.

package org.springframework.cloud.aws.it.context.support.io;

import org.springframework.test.context.ContextConfiguration;

/**
 * @author Agim Emruli
 */
@ContextConfiguration
public class XmlResourceLoaderAwsTest extends ResourceLoaderAwsTest {

}


text:
/***************************************************************************/
/*                                                                         */
/*  rastpic.h                                                              */
/*                                                                         */
/*    The FreeType position independent code services for raster module.   */
/*                                                                         */
/*  Copyright 2009 by                                                      */
/*  Oran Agra and Mickey Gabel.                                            */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

#ifndef __RASTPIC_H__
#define __RASTPIC_H__

FT_BEGIN_HEADER

#include "../../include/freetype/internal/ftpic.h"

#ifndef FT_CONFIG_OPTION_PIC

#define FT_STANDARD_RASTER_GET  ft_standard_raster

#else /* FT_CONFIG_OPTION_PIC */

  typedef struct  RasterPIC_
  {
    int              ref_count;
    FT_Raster_Funcs  ft_standard_raster;

  } RasterPIC;

#define GET_PIC( lib )                                    \
          ( (RasterPIC*)( (lib)->pic_container.raster ) )
#define FT_STANDARD_RASTER_GET  ( GET_PIC( library )->ft_standard_raster )

  /* see rastpic.c for the implementation */
  void
  ft_raster1_renderer_class_pic_free( FT_Library  library );

  void
  ft_raster5_renderer_class_pic_free( FT_Library  library );

  FT_Error
  ft_raster1_renderer_class_pic_init( FT_Library  library );

  FT_Error
  ft_raster5_renderer_class_pic_init( FT_Library  library );

#endif /* FT_CONFIG_OPTION_PIC */

 /* */

FT_END_HEADER

#endif /* __RASTPIC_H__ */

/* END */


text:
package red

import (
	"bytes"
	"encoding/binary"
)

// ClientTicket is a spice packet send by the client
// that contains a ticket
type ClientTicket struct {
	// Ticket is the RSA encrypted ticket
	Ticket [ClientTicketBytes]byte
}

// MarshalBinary marshals a Packet into a byte slice.
func (p *ClientTicket) MarshalBinary() ([]byte, error) {
	p.finish()

	var buf bytes.Buffer
	if err := binary.Write(&buf, binary.LittleEndian, p.Ticket); err != nil {
		return nil, err
	}

	return buf.Bytes()[0:ClientTicketBytes], nil
}

// UnmarshalBinary unmarshals the contents of a byte slice into a Packet.
func (p *ClientTicket) UnmarshalBinary(b []byte) error {
	if len(b) != ClientTicketBytes {
		return errInvalidPacket
	}

	buf := bytes.NewReader(b[0:ClientTicketBytes])
	if err := binary.Read(buf, binary.LittleEndian, p.Ticket[:]); err != nil {
		return err
	}

	return p.validate()
}

// validate is used to validate the Packet.
func (p *ClientTicket) validate() error {
	return nil
}

// finish is used to finish the Packet for sending.
func (p *ClientTicket) finish() {
}


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>Kazlist</title>
    <link rel="shortcut icon" href="images/logo1.png" />
    <meta name="description" content="My App description">

    <link rel="manifest" href="/manifest.json">

    <meta name="theme-color" content="#3f51b5">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="My App">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="My App">

    <!-- Tile icon for Windows 8 (144x144 + tile color) -->
    <meta name="msapplication-TileColor" content="#3f51b5">
    <meta name="msapplication-tap-highlight" content="no">

    <script>
      // Setup Polymer options
      window.Polymer = {
        dom: 'shadow',
        lazyRegister: true
      };

      // Load webcomponentsjs polyfill if browser does not support native Web Components
      (function() {
        'use strict';

        var onload = function() {
          // For native Imports, manually fire WebComponentsReady so user code
          // can use the same code path for native and polyfill'd imports.
          if (!window.HTMLImports) {
            document.dispatchEvent(
              new CustomEvent('WebComponentsReady', {bubbles: true})
            );
          }
        };

        var webComponentsSupported = (
          'registerElement' in document
          && 'import' in document.createElement('link')
          && 'content' in document.createElement('template')
        );

        if (!webComponentsSupported) {
          var script = document.createElement('script');
          script.async = true;
          script.src = '/bower_components/webcomponentsjs/webcomponents-lite.min.js';
          script.onload = onload;
          document.head.appendChild(script);
        } else {
          onload();
        }
      })();

      // Load pre-caching Service Worker
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/service-worker.js');
        });
      }
    </script>

    <link rel="import" href="/src/dashboard-view.html">

    <style>
      body {
        margin: 0;
        font-family: 'Roboto', 'Noto', sans-serif;
        line-height: 1.5;
        min-height: 100vh;
        background-color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <dashboard-view></dashboard-view>
    <!-- Built with love using Polymer Starter Kit -->
  </body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace p05.IntegerToBase
{
    class Program
    {
        static void Main(string[] args)
        {
            int decimalNumber = int.Parse(Console.ReadLine());
            int baseToConvert = int.Parse(Console.ReadLine());

            IntBase(decimalNumber, baseToConvert);

        }

        static void IntBase(int number, int toBase)
        {
            string result = String.Empty;
            int remainder = 0;
            do
            {
                int curentDigit = number % toBase;
                string digitTostring = Convert.ToString(curentDigit);
                remainder = number / toBase;
                number = remainder;
                result = digitTostring + result;

            } while (remainder != 0);

            Console.WriteLine(result);
        }
    }
}


text:
package sgl.image;

import sgl.image.color.Color;
import sgl.image.raster.Raster;

import java.nio.Buffer;

/**
 * @author link
 */
public interface Image2D<C extends Canvas2D, R extends Raster, B extends Buffer> extends Image<C, R> {

	int getWidth();

	int getHeight();

	Color get(int s, int t);

	void set(int s, int t, Color color);

	B getValues(int startS, int endS, int startT, int endT);

	void setValues(int startS, int endS, int startT, int endT, B buffer);

}


text:
/**
 *
 * Ice
 *
 * Description :
 *  Move the entities which are above faster
 *
 *
 * @param game
 * @param x position
 * @param y position
 * @param parameters {Levels.level.TileParameters.type}
 *
 */

var IceTile = function (game, x, y, parameters) {

    // Sprite
    Tile.call(this, game, x, y, 'ice', parameters);

    // Randomize the order of sprites
    var animOrder = [0,1,2].sort(function() {
        return .5 - Math.random();
    });

    // Animations
    this.animations.add('tile_animation', animOrder, 2, true);
    this.animations.play("tile_animation");
};

IceTile.prototype = Object.create(Tile.prototype);
IceTile.prototype.constructor = IceTile;

IceTile.prototype.update = function() {

    this.bringToTop();

    var self = this;
    // Increase the speed of the entities which overlap the tile
    this.game.entities.forEachAlive(function(entity){
        if(self.checkOverlap(self.collisions, entity)){
            entity.increaseSpeed(self.speedIncrease);
        }
    });

};


text:
export default {
	'path': './application/tasks'
};


text:
import os
import re
import unittest

from king_phisher import testing
from king_phisher.client.mailer import *
from king_phisher.templates import MessageTemplateEnvironment
from king_phisher.utilities import random_string

class ClientMailerTests(testing.KingPhisherTestCase):
	def setUp(self):
		self.config = {
			'mailer.webserver_url': 'http://king-phisher.local/foobar',
			'server_config': {
				'server.secret_id': random_string(24),
				'server.tracking_image': "{0}.gif".format(random_string(32))
			}
		}
		self.image_cid_regex = r'img_[a-z0-9]{8}' + re.escape(os.path.splitext(testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE)[-1])

	def test_mailer_guess_smtp_server_address(self):
		random_host = random_string(7) + '.' + random_string(7) + '.' + random_string(3)
		self.assertIsNone(guess_smtp_server_address('localhost'))
		self.assertIsNone(guess_smtp_server_address('127.0.0.1'))
		self.assertIsNone(guess_smtp_server_address('::1'))
		self.assertIsNone(guess_smtp_server_address('localhost', 'localhost'))
		self.assertIsNone(guess_smtp_server_address('localhost', random_host))

		self.assertEqual(str(guess_smtp_server_address('10.0.0.1')), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('10.0.0.1', random_host)), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('127.0.0.1', '10.0.0.1')), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('::1', '10.0.0.1')), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('localhost', '10.0.0.1')), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('10.0.0.1', 'localhost')), '10.0.0.1')
		self.assertEqual(str(guess_smtp_server_address('10.0.0.1', '10.0.0.2')), '10.0.0.1')

	def test_mailer_message_format(self):
		secret_id = re.escape(self.config['server_config']['server.secret_id'])
		tracking_image = re.escape(self.config['server_config']['server.tracking_image'])

		formatted_msg = format_message(testing.TEST_MESSAGE_TEMPLATE, self.config)
		regexp = """()""".format(secret_id)
		self.assertRegex(formatted_msg, regexp, msg='The web server URL was not inserted correctly')
		regexp = """()""".format(tracking_image, secret_id)
		self.assertRegex(formatted_msg, regexp, msg='The tracking image tag was not inserted correctly')

	def test_client_template_environment_mode_analyze(self):
		tenv = MessageTemplateEnvironment()
		self.assertTrue(hasattr(tenv, 'attachment_images'))
		self.assertIsInstance(tenv.attachment_images, dict)
		self.assertEqual(len(tenv.attachment_images), 0)

		tenv.set_mode(MessageTemplateEnvironment.MODE_ANALYZE)
		template = tenv.from_string(testing.TEST_MESSAGE_TEMPLATE)
		template.render(dict(client=dict(), url=dict()))
		msg = 'The analysis mode failed to identify the inline image'
		self.assertIn(testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE, tenv.attachment_images, msg=msg)
		cid_value = tenv.attachment_images[testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE]
		self.assertRegex(cid_value, self.image_cid_regex)

	def test_client_template_environment_mode_preview(self):
		tenv = MessageTemplateEnvironment()
		tenv.set_mode(MessageTemplateEnvironment.MODE_PREVIEW)
		self.assertTrue('inline_image' in tenv.globals)
		inline_image = tenv.globals['inline_image']
		img_tag_result = inline_image(testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE)
		img_tag_test = "".format(testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE)
		msg = 'The preview mode failed to properly format the img HTML tag'
		self.assertEqual(img_tag_result, img_tag_test, msg=msg)

	def test_client_template_environment_mode_send(self):
		tenv = MessageTemplateEnvironment()
		tenv.set_mode(MessageTemplateEnvironment.MODE_SEND)
		self.assertTrue('inline_image' in tenv.globals)
		inline_image = tenv.globals['inline_image']
		img_tag_result = inline_image(testing.TEST_MESSAGE_TEMPLATE_INLINE_IMAGE)
		img_tag_test = r''
		msg = 'The send mode failed to properly format the img HTML tag'
		self.assertRegex(img_tag_result, img_tag_test, msg=msg)

if __name__ == '__main__':
	unittest.main()


text:
import java.io.*;
import java.util.Random;

class Collisions {
	static final int tablesize = 1000003;
	static Random r = new Random();
	static boolean[] check = new boolean[tablesize];

	/**
	 * Returns the next uniformly distributed random hash value
	 */
	static int nextHashValue() {
		return r.nextInt(tablesize);
	}

	public static void main(String[] args) throws IOException {

		// Sample risk of collision for i keys
		for (int i = 0; i < 10000; i += 50) {
			// Set counter to zero
			int cnt = 0;

			// Make 100 samples for each i
			for (int j = 1; j <= 100; j++) {
				// Reset the check array
				for (int m = 0; m < check.length; m++) {
					check[m] = false;
				}

				// Hash i values and check for the first collision
				for (int k = 0; k < i; k++) {
					int h = nextHashValue();
					if (check[h]) {
						cnt++; // increase counter if a collision occurred
						break;
					} else {
						check[h] = true;
					}
				}
			}

			// Print sample risk
			System.out.println(i + " " + ((double) cnt) / 100.0);
		}
	}
}


text:
package net.sourceforge.squirrel_sql.client.session.action;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

import net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo;
import net.sourceforge.squirrel_sql.fw.util.ICommand;

import net.sourceforge.squirrel_sql.client.session.IObjectTreeAPI;

/**
 * This Action will copy the object names of all objects
 * currently in the object tree and place on the system clipboard.
 *
 * @author Colin Bell
 */
public class CopyObjectNameCommand implements ICommand
{
	/** Type of copy to do. */
	public interface ICopyTypes
	{
		int SIMPLE_NAME = 0;
		int QUALIFIED_NAME = 1;
	}

	private IObjectTreeAPI _api;

	/** Type of copy to do. @see ICopyTypes */
	private int _copyType;

	/**
	 * Ctor specifying copy type.
	 *
	 * @param	api
	 * @param	copyType	Type of copy to do. @see ICopyTypes.
	 *
	 * @throws	IllegalArgumentException
	 * 			Thrown if a <TT>null</TT> <TT>ISession</TT> or an invalid
				<TT>copyType</TT> passed.
	 */
	public CopyObjectNameCommand(IObjectTreeAPI api, int copyType)
	{
		super();
		if (api == null)
		{
			throw new IllegalArgumentException("IObjectTreeAPI == null");
		}
		if (copyType < ICopyTypes.SIMPLE_NAME || copyType > ICopyTypes.QUALIFIED_NAME)
		{
			throw new IllegalArgumentException("Invalid copyType of : " + copyType + " passed");
		}

		_api = api;
		_copyType = copyType;
	}

	/**
	 * Copy to clipboard.
    */
	public void execute()
	{
		final StringBuffer buf = new StringBuffer(100);
		final IDatabaseObjectInfo[] dbObjs = _api.getSelectedDatabaseObjects();

		// Get all the selected object names and place in a comma separated list.
		for (int i = 0; i < dbObjs.length; i++)
		{
			final IDatabaseObjectInfo doi = dbObjs[i];
			final String name = _copyType == ICopyTypes.SIMPLE_NAME
									? doi.getSimpleName()
									: doi.getQualifiedName();
			buf.append(name).append(", ");
		}
		if (buf.length() > 0)
		{
			buf.setLength(buf.length() - 2);	// Remove trailing ", ".
			Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
			StringSelection data = new StringSelection(buf.toString());
			clip.setContents(data, data);
		}
	}
}


text:
I implement a streaming player for MPEG or MP3 files.
Example of use:
	(StreamingMP3Sound onFileNamed: 'song.mp3') play.


text:
require "spec_helper"

describe Mongoid::Document do

  before do
    Mongoid.database.collection(:people).drop
  end

  describe "#new" do

    it "gets a new or current database connection" do
      person = Person.new
      person.collection.should be_a_kind_of(Mongo::Collection)
    end

  end

  describe "#count" do

    before do
      Person.create(:title => "Sir")
    end

    it "returns the count" do
      Person.count.should == 1
    end

  end

  describe "#create" do

    it "persists a new record to the database" do
      person = Person.create(:title => "Test")
      person.id.should be_a_kind_of(String)
      person.attributes[:title].should == "Test"
    end

    context "when creating a has many" do

      before do
        @person = Person.new(:title => "Esquire")
        @person.addresses.create(:street => "Nan Jing Dong Lu", :city => "Shanghai")
      end

      it "should create and save the entire graph" do
        person = Person.find(@person.id)
        person.addresses.first.street.should == "Nan Jing Dong Lu"
      end

    end

  end

  context "chaining criteria scopes" do

    before do
      @one = Person.create(:title => "Mr", :age => 55, :terms => true)
      @two = Person.create(:title => "Sir", :age => 55, :terms => true)
      @three = Person.create(:title => "Sir", :age => 35, :terms => true)
      @four = Person.create(:title => "Sir", :age => 55, :terms => false)
    end

    it "finds by the merged criteria" do
      people = Person.old.accepted.knight
      people.count.should == 1
      people.first.should == @two
    end

  end

  context "using dynamic finders" do

    before do
      @person = Person.create(:title => "Mr", :age => 25)
    end

    context "finding by a single attribute" do

      it "returns found documents" do
        Person.find_by_title("Mr").should == @person
      end

    end

    context "finding by multiple attributes" do

      it "returns found documents" do
        Person.find_by_title_and_age("Mr", 25).should == @person
      end

    end

    context "finding all by a single attribute" do

      it "returns found documents" do
        Person.find_all_by_title("Mr").should == [@person]
      end

    end

    context "finding all by multiple attributes" do

      it "returns found documents" do
        Person.find_all_by_title_and_age("Mr", 25).should == [@person]
      end

    end
  end

  describe "#find" do

    before do
      @person = Person.create(:title => "Test")
    end

    context "finding all documents" do

      it "returns an array of documents based on the selector provided" do
        documents = Person.find(:all, :conditions => { :title => "Test"})
        documents.first.title.should == "Test"
      end

    end

    context "finding first document" do

      it "returns the first document based on the selector provided" do
        person = Person.find(:first, :conditions => { :title => "Test" })
        person.title.should == "Test"
      end

    end

    context "finding by id" do

      it "finds the document by the supplied id" do
        person = Person.find(@person.id)
        person.id.should == @person.id
      end

    end

  end

  describe "#find_by_id" do

    before do
      @person = Person.create
    end

    it "returns the document with the matching id" do
      Person.find_by_id(@person.id).should == @person
    end

  end

  describe "#group" do

    before do
      30.times do |num|
        Person.create(:title => "Sir", :age => num)
      end
    end

    it "returns grouped documents" do
      grouped = Person.select(:title).group
      people = grouped.first["group"]
      person = people.first
      person.should be_a_kind_of(Person)
      person.title.should == "Sir"
    end

  end

  describe "#paginate" do

    before do
      10.times do |num|
        Person.create(:title => "Test-#{num}")
      end
    end

    it "returns paginated documents" do
      Person.paginate(:per_page => 5, :page => 2).length.should == 5
    end

    it "returns a proper count" do
      @criteria = Mongoid::Criteria.translate(Person, { :per_page => 5, :page => 1 })
      @criteria.count.should == 10
    end

  end

  describe "#reload" do

    before do
      @person = Person.new(:title => "Sir")
      @person.save
      @from_db = Person.find(@person.id)
      @from_db.age = 35
      @from_db.save
    end

    it "reloads the obejct attributes from the db" do
      @person.reload
      @person.age.should == 35
    end

  end

  describe "#save" do

    context "on a has_one association" do

      before do
        @person = Person.new(:title => "Sir")
        @name = Name.new(:first_name => "Test")
        @person.name = @name
      end

      it "saves the parent document" do
        @name.save
        person = Person.find(@person.id)
        person.name.first_name.should == @name.first_name
      end

    end

  end

  context "when has many exists through a has one" do

    before do
      @owner = PetOwner.new(:title => "Sir")
      @pet = Pet.new(:name => "Fido")
      @visit = VetVisit.new(:date => Date.today)
      @pet.vet_visits << @visit
      @owner.pet = @pet
    end

    it "can clear the association" do
      @owner.pet.vet_visits.size.should == 1
      @owner.pet.vet_visits.clear
      @owner.pet.vet_visits.size.should == 0
    end

  end

  context "the lot" do

    before do
      @person = Person.new(:title => "Sir")
      @name = Name.new(:first_name => "Syd", :last_name => "Vicious")
      @home = Address.new(:street => "Oxford Street")
      @business = Address.new(:street => "Upper Street")
      @person.name = @name
      @person.addresses << @home
      @person.addresses << @business
    end

    it "allows adding multiples on a has_many in a row" do
      @person.addresses.length.should == 2
    end

    context "when saving on a has_one" do

      before do
        @name.save
      end

      it "saves the entire graph up from the has_one" do
        person = Person.first(:conditions => { :title => "Sir" })
        person.should == @person
      end

    end

    context "when saving on a has_many" do

      before do
        @home.save
      end

      it "saves the entire graph up from the has_many" do
        person = Person.first(:conditions => { :title => "Sir" })
        person.should == @person
      end
    end

  end

  context "setting belongs_to" do

    before do
      @person = Person.new(:title => "Mr")
      @address = Address.new(:street => "Bloomsbury Ave")
      @person.save!
    end

    it "allows the parent reference to change" do
      @address.addressable = @person
      @address.save!
      @person.addresses.first.should == @address
    end

  end

  context "typecasting" do

    before do
      @date = Date.new(1976, 7, 4)
      @person = Person.new(:dob => @date)
      @person.save
    end

    it "properly casts dates and times" do
      person = Person.first
      person.dob.should == @date
    end

  end

  context "versioning" do

    before do
      @comment = Comment.new(:text => "Testing")
      @comment.save
    end

    after do
      Comment.collection.drop
    end

    context "first save" do

      it "creates a new version" do
        @from_db = Comment.find(@comment.id)
        @from_db.text = "New"
        @from_db.save
        @from_db.versions.size.should == 1
        @from_db.version.should == 2
      end

    end

    context "multiple saves" do

      before do
        5.times do |n|
          @comment.save
        end
      end

      it "creates new versions" do
        @from_db = Comment.find(@comment.id)
        @from_db.version.should == 6
        @from_db.versions.size.should == 5
      end

    end

  end

  context "executing criteria with date comparisons" do

    context "handling specific dates" do

      before do
        @person = Person.create(:dob => Date.new(2000, 10, 31))
      end

      it "handles comparisons with todays date"do
        people = Person.select.where("this.dob < new Date()")
        people.first.should == @person
      end

      it "handles conparisons with a date range" do
        people = Person.select.where("new Date(1976, 10, 31) < this.dob && this.dob < new Date()")
        people.first.should == @person
      end

      it "handles false comparisons in a date range" do
        people = Person.select.where("new Date(2005, 10, 31) < this.dob && this.dob < new Date()")
        people.should be_empty
      end

      it "handles comparisons with date objects"do
        people = Person.select.where(:dob => { "$lt" => Date.today.midnight })
        people.first.should == @person
      end

    end

  end

end


text:
package org.nexbook.app

import org.nexbook.neworderhandler.NewOrderHandler

/**
  * Created by milczu on 12/21/15.
  */
trait OrderHandlersModule {

  def newOrderHandler: NewOrderHandler

}


text:
from django.db.models import Sum
from django.utils.timezone import now
from le_utils.constants import content_kinds
from le_utils.constants import exercises
from rest_framework import serializers

from kolibri.core.auth.models import FacilityUser
from kolibri.core.logger.constants.exercise_attempts import MAPPING
from kolibri.core.logger.models import AttemptLog
from kolibri.core.logger.models import ContentSessionLog
from kolibri.core.logger.models import ContentSummaryLog
from kolibri.core.logger.models import ExamAttemptLog
from kolibri.core.logger.models import ExamLog
from kolibri.core.logger.models import MasteryLog
from kolibri.core.logger.models import UserSessionLog
from kolibri.core.notifications.api import create_examattemptslog
from kolibri.core.notifications.api import create_examlog
from kolibri.core.notifications.api import create_summarylog
from kolibri.core.notifications.api import parse_attemptslog
from kolibri.core.notifications.api import parse_examlog
from kolibri.core.notifications.api import parse_summarylog
from kolibri.core.notifications.tasks import wrap_to_save_queue
from kolibri.core.serializers import KolibriModelSerializer
from kolibri.utils.time_utils import local_now

class ContentSessionLogSerializer(KolibriModelSerializer):

    extra_fields = serializers.JSONField(default="{}")

    """
    If we don't have a user, set the visitor_id to the session_key
    """

    def create(self, validated_data):
        request = self.context.get("request")
        # Must ensure there is no user here to maintain user privacy for logging.
        if request and hasattr(request, "COOKIES") and not validated_data.get("user"):
            validated_data["visitor_id"] = request.COOKIES.get("visitor_id")
        instance = super(ContentSessionLogSerializer, self).create(validated_data)
        return instance

    class Meta:
        model = ContentSessionLog
        fields = (
            "id",
            "user",
            "visitor_id",
            "content_id",
            "channel_id",
            "start_timestamp",
            "end_timestamp",
            "time_spent",
            "kind",
            "extra_fields",
            "progress",
        )

class ExamLogSerializer(KolibriModelSerializer):
    progress = serializers.SerializerMethodField()
    score = serializers.SerializerMethodField()

    def get_progress(self, obj):
        return obj.attemptlogs.values_list("item").distinct().count()

    def get_score(self, obj):
        return (
            obj.attemptlogs.values_list("item")
            .order_by("completion_timestamp")
            .distinct()
            .aggregate(Sum("correct"))
            .get("correct__sum")
        )

    class Meta:
        model = ExamLog
        fields = (
            "id",
            "exam",
            "user",
            "closed",
            "progress",
            "score",
            "completion_timestamp",
        )
        read_only_fields = ("completion_timestamp",)

    def update(self, instance, validated_data):
        # This has changed, set the completion timestamp
        if validated_data.get("closed") and not instance.closed:
            instance.completion_timestamp = now()
        instance = super(ExamLogSerializer, self).update(instance, validated_data)
        # to check if a notification must be created:
        wrap_to_save_queue(parse_examlog, instance, local_now())
        return instance

    def create(self, validated_data):
        instance = super(ExamLogSerializer, self).create(validated_data)
        # to check if a notification must be created:
        wrap_to_save_queue(create_examlog, instance, local_now())
        return instance

class MasteryLogSerializer(KolibriModelSerializer):

    pastattempts = serializers.SerializerMethodField()
    totalattempts = serializers.SerializerMethodField()
    mastery_criterion = serializers.JSONField(default="{}")
    update_fields = ("pastattempts",)

    class Meta:
        model = MasteryLog
        fields = (
            "id",
            "summarylog",
            "start_timestamp",
            "pastattempts",
            "totalattempts",
            "user",
            "end_timestamp",
            "completion_timestamp",
            "mastery_criterion",
            "mastery_level",
            "complete",
        )

    def get_pastattempts(self, obj):
        mastery_criterion = obj.mastery_criterion
        exercise_type = mastery_criterion.get("type")
        attemptlogs = (
            AttemptLog.objects.filter(masterylog__summarylog=obj.summarylog)
            .values("correct", "hinted", "error")
            .order_by("-start_timestamp")
        )

        # get the first x logs depending on the exercise type
        if exercise_type == exercises.M_OF_N:
            return attemptlogs[: mastery_criterion["n"]]
        elif MAPPING.get(exercise_type):
            return attemptlogs[: MAPPING.get(exercise_type)]
        else:
            return attemptlogs[:10]

    def get_totalattempts(self, obj):
        return AttemptLog.objects.filter(masterylog__summarylog=obj.summarylog).count()

class AttemptLogSerializer(KolibriModelSerializer):
    answer = serializers.JSONField(default="{}")
    interaction_history = serializers.JSONField(default="[]")

    class Meta:
        model = AttemptLog
        fields = (
            "id",
            "masterylog",
            "start_timestamp",
            "sessionlog",
            "end_timestamp",
            "completion_timestamp",
            "item",
            "time_spent",
            "user",
            "complete",
            "correct",
            "hinted",
            "answer",
            "simple_answer",
            "interaction_history",
            "error",
        )

    def create(self, validated_data):
        instance = super(AttemptLogSerializer, self).create(validated_data)
        # to check if a notification must be created:
        wrap_to_save_queue(parse_attemptslog, instance)
        return instance

    def update(self, instance, validated_data):
        instance = super(AttemptLogSerializer, self).update(instance, validated_data)
        # to check if a notification must be created:
        wrap_to_save_queue(parse_attemptslog, instance)
        return instance

class ExamAttemptLogSerializer(KolibriModelSerializer):
    answer = serializers.JSONField(default="{}", allow_null=True)
    interaction_history = serializers.JSONField(default="[]")

    class Meta:
        model = ExamAttemptLog
        fields = (
            "id",
            "examlog",
            "start_timestamp",
            "content_id",
            "end_timestamp",
            "completion_timestamp",
            "item",
            "time_spent",
            "user",
            "complete",
            "correct",
            "hinted",
            "answer",
            "simple_answer",
            "interaction_history",
        )

    def validate(self, data):
        # Only do this validation when both are being set
        # not necessary on PATCH, for example
        if data.get("examlog") and data.get("user"):
            try:
                if data["examlog"].user != data["user"]:
                    raise serializers.ValidationError(
                        "User field and user for related exam log are not the same"
                    )
            except ExamLog.DoesNotExist:
                raise serializers.ValidationError("Invalid exam log")
        return data

    def create(self, validated_data):
        instance = super(ExamAttemptLogSerializer, self).create(validated_data)
        # to check if a notification must be created:
        wrap_to_save_queue(create_examattemptslog, instance.examlog, local_now())
        return instance

class ContentSummaryLogSerializer(KolibriModelSerializer):

    currentmasterylog = serializers.SerializerMethodField()
    extra_fields = serializers.JSONField(default="{}")
    update_fields = ()

    class Meta:
        model = ContentSummaryLog
        fields = (
            "id",
            "user",
            "content_id",
            "channel_id",
            "start_timestamp",
            "currentmasterylog",
            "end_timestamp",
            "completion_timestamp",
            "time_spent",
            "progress",
            "kind",
            "extra_fields",
        )

    def get_currentmasterylog(self, obj):
        try:
            current_log = obj.masterylogs.latest("end_timestamp")
            return MasteryLogSerializer(current_log).data
        except MasteryLog.DoesNotExist:
            return None

    def create(self, validated_data):
        instance = super(ContentSummaryLogSerializer, self).create(validated_data)
        # dont create notifications upon creating a summary log for an exercise
        # notifications should only be triggered upon first attempting a question in the exercise
        if instance.kind == content_kinds.EXERCISE:
            return instance
        # to check if a notification must be created:
        wrap_to_save_queue(create_summarylog, instance)
        return instance

    def update(self, instance, validated_data):
        instance = super(ContentSummaryLogSerializer, self).update(
            instance, validated_data
        )
        # to check if a notification must be created:
        wrap_to_save_queue(parse_summarylog, instance)
        return instance

class UserSessionLogSerializer(KolibriModelSerializer):

    update_fields = ()

    class Meta:
        model = UserSessionLog
        fields = (
            "id",
            "user",
            "channels",
            "start_timestamp",
            "last_interaction_timestamp",
            "pages",
        )

class TotalContentProgressSerializer(serializers.ModelSerializer):

    progress = serializers.SerializerMethodField()

    class Meta:
        model = FacilityUser
        fields = ("progress", "id")

    def get_progress(self, obj):
        return (
            obj.contentsummarylog_set.filter(progress=1)
            .aggregate(Sum("progress"))
            .get("progress__sum")
        )