text:
package com.yogee.zhebuy.modules.ebuy.web;

import com.yogee.zhebuy.common.beanvalidator.BeanValidators;
import com.yogee.zhebuy.common.config.Global;
import com.yogee.zhebuy.common.mapper.JsonMapper;
import com.yogee.zhebuy.common.persistence.Page;
import com.yogee.zhebuy.common.utils.DateUtils;
import com.yogee.zhebuy.common.utils.StringUtils;
import com.yogee.zhebuy.common.utils.excel.ExportExcel;
import com.yogee.zhebuy.common.utils.excel.ImportExcel;
import com.yogee.zhebuy.common.web.BaseController;
import com.yogee.zhebuy.common.weixin.web.TemplateMsg;
import com.yogee.zhebuy.interfaces.util.Constant;
import com.yogee.zhebuy.interfaces.util.HanyuPinyinHelper;
import com.yogee.zhebuy.modules.ebuy.entity.*;
import com.yogee.zhebuy.modules.ebuy.export.ExportBusinessNew;
import com.yogee.zhebuy.modules.ebuy.export.ExportItemNew;
import com.yogee.zhebuy.modules.ebuy.export.ExportItemNewImg;
import com.yogee.zhebuy.modules.ebuy.service.*;
import com.yogee.zhebuy.modules.sys.utils.UserUtils;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 商品Controller
 * @author jackqth
 * @version 2017-06-02
 */
@Controller
@RequestMapping(value = "${adminPath}/ebuy/ebuyProItem")
public class EbuyProItemController extends BaseController {

	@Autowired
	private EbuyProSpecifyService ebuyProSpecifyService;

	@Autowired
	private EbuyProItemService ebuyProItemService;

	@Autowired
	private EbuyProCategoryService ebuyProCategoryService;

	@Autowired
	private EbuyProUnitService ebuyProUnitService;

	@Autowired
	private EbuyProItemMerchantService ebuyProItemMerchantService;

	@Autowired
	private EbuyBusinessService ebuyBusinessService;

	@Autowired
	private EbuyOffenBuyService ebuyOffenBuyService;

	@ModelAttribute
	public EbuyProItem get(@RequestParam(required=false) String id) {
		EbuyProItem entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = ebuyProItemService.get(id);
		}
		if (entity == null){
			entity = new EbuyProItem();
		}
		return entity;
	}

	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = {"list", ""})
	public String list(EbuyProItem ebuyProItem, HttpServletRequest request, EbuyProCategory ebuyProCategory, HttpServletResponse response, Model model) {
		String cityId = UserUtils.getUser().getCompany().getArea().getId();
		if(StringUtils.isNotEmpty(cityId) && !Constant.AREA_SICHUAN.equals(cityId)){
			ebuyProItem.setDescs(cityId);
		}
		//拆分查询
		String itemName ="";
		if(StringUtils.isNotEmpty(ebuyProItem.getName())){
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i <ebuyProItem.getName().length(); i++) {

				if(sb.toString() != null && sb.toString() !=""){
					sb.append(",");
				}
				sb.append(ebuyProItem.getName().charAt(i));
			}
			itemName = sb.toString().substring(1);
			itemName = itemName.replaceAll(",", "%");
		}
		ebuyProItem.setName(itemName);
		Page<EbuyProItem> page = ebuyProItemService.findPage(new Page<EbuyProItem>(request, response), ebuyProItem);
		//获取一级分类
		List<EbuyProCategory> categorySecond = ebuyProCategoryService.findListTop(ebuyProCategory);
		model.addAttribute("categorySecond", categorySecond);
		model.addAttribute("page", page);
		return "modules/ebuy/ebuyProItemList";
	}

	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = "auditList")
	public String auditList(EbuyProItem ebuyProItem, HttpServletRequest request, EbuyProCategory ebuyProCategory, HttpServletResponse response, Model model) {
		String cityId = UserUtils.getUser().getCompany().getArea().getId();
		if(StringUtils.isNotEmpty(cityId) && !Constant.AREA_SICHUAN.equals(cityId)){
			ebuyProItem.setDescs(cityId);
		}
		if(StringUtils.isEmpty(ebuyProItem.getStatus())){
			ebuyProItem.setStatus("1");
		}
		//拆分查询
		String itemName ="";
		if(StringUtils.isNotEmpty(ebuyProItem.getName())){
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i <ebuyProItem.getName().length(); i++) {

				if(sb.toString() != null && sb.toString() !=""){
					sb.append(",");
				}
				sb.append(ebuyProItem.getName().charAt(i));
			}
			itemName = sb.toString().substring(1);
			itemName = itemName.replaceAll(",", "%");
		}
		ebuyProItem.setName(itemName);
		Page<EbuyProItem> page = ebuyProItemService.findAuditPage(new Page<EbuyProItem>(request, response), ebuyProItem);

		//获取二级分类
		List<EbuyProCategory> categorySecond = ebuyProCategoryService.findListSecond(ebuyProCategory);
		model.addAttribute("categorySecond", categorySecond);
		model.addAttribute("page", page);
		return "modules/ebuy/ebuyProItemAuditList";
	}

	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = "form")
	public String form(EbuyProItem ebuyProItem,EbuyProCategory ebuyProCategory, Model model) {
		//获取二级分类
		List<EbuyProCategory> topCate = ebuyProCategoryService.findListTop(ebuyProCategory);
		List<EbuyProCategory> categorySecond = ebuyProCategoryService.findListSecond(ebuyProCategory);
		if(StringUtils.isNotEmpty(ebuyProItem.getId())){
			List specifies = ebuyProSpecifyService.findSpecifyList(Integer.parseInt(ebuyProItem.getId()));
			model.addAttribute("specifies", specifies);
		}

		List proUnit = ebuyProUnitService.getUnitList();
		model.addAttribute("proUnit", proUnit);
		model.addAttribute("ebuyProItem", ebuyProItem);
		model.addAttribute("categorySecond", categorySecond);
		model.addAttribute("topCate", topCate);
		return "modules/ebuy/ebuyProItemForm";
	}
	//新增商品导入
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "batchImport")
	public String batchImport(EbuyProItem ebuyProItem, Model model) {
		model.addAttribute("ebuyProItem", ebuyProItem);
		return "modules/ebuy/ebuyProItemImport";
	}
	//商品图片导入
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "batchImportImg")
	public String batchImportImg(EbuyProItem ebuyProItem, Model model) {
		model.addAttribute("ebuyProItem", ebuyProItem);
		return "modules/ebuy/ebuyProItemImportImg";
	}
	//修改商品信息导入
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "updateImport")
	public String updateImport(EbuyProItem ebuyProItem, Model model) {
		model.addAttribute("ebuyProItem", ebuyProItem);
		return "modules/ebuy/ebuyProItemUpdateImport";
	}

	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = "auditForm")
	public String auditForm(EbuyProItem ebuyProItem,EbuyProCategory ebuyProCategory, Model model) {
		//获取二级分类
		List<EbuyProCategory> categorySecond = ebuyProCategoryService.findListSecond(ebuyProCategory);
		if(StringUtils.isNotEmpty(ebuyProItem.getId())){
			List specifies = ebuyProSpecifyService.findSpecifyList(Integer.parseInt(ebuyProItem.getId()));
			model.addAttribute("specifies", specifies);
		}

		List proUnit = ebuyProUnitService.getUnitList();
		model.addAttribute("proUnit", proUnit);
		model.addAttribute("ebuyProItem", ebuyProItem);
		model.addAttribute("categorySecond", categorySecond);
		return "modules/ebuy/ebuyProItemAuditForm";
	}

	@Transactional(readOnly = false)
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "save")
	public String save(final EbuyProItem ebuyProItem, Model model, EbuyProCategory ebuyProCategory, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, ebuyProItem)){
			return form(ebuyProItem, ebuyProCategory, model);
		}
		try{
			//审核状态初始化
			if(StringUtils.isEmpty(ebuyProItem.getAuditStatus())){
				ebuyProItem.setAuditStatus(Constant.AUDIT_FLAG_SUCCESS);
			}
			String[] sid = request.getParameterValues("sid[]");
			String[] num = request.getParameterValues("num[]");
			String[] specify = request.getParameterValues("specify[]");
			String[] type = request.getParameterValues("type[]");
			String[] weights = request.getParameterValues("weights[]");
			ebuyProItem.setName(ebuyProItem.getItemName());
			String fullName = ebuyProItem.getBrand()+ebuyProItem.getName()+ebuyProItem.getSpecification()+"/"+ebuyProUnitService.get(specify[0]).getName();
			ebuyProItem.setFullName(fullName);
			ebuyProItem.setPinyinFullName(HanyuPinyinHelper.toHanyuPinyin(fullName));
			ebuyProItemService.save(ebuyProItem);
			addMessage(redirectAttributes, "保存商品成功");
			if(StringUtils.isNotEmpty(ebuyProItem.getId())){
				//修改增加转换率 把所有商户有该商品的都增加此转换率
				//查询有该商品的商户有哪些
				final List<EbuyProItemMerchant> ebuyProItemMerchantList = ebuyProItemMerchantService.findUserByItemId(ebuyProItem.getId());
				for (int i=0; i<num.length; i++){
					EbuyProSpecify ebuyProSpecify = ebuyProSpecifyService.get(sid[i]);
					if (ebuyProSpecify == null){
						ebuyProSpecify = new EbuyProSpecify();
					}
					ebuyProSpecify.setItemId(Integer.parseInt(ebuyProItem.getId()));
					ebuyProSpecify.setCount(num[i]);
					ebuyProSpecify.setType(type[i]);
					ebuyProSpecify.setWeight(weights[i]);
					ebuyProSpecify.setUnit(Long.parseLong(specify[i]));
					if(type[i].equals("0")){
						ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
					}else{
						//查询该商品的基础规格 单位
						EbuyProSpecify bean = ebuyProSpecifyService.findByItemIdAndTypeOne(ebuyProItem.getId());
						if(StringUtils.isNotEmpty(bean.getUnit().toString())){
							ebuyProSpecify.setSpecName(num[i]+ebuyProUnitService.get(bean.getUnit().toString()).getName()+"/"+ ebuyProUnitService.get(specify[i]).getName());
						}else{
							ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
						}
					}
					ebuyProSpecifyService.save(ebuyProSpecify);
					//新增获取主键id
					int specyId =  ebuyProSpecify.getAutoId();
					//新增的转换率  插入有该商品的没有该规格的商户
					if(specyId>0){
						final int finalSpecyId = specyId;
						new Thread() {
							public void run() {
								for (EbuyProItemMerchant bean : ebuyProItemMerchantList) {
									//根据商品规格和商品id和商家  查询商家是否上了此商品的此规格
									if (ebuyProItemMerchantService.findByItemUserSpec(finalSpecyId + "", bean.getUserId(), ebuyProItem.getId()) == 0) {
										//说明此商家没有上架该商品的这个规格 插入
										ebuyProItemMerchantService.insertMerchant(finalSpecyId + "", bean.getUserId(), ebuyProItem.getId());
									}
								}
							}
					  }.start();
					}
				}
			}else {
				for (int i=0; i<num.length; i++){
					EbuyProSpecify ebuyProSpecify = new EbuyProSpecify();
					ebuyProSpecify.setItemId(ebuyProItem.getAutoId());
					ebuyProSpecify.setCount(num[i]);
					ebuyProSpecify.setType(type[i]);
					ebuyProSpecify.setUnit(Long.parseLong(specify[i]));
					if(type[i].equals("0")) {
						ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
					}else{
						//查询该商品的基础规格 单位
						String speciId =specify[0] ;
						ebuyProSpecify.setSpecName(num[i]+ebuyProUnitService.get(speciId).getName()+"/"+ ebuyProUnitService.get(specify[i]).getName());
					}
					ebuyProSpecifyService.save(ebuyProSpecify);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new NullPointerException("保存商品成功抛异常,请联系管理员");
		}
		return "redirect:"+ Global.getAdminPath()+"/ebuy/ebuyProItem/?repage";
	}
	//保存审核
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "auditSave")
	public String auditSave(EbuyProItem ebuyProItem, Model model, EbuyProCategory ebuyProCategory, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, ebuyProItem)){
			return form(ebuyProItem, ebuyProCategory, model);
		}
		String[] sid = request.getParameterValues("sid[]");
		String[] num = request.getParameterValues("num[]");
		String[] specify = request.getParameterValues("specify[]");//单位
		String[] type = request.getParameterValues("type[]");
		String[] weights = request.getParameterValues("weights[]");
		ebuyProItem.setName(ebuyProItem.getItemName());
		String fullName = ebuyProItem.getBrand()+ebuyProItem.getName()+ebuyProItem.getSpecification()+"/"+ebuyProUnitService.get(specify[0]).getName();
		ebuyProItem.setFullName(fullName);
		ebuyProItem.setPinyinFullName(HanyuPinyinHelper.toHanyuPinyin(fullName));
		ebuyProItemService.save(ebuyProItem);
		if (ebuyProItem.getAuditStatus().equals("0")||ebuyProItem.getAuditStatus().equals("2")){
			TemplateMsg.pushMsgPriceChange(ebuyProItem.getUser().getWxOpenid(),"您提交的"+ebuyProItem.getName()+"未通过审核","审核审核失败","商品审核未通过,请您重新提交","原因:"+ebuyProItem.getAuditDesc(),Global.getConfig("domain.web")+"/#/serverMyGoods");
		}
		if (ebuyProItem.getAuditStatus().equals("1")){//通过
			Long specifyId = ebuyProSpecifyService.findByItemIdAndType(ebuyProItem.getId());
			ebuyProItemMerchantService.updateIsSale(specifyId,ebuyProItem.getId());
			addMessage(redirectAttributes, "保存商品成功");
			if(StringUtils.isNotEmpty(ebuyProItem.getId())){
				for (int i=0; i<num.length; i++){
					EbuyProSpecify ebuyProSpecify = ebuyProSpecifyService.get(sid[i]);
					if (ebuyProSpecify == null){
						ebuyProSpecify = new EbuyProSpecify();
					}
					ebuyProSpecify.setItemId(Integer.parseInt(ebuyProItem.getId()));
					ebuyProSpecify.setCount(num[i]);
					ebuyProSpecify.setType(type[i]);
					ebuyProSpecify.setWeight(weights[i]);
					ebuyProSpecify.setUnit(Long.parseLong(specify[i]));
					if(type[i].equals("0")){
						ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
					}else{
						//查询该商品的基础规格 单位
						EbuyProSpecify bean = ebuyProSpecifyService.findByItemIdAndTypeOne(ebuyProItem.getId());
						if(StringUtils.isNotEmpty(bean.getUnit().toString())){
							ebuyProSpecify.setSpecName(num[i]+ebuyProUnitService.get(bean.getUnit().toString()).getName()+"/"+ ebuyProUnitService.get(specify[i]).getName());
						}else{
							ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
						}
					}
					ebuyProSpecifyService.save(ebuyProSpecify);
				}
			}else {
				for (int i=0; i<num.length; i++){
					EbuyProSpecify ebuyProSpecify = new EbuyProSpecify();
					ebuyProSpecify.setItemId(ebuyProItem.getAutoId());
					ebuyProSpecify.setCount(num[i]);
					ebuyProSpecify.setType(type[i]);
					ebuyProSpecify.setUnit(Long.parseLong(specify[i]));
					if(type[i].equals("0")){
						ebuyProSpecify.setSpecName(num[i] + ebuyProUnitService.get(specify[i]).getName());
					}else{
						//查询该商品的基础规格
						String speciId =specify[0];
						ebuyProSpecify.setSpecName(num[i]+ebuyProUnitService.get(speciId).getName()+"/"+ ebuyProUnitService.get(specify[i]).getName());
					}
					ebuyProSpecifyService.save(ebuyProSpecify);
				}
			}
			if(ebuyProItem.getUser().getWxOpenid() != null){
				TemplateMsg.pushMsgPriceChange(ebuyProItem.getUser().getWxOpenid(),"您提交的"+ebuyProItem.getName()+"通过审核","审核成功","商品审核成功,请您尽快上架","点击详情可进入商品管理",Global.getConfig("domain.web")+"/#/serverMyGoods");
			}
		}
		return "redirect:"+ Global.getAdminPath()+"/ebuy/ebuyProItem/auditList?repage";
	}

	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "delete")
	public String delete(EbuyProItem ebuyProItem, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		//平台删除商品  相关所有商家关联此商品都逻辑删除
		ebuyProItemMerchantService.deleteItemMerchantByItemId(ebuyProItem.getId());
		//平台删除商品  相关商品的常购也逻辑删除
		ebuyOffenBuyService.deleteItemOffBuyByItemId(ebuyProItem.getId());
		//平台删除商品操作
		ebuyProItemService.delete(ebuyProItem);
		addMessage(redirectAttributes, "删除商品成功");
		String audit = request.getParameter("audit");
		if (audit.equals("0")){
			return "redirect:"+Global.getAdminPath()+"/ebuy/ebuyProItem/?repage";
		}else {
			return "redirect:"+ Global.getAdminPath()+"/ebuy/ebuyProItem/auditList?repage";
		}
	}

	/**
	 * 导入商家商品数据
	 * @param file
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "importFile", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String userId = UserUtils.getUser().getId();
		if(StringUtils.isEmpty(userId)){
			addMessage(redirectAttributes, "用户数据异常,请重新登录。");
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			String itemCount = "";
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<EbuyProItem> list = ei.getDataList(EbuyProItem.class);
			for (EbuyProItem ebuyProItem : list){
				try{
					//获取基础规格信息
					EbuyProUnit ebuyProUnit = ebuyProUnitService.getByName(ebuyProItem.getMinUnit());
					if(null == ebuyProUnit){
						//此基础规格不存在,无法导入
						failureMsg.append("
此基础规格 "+ebuyProItem.getMinUnit()+" 不存在; ");
						failureNum++;
						continue;
					}
					String name =ebuyProItem.getBrand()+ ebuyProItem.getName()+ebuyProItem.getSpecification()+"/"+ebuyProUnit.getName();
					if(StringUtils.isEmpty(name)){
						break;
					}
					EbuyProItem checkExist = ebuyProItemService.getByName(name);
					if (null == checkExist) {
						//获取分类信息
						EbuyProCategory ebuyProCategory = ebuyProCategoryService.getByName(ebuyProItem.getCategoryId());
						if(null == ebuyProCategory){
							//此分类不存在,无法导入
							failureMsg.append("
此分类 "+ebuyProItem.getCategoryId()+" 不存在; ");
							failureNum++;
							continue;
						}
						EbuyProUnit ebuyProUnitBean = new EbuyProUnit();
						if(ebuyProItem.getProUnit()!=null && !ebuyProItem.getProUnit().equals("") && ebuyProItem.getProUnitValue() !=null && !ebuyProItem.getProUnitValue().equals("")){
							//获取转换率信息
							ebuyProUnitBean = ebuyProUnitService.getByName(ebuyProItem.getProUnit());
							if(null == ebuyProUnitBean){
								//此分类不存在,无法导入
								failureMsg.append("
此转换规格 "+ebuyProItem.getProUnit()+" 不存在; ");
								failureNum++;
								continue;
							}
						}
						//赋值分类数据
						ebuyProItem.setCategoryId(ebuyProCategory.getId());
						//初始化其他信息
						ebuyProItem.setItemLabel(ebuyProItem.getItemLabel());
						ebuyProItem.setStatus(Constant.AUDIT_FLAG_SUCCESS);
						ebuyProItem.setAuditStatus(Constant.AUDIT_FLAG_SUCCESS);
						ebuyProItem.setAuditUserId(userId);
						ebuyProItem.setImg("|/userfiles/1/images/itemImage/2017/08/2222.png");
						ebuyProItem.setDefaultImg("1");
						ebuyProItem.setAuditDesc("批量导入数据");
						String fullName = ebuyProItem.getBrand()+ebuyProItem.getName()+ebuyProItem.getSpecification()+"/"+ebuyProUnit.getName();
						ebuyProItem.setFullName(fullName);
						ebuyProItem.setPinyinFullName(HanyuPinyinHelper.toHanyuPinyin(fullName));
						ebuyProItemService.save(ebuyProItem);

						//保存基础转换率信息
						EbuyProSpecify ebuyProSpecify = new EbuyProSpecify();
						ebuyProSpecify.setItemId(ebuyProItem.getAutoId());
						ebuyProSpecify.setUnit(Long.parseLong(ebuyProUnit.getId()));
						ebuyProSpecify.setCount("1");
						ebuyProSpecify.setType("0");
						ebuyProSpecify.setSpecName("1"+ebuyProUnit.getName());
						ebuyProSpecifyService.save(ebuyProSpecify);

						if(ebuyProItem.getProUnit()!=null && !ebuyProItem.getProUnit().equals("") && ebuyProItem.getProUnitValue() !=null && !ebuyProItem.getProUnitValue().equals("")){
							//保存转换率信息
							EbuyProSpecify bean = new EbuyProSpecify();
							bean.setItemId(ebuyProItem.getAutoId());
							bean.setUnit(Long.parseLong(ebuyProUnitBean.getId()));
							bean.setCount(ebuyProItem.getProUnitValue());
							bean.setType("1");
							bean.setSpecName(ebuyProItem.getProUnitValue()+ebuyProUnit.getName()+"/" + ebuyProUnitBean.getName());
							ebuyProSpecifyService.save(bean);
						}
						successNum++;
					}else{
						//平台已添加此商品,无法导入
						failureMsg.append("
平台已添加此商品 " + ebuyProItem.getName()+"; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("
商品数据 "+ebuyProItem.getName()+" 导入失败:");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("
商品数据 "+ebuyProItem.getName()+" 导入失败:"+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, ",失败 "+failureNum+" 条数据,导入信息如下:");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条商品数据"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入商品数据失败!失败信息:"+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ebuy/ebuyProItem/list?repage";
	}

	/**
	 * 导入修改商品信息
	 * @param file
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "updateImportFile", method= RequestMethod.POST)
	public String updateImportFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String userId = UserUtils.getUser().getId();
		if(StringUtils.isEmpty(userId)){
			addMessage(redirectAttributes, "用户数据异常,请重新登录。");
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ExportItemNew> list = ei.getDataList(ExportItemNew.class);
			for (ExportItemNew exportItemNew : list){
				try{
					String id = exportItemNew.getSku();
					if(StringUtils.isEmpty(id)){
						break;
					}
					EbuyProItem checkExist = ebuyProItemService.get(id);
					if (checkExist !=null) {
						EbuyProSpecify ebuyProSpecify = ebuyProSpecifyService.findByItemIdAndTypeOne(id);
						checkExist.setItemLabel(exportItemNew.getItemLabel());
						checkExist.setBrand(exportItemNew.getBrand());
						checkExist.setName(exportItemNew.getItemName());
						checkExist.setSpecification(exportItemNew.getSpecification());
						String fullName = exportItemNew.getBrand()+exportItemNew.getItemName()+exportItemNew.getSpecification()+"/"+ebuyProSpecify.getSpecName().replace("1","");
						checkExist.setFullName(fullName);
						checkExist.setPinyinFullName(HanyuPinyinHelper.toHanyuPinyin(fullName));
						checkExist.setAlias(exportItemNew.getAlias());
						checkExist.setDescs(exportItemNew.getDescs());
						checkExist.setCategoryId(ebuyProCategoryService.getByName(exportItemNew.getCateName()).getId());
						checkExist.setStatus(exportItemNew.getStatus());
						if(StringUtils.isNotEmpty(exportItemNew.getShelfLife())){
							checkExist.setShelfLife(this.getDigital(exportItemNew.getShelfLife()));
						}else{
							checkExist.setShelfLife(null);
						}
						checkExist.setLicense(exportItemNew.getLicense());
						checkExist.setManufactor(exportItemNew.getManufactor());
						checkExist.setConditions(exportItemNew.getConditions());
						checkExist.setIngredient(exportItemNew.getIngredient());
						checkExist.setProvenance(exportItemNew.getProvenance());
						ebuyProItemService.save(checkExist);
						successNum++;
					} else {
						//平台未添加此商品,无法修改
						failureMsg.append("
平台未添加此商品 " + exportItemNew.getItemName()+"; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("
商品数据 "+exportItemNew.getItemName()+" 修改失败:");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					ex.printStackTrace();
					failureMsg.append("
商品数据 "+exportItemNew.getItemName()+" 修改失败:"+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, ",失败 "+failureNum+" 条数据,导入信息如下:");
			}
			addMessage(redirectAttributes, "已成功修改 "+successNum+" 条商品数据"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "修改商品数据失败!失败信息:"+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ebuy/ebuyProItem/list?repage";
	}
	/**
	 * 导入商品图片信息
	 * @param file
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequiresPermissions("ebuy:ebuyProItem:edit")
	@RequestMapping(value = "batchImportImg", method= RequestMethod.POST)
	public String batchImportImg(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String userId = UserUtils.getUser().getId();
		if(StringUtils.isEmpty(userId)){
			addMessage(redirectAttributes, "用户数据异常,请重新登录。");
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ExportItemNewImg> list = ei.getDataList(ExportItemNewImg.class);
			for (ExportItemNewImg exportItemNewImg : list){
				try{
					String id = exportItemNewImg.getSku();
					if(StringUtils.isEmpty(id)){
						break;
					}
					EbuyProItem checkExist = ebuyProItemService.get(id);
					if (checkExist !=null) {
						String month="";
						if(StringUtils.isEmpty(exportItemNewImg.getMonth())){
							month= DateUtils.getMonth();
						}else {
							month = exportItemNewImg.getMonth();
						}
						String imgFormat="";
						if (StringUtils.isEmpty(exportItemNewImg.getFormat())){
							imgFormat = "jpg";
						}else{
							if(exportItemNewImg.getFormat().contains("jpg")){
								imgFormat = "jpg";
							}else if(exportItemNewImg.getFormat().contains("png")){
								imgFormat = "png";
							}else{
								imgFormat = "jpg";
							}
						}
						String img = "|/userfiles/1/_thumbs/images/itemImage/"+DateUtils.getYear()+"/"+month+"/"+id+"."+imgFormat;
						checkExist.setImg(img);
						checkExist.setFullName(checkExist.getName());
						checkExist.setName(checkExist.getItemName());
						ebuyProItemService.save(checkExist);
						successNum++;
					} else {
						//平台未添加此商品,无法修改
						failureMsg.append("
平台未添加此商品的SKU " + exportItemNewImg.getSku()+"; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("
商品数据的SKU"+exportItemNewImg.getSku()+" 修改失败:");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					ex.printStackTrace();
					failureMsg.append("
商品数据的SKU"+exportItemNewImg.getSku()+" 修改失败:"+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, ",失败 "+failureNum+" 条数据,导入信息如下:");
			}
			addMessage(redirectAttributes, "已成功修改 "+successNum+" 条商品数据"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "修改商品数据失败!失败信息:"+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ebuy/ebuyProItem/list?repage";
	}

	public static Long getDigital(String name) {
		String r_name3 = "sml-rank-stars sml-str45";
		Pattern pattern = Pattern.compile("[^0-9]");
		Matcher matcher = pattern.matcher(name);
		String ss = matcher.replaceAll("");
		return Long.valueOf(ss);
	}

	/**
	 * 导出商品数据
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = "itemExport")
	public String newUserExport(HttpServletResponse response, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String createDate = request.getParameter("createDate");
		String dateEnd = request.getParameter("dateEnd");
		String categoryId = request.getParameter("categoryId");
		String name = request.getParameter("name");
		//拆分查询
		String itemName ="";
		if(StringUtils.isNotEmpty(name)){
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i <name.length(); i++) {

				if(sb.toString() != null && sb.toString() !=""){
					sb.append(",");
				}
				sb.append(name.charAt(i));
			}
			itemName = sb.toString().substring(1);
			itemName = itemName.replaceAll(",", "%");
		}
		String format_date ="";
		if(createDate.equals("")){
			format_date ="";
		}else{
			format_date = createDate.substring(0,7).replace("-", "年");
		}
		try {
			String fileName = format_date+"商品信息.xlsx";
//			// 获取当月新增客户
			String cityId = UserUtils.getUser().getCompany().getArea().getId();
			List<ExportItemNew> businessNewList = ebuyProItemService.findBusinessNewByMonth(createDate,dateEnd,categoryId,itemName);
			new ExportExcel(format_date+"商品信息", ExportItemNew.class, 1).setDataList(businessNewList).write(response, fileName).dispose();
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, format_date+"新增商品下载失败!失败信息:"+e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/ebuy/ebuyProItem/?repage";
	}

	/**
	 * 推荐热门商品
	 * @param ebuyProItem
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "editHot")
	public String editHot(EbuyProItem ebuyProItem, RedirectAttributes redirectAttributes) {
		if(ebuyProItem.getIsHot().equals("1")){
			addMessage(redirectAttributes, "添加热门商品成功");
		}else{
			addMessage(redirectAttributes, "取消热门商品成功");
		}
		ebuyProItem.setPinyinFullName(HanyuPinyinHelper.toHanyuPinyin(ebuyProItem.getFullName()));
		ebuyProItemService.save(ebuyProItem);
		return "redirect:"+Global.getAdminPath()+"/ebuy/ebuyProItem/?repage";
	}
	/**
	 *	添加到商户
	 * @param ebuyProItem
	 * @return
	 */
	@RequestMapping(value = "addItem")
	public String addItem(EbuyProItem ebuyProItem,Model model) {
		List<EbuyProSpecify> ebuyProSpecifyList = ebuyProSpecifyService.findProSpecifyByItemId(ebuyProItem.getId());
		//最小单位
		String mixUnit = "";
		if(ebuyProSpecifyList.size()>0){
			mixUnit = ebuyProSpecifyList.get(0).getUnitName();
		}
		List<EbuyBusiness> businessesList = ebuyBusinessService.findBusinessByType("0","1");
		model.addAttribute("businessesList", businessesList);
		model.addAttribute("ebuyProSpecifyList", ebuyProSpecifyList);
		model.addAttribute("itemId", ebuyProItem.getId());
		model.addAttribute("ebuyProItemMerchant", new EbuyProItemMerchant());
		model.addAttribute("mixUnit", mixUnit);
		return "modules/ebuy/ebuyProItemAddList";
	}

	/**
	 *	获取二级分类
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getSecondCate")
	@ResponseBody
	public List getSecondCate(HttpServletRequest request) {
		//一级分类id
		String id = request.getParameter("id");
		List<EbuyProCategory> categoryList = ebuyProCategoryService.findSecondByTopId(Integer.valueOf(id));
		return categoryList;
	}

	//一键添加商品跳转页
	@RequiresPermissions("ebuy:ebuyProItem:view")
	@RequestMapping(value = "aKeyAdd")
	public String aKeyAdd(Model model) {
		model.addAttribute("ebuyProItemMerchant", new EbuyProItemMerchant());
		return "modules/ebuy/ebuyProItemAKeyAddList";
	}

}


text:
namespace sling {
namespace nlp {

// A document corpus is a set of record files with SLING-encoded documents.
class DocumentCorpus {
 public:
  // Initialize document corpus.
  DocumentCorpus(Store *commons, const string &filepattern);
  DocumentCorpus(Store *commons, const std::vector<string> &filenames);
  ~DocumentCorpus();

  // Read next document into store and return it or null of there are no
  // more document. The returned document is owned by the caller.
  Document *Next(Store *store);

  // Rewind to the start of the corpus.
  void Rewind();

 private:
  // Record files with documents.
  RecordDatabase corpus_;

  // Document schema.
  DocumentNames *docnames_;
};

}  // namespace nlp
}  // namespace sling

#endif  // SLING_NLP_DOCUMENT_DOCUMENT_CORPUS_H_

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import type {Sink} from '../relay-runtime/network/RelayObservable';
import type {
  GeneratedNodeMap,
  ObserverOrCallback,
  RefetchOptions,
  RelayPaginationProp,
  $RelayProps,
} from './ReactRelayTypes';
import type {
  CacheConfig,
  ConnectionMetadata,
  Disposable,
  FragmentMap,
  FragmentSpecResolver,
  GraphQLTaggedNode,
  Observer,
  PageInfo,
  RelayContext,
  Subscription,
  Variables,
} from 'relay-runtime';

const buildReactRelayContainer = require('./buildReactRelayContainer');
const getRootVariablesForFragments = require('./getRootVariablesForFragments');
const {
  getComponentName,
  getContainerName,
} = require('./ReactRelayContainerUtils');
const ReactRelayContext = require('./ReactRelayContext');
const ReactRelayQueryFetcher = require('./ReactRelayQueryFetcher');
const {assertRelayContext} = require('./RelayContext');
const areEqual = require('areEqual');
const invariant = require('invariant');
const React = require('react');
const {
  ConnectionInterface,
  Observable,
  RelayFeatureFlags,
  createFragmentSpecResolver,
  createOperationDescriptor,
  getDataIDsFromObject,
  getRequest,
  getVariablesFromObject,
  isScalarAndEqual,
} = require('relay-runtime');
const warning = require('warning');

type ContainerState = {
  data: {[key: string]: mixed, ...},
  relayProp: RelayPaginationProp,
  prevContext: RelayContext,
  contextForChildren: RelayContext,
  resolverGeneration: number,
  ...
};

const FORWARD = 'forward';

type FragmentVariablesGetter = (
  prevVars: Variables,
  totalCount: number,
) => Variables;

export type ConnectionConfig = {
  direction?: 'backward' | 'forward',
  getConnectionFromProps?: (props: Object) => ?ConnectionData,
  getFragmentVariables?: FragmentVariablesGetter,
  getVariables: (
    props: Object,
    paginationInfo: {
      count: number,
      cursor: ?string,
      ...
    },
    fragmentVariables: Variables,
  ) => Variables,
  query: GraphQLTaggedNode,
  ...
};
export type ConnectionData = {
  +edges?: ?$ReadOnlyArray<any>,
  +pageInfo?: ?PageInfo,
  ...
};

/**
 * Extends the functionality of RelayFragmentContainer by providing a mechanism
 * to load more data from a connection.
 *
 * # Configuring a PaginationContainer
 *
 * PaginationContainer accepts the standard FragmentContainer arguments and an
 * additional `connectionConfig` argument:
 *
 * - `Component`: the component to be wrapped/rendered.
 * - `fragments`: an object whose values are `graphql` fragments. The object
 *   keys determine the prop names by which fragment data is available.
 * - `connectionConfig`: an object that determines how to load more connection
 *   data. Details below.
 *
 * # Loading More Data
 *
 * Use `props.relay.hasMore()` to determine if there are more items to load.
 *
 * ```
 * hasMore(): boolean
 * ```
 *
 * Use `props.relay.isLoading()` to determine if a previous call to `loadMore()`
 * is still pending. This is convenient for avoiding duplicate load calls.
 *
 * ```
 * isLoading(): boolean
 * ```
 *
 * Use `props.relay.loadMore()` to load more items. This will return null if
 * there are no more items to fetch, otherwise it will fetch more items and
 * return a Disposable that can be used to cancel the fetch.
 *
 * `pageSize` should be the number of *additional* items to fetch (not the
 * total).
 *
 * ```
 * loadMore(pageSize: number, callback: ?(error: ?Error) => void): ?Disposable
 * ```
 *
 * A complete example:
 *
 * ```
 * class Foo extends React.Component {
 *   ...
 *   _onEndReached() {
 *     if (!this.props.relay.hasMore() || this.props.relay.isLoading()) {
 *       return;
 *     }
 *     this.props.relay.loadMore(10);
 *   }
 *   ...
 * }
 * ```
 *
 * # Connection Config
 *
 * Here's an example, followed by details of each config property:
 *
 * ```
 * ReactRelayPaginationContainer.createContainer(
 *   Component,
 *   {
 *     user: graphql`fragment FriendsFragment on User {
 *       friends(after: $afterCursor first: $count) @connection {
 *         edges { ... }
 *         pageInfo {
 *           startCursor
 *           endCursor
 *           hasNextPage
 *           hasPreviousPage
 *         }
 *       }
 *     }`,
 *   },
 *   {
 *     direction: 'forward',
 *     getConnectionFromProps(props) {
 *       return props.user && props.user.friends;
 *     },
 *     getFragmentVariables(vars, totalCount) {
 *       // The component presumably wants *all* edges, not just those after
 *       // the cursor, so notice that we don't set $afterCursor here.
 *       return {
 *         ...vars,
 *         count: totalCount,
 *       };
 *     },
 *     getVariables(props, {count, cursor}, fragmentVariables) {
 *       return {
 *         id: props.user.id,
 *         afterCursor: cursor,
 *         count,
 *       },
 *     },
 *     query: graphql`
 *       query FriendsQuery($id: ID!, $afterCursor: ID, $count: Int!) {
 *         node(id: $id) {
 *           ...FriendsFragment
 *         }
 *       }
 *     `,
 *   }
 * );
 * ```
 *
 * ## Config Properties
 *
 * - `direction`: Either "forward" to indicate forward pagination using
 *   after/first, or "backward" to indicate backward pagination using
 *   before/last.
 * - `getConnectionFromProps(props)`: PaginationContainer doesn't magically know
 *   which connection data you mean to fetch more of (a container might fetch
 *   multiple connections, but can only paginate one of them). This function is
 *   given the fragment props only (not full props), and should return the
 *   connection data. See the above example that returns the friends data via
 *   `props.user.friends`.
 * - `getFragmentVariables(previousVars, totalCount)`: Given the previous variables
 *   and the new total number of items, get the variables to use when reading
 *   your fragments. Typically this means setting whatever your local "count"
 *   variable is to the value of `totalCount`. See the example.
 * - `getVariables(props, {count, cursor})`: Get the variables to use when
 *   fetching the pagination `query`. You may determine the root object id from
 *   props (see the example that uses `props.user.id`) and may also set whatever
 *   variables you use for the after/first/before/last calls based on the count
 *   and cursor.
 * - `query`: A query to use when fetching more connection data. This should
 *   typically reference one of the container's fragment (as in the example)
 *   to ensure that all the necessary fields for sub-components are fetched.
 */

function createGetConnectionFromProps(metadata: ReactConnectionMetadata) {
  const path = metadata.path;
  invariant(
    path,
    'ReactRelayPaginationContainer: Unable to synthesize a ' +
      'getConnectionFromProps function.',
  );
  return (props: any) => {
    let data = props[metadata.fragmentName];
    for (let i = 0; i < path.length; i++) {
      if (!data || typeof data !== 'object') {
        return null;
      }
      data = data[path[i]];
    }
    return data;
  };
}

function createGetFragmentVariables(
  metadata: ReactConnectionMetadata,
): FragmentVariablesGetter {
  const countVariable = metadata.count;
  invariant(
    countVariable,
    'ReactRelayPaginationContainer: Unable to synthesize a ' +
      'getFragmentVariables function.',
  );
  return (prevVars: Variables, totalCount: number): Variables => ({
    ...prevVars,
    [(countVariable: string)]: totalCount,
  });
}

type ReactConnectionMetadata = ConnectionMetadata & {fragmentName: string, ...};

function findConnectionMetadata(
  fragments: FragmentMap,
): ReactConnectionMetadata {
  let foundConnectionMetadata = null;
  let isRelayModern = false;
  for (const fragmentName in fragments) {
    const fragment = fragments[fragmentName];
    const connectionMetadata: ?Array<ConnectionMetadata> = (fragment.metadata &&
      fragment.metadata.connection: any);
    // HACK: metadata is always set to `undefined` in classic. In modern, even
    // if empty, it is set to null (never undefined). We use that knowlege to
    // check if we're dealing with classic or modern
    if (fragment.metadata !== undefined) {
      isRelayModern = true;
    }
    if (connectionMetadata) {
      invariant(
        connectionMetadata.length === 1,
        'ReactRelayPaginationContainer: Only a single @connection is ' +
          'supported, `%s` has %s.',
        fragmentName,
        connectionMetadata.length,
      );
      invariant(
        !foundConnectionMetadata,
        'ReactRelayPaginationContainer: Only a single fragment with ' +
          '@connection is supported.',
      );
      foundConnectionMetadata = {
        ...connectionMetadata[0],
        fragmentName,
      };
    }
  }
  invariant(
    !isRelayModern || foundConnectionMetadata !== null,
    'ReactRelayPaginationContainer: A @connection directive must be present.',
  );
  return foundConnectionMetadata || ({}: any);
}

function toObserver(observerOrCallback: ?ObserverOrCallback): Observer<void> {
  return typeof observerOrCallback === 'function'
    ? {
        error: observerOrCallback,
        complete: observerOrCallback,
        unsubscribe: (subscription: Subscription) => {
          typeof observerOrCallback === 'function' && observerOrCallback();
        },
      }
    : observerOrCallback || ({}: any);
}

function createContainerWithFragments<
  Props: {...},
  TComponent: React.ComponentType<Props>,
>(
  Component: TComponent,
  fragments: FragmentMap,
  connectionConfig: ConnectionConfig,
): React.ComponentType<
  $RelayProps<React$ElementConfig<TComponent>, RelayPaginationProp>,
> {
  const componentName = getComponentName(Component);
  const containerName = getContainerName(Component);

  const metadata = findConnectionMetadata(fragments);

  const getConnectionFromProps =
    connectionConfig.getConnectionFromProps ||
    createGetConnectionFromProps(metadata);

  const direction = connectionConfig.direction || metadata.direction;
  invariant(
    direction,
    'ReactRelayPaginationContainer: Unable to infer direction of the ' +
      'connection, possibly because both first and last are provided.',
  );

  const getFragmentVariables =
    connectionConfig.getFragmentVariables ||
    createGetFragmentVariables(metadata);

  return class extends React.Component<$FlowFixMeProps, ContainerState> {
    // $FlowFixMe[missing-local-annot]
    static displayName = containerName;

    _isARequestInFlight: boolean;
    _refetchSubscription: ?Subscription;
    _refetchVariables: ?Variables;
    _resolver: FragmentSpecResolver;
    _queryFetcher: ?ReactRelayQueryFetcher;
    _isUnmounted: boolean;
    _hasFetched: boolean;

    constructor(props: any) {
      super(props);
      const relayContext = assertRelayContext(props.__relayContext);
      const rootIsQueryRenderer = props.__rootIsQueryRenderer ?? false;
      this._isARequestInFlight = false;
      this._refetchSubscription = null;
      this._refetchVariables = null;

      if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {
        this._resolver = createFragmentSpecResolver(
          relayContext,
          containerName,
          fragments,
          props,
          rootIsQueryRenderer,
        );
      } else {
        this._resolver = createFragmentSpecResolver(
          relayContext,
          containerName,
          fragments,
          props,
          rootIsQueryRenderer,
          this._handleFragmentDataUpdate,
        );
      }
      this.state = {
        data: this._resolver.resolve(),
        prevContext: relayContext,
        contextForChildren: relayContext,
        relayProp: this._buildRelayProp(relayContext),
        resolverGeneration: 0,
      };
      this._isUnmounted = false;
      this._hasFetched = false;
    }

    componentDidMount() {
      this._isUnmounted = false;
      if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {
        this._subscribeToNewResolverAndRerenderIfStoreHasChanged();
      }
    }

    componentDidUpdate(prevProps: Props, prevState: ContainerState) {
      if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {
        if (prevState.resolverGeneration !== this.state.resolverGeneration) {
          this._subscribeToNewResolverAndRerenderIfStoreHasChanged();
        } else {
          this._rerenderIfStoreHasChanged();
        }
      }
    }

    /**
     * When new props are received, read data for the new props and subscribe
     * for updates. Props may be the same in which case previous data and
     * subscriptions can be reused.
     */
    UNSAFE_componentWillReceiveProps(nextProps: any) {
      const relayContext = assertRelayContext(nextProps.__relayContext);
      const rootIsQueryRenderer = nextProps.__rootIsQueryRenderer ?? false;
      const prevIDs = getDataIDsFromObject(fragments, this.props);
      const nextIDs = getDataIDsFromObject(fragments, nextProps);
      const prevRootVariables = getRootVariablesForFragments(
        fragments,
        this.props,
      );
      const nextRootVariables = getRootVariablesForFragments(
        fragments,
        nextProps,
      );

      // If the environment has changed or props point to new records then
      // previously fetched data and any pending fetches no longer apply:
      // - Existing references are on the old environment.
      // - Existing references are based on old variables.
      // - Pending fetches are for the previous records.
      if (
        relayContext.environment !== this.state.prevContext.environment ||
        !areEqual(prevRootVariables, nextRootVariables) ||
        !areEqual(prevIDs, nextIDs)
      ) {
        this._cleanup();
        // Child containers rely on context.relay being mutated (for gDSFP).
        if (RelayFeatureFlags.ENABLE_CONTAINERS_SUBSCRIBE_ON_COMMIT === true) {
          this._resolver = createFragmentSpecResolver(
            relayContext,
            containerName,
            fragments,
            nextProps,
            rootIsQueryRenderer,
          );
        } else {
          this._resolver = createFragmentSpecResolver(
            relayContext,
            containerName,
            fragments,
            nextProps,
            rootIsQueryRenderer,
            this._handleFragmentDataUpdate,
          );
        }
        this.setState(prevState => ({
          prevContext: relayContext,
          contextForChildren: relayContext,
          relayProp: this._buildRelayProp(relayContext),
          resolverGeneration: prevState.resolverGeneration + 1,
        }));
      } else if (!this._hasFetched) {
        this._resolver.setProps(nextProps);
      }
      const data = this._resolver.resolve();
      if (data !== this.state.data) {
        this.setState({data});
      }
    }

    componentWillUnmount() {
      this._isUnmounted = true;
      this._cleanup();
    }

    shouldComponentUpdate(
      nextProps: Props,
      nextState: ContainerState,
    ): boolean {
      // Short-circuit if any Relay-related data has changed
      if (
        nextState.data !== this.state.data ||
        nextState.relayProp !== this.state.relayProp ||
        nextState.resolverGeneration !== this.state.resolverGeneration
      ) {
        return true;
      }
      // Otherwise, for convenience short-circuit if all non-Relay props
      // are scalar and equal
      const keys = Object.keys(nextProps);
      for (let ii = 0; ii < keys.length; ii++) {
        const key = keys[ii];
        if (key === '__relayContext') {
          if (
            nextState.prevContext.environment !==
            this.state.prevContext.environment
          ) {
            return true;
          }
        } else {
          if (
            !fragments.hasOwnProperty(key) &&
            !isScalarAndEqual(nextProps[key], this.props[key])
          ) {
            return true;
          }
        }
      }
      return false;
    }

    _buildRelayProp(relayContext: RelayContext): RelayPaginationProp {
      return {
        hasMore: this._hasMore,
        isLoading: this._isLoading,
        loadMore: this._loadMore,
        refetchConnection: this._refetchConnection,
        environment: relayContext.environment,
      };
    }

    _rerenderIfStoreHasChanged() {
      const {data} = this.state;
      // External values could change between render and commit.
      // Check for this case, even though it requires an extra store read.
      const maybeNewData = this._resolver.resolve();
      if (data !== maybeNewData) {
        this.setState({data: maybeNewData});
      }
    }

    _subscribeToNewResolverAndRerenderIfStoreHasChanged() {
      const {data} = this.state;
      const maybeNewData = this._resolver.resolve();

      // Event listeners are only safe to add during the commit phase,
      // So they won't leak if render is interrupted or errors.
      this._resolver.setCallback(this.props, this._handleFragmentDataUpdate);

      // External values could change between render and commit.
      // Check for this case, even though it requires an extra store read.
      if (data !== maybeNewData) {
        this.setState({data: maybeNewData});
      }
    }

    /**
     * Render new data for the existing props/context.
     */
    _handleFragmentDataUpdate = () => {
      this.setState({data: this._resolver.resolve()});
    };

    _getConnectionData(): ?{
      cursor: ?string,
      edgeCount: number,
      hasMore: boolean,
      ...
    } {
      // Extract connection data and verify there are more edges to fetch
      // eslint-disable-next-line no-unused-vars
      const {componentRef: _, ...restProps} = this.props;
      const props = {
        ...restProps,
        ...this.state.data,
      };
      const connectionData = getConnectionFromProps(props);
      if (connectionData == null) {
        return null;
      }
      const {
        EDGES,
        PAGE_INFO,
        HAS_NEXT_PAGE,
        HAS_PREV_PAGE,
        END_CURSOR,
        START_CURSOR,
      } = ConnectionInterface.get();

      invariant(
        typeof connectionData === 'object',
        'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
          'to return `null` or a plain object with %s and %s properties, got `%s`.',
        componentName,
        EDGES,
        PAGE_INFO,
        connectionData,
      );
      const edges = connectionData[EDGES];
      const pageInfo = connectionData[PAGE_INFO];
      if (edges == null || pageInfo == null) {
        return null;
      }
      invariant(
        Array.isArray(edges),
        'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
          'to return an object with %s: Array, got `%s`.',
        componentName,
        EDGES,
        edges,
      );
      invariant(
        typeof pageInfo === 'object',
        'ReactRelayPaginationContainer: Expected `getConnectionFromProps()` in `%s`' +
          'to return an object with %s: Object, got `%s`.',
        componentName,
        PAGE_INFO,
        pageInfo,
      );
      const hasMore =
        direction === FORWARD
          ? pageInfo[HAS_NEXT_PAGE]
          : pageInfo[HAS_PREV_PAGE];
      const cursor =
        direction === FORWARD ? pageInfo[END_CURSOR] : pageInfo[START_CURSOR];
      if (
        typeof hasMore !== 'boolean' ||
        (edges.length !== 0 && typeof cursor === 'undefined')
      ) {
        warning(
          false,
          'ReactRelayPaginationContainer: Cannot paginate without %s fields in `%s`. ' +
            'Be sure to fetch %s (got `%s`) and %s (got `%s`).',
          PAGE_INFO,
          componentName,
          direction === FORWARD ? HAS_NEXT_PAGE : HAS_PREV_PAGE,
          hasMore,
          direction === FORWARD ? END_CURSOR : START_CURSOR,
          cursor,
        );
        return null;
      }
      return {
        cursor,
        edgeCount: edges.length,
        hasMore,
      };
    }

    _hasMore = (): boolean => {
      const connectionData = this._getConnectionData();
      return !!(
        connectionData &&
        connectionData.hasMore &&
        connectionData.cursor
      );
    };

    _isLoading = (): boolean => {
      return !!this._refetchSubscription;
    };

    _refetchConnection = (
      totalCount: number,
      observerOrCallback: ?ObserverOrCallback,
      refetchVariables: ?Variables,
    ): Disposable => {
      if (!this._canFetchPage('refetchConnection')) {
        return {
          dispose() {},
        };
      }
      this._refetchVariables = refetchVariables;
      const paginatingVariables = {
        count: totalCount,
        cursor: null,
        totalCount,
      };
      const fetch = this._fetchPage(
        paginatingVariables,
        toObserver(observerOrCallback),
        {force: true},
      );

      return {dispose: fetch.unsubscribe};
    };

    _loadMore = (
      pageSize: number,
      observerOrCallback: ?ObserverOrCallback,
      options: ?RefetchOptions,
    ): ?Disposable => {
      if (!this._canFetchPage('loadMore')) {
        return {
          dispose() {},
        };
      }

      const observer = toObserver(observerOrCallback);
      const connectionData = this._getConnectionData();
      if (!connectionData) {
        Observable.create<empty>(sink => sink.complete()).subscribe(observer);
        return null;
      }
      const totalCount = connectionData.edgeCount + pageSize;
      if (options && options.force) {
        return this._refetchConnection(totalCount, observerOrCallback);
      }
      const {END_CURSOR, START_CURSOR} = ConnectionInterface.get();
      const cursor = connectionData.cursor;
      warning(
        cursor != null && cursor !== '',
        'ReactRelayPaginationContainer: Cannot `loadMore` without valid `%s` (got `%s`)',
        direction === FORWARD ? END_CURSOR : START_CURSOR,
        cursor,
      );
      const paginatingVariables = {
        count: pageSize,
        cursor: cursor,
        totalCount,
      };
      const fetch = this._fetchPage(paginatingVariables, observer, options);
      return {dispose: fetch.unsubscribe};
    };

    _getQueryFetcher(): ReactRelayQueryFetcher {
      if (!this._queryFetcher) {
        this._queryFetcher = new ReactRelayQueryFetcher();
      }
      return this._queryFetcher;
    }

    _canFetchPage(method: 'loadMore' | 'refetchConnection'): boolean {
      if (this._isUnmounted) {
        warning(
          false,
          'ReactRelayPaginationContainer: Unexpected call of `%s` ' +
            'on unmounted container `%s`. It looks like some instances ' +
            'of your container still trying to fetch data but they already ' +
            'unmounted. Please make sure you clear all timers, intervals, async ' +
            'calls, etc that may trigger `%s` call.',
          method,
          containerName,
          method,
        );
        return false;
      }
      return true;
    }

    _fetchPage(
      paginatingVariables: {
        count: number,
        cursor: ?string,
        totalCount: number,
        ...
      },
      observer: Observer<void>,
      options: ?RefetchOptions,
    ): Subscription {
      const {environment} = assertRelayContext(this.props.__relayContext);
      const {
        // eslint-disable-next-line no-unused-vars
        componentRef: _,
        // eslint-disable-next-line no-unused-vars
        __relayContext,
        // eslint-disable-next-line no-unused-vars
        __rootIsQueryRenderer,
        ...restProps
      } = this.props;
      const props = {
        ...restProps,
        ...this.state.data,
      };
      let fragmentVariables: Variables;
      const rootVariables = getRootVariablesForFragments(fragments, restProps);
      fragmentVariables = getVariablesFromObject(fragments, restProps);
      fragmentVariables = {
        ...rootVariables,
        ...fragmentVariables,
        ...this._refetchVariables,
      };
      let fetchVariables: Variables = connectionConfig.getVariables(
        props,
        {
          count: paginatingVariables.count,
          cursor: paginatingVariables.cursor,
        },
        fragmentVariables,
      );
      invariant(
        typeof fetchVariables === 'object' && fetchVariables !== null,
        'ReactRelayPaginationContainer: Expected `getVariables()` to ' +
          'return an object, got `%s` in `%s`.',
        fetchVariables,
        componentName,
      );
      fetchVariables = ({
        ...fetchVariables,
        ...this._refetchVariables,
      }: Variables);
      fragmentVariables = ({
        ...fetchVariables,
        ...fragmentVariables,
      }: Variables);

      const cacheConfig: ?CacheConfig = options
        ? {force: !!options.force}
        : undefined;
      if (cacheConfig != null && options?.metadata != null) {
        cacheConfig.metadata = options?.metadata;
      }
      const request = getRequest(connectionConfig.query);
      const operation = createOperationDescriptor(
        request,
        fetchVariables,
        cacheConfig,
      );

      let refetchSubscription = null;

      if (this._refetchSubscription) {
        this._refetchSubscription.unsubscribe();
      }
      this._hasFetched = true;

      const onNext = (payload: mixed, complete: () => void) => {
        const prevData = this._resolver.resolve();
        this._resolver.setVariables(
          getFragmentVariables(
            fragmentVariables,
            paginatingVariables.totalCount,
          ),
          operation.request.node,
        );
        const nextData = this._resolver.resolve();

        // Workaround slightly different handling for connection in different
        // core implementations:
        // - Classic core requires the count to be explicitly incremented
        // - Modern core automatically appends new items, updating the count
        //   isn't required to see new data.
        //
        // `setState` is only required if changing the variables would change the
        // resolved data.
        // TODO #14894725: remove PaginationContainer equal check
        if (!areEqual(prevData, nextData)) {
          this.setState(
            {
              data: nextData,
              contextForChildren: {
                environment: this.props.__relayContext.environment,
              },
            },
            complete,
          );
        } else {
          complete();
        }
      };

      const cleanup = () => {
        if (this._refetchSubscription === refetchSubscription) {
          this._refetchSubscription = null;
          this._isARequestInFlight = false;
        }
      };

      this._isARequestInFlight = true;
      refetchSubscription = this._getQueryFetcher()
        .execute({
          environment,
          operation,
          preservePreviousReferences: true,
        })
        .mergeMap<void>(payload =>
          Observable.create<void>((sink: Sink<void>) => {
            onNext(payload, () => {
              sink.next(); // pass void to public observer's `next`
              sink.complete();
            });
          }),
        )
        // use do instead of finally so that observer's `complete` fires after cleanup
        .do({
          error: cleanup,
          complete: cleanup,
          unsubscribe: cleanup,
        })
        .subscribe(observer || {});

      this._refetchSubscription = this._isARequestInFlight
        ? refetchSubscription
        : null;

      return refetchSubscription;
    }

    _cleanup() {
      this._resolver.dispose();
      this._refetchVariables = null;
      this._hasFetched = false;
      if (this._refetchSubscription) {
        this._refetchSubscription.unsubscribe();
        this._refetchSubscription = null;
        this._isARequestInFlight = false;
      }
      if (this._queryFetcher) {
        this._queryFetcher.dispose();
      }
    }

    // $FlowFixMe[missing-local-annot]
    render() {
      // eslint-disable-next-line no-unused-vars
      const {componentRef, __relayContext, __rootIsQueryRenderer, ...props} =
        this.props;
      return (
        <ReactRelayContext.Provider value={this.state.contextForChildren}>
          <Component
            {...props}
            {...this.state.data}
            ref={componentRef}
            relay={this.state.relayProp}
          />
        </ReactRelayContext.Provider>
      );
    }
  };
}

/**
 * Wrap the basic `createContainer()` function with logic to adapt to the
 * `context.relay.environment` in which it is rendered. Specifically, the
 * extraction of the environment-specific version of fragments in the
 * `fragmentSpec` is memoized once per environment, rather than once per
 * instance of the container constructed/rendered.
 */
function createContainer<Props: {...}, TComponent: React.ComponentType<Props>>(
  Component: TComponent,
  fragmentSpec: GeneratedNodeMap,
  connectionConfig: ConnectionConfig,
): React.ComponentType<
  $RelayProps<React$ElementConfig<TComponent>, RelayPaginationProp>,
> {
  // $FlowFixMe[incompatible-return]
  return buildReactRelayContainer(
    Component,
    fragmentSpec,
    (ComponentClass, fragments) =>
      createContainerWithFragments(ComponentClass, fragments, connectionConfig),
  );
}

module.exports = {
  createContainer,
};


text:
/*
 * This file is part of the \BlueLaTeX project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gnieh.blue
package http
package impl

import tiscaf._

import org.osgi.framework._
import org.osgi.util.tracker.ServiceTracker

import scala.collection.mutable.Map

/** Tracks the `RestHandler` services that are (un)registered to dynamically extend
 *  the server interface
 *
 *  @author Lucas Satabin
 */
class RestServiceTracker(context: BundleContext, app: ExtensibleApp)
  extends ServiceTracker[RestApi, Long](context, classOf[RestApi], null) {

  override def addingService(ref: ServiceReference[RestApi]): Long = {
    // get the service instance
    val service = context.getService(ref)
    // get the servive identifier
    val id = ref.getProperty(Constants.SERVICE_ID).asInstanceOf[Long]
    app.synchronized {
      // register the rest interface with the generated identifier
      app.apps(id) = service
    }
    id
  }

  override def removedService(ref: ServiceReference[RestApi], id: Long): Unit = app.synchronized {
    // unregister the handlers for the given identifier
    app.apps -= id
  }

}


text:
<?php

if ( ! defined('BASEPATH'))
{
    exit('No direct script access allowed');
}

/**
 * Http_auth class
 *
 * Handles http authentication check.
 *
 * @package     Project
 * @subpackage  Application
 * @category    Libraries
 * @author      Author
 * @link        void
 */
class Http_auth {
    public $CI;
    public $username;
    public $password;
    public $realm;

    public function __construct($config)
    {
        // Initialize the username and password against which authentication
        // check is to be done.
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->realm = isset($config['realm']) ? $config['realm'] : 'Restricted area';
        $this->CI = & get_instance();
    }

    /**
     * Authenticates user.
     *
     * @access public
     * @param  void
     * @return void
     */
    public function authenticate()
    {
        $php_auth_digest = $this->CI->input->server('PHP_AUTH_DIGEST');

        if ( ! $php_auth_digest

            // Analyze the PHP_AUTH_DIGEST variable.
            || ! ($data = $this->_http_digest_parse()) || $this->username !== $data['username']

            // Validate auth data.
            || ! $this->_validate_auth_response($data))
        {
            $this->_send_authentication_headers();
        }
    }

    /**
     * Validates authentication info entered.
     *
     * @access private
     * @param  array $data
     * @return bool
     */
    private function _validate_auth_response($data)
    {
        // Generate the valid response.
        $A1 = md5($data['username'] . ':' . $this->realm . ':' . $this->password);
        $A2 = md5($this->CI->input->server('REQUEST_METHOD') . ':' . $data['uri']);
        $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc']
            . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2);

        return ($data['response'] !== $valid_response) ? FALSE : TRUE;
    }

    /**
     * Send authentication headers to display authenticaltion dialog.
     *
     * @access private
     * @param  void
     * @return void
     */
    private function _send_authentication_headers()
    {
        header('HTTP/1.1 401 Unauthorized');
        header('WWW-Authenticate: Digest realm="' . $this->realm . '",qop="auth",nonce="'
            . uniqid() . '",opaque="' . md5($this->realm) . '"');

        // Control comes to below part if cancel button is clicked.
        exit('Cancel action selected.');
    }

    /**
     * Function to parse the http auth header.
     *
     * @access private
     * @param  void
     * @return mixed
     */
    private function _http_digest_parse()
    {
        $txt = $this->CI->input->server('PHP_AUTH_DIGEST');

        // Protect against missing data.
        $needed_parts = [
            'nonce' => 1,
            'nc' => 1,
            'cnonce' => 1,
            'qop' => 1,
            'username' => 1,
            'uri' => 1,
            'response' => 1
        ];
        $data = [];
        $keys = implode('|', array_keys($needed_parts));
        preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@',
            $txt, $matches, PREG_SET_ORDER);

        foreach ($matches as $match)
        {
            $data[$match[1]] = $match[3] ? $match[3] : $match[4];
            unset($needed_parts[$match[1]]);
        }

        return $needed_parts ? FALSE : $data;
    }
}

/* End of file Http_auth.php */
/* Location: ./application/libraries/Http_auth.php */


text:
#include "uv.h"
#include "runner.h"

static void connection_cb(uv_stream_t* server, int status) {
  TUV_ASSERT(0 && "this will never be called");
}

TEST_IMPL(pipe_pending_instances) {
  int r;
  uv_pipe_t pipe_handle;
  uv_loop_t* loop;

  loop = uv_default_loop();

  r = uv_pipe_init(loop, &pipe_handle, 0);
  TUV_ASSERT(r == 0);

  uv_pipe_pending_instances(&pipe_handle, 8);

  r = uv_pipe_bind(&pipe_handle, TEST_PIPENAME);
  TUV_ASSERT(r == 0);

  uv_pipe_pending_instances(&pipe_handle, 16);

  r = uv_listen((uv_stream_t*)&pipe_handle, 128, connection_cb);
  TUV_ASSERT(r == 0);

  uv_close((uv_handle_t*)&pipe_handle, NULL);

  r = uv_run(loop, UV_RUN_DEFAULT);
  TUV_ASSERT(r == 0);

  return 0;
}


text:
/*
 * Helper functions for importers.
 */

'use strict';

var _ = require('underscore');

/*
 * Create a Date object from a string representation of a date.
 * The input string must be in the format of "dd.mm.yyyy".
 *
 * Returns a Date object if parsing succeeds, otherwise null.
 */
var parseDate = function (dateStr) {
    if (!dateStr) {
        return null;
    }

    var fields = dateStr.split('.');
    if (fields.length !== 3) {
        return null;
    }

    var day = parseInt(fields[0], 10);
    var month = parseInt(fields[1], 10);
    var year = parseInt(fields[2], 10);

    if (isNaN(day) || isNaN(month) || isNaN(year)) {
        return null;
    }

    return new Date(year, month - 1, day);
};

/*
 * Convert a Date object into a string in the format of "dd/mm/yyyy".
 * Return the resulting string on success, otherwise null.
 */
var dateToString = function (date) {
    if (!(date instanceof Date)) {
        return null;
    }

    var padIfNeeded = function (num) {
        return (num < 10 ? '0' : '') + num;
    };

    return padIfNeeded(date.getDate()) + '/' + padIfNeeded(date.getMonth() + 1) + '/' + date.getFullYear();
};

var parseAmount = function (inputStr) {
    if (typeof(inputStr) !== 'string') {
        return null;
    }

    inputStr = inputStr.replace(/,/, '.').replace(/\s/g, '');

    if (inputStr.match(/^-?\d+\.?\d*$/)) {
        return parseFloat(inputStr);
    }

    return null;
};

module.exports = {
    parseDate: parseDate,
    dateToString: dateToString,
    parseAmount: parseAmount
};


text:
package org.jamocha.function.fwa;

/**
 * @author Fabian Ohler <fabian.ohler1@rwth-aachen.de>
 */
public interface DefaultFunctionWithArgumentsVisitor<L extends ExchangeableLeaf<L>>
        extends FunctionWithArgumentsVisitor<L> {

    void defaultAction(final FunctionWithArguments<L> function);

    @Override
    default void visit(final FunctionWithArgumentsComposite<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final PredicateWithArgumentsComposite<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final ConstantLeaf<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final GlobalVariableLeaf<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final L fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Bind<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Assert<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Assert.TemplateContainer<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Retract<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Modify<L> fwa) {
        defaultAction(fwa);
    }

    @Override
    default void visit(final Modify.SlotAndValue<L> fwa) {
        defaultAction(fwa);
    }
}


text:
/********************************************************************************
 * CSHARP Atom Data Library - General Elements used to work with atom feed data
 *
 * NOTE: Adapted from Clinch.Xml
 *
 * LICENSE: Free to use provided details on fixes and/or extensions emailed to
 *          chris.williams@readwatchcreate.com
 ********************************************************************************/

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using CSHARP.Diagnostics;

namespace CSHARP.Data.Xml.Atom
{
    /// <summary>
    /// ATOM Feed Helper Functions
    /// </summary>
    /// <remarks>NEW in v1.0.0.1</remarks>
    public static class AtomHelper
    {
        /// <summary>
        /// Returns .net dataset friendly xml based on an Atom feed
        /// </summary>
        /// <param name="atomXmlData"></param>
        /// <param name="eventLog"></param>
        /// <returns></returns>
        /// <remarks>Adapted from this forum post: http://social.msdn.microsoft.com/Forums/eu/xmlandnetfx/thread/2aad018f-7af1-41c3-bfa1-8691eed0eb38 </remarks>
        public static String AtomToXml(string atomXmlData, IEventLog eventLog)
        {
            var stringReader = new StringReader(atomXmlData);
            var reader = new XmlTextReader(stringReader) {WhitespaceHandling = WhitespaceHandling.None};
            var builder = new StringBuilder();

            var fContinue = reader.Read();
            while (fContinue)
            {
                var sName = reader.Name.Replace(":", "_");

                var isClosed = reader.IsEmptyElement;
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        builder.Append("<" + sName);
                        if (reader.HasAttributes)
                        {
                            while (reader.MoveToNextAttribute())
                            {
                                sName = reader.Name.Replace(":", "_");
                                builder.Append(" " + sName + "=\"" + reader.Value.Replace("&", "&") + "\"");
                            }
                        }
                        if (isClosed)
                            builder.Append("/");
                        builder.Append(">");
                        break;
                    case XmlNodeType.Text:
                        builder.Append(HttpUtility.HtmlEncode(reader.Value));
                        break;
                    case XmlNodeType.EndElement:
                        builder.Append("</" + sName + ">");
                        break;
                }

                fContinue = reader.Read();
            }

            stringReader.Close();
            stringReader.Dispose();

            reader.Close();

            var sXmlResult = "<atom>" + builder + "</atom>";

            var dataSet = new DataSet();
            var oStringReader = new StringReader(sXmlResult);
            try
            {
                dataSet.ReadXml(oStringReader, XmlReadMode.Auto);
            }
            catch (Exception exception)
            {
                if (eventLog != null) eventLog.LogEvent(0, "ERROR Converting Atom To Xml - " + exception);
            }

            oStringReader.Close();
            oStringReader.Dispose();
            reader.Close();
            return dataSet.Tables.Count == 0 ? null : dataSet.GetXml();
        }
   }
}


text:
package entrenadores;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import pokemon.Pokemon;

/**
 *
 * @author Javier Beltran, Jorge Cancer, Alejandro Dieste
 *
 * La clase representa a un jugador. Un jugador es un entrenador
 * controlable por el usuario, que tiene todas las caracteristicas
 * de un entrenador y tambien una lista de medallas obtenidas y
 * acceso a su mochila.
 *
 */
public class Jugador extends Entrenador implements Serializable {

	private static final long serialVersionUID = 3568306953866442225L;

	private List<Medalla> medallas;

	/**
	 *
	 * Crea un Jugador con un nombre y un genero. Un jugador
	 * solo sera creado al inicio de la partida o al cargar una
	 * partida existente.
	 *
	 * @param nombre el nombre del jugador.
	 * @param esHombre true, si es hombre; false, si es mujer.
	 */
	public Jugador(String nombre, boolean esHombre) {
		this.setNombre(nombre);
		this.setHombre(esHombre);
		setMedallas(new ArrayList<Medalla>());
		setEquipo(new ArrayList<Pokemon>());
	}

	public List<Medalla> getMedallas() {
		return medallas;
	}

	public void setMedallas(List<Medalla> medallas) {
		this.medallas = medallas;
	}

	public void addMedalla(Medalla medalla) {
		medallas.add(medalla);
	}

	public static Jugador nuevoJugador(Jugador jugador){
		Jugador aux=new Jugador(jugador.getNombre(),jugador.isHombre());
		aux.setMedallas(jugador.getMedallas());
		aux.setEquipo(jugador.getEquipo());
		return aux;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="list_default_height">48dp</dimen>
    <dimen name="nav_header_vertical_spacing">8dp</dimen>
    <dimen name="nav_header_height">176dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
</resources>


text:
<?php

namespace Symfony\Component\Intl;

use Symfony\Component\Intl\Exception\MissingResourceException;

/**
 * Gives access to locale-related ICU data.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 * @author Roland Franssen <franssen.roland@gmail.com>
 */
final class Locales extends ResourceBundle
{
    /**
     * @return string[]
     */
    public static function getLocales(): array
    {
        return self::readEntry(['Locales'], 'meta');
    }

    /**
     * @return string[]
     */
    public static function getAliases(): array
    {
        return self::readEntry(['Aliases'], 'meta');
    }

    public static function exists(string $locale): bool
    {
        try {
            self::readEntry(['Names', $locale]);

            return true;
        } catch (MissingResourceException $e) {
            return \in_array($locale, self::getAliases(), true);
        }
    }

    /**
     * @throws MissingResourceException if the locale does not exists
     */
    public static function getName(string $locale, string $displayLocale = null): string
    {
        try {
            return self::readEntry(['Names', $locale], $displayLocale);
        } catch (MissingResourceException $e) {
            if (false === $aliased = array_search($locale, self::getAliases(), true)) {
                throw $e;
            }

            return self::readEntry(['Names', $aliased], $displayLocale);
        }
    }

    /**
     * @return string[]
     */
    public static function getNames($displayLocale = null): array
    {
        return self::asort(self::readEntry(['Names'], $displayLocale), $displayLocale);
    }

    protected static function getPath(): string
    {
        return Intl::getDataDirectory().'/'.Intl::LOCALE_DIR;
    }
}


text:
#import "SAAceSerializable-Protocol.h"

@class NSString;

@protocol SAGKStructuredAnswer <SAAceSerializable>
@property(copy, nonatomic) NSString *category;
@end