text:
package com.innovaee.eorder.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import com.innovaee.eorder.entity.Dish;
import com.innovaee.eorder.exception.CategoryNotFoundException;
import com.innovaee.eorder.exception.DishNotFoundException;
import com.innovaee.eorder.exception.DuplicateNameException;
import com.innovaee.eorder.exception.InvalidPageSizeException;
import com.innovaee.eorder.exception.PageIndexOutOfBoundExcpeiton;
import com.innovaee.eorder.vo.DishVO;

import org.junit.Test;

import javax.annotation.Resource;

/**
 * @Title: DishServiceTest
 * @Description: DishService 单元测试类
 *
 * @version V1.0
 */
public class DishServiceTest extends BaseSpringTestCase {

    @Resource
    private DishService dishService;

    /**
     * 单元测试 - 通过错误的菜品ID获取菜品
     */
    @Test
    public void getDishByInvalidIdTest() {
        try {
            dishService.getDishById(1000L);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 通过正确的菜品ID获取菜品
     */
    @Test
    public void getDishByIdTest() throws DishNotFoundException {
        Dish dish = dishService.getDishById(1L);

        assertEquals(dish.getName(), "手撕包菜");
    }

    /**
     * 单元测试 - 通过错误的菜品名获取菜品
     */
    @Test
    public void getDishByInvalidNameTest() {
        try {
            dishService.getDishByName("手撕包菜1");
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 通过正确的菜品名获取菜品
     */
    @Test
    public void getDishByNameTest() throws DishNotFoundException {
        Dish dish = dishService.getDishByName("手撕包菜");

        assertNotNull(dish);
    }

    /**
     * 单元测试 - 添加重名菜品
     */
    @Test
    public void addDishWithDuplicateNameTest() {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜");
        dishVO.setPrice(150.0f);
        dishVO.setPicPath("");

        try {
            dishService.addDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DuplicateNameException.class);
        }
    }

    /**
     * 添加错误分类的菜品信息
     */
    @Test
    public void addDishWithInvalidCategoryTest() {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜1");
        dishVO.setPrice(150.0f);
        dishVO.setPicPath("");

        try {
            dishService.addDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), CategoryNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 添加菜品信息
     *
     * @throws CategoryNotFoundException
     * @throws DuplicateNameException
     */
    @Test
    public void addDishTest() throws DuplicateNameException,
            CategoryNotFoundException {
        DishVO dishVO = new DishVO();

        dishVO.setCategoryId(1L);
        dishVO.setMisc("misc");
        dishVO.setName("手撕包菜1");
        dishVO.setPrice(150.0f);
        dishVO.setPicPath("");

        Dish dish = dishService.addDish(dishVO);

        assertNotNull(dish);
        assertTrue(dish.getId() > 0L);
    }

    /**
     * 单元测试 - 使用已存在的菜品名更新菜品
     *
     * @throws DishNotFoundException
     */
    @Test
    public void updateDishWithDuplicateNameTest() throws DishNotFoundException {
        String duplicateName = "无油版左公鸡";
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(dish.getCategory().getId());
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(duplicateName);
        dishVO.setPicPath(dish.getPicPath());
        dishVO.setPrice(dish.getPrice());

        try {
            dishService.updateDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DuplicateNameException.class);
        }
    }

    /**
     * 单元测试 - 使用错误的菜品分类信息更新菜品
     *
     * @throws DishNotFoundException
     */
    @Test
    public void updateDishWithInvalidCategoryTest()
            throws DishNotFoundException {
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(1000L);
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(dish.getName());
        dishVO.setPicPath(dish.getPicPath());
        dishVO.setPrice(dish.getPrice());

        try {
            dishService.updateDish(dishVO);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), CategoryNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 更新菜品信息
     *
     * @throws DishNotFoundException
     * @throws CategoryNotFoundException
     * @throws DuplicateNameException
     */
    @Test
    public void updateDishTest() throws DishNotFoundException,
            CategoryNotFoundException, DuplicateNameException {
        Dish dish = dishService.getDishById(1L);
        DishVO dishVO = new DishVO();

        dishVO.setId(dish.getId());
        dishVO.setCategoryId(dish.getCategory().getId());
        dishVO.setMisc(dish.getMisc());
        dishVO.setName(dish.getName());
        dishVO.setPicPath(dish.getPicPath());
        dishVO.setPrice(dish.getPrice());

        dishService.updateDish(dishVO);
    }

    /**
     * 单元测试 - 删除非法ID指定的菜品信息
     */
    @Test
    public void deleteDishWithInvalidIdTest() {
        try {
            dishService.deleteDish(1000L);
        } catch (Exception exception) {
            assertEquals(exception.getClass(), DishNotFoundException.class);
        }
    }

    /**
     * 单元测试 - 删除菜品信息
     */
    @Test
    public void deleteDishTest() throws DishNotFoundException {
        dishService.deleteDish(1L);
    }

    /**
     * 单元测试 - 菜品分页总数
     *
     * @throws InvalidPageSizeException
     * @throws CategoryNotFoundException
     */
    @Test
    public void getDishPageCountTest() throws InvalidPageSizeException,
            CategoryNotFoundException {
        Long categoryId = 1L;

        int pageCount = dishService.getDishPageCount(5, categoryId);

        assertEquals(2, pageCount);
    }

    /**
     * 单元测试 - 菜品分页
     *
     * @throws InvalidPageSizeException
     * @throws CategoryNotFoundException
     * @throws PageIndexOutOfBoundExcpeiton
     */
    @Test
    public void getDishByCategoryTest() throws PageIndexOutOfBoundExcpeiton,
            CategoryNotFoundException, InvalidPageSizeException {
        dishService.getDishesByPage(1, 5, 1L);
    }
}


text:
Password type.

See the [example](http://subschema.github.io/subschema/#/Login)

redpajama_set_name: RedPajamaGithub


text:
package com.canoo.webtest.engine;

import junit.framework.TestCase;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.taskdefs.Sleep;

import com.canoo.webtest.ant.WebtestTask;
import com.canoo.webtest.interfaces.IWebtestCustomizer;
import com.canoo.webtest.reporting.StepExecutionListener;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper;

/**
 * @author Ardeshir Arfaian
 */
public class DefaultWebtestCustomizerTest extends TestCase {

	private Project project;
	private WebtestTask webTest;
	private Configuration config;
	private Context context;

	public void setUp() {
		project = new Project();
		webTest = new WebtestTask();
		webTest.setProject(project);
		webTest.setName("TestWebTest");
		config	= new Configuration(webTest);

        context = new Context(webTest);
        config.setProject(project);
        config.setContext(context);
	}

	public void testNoReference() {
		final Context context = new Context(webTest);

		config = new Configuration();
        config.setProject(project);
        config.setContext(context);
        config.execute();

        assertEquals(DefaultWebtestCustomizer.class, webTest.getWebtestCustomizer().getClass());
        assertEquals(WebClient.class, context.getWebClient().getClass());
        assertEquals(CSVTracingWebConnection.class, context.getWebClient().getWebConnection().getClass());
	}

	public void testCustomWebtestCustomizer() {
        project.addReference("wt.webtestCustomizer", new IWebtestCustomizer() {
			public StepExecutionListener createExecutionListener(WebtestTask wt) {
				return new StepExecutionListener(wt.getConfig().getContext());
			}
			public WebClient customizeWebClient(WebClient wc) {
				new WebConnectionWrapper(wc);
				return wc;
			}
		});

        webTest.setProject(project);
        config.execute();

        assertNotSame(DefaultWebtestCustomizer.class, webTest.getWebtestCustomizer().getClass());
        assertEquals(WebClient.class, context.getWebClient().getClass());
        assertEquals(CSVTracingWebConnection.class, context.getWebClient().getWebConnection().getClass());
	}

	public void testWrongTypeReference() {
        boolean isCatched = false;
        project.addReference("wt.webtestCustomizer", new Object());

        try {
          webTest.setProject(project);
        } catch (BuildException be) {
          isCatched = true;
        }
        assertTrue("Wrong reference didn't cause an exception", isCatched);

        config.execute();

        assertEquals(DefaultWebtestCustomizer.class, webTest.getWebtestCustomizer().getClass());
        assertEquals(WebClient.class, context.getWebClient().getClass());
	}

	public void testAllMethodsInvoked() {
		class DummyCustomizerImpl implements IWebtestCustomizer {

        	private boolean isCreateExecutionListenerInvoked = false;
    		private boolean isCustomizeWebClientInvoked = false;

        	public StepExecutionListener createExecutionListener(WebtestTask wt) {
				isCreateExecutionListenerInvoked = true;
        		return new StepExecutionListener(wt.getConfig().getContext());
			}

			public WebClient customizeWebClient(WebClient wc) {
				isCustomizeWebClientInvoked = true;
				return wc;
			}
		};

		DummyCustomizerImpl dummyCustomizer = new DummyCustomizerImpl();
		project.addReference("wt.webtestCustomizer", dummyCustomizer);
        webTest.setProject(project);

        final Sleep dummyTask = new Sleep();
        dummyTask.setMilliseconds(0);
        dummyTask.setProject(project);
        webTest.addTask(dummyTask);

        Target target = new Target();
        target.setProject(project);

        webTest.setOwningTarget(target);
        webTest.execute();

        assertTrue(dummyCustomizer.isCreateExecutionListenerInvoked);
        assertTrue(dummyCustomizer.isCustomizeWebClientInvoked);
	}

	public void testNullReference() {
        project.addReference("wt.webtestCustomizer", null);
		webTest.setProject(project);

        config.execute();

        assertEquals(DefaultWebtestCustomizer.class, webTest.getWebtestCustomizer().getClass());
        assertEquals(WebClient.class, context.getWebClient().getClass());
	}
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class HearingScript : System.Object {

	/*
	 * Use:
	 *
	 * 	//In script that wants to react to sounds
	 *	HearingScript.registerListener(new Listener( gameObject, FunctionName ));
	 *
	 *	//In script that wants to create sounds
	 *	HearingScript.createNoise( positionOfSound, 1f );
	 *
	 *
	 * Possible additions/changse:
	 * 	-Have walls dampen sound range (simplistic model, just linecast between
	 * 	 listeners in range and shrink radius if something is hit)?
	 *
	 *  -I should set up a Globals ScriptableObject and it should contain the
	 * 	 radius for "quiet" and "loud" sounds (unless that gets changed)
	 *
	 *	-Sound types or seperate listener pools?
	 */

	public struct Listener
	{
		public delegate void HearingDelegate();

		public GameObject gameObject;
		public HearingDelegate didHearSound;
		public float soundRangeModifier;

		public Listener(GameObject self, HearingDelegate didHearSound)
		{
			this.gameObject = self;
			this.didHearSound = didHearSound;
			this.soundRangeModifier = 1;
		}

		public Listener(GameObject self, HearingDelegate didHearSound, float soundRangeModifier)
		{
			this.gameObject = self;
			this.didHearSound = didHearSound;
			this.soundRangeModifier = soundRangeModifier;
		}
	}

	private static List<Listener> registeredListeners = new List<Listener>();
	public static bool debug;

	public static void registerListener(Listener listener)
	{
		registeredListeners.Add(listener);
	}

	public static void unregisterListener(Listener listener)
	{
		registeredListeners.Remove(listener);
	}

	public static void createNoise(Vector3 location, float radius)
	{
		if(debug)
		{
			DebugScript.DrawCircle(100, radius, location, Color.cyan, 0.5f);
		}

		float sqrRadius = radius * radius;

		foreach(Listener listener in registeredListeners)
		{
			Vector3 soundOffset = location - listener.gameObject.transform.position;

			//Do easy, arithmatic only check to see if listener could possibly be close enough to hear
			if( Mathf.Abs(soundOffset.x) > radius || Mathf.Abs(soundOffset.y) > radius )
				continue;

			float sqrDistance = soundOffset.sqrMagnitude;

			if(sqrDistance <= sqrRadius * listener.soundRangeModifier)
			{
				listener.didHearSound();
			}
		}
	}

}


text:
import { push } from 'connected-react-router';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm } from 'redux-form';

import {
  fetchOAuth2Application,
  updateOAuth2Application,
} from 'app/actions/OAuth2Actions';
import { selectOAuth2ApplicationById } from 'app/reducers/oauth2';
import { createValidator, required } from 'app/utils/validation';
import withPreparedDispatch from 'app/utils/withPreparedDispatch';
import UserSettingsOAuth2Form from './components/UserSettingsOAuth2Form';

const validate = createValidator({
  name: [required()],
  description: [required()],
  redirectUris: [required()],
});

const mapStateToProps = (state, props) => {
  const { applicationId } = props.match.params;
  const application = selectOAuth2ApplicationById(state, {
    applicationId,
  });
  return {
    initialValues: application,
    application,
  };
};

const mapDispatchToProps = {
  updateOAuth2Application,
  push,
};
export default compose(
  withPreparedDispatch('fetchUserSettingsOAuth2Edit', (props, dispatch) =>
    dispatch(fetchOAuth2Application(props.match.params.applicationId))
  ),
  connect(mapStateToProps, mapDispatchToProps),
  reduxForm({
    form: 'oauth2',
    validate,
    enableReinitialize: true,
  })
)(UserSettingsOAuth2Form);


text:
package cn.it.weatherforecast.activity;

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

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import cn.it.weatherforecast.R;
import cn.it.weatherforecast.db.WeatherForecastDB;
import cn.it.weatherforecast.fragment.EmptyWeatherInfoFragment;
import cn.it.weatherforecast.fragment.WeatherInfoFragment;
import cn.it.weatherforecast.fragment.adapter.AdapterForWeatherInfoPager;
import cn.it.weatherforecast.model.SelectedAreas;
import cn.it.weatherforecast.service.AutoUpdateWeatherService;
import cn.it.weatherforecast.service.DownAreasService;
import cn.it.weatherforecast.util.HttpCallbackListenerForJson;
import cn.it.weatherforecast.util.HttpUtilForDowloadJson;
import cn.it.weatherforecast.util.MyApplication;
import cn.it.weatherforecast.util.Utility;
/*
 * ¸ÃÀàʵÏֵŦÄÜ£º
 * 1£¬ÏÔʾSQLiteÖд洢µÄÑ¡ÖеijÇÊÐÁбíµÄÌìÆøÏêϸÐÅÏ¢
 * 2£¬ÊÖ¶¯Ë¢ÐÂ
 * 3£¬ViewPagerÌí¼ÓpagerchangedListener£¬»î¶¯Ë¢ÐÂ
 * 4£¬ÉèÖøüÐÂʱ¼ä£¬Ã¿¸öÊ®Îå·ÖÖÓ£¬²Å»áÔÙ´ÎË¢ÐÂ
 */
public class WeatherInfo extends FragmentActivity {

	private Button mSelectAreasButton;

	// µ±Ç°ViewPagerÏÔʾµÄ³ÇÊÐÐÅÏ¢µÄCode
	private int mCurrentIndex = 0;
	private SharedPreferences mIndexRember;
	private String LAST_INDEX = "Last_Index";
	// ViewPager×é¼þ¼°ÊÊÅäÆ÷
	private ViewPager mWeatherInfoPager;
	private AdapterForWeatherInfoPager mWeatherInfoPagerdapter;
	// »ñÈ¡Êý¾Ý¿â£¬²¢È¡³öÆäÖеÄÊý¾Ý
	private WeatherForecastDB mDB;
	// Ñ¡ÔñµÄ³ÇÊеÄfragment
	private List<Fragment> mSelectCityFragment;

	// Á½¸ö±êÖ¾±äÁ¿£¬ÓÃÓÚÅжϸû´ÓʲôµØ·½Ìøת
	protected static String FROM_DIALOG = "FromDialog";
	protected static final String FROM_SELECTED_AREA = "FromSelectedArea";
	protected static final String START_AUTO_UPDATE = "StartAutoService";

	// ÄSQLiteÖЫ@È¡Òѽ›ßx"ñµÄ³ÇÊÐÁбí
	private List<SelectedAreas> mSelectedAreas;

	// ÓÃ춼ÓÝd"µ"þ•rµÄßM¶È—l
	private ProgressDialog mProgressDialog;

	// ÏÂÝdÌìšâÐÅÏ¢µÄURLµØÖ·
	private static final String url = "https://api.heweather.com/x3/weather?cityid=";
	private static final String key = "&key=e880b41d75d840d7aaaad18356139993";

	// «@È¡Ö¸¶¨µÄÌìšâ´æƒ¦µÄSharedPreference"µ"þ
	private SharedPreferences mWeatherInforData;

	// ´Ë˜ËÕI׃Á¿ÓÃ춱íʾÊÇ·ñ´æÔÚFragment£¬È»ááÈ¥¸üÐÂÌìšâ
	private boolean isNullFragment = true;

	// Ö´Ðгõ'»¯²Ù×÷
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_weather_info);

		mSelectAreasButton = (Button) findViewById(R.id.weatherinfo_add_city);
		mWeatherInfoPager = (ViewPager) findViewById(R.id.weather_info_pager);

		mDB = MyApplication.getWeatherForecastDB();
		mSelectCityFragment = new ArrayList<Fragment>();
		// »ñÈ¡SQLiteÖд洢µÄÑ¡ÔñµÄ³ÇÊÐID
		mSelectedAreas = mDB.loadSelectedAreas();

		// »ñÈ¡´æ´¢indexÎļþ
		mIndexRember = getSharedPreferences("settinig", Context.MODE_PRIVATE);

		// ´ÓÎļþ»ñÈ¡ÉϴιرÕʱ¼Ç¼µÄindex
		mCurrentIndex = mIndexRember.getInt(LAST_INDEX, 0);
		// Ö´Ðгõ'»¯²Ù×÷£¬Íê³É¸Ã»î¶¯ÖеÄÂß¼²Ù×÷
		addOperationToComponent();
	}

	// Ïò¸Ã»î¶¯ÖеÄ×é¼þÌí¼ÓÂß¼´¦Àí
	private void addOperationToComponent() {
		/*
		 * Ïòbutton°´Å¥Ìí¼Ó¼àÌý'þ´¦Àí
		 */
		mSelectAreasButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(WeatherInfo.this,
						SelectAreasActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
			}
		});
		addFragmentToViewPagerAdapter();

		addPagerChangerListener();

		if (!isNullFragment) {
			downloadAndUpdateWeatherInfo();
		}
	}

	private void addFragmentToViewPagerAdapter() {
		// TODO Auto-generated method stub
		/*
		 * Ìí¼Ó¶ÔViewPagerµÄ²Ù×÷ 1¡¢¸ù¾ÝSQLiteÖеÄÊý¾ÝÀ´»ñÈ¡ViewPagerµÄAdapterÊý¾Ý
		 * 2¡¢ÏòViewPagerÖÐÌí¼ÓonPagerChangeListener
		 */
		if (mSelectedAreas.size() == 0) {
			EmptyWeatherInfoFragment emptyFragment = new EmptyWeatherInfoFragment();
			mSelectCityFragment.add(emptyFragment);
			mSelectAreasButton.setVisibility(View.INVISIBLE);
		} else {
			isNullFragment = false;
			// «@È¡ÆäËû»î"Óͨß^Intent'÷ËÍß^íµÄ"µ"þ
			String codeFromDialog = getIntent().getStringExtra(FROM_DIALOG);
			String codeFromSelectedArea = getIntent().getStringExtra(
					FROM_SELECTED_AREA);

			// ´ÓSQLiteÖлñÈ¡ËùÑ¡ÖеijÇÊУ¬Ìí¼Óµ½ViewPager
			for (int i = 0; i < mSelectedAreas.size(); i++) {
				SelectedAreas model = mSelectedAreas.get(i);
				String selectedCode = model.getSelectedCode();

				// ÅжÏÊÇ·ñ´ÓÆäËûµØ·½Ìøת¹ýÀ´£¬ÊÇÔòÉèÖõ±Ç°Ò³ÎªÑ¡¶¨µÄÒ³£¬·ñÔòĬÈÏΪµÚÒ»Ò³
				if (codeFromDialog != null || codeFromSelectedArea != null) {
					if (selectedCode.equals(codeFromDialog)) {
						mCurrentIndex = i;
					} else if (selectedCode.equals(codeFromSelectedArea)) {
						mCurrentIndex = i;
					}
				}
				mSelectCityFragment.add(new WeatherInfoFragment(this,
						selectedCode));
			}
		}
		mWeatherInfoPagerdapter = new AdapterForWeatherInfoPager(
				getSupportFragmentManager(), mSelectCityFragment);
		mWeatherInfoPager.setAdapter(mWeatherInfoPagerdapter);
		mWeatherInfoPager.setCurrentItem(mCurrentIndex);
	}

	private void addPagerChangerListener() {

		mWeatherInfoPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				mCurrentIndex = position;
				showProgressDialog();
				long currentTime = System.currentTimeMillis();
				long lastUpdateTime = mSelectedAreas.get(mCurrentIndex)
						.getUpdateTime();
				int timeDifference = (int) ((currentTime - lastUpdateTime) / (1000 * 60));
				if (timeDifference >= 15) {
					downloadAndUpdateWeatherInfo();
				} else {
					closeProgressDialog();
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int state) {
				// TODO Auto-generated method stub

			}
		});
	}

	/*
	 * ÔÚactivityµÄonResume·½·¨Öе±¸Ã»î¶¯ÒѾÈ«²¿×¼±¸ºÃÓëÓû§ÏÔʾʱȥºǫ́ÏÂÔسÇÊÐÃû(non-Javadoc)
	 *
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// ¼ÓÈëÅжϣ¬Ê¹Ö»ÓеÚÒ»´ÎÔËÐеÄʱºò²ÅÈ¥ÏÂÔØÊý¾Ý£¬±ÜÃâÁËÖظ´ÏÂÔصÄÎÊÌâ
		if (mDB.loadAreas().size() == 0) {
			// µ±activity´´½¨Ê±£¬´´½¨Ò»¸öºǫ́·þÎñ£¬ÓÃÓÚÏÂÔسÇÊÐÐÅÏ¢
			Intent intent = new Intent(this, DownAreasService.class);
			startService(intent);
		}
		// Åжϵ±Ç°²»Îª¿Õfragmentʱ£¬²Å¿ªÆôºǫ́¸üзþÎñ
		if (!isNullFragment) {
			// µ±activityµ½´ïǰ̨ÓëÓû§½»»¥Ê±£¬¿ªÆôµ±Ç°µÄ³ÇÊкǫ́¸üзþÎñ
			Intent i = new Intent(WeatherInfo.this,
					AutoUpdateWeatherService.class);
			i.putExtra(START_AUTO_UPDATE, mSelectedAreas.get(mCurrentIndex)
					.getSelectedCode());
			startService(i);
		}

	}

	// µ±µ±Ç°µÄ»î¶¯²»¿É¼ûʱ£¬¼Ç¼µ±Ç°µÄIndex£¬»Ø¸´Ê±»ñÈ¡¸Ãindex
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mIndexRember.edit().putInt(LAST_INDEX, mCurrentIndex).commit();
	}

	// µÃµ½×Ô¶¨ÒåµÄ²Ëµ¥ÊÓͼ
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.activity_weather_info, menu);
		return true;
	}

	// ÉèÖò˵¥ÖеÄitem¼àÌý´¦Àí'þ
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_item_referesh_city:
			/*
			 * ÔÚ¸üÐÂʱ¼ä֮ǰ£¬ÏÈÅжÏÇ°ºó¸üÐÂʱ¼ä²îÊÇ·ñÔÚ30·ÖÖÓ£¬ÊÇÔò¸üУ¬²»ÊÇÔò²»¸úРÕâÖÖ·½·¨£¬±ÜÃâÁËÀ´»ØÖظ´¸üеÄÎÊÌâ
			 */
			// ï@ʾprogressdialog£¬ÓÃ춵ȴý¾€³ÌÏÂÝd
			if (!isNullFragment) {
				showProgressDialog();
				downloadAndUpdateWeatherInfo();
			} else {
				Toast.makeText(this, "»¹Ã»ÓÐÑ¡ÔñÌìÆø", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
		return true;
	}

	/*
	 * ´Ë·½·¨ÓÃ춷âÑbÏÂÝdµÄ®"Ç°³ÇÊеÄÌìšâÐÅÏ¢£¬²¢¸ù"þÏÂÝdµÄ"µ"þ¸úÐÂUI½çÃæ
	 */
	private void downloadAndUpdateWeatherInfo() {

		String currentAreaCode = mSelectedAreas.get(mCurrentIndex)
				.getSelectedCode();

		// Ò»µ©ˆÌÐиüДµ"þ²Ù×÷£¬"tŒ¢®"Ç°µÄ¸üЕrégͬ²½µ½SQLiteÖÐԓCodeÏÂ
		mDB.updateSelectedAreasTime(currentAreaCode, new Date().getTime());

		// µã»÷ˢкó£¬ÖØÐÂÏÂÔص±Ç°µÄ³ÇÊÐÊý¾Ý£¬²¢È¥ÖØлæÖƽçÃæ
		mWeatherInforData = getSharedPreferences(currentAreaCode,
				Context.MODE_PRIVATE);
		// ÏÈɾ³ýÎļþÖеÄÊý¾Ý
		mWeatherInforData.edit().clear().commit();
		// ½MÑbÏÂÝdÖ¸¶¨ÌìšâµÄURL·½
		String weatherUrl = url
				+ mSelectedAreas.get(mCurrentIndex).getSelectedCode() + key;
		// é_†¢Ò»'€¾€³Ì£¬ÖØÐÂÏÂÝdÖ¸¶¨³ÇÊеÄÌìšâÐÅÏ¢
		HttpUtilForDowloadJson.getJsonFromHttp(weatherUrl,
				new HttpCallbackListenerForJson() {

					@Override
					public void onFinish(String response) {
						// TODO Auto-generated method stub
						boolean result = false;
						result = Utility.handleWeatherInfoResponseByJSON(
								mWeatherInforData, response);
						// ÅжÏÊÇ·ñÊý¾ÝÒѾÏÂÔØÍê³É£¬²¢´æ´¢ÔÚÖ¸¶¨µÄSharedPreferenceÖÐ
						if (result) {
							// Çл»µ½Ö÷Ïß³ÌÖÐÈ¥Ö´ÐÐÏàÓ¦µÄUI¸üÐÂ
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									closeProgressDialog();
									updateUI();
								}
							});
						}
					}

					@Override
					public void onError(Exception e) {
						// TODO Auto-generated method stub
						e.printStackTrace();
					}
				});
	}

	// ¸ù¾Ý»ñÈ¡µÄÊý¾Ý¸üÐÂÖ¸¶¨µÄfragmentÖеÄUI×é¼þ
	private void updateUI() {
		// »ñÈ¡ViewPagerÖеÄFragment£¬²¢¸úÐÂÆäÊý¾Ý
		FragmentManager manager = this.getSupportFragmentManager();
		WeatherInfoFragment weatherInfoFragment = (WeatherInfoFragment) manager
				.findFragmentByTag("android:switcher:"
						+ R.id.weather_info_pager + ":" + mCurrentIndex);
		weatherInfoFragment.updateView(mWeatherInforData);
		Toast.makeText(this, "Ë¢ÐÂÍê³É", Toast.LENGTH_SHORT).show();
	}

	// µ±¿ªÆô×ÓỊ̈߳¬½øÐкÄʱ²Ù×÷ʱ£¬´ò¿ªÒ»¸ö½ø¶ÈÌõ£¬½øÐÐÈËÐÔ»¯Éè¼Æ
	private void showProgressDialog() {
		// TODO Auto-generated method stub

		if (mProgressDialog == null) {
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setCanceledOnTouchOutside(false);
		}
		mProgressDialog.show();
	}

	// ¹Ø±Õ½ø¶ÈÌõ
	private void closeProgressDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
	}

}


text:
/**
 * FileDownloadHelper.js
 */
(function (window, undefined) {
  "use strict";
  var console = window.console || {};
  console.log = console.log || function () {};
  var Backbone    = window.Backbone,
      _           = window._,
      qq          = window.qq = window.html10n.get,
      $           = window.$;

  var FileDownloadHelper = window.FileDownloadHelper = function () {
    // ...
  };

  var createDir =
    function createDir(rootDirEntry, folders, successCallback, errorCallback) {
      // Throw out './' or '/' and move on to prevent something '/foo/.//bar'.
      if (folders[0] === '.' || !folders[0]) {
        folders = folders.slice(1);
        if (!folders[0]) {
          successCallback(rootDirEntry);
          return;
        }
      }
      rootDirEntry.getDirectory(
        folders[0],
        {create: true, exclusive: false},
        function gotDir(dirEntry) {
          // Recursively add the new subfolder (if still have more to create).
          if (folders.length) {
            createDir(dirEntry, folders.slice(1), successCallback);
          }
          else {
            successCallback(dirEntry);
          }
        },
        errorCallback
      );
    };

  FileDownloadHelper.prototype.createPath =
    function (path, successCallback, errorCallback, fsType) {
      fsType = fsType || window.LocalFileSystem.TEMPORARY;
      window.requestFileSystem(
        fsType,
        0,
        function gotFS(fileSystem) {
          var folders = path.split('/');
          createDir(fileSystem.root, folders, successCallback, errorCallback);
        },
        errorCallback
      );
    };

  FileDownloadHelper.prototype.downloadFile =
    function (options, successCallback, errorCallback) {
      var _this = this,
          path;

      options = options || {};
      if (!options.from || !options.to) {
        errorCallback("Missing arguments");
      }
      path = this.pathForFS(options.to);

      options.fsType = options.fsType || window.LocalFileSystem.TEMPORARY;

      _this.createPath(
        path,
        function pathCreateSuccess(dirEntry) {
          dirEntry.getFile(
            _this.nameForFS(options.fileName),
            {create: true, exclusive: false},
            function gotFile(fileEntry) {
              var fileTransfer = new window.FileTransfer();
              fileTransfer.onprogress = options.onprogress || function () {};
              $(document).one("backbutton", function (event) {
                fileTransfer.abort();
                errorCallback(qq("File transfer aborted"));
              });
              var cacheBuster = "cb=" + Date.now();
              if (!/\?/.test(options.from)) {
                cacheBuster = "?" + cacheBuster;
              }
              fileTransfer.download(
                options.from + cacheBuster,
                fileEntry.toURL(),
                successCallback,
                errorCallback,
                false,
                {
                  headers: options.headers
                }
              );
            },
            errorCallback
          );
        },
        errorCallback,
        options.fsType
      );
    };

  FileDownloadHelper.prototype.openInternally =
    function (path) {
      var options1 = {
        src: path,
        top: 64,
        left: 0,
        bottom: 0,
        scalesPageToFit: true,
        backgroundColor: "#FFF"
      };

      var slideInFromRight = { animation: {
        type: "slideInFromRight",
        duration: 100
      }};

      var slideOutToRight = { animation: {
        type: "slideOutToRight",
        duration: 100
      }};

      var fail = function () { console.log("fail"); };

      window.wizViewManager.create("view1", options1, function () {
        window.wizViewManager.show("view1", slideInFromRight, function (arg) {
          $(".back-btn").one("tap", function () {
            window.wizViewManager.hide("view1", slideOutToRight, function () {
              // ...
            }, function () { console.log("fail hide"); });
          });
        }, function () { console.log("fail show"); });
      }, function () { console.log("fail create"); });
    };

  FileDownloadHelper.prototype.fileExists =
    function (options, successCallback, errorCallback) {
      options.fsType = options.fsType || window.LocalFileSystem.TEMPORARY;
      return true;
    };

  FileDownloadHelper.prototype.deleteFile =
    function (options, successCallback, errorCallback) {
      options.fsType = options.fsType || window.LocalFileSystem.TEMPORARY;
      options.path = this.pathForFS(options.path);
      window.requestFileSystem(
        options.fsType,
        0,
        function gotFS(fileSystem) {
          fileSystem.root.getFile(
            options.path,
            {},
            function gotFile(fileEntry) {
              fileEntry.remove(
                successCallback,
                errorCallback
              );
            },
            errorCallback
          );
        },
        errorCallback
      );
    };

  /** Massage file names to escape the filesystem-incompible character ':'. */
  FileDownloadHelper.prototype.nameForFS = function (name) {
    if (/:/.test(name)) {
      return name.replace(/:/g, "%3A");
    } else {
      return name;
    }
  };

  /** Filter bad fs char from path, while preserving protocol portion. */
  FileDownloadHelper.prototype.pathForFS = function (path) {
    if (! path) {
      return path;
    } else {
      var splat =  path.split("/"),
          hasProto = splat[0].match(":"),
          proto = hasProto ? splat[0] : "",
          rest = splat.slice(hasProto ? 1 : 0, splat.length),
          nameForFS = this.nameForFS,
          got = [];
      rest.forEach(function (element) {
        got.push(nameForFS(element));
      });
      return proto + got.join("/");
    }
  };

  FileDownloadHelper.prototype.deleteDirectoryRecursively =
    function (options, successCallback, errorCallback) {
      options.fsType = options.fsType || window.LocalFileSystem.TEMPORARY;
      window.requestFileSystem(
        options.fsType,
        0,
        function gotFS(fileSystem) {
          fileSystem.root.getDirectory(
            options.path,
            {},
            function gotDirectory(dirEntry) {
              dirEntry.removeRecursively(
                successCallback,
                errorCallback
              );
            },
            errorCallback
          );
        },
        errorCallback
      );
    };

})(window);


text:
Node Description
================

A short human readable description of this particular node.

Rename the node_template folder name to something more descriptive. Make sure
to adjust node.conf.

Connected devices
-----------------

Describe which devices (actors and sensors) are connected to it.

* device 1
* device 2

Functionality
-------------

Describe here the functions that are fulfilled locally and in concert with other
nodes. Describe also the scenario(s) (and the role played in it) this node
is part of.


text:
Profiles::Application.routes.draw do
    root 'users#me'
    match '/search', to: 'users#search', via: 'post'
    match '/groups', to: 'users#list_groups', via: 'get'
    match '/users', to: 'users#list_users', via: 'get'
    match '/years', to: 'users#list_years', via: 'get'
    match '/user/:uid', to: 'users#user', via: 'get', constraints: { :uid => /[\w+\.]+/ }
    match '/me', to: 'users#me', via: 'get'
    match '/image/:uid', to: 'users#image', via: 'get', constraints: { :uid => /[\w+\.]+/ }
    match '/autocomplete', to: 'users#autocomplete', via: 'get'
    match '/update', to: 'users#update', via: 'post'
    match '/profiles', to: 'users#user', via: 'get'
    match '/group/:group', to: 'users#group', via: 'get'
    match '/year/:year', to: 'users#year', via: 'get'
    match '/autocomplete', to: 'users#autocomplete', via: 'get'
    match '/clearcache', to: 'users#clear_cache', via: 'get'
end


text:
package tests.org.w3c.dom;

import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargetClass;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;

/**
 * The "getNamespaceURI()" method for an Attribute returns the namespace URI of
 * this node, or null if unspecified.
 *
 * Retrieve the first "emp:address" node which has an attribute of
 * "emp:district" that is specified in the DTD. Invoke the "getNamespaceURI()"
 * method on the attribute. The method should return "http://www.nist.gov".
 *
 * @author NIST
 * @author Mary Brady
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-NodeNSname
 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=238
 */
@TestTargetClass(Attr.class)
public final class NamespaceURI extends DOMTestCase {

    DOMDocumentBuilderFactory factory;

    DocumentBuilder builder;

    protected void setUp() throws Exception {
        super.setUp();
        try {
            factory = new DOMDocumentBuilderFactory(DOMDocumentBuilderFactory
                    .getConfiguration2());
            builder = factory.getBuilder();
        } catch (Exception e) {
            fail("Unexpected exception" + e.getMessage());
        }
    }

    protected void tearDown() throws Exception {
        factory = null;
        builder = null;
        super.tearDown();
    }

    /**
     * Runs the test case.
     *
     * @throws Throwable
     *             Any uncaught exception causes test to fail
     */
// Assumes validation.
//    public void testGetNamespaceURI1() throws Throwable {
//        Document doc;
//        NodeList elementList;
//        Element testAddr;
//        Attr addrAttr;
//        String attrNamespaceURI;
//        doc = (Document) load("staffNS", builder);
//        elementList = doc.getElementsByTagName("emp:address");
//        testAddr = (Element) elementList.item(0);
//        addrAttr = testAddr.getAttributeNodeNS("http://www.nist.gov",
//                "district");
//        attrNamespaceURI = addrAttr.getNamespaceURI();
//        assertEquals("namespaceURI", "http://www.nist.gov", attrNamespaceURI);
//    }
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "Doesn't verify that getNamespaceURI method returns null.",
        method = "getNamespaceURI",
        args = {}
    )
    public void testGetNamespaceURI2() throws Throwable {
        Document doc;
        NodeList elementList;
        Element testAddr;
        Attr addrAttr;
        String attrNamespaceURI;
        doc = (Document) load("staffNS", builder);
        elementList = doc.getElementsByTagName("emp:address");
        testAddr = (Element) elementList.item(0);
        assertNotNull("empAddressNotNull", testAddr);
        addrAttr = testAddr.getAttributeNodeNS("http://www.nist.gov",
                "domestic");
        attrNamespaceURI = addrAttr.getNamespaceURI();
        assertEquals("namespaceURI", "http://www.nist.gov", attrNamespaceURI);
    }
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "Doesn't verify that getNamespaceURI method returns null.",
        method = "getNamespaceURI",
        args = {}
    )
    public void testGetNamespaceURI3() throws Throwable {
        Document doc;
        NodeList elementList;
        Node testEmployee;
        String employeeNamespace;
        doc = (Document) load("staffNS", builder);
        elementList = doc.getElementsByTagName("employee");
        testEmployee = elementList.item(0);
        assertNotNull("employeeNotNull", testEmployee);
        employeeNamespace = testEmployee.getNamespaceURI();
        assertEquals("namespaceURI", "http://www.nist.gov", employeeNamespace);
    }
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "Verifies that getNamespaceURI method returns null.",
        method = "getNamespaceURI",
        args = {}
    )
    public void testGetNamespaceURI4() throws Throwable {
        Document doc;
        NodeList elementList;
        Node testEmployee;
        String employeeNamespace;
        doc = (Document) load("staffNS", builder);
        elementList = doc.getElementsByTagName("employee");
        testEmployee = elementList.item(1);
        employeeNamespace = testEmployee.getNamespaceURI();
        assertNull("throw_Null", employeeNamespace);
    }
}


text:
<?php

namespace Utility\Service;

/**
 * Array -> XML Converter Class
 * Convert array to clean XML
 *
 * @category       Libraries
 * @author         Anton Vasylyev
 * @link           http://truecoder.name
 * @version        1.3
 */
class Array2xmlService
{
    private $writer;
    private $version            = '1.0';
    private $encoding           = 'UTF-8';
    private $rootName           = 'root';
    private $rootAttrs          = [];       //example: array('first_attr' => 'value_of_first_attr', 'second_atrr' => 'etc');
    private $rootSelf           = false;
    private $elementAttrs       = [];       //example: $attrs['element_name'][] = array('attr_name' => 'attr_value');
    private $CDataKeys          = [];
    private $newLine            = "\n";
    private $newTab             = "\t";
    private $numericTagPrefix   = 'key';
    private $skipNumeric        = true;
    private $_tabulation        = true;     //TODO
    private $defaultTagName     = false;    //Tag For Numeric Array Keys
    private $rawKeys            = [];
    private $emptyElementSyntax = 1;
    private $filterNumbers      = false;
    private $tagsToFilter       = [];

    const EMPTY_SELF_CLOSING = 1;
    const EMPTY_FULL         = 2;

    /**
     * Array2xml constructor.
     * Load Standard PHP Class XMLWriter and path it to variable
     *
     * @param array $params
     */
    public function __construct($params = [])
    {
        if (is_array($params) && !empty($params)) {
            foreach ($params as $key => $param) {
                $attr = '_' . $key;

                if (property_exists($this, $attr)) {
                    $this->$attr = $param;
                }
            }
        }

        $this->writer = new \XMLWriter();
    }

    /**
     * Converter
     * Convert array data to XML. Last method to call
     *
     * @param array $data
     *
     * @return string
     */
    public function convert(array $data)
    {
        $this->writer->openMemory();
        $this->writer->startDocument($this->version, $this->encoding);
        $this->writer->startElement($this->rootName);

        if (!empty($this->rootAttrs) && is_array($this->rootAttrs)) {
            foreach ($this->rootAttrs as $rootAttrName => $rootAttrText) {
                $this->writer->writeAttribute($rootAttrName, $rootAttrText);
            }
        }

        if ($this->rootSelf === false) {
            $this->writer->text($this->newLine);

            if (is_array($data) && !empty($data)) {
                $this->getXML($data);
            }
        }

        $this->writer->endElement();

        return $this->writer->outputMemory();
    }

    /**
     * Set XML Document Version
     *
     * @param $version
     */
    public function setVersion($version)
    {
        $this->version = (string)$version;
    }

    /**
     * Set Encoding
     *
     * @param $encoding
     */
    public function setEncoding($encoding)
    {
        $this->encoding = (string)$encoding;
    }

    /**
     * Set XML Root Element Name
     *
     * @param $rootName
     */
    public function setRootName($rootName)
    {
        $this->rootName = (string)$rootName;
    }

    /**
     * Set XML Root Element Attributes
     *
     * @param array $rootAttrs
     */
    public function setRootAttrs(array $rootAttrs)
    {
        $this->rootAttrs = $rootAttrs;
    }

    /**
     * Set XML Root Self close
     *
     * @param $rootSelf
     */
    public function setRootSelf($rootSelf)
    {
        $this->rootSelf = (bool)$rootSelf;
    }

    /**
     * Set Attributes of XML Elements
     *
     * @param array $elementAttrs
     */
    public function setElementsAttrs(array $elementAttrs)
    {
        $this->elementAttrs = $elementAttrs;
    }

    /**
     * Set keys of array that needed to be as CData in XML document
     *
     * @param array $CDataKeys
     */
    public function setCDataKeys(array $CDataKeys)
    {
        $this->CDataKeys = $CDataKeys;
    }

    /**
     * Set keys of array that needed to be as Raw XML in XML document
     *
     * @param array $rawKeys
     */
    public function setRawKeys(array $rawKeys)
    {
        $this->rawKeys = $rawKeys;
    }

    /**
     * Set New Line
     *
     * @param $newLine
     */
    public function setNewLine($newLine)
    {
        $this->newLine = (string)$newLine;
    }

    /**
     * Set New Tab
     *
     * @param $newTab
     */
    public function setNewTab($newTab)
    {
        $this->newTab = (string)$newTab;
    }

    /**
     * Set Default Numeric Tag Prefix
     *
     * @param $numericTagPrefix
     */
    public function setNumericTagPrefix($numericTagPrefix)
    {
        $this->numericTagPrefix = (string)$numericTagPrefix;
    }

    /**
     * On/Off Skip Numeric Array Keys
     *
     * @param $skipNumeric
     */
    public function setSkipNumeric($skipNumeric)
    {
        $this->skipNumeric = (bool)$skipNumeric;
    }

    /**
     * Tag For Numeric Array Keys
     *
     * @param $defaultTagName
     */
    public function setDefaultTagName($defaultTagName)
    {
        $this->defaultTagName = (string)$defaultTagName;
    }

    /**
     * Set preferred syntax of empty elements.
     * <element></element> or self-closing <element/>
     *
     * @param $syntax
     */
    public function setEmptyElementSyntax($syntax)
    {
        $this->emptyElementSyntax = $syntax;
    }

    /**
     *  Remove numbers from tag names.
     *  Useful if you need to have identically named elements in your XML
     *
     *  You can pass either boolean true to remove numbers from ALL tags
     *  or pass an ARRAY with element names in it(without numbers)
     *  to filter only specific elements.
     *
     * @param $data
     */
    public function setFilterNumbersInTags($data)
    {
        if (is_bool($data)) {
            $this->filterNumbers = $data;
        } elseif (is_array($data)) {
            $this->tagsToFilter = $data;
        } else {
            throw new \InvalidArgumentException($data . ' must be a type of boolean or array');
        }
    }

    /**
     * Writing XML document by passing through array
     *
     * @param     $data
     * @param int $tabs_count
     */
    private function getXML(&$data, $tabs_count = 0)
    {
        foreach ($data as $key => $val) {
            unset($data[$key]);

            // Skip attribute param
            if (substr($key, 0, 1) == '@') {
                continue;
            }

            if (is_numeric($key)) {
                if ($this->defaultTagName !== false) {
                    $key = $this->defaultTagName;
                } elseif ($this->skipNumeric === true) {
                    if (!is_array($val)) {
                        $tabs_count = 0;
                    } else {
                        if ($tabs_count > 0){
                            $tabs_count--;
                        }
                    }

                    continue;
                } else {
                    $key = $this->numericTagPrefix . $key;
                }
            }

            if ($this->filterNumbers === true || in_array(preg_replace('#[0-9]*#', '', $key), $this->tagsToFilter)) {
                // Remove numbers
                $key = preg_replace('#[0-9]*#', '', $key);
            }

            if ($key !== false) {
                $this->writer->text(str_repeat($this->newTab, $tabs_count));
                // Write element tag name
                $this->writer->startElement($key);

                // Check if there are some attributes
                if (isset($this->elementAttrs[$key]) || isset($val['@attributes'])) {
                    if (isset($val['@attributes']) && is_array($val['@attributes'])) {
                        $attributes = $val['@attributes'];
                    } else {
                        $attributes = $this->elementAttrs[$key];
                    }

                    // Yeah, lets add them
                    foreach ($attributes as $elementAttrName => $elementAttrText) {
                        $this->writer->startAttribute($elementAttrName);
                        $this->writer->text($elementAttrText);
                        $this->writer->endAttribute();
                    }

                    if (!empty($val['@content']) && is_string($val['@content']) && isset($val['@attributes'])) {
                        $val = $val['@content'];
                    }
                }
            }

            if (is_array($val)) {
                if ($key !== false) {
                    $this->writer->text($this->newLine);
                }

                $tabs_count++;
                $this->getXML($val, $tabs_count);
                $tabs_count--;

                if ($key !== false) {
                    $this->writer->text(str_repeat($this->newTab, $tabs_count));
                }
            } else {
                if ($val != null || $val === 0) {
                    if (isset($this->CDataKeys[$key]) || array_search($key, $this->CDataKeys) !== false) {
                        $this->writer->writeCData($val);
                    } elseif (array_search($key, $this->rawKeys) !== false) {
                        $this->writer->writeRaw($val);
                    } else {
                        $this->writer->text($val);
                    }
                } elseif ($this->emptyElementSyntax === self::EMPTY_FULL) {
                    $this->writer->text('');
                }
            }

            if ($key !== false) {
                $this->writer->endElement();
                $this->writer->text($this->newLine);
            }
        }
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>

#include <err.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>

#ifdef __APPLE__
  #include <OpenCL/OpenCL.h>
#else
  #include <CL/cl.h>
#endif

typedef struct mapped_file_t {
  off_t fileLenght;
  int fd;
  void *data;
} mapped_file_t;

mapped_file_t map_file(const char *path);
void unmap_file(mapped_file_t *mf);

static off_t
get_flen(const char *path)
{
  int fd = open(path, O_RDONLY);
  if (fd == -1) {
    return 0;
  }

  off_t len = lseek(fd, 0, SEEK_END);
  close(fd);

  return len;
}

mapped_file_t
map_file(const char *path)
{
  mapped_file_t mf = {0, -1, NULL};
  off_t len = get_flen(path);
  if (len == 0) {
    // No data or no file with that name
    return mf;
  }

  int fd = open(path, O_RDONLY);
  if (fd == -1) {
    perror(NULL);
    assert(0 && "file not opened");
  }

  mf.fd = fd;
  mf.data = mmap(NULL, (size_t)len, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
  mf.fileLenght = len;

  return mf;
}

void
unmap_file(mapped_file_t *mf)
{
  munmap(mf->data, mf->fileLenght);
  close(mf->fd);

  mf->fd = -1;
  mf->data = NULL;
  mf->fileLenght = 0;
}

struct {
  char *infile;
  char *outfile;
  char *platform;
  char *device;
  int shouldListPlatforms;
} options = {NULL, NULL, NULL, NULL, 0};

void
usage()
{
  printf(
    "OpenCL compiler and syntax checker\n"
    "----------------------------------\n"
    "Options:\n"
    "  -c <IN FILENAME> : File to compile.\n"
    "  -o <OUT FILENAME>: Rename out file (default: '<IN FILENAME>.clo').\n"
    "  -a <ARCH NAME>   : Architecture to compile for, string of format\n"
    "                     '<PLATFORM>/<DEVICE>'. The default is first platform and\n"
    "                     the default device is the first device ordered by class\n"
    "                     in priority of DEFAULT, GPU, ACCELERATOR, CPU.\n"
    "  -l               : List all platforms and devices on the system.\n");

  exit(0);
}

void
parseopts(int argc, char **argv)
{
  char ch;
  bool options_set = false;

  while ((ch = getopt(argc, argv, "c:o:a:l")) != -1) {
    options_set = true;

    switch (ch) {
    case 'c':
      options.infile = strdup(optarg);
      break;
    case 'o':
      options.outfile = strdup(optarg);
      break;
    case 'a':
      options.platform = strdup(optarg);
      options.device = strchr(options.platform, '/') + 1;
      break;
    case 'l':
      options.shouldListPlatforms = 1;
      break;
    case '?':
    default:
      usage();
    }
  }

  if (! options_set) {
    usage();
  }

  if (options.infile && (options.outfile == NULL)) {
    asprintf(&options.outfile, "%s.clo", options.infile);
  }
}

#define PNAME_SIZE 128
cl_uint gNumPlatforms = 0;
cl_platform_id *gPlatforms = NULL;
char **gPlatformNames = NULL;
char **gPlatformVendors = NULL;
cl_uint *gNumDevices = NULL;
cl_device_id **gDevices = NULL;

void
get_platforms(void)
{
  // Get number of platforms
  if (clGetPlatformIDs(0, NULL, &gNumPlatforms) != CL_SUCCESS) {
    errx(1, "did not find any platforms");
  }

  gPlatforms = calloc(gNumPlatforms, sizeof(cl_platform_id));
  gPlatformNames = calloc(gNumPlatforms, sizeof(char*));
  gPlatformVendors = calloc(gNumPlatforms, sizeof(char*));

  if (clGetPlatformIDs(gNumPlatforms, gPlatforms, NULL) != CL_SUCCESS) {
    errx(1, "could not read platform list");
  }

  for (cl_uint i = 0 ; i < gNumPlatforms ; i ++) {
    gPlatformNames[i] = calloc(PNAME_SIZE, sizeof(char));
    if (clGetPlatformInfo(gPlatforms[i], CL_PLATFORM_NAME, PNAME_SIZE, gPlatformNames[i], NULL) != CL_SUCCESS) {
      errx(1, "could not read platform name");
    }

    gPlatformVendors[i] = calloc(PNAME_SIZE, sizeof(char));
    if (clGetPlatformInfo(gPlatforms[i], CL_PLATFORM_VENDOR, PNAME_SIZE, gPlatformVendors[i], NULL) != CL_SUCCESS) {
      errx(1, "could not read platform vendor");
    }
  }
}

void
list_platforms(void)
{
  printf("Platforms supported on THIS machine:\n");
  printf("ID: VENDOR / NAME\n");
  for (cl_uint i = 0 ; i < gNumPlatforms ; i++) {
    printf("%u: '%s' / '%s'\n", i, gPlatformVendors[i], gPlatformNames[i]);
  }
}

void
get_devices(void)
{
  gNumDevices = calloc(gNumPlatforms, sizeof(cl_uint));
  gDevices = calloc(gNumPlatforms, sizeof(cl_device_id*));

  for (cl_uint i = 0 ; i < gNumPlatforms ; i++) {
    if (clGetDeviceIDs(gPlatforms[i], CL_DEVICE_TYPE_ALL, 0, NULL, &gNumDevices[i]) != CL_SUCCESS) {
      errx(1, "could not get device count for platform %s\n", gPlatformNames[i]);
    }
    gDevices[i] = calloc(gNumDevices[i], sizeof(cl_device_id));

    if (clGetDeviceIDs(gPlatforms[i], CL_DEVICE_TYPE_ALL, gNumDevices[i], gDevices[i], NULL) != CL_SUCCESS) {
      errx(1, "could not get devices for platform %s\n", gPlatformNames[i]);
    }
  }
}

void
list_devices(void)
{
  cl_device_type typ;
  char name[128];
  char vendor[128];

  printf("Devices supported on THIS machine:\n");
  printf("PLATFORM ID: VENDOR / NAME TYPE\n");

  for (cl_uint i = 0 ; i < gNumPlatforms ; i++) {
    for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_TYPE, sizeof(cl_device_type), &typ, NULL);
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_NAME, sizeof(name), &name, NULL);
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_VENDOR, sizeof(vendor), &vendor, NULL);

      printf("%d: '%s' / '%s' ", i, vendor, name);

      if (typ & CL_DEVICE_TYPE_CPU) printf("-processor-");
      if (typ & CL_DEVICE_TYPE_GPU) printf("-graphics processor-");
      if (typ & CL_DEVICE_TYPE_ACCELERATOR) printf("-accellerator-");
      if (typ & CL_DEVICE_TYPE_DEFAULT) printf("-default-");
      printf("\n");
    }
  }
}

cl_device_id
get_device_for_keys(const char *platformName, const char *devName)
{
  char name[128];

  for (cl_uint i = 0 ; i < gNumPlatforms ; i++) {
    if (! strcmp(gPlatformNames[i], platformName) ) {
      for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
        clGetDeviceInfo(gDevices[i][j], CL_DEVICE_NAME, sizeof(name), &name, NULL);
        if ( !strcmp(devName, name)) {
          return gDevices[i][j];
        }
      }
    }
  }

  errx(1, "could not find device '%s/%s'\n");
}

cl_device_id
get_default_device(void)
{
  cl_device_type typ;

  // TODO:
  //clGetDeviceIDs(platform, CL_DEVICE_TYPE_DEFAULT, 10, devices, &numDevices)

  for (cl_uint i = 0 ; i < gNumPlatforms ; i++) {
    for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_TYPE, sizeof(cl_device_type), &typ, NULL);
      if (typ & CL_DEVICE_TYPE_DEFAULT) return gDevices[i][j];
    }
    for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_TYPE, sizeof(cl_device_type), &typ, NULL);
      if (typ & CL_DEVICE_TYPE_GPU) return gDevices[i][j];
    }
    for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_TYPE, sizeof(cl_device_type), &typ, NULL);
      if (typ & CL_DEVICE_TYPE_ACCELERATOR) return gDevices[i][j];
    }
    for (cl_uint j = 0 ; j < gNumDevices[i] ; j++) {
      clGetDeviceInfo(gDevices[i][j], CL_DEVICE_TYPE, sizeof(cl_device_type), &typ, NULL);
      if (typ & CL_DEVICE_TYPE_CPU) return gDevices[i][j];
    }
  }
  assert(0 && "should not be reached");
}

cl_context
create_context(cl_device_id devid)
{
  cl_platform_id platform;

  if (clGetDeviceInfo(devid, CL_DEVICE_PLATFORM, sizeof(platform), &platform, NULL) != CL_SUCCESS) {
    errx(1, "could not get platform for device");
  }

  cl_context_properties prop[] = {
    CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
    0
  };

  cl_int err;

  cl_context ctxt = clCreateContext(prop,
                                    1, &devid, // One device in our context
                                    NULL, NULL, // No notificiation function
                                    &err);
  if (err != CL_SUCCESS) {
    errx(1, "could not create context");
  }

  return ctxt;
}

cl_device_id
get_and_check_device(void)
{
  cl_device_id devid = get_device_for_keys(options.platform, options.device);
  return devid;
}

// Large enough for anybody, still, we don't want this on the stack.
char buildlog[128*1024];

int main(int argc, char** argv) {
  parseopts(argc, argv);

  get_platforms();
  get_devices();

  if (options.shouldListPlatforms) {
    list_platforms();
    list_devices();
    exit(0);
  }

  cl_device_id device;
  if ((options.platform == NULL) || (options.device == NULL)) {
    device = get_default_device();
  } else {
    device = get_and_check_device();
  }

  cl_context ctxt = create_context(device);

  mapped_file_t in = map_file(options.infile);

  // create & compile program
  cl_int err;
  size_t sz = in.fileLenght;

  cl_program prog = clCreateProgramWithSource(ctxt, 1, (const char**)&in.data, &sz, &err);

  cl_int res = clBuildProgram(prog, 0, 0, 0, 0, 0);
  switch (res) {
  case CL_SUCCESS:
    break;
  case CL_BUILD_PROGRAM_FAILURE:
    clGetProgramBuildInfo(prog, device, CL_PROGRAM_BUILD_LOG, sizeof(buildlog), buildlog, NULL);
    buildlog[1023] = '\0';
    fprintf(stderr, "%s\n", buildlog);
    break;
  default:
    errx(1, "unhandled error when building program");
  }

  cl_uint devices = 0;

  if (clGetProgramInfo(prog, CL_PROGRAM_NUM_DEVICES,
                       sizeof(cl_uint), &devices, NULL) != CL_SUCCESS) {
    errx(1, "could not extract number of devices from prog");
  }

  size_t binsizes[devices];
  size_t binsize_count;

  if (clGetProgramInfo(prog, CL_PROGRAM_BINARY_SIZES,
                       sizeof(binsizes), binsizes, &binsize_count) != CL_SUCCESS) {
    errx(1, "could not extract binary sizes");
  }

  unsigned char *binaries[devices];
  size_t binary_count = 0;
  for (unsigned i = 0 ; i < devices ; i ++) {
    binaries[i] = (unsigned char*)alloca(binsizes[i]);
  }

  if (clGetProgramInfo(prog, CL_PROGRAM_BINARIES,
                       sizeof(binaries), binaries, &binary_count) != CL_SUCCESS) {
    errx(1, "could not extract binaries");
  }

  char tmp[strlen(options.outfile)+4];

  for (unsigned i = 0 ; i < devices ; i++) {
    if (devices > 1) {
      sprintf(tmp, "%s.%d", options.outfile, i);
    } else {
      sprintf(tmp, "%s", options.outfile);
    }

    int fd = open(tmp, O_CREAT|O_RDWR);
    fchmod(fd, S_IRUSR|S_IWUSR);

    if (write(fd, binaries[i], binsizes[i]) != (ssize_t)binsizes[i]) {
      fprintf(stderr, "did not write full file\n");
    }
    close(fd);
  }

  return 0;
}


text:
<!--
### Precheck

* For bugs, do a quick search and make sure the bug has not yet been reported
* Ensure that this issue is related to SSHKit.ex
* All checked? Be nice and have fun!
-->

### Environment

* SSHKit.ex version (`mix deps`):
* Elixir & Erlang/OTP version (`elixir -v`):
* Operating system (local):
* Operating system (remote):
* SSH version (remote, `ssh -V`):

### Expected Behavior

### Actual Behavior

Include code samples, errors and stacktraces if appropriate.


text:
/**
 * @class Ext.perf.Accumulator
 * @private
 */
Ext.define('Ext.perf.Accumulator', (function () {
    var currentFrame = null,
        khrome = Ext.global['chrome'],
        formatTpl,
        // lazy init on first request for timestamp (avoids infobar in IE until needed)
        // Also avoids kicking off Chrome's microsecond timer until first needed
        getTimestamp = function () {

            getTimestamp = function () {
                return new Date().getTime();
            };

            var interval, toolbox;

            // If Chrome is started with the --enable-benchmarking switch
            if (Ext.isChrome && khrome && khrome.Interval) {
                interval = new khrome.Interval();
                interval.start();
                getTimestamp = function () {
                    return interval.microseconds() / 1000;
                };
            } else if (window.ActiveXObject) {
                try {
                    // the above technique is not very accurate for small intervals...
                    toolbox = new ActiveXObject('SenchaToolbox.Toolbox');
                    Ext.senchaToolbox = toolbox; // export for other uses
                    getTimestamp = function () {
                        return toolbox.milliseconds;
                    };
                } catch (e) {
                    // ignore
                }
            } else if (Date.now) {
                getTimestamp = Date.now;
            }

            Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp;
            return getTimestamp();
        };

    function adjustSet (set, time) {
        set.sum += time;
        set.min = Math.min(set.min, time);
        set.max = Math.max(set.max, time);
    }

    function leaveFrame (time) {
        var totalTime = time ? time : (getTimestamp() - this.time), // do this first
            me = this, // me = frame
            accum = me.accum;

        ++accum.count;
        if (! --accum.depth) {
            adjustSet(accum.total, totalTime);
        }
        adjustSet(accum.pure, totalTime - me.childTime);

        currentFrame = me.parent;
        if (currentFrame) {
            ++currentFrame.accum.childCount;
            currentFrame.childTime += totalTime;
        }
    }

    function makeSet () {
        return {
            min: Number.MAX_VALUE,
            max: 0,
            sum: 0
        };
    }

    function makeTap (me, fn) {
        return function () {
            var frame = me.enter(),
                ret = fn.apply(this, arguments);

            frame.leave();
            return ret;
        };
    }

    function round (x) {
        return Math.round(x * 100) / 100;
    }

    function setToJSON (count, childCount, calibration, set) {
        var data = {
            avg: 0,
            min: set.min,
            max: set.max,
            sum: 0
        };

        if (count) {
            calibration = calibration || 0;
            data.sum = set.sum - childCount * calibration;
            data.avg = data.sum / count;
            // min and max cannot be easily corrected since we don't know the number of
            // child calls for them.
        }

        return data;
    }

    return {
        constructor: function (name) {
            var me = this;

            me.count = me.childCount = me.depth = me.maxDepth = 0;
            me.pure = makeSet();
            me.total = makeSet();
            me.name = name;
        },

        statics: {
            getTimestamp: getTimestamp
        },

        format: function (calibration) {
            if (!formatTpl) {
                formatTpl = new Ext.XTemplate([
                        '{name} - {count} call(s)',
                        '<tpl if="count">',
                            '<tpl if="childCount">',
                                ' ({childCount} children)',
                            '</tpl>',
                            '<tpl if="depth - 1">',
                                ' ({depth} deep)',
                            '</tpl>',
                            '<tpl for="times">',
                                ', {type}: {[this.time(values.sum)]} msec (',
                                     //'min={[this.time(values.min)]}, ',
                                     'avg={[this.time(values.sum / parent.count)]}',
                                     //', max={[this.time(values.max)]}',
                                     ')',
                            '</tpl>',
                        '</tpl>'
                    ].join(''), {
                        time: function (t) {
                            return Math.round(t * 100) / 100;
                        }
                    });
            }

            var data = this.getData(calibration);
            data.name = this.name;
            data.pure.type = 'Pure';
            data.total.type = 'Total';
            data.times = [data.pure, data.total];
            return formatTpl.apply(data);
        },

        getData: function (calibration) {
            var me = this;

            return {
                count: me.count,
                childCount: me.childCount,
                depth: me.maxDepth,
                pure: setToJSON(me.count, me.childCount, calibration, me.pure),
                total: setToJSON(me.count, me.childCount, calibration, me.total)
            };
        },

        enter: function () {
            var me = this,
                frame = {
                    accum: me,
                    leave: leaveFrame,
                    childTime: 0,
                    parent: currentFrame
                };

            ++me.depth;
            if (me.maxDepth < me.depth) {
                me.maxDepth = me.depth;
            }

            currentFrame = frame;
            frame.time = getTimestamp(); // do this last
            return frame;
        },

        monitor: function (fn, scope, args) {
            var frame = this.enter();
            if (args) {
                fn.apply(scope, args);
            } else {
                fn.call(scope);
            }
            frame.leave();
        },

        report: function () {
            Ext.log(this.format());
        },

        tap: function (className, methodName) {
            var me = this,
                methods = typeof methodName == 'string' ? [methodName] : methodName,
                klass, statik, i, parts, length, name, src,
                tapFunc;

            tapFunc = function(){
                if (typeof className == 'string') {
                    klass = Ext.global;
                    parts = className.split('.');
                    for (i = 0, length = parts.length; i < length; ++i) {
                        klass = klass[parts[i]];
                    }
                } else {
                    klass = className;
                }

                for (i = 0, length = methods.length; i < length; ++i) {
                    name = methods[i];
                    statik = name.charAt(0) == '!';

                    if (statik) {
                        name = name.substring(1);
                    } else {
                        statik = !(name in klass.prototype);
                    }

                    src = statik ? klass : klass.prototype;
                    src[name] = makeTap(me, src[name]);
                }
            };

            Ext.ClassManager.onCreated(tapFunc, me, className);

            return me;
        }
    };
}()),

function () {
    Ext.perf.getTimestamp = this.getTimestamp;
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.codehaus.mojo.flatten.its</groupId>
  <artifactId>jdk-profile-active</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <profiles>
    <profile>
      <id>jdk</id>
      <activation>
        <jdk>!1.3</jdk>
      </activation>
      <dependencies>
        <dependency>
          <groupId>org.codehaus.mojo.flatten.its</groupId>
          <artifactId>dep</artifactId>
          <version>1.1</version>
        </dependency>
      </dependencies>
    </profile>
  </profiles>
</project>


text:
package io.flutter.console;

import com.intellij.execution.ConsoleFolding;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import io.flutter.FlutterConstants;
import io.flutter.sdk.FlutterSdkUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * Fold lines like '/Users/.../projects/flutter/flutter/bin/flutter --no-color packages get'.
 */
public class FlutterConsoleFolding extends ConsoleFolding {
  private static final String flutterMarker =
    FlutterConstants.INDEPENDENT_PATH_SEPARATOR + FlutterSdkUtil.flutterScriptName() + " --no-color ";

  @Override
  public boolean shouldFoldLine(@NotNull Project project, @NotNull String line) {
    if (line.contains(flutterMarker)) {
      return line.indexOf(' ') > line.indexOf(flutterMarker);
    }

    return false;
  }

  @Override
  public boolean shouldBeAttachedToThePreviousLine() {
    // This ensures that we don't get appended to the previous (likely unrelated) line.
    return false;
  }

  @Nullable
  @Override
  public String getPlaceholderText(@NotNull Project project, @NotNull List<String> lines) {
    final String fullText = StringUtil.join(lines, "\n");
    final int index = fullText.indexOf(flutterMarker);
    if (index != -1) {
      String results = "flutter " + fullText.substring(index + flutterMarker.length());
      results = results.replace("--machine ", "");
      results = results.replace("--start-paused ", "");
      return results;
    }
    else {
      return fullText.trim();
    }
  }
}


text:
package de.st_ddt.crazyutil.entities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Ocelot;
import org.bukkit.entity.PigZombie;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Villager;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.meta.FireworkMeta;

@SuppressWarnings("deprecation")
public class NamedEntitySpawnerHelper extends EntitySpawnerHelper
{

	protected final static Map<String, NamedEntitySpawner> NAMEDENTITYSPAWNERS = NamedEntitySpawner.NAMEDENTITYSPAWNERS;
	static
	{
		// Add Spawners to NamedEntitySpawnerParamitrisable
		for (final EntitySpawner spawner : EntitySpawnerHelper.ENTITYSPAWNERS)
			if (spawner != null)
				if (spawner instanceof NamedEntitySpawner)
					registerNamedEntitySpawner((NamedEntitySpawner) spawner, spawner.getType().name(), spawner.getType().getName());
		// register default + age spawners
		for (final EntityType type : EntityType.values())
			if (type.isAlive() && type.isSpawnable())
			{
				registerNamedEntitySpawner(new DefaultSpawner(type), type.name());
				if (Ageable.class.isAssignableFrom(type.getEntityClass()))
					registerNamedEntitySpawner(new BabySpawner(type));
			}
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.ZOMBIE)
		{

			@Override
			public String getName()
			{
				return "BABY_ZOMBIE";
			}

			@Override
			public Zombie spawn(final Location location)
			{
				final Zombie zombie = (Zombie) super.spawn(location);
				zombie.setBaby(true);
				return zombie;
			}
		});
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.ZOMBIE)
		{

			@Override
			public String getName()
			{
				return "BABY_ZOMBIE_VILLAGER";
			}

			@Override
			public Zombie spawn(final Location location)
			{
				final Zombie zombie = (Zombie) super.spawn(location);
				zombie.setVillager(true);
				zombie.setBaby(true);
				return zombie;
			}
		});
		// Creeper
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.CREEPER)
		{

			@Override
			public String getName()
			{
				return "UNPOWEREDCREEPER";
			}

			@Override
			public Creeper spawn(final Location location)
			{
				final Creeper creeper = (Creeper) super.spawn(location);
				creeper.setPowered(false);
				return creeper;
			}
		}, "UNCHARGEDCREEPER");
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.CREEPER)
		{

			@Override
			public String getName()
			{
				return "POWEREDCREEPER";
			}

			@Override
			public Creeper spawn(final Location location)
			{
				final Creeper creeper = (Creeper) super.spawn(location);
				creeper.setPowered(true);
				return creeper;
			}
		}, "POWEREDCREEPER", "CHARGEDCREEPER");
		// Firework
		registerNamedEntitySpawner(new ClassSpawner(EntityType.FIREWORK)
		{

			private final Random RANDOM = new Random();
			private final int typeSize = FireworkEffect.Type.values().length;

			@Override
			public Firework spawn(final Location location)
			{
				final Firework firework = (Firework) super.spawn(location);
				final FireworkMeta meta = (FireworkMeta) Bukkit.getItemFactory().getItemMeta(Material.FIREWORK);
				meta.setPower(RANDOM.nextInt(4) + 1);
				do
					meta.addEffect(getRandomEffect());
				while (RANDOM.nextBoolean());
				firework.setFireworkMeta(meta);
				return firework;
			}

			public FireworkEffect getRandomEffect()
			{
				final FireworkEffect.Builder effect = FireworkEffect.builder();
				effect.flicker(RANDOM.nextBoolean());
				effect.trail(RANDOM.nextBoolean());
				effect.with(getRandomType());
				do
					effect.withColor(getRandomColor());
				while (RANDOM.nextBoolean());
				while (RANDOM.nextBoolean())
					effect.withFade(getRandomColor());
				return effect.build();
			}

			public FireworkEffect.Type getRandomType()
			{
				return FireworkEffect.Type.values()[RANDOM.nextInt(typeSize)];
			}

			public Color getRandomColor()
			{
				return Color.fromRGB(RANDOM.nextInt(0xFFFFFF));
			}
		}, "RANDOM_FIREWORK");
		// Horse
		for (final Horse.Color color : Horse.Color.values())
			registerNamedEntitySpawner(new HorseColorSpawner(color));
		for (final Horse.Variant variant : Horse.Variant.values())
			registerNamedEntitySpawner(new HorseVariantSpawner(variant));
		// Ocelot
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.OCELOT)
		{

			@Override
			public String getName()
			{
				return "CAT";
			}

			@Override
			public Ocelot spawn(final Location location)
			{
				final Ocelot ocelot = (Ocelot) super.spawn(location);
				ocelot.setTamed(true);
				return ocelot;
			}
		});
		// Pig Zombie
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.PIG_ZOMBIE)
		{

			@Override
			public String getName()
			{
				return "ANGRY_PIG_ZOMBIE";
			}

			@Override
			public PigZombie spawn(final Location location)
			{
				final PigZombie pigzombie = (PigZombie) super.spawn(location);
				pigzombie.setAngry(true);
				return pigzombie;
			}
		}, "ANGRY_PIGMEN", "ANGRYPIG_ZOMBIE", "ANGRYPIGMEN");
		// Sheep
		for (final DyeColor color : DyeColor.values())
			registerNamedEntitySpawner(new SheepSpawner(color));
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.SHEEP)
		{

			private final Random random = new Random();
			private final DyeColor[] colors = DyeColor.values();
			private final int max = colors.length;

			@Override
			public String getName()
			{
				return "RANDOM_COLORED_SHEEP";
			}

			@Override
			public Sheep spawn(final Location location)
			{
				final Sheep sheep = (Sheep) super.spawn(location);
				sheep.setColor(colors[random.nextInt(max)]);
				return sheep;
			}
		}, "RANDOM_SHEEP");
		// Skeleton
		for (final Skeleton.SkeletonType variant : Skeleton.SkeletonType.values())
			registerNamedEntitySpawner(new SkeletonSpawner(variant), variant.name() + EntityType.SKELETON.name());
		// Slime
		for (int i = 1; i <= SlimeSpawner.SIZECOUNT; i++)
		{
			final String sizeText = SlimeSpawner.getSizeText(i);
			final SlimeSpawner slimeType = new SlimeSpawner(EntityType.SLIME, i);
			registerNamedEntitySpawner(slimeType, sizeText + "SLIME");
			final SlimeSpawner magmaType = new SlimeSpawner(EntityType.MAGMA_CUBE, i);
			registerNamedEntitySpawner(magmaType, sizeText + "LAVASLIME", sizeText + "MAGMACUBE", sizeText + "_MAGMACUBE");
		}
		// Villager
		for (final Villager.Profession profession : Villager.Profession.values())
			registerNamedEntitySpawner(new VillagerSpawner(profession));
		// Wolf
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.WOLF)
		{

			@Override
			public String getName()
			{
				return "ANGRY_WOLF";
			}

			@Override
			public Wolf spawn(final Location location)
			{
				final Wolf wolf = (Wolf) super.spawn(location);
				wolf.setAngry(true);
				return wolf;
			}
		}, "ANGRYWOLF");
		// Zombie
		registerNamedEntitySpawner(new DefaultSpawner(EntityType.ZOMBIE)
		{

			@Override
			public String getName()
			{
				return "ZOMBIE_VILLAGER";
			}

			@Override
			public Zombie spawn(final Location location)
			{
				final Zombie zombie = (Zombie) super.spawn(location);
				zombie.setVillager(true);
				return zombie;
			}
		});
	}

	public static void registerNamedEntitySpawner(final NamedEntitySpawner entitySpawner, final String... aliases)
	{
		if (entitySpawner == null)
			throw new IllegalArgumentException("EntitySpawner cannot be null!");
		if (entitySpawner.getName() == null)
			throw new IllegalArgumentException("EntitySpawner's name cannot be null (" + entitySpawner + ")!");
		NAMEDENTITYSPAWNERS.put(entitySpawner.getName().toUpperCase(), entitySpawner);
		for (final String alias : aliases)
			if (alias != null)
				NAMEDENTITYSPAWNERS.put(alias.toUpperCase(), entitySpawner);
	}

	public static NamedEntitySpawner getNamedEntitySpawner(final String name)
	{
		if (name == null)
			return null;
		else
			return NAMEDENTITYSPAWNERS.get(name.toUpperCase());
	}

	public static List<NamedEntitySpawner> getNamedEntitySpawnerList(final Collection<String> names)
	{
		if (names == null)
			return new ArrayList<NamedEntitySpawner>(0);
		final List<NamedEntitySpawner> res = new ArrayList<NamedEntitySpawner>(names.size());
		for (final String name : names)
			res.add(getNamedEntitySpawner(name));
		return res;
	}

	protected NamedEntitySpawnerHelper()
	{
	}

	private final static class BabySpawner extends DefaultSpawner
	{

		public BabySpawner(final EntityType type)
		{
			super(type);
		}

		@Override
		public String getName()
		{
			return "BABY_" + super.getName();
		}

		@Override
		public Ageable spawn(final Location location)
		{
			final Ageable ageable = (Ageable) super.spawn(location);
			ageable.setBaby();
			return ageable;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Ageable)
			{
				final Ageable ageable = (Ageable) entity;
				return !ageable.isAdult();
			}
			else
				return false;
		}
	}

	private final static class HorseColorSpawner extends DefaultSpawner
	{

		private final Horse.Color color;

		public HorseColorSpawner(final Horse.Color color)
		{
			super(EntityType.HORSE);
			this.color = color;
		}

		@Override
		public String getName()
		{
			return color.name() + "_" + super.getName();
		}

		@Override
		public Horse spawn(final Location location)
		{
			final Horse horse = (Horse) super.spawn(location);
			horse.setColor(color);
			return horse;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Horse)
			{
				final Horse horse = (Horse) entity;
				return horse.getColor() == color;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; color: " + color.name() + "}";
		}
	}

	private final static class HorseVariantSpawner extends DefaultSpawner
	{

		private final Horse.Variant variant;

		public HorseVariantSpawner(final Horse.Variant variant)
		{
			super(EntityType.HORSE);
			this.variant = variant;
		}

		@Override
		public String getName()
		{
			return variant.name();
		}

		@Override
		public Horse spawn(final Location location)
		{
			final Horse horse = (Horse) super.spawn(location);
			horse.setVariant(variant);
			return horse;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Entity)
			{
				final Horse horse = (Horse) entity;
				return horse.getVariant() == variant;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; variant: " + variant.name() + "}";
		}
	}

	// Sheep
	private final static class SheepSpawner extends DefaultSpawner
	{

		private final DyeColor color;

		public SheepSpawner(final DyeColor color)
		{
			super(EntityType.SHEEP);
			this.color = color;
		}

		@Override
		public String getName()
		{
			return color.name() + "_SHEEP";
		}

		@Override
		public Sheep spawn(final Location location)
		{
			final Sheep sheep = (Sheep) super.spawn(location);
			sheep.setColor(color);
			return sheep;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Entity)
			{
				final Sheep sheep = (Sheep) entity;
				return sheep.getColor() == color;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; color: " + color.name() + "}";
		}
	}

	// Skeleton
	private final static class SkeletonSpawner extends DefaultSpawner
	{

		private final Skeleton.SkeletonType variant;

		public SkeletonSpawner(final Skeleton.SkeletonType variant)
		{
			super(EntityType.SKELETON);
			this.variant = variant;
		}

		@Override
		public String getName()
		{
			return variant.name() + "_" + super.getName();
		}

		@Override
		public Skeleton spawn(final Location location)
		{
			final Skeleton skeleton = (Skeleton) super.spawn(location);
			skeleton.setSkeletonType(variant);
			return skeleton;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Entity)
			{
				final Skeleton skeleton = (Skeleton) entity;
				return skeleton.getSkeletonType() == variant;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; variant: " + variant.name() + "}";
		}
	}

	// Slime
	private static class SlimeSpawner extends DefaultSpawner
	{

		private final static String[] SIZES = new String[] { "TINY", "SMALL", "DEFAULT", "LARGE", "HUGE", "TINYGIANT", "SMALLGIANT", "GIANT", "LARGEGIANT", "HUGEGIANT" };
		private final static int SIZECOUNT = SIZES.length;
		private final int size;

		public static String getSizeText(final int size)
		{
			return SIZES[size - 1];
		}

		public SlimeSpawner(final EntityType slimeType, final int size)
		{
			super(slimeType);
			this.size = size;
		}

		@Override
		public String getName()
		{
			return getSizeText() + "_" + super.getName();
		}

		public final String getSizeText()
		{
			return getSizeText(size);
		}

		@Override
		public Slime spawn(final Location location)
		{
			final Slime slime = (Slime) super.spawn(location);
			slime.setSize(size);
			return slime;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Entity)
			{
				final Slime slime = (Slime) entity;
				return slime.getSize() == size;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; size: " + size + "}";
		}
	}

	// Villager
	private final static class VillagerSpawner extends DefaultSpawner
	{

		private final Villager.Profession variant;

		public VillagerSpawner(final Villager.Profession variant)
		{
			super(EntityType.VILLAGER);
			this.variant = variant;
		}

		@Override
		public String getName()
		{
			return variant.toString();
		}

		@Override
		public Villager spawn(final Location location)
		{
			final Villager villager = (Villager) super.spawn(location);
			villager.setProfession(variant);
			return villager;
		}

		@Override
		public boolean matches(final Entity entity)
		{
			if (super.matches(entity) && entity instanceof Entity)
			{
				final Villager villager = (Villager) entity;
				return villager.getProfession() == variant;
			}
			else
				return false;
		}

		@Override
		public String toString()
		{
			return getClass().getSimpleName() + "{type: " + type.name() + "; profession: " + variant.name() + "}";
		}
	}
}


text:
package com.blogspot.sontx.badspy.badserver.bo;

import com.blogspot.sontx.badspy.badserver.Config;
import com.blogspot.sontx.badspy.badserver.bean.SpyDataHeader;
import com.blogspot.sontx.jlog.Log;

import java.io.IOException;
import java.io.InputStream;

public class SpyReader {
    private InputStream in;

    public SpyReader(InputStream in) {
        this.in = in;
    }

    private boolean waitForAvailable(int timeout) throws IOException {
        long startMillis = System.currentTimeMillis();
        while ((in.available() == 0) && (System.currentTimeMillis() - startMillis < timeout)) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                break;
            }
        }
        return in.available() > 0;
    }

    public int read(byte[] buffer, int offset, int length, int timeout) throws IOException {
        int receivedBytes = 0;
        while (receivedBytes < length && waitForAvailable(timeout)) {
            receivedBytes += in.read(buffer, offset + receivedBytes, length - receivedBytes);
        }
        return receivedBytes;
    }

    public int read(byte[] buffer, int offset, int length) throws IOException {
        Log.d(String.format("Read %d bytes...", length));
        return read(buffer, offset, length, Config.READ_TIMEOUT);
    }

    public int read(byte[] buffer) throws IOException {
        return read(buffer, 0, buffer.length);
    }

    public SpyDataHeader readHeader() throws IOException {
        byte[] buffer = new byte[5];
        return read(buffer) == buffer.length ? SpyDataHeader.parse(buffer) : null;
    }

    public int readFlag() throws IOException {
        return waitForAvailable(Config.READ_TIMEOUT) ? in.read() : -1;
    }
}