text:
<!doctype html>

		<meta charset="utf-8">

		<title>Ruby native extensions</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Povilas Jurčys">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/beige.css" id="theme">
		<link rel="stylesheet" href="css/custom.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

						+

						=

					http://facts.randomhistory.com/2009/08/04_love.html

						Created by Povilas Jurčys / @PovilasJurcys

PostgreSql

							Postresql already becomes rails developer top choise. Let's talk why

Remoe and Juliet effect

						Sometimes called the "Romeo and Juliet effect," a situation with challenges
						or obstructions is likely to intensify one's passion for a loved one

							Postresql already becomes rails developer top choise. Let's talk why

What is good about Postgresql

Datatypes

Foreign key support

Full text search

							Postresql already becomes rails developer top choise. Let's talk why

Remoe and Juliet effect

						A study conducted in 1989 assures that simple eye contact could make
						a person fall in love with you (Kellerman, Lewis, and Laird).
						The Power of Eye Contact - Make Someone Fall in Love With You!
						In this study two opposite sex strangers were asked to gaze into each other's eyes
						for two minutes, which in some cases, was enough to produce passionate feelings for each other

							Postresql already becomes rails developer top choise. Let's talk why

Datatype: citext

								enable_extension 'citext'

								create_table :users do |t|
								  t.citext :username, null: false
								end

								add_index :users, :username, unique: true

							User.create(username: 'BloomRain') # ok
							User.create(username: 'bloomrain') # fail
							User.find_by(username: 'BlooMrAiN')

Datatype: Array

							create_table :books do |t|
							  t.string 'title'
							  t.string 'tags', array: true
							  t.integer 'ratings', array: true
							end
							add_index :books, :tags, using: 'gin'
							add_index :books, :ratings, using: 'gin'

	Book.create(tags: ['fantasy', 'fiction], ratings: [4, 5])
	Book.where("'fantasy' = ANY (tags)")
	Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])
	Book.where("array_length(ratings, 1) >= 3")

Datatype: JSON(B)

							create_table :product do |t|
								t.sort :string
							  t.jsonb 'details', array: true
							end
							add_index :books, :info, using: 'gin'

							Product.create(sort: 'Book', details: {'ISBN': '047X', lang: 'en'})
							# has key?
							Product.where('details ? "ISBN"')
							# has key/val pair?
							Product.where('details @> {"ISBN": "047X" }')

PostgreSql

						http://edgeguides.rubyonrails.org/active_record_postgresql.html

								Complex data types

Array

JSON, JSONB

XML, date ranges, custom types...

								Foreign key constraints

								Full text search support

						http://simononsoftware.com/great-presentation-postgresql-and-rails/

Rails 4.2 and Postgres 9.4

Foreign Key Support (PostgeSql, MySql)

JSONB format (PostgeSql)

Citext format (PostgeSql)

Foreign key constraints

https://robots.thoughtbot.com/referential-integrity-with-foreign-keys

https://robots.thoughtbot.com/referential-integrity-with-foreign-keys

http://adamsanderson.github.io/railsconf_2013/?full#49

Hstore stores all values as text :(

Questions?

Thanks!


text:
const NONE = 0;
const READ_ONLY = 1;
const DONT_ENUM = 2;
const DONT_DELETE = 4;

# Constants used for getter and setter operations.
const GETTER = 0;
const SETTER = 1;

# These definitions must match the index of the properties in objects.h.
const kApiTagOffset =                  0;
const kApiPropertyListOffset =         1;
const kApiSerialNumberOffset =         2;
const kApiConstructorOffset =          2;
const kApiPrototypeTemplateOffset =    5;
const kApiParentTemplateOffset =       6;

const NO_HINT     = 0;
const NUMBER_HINT = 1;
const STRING_HINT = 2;

const kFunctionTag =          0;
const kNewObjectTag =         1;

# For date.js
const HoursPerDay =                24;
const MinutesPerHour =             60;
const SecondsPerMinute =           60;
const msPerSecond =              1000;
const msPerMinute =             60000;
const msPerHour =             3600000;
const msPerDay =             86400000;

# Note: kDayZeroInJulianDay = ToJulianDay(1970, 0, 1)
const kInvalidDate =   'Invalid Date';
const kDayZeroInJulianDay =   2440588;
const kMonthMask = 0x1e0;
const kDayMask   = 0x01f;
const kYearShift = 9;
const kMonthShift = 5;

# Type query macros
macro IS_NULL(arg)              = (arg === null);
macro IS_NULL_OR_UNDEFINED(arg) = (arg == null);
macro IS_UNDEFINED(arg)         = (typeof(arg) === 'undefined');
macro IS_FUNCTION(arg)          = (typeof(arg) === 'function');
macro IS_NUMBER(arg)            = (typeof(arg) === 'number');
macro IS_STRING(arg)            = (typeof(arg) === 'string');
macro IS_OBJECT(arg)            = (typeof(arg) === 'object');
macro IS_BOOLEAN(arg)           = (typeof(arg) === 'boolean');
macro IS_REGEXP(arg)            = (%ClassOf(arg) === 'RegExp');
macro IS_ARRAY(arg)             = (%ClassOf(arg) === 'Array');
macro IS_DATE(arg)              = (%ClassOf(arg) === 'Date');
macro IS_ERROR(arg)             = (%ClassOf(arg) === 'Error');
macro IS_SCRIPT(arg)            = (%ClassOf(arg) === 'Script');

# 'Inline' macros
# (Make sure arg is evaluated only once via %IS_VAR)
macro NUMBER_IS_NAN(arg)        = (!%_IsSmi(%IS_VAR(arg)) && !(arg == arg));
macro TO_INTEGER(arg)           = (%_IsSmi(%IS_VAR(arg)) ? arg : ToInteger(arg));
macro TO_INT32(arg)             = (%_IsSmi(%IS_VAR(arg)) ? arg : ToInt32(arg));

python macro CHAR_CODE(str)     = ord(str[1]);

# Accessors for original global properties that ensure they have been loaded.
const ORIGINAL_REGEXP     = (global.RegExp, $RegExp);
const ORIGINAL_DATE       = (global.Date, $Date);

redpajama_set_name: RedPajamaGithub


text:
package io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;

import structure.map.TokenMap;

import com.google.gson.Gson;

public class Writer
{
	private static Writer mInstance = null;

	private Writer() {}

	public static void init()
	{
		if (mInstance == null)
			mInstance = new Writer();
	}

	public static Writer getInstance()
	{
		return mInstance;
	}

	/**
	 * Cria arquivo com a frequencia das palavras
	 * @param map
	 * @throws IOException
	 */
	public void createFrequencyMapFile(String path, TreeMap<String, Integer> map) throws IOException
	{
		createGenericFile(path, map);
		/*for (Entry<String , Integer> entry : map.entrySet())
		{
			bw.write(entry.getKey());
			bw.write(";");
			bw.write(entry.getValue().toString());
			bw.newLine();
		}*/
	}

	public void createInvertedIndexFiles(String sortedMapPath, String reverseMapPath, TokenMap invertedIndex) throws IOException
	{
		createGenericFile(sortedMapPath, invertedIndex.getSortedTokenMap());
		createGenericFile(reverseMapPath, invertedIndex.getReverseTokenMap());
		/*for (Entry<String, ArrayList<Integer>> entry : map.entrySet())
		{
			bw.write(entry.getKey());
			bw.write(":");
			for (Integer i : entry.getValue())
			{
				bw.write(i.toString());
				bw.write(";");
			}
			bw.newLine();
		}*/
	}

	/**
	 * Create a index file with all files in the collection,
	 * only if the file don't exist.
	 * @param files
	 * @throws IOException
	 */
	public void createDocumentsIndexFile(String docsIndexPath, ArrayList<File> files) throws IOException
	{
		HashMap<Integer, String> filesIndex = new HashMap<Integer, String>();
		for (int i = 0; i < files.size(); ++i)
			filesIndex.put(i, files.get(i).getAbsolutePath());

		Gson gson = new Gson();
		String filesJSON = gson.toJson(filesIndex);

		createFile(docsIndexPath, filesJSON);
	}

	private void createGenericFile(String path, Object obj) throws IOException
	{
		Gson gson = new Gson();
		String filesJSON = gson.toJson(obj);

		createFile(path, filesJSON);
	}

	private void createFile(String docsIndexPath, String content) throws IOException
	{
		File outFile = new File(docsIndexPath);
		outFile.createNewFile();

		FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(content);
		bw.close();
	}
}


text:
//
//  Config.h
//  arbf-image-super_resolution
//
//  Created by Ke Liu on 2/26/15.
//  Copyright (c) 2015 Ke Liu. All rights reserved.
//

#ifndef __arbf_image_super_resolution__Config__
#define __arbf_image_super_resolution__Config__

#include <string>

//////////////////////////////////////////////////////
// choose one of the two
//#define NEIGHBOR_1RING // use 1-ring neighborhood
#define NEIGHBOR_2RING // use 2-ring neighborhood

//////////////////////////////////////////////////////
//#define ISO_RBF // use isotropic RBF interpolation

//////////////////////////////////////////////////////
//#define WEIGHTED // take weighted average

class Config
{
public:
    static const double EPSILON;
    static const double C0; // C0 parameter in paper
    static bool isUsing2Ring; // if use 2-ring neighborhood
    static bool isUsingWeightedInterpolation; // if use weighted interpolation
    static bool isUsingISORBF; // if use ISO-RBF for eigenvalues

//    static std::string loggerName;
//    static const std::string loggerINFO;
//    static const std::string loggerWARNING;
//    static const std::string loggerERROR;
//    static const std::string loggerFATAL;
};

#endif /* defined(__arbf_image_super_resolution__Config__) */


text:
<component name="libraryTable">
  <library name="jbox2d">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/jbox2d.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
"""
tests.test_component_sun
~~~~~~~~~~~~~~~~~~~~~~~~~~

Tests Sun component.
"""
# pylint: disable=too-many-public-methods,protected-access
import unittest
import datetime as dt

import ephem

import homeassistant as ha
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
import homeassistant.components.sun as sun

class TestSun(unittest.TestCase):
    """ Test the sun module. """

    def setUp(self):  # pylint: disable=invalid-name
        self.hass = ha.HomeAssistant()

    def tearDown(self):  # pylint: disable=invalid-name
        """ Stop down stuff we started. """
        self.hass.stop()

    def test_is_on(self):
        """ Test is_on method. """
        self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON)
        self.assertTrue(sun.is_on(self.hass))
        self.hass.states.set(sun.ENTITY_ID, sun.STATE_BELOW_HORIZON)
        self.assertFalse(sun.is_on(self.hass))

    def test_setting_rising(self):
        """ Test retrieving sun setting and rising. """
        # Compare it with the real data
        self.assertTrue(sun.setup(
            self.hass,
            {ha.DOMAIN: {
                CONF_LATITUDE: '32.87336',
                CONF_LONGITUDE: '117.22743'
            }}))

        observer = ephem.Observer()
        observer.lat = '32.87336'  # pylint: disable=assigning-non-slot
        observer.long = '117.22743'  # pylint: disable=assigning-non-slot

        utc_now = dt.datetime.utcnow()
        body_sun = ephem.Sun()  # pylint: disable=no-member
        next_rising_dt = ephem.localtime(
            observer.next_rising(body_sun, start=utc_now))
        next_setting_dt = ephem.localtime(
            observer.next_setting(body_sun, start=utc_now))

        # Home Assistant strips out microseconds
        # strip it out of the datetime objects
        next_rising_dt = next_rising_dt - dt.timedelta(
            microseconds=next_rising_dt.microsecond)
        next_setting_dt = next_setting_dt - dt.timedelta(
            microseconds=next_setting_dt.microsecond)

        self.assertEqual(next_rising_dt, sun.next_rising(self.hass))
        self.assertEqual(next_setting_dt, sun.next_setting(self.hass))

        # Point it at a state without the proper attributes
        self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON)
        self.assertIsNone(sun.next_rising(self.hass))
        self.assertIsNone(sun.next_setting(self.hass))

        # Point it at a non-existing state
        self.assertIsNone(sun.next_rising(self.hass, 'non.existing'))
        self.assertIsNone(sun.next_setting(self.hass, 'non.existing'))

    def test_state_change(self):
        """ Test if the state changes at next setting/rising. """
        self.assertTrue(sun.setup(
            self.hass,
            {ha.DOMAIN: {
                CONF_LATITUDE: '32.87336',
                CONF_LONGITUDE: '117.22743'
            }}))

        if sun.is_on(self.hass):
            test_state = sun.STATE_BELOW_HORIZON
            test_time = sun.next_setting(self.hass)
        else:
            test_state = sun.STATE_ABOVE_HORIZON
            test_time = sun.next_rising(self.hass)

        self.assertIsNotNone(test_time)

        self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
                           {ha.ATTR_NOW: test_time + dt.timedelta(seconds=5)})

        self.hass.pool.block_till_done()

        self.assertEqual(test_state, self.hass.states.get(sun.ENTITY_ID).state)

    def test_setup(self):
        """ Test Sun setup with empty and wrong configs. """
        self.assertFalse(sun.setup(self.hass, {}))
        self.assertFalse(sun.setup(self.hass, {sun.DOMAIN: {}}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {CONF_LATITUDE: '32.87336'}}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {CONF_LONGITUDE: '117.22743'}}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {CONF_LATITUDE: 'hello'}}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {CONF_LONGITUDE: 'how are you'}}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {
                CONF_LATITUDE: 'wrong', CONF_LONGITUDE: '117.22743'
            }}))
        self.assertFalse(sun.setup(
            self.hass, {ha.DOMAIN: {
                CONF_LATITUDE: '32.87336', CONF_LONGITUDE: 'wrong'
            }}))

        # Test with correct config
        self.assertTrue(sun.setup(
            self.hass, {ha.DOMAIN: {
                CONF_LATITUDE: '32.87336', CONF_LONGITUDE: '117.22743'
            }}))


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkgem.jeesite.modules.weixin.dao.JtydWeixinArticleDao">

	<sql id="jtydWeixinArticleColumns">
		a.id AS "id",
		a.weixin_name AS "weixinName",
		a.weixin_code AS "weixinCode",
		a.article_name AS "articleName",
		a.article_url AS "articleUrl",
		a.article_content AS "articleContent",
		a.create_date AS "createDate",
		a.update_by AS "updateBy.id",
		a.update_date AS "updateDate",
		a.remarks AS "remarks",
		a.del_flag AS "delFlag"
	</sql>

	<sql id="jtydWeixinArticleJoins">
	</sql>

	<select id="get" resultType="JtydWeixinArticle">
		SELECT
			<include refid="jtydWeixinArticleColumns"/>
		FROM jtyd_weixin_article a
		<include refid="jtydWeixinArticleJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="JtydWeixinArticle">
		SELECT
			<include refid="jtydWeixinArticleColumns"/>
		FROM jtyd_weixin_article a
		<include refid="jtydWeixinArticleJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
			<if test="weixinName != null and weixinName != ''">
				AND a.weixin_name LIKE
					<if test="dbName == 'oracle'">'%'||#{weixinName}||'%'</if>
					<if test="dbName == 'mssql'">'%'+#{weixinName}+'%'</if>
					<if test="dbName == 'mysql'">concat('%',#{weixinName},'%')</if>
			</if>
			<if test="weixinCode != null and weixinCode != ''">
				AND a.weixin_code = #{weixinCode}
			</if>
			<if test="articleName != null and articleName != ''">
				AND a.article_name LIKE
					<if test="dbName == 'oracle'">'%'||#{articleName}||'%'</if>
					<if test="dbName == 'mssql'">'%'+#{articleName}+'%'</if>
					<if test="dbName == 'mysql'">concat('%',#{articleName},'%')</if>
			</if>
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>

	<select id="findAllList" resultType="JtydWeixinArticle">
		SELECT
			<include refid="jtydWeixinArticleColumns"/>
		FROM jtyd_weixin_article a
		<include refid="jtydWeixinArticleJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>

	<insert id="insert">
		INSERT INTO jtyd_weixin_article(
			id,
			weixin_name,
			weixin_code,
			article_name,
			article_url,
			article_content,
			create_date,
			update_by,
			update_date,
			remarks,
			del_flag
		) VALUES (
			#{id},
			#{weixinName},
			#{weixinCode},
			#{articleName},
			#{articleUrl},
			#{articleContent},
			#{createDate},
			#{updateBy.id},
			#{updateDate},
			#{remarks},
			#{delFlag}
		)
	</insert>

	<update id="update">
		UPDATE jtyd_weixin_article SET
			weixin_name = #{weixinName},
			weixin_code = #{weixinCode},
			article_name = #{articleName},
			article_url = #{articleUrl},
			article_content = #{articleContent},
			update_by = #{updateBy.id},
			update_date = #{updateDate},
			remarks = #{remarks}
		WHERE id = #{id}
	</update>

	<update id="delete">
		UPDATE jtyd_weixin_article SET
			del_flag = #{DEL_FLAG_DELETE}
		WHERE id = #{id}
	</update>

</mapper>


text:
Sample collection for Wikitude
===================

A few samples and snippets working with Wikitude SDK


text:
Telegram Plugin
===============

Send alerts to Telegram Bot.

![Telegram Message](./images/alerta-telegram-plugin.png)

For help, join [![Gitter chat](https://badges.gitter.im/alerta/chat.png)](https://gitter.im/alerta/chat)

Installation
------------

Clone the GitHub repo and run:

    $ python setup.py install

Or, to install remotely from GitHub run:

    $ pip install git+https://github.com/alerta/alerta-contrib.git#subdirectory=plugins/telegram

Note: If Alerta is installed in a python virtual environment then plugins
need to be installed into the same environment for Alerta to dynamically
discover them.

Configuration
-------------

Add `telegram` to the list of enabled `PLUGINS` in `alertad.conf` server
configuration file and set plugin-specific variables either in the
server configuration file or as environment variables.

```python
PLUGINS = ['telegram']
TELEGRAM_TOKEN = ''  # default="not set"
TELEGRAM_CHAT_ID = ''  # default="not set"
```

Create a new Telegram Bot using a Telegram client.

See https://core.telegram.org/bots#creating-a-new-bot

To `ack`, `close` or `blackout` an alert from the Telegram client set
the webhook URL to your Alerta API Telegram endpoint (must be HTTPS):

```python
TELEGRAM_WEBHOOK_URL = 'https://alerta.example.com/webhooks/telegram'
BLACKOUT_DURATION = 86400   # default=3600 ie. 1 hour
```

Troubleshooting
---------------

Restart Alerta API and confirm that the plugin has been loaded and enabled.

Set `DEBUG=True` in the `alertad.conf` configuration file and look for log
entries similar to below:

```
--------------------------------------------------------------------------------
DEBUG in __init__ [/Users/nsatterl/.virtualenvs/telegram/lib/python2.7/site-packages/alerta/plugins/__init__.py:46]:
Server plug-in 'telegram' found.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in alerta_telegram [build/bdist.macosx-10.12-x86_64/egg/alerta_telegram.py:21]:
Telegram: {u'username': u'alertaio_bot', u'first_name': u'alerta-bot', u'id': 264434259}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
INFO in __init__ [/Users/nsatterl/.virtualenvs/telegram/lib/python2.7/site-packages/alerta/plugins/__init__.py:53]:
Server plug-in 'telegram' enabled.
--------------------------------------------------------------------------------
```

References
----------

  * Telegram Bots Intro: https://core.telegram.org/bots
  * Telepot Python Client: http://telepot.readthedocs.io/en/latest/

License
-------

Copyright (c) 2016 Nick Satterly. Available under the MIT License.


text:
var client = require('socket.io').listen(8080).sockets;
//contain room objs
//room obj = {"name": *yourRoomName, "people": [the client id]}
var rooms = [];				// save the room status

var roomUuidCounter = 0;
/*
	contains client info
	client obj = {"name": the name of the client, "id": the id of the socket}
*/
var allClients = [];		//save all socket in the gobal var
var allPeople={};

//the socket which disconnected
var disconnectSocket = [];

var RoomMaxClient = 4;			//A setting var for control the max people in the room

/*
	This obj for managing the room operation in the server side
	which in the stage II
*/
var RoomManager = {
	Rooms: [],
	UUIDCounter : 0,
	/*
		Get the UUID and increase the UUID counter
	*/
	GetUUID: function(){
		return this.UUIDCounter++;
	},
	/*
		Return a room obj
		input: name, first people socket id,
	*/
	CreateRoom : function(name, SocketId, master,RmId){
		tempRoom = {
			"name":name,
			"peopleInfo":{length:1},
			"inGame": false,
			"deleted":false,
			"maxPeople":7,
			"stage":3,
			"RmId": RmId,
			"version":0,
			"deleted":false,
			"masterSocketId":SocketId
		};
		tempRoom["peopleInfo"][SocketId]= this.CreateClientInfo(master,"screen",this.GetClient(SocketId)["name"]);
		return tempRoom;
	},
	/*
		Create the Client info obj, which contain the absic imformation of the client
	*/
	CreateClientInfo: function(master,mode,name){
		clientInfo = {
			"ready": false, 			// A ready flag
			"mode":mode, 				//controller mode or screen mode
			"master":master,			// Master flag
			"stage":3,					// the stage flag
			"loadedSrc":false,			// A flag to state the client load the src already
			"gameData":{},				// for future use {game mode}
			"name":name
		};
		return clientInfo;
	},
	/*
		Get the name from the system
	*/
	GetClient: function(SocketId){
		for(i = 0 ; i < allClients.length; i++){
			if(SocketId == allClients[i]["id"]){
				return allClients[i];
			}
		}
		return null;
	},
	/*
		Broadcast data to every room client
	*/
	RoomBroadcast: function(room, data, Tag){
		//console.log(RoomManager.GetClient(room["people"][0]));
		console.log(room);

		for(i in room["peopleInfo"]){
			if(i != "length"){
				console.log(room["peopleInfo"][i]);
				RoomManager.GetClient(i).socket.emit(Tag, data);
			}
		}
	},
	/*
		copy room info to the server
	*/
	CopyClientInfo: function(room, RmId){
		rooms[RmId] = room;
	},
	/*
		boardcast room status
	*/
	BroadcasRmStatus: function(room, Tag, type){
		console.log("i am Broadcasting the msg to all user");
		data = {
					"type":type,
					"data":room
				}
		RoomManager.RoomBroadcast(room, data, Tag)
	},

	/*
		Delete the socket info in the room
	*/
	DeleteSocketInRoom: function(room, SocketId){
		for(i = 0; i < room["people"].length; i++){
			if(room["people"][i] == SocketId){
				room["people"] = room["people"].splice(i , SocketId);

				delete room["peopleInfo"][SocketId] ;
			}
		}
	},
	/*
		Deleted the Empty Room
	*/
	CheckEmptyRoom: function(){
		console.log(".......CheckEmptyRoom  and delate the emty room.....");
		for(i in rooms){
			console.log(rooms[i]);
			if(rooms[i]["peopleInfo"].length <1 && !rooms[i]["deleted"]){
				rooms[i]["deleted"]=true;
				console.log("found emty Room");
			}
		}
	},
	/*
		For delete the record from the system
	*/
	DeleteSocketInRooms: function(SocketId){
		console.log(".......DeleteSocketInRooms.....");
		var tempSocketId=SocketId;

		for(i in rooms){
			//console.log("this is room obj:");
			//console.log(rooms[i]);
			if(rooms[i]["peopleInfo"][SocketId] != undefined){
				console.log("i found in peopleInfo at room: "+ rooms[i]["name"])
				console.log(rooms[i]["people"]);

				//delate people with that socket id
				delete rooms[i]["peopleInfo"][SocketId];
				rooms[i]["peopleInfo"].length--;

				//boardcast to all client
				RoomManager.BroadcasRmStatus(rooms[i], "WaitingRoom", "RoomUpdate");

			}else{
				console.log("i can't found in peopleInfo at room: "+ rooms[i]["name"])
			}
		}

		this.CheckEmptyRoom();

		return;

	},
	/*
		The join Room function, which responsible for upgrading the client to the game waiting room
	*/
	JoinRoom: function(SocketObj, data){
		console.log("The data to the joinroom "+SocketObj.id);
		console.log(data);
		console.log(rooms);
		//insert new record in to room
		if(rooms[data.id]["name"] == data.name){
			//rooms[data.id]["people"].push(SocketObj.id);
			SocketObj.emit('roomMangement', {
							"result":true,
							"type":"upgrade",
							"NextStage": 3,
							"message": "go to waiting room!",
							"master":false,
							"mode":"controller",
							"RoomID": data.id,
							"RoomName": data.name
						});

			rooms[data.id]["peopleInfo"].length++;

			//add the imformation of the poepleInfo
			rooms[data.id]["peopleInfo"][SocketObj.id] = RoomManager.CreateClientInfo(false,"controller",this.GetClient(SocketObj.id)["name"]);
		}else{
			SocketObj.emit('roomMangement', {"result":false, "type":"join","message": "please get the latest rooms list"});
		}
	},
	//Slectect the Room that reuiqre
	SlectRoom: function(RoomNumber){
		return rooms[RoomNumber];
	}
}

var StageIV = {

};

//each connection form each connector
client.on('connection', function(socket){

	console.log("New user: "+socket.id);

	var sendStatus=function(s){
			socket.emit('status',s);
		},
		debug = function(s){
			socket.emit('debug',s);
		}
	var removeDisconnectElement = function(){
			//delete the old socket id
			for( i = 0 ; i < disconnectSocket.length; i++){
				for( j = 0 ; j < allClients.length; j++){
					if(disconnectSocket[i] == allClients[j].id){
						allClients.splice( j, 1 );
						disconnectSocket.splice( i, 1 );
						removeDisconnectElement();
						console.log("delete the old record !!!!")
					}
				}
			}
			return;
	};

	var checkName = function (name){

			removeDisconnectElement();

			console.log("checking name with allClients ");
			if(allClients.length < 1)
				return true;

			for(i = 0 ; i < allClients.length; i++){
				if(allClients[i].name == name){
					console.log(name + ' is found in the system');
					return false;
				}
			}
			console.log(name + ' can not found in the system');
			return true;
		},
		checkIdInRoom = function(id){
			console.log("--------------------------------");
			console.log("start check any room have the id of:"+id);
			if(rooms == undefined)
				rooms = [];

			console.log("you are here" );
			console.log(rooms);

			RoomManager.CheckEmptyRoom();

			for(i in rooms){
				for(j in rooms[i]["people"]){
					if(rooms[i]["people"][i] == id){
						return true;
					}
				}
			}

			return false;
		},
		joinRoom = function(data){
			console.log("The data to the joinroom");
			//console.log(data);
			//console.log(rooms);
			//insert new record in to room
			if(rooms[data.id]["name"] == data.name){
				//rooms[data.id]["people"].push(socket.id);
				socket.emit('roomMangement', {"result":true, "type":"join","message": "you got into room "+ data.id +" name: "+ data.name});
				//add the imformation of the poepleInfo
				rooms[data.id]["peopleInfo"][socket.id] = {};
				rooms[data.id]["peopleInfo"].length++;
			}else{
				socket.emit('roomMangement', {"result":false, "type":"join","message": "please get the latest rooms list"});
			}

		};

	/*
		websocket listener: listen the tag of registerUser
		client will ask server is the name exist in the server or not, if yes the server will return error
	*/
	socket.on('registerUser', function(data){
		console.log("hello "+ data.name);

		whitespacePattern = /^\s*$/;
		//check the name and return the user exist or not
		if(checkName(data.name)  && !whitespacePattern.test(data.name)){
			found = false;
			if(allClients != undefined || allClients.length != undefined){
				for(i = 0 ; i < allClients.length; i++ ){

					if(allClients[i]["id"] == socket.id){
						allClients[i]["name"] = data.name;
						found = true;
						console.log("update the name for id:"+data.name);
					}
				}
			}
			if(found == false){
				//allPeople[socket.id]={ "name": data.name, "socket":socket};
				allClients.push({ "name": data.name, "id": socket.id, "socket":socket});
			}

			socket.emit('registerUser', {"name":data.name, "result":true});
		}else{
			socket.emit('registerUser', {"name":data.name, "result":false, "message": "please choose other name!"});
		}
	});

	//this is for the stage II - choose room or create room
	socket.on('roomMangement', function(data){
		console.log('------------ roomMangement ---------');

		if(rooms == undefined)
			rooms=[];

		if(data.type == undefined)
			socket.emit('roomMangement', {"result":false, "message": "Input Error"});

		//client want to request the list of rooms can get in
		if(data.type == "check"){
			console.log("----------- output Room Lsit ----------");
			var roomList = [];
			for(i in rooms){
				if(!rooms[i]["deleted"])
					roomList.push({"id":i, "name":rooms[i]["name"], "noPeople": rooms[i]["peopleInfo"].length});
			}

			//output the result
			//socket.emit('roomMangement', {"type": "roomList", "rooms":JSON.stringify(roomList, null, 4)});
			socket.emit('roomMangement', {"type": "roomList", "rooms":roomList, data:rooms});
			delete roomList;
			return;
		}

		//client want to remove thier record from the system
		//remove the old record in the room, if the room less than one people, remove the room
		if(data.type == "removeFromRoom"){
			for(i = 0 ; i < rooms.length; i++){
				for(j = 0; j < rooms[i][people].length; j++){
					if(	rooms[i][people][j] == socket.id ){
						console.log("id "+socket.id+"has been delated from room "+ i + " name: "+ rooms[i]["name"]);
						rooms[i][people] = rooms[i][people].splice( j, 1 );
						if(rooms[i][people].length < 1){
							delete rooms[i];
							//rooms = rooms.splice(i, 1);
							console.log("Room "+ i +"has been deleted, due to no of ppl in the room less than 1");
						}
					}
				}
			}
		}

		//check if the socket id is in any room or not
		if(checkIdInRoom(socket.id)){
			console.log("you are in the room!!!!");
			switch(data.type){
				//delate the record in the database and update the new decision
				case "join":
					//delate the old record
					for( i = 0 ; i < rooms.length; i ++){
						for(j = 0 ; j< rooms[i]["people"].length; j++){
							if(rooms[i]["people"][j] == socket.id){
								rooms[i]["people"] = rooms[i]["people"].splice(j , 1);
								console.log("socket id: "+ socket.id + " has been deleted from the room "+ rooms[i]["name"]);
							}
						}
					}

					//insert new record in to room
					joinRoom(data);

					//get the room tht client in
					room = RoomManager.SlectRoom(rmid);

					//boardcast the lastest Room imformation to client
					RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");

					break;
				case "create":
					socket.emit('roomMangement', {"result":false, "type":"join","message": "please quit the room first"});
					break;
			}
		}else{

			console.log("you are not in the room!!!!");
			//not in any room yet, he can create or remove the room, edit the room name
			switch(data.type){
				case "create":
				//for creating room
					if(data.name != undefined){
						rmid = RoomManager.GetUUID();
						rooms[rmid] = RoomManager.CreateRoom(data.name, socket.id, true, rmid);
						socket.emit('roomMangement', {
							"result":true,
							"type":"upgrade",
							"NextStage": 3,
							"message": "go to waiting room!",
							"master":true,
							"mode":"screen",
							"RoomID": rmid,
							"RoomName": data.name
						});
						console.log("Room name: "+ data.name +" has been created ");

						//get the room tht client in
						room = RoomManager.SlectRoom(rmid);

						//boardcast the lastest Room imformation to client
						RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");
					}else{
						socket.emit('roomMangement', {"result":false, "type":"create","message": "please input correct name for your room"});
					}
					break;
				//put this new socket id to the room
				case "join":

					//joinRoom(data);
					RoomManager.JoinRoom(socket, data);

					//get the room tht client in
					room = RoomManager.SlectRoom(data.id);

					//boardcast the lastest Room imformation to client
					RoomManager.BroadcasRmStatus(rooms[data.id], "WaitingRoom", "RoomUpdate");
					break;

			}
		}

	});

	//stage 4 room
	socket.on('game', function(data){
		Room =  RoomManager.SlectRoom(RoomNumber);
	});

	//stage 3 room operation
	socket.on('WaitingRoom', function(data){
		console.log("----------------------------------")
		console.log('This is stage III with socket : '+socket.id);
		//console.log(room);
		room = RoomManager.SlectRoom(data.RmId);
		//every client will save tthe Room status
		switch(data.type){
			//cal by every client
			case "IAmLoaded":
			case "IAmReady":
				//copy client profile data
				rooms[data.RmId].peopleInfo[socket.id] = data.ClientProfile;
				//get lastest room message
				room = RoomManager.SlectRoom(data.RmId);
				//boardcast the startgame message to every client
				RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");
				break;
			case "StartGame":
				//only master can give this command to others
				if(!room["peopleInfo"][socket.id]["master"])
					return;
				//update room in game flag
				rooms[data.RmId]["inGame"] = true;

				//get lastest room message
				room = RoomManager.SlectRoom(data.RmId);

				//boardcast the startgame message to every client
				RoomManager.RoomBroadcast(room, data, "WaitingRoom")
				break;
			case "LoadImg":
				//only master can give this command to others
				if(!room["peopleInfo"][socket.id]["master"])
					return;
				//boardcast the startgame message to every client
				RoomManager.BroadcasRmStatus(room, "WaitingRoom", "LoadImg");
				break;
			case "QuitRoom":
				//delete the particular client in the room
				RoomManager.DeleteSocketInRoom(room, socket.id)
				//boardcast the lastest Room imformation to client
				RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");
				break;
			case "UpdateClientInfo":
				console.log(data.data);
				//copy the info to server
				RoomManager.CopyClientInfo(data.data, data.RmId);

				room = RoomManager.SlectRoom(data.RmId);

				//boardcast to all client
				RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");
				break;
			case "UpdateRoomInfo":
				//only can done by master
					//if not emit msg"no permission" and return
				if(!RoomManager.GetClient(socket)["master"])
					return;
				else
					socket.emit("debug",{"msg":"no permission"});

				//update to server
				RoomManager.BroadcasRmStatus(room, "WaitingRoom", "RoomUpdate");
				break;

		}
		console.log('The room result');
		console.log(rooms[data.RmId]);
		console.log('This is the end of stage III with socket : '+socket.id);
		console.log("----------------------------------")
	});

	//wait for input form the socket
	socket.on('InGame', function(data){
		//Handle if the data only have to route to other
		if(data.TransmitOnly){
			if(data.To == "ALL")
				RoomManager.RoomBroadcast(rooms[data.RmId], data, "InGame")
			else
				RoomManager.GetClient(data.To)["socket"].emit("InGame", data);
			return;
		}
	});

	//wait for input form the socket
	socket.on('input', function(data){
		var name = data.name,
			message = data.message,
			whitespacePattern = /^\s*$/;

		if(whitespacePattern.test(name) || whitespacePattern.test(message)){
			sendStatus('Name and Message is required');
		}else{

			//Emit latest msg to all clients
			client.emit('output',[data]);

			sendStatus({
				message:"message send",
				clear:true
			});
		}

	});

	socket.on('disconnect', function() {
		console.log('Got disconnect! from id:' + socket.id);

		//console.log("this is all poeple");
		//console.log(allPeople);

		if(allClients == undefined){
			var allClients = [];
		}

		for(i = 0 ; i < allClients.length; i++){
			console.log(allClients[i]);
			if(allClients[i]["id"] == socket.id){
				delete allClients[i];
				if(allClients == undefined){
					var allClients = []; // initialzed
				}
				console.log(socket.id + " found the socket and i will delete it");
				break;
			}
			console.log("deleting loop");
		}

		disconnectSocket.push(socket.id);
		RoomManager.DeleteSocketInRooms(socket.id);
   	});

});


text:
layout: page
title: Temple Dart Systems Trade Fair
date: 2016-05-24
author: Paul Wheeler
tags: weekly links, java
status: published
summary: Donec aliquet erat sit amet metus mattis, a facilisis.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/26/2017
  endDate: 06/28/2017
  ctyhocn: DRYKYHX
  groupCode: TDSTF
published: true
---
In at gravida massa. Donec blandit tellus at metus blandit, in elementum libero consectetur. Fusce volutpat ipsum vitae nibh accumsan, non accumsan mi fringilla. Sed dignissim neque pulvinar blandit mattis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis vitae pulvinar erat. Etiam porta lectus non dignissim molestie. Curabitur laoreet eros non erat venenatis, tempus laoreet justo imperdiet.

* Nam aliquam felis ac nunc egestas pulvinar
* Nullam ornare dolor eget odio malesuada consectetur
* Cras et libero sit amet eros pellentesque pretium
* Donec maximus purus pharetra, efficitur augue ut, feugiat mauris.

Nunc euismod porttitor nisi tincidunt luctus. Nulla hendrerit consectetur purus sed scelerisque. Praesent sodales molestie imperdiet. Aenean ut ligula ipsum. Mauris viverra ipsum a tortor feugiat imperdiet. Cras blandit leo ultricies nisi ultricies feugiat. Duis eu quam ut massa lacinia gravida ac et tellus. Curabitur ac interdum libero, ac facilisis elit.


text:
package syscall

func Ioctl(fd, req, arg uintptr) (err Errno) {
	_, _, err = Syscall(SYS_IOCTL, fd, req, arg)
	return err
}


text:
<?PHP
namespace DanielBingham\FrameworkInterface;

interface Request {

	public function getFromPost($name='');

	public function getFromGet($name='');

	public function getFromCookie($name='');

	public function getFromRequest($name='');
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.coursera.androidcapstone.potlatch.activities.GiftDisplayActivity$PlaceholderFragment">

    <ImageView
        android:id="@+id/ivProfile"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:padding="8dp"
        android:src="@drawable/admin" />

    <TextView
        android:id="@+id/tvUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_below="@id/ivProfile"
        android:paddingBottom="8dp"
        android:textSize="@dimen/abc_text_size_menu_material"
        android:layout_alignStart="@id/ivProfile"
        android:layout_alignEnd="@id/ivProfile"
        android:gravity="center_horizontal"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/ivProfile"
        android:layout_toEndOf="@id/ivProfile"
        android:padding="8dp" />

    <TextView
        android:id="@+id/tvText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@id/tvTitle"
        android:layout_below="@id/tvTitle"
        android:padding="8dp" />

    <ImageView
        android:id="@+id/ivObscene"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@id/tvText"
        android:padding="4dp"
        android:src="@drawable/obscene_no" />

    <TextView
        android:id="@+id/tvTouches"
        android:layout_width="wrap_content"
        android:layout_height="24dp"
        android:layout_alignBottom="@id/ivObscene"
        android:layout_marginRight="4dp"
        android:layout_toLeftOf="@id/ivObscene"
        android:padding="4dp" />

    <ImageView
        android:id="@+id/ivTouched"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignBottom="@id/ivObscene"
        android:layout_marginRight="4dp"
        android:layout_toLeftOf="@id/tvTouches"
        android:padding="4dp"
        android:src="@drawable/touched_no" />

    <org.coursera.androidcapstone.potlatch.views.AspectRatioImageView
        android:id="@+id/ivGiftImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tvUser"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:padding="4dp"
        android:layout_marginTop="8dp"
        android:scaleType="centerCrop" />

</RelativeLayout>


text:
package com.heitao.exogfx.core;

import android.content.Context;
import android.os.Handler;

import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.video.MediaCodecVideoRenderer;
import com.google.android.exoplayer2.video.VideoRendererEventListener;

/**
 * Created by showtime on 10/11/2017.
 */

public class ExogfxCodecVideoRenderer extends MediaCodecVideoRenderer {

    public ExogfxCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector) {
        super(context, mediaCodecSelector);
    }

    public ExogfxCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector, long allowedJoiningTimeMs) {
        super(context, mediaCodecSelector, allowedJoiningTimeMs);
    }

    public ExogfxCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
                                        long allowedJoiningTimeMs, DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
                                        boolean playClearSamplesWithoutKeys, Handler eventHandler,
                                        VideoRendererEventListener eventListener, int maxDroppedFramesToNotify) {
        super(context, mediaCodecSelector, allowedJoiningTimeMs, drmSessionManager, playClearSamplesWithoutKeys, eventHandler, eventListener, maxDroppedFramesToNotify);
    }

    @Override
    protected void onQueueInputBuffer(DecoderInputBuffer buffer) {

        byte[] data = new byte[20];

        buffer.data.get(data);

        super.onQueueInputBuffer(buffer);
    }
}


text:
title: 'RoboHydra: A New Testing Tool for Client-Server Interactions'
authors:
- esteban-velazquez
intro: 'RoboHydra is a web server designed to help you write and test software that uses HTTP as a communication protocol. This article will take you through the basics of how RoboHydra works and how to install and use it at a basic level. You'll see how to use it as a proxy for an existing site, and how you can make changes to local files and see those changes immediately reflected on the live site!'
license: cc-by-3.0
---

Introduction

HTTP is the most used protocol on the internet. Most APIs available on the internet use it — not only web pages, but also mobile applications, public APIs, programs for backend service integration, etc. Considering how much software uses HTTP to talk to other software, it's surprising that there aren't many tools to assist us in situations where we want to test communication between client and server across HTTP.

RoboHydra is a web server designed precisely to help you write and test software that uses HTTP as a communication protocol. There are many ways to use RoboHydra, but the most common use cases are as follows:

RoboHydra allows you to combine a locally stored website front end with a back end sat on a remote server, allowing you to test your own local front end installation with a fully functional back end, without having to install the back end on your local machine.

If you write a program designed to talk to a server using HTTP, you can use RoboHydra to imitate that server and pass custom responses to the program. This can help you reproduce different bugs and situations that might be otherwise hard, if not impossible, to test.

This article will take you through the basics of how RoboHydra works and how to install and use it at a basic level; at the end you will explore the first scenario listed above. Future articles will explore the second scenario listed above, and look at more advanced uses of RoboHydra.

A RoboHydra's anatomy

A RoboHydra web server is composed of many heads. A RoboHydra head is a piece of software that serves requests for a certain URL path, and defines a certain behaviour for that head to apply to that URL. For example, a RoboHydra server could have one head listening in /articles/newest that returns a fixed list of articles, another head listening in /static that proxies HTTP requests to the production server, and so on.

The behaviour of each head is determined by its type: there are heads that always return a fixed response, heads that proxy requests to another server, heads that serve files from the local filesystem, heads that execute a given JavaScript function, etc. You can program your own heads to define whatever behaviour you want.

When a RoboHydra server receives a request, it will go through all its heads in order, trying to find one that matches the URL of the incoming request. When it finds one, it will make that head process the request.

RoboHydra runs as a Node JS package. That means it is written in JavaScript but runs on the command line, not in the browser (remember — it's a server, not a client!)

Installing RoboHydra

You can essentially install and use Robohydra wherever you like on your local drive, but you need to choose a single directory to do your installation and work inside. Therefore, before installing anything, we'll create a directory called devo-robohydra that will contain all the files created for this article, and the RoboHydra installation itself. Execute all commands from this directory: RoboHydra uses relative paths to find its files.

The first step towards using RoboHydra on your computer is to make sure you have Node JS installed (you can check by typing node -v in a terminal; you should get at least version v0.6.0). If not, you'll have to install Node JS first. You can compile Node from source or download the pre-compiled binaries (.pkg, .exe, etc.) for the platform of your choice — see nodejs.org for more.

Next, install RoboHydra itself by typing npm install robohydra in your command line. You should end up with RoboHydra installed inside the directory devo-robohydra/node_modules/robohydra. Once installed, you don't actually need to touch anything inside the node_modules directory.

Note: You can also install RoboHydra by downloading it directly from the RoboHydra project on GitHub and putting it inside a manually created node_modules directory.

RoboHydra basics

Once installed, you can run RoboHydra from your working directory by invoking your own custom configuration files like so:

./node_modules/.bin/robohydra configuration-file-name

Or, if you add node_modules/.bin to your $PATH, simply with:

robohydra configuration-file-name

So robohydra is run from inside the node_modules directory, and your configuration files are placed inside the root of your working directory, which in this case is devo-robohydra.

RoboHydra configuration files are simple JSON files that specify a list of plugins to be loaded. Plugins are special scripts that define one or more heads that you want to load together. A configuration file loading two plugins, monitor and dev-proxy, would look like this:

{
	"plugins": [
		{"name": "monitor", "config": {}},
		{"name": "dev-proxy", "config": {}}
	]
}

The actual code of your plugins is written in JavaScript, and needs to be stored in a directory robohydra/plugins, placed inside your working directory. So by default, the example plugins mentioned above would be loaded from devo-robohydra/robohydra/plugins/monitor/index.js and devo-robohydra/robohydra/plugins/dev-proxy/index.js. We will see how to write a full plugin in the example that follows.

For more example plugins and configuration files, look in the devo-robohydra/node_modules/robohydra/examples directory.

Using RoboHydra as a proxy

As we explained earlier, one of the situations in which RoboHydra can be useful is when you're developing the front end of a web application. Imagine you are one of the front end developers for http://www.opera.com. It would be convenient to be able to connect to some URL in your browser that behaves like opera.com, except that the front end files are served from your local filesystem, and the back end is hosted somewhere else — you don't actually need to have the whole opera.com backend on your local machine!

To achieve this you can create a simple RoboHydra web server that serves local files for any requests starting with a certain path containing your local code (for example /js/), and proxies every other request (e.g. /developer/tools) to http://www.opera.com.

Writing a proxy plugin

To achieve this, we'll have to write a RoboHydra plugin containing two heads: one to serve local files from /js/ and another to proxy everything else to http://www.opera.com. The former will serve static files, and the latter will be a proxying head. The plugin code will look like this:

var heads                   = require('robohydra').heads,
		RoboHydraHeadFilesystem = heads.RoboHydraHeadFilesystem,
		RoboHydraHeadProxy      = heads.RoboHydraHeadProxy;

exports.getBodyParts = function(config) {
	var projectPath = config.rootpath || '.';

	return {
		heads: [
			new RoboHydraHeadFilesystem
			(
				{
					name: 'js',
					mountPath: '/js',
					documentRoot: projectPath + '/static/js'
				}
			),

			// When none of the above heads match, this head
			// always matches
			new RoboHydraHeadProxy
			(
				{
					name: 'proxy',
					mountPath: '/',
					proxyTo: 'http://www.opera.com',
					setHostHeader: true
				}
			)
		]
	};
};

We'll call our plugin operacom-dev: save the above code as devo-robohydra/robohydra/plugins/operacom-dev/index.js.

Now create a configuration file called operacom-dev.conf inside devo-robohydra with the following contents:

{
	"plugins": [
		{"name": "operacom-dev", "config": {"rootpath": "operacom"}}
	]
}

As a last step, you'll have to download the JavaScript files for www.opera.com and uncompress the ZIP file in the devo-robohydra directory.

Now you should have all these files and directories in devo-robohydra:

node_modules, containing the installed robohydra package.

robohydra/plugins/operacom-dev, containing your plugin.

operacom-dev.conf, your configuration file.

The operacom/static/js directory, containing your front-end files for www.opera.com.

RoboHydra in action

Now that everything is in place, you can start the custom server by telling RoboHydra which configuration file it should load:

./node_modules/.bin/robohydra operacom-dev.conf

RoboHydra will then listen on port 3000. This means you can go to http://localhost:3000 with your browser, and you'll see opera.com. However, if you modify the files under operacom/static/js, you'll see the changes immediately: you could be a front-end developer for www.opera.com!

Note: To start RoboHydra listening on a different port, you need to start it and include the -p flag, followed by the desired port number. So for example, ./node_modules/.bin/robohydra -p 3001 operacom-dev.conf would start it on port 3001.

Let's see this in action. Open operacom/static/js/mainmenu.js and find the following function:

frm.onsubmit=function() {
	if(this.words.value=='Search www.opera.com'||this.words.value=='') {
		alert('Please enter a search term.');
		this.words.focus();
		return false;
	}
}

If you click on the search button at the bottom of the page without typing in any words, the alert box will appear to tell you what to do. Let's try changing this function to the following, to present the error message to the user in a different way:

frm.onsubmit=function() {
	if(this.words.value=='Search www.opera.com'||this.words.value=='') {
		wrd.value = 'Please enter a search term.';
		wrd.style.color = 'black';
		wrd.style.fontWeight = 'bold';
		this.words.focus();
		return false;
	}
}

Save your JS file, then go to http://localhost:3000 with your browser and reload the page to make sure you're using the latest JavaScript files. If you go to the bottom of the page and click on the search button without typing any words, you'll see the updated effect. This illustrates just how great RoboHydra is for such experimentation.

The admin interface

Another RoboHydra feature that comes in handy in many situations is the admin interface. From it you can, among other things, see the available heads, create heads with fixed content, and enable and disable heads — see Figure 1. It's always available at http://localhost:3000/robohydra-admin/.

Figure 1: The RoboHydra admin interface. Note that our custom heads are listed, along with attach and detach buttons.

In the context of using RoboHydra as a front-end development proxy, one practical use of the admin interface is to compare how the site behaves with our local JavaScript code and the original code. To do so, we only have to detach and reattach the "js" head. When the head is detached, only the "proxy" head will be active, so all requests will pass through to www.opera.com.

Summary

This concludes our short tour of RoboHydra. By now you should be familiar with how to install and use RoboHydra and write a simple plugin for it. You should also now be well aware of how useful it can be! In subsequent articles, we'll show you some more interesting and complex use cases, like emulating a server to build a test suite or saving and replaying traffic to allow you to work offline.


text:
pkg_prereqs=('apt-get' 'git' 'node')
pkg_extract_path=~/
pkg_description='vim - the best code editor ever'

function install_package() {
  b.system.pretend_super

  # remove old vims
  sudo apt-get remove --purge vim vim-runtime gvim vim-nox vim-gnome
  sudo apt-get remove --purge vim-tiny vim-common vim-gui-common

  # install dependencies
  sudo apt-get install -y curl
  sudo apt-get install -y exuberant-ctags
  sudo apt-get install -y build-essential cmake
  sudo apt-get install -y mercurial python python-dev python3 python3-dev ruby ruby-dev libx11-dev libxt-dev libgtk2.0-dev libncurses5 ncurses-dev
  sudo apt-get autoremove
  sudo apt-get install -y silversearcher-ag
  sudo apt-get install -y libclang-dev
  sudo apt-get install -y libperl-dev
  sudo apt-get install -y lua5.1 liblua5.1-dev
  # sudo apt-get build-dep vim

  # fix liblua/luajit paths and issues
  sudo mkdir /usr/include/lua5.1/include
  sudo cp /usr/include/lua5.1/*.h /usr/include/lua5.1/include

  cd /tmp
  git clone http://luajit.org/git/luajit-2.0.git
  cd luajit-2.0
  make
  sudo make install

  # configure vim dirs
  vim_dir="$HOME/.vim"
  vimruntime="/usr/local/share/vim/vim80"
  vim_tpm_dir="/tmp/vim80"

  # delete & install vim
  sudo rm -rf $vim_tpm_dir
  sudo rm -f /usr/bin/vim
  sudo rm -rf /usr/local/share/vim

  cd /tmp && git clone https://github.com/vim/vim.git vim80
  cd ./vim80

  ./configure --enable-perlinterp \
    --enable-python3interp \
    --enable-pythoninterp \
    --enable-rubyinterp \
    --enable-luainterp \
    --enable-gui=auto \
    --enable-gtk2-check \
    --enable-gnome-check \
    --enable-fail-if-missing \
    --enable-multibyte \
    --enable-largefile \
    --disable-netbeans \
    --with-luajit \
    --with-features=huge \
    --with-x \
    --with-ruby-command=/usr/bin/ruby \
    --with-lua-prefix=/usr/include/lua5.1 \
    --with-python3-config-dir=/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/

  make VIMRUNTIMEDIR=$vimruntime
  sudo make install
  sudo rm -rf $vim_tmp_dir

  rm -rf ~/.vim_old
  mv ~/.vimrc ~/.vimrc_old
  mv ~/.vim ~/.vim_old
  mv ~/.NERDTreeBookmarks ~/.NERDTreeBookmarks_old

  mkdir $vim_dir
  cd $vim_dir
  mkdir "$vim_dir/bundle"
  git clone https://github.com/Shougo/neobundle.vim "$vim_dir/bundle/neobundle.vim"

  # install neverland theme
  cd /tmp
  rm -rf ./neverland-vim-theme
  git clone https://github.com/trapd00r/neverland-vim-theme.git
  sudo cp -a /tmp/neverland-vim-theme/colors/* "$vimruntime/colors"

  ln -s ~/.vim/.vimrc ~/.vimrc
  mkdir ~/.vim/undodir

  sudo curl -o /usr/local/share/fonts/VeraMono-Powerline.ttf -L https://gist.githubusercontent.com/smileart/9741746/raw/72573cff6dd7a2a99d27c7339e08705976f5abeb/VeraMono-Powerline.ttf

  echo
  b.color.cecho_warning
  b.color.cecho $ansi_yellow 'Before using vim, reload your terminal OR `source ~/.bashrc or ~/.omgzsh`'
  b.color.cecho $ansi_yellow 'OR execute `export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib"`'
  echo

  if [ -f "~/.omgzsh" ]
  then
    if [ ! $( b.framework.is_string_existed 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib' ~/.omgzsh ) = "1" ]
    then
      echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib' >> ~/.omgzsh
      echo 'export LD_LIBRARY_PATH' >> ~/.omgzsh
    fi
  fi

  if [ ! $( b.framework.is_string_existed 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib' ~/.bashrc ) = "1" ]
  then
    echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib' >> ~/.bashrc
    echo 'export LD_LIBRARY_PATH' >> ~/.bashrc
  fi
}


text:
package com.mossle.user.persistence.domain;

// Generated by Hibernate Tools
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * PersonInfo 个人信息.
 *
 * @author Lingo
 */
@Entity
@Table(name = "PERSON_INFO")
public class PersonInfo implements java.io.Serializable {
    private static final long serialVersionUID = 0L;

    /** 主键. */
    private Long id;

    /** 唯一标识. */
    private String code;

    /** 账号. */
    private String username;

    /** 姓氏. */
    private String familyName;

    /** 名字. */
    private String givenName;

    /** 全名. */
    private String fullName;

    /** 手机区号. */
    private String cellphoneCode;

    /** 手机. */
    private String cellphone;

    /** 座机. */
    private String telephone;

    /** 邮箱. */
    private String email;

    /** 即时通讯. */
    private String im;

    /** 国家. */
    private String country;

    /** 省. */
    private String province;

    /** 市. */
    private String city;

    /** 办公楼. */
    private String building;

    /** 楼层. */
    private String floor;

    /** 工位. */
    private String seat;

    /** 工号. */
    private String employeeNo;

    /** 员工类型. */
    private String employeeType;

    /** 工卡. */
    private String card;

    /** 公司编码. */
    private String companyCode;

    /** 公司名称. */
    private String companyName;

    /** 部门编码. */
    private String departmentCode;

    /** 部门名称. */
    private String departmentName;

    /** null. */
    private String departmentPath;

    /** 职位编码. */
    private String positionCode;

    /** 职位名称. */
    private String positionName;

    /** null. */
    private String costCenterCode;

    /** null. */
    private String costCenterName;

    /** null. */
    private String superiourCode;

    /** null. */
    private String superiourName;

    /** 入职时间. */
    private Date entryDate;

    /** 性别. */
    private String gender;

    /** 生日. */
    private Date birthday;

    /** 证件类型. */
    private String idCardType;

    /** 证件编号. */
    private String idCardValue;

    /** 国籍. */
    private String nationality;

    /** 星座. */
    private String star;

    /** 血型. */
    private String blood;

    /** 衣服大小. */
    private String clothSize;

    /** 租户. */
    private String tenantId;

    /** 显示名. */
    private String displayName;

    /** 类型. */
    private String type;

    /** 状态. */
    private String status;

    public PersonInfo() {
    }

    public PersonInfo(Long id) {
        this.id = id;
    }

    public PersonInfo(Long id, String code, String username, String familyName,
            String givenName, String fullName, String cellphoneCode,
            String cellphone, String telephone, String email, String im,
            String country, String province, String city, String building,
            String floor, String seat, String employeeNo, String employeeType,
            String card, String companyCode, String companyName,
            String departmentCode, String departmentName,
            String departmentPath, String positionCode, String positionName,
            String costCenterCode, String costCenterName, String superiourCode,
            String superiourName, Date entryDate, String gender, Date birthday,
            String idCardType, String idCardValue, String nationality,
            String star, String blood, String clothSize, String tenantId,
            String displayName, String type, String status) {
        this.id = id;
        this.code = code;
        this.username = username;
        this.familyName = familyName;
        this.givenName = givenName;
        this.fullName = fullName;
        this.cellphoneCode = cellphoneCode;
        this.cellphone = cellphone;
        this.telephone = telephone;
        this.email = email;
        this.im = im;
        this.country = country;
        this.province = province;
        this.city = city;
        this.building = building;
        this.floor = floor;
        this.seat = seat;
        this.employeeNo = employeeNo;
        this.employeeType = employeeType;
        this.card = card;
        this.companyCode = companyCode;
        this.companyName = companyName;
        this.departmentCode = departmentCode;
        this.departmentName = departmentName;
        this.departmentPath = departmentPath;
        this.positionCode = positionCode;
        this.positionName = positionName;
        this.costCenterCode = costCenterCode;
        this.costCenterName = costCenterName;
        this.superiourCode = superiourCode;
        this.superiourName = superiourName;
        this.entryDate = entryDate;
        this.gender = gender;
        this.birthday = birthday;
        this.idCardType = idCardType;
        this.idCardValue = idCardValue;
        this.nationality = nationality;
        this.star = star;
        this.blood = blood;
        this.clothSize = clothSize;
        this.tenantId = tenantId;
        this.displayName = displayName;
        this.type = type;
        this.status = status;
    }

    /** @return 主键. */
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    /**
     * @param id
     *            主键.
     */
    public void setId(Long id) {
        this.id = id;
    }

    /** @return 唯一标识. */
    @Column(name = "CODE", length = 200)
    public String getCode() {
        return this.code;
    }

    /**
     * @param code
     *            唯一标识.
     */
    public void setCode(String code) {
        this.code = code;
    }

    /** @return 账号. */
    @Column(name = "USERNAME", length = 200)
    public String getUsername() {
        return this.username;
    }

    /**
     * @param username
     *            账号.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /** @return 姓氏. */
    @Column(name = "FAMILY_NAME", length = 200)
    public String getFamilyName() {
        return this.familyName;
    }

    /**
     * @param familyName
     *            姓氏.
     */
    public void setFamilyName(String familyName) {
        this.familyName = familyName;
    }

    /** @return 名字. */
    @Column(name = "GIVEN_NAME", length = 200)
    public String getGivenName() {
        return this.givenName;
    }

    /**
     * @param givenName
     *            名字.
     */
    public void setGivenName(String givenName) {
        this.givenName = givenName;
    }

    /** @return 全名. */
    @Column(name = "FULL_NAME", length = 200)
    public String getFullName() {
        return this.fullName;
    }

    /**
     * @param fullName
     *            全名.
     */
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    /** @return 手机区号. */
    @Column(name = "CELLPHONE_CODE", length = 10)
    public String getCellphoneCode() {
        return this.cellphoneCode;
    }

    /**
     * @param cellphoneCode
     *            手机区号.
     */
    public void setCellphoneCode(String cellphoneCode) {
        this.cellphoneCode = cellphoneCode;
    }

    /** @return 手机. */
    @Column(name = "CELLPHONE", length = 50)
    public String getCellphone() {
        return this.cellphone;
    }

    /**
     * @param cellphone
     *            手机.
     */
    public void setCellphone(String cellphone) {
        this.cellphone = cellphone;
    }

    /** @return 座机. */
    @Column(name = "TELEPHONE", length = 200)
    public String getTelephone() {
        return this.telephone;
    }

    /**
     * @param telephone
     *            座机.
     */
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    /** @return 邮箱. */
    @Column(name = "EMAIL", length = 200)
    public String getEmail() {
        return this.email;
    }

    /**
     * @param email
     *            邮箱.
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /** @return 即时通讯. */
    @Column(name = "IM", length = 200)
    public String getIm() {
        return this.im;
    }

    /**
     * @param im
     *            即时通讯.
     */
    public void setIm(String im) {
        this.im = im;
    }

    /** @return 国家. */
    @Column(name = "COUNTRY", length = 200)
    public String getCountry() {
        return this.country;
    }

    /**
     * @param country
     *            国家.
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /** @return 省. */
    @Column(name = "PROVINCE", length = 200)
    public String getProvince() {
        return this.province;
    }

    /**
     * @param province
     *            省.
     */
    public void setProvince(String province) {
        this.province = province;
    }

    /** @return 市. */
    @Column(name = "CITY", length = 200)
    public String getCity() {
        return this.city;
    }

    /**
     * @param city
     *            市.
     */
    public void setCity(String city) {
        this.city = city;
    }

    /** @return 办公楼. */
    @Column(name = "BUILDING", length = 200)
    public String getBuilding() {
        return this.building;
    }

    /**
     * @param building
     *            办公楼.
     */
    public void setBuilding(String building) {
        this.building = building;
    }

    /** @return 楼层. */
    @Column(name = "FLOOR", length = 200)
    public String getFloor() {
        return this.floor;
    }

    /**
     * @param floor
     *            楼层.
     */
    public void setFloor(String floor) {
        this.floor = floor;
    }

    /** @return 工位. */
    @Column(name = "SEAT", length = 200)
    public String getSeat() {
        return this.seat;
    }

    /**
     * @param seat
     *            工位.
     */
    public void setSeat(String seat) {
        this.seat = seat;
    }

    /** @return 工号. */
    @Column(name = "EMPLOYEE_NO", length = 50)
    public String getEmployeeNo() {
        return this.employeeNo;
    }

    /**
     * @param employeeNo
     *            工号.
     */
    public void setEmployeeNo(String employeeNo) {
        this.employeeNo = employeeNo;
    }

    /** @return 员工类型. */
    @Column(name = "EMPLOYEE_TYPE", length = 50)
    public String getEmployeeType() {
        return this.employeeType;
    }

    /**
     * @param employeeType
     *            员工类型.
     */
    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

    /** @return 工卡. */
    @Column(name = "CARD", length = 200)
    public String getCard() {
        return this.card;
    }

    /**
     * @param card
     *            工卡.
     */
    public void setCard(String card) {
        this.card = card;
    }

    /** @return 公司编码. */
    @Column(name = "COMPANY_CODE", length = 200)
    public String getCompanyCode() {
        return this.companyCode;
    }

    /**
     * @param companyCode
     *            公司编码.
     */
    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }

    /** @return 公司名称. */
    @Column(name = "COMPANY_NAME", length = 200)
    public String getCompanyName() {
        return this.companyName;
    }

    /**
     * @param companyName
     *            公司名称.
     */
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    /** @return 部门编码. */
    @Column(name = "DEPARTMENT_CODE", length = 200)
    public String getDepartmentCode() {
        return this.departmentCode;
    }

    /**
     * @param departmentCode
     *            部门编码.
     */
    public void setDepartmentCode(String departmentCode) {
        this.departmentCode = departmentCode;
    }

    /** @return 部门名称. */
    @Column(name = "DEPARTMENT_NAME", length = 200)
    public String getDepartmentName() {
        return this.departmentName;
    }

    /**
     * @param departmentName
     *            部门名称.
     */
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    /** @return null. */
    @Column(name = "DEPARTMENT_PATH", length = 200)
    public String getDepartmentPath() {
        return this.departmentPath;
    }

    /**
     * @param departmentPath
     *            null.
     */
    public void setDepartmentPath(String departmentPath) {
        this.departmentPath = departmentPath;
    }

    /** @return 职位编码. */
    @Column(name = "POSITION_CODE", length = 200)
    public String getPositionCode() {
        return this.positionCode;
    }

    /**
     * @param positionCode
     *            职位编码.
     */
    public void setPositionCode(String positionCode) {
        this.positionCode = positionCode;
    }

    /** @return 职位名称. */
    @Column(name = "POSITION_NAME", length = 200)
    public String getPositionName() {
        return this.positionName;
    }

    /**
     * @param positionName
     *            职位名称.
     */
    public void setPositionName(String positionName) {
        this.positionName = positionName;
    }

    /** @return null. */
    @Column(name = "COST_CENTER_CODE", length = 200)
    public String getCostCenterCode() {
        return this.costCenterCode;
    }

    /**
     * @param costCenterCode
     *            null.
     */
    public void setCostCenterCode(String costCenterCode) {
        this.costCenterCode = costCenterCode;
    }

    /** @return null. */
    @Column(name = "COST_CENTER_NAME", length = 200)
    public String getCostCenterName() {
        return this.costCenterName;
    }

    /**
     * @param costCenterName
     *            null.
     */
    public void setCostCenterName(String costCenterName) {
        this.costCenterName = costCenterName;
    }

    /** @return null. */
    @Column(name = "SUPERIOUR_CODE", length = 200)
    public String getSuperiourCode() {
        return this.superiourCode;
    }

    /**
     * @param superiourCode
     *            null.
     */
    public void setSuperiourCode(String superiourCode) {
        this.superiourCode = superiourCode;
    }

    /** @return null. */
    @Column(name = "SUPERIOUR_NAME", length = 200)
    public String getSuperiourName() {
        return this.superiourName;
    }

    /**
     * @param superiourName
     *            null.
     */
    public void setSuperiourName(String superiourName) {
        this.superiourName = superiourName;
    }

    /** @return 入职时间. */
    @Temporal(TemporalType.DATE)
    @Column(name = "ENTRY_DATE", length = 10)
    public Date getEntryDate() {
        return this.entryDate;
    }

    /**
     * @param entryDate
     *            入职时间.
     */
    public void setEntryDate(Date entryDate) {
        this.entryDate = entryDate;
    }

    /** @return 性别. */
    @Column(name = "GENDER", length = 500)
    public String getGender() {
        return this.gender;
    }

    /**
     * @param gender
     *            性别.
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /** @return 生日. */
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "BIRTHDAY", length = 26)
    public Date getBirthday() {
        return this.birthday;
    }

    /**
     * @param birthday
     *            生日.
     */
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    /** @return 证件类型. */
    @Column(name = "ID_CARD_TYPE", length = 50)
    public String getIdCardType() {
        return this.idCardType;
    }

    /**
     * @param idCardType
     *            证件类型.
     */
    public void setIdCardType(String idCardType) {
        this.idCardType = idCardType;
    }

    /** @return 证件编号. */
    @Column(name = "ID_CARD_VALUE", length = 50)
    public String getIdCardValue() {
        return this.idCardValue;
    }

    /**
     * @param idCardValue
     *            证件编号.
     */
    public void setIdCardValue(String idCardValue) {
        this.idCardValue = idCardValue;
    }

    /** @return 国籍. */
    @Column(name = "NATIONALITY", length = 200)
    public String getNationality() {
        return this.nationality;
    }

    /**
     * @param nationality
     *            国籍.
     */
    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    /** @return 星座. */
    @Column(name = "STAR", length = 50)
    public String getStar() {
        return this.star;
    }

    /**
     * @param star
     *            星座.
     */
    public void setStar(String star) {
        this.star = star;
    }

    /** @return 血型. */
    @Column(name = "BLOOD", length = 50)
    public String getBlood() {
        return this.blood;
    }

    /**
     * @param blood
     *            血型.
     */
    public void setBlood(String blood) {
        this.blood = blood;
    }

    /** @return 衣服大小. */
    @Column(name = "CLOTH_SIZE", length = 50)
    public String getClothSize() {
        return this.clothSize;
    }

    /**
     * @param clothSize
     *            衣服大小.
     */
    public void setClothSize(String clothSize) {
        this.clothSize = clothSize;
    }

    /** @return 租户. */
    @Column(name = "TENANT_ID", length = 64)
    public String getTenantId() {
        return this.tenantId;
    }

    /**
     * @param tenantId
     *            租户.
     */
    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }

    /** @return 显示名. */
    @Column(name = "DISPLAY_NAME", length = 50)
    public String getDisplayName() {
        return this.displayName;
    }

    /**
     * @param displayName
     *            显示名.
     */
    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    /** @return 类型. */
    @Column(name = "TYPE", length = 50)
    public String getType() {
        return this.type;
    }

    /**
     * @param type
     *            类型.
     */
    public void setType(String type) {
        this.type = type;
    }

    /** @return 状态. */
    @Column(name = "STATUS", length = 50)
    public String getStatus() {
        return this.status;
    }

    /**
     * @param status
     *            状态.
     */
    public void setStatus(String status) {
        this.status = status;
    }
}


text:
{% extends 'common/templates/form_mobile_confirm.html' %}
{% block buttons %}
<input type="hidden" name="redirect_to" value="{{redirect_to}}" />
<button type="submit">
    <big class="active">› Activate</big>
</button>

or skip this now

{% endblock %}


text:
package sys.net.impl;

import sys.net.api.rpc.AbstractRpcHandler;
import sys.net.api.rpc.RpcHandle;

/**
 *
 * @author smd
 *
 */
abstract public class Handler extends AbstractRpcHandler {

    public void onReceive(final Reply r) {
        Thread.dumpStack();
    }

    public void onReceive(final RpcHandle handle, final Reply r) {
        Thread.dumpStack();
    }

    public void onReceive(final RpcHandle handle, final Request r) {
        Thread.dumpStack();
    }
}


text:
module Epub
  class Toc

    def initialize(tocfile, reader)
      @tocfile = tocfile
      @reader  = reader
      @file    = @reader.file
      @content = get_toc_content
      @xml     = Nokogiri::XML(@content).remove_namespaces!
    end

    def content
      if ncx?
        if has_toc?
          ncx_to_html
        else
          spine_to_html
        end
      else
        @content
      end
    end

    def pages
      points = @xml.css("ncx navMap navPoint")
      items  = @reader.package.reading_order
      if ncx? && has_toc? && points.size > 1
        points.map do |point|
          title = point.css('navLabel > text').first.text
          file_path  = @reader.package.relative_content_path + point.css('content').attr('src').to_s
          Page.new(title, file_path, @reader.file)
        end
      else
        items.map do |item|
          title = ""
          file_path  = @reader.package.relative_content_path + item.attr('href').to_s
          Page.new(title, file_path, @reader.file)
        end
      end
    end

    private

    def ncx?
      @tocfile.match(/(\.ncx)$/)
    end

    def has_toc?
      @xml.css('navMap > navPoint').size > 0
    end

    def get_toc_content
      begin
        @reader.file.get_input_stream(@tocfile).read
      rescue
        ""
      end
    end

    # TODO: Add Stylesheets
    # TODO: Convert nested navigation
    # TODO: Refactoring to DRY with spine_to_html
    def ncx_to_html
      html     = <<EOF
<?xml version="1.0" encoding="UTF-8"?>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>#{title}</title>

EOF
          selector = "ncx > navMap > navPoint"
          @xml.css(selector).each do |point|
            html += "
#{point.css('navLabel text').text}
"
          end
          html += <<EOF

EOF
      html
    end

    def spine_to_html
      html     = <<EOF
<?xml version="1.0" encoding="UTF-8"?>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>#{title}</title>

EOF
      @reader.package.reading_order.each do |item|
        link = item.attr('href').to_s
        html += "
#{link[0,link.rindex('.')]}
"
      end
      html += <<EOF

EOF
      html
    end

    def title
      root.css('docTitle > text').text
    end

    def root
      @xml.css('ncx')
    end

    def navmap
      root.css('navMap')
    end

  end
end


text:
require 'spec_helper'

describe Repository::Support::ResultBuilder do
  describe 'initialisation' do
    it 'requires one parameter' do
      message = /wrong number of arguments \(.+?\)/
      expect { described_class.new }.to raise_error ArgumentError, message
    end

    it 'can be initialised with anything' do
      init_values = ['something', nil, 42.7, self]
      init_values.each do |value|
        expect { described_class.new value }.not_to raise_error
      end
    end
  end # describe 'initialisation'

  describe 'has a #build method that' do
    let(:obj) { described_class.new record }

    context 'when the initialiser parameter is truthy' do
      let(:record) { true }
      let(:result) { obj.build }

      describe 'returns a StoreResult instance which' do
        it 'is successful' do
          expect(result).to be_success
        end

        it 'returns the initialiser parameter as its :entity attribute' do
          expect(result.entity).to eq record
        end

        it 'returns an empty Array as its :errors attribute' do
          errors = result.errors
          expect(errors).to respond_to :to_ary
          expect(errors).to be_empty
        end
      end # describe 'returns a StoreResult instance which'
    end # context 'when the initialiser parameter is truthy'

    context 'when the initialiser parameter is falsy' do
      let(:record) { false }

      it 'requires a block' do
        # message = 'no block given (yield)'
        expect { obj.build }.to raise_error LocalJumpError # , message
      end

      describe 'returns a StoreResult instance which' do
        let(:errors_value) { 'RETURNED FROM BLOCK' }
        let(:result) { obj.build { |_r| errors_value } }

        it 'is not successful' do
          expect(result).not_to be_success
        end

        it 'returns an :entity attribute value of nil' do
          expect(result.entity).to be nil
        end

        it 'returns the return value of the block as the :errors attribute' do
          expect(result.errors).to be errors_value
        end
      end # describe 'returns a StoreResult instance which'
    end # context 'when the initialiser parameter is falsy'
  end # describe 'has a #build method that'
end # describe Repository::Support::ResultBuilder


text:
import React from 'react';
import {Link} from 'react-router';
import Header from '../components/Header';

class App extends React.Component {
  render(){
    let styles = {
      base: {
        topSpace: {
          marginTop: '60px'
        },
        smallTopSpace: {
          marginTop: '20px'
        }
      }
    };

    return (

Hello World ! Buds

          <Link className="btn btn btn-default" to={`/subroute`}>Go to subroute</Link>

            {this.props.children}

    );
  }
}

export default App;


text:
package io.subutai.core.metric.impl;

public final class Constants
{

    private Constants()
    {
    }

    //max length of subscriber id to store in database varchar(100) field
    public static final int MAX_SUBSCRIBER_ID_LEN = 100;

    //metric request timeout in seconds
    public static final int METRIC_REQUEST_TIMEOUT = 60;

    //notifyOnAlert timeout in seconds
    public static final int ALERT_TIMEOUT = 30;

    //monitoring activation timeout
    public static final int MONITORING_ACTIVATION_TIMEOUT = 60;
}


text:
extern int elf32_tic6x_merge_arch_attributes (int, int);

/* This function is provided for use from the assembler.  */

extern void elf32_tic6x_set_use_rela_p (bfd *, bfd_boolean);


text:
def extractBeanylandCom(item):
	'''
	Parser for 'beanyland.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('fight for love and peace',                'Fight for Peace and Love',                               'translated'),
		('i'm bearing my love rival's child',       'i'm bearing my love rival's child',                      'translated'),
		('turn on the love system',                 'turn on the love system',                                'translated'),
		('crossing to the primitive',               'crossing to the primitive',                              'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
exports.driver = {
  belt: function() {
    return Titanium.UI.createImageView({
      image: "../images/belt.png",
      width: 480
    });
  },
  driver: function() {
    return Titanium.UI.createImageView({
      image: "../images/" + win.combo + ".png",
      width: 480,
      changed: false,
      completed: false
    });
  },
  cover: function() {
    return Ti.UI.createImageView({
      image: "../images/cover.png",
      width: 480
    });
  },
  anime: function() {
    return Titanium.UI.createAnimation({
      transform: Ti.UI.create2DMatrix({
        rotate: 28
      }),
      duration: 200
    });
  },
  o_scanner: function() {
    return Ti.UI.createImageView({
      top: -80,
      left: -70,
      height: 200,
      width: 200,
      image: "../images/o_scanner.png",
      visible: false,
      vanish: function() {
        return this.animate(Ti.UI.createAnimation({
          top: 350,
          left: 600,
          duration: 2000
        }));
      }
    });
  }
};


text:
@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

C:\julia\bin\julia -e "Pkg.add(\"JuMP\");Pkg.add(\"AmplNLWriter\");Pkg.add(\"Lazy\");Pkg.add(\"Iterators\");Pkg.add(\"JSON\");Pkg.add(\"Cbc\");using JuMP;using AmplNLWriter;using Lazy;using Iterators;using JSON;using Cbc"
PAUSE


text:
<?php

/**
 * Class for pie charts. Can only use one dataset which will be dispalyed as a
 * pie chart.
 *
 *
 *  // Create a new pie chart
 *  $chart = new ezcGraphPieChart();
 *
 *  // Add data to line chart
 *  $chart->data['sample dataset'] = new ezcGraphArrayDataSet(
 *      array(
 *          'one' => 1.2,
 *          'two' => 43.2,
 *          'three' => -34.14,
 *          'four' => 65,
 *          'five' => 123,
 *      )
 *  );
 *
 *  // Render chart with default 2d renderer and default SVG driver
 *  $chart->render( 500, 200, 'pie_chart.svg' );
 *
 *
 * Each chart consists of several chart elements which represents logical
 * parts of the chart and can be formatted independently. The pie chart
 * consists of:
 *  - title ( {@link ezcGraphChartElementText} )
 *  - legend ( {@link ezcGraphChartElementLegend} )
 *  - background ( {@link ezcGraphChartElementBackground} )
 *
 * All elements can be configured by accessing them as properties of the chart:
 *
 *
 *  $chart->legend->position = ezcGraph::RIGHT;
 *
 *
 * The chart itself also offers several options to configure the appearance.
 * The extended configure options are available in
 * {@link ezcGraphPieChartOptions} extending the {@link ezcGraphChartOptions}.
 *
 * @property ezcGraphPieChartOptions $options
 *           Chart options class
 *
 * @version 1.4.3
 * @package Graph
 * @mainclass
 */
class ezcGraphPieChart extends ezcGraphChart
{

    /**
     * Constructor
     *
     * @param array $options Default option array
     * @return void
     * @ignore
     */
    public function __construct( array $options = array() )
    {
        $this->options = new ezcGraphPieChartOptions( $options );

        parent::__construct( $options );

        $this->data = new ezcGraphChartSingleDataContainer( $this );
    }

    /**
     * Render the assigned data
     *
     * Will renderer all charts data in the remaining boundings after drawing
     * all other chart elements. The data will be rendered depending on the
     * settings in the dataset.
     *
     * @param ezcGraphRenderer $renderer Renderer
     * @param ezcGraphBoundings $boundings Remaining boundings
     * @return void
     */
    protected function renderData( ezcGraphRenderer $renderer, ezcGraphBoundings $boundings )
    {
        // Only draw the first (and only) dataset
        $dataset = $this->data->rewind();
        $datasetName = $this->data->key();

        $this->driver->options->font = $this->options->font;

        // Calculate sum of all values to be able to calculate percentage
        $sum = 0;
        foreach ( $dataset as $name => $value )
        {
            if ( $value < 0 )
            {
                throw new ezcGraphInvalidDataException( "Values >= 0 required, '$name' => '$value'." );
            }

            $sum += $value;
        }
        if ( $this->options->sum !== false )
        {
            $sum = max( $sum, $this->options->sum );
        }

        if ( $sum <= 0 )
        {
            throw new ezcGraphInvalidDataException( "Pie charts require a value sum > 0, your value: '$sum'." );
        }

        $angle = 0;
        foreach ( $dataset as $label => $value )
        {
            // Skip rendering values which equals 0
            if ( $value <= 0 )
            {
                continue;
            }

            switch ( $dataset->displayType->default )
            {
                case ezcGraph::PIE:
                    $displayLabel = ( $this->options->labelCallback !== null
                        ? call_user_func( $this->options->labelCallback, $label, $value, $value / $sum )
                        : sprintf( $this->options->label, $label, $value, $value / $sum * 100 ) );

                    $renderer->drawPieSegment(
                        $boundings,
                        new ezcGraphContext( $datasetName, $label, $dataset->url[$label] ),
                        $dataset->color[$label],
                        $angle,
                        $angle += $value / $sum * 360,
                        $displayLabel,
                        $dataset->highlight[$label]
                    );
                    break;
                default:
                    throw new ezcGraphInvalidDisplayTypeException( $dataset->displayType->default );
                    break;
            }
        }
    }

    /**
     * Returns the default display type of the current chart type.
     *
     * @return int Display type
     */
    public function getDefaultDisplayType()
    {
        return ezcGraph::PIE;
    }

    /**
     * Apply tresh hold
     *
     * Iterates over the dataset and applies the configured tresh hold to
     * the datasets data.
     *
     * @return void
     */
    protected function applyThreshold()
    {
        if ( $this->options->percentThreshold || $this->options->absoluteThreshold )
        {
            $dataset = $this->data->rewind();

            $sum = 0;
            foreach ( $dataset as $value )
            {
                $sum += $value;
            }
            if ( $this->options->sum !== false )
            {
                $sum = max( $sum, $this->options->sum );
            }

            $unset = array();
            foreach ( $dataset as $label => $value )
            {
                if ( $label === $this->options->summarizeCaption )
                {
                    continue;
                }

                if ( ( $value <= $this->options->absoluteThreshold ) ||
                     ( ( $value / $sum ) <= $this->options->percentThreshold ) )
                {
                    if ( !isset( $dataset[$this->options->summarizeCaption] ) )
                    {
                        $dataset[$this->options->summarizeCaption] = $value;
                    }
                    else
                    {
                        $dataset[$this->options->summarizeCaption] += $value;
                    }

                    $unset[] = $label;
                }
            }

            foreach ( $unset as $label )
            {
                unset( $dataset[$label] );
            }
        }
    }

    /**
     * Renders the basic elements of this chart type
     *
     * @param int $width
     * @param int $height
     * @return void
     */
    protected function renderElements( $width, $height )
    {
        if ( !count( $this->data ) )
        {
            throw new ezcGraphNoDataException();
        }

        // Set image properties in driver
        $this->driver->options->width = $width;
        $this->driver->options->height = $height;

        // Apply tresh hold
        $this->applyThreshold();

        // Generate legend
        $this->elements['legend']->generateFromDataSet( $this->data->rewind() );

        // Get boundings from parameters
        $this->options->width = $width;
        $this->options->height = $height;

        $boundings = new ezcGraphBoundings();
        $boundings->x1 = $this->options->width;
        $boundings->y1 = $this->options->height;

        // Render subelements
        foreach ( $this->elements as $name => $element )
        {
            // Skip element, if it should not get rendered
            if ( $this->renderElement[$name] === false )
            {
                continue;
            }

            $this->driver->options->font = $element->font;
            $boundings = $element->render( $this->renderer, $boundings );
        }

        // Render graph
        $this->renderData( $this->renderer, $boundings );
    }

    /**
     * Render the pie chart
     *
     * Renders the chart into a file or stream. The width and height are
     * needed to specify the dimensions of the resulting image. For direct
     * output use 'php://stdout' as output file.
     *
     * @param int $width Image width
     * @param int $height Image height
     * @param string $file Output file
     * @apichange
     * @return void
     */
    public function render( $width, $height, $file = null )
    {
        $this->renderElements( $width, $height );

        if ( !empty( $file ) )
        {
            $this->renderer->render( $file );
        }

        $this->renderedFile = $file;
    }

    /**
     * Renders this chart to direct output
     *
     * Does the same as ezcGraphChart::render(), but renders directly to
     * output and not into a file.
     *
     * @param int $width
     * @param int $height
     * @apichange
     * @return void
     */
    public function renderToOutput( $width, $height )
    {
        // @TODO: merge this function with render an deprecate ommit of third
        // argument in render() when API break is possible
        $this->renderElements( $width, $height );
        $this->renderer->render( null );
    }
}

?>


text:
Мероприятия

Никольские вечера

Анонс встреч, архив видеозаписей, Ваши вопросы и заявки по тема

      подробнее

Выставка икон

Информация о благотворительной выставке «Украина - дом Пресвятой Богородицы»

      подробнее

Окно помощи

Оставьте заявку о помощи, узнайте статус или ответ по заявке

      подробнее

Помощь получена!

Информация о предоставленной помощи

      подробнее

Фото блок

  <uib-carousel interval="12000" class="photo-with-caption-container" active="active">
    <uib-slide ng-repeat="albumGroup in albumGroups" index="$index"  >

                {{album.title}}

    </uib-slide>
  </uib-carousel>

Видео блок

  <uib-carousel interval="12000" class="photo-with-caption-container" active="active">
    <uib-slide ng-repeat="videoGroup in videoGroups" index="$index"  >

              {{video.title}}

    </uib-slide>
  </uib-carousel>

 0">

Новости проекта

{{novelty.title}}

{{novelty.summary}}

          {{novelty.date | date : "dd.MM.yyyy"}}
          подробнее

  Показать все новости