text:
// @file InterFace.cpp

#include <algorithm>
#include "jhpcndf.h"
#include "Utility.h"
#include "FileInfoManager.h"
#include "Encoder.h"
#include "Decoder.h"
#include "IO.h"
#ifdef TIME_MEASURE
#include <omp.h>
#endif

//
// implementation of C++ Interface routines
//
namespace JHPCNDF
{
  namespace
  {
    template <typename T>
      size_t fwrite_helper(const T* data, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap)
      {
#ifdef TIME_MEASURE
        double t0=0.0;
        double t1=0.0;
        if(time_measuring)
        {
          t0=omp_get_wtime();
        }
#endif
        size_t output_size=0;
        T* work_upper = NULL;
        T* work_lower = NULL;
        try
        {
          work_upper = new T[nmemb];
        }
        catch (std::bad_alloc)
        {
          std::cerr<<"can't allocate working memory for encode"<<std::endl;
          return 0;
        }

        FILE* fp_lower= FileInfoManager::GetInstance().get_lower_file_pointer(key);
        if(fp_lower != NULL)
        {
          try
          {
            work_lower = new T[nmemb];
          }
          catch (std::bad_alloc)
          {
            std::cerr<<"can't allocate working memory for encode"<<std::endl;
            delete [] work_upper;
            return 0;
          }
        }

#ifdef TIME_MEASURE
        if(time_measuring)
        {
          t1=omp_get_wtime()-t0;
          std::cerr<<"elapsed time for initialize: "<<t1<<" sec"<<std::endl;
          t0=omp_get_wtime();
        }
#endif
        // encode関数内部で計時しているので、この部分は計時しない
        encode<T>(nmemb, data, work_upper, work_lower, tolerance, is_relative, enc, time_measuring);
#ifdef TIME_MEASURE
        if(time_measuring)
        {
          t0=omp_get_wtime();
        }
#endif
        FILE* fp_upper = FileInfoManager::GetInstance().get_upper_file_pointer(key);
        if(byte_swap)
        {
          convert_endian<sizeof(T)>((char*)work_upper, nmemb);
        }
        FileInfoManager& FIM=FileInfoManager::GetInstance();
        IO* io=IOFactory(FIM.get_compression_method(key), FIM.get_buff_size(key));
        output_size=io->fwrite(work_upper, size, nmemb, fp_upper);
#ifdef TIME_MEASURE
        if(time_measuring)
        {
          t1=omp_get_wtime()-t0;
          std::cerr<<"elapsed time for output: "<<t1<<" sec"<<std::endl;
          t0=omp_get_wtime();
        }
#endif
        if(fp_lower != NULL)
        {
          if(byte_swap)
          {
            convert_endian<sizeof(T)>((char*)work_lower, nmemb);
          }
          io->fwrite(work_lower, size, nmemb, fp_lower);
#ifdef TIME_MEASURE
          if(time_measuring)
          {
            t1=omp_get_wtime()-t0;
            std::cerr<<"elapsed time for output lower bits: "<<t1<<" sec"<<std::endl;
          }
#endif
        }
        delete [] work_lower;
        delete [] work_upper;
        delete io;
        return output_size;
      }

    template <typename T>
      size_t fread_helper(T *data, size_t size, const int& key, const bool& byte_swap)
      {
        FileInfoManager& FIM=FileInfoManager::GetInstance();
        IO* io=IOFactory(FIM.get_compression_method(key), FileInfoManager::GetInstance().get_buff_size(key));
        FILE* fp_upper = FileInfoManager::GetInstance().get_upper_file_pointer(key);
        size_t read_size=io->fread(data, sizeof(T), size, fp_upper);

        FILE* fp_lower= FileInfoManager::GetInstance().get_lower_file_pointer(key);
        if(fp_lower!=NULL)
        {
          T* work;
          T* lower;
          try
          {
            work=new T [size];
          }
          catch (std::bad_alloc)
          {
            std::cerr<<"can't allocate working memory for decode"<<std::endl;
            return read_size;
          }
          try
          {
            lower=new T [size];
          }
          catch (std::bad_alloc)
          {
            std::cerr<<"can't allocate working memory for decode"<<std::endl;
            delete lower;
            return read_size;
          }
          io->fread(lower, sizeof(T), size, fp_lower);
          decode<T>(size, data, lower, work);
          delete lower;
          for(size_t i=0;i<size;i++)
          {
            data[i]=work[i];
          }
          delete work;
        }
        delete io;
        if(byte_swap)
        {
          convert_endian<sizeof(T)>((char*)data, size);
        }
        return read_size;
      }
  }//end of unnamed namespace

  int fopen(const std::string& filename_upper, const std::string& filename_lower, const char* mode, const std::string& comp, const size_t& buff_size)
  {
    return FileInfoManager::GetInstance().create_new_entry(filename_upper, filename_lower, -1, mode, comp, buff_size);
  }
  void fclose(const int& key)
  {
    FileInfoManager::GetInstance().destroy_entry(key);
  }

  template <typename T>
    size_t fwrite(const T* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap)
    {
      FileInfoManager& FIM=FileInfoManager::GetInstance();
      FILE* fp_upper = FIM.get_upper_file_pointer(key);
      T* work;
      if(byte_swap)
      {
        work = new T[nmemb];
        for(int i =0; i<nmemb; i++)
        {
          work[i]=ptr[i];
        }
        convert_endian<sizeof(T)>((char*)work, nmemb);
      }else{
        work=const_cast<T *>(ptr);
      }

      IO* io=IOFactory(FIM.get_compression_method(key), FIM.get_buff_size(key));
      const size_t output_size=io->fwrite(work, size, nmemb, fp_upper);

      FILE* fp_lower= FileInfoManager::GetInstance().get_lower_file_pointer(key);
      if(fp_lower != NULL)
      {
        io->fwrite(work, size, nmemb, fp_lower);
      }
      delete io;
      return output_size;
    }
  template <>
    size_t fwrite(const float* ptr, size_t size, size_t nmemb,  const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap)
    {
      return fwrite_helper(ptr, size, nmemb, key, tolerance, is_relative, enc, time_measuring, byte_swap);
    }
  template <>
    size_t fwrite(const double* ptr, size_t size, size_t nmemb,  const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap)
    {
      return fwrite_helper(ptr, size, nmemb, key, tolerance, is_relative, enc, time_measuring, byte_swap);
    }

  template <typename T>
    size_t fread(T* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap)
    {
      FileInfoManager& FIM=FileInfoManager::GetInstance();
      //seek位置を保存
      FILE* fp_upper = FIM.get_upper_file_pointer(key);
      long org_upper_position=ftell(fp_upper);

      //先頭2byte分を読み込んでヘッダを判定(gzip or not)
      unsigned char work[2];
      if(::fread(work, 1, 2, fp_upper)!=2)
      {
        std::cerr<<"upper bits file read failed"<<std::endl;
      }
      fseek(fp_upper, org_upper_position, 0);

      //読み込んだヘッダを元にIOクラスを作成
      IO* io;
      if(work[0]==0x1f && work[1] == 0x8b)
      {
        io=IOFactory("gzip", FIM.get_buff_size(key));
      }else{
        io=IOFactory("stdio", FIM.get_buff_size(key));
      }

      size_t read_size=io->fread(ptr, size, nmemb, fp_upper);
      if(byte_swap)
      {
        convert_endian<sizeof(T)>((char*)ptr, size);
      }
      delete io;
      return 0;
    }

  template <>
    size_t fread(float* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap)
    {
      return fread_helper(ptr, nmemb, key, byte_swap);
    }
  template <>
    size_t fread(double* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap)
    {
      return fread_helper(ptr, nmemb, key, byte_swap);
    }

  template <typename T>
    void encode(const size_t& length, const T* const src, T* const dst, T* const dst_lower, const float& tolerance, const bool& is_relative, const std::string& enc, const bool time_measuring)
    {
#ifdef TIME_MEASURE
      double t0=0.0;
      double t1=0.0;
      if(time_measuring)
      {
        t0=omp_get_wtime();
      }
#endif
      Encoder<T>* tmp=EncoderFactory<T>(enc, tolerance, is_relative);
      Encoder<T>& encoder = *tmp;
      encoder(length, src, dst, dst_lower);
#ifdef TIME_MEASURE
      if(time_measuring)
      {
        t1=omp_get_wtime()-t0;
        std::cerr<<"elapsed time for encode: "<<t1<<" sec"<<std::endl;
      }
#endif
      delete tmp;
    }

  template <typename T>
    void decode(const size_t& length, const T* const src_upper, const T* const src_lower, T* const dst)
    {
      Decoder<T> decoder;
      decoder(length, src_upper, src_lower, dst);
    }
}//end of namespace JHPCNDF

//
// implementation of C Interface routines
//
int JHPCNDF_fopen(const char* filename_upper, const char* filename_lower, const char* mode, const char* comp, const size_t buff_size)
{
  return JHPCNDF::fopen(filename_upper, filename_lower, mode, comp, buff_size);
}
void JHPCNDF_fclose(const int key)
{
  JHPCNDF::fclose(key);
}

size_t JHPCNDF_fwrite_float(const float* ptr, size_t size, size_t nmemb, const int key, const float tolerance, const int is_relative, const char* enc)
{
  return JHPCNDF::fwrite(ptr, size, nmemb, key, tolerance, is_relative, enc);
}
size_t JHPCNDF_fwrite_double(const double *ptr, size_t size, size_t nmemb, const int key, const float tolerance, const int is_relative, const char* enc)
{
  return JHPCNDF::fwrite(ptr, size, nmemb, key, tolerance, is_relative, enc);
}
size_t JHPCNDF_fwrite(const void *ptr, size_t size, size_t nmemb, const int key, const char* enc)
{
  return JHPCNDF::fwrite((char*)ptr, 1, size*nmemb, key, 0.1, enc);
}
size_t JHPCNDF_fread_float(float* ptr, size_t size, size_t nmemb, const int key)
{
  return JHPCNDF::fread(ptr, size, nmemb, key);
}
size_t JHPCNDF_fread_double(double *ptr, size_t size, size_t nmemb, const int key)
{
  return JHPCNDF::fread(ptr, size, nmemb, key);
}
size_t JHPCNDF_fread(void *ptr, size_t size, size_t nmemb, const int key)
{
  return JHPCNDF::fread((char*)ptr, 1, size*nmemb, key);
}
void JHPCNDF_encode_float(const size_t length, const float* const src, float* const dst, float* const dst_lower, const float tolerance, const int is_relative, const char* enc)
{
  JHPCNDF::encode<float>(length, src, dst, dst_lower, tolerance, is_relative, enc);
}
void JHPCNDF_encode_double(const size_t length, const double* const src, double* const dst, double* const dst_lower, const float tolerance, const int is_relative, const char* enc)
{
  JHPCNDF::encode<double>(length, src, dst, dst_lower, tolerance, is_relative, enc);
}
void JHPCNDF_decode_float(const size_t length, const float* const src_upper, const float* const src_lower, float* const dst)
{
  JHPCNDF::decode<float>(length, src_upper, src_lower, dst);
}
void JHPCNDF_decode_double(const size_t length, const double* const src_upper, const double* const src_lower, double* const dst)
{
  JHPCNDF::decode<double>(length, src_upper, src_lower, dst);
}

//
// implementation of Fortran Interface routines
//
extern "C"
{
  //subroutine jhpcndf_open(unit, ufile, lfile, action, comp, buff_size)
  void jhpcndf_open__(int* unit, const char* ufile, const char* lfile, const char* action, const char* comp, const size_t* buff_size)
  {
    std::string mode(action);
    std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower);
    mode=mode=="write"?"w+b":"rb";
    *unit = JHPCNDF::fopen(ufile, lfile, mode.c_str(), comp, *buff_size);
  }

  //subroutine jhpcndf_close(unit)
  void jhpcndf_close__(int* unit)
  {
    JHPCNDF::fclose(*unit);
  }

  //subroutine jhpcndf_write_real4(unit, recl, data, tol, enc)
  void jhpcndf_write_real4__(int* unit, size_t* recl, float* data, float* tolerance, bool* is_relative, const char* enc)
  {
    JHPCNDF::fwrite(data, sizeof(float), *recl, *unit, *tolerance, *is_relative, enc);
  }
  //subroutine jhpcndf_write_real8(unit, recl, data, tol, enc)
  void jhpcndf_write_real8__(int* unit, size_t* recl, float* data, float* tolerance, bool* is_relative, const char* enc)
  {
    JHPCNDF::fwrite(data, sizeof(double), *recl, *unit, *tolerance, *is_relative, enc);
  }
  //subroutine jhpcndf_write_integer4(unit, recl, data, tol, enc)
  void jhpcndf_write_integer4__(int* unit, size_t* recl, int* data, float* tolerance, const char* enc)
  {
    JHPCNDF::fwrite(data, 1, (*recl)*4, *unit, *tolerance, 1, enc);
  }
  //subroutine jhpcndf_write_integer8(unit, recl, data, tol, enc)
  void jhpcndf_write_integer8__(int* unit, size_t* recl, long long* data, float* tolerance, const char* enc)
  {
    JHPCNDF::fwrite(data, 1, (*recl)*8, *unit, *tolerance, 1, enc);
  }
  //subroutine jhpcndf_write_character(unit, recl, data, tol, enc)
  void jhpcndf_write_character__(int* unit, size_t* recl, char* data, float* tolerance, const char* enc)
  {
    JHPCNDF::fwrite(data, 1, *recl, *unit, *tolerance, 1, enc);
  }
  //subroutine jhpcndf_read_real4(unit, recl, data)
  void jhpcndf_read_real4__(int* unit, size_t* recl, float* data)
  {
    JHPCNDF::fread(data, 4, *recl, *unit);
  }
  //subroutine jhpcndf_read_real8(unit, recl, data)
  void jhpcndf_read_real8__(int* unit, size_t* recl, double* data)
  {
    JHPCNDF::fread(data, 8, *recl, *unit);
  }
  //subroutine jhpcndf_read_integer4(unit, recl, data)
  void jhpcndf_read_integer4__(int* unit, size_t* recl, int* data)
  {
    JHPCNDF::fread(data, 4, *recl, *unit);
  }
  //subroutine jhpcndf_read_integer8(unit, recl, data)
  void jhpcndf_read_integer8__(int* unit, size_t* recl, long long* data)
  {
    JHPCNDF::fread(data, 8, *recl, *unit);
  }
  //subroutine jhpcndf_read_character(unit, recl, data)
  void jhpcndf_read_character__(int* unit, size_t* recl, char* data)
  {
    JHPCNDF::fread(data, 1, *recl, *unit);
  }

  void jhpcndf_encode_real4__(const size_t* length, const float* const src, float* const dst, float* const dst_lower, const float* tolerance, bool* is_relative, const char* enc)
  {
    JHPCNDF::encode<float>(*length, src, dst, dst_lower, *tolerance, *is_relative, enc);
  }
  void jhpcndf_encode_real8__(const size_t* length, const double* const src, double* const dst, double* const dst_lower, const float* tolerance, bool* is_relative, const char* enc)
  {
    JHPCNDF::encode<double>(*length, src, dst, dst_lower, *tolerance, *is_relative, enc);
  }
  void jhpcndf_decode_real4__(const size_t* length, const float* const src_upper, const float* const src_lower, float* const dst)
  {
    JHPCNDF::decode<float>(*length, src_upper, src_lower, dst);
  }
  void jhpcndf_decode_real8__(const size_t* length, const double* const src_upper, const double* const src_lower, double* const dst)
  {
    JHPCNDF::decode<double>(*length, src_upper, src_lower, dst);
  }
}

//
// explicit instantiation
//
namespace JHPCNDF
{
  template
    size_t fwrite<bool>(const bool* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<char>(const char* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<unsigned char>(const unsigned char* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<signed char>(const signed char* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<short>(const short* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<unsigned short>(const unsigned short* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<int>(const int* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc,  const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<unsigned int>(const unsigned int* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<long>(const long* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);
  template
    size_t fwrite<unsigned long>(const unsigned long* ptr, size_t size, size_t nmemb, const int& key, const float& tolerance, const bool& is_relative, const std::string& enc, const bool& time_measuring, const bool& byte_swap);

  template
    size_t fread<char>(char* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);
  template
    size_t fread<unsigned char>(unsigned char* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);
  template
    size_t fread<int>(int* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);
  template
    size_t fread<unsigned int>(unsigned int* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);
  template
    size_t fread<long>(long* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);
  template
    size_t fread<unsigned long>(unsigned long* ptr, size_t size, size_t nmemb, const int& key, const bool& byte_swap);

  template
    void encode<float>(const size_t& length, const float* const src, float* const dst, float* const dst_lower, const float& tolerance, const bool& is_relative, const std::string& enc, const bool time_measuring);
  template
    void encode<double>(const size_t& length, const double* const src, double* const dst, double* const dst_lower, const float& tolerance, const bool& is_relative, const std::string& enc, const bool time_measuring);

  template
    void decode<float>(const size_t& length, const float* const src_upper, const float* const src_lower, float* const dst);
  template
    void decode<double>(const size_t& length, const double* const src_upper, const double* const src_lower, double* const dst);
}//end of namespace JHPCNDF


text:
#include <csignal>

#include <thread>

#include "utils/common.h"
#include "utils/logger.h"
#include "utils/global.h"
#include "utils/scopeguard.h"
#include "collector/ctpmarketdatacollector.h"

namespace {

volatile std::sig_atomic_t is_running;

}  // namespace

extern "C" void signal_handler(int signal) {
    ILOG("Detect signal:{}", signal);
    is_running = 0;
}

int32 main(int32 argc, char** argv) {
    is_running = 1;
    std::signal(SIGTERM, signal_handler);
    std::signal(SIGINT, signal_handler);

    logger::initLogger();
    auto guard = utils::make_guard([] { logger::releaseLogger(); });

    int32 result = 0;

    CtpMarketDataCollector collector;

    result = collector.loadConfig(argc, argv);
    if (result != 0) {
        ELOG("Collector load config failed! Result:{}", result);
        return -1;
    }
    ILOG("Collector load config success!");

    result = collector.createPath();
    if (result != 0) {
        ELOG("Collector create path failed! Result:{}", result);
        return -2;
    }
    ILOG("Collector create path success!");

    result = collector.init();
    if (result != 0) {
        ELOG("Collector init failed! Result:{}", result);
        return -3;
    }
    ILOG("Collector init success!");

    result = collector.start();
    if (result != 0) {
        ELOG("Collector start failed! Result:{}", result);
        return -4;
    }
    ILOG("Collector start success!");

    while (is_running) {
        if (global::need_reconnect.load(std::memory_order_relaxed)) {
            auto result = collector.reConnect();
            if (result == 0) {
                ILOG("Collector reconnet success!");
            }
        }
		using namespace std::chrono_literals;
        std::this_thread::sleep_for(10s);//
    }
    ILOG("Collector try stop");
    result = collector.stop();
    ILOG("Collector is not running, exited! Result:{}", result);

    return result;
}

redpajama_set_name: RedPajamaGithub


text:
package com.coolweather.app.activity;

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

import com.coolweather.app.R;
import com.coolweather.app.db.CoolWeatherDBUtil;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import com.coolweather.app.util.VWConsts;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Ñ¡ÔñµØÇøActivity
 * @author zhangkcode
 * @createDate 20170428
 */
public class ChooseAreaActivity extends Activity{
	private TextView textView = null;
	private ListView listView = null;
	ArrayAdapter<String> adapter = null;
	private List<String> dataList = new ArrayList<String>();
	//0Ê¡ 1ÊÐ 2ÏØ
	private int currentLevel = 0;
	private CoolWeatherDBUtil DBUtil;
	private ProgressDialog dialog = null;
	private Province selectedProvince;
	private City selectedCity;
	private County selectedCounty;
	private List<Province> provinceList;
	private List<City> cityList;
	private List<County> countyList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);

		initComponent();
	}
	/**
	 * ³õ'»¯¿Ø¼þ
	 */
	private void initComponent(){
		textView = (TextView) findViewById(R.id.title_text);
		listView = (ListView) findViewById(R.id.list_view);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
		queryAreaData(currentLevel,-1);
		listView.setAdapter(adapter);
		//µã»÷'þ
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(currentLevel == 0){
					selectedProvince =  (Province) provinceList.get(position);
					queryAreaData(1,selectedProvince.getId());
				}else if(currentLevel == 1){
					selectedCity = (City) cityList.get(position);
					queryAreaData(2,selectedCity.getId());
				}else if(currentLevel == 2){
					selectedCounty = (County)countyList.get(position);
					Intent intent = new Intent (ChooseAreaActivity.this,WeatherActivity.class);
					intent.putExtra("weatherId", selectedCounty.getWeather_id());
					startActivity(intent);
					finish();
				}

			}
		});
	}
	/**
	 * ²éѯµØÓòÊý¾Ýµ±±¾µØÊý¾Ý¿âÎÞÊý¾Ýʱ´Ó·þÎñÆ÷ÖлñÈ¡
	 */
	private void queryAreaData(int levelFlag,int parentId){
		DBUtil = CoolWeatherDBUtil.getInstance(this);
		switch(levelFlag){
		 //µ±Ç°ÎªÊ¡¼¶
		 case 0:
			 textView.setText("Öйú");
			 provinceList = DBUtil.queryProvinceList();
			 if(provinceList != null && provinceList.size()>0){
				dataList.clear();
				for(Province province :provinceList){
					dataList.add(province.getName());
				}
				adapter.notifyDataSetChanged();
			 }else{
				 queryAreaDataFromServer(levelFlag,-1);
			 }
			 break;
	     //µ±Ç°ÎªÊм¶
		 case 1:
			 currentLevel = 1;
			 textView.setText(selectedProvince.getName());
			 cityList = DBUtil.queryCityList(parentId);
			 if(cityList != null && cityList.size()>0){
				dataList.clear();
				for(City city :cityList){
					dataList.add(city.getName());
				}
				adapter.notifyDataSetChanged();
			 }else{
				 queryAreaDataFromServer(levelFlag,parentId);
			 }
			 break;
	     //µ±Ç°ÎªÏؼ¶
		 case 2:
			 currentLevel = 2;
			 textView.setText(selectedCity.getName());
             countyList = DBUtil.queryCountyList(parentId);
             if(countyList != null && countyList.size() > 0){
            	 dataList.clear();
            	 for(County county : countyList){
            		 dataList.add(county.getName());
            	 }
            	 adapter.notifyDataSetChanged();
             }else{
            	 queryAreaDataFromServer(levelFlag, parentId);
             }
			 break;
	     default:
	    	 break;
		}

	}
	/**
	 * ´Ó·þÎñÆ÷²éѯÇøÓòÊý¾Ý
	 */
	private void queryAreaDataFromServer(final int levelFlag,final int parentId){
		showProgressDialog();
		switch(levelFlag){
		//²éѯʡ¼¶Êý¾Ý
	     case 0:
			   HttpUtil.sendHttpRequest(VWConsts.NET_ADDRESS, new HttpCallbackListener() {

					@Override
					public void onFinish(String response) {
						if(Utility.parsePronvinceData(response, DBUtil)){
							runOnUiThread(new Runnable() {
								public void run() {
									queryAreaData(levelFlag,-1);
								}
							});
							closeProgressDialog();
						}
					}

					@Override
					public void onError(Exception e) {
						closeProgressDialog();
						e.printStackTrace();
					}
				});
	    	 break;
	    //²éѯÊм¶Êý¾Ý
	     case 1:
			   HttpUtil.sendHttpRequest(VWConsts.NET_ADDRESS+"/"+selectedProvince.getCode(), new HttpCallbackListener() {

					@Override
					public void onFinish(String response) {
						if(Utility.parseCityData(response, DBUtil, parentId)){
							runOnUiThread(new Runnable() {
								public void run() {
									queryAreaData(levelFlag,parentId);
								}
							});
							closeProgressDialog();
						}
					}

					@Override
					public void onError(Exception e) {
						closeProgressDialog();
						e.printStackTrace();
					}
				});
	    	   break;
	     //²éѯÏؼ¶Êý¾Ý
	     case 2:
  			   HttpUtil.sendHttpRequest(VWConsts.NET_ADDRESS+"/"+selectedProvince.getCode()+"/"+selectedCity.getCode(), new HttpCallbackListener() {

  					@Override
  					public void onFinish(String response) {
  						if(Utility.parseCountyData(response, DBUtil, parentId)){
  							runOnUiThread(new Runnable() {
								public void run() {
									queryAreaData(levelFlag,parentId);
								}
							});
  							closeProgressDialog();
  						}
  					}

  					@Override
  					public void onError(Exception e) {
  						closeProgressDialog();
  						e.printStackTrace();
  						Toast.makeText(ChooseAreaActivity.this, "¼ÓÔØʧ°Ü£¡", Toast.LENGTH_SHORT).show();
  					}
  				});
	    	 break;
	     default:
				break;
		}
	}
	/**
	 * չʾProgressDialog
	 */
   private void showProgressDialog(){
		dialog = new ProgressDialog(ChooseAreaActivity.this);
		dialog.setMessage("ÕýÔÚ¼ÓÔØÖÐ...");
		dialog.show();
   }
   /**
    * ¹Ø±ÕProgressDialog
    */
   private void closeProgressDialog(){
	   if(dialog != null){
		   dialog.dismiss();
	   }
   }
   /**
    * ÖØдonBackPressed·½·¨
    */
   @Override
public void onBackPressed() {
   switch(currentLevel){
	   case 0:
		    finish();
		    break;
	   case 1:
		   currentLevel = 0;
		   queryAreaData(currentLevel,-1);
		   break;
	   case 2:
		   currentLevel = 1;
		   queryAreaData(currentLevel, selectedProvince.getCode());
		   break;
	   default:
		   finish();
		   break;
   }
}

}


text:
package com.koch.ambeth.cache.datachange.revert;

import java.util.Objects;

import com.koch.ambeth.util.typeinfo.ITypeInfoItem;

public class ObjectBackup implements IBackup {
	protected final ITypeInfoItem[] allMembers;

	protected final Object[] values;

	public ObjectBackup(ITypeInfoItem[] allMembers, Object[] values) {
		this.allMembers = allMembers;
		this.values = values;
	}

	@Override
	public void restore(Object target) {
		for (int b = allMembers.length; b-- > 0;) {
			Object originalValue = values[b];
			if (originalValue instanceof IBackup) {
				((IBackup) originalValue).restore(target);
				continue;
			}
			ITypeInfoItem member = allMembers[b];
			if (!Objects.equals(member.getValue(target), originalValue)) {
				member.setValue(target, originalValue);
			}
		}
	}
}


text:
<?php

// carga libreria para manejo de cache
Load::lib('cache');

/**
 * Consola para manejar la cache
 *
 * @category   Kumbia
 * @package    Console
 */
class CacheConsole
{

    /**
     * Comando de consola para limpiar la cache
     *
     * @param array $params parametros nombrados de la consola
     * @param string $group nombre de grupo
     * @throw KumbiaException
     */
    public function clean($params, $group = '')
    {
        // obtiene el driver de cache
        $cache = $this->setDriver($params);

        // limpia la cache
        if ($cache->clean($group)) {
            if ($group) {
                echo "-> Se ha limpiado el grupo $group", PHP_EOL;
            } else {
                echo "-> Se ha limpiado la cache", PHP_EOL;
            }
        } else {
            throw new KumbiaException('No se ha logrado eliminar el contenido de la cache');
        }
    }

    /**
     * Comando de consola para eliminar un elemento cacheado
     *
     * @param array $params parametros nombrados de la consola
     * @param string $id id del elemento
     * @param string $group nombre de grupo
     * @throw KumbiaException
     */
    public function remove($params, $id, $group = 'default')
    {
        // obtiene el driver de cache
        $cache = $this->setDriver($params);

        // elimina el elemento
        if ($cache->remove($id, $group)) {
            echo '-> Se ha eliminado el elemento de la cache', PHP_EOL;
        } else {
            throw new KumbiaException("No se ha logrado eliminar el elemento \"$id\" del grupo \"$group\"");
        }
    }

    /**
     * Devuelve una instancia de cache del driver pasado
     *
     * @param array $params parametros nombrados
     */
    private function setDriver($params)
    {
        if (isset($params['driver'])) {
            return Cache::driver($params['driver']);
        }
        return Cache::driver();

    }

}


text:
<?

# XXX Lots here copied from elsewhere... Damn you deadlines.

include_once 'min-init.php';
include_once INCLUDESPATH . 'easyparliament/member.php';
include_once '../api/api_functions.php';

$pid = $_GET['pid'];

$db = new ParlDB;
$q = $db->query("select * from member
	where house=1 and person_id = '" . mysql_escape_string($pid) . "'
	order by left_house desc limit 1");
if (!$q->rows()) {
	print '<error>Unknown ID</error>'; exit;
}

$row = $q->row(0);
$row['full_name'] = member_full_name($row['house'], $row['title'], $row['first_name'],
	$row['last_name'], $row['constituency']);
if (isset($parties[$row['party']]))
	$row['party'] = $parties[$row['party']];
list($image,$sz) = find_rep_image($row['person_id'], true);
if ($image) $row['image'] = $image;

$q = $db->query("SELECT position,dept FROM moffice WHERE to_date='9999-12-31'
	and source='chgpages/selctee' and person=" .
	mysql_escape_string($pid) . ' ORDER BY from_date DESC');
for ($i=0; $i<$q->rows(); $i++) {
	$row['selctee'][] = prettify_office($q->field($i, 'position'), $q->field($i, 'dept'));
}

/*
$q = $db->query("SELECT title,chairman from pbc_members,bills where member_id=".$row['member_id']
	. ' and bill_id=bills.id');
for ($i=0; $i<$q->rows(); $i++) {
	$member = 'Member';
	if ($q->field($i, 'chairman')) {
		$member = 'Chairman';
	}
	$row['selctee'][] = $member . ', ' . $q->field($i, 'title');
}
*/

$q = $db->query("select data_key, data_value from personinfo
	where data_key like 'public\_whip%' and person_id = '" . mysql_escape_string($pid) . "'
	order by data_key"); # order so both_voted is always first...
$none = false;
$output = array();
for ($i=0; $i<$q->rows(); $i++) {
	$key = str_replace(array('public_whip_dreammp', '_distance'), '', $q->field($i, 'data_key'));
	if (preg_match('#_absent$#', $key)) continue;
	if ($none) {
		$none = false;
		$output[$key] = -1;
		continue;
	}
	$value = $q->field($i, 'data_value');
	if (preg_match('#_both_voted$#', $key)) {
	       	if ($value == 0) $none = true;
		continue;
	}
	$output[$key] = $value;
}
$pw = '
';
display_dream_comparison(996, "a transparent Parliament");
display_dream_comparison(811, "introducing a smoking ban");
display_dream_comparison(230, "introducing ID cards", true);
display_dream_comparison(363, "introducing foundation hospitals");
display_dream_comparison(367, "introducing student top-up fees", true);
display_dream_comparison(258, "Labour's anti-terrorism laws", true);
display_dream_comparison(219, "the Iraq war", true);
display_dream_comparison(975, "investigating the Iraq war");
display_dream_comparison(984, "replacing Trident");
display_dream_comparison(358, "the hunting ban", true);
display_dream_comparison(826, "equal gay rights");
function display_dream_comparison($id, $text, $inverse = false) {
	global $pw, $output;
	if (!array_key_exists($id, $output)) return;
	$score = $output[$id];
	if ($score == -1) {
		$pw .= '
Has never voted on';
	} else {
		if ($inverse) $score = 1 - $score;
		$pw .= '
Voted ' . score_to_strongly($score) . '';
	}
	$pw .= ' ' . $text . '
';
}

$pw .= '
';

$output = $row;
$output['pw_data'] = $pw;

$q = $db->query("select * from memberinfo where member_id = " . $row['member_id']
	. " and data_key in ('swing_to_lose_seat_today', 'majority_in_seat')");
for ($i=0; $i<$q->rows(); $i++) {
	$key = $q->field($i, 'data_key');
	$output[$key] = number_format($q->field($i, 'data_value'));
}

print '<twfy>' . api_output_xml($output) . '</twfy>';

function score_to_strongly($dmpscore) {
	$dmpdesc = "unknown about";
	if ($dmpscore > 0.95 && $dmpscore <= 1.0)
		$dmpdesc = "very strongly against";
	elseif ($dmpscore > 0.85)
		$dmpdesc = "strongly against";
	elseif ($dmpscore > 0.6)
		$dmpdesc = "moderately against";
	elseif ($dmpscore > 0.4)
		$dmpdesc = "a mixture of for and against";
	elseif ($dmpscore > 0.15)
		$dmpdesc = "moderately for";
	elseif ($dmpscore > 0.05)
		$dmpdesc = "strongly for";
	elseif ($dmpscore >= 0.0)
		$dmpdesc = "very strongly for";
	return $dmpdesc;
}


text:
package generated.zcsclient.adminext;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for attrsImpl complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="attrsImpl">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="a" type="{urn:zimbraAdminExt}attr" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "attrsImpl", propOrder = {
    "a"
})
@XmlSeeAlso({
    testGenerateBulkProvisionFileFromLDAPRequest.class,
    testBulkImportAccountsRequest.class,
    testBulkIMAPImportTaskInfo.class
})
public abstract class testAttrsImpl {

    protected List<testAttr> a;

    /**
     * Gets the value of the a property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the a property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getA().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link testAttr }
     *
     *
     */
    public List<testAttr> getA() {
        if (a == null) {
            a = new ArrayList<testAttr>();
        }
        return this.a;
    }

}


text:
def normalize_revision(rev_doc):
    autolabel = rev_doc.get('autolabel', {})
    if "needs_review" in rev_doc:
        autolabel['needs_review'] = ensure_bool(rev_doc['needs_review'])
        del rev_doc['needs_review']
    if "reason" in rev_doc:
        autolabel['reason'] = rev_doc['reason'] \
            if rev_doc['reason'] != "NULL" else None
        del rev_doc['reason']

    rev_doc['rev_id'] = int(rev_doc['rev_id'])
    rev_doc['autolabel'] = autolabel

    return rev_doc

def ensure_bool(val):
    if isinstance(val, bool):
        return val
    elif isinstance(val, str):
        return val.lower() in ("true", "1", "t", "y")
    else:
        return bool(val)


text:
namespace TheQ.DexiIo.Client.Implementation
{
	/// <summary>
	///     Cloud Scrape Result DTO
	/// </summary>
	public class Result
	{
		public string[] Headers { get; set; }

		public string[][] Rows { get; set; }

		public int TotalRows { get; set; }
	}
}


text:
Instructions:
1. Install all dependency using ``` npm install ```
2. Run the app using ``` grunt ```


text:
package com.landicorp.android.wofupay.bean;

import java.util.List;

/**
 * Created by Administrator on 2016/6/7 0007.
 */
public class CityInfoModel {

    private String name;
    private List<DistrictInfoModel> districtList;

    public CityInfoModel() {
        super();
    }

    public CityInfoModel(String name, List<DistrictInfoModel> districtList) {
        super();
        this.name = name;
        this.districtList = districtList;
    }

    public String getName() {
        return name;
    }

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

    public List<DistrictInfoModel> getDistrictList() {
        return districtList;
    }

    public void setDistrictList(List<DistrictInfoModel> districtList) {
        this.districtList = districtList;
    }

    @Override
    public String toString() {
        return "CityInfoModel [name=" + name + ", districtList=" + districtList
                + "]";
    }
}


text:
package com.google.common.collect.testing.testers;

import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;

import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;

import java.util.Collection;

/**
 * Tests {@link java.util.Set#hashCode}.
 *
 * @author George van den Driessche
 */
@GwtCompatible(emulated = true)
public class SetHashCodeTester<E> extends AbstractSetTester<E> {
  public void testHashCode() {
    int expectedHashCode = 0;
    for (E element : getSampleElements()) {
      expectedHashCode += ((element == null) ? 0 : element.hashCode());
    }
    assertEquals(
        "A Set's hashCode() should be the sum of those of its elements.",
        expectedHashCode, getSet().hashCode());
  }

  @CollectionSize.Require(absent = CollectionSize.ZERO)
  @CollectionFeature.Require(ALLOWS_NULL_VALUES)
  public void testHashCode_containingNull() {
    Collection<E> elements = getSampleElements(getNumElements() - 1);
    int expectedHashCode = 0;
    for (E element : elements) {
      expectedHashCode += ((element == null) ? 0 : element.hashCode());
    }

    elements.add(null);
    collection = getSubjectGenerator().create(elements.toArray());
    assertEquals(
        "A Set's hashCode() should be the sum of those of its elements (with "
            + "a null element counting as having a hash of zero).",
        expectedHashCode, getSet().hashCode());
  }
}


text:
<?php

namespace Symfony\Component\Translation;

/**
 * MetadataAwareInterface.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface MetadataAwareInterface
{
    /**
     * Gets metadata for the given domain and key.
     *
     * Passing an empty domain will return an array with all metadata indexed by
     * domain and then by key. Passing an empty key will return an array with all
     * metadata for the given domain.
     *
     * @param string $key    The key
     * @param string $domain The domain name
     *
     * @return mixed The value that was set or an array with the domains/keys or null
     */
    public function getMetadata(string $key = '', string $domain = 'messages');

    /**
     * Adds metadata to a message domain.
     *
     * @param string $key    The key
     * @param mixed  $value  The value
     * @param string $domain The domain name
     */
    public function setMetadata(string $key, $value, string $domain = 'messages');

    /**
     * Deletes metadata for the given key and domain.
     *
     * Passing an empty domain will delete all metadata. Passing an empty key will
     * delete all metadata for the given domain.
     *
     * @param string $key    The key
     * @param string $domain The domain name
     */
    public function deleteMetadata(string $key = '', string $domain = 'messages');
}


text:
import { Question } from './question';

export class Mystery {
    title: string;
    category: string;
    story: string;
    questions: Question[];
}


text:
export function HeaderController($log) {
    'ngInject';
    $log.debug('header is optional')
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace iCal_sync.ical_NET.Model
{
    public class vCalendar
    {
        public List<ContentLine> Properties { get; set; }
        public List<vEvent> vEvents { get; set; }

        public vCalendar(string icsFile)
        {
            Properties = new List<ContentLine>();
            vEvents = new List<vEvent>();
            foreach (Match contentline in
                    Regex.Matches(Regex.Match(icsFile, @"BEGIN:VCALENDAR(.*?)BEGIN:VEVENT", RegexOptions.Singleline).Groups[1].Value, @"(.*?:.*(\n\s.*)*)"))
                Properties.Add(new ContentLine(contentline.Groups[1].Value));
            foreach (Match vevent in Regex.Matches(icsFile, @"BEGIN:VEVENT(.*?)END:VEVENT", RegexOptions.Singleline))
                vEvents.Add(new vEvent(vevent.Groups[1].Value));
        }

        public ContentLine GetProperty(string name)
        {
            return Properties.FirstOrDefault(x => x.Name.Equals(name));
        }
    }
}


text:
<?php
class Kwf_Assets_CommonJs_JQueryPluginProvider extends Kwf_Assets_Provider_Abstract
{
    public function getDependency($dependencyName)
    {
        if (substr($dependencyName, 0, 18) == 'kwf-jquery-plugin/') {
            $dependencyName = substr($dependencyName, 18);
            $dep = $this->_providerList->findDependency($dependencyName);
            $dep = $this->_transformDep($dep);
            if ($dep instanceof Kwf_Assets_CommonJs_JQueryPluginDecoratorDependency) {
                $dep->addDependency(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_COMMONJS, $this->_providerList->findDependency('jQuery'), 'jQuery');
            }
            return $dep;
        }
    }

    private function _transformDep($dep)
    {
        if ($dep instanceof Kwf_Assets_Dependency_Dependencies) {
            if ($dep->getDependencies(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_USES)) {
                throw new Kwf_Exception_NotYetImplemented();
            }
            $transformedDepsJs = array();
            $transformedDepsCss = array();
            foreach ($dep->getDependencies(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_REQUIRES) as $k=>$i) {
                if ($i->getMimeType() == 'text/javascript') {
                    $i = $this->_transformDep($i);
                    if ($i) $transformedDepsJs[$k] = $i;
                } else {
                    $transformedDepsCss[$k] = $i;
                }
            }
            if (count($transformedDepsJs) == 1) {
                //if a single js dependency transform into something that is compatible with commonjs
                $transformedDepsJs = array_values($transformedDepsJs);
                $ret = $transformedDepsJs[0];
                $ret->addDependency(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_COMMONJS, $this->_providerList->findDependency('jQuery'), 'jQuery');
                $ret->setDependencies(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_REQUIRES, $transformedDepsCss);
                return $ret;
            } else {
                $dep->setDependencies(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_COMMONJS, $transformedDepsJs);
                $dep->setDependencies(Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_REQUIRES, $transformedDepsCss);
                return $dep;
            }
        } else if ($dep instanceof Kwf_Assets_Dependency_File && $dep->getFileNameWithType() == 'jquery/dist/jquery.js') {
            return null;
        } else {
            if ($dep->getMimeType() == 'text/javascript') {
                return new Kwf_Assets_CommonJs_JQueryPluginDecoratorDependency($this->_providerList, $dep);
            } else {
                return $dep;
            }
        }
    }
}


text:
require 'test/test_helper'

class DlFolderTest < ActiveSupport::TestCase
  fixtures [:DLFileEntry, :DLFolder, :Company, :User_, :Group_]

  def setup
    @folders = DlFolder.all
  end

  def test_files
    @folders.each do |dlf|
      dlf.files.each do |f|
        assert_not_nil f
      end
    end
  end

  def test_company
    @folders.each do |dlf|
      assert_not_nil dlf.company
    end
  end

  def test_user
    @folders.each do |dlf|
      assert_not_nil dlf.user
    end
  end

  def test_group
    @folders.each do |dlf|
      assert_not_nil dlf.group
    end
  end
end


text:
<?php

namespace NAD\PageBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMS;

/**
 * Page
 *
 * @author Mohammadreza Razzaghi <razzaghi229@gmail.com>
 *
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="NAD\PageBundle\Entity\PageRepository")
 * @ORM\Table(name="nad_page")
 * @JMS\ExclusionPolicy("all")
 */
class Page
{
    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @JMS\Expose
     * @JMS\Type("integer")
     */
    private $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=2, nullable=false)
     * @Assert\NotNull()
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $locale;

    /**
     * @var string
     * @ORM\Column(type="string", length=255)
     * @Assert\Type(type="string")
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $title;

    /**
     * @var string
     * @ORM\Column(type="text")
     * @Assert\NotNull()
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $content;

    /**
     * @var boolean
     * @ORM\Column(type="boolean")
     * @Assert\Type(type="bool")
     * @Assert\NotNull()
     * @JMS\Expose
     * @JMS\Type("boolean")
     */
    private $status = false;

    /**
     * @var boolean
     * @ORM\Column(type="boolean")
     * @Assert\Type(type="bool")
     * @Assert\NotNull()
     * @JMS\Expose
     * @JMS\Type("boolean")
     */
    private $commentStatus = false;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\Type(type="string")
     * @Assert\NotNull()
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $metaUrl;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Type(type="string")
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $metaTitle;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Type(type="string")
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $metaDescription;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Type(type="string")
     * @JMS\Expose
     * @JMS\Type("string")
     */
    private $metaKeywords;

    /**
     * @var \DateTime
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     * @JMS\Expose
     * @JMS\Type("DateTime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     * @JMS\Expose
     * @JMS\Type("DateTime")
     */
    private $updatedAt;

    /**
     * @var ArrayCollection
     * @ORM\ManyToMany(targetEntity="NAD\PageBundle\Entity\Category")
     * @ORM\JoinTable(
     *     name="nad_page_page_category",
     *     joinColumns={@ORM\JoinColumn(name="page_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
     * )
     * @JMS\Expose
     * @JMS\MaxDepth(1)
     * @JMS\Type("ArrayCollection<NAD\PageBundle\Entity\Category>")
     */
    private $categories;

    /**
     * @inheritdoc
     */
    public function __toString()
    {
        return $this->getTitle();
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set locale
     *
     * @param  string $locale
     * @return Page
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;

        return $this;
    }

    /**
     * Get locale
     *
     * @return string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * Set title
     *
     * @param  string $title
     * @return Page
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set content
     *
     * @param  string $content
     * @return Page
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set status
     *
     * @param  boolean $status
     * @return Page
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return boolean
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set commentStatus
     *
     * @param  boolean $commentStatus
     * @return Page
     */
    public function setCommentStatus($commentStatus)
    {
        $this->commentStatus = $commentStatus;

        return $this;
    }

    /**
     * Get commentStatus
     *
     * @return boolean
     */
    public function getCommentStatus()
    {
        return $this->commentStatus;
    }

    /**
     * Set metaUrl
     *
     * @param  string $metaUrl
     * @return Page
     */
    public function setMetaUrl($metaUrl)
    {
        $this->metaUrl = $metaUrl;

        return $this;
    }

    /**
     * Get metaUrl
     *
     * @return string
     */
    public function getMetaUrl()
    {
        return $this->metaUrl;
    }

    /**
     * Set metaTitle
     *
     * @param  string $metaTitle
     * @return Page
     */
    public function setMetaTitle($metaTitle)
    {
        $this->metaTitle = $metaTitle;

        return $this;
    }

    /**
     * Get metaTitle
     *
     * @return string
     */
    public function getMetaTitle()
    {
        return $this->metaTitle;
    }

    /**
     * Set metaDescription
     *
     * @param  string $metaDescription
     * @return Page
     */
    public function setMetaDescription($metaDescription)
    {
        $this->metaDescription = $metaDescription;

        return $this;
    }

    /**
     * Get metaDescription
     *
     * @return string
     */
    public function getMetaDescription()
    {
        return $this->metaDescription;
    }

    /**
     * Set metaKeywords
     *
     * @param  string $metaKeywords
     * @return Page
     */
    public function setMetaKeywords($metaKeywords)
    {
        $this->metaKeywords = $metaKeywords;

        return $this;
    }

    /**
     * Get metaKeywords
     *
     * @return string
     */
    public function getMetaKeywords()
    {
        return $this->metaKeywords;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param  \DateTime $updatedAt
     * @return Page
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Add categories
     *
     * @param Category $categories
     *
     * @return Page
     */
    public function addCategory(Category $categories)
    {
        $this->categories[] = $categories;

        return $this;
    }

    /**
     * Remove categories
     *
     * @param Category $categories
     */
    public function removeCategory(Category $categories)
    {
        $this->categories->removeElement($categories);
    }

    /**
     * Get categories
     *
     * @return ArrayCollection
     */
    public function getCategories()
    {
        return $this->categories;
    }

    /**
     * Get categories
     *
     * @param Category $categories
     *
     * @return Page
     */
    public function setCategories($categories)
    {
        $this->categories = $categories;
    }
}


text:
#include "BDDUtil.h"
#include "BDDStepBuilder.h"
#include "BDDStepImplBuilderContext.h"
#include "BDDStepImplCppBuilder.h"

using namespace std;
using namespace GherkinAst;
using namespace CucumberCpp;

wstring BDDStepImplCppBuilder::BuildStepImplCpp()
{
    wstring stepImplCpp;
    stepImplCpp
        .append(wstring(L"#include \"") + BDDStepImplBuilderContext::StepHeaderFileName() + L"\"")
        .append(BDDUtil::NEW_LINE)
        .append(BDDUtil::NEW_LINE)
        .append(BuildStepImps())
        .append(BDDUtil::NEW_LINE);

    return stepImplCpp;
}

wstring BDDStepImplCppBuilder::BuildStepImps()
{
    wstring stepImps;
    for (BDDStepBuilder* pStepBuilder : BDDStepImplBuilderContext::NonDuplicateStepBuilders())
    {
        stepImps
            .append(MakeStepComments(*pStepBuilder))
            .append(pStepBuilder->BuildStepImp())
            .append(BDDUtil::NEW_LINE)
            .append(BDDUtil::NEW_LINE);
    }

    return stepImps;
}

wstring BDDStepImplCppBuilder::MakeStepComments(BDDStepBuilder& stepBuilder)
{
    wstring comments;
    for (wstring str : stepBuilder.StepComments())
    {
        comments
            .append(L"// " + str)
            .append(BDDUtil::NEW_LINE);
    }

    return comments;
}


text:
package log

import (
	"reflect"
	"testing"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/plugin/pkg/response"
)

func TestLogParse(t *testing.T) {
	tests := []struct {
		inputLogRules    string
		shouldErr        bool
		expectedLogRules []Rule
	}{
		{`log`, false, []Rule{{
			NameScope: ".",
			Format:    DefaultLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org`, false, []Rule{{
			NameScope: "example.org.",
			Format:    DefaultLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org. {common}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org {combined}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CombinedLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org.
		log example.net {combined}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    DefaultLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}, {
			NameScope: "example.net.",
			Format:    CombinedLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org {host}
			  log example.org {when}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    "{host}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}, {
			NameScope: "example.org.",
			Format:    "{when}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org example.net`, false, []Rule{{
			NameScope: "example.org.",
			Format:    DefaultLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}, {
			NameScope: "example.net.",
			Format:    DefaultLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org example.net {host}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    "{host}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}, {
			NameScope: "example.net.",
			Format:    "{host}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org example.net {when} {
			class denial
		}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    "{when}",
			Class:     map[response.Class]struct{}{response.Denial: {}},
		}, {
			NameScope: "example.net.",
			Format:    "{when}",
			Class:     map[response.Class]struct{}{response.Denial: {}},
		}}},

		{`log example.org {
				class all
			}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org {
			class denial
		}`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.Denial: {}},
		}}},
		{`log {
			class denial
		}`, false, []Rule{{
			NameScope: ".",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.Denial: {}},
		}}},
		{`log {
			class denial error
		}`, false, []Rule{{
			NameScope: ".",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.Denial: {}, response.Error: {}},
		}}},
		{`log {
			class denial
			class error
		}`, false, []Rule{{
			NameScope: ".",
			Format:    CommonLogFormat,
			Class:     map[response.Class]struct{}{response.Denial: {}, response.Error: {}},
		}}},
		{`log {
			class abracadabra
		}`, true, []Rule{}},
		{`log {
			class
		}`, true, []Rule{}},
		{`log {
			unknown
		}`, true, []Rule{}},
		{`log example.org "{combined} {/forward/upstream}"`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CombinedLogFormat + " {/forward/upstream}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org "{common} {/forward/upstream}"`, false, []Rule{{
			NameScope: "example.org.",
			Format:    CommonLogFormat + " {/forward/upstream}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org "{when} {combined} {/forward/upstream}"`, false, []Rule{{
			NameScope: "example.org.",
			Format:    "{when} " + CombinedLogFormat + " {/forward/upstream}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
		{`log example.org "{when} {common} {/forward/upstream}"`, false, []Rule{{
			NameScope: "example.org.",
			Format:    "{when} " + CommonLogFormat + " {/forward/upstream}",
			Class:     map[response.Class]struct{}{response.All: {}},
		}}},
	}
	for i, test := range tests {
		c := caddy.NewTestController("dns", test.inputLogRules)
		actualLogRules, err := logParse(c)

		if err == nil && test.shouldErr {
			t.Errorf("Test %d with input '%s' didn't error, but it should have", i, test.inputLogRules)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d with input '%s' errored, but it shouldn't have; got '%v'",
				i, test.inputLogRules, err)
		}
		if len(actualLogRules) != len(test.expectedLogRules) {
			t.Fatalf("Test %d expected %d no of Log rules, but got %d",
				i, len(test.expectedLogRules), len(actualLogRules))
		}
		for j, actualLogRule := range actualLogRules {
			if actualLogRule.NameScope != test.expectedLogRules[j].NameScope {
				t.Errorf("Test %d expected %dth LogRule NameScope for '%s' to be  %s  , but got %s",
					i, j, test.inputLogRules, test.expectedLogRules[j].NameScope, actualLogRule.NameScope)
			}

			if actualLogRule.Format != test.expectedLogRules[j].Format {
				t.Errorf("Test %d expected %dth LogRule Format for '%s' to be  %s  , but got %s",
					i, j, test.inputLogRules, test.expectedLogRules[j].Format, actualLogRule.Format)
			}

			if !reflect.DeepEqual(actualLogRule.Class, test.expectedLogRules[j].Class) {
				t.Errorf("Test %d expected %dth LogRule Class to be  %v  , but got %v",
					i, j, test.expectedLogRules[j].Class, actualLogRule.Class)
			}
		}
	}
}


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

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="120dp"
    android:height="120dp"
    android:viewportHeight="@integer/viewport_height"
    android:viewportWidth="@integer/viewport_width">

    <group
        android:name="@string/group_play_pause"
        android:pivotX="@integer/viewport_center_x"
        android:pivotY="@integer/viewport_center_y">

        <path
            android:name="@string/play"
            android:fillColor="@android:color/black"
            android:pathData="@string/play_path" />

    </group>

</vector>


text:
/// <reference types="express" />
/// <reference types="node" />
import * as express from "express";
export interface IHttpInfo {
    readonly statusCode?: number;
    readonly contentType?: string;
}
export interface IResult {
    /**
     * Additional result metadata properties.
     */
    readonly properties: Map<string, any>;
    /**
     * Http specific properties.
     */
    httpInfo?: IHttpInfo;
    /**
     * Concatenate current result with the specified result.
     * In case of conflict the specified result wins over current values.
     * Returns a new instance.
     * @param {IResult} other The result to concatenate.
     */
    concat(other: IResult): IResult;
    /**
     * Write the current result to an express response (http output).
     */
    writeTo(req: express.Request, res: express.Response): Promise<void>;
    /**
     * Clone the current result.
     */
    clone(): IResult;
}
export declare class Result {
    readonly httpInfo: IHttpInfo;
    readonly properties: Map<string, any>;
    static mergeHttpInfo(left?: IHttpInfo, right?: IHttpInfo): IHttpInfo;
    constructor(httpInfo?: IHttpInfo, properties?: Map<string, any>);
    concat(other: IResult): IResult;
    writeTo(req: express.Request, res: express.Response): Promise<void>;
    clone(): IResult;
    withProperty(key: string, value: any): this;
}
export declare class TextResult extends Result {
    readonly content: string;
    isStringResult: boolean;
    constructor(content: string, httpInfo?: IHttpInfo, properties?: Map<string, any>);
    concat(other: IResult): IResult;
    writeTo(req: express.Request, res: express.Response): Promise<void>;
    clone(): IResult;
}
export declare class BufferResult extends Result {
    readonly content: Buffer;
    isBufferResult: boolean;
    constructor(content: Buffer, httpInfo?: IHttpInfo, properties?: Map<string, any>);
    concat(other: IResult): IResult;
    writeTo(req: express.Request, res: express.Response): Promise<void>;
    clone(): IResult;
}


text:
package com.twitter.scalding

import cascading.tuple.Fields
import java.io.File
import java.nio.file.Files
import org.scalatest.WordSpec
import scala.collection.JavaConverters._
import org.apache.hadoop.mapred.JobConf

class ReplTest extends WordSpec {
  import ReplImplicits._
  import ReplImplicitContext._

  val state = implicitly[BaseReplState]
  import state._

  val tutorialData = "../tutorial/data"
  val helloPath = tutorialData + "/hello.txt"

  def test() = {

    val suffix = mode match {
      case _: CascadingLocal => "local"
      case _: HadoopMode => "hadoop"
    }
    val testPath = "/tmp/scalding-repl/test/" + suffix + "/"
    val helloRef = List("Hello world", "Goodbye world")

    "save -- TypedPipe[String]" in {
      val hello = TypedPipe.from(TextLine(helloPath))
      val out = TypedTsv[String](testPath + "output0.txt")
      hello.save(out)

      val output = out.toIterator.toList
      assert(output === helloRef)
    }

    "snapshot" should {
      "only -- TypedPipe[String]" in {
        val hello = TypedPipe.from(TextLine(helloPath))
        val s: TypedPipe[String] = hello.snapshot
        // shallow verification that the snapshot was created correctly without
        // actually running a new flow to check the contents (just check that
        // it's a TypedPipe from a MemorySink or SequenceFile)
        assert(s.toString.contains("IterablePipe") || s.toString.contains("TypedPipeFactory"))

        val pipeName = mode match {
          case m: HadoopMode => m.jobConf.get("hadoop.tmp.dir")
          case _ => "IterableSource"
        }
        assert(s.toPipe(Fields.ALL).toString.contains(pipeName))

      }

      "can be mapped and saved -- TypedPipe[String]" in {
        val s = TypedPipe.from(TextLine(helloPath))
          .flatMap(_.split("\\s+"))
          .snapshot

        val out = TypedTsv[String](testPath + "output1.txt")

        // can call 'map' and 'save' on snapshot
        s.map(_.toLowerCase).save(out)

        val output = out.toIterator.toList
        assert(output === helloRef.flatMap(_.split("\\s+")).map(_.toLowerCase))
      }

      "tuples -- TypedPipe[(String,Int)]" in {
        val s = TypedPipe.from(TextLine(helloPath))
          .flatMap(_.split("\\s+"))
          .map(w => (w.toLowerCase, w.length))
          .snapshot

        val output = s.toList
        assert(output === helloRef.flatMap(_.split("\\s+")).map(w => (w.toLowerCase, w.length)))
      }

      "grouped -- Grouped[String,String]" which {
        val grp = TypedPipe.from(TextLine(helloPath))
          .groupBy(_.toLowerCase)

        val correct = helloRef.map(l => (l.toLowerCase, l))

        "is explicit" in {
          (grp.snapshot.toList === correct)
        }

        // Note: Must explicitly to toIterator because `grp.toList` resolves to `KeyedList.toList`
        "is implicit" in {
          assert(grp.toIterator.toList === correct)
        }
      }

      "joined -- CoGrouped[String, Long]" which {
        val linesByWord = TypedPipe.from(TextLine(helloPath))
          .flatMap(_.split("\\s+"))
          .groupBy(_.toLowerCase)
        val wordScores = TypedPipe.from(TypedTsv[(String, Double)](tutorialData + "/word_scores.tsv")).group

        val grp = linesByWord.join(wordScores)
          .mapValues { case (text, score) => score }
          .sum

        val correct = Map("hello" -> 1.0, "goodbye" -> 3.0, "world" -> 4.0)

        "is explicit" in {
          val s = grp.snapshot
          assert(s.toIterator.toMap === correct)
        }
        "is implicit" in {
          assert(grp.toIterator.toMap === correct)
        }
      }

      "support toOption on ValuePipe" in {
        val hello = TypedPipe.from(TextLine(helloPath))
        val res = hello.map(_.length).sum
        val correct = helloRef.map(_.length).sum
        assert(res.toOption === Some(correct))
      }
    }

    "reset flow" in {
      resetFlowDef()
      assert(flowDef.getSources.asScala.isEmpty)
    }

    "run entire flow" in {
      resetFlowDef()
      val hello = TypedPipe.from(TextLine(helloPath))
        .flatMap(_.split("\\s+"))
        .map(_.toLowerCase)
        .distinct

      val out = TypedTsv[String](testPath + "words.tsv")

      hello.write(out)
      ReplState.run

      val words = out.toIterator.toSet
      assert(words === Set("hello", "world", "goodbye"))
    }

    "TypedPipe of a TextLine" should {
      val hello = TypedPipe.from(TextLine(helloPath))
      "support toIterator" in {
        hello.toIterator.foreach { line: String =>
          assert(line.contains("Hello world") || line.contains("Goodbye world"))
        }
      }
      "support toList" in {
        assert(hello.toList === helloRef)
      }
    }

    "toIterator should generate a snapshot for TypedPipe with" should {
      val hello = TypedPipe.from(TextLine(helloPath))
      "flatMap" in {
        val out = hello.flatMap(_.split("\\s+")).toList
        assert(out === helloRef.flatMap(_.split("\\s+")))
      }
      "tuple" in {
        assert(hello.map(l => (l, l.length)).toList === helloRef.map(l => (l, l.length)))
      }
    }
  }

  "REPL in Local mode" should {
    mode = Local(strictSources = true)
    test()
  }

  "REPL in Hadoop mode" should {
    mode = Hdfs(strict = true, new JobConf)
    test()
  }

  "findAllUpPath" should {
    val root = Files.createTempDirectory("scalding-repl").toFile
    root.deleteOnExit()

    val matchingFile = new File(root, "this_matches")
    matchingFile.createNewFile()

    val currentDirectory = new File(root, "arbitrary_directory")
    currentDirectory.mkdir()

    "enumerate matching files" in {
      root.setReadable(true)

      val actual = ScaldingILoop
        .findAllUpPath(currentDirectory.getAbsolutePath)("this_matches")
      assert(actual === List(matchingFile))
    }

    "ignore directories with restricted permissions" in {
      root.setReadable(false)

      val actual = ScaldingILoop
        .findAllUpPath(currentDirectory.getAbsolutePath)("this_matches")
      assert(actual === List.empty)
    }
  }
}


text:
<?php
// @codingStandardsIgnoreFile
/*
WPUpdates Theme Updater Class
http://wp-updates.com
v2.0

Example Usage:
require_once('wp-updates-theme.php');
new WPUpdatesThemeUpdater_2050( 'http://wp-updates.com/api/2/theme', basename(get_template_directory()) );
*/

if( !class_exists('WPUpdatesThemeUpdater_2050') ) {
    class WPUpdatesThemeUpdater_2050 {

        var $api_url;
    	var $theme_id = 2050;
    	var $theme_slug;
    	var $license_key;

        function __construct( $api_url, $theme_slug, $license_key = null ) {
    		$this->api_url = $api_url;
    		$this->theme_slug = $theme_slug;
	        $this->license_key = $license_key;

    		add_filter( 'pre_set_site_transient_update_themes', array(&$this, 'check_for_update') );

    		// This is for testing only!
    		//set_site_transient('update_themes', null);
    	}

    	function check_for_update( $transient ) {
        	if (empty($transient->checked)) return $transient;

        	$request_args = array(
    		    'id' => $this->theme_id,
    		    'slug' => $this->theme_slug,
    			'version' => $transient->checked[$this->theme_slug]
    		);
    		if ($this->license_key) $request_args['license'] = $this->license_key;

    		$request_string = $this->prepare_request( 'theme_update', $request_args );
    		$raw_response = wp_remote_post( $this->api_url, $request_string );

        	$response = null;
    		if( !is_wp_error($raw_response) && ($raw_response['response']['code'] == 200) )
    			$response = unserialize($raw_response['body']);

    		if( !empty($response) ) // Feed the update data into WP updater
    			$transient->response[$this->theme_slug] = $response;

        	return $transient;
        }

        function prepare_request( $action, $args ) {
    		global $wp_version;

    		return array(
    			'body' => array(
    				'action' => $action,
    				'request' => serialize($args),
    				'api-key' => md5(home_url())
    			),
    			'user-agent' => 'WordPress/'. $wp_version .'; '. home_url()
    		);
    	}

    }
}


text:
// ----------------------------------------------------------------------------------
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Author: Shihua (Simon) Xiao, sixiao@microsoft.com
// ----------------------------------------------------------------------------------

#include "throughputmanagement.h"

void check_bandwidth_limit(struct ntttcp_test_endpoint *tep)
{
	/*
	   Return immediately in the case of:
	    a) this is receiver (we don't limit receiver);
	    b) this is sender, but user did not specify the bandwidth limit.
	*/
	if ( (tep->endpoint_role == ROLE_RECEIVER) || (tep->test->bandwidth_limit == 0) )
		return;

	struct timeval this_check_time;
	double test_time_elapsed;
	ulong current_throughput;
	uint n = 0;

	gettimeofday(&this_check_time, NULL);
	test_time_elapsed = get_time_diff(&this_check_time, &tep->start_time);

	for (n = 0; n < tep->total_threads; n++) {
		/* No need to check the current sc is the sync_thread or not,
		   because sender does not have a delegated thread for sync */

		current_throughput = (tep->client_streams[n]->total_bytes_transferred) / test_time_elapsed;
		if (current_throughput > tep->client_streams[n]->sc_bandwidth_limit_bytes)
			tep->client_streams[n]->hold_on = true;
		else
			tep->client_streams[n]->hold_on = false;
	}
}

struct report_segment report_real_time_throughput(struct ntttcp_test_endpoint *tep,
						  struct report_segment last_checkpoint,
						  uint total_test_threads)
{
	struct report_segment this_checkpoint;

	uint64_t this_total_bytes = 0;
	uint64_t last_total_bytes = last_checkpoint.bytes;
	uint64_t total_bytes = 0;

	struct timeval this_check_time;
	struct timeval last_check_time = last_checkpoint.time;
	double test_time = 0;
	uint n = 0;

	for (n = 0; n < total_test_threads; n++) {
		if (tep->test->client_role == true )
			this_total_bytes += tep->client_streams[n]->total_bytes_transferred;
		else
			this_total_bytes += tep->server_streams[n]->total_bytes_transferred;
	}
	gettimeofday(&this_check_time, NULL);
	test_time = get_time_diff(&this_check_time, &last_check_time);
	total_bytes = this_total_bytes - last_total_bytes;

	if (!tep->test->quiet) {
		char *throughput = format_throughput(total_bytes, test_time);
		char line_end = '\n';
		if (tep->running_tty) {
			printf("%c[2K", 27); /* cleanup current line */
			line_end = '\r';
		}
		printf("%s: %s%c", "Real-time throughput", throughput, line_end);
		fflush(stdout);
		free(throughput);
	}

	this_checkpoint.interval_sec = test_time;
	this_checkpoint.time  = this_check_time;
	this_checkpoint.bytes = this_total_bytes;

	return this_checkpoint;
}

void run_ntttcp_throughput_management(struct ntttcp_test_endpoint *tep)
{
	uint n = 0;
	uint i = 0;
	double elapsed_sec = 0.0;

	struct timeval now;
	double actual_test_time = 0;

	struct report_segment last_checkpoint;

	uint64_t total_bytes_warmup = 0;
	uint64_t total_bytes_duration = 0;
	uint64_t nbytes;
	uint total_test_threads = tep->total_threads;

	/* light is already turned on before entering this function */

	/* Now the ntttcp test traffic is running now */
	tep->state = TEST_RUNNING;

	/* run the timer. it will trigger turn_off_light() after timer timeout */
	run_test_timer(tep->negotiated_test_cycle_time);

	/* 1) run test warm-up, if it is specified */
	if (tep->test->warmup > 0 ) {
		gettimeofday(&last_checkpoint.time, NULL);
		last_checkpoint.bytes = 0;
		elapsed_sec = 0;
		while (elapsed_sec < (double)tep->test->warmup) {
			/* wait 0.5 second, or 1000 test status poll cycles.
			 * we don't roll up the warmup bytes into final throughput report,
			 * so we don't care the time accuracy */
			usleep(THROUGHPUT_INTERVAL_U_SEC);	/* 500000 micro-seconds */
			last_checkpoint = report_real_time_throughput(tep,
					                               last_checkpoint,
								       total_test_threads);

			elapsed_sec += last_checkpoint.interval_sec;

			/* if test was interrupted by CTRL + C */
			if (!is_light_turned_on()) {
				PRINT_INFO("Test was interrupted.");
				goto END;
			}
		}
		PRINT_INFO("Test warmup completed.");
		/*
		 * 1) reset each stream's total_bytes_transferred counter to 0 (discard warmup bytes)
		 * 2) do a simple stats for how many bytes transferred in this warmup stage
		 */
		for (n = 0; n < total_test_threads; n++) {
			if (tep->test->client_role == true) {
				total_bytes_warmup += (uint64_t)__sync_lock_test_and_set(&(tep->client_streams[n]->total_bytes_transferred), 0);
			} else {
				/* exclude the sync thread (only receiver has a thread for sync) */
				if (tep->server_streams[n]->is_sync_thread == true)
					continue;

				total_bytes_warmup += (uint64_t)__sync_lock_test_and_set(&(tep->server_streams[n]->total_bytes_transferred), 0);
			}
		}
	}

	/* 2) now, let's run the real test duration */
	elapsed_sec = 0;		/* reset the counter */
	last_checkpoint.bytes = 0;	/* the counters in streams have been reset to 0 above */
	gettimeofday(&now, NULL);	/* reset the timestamp to now */
	last_checkpoint.time = now;
	tep->start_time = now;

	/* calculate the initial resource usage */
	get_cpu_usage( tep->results->init_cpu_usage );
	get_cpu_usage_from_proc_stat( tep->results->init_cpu_ps );
	get_tcp_retrans( tep->results->init_tcp_retrans );
	tep->results->init_tx_packets = get_single_value_from_os_file(tep->test->show_interface_packets, "tx");
	tep->results->init_rx_packets = get_single_value_from_os_file(tep->test->show_interface_packets, "rx");
	tep->results->init_interrupts = get_interrupts_from_proc_by_dev(tep->test->show_dev_interrupts);

	while(is_light_turned_on()) {
		/* Wait 500 micro-seconds. We don't want to pull the status too often.
		 * But, we also don't want to wait too long time;
		 * otherwise, in the case of CTRL+C, the test streams have been stopped by CTRL+C (then light is turned off), but we are still waiting here
		 * which will make the "actual_test_time" longer than actual stream run time,
		 * and eventually make the final throughput reported inaccurate (will be lower than actual throughput)
		 */
		usleep(TEST_STATUS_POLL_INTERVAL_U_SEC);

		check_bandwidth_limit(tep);

		/* if we have already waited 1000 poll times (0.5 second), then let's report the throughput */
		i++;
		if (i == THROUGHPUT_INTERVAL_POLLS) {
			last_checkpoint = report_real_time_throughput(tep,
								      last_checkpoint,
								      total_test_threads);
			i = 0; //reset the counter
			elapsed_sec += last_checkpoint.interval_sec;
		}

		/* if test duration time is reached, then exit this stage */
		if (elapsed_sec > tep->test->duration)
			break;
	}

	/* calculate the end resource usage */
	get_cpu_usage( tep->results->final_cpu_usage );
	get_cpu_usage_from_proc_stat( tep->results->final_cpu_ps );
	get_tcp_retrans( tep->results->final_tcp_retrans );
	tep->results->final_tx_packets = get_single_value_from_os_file(tep->test->show_interface_packets, "tx");
	tep->results->final_rx_packets = get_single_value_from_os_file(tep->test->show_interface_packets, "rx");
	tep->results->final_interrupts = get_interrupts_from_proc_by_dev(tep->test->show_dev_interrupts);

	gettimeofday(&now, NULL);
	tep->end_time = now;

	/* calculate the actual test run time */
	actual_test_time = get_time_diff(&tep->end_time, &tep->start_time);

	for (n = 0; n < total_test_threads; n++) {
		if (tep->test->client_role == true) {
			nbytes = (uint64_t)__sync_lock_test_and_set(&(tep->client_streams[n]->total_bytes_transferred), 0);
		} else {
			/* exclude the sync thread (only receiver has a thread for sync) */
			if (tep->server_streams[n]->is_sync_thread == true)
				continue;

			nbytes = (uint64_t)__sync_lock_test_and_set(&(tep->server_streams[n]->total_bytes_transferred), 0);
		}

		tep->results->threads[n]->total_bytes = nbytes;
		tep->results->threads[n]->actual_test_time = actual_test_time;
		total_bytes_duration += nbytes;
	}

	PRINT_INFO("Test run completed.");

	tep->results->total_bytes = total_bytes_duration;
	tep->results->actual_test_time = actual_test_time;

	/* 3) wait, if cool-down specified. there are some possibilities:
	 *    a) "-C" is specified by user, then Cooldown here.
	 *    b) "-C" is not specified (Cooldown time is 0), but the total test cycle time negotiated with remote peer,
	 *    is longer than the local one, then the excess time will be treated as Cooldown.
	 *    Example:
	 *    This endpoint   is running with: warmup:  5, duration: 60, cooldown:  0
	 *    Remote endpoint is running with: warmup: 10, duration: 90, cooldown: 10
	 *    Then, this endpoint will have 110 secs of test cycle time (total time), which is negotiated with remote endpoint (use the max one);
	 *    Then, this endpoint will have 45 seconds of cooldown time (= 110 - 5 - 60) */
	if (tep->negotiated_test_cycle_time - tep->test->warmup - tep->test->duration > 0)
		PRINT_INFO("Test cooldown is in progress...");

	wait_light_off();
	PRINT_INFO("Test cycle finished.");

END:
	if (tep->test->client_role == true && tep->test->no_synch == false) {
		/*
		 * if actual_test_time < tep->negotiated_test_cycle_time;
		 * then this indicates that in the sender side, test is being interrupted.
		 * hence, tell receiver about this.
		 */
		if (actual_test_time < tep->negotiated_test_cycle_time) {
			tell_receiver_test_exit(tep->synch_socket);
		}
		close(tep->synch_socket);
	}

	tep->state = TEST_FINISHED;
	return;
}


text:
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using JoinRpg.Helpers.Web;
using JoinRpg.Markdown;
using JoinRpg.Services.Interfaces;
using JoinRpg.Services.Interfaces.Search;
using Microsoft.AspNetCore.Html;

namespace JoinRpg.Web.Models;

///
/// A view model for a single item from search result
/// carrying, in additon, the target of the made search.
///
public class TargetedSearchResultViewModel
{
    private string SearchTarget { get; }
    public ISearchResult SearchResult { get; }
    public GameObjectLinkType LinkType => SearchResult.LinkType.AsViewModel();
    public Uri Url { get; }

    public JoinHtmlString GetFormattedDescription(int maxLengthToShow)
    {
        var descriptionToShow = TruncateString(
            SearchResult.Description.ToPlainText().ToHtmlString(),
            SearchTarget,
            maxLengthToShow);

        descriptionToShow = Regex.Replace(
            descriptionToShow,
            Regex.Escape(SearchTarget),
            match => "" + match.Value + "",
            RegexOptions.IgnoreCase);

        return new HtmlString(descriptionToShow);
    }

    private static string TruncateString(
        [NotNull] string stringToTruncate,
        [NotNull] string targetText,
        int maxLength,
        StringComparison stringComparison = StringComparison.InvariantCultureIgnoreCase)
    {
        if (targetText.Length > maxLength)
        {
            targetText = targetText.Substring(0, maxLength);
        }
        if (stringToTruncate.Length <= maxLength)
        {
            return stringToTruncate;
        }

        var startOfSearchedFragment = stringToTruncate.IndexOf(targetText, stringComparison);

        //show the beginning of the string if target fragment is not found
        startOfSearchedFragment = startOfSearchedFragment < 0 ? 0 : startOfSearchedFragment;

        //Try to put the beginning of the searched fragment in the middle of the substring
        var startOfSubtringToShow = startOfSearchedFragment > (maxLength / 2)
            ? startOfSearchedFragment - (maxLength / 2)
            : 0;

        //Move substring to the left, if needed
        startOfSubtringToShow = (startOfSubtringToShow + maxLength) > stringToTruncate.Length
            ? stringToTruncate.Length - maxLength
            : startOfSubtringToShow;

        var truncatedString = stringToTruncate.Substring(startOfSubtringToShow, maxLength);

        if (startOfSubtringToShow > 0)
        {
            truncatedString = "..." + truncatedString;
        }
        if (startOfSubtringToShow + maxLength < stringToTruncate.Length)
        {
            truncatedString += "...";
        }
        return truncatedString;
    }

    public TargetedSearchResultViewModel([NotNull] ISearchResult searchResult,
        [NotNull] string searchTarget,
        IUriService uriService)
    {
        SearchResult = searchResult ?? throw new ArgumentNullException(nameof(searchResult));
        SearchTarget = searchTarget ?? throw new ArgumentNullException(nameof(searchTarget));
        Url = uriService.GetUri(searchResult);
    }
}


text:
//packaged application compatability code
if (typeof iconsDir == "undefined") {
	//temporary fix for packaged application compatability
	var iconsDir = __dirname + '/content/icons';
}
if (typeof app == "undefined") {
	var app = require('appjs');
	app.serveFilesFrom(__dirname + '/content');
}
var window = app.createWindow({
  width  : 640,
  height : 368,
  icons  : iconsDir,
  showChrome : false,
  alpha: true,
  autoResize: false,
  resizable: true

  /***************************** defaults ********************************
* url            : 'http://appjs', // serve static file root and routers
* autoResize     : false,          // resizes in response to html content
* showChrome     : true,           // show border and title bar
* resizable      : false,          // control if users can resize window
* disableSecurity: true,           // allow cross origin requests
* opacity        : 1,              // flat percent opacity for window
* alpha          : false,          // per-pixel alpha blended (Win & Mac)
* fullscreen     : false,          // client area covers whole screen
* left           : -1,             // centered by default
* top            : -1,             // centered by default
*************************************************************************/

});

var trayMenu = app.createMenu([{
  label:'Show',
  action:function(){
    window.frame.show();
  },
},{
  label:'Minimize',
  action:function(){
    window.frame.hide();
  }
},{
  label:'Exit',
  action:function(){
    window.close();
  }
}]);

var statusIcon = app.createStatusIcon({
  icon:'./data/content/icons/32.png',
  tooltip:'AppJS Hello World',
  menu:trayMenu
});

window.on('create', function(){
  console.log("Window Created");
  window.frame.show();
  window.frame.center();
});

window.on('ready', function(){
  console.log("Window Ready");
  window.require = require;
  window.process = process;
  window.module = module;

  function F12(e){ return e.keyIdentifier === 'F12' }
  function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey }

  window.addEventListener('keydown', function(e){
    if (F12(e) || Command_Option_J(e)) {
      window.frame.openDevTools();
    }

  });

  this.dispatchEvent(new this.Event('app-ready'));
});

window.on('close', function(){
  console.log("Window Closed");
});


text:
package org.mockito.internal.configuration.plugins;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.io.IOUtil;
import org.mockito.plugins.PluginSwitch;

class PluginFinder {

    private final PluginSwitch pluginSwitch;

    public PluginFinder(PluginSwitch pluginSwitch) {
        this.pluginSwitch = pluginSwitch;
    }

    String findPluginClass(Iterable<URL> resources) {
        for (URL resource : resources) {
            InputStream s = null;
            try {
                s = resource.openStream();
                String pluginClassName = new PluginFileReader().readPluginClass(s);
                if (pluginClassName == null) {
                    // For backwards compatibility
                    // If the resource does not have plugin class name we're ignoring it
                    continue;
                }
                if (!pluginSwitch.isEnabled(pluginClassName)) {
                    continue;
                }
                return pluginClassName;
            } catch (Exception e) {
                throw new MockitoException(
                        "Problems reading plugin implementation from: " + resource, e);
            } finally {
                IOUtil.closeQuietly(s);
            }
        }
        return null;
    }

    List<String> findPluginClasses(Iterable<URL> resources) {
        List<String> pluginClassNames = new ArrayList<>();
        for (URL resource : resources) {
            InputStream s = null;
            try {
                s = resource.openStream();
                String pluginClassName = new PluginFileReader().readPluginClass(s);
                if (pluginClassName == null) {
                    // For backwards compatibility
                    // If the resource does not have plugin class name we're ignoring it
                    continue;
                }
                if (!pluginSwitch.isEnabled(pluginClassName)) {
                    continue;
                }
                pluginClassNames.add(pluginClassName);
            } catch (Exception e) {
                throw new MockitoException(
                        "Problems reading plugin implementation from: " + resource, e);
            } finally {
                IOUtil.closeQuietly(s);
            }
        }
        return pluginClassNames;
    }
}


text:
Issues:

08/04/2017: Speed peformance ~2X poorer than expected for given core count and CPU specification.  This is to be
resolved before introducing further functionality (e.g. different transfer/activation functions, cost functions,
momentum, dropout, regularisation etc...)

13/04/2017: NumPy is slow at matrix multiplication with OpenBLAS. Using MKL (via conda) increased CPU usage to multiple
cores without notable speedup - it often takes longer.

Todo:

Identify NumPy bottlenecks and resolve. This will probably require Cython with C++/assembler.
Nnet development is suspended until new C++ library CLAS is usable and Cython-wrapped.


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

namespace OpenCube.IO.FileSystem
{
	/// <summary>
	/// Extensions on the <see cref="IFolder"/> interface.
	/// </summary>
	public static class FolderExtensions
	{
		/// <summary>
		/// Get the file on or more folders deep.
		/// </summary>
		/// <param name="folder">The folder to start as relative path from</param>
		/// <param name="firstName">The first required file or folder name.</param>
		/// <param name="moreNames">The following file or folder names.</param>
		/// <returns>The requested file.</returns>
		public static IFile GetFile(this IFolder folder, string firstName, params string[] moreNames)
		{
			if (folder == null || firstName == null)
				return null;

			string[] names = new[] { firstName }.Concat(moreNames ?? new string[0]).ToArray();
			for (int i = 0; i < names.Length; i++)
			{
				if (folder == null)
					return null;

				if (i < names.Length - 1)
					folder = folder.GetFolder(names[i]);
				else
					return folder.GetFile(names[i]);
			}

			return null;
		}

		/// <summary>
		/// Get the folder on or more folders deep.
		/// </summary>
		/// <param name="folder">The folder to start as relative path from</param>
		/// <param name="firstName">The first required folder name.</param>
		/// <param name="moreNames">The following folder names.</param>
		/// <returns>The requested file.</returns>
		public static IFolder GetFolder(this IFolder folder, string firstName, params string[] moreNames)
		{
			if (folder == null || firstName == null)
				return null;

			string[] names = new[] { firstName }.Concat(moreNames ?? new string[0]).ToArray();
			foreach (string name in names)
			{
				if (folder == null)
					return null;

				folder = folder.GetFolder(name);
			}

			return folder;
		}

		/// <summary>
		/// Gets all files from this and all possible nested folders
		/// </summary>
		/// <param name="folder">The folder to get all files from, recursively scanning sub-folders as well.</param>
		/// <returns>A sequence of all the files.</returns>
		public static IEnumerable<IFile> GetAllFilesRecursive(this IFolder folder)
		{
			foreach (IFile file in folder.GetFiles())
				yield return file;

			foreach (IFolder subFolder in folder.GetFolders())
			{
				foreach (IFile subFile in subFolder.GetAllFilesRecursive())
					yield return subFile;
			}
		}

		/// <summary>
		/// Parse a path relative to this folder.
		/// </summary>
		/// <param name="folder">The folder that is the starting point for the relative path.</param>
		/// <param name="relativePath">The relative path to parse</param>
		/// <returns>
		/// A IFileSystemEntry with the file or folder, or <c>null</c> when the file or folder does not exist.
		/// </returns>
		/// <exception cref="System.InvalidOperationException">The given folder has no IFileSystemService in it's tree</exception>
		/// <exception cref="FormatException">Thrown when the path could not be parsed.</exception>
		/// <remarks>
		/// Scans the tree upwards until it finds a <see cref="IFileSystem" /> and uses it's ParseRelativePath method
		/// </remarks>
		public static IFileSystemEntry ParsePath(this IFolder folder, string relativePath)
		{
			IFileSystem service;
			do
			{
				if (folder == null)
					throw new InvalidOperationException("The given folder has no IFileSystemService in it's tree");

				service = folder as IFileSystem;
				folder = folder.ParentFolder;
			}
			while (service == null);

			return service.ParseRelativePath(folder, relativePath);
		}
	}
}


text:
<?php

use yii\db\Migration;

class m161012_192219_create_table_comments_anekdot extends Migration
{
    public function up()
    {
        $this->createTable('comments_anekdot', [
            'id' => $this->primaryKey(),
            'id_poem' => $this->integer()->notNull(),
            'id_user' => $this->integer()->notNull(),
            'comment' => $this->string(100)->notNull(),
            'date' => $this->string(16)->notNull(),
            'utime' => $this->integer()->notNull(),
        ]);
    }

    public function down()
    {
        $this->dropTable('comments_anekdot');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}