text:
<!DOCTYPE html>

        <meta charset="utf-8" />
         <title>HUTECH DEVLOPERS CLUB ADMINISTRATOR</title>
         <link rel="shortcut icon" href="<?php echo base_url();?>template/favicon.ico" type="image/x-icon" />
        <meta name="description" content="and Validation" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link href="<?php echo base_url() ?>template/admin/assets/css/bootstrap.min.css" rel="stylesheet" />
        <link href="<?php echo base_url() ?>template/admin/assets/css/bootstrap-responsive.min.css" rel="stylesheet" />
        <link rel="stylesheet" href="<?php echo base_url() ?>template/admin/assets/css/font-awesome.min.css" />

        <link rel="stylesheet" href="<?php echo base_url() ?>template/admin/assets/css/select2.css" />

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,300" />

        <link rel="stylesheet" href="<?php echo base_url() ?>template/admin/assets/css/ace.min.css" />
        <link rel="stylesheet" href="<?php echo base_url() ?>template/admin/assets/css/ace-responsive.min.css" />
        <link rel="stylesheet" href="<?php echo base_url() ?>template/admin/assets/css/ace-skins.min.css" />

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

                            HUTECH DEVELOPERS CLUB ADMINISTRATOR

                                <img class="nav-user-photo" src="<?php echo base_url();?>file/uploads/avatar/<?php echo $this->session->userdata['file']?>" alt="Jason's Photo" />

                                    Welcome,
                                    <?php echo $this->session->userdata['username']?>

                                    <a href="<?php echo base_url();?>admin/userlist/change_pass">

                                        Profile

                                    <a href="<?php echo base_url();?>admin/index/logout">

                                        Logout

                <button class="btn btn-small btn-success">

                </button>

                <button class="btn btn-small btn-info">

                </button>

                <button class="btn btn-small btn-warning">

                </button>

                <button class="btn btn-small btn-danger">

                </button>

						<a href="<?php echo base_url();?>admin/userlist/listuser">

							 Users

						<a href="<?php echo base_url();?>admin/cate/listcate">

							 Cates

						<a href="<?php echo base_url();?>admin/post/listpost">

							 Posts

						<a href="<?php echo base_url();?>admin/mem/list_mem">

							 Member

							 Money

        <?php $this->load->view($main_content);?>

redpajama_set_name: RedPajamaGithub


text:
package com.spectralogic.ds3client.helpers.channelbuilders;

import com.spectralogic.ds3client.helpers.Ds3ClientHelpers;

import java.io.IOException;
import java.nio.channels.SeekableByteChannel;

public class PrefixAdderObjectChannelBuilder implements Ds3ClientHelpers.ObjectChannelBuilder {
    final private Ds3ClientHelpers.ObjectChannelBuilder channelBuilder;
    final private String prefix;

    public PrefixAdderObjectChannelBuilder(final Ds3ClientHelpers.ObjectChannelBuilder channelBuilder, final String prefix) {
        this.channelBuilder = channelBuilder;
        this.prefix = prefix;
    }

    @Override
    public SeekableByteChannel buildChannel(final String s) throws IOException {
        return channelBuilder.buildChannel(Ds3ClientHelpers.stripLeadingPath(s, prefix));
    }
}


text:
package wm.xmwei.core.image.universalimageloader.cache.disc.naming;

/**
 * Generates names for files at disk cache
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.3.1
 */
public interface FileNameGenerator {

	/** Generates unique file name for image defined by URI */
	String generate(String imageUri);
}


text:
package com.mit.dstore.ui.shopping;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.mit.dstore.R;
import com.mit.dstore.adapter.WriteOrderAdapter;
import com.mit.dstore.app.BaseActivity;
import com.mit.dstore.engine.MyApplication;
import com.mit.dstore.entity.CartInfoItem;
import com.mit.dstore.entity.DeliveryAddress;
import com.mit.dstore.entity.DeliveryAddress.DeliveryAddressItem;
import com.mit.dstore.entity.JSON;
import com.mit.dstore.entity.RechargeIntegralOrder;
import com.mit.dstore.entity.RechargeIntegralOrder.RechargeIntegralOrderItem;
import com.mit.dstore.entity.ScanStoreChridJson;
import com.mit.dstore.entity.UserAmountExchange;
import com.mit.dstore.entity.UserAmountExchangeInfo;
import com.mit.dstore.net.Methods;
import com.mit.dstore.net.MySoap;
import com.mit.dstore.ui.setting.accountpwd.SetPayPwdActivity;
import com.mit.dstore.ui.system.SelectePayWayActivity;
import com.mit.dstore.ui.wallet.mybill.BillDetailActivity;
import com.mit.dstore.util.BingContextUtil;
import com.mit.dstore.util.Constant;
import com.mit.dstore.util.DialogUtil;
import com.mit.dstore.util.EncryptUtil;
import com.mit.dstore.util.JsonUtil;
import com.mit.dstore.util.L;
import com.mit.dstore.util.NewPayUtil;
import com.mit.dstore.util.PayWayUtil;
import com.mit.dstore.util.SharedPreferencesUtil;
import com.mit.dstore.util.T;
import com.mit.dstore.util.NewPayUtil.OnPayPassdword;
import com.mit.dstore.widget.NoScrollListview;
import com.mit.dstore.wxapi.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import de.greenrobot.event.EventBus;

/**
 * @ClassName: ShoppingWriteOrderActivity
 * @Description: TODO(填写订单)
 * @author A18ccms a18ccms_gmail_com
 * @date 2015年11月6日 上午11:29:50
 *
 */
public class ShoppingWriteOrderActivity extends BaseActivity {
	private Context mContext = this;
	@Bind(R.id.shopping_order_fare)
	TextView shopping_order_fare;
	@Bind(R.id.shopping_order_receiver)
	LinearLayout shopping_order_receiver;
	@Bind(R.id.shopping_order_goods)
	NoScrollListview shopping_order_goods;
	@Bind(R.id.shopping_order_pay_way)
	LinearLayout shopping_order_pay_way;
	@Bind(R.id.shopping_order_remark)
	EditText shopping_order_remark;
	@Bind(R.id.shopping_address_info)
	TextView shopping_address_info;
	@Bind(R.id.shopping_text_order_receiver)
	TextView shopping_text_order_receiver;
	@Bind(R.id.shopping_text_order_phone)
	TextView shopping_text_order_phone;
	@Bind(R.id.shopping_count_num)
	TextView shopping_count_num;
	@Bind(R.id.shopping_button_pay)
	Button shopping_button_pay;
	@Bind(R.id.paystyle_text)
	TextView paystyle_text;
	@Bind(R.id.frame_input_error)
	FrameLayout frame_input_error;

	public final String TAG = this.getClass().getSimpleName();
	private List<CartInfoItem> list = new ArrayList<CartInfoItem>();
	private WriteOrderAdapter adapter;
	private DeliveryAddress address;
	private static final int requestCode = 5;
	private static final int pay_requestCode = 0x000002;
	private static final int charge_requestCode = 0x000003;
	private EditText passwordEditText;
	/**
	 * 1 ICBC 2 alipay 3 weichat 4 chargepay
	 */
	// private int PAY_TYPE = 0;
	// 用來標誌是從商品相親點進來還是購物車點進來, flag = false是從購物車跳轉過來,flag = true是商品詳情跳轉過來,
	private boolean flag = false;
	private DeliveryAddressItem item;
	private String defaultAdress = "";
	/** ===================微信支付变量申明 Start============================ */
	PayReq req;
	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	// TextView show;
	Map<String, String> resultunifiedorder;
	StringBuffer sb;
	/** ===================微信支付变量申明 End============================ */

	// 支付宝
	private int queryOrderCount;// 提交一次订单之后,查询账单的次数最多2次
	// 总价
	private double coutAmount = 0;
	private int goods_num = 1;
	private Dialog payDialog;
	private String mPayAmount = "0";
	private TextView trading_member_name, trading_member_amount;
	private String PayNo = "";
	private RechargeIntegralOrderItem itemSelected;
	private LinearLayout credit_add_linear_inpupassword;
	private TextView dlgAmountTv;
	private RechargeIntegralOrder orders;
	private ImageView trading_member_image;
	private TextView trading_member_currency;
	private NewPayUtil newPayUtil;
	private String NumPrice = "0";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shopping_write_order);
		initTopbar(R.string.shopping_title_write_order);
		ButterKnife.bind(this);
		list = (ArrayList<CartInfoItem>) getIntent().getSerializableExtra(Constant.CartInfo);
		initData();
		PayNo = UUID.randomUUID().toString();
	}

	private void initData() {
		flag = getIntent().getBooleanExtra("flag", false);
		EventBus.getDefault().register(this);
		adapter = new WriteOrderAdapter(mContext, list, flag);
		shopping_order_goods.setAdapter(adapter);
		getAddressList();
		for (CartInfoItem i : list) {
			coutAmount += (i.getShop_price() * i.getCart_goods_number());
		}
		SpannableString spannableString = new SpannableString(" MOP " + BingContextUtil.formatNum(coutAmount));
		spannableString.setSpan(new TextAppearanceSpan(mContext, R.style.style4), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		shopping_count_num.setText(spannableString, TextView.BufferType.SPANNABLE);
		req = new PayReq();
		sb = new StringBuffer();
		msgApi.registerApp(Constants.APP_ID);
	}

	@OnClick(R.id.shopping_order_receiver)
	public void setAddress(View v) {
		Intent intent = new Intent(mContext, ShoppingAddressManagerActivity.class);
		startActivityForResult(intent, requestCode);
	}

	@OnClick(R.id.shopping_button_pay)
	public void payCommit(View v) {

			if (flag) {
				getInsertByAlone();
			} else {
				getOrderInsert();
			}

	}

	@OnClick(R.id.shopping_order_pay_way)
	public void selectedPay(View v) {
		Intent intent = new Intent(mContext, ShoppingSelectedPayActivity.class);
		intent.putExtra("count", String.valueOf(coutAmount));
		startActivityForResult(intent, pay_requestCode);
	}

	private void getAddressList() {
		Methods.setUrl(mContext, MyApplication.getInstance().getEndPoint());
		MySoap mySoap = new MySoap(new MySoap.OnGetDatas() {

			@Override
			public void onSuccess(String tag, String datas) {
				loadingDialog.dismiss();
				address = (DeliveryAddress) JsonUtil.getJsonObect(datas, DeliveryAddress.class);
				if (address.getFlag() == 1) {
					if (address.getObject().size() > 0) {
						for (int i = 0; i < address.getObject().size(); i++) {
							if (address.getObject().get(i).getIsDefault() == 1) {
								String str = address.getObject().get(i).getProvince() + " " + address.getObject().get(i).getCity() + " "
										+ address.getObject().get(i).getArea() + " " + address.getObject().get(i).getDetailAddress() + " ";
								shopping_address_info.setText(str);
								item = address.getObject().get(i);
								shopping_text_order_receiver.setText("收貨人:" + address.getObject().get(i).getReceiver());
								shopping_text_order_phone.setText(address.getObject().get(i).getCountryCode()
										+ address.getObject().get(i).getMobile());
							}else {
								defaultAdress =  address.getObject().get(0).getProvince() + " " + address.getObject().get(0).getCity() + " "
										+ address.getObject().get(0).getArea() + " " + address.getObject().get(0).getDetailAddress() + " ";
								shopping_address_info.setText(defaultAdress);
								item = address.getObject().get(0);
								shopping_text_order_receiver.setText("收貨人:" + address.getObject().get(0).getReceiver());
								shopping_text_order_phone.setText(address.getObject().get(0).getCountryCode()
										+ address.getObject().get(0).getMobile());
							}
						}
					}
				}
			}

			@Override
			public void onFail(String tag, String errorMsg) {
				loadingDialog.dismiss();
			}

			@Override
			public void onLoading() {
				loadingDialog.show();
			}
		});
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("UserNeiMa", SharedPreferencesUtil.getString(mContext, R.string.UserNeiMa));
		mySoap.request(Methods.ShoppingManage_UserDeliveryAddress_GetList, Methods.ShoppingManage_UserDeliveryAddress_GetList, param);
	}

	/**
	 *
	 * @Title: getOrderInsert
	 * @Description: TODO(【生成购物车商品订单】 )
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void getOrderInsert() {
		if (null == item) {
			T.showShort(mContext, "請先選擇地址");
			return;
		}
		Methods.setUrl(mContext, MyApplication.getInstance().getEndPoint());
		MySoap mySoap = new MySoap(new MySoap.OnGetDatas() {

			@Override
			public void onSuccess(String tag, String datas) {
				loadingDialog.dismiss();
				if (datas.equalsIgnoreCase("")) {
					T.showShort(mContext, R.string.net_error);
					return;
				}
				orders = (RechargeIntegralOrder) JsonUtil.getJsonObect(datas, RechargeIntegralOrder.class);
				if (orders.getFlag() == 1) {// 获取订单成功
					itemSelected = orders.getObject().get(0);
//					doConfirm(itemSelected.getPayTypeName(), BingContextUtil.subZeroAndDot(String.valueOf(itemSelected.getPrice())));
					PayNo = UUID.randomUUID().toString();
					newPayUtil = new NewPayUtil(mContext,getString(R.string.comform_paytype), itemSelected.getPayTypeName(), NumPrice, orders,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									newPayUtil.dismiss();
									Intent intent = new Intent(mContext, ShoppingMainBillActivity.class);
									startActivity(intent);
									finish();
								}
							});
					newPayUtil.setOnPayPassdword(new OnPayPassdword() {

						@Override
						public void OnPassdWord(String passwrod, RechargeIntegralOrderItem itemSelected) {
							// TODO Auto-generated method stub
							mobileRecharge(passwrod,  itemSelected);
						}
					});
				} else {
					T.showLong(mContext, orders.getDecription());
				}
			}

			@Override
			public void onFail(String tag, String errorMsg) {
				loadingDialog.dismiss();
			}

			@Override
			public void onLoading() {
				loadingDialog.show();
			}
		});
		StringBuffer buffer = new StringBuffer();
		double countAmount = 0;
		for (CartInfoItem cartInfoItem : list) {
			if (list.size() == 1) {
				buffer.append(cartInfoItem.getRec_id());
			} else {
				buffer.append(cartInfoItem.getRec_id()).append(";");
			}
			countAmount += (cartInfoItem.getShop_price() * cartInfoItem.getCart_goods_number());
		}
		NumPrice = BingContextUtil.formatNum(countAmount);
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("UserNeiMa", SharedPreferencesUtil.getString(mContext, R.string.UserNeiMa));
		param.put("UserDeliveryAddressID", String.valueOf(item.getUserDeliveryAddressID()));
		param.put("CartXML", buffer.toString());
		param.put("OrderMemo", shopping_order_remark.getText().toString().trim());
		param.put("PayAmount", BingContextUtil.formatNum(countAmount));
		param.put("Operator", user.getUserName());
		param.put("OperUserID", user.getUserNeiMa());
		param.put("DeviceType", "1");
		param.put("DeviceID", BingContextUtil.getDeviceId(mContext));
		param.put("Mobile", user.getMobile());
		param.put("PayNo", PayNo);
		mySoap.request(Methods.ShoppingManage_Order_Insert, Methods.ShoppingManage_Order_Insert, param);
	}

	/**
	 * 【生成单独购买商品订单】
	 */
	private void getInsertByAlone() {
		if (null == item) {
			T.showShort(mContext, "請先選擇地址");
			return;
		}
		Methods.setUrl(mContext, MyApplication.getInstance().getEndPoint());
		MySoap mySoap = new MySoap(new MySoap.OnGetDatas() {

			@Override
			public void onSuccess(String tag, String datas) {
				loadingDialog.dismiss();
				if (datas.equalsIgnoreCase("")) {
					T.showShort(mContext, R.string.net_error);
					return;
				}
				orders = (RechargeIntegralOrder) JsonUtil.getJsonObect(datas, RechargeIntegralOrder.class);
				if (orders.getFlag() == 1) {// 获取订单成功
					itemSelected = orders.getObject().get(0);
					doConfirm(itemSelected.getExchangeObjectName(), String.valueOf(itemSelected.getPrice()));
				} else {
					T.showLong(mContext, orders.getDecription());
				}
			}

			@Override
			public void onFail(String tag, String errorMsg) {
				loadingDialog.dismiss();
			}

			@Override
			public void onLoading() {
				loadingDialog.show();
			}
		});
		StringBuffer buffer = new StringBuffer();
		double countAmount = 0;
		for (CartInfoItem cartInfoItem : list) {
			buffer.append(cartInfoItem.getGoods_id());
			countAmount += (cartInfoItem.getShop_price() * cartInfoItem.getCart_goods_number());
		}
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("UserNeiMa", SharedPreferencesUtil.getString(mContext, R.string.UserNeiMa));
		param.put("UserDeliveryAddressID", String.valueOf(item.getUserDeliveryAddressID()));
		param.put("goods_id", buffer.toString());
		param.put("goods_num", String.valueOf(goods_num));
		param.put("OrderMemo", shopping_order_remark.getText().toString().trim());
		param.put("PayAmount", BingContextUtil.formatNum(countAmount));
		param.put("Operator", user.getUserName());
		param.put("OperUserID", user.getUserNeiMa());
		param.put("DeviceType", "1");
		param.put("DeviceID", BingContextUtil.getDeviceId(mContext));
		param.put("Mobile", item.getMobile());
		param.put("PayNo", PayNo);
		mySoap.request(Methods.ShoppingManage_Order_InsertByAlone, Methods.ShoppingManage_Order_InsertByAlone, param);
	}

	public void getGoods_num(int mposition) {
		coutAmount = 0;
		for (CartInfoItem i : list) {
			coutAmount += (i.getShop_price() * i.getCart_goods_number());
		}
		goods_num = mposition;

		SpannableString spannableString = new SpannableString(" MOP " + BingContextUtil.formatNum(coutAmount));
		spannableString.setSpan(new TextAppearanceSpan(mContext, R.style.style4), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		shopping_count_num.setText(spannableString, TextView.BufferType.SPANNABLE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ShoppingWriteOrderActivity.requestCode && resultCode == Activity.RESULT_OK) {
			item = (DeliveryAddressItem) data.getExtras().getSerializable(Constant.Address);
			String str = item.getProvince() + " " + item.getCity() + " " + item.getArea() + " " + item.getDetailAddress() + " ";
			shopping_address_info.setText(str);
			shopping_text_order_receiver.setText("收貨人:" + item.getReceiver());
			shopping_text_order_phone.setText(item.getCountryCode() + item.getMobile());
		} else if (null != data && requestCode == Constant.VIPCARD_REQUEST) {
			itemSelected = (RechargeIntegralOrderItem) data.getSerializableExtra(Constant.Selected_Pay_Way);
			String cardName = itemSelected.getPayTypeName();
			double PayAmount = itemSelected.getPrice();
			trading_member_name.setText(cardName);
			trading_member_currency.setText("- "+itemSelected.getCurrencyName() + " ");
			trading_member_amount.setText(BingContextUtil.subZeroAndDot(String.valueOf(PayAmount)));
			ImageLoader.getInstance().displayImage(itemSelected.getPayTypeLogo(), trading_member_image);
//			dlgAmountTv.setText(BingContextUtil.subZeroAndDot(String.valueOf(itemSelected.getPrice())));
			L.d(itemSelected.toString());
			if (itemSelected.getPayType() == 1) {
				credit_add_linear_inpupassword.setVisibility(View.VISIBLE);
				payDialog.getWindow().getDecorView().postInvalidate();
				// 積分會員卡支付
			} else {
				// 第三方支付
				credit_add_linear_inpupassword.setVisibility(View.GONE);
				payDialog.getWindow().getDecorView().postInvalidate();
			}

		}else if (requestCode==	Constant.REQUEST_CODE_SET_PAYPASSWORD&&resultCode==Activity.RESULT_OK) {
			user = SharedPreferencesUtil.getUserInfoFromShare(mContext);
		}
	}

	private void getOrderRequest(String orderId) {
		if (orderId == null || orderId.trim().isEmpty()) {
			T.showShort(mContext, R.string.credit_order_not_null);
			return;
		}

		Methods.setUrl(this, MyApplication.getInstance().getEndPoint());
		MySoap mySoap = new MySoap(new MySoap.OnGetDatas() {
			@Override
			public void onSuccess(String tag, String response) {
				loadingDialog.dismiss();
				UserAmountExchange exchange = (UserAmountExchange) JsonUtil.getJsonObect(response, UserAmountExchange.class);
				if (exchange.getObject().size() == 0) {
					return;
				}
				UserAmountExchangeInfo exchangeInfo = exchange.getObject().get(0);
				if (exchangeInfo.getExchangeStatus().trim().equals(UserAmountExchangeInfo.EXCHANGE_STATUS_SUCCESS)) {
					Intent intent = new Intent(mContext, BillDetailActivity.class);
					intent.putExtra("isPayBillDetail", true);
					intent.putExtra("UserAmountExchangeInfo", exchangeInfo);
					startActivity(intent);
					MyApplication.getInstance().finishActivity(ShoppingWriteOrderActivity.class);
					MyApplication.getInstance().finishActivity(ShoppingCartActivity.class);
					MyApplication.getInstance().finishActivity(ShoppingInfoActivity.class);
					MyApplication.getInstance().finishActivity(ShoppingSpeciesActivity.class);
					MyApplication.getInstance().finishActivity(ShoppingDetailActivity.class);
				} else if (exchangeInfo.getExchangeStatus().trim().equals(UserAmountExchangeInfo.EXCHANGE_STATUS_WAIT)) {
					if (queryOrderCount < 2) {
						showQueryOrderDlg();
					} else {
						DialogUtil.getSomeMsgDialog((Activity) mContext, getString(R.string.server_busy_msg));
					}
				}

			}

			@Override
			public void onLoading() {
				loadingDialog.show();
			}

			@Override
			public void onFail(String tag, String errorMsg) {
				loadingDialog.dismiss();
			}
		});
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("ExchangeNo", orderId);
		queryOrderCount++;
		mySoap.request(Methods.MyWallet_UserAmountExchange_GetInfoByExchangeNo, Methods.MyWallet_UserAmountExchange_GetInfoByExchangeNo, map);
	}

	/** 支付成功,但是服务器返回的账单显示还未支付,需要弹一个弹出框出来问用户是否查看订单详情 */
	private void showQueryOrderDlg() {
		final Dialog dlg = DialogUtil.getSomeMsgDialog(this, getString(R.string.credit_query_order_dlg_msg), getString(R.string.yes),
				getString(R.string.no));
		dlg.findViewById(R.id.dialog_ok_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (itemSelected != null) {
					getOrderRequest(itemSelected.getExchangeNo());
					dlg.dismiss();
				}
			}
		});
	}

	public Map<String, String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName = parser.getName();
				switch (event) {
				case XmlPullParser.START_DOCUMENT:

					break;
				case XmlPullParser.START_TAG:

					if ("xml".equals(nodeName) == false) {
						// 实例化student对象
						xml.put(nodeName, parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion", e.toString());
		}
		return null;

	}

	/**
	 *
	 * @Title: doConfirm
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param tansforCardName 交易会员卡名字
	 * @param @param amountStr 交易金额
	 * @param transforGoodsName
	 *            交易物品名称
	 * @return void 返回类型
	 * @throws
	 */
	private void doConfirm(String tansforCardName, String amountStr) {
		if (TextUtils.isEmpty(amountStr)) {
			T.showShort(mContext, getString(R.string.pls_input_transper_amount));
			return;
		}
		payDialog = DialogUtil.getPayBillCreateQRCodeDlg(this, new InputPasswordListener(), new onCanalListener());
		dlgAmountTv = (TextView) payDialog.getWindow().getDecorView().findViewById(R.id.trading_amount_tv);
		passwordEditText = (EditText) payDialog.findViewById(R.id.pay_pwd_et);
		trading_member_image = (ImageView) payDialog.findViewById(R.id.trading_member_image);
		TextView goods_name = (TextView) payDialog.findViewById(R.id.goods_name);
		trading_member_currency = (TextView) payDialog.findViewById(R.id.trading_member_currency);
		trading_member_image = (ImageView) payDialog.findViewById(R.id.trading_member_image);
		trading_member_currency.setText("- "+itemSelected.getCurrencyName()+" ");
		credit_add_linear_inpupassword = (LinearLayout) payDialog.findViewById(R.id.credit_add_linear_inpupassword);
		if (itemSelected.getPayType() == 1) {
			credit_add_linear_inpupassword.setVisibility(View.VISIBLE);
		} else {
			credit_add_linear_inpupassword.setVisibility(View.GONE);
		}
		ImageLoader.getInstance().displayImage(itemSelected.getPayTypeLogo(), trading_member_image);
		trading_member_name = (TextView) payDialog.findViewById(R.id.trading_member_name);
		trading_member_amount = (TextView) payDialog.findViewById(R.id.trading_member_amount);
		trading_member_name.setText(BingContextUtil.subZeroAndDot(tansforCardName));
		trading_member_amount.setText(BingContextUtil.subZeroAndDot(amountStr));
		ImageLoader.getInstance().displayImage(itemSelected.getPayTypeLogo(), trading_member_image);
		goods_name.setText(itemSelected.getExchangeObjectName());
		LinearLayout trading_amountselect_layout = (LinearLayout) payDialog.getWindow().getDecorView().findViewById(R.id.trading_amountselect_layout);
		trading_amountselect_layout.setOnClickListener(new GetVipCardIdListener(mPayAmount));
		BingContextUtil.SpannableStringUtil(mContext, "MOP "+amountStr, dlgAmountTv, R.style.style3, 3);
//		dlgAmountTv.setText(BingContextUtil.subZeroAndDot(String.valueOf(itemSelected.getPrice())));
		payDialog.show();
	}

	/**
	 *
	 * @ClassName: InputPasswordListener
	 * @Description: TODO(彈出輸入支付密碼對話框確定監聽)
	 * @author A18ccms a18ccms_gmail_com
	 * @date 2015年6月4日 下午4:35:53
	 *
	 */
	class InputPasswordListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (null != itemSelected) {
				if (itemSelected.getPayType() == 1) {
					// 積分支付
					String payPassword = passwordEditText.getText().toString().trim();
					if (TextUtils.isEmpty(payPassword)) {
						T.showShort(mContext, R.string.pay_pwd_title);
						return;
					}
					if (payPassword.length() < 6) {
						T.showShort(mContext, R.string.toast_pay_password_length);
						return;
					}
//					mobileRecharge(payPassword);
					// getGoodNumbers_ApplyInsert(itemSelected.getExchangeNo());
				} else {
					// 第三方支付
					PayWayUtil wayUtil = new PayWayUtil(ShoppingWriteOrderActivity.this);
					wayUtil.setShoppingOrderChirdJson(itemSelected);
					wayUtil.getPayWayUtil(itemSelected.getPayType());
				}
			}
		}

	}

	class onCanalListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			payDialog.dismiss();
			Intent intent = new Intent(mContext, ShoppingMainBillActivity.class);
			startActivity(intent);
			finish();
		}

	}

	private void mobileRecharge(String password,final  RechargeIntegralOrderItem itemSelected) {
		// TODO Auto-generated method stub
		Methods.setUrl(mContext, MyApplication.getInstance().getEndPoint());
		MySoap mySoap = new MySoap(new MySoap.OnGetDatas() {

			@Override
			public void onSuccess(String tag, String datas) {
				loadingDialog.dismiss();
				if (datas.equalsIgnoreCase("")) {
					T.showLong(mContext, R.string.network_connection_fail);
					return;
				}
				JSON json = (JSON) JsonUtil.getJsonObect(datas, JSON.class);
				T.showShort(mContext, json.getDecription().toString());
				if (json.getFlag() == 1) {
					getOrderRequest(itemSelected.getExchangeNo());
					newPayUtil.dismiss();
				}else {
				}
			}

			@Override
			public void onFail(String tag, String errorMsg) {
				loadingDialog.dismiss();
			}

			@Override
			public void onLoading() {
				loadingDialog.show();
			}
		});
		// HashMap<String, String> map = new HashMap<String, String>();
		// // map.put("UserNeiMa",
		// SharedPreferencesUtil.getUserInfoFromShare(mContext).getUserNeiMa());
		// // map.put("ExchangeNo", shoppingOrderChirdJson.getExchangeNo());
		// // map.put("Value",
		// trading_member_amount.getText().toString().trim().replace("-", ""));
		// // map.put("SafePassword", string);
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("UserNeiMa", SharedPreferencesUtil.getUserInfoFromShare(mContext).getUserNeiMa());
			jsonObject.put("ExchangeNo",  itemSelected.getExchangeNo());
			jsonObject.put("Value", BingContextUtil.formatNum(itemSelected.getPrice()));
			jsonObject.put("SafePassword", password);
			jsonObject.put("VipCardID", itemSelected.getVipCardID());
		} catch (JSONException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		HashMap<String, String> map = new HashMap<String, String>();
		String json = jsonObject.toString();
		L.d("test----" + json);
		String tempData[] = EncryptUtil.getEncryptArgment(json);
		if (null == map)
			return;
		map.put("Content", tempData[0]);
		map.put("Key", tempData[1]);
		mySoap.request(Methods.ShoppingManage_UserAmountExchange_UpdateByPayment, Methods.ShoppingManage_UserAmountExchange_UpdateByPayment, map);
	}

	class GetVipCardIdListener implements View.OnClickListener {

		private String amount = "";

		public GetVipCardIdListener(String amount) {
			super();
			this.amount = amount;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ScanStoreChridJson scanStoreChridJson = new ScanStoreChridJson();
			Intent intent = new Intent(mContext, SelectePayWayActivity.class);
			intent.putExtra(Constant.RechargeIntegralOrderItem, (ArrayList<RechargeIntegralOrderItem>) orders.getObject());
			startActivityForResult(intent, Constant.VIPCARD_REQUEST);
		}

	}
	public void onEventMainThread(RechargeIntegralOrderItem event) {
		newPayUtil.onEventMainThread(event);
	}
}


text:
var chai = require('chai')
var expect = chai.expect
var sinon = require('sinon')
var proxyquire = require('proxyquire')
var testUtils = require('../test-utils')

chai.use(require('sinon-chai'))

describe('Fun Controller', function () {
  var botkitControllerMock
  var botMock
  var messageMock
  var imagesMock
  var controller

  beforeEach(function () {
    botkitControllerMock = {
      hears: sinon.stub()
    }

    botMock = {
      reply: sinon.stub()
    }

    messageMock = {}

    imagesMock = {
      get: sinon.stub().returnsArg(0)
    }

    controller = proxyquire('../../src/controllers/fun', {
      '../lib/images': imagesMock
    })
  })

  describe('init', function () {
    it('should register listeners', function () {
      controller.use(botkitControllerMock)
      expect(botkitControllerMock.hears.callCount).to.equal(1)
    })
  })

  describe('listeners', function () {
    beforeEach(function () {
      controller.use(botkitControllerMock)
    })

    describe('guac me', function () {
      var callback

      beforeEach(function () {
        callback = testUtils.getHearsCallbackForMessage(botkitControllerMock, 'guac me')
      })

      it('should reply with an awesome gif', function () {
        callback(botMock, messageMock)
        expect(imagesMock.get).to.have.been.calledWith('guacamole')
        expect(botMock.reply).to.have.been.calledWith(messageMock, 'guacamole')
      })
    })
  })
})


text:
package dk.statsbiblioteket.doms.client.exceptions;

/**
 * Created by IntelliJ IDEA.
 * User: abr
 * Date: 11/1/11
 * Time: 4:01 PM
 * To change this template use File | Settings | File Templates.
 */
public class ValidationFailed extends ServerOperationFailed {
    public ValidationFailed(String message) {
        super(message);
    }

    public ValidationFailed(String message, Exception e) {
        super(message, e);
    }
}


text:
suite('Microtask', function() {

  var setEndOfMicrotask = ShadowDOMPolyfill.setEndOfMicrotask;

  test('single', function(done) {
    setEndOfMicrotask(done);
  });

  test('multiple', function(done) {
    var count = 0;
    setEndOfMicrotask(function() {
      count++;
      assert.equal(2, count);
    });
    setEndOfMicrotask(function() {
      count++;
      assert.equal(3, count);
    });
    setEndOfMicrotask(function() {
      count++;
      assert.equal(4, count);
      done();
    });
    count++;
  });

  test('nested', function(done) {
    var count = 0;
    setEndOfMicrotask(function() {
      assert.equal(1, count);
      setEndOfMicrotask(function() {
        assert.equal(2, count);
        done();
      });
      count++;
    });
    count++;
  });

});


text:
package hirez.realm;

import hirez.api.*;
import hirez.api.object.*;
import hirez.api.object.interfaces.Queue;
import hirez.realm.object.PlayerQuery;
import hirez.realm.object.*;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import java.util.function.Consumer;

@Slf4j
public class RealmRoyale extends Endpoint {
    private static final BaseEndpoint DEFAULT_BASE = new BaseEndpoint() {
        @Override
        public Game getGame() {
            return new Game("35lh77mxwjy9", "Realm Royale");
        }

        @Override
        public Platform getPlatform() {
            return new Platform("4bsbxhr3mrlz", "PC");
        }

        @Override
        public String getBaseUrl() {
            return "http://api.realmroyale.com/realmapi.svc";
        }
    };

    private RealmRoyale(Configuration configuration) {
        super(configuration);
    }

    public static RealmRoyale create(Consumer<ConfigurationBuilder> configuration) {
        return new RealmRoyale(new ConfigurationBuilder().applyFrom((cfg) -> {
            configuration.accept(cfg);
            if (cfg.getBaseEndpoint() == null) {
                cfg.setBaseEndpoint(DEFAULT_BASE);
            }
        }).build());
    }

    /**
     * @deprecated This endpoint is not exist. Will be removed in the next release.
     */
    @Deprecated
    public Flowable<Talent> getTalents(Language language) {
        return Flowable.error(new HiRezException("This endpoint has been removed!"));
    }

    /**
     * @deprecated This endpoint is not exist. Will be removed in the next release.
     */
    @Deprecated
    public Flowable<Talent> getTalents() {
        return getTalents(getConfiguration().getLanguage());
    }

    public Single<Leaderboard> getLeaderboard(Queue queue, Criteria criteria) {
        return testAndCall(Leaderboard.class, "getleaderboard", queue.getId().toString(), criteria.id.toString());
    }

    public Single<MatchDetails> getMatchDetails(long matchId) {
        return testAndCall(MatchDetails.class, "getmatchdetails", Long.toString(matchId));
    }

    public Flowable<MatchId> getMatchIdsByQueue(Queue queue, Date timestamp) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd/hh");
        DateFormat mdf = new SimpleDateFormat("mm");

        int minutes = Integer.parseInt(mdf.format(timestamp));

        minutes = minutes - minutes % 10 + ((minutes % 10) > 4 ? 10 : 0);

        return testAndCall(MatchId[].class, "getmatchidsbyqueue", queue.getId().toString(), df.format(timestamp) + minutes)
                .flattenAsFlowable(Arrays::asList);
    }

    public Single<PlayerMatchHistory> getPlayerMatchHistory(long userId) {
        return testAndCall(PlayerMatchHistory.class, "getplayermatchhistory", Long.toString(userId));
    }

    public Single<PlayerMatchHistory> getPlayerMatchHistoryAfterDateTime(long userId, Date after) {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        df.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
        return testAndCall(PlayerMatchHistory.class, "getplayermatchhistoryafterdatetime", df.format(after), Long.toString(userId));
    }

    public Single<Player> getPlayer(long userId) {
        return testAndCall(Player.class, "getplayer", Long.toString(userId), "hirez");
    }

    public Single<Player> getPlayerBySteamId(long steamId) {
        return testAndCall(Player.class, "getplayer", Long.toString(steamId), "steam");
    }

    public Flowable<PlayerIdPortal> getPlayerIdByName(String query) {
        return testAndCall(PlayerIdPortal.class, "getplayeridbyname", query)
                .flattenAsFlowable(Arrays::asList);
    }

    public Flowable<PlayerIdPortal> getPlayerIdByPortalUserId(Portal portal, long id) {
        return testAndCall(PlayerIdPortal[].class, "getplayeridbyportaluserid", portal.getId().toString(), Long.toString(id))
                .flattenAsFlowable(Arrays::asList);
    }

    public Flowable<PlayerIdPortal> getPlayerIdsByGamerTag(Portal portal, String query) {
        return testAndCall(PlayerIdPortal[].class, "getplayeridsbygamertag", portal.getId().toString(), query)
                .flattenAsFlowable(Arrays::asList);
    }

    public Single<PlayerStats> getPlayerStats(long userId) {
        return testAndCall(PlayerStats.class, "getplayerstats", Long.toString(userId));
    }

    public Single<PlayerStatus> getPlayerStatus(long userId) {
        return testAndCall(PlayerStatus.class, "getplayerstatus", Long.toString(userId));
    }

    public Flowable<PlayerQuery> searchPlayer(String query) {
        return testAndCall(PlayerQuery[].class, "searchplayers", query)
                .flattenAsFlowable(Arrays::asList);
    }

    @Override
    public Flowable<HiRezServer> getHiRezServerStatus() {
        return testAndCall(HiRezServer.class, "gethirezserverstatus")
                .flattenAsFlowable(Arrays::asList);
    }

    public Single<DataUsage> getDataUsed() {
        return testAndCall(DataUsage.class, "getdataused");
    }
}


text:
1. [Overview - _What it is_](#overview)
2. [Description - _What it does_](#description)
3. [Setup - _How to set it up_](#setup)
    * [Requirements](#requirements)
    * [Installation](#installation)
4. [Usage - _How to use it_](#usage)
    * [watchgit.py - _daemon_](#watchgitpy)
    * [watchgit.conf - _configuration file_](#watchgitconf)

## Overview
Keep local git repositories in sync

## Description
Watchgit is a daemon that keeps local git repositories in sync. It does this by periodically pulling a remote for every repository specified in its configuration file.

* Monitors repositories specified in [watchgit.conf](#watchgitconf)
* Periodically pulls a ref specified by [ref](#watchgitconf) and [interval](#watchgitconf) from a [remote](#watchgitconf)
* Clones the repository if it does not exist.

## Setup

### Requirements
* Python 2.7
* [python-daemon](https://pypi.python.org/pypi/python-daemon/1.6) (>=1.6)
* [GitPython](http://pythonhosted.org/GitPython/0.3.2/) (>= 0.3.1)

### Installation
#### Setuptools
    python setup.py install

#### RPM
(**TODO** - files can be found under [ext/redhat](ext/redhat))

## Usage

### watchgit.py

    usage: watchgit.py [-h] [-c CONFIG] [-p PIDFILE] [-f] command

    positional arguments:
      command               [start|stop|status]

    optional arguments:
      -h, --help            show this help message and exit
      -c CONFIG, --config CONFIG
                            configuration file. (Default: watchgit.conf)
      -p PIDFILE, --pidfile PIDFILE
                            pid file. (Default: watchgit.pid)
      -f, --foreground      run in foreground

### watchgit.conf
Global defaults and parameters such as logfile and loglevel are specified under the `GLOBAL` section.

    [GLOBAL]
    all_remotes   = false
    interval      = 5
    ref           = master
    reset         = true
    logfile       = watchgit.log
    loglevel      = info
    skip_on_error = false
    user          = nobody
    group         = nogroup

Individual repositories are specified as their own section with the name of the repository as the section name.

    [watchgit]
    all_remotes   = true
    interval      = 300
    local         = /opt/watchgit/
    remote        = https://github.com/tdevelioglu/watchgit.git
    reset         = false
    skip_on_error = true
    user          = someuser
    group         = somegroup

#### Global parameters

* `all_remotes` - Whether to pull all git remotes in a repository's git configuration.
* `interval` - How frequently to pull a repository's remote.
* `ref` - Remote ref to use when pulling.
* `reset` - Whether to reset the local HEAD before pulling.
* `logfile` - Location of the logfile.
* `loglevel` - Log level.
* `skip_on_error` - Whether to skip repositories if an error occurs during clone or open.
* `user` - User to run the watchgit daemon as.
* `group` - Group to run the watchgit daemon as.

#### Repo parameters
* `all_remotes` - Whether to pull all git remotes in the repository's git configuration.
* `interval` - How frequently to pull the repository's remote.
* `local` - Local filesystem path to the repository.
* `remote` - Url to the remote repository.
* `ref` - Remote ref to use when pulling.
* `reset` - Whether to reset the local HEAD before pulling.
* `skip_on_error` - Whether to skip the repository if an error occurs during clone or open.
* `user` - User to watch the repository as.
* `group` - Group to watch the repository as.


text:
require 'fog'
module InstanceManager
  module Actions
    class Search < Action

      def run
        connection = InstanceManager::Connection.instance.compute_connection
        st = prepare_search_hash(connection)
        instances = connection.servers.all(st)

        if instances.nil? || instances.size == 0
          puts "No instances found that match #{@args}"
        else
          puts InstanceFormatter.new(instances).format_output
        end
      end

      private

      def prepare_search_hash(connection)
        if instance_id?
          filter = "instance-id"
        elsif private_ip?
          filter = "private-ip-address"
        elsif public_ip?
          filter = "ip-address"
        elsif private_hostname?
          filter = "private-dns-name"
        elsif public_hostname?
          filter = "dns-name"
        end
        {filter => append_domain_name}
      end

      def append_domain_name
        args = @args.dup
        ec2 = args.match(/ec2.internal/)
        compute = args.match(/compute-1.internal/)
        if args =~ /^domU/ && !compute
          args << ".compute-1.internal"
        elsif args =~ /^ip/ && !ec2
          args << ".ec2.internal"
        end
        args
      end

      def instance_id?
        !!@args.match(/^i-/)
      end
      def private_ip?
        !!@args.match(/^10\./)
      end
      def public_ip?
        !!@args.match(/^\d{1,3}/)
      end
      def public_hostname?
        !!@args.match(/^(ec2)/)
      end
      def private_hostname?
        @args.match(/^(ip|domU)/)
      end

    end
  end
end


text:
{% if perms.catalog.add_vendorkey or perms.catalog.change_vendorkey %}

    <form>

    	<input id="edit-vendorkey-id" type="hidden" value="0">

    	Вариант написания
    		<input id="edit-vendorkey-name" type="text" value="">

    	Загрузчик
    		<select id="edit-vendorkey-updater">
    			{% for updater in updaters %}
    			<option value="{{ updater.id }}">{{ updater.name }}</option>
    			{% endfor %}
    		</select>

    	Производитель
    		<select id="edit-vendorkey-vendor">
    			<option value="0" selected> - Не определён (None) - </option>
    			{% for vendor in vendors %}
    			<option value="{{ vendor.id }}">{{ vendor.name }}</option>
    			{% endfor %}
    		</select>

            Сохранить
            Отменить

    </form>

    <button class="close-button" data-close aria-label="Close modal" type="button">
        ×
    </button>

{% endif %}


text:
package org.abstractform.binding;

import java.util.Iterator;
import java.util.ServiceLoader;

import javax.management.ServiceNotFoundException;

public class BindingService {

	private static BindingService instance;

	private ServiceLoader<BindingToolkit> loader;

	private BindingService() {
		loader = ServiceLoader.load(BindingToolkit.class);
	}

	public static synchronized BindingService getInstance() {
		if (instance == null) {
			instance = new BindingService();
		}
		return instance;
	}

	public BindingToolkit getBindingToolkit() throws ServiceNotFoundException {
		Iterator<BindingToolkit> it = loader.iterator();
		BindingToolkit toolkit = null;
		while (toolkit == null && it.hasNext()) {
			BindingToolkit tl = it.next();
			toolkit = tl;
		}
		if (toolkit == null) {
			throw new ServiceNotFoundException();
		} else {
			return toolkit;
		}
	}

}


text:
SpriteSheet::SpriteSheet(sf::Texture& texture, unsigned char width, unsigned char height) : mTexture(texture)
{
    auto tSize = texture.getSize();
    mSize = sf::Vector2u(width, height);
    mSpriteSize = sf::Vector2u((float)tSize.x / mSize.x, (float)tSize.y / mSize.y);

}

SpriteSheet::~SpriteSheet()
{
}

sf::IntRect SpriteSheet::getRect(unsigned char x, unsigned char y)
{
    return sf::IntRect(mSpriteSize.x * x, mSpriteSize.y * y, mSpriteSize.x, mSpriteSize.y);
}


text:
'use strict';

var helpers = require('./helpers');
var escape = helpers.escape;
var unescape = helpers.unescape;

/**
 * Renderer
 */

module.exports = Renderer;

function Renderer(options) {
  this.options = options || {};
}

Renderer.prototype.code = function(code, lang, escaped) {
  if (this.options.highlight) {
    var out = this.options.highlight(code, lang);
    if (out !== null && out !== code) {
      escaped = true;
      code = out;
    }
  }

  if (!lang) {
    return '
'
      + (escaped ? code : escape(code, true))
      + '\n
';
  }

  return '
'
    + (escaped ? code : escape(code, true))
    + '\n
\n';
};

Renderer.prototype.blockquote = function(quote) {
  return '
\n' + quote + '
\n';
};

Renderer.prototype.html = function(html) {
  return html;
};

Renderer.prototype.heading = function(text, level, raw) {
  return '<h'
    + level
    + ' id="'
    + this.options.headerPrefix
    + raw.toLowerCase().replace(/[^\w]+/g, '-')
    + '">'
    + text
    + '</h'
    + level
    + '>\n';
};

Renderer.prototype.hr = function() {
  return this.options.xhtml ? '
\n' : '
\n';
};

Renderer.prototype.list = function(body, ordered) {
  var type = ordered ? 'ol' : 'ul';
  return '<' + type + '>\n' + body + '</' + type + '>\n';
};

Renderer.prototype.listitem = function(text) {
  return '
' + text + '
\n';
};

Renderer.prototype.paragraph = function(text) {
  return '
' + text + '
\n';
};

Renderer.prototype.table = function(header, body) {
  return '
\n'
    + '
\n'
    + header
    + '
\n'
    + '
\n'
    + body
    + '
\n'
    + '
\n';
};

Renderer.prototype.tablerow = function(content) {
  return '
\n' + content + '
\n';
};

Renderer.prototype.tablecell = function(content, flags) {
  var type = flags.header ? 'th' : 'td';
  var tag = flags.align
    ? '<' + type + ' style="text-align:' + flags.align + '">'
    : '<' + type + '>';
  return tag + content + '</' + type + '>\n';
};

// span level renderer
Renderer.prototype.strong = function(text) {
  return '' + text + '';
};

Renderer.prototype.em = function(text) {
  return '' + text + '';
};

Renderer.prototype.codespan = function(text) {
  return '' + text + '';
};

Renderer.prototype.br = function() {
  return this.options.xhtml ? '
' : '
';
};

Renderer.prototype.del = function(text) {
  return '' + text + '';
};

Renderer.prototype.link = function(href, title, text) {
  var prot;
  if (this.options.sanitize) {
    try {
       prot = decodeURIComponent(unescape(href))
        .replace(/[^\w:]/g, '')
        .toLowerCase();
    } catch (e) {
      return '';
    }
    if (prot.indexOf('javascript:') === 0) {
      return '';
    }
  }
  var out = '' + text + '';
  return out;
};

Renderer.prototype.image = function(href, title, text) {
  var out = '' : '>';
  return out;
};


text:
package org.appenders.log4j2.elasticsearch;

import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
import org.appenders.core.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

import static org.appenders.core.logging.InternalLogging.getLogger;
import static org.appenders.core.logging.InternalLogging.setLogger;
import static org.appenders.core.logging.InternalLoggingTest.mockTestLogger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class AsyncBatchEmitterTest {

    public static final int TEST_DELIVERY_INTERVAL = 100000000;
    public static final int TEST_BATCH_SIZE = 2;
    public static final String TEST_DATA = "dummyData";

    @BeforeEach
    public void setup() {
        System.setProperty("appenders." + AsyncBatchEmitter.EmitterLoop.class.getSimpleName() + ".startDelay", "0");
    }

    @AfterEach
    public void tearDown() {
        setLogger(null);
    }

    @Test
    public void notifiesOnBatchWithGivenSize() {

        // given
        int batchSize = 3;
        AsyncBatchEmitter emitter = createTestBulkEmitter(batchSize, TEST_DELIVERY_INTERVAL, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        System.setProperty("appenders." + AsyncBatchEmitter.EmitterLoop.class.getSimpleName() + ".startDelay", "0");
        emitter.start();

        // when
        for (int ii = 0; ii < batchSize; ii++) {
            emitter.add(new TestBatchItem(TEST_DATA));
        }

        // then
        ArgumentCaptor<TestBatch> captor = ArgumentCaptor.forClass(TestBatch.class);
        verify(dummyObserver, timeout(100)).apply(captor.capture());
        assertEquals(batchSize, captor.getValue().items.size());

    }

    @Test
    public void notifiesOnEveryCompletedBatch() {

        // given
        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations());

        System.setProperty("appenders." + AsyncBatchEmitter.EmitterLoop.class.getSimpleName() + ".startDelay", "0");
        emitter.start();

        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        int expectedNumberOfBatches = 2;

        // when
        for (int ii = 0; ii < TEST_BATCH_SIZE * expectedNumberOfBatches ; ii++) {
            emitter.add(new TestBatchItem(TEST_DATA));
        }

        // then
        ArgumentCaptor<TestBatch> captor = ArgumentCaptor.forClass(TestBatch.class);
        verify(dummyObserver, timeout(500).times(expectedNumberOfBatches)).apply(captor.capture());
        for (TestBatch batch : captor.getAllValues()) {
            assertEquals(TEST_BATCH_SIZE, batch.items.size());
        }

    }

    @Test
    public void listenerIsNotNotifiedWhenThereNoItemsToBatch() {

        // given
        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        // when
        emitter.notifyListener();

        // then
        verify(dummyObserver, never()).apply(any());

    }

    @Test
    public void listenerIsNotNotifiedWhenAlreadyNotifying() {

        // given
        final Logger logger = mockTestLogger();
        final AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations());
        final CountDownLatch latch = new CountDownLatch(1);
        final Function<TestBatch, Boolean> dummyObserver = spy(new Function<TestBatch, Boolean>() {
            @Override
            public Boolean apply(TestBatch testBatch) {
                try {
                    getLogger().info("Notified");
                    latch.await();
                    return true;
                } catch (InterruptedException e) {
                    return false;
                }
            }
        });
        emitter.addListener(dummyObserver);

        emitter.add(new TestBatchItem(TEST_DATA));

        // when
        new Thread(emitter::notifyListener).start();

        verify(logger, timeout(500)).info("Notified");

        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.notifyListener();

        latch.countDown();

        // then
        verify(dummyObserver, times(1)).apply(any());

        setLogger(null);

    }

    @Test
    public void listenerIsNotNotifiedWithIncompleteBatchIfNotShuttingDown() {

        // given
        final Logger logger = mockTestLogger();
        final AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations());
        final Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));

        // when
        new Thread(emitter::notifyListener).start();

        verify(logger, timeout(500)).info("Dummy notified");

        emitter.notifyListener();

        // then
        verify(dummyObserver, times(1)).apply(any());

        setLogger(null);

    }

    @Test
    public void listenerIsNotNotifiedWithIncompleteBatchIfLastNotificationPeriodLowerThanDeliveryInterval() {

        // given
        final Logger logger = mockTestLogger();
        final AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 500, new TestBatchOperations());
        final Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));

        emitter.start();
        verify(logger, timeout(500)).info("Dummy notified");
        verify(dummyObserver, times(1)).apply(any());

        // when
        Mockito.reset(logger);
        verify(logger, times(0)).info("Dummy notified"); // sanity check

        verify(logger, timeout(2000)).info("Dummy notified"); // wait until last notification gap grows beyond interval

        // then
        verify(dummyObserver, times(2)).apply(any());

        setLogger(null);

    }

    @Test
    public void listenerIsNotifiedWithIncompleteBatchIfLastNotificationPeriodLowerThanDeliveryIntervalIfShuttingDown() {

        // given
        final Logger logger = mockTestLogger();
        final AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 500, new TestBatchOperations());
        final Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));
        emitter.add(new TestBatchItem(TEST_DATA));

        emitter.start();
        verify(logger, timeout(500)).info("Dummy notified");
        verify(dummyObserver, times(1)).apply(any());

        // when
        Mockito.reset(logger);
        verify(logger, times(0)).info("Dummy notified"); // sanity check

        emitter.stop();

        // then
        verify(dummyObserver, times(2)).apply(any());

        setLogger(null);

    }

    @Test
    public void listenerIsNotifiedByScheduledTask() {

        // given
        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 10, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);
        emitter.start();

        assertTrue(TEST_BATCH_SIZE > 1);

        // when
        emitter.add(new Object());

        // then
        verify(dummyObserver, timeout(100)).apply(any());

    }

    @Test
    public void listenerIsNotifiedOnLifecycleStop() {

        // given
        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 1000, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        assertTrue(TEST_BATCH_SIZE > 1);

        emitter.start();

        // when
        emitter.add(new Object());
        emitter.stop();

        // then
        verify(dummyObserver, timeout(100)).apply(any());

    }

    @Test
    public void listenerIsNotNotifiedAfterLifecycleStopCauseSchedulerIsCancelled() throws InterruptedException {

        // given
        assertTrue(TEST_BATCH_SIZE > 1);

        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 10, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        emitter.start();

        // when
        emitter.add(new Object());
        int invocations = Mockito.mockingDetails(dummyObserver).getInvocations().size();
        emitter.stop();
        Thread.sleep(50);

        // then
        // stop() notifies explicitly, hence +1
        verify(dummyObserver, times(invocations + 1)).apply(any());

    }

    @Test
    public void listenerIsNotifiedIfShutdownDecrementFitsStopTimeout() throws InterruptedException {

        // given
        final Logger logger = mockTestLogger();

        assertTrue(TEST_BATCH_SIZE > 1);

        System.setProperty("appenders." + AsyncBatchEmitter.class.getSimpleName() + ".shutdownDecrementMillis", "10");

        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 10, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = dummyObserver();
        emitter.addListener(dummyObserver);

        emitter.start();

        // when
        emitter.add(new Object());
        verify(logger, timeout(500)).info("Dummy notified");

        Mockito.reset(logger);

        verify(logger, never()).info("Dummy notified"); // sanity check

        emitter.add(new Object());

        emitter.stop(500, true);

        // then
        verify(logger, timeout(500)).info("Dummy notified");

        System.clearProperty("appenders." + AsyncBatchEmitter.class.getSimpleName() + ".shutdownDecrementMillis");

        setLogger(null);

    }

    @Test
    public void listenerExceptionsAreHandled() {

        // given
        final Logger logger = mockTestLogger();

        assertTrue(TEST_BATCH_SIZE > 1);

        AsyncBatchEmitter emitter = createTestBulkEmitter(TEST_BATCH_SIZE, 10000, new TestBatchOperations());
        Function<TestBatch, Boolean> dummyObserver = testBatch -> {
            throw new IllegalArgumentException("test");
        };
        emitter.addListener(dummyObserver);

        emitter.start();

        // when
        emitter.add(new Object());
        emitter.add(new Object());

        verify(logger, timeout(500)).error("{}: Execution failed: {}", AsyncBatchEmitter.EmitterLoop.class.getSimpleName(), "test");
        Mockito.reset(logger);

        emitter.add(new Object());
        emitter.add(new Object()); // second batch to ensure that loop was reset

        // then
        verify(logger, timeout(500)).error("{}: Execution failed: {}", AsyncBatchEmitter.EmitterLoop.class.getSimpleName(), "test");

        emitter.stop(500, true);
        setLogger(null);

    }

    @Test
    public void lifecycleStart() {

        // given
        LifeCycle lifeCycle = createLifeCycleTestObject();

        assertTrue(lifeCycle.isStopped());

        // when
        lifeCycle.start();

        // then
        assertFalse(lifeCycle.isStopped());
        assertTrue(lifeCycle.isStarted());

    }

    @Test
    public void lifecycleStop() {

        // given
        LifeCycle lifeCycle = createLifeCycleTestObject();

        assertTrue(lifeCycle.isStopped());

        lifeCycle.start();
        assertTrue(lifeCycle.isStarted());

        // when
        lifeCycle.stop();

        // then
        assertFalse(lifeCycle.isStarted());
        assertTrue(lifeCycle.isStopped());

    }

    @Test
    public void lifecycleStartStartsOnlyOnce() {

        // given
        AsyncBatchEmitter lifeCycle = spy(createLifeCycleTestObject());

        assertTrue(lifeCycle.isStopped());

        // when
        lifeCycle.start();
        lifeCycle.start();

        // then
        verify(lifeCycle).getEmitterLoop();
        assertTrue(lifeCycle.isStarted());

        lifeCycle.stop();

    }

    @Test
    public void lifecycleStopStopsOnlyOnce() {

        // given
        final AtomicInteger shutdownCaptor = new AtomicInteger();
        AsyncBatchEmitter lifeCycle = new AsyncBatchEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations()) {
            @Override
            void shutdownExecutor() {
                shutdownCaptor.incrementAndGet();
            }
        };

        assertTrue(lifeCycle.isStopped());

        lifeCycle.start();
        assertTrue(lifeCycle.isStarted());

        // when
        lifeCycle.stop();
        lifeCycle.stop();

        // then
        assertFalse(lifeCycle.isStarted());
        assertEquals(1, shutdownCaptor.get());

    }

    private AsyncBatchEmitter createLifeCycleTestObject() {
        return createTestBulkEmitter(TEST_BATCH_SIZE, TEST_DELIVERY_INTERVAL, new TestBatchOperations());
    }

    public static AsyncBatchEmitter createTestBulkEmitter(int batchSize, int interval, BatchOperations batchOperations) {
        return new AsyncBatchEmitter(batchSize, interval, batchOperations);
    }

    private BatchOperations<Collection> createDummyBatchOperations() {
        return new BatchOperations<Collection>() {
            @Override
            public Object createBatchItem(String indexName, Object source) {
                return source;
            }

            @Override
            public Object createBatchItem(String indexName, ItemSource source) {
                return source;
            }

            @Override
            public BatchBuilder<Collection> createBatchBuilder() {
                return createTestBatchBuilder();
            }

        };
    }

    private Function<TestBatch, Boolean> dummyObserver() {
        return spy(new DummyListener());
    }

    private BatchBuilder<Collection> createTestBatchBuilder() {
        return new BatchBuilder<Collection>() {
            final Collection items = new ConcurrentLinkedQueue();

            @Override
            public void add(Object item) {
                items.add(item);
            }
            @Override
            public Collection build() {
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    iterator.next();
                }
                return items;
            }

        };
    }

    static class DummyListener implements Function<TestBatch, Boolean> {

        @Override
        public Boolean apply(TestBatch arg1) {
            getLogger().info("Dummy notified");
            return true;
        }
    }

    public static class TestBatchOperations implements BatchOperations {

        @Override
        public Object createBatchItem(String indexName, Object source) {
            return new TestBatchItem(source);
        }

        @Override
        public Object createBatchItem(String indexName, ItemSource source) {
            return new TestBatchItem(source.getSource());
        }

        @Override
        public BatchBuilder createBatchBuilder() {
            return new TestBatchBuilder();
        }

    }
    public static class TestBatchBuilder implements BatchBuilder {

        private final Collection<Object> items = new ConcurrentLinkedQueue<>();

        @Override
        public void add(Object item) {
            items.add(item);
        }

        @Override
        public Object build() {
            return new TestBatch(items);
        }

    }

    public static class TestBatchItem {

        private final Object data;

        public TestBatchItem(Object data) {
            this.data = data;
        }

        public Object getData(Object o) {
            return data;
        }
    }
    public static class TestBatch {

        public Collection<Object> items;

        public TestBatch(Collection<Object> items) {
            this.items = items;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Gdns' Bull. , Singapore. Supplement 2: 79 (1991)

#### Original name
Trogia subtranslucens Corner

### Remarks
null


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <bean id="http401UnauthorizedEntryPoint"
          class="<%= groupArtifactName %>.<%=packageAppName%>.security.Http401UnauthorizedEntryPoint"/>

    <bean id="ajaxAuthenticationFailureHandler"
          class="<%= groupArtifactName %>.<%=packageAppName%>.security.AjaxAuthenticationFailureHandler"/>
    <bean id="ajaxAuthenticationSuccessHandler"
          class="<%= groupArtifactName %>.<%=packageAppName%>.security.AjaxAuthenticationSuccessHandler"/>

        <bean id="ajaxLogoutSuccessHandler"
          class="<%= groupArtifactName %>.<%=packageAppName%>.security.AjaxLogoutSuccessHandler"/>

    <security:http pattern="/*" security="none"/>
    <security:http pattern="/resources/**" security="none"/>
    <security:http pattern="/views/**" security="none"/>

    <security:http pattern="/services/rest/**" entry-point-ref="http401UnauthorizedEntryPoint" use-expressions="true">
        <security:intercept-url pattern="/**" access="isAuthenticated()"/>
    </security:http>

    <security:http auto-config='true' use-expressions="true">

        <security:intercept-url pattern="/services/rest/**" access="isAuthenticated()"/>

        <security:form-login
            login-processing-url="/services/authentication"
            login-page="/"
            authentication-failure-handler-ref="ajaxAuthenticationFailureHandler"
            authentication-success-handler-ref="ajaxAuthenticationSuccessHandler"/>

        <security:logout logout-url="/services/logout"
                             success-handler-ref="ajaxLogoutSuccessHandler"/>
    </security:http>

    <security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" />

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="admin" authorities="ROLE_ADMIN" />
                <security:user name="stanislas" password="stanislas" authorities="ROLE_USER" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

</beans>


text:
import rethinkdb as r
from rethinkdb.errors import RqlRuntimeError, RqlDriverError
import time
import json

def action(**kwargs):
    ''' This method is called to action a reaction '''
    redata = kwargs['redata']
    jdata = kwargs['jdata']
    rdb = kwargs['rdb']
    r_server = kwargs['r_server']
    logger = kwargs['logger']
    return logit(jdata, rdb, r_server, logger)

def logit(jdata, rdb, r_server, logger):
    ''' This method will be called to log monitor transaction history '''
    transaction = {
        'cid': jdata['cid'],
        'type': "monitor",
        'starttime': jdata['time_tracking']['control'],
        'zone': jdata['zone'],
        'uid': jdata['uid'],
        'url': jdata['url'],
        'failcount': jdata['failcount'],
        'status': jdata['check']['status'],
        'method': jdata['check']['method'],
        'time': time.time(),
        'cacheonly': jdata['cacheonly'],
        'name': jdata['name']
    }
    success = False
    cacheonly = False

    # Try to set rethinkdb first
    try:
        results = r.table('history').insert(transaction).run(rdb)
        if results['inserted'] == 1:
            success = True
            cacheonly = False
        else:
            success = False
    except (RqlDriverError, RqlRuntimeError) as e:
        success = False
        cacheonly = True
        line = "logit-monitor: RethinkDB is inaccessible cannot log %s, sending to redis" % jdata['cid']
        logger.info(line)
        line = "logit-monitor: RethinkDB Error: %s" % e.message
        logger.info(line)
        try:
            # Then set redis cache
            ldata = json.dumps(transaction)
            r_server.sadd("history", ldata)
            success = True
        except:
            line = "logit-monitor: Redis is inaccessible cannot log %s, via redis" % jdata['cid']
            logger.info(line)
            success = False
    return success


text:
(function() {
  'use strict';

  angular
    .module('guh.ui')
    .directive('guhToggleGrid', guhToggleGrid);

    guhToggleGrid.$inject = ['$log', 'hotkeys'];

    function guhToggleGrid($log, hotkeys) {
      var directive = {
        link: guhToggleGridLink,
        restrict: 'A'
      };

      return directive;

      function guhToggleGridLink(scope, element, attrs) {

        var key = 'ctrl+g';
        var gridClass = 'grid-overlay';

        /*
         * Private methods
         *
         */

        var _init = function() {
          // Add grid-class if it should be enabled by default
          if(attrs.guhToggleGrid && attrs.guhToggleGrid === 'show') {
            element.addClass(gridClass);
          }

          // Add hotkey to toggle the grid
          hotkeys.add({
            combo: key,
            description: 'Toggles the layout grid for CSS development.',
            callback: scope.toggle
          });
        };

        /*
         * Public methods
         *
         */

        scope.toggle = function() {
          element.toggleClass(gridClass);
        };

        /*
         * Events
         *
         */

        // Remove the hotkey if the directive is destroyed:
        element.bind('$destroy', function() {
          hotkeys.del(scope.key);
        });

        /*
         * Initialize
         */

        _init();

      }
    }

}());


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

namespace Azure.ResourceManager.DataFactory.Models
{
    /// <summary> Azure Databricks Delta Lake import command settings. </summary>
    public partial class AzureDatabricksDeltaLakeImportCommand : ImportSettings
    {
        /// <summary> Initializes a new instance of AzureDatabricksDeltaLakeImportCommand. </summary>
        public AzureDatabricksDeltaLakeImportCommand()
        {
            ImportSettingsType = "AzureDatabricksDeltaLakeImportCommand";
        }

        /// <summary> Initializes a new instance of AzureDatabricksDeltaLakeImportCommand. </summary>
        /// <param name="importSettingsType"> The import setting type. </param>
        /// <param name="additionalProperties"> Additional Properties. </param>
        /// <param name="dateFormat"> Specify the date format for csv in Azure Databricks Delta Lake Copy. Type: string (or Expression with resultType string). </param>
        /// <param name="timestampFormat"> Specify the timestamp format for csv in Azure Databricks Delta Lake Copy. Type: string (or Expression with resultType string). </param>
        internal AzureDatabricksDeltaLakeImportCommand(string importSettingsType, IDictionary<string, BinaryData> additionalProperties, BinaryData dateFormat, BinaryData timestampFormat) : base(importSettingsType, additionalProperties)
        {
            DateFormat = dateFormat;
            TimestampFormat = timestampFormat;
            ImportSettingsType = importSettingsType ?? "AzureDatabricksDeltaLakeImportCommand";
        }

        /// <summary>
        /// Specify the date format for csv in Azure Databricks Delta Lake Copy. Type: string (or Expression with resultType string).
        /// <para>
        /// To assign an object to this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public BinaryData DateFormat { get; set; }
        /// <summary>
        /// Specify the timestamp format for csv in Azure Databricks Delta Lake Copy. Type: string (or Expression with resultType string).
        /// <para>
        /// To assign an object to this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public BinaryData TimestampFormat { get; set; }
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.PodCluster;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.gpu.HostGpuGroupsVO;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ResourceState.Event;
import com.cloud.utils.fsm.NoTransitionException;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;

/**
 * ResourceManager manages how physical resources are organized within the
 * CloudStack. It also manages the life cycle of the physical resources.
 */
public interface ResourceManager extends ResourceService, Configurable {

    ConfigKey<Boolean> KvmSshToAgentEnabled = new ConfigKey<>("Advanced", Boolean.class,
            "kvm.ssh.to.agent","true",
            "Number of retries when preparing a host into Maintenance Mode is faulty before failing",
            false);

    /**
     * Register a listener for different types of resource life cycle events.
     * There can only be one type of listener per type of host.
     *
     * @param Event type see ResourceListener.java, allow combination of multiple events.
     * @param listener the listener to notify.
     */
    public void registerResourceEvent(Integer event, ResourceListener listener);

    public void unregisterResourceEvent(ResourceListener listener);

    /**
     *
     * @param name of adapter
     * @param adapter
     * @param hates, a list of names which will be eliminated by this adapter. Especially for the case where
     * can be only one adapter responds to an event, e.g. startupCommand
     */
    public void registerResourceStateAdapter(String name, ResourceStateAdapter adapter);

    public void unregisterResourceStateAdapter(String name);

    public Host createHostAndAgent(Long hostId, ServerResource resource, Map<String, String> details, boolean old, List<String> hostTags, boolean forRebalance);

    public Host addHost(long zoneId, ServerResource resource, Type hostType, Map<String, String> hostDetails);

    public HostVO createHostVOForConnectedAgent(StartupCommand[] cmds);

    public void checkCIDR(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask);

    public HostVO fillRoutingHostVO(HostVO host, StartupRoutingCommand ssCmd, HypervisorType hyType, Map<String, String> details, List<String> hostTags);

    public void deleteRoutingHost(HostVO host, boolean isForced, boolean forceDestroyStorage) throws UnableDeleteHostException;

    public boolean executeUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException;

    boolean resourceStateTransitTo(Host host, Event event, long msId) throws NoTransitionException;

    boolean umanageHost(long hostId);

    boolean migrateAwayFailed(long hostId, long vmId);

    public boolean maintain(final long hostId) throws AgentUnavailableException;

    public boolean checkAndMaintain(final long hostId);

    @Override
    public boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage);

    public List<HostVO> findDirectlyConnectedHosts();

    public List<HostVO> listAllUpAndEnabledHosts(Host.Type type, Long clusterId, Long podId, long dcId);

    public List<HostVO> listAllHosts(final Host.Type type, final Long clusterId, final Long podId, final long dcId);

    public List<HostVO> listAllUpHosts(Host.Type type, Long clusterId, Long podId, long dcId);

    public List<HostVO> listAllHostsInCluster(long clusterId);

    public List<HostVO> listHostsInClusterByStatus(long clusterId, Status status);

    public List<HostVO> listAllUpAndEnabledHostsInOneZoneByType(Host.Type type, long dcId);

    public List<HostVO> listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType type, long dcId);

    public List<HostVO> listAllUpAndEnabledHostsInOneZone(long dcId);

    public List<HostVO> listAllHostsInOneZoneByType(Host.Type type, long dcId);

    public List<HostVO> listAllHostsInAllZonesByType(Type type);

    public List<HypervisorType> listAvailHypervisorInZone(Long hostId, Long zoneId);

    public HostVO findHostByGuid(String guid);

    public HostVO findHostByName(String name);

    HostStats getHostStatistics(long hostId);

    Long getGuestOSCategoryId(long hostId);

    String getHostTags(long hostId);

    List<PodCluster> listByDataCenter(long dcId);

    List<HostVO> listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId);

    HypervisorType getDefaultHypervisor(long zoneId);

    HypervisorType getAvailableHypervisor(long zoneId);

    Discoverer getMatchingDiscover(HypervisorType hypervisorType);

    List<HostVO> findHostByGuid(long dcId, String guid);

    /**
     * @param type
     * @param clusterId
     * @param podId
     * @param dcId
     * @return
     */
    List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId);

    /**
     * Check if host is GPU enabled
     * @param hostId the host to be checked
     * @return true if host contains GPU card else false
     */
    boolean isHostGpuEnabled(long hostId);

    /**
     * Check if host has GPU devices available
     * @param hostId the host to be checked
     * @param groupName: gpuCard name
     * @param vgpuType the VGPU type
     * @return true when the host has the capacity with given VGPU type
     */
    boolean isGPUDeviceAvailable(long hostId, String groupName, String vgpuType);

    /**
     * Get available GPU device
     * @param hostId the host to be checked
     * @param groupName: gpuCard name
     * @param vgpuType the VGPU type
     * @return GPUDeviceTO[]
     */
    GPUDeviceTO getGPUDevice(long hostId, String groupName, String vgpuType);

    /**
     * Return listof available GPU devices
     * @param hostId, the host to be checked
     * @param groupName: gpuCard name
     * @param vgpuType the VGPU type
     * @return List of HostGpuGroupsVO.
     */
    List<HostGpuGroupsVO> listAvailableGPUDevice(long hostId, String groupName, String vgpuType);

    /**
     * Update GPU device details (post VM deployment)
     * @param hostId, the dest host Id
     * @param groupDetails, capacity of GPU group.
     */
    void updateGPUDetails(long hostId, HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails);

    /**
     * Get GPU details for a host
     * @param host, the Host object
     * @return Details of groupNames and enabled VGPU type with remaining capacity.
     */
    HashMap<String, HashMap<String, VgpuTypesInfo>> getGPUStatistics(HostVO host);

    HostVO findOneRandomRunningHostByHypervisor(HypervisorType type);

    boolean cancelMaintenance(final long hostId);
}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

/**
 * Class CreateLanguagesTable.
 */
final class CreateLanguagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create("languages", function (Blueprint $table) {
            $table->bigIncrements("id");
            $table->string("name")->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists("languages");
    }
}


text:
import { MathApi } from "./application";

const actual1 = MathApi.pow(3, 5);
const expected1 = 243;
const asertion1 = actual1 === expected1;

if (asertion1 === false) {
    throw new Error(
        `Expected 'actual1' to be ${expected1} ` +
        `but got ${actual1}!`
    );
}

const actual2 = MathApi.pow(5, 3);
const expected2 = 125;
const asertion2 = actual2 === expected2;

if (asertion2 === false) {
    throw new Error(
        `Expected 'actual2' to be ${expected2} ` +
        `but got ${actual2}!`
    );
}


text:
require "webpacker/file_loader"

class Webpacker::Manifest < Webpacker::FileLoader
  class << self
    def file_path
      Webpacker::Configuration.manifest_path
    end

    def lookup(name)
      load if Webpacker.env.development?

      if Webpacker.env.test?
        find(name) || compile_and_find!(name)
      else
        find!(name)
      end
    end

    def lookup_path(name)
      Rails.root.join(File.join(Webpacker::Configuration.output_path, lookup(name)))
    end

    private
      def find(name)
        instance.data[name.to_s] if instance
      end

      def find!(name)
        raise Webpacker::FileLoader::FileLoaderError.new("Webpacker::Manifest.load must be called first") unless instance
        instance.data[name.to_s] || raise(Webpacker::FileLoader::NotFoundError.new("Can't find #{name} in #{file_path}. Is webpack still compiling?"))
      end

      def compile_and_find!(name)
        Webpacker.compile
        find!(name)
      end
  end

  private
    def load
      return super unless File.exist?(@path)
      JSON.parse(File.read(@path))
    end
end


text:
package elasta.core.flow;

/**
 * Created by Khan on 5/7/2016.
 */
public class FlowException extends RuntimeException {
    public FlowException(String s) {
        super(s);
    }
}


text:
package net.dirtyfilthy.bouncycastle.asn1;

import java.io.IOException;
import java.util.Enumeration;

/**
 * @deprecated use BERSequence
 */
public class BERConstructedSequence
    extends DERConstructedSequence
{
    /*
     */
    void encode(
        DEROutputStream out)
        throws IOException
    {
        if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
        {
            out.write(SEQUENCE | CONSTRUCTED);
            out.write(0x80);

            Enumeration e = getObjects();
            while (e.hasMoreElements())
            {
                out.writeObject(e.nextElement());
            }

            out.write(0x00);
            out.write(0x00);
        }
        else
        {
            super.encode(out);
        }
    }
}


text: Open Container Initiative Testing Daemon