text:
package com.gdn.venice.server.app.fraud.presenter.commands;

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

import com.djarum.raf.utilities.Locator;
import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.facade.VenBinCreditLimitEstimateSessionEJBRemote;
import com.gdn.venice.facade.VenContactDetailSessionEJBRemote;
import com.gdn.venice.facade.VenOrderItemSessionEJBRemote;
import com.gdn.venice.facade.VenOrderPaymentAllocationSessionEJBRemote;
import com.gdn.venice.facade.VenOrderSessionEJBRemote;
import com.gdn.venice.persistence.VenBinCreditLimitEstimate;
import com.gdn.venice.persistence.VenContactDetail;
import com.gdn.venice.persistence.VenOrder;
import com.gdn.venice.persistence.VenOrderContactDetail;
import com.gdn.venice.persistence.VenOrderItem;
import com.gdn.venice.persistence.VenOrderPaymentAllocation;
import com.gdn.venice.server.command.RafDsCommand;
import com.gdn.venice.server.data.RafDsRequest;
import com.gdn.venice.server.data.RafDsResponse;
import com.gdn.venice.server.util.Util;
import com.gdn.venice.util.VeniceConstants;

/**
 * Fetch same Order
 *
 * @author Arifin
 */

public class FetchSameOrderHistory implements RafDsCommand {

	RafDsRequest request;

	public FetchSameOrderHistory(RafDsRequest request){
		this.request=request;
	}
	@Override
	public RafDsResponse execute() {
		RafDsResponse rafDsResponse = new RafDsResponse();
		List<HashMap<String, String>> dataList= new ArrayList<HashMap<String, String>>();
		Locator<Object> locator=null;

		try{
			locator = new Locator<Object>();
			VenOrderSessionEJBRemote ordersessionHome = (VenOrderSessionEJBRemote) locator.lookup(VenOrderSessionEJBRemote.class, "VenOrderSessionEJBBean");
			VenOrderItemSessionEJBRemote orderitemsessionHome = (VenOrderItemSessionEJBRemote) locator.lookup(VenOrderItemSessionEJBRemote.class, "VenOrderItemSessionEJBBean");
			VenOrderPaymentAllocationSessionEJBRemote allocationsessionHome = (VenOrderPaymentAllocationSessionEJBRemote) locator.lookup(VenOrderPaymentAllocationSessionEJBRemote.class, "VenOrderPaymentAllocationSessionEJBBean");
			VenContactDetailSessionEJBRemote cpsessionHome = (VenContactDetailSessionEJBRemote) locator.lookup(VenContactDetailSessionEJBRemote.class, "VenContactDetailSessionEJBBean");
			VenBinCreditLimitEstimateSessionEJBRemote binSessionHome = (VenBinCreditLimitEstimateSessionEJBRemote) locator.lookup(VenBinCreditLimitEstimateSessionEJBRemote.class, "VenBinCreditLimitEstimateSessionEJBBean");

			/*
			 * 1. cari order yang nama customernya sama
			 * 2. cari order yang no telp sama
			 * 3. cari order yang no Hp sama
			 * 4. cari order yang email sama
			 * 5. cari order yang customer address sama
			 * 6. cari order yang shipping address sama
			 * 7. cari order yang billing address sama
			 * 8. cari order yang no CC sama
			 */
			List<VenOrder> itemList = null;
			List<VenOrder> count=null;
			String query="";
			if(request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)!=""){
				if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CUSTOMER_FULLNAME_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
							query = "select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and UPPER(o.venCustomer.venParty.fullOrLegalName) like '"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+"' and o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"'";
							itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
							count = ordersessionHome.queryByRange(query,0, 0);
					}
				} if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CUSTOMER_PHONE_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and ( o.venCustomer.venParty.partyId in (select u.venParty.partyId from VenContactDetail u where u.contactDetail in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+") and u.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_PHONE+") "+
						"or o.orderId in (select r.venOrder.orderId from VenOrderContactDetail r where r.venContactDetail.contactDetail in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+") and r.venContactDetail.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_PHONE+") )";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
							count = ordersessionHome.queryByRange(query,0, 0);
					}
				} else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CUSTOMER_MOBILE_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and ( o.venCustomer.venParty.partyId in (select u.venParty.partyId from VenContactDetail u where u.contactDetail in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+") and u.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_MOBILE+") "+
						"or o.orderId in (select r.venOrder.orderId from VenOrderContactDetail r where r.venContactDetail.contactDetail in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+") and r.venContactDetail.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_MOBILE+") )";
							itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
							count = ordersessionHome.queryByRange(query,0, 0);
					}
				}else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CUSTOMER_EMAIL_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and ( o.venCustomer.venParty.partyId in (select u.venParty.partyId from VenContactDetail u where UPPER(u.contactDetail) in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+") and u.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_EMAIL+") "+
						"or o.orderId in (select r.venOrder.orderId from VenOrderContactDetail r where UPPER(r.venContactDetail.contactDetail) in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+") and r.venContactDetail.venContactDetailType.contactDetailTypeId="+VeniceConstants.VEN_CONTACT_TYPE_EMAIL+")) ";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
							count = ordersessionHome.queryByRange(query,0, 0);
					}
				}if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CUSTOMER_ADDRESS_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and ( o.venCustomer.venParty.partyId in (select u.venParty.partyId from VenPartyAddress u where UPPER(u.venAddress.streetAddress1) in ('"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+"')) or "+
						"o.orderId in (select u.venOrder.orderId from VenOrderAddress u where UPPER(u.venAddress.streetAddress1) in ('"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+"')) )";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
						count = ordersessionHome.queryByRange(query,0, 0);
					}
				} else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_SHIPPING_ADDRESS_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query = "select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and o.orderId in (select u.venOrder.orderId from VenOrderItem u where UPPER(u.venAddress.streetAddress1) like '"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+"' group by  u.venOrder.orderId)";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
						count = ordersessionHome.queryByRange(query,0, 0);
					}
				}else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_BILLING_ADDRESS_FILTER)){
					query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and o.orderId in (select u.venOrder.orderId from VenOrderPaymentAllocation u where UPPER(u.venOrderPayment.venAddress.streetAddress1) like '"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).toUpperCase()+"')";
					itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
					count = ordersessionHome.queryByRange(query,0, 0);
				}else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_IP_ADDRESS_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and o.ipAddress like '"+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+"'";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
						count = ordersessionHome.queryByRange(query,0, 0);
					}
				}	else if(request.getParams().get(DataNameTokens.VENORDER_ORDERID).equals(VeniceConstants.FRD_ORDER_HISTORY_CC_NUMBER_FILTER)){
					if(!request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER).equals("")){
						query="select o from VenOrder o left join fetch o.venOrderContactDetails where o.wcsOrderId <> '"+request.getParams().get(DataNameTokens.VENORDER_WCSORDERID)+"' and  o.orderId in (select u.venOrder.orderId from VenOrderPaymentAllocation u where u.venOrderPayment.maskedCreditCardNumber in ("+request.getParams().get(DataNameTokens.ORDERHISTORY_STRINGFILTER)+"))";
						itemList = ordersessionHome.queryByRange(query,request.getStartRow(), request.getEndRow()-request.getStartRow());
						count = ordersessionHome.queryByRange(query,0, 0);
					}
				}
			}
			int startRow=new Integer(request.getStartRow());

			if(itemList!=null && !itemList.isEmpty()){
				for(int i=0; i<itemList.size();i++){
					startRow=startRow+1;
					HashMap<String, String> map = new HashMap<String, String>();
					VenOrder list = itemList.get(i);

					List<VenOrderItem> orItems=null;
					List<VenOrderPaymentAllocation> allocations=null;
					List<VenContactDetail> cpList=null;
					map.put(DataNameTokens.VENORDER_ORDERID, Util.isNull(list.getOrderId(), "").toString());
					map.put(DataNameTokens.VENORDER_WCSORDERID, Util.isNull(list.getWcsOrderId(), "").toString());
					map.put(DataNameTokens.VENORDER_VENORDERSTATUS_ORDERSTATUSCODE, Util.isNull(list.getVenOrderStatus().getOrderStatusCode(), "").toString());
					map.put(DataNameTokens.VENORDER_ORDERDATE, Util.isNull(list.getOrderDate(), "").toString());
					map.put(DataNameTokens.VENORDER_AMOUNT, Util.isNull(list.getAmount(), "").toString());
					map.put(DataNameTokens.VENORDER_IPADDRESS, Util.isNull(list.getIpAddress(), "").toString());

					 String phone="",mobile="",email="",customer="";
			    	 if(list.getVenOrderContactDetails()!=null && list.getVenOrderContactDetails().size()>0){
			    		 if(list.getVenCustomer().getVenParty()!=null){
			    			 customer=list.getVenCustomer().getVenParty().getFullOrLegalName();
			    		 }
			    		 for(VenOrderContactDetail itemVenCont : list.getVenOrderContactDetails()){
			    			 if(itemVenCont.getVenContactDetail().getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_MOBILE && mobile.equals("")){
									mobile=itemVenCont.getVenContactDetail().getContactDetail();
								}else if(itemVenCont.getVenContactDetail().getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_PHONE && phone.equals("")){
									phone=itemVenCont.getVenContactDetail().getContactDetail();
								}else if(itemVenCont.getVenContactDetail().getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_EMAIL && email.equals("")){
									email=itemVenCont.getVenContactDetail().getContactDetail();
								}
			    		 }
	    			 }else	if(list.getVenCustomer()!=null){
						if(list.getVenCustomer().getVenParty()!=null){
							 customer=list.getVenCustomer().getVenParty().getFullOrLegalName();
							/*
							 * get informasi contact detail untuk order tersebut
							 */
							cpList=cpsessionHome.queryByRange("select o from VenContactDetail o where o.venParty.partyId="+list.getVenCustomer().getVenParty().getPartyId(), 0, 0);
							if(cpList!=null && !cpList.isEmpty()){
								for(VenContactDetail itemCp:cpList){
									if(itemCp.getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_MOBILE && mobile.equals("")){
										mobile=itemCp.getContactDetail();
									}else if(itemCp.getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_PHONE && phone.equals("")){
										phone=itemCp.getContactDetail();
									}else if(itemCp.getVenContactDetailType().getContactDetailTypeId()==VeniceConstants.VEN_CONTACT_TYPE_EMAIL && email.equals("")){
										email=itemCp.getContactDetail();
									}
								}
							}
						}
					}
			    	 	map.put(DataNameTokens.VENPARTY_FULLORLEGALNAME, Util.isNull(customer, "").toString());
			    	 	map.put(DataNameTokens.ORDERHISTORY_PHONE_NUMBER, Util.isNull(phone, "").toString());
						map.put(DataNameTokens.ORDERHISTORY_MOBILE_NUMBER, Util.isNull(mobile, "").toString());
						map.put(DataNameTokens.ORDERHISTORY_EMAIL, Util.isNull(email, "").toString());
					/*
					 * get data untuk informasi order item
					 */
					orItems=orderitemsessionHome.queryByRange("select o from VenOrderItem o where o.venOrder.orderId="+list.getOrderId(), 0, 0);
					if(!orItems.isEmpty() && orItems!=null){
							map.put(DataNameTokens.ORDERHISTORY_PRODUCT_NAME,Util.isNull(orItems.get(0).getVenMerchantProduct().getWcsProductName(), "").toString());
							map.put(DataNameTokens.ORDERHISTORY_QTY, Util.isNull(orItems.size(), "").toString());
							map.put(DataNameTokens.ORDERHISTORY_SHPIPPING_ADDRESS, Util.isNull(orItems.get(0).getVenAddress().getStreetAddress1(), "").toString());
					}else{
						map.put(DataNameTokens.ORDERHISTORY_QTY, "");
						map.put(DataNameTokens.ORDERHISTORY_SHPIPPING_ADDRESS,"");
						map.put(DataNameTokens.ORDERHISTORY_PRODUCT_NAME,"");
					}
					/*
					 * get data untuk infomasi payment
					 */
					allocations=allocationsessionHome.queryByRange("select o from VenOrderPaymentAllocation o where o.venOrder.orderId="+list.getOrderId(), 0, 0);
					if(!allocations.isEmpty() && allocations!=null){
						map.put(DataNameTokens.ORDERHISTORY_BILLING_METHOD, Util.isNull(allocations.get(0).getVenOrderPayment().getVenWcsPaymentType().getWcsPaymentTypeDesc(), "").toString());
						map.put(DataNameTokens.ORDERHISTORY_STATUS, Util.isNull(allocations.get(0).getVenOrderPayment().getVenPaymentStatus().getPaymentStatusCode(), "").toString());
						map.put(DataNameTokens.ORDERHISTORY_CC, Util.isNull(allocations.get(0).getVenOrderPayment().getMaskedCreditCardNumber(), "").toString());

						String creditCardNumber = "";
						String binNumber="", bankName="";
						creditCardNumber = allocations.get(0).getVenOrderPayment().getMaskedCreditCardNumber()!=null?allocations.get(0).getVenOrderPayment().getMaskedCreditCardNumber():"";
						if(!creditCardNumber.equals("")){
							//check CC limit from BIN number
							if(creditCardNumber.length()>6){
								binNumber = creditCardNumber.substring(0, 6);
							}
						}
						List<VenBinCreditLimitEstimate> binCreditLimitList = binSessionHome.queryByRange("select o from VenBinCreditLimitEstimate o where o.isActive=true and o.binNumber like '"+binNumber+"'", 0, 1);
						if(binCreditLimitList.size()>0){
							bankName=binCreditLimitList.get(0).getBankName();
						}

						map.put(DataNameTokens.ORDERHISTORY_ISSUER, Util.isNull(bankName, "").toString());
						map.put(DataNameTokens.ORDERHISTORY_ECI, Util.isNull(allocations.get(0).getVenOrderPayment().getThreeDsSecurityLevelAuth(), "").toString());
					}else{
						map.put(DataNameTokens.ORDERHISTORY_BILLING_METHOD, "");
						map.put(DataNameTokens.ORDERHISTORY_STATUS, "");
						map.put(DataNameTokens.ORDERHISTORY_CC, "");
						map.put(DataNameTokens.ORDERHISTORY_ISSUER, "");
						map.put(DataNameTokens.ORDERHISTORY_ECI, "");
					}
					dataList.add(map);
				}
				if(count.size()<=(request.getStartRow()+itemList.size())){
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(DataNameTokens.VENORDER_ORDERID, "");
					map.put(DataNameTokens.VENORDER_WCSORDERID, "END");
					map.put(DataNameTokens.VENORDER_ORDERDATE, "");
					map.put(DataNameTokens.VENORDER_AMOUNT, "");
					map.put(DataNameTokens.VENORDER_IPADDRESS, "");
					map.put(DataNameTokens.VENPARTY_FULLORLEGALNAME, "");
					map.put(DataNameTokens.ORDERHISTORY_PHONE_NUMBER, "");
					map.put(DataNameTokens.ORDERHISTORY_MOBILE_NUMBER, "");
					map.put(DataNameTokens.ORDERHISTORY_EMAIL, "");
					map.put(DataNameTokens.ORDERHISTORY_QTY, "");
					map.put(DataNameTokens.ORDERHISTORY_SHPIPPING_ADDRESS,"");
					map.put(DataNameTokens.ORDERHISTORY_PRODUCT_NAME,"");
					map.put(DataNameTokens.ORDERHISTORY_BILLING_METHOD, "");
					map.put(DataNameTokens.ORDERHISTORY_STATUS, "");
					map.put(DataNameTokens.ORDERHISTORY_CC, "");
					map.put(DataNameTokens.ORDERHISTORY_ISSUER, "");
					map.put(DataNameTokens.ORDERHISTORY_ECI, "");
					dataList.add(map);
				}
			}

			rafDsResponse.setStatus(0);
			rafDsResponse.setStartRow(request.getStartRow());
			rafDsResponse.setTotalRows(dataList.size());
			rafDsResponse.setEndRow(request.getStartRow()+dataList.size());
		}catch(Exception e){
			e.printStackTrace();
			rafDsResponse.setStatus(-1);
		}finally{
			try{
				if(locator!=null){
					locator.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		rafDsResponse.setData(dataList);
		return rafDsResponse;
	}
}


text:
package com.nick.love.myra;

import java.util.Base64;

public class TestBase64 {

	public static void main(String[] args) {
        Base64.Encoder encoder = Base64.getEncoder();
        String encoderResult = encoder.encodeToString("Myra is my girl.".getBytes());
        System.out.println(encoderResult);

        Base64.Decoder decoder = Base64.getDecoder();
        System.out.println(new String(decoder.decode(encoderResult)));
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jmeter.protocol.http.control.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ItemEvent;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

import org.apache.jmeter.gui.GUIMenuSortOrder;
import org.apache.jmeter.gui.util.HorizontalPanel;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.protocol.http.config.gui.UrlConfigGui;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerFactory;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.JLabeledTextField;

/**
 * HTTP Sampler GUI
 */
@GUIMenuSortOrder(1)
public class HttpTestSampleGui extends AbstractSamplerGui {

    private static final long serialVersionUID = 241L;

    private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font");
    private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8));

    private UrlConfigGui urlConfigGui;
    private JCheckBox retrieveEmbeddedResources;
    private JCheckBox concurrentDwn;
    private JTextField concurrentPool;
    private JCheckBox useMD5;
    private JLabeledTextField embeddedRE; // regular expression used to match against embedded resource URLs
    private JTextField sourceIpAddr; // does not apply to Java implementation
    private JComboBox<String> sourceIpType = new JComboBox<>(HTTPSamplerBase.getSourceTypeList());
    private JTextField proxyScheme;
    private JTextField proxyHost;
    private JTextField proxyPort;
    private JTextField proxyUser;
    private JPasswordField proxyPass;
    private JComboBox<String> httpImplementation = new JComboBox<>(HTTPSamplerFactory.getImplementations());
    private JTextField connectTimeOut;
    private JTextField responseTimeOut;

    private final boolean isAJP;

    public HttpTestSampleGui() {
        isAJP = false;
        init();
    }

    // For use by AJP
    protected HttpTestSampleGui(boolean ajp) {
        isAJP = ajp;
        init();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void configure(TestElement element) {
        super.configure(element);
        final HTTPSamplerBase samplerBase = (HTTPSamplerBase) element;
        urlConfigGui.configure(element);
        retrieveEmbeddedResources.setSelected(samplerBase.isImageParser());
        concurrentDwn.setSelected(samplerBase.isConcurrentDwn());
        concurrentPool.setText(samplerBase.getConcurrentPool());
        useMD5.setSelected(samplerBase.useMD5());
        embeddedRE.setText(samplerBase.getEmbeddedUrlRE());
        if (!isAJP) {
            sourceIpAddr.setText(samplerBase.getIpSource());
            sourceIpType.setSelectedIndex(samplerBase.getIpSourceType());
            proxyScheme.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.PROXYSCHEME));
            proxyHost.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.PROXYHOST));
            proxyPort.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.PROXYPORT));
            proxyUser.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.PROXYUSER));
            proxyPass.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.PROXYPASS));
            httpImplementation.setSelectedItem(samplerBase.getPropertyAsString(HTTPSamplerBase.IMPLEMENTATION));
            connectTimeOut.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.CONNECT_TIMEOUT));
            responseTimeOut.setText(samplerBase.getPropertyAsString(HTTPSamplerBase.RESPONSE_TIMEOUT));
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public TestElement createTestElement() {
        HTTPSamplerBase sampler = new HTTPSamplerProxy();
        modifyTestElement(sampler);
        return sampler;
    }

    /**
     * Modifies a given TestElement to mirror the data in the gui components.
     * <p>
     * {@inheritDoc}
     */
    @Override
    public void modifyTestElement(TestElement sampler) {
        sampler.clear();
        urlConfigGui.modifyTestElement(sampler);
        final HTTPSamplerBase samplerBase = (HTTPSamplerBase) sampler;
        samplerBase.setImageParser(retrieveEmbeddedResources.isSelected());
        enableConcurrentDwn(retrieveEmbeddedResources.isSelected());
        samplerBase.setConcurrentDwn(concurrentDwn.isSelected());
        samplerBase.setConcurrentPool(concurrentPool.getText());
        samplerBase.setMD5(useMD5.isSelected());
        samplerBase.setEmbeddedUrlRE(embeddedRE.getText());
        if (!isAJP) {
            samplerBase.setIpSource(sourceIpAddr.getText());
            samplerBase.setIpSourceType(sourceIpType.getSelectedIndex());
            samplerBase.setProperty(HTTPSamplerBase.PROXYSCHEME, proxyScheme.getText(),"");
            samplerBase.setProperty(HTTPSamplerBase.PROXYHOST, proxyHost.getText(),"");
            samplerBase.setProperty(HTTPSamplerBase.PROXYPORT, proxyPort.getText(),"");
            samplerBase.setProperty(HTTPSamplerBase.PROXYUSER, proxyUser.getText(),"");
            samplerBase.setProperty(HTTPSamplerBase.PROXYPASS, String.valueOf(proxyPass.getPassword()),"");
            samplerBase.setProperty(HTTPSamplerBase.IMPLEMENTATION, httpImplementation.getSelectedItem().toString(),"");
            samplerBase.setProperty(HTTPSamplerBase.CONNECT_TIMEOUT, connectTimeOut.getText());
            samplerBase.setProperty(HTTPSamplerBase.RESPONSE_TIMEOUT, responseTimeOut.getText());
        }
        super.configureTestElement(sampler);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getLabelResource() {
        return "web_testing_title"; // $NON-NLS-1$
    }

    private void init() {// called from ctor, so must not be overridable
        setLayout(new BorderLayout(0, 5));
        setBorder(makeBorder());

        // URL CONFIG
        urlConfigGui = new UrlConfigGui(true, true, true);

        // HTTP request options
        JPanel httpOptions = new HorizontalPanel();
        httpOptions.add(getImplementationPanel());
        httpOptions.add(getTimeOutPanel());
        // AdvancedPanel (embedded resources, source address and optional tasks)
        JPanel advancedPanel = new VerticalPanel();
        if (!isAJP) {
            advancedPanel.add(httpOptions);
        }
        advancedPanel.add(createEmbeddedRsrcPanel());
        if (!isAJP) {
            advancedPanel.add(createSourceAddrPanel());
            advancedPanel.add(getProxyServerPanel());
        }

        advancedPanel.add(createOptionalTasksPanel());

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.add(JMeterUtils
                .getResString("web_testing_basic"), urlConfigGui);
        tabbedPane.add(JMeterUtils
                .getResString("web_testing_advanced"), advancedPanel);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, makeTitlePanel(), tabbedPane);
        splitPane.setOneTouchExpandable(true);
        add(splitPane);
    }

    private JPanel getTimeOutPanel() {
        JPanel timeOut = new HorizontalPanel();
        timeOut.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                JMeterUtils.getResString("web_server_timeout_title"))); // $NON-NLS-1$
        final JPanel connPanel = getConnectTimeOutPanel();
        final JPanel reqPanel = getResponseTimeOutPanel();
        timeOut.add(connPanel);
        timeOut.add(reqPanel);
        return timeOut;
    }

    private JPanel getConnectTimeOutPanel() {
        connectTimeOut = new JTextField(10);

        JLabel label = new JLabel(JMeterUtils.getResString("web_server_timeout_connect")); // $NON-NLS-1$
        label.setLabelFor(connectTimeOut);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(connectTimeOut, BorderLayout.CENTER);

        return panel;
    }

    private JPanel getResponseTimeOutPanel() {
        responseTimeOut = new JTextField(10);

        JLabel label = new JLabel(JMeterUtils.getResString("web_server_timeout_response")); // $NON-NLS-1$
        label.setLabelFor(responseTimeOut);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(responseTimeOut, BorderLayout.CENTER);

        return panel;
    }

    protected JPanel createEmbeddedRsrcPanel() {
        // retrieve Embedded resources
        retrieveEmbeddedResources = new JCheckBox(JMeterUtils.getResString("web_testing_retrieve_images")); // $NON-NLS-1$
        // add a listener to activate or not concurrent dwn.
        retrieveEmbeddedResources.addItemListener(e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) { enableConcurrentDwn(true); }
            else { enableConcurrentDwn(false); }
        });
        // Download concurrent resources
        concurrentDwn = new JCheckBox(JMeterUtils.getResString("web_testing_concurrent_download")); // $NON-NLS-1$
        concurrentDwn.addItemListener(e -> {
            if (retrieveEmbeddedResources.isSelected() && e.getStateChange() == ItemEvent.SELECTED) { concurrentPool.setEnabled(true); }
            else { concurrentPool.setEnabled(false); }
        });
        concurrentPool = new JTextField(2); // 2 column size
        concurrentPool.setMinimumSize(new Dimension(10, (int) concurrentPool.getPreferredSize().getHeight()));
        concurrentPool.setMaximumSize(new Dimension(30, (int) concurrentPool.getPreferredSize().getHeight()));

        final JPanel embeddedRsrcPanel = new HorizontalPanel();
        embeddedRsrcPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), JMeterUtils
                .getResString("web_testing_retrieve_title"))); // $NON-NLS-1$
        embeddedRsrcPanel.add(retrieveEmbeddedResources);
        embeddedRsrcPanel.add(concurrentDwn);
        embeddedRsrcPanel.add(concurrentPool);

        // Embedded URL match regex
        embeddedRE = new JLabeledTextField(JMeterUtils.getResString("web_testing_embedded_url_pattern"),20); // $NON-NLS-1$
        embeddedRsrcPanel.add(embeddedRE);

        return embeddedRsrcPanel;
    }

    /**
     * Create a panel containing the implementation details
     *
     * @return the panel
     */
    protected final JPanel getImplementationPanel(){
        JPanel implPanel = new HorizontalPanel();
        implPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                JMeterUtils.getResString("web_server_client"))); // $NON-NLS-1$
        implPanel.add(new JLabel(JMeterUtils.getResString("http_implementation"))); // $NON-NLS-1$
        httpImplementation.addItem("");// $NON-NLS-1$
        implPanel.add(httpImplementation);
        return implPanel;
    }

    protected JPanel createOptionalTasksPanel() {
        // OPTIONAL TASKS
        final JPanel checkBoxPanel = new VerticalPanel();
        checkBoxPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), JMeterUtils
                .getResString("optional_tasks"))); // $NON-NLS-1$

        // Use MD5
        useMD5 = new JCheckBox(JMeterUtils.getResString("response_save_as_md5")); // $NON-NLS-1$
        checkBoxPanel.add(useMD5);

        return checkBoxPanel;
    }

    protected JPanel createSourceAddrPanel() {
        final JPanel sourceAddrPanel = new HorizontalPanel();
        sourceAddrPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), JMeterUtils
                .getResString("web_testing_source_ip"))); // $NON-NLS-1$

        // Add a new field source ip address (for HC implementations only)
        sourceIpType.setSelectedIndex(HTTPSamplerBase.SourceType.HOSTNAME.ordinal()); //default: IP/Hostname
        sourceAddrPanel.add(sourceIpType);

        sourceIpAddr = new JTextField();
        sourceAddrPanel.add(sourceIpAddr);
        return sourceAddrPanel;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension getPreferredSize() {
        return getMinimumSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clearGui() {
        super.clearGui();
        retrieveEmbeddedResources.setSelected(false);
        concurrentDwn.setSelected(false);
        concurrentPool.setText(String.valueOf(HTTPSamplerBase.CONCURRENT_POOL_SIZE));
        enableConcurrentDwn(false);
        useMD5.setSelected(false);
        urlConfigGui.clear();
        embeddedRE.setText(""); // $NON-NLS-1$
        if (!isAJP) {
            sourceIpAddr.setText(""); // $NON-NLS-1$
            sourceIpType.setSelectedIndex(HTTPSamplerBase.SourceType.HOSTNAME.ordinal()); //default: IP/Hostname
            proxyScheme.setText(""); // $NON-NLS-1$
            proxyHost.setText(""); // $NON-NLS-1$
            proxyPort.setText(""); // $NON-NLS-1$
            proxyUser.setText(""); // $NON-NLS-1$
            proxyPass.setText(""); // $NON-NLS-1$
            httpImplementation.setSelectedItem(""); // $NON-NLS-1$
            connectTimeOut.setText(""); // $NON-NLS-1$
            responseTimeOut.setText(""); // $NON-NLS-1$
        }
    }

    private void enableConcurrentDwn(boolean enable) {
        if (enable) {
            concurrentDwn.setEnabled(true);
            embeddedRE.setEnabled(true);
            if (concurrentDwn.isSelected()) {
                concurrentPool.setEnabled(true);
            }
        } else {
            concurrentDwn.setEnabled(false);
            concurrentPool.setEnabled(false);
            embeddedRE.setEnabled(false);
        }
    }

    /**
     * Create a panel containing the proxy server details
     *
     * @return the panel
     */
    protected final JPanel getProxyServerPanel(){
        JPanel proxyServer = new HorizontalPanel();
        proxyServer.add(getProxySchemePanel(), BorderLayout.WEST);
        proxyServer.add(getProxyHostPanel(), BorderLayout.CENTER);
        proxyServer.add(getProxyPortPanel(), BorderLayout.EAST);

        JPanel proxyLogin = new HorizontalPanel();
        proxyLogin.add(getProxyUserPanel());
        proxyLogin.add(getProxyPassPanel());

        JPanel proxyServerPanel = new HorizontalPanel();
        proxyServerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                JMeterUtils.getResString("web_proxy_server_title"))); // $NON-NLS-1$
        proxyServerPanel.add(proxyServer);
        proxyServerPanel.add(proxyLogin);

        return proxyServerPanel;
    }

    private JPanel getProxySchemePanel() {
        proxyScheme = new JTextField(5);

        JLabel label = new JLabel(JMeterUtils.getResString("web_proxy_scheme")); // $NON-NLS-1$
        label.setLabelFor(proxyScheme);
        label.setFont(FONT_SMALL);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(proxyScheme, BorderLayout.CENTER);
        return panel;
    }

    private JPanel getProxyHostPanel() {
        proxyHost = new JTextField(10);

        JLabel label = new JLabel(JMeterUtils.getResString("web_server_domain")); // $NON-NLS-1$
        label.setLabelFor(proxyHost);
        label.setFont(FONT_SMALL);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(proxyHost, BorderLayout.CENTER);
        return panel;
    }

    private JPanel getProxyPortPanel() {
        proxyPort = new JTextField(10);

        JLabel label = new JLabel(JMeterUtils.getResString("web_server_port")); // $NON-NLS-1$
        label.setLabelFor(proxyPort);
        label.setFont(FONT_SMALL);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(proxyPort, BorderLayout.CENTER);

        return panel;
    }

    private JPanel getProxyUserPanel() {
        proxyUser = new JTextField(5);

        JLabel label = new JLabel(JMeterUtils.getResString("username")); // $NON-NLS-1$
        label.setLabelFor(proxyUser);
        label.setFont(FONT_SMALL);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(proxyUser, BorderLayout.CENTER);
        return panel;
    }

    private JPanel getProxyPassPanel() {
        proxyPass = new JPasswordField(5);

        JLabel label = new JLabel(JMeterUtils.getResString("password")); // $NON-NLS-1$
        label.setLabelFor(proxyPass);
        label.setFont(FONT_SMALL);

        JPanel panel = new JPanel(new BorderLayout(5, 0));
        panel.add(label, BorderLayout.WEST);
        panel.add(proxyPass, BorderLayout.CENTER);
        return panel;
    }
}


text:
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Umbraco.Core;

namespace Umbraco.Web.WebApi.Filters
{
    /// <summary>
    /// Sets the json outgoing/serialized datetime format
    /// </summary>
    internal sealed class OutgoingDateTimeFormatAttribute :  Attribute, IControllerConfiguration
    {
        private readonly string _format = "yyyy-MM-dd HH:mm:ss";

        /// <summary>
        /// Specify a custom format
        /// </summary>
        /// <param name="format"></param>
        public OutgoingDateTimeFormatAttribute(string format)
        {
            Mandate.ParameterNotNullOrEmpty(format, "format");
            _format = format;
        }

        /// <summary>
        /// Will use the standard ISO format
        /// </summary>
        public OutgoingDateTimeFormatAttribute(){

        }

        public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
        {
            var jsonFormatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>();
            foreach (var r in jsonFormatter)
            {
                r.SerializerSettings.Converters.Add(new CustomDateTimeConvertor(_format));
            }
        }

    }
}


text:
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}

{-# OPTIONS_GHC -Wno-missing-signatures #-}

module Nix.Cited where

import           Control.Comonad
import           Control.Comonad.Env
import           Data.Typeable                  ( Typeable )
import           GHC.Generics
import           Lens.Family2.TH

import           Nix.Expr.Types.Annotated
import           Nix.Scope

data Provenance m v = Provenance
    { _lexicalScope :: Scopes m v
    , _originExpr   :: NExprLocF (Maybe v)
      -- ^ When calling the function x: x + 2 with argument x = 3, the
      --   'originExpr' for the resulting value will be 3 + 2, while the
      --   'contextExpr' will be @(x: x + 2) 3@, preserving not only the
      --   result of the call, but what was called and with what arguments.
    }
    deriving (Generic, Typeable, Show)

data NCited m v a = NCited
    { _provenance :: [Provenance m v]
    , _cited      :: a
    }
    deriving (Generic, Typeable, Functor, Foldable, Traversable, Show)

instance Applicative (NCited m v) where
  pure = NCited []
  NCited xs f <*> NCited ys x = NCited (xs <> ys) (f x)

instance Comonad (NCited m v) where
  duplicate p = NCited (_provenance p) p
  extract = _cited

instance ComonadEnv [Provenance m v] (NCited m v) where
  ask = _provenance

$(makeLenses ''Provenance)
$(makeLenses ''NCited)

class HasCitations m v a where
    citations :: a -> [Provenance m v]
    addProvenance :: Provenance m v -> a -> a

instance HasCitations m v (NCited m v a) where
  citations = _provenance
  addProvenance x (NCited p v) = (NCited (x : p) v)

class HasCitations1 m v f where
    citations1 :: f a -> [Provenance m v]
    addProvenance1 :: Provenance m v -> f a -> f a


text:
package org.bson.codecs;

import org.bson.BsonReader;
import org.bson.BsonRegularExpression;
import org.bson.BsonWriter;

/**
 * A codec for BSON regular expressions.
 *
 * @since 3.0
 */
public class BsonRegularExpressionCodec implements Codec<BsonRegularExpression> {
    @Override
    public BsonRegularExpression decode(final BsonReader reader, final DecoderContext decoderContext) {
        return reader.readRegularExpression();
    }

    @Override
    public void encode(final BsonWriter writer, final BsonRegularExpression value, final EncoderContext encoderContext) {
        writer.writeRegularExpression(value);
    }

    @Override
    public Class<BsonRegularExpression> getEncoderClass() {
        return BsonRegularExpression.class;
    }
}


text:
<?php

namespace Skim\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Follower
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Skim\MainBundle\Entity\FollowerRepository")
 */
class Follower
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="type", type="integer")
     */
    private $type;

    /**
     * @var integer
     *
     * @ORM\Column(name="round", type="integer")
     */
    private $round;

    /**
     * @var integer
     *
     * @ORM\Column(name="not_interests", type="integer")
     */
    private $not_interests;

    /**
     * @ORM\ManyToOne(targetEntity="Skim\MainBundle\Entity\User", inversedBy="following")
     * @ORM\JoinColumn(name="follower_id", referencedColumnName="id")
     */
    protected $follower;

    /**
     * @ORM\ManyToOne(targetEntity="Skim\MainBundle\Entity\User", inversedBy="followers")
     * @ORM\JoinColumn(name="following_id", referencedColumnName="id")
     */
    protected $following;

    public function __construct()
    {
        $this->not_interests = 0;
    }

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

    /**
     * Set type
     *
     * @param integer $type
     * @return Follower
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

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

    /**
     * Set round
     *
     * @param integer $round
     * @return Follower
     */
    public function setRound($round)
    {
        $this->round = $round;

        return $this;
    }

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

    /**
     * Set follower
     *
     * @param \Skim\MainBundle\Entity\User $follower
     * @return Follower
     */
    public function setFollower(\Skim\MainBundle\Entity\User $follower = null)
    {
        $this->follower = $follower;

        return $this;
    }

    /**
     * Get follower
     *
     * @return \Skim\MainBundle\Entity\User
     */
    public function getFollower()
    {
        return $this->follower;
    }

    /**
     * Set following
     *
     * @param \Skim\MainBundle\Entity\User $following
     * @return Follower
     */
    public function setFollowing(\Skim\MainBundle\Entity\User $following = null)
    {
        $this->following = $following;

        return $this;
    }

    /**
     * Get following
     *
     * @return \Skim\MainBundle\Entity\User
     */
    public function getFollowing()
    {
        return $this->following;
    }

    /**
     * Set not_interests
     *
     * @param integer $notInterests
     * @return Follower
     */
    public function setNotInterests($notInterests)
    {
        $this->not_interests = $notInterests;

        return $this;
    }

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


text:
Sparkle Graph
---
Sparkle Graph **sg.js** is a d3.js based javascript library for displaying
interactive charts of potentially large data sets.
Charts are customizable with declarative javascript, and extensible with d3.
sg.js currently offers support for line charts, scatter plots, bar charts, etc.
and is easily extensible to support more chart types.

Notable in Sparkle Graph:

* All charts support a drag-based zooming UI.

* Sparkle Graph supports the sparkle-data-server api,
enabling zooming charts of potentially huge server hosted data sets,
the option of offloading data transformations to the server,
and (soon) server pushed updates to locally displayed charts.

Dashboard
---
The repo includes an Angular.js / Material Design dashboard built around Sparkle Graph.

The dashboard includes:

* An autocomplete based chooser for selecting data series from the server.
* A widget for uploading .csv/.tsv files via drag and drop.
* A control panel for changing graph types, summary parameters, time series and non time series, etc.


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class NoCompatibleHardAffinityHost extends VmConfigFault
{
  public String vmName;

  public String getVmName()
  {
    return this.vmName;
  }

  public void setVmName(String vmName)
  {
    this.vmName=vmName;
  }
}


text:
<template name="serverInformationForm">
    {{#form class='server-information-form' schema=instance.currentSchema api=this.api}}
        {{>inputHidden key='_id'}}

                {{>inputText labelClass='form-group' key='name'}}

                {{>inputSelect labelClass='form-group' key='type'
                    hideSearch=true disabled=(eq this.mode.get 'edit')
                    options=(clone placeholder='Choose a server type')}}

        {{#if eq this.serverType.get 'dicomWeb'}}
          {{>serverInformationDicomWeb this}}
        {{/if}}
        {{#if eq this.serverType.get 'dimse'}}
          {{>serverInformationDimse this}}
        {{/if}}
        {{#if this.serverType.get}}

                {{#button class='btn-primary' action='save'}}Save{{/button}}

        {{/if}}
    {{/form}}
</template>


text:
def mexFunction(s, upperBound):
    found = -1
    for i in range(upperBound):
        if not i in s:
            found = i
            break
    else:
        return upperBound

    return found


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Using require.js - Editor.md examples</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="../lib/codemirror/codemirror.min.css" />

        <link rel="stylesheet" href="../css/editormd.min.css" />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />

Using require.js

Enable HTML tags decode

Enable TeX, Flowchart, Sequence Diagram, Emoji, FontAwesome, Task lists

Enable Image upload

Enable [TOCM], Search Replace, Code fold

                <button id="show-btn">Show editor</button>
                <button id="hide-btn">Hide editor</button>
                <button id="get-md-btn">Get Markdown</button>
                <button id="get-html-btn">Get HTML</button>
                <button id="watch-btn">Watch</button>
                <button id="unwatch-btn">Unwatch</button>
                <button id="preview-btn">Preview HTML (Press Shift + ESC cancel)</button>
                <button id="fullscreen-btn">Fullscreen (Press ESC cancel)</button>
                <button id="show-toolbar-btn">Show toolbar</button>
                <button id="close-toolbar-btn">Hide toolbar</button>
                <button id="toc-menu-btn">ToC Dropdown menu</button>
                <button id="toc-default-btn">ToC default</button>


text:
<?php

/**
 * Add to GridSheetModelAdmins which will be dealing with GridSheet enabled models. Can't use ModelAdmin itself because
 * the $modelClass is a protected member variable which we expose via GridSheetModelAdmin.getModelClass().
 */
class GridSheetModelAdminExtension extends ModularDataExtension {

    /**
     * @param array $data
     * @param Form $form
     * @param SS_HTTPRequest|null $request
     * @return SS_HTTPResponse|void
     */
    public function saveGridSheet(array $data, Form $form, SS_HTTPRequest $request = null) {
        $this->save($data, $form, false, $request);
    }

    /**
     * @param array $data
     * @param Form $form
     * @param SS_HTTPRequest|null $request
     * @return SS_HTTPResponse|void
     */
    public function saveAndPublishGridSheet(array $data, Form $form, SS_HTTPRequest $request = null) {
        $this->save($data, $form, true, $request);
    }

    protected function save(array $data, Form $form, $publish = false, SS_HTTPRequest $request = null) {
        $modelClass = $this->getModelClass();

        if (isset($data[$modelClass])) {
            if ($gridField = $form->Fields()->fieldByName($modelClass)) {
                if ($gridField instanceof GridField) {

                    GridSheetModule::save_new_rows($gridField, $publish);

                    GridSheetModule::save_existing_rows($gridField, $publish);
                }
            }
        }
        if (isset($data['BackURL'])) {
            $this->owner->redirect($data['BackURL']);
        }
    }

    protected function getModelClass() {
        if (!$this->owner instanceof GridSheetModelAdmin) {
            throw new Exception("GridSheetModelAdminExtension should only extend GridSheetModelAdmin derived classes");
        }
        return $this->owner->getModelClass();
    }

}


text:
<?php

namespace Survingo\LuckyBlockWars;

use pocketmine\event\block\{BlockBreakEvent, SignChangeEvent};
use pocketmine\event\Listener;
use pocketmine\event\player\{PlayerDeathEvent, PlayerInteractEvent, PlayerQuitEvent};
use Survingo\LuckyBlockWars\game\{LuckyBlocks, UnluckyBlocks};

class EventManager implements Listener{
  /** @var LuckyBlockWars */
  private $plugin;

  public function __construct(LuckyBlockWars $plugin){
    $this->plugin = $plugin;
  }

  /**
   * @param BlockBreakEvent $event
   *
   */
  public function onBlockBreak(BlockBreakEvent $event){
     if($event->getBlock()->getId() == $this->plugin->getConfig("luckyblock-id")){
        if($this->plugin->running == true){
           if($event->getPlayer()->hasPermission("lbw.game.use")){
              switch(mt_rand(1,2)){
                 case 1: (new LuckyBlocks($this->plugin, $event->getBlock(), $event->getPlayer()))->run();
                 break;
                 case 2: (new UnluckyBlocks($this->plugin, $event->getBlock(), $event->getPlayer()))->run();
                 break;
              }
           }else{
              $event->setCancelled(true);
              $this->plugin->sendMessage($event->getPlayer(), "not-allowed-to-use-luckyblock");
           }
        }else{
           $this->plugin->sendMessage($event->getPlayer(), "game-is-not-running");
        }
     }
  }

  /**
   * @param SignChangeEvent $event
   *
   */
  public function onSignChange(SignChangeEvent $event){
    if($event->getLine(0) == "[LBW]" or $event->getLine(0) == "[LuckyBlock]" or $event->getLine(0) == "/lbw join"){
       if($event->getPlayer()->hasPermission("lbw.game.create-signs")){
          $this->plugin->getConfig()->set("sign-x", $event->getBlock()->getX());
          $this->plugin->getConfig()->save();
          $this->plugin->getConfig()->set("sign-y", $event->getBlock()->getY());
          $this->plugin->getConfig()->save();
          $this->plugin->getConfig()->set("sign-z", $event->getBlock()->getZ());
          $this->plugin->getConfig()->save();
          $this->plugin->getConfig()->set("sign-world", $event->getPlayer()->getLevel()->getName());
          $this->plugin->getConfig()->save();
          $this->plugin->getConfig()->set("sign-mode", true);
          $this->plugin->getConfig()->save;
          $event->setLine(0, "§l[§6L§eB§cW§f]");
          $event->setLine(1, "§aJoin");
       }else{
          $event->setLine(0, "No");
          $event->setLine(1, "Permission");
       }
    }
 }

 /**
   * @param PlayerDeathEvent $event
   *
   */
 public function onDeath(PlayerDeathEvent $event){
    if($this->plugin->running == true){
       if(in_array($event->getEntity()->getName(), $this->plugin->players)){
          unset($this->plugin->players{array_search($event->getEntity()->getName(), $this->plugin->players)});
          $event->setDeathMessage($this->plugin->prefix . str_replace("{name}", $event->getEntity()->getName(), $this->plugin->msg["death-message"]));
          $event->getEntity()->teleport($this->plugin->getServer()->getLevelByName($this->plugin->getConfig()->get("respawn-level"))->getSafeSpawn());
       }
       if(count($this->plugin->players == 1)){
          $this->plugin->getServer()->getPlayer($this->plugin->players)->teleport($this->plugin->getServer()->getLevelByName($this->plugin->cfg["respawn-level"])->getSafeSpawn());
          $this->plugin->getServer()->broadcastMessage($this->plugin->prefix . str_replace(["{name}", "{health}"], [$this->plugin->players, $this->plugin->getServer()->getPlayer($this->plugin->players)->getHealth()], $this->plugin->msg["won-broadcast"]));
          $this->plugin->getServer()->getPlayer($this->plugin->players)->setHealth(20);
          $this->plugin->players = array();
          $this->plugin->running = false;
       }
    }
 }

 /**
   * @param BlockInteractEvent $event
   *
   */
 public function onInteract(PlayerInteractEvent $event){
    if($event->getBlock()->getX() === $this->plugin->cfg["sign-x"] and $event->getBlock()->getY() === $this->plugin->cfg["sign-y"] and $event->getBlock()->getZ() === $this->plugin->cfg["sign-z"]){
       if($this->plugin->running == false){
          $this->addToGame($event->getPlayer()->getName());
       }else{
          $this->plugin->sendMessage($event->getPlayer(), "game-is-running");
       }
    }
 }

 /**
   * @param BlockQuitEvent $event
   *
   */
 public function onQuit(PlayerQuitEvent $event){
    if($this->plugin->running == true){
       if(in_array($event->getPlayer()->getName(), $this->plugin->players)){
          unset($this->plugin->players{array_search($event->getPlayer()->getName(), $this->plugin->players)});
          $event->setQuitMessage($this->plugin->prefix . str_replace("{name}", $event->getPlayer()->getName(), $this->plugin->msg["quit-message"]));
       }
       if(count($this->plugin->players) == 1){
          $this->plugin->getServer()->getPlayer($this->plugin->players)->teleport($this->plugin->getServer()->getLevelByName($this->plugin->cfg["respawn-level"])->getSafeSpawn());
          $this->plugin->getServer()->broadcastMessage(str_replace(["{name}", "{health}"], [$this->plugin->players, $this->plugin->getServer()->getPlayer($this->plugin->players)->getHealth()], $this->plugin->cfg["won-broadcast"]));
          $this->plugin->getServer()->getPlayer($this->plugin->players)->setHealth(20);
          $this->plugin->players = array();
          $this->plugin->running = false;
       }
    }
 }

}


text:
require 'spec_helper'
require 'ruby_event_store/rom/sql'
require 'ruby_event_store/spec/rom/relations/stream_entries_lint'

module RubyEventStore
  module ROM
  module SQL
  RSpec.describe Relations::StreamEntries do
    let(:rom_helper) { SpecHelper.new }

    it_behaves_like :stream_entries_relation, Relations::StreamEntries
  end
  end
  end
end


text:
<?php
/* Prototype  : proto int xml_set_character_data_handler(resource parser, string hdl)
 * Description: Set up character data handler
 * Source code: ext/xml/xml.c
 * Alias to functions:
 */

echo "*** Testing xml_set_character_data_handler() : error conditions ***\n";

//Test xml_set_character_data_handler with one more than the expected number of arguments
echo "\n-- Testing xml_set_character_data_handler() function with more than expected no. of arguments --\n";

$hdl = 'string_val';
$extra_arg = 10;
var_dump( xml_set_character_data_handler(null, $hdl, $extra_arg) );

// Testing xml_set_character_data_handler with one less than the expected number of arguments
echo "\n-- Testing xml_set_character_data_handler() function with less than expected no. of arguments --\n";

var_dump( xml_set_character_data_handler(null) );

echo "Done";
?>


text:
namespace oakvr
{
	class OakVRObjectUnit
	{
	public:
		ObjectSharedPointer CreateObject(const StringId &name);
		auto AddObjectToGraph(ObjectSharedPointer pObject, const StringId &parentId = StringId("root")) -> void;
		auto RemoveObjectFromGraph(const StringId &name) -> void;
		auto FindObject(const StringId &objectId) -> ObjectSharedPointer;
		auto TransferObject(const StringId &id, const StringId &newParentId) -> void;

		auto GetAllObjects() -> ObjectVector &;
		auto GetAllObjects() const -> const ObjectVector &;

		OakVRObjectUnit();
		~OakVRObjectUnit();
	protected:
		class OakVRObjectUnitImpl;
		up<OakVRObjectUnitImpl> m_pImpl;
	};
}


text:
extern "C" {
#include "third_party/pqclean/crypto_sign/dilithium2/api.h"
#include "third_party/pqclean/crypto_sign/dilithium2aes/api.h"
#include "third_party/pqclean/crypto_sign/dilithium3/api.h"
#include "third_party/pqclean/crypto_sign/dilithium3aes/api.h"
#include "third_party/pqclean/crypto_sign/dilithium5/api.h"
#include "third_party/pqclean/crypto_sign/dilithium5aes/api.h"
}

namespace crypto {
namespace tink {
namespace subtle {
namespace {

struct DilithiumTestCase {
  std::string test_name;
  int32_t key_size;
  int32_t signature_length;
  DilithiumSeedExpansion seed_expansion;
};

using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
using crypto::tink::util::Status;

using DilithiumAvx2SignTest = testing::TestWithParam<DilithiumTestCase>;

TEST(DilithiumAvx2SignTest, InvalidPrivateKeys) {
  if (IsFipsModeEnabled()) {
    GTEST_SKIP() << "Test assumes kOnlyUseFips is false.";
  }

  for (int keysize = 0;
       keysize <= PQCLEAN_DILITHIUM5_CRYPTO_SECRETKEYBYTES; keysize++) {
    if (keysize == PQCLEAN_DILITHIUM2_CRYPTO_SECRETKEYBYTES ||
        keysize == PQCLEAN_DILITHIUM3_CRYPTO_SECRETKEYBYTES ||
        keysize == PQCLEAN_DILITHIUM5_CRYPTO_SECRETKEYBYTES) {
      // Valid key size.
      continue;
    }

    util::SecretData key_data(keysize, 'x');
    EXPECT_FALSE(
        DilithiumAvx2Sign::New(
            *DilithiumPrivateKeyPqclean::NewPrivateKey(
                key_data, DilithiumSeedExpansion::SEED_EXPANSION_SHAKE))
            .ok());
  }
}

TEST_P(DilithiumAvx2SignTest, SignatureLength) {
  if (IsFipsModeEnabled()) {
    GTEST_SKIP() << "Test assumes kOnlyUseFips is false.";
  }

  const DilithiumTestCase& test_case = GetParam();

  // Generate key pair.
  util::StatusOr<
      std::pair<DilithiumPrivateKeyPqclean, DilithiumPublicKeyPqclean>>
      key_pair = DilithiumPrivateKeyPqclean::GenerateKeyPair(
          test_case.key_size, test_case.seed_expansion);

  ASSERT_THAT(key_pair, IsOk());

  // Create a new signer.
  util::StatusOr<std::unique_ptr<PublicKeySign>> signer =
      DilithiumAvx2Sign::New(key_pair->first);
  ASSERT_THAT(signer, IsOk());

  // Sign a message.
  std::string message = "message to be signed";
  util::StatusOr<std::string> signature = (*std::move(signer))->Sign(message);
  ASSERT_THAT(signature, IsOk());

  // Check signature size.
  EXPECT_NE(*signature, message);
  EXPECT_EQ((*signature).size(), test_case.signature_length);
}

TEST_P(DilithiumAvx2SignTest, Determinism) {
  if (IsFipsModeEnabled()) {
    GTEST_SKIP() << "Test assumes kOnlyUseFips is false.";
  }

  const DilithiumTestCase& test_case = GetParam();

  // Generate key pair.
  util::StatusOr<
      std::pair<DilithiumPrivateKeyPqclean, DilithiumPublicKeyPqclean>>
      key_pair = DilithiumPrivateKeyPqclean::GenerateKeyPair(
          test_case.key_size, test_case.seed_expansion);

  ASSERT_THAT(key_pair, IsOk());

  // Create two signers based on same private key.
  util::StatusOr<std::unique_ptr<PublicKeySign>> first_signer =
      DilithiumAvx2Sign::New(key_pair->first);
  ASSERT_THAT(first_signer, IsOk());

  util::StatusOr<std::unique_ptr<PublicKeySign>> second_signer =
      DilithiumAvx2Sign::New(key_pair->first);
  ASSERT_THAT(second_signer, IsOk());

  // Sign the same message twice, using the same private key.
  std::string message = "message to be signed";
  util::StatusOr<std::string> first_signature =
      (*std::move(first_signer))->Sign(message);
  ASSERT_THAT(first_signature, IsOk());

  util::StatusOr<std::string> second_signature =
      (*std::move(second_signer))->Sign(message);
  ASSERT_THAT(second_signature, IsOk());

  // Check signatures size.
  EXPECT_NE(*first_signature, message);
  EXPECT_EQ((*first_signature).size(), test_case.signature_length);

  EXPECT_NE(*second_signature, message);
  EXPECT_EQ((*second_signature).size(), test_case.signature_length);

  // Check if signatures are equal.
  EXPECT_EQ(*first_signature, *second_signature);
}

TEST_P(DilithiumAvx2SignTest, FipsMode) {
  if (!IsFipsModeEnabled()) {
    GTEST_SKIP() << "Test assumes kOnlyUseFips.";
  }

  const DilithiumTestCase& test_case = GetParam();

  // Generate key pair.
  util::StatusOr<
      std::pair<DilithiumPrivateKeyPqclean, DilithiumPublicKeyPqclean>>
      key_pair = DilithiumPrivateKeyPqclean::GenerateKeyPair(
          test_case.key_size, test_case.seed_expansion);

  ASSERT_THAT(key_pair, IsOk());

  // Create a new signer.
  EXPECT_THAT(DilithiumAvx2Sign::New(key_pair->first).status(),
              StatusIs(absl::StatusCode::kInternal));
}

INSTANTIATE_TEST_SUITE_P(
    DilithiumAvx2SignTests, DilithiumAvx2SignTest,
    testing::ValuesIn<DilithiumTestCase>({
        {"Dilithium2", PQCLEAN_DILITHIUM2_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM2_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_SHAKE},
        {"Dilithium3", PQCLEAN_DILITHIUM3_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM3_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_SHAKE},
        {"Dilithium5", PQCLEAN_DILITHIUM5_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM5_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_SHAKE},
        {"Dilithium2Aes", PQCLEAN_DILITHIUM2AES_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM2AES_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_AES},
        {"Dilithium3Aes", PQCLEAN_DILITHIUM3AES_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM3_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_AES},
        {"Dilithium5Aes", PQCLEAN_DILITHIUM5AES_CRYPTO_SECRETKEYBYTES,
         PQCLEAN_DILITHIUM5AES_CRYPTO_BYTES,
         DilithiumSeedExpansion::SEED_EXPANSION_AES},
    }),
    [](const testing::TestParamInfo<DilithiumAvx2SignTest::ParamType>& info) {
      return info.param.test_name;
    });

}  // namespace
}  // namespace subtle
}  // namespace tink
}  // namespace crypto


text:
<?php
declare(strict_types=1);

namespace WoohooLabs\Zen\Examples\Utils;

class UserUtil
{
    public function __construct()
    {
    }
}


text:
@class FEMObjectStore, FEMMapping, NSManagedObject, NSFetchRequest, NSManagedObjectContext;
@class FEMDeserializer;

@protocol FEMDeserializerDelegate <NSObject>

@optional
- (void)deserializer:(nonnull FEMDeserializer *)deserializer willMapObjectFromRepresentation:(nonnull id)representation mapping:(nonnull FEMMapping *)mapping;
- (void)deserializer:(nonnull FEMDeserializer *)deserializer didMapObject:(nonnull id)object fromRepresentation:(nonnull id)representation mapping:(nonnull FEMMapping *)mapping;

- (void)deserializer:(nonnull FEMDeserializer *)deserializer willMapCollectionFromRepresentation:(nonnull NSArray *)representation mapping:(nonnull FEMMapping *)mapping;
- (void)deserializer:(nonnull FEMDeserializer *)deserializer didMapCollection:(nonnull NSArray *)collection fromRepresentation:(nonnull NSArray *)representation mapping:(nonnull FEMMapping *)mapping;

@end

@interface FEMDeserializer : NSObject

@property (nonatomic, strong, readonly, nonnull) FEMObjectStore *store;
- (nonnull instancetype)initWithStore:(nonnull FEMObjectStore *)store NS_DESIGNATED_INITIALIZER;

- (nonnull instancetype)init;
- (nonnull instancetype)initWithContext:(nonnull NSManagedObjectContext *)context;

@property (nonatomic, unsafe_unretained, nullable) id<FEMDeserializerDelegate> delegate;

- (nonnull id)objectFromRepresentation:(nonnull NSDictionary *)representation mapping:(nonnull FEMMapping *)mapping;
- (nonnull id)fillObject:(nonnull id)object fromRepresentation:(nonnull NSDictionary *)representation mapping:(nonnull FEMMapping *)mapping;
- (nonnull NSArray *)collectionFromRepresentation:(nonnull NSArray *)representation mapping:(nonnull FEMMapping *)mapping;

@end

@interface FEMDeserializer (Extension)

+ (nonnull id)objectFromRepresentation:(nonnull NSDictionary *)representation mapping:(nonnull FEMMapping *)mapping context:(nonnull NSManagedObjectContext *)context;
+ (nonnull id)objectFromRepresentation:(nonnull NSDictionary *)representation mapping:(nonnull FEMMapping *)mapping;

+ (nonnull id)fillObject:(nonnull id)object fromRepresentation:(nonnull NSDictionary *)representation mapping:(nonnull FEMMapping *)mapping;

+ (nonnull NSArray *)collectionFromRepresentation:(nonnull NSArray *)representation mapping:(nonnull FEMMapping *)mapping context:(nonnull NSManagedObjectContext *)context;
+ (nonnull NSArray *)collectionFromRepresentation:(nonnull NSArray *)representation mapping:(nonnull FEMMapping *)mapping;

@end

@interface FEMDeserializer (FEMObjectDeserializer_Deprecated)

+ (nonnull id)deserializeObjectExternalRepresentation:(nonnull NSDictionary *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping __attribute__((deprecated("Use +[FEMDeserializer objectFromRepresentation:mapping:] instead")));
+ (nonnull id)fillObject:(nonnull id)object fromExternalRepresentation:(nonnull NSDictionary *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping __attribute__((deprecated("Use +[FEMDeserializer fillObject:fromRepresentation:mapping:] instead")));
+ (nonnull NSArray *)deserializeCollectionExternalRepresentation:(nonnull NSArray *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping __attribute__((deprecated("Use +[FEMDeserializer collectionFromRepresentation:mapping:] instead")));

@end

@interface FEMDeserializer (FEMManagedObjectDeserializer_Deprecated)

+ (nonnull id)deserializeObjectExternalRepresentation:(nonnull NSDictionary *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping context:(nonnull NSManagedObjectContext *)context __attribute__((deprecated("Use +[FEMDeserializer objectFromRepresentation:mapping:context:] instead")));
+ (nonnull NSArray *)deserializeCollectionExternalRepresentation:(nonnull NSArray *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping context:(nonnull NSManagedObjectContext *)context __attribute__((deprecated("Use +[FEMDeserializer collectionFromRepresentation:mapping:context:] instead")));
+ (nonnull NSArray *)synchronizeCollectionExternalRepresentation:(nonnull NSArray *)externalRepresentation usingMapping:(nonnull FEMMapping *)mapping predicate:(nonnull NSPredicate *)predicate context:(nonnull NSManagedObjectContext *)context __attribute__((unavailable));

@end


text:
namespace precache {

namespace {

// A map of histogram names to the total sample counts.
typedef std::map<std::string, base::HistogramBase::Count> HistogramCountMap;

const char kConfigURL[] = "http://config-url.com";
const char kManifestURLPrefix[] = "http://manifest-url-prefix.com/";

base::HistogramBase::Count GetHistogramTotalCount(const char* histogram_name) {
  base::HistogramBase* histogram =
      base::StatisticsRecorder::FindHistogram(histogram_name);
  return histogram ? histogram->SnapshotSamples()->TotalCount() : 0;
}

HistogramCountMap GetHistogramCountMap() {
  // Note that the PrecacheManager tests don't care about the ".Cellular"
  // histograms.
  const char* kHistogramNames[] = {"Precache.DownloadedPrecacheMotivated",
                                   "Precache.DownloadedNonPrecache",
                                   "Precache.Saved"};

  HistogramCountMap histogram_count_map;
  for (size_t i = 0; i < arraysize(kHistogramNames); ++i) {
    histogram_count_map[kHistogramNames[i]] =
        GetHistogramTotalCount(kHistogramNames[i]);
  }
  return histogram_count_map;
}

class TestURLFetcherCallback {
 public:
  scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
      const GURL& url, net::URLFetcherDelegate* delegate,
      const std::string& response_data, net::HttpStatusCode response_code,
      net::URLRequestStatus::Status status) {
    scoped_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher(
        url, delegate, response_data, response_code, status));

    requested_urls_.insert(url);
    return fetcher.Pass();
  }

  const std::multiset<GURL>& requested_urls() const {
    return requested_urls_;
  }

 private:
  // Multiset with one entry for each URL requested.
  std::multiset<GURL> requested_urls_;
};

class FakeURLListProvider : public URLListProvider {
 public:
  FakeURLListProvider(const std::list<GURL>& urls, bool run_immediately)
      : urls_(urls),
        run_immediately_(run_immediately),
        was_get_urls_called_(false) {}

  void GetURLs(const GetURLsCallback& callback) override {
    was_get_urls_called_ = true;

    if (run_immediately_) {
      callback.Run(urls_);
    } else {
      // Post the callback to be run later in the message loop.
      base::MessageLoop::current()->PostTask(FROM_HERE,
                                             base::Bind(callback, urls_));
    }
  }

  bool was_get_urls_called() const {
    return was_get_urls_called_;
  }

 private:
  const std::list<GURL> urls_;
  const bool run_immediately_;
  bool was_get_urls_called_;
};

class TestPrecacheCompletionCallback {
 public:
  TestPrecacheCompletionCallback() : was_on_done_called_(false) {}

  void OnDone() {
    was_on_done_called_ = true;
  }

  PrecacheManager::PrecacheCompletionCallback GetCallback() {
    return base::Bind(&TestPrecacheCompletionCallback::OnDone,
                      base::Unretained(this));
  }

  bool was_on_done_called() const {
    return was_on_done_called_;
  }

 private:
  bool was_on_done_called_;
};

class PrecacheManagerTest : public testing::Test {
 public:
  PrecacheManagerTest()
      : precache_manager_(&browser_context_),
        factory_(NULL, base::Bind(&TestURLFetcherCallback::CreateURLFetcher,
                                  base::Unretained(&url_callback_))) {}

 protected:
  void SetUp() override {
    base::StatisticsRecorder::Initialize();

    base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kPrecacheConfigSettingsURL, kConfigURL);
    base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kPrecacheManifestURLPrefix, kManifestURLPrefix);

    // Make the fetch of the precache configuration settings fail. Precaching
    // should still complete normally in this case.
    factory_.SetFakeResponse(GURL(kConfigURL), "",
                             net::HTTP_INTERNAL_SERVER_ERROR,
                             net::URLRequestStatus::FAILED);
  }

  content::TestBrowserThreadBundle test_browser_thread_bundle_;
  content::TestBrowserContext browser_context_;
  PrecacheManager precache_manager_;
  TestURLFetcherCallback url_callback_;
  net::FakeURLFetcherFactory factory_;
  TestPrecacheCompletionCallback precache_callback_;
};

TEST_F(PrecacheManagerTest, StartAndFinishPrecaching) {
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  FakeURLListProvider url_list_provider(
      std::list<GURL>(1, GURL("http://starting-url.com")), false);
  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);

  EXPECT_TRUE(precache_manager_.IsPrecaching());

  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_FALSE(precache_manager_.IsPrecaching());
  EXPECT_TRUE(url_list_provider.was_get_urls_called());
  EXPECT_TRUE(precache_callback_.was_on_done_called());

  std::multiset<GURL> expected_requested_urls;
  expected_requested_urls.insert(GURL(kConfigURL));
  EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls());
}

TEST_F(PrecacheManagerTest, StartAndCancelPrecachingBeforeURLsReceived) {
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  FakeURLListProvider url_list_provider(
      std::list<GURL>(1, GURL("http://starting-url.com")), false);

  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);
  EXPECT_TRUE(precache_manager_.IsPrecaching());

  precache_manager_.CancelPrecaching();
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_FALSE(precache_manager_.IsPrecaching());
  EXPECT_TRUE(url_list_provider.was_get_urls_called());
  EXPECT_FALSE(precache_callback_.was_on_done_called());
  EXPECT_TRUE(url_callback_.requested_urls().empty());
}

TEST_F(PrecacheManagerTest, StartAndCancelPrecachingAfterURLsReceived) {
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  FakeURLListProvider url_list_provider(
      std::list<GURL>(1, GURL("http://starting-url.com")), true);

  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);

  // Since the |url_list_provider| ran the callback immediately, Start() has
  // been called on the PrecacheFetcher, and the precache config settings have
  // been requested. The response has not yet been received though, so
  // precaching is still in progress.
  EXPECT_TRUE(precache_manager_.IsPrecaching());

  precache_manager_.CancelPrecaching();
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_FALSE(precache_manager_.IsPrecaching());
  EXPECT_TRUE(url_list_provider.was_get_urls_called());
  EXPECT_FALSE(precache_callback_.was_on_done_called());

  // Even though the response for the precache config settings should not have
  // been received, the request should still have been made.
  std::multiset<GURL> expected_requested_urls;
  expected_requested_urls.insert(GURL(kConfigURL));
  EXPECT_EQ(expected_requested_urls, url_callback_.requested_urls());
}

TEST_F(PrecacheManagerTest, RecordStatsForFetchWithIrrelevantFetches) {
  HistogramCountMap expected_histogram_count_map = GetHistogramCountMap();

  // Fetches with size 0 should be ignored.
  precache_manager_.RecordStatsForFetch(GURL("http://url.com"), base::Time(), 0,
                                        false);
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());

  // Fetches for URLs with schemes other than HTTP or HTTPS should be ignored.
  precache_manager_.RecordStatsForFetch(GURL("ftp://ftp.com"), base::Time(),
                                        1000, false);
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());

  // Fetches for empty URLs should be ignored.
  precache_manager_.RecordStatsForFetch(GURL(), base::Time(), 1000, false);
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());
}

TEST_F(PrecacheManagerTest, RecordStatsForFetchDuringPrecaching) {
  HistogramCountMap expected_histogram_count_map = GetHistogramCountMap();

  FakeURLListProvider url_list_provider(std::list<GURL>(), false);
  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);

  EXPECT_TRUE(precache_manager_.IsPrecaching());
  precache_manager_.RecordStatsForFetch(GURL("http://url.com"), base::Time(),
                                        1000, false);

  precache_manager_.CancelPrecaching();

  base::MessageLoop::current()->RunUntilIdle();
  expected_histogram_count_map["Precache.DownloadedPrecacheMotivated"]++;
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());
}

TEST_F(PrecacheManagerTest, RecordStatsForFetchHTTP) {
  HistogramCountMap expected_histogram_count_map = GetHistogramCountMap();

  precache_manager_.RecordStatsForFetch(GURL("http://http-url.com"),
                                        base::Time(), 1000, false);
  base::MessageLoop::current()->RunUntilIdle();

  expected_histogram_count_map["Precache.DownloadedNonPrecache"]++;
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());
}

TEST_F(PrecacheManagerTest, RecordStatsForFetchHTTPS) {
  HistogramCountMap expected_histogram_count_map = GetHistogramCountMap();

  precache_manager_.RecordStatsForFetch(GURL("https://https-url.com"),
                                        base::Time(), 1000, false);
  base::MessageLoop::current()->RunUntilIdle();

  expected_histogram_count_map["Precache.DownloadedNonPrecache"]++;
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());
}

TEST_F(PrecacheManagerTest, DeleteExpiredPrecacheHistory) {
  // This test has to use Time::Now() because StartPrecaching uses Time::Now().
  const base::Time kCurrentTime = base::Time::Now();
  HistogramCountMap expected_histogram_count_map = GetHistogramCountMap();

  FakeURLListProvider url_list_provider(std::list<GURL>(), false);
  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);
  EXPECT_TRUE(precache_manager_.IsPrecaching());

  // Precache a bunch of URLs, with different fetch times.
  precache_manager_.RecordStatsForFetch(
      GURL("http://old-fetch.com"),
      kCurrentTime - base::TimeDelta::FromDays(61), 1000, false);
  precache_manager_.RecordStatsForFetch(
      GURL("http://recent-fetch.com"),
      kCurrentTime - base::TimeDelta::FromDays(59), 1000, false);
  precache_manager_.RecordStatsForFetch(
      GURL("http://yesterday-fetch.com"),
      kCurrentTime - base::TimeDelta::FromDays(1), 1000, false);
  expected_histogram_count_map["Precache.DownloadedPrecacheMotivated"] += 3;

  precache_manager_.CancelPrecaching();
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());

  // The expired precache will be deleted during precaching this time.
  precache_manager_.StartPrecaching(precache_callback_.GetCallback(),
                                    &url_list_provider);
  EXPECT_TRUE(precache_manager_.IsPrecaching());

  precache_manager_.CancelPrecaching();
  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_FALSE(precache_manager_.IsPrecaching());

  // A fetch for the same URL as the expired precache was served from the cache,
  // but it isn't reported as saved bytes because it had expired in the precache
  // history.
  precache_manager_.RecordStatsForFetch(
      GURL("http://old-fetch.com"),
      kCurrentTime, 1000, true);

  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());

  // The other precaches should not have expired, so the following fetches from
  // the cache should count as saved bytes.
  precache_manager_.RecordStatsForFetch(
      GURL("http://recent-fetch.com"),
      kCurrentTime, 1000, true);
  precache_manager_.RecordStatsForFetch(
      GURL("http://yesterday-fetch.com"),
      kCurrentTime, 1000, true);
  expected_histogram_count_map["Precache.Saved"] += 2;

  base::MessageLoop::current()->RunUntilIdle();
  EXPECT_EQ(expected_histogram_count_map, GetHistogramCountMap());
}

}  // namespace

}  // namespace precache


text:
package Paws::SDB;
  use Moose;
  sub service { 'sdb' }
  sub version { '2009-04-15' }
  sub flattened_arrays { 1 }
  has max_attempts => (is => 'ro', isa => 'Int', default => 5);
  has retry => (is => 'ro', isa => 'HashRef', default => sub {
    { base => 'rand', type => 'exponential', growth_factor => 2 }
  });
  has retriables => (is => 'ro', isa => 'ArrayRef', default => sub { [
  ] });

  with 'Paws::API::Caller', 'Paws::API::EndpointResolver', 'Paws::Net::V2Signature', 'Paws::Net::QueryCaller', 'Paws::Net::XMLResponse';

  has '+region_rules' => (default => sub {
    my $regioninfo;
      $regioninfo = [
    {
      constraints => [
        [
          'region',
          'equals',
          'us-east-1'
        ]
      ],
      uri => 'https://sdb.amazonaws.com'
    }
  ];

    return $regioninfo;
  });

  sub BatchDeleteAttributes {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::BatchDeleteAttributes', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub BatchPutAttributes {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::BatchPutAttributes', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub CreateDomain {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::CreateDomain', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub DeleteAttributes {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::DeleteAttributes', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub DeleteDomain {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::DeleteDomain', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub DomainMetadata {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::DomainMetadata', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub GetAttributes {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::GetAttributes', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub ListDomains {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::ListDomains', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub PutAttributes {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::PutAttributes', @_);
    return $self->caller->do_call($self, $call_object);
  }
  sub Select {
    my $self = shift;
    my $call_object = $self->new_with_coercions('Paws::SDB::Select', @_);
    return $self->caller->do_call($self, $call_object);
  }

  sub ListAllDomains {
    my $self = shift;

    my $callback = shift @_ if (ref($_[0]) eq 'CODE');
    my $result = $self->ListDomains(@_);
    my $next_result = $result;

    if (not defined $callback) {
      while ($next_result->NextToken) {
        $next_result = $self->ListDomains(@_, NextToken => $next_result->NextToken);
        push @{ $result->DomainNames }, @{ $next_result->DomainNames };
      }
      return $result;
    } else {
      while ($result->NextToken) {
        $callback->($_ => 'DomainNames') foreach (@{ $result->DomainNames });
        $result = $self->ListDomains(@_, NextToken => $result->NextToken);
      }
      $callback->($_ => 'DomainNames') foreach (@{ $result->DomainNames });
    }

    return undef
  }
  sub SelectAll {
    my $self = shift;

    my $callback = shift @_ if (ref($_[0]) eq 'CODE');
    my $result = $self->Select(@_);
    my $next_result = $result;

    if (not defined $callback) {
      while ($next_result->NextToken) {
        $next_result = $self->Select(@_, NextToken => $next_result->NextToken);
        push @{ $result->Items }, @{ $next_result->Items };
      }
      return $result;
    } else {
      while ($result->NextToken) {
        $callback->($_ => 'Items') foreach (@{ $result->Items });
        $result = $self->Select(@_, NextToken => $result->NextToken);
      }
      $callback->($_ => 'Items') foreach (@{ $result->Items });
    }

    return undef
  }

  sub operations { qw/BatchDeleteAttributes BatchPutAttributes CreateDomain DeleteAttributes DeleteDomain DomainMetadata GetAttributes ListDomains PutAttributes Select / }

1;

### main pod documentation begin ###

=head1 NAME

Paws::SDB - Perl Interface to AWS Amazon SimpleDB

=head1 SYNOPSIS

  use Paws;

  my $obj = Paws->service('SDB');
  my $res = $obj->Method(
    Arg1 => $val1,
    Arg2 => [ 'V1', 'V2' ],
    # if Arg3 is an object, the HashRef will be used as arguments to the constructor
    # of the arguments type
    Arg3 => { Att1 => 'Val1' },
    # if Arg4 is an array of objects, the HashRefs will be passed as arguments to
    # the constructor of the arguments type
    Arg4 => [ { Att1 => 'Val1'  }, { Att1 => 'Val2' } ],
  );

=head1 DESCRIPTION

Amazon SimpleDB is a web service providing the core database functions
of data indexing and querying in the cloud. By offloading the time and
effort associated with building and operating a web-scale database,
SimpleDB provides developers the freedom to focus on application
development.

A traditional, clustered relational database requires a sizable upfront
capital outlay, is complex to design, and often requires extensive and
repetitive database administration. Amazon SimpleDB is dramatically
simpler, requiring no schema, automatically indexing your data and
providing a simple API for storage and access. This approach eliminates
the administrative burden of data modeling, index maintenance, and
performance tuning. Developers gain access to this functionality within
Amazon's proven computing environment, are able to scale instantly, and
pay only for what they use.

Visit http://aws.amazon.com/simpledb/ for more information.

=head1 METHODS

=head2 BatchDeleteAttributes(DomainName => Str, Items => ArrayRef[L<Paws::SDB::DeletableItem>])

Each argument is described in detail in: L<Paws::SDB::BatchDeleteAttributes>

Returns: nothing

  Performs multiple DeleteAttributes operations in a single call, which
reduces round trips and latencies. This enables Amazon SimpleDB to
optimize requests, which generally yields better throughput.

The following limitations are enforced for this operation:

=over

=item * 1 MB request size

=item * 25 item limit per BatchDeleteAttributes operation

=back

=head2 BatchPutAttributes(DomainName => Str, Items => ArrayRef[L<Paws::SDB::ReplaceableItem>])

Each argument is described in detail in: L<Paws::SDB::BatchPutAttributes>

Returns: nothing

  The C<BatchPutAttributes> operation creates or replaces attributes
within one or more items. By using this operation, the client can
perform multiple PutAttribute operation with a single call. This helps
yield savings in round trips and latencies, enabling Amazon SimpleDB to
optimize requests and generally produce better throughput.

The client may specify the item name with the C<Item.X.ItemName>
parameter. The client may specify new attributes using a combination of
the C<Item.X.Attribute.Y.Name> and C<Item.X.Attribute.Y.Value>
parameters. The client may specify the first attribute for the first
item using the parameters C<Item.0.Attribute.0.Name> and
C<Item.0.Attribute.0.Value>, and for the second attribute for the first
item by the parameters C<Item.0.Attribute.1.Name> and
C<Item.0.Attribute.1.Value>, and so on.

Attributes are uniquely identified within an item by their name/value
combination. For example, a single item can have the attributes C<{
"first_name", "first_value" }> and C<{ "first_name", "second_value" }>.
However, it cannot have two attribute instances where both the
C<Item.X.Attribute.Y.Name> and C<Item.X.Attribute.Y.Value> are the
same.

Optionally, the requester can supply the C<Replace> parameter for each
individual value. Setting this value to C<true> will cause the new
attribute values to replace the existing attribute values. For example,
if an item C<I> has the attributes C<{ 'a', '1' }, { 'b', '2'}> and C<{
'b', '3' }> and the requester does a BatchPutAttributes of C<{'I', 'b',
'4' }> with the Replace parameter set to true, the final attributes of
the item will be C<{ 'a', '1' }> and C<{ 'b', '4' }>, replacing the
previous values of the 'b' attribute with the new value.

This operation is vulnerable to exceeding the maximum URL size when
making a REST request using the HTTP GET method. This operation does
not support conditions using C<Expected.X.Name>, C<Expected.X.Value>,
or C<Expected.X.Exists>.

You can execute multiple C<BatchPutAttributes> operations and other
operations in parallel. However, large numbers of concurrent
C<BatchPutAttributes> calls can result in Service Unavailable (503)
responses.

The following limitations are enforced for this operation:

=over

=item * 256 attribute name-value pairs per item

=item * 1 MB request size

=item * 1 billion attributes per domain

=item * 10 GB of total user data storage per domain

=item * 25 item limit per C<BatchPutAttributes> operation

=back

=head2 CreateDomain(DomainName => Str)

Each argument is described in detail in: L<Paws::SDB::CreateDomain>

Returns: nothing

  The C<CreateDomain> operation creates a new domain. The domain name
should be unique among the domains associated with the Access Key ID
provided in the request. The C<CreateDomain> operation may take 10 or
more seconds to complete.

The client can create up to 100 domains per account.

If the client requires additional domains, go to
http://aws.amazon.com/contact-us/simpledb-limit-request/.

=head2 DeleteAttributes(DomainName => Str, ItemName => Str, [Attributes => ArrayRef[L<Paws::SDB::DeletableAttribute>], Expected => L<Paws::SDB::UpdateCondition>])

Each argument is described in detail in: L<Paws::SDB::DeleteAttributes>

Returns: nothing

  Deletes one or more attributes associated with an item. If all
attributes of the item are deleted, the item is deleted.

C<DeleteAttributes> is an idempotent operation; running it multiple
times on the same item or attribute does not result in an error
response.

Because Amazon SimpleDB makes multiple copies of item data and uses an
eventual consistency update model, performing a GetAttributes or Select
operation (read) immediately after a C<DeleteAttributes> or
PutAttributes operation (write) might not return updated item data.

=head2 DeleteDomain(DomainName => Str)

Each argument is described in detail in: L<Paws::SDB::DeleteDomain>

Returns: nothing

  The C<DeleteDomain> operation deletes a domain. Any items (and their
attributes) in the domain are deleted as well. The C<DeleteDomain>
operation might take 10 or more seconds to complete.

=head2 DomainMetadata(DomainName => Str)

Each argument is described in detail in: L<Paws::SDB::DomainMetadata>

Returns: a L<Paws::SDB::DomainMetadataResult> instance

  Returns information about the domain, including when the domain was
created, the number of items and attributes in the domain, and the size
of the attribute names and values.

=head2 GetAttributes(DomainName => Str, ItemName => Str, [AttributeName => Str, ConsistentRead => Bool])

Each argument is described in detail in: L<Paws::SDB::GetAttributes>

Returns: a L<Paws::SDB::GetAttributesResult> instance

  Returns all of the attributes associated with the specified item.
Optionally, the attributes returned can be limited to one or more
attributes by specifying an attribute name parameter.

If the item does not exist on the replica that was accessed for this
operation, an empty set is returned. The system does not return an
error as it cannot guarantee the item does not exist on other replicas.

=head2 ListDomains([MaxNumberOfDomains => Int, NextToken => Str])

Each argument is described in detail in: L<Paws::SDB::ListDomains>

Returns: a L<Paws::SDB::ListDomainsResult> instance

  The C<ListDomains> operation lists all domains associated with the
Access Key ID. It returns domain names up to the limit set by
MaxNumberOfDomains. A NextToken is returned if there are more than
C<MaxNumberOfDomains> domains. Calling C<ListDomains> successive times
with the C<NextToken> provided by the operation returns up to
C<MaxNumberOfDomains> more domain names with each successive operation
call.

=head2 PutAttributes(Attributes => ArrayRef[L<Paws::SDB::ReplaceableAttribute>], DomainName => Str, ItemName => Str, [Expected => L<Paws::SDB::UpdateCondition>])

Each argument is described in detail in: L<Paws::SDB::PutAttributes>

Returns: nothing

  The PutAttributes operation creates or replaces attributes in an item.
The client may specify new attributes using a combination of the
C<Attribute.X.Name> and C<Attribute.X.Value> parameters. The client
specifies the first attribute by the parameters C<Attribute.0.Name> and
C<Attribute.0.Value>, the second attribute by the parameters
C<Attribute.1.Name> and C<Attribute.1.Value>, and so on.

Attributes are uniquely identified in an item by their name/value
combination. For example, a single item can have the attributes C<{
"first_name", "first_value" }> and C<{ "first_name", second_value" }>.
However, it cannot have two attribute instances where both the
C<Attribute.X.Name> and C<Attribute.X.Value> are the same.

Optionally, the requestor can supply the C<Replace> parameter for each
individual attribute. Setting this value to C<true> causes the new
attribute value to replace the existing attribute value(s). For
example, if an item has the attributes C<{ 'a', '1' }>, C<{ 'b', '2'}>
and C<{ 'b', '3' }> and the requestor calls C<PutAttributes> using the
attributes C<{ 'b', '4' }> with the C<Replace> parameter set to true,
the final attributes of the item are changed to C<{ 'a', '1' }> and C<{
'b', '4' }>, which replaces the previous values of the 'b' attribute
with the new value.

You cannot specify an empty string as an attribute name.

Because Amazon SimpleDB makes multiple copies of client data and uses
an eventual consistency update model, an immediate GetAttributes or
Select operation (read) immediately after a PutAttributes or
DeleteAttributes operation (write) might not return the updated data.

The following limitations are enforced for this operation:

=over

=item * 256 total attribute name-value pairs per item

=item * One billion attributes per domain

=item * 10 GB of total user data storage per domain

=back

=head2 Select(SelectExpression => Str, [ConsistentRead => Bool, NextToken => Str])

Each argument is described in detail in: L<Paws::SDB::Select>

Returns: a L<Paws::SDB::SelectResult> instance

  The C<Select> operation returns a set of attributes for C<ItemNames>
that match the select expression. C<Select> is similar to the standard
SQL SELECT statement.

The total size of the response cannot exceed 1 MB in total size. Amazon
SimpleDB automatically adjusts the number of items returned per page to
enforce this limit. For example, if the client asks to retrieve 2500
items, but each individual item is 10 kB in size, the system returns
100 items and an appropriate C<NextToken> so the client can access the
next page of results.

For information on how to construct select expressions, see Using
Select to Create Amazon SimpleDB Queries in the Developer Guide.

=head1 PAGINATORS

Paginator methods are helpers that repetively call methods that return partial results

=head2 ListAllDomains(sub { },[MaxNumberOfDomains => Int, NextToken => Str])

=head2 ListAllDomains([MaxNumberOfDomains => Int, NextToken => Str])

If passed a sub as first parameter, it will call the sub for each element found in :

 - DomainNames, passing the object as the first parameter, and the string 'DomainNames' as the second parameter

If not, it will return a a L<Paws::SDB::ListDomainsResult> instance with all the C<param>s;  from all the responses. Please take into account that this mode can potentially consume vasts ammounts of memory.

=head2 SelectAll(sub { },SelectExpression => Str, [ConsistentRead => Bool, NextToken => Str])

=head2 SelectAll(SelectExpression => Str, [ConsistentRead => Bool, NextToken => Str])

If passed a sub as first parameter, it will call the sub for each element found in :

 - Items, passing the object as the first parameter, and the string 'Items' as the second parameter

If not, it will return a a L<Paws::SDB::SelectResult> instance with all the C<param>s;  from all the responses. Please take into account that this mode can potentially consume vasts ammounts of memory.

=head1 SEE ALSO

This service class forms part of L<Paws>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
import React, { PropTypes } from 'react';

import styles from './styles.css';

const FetchTaskError = ({ error }) => (

        {error.taskFetchError &&
          error.taskFetchError.message
          || 'Something bad happened.'
        }

);

FetchTaskError.propTypes = {
  error: PropTypes.object.isRequired
};

export default FetchTaskError;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dmodena.model;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author dmodena
 */
public class NumberValidatorTest {

    public NumberValidatorTest() {
    }

    /**
     * Tests of validate method, of class NumberValidator.
     */
    @Test
    public void testValidate1() {
        System.out.println("validate");
        String hex = "foo123.45";
        NumberValidator instance = new NumberValidator();
        boolean expResult = false;
        boolean result = instance.validate(hex);
        assertEquals(expResult, result);
    }

    @Test
    public void testValidate2() {
        System.out.println("validate");
        String hex = "45,32";
        NumberValidator instance = new NumberValidator();
        boolean expResult = false;
        boolean result = instance.validate(hex);
        assertEquals(expResult, result);
    }

    @Test
    public void testValidate3() {
        System.out.println("validate");
        String hex = "12.34";
        NumberValidator instance = new NumberValidator();
        boolean expResult = true;
        boolean result = instance.validate(hex);
        assertEquals(expResult, result);
    }

    @Test
    public void testValidate4() {
        System.out.println("validate");
        String hex = ".5";
        NumberValidator instance = new NumberValidator();
        boolean expResult = true;
        boolean result = instance.validate(hex);
        assertEquals(expResult, result);
    }

}