text:
package com.ipcamera.demo;

import com.yj.smarthome.R;
import com.ipcamera.demo.BridgeService.SDCardInterface;
import com.ipcamera.demo.bean.SdcardBean;
import com.ipcamera.demo.utils.ContentCommon;

import vstc2.nativecaller.NativeCaller;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SettingSDCardActivity extends BaseActivity implements
		OnClickListener, OnCheckedChangeListener, SDCardInterface {
	private TextView tvSdTotal = null;
	private TextView tvSdRemain = null;
	private TextView tvSdStatus = null;
	private Button btnFormat = null;
	private CheckBox cbxConverage = null;
	private EditText editRecordLength = null;
	private CheckBox cbxRecordTime = null;
	private Button btnBack = null;
	private Button btnOk = null;
	private final int TIMEOUT = 3000;
	private String strDID = null;// camera id
	// private String cameraName = null;
	private ProgressDialog progressDialog = null;
	private boolean successFlag = false;// 获取和设置的结果
	private final int FAILED = 0;
	private final int SUCCESS = 1;
	private final int PARAMS = 2;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case FAILED:
				showToast(R.string.sdcard_set_failed);
				break;
			case SUCCESS:
				showToast(R.string.sdcard_set_success);
				finish();
				break;
			case PARAMS:
				successFlag = true;
				progressDialog.dismiss();
				tvSdTotal.setText(sdcardBean.getSdtotal() + "MB");
				tvSdRemain.setText(sdcardBean.getSdfree() + "MB");
				if (sdcardBean.getRecord_sd_status() == 1)
				{
					tvSdStatus
							.setText(SettingSDCardActivity.this.getResources()
									.getString(R.string.sdcard_inserted));
				}
				else if (sdcardBean.getRecord_sd_status() == 2)
				{
					tvSdStatus.setText(getString(R.string.sdcard_video));
				}
				else if(sdcardBean.getRecord_sd_status() == 3)
				{
					tvSdStatus.setText(getString(R.string.sdcard_file_error));
				}
				else if(sdcardBean.getRecord_sd_status() == 4)
				{
					tvSdStatus.setText(getString(R.string.sdcard_isformatting));
				}
				else {
					tvSdStatus.setText(SettingSDCardActivity.this
							.getResources().getString(
									R.string.sdcard_status_info));
				}
				cbxConverage.setChecked(true);
				if (sdcardBean.getRecord_time_enable() == 1) {
					cbxRecordTime.setChecked(true);
				} else {
					cbxRecordTime.setChecked(false);
				}
				// editRecordLength.setText(sdcardBean.getRecord_timer() + "");
				editRecordLength.setText(15 + "");
				break;
			default:
				break;
			}

		}
	};

	@Override
	protected void onPause() {
		overridePendingTransition(R.anim.out_to_right, R.anim.in_from_left);//动画
		super.onPause();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getDataFromOther();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.settingsdcard);
		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage(getString(R.string.sdcard_getparams));
		progressDialog.show();
		sdcardBean = new SdcardBean();
		handler.postDelayed(runnable, TIMEOUT);
		findView();
		setLister();
		BridgeService.setSDCardInterface(this);
		NativeCaller.PPPPGetSystemParams(strDID,
				ContentCommon.MSG_TYPE_GET_RECORD);
	}

	private void getDataFromOther() {
		Intent intent = getIntent();
		strDID = intent.getStringExtra(ContentCommon.STR_CAMERA_ID);
		Log.i("info", "did:" + strDID);
		// cameraName = intent.getStringExtra(ContentCommon.STR_CAMERA_NAME);
	}

	private Runnable runnable = new Runnable() {

		@Override
		public void run() {
			if (!successFlag) {
				successFlag = false;
				progressDialog.dismiss();
			}
		}
	};
	private SdcardBean sdcardBean;

	private void setLister() {
		btnBack.setOnClickListener(this);
		btnOk.setOnClickListener(this);
		btnFormat.setOnClickListener(this);
		cbxConverage.setOnCheckedChangeListener(this);
		cbxRecordTime.setOnCheckedChangeListener(this);

	}

	private void findView() {
		tvSdTotal = (TextView) findViewById(R.id.tv_sd_total);
		tvSdRemain = (TextView) findViewById(R.id.tv_sd_remain);
		tvSdStatus = (TextView) findViewById(R.id.tv_state);
		btnFormat = (Button) findViewById(R.id.btn_format);
		cbxConverage = (CheckBox) findViewById(R.id.cbx_coverage);
		editRecordLength = (EditText) findViewById(R.id.edit_record_length);
		cbxRecordTime = (CheckBox) findViewById(R.id.cbx_record_time);
		btnBack = (Button) findViewById(R.id.back);
		btnOk = (Button) findViewById(R.id.ok);

		RelativeLayout layout = (RelativeLayout) findViewById(R.id.top);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.top_bg);
		BitmapDrawable drawable = new BitmapDrawable(bitmap);
		drawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
		drawable.setDither(true);
		layout.setBackgroundDrawable(drawable);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.ok:
			setSDCardSchedule();
			break;
		case R.id.btn_format:
			showFormatDialog();
			break;
		default:
			break;
		}
	}

	void showFormatDialog() {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		adb.setMessage(R.string.sdcard_formatsd);
		adb.setPositiveButton(R.string.str_ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Log.i("info", "格式化");
						NativeCaller.FormatSD(strDID);
						dialog.dismiss();
					}

				})
				.setNegativeButton(R.string.str_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						}).create().show();
	}

	// 20140226修改测试

	private void setSDCardSchedule() {

		if (sdcardBean.getRecord_time_enable() == 0) {
			sdcardBean.setSun_0(0);
			sdcardBean.setSun_1(0);
			sdcardBean.setSun_2(0);
			sdcardBean.setMon_0(0);
			sdcardBean.setMon_1(0);
			sdcardBean.setMon_2(0);
			sdcardBean.setTue_0(0);
			sdcardBean.setTue_1(0);
			sdcardBean.setTue_2(0);
			sdcardBean.setWed_0(0);
			sdcardBean.setWed_1(0);
			sdcardBean.setWed_2(0);
			sdcardBean.setThu_0(0);
			sdcardBean.setThu_1(0);
			sdcardBean.setThu_2(0);
			sdcardBean.setFri_0(0);
			sdcardBean.setFri_1(0);
			sdcardBean.setFri_2(0);
			sdcardBean.setSat_0(0);
			sdcardBean.setSat_1(0);
			sdcardBean.setSat_2(0);
		} else {
			sdcardBean.setSun_0(-1);
			sdcardBean.setSun_1(-1);
			sdcardBean.setSun_2(-1);
			sdcardBean.setMon_0(-1);
			sdcardBean.setMon_1(-1);
			sdcardBean.setMon_2(-1);
			sdcardBean.setTue_0(-1);
			sdcardBean.setTue_1(-1);
			sdcardBean.setTue_2(-1);
			sdcardBean.setWed_0(-1);
			sdcardBean.setWed_1(-1);
			sdcardBean.setWed_2(-1);
			sdcardBean.setThu_0(-1);
			sdcardBean.setThu_1(-1);
			sdcardBean.setThu_2(-1);
			sdcardBean.setFri_0(-1);
			sdcardBean.setFri_1(-1);
			sdcardBean.setFri_2(-1);
			sdcardBean.setSat_0(-1);
			sdcardBean.setSat_1(-1);
			sdcardBean.setSat_2(-1);
		}

		sdcardBean.setRecord_timer(15);
		NativeCaller.PPPPSDRecordSetting(strDID,
				sdcardBean.getRecord_conver_enable(),
				sdcardBean.getRecord_timer(), sdcardBean.getRecord_size(),sdcardBean.getRecord_chnl(),
				sdcardBean.getRecord_time_enable(), sdcardBean.getSun_0(),
				sdcardBean.getSun_1(), sdcardBean.getSun_2(),
				sdcardBean.getMon_0(), sdcardBean.getMon_1(),
				sdcardBean.getMon_2(), sdcardBean.getTue_0(),
				sdcardBean.getTue_1(), sdcardBean.getTue_2(),
				sdcardBean.getWed_0(), sdcardBean.getWed_1(),
				sdcardBean.getWed_2(), sdcardBean.getThu_0(),
				sdcardBean.getThu_1(), sdcardBean.getThu_2(),
				sdcardBean.getFri_0(), sdcardBean.getFri_1(),
				sdcardBean.getFri_2(), sdcardBean.getSat_0(),
				sdcardBean.getSat_1(), sdcardBean.getSat_2());

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onCheckedChanged(CompoundButton v, boolean isChecked) {
		switch (v.getId()) {
		// case R.id.cbx_coverage:
		// if (isChecked) {
		// sdcardBean.setRecord_conver_enable(1);
		// } else {
		// sdcardBean.setRecord_conver_enable(0);
		// }
		// break;
		case R.id.cbx_record_time:
			if (isChecked) {
				sdcardBean.setRecord_time_enable(1);
			} else {
				sdcardBean.setRecord_time_enable(0);
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void callBackRecordSchParams(String did, int record_cover_enable,
			int record_timer, int record_size, int record_time_enable,
			int record_schedule_sun_0, int record_schedule_sun_1,
			int record_schedule_sun_2, int record_schedule_mon_0,
			int record_schedule_mon_1, int record_schedule_mon_2,
			int record_schedule_tue_0, int record_schedule_tue_1,
			int record_schedule_tue_2, int record_schedule_wed_0,
			int record_schedule_wed_1, int record_schedule_wed_2,
			int record_schedule_thu_0, int record_schedule_thu_1,
			int record_schedule_thu_2, int record_schedule_fri_0,
			int record_schedule_fri_1, int record_schedule_fri_2,
			int record_schedule_sat_0, int record_schedule_sat_1,
			int record_schedule_sat_2, int record_sd_status, int sdtotal,
			int sdfree) {
		Log.i("info", "---record_cover_enable" + record_cover_enable
				+ "---record_time_enable" + record_time_enable
				+ "---record_timer" + record_timer);
		Log.i("info", "record_schedule_sun_0:" + record_schedule_sun_0
				+ ",record_schedule_sun_1:" + record_schedule_sun_1
				+ ",record_schedule_sun_2:" + record_schedule_sun_2
				+ ",record_schedule_mon_0:" + record_schedule_mon_0
				+ ",record_schedule_mon_1:" + record_schedule_mon_1
				+ ",record_schedule_mon_2:" + record_schedule_mon_2);
		sdcardBean.setDid(did);
		sdcardBean.setRecord_conver_enable(record_cover_enable);
		sdcardBean.setRecord_timer(record_timer);
		sdcardBean.setRecord_size(record_size);
		sdcardBean.setRecord_time_enable(record_time_enable);
		sdcardBean.setRecord_sd_status(record_sd_status);
		sdcardBean.setSdtotal(sdtotal);
		sdcardBean.setSdfree(sdfree);
		sdcardBean.setSun_0(record_schedule_sun_0);
		sdcardBean.setSun_1(record_schedule_sun_1);
		sdcardBean.setSun_2(record_schedule_sun_2);
		sdcardBean.setMon_0(record_schedule_mon_0);
		sdcardBean.setMon_1(record_schedule_mon_1);
		sdcardBean.setMon_2(record_schedule_mon_2);
		sdcardBean.setTue_0(record_schedule_tue_0);
		sdcardBean.setTue_1(record_schedule_tue_1);
		sdcardBean.setTue_2(record_schedule_tue_2);
		sdcardBean.setWed_0(record_schedule_wed_0);
		sdcardBean.setWed_1(record_schedule_wed_1);
		sdcardBean.setWed_2(record_schedule_wed_2);
		sdcardBean.setThu_0(record_schedule_thu_0);
		sdcardBean.setThu_1(record_schedule_thu_1);
		sdcardBean.setThu_2(record_schedule_thu_2);
		sdcardBean.setFri_0(record_schedule_fri_0);
		sdcardBean.setFri_1(record_schedule_fri_1);
		sdcardBean.setFri_2(record_schedule_fri_2);
		sdcardBean.setSat_0(record_schedule_sat_0);
		sdcardBean.setSat_1(record_schedule_sat_1);
		sdcardBean.setSat_2(record_schedule_sat_2);
		handler.sendEmptyMessage(PARAMS);
	}

	@Override
	public void callBackSetSystemParamsResult(String did, int paramType,
			int result) {
		Log.d("tag", "result:" + result + " paramType:" + paramType);
		if (strDID.equals(did)) {
			handler.sendEmptyMessage(result);
		}
	}
}


text:
class CreateContextsWordsJoinTable < ActiveRecord::Migration
  def self.up
  	 create_table :contexts_words, :id => false do |t|
	   t.integer :context_id
	   t.integer :word_id
	 end
  end

  def self.down
  	drop_table :contexts_words
  end
end

redpajama_set_name: RedPajamaGithub


text:
use strict;
use warnings;

use Regexp::Common qw /net/;
use Scalar::Util 'blessed';
use JIRA::REST;
use Git::Hooks;
use Try::Tiny;
use Carp qw(cluck confess);

our %cache;

my $osx_kernel = qr/darwin/i;
my $config;

BEGIN {
    if (-f $ENV{GIT_HOOK_CONFIG}) {
        my $xs = try {
            require YAML::XS;
            YAML::XS->import('LoadFile', 'Dump');
            1;
        };

        if (not $xs) {
            try {
                require YAML;
                YAML->import('LoadFile', 'Dump');
            } catch {
                confess "No YAML parser found. Please install either YAML::XS (recommended) or YAML";
            };
        }

        $config = LoadFile($ENV{GIT_HOOK_CONFIG});
    }
    else {
        confess "No config file found. Please create a YAML config file and export it to ENV{GIT_HOOK_CONFIG}";
    }
};

my $jira = JIRA::REST->new({
    url      => $config->{jira_url}       // $ENV{JIRA_URL},
    username => $config->{jira_username}  // $ENV{JIRA_USERNAME},
    password => $config->{jira_password}  // $ENV{JIRA_PASSWORD},
});

PRE_PUSH   sub { parse_commits('pre-push') };
POST_MERGE sub { parse_commits('post-merge') };

run_hook $0, @ARGV;

sub parse_commits {
    my $stage = shift;

    my $target     = _target_branch($stage);
    my $transition = _transition($stage);

    return unless $transition;
    return unless _server_ok();

    return if not $target or _current_branch() eq $target;

    my $out     = `git log origin/$target..HEAD`;
    my $tickets = _parse_log($out);

    return unless @$tickets;

    foreach my $tick (@$tickets) {
        my ($prefix, $num) = split '-', $tick;

        if (not $prefix and not $num) {
            _error("No ticket info found");
            return;
        }

        _advance_ticket($transition, $prefix, $num);
    }
}

sub _advance_ticket {
    my ($transition, $prefix, $num) = @_;

    try {
        my $issue = "$prefix-$num";

        print "Updating issue: $issue\n";

        my $resp = $jira->POST(
            '/issue/' . $issue . '/transitions?expand=transitions.fields',
            undef,
            {
                transition => {
                    id => 0 + $transition
                }
            }
       );
    } catch {
        cluck $_;
    };

    return;
}

sub _transition {
    my $key = shift;
    my $transition = $config->{$key}{transition};

    if (not $transition) {
        _error("No transition found for $key");
        return;
    }

    return $transition;
}

sub _target_branch {
    my $key    = shift;
    my $target = $config->{$key}{target_branch};

    if (not $target) {
        _error("No target_branch found for $key");
        return;
    }

    return $target;
}

sub _parse_log {
    my $out = shift;

    my @matches = $out =~ /\[(\w+-\d+)\]/g;
    my %seen    = ();

    return [ grep { !$seen{$_}++ } @matches ];
}

sub _current_branch {
    my $out = `git rev-parse --abbrev-ref HEAD`;

    chomp($out);

    return $out;
}

sub _server_ok {
    my $key = shift;
    my $current = _current_server();

    return 1 if $current eq '*';

    if (not $current) {
        _error("Cannot find current server");
        return;
    }

    my $target  = _target_server($key);

    return 1 if $current eq '*';
    return 1 if grep { $current eq $_ } @$target;
}

sub _target_server {
    my $key = shift;
    my $target = $config->{$key}{target_server};

    if (not $target) {
         _error("No target server found for $key");
        return [];
    }
    elsif (not @$target) {
        _error("Invalid data structure found for target server");
        return [];
    }

    return $target;
}

sub _ip_addr {
    if (_is_linux()) {
        my ($addr) = split ' ', `hostname -I`;
        return $addr;
    }
    elsif (_is_osx()) {
        return `ipconfig getifaddr en0`;
    }
    else {
        _error('Unsupported OS');
    }

    return;
}

sub _hostname {
    $cache{current_server} ||= `hostname`;

    return $cache{current_server};
}

sub _is_linux         { $^O =~ /linux/ }
sub _is_osx           { $^O =~ $osx_kernel }
sub _current_server   { _looks_like_ipv4(shift) ? _hostname() : _ip_addr() }
sub _looks_like_ipv4  { shift =~ /$RE{net}{IPv4}/ }
sub _error            { $ENV{GIT_HOOK_DEBUG} ? cluck shift : return }

exit 0;


text:
/**
 * Created by Adam on 2015.02.12..
 */
var grid = require('gridfs-stream');
var Promise = require('bluebird');
var mongoose = require('mongoose');

function DataStorage() {
    if (!(this instanceof DataStorage)) {
        return new DataStorage();
    }

    this.connection = null;
    this.gfs = null;
};

module.exports = DataStorage;

DataStorage.prototype.connect = function(host,db) {
    var self = this;
    return new Promise(function(resolve,reject) {
        mongoose.connect(uri(host, db), function (err) {
            if (err) {
                reject(err);
            } else {
                self.connection = mongoose.connection;
                self.gfs = grid(self.connection.db, mongoose.mongo);
                resolve();
            }
        });
    });
};

DataStorage.prototype.disconnect = function() {
    return new Promise(function(resolve,reject){
        mongoose.disconnect(function(err){
            if (err) {
                reject(err);
            } else {
                resolve();
            }
        });
    });
};

var states = [
    'disconnected',
    'connected',
    'connecting',
    'disconnecting'
]

DataStorage.prototype.state = function() {
    var code = this.connection.readyState;
    return {
        'text':states[code],
        'code':code
    };
};

DataStorage.prototype.stateAsync = function() {
    return Promise.resolve(this.state());
}

DataStorage.prototype.readAsync = function(fname) {
    return Promise.all([
        this.metaAsync(fname),
        this.streamAsync(fname)
    ]);
};

DataStorage.prototype.metaAsync = function(fname) {
    var self = this;
    return new Promise(function(resolve,reject){
        self.gfs.files.findOne({filename:fname},function(err,meta){
            if (err) {
                reject(err);
            } else {
                resolve(meta);
            }
        });
    });
};

DataStorage.prototype.streamAsync = function(fname) {
    return Promise.resolve(this.gfs.createReadStream({
        filename:fname
    }));
}

function uri(host,db) {
    return 'mongodb://' + host + '/' + db;
}


text:
"""
This module is the disconnect command of bowl.

Created on 15 March 2014
@author: Charlie Lewis
"""
import ast
import fileinput
import os

class disconnect(object):
    """
    This class is responsible for the disconnect command of the cli.
    """
    @classmethod
    def main(self, args):
        # !! TODO needs to implement login if using that

        try:
            directory = args.metadata_path
            directory = os.path.expanduser(directory)
            # !! TODO need to do check if specfied host was not there to begin with
            for line in fileinput.input(os.path.join(directory, "hosts"), inplace=True):
                host = ast.literal_eval(line.rstrip('\n'))
                if args.DOCKER_HOST != host['title']:
                    print "%s" % (line),
        except:
            print "unable to remove docker host"
            return False
        return True


text:
<base href="http://www.366.ru/">

    Test for bug 19884
    Locating a store at www.366.ru doesn't work.

FAIL

<form id="t" action="" onsubmit="return true"><input name=a value=b></form>


text:
const SwaggerController = {
  doc (req, res) {
    res.status(200).jsonx(sails.hooks.swagger.doc)
  },

  ui (req, res) {
    let docUrl = req.protocol + '://' + req.get('Host') + '/swagger/doc';
    res.redirect(sails.config.swagger.ui.url + '?url=' + encodeURIComponent(docUrl))
  }
};

module.exports = SwaggerController;


text:
package io.questions.testdata

import io.questions.model.questionnaire.FieldName.FieldNameStringSyntax
import io.questions.model.questionnaire.QuestionText.QuestionTextSyntax
import io.questions.model.questionnaire.nodekey.NodeKey
import io.questions.model.questionnaire.{ Element, QuestionnaireId, QuestionnaireNode, QuestionnaireNodePredicate }
import io.questions.testdata.samples.questions.PersonalQuestions
import io.questions.testdata.samples.samplequestionnaire.QuestionTypes._
import io.questions.testdata.samples.enumerations.{ Title, YesNo }

object OfficerQuestionnaire {
  val id: QuestionnaireId = QuestionnaireId.random

  val officerNameFromOpenCorporates: QuestionnaireNode =
    stringQuestion("officerName".fieldName, "Officer Name (OpenCorporates)".text).copy(editability = QuestionnaireNodePredicate.False)

  val officerName: QuestionnaireNode =
    PersonalQuestions.currentFullName

//  val favouritePet: QuestionnaireNode =
//    stringQuestion("pet".fieldName, "Favourite Pet".text)

  val informationSection: QuestionnaireNode = pageQuestion(
    "information".fieldName,
    "Officer Information".text,
    officerNameFromOpenCorporates,
    officerName
//    ,favouritePet
  )

  val approvalQuestion: QuestionnaireNode =
    ExampleComponents.approvalQuestion("applicationApproved".fieldName, "Do you approve this officer?".text)

  val approvalPage: QuestionnaireNode = pageQuestion(
    "approvalPage".fieldName,
    "Approval".text,
    approvalQuestion
  )

  val questionnaire: QuestionnaireNode = ExampleComponents.standard(
    NodeKey.random,
    "officer".fieldName,
    "Officer".text,
    Element.NonRepeatingParent(
      informationSection,
      approvalPage
    ),
    enums = Map(
      YesNo.name → YesNo.values,
      Title.name → Title.values
    ),
    questionnaireId = id
  )
}


text:
// # Has Helper
// Usage: `{{#has tag="video, music"}}`, `{{#has author="sam, pat"}}`
//        `{{#has author="count:1"}}`, `{{#has tag="count:>1"}}`
//
// Checks if a post has a particular property

var proxy = require('./proxy'),
    _ = require('lodash'),
    logging = proxy.logging,
    i18n = proxy.i18n,
    validAttrs = ['tag', 'author', 'slug', 'id', 'number', 'index', 'any', 'all'];

function handleCount(ctxAttr, data) {
    let count;

    if (ctxAttr.match(/count:\d+/)) {
        count = Number(ctxAttr.match(/count:(\d+)/)[1]);
        return count === data.length;
    } else if (ctxAttr.match(/count:>\d/)) {
        count = Number(ctxAttr.match(/count:>(\d+)/)[1]);
        return count < data.length;
    } else if (ctxAttr.match(/count:<\d/)) {
        count = Number(ctxAttr.match(/count:<(\d+)/)[1]);
        return count > data.length;
    }

    return false;
}

function evaluateTagList(expr, tags) {
    return expr.split(',').map(function (v) {
        return v.trim();
    }).reduce(function (p, c) {
        return p || (_.findIndex(tags, function (item) {
            // Escape regex special characters
            item = item.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
            item = new RegExp('^' + item + '$', 'i');
            return item.test(c);
        }) !== -1);
    }, false);
}

function handleTag(data, attrs) {
    if (!attrs.tag) {
        return false;
    }

    if (attrs.tag.match(/count:/)) {
        return handleCount(attrs.tag, data.tags);
    }

    return evaluateTagList(attrs.tag, _.map(data.tags, 'name')) || false;
}

function evaluateAuthorList(expr, authors) {
    var authorList = expr.split(',').map(function (v) {
        return v.trim().toLocaleLowerCase();
    });

    return _.filter(authors, (author) => {
        return _.includes(authorList, author.name.toLocaleLowerCase());
    }).length;
}

function handleAuthor(data, attrs) {
    if (!attrs.author) {
        return false;
    }

    if (attrs.author.match(/count:/)) {
        return handleCount(attrs.author, data.authors);
    }

    return evaluateAuthorList(attrs.author, data.authors) || false;
}

function evaluateIntegerMatch(expr, integer) {
    var nthMatch = expr.match(/^nth:(\d+)/);
    if (nthMatch) {
        return integer % parseInt(nthMatch[1], 10) === 0;
    }

    return expr.split(',').reduce(function (bool, _integer) {
        return bool || parseInt(_integer, 10) === integer;
    }, false);
}

function evaluateStringMatch(expr, str, ci) {
    if (ci) {
        return expr && str && expr.toLocaleLowerCase() === str.toLocaleLowerCase();
    }

    return expr === str;
}

/**
 *
 * @param {String} type - either some or every - the lodash function to use
 * @param {String} expr - the attribute value passed into {{#has}}
 * @param {Object} obj - "this" context from the helper
 * @param {Object} data - global params
 */
function evaluateList(type, expr, obj, data) {
    return expr.split(',').map(function (prop) {
        return prop.trim().toLocaleLowerCase();
    })[type](function (prop) {
        if (prop.match(/^@/)) {
            return _.has(data, prop.replace(/@/, '')) && !_.isEmpty(_.get(data, prop.replace(/@/, '')));
        } else {
            return _.has(obj, prop) && !_.isEmpty(_.get(obj, prop));
        }
    });
}

module.exports = function has(options) {
    options = options || {};
    options.hash = options.hash || {};
    options.data = options.data || {};

    var self = this,
        attrs = _.pick(options.hash, validAttrs),
        data = _.pick(options.data, ['blog', 'config', 'labs']),
        checks = {
            tag: function () {
                return handleTag(self, attrs);
            },
            author: function () {
                return handleAuthor(self, attrs);
            },
            number: function () {
                return attrs.number && evaluateIntegerMatch(attrs.number, options.data.number) || false;
            },
            index: function () {
                return attrs.index && evaluateIntegerMatch(attrs.index, options.data.index) || false;
            },
            slug: function () {
                return attrs.slug && evaluateStringMatch(attrs.slug, self.slug, true) || false;
            },
            id: function () {
                return attrs.id && evaluateStringMatch(attrs.id, self.id, true) || false;
            },
            any: function () {
                return attrs.any && evaluateList('some', attrs.any, self, data) || false;
            },
            all: function () {
                return attrs.all && evaluateList('every', attrs.all, self, data) || false;
            }
        },
        result;

    if (_.isEmpty(attrs)) {
        logging.warn(i18n.t('warnings.helpers.has.invalidAttribute'));
        return;
    }

    result = _.some(attrs, function (value, attr) {
        return checks[attr]();
    });

    if (result) {
        return options.fn(this);
    }

    return options.inverse(this);
};


text:
.class public abstract Lcom/activeandroid/Model;
.super Ljava/lang/Object;

# instance fields
.field private mId:Ljava/lang/Long;
    .annotation runtime Lcom/activeandroid/annotation/Column;
        name = "Id"
    .end annotation
.end field

.field private mTableInfo:Lcom/activeandroid/TableInfo;

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0}, Lcom/activeandroid/Cache;->getTableInfo(Ljava/lang/Class;)Lcom/activeandroid/TableInfo;

    move-result-object v0

    iput-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-static {p0}, Lcom/activeandroid/Cache;->addEntity(Lcom/activeandroid/Model;)V

    return-void
.end method

.method public static delete(Ljava/lang/Class;J)V
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/Class",
            "<+",
            "Lcom/activeandroid/Model;",
            ">;J)V"
        }
    .end annotation

    new-instance v0, Lcom/activeandroid/query/Delete;

    invoke-direct {v0}, Lcom/activeandroid/query/Delete;-><init>()V

    invoke-virtual {v0, p0}, Lcom/activeandroid/query/Delete;->from(Ljava/lang/Class;)Lcom/activeandroid/query/From;

    move-result-object v0

    const-string v1, "Id=?"

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Object;

    const/4 v3, 0x0

    invoke-static {p1, p2}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v4

    aput-object v4, v2, v3

    invoke-virtual {v0, v1, v2}, Lcom/activeandroid/query/From;->where(Ljava/lang/String;[Ljava/lang/Object;)Lcom/activeandroid/query/From;

    move-result-object v0

    invoke-virtual {v0}, Lcom/activeandroid/query/From;->execute()Ljava/util/List;

    return-void
.end method

.method public static load(Ljava/lang/Class;J)Lcom/activeandroid/Model;
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<T:",
            "Lcom/activeandroid/Model;",
            ">(",
            "Ljava/lang/Class",
            "<+",
            "Lcom/activeandroid/Model;",
            ">;J)TT;"
        }
    .end annotation

    new-instance v0, Lcom/activeandroid/query/Select;

    invoke-direct {v0}, Lcom/activeandroid/query/Select;-><init>()V

    invoke-virtual {v0, p0}, Lcom/activeandroid/query/Select;->from(Ljava/lang/Class;)Lcom/activeandroid/query/From;

    move-result-object v0

    const-string v1, "Id=?"

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Object;

    const/4 v3, 0x0

    invoke-static {p1, p2}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v4

    aput-object v4, v2, v3

    invoke-virtual {v0, v1, v2}, Lcom/activeandroid/query/From;->where(Ljava/lang/String;[Ljava/lang/Object;)Lcom/activeandroid/query/From;

    move-result-object v0

    invoke-virtual {v0}, Lcom/activeandroid/query/From;->executeSingle()Lcom/activeandroid/Model;

    move-result-object v0

    return-object v0
.end method

# virtual methods
.method public final delete()V
    .locals 6

    invoke-static {}, Lcom/activeandroid/Cache;->openDatabase()Landroid/database/sqlite/SQLiteDatabase;

    move-result-object v0

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v1

    const-string v2, "Id=?"

    const/4 v3, 0x1

    new-array v3, v3, [Ljava/lang/String;

    const/4 v4, 0x0

    invoke-virtual {p0}, Lcom/activeandroid/Model;->getId()Ljava/lang/Long;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/Long;->toString()Ljava/lang/String;

    move-result-object v5

    aput-object v5, v3, v4

    invoke-virtual {v0, v1, v2, v3}, Landroid/database/sqlite/SQLiteDatabase;->delete(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)I

    invoke-static {p0}, Lcom/activeandroid/Cache;->removeEntity(Lcom/activeandroid/Model;)V

    invoke-static {}, Lcom/activeandroid/Cache;->getContext()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1}, Lcom/activeandroid/TableInfo;->getType()Ljava/lang/Class;

    move-result-object v1

    iget-object v2, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    invoke-static {v1, v2}, Lcom/activeandroid/content/ContentProvider;->createUri(Ljava/lang/Class;Ljava/lang/Long;)Landroid/net/Uri;

    move-result-object v1

    const/4 v2, 0x0

    invoke-virtual {v0, v1, v2}, Landroid/content/ContentResolver;->notifyChange(Landroid/net/Uri;Landroid/database/ContentObserver;)V

    return-void
.end method

.method public equals(Ljava/lang/Object;)Z
    .locals 2

    check-cast p1, Lcom/activeandroid/Model;

    iget-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v0}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v0

    iget-object v1, p1, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    iget-object v1, p1, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    invoke-virtual {v0, v1}, Ljava/lang/Long;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public final getId()Ljava/lang/Long;
    .locals 1

    iget-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    return-object v0
.end method

.method protected final getMany(Ljava/lang/Class;Ljava/lang/String;)Ljava/util/List;
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Lcom/activeandroid/Model;",
            ">(",
            "Ljava/lang/Class",
            "<+",
            "Lcom/activeandroid/Model;",
            ">;",
            "Ljava/lang/String;",
            ")",
            "Ljava/util/List",
            "<TE;>;"
        }
    .end annotation

    new-instance v0, Lcom/activeandroid/query/Select;

    invoke-direct {v0}, Lcom/activeandroid/query/Select;-><init>()V

    invoke-virtual {v0, p1}, Lcom/activeandroid/query/Select;->from(Ljava/lang/Class;)Lcom/activeandroid/query/From;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-static {p1}, Lcom/activeandroid/Cache;->getTableName(Ljava/lang/Class;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, "."

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, "=?"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/Object;

    const/4 v3, 0x0

    invoke-virtual {p0}, Lcom/activeandroid/Model;->getId()Ljava/lang/Long;

    move-result-object v4

    aput-object v4, v2, v3

    invoke-virtual {v0, v1, v2}, Lcom/activeandroid/query/From;->where(Ljava/lang/String;[Ljava/lang/Object;)Lcom/activeandroid/query/From;

    move-result-object v0

    invoke-virtual {v0}, Lcom/activeandroid/query/From;->execute()Ljava/util/List;

    move-result-object v0

    return-object v0
.end method

.method public final loadFromCursor(Landroid/database/Cursor;)V
    .locals 14

    const/4 v2, 0x0

    const/4 v3, 0x1

    const/4 v4, 0x0

    iget-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v0}, Lcom/activeandroid/TableInfo;->getFields()Ljava/util/Collection;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v6

    :cond_0
    :goto_0
    invoke-interface {v6}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_19

    invoke-interface {v6}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/reflect/Field;

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1, v0}, Lcom/activeandroid/TableInfo;->getColumnName(Ljava/lang/reflect/Field;)Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v0}, Ljava/lang/reflect/Field;->getType()Ljava/lang/Class;

    move-result-object v1

    invoke-interface {p1, v5}, Landroid/database/Cursor;->getColumnIndex(Ljava/lang/String;)I

    move-result v7

    if-ltz v7, :cond_0

    invoke-virtual {v0, v3}, Ljava/lang/reflect/Field;->setAccessible(Z)V

    :try_start_0
    invoke-interface {p1, v7}, Landroid/database/Cursor;->isNull(I)Z

    move-result v8

    invoke-static {v1}, Lcom/activeandroid/Cache;->getParserForType(Ljava/lang/Class;)Lcom/activeandroid/serializer/TypeSerializer;

    move-result-object v9

    if-eqz v9, :cond_1b

    invoke-virtual {v9}, Lcom/activeandroid/serializer/TypeSerializer;->getSerializedType()Ljava/lang/Class;

    move-result-object v1

    move-object v5, v1

    :goto_1
    if-eqz v8, :cond_2

    move-object v0, v2

    move-object v1, v2

    :goto_2
    if-eqz v9, :cond_1

    if-nez v8, :cond_1

    invoke-virtual {v9, v0}, Lcom/activeandroid/serializer/TypeSerializer;->deserialize(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    :cond_1
    if-eqz v0, :cond_0

    invoke-virtual {v1, p0, v0}, Ljava/lang/reflect/Field;->set(Ljava/lang/Object;Ljava/lang/Object;)V
    :try_end_0
    .catch Ljava/lang/IllegalArgumentException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/lang/SecurityException; {:try_start_0 .. :try_end_0} :catch_2

    goto :goto_0

    :catch_0
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-static {v1, v0}, Lcom/activeandroid/util/Log;->e(Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    :cond_2
    :try_start_1
    const-class v1, Ljava/lang/Byte;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_3

    sget-object v1, Ljava/lang/Byte;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_4

    :cond_3
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getInt(I)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto :goto_2

    :cond_4
    const-class v1, Ljava/lang/Short;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_5

    sget-object v1, Ljava/lang/Short;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_6

    :cond_5
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getInt(I)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto :goto_2

    :cond_6
    const-class v1, Ljava/lang/Integer;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_7

    sget-object v1, Ljava/lang/Integer;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_8

    :cond_7
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getInt(I)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto :goto_2

    :cond_8
    const-class v1, Ljava/lang/Long;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_9

    sget-object v1, Ljava/lang/Long;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_a

    :cond_9
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v10

    invoke-static {v10, v11}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_a
    const-class v1, Ljava/lang/Float;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_b

    sget-object v1, Ljava/lang/Float;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_c

    :cond_b
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getFloat(I)F

    move-result v1

    invoke-static {v1}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_c
    const-class v1, Ljava/lang/Double;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_d

    sget-object v1, Ljava/lang/Double;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_e

    :cond_d
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getDouble(I)D

    move-result-wide v10

    invoke-static {v10, v11}, Ljava/lang/Double;->valueOf(D)Ljava/lang/Double;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_e
    const-class v1, Ljava/lang/Boolean;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_f

    sget-object v1, Ljava/lang/Boolean;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_11

    :cond_f
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getInt(I)I

    move-result v1

    if-eqz v1, :cond_10

    move v1, v3

    :goto_3
    invoke-static {v1}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_10
    move v1, v4

    goto :goto_3

    :cond_11
    const-class v1, Ljava/lang/Character;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_12

    sget-object v1, Ljava/lang/Character;->TYPE:Ljava/lang/Class;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_13

    :cond_12
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v1

    const/4 v5, 0x0

    invoke-virtual {v1, v5}, Ljava/lang/String;->charAt(I)C

    move-result v1

    invoke-static {v1}, Ljava/lang/Character;->valueOf(C)Ljava/lang/Character;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_13
    const-class v1, Ljava/lang/String;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_14

    invoke-interface {p1, v7}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_14
    const-class v1, [Ljava/lang/Byte;

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_15

    const-class v1, [B

    invoke-virtual {v5, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_16

    :cond_15
    invoke-interface {p1, v7}, Landroid/database/Cursor;->getBlob(I)[B

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_16
    invoke-static {v5}, Lcom/activeandroid/util/ReflectionUtils;->isModel(Ljava/lang/Class;)Z

    move-result v1

    if-eqz v1, :cond_18

    invoke-interface {p1, v7}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v10

    invoke-static {v5, v10, v11}, Lcom/activeandroid/Cache;->getEntity(Ljava/lang/Class;J)Lcom/activeandroid/Model;

    move-result-object v1

    if-nez v1, :cond_17

    new-instance v1, Lcom/activeandroid/query/Select;

    invoke-direct {v1}, Lcom/activeandroid/query/Select;-><init>()V

    invoke-virtual {v1, v5}, Lcom/activeandroid/query/Select;->from(Ljava/lang/Class;)Lcom/activeandroid/query/From;

    move-result-object v1

    const-string v5, "Id=?"

    const/4 v7, 0x1

    new-array v7, v7, [Ljava/lang/Object;

    const/4 v12, 0x0

    invoke-static {v10, v11}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v10

    aput-object v10, v7, v12

    invoke-virtual {v1, v5, v7}, Lcom/activeandroid/query/From;->where(Ljava/lang/String;[Ljava/lang/Object;)Lcom/activeandroid/query/From;

    move-result-object v1

    invoke-virtual {v1}, Lcom/activeandroid/query/From;->executeSingle()Lcom/activeandroid/Model;

    move-result-object v1

    :cond_17
    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :cond_18
    const-class v1, Ljava/lang/Enum;

    invoke-static {v5, v1}, Lcom/activeandroid/util/ReflectionUtils;->isSubclassOf(Ljava/lang/Class;Ljava/lang/Class;)Z

    move-result v1

    if-eqz v1, :cond_1a

    invoke-interface {p1, v7}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v1

    invoke-static {v5, v1}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
    :try_end_1
    .catch Ljava/lang/IllegalArgumentException; {:try_start_1 .. :try_end_1} :catch_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_1 .. :try_end_1} :catch_1
    .catch Ljava/lang/SecurityException; {:try_start_1 .. :try_end_1} :catch_2

    move-result-object v1

    move-object v13, v1

    move-object v1, v0

    move-object v0, v13

    goto/16 :goto_2

    :catch_1
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-static {v1, v0}, Lcom/activeandroid/util/Log;->e(Ljava/lang/String;Ljava/lang/Throwable;)I

    goto/16 :goto_0

    :catch_2
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-static {v1, v0}, Lcom/activeandroid/util/Log;->e(Ljava/lang/String;Ljava/lang/Throwable;)I

    goto/16 :goto_0

    :cond_19
    return-void

    :cond_1a
    move-object v1, v0

    move-object v0, v2

    goto/16 :goto_2

    :cond_1b
    move-object v5, v1

    goto/16 :goto_1
.end method

.method public final save()V
    .locals 12

    const/4 v11, 0x1

    const/4 v10, 0x0

    invoke-static {}, Lcom/activeandroid/Cache;->openDatabase()Landroid/database/sqlite/SQLiteDatabase;

    move-result-object v2

    new-instance v3, Landroid/content/ContentValues;

    invoke-direct {v3}, Landroid/content/ContentValues;-><init>()V

    iget-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v0}, Lcom/activeandroid/TableInfo;->getFields()Ljava/util/Collection;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v4

    :cond_0
    :goto_0
    invoke-interface {v4}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_17

    invoke-interface {v4}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/reflect/Field;

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1, v0}, Lcom/activeandroid/TableInfo;->getColumnName(Ljava/lang/reflect/Field;)Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v0}, Ljava/lang/reflect/Field;->getType()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v0, v11}, Ljava/lang/reflect/Field;->setAccessible(Z)V

    :try_start_0
    invoke-virtual {v0, p0}, Ljava/lang/reflect/Field;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    if-eqz v0, :cond_1

    invoke-static {v1}, Lcom/activeandroid/Cache;->getParserForType(Ljava/lang/Class;)Lcom/activeandroid/serializer/TypeSerializer;

    move-result-object v6

    if-eqz v6, :cond_1

    invoke-virtual {v6, v0}, Lcom/activeandroid/serializer/TypeSerializer;->serialize(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    if-eqz v0, :cond_1

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v6}, Lcom/activeandroid/serializer/TypeSerializer;->getSerializedType()Ljava/lang/Class;

    move-result-object v7

    invoke-virtual {v1, v7}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v7

    if-nez v7, :cond_1

    const-string v7, "TypeSerializer returned wrong type: expected a %s but got a %s"

    const/4 v8, 0x2

    new-array v8, v8, [Ljava/lang/Object;

    const/4 v9, 0x0

    invoke-virtual {v6}, Lcom/activeandroid/serializer/TypeSerializer;->getSerializedType()Ljava/lang/Class;

    move-result-object v6

    aput-object v6, v8, v9

    const/4 v6, 0x1

    aput-object v1, v8, v6

    invoke-static {v7, v8}, Ljava/lang/String;->format(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v6

    invoke-static {v6}, Lcom/activeandroid/util/Log;->w(Ljava/lang/String;)I

    :cond_1
    if-nez v0, :cond_2

    invoke-virtual {v3, v5}, Landroid/content/ContentValues;->putNull(Ljava/lang/String;)V
    :try_end_0
    .catch Ljava/lang/IllegalArgumentException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_0 .. :try_end_0} :catch_1

    goto :goto_0

    :catch_0
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-static {v1, v0}, Lcom/activeandroid/util/Log;->e(Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    :cond_2
    :try_start_1
    const-class v6, Ljava/lang/Byte;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_3

    sget-object v6, Ljava/lang/Byte;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_4

    :cond_3
    check-cast v0, Ljava/lang/Byte;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Byte;)V
    :try_end_1
    .catch Ljava/lang/IllegalArgumentException; {:try_start_1 .. :try_end_1} :catch_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_1 .. :try_end_1} :catch_1

    goto :goto_0

    :catch_1
    move-exception v0

    invoke-virtual {v0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-static {v1, v0}, Lcom/activeandroid/util/Log;->e(Ljava/lang/String;Ljava/lang/Throwable;)I

    goto/16 :goto_0

    :cond_4
    :try_start_2
    const-class v6, Ljava/lang/Short;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_5

    sget-object v6, Ljava/lang/Short;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_6

    :cond_5
    check-cast v0, Ljava/lang/Short;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Short;)V

    goto/16 :goto_0

    :cond_6
    const-class v6, Ljava/lang/Integer;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_7

    sget-object v6, Ljava/lang/Integer;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_8

    :cond_7
    check-cast v0, Ljava/lang/Integer;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V

    goto/16 :goto_0

    :cond_8
    const-class v6, Ljava/lang/Long;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_9

    sget-object v6, Ljava/lang/Long;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_a

    :cond_9
    check-cast v0, Ljava/lang/Long;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Long;)V

    goto/16 :goto_0

    :cond_a
    const-class v6, Ljava/lang/Float;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_b

    sget-object v6, Ljava/lang/Float;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_c

    :cond_b
    check-cast v0, Ljava/lang/Float;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Float;)V

    goto/16 :goto_0

    :cond_c
    const-class v6, Ljava/lang/Double;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_d

    sget-object v6, Ljava/lang/Double;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_e

    :cond_d
    check-cast v0, Ljava/lang/Double;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Double;)V

    goto/16 :goto_0

    :cond_e
    const-class v6, Ljava/lang/Boolean;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_f

    sget-object v6, Ljava/lang/Boolean;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_10

    :cond_f
    check-cast v0, Ljava/lang/Boolean;

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Boolean;)V

    goto/16 :goto_0

    :cond_10
    const-class v6, Ljava/lang/Character;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_11

    sget-object v6, Ljava/lang/Character;->TYPE:Ljava/lang/Class;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_12

    :cond_11
    invoke-virtual {v0}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/String;)V

    goto/16 :goto_0

    :cond_12
    const-class v6, Ljava/lang/String;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_13

    invoke-virtual {v0}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/String;)V

    goto/16 :goto_0

    :cond_13
    const-class v6, [Ljava/lang/Byte;

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-nez v6, :cond_14

    const-class v6, [B

    invoke-virtual {v1, v6}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v6

    if-eqz v6, :cond_15

    :cond_14
    check-cast v0, [B

    check-cast v0, [B

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;[B)V

    goto/16 :goto_0

    :cond_15
    invoke-static {v1}, Lcom/activeandroid/util/ReflectionUtils;->isModel(Ljava/lang/Class;)Z

    move-result v6

    if-eqz v6, :cond_16

    check-cast v0, Lcom/activeandroid/Model;

    invoke-virtual {v0}, Lcom/activeandroid/Model;->getId()Ljava/lang/Long;

    move-result-object v0

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Long;)V

    goto/16 :goto_0

    :cond_16
    const-class v6, Ljava/lang/Enum;

    invoke-static {v1, v6}, Lcom/activeandroid/util/ReflectionUtils;->isSubclassOf(Ljava/lang/Class;Ljava/lang/Class;)Z

    move-result v1

    if-eqz v1, :cond_0

    check-cast v0, Ljava/lang/Enum;

    invoke-virtual {v0}, Ljava/lang/Enum;->name()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v3, v5, v0}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/String;)V
    :try_end_2
    .catch Ljava/lang/IllegalArgumentException; {:try_start_2 .. :try_end_2} :catch_0
    .catch Ljava/lang/IllegalAccessException; {:try_start_2 .. :try_end_2} :catch_1

    goto/16 :goto_0

    :cond_17
    iget-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    if-nez v0, :cond_18

    iget-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v0}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v2, v0, v10, v3}, Landroid/database/sqlite/SQLiteDatabase;->insert(Ljava/lang/String;Ljava/lang/String;Landroid/content/ContentValues;)J

    move-result-wide v0

    invoke-static {v0, v1}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v0

    iput-object v0, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    :goto_1
    invoke-static {}, Lcom/activeandroid/Cache;->getContext()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1}, Lcom/activeandroid/TableInfo;->getType()Ljava/lang/Class;

    move-result-object v1

    iget-object v2, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    invoke-static {v1, v2}, Lcom/activeandroid/content/ContentProvider;->createUri(Ljava/lang/Class;Ljava/lang/Long;)Landroid/net/Uri;

    move-result-object v1

    invoke-virtual {v0, v1, v10}, Landroid/content/ContentResolver;->notifyChange(Landroid/net/Uri;Landroid/database/ContentObserver;)V

    return-void

    :cond_18
    iget-object v0, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v0}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Id="

    invoke-virtual {v1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v4, p0, Lcom/activeandroid/Model;->mId:Ljava/lang/Long;

    invoke-virtual {v1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v2, v0, v3, v1, v10}, Landroid/database/sqlite/SQLiteDatabase;->update(Ljava/lang/String;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I

    goto :goto_1
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    iget-object v1, p0, Lcom/activeandroid/Model;->mTableInfo:Lcom/activeandroid/TableInfo;

    invoke-virtual {v1}, Lcom/activeandroid/TableInfo;->getTableName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, "@"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {p0}, Lcom/activeandroid/Model;->getId()Ljava/lang/Long;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
package org.pentaho.di.core.database.util;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.core.database.DataSourceNamingException;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.UUID;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.pentaho.di.core.database.DataSourceProviderInterface.DatasourceType;

public class DatabaseUtilTest {
  private Context context;
  private String testName;

  @Before
  public void setup() {
    DatabaseUtil.clearDSCache();
    context = mock( Context.class );
    testName = "testName";
  }

  @After
  public void tearDown() {
    DatabaseUtil.clearDSCache();
  }

  @Test( expected = NamingException.class )
  public void testNullName() throws NamingException {
    DatabaseUtil.getDataSourceFromJndi( null, context );
  }

  @Test( expected = NamingException.class )
  public void testEmptyName() throws NamingException {
    DatabaseUtil.getDataSourceFromJndi( "", context );
  }

  @Test( expected = NamingException.class )
  public void testWrongType() throws NamingException {
    when( context.lookup( anyString() ) ).thenReturn( new Object() );
    DatabaseUtil.getDataSourceFromJndi( testName, context );
  }

  @Test( expected = NamingException.class )
  public void testNotFound() throws NamingException {
    when( context.lookup( anyString() ) ).thenThrow( new NamingException() );
    try {
      DatabaseUtil.getDataSourceFromJndi( testName, context );
    } catch ( NamingException ne ) {
      verify( context.lookup( testName ) );
      verify( context.lookup( "java:" + testName ) );
      verify( context.lookup( "java:comp/env/jdbc/" + testName ) );
      verify( context.lookup( "jdbc/" + testName ) );
      throw ne;
    }
  }

  @Test
  public void testCl() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( testName ) ).thenReturn( dataSource );
    DatabaseUtil util = new DatabaseUtil();
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    ClassLoader cl = mock( ClassLoader.class );
    try {
      Thread.currentThread().setContextClassLoader( cl );
      util.getNamedDataSource( testName );
    } catch ( Exception ex ) {
    } finally {
      try {
        verify( cl, never() ).loadClass( anyString() );
        verify( cl, never() ).getResource( anyString() );
        verify( cl, never() ).getResourceAsStream( anyString() );
      } catch ( Exception ex ) {
      }
      Thread.currentThread().setContextClassLoader( orig );
    }
  }

  @Test
  public void testNormal() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( testName ) ).thenReturn( dataSource );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
  }

  @Test
  public void testJBoss() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( "java:" + testName ) ).thenReturn( dataSource );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
  }

  @Test
  public void testTomcat() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( "java:comp/env/jdbc/" + testName ) ).thenReturn( dataSource );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
  }

  @Test
  public void testOther() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( "jdbc/" + testName ) ).thenReturn( dataSource );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
  }

  @Test
  public void testCaching() throws NamingException {
    DataSource dataSource = mock( DataSource.class );
    when( context.lookup( testName ) ).thenReturn( dataSource ).thenThrow( new NullPointerException() );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
    assertEquals( dataSource, DatabaseUtil.getDataSourceFromJndi( testName, context ) );
  }

  @Test
  public void testInvalidateNamedDataSource() throws DataSourceNamingException, NamingException {
    DatabaseUtil dsp = new DatabaseUtil();
    String namedDatasource = UUID.randomUUID().toString();
    DataSource dataSource = mock( DataSource.class );

    assertEquals( null, dsp.invalidateNamedDataSource( namedDatasource, DatasourceType.POOLED ) );
    when( context.lookup( namedDatasource ) ).thenReturn( dataSource );
    DatabaseUtil.getDataSourceFromJndi( namedDatasource, context );
    assertEquals( dataSource, dsp.invalidateNamedDataSource( namedDatasource, DatasourceType.POOLED ) );
    assertEquals( null, dsp.invalidateNamedDataSource( namedDatasource, DatasourceType.POOLED ) );
  }

}


text:
title:      Bambi
lang:       fr
tags:       [lumière, photo, neige, nuit]
---

Rien de tel qu'une biche lumineuse pour faire plaisir aux enfants durant les fêtes de fin d'année. Et quand la neige est là, c'est encore plus magique !

<figure>
  {% picture bambi.jpg %}
  <figcaption>
    Bambi
  </figcaption>
</figure>


text:
package org.jboss.hal.client.configuration.subsystem.mail;

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

import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.ModelNodeHelper;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.Property;
import org.jboss.hal.resources.Names;

import static org.jboss.hal.dmr.ModelDescriptionConstants.OUTBOUND_SOCKET_BINDING_REF;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SERVER;

class MailSession extends NamedNode {

    MailSession(Property property) {
        super(property);
    }

    MailSession(final String name, final ModelNode node) {
        super(name, node);
    }

    List<String> getServers() {
        List<String> servers = new ArrayList<>();
        if (hasServer(ModelDescriptionConstants.SMTP)) {
            servers.add(ModelDescriptionConstants.SMTP.toUpperCase());
        }
        if (hasServer(ModelDescriptionConstants.IMAP)) {
            servers.add(ModelDescriptionConstants.IMAP.toUpperCase());
        }
        if (hasServer(ModelDescriptionConstants.POP3)) {
            servers.add(ModelDescriptionConstants.POP3.toUpperCase());
        }
        return servers;
    }

    boolean hasServer(String name) {
        return hasDefined(SERVER) && get(SERVER).hasDefined(name);
    }

    String getServerSocketBinding(String name) {
        ModelNode node = ModelNodeHelper.failSafeGet(this, SERVER + "/" + name + "/" + OUTBOUND_SOCKET_BINDING_REF);
        return node.isDefined() ? node.asString() : Names.NOT_AVAILABLE;
    }
}


text:
OpenBLAS is an optimized BLAS library based on GotoBLAS2 1.13 BSD version. OpenBLAS is an open source project supported by Lab of Parallel Software and Computational Science, ISCAS <http://www.rdcps.ac.cn>.

Please read the documents on OpenBLAS wiki pages <http://github.com/xianyi/OpenBLAS/wiki>.

## Installation
Download from project homepage. http://xianyi.github.com/OpenBLAS/

Or, check out codes from git://github.com/xianyi/OpenBLAS.git
### Normal compile
  * type "make" to detect the CPU automatically.
  or
  * type "make TARGET=xxx" to set target CPU, e.g. "make TARGET=NEHALEM". The full target list is in file TargetList.txt.

### Cross compile
Please set CC and FC with the cross toolchains. Then, set HOSTCC with your host C compiler. At last, set TARGET explicitly.

Examples:

On X86 box, compile this library for loongson3a CPU.

    make BINARY=64 CC=mips64el-unknown-linux-gnu-gcc FC=mips64el-unknown-linux-gnu-gfortran HOSTCC=gcc TARGET=LOONGSON3A

### Debug version

    make DEBUG=1

### Install to the directory (optional)

Example:

    make install PREFIX=your_installation_directory

The default directory is /opt/OpenBLAS

## Support CPU & OS
Please read GotoBLAS_01Readme.txt

### Additional support CPU:

#### x86/x86-64:
- **Intel Xeon 56xx (Westmere)**: Used GotoBLAS2 Nehalem codes.
- **Intel Sandy Bridge**: Optimized Level-3 BLAS with AVX on x86-64.
- **Intel Haswell**: Optimized Level-3 BLAS with AVX on x86-64 (identical to Sandy Bridge).
- **AMD Bobcat**: Used GotoBLAS2 Barcelona codes.
- **AMD Bulldozer**: x86-64 S/DGEMM AVX kernels. (Thank Werner Saar)

#### MIPS64:
- **ICT Loongson 3A**: Optimized Level-3 BLAS and the part of Level-1,2.
- **ICT Loongson 3B**: Experimental

### Support OS:
- **GNU/Linux**
- **MingWin/Windows**: Please read <https://github.com/xianyi/OpenBLAS/wiki/How-to-use-OpenBLAS-in-Microsoft-Visual-Studio>.
- **Darwin/Mac OS X**: Experimental. Although GotoBLAS2 supports Darwin, we are the beginner on Mac OS X.
- **FreeBSD**: Supported by community. We didn't test the library on this OS.

## Usages
Link with libopenblas.a or -lopenblas for shared library.

### Set the number of threads with environment variables.

Examples:

    export OPENBLAS_NUM_THREADS=4

 or

    export GOTO_NUM_THREADS=4

 or

    export OMP_NUM_THREADS=4

The priorities are OPENBLAS_NUM_THREADS > GOTO_NUM_THREADS > OMP_NUM_THREADS.

If you compile this lib with USE_OPENMP=1, you should set OMP_NUM_THREADS environment variable. OpenBLAS ignores OPENBLAS_NUM_THREADS and GOTO_NUM_THREADS with USE_OPENMP=1.

### Set the number of threads on runtime.

We provided the below functions to control the number of threads on runtime.

    void goto_set_num_threads(int num_threads);

    void openblas_set_num_threads(int num_threads);

If you compile this lib with USE_OPENMP=1, you should use the above functions, too.

## Report Bugs
Please add a issue in https://github.com/xianyi/OpenBLAS/issues

## Contact
* OpenBLAS users mailing list: https://groups.google.com/forum/#!forum/openblas-users
* OpenBLAS developers mailing list: https://groups.google.com/forum/#!forum/openblas-dev

## ChangeLog
Please see Changelog.txt to obtain the differences between GotoBLAS2 1.13 BSD version.

## Troubleshooting
* Please read [Faq](https://github.com/xianyi/OpenBLAS/wiki/Faq) at first.
* Please use gcc version 4.6 and above to compile Sandy Bridge AVX kernels on Linux/MingW/BSD.
* Please use Clang version 3.1 and above to compile the library on Sandy Bridge microarchitecture. The Clang 3.0 will generate the wrong AVX binary code.
* The number of CPUs/Cores should less than or equal to 256.
* On Linux, OpenBLAS sets the processor affinity by default. This may cause [the conflict with R parallel](https://stat.ethz.ch/pipermail/r-sig-hpc/2012-April/001348.html). You can build the library with NO_AFFINITY=1.
* On Loongson 3A. make test would be failed because of pthread_create error. The error code is EAGAIN. However, it will be OK when you run the same testcase on shell.

## Specification of Git Branches
We used the git branching model in this article (http://nvie.com/posts/a-successful-git-branching-model/).
Now, there are 4 branches in github.com.
  * The master branch. This a main branch to reflect a production-ready state.
  * The develop branch. This a main branch to reflect a state with the latest delivered development changes for the next release.
  * The loongson3a branch. This is a feature branch. We develop Loongson3A codes on this branch. We will merge this feature to develop branch in future.
  * The gh-pages branch. This is for web pages


text:
import os
import pytest
from PIL import Image
from common.image_utils import resize

def test_resize(tmpdir):

  def gen_images(input_folder):
    image_path = os.path.join(input_folder, 'image1.jpg')
    with Image.new('RGB', size=(100, 100), color=(0, 0, 0)) as image:
      image.save(image_path)
    yield image_path
    image_path = os.path.join(input_folder, 'image2.jpg')
    with Image.new('RGB', size=(100, 400), color=(0, 0, 0)) as image:
      image.save(image_path)
    yield image_path
    image_path = os.path.join(input_folder, 'image3.jpg')
    with Image.new('RGB', size=(400, 100), color=(0, 0, 0)) as image:
      image.save(image_path)
    yield image_path

  # arrange
  input_folder = os.path.join(tmpdir, 'input')
  os.makedirs(input_folder, exist_ok=True)
  for image_path in gen_images(input_folder):
    # act
    print(os.path.basename(image_path))
    image_paths = resize(image_path, tmpdir)
    # assert
    assert len(image_paths) == 2
    with Image.open(image_paths[0]) as image:
      # first is square
      print('\t', image.size)
      assert image.width >= 300 and image.width >= 300
      assert image.width == image.height
    with Image.open(image_paths[1]) as image:
      # second is landscape
      print('\t', image.size)
      assert image.width >= 300 and image.width >= 300
      assert round(image.width / image.height, 2) == 1.91


text:
<?php
define("LULU_IMAGEBOARD_WWW", __DIR__);

if (preg_match('/\/public\//', $_SERVER["REQUEST_URI"])) {
    return false;
}else if(preg_match('/^\/backend\//', $_SERVER['REQUEST_URI'])) {
    require_once LULU_IMAGEBOARD_WWW . '/backend.php';
}else{
    require_once LULU_IMAGEBOARD_WWW . '/frontend.php';
}


text:
This script parse html from vk.com contained audio tracks and display on browser. Script saves playlist in file if you run it through command line.

## Dev Requirements
* php

## Installation

```
git clone git@github.com:maksimsaratov/vk_playlist_import.git vk_playlist_import.git
```

## Usage
* open your audio tracks page https://new.vk.com/audios**********
* scroll down to load all your tracks
* open web developer tools and copy page html
* put html to vk.html. It should be in the project root directory

Browser:
* open index.php on browser through server with php

Command line:
```
cd vk_playlist_import.git
php index.php
```
"playlist.txt" file will created in the same directory.


text:
/**
 * The WASI API provides an implementation of the [WebAssembly System Interface](https://wasi.dev/)specification. WASI gives sandboxed WebAssembly applications access to the
 * underlying operating system via a collection of POSIX-like functions.
 *
 * ```js
 * import fs from 'fs';
 * import { WASI } from 'wasi';
 * import { argv, env } from 'process';
 *
 * const wasi = new WASI({
 *   args: argv,
 *   env,
 *   preopens: {
 *     '/sandbox': '/some/real/path/that/wasm/can/access'
 *   }
 * });
 * const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
 *
 * const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
 * const instance = await WebAssembly.instantiate(wasm, importObject);
 *
 * wasi.start(instance);
 * ```
 *
 * To run the above example, create a new WebAssembly text format file named`demo.wat`:
 *
 * ```text
 * (module
 *     ;; Import the required fd_write WASI function which will write the given io vectors to stdout
 *     ;; The function signature for fd_write is:
 *     ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
 *     (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
 *
 *     (memory 1)
 *     (export "memory" (memory 0))
 *
 *     ;; Write 'hello world\n' to memory at an offset of 8 bytes
 *     ;; Note the trailing newline which is required for the text to appear
 *     (data (i32.const 8) "hello world\n")
 *
 *     (func $main (export "_start")
 *         ;; Creating a new io vector within linear memory
 *         (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
 *         (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\n' string
 *
 *         (call $fd_write
 *             (i32.const 1) ;; file_descriptor - 1 for stdout
 *             (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
 *             (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
 *             (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
 *         )
 *         drop ;; Discard the number of bytes written from the top of the stack
 *     )
 * )
 * ```
 *
 * Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm`
 *
 * ```console
 * $ wat2wasm demo.wat
 * ```
 *
 * The `--experimental-wasi-unstable-preview1` CLI argument is needed for this
 * example to run.
 * @experimental
 * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/wasi.js)
 */
declare module 'wasi' {
    interface WASIOptions {
        /**
         * An array of strings that the WebAssembly application will
         * see as command line arguments. The first argument is the virtual path to the
         * WASI command itself.
         */
        args?: string[] | undefined;
        /**
         * An object similar to `process.env` that the WebAssembly
         * application will see as its environment.
         */
        env?: object | undefined;
        /**
         * This object represents the WebAssembly application's
         * sandbox directory structure. The string keys of `preopens` are treated as
         * directories within the sandbox. The corresponding values in `preopens` are
         * the real paths to those directories on the host machine.
         */
        preopens?: NodeJS.Dict<string> | undefined;
        /**
         * By default, WASI applications terminate the Node.js
         * process via the `__wasi_proc_exit()` function. Setting this option to `true`
         * causes `wasi.start()` to return the exit code rather than terminate the
         * process.
         * @default false
         */
        returnOnExit?: boolean | undefined;
        /**
         * The file descriptor used as standard input in the WebAssembly application.
         * @default 0
         */
        stdin?: number | undefined;
        /**
         * The file descriptor used as standard output in the WebAssembly application.
         * @default 1
         */
        stdout?: number | undefined;
        /**
         * The file descriptor used as standard error in the WebAssembly application.
         * @default 2
         */
        stderr?: number | undefined;
    }
    /**
     * The `WASI` class provides the WASI system call API and additional convenience
     * methods for working with WASI-based applications. Each `WASI` instance
     * represents a distinct sandbox environment. For security purposes, each `WASI`instance must have its command-line arguments, environment variables, and
     * sandbox directory structure configured explicitly.
     * @since v13.3.0, v12.16.0
     */
    class WASI {
        constructor(options?: WASIOptions);
        /**
         * Attempt to begin execution of `instance` as a WASI command by invoking its`_start()` export. If `instance` does not contain a `_start()` export, or if`instance` contains an `_initialize()`
         * export, then an exception is thrown.
         *
         * `start()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`. If
         * `instance` does not have a `memory` export an exception is thrown.
         *
         * If `start()` is called more than once, an exception is thrown.
         * @since v13.3.0, v12.16.0
         */
        start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
        /**
         * Attempt to initialize `instance` as a WASI reactor by invoking its`_initialize()` export, if it is present. If `instance` contains a `_start()`export, then an exception is thrown.
         *
         * `initialize()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named`memory`.
         * If `instance` does not have a `memory` export an exception is thrown.
         *
         * If `initialize()` is called more than once, an exception is thrown.
         * @since v14.6.0, v12.19.0
         */
        initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
        /**
         * `wasiImport` is an object that implements the WASI system call API. This object
         * should be passed as the `wasi_snapshot_preview1` import during the instantiation
         * of a [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance).
         * @since v13.3.0, v12.16.0
         */
        readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types
    }
}
declare module 'node:wasi' {
    export * from 'wasi';
}


text:
class Timer
{
    private:
    int startTicks, pausedTicks;
    bool paused, started;
    public:
    Timer();
    void Start();
    void Stop();
    void Pause();
    void UnPause();
    int GetTicks();
    bool IsStarted();
    bool IsPaused();
};

#endif // TIMER_HPP_INCLUDED


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>GameManager</title>
<meta name="date" content="2015-01-10">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.haw.projecthorse.gamemanager

Interface GameManager

public interface GameManager

Der GameManager ist ein Singleton und für die Kommunikation zwischen den
 einzelnen Modulen zuständig. Die Konfiguration wird aus der GameConfig.json
 geladen.

Version:

1.0

Author:

Philipp Grulich

Method Summary

Methods

Modifier and Type
Method and Description

CityObject
getCityObject(java.lang.String levelID)

Liefert das CityObject zurück falls die LevelID existiert.

java.lang.String
getCurrentLevelID()

Liefert die aktuelle LevelID zurück.

GameConfig
getGameConfig()

Liefert das GameConfig Object zurück. über dieses Object können
 Informationen über das Spiel abgefragt werden.

GameObject
getGameObject(java.lang.String levelID)

Liefert das GameObject zurück falls die LevelID existiert.

MenuObject
getMenuObject(java.lang.String levelID)

Liefert das MenuObject zurück falls die LevelID existiert.

Platform
getPlatform()

Liefert die Implementierung des Platform Interfaces zurück.

java.lang.Object
getScoreManager()

Liefert eine Referenz auf das Spielstand Modul

Settings
getSettings()

Liefert eine Referenz auf das Settings Modul

void
navigateBack()

Navigiert zu dem vorherigen Level.

void
navigateToLevel(java.lang.String levelID)

Navigiert zu einer Stadt oder einem Spiel welches anhand der LevelID
 (String) identifiziert wird.

void
navigateToMainMenu()

Navigiert zum MainMenu.

void
navigateToWorldMap()

Navigiert zur Worldmap.

Method Detail

navigateBack

void navigateBack()

Navigiert zu dem vorherigen Level.

navigateToLevel

void navigateToLevel(java.lang.String levelID)

Navigiert zu einer Stadt oder einem Spiel welches anhand der LevelID
 (String) identifiziert wird.

Parameters:

levelID - LevelID

navigateToWorldMap

void navigateToWorldMap()

Navigiert zur Worldmap. Als Verkürzung zum navigateToLevel.

navigateToMainMenu

void navigateToMainMenu()

Navigiert zum MainMenu. Als Verkürzung zum navigateToLevel.

getGameConfig

GameConfig getGameConfig()

Liefert das GameConfig Object zurück. über dieses Object können
 Informationen über das Spiel abgefragt werden.

Returns:

GameConfig

getCityObject

CityObject getCityObject(java.lang.String levelID)
                         throws LevelNotFoundException

Liefert das CityObject zurück falls die LevelID existiert. Wenn nicht
 wird eine LevelNotFoundException geworfen.

Parameters:

levelID - gesuchte LevelID

Returns:

CityObjectImpl

Throws:

LevelNotFoundException - Wenn die Stadt nicht vorhanden ist.

getGameObject

GameObject getGameObject(java.lang.String levelID)
                         throws LevelNotFoundException

Liefert das GameObject zurück falls die LevelID existiert. Wenn nicht
 wird eine LevelNotFoundException geworfen.

Parameters:

levelID - gesuchte LevelID

Returns:

GameObjecttImpl

Throws:

LevelNotFoundException - Wenn das Spiel nicht vorhanden ist.

getMenuObject

MenuObject getMenuObject(java.lang.String levelID)
                         throws LevelNotFoundException

Liefert das MenuObject zurück falls die LevelID existiert. Wenn nicht
 wird eine LevelNotFoundException geworfen.

Parameters:

levelID - gesuchte LevelID

Returns:

MenuObject

Throws:

LevelNotFoundException - Wenn das Menü nicht vorhanden ist.

getScoreManager

java.lang.Object getScoreManager()

Liefert eine Referenz auf das Spielstand Modul. *

Returns:

Spielstand

getSettings

Settings getSettings()

Liefert eine Referenz auf das Settings Modul. *

Returns:

Settings

getCurrentLevelID

java.lang.String getCurrentLevelID()

Liefert die aktuelle LevelID zurück.

Returns:

LevelID

getPlatform

Platform getPlatform()

Liefert die Implementierung des Platform Interfaces zurück.

Returns:

Native Platform.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import numpy as np
import argparse
from os import path, getcwd
import os
import re
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import cross_val_score

from utils import *

import logging
import logging.handlers

fmt = ("%(asctime)s - %(filename)s:%(lineno)s - "
       "%(name)s - %(levelname)s - %(message)s")
formatter = logging.Formatter(fmt)

handler = logging.FileHandler("glm_l1.log")
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(logging.WARNING)

logger = logging.getLogger('glm_l1')
logger.addHandler(handler)
logger.addHandler(console)
logger.setLevel(logging.DEBUG)

# logger.debug('This is debug message')
# logger.info('This is info message')
# logger.warning('This is warning message')

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_folder', type=str, default="../feature/5_75")
    parser.add_argument('--data_set', choices=['21k', 'v3', 'colHist'],
                        default="21k")
    return parser.parse_args()

def get_params(args):
    data_dir_path = path.abspath(path.join(getcwd(), args.data_folder))
    assert path.exists(data_dir_path)
    dir_name = path.basename(data_dir_path)
    m = re.match(r"(\d+)_(\d+)", dir_name)
    reps, prob = int(m.group(1)), int(m.group(2)) / 100
    return data_dir_path, reps, prob

def get_data_train(data_dir, args):
    X_path = path.join(data_dir, "X_train.npy")
    y_path = path.join(data_dir, "y_train.npy")
    X = np.load(X_path)
    y = np.load(y_path)
    if args.data_set == '21k':
        sel_range = range(0, 2048)
    elif args.data_set == 'colHist':
        sel_range = range(2048, 2048 + 772)
    else:
        sel_range = range(2048 + 772, 6916)
    return (X[:, sel_range], y)

########################################################################

# functions for hyperparameters optimization

class Score:
    def __init__(self, X, y, y_ix, reps):
        self.y = y[:, y_ix]
        self.X = X
        self.reps = reps

    def get_score(self, params):
        logger.info("Training with params:")
        params['max_iter'] = int(params['max_iter'])
        logger.info(params)

        # cross validation here
        clf = make_pipeline(StandardScaler(), LogisticRegression(**params))
        score_list = cross_val_score(estimator=clf,
                                     X=self.X,
                                     y=self.y,
                                     scoring='f1',
                                     cv=makeKFold(5, self.y, self.reps),
                                     n_jobs=-1,
                                     verbose=1)
        score = np.mean(score_list)
        logger.info(score)
        return {'loss': -score, 'status': STATUS_OK}

def optimize(trials, X, y, y_ix, reps, max_evals):
    space = {
        'C': hp.loguniform('C', -3, 2),
        'max_iter': hp.quniform('max_iter', 100, 300, 50),
        'n_jobs': -1,
        'class_weight': 'balanced',
        'penalty': 'l1'
    }
    s = Score(X, y, y_ix, reps)
    best = fmin(s.get_score,
                space,
                algo=tpe.suggest,
                trials=trials,
                max_evals=max_evals
                )
    best['max_iter'] = int(best['max_iter'])
    best['n_jobs'] = -1
    best['class_weight'] = 'balanced'
    best['penalty'] = 'l1'
    del s
    return best

def out_fold_pred(params, X, y_array, y_ix, reps):
    y = y_array[:, y_ix]

    # cross validation here
    preds = np.zeros((y_array.shape[0]))
    clf = make_pipeline(StandardScaler(), LogisticRegression(**params))

    for train_ix, test_ix in makeKFold(5, y, reps):
        X_train, y_train = X[train_ix, :], y[train_ix]
        X_test = X[test_ix, :]
        clf = make_pipeline(StandardScaler(), LogisticRegression(**params))
        clf.fit(X_train, y_train)
        pred = clf.predict_proba(X_test)[:, 1]
        preds[test_ix] = pred
    return preds

def get_model(params, X, y_array, y_ix, reps):
    y = y_array[:, y_ix]
    clf = make_pipeline(StandardScaler(), LogisticRegression(**params))
    clf.fit(X, y)
    return clf

if __name__ == "__main__":
    args = parse_args()

    logger.info("Data Directory: " + args.data_folder)
    logger.info("Data set: " + args.data_set)

    data_dir, reps, prob = get_params(args)
    X, y = get_data_train(data_dir, args)

    # save place
    save_dir_name = path.basename(__file__)[:-3] + "_" + \
        str(reps) + "_" + str(int(100 * prob)) + "_" + args.data_set
    save_dir = path.join(path.dirname(path.abspath(__file__)),
                         save_dir_name)
    if not path.isdir(save_dir):
        os.mkdir(save_dir)

    # begin trainnig
    for y_ix in range(9):
        logger.info("training for class " + str(y_ix))
        trials = Trials()
        params = optimize(trials, X, y, y_ix, reps, 15)
        preds = out_fold_pred(params, X, y, y_ix, reps)
        model = get_model(params, X, y, y_ix, reps)

        pickle.dump(params,
                    open(path.join(save_dir, "param_" + str(y_ix) + ".pkl"),
                         'wb'))
        np.save(path.join(save_dir, "outFold_" + str(y_ix) + ".npy"), preds)
        pickle.dump(model,
                    open(path.join(save_dir, "model_" + str(y_ix) + ".pkl"),
                         'wb'))
        logger.info(str(y_ix) + " completes!")


text:
package com.adaptris.core.common;

import static com.adaptris.util.stream.StreamUtil.copyAndClose;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.io.IOException;

import com.adaptris.annotation.AdvancedConfig;
import com.adaptris.annotation.DisplayOrder;
import com.adaptris.core.util.ExceptionHelper;
import com.adaptris.interlok.InterlokException;
import com.adaptris.interlok.config.DataOutputParameter;
import com.adaptris.interlok.types.InterlokMessage;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * This {@code DataOutputParameter} is used when you want to write data to the {@link com.adaptris.core.AdaptrisMessage} payload.
 *
 *
 * @config stream-payload-output-parameter
 *
 */
@XStreamAlias("stream-payload-output-parameter")
@DisplayOrder(order = {"contentEncoding"})
public class PayloadStreamOutputParameter implements DataOutputParameter<InputStreamWithEncoding> {
  @AdvancedConfig
  private String contentEncoding;

  @Override
  public void insert(InputStreamWithEncoding data, InterlokMessage msg) throws InterlokException {
    try {
      String encoding = defaultIfEmpty(getContentEncoding(), data.encoding);
      if (isEmpty(encoding)) {
        copyAndClose(data.inputStream, msg.getOutputStream());
      } else {
        copyAndClose(data.inputStream, msg.getWriter(encoding));
        msg.setContentEncoding(encoding);
      }
    } catch (IOException e) {
      throw ExceptionHelper.wrapCoreException(e);
    }
  }

  public String getContentEncoding() {
    return contentEncoding;
  }

  public void setContentEncoding(String contentEncoding) {
    this.contentEncoding = contentEncoding;
  }

}


text:
package io.netty.example.common;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;

/**
 * Created by F.Fang on 2015/5/24.
 * Version :2015/5/24
 */
public class CommonClient1 {

    private EventLoopGroup group;

    private Channel channel;

    public CommonClient1() {
        group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new ByteArrayEncoder())
                                    .addLast(new ByteArrayDecoder())
                                    .addLast(new CommonClientHandler());
                        }
                    }).option(ChannelOption.TCP_NODELAY, true);

            // Make the connection attempt.
            ChannelFuture f = b.connect("127.0.0.1", 8080).sync();
            this.channel = f.channel();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close(){
        if(channel!=null){
            try {
                channel.closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(group!=null){
                    group.shutdownGracefully();
                }
            }
        }
    }

    public void sendMsg(String msg) throws Exception {
        if (msg != null && msg.length() > 0) {
            ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes());
            channel.writeAndFlush(buf).sync();
        }
    }

    public static void main(String[] args) throws Exception {
        CommonClient1 client = new CommonClient1();
        client.sendMsg("hello world!");
        Thread.sleep(3000);
        client.sendMsg("end");
        client.close();
    }
}