hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
6574d923f3f576593c81204b954b1d4916ef2e9e
| 940
|
package io.palyvos.provenance.ananke.functions;
import io.palyvos.provenance.util.TimestampedUIDTuple;
import io.palyvos.provenance.genealog.GenealogTupleType;
import io.palyvos.provenance.util.UIDAssigner;
import org.apache.flink.api.common.functions.MapFunction;
/**
* ProvenanceInitializer for cases where source tuples already implement {@link TimestampedUIDTuple}.
* <b>WARNING:</b> Applied after the tuples have been assigned a UID using a {@link UIDAssigner}.
* <b>WARNING:</b> Will not work if first provenance node is aggregate!
* @param <T> The type of source tuples.
*/
public class ProvenanceInitializerAssisted<T extends TimestampedUIDTuple>
implements MapFunction<T, ProvenanceTupleContainer<T>> {
@Override
public ProvenanceTupleContainer<T> map(T value) {
ProvenanceTupleContainer<T> out = new ProvenanceTupleContainer<>(value);
out.initGenealog(GenealogTupleType.META_SOURCE);
return out;
}
}
| 39.166667
| 101
| 0.784043
|
3dfb6389a48ab213b59b1d61b1777c75790be17b
| 779
|
package util.study.collection;/**
* @version: java version 1.7+
* @Author : mzp
* @Time : 2020/5/28 10:19
* @File : MyGeneric
* @Software: IntelliJ IDEA 2019.3.15
*/
import java.util.ArrayList;
import java.util.List;
/**
* 自定义泛型类:在类名后加上<T>, 不确定是什么类型,就用T做通配符
* <T> 中类型的字母可以随便写,但习惯上 T:Type E:Element K: Key V:Value R:Return
* @Description:
* @Author maozp3
* @Date: 2020/5/28 10:19
*/
public class MyGeneric<T> {
private T value;
private List<T> list = new ArrayList<>();
public void addList(T t){
this.value = t;
this.list.add(this.value);
}
public T getValue(){
return value;
}
public List<T> getList(){
return this.list;
}
public void update(int id,T t){
// ...
}
}
| 19
| 77
| 0.584082
|
e32eaf2e0d82f8f7126b0e7ec6c2086a981845f9
| 1,498
|
package cn.hutool.core.bean.copier;
import cn.hutool.core.util.TypeUtil;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Map属性拷贝到Map中的拷贝器
*
* @since 5.8.0
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class MapToMapCopier extends AbsCopier<Map, Map> {
/**
* 目标的类型(用于泛型类注入)
*/
private final Type targetType;
/**
* 构造
*
* @param source 来源Map
* @param target 目标Bean对象
* @param targetType 目标泛型类型
* @param copyOptions 拷贝选项
*/
public MapToMapCopier(Map source, Map target, Type targetType, CopyOptions copyOptions) {
super(source, target, copyOptions);
this.targetType = targetType;
}
@Override
public Map copy() {
this.source.forEach((sKey, sValue) -> {
if (null == sKey) {
return;
}
final String sKeyStr = copyOptions.editFieldName(sKey.toString());
// 对key做转换,转换后为null的跳过
if (null == sKeyStr) {
return;
}
final Object targetValue = target.get(sKeyStr);
// 非覆盖模式下,如果目标值存在,则跳过
if (false == copyOptions.override && null != targetValue) {
return;
}
// 获取目标值真实类型并转换源值
final Type[] typeArguments = TypeUtil.getTypeArguments(this.targetType);
if(null != typeArguments){
//sValue = Convert.convertWithCheck(typeArguments[1], sValue, null, this.copyOptions.ignoreError);
sValue = this.copyOptions.convertField(typeArguments[1], sValue);
sValue = copyOptions.editFieldValue(sKeyStr, sValue);
}
// 目标赋值
target.put(sKeyStr, sValue);
});
return this.target;
}
}
| 22.69697
| 102
| 0.676903
|
4bef041ef3587ac7d8ab95f31f2ddcdebfc3ba12
| 4,618
|
package com.weique.commonres.utils.globalutils;
import android.content.Context;
import android.os.Build;
import com.blankj.utilcode.util.ObjectUtils;
import com.google.gson.Gson;
import com.jess.arms.utils.ArmsUtils;
import com.weique.commonres.constans.Constants;
import com.weique.commonres.core.RouterHub;
import com.weique.commonres.utils.BaseSingleton;
import com.weique.commonres.utils.commonutils.ACache;
import com.weique.commonres.utils.commonutils.ARouterUtils;
import com.weique.commonservice.zongzhi.bean.UserInfoBean;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
/**
* @author GK
* @description: 用户信息管理
* @date :2020/6/8 14:13
*/
public class UserInfoUtils extends BaseSingleton {
/**
* 用户信息缓存KEY
*/
private static final String USER_INFO = "USER_INFO";
/**
* 实例化
*/
public static UserInfoUtils getInstance() {
return getSingleton(UserInfoUtils.class);
}
/**
* 存储用户信息
*
* @param userInfoBean userInfoBean
*/
public void saveUserInfo(UserInfoBean userInfoBean) {
try {
if (userInfoBean == null) {
return;
}
Constants.userinfo = userInfoBean;
ACache aCache = ACache.getUserInfo();
//登录成功刷新我的页面余额
aCache.put(USER_INFO, new Gson().toJson(userInfoBean));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查询
*
* @return GlobalUserInfoBean
*/
public UserInfoBean getUserInfo() {
if (Constants.userinfo != null) {
return Constants.userinfo;
}
Constants.userinfo = null;
try {
ACache aCache = ACache.getUserInfo();
//登录成功刷新我的页面余额
String userInfo = aCache.getAsString(USER_INFO);
Constants.userinfo = new Gson().fromJson(userInfo, UserInfoBean.class);
} catch (Exception e) {
e.printStackTrace();
}
return Constants.userinfo;
}
/**
* 退出登录以后删除用户信息
*/
public void loginOut() {
Constants.userinfo = null;
ACache aCache = ACache.getUserInfo();
aCache.clear();
}
/**
* 历史搜索key
*/
public static final String HISTORY_SEARCH_KEY = "HISTORY_SEARCH_KEY";
public static List<String> getSearchKeywordList() {
List<String> list = new ArrayList<>();
try {
ACache aCache = ACache.getPartySearchRecord();
JSONArray asJSONArray = aCache.getAsJSONArray(HISTORY_SEARCH_KEY);
if (asJSONArray == null) {
aCache.put(HISTORY_SEARCH_KEY, new JSONArray());
}
if (asJSONArray != null) {
//去除相同的 字
for (int i = asJSONArray.length() - 1; i >= 0; i--) {
list.add((String) asJSONArray.get(i));
}
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 添加一个搜索关键字
*
* @param keyword keyword
*/
public static void addSearchKeyword(String keyword) {
try {
if (ObjectUtils.isEmpty(keyword)) {
return;
}
ACache aCache = ACache.getPartySearchRecord();
JSONArray hitoryArray = aCache.getAsJSONArray(HISTORY_SEARCH_KEY);
if (hitoryArray == null) {
aCache.put(HISTORY_SEARCH_KEY, new JSONArray());
} else {
if (hitoryArray.length() > 10) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
hitoryArray.remove(hitoryArray.length() - 1);
}
}
//去除相同的 字
for (int i = 0; i < hitoryArray.length(); i++) {
if (keyword.equals(hitoryArray.get(i))) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
hitoryArray.remove(i);
}
break;
}
}
hitoryArray.put(keyword);
}
aCache.put(HISTORY_SEARCH_KEY, hitoryArray);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void cleanSearchKeyword() {
try {
ACache aCache = ACache.getPartySearchRecord();
aCache.remove(HISTORY_SEARCH_KEY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 27.987879
| 83
| 0.54634
|
32460f59a8e9a2a5bfaaa94ffac0d907a8f9c1af
| 1,662
|
/*
* Copyright 2017-2020 original authors
*
* 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
*
* https://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 io.micronaut.servlet.http;
import io.micronaut.core.annotation.AnnotationMetadata;
import io.micronaut.core.annotation.Indexed;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.MutableHttpResponse;
import org.reactivestreams.Publisher;
/**
* An interface for custom encoding of the HTTP response.
*
* @author graemerocher
* @since 1.0.0
* @param <T> The response type
*/
@Indexed(ServletResponseEncoder.class)
public interface ServletResponseEncoder<T> {
/**
* @return The response type.
*/
Class<T> getResponseType();
/**
* Encode the given value.
* @param exchange The change
* @param annotationMetadata The annotation metadata declared on the method
* @param value The value to encode
* @return A publisher that emits completes with the response once the value has been encoded
*/
Publisher<MutableHttpResponse<?>> encode(
@NonNull ServletExchange<?, ?> exchange,
AnnotationMetadata annotationMetadata,
@NonNull T value);
}
| 31.358491
| 97
| 0.722022
|
6b3e34d303cd8e6471b4a302ba163c7880b8e381
| 788
|
package buoy.xml.delegate;
import buoy.widget.*;
import java.beans.*;
/**
* This class is a PersistenceDelegate for serializing BSplitPanes.
*
* @author Peter Eastman
*/
public class BSplitPaneDelegate extends EventSourceDelegate
{
/**
* Create a BSplitPaneDelegate.
*/
public BSplitPaneDelegate()
{
}
protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out)
{
super.initialize(type, oldInstance, newInstance, out);
BSplitPane old = (BSplitPane) oldInstance;
if (old.getChildCount() != ((BSplitPane) newInstance).getChildCount())
for (int i = 0; i < old.getChildCount(); i++)
out.writeStatement(new Statement(oldInstance, "add", new Object [] {
old.getChild(i), new Integer(i)}));
}
}
| 24.625
| 92
| 0.682741
|
14ff59a820891be8f7d222269cddce4bf106de05
| 4,982
|
package com.iotechn.unimall.app.api.vip;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dobbinsoft.fw.core.exception.AppServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.core.util.GeneratorUtil;
import com.dobbinsoft.fw.pay.enums.PayChannelType;
import com.dobbinsoft.fw.pay.enums.PayPlatformType;
import com.dobbinsoft.fw.pay.exception.MatrixPayException;
import com.dobbinsoft.fw.pay.model.request.MatrixPayUnifiedOrderRequest;
import com.dobbinsoft.fw.pay.service.pay.MatrixPayService;
import com.dobbinsoft.fw.support.component.MachineComponent;
import com.dobbinsoft.fw.support.model.Page;
import com.dobbinsoft.fw.support.properties.FwWxPayProperties;
import com.dobbinsoft.fw.support.service.BaseService;
import com.iotechn.unimall.biz.util.PaySelector;
import com.iotechn.unimall.data.domain.VipOrderDO;
import com.iotechn.unimall.data.domain.VipTemplateDO;
import com.iotechn.unimall.data.dto.AdminDTO;
import com.iotechn.unimall.data.dto.UserDTO;
import com.iotechn.unimall.data.enums.VipOrderStatusType;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.VipOrderMapper;
import com.iotechn.unimall.data.mapper.VipTemplateMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class VipOrderServiceImpl extends BaseService<UserDTO, AdminDTO> implements VipOrderService {
@Autowired
private VipTemplateMapper templateMapper;
@Autowired
private VipOrderMapper vipOrderMapper;
@Autowired
private MatrixPayService matrixPayService;
@Autowired
private FwWxPayProperties fwWxPayProperties;
@Autowired
private MachineComponent machineComponent;
@Value("${com.dobbinsoft.fw.env}")
private String ENV;
@Autowired
private PaySelector paySelector;
private static final Logger logger = LoggerFactory.getLogger(VipOrderServiceImpl.class);
@Override
@Transactional(rollbackFor = Exception.class)
public Object prepay(Integer payPlatform, String payChannel, Long templateId, String ip, Long userId) throws ServiceException {
VipTemplateDO vipTemplateDO = templateMapper.selectById(templateId);
if (vipTemplateDO == null || 1 != vipTemplateDO.getDisplay().intValue()) {
throw new AppServiceException(ExceptionDefinition.VIP_TEMPLATE_NULL_OR_NOT_DISPLAY);
}
String orderNo = GeneratorUtil.genOrderId(this.machineComponent.getMachineNo() + "", this.ENV);
VipOrderDO vipOrderDO = new VipOrderDO();
vipOrderDO.setDayNum(vipTemplateDO.getDayNum());
vipOrderDO.setPrice(vipTemplateDO.getPrice());
vipOrderDO.setStatus(VipOrderStatusType.WAIT_BUY.getCode());
vipOrderDO.setTemplateId(vipTemplateDO.getId());
vipOrderDO.setOrderNo(orderNo);
vipOrderDO.setUserId(userId);
vipOrderDO.setTitle(vipTemplateDO.getTitle());
vipOrderDO.setDescription(vipTemplateDO.getDescription());
vipOrderMapper.insert(vipOrderDO);
try {
// 前端来决定支付方式
MatrixPayUnifiedOrderRequest orderRequest = new MatrixPayUnifiedOrderRequest();
paySelector.packPayChannel(orderRequest, payPlatform, payChannel);
orderRequest.setNotifyUrl(fwWxPayProperties.getNotifyUrl() + "/vip");
// 区分回调 直接通过 S 来判断
orderRequest.setOutTradeNo(orderNo);
orderRequest.setOpenid(sessionUtil.getUser().getWxMpOpenId());
orderRequest.setBody("vip_" + orderNo);
orderRequest.setTotalFee(vipOrderDO.getPrice());
orderRequest.setSpbillCreateIp(ip);
orderRequest.setPayPlatform(PayPlatformType.getByCode(payPlatform));
orderRequest.setPayChannel(PayChannelType.getByCode(payChannel));
Object object = matrixPayService.createOrder(orderRequest);
return object;
} catch (MatrixPayException e) {
logger.error("[Matrix支付] 异常", e);
throw new AppServiceException(e.getErrCodeDes(), ExceptionDefinition.THIRD_PART_SERVICE_EXCEPTION.getCode());
} catch (Exception e) {
logger.error("[预付款异常]", e);
throw new AppServiceException(ExceptionDefinition.ORDER_UNKNOWN_EXCEPTION);
}
}
@Override
public Page<VipOrderDO> queryVipOrder(Integer status, Integer pageNo, Integer limit, Long userId) throws ServiceException {
QueryWrapper<VipOrderDO> wrapper = new QueryWrapper<>();
wrapper.eq("user_id", userId);
if (status != null) {
wrapper.eq("status", status);
}
return vipOrderMapper.selectPage(Page.div(pageNo, limit, VipOrderDO.class), wrapper);
}
}
| 44.882883
| 131
| 0.746086
|
33cef3d393c5d63b0ac45e3ed9e7c91262f6d150
| 964
|
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* CRPaymentInitiationTransactionInitiateInputModelPaymentInitiationTransactionInstanceRecordPaymentTransactionDocumentReference
*/
public class CRPaymentInitiationTransactionInitiateInputModelPaymentInitiationTransactionInstanceRecordPaymentTransactionDocumentReference {
private Object documentRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The copy of the identification document used
* @return documentRecord
**/
public Object getDocumentRecord() {
return documentRecord;
}
public void setDocumentRecord(Object documentRecord) {
this.documentRecord = documentRecord;
}
}
| 29.212121
| 169
| 0.813278
|
ece4038bf09fb327dd62abe894f28b78edade07d
| 5,441
|
package com.ruoyi.web.platform.partyInfo.controller;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.platform.partyInfo.domain.PartyInfo;
import com.ruoyi.web.platform.partyInfo.service.IPartyInfoService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
/**
* 党员信息Controller
*
* @author party-platform
* @date 2020-10-10
*/
@Controller
@Api("党员信息Controller")
@RequestMapping("/admin/partyInfo")
public class PartyInfoController extends BaseController {
private String prefix = "admin/partyInfo";
@Autowired
private IPartyInfoService partyInfoService;
@RequiresPermissions("admin:partyInfo:view")
@GetMapping()
public String partyInfo() {
return prefix + "/partyInfo";
}
/**
* 查询党员信息列表
*/
@ApiOperation(value = "查询党员信息列表", notes = "查询党员信息列表详情", tags = {"党员信息Controller"})
@RequiresPermissions("admin:partyInfo:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(PartyInfo partyInfo) {
startPage();
List<PartyInfo> list = partyInfoService.selectPartyInfoList(partyInfo);
return getDataTable(list);
}
/**
* 导出党员信息列表
*/
@ApiOperation(value = "导出党员信息列表", notes = "导出党员信息列表详情", tags = {"党员信息Controller"})
@RequiresPermissions("admin:partyInfo:export")
@Log(title = "党员信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(PartyInfo partyInfo) {
return partyInfoService.exportPartyInfoList(partyInfo);
}
/**
* 导入数据
*
* @param file
* @param updateSupport
* @return
* @throws Exception
*/
@Log(title = "党员信息管理", businessType = BusinessType.IMPORT)
@RequiresPermissions("admin:partyInfo:import")
@PostMapping("/importData")
@ResponseBody
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
ExcelUtil<PartyInfo> util = new ExcelUtil<PartyInfo>(PartyInfo.class);
List<PartyInfo> partyInfoList = util.importExcel(file.getInputStream());
String operName = ShiroUtils.getSysUser().getLoginName();
String message = partyInfoService.importPartyInfo(partyInfoList, updateSupport, operName);
return AjaxResult.success(message);
}
@RequiresPermissions("admin:partyInfo:view")
@GetMapping("/importTemplate")
@ResponseBody
public AjaxResult importTemplate() {
ExcelUtil<PartyInfo> util = new ExcelUtil<PartyInfo>(PartyInfo.class);
return util.importTemplateExcel("学生党员数据");
}
/**
* 新增党员信息
*/
@GetMapping("/add")
public String add() {
return prefix + "/add";
}
/**
* 新增保存党员信息
*/
@ApiOperation(value = "新增保存党员信息", notes = "新增保存党员信息详情", tags = {"党员信息Controller"})
@RequiresPermissions("admin:partyInfo:add")
@Log(title = "党员信息", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(PartyInfo partyInfo) {
return toAjax(partyInfoService.insertPartyInfo(partyInfo));
}
/**
* 修改党员信息
*/
@ApiOperation(value = "修改党员信息", notes = "修改党员信息详情", tags = {"党员信息Controller"})
@ApiImplicitParam(name = "partyId", value = "主键ID", dataType = "Long", paramType = "path")
@GetMapping("/edit/{partyId}")
public String edit(@PathVariable("partyId") Long partyId, ModelMap mmap) {
PartyInfo partyInfo = partyInfoService.selectPartyInfoById(partyId);
mmap.put("partyInfo", partyInfo);
return prefix + "/edit";
}
/**
* 修改保存党员信息
*/
@ApiOperation(value = "修改保存党员信息", notes = "修改保存党员信息详情", tags = {"党员信息Controller"})
@RequiresPermissions("admin:partyInfo:edit")
@Log(title = "党员信息", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(PartyInfo partyInfo) {
return toAjax(partyInfoService.updatePartyInfo(partyInfo));
}
/**
* 删除党员信息
*
* @ApiOperation("删除党员信息")
*/
@ApiOperation(value = "删除党员信息", notes = "删除党员信息详情", tags = {"党员信息Controller"})
@RequiresPermissions("admin:partyInfo:remove")
@Log(title = "党员信息", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
return toAjax(partyInfoService.deletePartyInfoByIds(ids));
}
}
| 33.58642
| 98
| 0.702812
|
8d2709256c97c2c3bae16cc541f543aefc18cd4e
| 326
|
package com.easy.throttling.api;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Application config
*/
@Log4j
@Configuration
@ComponentScan({
"com.easy.throttling.services"})
public class ApiConfig {
}
| 18.111111
| 60
| 0.785276
|
6431891097533a633a925b1a6cb9b92f4b988660
| 2,494
|
package com.binancetracker.repo.api.runnable.futures;
import com.binance.api.client.api.sync.BinanceApiSpotRestClient;
import com.binance.api.client.domain.account.FuturesTransactionHistory;
import com.binance.api.client.domain.account.FuturesTransactionList;
import com.binance.api.client.factory.BinanceSpotApiClientFactory;
import com.binancetracker.MyApplication;
import com.binancetracker.R;
import com.binancetracker.repo.api.runnable.ClientFactoryRunner;
import com.binancetracker.repo.api.runnable.JsonToDBConverter;
import com.binancetracker.repo.room.SingletonDataBase;
import com.binancetracker.repo.room.entity.FuturesTransactionHistoryEntity;
import java.util.ArrayList;
import java.util.List;
public class DownloadFuturesTransactionHistory extends ClientFactoryRunner<BinanceSpotApiClientFactory> {
public DownloadFuturesTransactionHistory(BinanceSpotApiClientFactory clientFactory, SingletonDataBase singletonDataBase) {
super(clientFactory, singletonDataBase);
}
@Override
public void processRun() {
BinanceApiSpotRestClient client = clientFactory.newRestClient();
List<String> assets = singletonDataBase.appDatabase.assetModelDao().getAllAssets();
singletonDataBase.binanceDatabase.futuresTransactionHistoryDao().deleteAll();
fireOnSyncStart(assets.size());
int i = 0;
for(String a : assets)
{
fireOnSyncUpdate(i++,a);
if (!isFiat(a)) {
FuturesTransactionList historyList = client.getWalletEndPoint().getFutureTransactionHistory(a, 1571436000000L);
if (historyList != null && historyList.getRows() != null) {
List<FuturesTransactionHistoryEntity> entities = new ArrayList<>();
for (FuturesTransactionHistory transactionHistory : historyList.getRows()) {
FuturesTransactionHistoryEntity entity = JsonToDBConverter.getFuturesTransactionHistoryEntity(transactionHistory);
entities.add(entity);
}
singletonDataBase.binanceDatabase.futuresTransactionHistoryDao().insertAll(entities);
}
}
}
fireOnSyncEnd();
}
private boolean isFiat(String in)
{
String[] fiat = MyApplication.getStringArrayFromRes(R.array.fiats);
for (String f : fiat) {
if (in.equals(f))
return true;
}
return false;
}
}
| 40.885246
| 138
| 0.702085
|
c50cfc92698a9bd08c3d497dc8128971b2f98b5b
| 235
|
package cn.leon.service;
import org.springframework.stereotype.Component;
@Component
public class NoFoundService implements HelloService {
@Override
public String hello(String name) {
return "sorry " + name;
}
}
| 18.076923
| 53
| 0.719149
|
f37d3d4194389114af06aa0bbb5d82505050103e
| 805
|
package org.weaver.alr.front.common.model;
import java.util.List;
public class Page <M>{
private Integer from;
private Integer size;
private Integer total;
private Integer count;
private List<M> items;
public Integer getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public List<M> getItems() {
return items;
}
public void setItems(List<M> items) {
this.items = items;
}
}
| 18.295455
| 43
| 0.650932
|
f6e23f09ec862635d6c3e42197aa4b175657482b
| 1,991
|
package com.example.smartsend.smartsendapp.activities;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.example.smartsend.smartsendapp.R;
import com.example.smartsend.smartsendapp.utilities.SplashPagerAdapter;
public class WelcomeActivity extends AppCompatActivity {
ViewPager welcomeViewPager;
SplashPagerAdapter welcomeViewPagerAdapter;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
welcomeViewPager =(ViewPager) findViewById(R.id.welcome_view_pager);
welcomeViewPagerAdapter = new SplashPagerAdapter(this);
welcomeViewPager.setAdapter(welcomeViewPagerAdapter);
ctx = this;
ViewPager.OnPageChangeListener listenerWelcomeViewPager = new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int pageNumber) {
// TODO Auto-generated method stub
if(pageNumber == 1){
goLoginActivity();
}
}
@Override
public void onPageScrolled(int pageScrolledOn, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
welcomeViewPager.setOnPageChangeListener(listenerWelcomeViewPager);
}
public void goLoginActivity(){
Intent intent = new Intent(WelcomeActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
}
}
| 31.109375
| 108
| 0.683074
|
063517e758bb8f67d279cf838d2e2aef64faa8bf
| 1,563
|
package com.honvay.cola.cloud.organization;
import com.honvay.cola.cloud.framework.oauth2.feign.EnableOAuth2ClientFeign;
import com.honvay.cola.cloud.framework.security.access.EnableSecurityAccess;
import org.springframework.boot.SpringApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
* @author LIQIU
* @date 2018-3-8
**/
@EnableOAuth2Client
@EnableOAuth2ClientFeign
@EnableResourceServer
@EnableFeignClients("com.honvay")
@ComponentScan("com.honvay")
@EnableCaching
@EnableSecurityAccess
@SpringCloudApplication
public class OrganizationApplication extends ResourceServerConfigurerAdapter {
public static void main(String[] args){
SpringApplication.run(OrganizationApplication.class, args);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/v2/api-docs").permitAll().and().authorizeRequests().anyRequest().authenticated();
}
}
| 39.075
| 112
| 0.818298
|
a730c7ba31699195f0f99cb3d683287fc3b37da5
| 4,923
|
/**
##**************************************************************
##
## Copyright (C) 2018-2020, OneDataShare Team,
## Department of Computer Science and Engineering,
## University at Buffalo, Buffalo, NY, 14260.
##
## 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 org.onedatashare.server.service;
import com.amazonaws.services.simpleemail.model.*;
import com.amazonaws.services.simpleemail.model.Message;
import org.springframework.stereotype.Service;
import javax.mail.*;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
/**
* This service class is responsible to send all emails for OneDataShare.
* Currently uses a AWS SimpleEmailService for sending out emails
*
* @version 1.0
* @since 03-Feb-2020
*/
@Service
public class EmailService {
private final String EMAIL_USERNAME = System.getenv("ODS_EMAIL_ADDRESS");
private final String AWS_ACCESS_KEY = System.getenv("AWS_ACCESS_KEY");
private final String AWS_SECRET_KEY = System.getenv("AWS_SECRET_KEY");
/**
* Method that creates and sends an email
*
* @param emailTo - email recipient
* @param subject - email subject
* @param emailText - content of the email
* @throws MessagingException - throws an exception if there was an error in sending email. Must be caught in referenced classes.
*/
public void sendEmail(String emailTo, String subject, String emailText){
try {
AmazonSimpleEmailService client = getAWSClient();
SendEmailRequest request = new SendEmailRequest()
.withDestination(
new Destination().withToAddresses(emailTo))
.withMessage(new Message()
.withBody(new Body()
.withHtml(new Content()
.withCharset("UTF-8").withData(emailText))
.withText(new Content()
.withCharset("UTF-8").withData(emailText)))
.withSubject(new Content()
.withCharset("UTF-8").withData(subject)))
.withSource(EMAIL_USERNAME);
client.sendEmail(request);
ODSLoggerService.logInfo("Sent email with subject \"" + subject + "\" to \""+ emailTo + "\" successfully.");
}
catch (Exception ex) {
ODSLoggerService.logError("Failure in sending email with " + subject + " to " + emailTo, ex);
}
}
/**
* This method returns the sending limit from the past 24hrs period.
*/
public GetSendQuotaResult getSendQuota() {
try {
AmazonSimpleEmailService client = getAWSClient();
GetSendQuotaRequest request = new GetSendQuotaRequest();
GetSendQuotaResult response = client.getSendQuota(request);
return response;
} catch (Exception e) {
ODSLoggerService.logError("Failure in getting email quota ", e);
}
return null;
}
/**
* This method returns the AWS Email Service object
* @return
*/
private AmazonSimpleEmailService getAWSClient(){
return AmazonSimpleEmailServiceClientBuilder.standard().withCredentials(new AWSCredentialsProvider() {
@Override
public AWSCredentials getCredentials() {
return new AWSCredentials() {
@Override
public String getAWSSecretKey() {
return AWS_SECRET_KEY;
}
@Override
public String getAWSAccessKeyId() {
return AWS_ACCESS_KEY;
}
};
}
@Override
public void refresh() {
}
}).withRegion(Regions.US_EAST_1).build();
}
public boolean isValidEmail(String email){
String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
return email.matches(regex);
}
}
| 37.015038
| 133
| 0.591509
|
86e2737cba19538376938cd9a37ff58ebdb914ec
| 4,217
|
/*-
* #%L
* IO Tesler - Model Core
* %%
* Copyright (C) 2018 - 2019 Tesler Contributors
* %%
* 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.
* #L%
*/
package io.tesler.model.core.listeners.hbn;
import static org.hibernate.event.spi.EventType.AUTO_FLUSH;
import static org.hibernate.event.spi.EventType.FLUSH;
import static org.hibernate.event.spi.EventType.FLUSH_ENTITY;
import static org.hibernate.event.spi.EventType.POST_DELETE;
import static org.hibernate.event.spi.EventType.POST_INSERT;
import static org.hibernate.event.spi.EventType.POST_UPDATE;
import io.tesler.model.core.listeners.hbn.change.ChangeInterceptor;
import io.tesler.model.core.listeners.hbn.flush.FlushInterceptor;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.AutoFlushEvent;
import org.hibernate.event.spi.AutoFlushEventListener;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.FlushEntityEvent;
import org.hibernate.event.spi.FlushEntityEventListener;
import org.hibernate.event.spi.FlushEvent;
import org.hibernate.event.spi.FlushEventListener;
import org.hibernate.event.spi.PostDeleteEvent;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.event.spi.PostInsertEvent;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.event.spi.PostUpdateEvent;
import org.hibernate.event.spi.PostUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DatabaseListener implements
PostInsertEventListener, PostUpdateEventListener, PostDeleteEventListener,
FlushEntityEventListener, FlushEventListener, AutoFlushEventListener {
@Autowired
private EntityManagerFactory emf;
@Autowired
private ChangeInterceptor changeInterceptor;
@Autowired
private FlushInterceptor flushInterceptor;
@Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
@Override
public void onPostDelete(PostDeleteEvent event) {
changeInterceptor.addEvent(event);
}
@Override
public void onPostInsert(PostInsertEvent event) {
changeInterceptor.addEvent(event);
}
@Override
public void onPostUpdate(PostUpdateEvent event) {
changeInterceptor.addEvent(event);
}
@Override
public void onAutoFlush(AutoFlushEvent event) throws HibernateException {
flushInterceptor.onFlush(event);
}
@Override
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
flushInterceptor.onFlush(event);
}
@Override
public void onFlush(FlushEvent event) throws HibernateException {
flushInterceptor.onFlush(event);
}
@PostConstruct
protected void init() {
prependListener(POST_INSERT, this);
prependListener(POST_UPDATE, this);
prependListener(POST_DELETE, this);
appendListener(FLUSH_ENTITY, this);
appendListener(FLUSH, this);
appendListener(AUTO_FLUSH, this);
}
private EventListenerRegistry getRegistry() {
SessionFactoryImplementor implementor = emf.unwrap(SessionFactoryImplementor.class);
return implementor.getServiceRegistry().getService(EventListenerRegistry.class);
}
private <T> void prependListener(EventType<T> eventType, T listener) {
getRegistry().getEventListenerGroup(eventType).prependListener(listener);
}
private <T> void appendListener(EventType<T> eventType, T listener) {
getRegistry().getEventListenerGroup(eventType).appendListener(listener);
}
}
| 32.945313
| 86
| 0.808869
|
1e3911346795f22a64858936b077257dab9e5736
| 44,840
|
/*
* Copyright 2016-present Open Networking Foundation
*
* 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 com.airlenet.yang.compiler.linker.impl;
import com.airlenet.yang.compiler.datamodel.LocationInfo;
import com.airlenet.yang.compiler.datamodel.TraversalType;
import com.airlenet.yang.compiler.datamodel.YangAtomicPath;
import com.airlenet.yang.compiler.datamodel.YangAugment;
import com.airlenet.yang.compiler.datamodel.YangAugmentableNode;
import com.airlenet.yang.compiler.datamodel.YangBase;
import com.airlenet.yang.compiler.datamodel.YangCase;
import com.airlenet.yang.compiler.datamodel.YangChoice;
import com.airlenet.yang.compiler.datamodel.YangGrouping;
import com.airlenet.yang.compiler.datamodel.YangIdentityRef;
import com.airlenet.yang.compiler.datamodel.YangIfFeature;
import com.airlenet.yang.compiler.datamodel.YangImport;
import com.airlenet.yang.compiler.datamodel.YangInclude;
import com.airlenet.yang.compiler.datamodel.YangLeaf;
import com.airlenet.yang.compiler.datamodel.YangLeafList;
import com.airlenet.yang.compiler.datamodel.YangLeafRef;
import com.airlenet.yang.compiler.datamodel.YangLeavesHolder;
import com.airlenet.yang.compiler.datamodel.YangList;
import com.airlenet.yang.model.YangNamespace;
import com.airlenet.yang.compiler.datamodel.YangNode;
import com.airlenet.yang.compiler.datamodel.YangNodeIdentifier;
import com.airlenet.yang.compiler.datamodel.YangPathPredicate;
import com.airlenet.yang.compiler.datamodel.YangReferenceResolver;
import com.airlenet.yang.compiler.datamodel.YangRelativePath;
import com.airlenet.yang.compiler.datamodel.YangType;
import com.airlenet.yang.compiler.datamodel.YangTypeDef;
import com.airlenet.yang.compiler.datamodel.YangUses;
import com.airlenet.yang.compiler.datamodel.exceptions.DataModelException;
import com.airlenet.yang.compiler.datamodel.utils.YangConstructType;
import com.airlenet.yang.compiler.linker.exceptions.LinkerException;
import com.airlenet.yang.compiler.translator.exception.TranslatorException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static com.airlenet.yang.compiler.datamodel.TraversalType.CHILD;
import static com.airlenet.yang.compiler.datamodel.TraversalType.PARENT;
import static com.airlenet.yang.compiler.datamodel.TraversalType.ROOT;
import static com.airlenet.yang.compiler.datamodel.TraversalType.SIBLING;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.COLLISION_DETECTION;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.FAILED_TO_ADD_CASE;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.TARGET_NODE;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.TGT_LEAF;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.getErrorMsg;
import static com.airlenet.yang.compiler.datamodel.exceptions.ErrorMessages.getErrorMsgCollision;
import static com.airlenet.yang.compiler.datamodel.utils.DataModelUtils.addResolutionInfo;
import static com.airlenet.yang.compiler.datamodel.utils.GeneratedLanguage.JAVA_GENERATION;
import static com.airlenet.yang.compiler.datamodel.utils.ResolvableStatus.RESOLVED;
import static com.airlenet.yang.compiler.datamodel.utils.YangConstructType.getYangConstructType;
import static com.airlenet.yang.compiler.datamodel.utils.builtindatatype.YangDataTypes.DERIVED;
import static com.airlenet.yang.compiler.datamodel.utils.builtindatatype.YangDataTypes.IDENTITYREF;
import static com.airlenet.yang.compiler.translator.tojava.YangDataModelFactory.getYangCaseNode;
import static com.airlenet.yang.compiler.utils.UtilConstants.BASE_LINKER_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.COLON;
import static com.airlenet.yang.compiler.utils.UtilConstants.COMMA;
import static com.airlenet.yang.compiler.utils.UtilConstants.EMPTY_STRING;
import static com.airlenet.yang.compiler.utils.UtilConstants.FEATURE_LINKER_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.GROUPING_LINKER_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.IDENTITYREF_LINKER_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.INVALID_TREE;
import static com.airlenet.yang.compiler.utils.UtilConstants.IS_INVALID;
import static com.airlenet.yang.compiler.utils.UtilConstants.LEAFREF_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.LEAFREF_LINKER_ERROR;
import static com.airlenet.yang.compiler.utils.UtilConstants.TYPEDEF_LINKER_ERROR;
/**
* Represent utilities for YANG linker.
*/
public final class YangLinkerUtils {
private static final int IDENTIFIER_LENGTH = 64;
private static final Pattern IDENTIFIER_PATTERN =
Pattern.compile("[a-zA-Z_][a-zA-Z0-9_.-]*");
private static final String XML = "xml";
private static final String INVALID_PATH_PRE =
"YANG file error: The path predicate of the leafref has an " +
"invalid path in ";
private static final String EMPTY_PATH_LIST_ERR =
"YANG file error : The atomic path list cannot be empty of the " +
"leafref in the path ";
private static final String TGT_LEAF_ERR =
"YANG file error: There is no leaf/leaf-list in YANG node as " +
"mentioned in the path predicate of the leafref path ";
private static final String LEAF_REF_LIST_ERR =
"YANG file error: Path predicates are only applicable for YANG " +
"list. The leafref path has path predicate for non-list " +
"node in the path ";
// No instantiation.
private YangLinkerUtils() {
}
/**
* Detects collision between target nodes' leaf/leaf-list or child node
* with augmented leaf/leaf-list or child node.
*
* @param tgt target node
* @param aug YANG augment
* @param augRoot augment's root
*/
private static void detectCollision(YangNode tgt, YangAugment aug,
YangNode augRoot) {
YangNode tgtRoot = getTgtRootNode(tgt);
String augNs = ((YangNamespace) augRoot).getModuleNamespace();
String tgtNs = ((YangNamespace) tgtRoot).getModuleNamespace();
if (tgt instanceof YangChoice) {
addCaseNodeToChoiceTarget(aug);
}
detectCollisionInTgt(tgt, aug, augNs, tgtNs);
}
/**
* Detects collision in the target node according to the namespace match
* of the nodes.
*
* @param tgt target node
* @param aug YANG augment
* @param augNs augment root namespace
* @param tgtNs target root namespace
*/
private static void detectCollisionInTgt(YangNode tgt, YangAugment aug,
String augNs, String tgtNs) {
if (!(augNs.equals(tgtNs))) {
return;
}
YangNode aChild = aug.getChild();
YangNode tChild = tgt.getChild();
List<YangLeaf> aL = aug.getListOfLeaf();
List<YangLeafList> aLl = aug.getListOfLeafList();
List<YangLeaf> tL = null;
List<YangLeafList> tLl = null;
if (tgt instanceof YangLeavesHolder) {
tL = ((YangLeavesHolder) tgt).getListOfLeaf();
tLl = ((YangLeavesHolder) tgt).getListOfLeafList();
}
detectLeavesCollision(tL, tLl, aL, aLl);
while (aChild != null) {
detectNodeCollision(aChild, tChild, aL, aLl);
detectLeafCollision(aChild.getName(), aChild, tL);
detectLeafListCollision(aChild.getName(), aChild, tLl);
aChild = aChild.getNextSibling();
}
}
/**
* Detects collision between augment's leaves and leaf lists' identifier
* with target node leaves and leaf lists' identifier.
*
* @param tL target leaves
* @param tLl target leaf lists
* @param aL augment leaves
* @param aLl augment leaf lists
*/
private static void detectLeavesCollision(List<YangLeaf> tL,
List<YangLeafList> tLl,
List<YangLeaf> aL,
List<YangLeafList> aLl) {
if (aL != null && !aL.isEmpty()) {
for (YangLeaf aLeaf : aL) {
detectLeafCollision(aLeaf.getName(), aLeaf, tL);
detectLeafListCollision(aLeaf.getName(), aLeaf, tLl);
}
}
if (aLl != null && !aLl.isEmpty()) {
for (YangLeafList aLeafList : aLl) {
detectLeafCollision(aLeafList.getName(), aLeafList, tL);
detectLeafListCollision(aLeafList.getName(), aLeafList, tLl);
}
}
}
/**
* Detects collision with list of leaf-list name and any comparable
* identifier.
*
* @param name comparable identifier
* @param info location info
* @param leavesList list of leaf-list
*/
private static void detectLeafListCollision(String name, LocationInfo info,
List<YangLeafList> leavesList) {
if (leavesList != null && !leavesList.isEmpty()) {
for (YangLeafList ll : leavesList) {
detectCollision(ll.getName(), name, info, TGT_LEAF);
}
}
}
/**
* Detects collision with list of leaf name and any comparable
* identifier.
*
* @param name comparable identifier
* @param info location info
* @param leaves list of leaf
*/
private static void detectLeafCollision(String name, LocationInfo info,
List<YangLeaf> leaves) {
if (leaves != null && !leaves.isEmpty()) {
for (YangLeaf leaf : leaves) {
detectCollision(leaf.getName(), name, info, TGT_LEAF);
}
}
}
/**
* Detects node collision of augment children nodes, leaves and leaf-lists
* with target node's children nodes.
*
* @param aug YANG augment's child
* @param tgt target node's child
* @param aL augment leaves
* @param aLl augment leaf lists
*/
private static void detectNodeCollision(YangNode aug, YangNode tgt,
List<YangLeaf> aL,
List<YangLeafList> aLl) {
while (tgt != null) {
detectCollision(tgt.getName(), aug.getName(), aug, TARGET_NODE);
detectLeafCollision(tgt.getName(), tgt, aL);
detectLeafListCollision(tgt.getName(), tgt, aLl);
tgt = tgt.getNextSibling();
}
}
/**
* Returns module or sub-module node of any YANG node.
*
* @param node YANG node
* @return root node
*/
private static YangNode getTgtRootNode(YangNode node) {
YangNode root = node;
while (!(root instanceof YangReferenceResolver)) {
root = root.getParent();
if (root == null) {
throw new LinkerException("Datamodel tree is not correct");
}
}
return root;
}
/**
* Detects collision for two strings and throws exception if collision
* occurs.
*
* @param first first string
* @param second second string
* @param info location info
* @param type collision type
*/
private static void detectCollision(String first, String second,
LocationInfo info, String type) {
if (first.equals(second)) {
throw new LinkerException(getErrorMsgCollision(
COLLISION_DETECTION, second, info.getLineNumber(),
info.getCharPosition(), type, info.getFileName()));
}
}
/**
* Adds a case node in augment when augmenting a choice node.
*
* @param augment augment node
*/
private static void addCaseNodeToChoiceTarget(YangAugment augment) {
try {
YangNode child = augment.getChild();
List<YangNode> childNodes = new ArrayList<>();
List<YangNode> caseNodes = new ArrayList<>();
while (child != null) {
if (!(child instanceof YangCase)) {
childNodes.add(child);
} else {
caseNodes.add(child);
}
child = child.getNextSibling();
}
augment.setChild(null);
for (YangNode node : childNodes) {
Map<YangNode, List<YangNode>> map = new LinkedHashMap<>();
node.setNextSibling(null);
node.setPreviousSibling(null);
node.setParent(null);
YangCase javaCase = getYangCaseNode(JAVA_GENERATION);
javaCase.setName(node.getName());
//Break the tree to from a new tree.
traverseAndBreak(node, map);
augment.addChild(javaCase);
node.setParent(javaCase);
javaCase.addChild(node);
//Connect each node to its correct parent again.
connectTree(map);
}
for (YangNode node : caseNodes) {
Map<YangNode, List<YangNode>> map = new LinkedHashMap<>();
node.setNextSibling(null);
node.setPreviousSibling(null);
node.setParent(null);
//Break the tree to from a new tree.
traverseAndBreak(node, map);
augment.addChild(node);
node.setParent(augment);
//Connect each node to its correct parent again.
connectTree(map);
}
if (augment.getListOfLeaf() != null) {
for (YangLeaf leaf : augment.getListOfLeaf()) {
YangCase javaCase = getYangCaseNode(JAVA_GENERATION);
javaCase.setName(leaf.getName());
javaCase.addLeaf(leaf);
augment.addChild(javaCase);
}
augment.getListOfLeaf().clear();
}
if (augment.getListOfLeafList() != null) {
for (YangLeafList leafList : augment.getListOfLeafList()) {
YangCase javaCase = getYangCaseNode(JAVA_GENERATION);
javaCase.setName(leafList.getName());
javaCase.addLeafList(leafList);
augment.addChild(javaCase);
}
augment.getListOfLeafList().clear();
}
} catch (DataModelException e) {
throw new TranslatorException(
getErrorMsg(FAILED_TO_ADD_CASE, augment.getName(),
augment.getLineNumber(), augment.getCharPosition(),
augment.getFileName()));
}
}
private static void connectTree(Map<YangNode, List<YangNode>> map)
throws DataModelException {
ArrayList<YangNode> keys = new ArrayList<>(map.keySet());
int size = keys.size();
for (int i = size - 1; i >= 0; i--) {
YangNode curNode = keys.get(i);
List<YangNode> nodes = map.get(curNode);
if (nodes != null) {
for (YangNode node : nodes) {
curNode.addChild(node);
}
}
}
map.clear();
}
private static void processHierarchyChild(YangNode node,
Map<YangNode, List<YangNode>> map) {
YangNode child = node.getChild();
if (child != null) {
List<YangNode> nodes = new ArrayList<>();
while (child != null) {
nodes.add(child);
child.setParent(null);
child = child.getNextSibling();
if (child != null) {
child.getPreviousSibling().setNextSibling(null);
child.setPreviousSibling(null);
}
}
map.put(node, nodes);
}
node.setChild(null);
}
private static void traverseAndBreak(YangNode rootNode,
Map<YangNode, List<YangNode>> map) {
YangNode curNode = rootNode;
TraversalType curTraversal = ROOT;
while (curNode != null) {
if (curTraversal != PARENT && curNode.getChild() != null) {
curTraversal = CHILD;
curNode = curNode.getChild();
} else if (curNode.getNextSibling() != null) {
curTraversal = SIBLING;
curNode = curNode.getNextSibling();
} else {
curTraversal = PARENT;
curNode = curNode.getParent();
if (curNode != null) {
processHierarchyChild(curNode, map);
}
}
}
}
/**
* Returns error messages.
*
* @param resolvable resolvable entity
* @return error message
*/
static String getErrorInfoForLinker(Object resolvable) {
if (resolvable instanceof YangType) {
return TYPEDEF_LINKER_ERROR;
}
if (resolvable instanceof YangUses) {
return GROUPING_LINKER_ERROR;
}
if (resolvable instanceof YangIfFeature) {
return FEATURE_LINKER_ERROR;
}
if (resolvable instanceof YangBase) {
return BASE_LINKER_ERROR;
}
if (resolvable instanceof YangIdentityRef) {
return IDENTITYREF_LINKER_ERROR;
}
return LEAFREF_LINKER_ERROR;
}
/**
* Returns leafref's error message.
*
* @param leafref leaf ref
* @return error message
*/
static String getLeafRefErrorInfo(YangLeafRef leafref) {
return getErrorMsg(
LEAFREF_ERROR + leafref.getPath() + COMMA + IS_INVALID, EMPTY_STRING,
leafref.getLineNumber(), leafref.getCharPosition(), leafref
.getFileName());
}
/**
* Detects collision between augment nodes' children and target nodes'
* nodes children and also between augment nodes' children and other
* augmented nodes.
*
* @param tgt target node
* @param aug YANG augment
* @param augRoot augment's root
*/
static void detectCollisionForAugment(YangNode tgt, YangAugment aug,
YangNode augRoot) {
// Detect collision for target node and augment node.
detectCollision(tgt, aug, augRoot);
List<YangAugment> infoList = ((YangAugmentableNode) tgt)
.getAugmentedInfoList();
// Detect collision for target augment node and current augment node.
for (YangAugment info : infoList) {
detectCollision(info, aug, augRoot);
}
}
/**
* Returns list of path names that are needed from augment.
*
* @param augment instance of YANG augment
* @param remainingAncestors ancestor count to move in augment path
* @return list of path names needed in leafref or YANG node
*/
static Object getPathWithAugment(YangAugment augment, int remainingAncestors) {
List<String> listOfPathName = new ArrayList<>();
YangNode node = augment.getAugmentedNode();
for (YangAtomicPath atomicPath : augment.getTargetNode()) {
if (atomicPath.getNodeIdentifier().getPrefix() != null &&
!atomicPath.getNodeIdentifier().getPrefix().equals(EMPTY_STRING)) {
listOfPathName.add(atomicPath.getNodeIdentifier().getPrefix()
+ COLON + atomicPath.getNodeIdentifier().getName());
} else {
listOfPathName.add(atomicPath.getNodeIdentifier().getName());
}
if (node != null) {
node = node.getParent();
}
}
for (int countOfAncestor = 0; countOfAncestor < remainingAncestors; countOfAncestor++) {
if (listOfPathName.isEmpty()) {
return getNodeFromUsesAug(node, remainingAncestors - countOfAncestor);
}
listOfPathName.remove(listOfPathName.size() - 1);
}
if (listOfPathName.isEmpty()) {
return getNodeFromUsesAug(node, 0);
}
return listOfPathName;
}
/**
* Returns the YANG node from uses augment.
*
* @param node YANG node
* @param count number of ancestors
* @return YANG node.
*/
private static YangNode getNodeFromUsesAug(YangNode node, int count) {
for (int val = 0; val < count; val++) {
node = node.getParent();
}
return node;
}
/**
* Skips the invalid nodes which cannot have data from YANG.
*
* @param curParent current parent
* @param leafRef YANG leaf-ref
* @return parent node which can hold data
* @throws LinkerException if linker rules are violated
*/
public static YangNode skipInvalidDataNodes(YangNode curParent,
YangLeafRef leafRef)
throws LinkerException {
YangNode node = curParent;
while (node instanceof YangChoice ||
node instanceof YangCase) {
if (node.getParent() == null) {
throw new LinkerException(getLeafRefErrorInfo(leafRef));
}
node = node.getParent();
}
return node;
}
/**
* Checks and return valid node identifier.
*
* @param nodeIdentifierString string from yang file
* @param yangConstruct yang construct for creating error message
* @return valid node identifier
*/
static YangNodeIdentifier getValidNodeIdentifier(String nodeIdentifierString,
YangConstructType yangConstruct) {
String[] tmpData = nodeIdentifierString.split(Pattern.quote(COLON));
if (tmpData.length == 1) {
YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
nodeIdentifier.setName(getValidIdentifier(tmpData[0], yangConstruct));
return nodeIdentifier;
} else if (tmpData.length == 2) {
YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
nodeIdentifier.setPrefix(getValidIdentifier(tmpData[0], yangConstruct));
nodeIdentifier.setName(getValidIdentifier(tmpData[1], yangConstruct));
return nodeIdentifier;
} else {
throw new LinkerException("YANG file error : " +
getYangConstructType(yangConstruct) + " name " +
nodeIdentifierString + " is not valid.");
}
}
/**
* Validates identifier and returns concatenated string if string contains plus symbol.
*
* @param identifier string from yang file
* @param yangConstruct yang construct for creating error message=
* @return concatenated string after removing double quotes
*/
public static String getValidIdentifier(String identifier, YangConstructType yangConstruct) {
if (identifier.length() > IDENTIFIER_LENGTH) {
throw new LinkerException("YANG file error : " +
getYangConstructType(yangConstruct) + " name " + identifier + " is " +
"greater than 64 characters.");
} else if (!IDENTIFIER_PATTERN.matcher(identifier).matches()) {
throw new LinkerException("YANG file error : " +
getYangConstructType(yangConstruct) + " name " + identifier + " is not " +
"valid.");
} else if (identifier.toLowerCase().startsWith(XML)) {
throw new LinkerException("YANG file error : " +
getYangConstructType(yangConstruct) + " identifier " + identifier +
" must not start with (('X'|'x') ('M'|'m') ('L'|'l')).");
} else {
return identifier;
}
}
/**
* Updates the priority for all the input files.
*
* @param yangNodeSet set of YANG files info
*/
public static void updateFilePriority(Set<YangNode> yangNodeSet) {
for (YangNode yangNode : yangNodeSet) {
updateFilePriorityOfNode(yangNode);
}
}
/**
* Updates priority of the node.
*
* @param yangNode YANG node information
*/
private static void updateFilePriorityOfNode(YangNode yangNode) {
int curNodePriority = yangNode.getPriority();
if (yangNode instanceof YangReferenceResolver) {
List<YangImport> yangImportList = ((YangReferenceResolver) yangNode).getImportList();
Iterator<YangImport> importInfoIterator = yangImportList.iterator();
// Run through the imported list to update priority.
while (importInfoIterator.hasNext()) {
YangImport yangImport = importInfoIterator.next();
YangNode importedNode = yangImport.getImportedNode();
if (curNodePriority >= importedNode.getPriority()) {
importedNode.setPriority(curNodePriority + 1);
updateFilePriorityOfNode(importedNode);
}
}
List<YangInclude> yangIncludeList = ((YangReferenceResolver) yangNode).getIncludeList();
Iterator<YangInclude> includeInfoIterator = yangIncludeList.iterator();
// Run through the imported list to update priority.
while (includeInfoIterator.hasNext()) {
YangInclude yangInclude = includeInfoIterator.next();
YangNode includedNode = yangInclude.getIncludedNode();
if (curNodePriority >= includedNode.getPriority()) {
includedNode.setPriority(curNodePriority + 1);
updateFilePriorityOfNode(includedNode);
}
}
}
}
/**
* Add the unresolved data under the root leve grouping to be resolved, since it will be used in interfile uses.
*
* @param referenceResolver module / sub-module
*/
public static void resolveGroupingInDefinationScope(YangReferenceResolver referenceResolver) {
YangNode potentialInterFileGrouping = ((YangNode) referenceResolver).getChild();
while (potentialInterFileGrouping != null) {
if (potentialInterFileGrouping instanceof YangGrouping) {
addGroupingResolvableEntitiesToResolutionList((YangGrouping) potentialInterFileGrouping);
}
potentialInterFileGrouping = potentialInterFileGrouping.getNextSibling();
}
}
/**
* Add the interfile grouping resolvable entities to reesolution list.
*
* @param interFileGrouping interfile grouping
*/
private static void addGroupingResolvableEntitiesToResolutionList(YangGrouping interFileGrouping) {
YangNode curNode = interFileGrouping;
TraversalType curTraversal = ROOT;
addResolvableLeavesToResolutionList((YangLeavesHolder) curNode);
curTraversal = CHILD;
curNode = interFileGrouping.getChild();
if (curNode == null) {
return;
}
while (curNode != interFileGrouping) {
if (curTraversal != PARENT) {
if (curNode instanceof YangGrouping || curNode instanceof YangUses) {
if (curNode.getNextSibling() != null) {
curTraversal = SIBLING;
curNode = curNode.getNextSibling();
} else {
curTraversal = PARENT;
curNode = curNode.getParent();
}
continue;
}
if (curNode instanceof YangLeavesHolder) {
addResolvableLeavesToResolutionList((YangLeavesHolder) curNode);
} else if (curNode instanceof YangTypeDef) {
List<YangType<?>> typeList = ((YangTypeDef) curNode).getTypeList();
if (!typeList.isEmpty()) {
YangType<?> type = typeList.get(0);
if (type.getDataType() == DERIVED) {
if (type.getResolvableStatus() != RESOLVED) {
type.setTypeForInterFileGroupingResolution(true);
// Add resolution information to the list
YangResolutionInfoImpl resolutionInfo =
new YangResolutionInfoImpl<YangType>(type, curNode, type.getLineNumber(),
type.getCharPosition());
try {
addResolutionInfo(resolutionInfo);
} catch (DataModelException e) {
String errorInfo = "Error in file: " + curNode.getName() + " in " +
curNode.getFileName() + " at " +
"line: " + e.getLineNumber() +
" at position: " + e.getCharPositionInLine()
+ e.getLocalizedMessage();
throw new LinkerException("Failed to add type info in grouping to resolution "
+ errorInfo, e);
}
}
}
}
}
}
if (curTraversal != PARENT && curNode.getChild() != null) {
curTraversal = CHILD;
curNode = curNode.getChild();
} else if (curNode.getNextSibling() != null) {
curTraversal = SIBLING;
curNode = curNode.getNextSibling();
} else {
curTraversal = PARENT;
curNode = curNode.getParent();
}
}
}
/**
* Add resolvable leaves type info to resolution list.
*
* @param leavesHolder leaves holder node
*/
private static void addResolvableLeavesToResolutionList(YangLeavesHolder leavesHolder) {
if (leavesHolder.getListOfLeaf() != null && !leavesHolder.getListOfLeaf().isEmpty()) {
for (YangLeaf leaf : leavesHolder.getListOfLeaf()) {
YangType type = leaf.getDataType();
if (type.getDataType() == DERIVED) {
type.setTypeForInterFileGroupingResolution(true);
// Add resolution information to the list
YangResolutionInfoImpl resolutionInfo =
new YangResolutionInfoImpl<>(type, (YangNode) leavesHolder,
type.getLineNumber(), type.getCharPosition());
try {
addResolutionInfo(resolutionInfo);
} catch (DataModelException e) {
throw new LinkerException("Failed to add leaf type info in grouping, to resolution ", e);
}
} else if (type.getDataType() == IDENTITYREF) {
YangIdentityRef identityRef = (YangIdentityRef) type.getDataTypeExtendedInfo();
identityRef.setIdentityForInterFileGroupingResolution(true);
// Add resolution information to the list
YangResolutionInfoImpl resolutionInfo =
new YangResolutionInfoImpl<>(identityRef, (YangNode) leavesHolder,
identityRef.getLineNumber(),
identityRef.getCharPosition());
try {
addResolutionInfo(resolutionInfo);
} catch (DataModelException e) {
throw new LinkerException("Failed to add leaf identity ref info in grouping, to resolution ",
e);
}
}
}
}
if (leavesHolder.getListOfLeafList() != null && !leavesHolder.getListOfLeafList().isEmpty()) {
for (YangLeafList leafList : leavesHolder.getListOfLeafList()) {
YangType type = leafList.getDataType();
if (type.getDataType() == DERIVED) {
type.setTypeForInterFileGroupingResolution(true);
// Add resolution information to the list
YangResolutionInfoImpl resolutionInfo =
new YangResolutionInfoImpl<>(type, (YangNode) leavesHolder,
type.getLineNumber(), type.getCharPosition());
try {
addResolutionInfo(resolutionInfo);
} catch (DataModelException e) {
throw new LinkerException("Failed to add leaf type info in grouping, to resolution ");
}
} else if (type.getDataType() == IDENTITYREF) {
YangIdentityRef identityRef = (YangIdentityRef) type.getDataTypeExtendedInfo();
identityRef.setIdentityForInterFileGroupingResolution(true);
// Add resolution information to the list
YangResolutionInfoImpl resolutionInfo =
new YangResolutionInfoImpl<>(identityRef, (YangNode) leavesHolder,
identityRef.getLineNumber(),
identityRef.getCharPosition());
try {
addResolutionInfo(resolutionInfo);
} catch (DataModelException e) {
throw new LinkerException("Failed to add leaf identity ref info in grouping, to resolution ");
}
}
}
}
}
/**
* Fills the path predicates of the leaf-ref with right axis node and
* left axis node, after linking the nodes.
*
* @param leafRef YANG leaf-ref
* @throws DataModelException if there is a data model error
*/
public static void fillPathPredicates(YangLeafRef<?> leafRef)
throws DataModelException {
List<YangAtomicPath> atomics = leafRef.getAtomicPath();
if (atomics != null) {
for (YangAtomicPath atom : atomics) {
List<YangPathPredicate> predicates =
atom.getPathPredicatesList();
if (predicates != null) {
for (YangPathPredicate predicate : predicates) {
setLeftAxisNode(leafRef, atom, predicate);
setRightAxisNode(leafRef, predicate);
}
}
}
}
}
/**
* Sets the left axis node in the YANG path predicate after finding it
* under the YANG list node.
*
* @param leafRef YANG leaf-ref
* @param atom atomic path content
* @param predicate predicate in the atomic path
* @throws DataModelException if there is a data model error
*/
private static void setLeftAxisNode(YangLeafRef<?> leafRef,
YangAtomicPath atom,
YangPathPredicate predicate)
throws DataModelException {
YangNode resolvedNode = atom.getResolvedNode();
if (!(resolvedNode instanceof YangList)) {
throw getDataModelExc(LEAF_REF_LIST_ERR, leafRef);
}
YangNodeIdentifier leftAxisName = predicate.getNodeId();
Object target = getTarget(leftAxisName, resolvedNode, leafRef);
predicate.setLeftAxisNode(target);
}
/**
* Returns the target leaf/leaf-list from the provided YANG node.
*
* @param leftAxisName name of node
* @param node node having target
* @param leafRef YANG leaf-ref
* @return target leaf/leaf-list
* @throws DataModelException if there is a data model error
*/
private static Object getTarget(YangNodeIdentifier leftAxisName,
YangNode node, YangLeafRef leafRef)
throws DataModelException {
YangLeaf leaf = getLeaf(leftAxisName, (YangLeavesHolder) node);
YangLeafList leafList = getLeafList(leftAxisName,
(YangLeavesHolder) node);
if (leaf == null && leafList == null) {
if (node instanceof YangAugmentableNode) {
List<YangAugment> augList = ((YangAugmentableNode) node)
.getAugmentedInfoList();
for (YangAugment aug : augList) {
leaf = getLeaf(leftAxisName, aug);
leafList = getLeafList(leftAxisName, aug);
if (leaf != null || leafList != null) {
break;
}
}
}
}
if (leaf == null && leafList == null) {
throw getDataModelExc(TGT_LEAF_ERR, leafRef);
}
return (leaf != null) ? leaf : leafList;
}
/**
* Returns the leaf by searching it in the node by the leaf name. Returns
* null when the name doesn't match.
*
* @param name leaf name
* @param holder holder of leaf
* @return YANG leaf
*/
private static YangLeaf getLeaf(YangNodeIdentifier name,
YangLeavesHolder holder) {
List<YangLeaf> listOfLeaf = holder.getListOfLeaf();
if (listOfLeaf != null) {
for (YangLeaf yangLeaf : listOfLeaf) {
if (yangLeaf.getName().equals(name.getName())) {
return yangLeaf;
}
}
}
return null;
}
/**
* Returns the leaf-list by searching it in the node by the leaf-list name.
* Returns null when the name doesn't match.
*
* @param name leaf-list name
* @param holder holder of leaf-list
* @return YANG leaf-list
*/
private static YangLeafList getLeafList(YangNodeIdentifier name,
YangLeavesHolder holder) {
List<YangLeafList> listOfLeafList = holder.getListOfLeafList();
if (listOfLeafList != null) {
for (YangLeafList yangLeafList : listOfLeafList) {
if (yangLeafList.getName().equals(name.getName())) {
return yangLeafList;
}
}
}
return null;
}
/**
* Returns the root node from which the path with the atomic node names
* has to be traversed through. With the ancestor count the nodes are
* moved upward.
*
* @param count ancestor count
* @param node current leaf-ref parent
* @param leafRef YANG leaf-ref
* @return root node from ancestor count
* @throws DataModelException if there is a data model error
*/
private static YangNode getRootNode(int count, YangNode node,
YangLeafRef leafRef)
throws DataModelException {
YangNode curParent = node;
int curCount = 0;
while (curCount < count) {
curCount = curCount + 1;
if (curCount != 1) {
if (curParent.getParent() == null) {
throw getDataModelExc(INVALID_TREE, leafRef);
}
curParent = curParent.getParent();
}
curParent = skipInvalidDataNodes(curParent, leafRef);
if (curParent instanceof YangAugment) {
YangAugment augment = (YangAugment) curParent;
curParent = augment.getAugmentedNode();
curCount = curCount + 1;
}
}
return curParent;
}
/**
* Returns the last node by traversing through the atomic node id by
* leaving the last target leaf/leaf-list.
*
* @param curNode current node
* @param relPath relative path
* @param leafRef YANG leaf-ref
* @return last YANG node
* @throws DataModelException if there is a data model error
*/
private static Object getLastNode(YangNode curNode,
YangRelativePath relPath,
YangLeafRef leafRef)
throws DataModelException {
YangNode node = curNode;
List<YangAtomicPath> atomics = new ArrayList<>();
atomics.addAll(relPath.getAtomicPathList());
if (atomics.isEmpty()) {
throw getDataModelExc(EMPTY_PATH_LIST_ERR, leafRef);
}
YangAtomicPath pathTgt = atomics.get(atomics.size() - 1);
if (atomics.size() == 1) {
return getTarget(pathTgt.getNodeIdentifier(), node, leafRef);
}
atomics.remove(atomics.size() - 1);
for (YangAtomicPath atomicPath : atomics) {
node = getNode(node.getChild(), atomicPath.getNodeIdentifier());
if (node == null) {
throw getDataModelExc(INVALID_PATH_PRE, leafRef);
}
}
return getTarget(pathTgt.getNodeIdentifier(), node, leafRef);
}
/**
* Returns the node from the parent node by matching it with the atomic
* name. If no child node matches the name then it returns null.
*
* @param curNode current node
* @param identifier atomic name
* @return node to be traversed
*/
private static YangNode getNode(YangNode curNode,
YangNodeIdentifier identifier) {
YangNode node = curNode;
while (node != null) {
if (node.getName().equals(identifier.getName())) {
return node;
}
node = node.getNextSibling();
}
return null;
}
/**
* Sets the right axis node in the YANG path predicate after finding it
* from the relative path.
*
* @param leafRef YANG leaf-ref
* @param predicate YANG path predicate
* @throws DataModelException if there is a data model error
*/
private static void setRightAxisNode(YangLeafRef leafRef,
YangPathPredicate predicate)
throws DataModelException {
YangNode parentNode = leafRef.getParentNode();
YangRelativePath relPath = predicate.getRelPath();
int ancestor = relPath.getAncestorNodeCount();
YangNode rootNode = getRootNode(ancestor, parentNode, leafRef);
Object target = getLastNode(rootNode, relPath, leafRef);
if (target == null) {
throw getDataModelExc(INVALID_PATH_PRE, leafRef);
}
predicate.setRightAxisNode(target);
}
/**
* Returns data model error messages for leaf-ref with the path.
*
* @param msg error message
* @param leafRef YANG leaf-ref
* @return data model exception
*/
private static DataModelException getDataModelExc(String msg,
YangLeafRef leafRef) {
DataModelException exc = new DataModelException(
msg + leafRef.getPath());
exc.setCharPosition(leafRef.getCharPosition());
exc.setLine(leafRef.getLineNumber());
return exc;
}
}
| 41.711628
| 120
| 0.579817
|
761c9e26ef04ad88ce2c843ea8e9d39bcac37fe0
| 22,040
|
/**
* Copyright (C) 2008-2011 10gen Inc.
*
* 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 org.bson;
import org.bson.io.BSONByteBuffer;
import org.bson.types.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* @author antoine
* @author brendan
* @author scotthernandez
* @author Kilroy Wuz Here
*/
public class LazyBSONObject implements BSONObject {
public LazyBSONObject( byte[] data, LazyBSONCallback callback ){
this( BSONByteBuffer.wrap( data ), callback );
}
public LazyBSONObject( byte[] data, int offset, LazyBSONCallback callback ){
this( BSONByteBuffer.wrap( data, offset, data.length - offset ), offset, callback );
}
public LazyBSONObject( BSONByteBuffer buffer, LazyBSONCallback callback ){
this( buffer, 0, callback );
}
public LazyBSONObject( BSONByteBuffer buffer, int offset, LazyBSONCallback callback ){
_callback = callback;
_input = buffer;
_doc_start_offset = offset;
}
class ElementRecord {
ElementRecord( final String name, final int offset ){
this.name = name;
this.offset = offset;
this.type = getElementType( offset - 1 );
this.fieldNameSize = sizeCString( offset );
this.valueOffset = offset + fieldNameSize;
}
final String name;
/**
* The offset the record begins at.
*/
final byte type;
final int fieldNameSize;
final int valueOffset;
final int offset;
}
class LazyBSONKeyIterator implements Iterator<String> {
public boolean hasNext(){
return !isElementEmpty( offset );
}
public String next(){
int fieldSize = sizeCString( offset + 1);
int elementSize = getElementBSONSize( offset );
String key = _input.getCString( offset + 1);
offset += fieldSize + elementSize + 1;
return key;
}
public void remove(){
throw new UnsupportedOperationException( "Read only" );
}
int offset = _doc_start_offset + FIRST_ELMT_OFFSET;
}
public class LazyBSONKeySet extends ReadOnlySet<String> {
/**
* This method runs in time linear to the total size of all keys in the document.
*
* @return the number of keys in the document
*/
@Override
public int size(){
int size = 0;
Iterator<String> iter = iterator();
while(iter.hasNext()) {
iter.next();
++size;
}
return size;
}
@Override
public boolean isEmpty(){
return LazyBSONObject.this.isEmpty();
}
@Override
public boolean contains( Object o ){
for ( String key : this ){
if ( key.equals( o ) ){
return true;
}
}
return false;
}
@Override
public Iterator<String> iterator(){
return new LazyBSONKeyIterator();
}
@Override
public String[] toArray(){
String[] a = new String[size()];
return toArray(a);
}
@SuppressWarnings( "unchecked" )
@Override
public <T> T[] toArray(T[] a) {
int size = size();
T[] localArray = a.length >= size ? a :
(T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
int i = 0;
for ( String key : this ){
localArray[i++] = (T) key;
}
if (localArray.length > i) {
localArray[i] = null;
}
return localArray;
}
@Override
public boolean add( String e ){
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public boolean remove( Object o ){
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public boolean containsAll( Collection<?> collection ){
for ( Object item : collection ){
if ( !contains( item ) ){
return false;
}
}
return true;
}
}
class LazyBSONEntryIterator implements Iterator<Map.Entry<String, Object>> {
public boolean hasNext(){
return !isElementEmpty( offset );
}
public Map.Entry<String, Object> next(){
int fieldSize = sizeCString(offset + 1);
int elementSize = getElementBSONSize(offset);
String key = _input.getCString(offset + 1);
final ElementRecord nextElementRecord = new ElementRecord(key, ++offset);
offset += fieldSize + elementSize;
return new Map.Entry<String, Object>() {
@Override
public String getKey() {
return nextElementRecord.name;
}
@Override
public Object getValue() {
return getElementValue(nextElementRecord);
}
@Override
public Object setValue(Object value) {
throw new UnsupportedOperationException("Read only");
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry) o;
return getKey().equals(e.getKey()) && getValue().equals(e.getValue());
}
@Override
public int hashCode() {
return getKey().hashCode() ^ getValue().hashCode();
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
};
}
public void remove(){
throw new UnsupportedOperationException( "Read only" );
}
int offset = _doc_start_offset + FIRST_ELMT_OFFSET;
}
class LazyBSONEntrySet extends ReadOnlySet<Map.Entry<String, Object>> {
@Override
public int size() {
return LazyBSONObject.this.keySet().size();
}
@Override
public boolean isEmpty() {
return LazyBSONObject.this.isEmpty();
}
@Override
public boolean contains(Object o) {
Iterator<Map.Entry<String, Object>> iter = iterator();
while (iter.hasNext()) {
if (iter.next().equals(o)) {
return true;
}
}
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object cur : c) {
if (!contains(cur)) {
return false;
}
}
return true;
}
@Override
public Iterator<Map.Entry<String, Object>> iterator() {
return new LazyBSONEntryIterator();
}
@Override
public Object[] toArray() {
Map.Entry[] array = new Map.Entry[size()];
return toArray(array);
}
@SuppressWarnings( "unchecked" )
@Override
public <T> T[] toArray(T[] a) {
int size = size();
T[] localArray = a.length >= size ? a :
(T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
Iterator<Map.Entry<String, Object>> iter = iterator();
int i = 0;
while(iter.hasNext()) {
localArray[i++] = (T) iter.next();
}
if (localArray.length > i) {
localArray[i] = null;
}
return localArray;
}
}
// Base class that throws UnsupportedOperationException for any method that writes to the Set
abstract class ReadOnlySet<E> implements Set<E> {
@Override
public boolean add(E e) {
throw new UnsupportedOperationException("Read-only Set");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Read-only Set");
}
@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException("Read-only Set");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("Read-only Set");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("Read-only Set");
}
@Override
public void clear() {
throw new UnsupportedOperationException("Read-only Set");
}
}
public Object put( String key, Object v ){
throw new UnsupportedOperationException( "Object is read only" );
}
public void putAll( BSONObject o ){
throw new UnsupportedOperationException( "Object is read only" );
}
public void putAll( Map m ){
throw new UnsupportedOperationException( "Object is read only" );
}
public Object get( String key ){
//get element up to the key
ElementRecord element = getElement(key);
//no found if null/empty
if (element == null) {
return null;
}
return getElementValue(element);
}
/**
* returns the ElementRecord for the given key, or null if not found
* @param key the field/key to find
* @return ElementRecord for key, or null
*/
ElementRecord getElement(String key){
int offset = _doc_start_offset + FIRST_ELMT_OFFSET;
while ( !isElementEmpty( offset ) ){
int fieldSize = sizeCString( offset + 1 );
int elementSize = getElementBSONSize( offset );
String name = _input.getCString( ++offset);
if (name.equals(key)) {
return new ElementRecord( name, offset );
}
offset += ( fieldSize + elementSize);
}
return null;
}
/**
* returns all the ElementRecords in this document
* @return list of ElementRecord
*/
List<ElementRecord> getElements(){
int offset = _doc_start_offset + FIRST_ELMT_OFFSET;
ArrayList<ElementRecord> elements = new ArrayList<LazyBSONObject.ElementRecord>();
while ( !isElementEmpty( offset ) ){
int fieldSize = sizeCString( offset + 1 );
int elementSize = getElementBSONSize( offset );
String name = _input.getCString( ++offset );
ElementRecord rec = new ElementRecord( name, offset );
elements.add( rec );
offset += ( fieldSize + elementSize );
}
return elements;
}
public Map toMap(){
throw new UnsupportedOperationException( "Not Supported" );
}
public Object removeField( String key ){
throw new UnsupportedOperationException( "Object is read only" );
}
@Deprecated
public boolean containsKey( String s ){
return containsField( s );
}
public boolean containsField( String s ){
return keySet().contains( s );
}
/**
*
* @return the set of all keys in the document
*/
public Set<String> keySet(){
return new LazyBSONKeySet();
}
/**
* This method will be more efficient than using a combination of keySet() and get(String key)
* @return the set of entries (key, value) in the document
*/
public Set<Map.Entry<String, Object>> entrySet(){
return new LazyBSONEntrySet();
}
protected boolean isElementEmpty( int offset ){
return getElementType( offset ) == BSON.EOO;
}
public boolean isEmpty(){
return isElementEmpty( _doc_start_offset + FIRST_ELMT_OFFSET );
}
private int getBSONSize( final int offset ){
return _input.getInt( offset );
}
public int getBSONSize(){
return getBSONSize( _doc_start_offset );
}
public int pipe(OutputStream os) throws IOException {
os.write(_input.array(), _doc_start_offset, getBSONSize());
return getBSONSize();
}
private String getElementFieldName( final int offset ){
return _input.getCString( offset );
}
protected byte getElementType( final int offset ){
return _input.get( offset );
}
protected int getElementBSONSize( int offset ){
int x = 0;
byte type = getElementType( offset++ );
int n = sizeCString( offset );
int valueOffset = offset + n;
switch ( type ){
case BSON.EOO:
case BSON.UNDEFINED:
case BSON.NULL:
case BSON.MAXKEY:
case BSON.MINKEY:
break;
case BSON.BOOLEAN:
x = 1;
break;
case BSON.NUMBER_INT:
x = 4;
break;
case BSON.TIMESTAMP:
case BSON.DATE:
case BSON.NUMBER_LONG:
case BSON.NUMBER:
x = 8;
break;
case BSON.OID:
x = 12;
break;
case BSON.SYMBOL:
case BSON.CODE:
case BSON.STRING:
x = _input.getInt( valueOffset ) + 4;
break;
case BSON.CODE_W_SCOPE:
x = _input.getInt( valueOffset );
break;
case BSON.REF:
x = _input.getInt( valueOffset ) + 4 + 12;
break;
case BSON.OBJECT:
case BSON.ARRAY:
x = _input.getInt( valueOffset );
break;
case BSON.BINARY:
x = _input.getInt( valueOffset ) + 4 + 1/*subtype*/;
break;
case BSON.REGEX:
// 2 cstrs
int part1 = sizeCString( valueOffset );
int part2 = sizeCString( valueOffset + part1 );
x = part1 + part2;
break;
default:
throw new BSONException( "Invalid type " + type + " for field " + getElementFieldName( offset ) );
}
return x;
}
/**
* Returns the size of the BSON cstring at the given offset in the buffer
* @param offset the offset into the buffer
* @return the size of the BSON cstring, including the null terminator
*/
protected int sizeCString( int offset ){
int end = offset;
while ( true ){
byte b = _input.get( end );
if ( b == 0 )
break;
else
end++;
}
return end - offset + 1;
}
protected Object getElementValue( ElementRecord record ){
switch ( record.type ){
case BSON.EOO:
case BSON.UNDEFINED:
case BSON.NULL:
return null;
case BSON.MAXKEY:
return new MaxKey();
case BSON.MINKEY:
return new MinKey();
case BSON.BOOLEAN:
return ( _input.get( record.valueOffset ) != 0 );
case BSON.NUMBER_INT:
return _input.getInt( record.valueOffset );
case BSON.TIMESTAMP:
int inc = _input.getInt( record.valueOffset );
int time = _input.getInt( record.valueOffset + 4 );
return new BSONTimestamp( time, inc );
case BSON.DATE:
return new Date( _input.getLong( record.valueOffset ) );
case BSON.NUMBER_LONG:
return _input.getLong( record.valueOffset );
case BSON.NUMBER:
return Double.longBitsToDouble( _input.getLong( record.valueOffset ) );
case BSON.OID:
return new ObjectId( _input.getIntBE( record.valueOffset ),
_input.getIntBE( record.valueOffset + 4 ),
_input.getIntBE( record.valueOffset + 8 ) );
case BSON.SYMBOL:
return new Symbol( _input.getUTF8String( record.valueOffset ) );
case BSON.CODE:
return new Code( _input.getUTF8String( record.valueOffset ) );
case BSON.STRING:
return _input.getUTF8String( record.valueOffset );
case BSON.CODE_W_SCOPE:
int strsize = _input.getInt( record.valueOffset + 4 );
String code = _input.getUTF8String( record.valueOffset + 4 );
BSONObject scope =
(BSONObject) _callback.createObject( _input.array(), record.valueOffset + 4 + 4 + strsize );
return new CodeWScope( code, scope );
case BSON.REF:
int csize = _input.getInt( record.valueOffset );
String ns = _input.getCString( record.valueOffset + 4 );
int oidOffset = record.valueOffset + csize + 4;
ObjectId oid = new ObjectId( _input.getIntBE( oidOffset ),
_input.getIntBE( oidOffset + 4 ),
_input.getIntBE( oidOffset + 8 ) );
return _callback.createDBRef( ns, oid );
case BSON.OBJECT:
return _callback.createObject( _input.array(), record.valueOffset );
case BSON.ARRAY:
return _callback.createArray( _input.array(), record.valueOffset );
case BSON.BINARY:
return readBinary( record.valueOffset );
case BSON.REGEX:
int patternCStringSize = sizeCString( record.valueOffset );
String pattern = _input.getCString( record.valueOffset );
String flags = _input.getCString( record.valueOffset + patternCStringSize + 1 );
return Pattern.compile( pattern, BSON.regexFlags( flags ) );
default:
throw new BSONException(
"Invalid type " + record.type + " for field " + getElementFieldName( record.offset ) );
}
}
private Object readBinary( int valueOffset ){
final int totalLen = _input.getInt( valueOffset );
valueOffset += 4;
final byte bType = _input.get( valueOffset );
valueOffset += 1;
byte[] bin;
switch ( bType ){
case BSON.B_GENERAL:{
bin = new byte[totalLen];
for ( int n = 0; n < totalLen; n++ ){
bin[n] = _input.get( valueOffset + n );
}
return bin;
}
case BSON.B_BINARY:
final int len = _input.getInt( valueOffset );
if ( len + 4 != totalLen )
throw new IllegalArgumentException(
"Bad Data Size; Binary Subtype 2. { actual len: " + len + " expected totalLen: " + totalLen
+ "}" );
valueOffset += 4;
bin = new byte[len];
for ( int n = 0; n < len; n++ ){
bin[n] = _input.get( valueOffset + n );
}
return bin;
case BSON.B_UUID:
if ( totalLen != 16 )
throw new IllegalArgumentException(
"Bad Data Size; Binary Subtype 3 (UUID). { total length: " + totalLen + " != 16" );
long part1 = _input.getLong( valueOffset );
valueOffset += 8;
long part2 = _input.getLong( valueOffset );
return new UUID( part1, part2 );
}
bin = new byte[totalLen];
for ( int n = 0; n < totalLen; n++ ){
bin[n] = _input.get( valueOffset + n );
}
return bin;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LazyBSONObject that = (LazyBSONObject) o;
return Arrays.equals(this._input.array(), that._input.array());
}
@Override
public int hashCode() {
return Arrays.hashCode(_input.array());
}
/**
* Returns a JSON serialization of this object
*
* @return JSON serialization
*/
public String toString(){
return com.mongodb.util.JSON.serialize( this );
}
/**
* In a "normal" (aka not embedded) doc, this will be the offset of the first element.
*
* In an embedded doc because we use ByteBuffers to avoid unecessary copying the offset must be manually set in
* _doc_start_offset
*/
final static int FIRST_ELMT_OFFSET = 4;
protected final int _doc_start_offset;
protected final BSONByteBuffer _input; // TODO - Guard this with synchronicity?
// callback is kept to create sub-objects on the fly
protected final LazyBSONCallback _callback;
private static final Logger log = Logger.getLogger( "org.bson.LazyBSONObject" );
}
| 32.081514
| 120
| 0.533621
|
be1997ddbd94669c536e670213daee8e2b3e378a
| 1,801
|
/*
* LicenseChecker Copyright 2019 Gamebuster19901
*
* 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 com.gamebuster19901.license.flags;
import java.io.File;
import java.io.FileNotFoundException;
import com.gamebuster19901.license.NotFileException;
import com.gamebuster19901.license.create.CheckerSettings;
import com.gamebuster19901.license.flags.HeaderFlag.LocationFlag;
import com.google.common.io.Files;
public final class FileFlag extends LocationFlag {
public FileFlag() {
super("file", "will read the license text from a file", 0);
this.exclude("string");
}
public byte[] getHeader(CheckerSettings settings, String location) throws Exception{
byte[] header;
File licenseFile = new File(settings.getMessage(location));
header = new byte[(int)licenseFile.length()];
Files.asByteSource(licenseFile).openStream().read(header, 0, (int)licenseFile.length());
return header;
}
@Override
public void validate(CheckerSettings settings, String extension, String value) throws Exception {
File f = new File(value);
if(!f.exists()) {
throw new FileNotFoundException("Could not find license file for extension " + extension + "\n\n" + f.getAbsolutePath());
}
if(f.isDirectory()) {
throw new NotFileException(f.getAbsolutePath());
}
}
}
| 32.745455
| 124
| 0.748473
|
90f73d7dd47bf38a238fd334ccfbfc2caa2c0761
| 3,664
|
/*
* MIT License
*
* Copyright (c) 2021 OpeningO Co.,Ltd.
*
* https://openingo.org
* contactus(at)openingo.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.openingo.spring.boot.extension.gedid.engine.etcd;
import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.KV;
import io.etcd.jetcd.kv.PutResponse;
import io.etcd.jetcd.options.PutOption;
import lombok.extern.slf4j.Slf4j;
import org.openingo.spring.boot.exception.DidException;
import org.openingo.spring.boot.extension.gedid.engine.IDidEngine;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* EtcdIdEngine
*
* @author Qicz
* @since 2021/7/2 23:45
*/
@Slf4j
public class EtcdIdEngine implements IDidEngine<Long> {
private final Client etcdClient;
private final KV kvClient;
private Long startId;
public EtcdIdEngine(Client etcdClient) {
this.etcdClient = etcdClient;
this.kvClient = etcdClient.getKVClient();
}
@Override
public void follow(String businessName, Long startId) {
this.startId = startId + 1L;
}
@Override
public String getEmbellishedName(String businessName) {
return String.format("%s-%s", GEDID, businessName);
}
@Override
public Long getFixedStartId(Long startId) {
if (Objects.isNull(startId)) {
return 1L;
}
if (startId < 0) {
startId = 1L;
}
return startId;
}
@Override
public Long next(String businessName) {
long id = -1L;
try {
PutOption putOption = PutOption.newBuilder().withPrevKV().build();
PutResponse putResponse = kvClient.put(
this.toByteSequence(this.getEmbellishedName(businessName)),
this.toByteSequence(""),
putOption).get();
id = putResponse.getPrevKv().getVersion() + this.startId;
} catch (Exception e) {
e.printStackTrace();
log.error(e.getLocalizedMessage());
throw new DidException(e.getLocalizedMessage());
}
return id;
}
@Override
public String engineName() {
return "etcd";
}
private ByteSequence toByteSequence(String data) {
return ByteSequence.from(data.getBytes(StandardCharsets.UTF_8));
}
/**
* will auto call when destroy
*/
private void close() {
String name = this.engineName();
log.info("the `{}` engine is closing...", name);
this.etcdClient.close();
log.info("the `{}` engine is closed", name);
}
}
| 31.050847
| 81
| 0.666485
|
2c164653ba4e881b6e7f5ee047cd8ae88612cf9c
| 2,515
|
package com.pacgame.provider.component.ui.text;
import com.pacgame.provider.Paint;
import com.pacgame.provider.alignment.PositionAlignment;
import com.pacgame.provider.component.UIElementProvidedObject;
public class Label extends UIElementProvidedObject {
protected LabelProxy proxy;
protected String text;
public Label(String text) {
this.text = text;
proxy = new LabelProxy();
proxy.setText(text);
}
public void setAlignment(PositionAlignment positionAlignment) {
proxy.setAlignment(positionAlignment.getProxy());
}
public void setText(String text) {
this.text = text;
proxy.setText(text);
}
public String getText() {
return text;
}
@Override
public void setBorder(Paint paint, int width) {
proxy.setBorder(paint.getProxy(), width);
}
@Override
protected LabelProxy getProxy() {
return proxy;
}
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
@Override
public String toString() {
String klassName = getClass().getName();
String simpleName = klassName.substring(klassName.lastIndexOf('.')+1);
StringBuilder sbuf = new StringBuilder(simpleName);
sbuf.append("[");
sbuf.append("Text=\"" + getText() + "\"");
sbuf.append(", ");
sbuf.append("X=" + getX());
sbuf.append(", ");
sbuf.append("Y=" + getY());
sbuf.append(", ");
sbuf.append("Width=" + getWidth());
sbuf.append(", ");
sbuf.append("Height=" + getHeight());
sbuf.append("]");
return sbuf.toString();
}
}
| 29.940476
| 78
| 0.623459
|
94aba1def98b75db8c52272d31b0c580861f90d6
| 2,861
|
package org.coredb.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* TopicView
*/
@Validated
public class TopicView {
@JsonProperty("topicId")
private String topicId = null;
@JsonProperty("position")
private Integer position = null;
@JsonProperty("revision")
private Integer revision = null;
public TopicView topicId(String topicId) {
this.topicId = topicId;
return this;
}
/**
* Get topicId
* @return topicId
**/
@Schema(required = true, description = "")
@NotNull
public String getTopicId() {
return topicId;
}
public void setTopicId(String topicId) {
this.topicId = topicId;
}
public TopicView position(Integer position) {
this.position = position;
return this;
}
/**
* Get position
* @return position
**/
@Schema(required = true, description = "")
@NotNull
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public TopicView revision(Integer revision) {
this.revision = revision;
return this;
}
/**
* Get revision
* @return revision
**/
@Schema(required = true, description = "")
@NotNull
@Valid
public Integer getRevision() {
return revision;
}
public void setRevision(Integer revision) {
this.revision = revision;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TopicView topicView = (TopicView) o;
return Objects.equals(this.topicId, topicView.topicId) &&
Objects.equals(this.position, topicView.position) &&
Objects.equals(this.revision, topicView.revision);
}
@Override
public int hashCode() {
return Objects.hash(topicId, position, revision);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TopicView {\n");
sb.append(" topicId: ").append(toIndentedString(topicId)).append("\n");
sb.append(" position: ").append(toIndentedString(position)).append("\n");
sb.append(" revision: ").append(toIndentedString(revision)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 21.674242
| 80
| 0.650472
|
614a1353bf8fcc386e36d0023c2f0b513c270e1f
| 1,283
|
package info.smart_tools.smartactors.checkpoint.interfaces;
import info.smart_tools.smartactors.checkpoint.interfaces.exceptions.RecoverStrategyExecutionException;
import info.smart_tools.smartactors.checkpoint.interfaces.exceptions.RecoverStrategyInitializationException;
import info.smart_tools.smartactors.iobject.iobject.IObject;
import info.smart_tools.smartactors.message_processing_interfaces.message_processing.IMessageProcessor;
/**
* Interface for a strategy re-sending a message.
*/
public interface IRecoverStrategy {
/**
* Prepare checkpoint entry for execution of this recover strategy.
*
* @param state state of checkpoint entry
* @param args recover strategy configuration
* @param processor message processor processing the original message
* @throws RecoverStrategyInitializationException if any error occurs
*/
void init(IObject state, IObject args, IMessageProcessor processor) throws RecoverStrategyInitializationException;
/**
* Re-send message.
*
* @param state state of the checkpoint entry associated with the message
* @throws RecoverStrategyExecutionException if eny error occurs
*/
void reSend(IObject state) throws RecoverStrategyExecutionException;
}
| 42.766667
| 118
| 0.777085
|
f83aac80dbf6cf1411bea76a9e0c0c80c9f75179
| 37,078
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.recovery;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.core.persistence.registry.RegistryResourceMgtService;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder;
import org.wso2.carbon.identity.recovery.model.ChallengeQuestion;
import org.wso2.carbon.identity.recovery.model.UserChallengeAnswer;
import org.wso2.carbon.identity.recovery.util.Utils;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.CollectionImpl;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.wso2.carbon.identity.recovery.IdentityRecoveryConstants.LOCALE_EN_US;
/**
* OSGi Service to handle functionality related to challenge question management and verification.
*/
public class ChallengeQuestionManager {
private static final Log log = LogFactory.getLog(ChallengeQuestionManager.class);
private static ChallengeQuestionManager instance = new ChallengeQuestionManager();
private ChallengeQuestionManager() {
}
public static ChallengeQuestionManager getInstance() {
return instance;
}
private IdentityRecoveryServiceDataHolder dataHolder = IdentityRecoveryServiceDataHolder.getInstance();
private RegistryResourceMgtService resourceMgtService = dataHolder.getResourceMgtService();
private static final String QUESTIONS_BASE_PATH = IdentityRecoveryConstants.IDENTITY_MANAGEMENT_QUESTIONS;
/**
* Get all challenge questions registered for a tenant.
*
* @param tenantDomain
* @return
* @throws IdentityRecoveryServerException
*/
public List<ChallengeQuestion> getAllChallengeQuestions(String tenantDomain) throws IdentityRecoveryServerException {
tenantDomain = validateTenantDomain(tenantDomain);
List<ChallengeQuestion> challengeQuestions = new ArrayList<>();
try {
Resource questionCollection = resourceMgtService.getIdentityResource(QUESTIONS_BASE_PATH, tenantDomain);
if (questionCollection != null) {
Collection questionSetCollection = (Collection) resourceMgtService.getIdentityResource(
QUESTIONS_BASE_PATH, tenantDomain);
for (String questionSetId : questionSetCollection.getChildren()) {
Collection questionIdCollection =
(Collection) resourceMgtService.getIdentityResource(questionSetId, tenantDomain);
// iterate each question to find the one with correct locale
for (String questionIdPath : questionIdCollection.getChildren()) {
Collection questions =
(Collection) resourceMgtService.getIdentityResource(questionIdPath, tenantDomain);
for (String question : questions.getChildren()) {
Resource resource = resourceMgtService.getIdentityResource(question, tenantDomain);
if (resource != null) {
challengeQuestions.add(createChallengeQuestion(resource));
}
}
}
}
}
return challengeQuestions;
} catch (RegistryException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_REGISTRY_EXCEPTION_GET_CHALLENGE_QUESTIONS, null, e);
}
}
/**
* Get registered challenge questions in tenant based on a locale.
*
* @param tenantDomain
* @param locale
* @return
* @throws IdentityRecoveryException
*/
public List<ChallengeQuestion> getAllChallengeQuestions(String tenantDomain, String locale)
throws IdentityRecoveryException {
// check the value and set defaults if empty or null
locale = validateLocale(locale);
tenantDomain = validateTenantDomain(tenantDomain);
List<ChallengeQuestion> questions = new ArrayList<>();
try {
Resource questionCollection = resourceMgtService.getIdentityResource(QUESTIONS_BASE_PATH, tenantDomain);
// check whether the base challenge question directory exists
if (questionCollection != null) {
Collection questionSetCollection = (Collection) resourceMgtService.getIdentityResource(
QUESTIONS_BASE_PATH, tenantDomain);
for (String questionSetId : questionSetCollection.getChildren()) {
Collection questionIdCollection = (Collection) resourceMgtService.
getIdentityResource(questionSetId, tenantDomain);
// iterate each question to find the one with correct locale
for (String questionIdPath : questionIdCollection.getChildren()) {
Resource questionResource = resourceMgtService.getIdentityResource(questionIdPath,
tenantDomain, locale);
if (questionResource != null) {
questions.add(createChallengeQuestion(questionResource));
}
}
}
}
} catch (RegistryException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_REGISTRY_EXCEPTION_GET_CHALLENGE_QUESTIONS, null, e);
}
return questions;
}
/**
* Get challenge questions available for a user.
*
* @param tenantDomain tenantDomain of the user
* @param user User object
* @return List of available challenge questions in user's locale in the tenantDomain. If no challenge questions
* are available we return challenge questions from the default en_US locale.
* @throws IdentityRecoveryException
*/
public List<ChallengeQuestion> getAllChallengeQuestionsForUser(String tenantDomain,
User user) throws IdentityRecoveryException {
// Identify the locale of the user
String locale = getLocaleOfUser(user, tenantDomain);
// get challenge questions in the given tenant domain for give locale.
List<ChallengeQuestion> challengeQuestions = getAllChallengeQuestions(tenantDomain, locale);
/*
If there are no challenge questions found in the locale of the user and the locale is not the default one.
we return challenge questions from default en_US locale.
*/
if (challengeQuestions.isEmpty() && !StringUtils.equalsIgnoreCase(LOCALE_EN_US, locale)) {
String error = "No challenge questions available in '%s' locale in %s tenant. Sending questions of " +
"default '%s' locale";
log.error(String.format(error, locale, tenantDomain, LOCALE_EN_US));
challengeQuestions = getAllChallengeQuestions(tenantDomain, LOCALE_EN_US);
}
return challengeQuestions;
}
/**
* Set default challenge questions to a tenant registry. (This is done during startup)
*
* @param tenantDomain
* @throws IdentityRecoveryException
*/
public void setDefaultChallengeQuestions(String tenantDomain) throws IdentityRecoveryException {
tenantDomain = validateTenantDomain(tenantDomain);
// check whether we already have default questions.
boolean isDefaultAvailable = !getAllChallengeQuestions(tenantDomain).isEmpty();
if (isDefaultAvailable) {
if (log.isDebugEnabled()) {
log.debug("Default Challenge Questions already available.");
}
return;
}
ChallengeQuestion[] questions = Utils.getDefaultChallengeQuestions();
addChallengeQuestions(questions, tenantDomain);
if (log.isDebugEnabled()) {
String errorMsg = "%d default challenge questions added to registry of %s tenant.";
log.debug(String.format(errorMsg, questions.length, tenantDomain));
}
}
/**
* Add new challenge questions to the registry of a tenant
*
* @param questions
* @param tenantDomain
* @throws IdentityRecoveryException
*/
public void addChallengeQuestions(ChallengeQuestion[] questions, String tenantDomain) throws IdentityRecoveryException {
try {
tenantDomain = validateTenantDomain(tenantDomain);
// check whether registry path for question collection exists
Resource challengeQuestionCollection =
resourceMgtService.getIdentityResource(QUESTIONS_BASE_PATH, tenantDomain);
// create the question collection if it does not exist
if (challengeQuestionCollection == null) {
challengeQuestionCollection = new CollectionImpl();
resourceMgtService.
putIdentityResource(challengeQuestionCollection, QUESTIONS_BASE_PATH, tenantDomain);
}
for (ChallengeQuestion challengeQuestion : questions) {
validateChallengeQuestionAttributes(challengeQuestion);
String questionPath = getQuestionPath(challengeQuestion);
String locale = validateLocale(challengeQuestion.getLocale());
// create a registry resource
Resource resource = createRegistryResource(challengeQuestion);
resourceMgtService.putIdentityResource(resource, questionPath, tenantDomain, locale);
}
} catch (RegistryException | UnsupportedEncodingException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_REGISTRY_EXCEPTION_SET_CHALLENGE_QUESTIONS, null, e);
}
}
/**
* Delete challenge questions from a tenant registry.
*
* @param challengeQuestions
* @param tenantDomain
* @throws IdentityRecoveryException
*/
public void deleteChallengeQuestions(ChallengeQuestion[] challengeQuestions, String tenantDomain)
throws IdentityRecoveryException {
try {
tenantDomain = validateTenantDomain(tenantDomain);
for (ChallengeQuestion question : challengeQuestions) {
if (isChallengeQuestionExists(question, tenantDomain)) {
String questionPath = getQuestionPath(question);
String locale = question.getLocale();
resourceMgtService.deleteIdentityResource(questionPath, tenantDomain, locale);
}
}
} catch (IdentityRuntimeException e) {
log.error("Error deleting challenge quesitons in " + tenantDomain);
throw new IdentityRecoveryException("Error when deleting challenge questions.", e);
}
}
/**
* Get challenge questions answered by a user.
*
* @param user
* @return
*/
public UserChallengeAnswer[] getChallengeAnswersOfUser(User user) throws IdentityRecoveryException {
validateUser(user);
List<UserChallengeAnswer> userChallengeAnswers = new ArrayList<>();
if (log.isDebugEnabled()) {
log.debug("Retrieving Challenge question from the user profile.");
}
List<String> challengesUris = getChallengeQuestionUris(user);
for (String challengesUri1 : challengesUris) {
String challengesUri = challengesUri1.trim();
String challengeValue;
try {
challengeValue = Utils.getClaimFromUserStoreManager(user, challengesUri);
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_GETTING_CHALLENGE_QUESTIONS, user.getUserName(), e);
}
String challengeQuestionSeparator = IdentityUtil.getProperty(IdentityRecoveryConstants.ConnectorConfig
.QUESTION_CHALLENGE_SEPARATOR);
if (StringUtils.isEmpty(challengeQuestionSeparator)) {
challengeQuestionSeparator = IdentityRecoveryConstants.DEFAULT_CHALLENGE_QUESTION_SEPARATOR;
}
String[] challengeValues = challengeValue.split(challengeQuestionSeparator);
if (challengeValues != null && challengeValues.length == 2) {
ChallengeQuestion userChallengeQuestion = new ChallengeQuestion(challengesUri,
challengeValues[0].trim());
UserChallengeAnswer userChallengeAnswer = new UserChallengeAnswer(userChallengeQuestion,
challengeValues[1].trim());
userChallengeAnswers.add(userChallengeAnswer);
}
}
if (!userChallengeAnswers.isEmpty()) {
return userChallengeAnswers.toArray(new UserChallengeAnswer[userChallengeAnswers.size()]);
} else {
return new UserChallengeAnswer[0];
}
}
/**
* Retrieve the challenge question answered from a particular challenge question set.
*
* @param user
* @param challengesUri claim uri of the challenge set
* @return
* @throws IdentityRecoveryException
*/
public ChallengeQuestion getUserChallengeQuestion(User user, String challengesUri) throws IdentityRecoveryException {
validateUser(user);
ChallengeQuestion userChallengeQuestion = null;
if (log.isDebugEnabled()) {
log.debug("Retrieving Challenge question from the user profile.");
}
String challengeValue = null;
try {
challengeValue = Utils.getClaimFromUserStoreManager(user, challengesUri);
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_GETTING_CHALLENGE_QUESTION, user.getUserName(), e);
}
if (challengeValue != null) {
String challengeQuestionSeparator = IdentityUtil.getProperty(IdentityRecoveryConstants.ConnectorConfig
.QUESTION_CHALLENGE_SEPARATOR);
if (StringUtils.isEmpty(challengeQuestionSeparator)) {
challengeQuestionSeparator = IdentityRecoveryConstants.DEFAULT_CHALLENGE_QUESTION_SEPARATOR;
}
String[] challengeValues = challengeValue.split(challengeQuestionSeparator);
if (challengeValues != null && challengeValues.length == 2) {
userChallengeQuestion = new ChallengeQuestion(challengesUri, challengeValues[0].trim());
}
}
return userChallengeQuestion;
}
public String[] getUserChallengeQuestionIds(User user)
throws IdentityRecoveryException {
validateUser(user);
if (log.isDebugEnabled()) {
log.debug("Retrieving answered Challenge question set ids from the user profile.");
}
List<String> challengesUris = getChallengeQuestionUris(user);
if (challengesUris.isEmpty()) {
String msg = "No associated challenge question found for the user : " + user.getUserName();
if (log.isDebugEnabled()) {
log.debug(msg);
}
return new String[0];
}
String[] urls = new String[challengesUris.size()];
return challengesUris.toArray(urls);
}
/**
* Get the claims URIs of the challenge sets answered by the user
*
* @param user
* @return
*/
public List<String> getChallengeQuestionUris(User user) throws IdentityRecoveryException {
validateUser(user);
if (log.isDebugEnabled()) {
String msg = String.format("Getting answered challenge question uris from %s's profile.", user.toString());
log.debug(msg);
}
List<String> challenges = new ArrayList<String>();
String claimValue = null;
String[] challengesUris;
try {
claimValue = Utils.getClaimFromUserStoreManager(user, IdentityRecoveryConstants.CHALLENGE_QUESTION_URI);
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_GETTING_CHALLENGE_URIS, user.getUserName(), e);
}
if (claimValue != null) {
String challengeQuestionSeparator = IdentityUtil.getProperty(IdentityRecoveryConstants.ConnectorConfig
.QUESTION_CHALLENGE_SEPARATOR);
if (StringUtils.isEmpty(challengeQuestionSeparator)) {
challengeQuestionSeparator = IdentityRecoveryConstants.DEFAULT_CHALLENGE_QUESTION_SEPARATOR;
}
if (claimValue.contains(challengeQuestionSeparator)) {
challengesUris = claimValue.split(challengeQuestionSeparator);
} else {
challengesUris = new String[]{claimValue.trim()};
}
for (String challengesUri : challengesUris) {
if (StringUtils.isNotBlank(challengesUri)) {
challenges.add(challengesUri.trim());
}
}
}
return challenges;
}
/**
* @param user
* @param userChallengeAnswers
* @throws IdentityException
*/
public void setChallengesOfUser(User user, UserChallengeAnswer[] userChallengeAnswers) throws IdentityRecoveryException {
validateUser(user);
if (log.isDebugEnabled()) {
log.debug(String.format("Setting user challenge question answers in %s's profile.", user.toString()));
}
try {
String tenantDomain = StringUtils.isBlank(user.getTenantDomain()) ?
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME : user.getTenantDomain();
// validate whether two questions from the same set has been answered.
validateSecurityQuestionDuplicate(userChallengeAnswers);
// check whether the answered questions exist in the tenant domain
checkChallengeQuestionExists(userChallengeAnswers, tenantDomain);
List<String> challengesUris = new ArrayList<String>();
String challengesUrisValue = "";
String separator = IdentityUtil.getProperty(IdentityRecoveryConstants.ConnectorConfig
.QUESTION_CHALLENGE_SEPARATOR);
if (StringUtils.isEmpty(separator)) {
separator = IdentityRecoveryConstants.DEFAULT_CHALLENGE_QUESTION_SEPARATOR;
}
if (!ArrayUtils.isEmpty(userChallengeAnswers)) {
for (UserChallengeAnswer userChallengeAnswer : userChallengeAnswers) {
if (userChallengeAnswer.getQuestion().getQuestionSetId() != null && userChallengeAnswer.getQuestion().getQuestion() !=
null && userChallengeAnswer.getAnswer() != null) {
String oldValue = Utils.
getClaimFromUserStoreManager(user, userChallengeAnswer.getQuestion().getQuestionSetId().trim());
if (oldValue != null && oldValue.contains(separator)) {
String oldAnswer = oldValue.split(separator)[1];
if (!oldAnswer.trim().equals(userChallengeAnswer.getAnswer().trim())) {
String claimValue = userChallengeAnswer.getQuestion().getQuestion().trim() + separator +
Utils.doHash(userChallengeAnswer.getAnswer().trim().toLowerCase());
Utils.setClaimInUserStoreManager(user, userChallengeAnswer.getQuestion().getQuestionSetId().trim(),
claimValue);
}
} else {
String claimValue = userChallengeAnswer.getQuestion().getQuestion().trim() + separator +
Utils.doHash(userChallengeAnswer.getAnswer().trim().toLowerCase());
Utils.setClaimInUserStoreManager(user, userChallengeAnswer.getQuestion().getQuestionSetId().trim(),
claimValue);
}
challengesUris.add(userChallengeAnswer.getQuestion().getQuestionSetId().trim());
}
}
for (String challengesUri : challengesUris) {
if ("".equals(challengesUrisValue)) {
challengesUrisValue = challengesUri;
} else {
challengesUrisValue = challengesUrisValue +
separator + challengesUri;
}
}
Utils.setClaimInUserStoreManager(user, IdentityRecoveryConstants.CHALLENGE_QUESTION_URI, challengesUrisValue);
}
} catch (org.wso2.carbon.user.api.UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_QUESTION_OF_USER, user.getUserName(), e);
}
}
/**
* @param user
* @param userChallengeAnswers
* @return
*/
public boolean verifyChallengeAnswer(User user, UserChallengeAnswer[] userChallengeAnswers) throws
IdentityRecoveryException {
validateUser(user);
boolean verification = false;
if (log.isDebugEnabled()) {
log.debug(String.format("Verifying challenge question answers for %s.", user.toString()));
}
UserChallengeAnswer[] storedAnswers = getChallengeAnswersOfUser(user);
for (UserChallengeAnswer userChallengeAnswer : userChallengeAnswers) {
if (StringUtils.isBlank(userChallengeAnswer.getAnswer())) {
return false;
}
for (UserChallengeAnswer storedAnswer : storedAnswers) {
if ((userChallengeAnswer.getQuestion().getQuestionSetId() == null || !userChallengeAnswer.getQuestion().getQuestionSetId()
.trim().equals(storedAnswer.getQuestion().getQuestionSetId())) &&
(userChallengeAnswer.getQuestion().getQuestion() == null || !userChallengeAnswer.getQuestion().getQuestion().
trim().equals(storedAnswer.getQuestion().getQuestion()))) {
continue;
}
String hashedAnswer = null;
try {
hashedAnswer = Utils.doHash(userChallengeAnswer.getAnswer().trim().toLowerCase());
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_NO_HASHING_ALGO, null, e);
}
if (hashedAnswer.equals(storedAnswer.getAnswer())) {
verification = true;
} else {
return false;
}
}
}
return verification;
}
public boolean verifyUserChallengeAnswer(User user, UserChallengeAnswer userChallengeAnswer)
throws IdentityRecoveryException {
// check whether user data are valid.
validateUser(user);
boolean verification = false;
if (log.isDebugEnabled()) {
log.debug(String.format("Verifying challenge question answer for %s.", user.toString()));
}
UserChallengeAnswer[] storedDto = getChallengeAnswersOfUser(user);
if (StringUtils.isBlank(userChallengeAnswer.getAnswer())) {
log.error("Invalid. Empty answer provided for the challenge question.");
return false;
}
for (UserChallengeAnswer dto : storedDto) {
if (dto.getQuestion().getQuestionSetId().equals(userChallengeAnswer.getQuestion().getQuestionSetId())) {
String hashedAnswer = null;
try {
hashedAnswer = Utils.doHash(userChallengeAnswer.getAnswer().trim().toLowerCase());
} catch (UserStoreException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages
.ERROR_CODE_NO_HASHING_ALGO, null, e);
}
if (hashedAnswer.equals(dto.getAnswer())) {
verification = true;
if (log.isDebugEnabled()) {
log.debug("Challenge question answer verified successfully.");
}
} else {
if (log.isDebugEnabled()) {
log.debug("Challenge question answer verification failed.");
}
return false;
}
}
}
return verification;
}
/**
* Check whether a challenge question exists in the tenant domain. Here we check whether a question exists with the
* given questionSetID, questionID and locale.
*
* @param challengeQuestion
* @param tenantDomain
* @return
* @throws IdentityRecoveryClientException
*/
private boolean isChallengeQuestionExists(ChallengeQuestion challengeQuestion, String tenantDomain)
throws IdentityRecoveryClientException {
validateChallengeQuestionAttributes(challengeQuestion);
String locale = validateLocale(challengeQuestion.getLocale());
String questionPath = getQuestionPath(challengeQuestion);
return (resourceMgtService.getIdentityResource(questionPath, tenantDomain, locale) != null);
}
/**
* Create a challenge question object from the registry resource
*
* @param resource
* @return
*/
private ChallengeQuestion createChallengeQuestion(Resource resource) throws RegistryException {
ChallengeQuestion challengeQuestion = null;
byte[] resourceContent = (byte[]) resource.getContent();
String questionText = new String(resourceContent, Charset.forName("UTF-8"));
String questionSetId = resource.getProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_SET_ID);
String questionId = resource.getProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_ID);
String questionLocale = resource.getProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_LOCALE);
if (questionSetId != null) {
if (IdentityUtil.isBlank(questionLocale)) {
questionLocale = LOCALE_EN_US;
}
challengeQuestion = new ChallengeQuestion(questionSetId, questionId, questionText, questionLocale);
}
return challengeQuestion;
}
/**
* Create registry resource from a challenge question model object.
*
* @param question
* @return
* @throws RegistryException
*/
private Resource createRegistryResource(ChallengeQuestion question) throws RegistryException, UnsupportedEncodingException {
byte[] questionText = question.getQuestion().getBytes("UTF-8");
String questionSetId = question.getQuestionSetId();
String questionId = question.getQuestionId();
String locale = question.getLocale();
Resource resource = new ResourceImpl();
resource.setContent(questionText);
resource.addProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_SET_ID, questionSetId);
resource.addProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_ID, questionId);
resource.addProperty(IdentityRecoveryConstants.Questions.CHALLENGE_QUESTION_LOCALE, locale); // added locale
resource.setMediaType(RegistryConstants.TAG_MEDIA_TYPE);
return resource;
}
/**
* Get the relative path to the parent directory of the challenge question resource.
*
* @param challengeQuestion
* @return Path to the parent of challenge question relative to the root of the registry.
*/
private String getQuestionPath(ChallengeQuestion challengeQuestion) {
// challenge set uri
String questionSetIdUri = challengeQuestion.getQuestionSetId();
String questionId = challengeQuestion.getQuestionId();
String questionSetId = Utils.getChallengeSetDirFromUri(questionSetIdUri);
return QUESTIONS_BASE_PATH + RegistryConstants.PATH_SEPARATOR + questionSetId +
RegistryConstants.PATH_SEPARATOR + questionId;
}
/**
* Validate whether two questions from the same question set have been answered (ie. we only allow a maximum of
* one question from each set)
*
* @param userChallengeAnswers
* @throws IdentityRecoveryException
*/
private void validateSecurityQuestionDuplicate(UserChallengeAnswer[] userChallengeAnswers)
throws IdentityRecoveryException {
Set<String> tmpMap = new HashSet<>();
UserChallengeAnswer challengeAnswer;
ChallengeQuestion challengeQuestion;
for (UserChallengeAnswer userChallengeAnswer : userChallengeAnswers) {
challengeAnswer = userChallengeAnswer;
challengeQuestion = challengeAnswer.getQuestion();
// if there's no challenge question details we throw a client exception
if (challengeQuestion == null) {
String errorMsg = "Challenge question details not provided with the challenge answers.";
throw Utils.handleClientException(
IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CHALLENGE_QUESTION_NOT_FOUND, errorMsg);
}
if (tmpMap.contains(challengeQuestion.getQuestionSetId())) {
String errMsg = "Validation Error. Cannot answer two questions from the same question set claim uri";
log.error(errMsg);
throw new IdentityRecoveryClientException(errMsg);
}
tmpMap.add(challengeQuestion.getQuestionSetId());
}
}
/**
* Check whether an answered challenge question actually exists in the tenant registry
*
* @param userChallengeAnswers
* @param tenantDomain
* @throws IdentityRecoveryClientException
*/
private void checkChallengeQuestionExists(UserChallengeAnswer[] userChallengeAnswers, String tenantDomain)
throws IdentityRecoveryException {
for (UserChallengeAnswer challengeAnswer : userChallengeAnswers) {
ChallengeQuestion challengeQuestion = challengeAnswer.getQuestion();
// if challenge question details are missing in the challenge answer we can't proceed further
if (challengeQuestion == null) {
String errorMsg = "Challenge question missing in the user challenge answer.";
throw new IdentityRecoveryClientException(errorMsg);
}
if (StringUtils.isBlank(challengeQuestion.getQuestion())) {
String errorMsg = "Invalid. Empty Challenge question provided.";
throw new IdentityRecoveryClientException(errorMsg);
}
String locale = validateLocale(challengeQuestion.getLocale());
List<ChallengeQuestion> challengeQuestions = getAllChallengeQuestions(tenantDomain, locale);
boolean isQuestionAvailable = false;
for (ChallengeQuestion availableQuestion : challengeQuestions) {
if (StringUtils.equals(availableQuestion.getQuestion().trim(), challengeQuestion.getQuestion().trim()
)) {
isQuestionAvailable = true;
}
}
if (!isQuestionAvailable) {
String error = "Error persisting user challenge answers for user. " +
"Challenge question answered is not registered with %s domain.";
throw Utils.handleClientException(
IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_CHALLENGE_QUESTION_NOT_FOUND,
String.format(error, tenantDomain));
}
}
}
private String validateTenantDomain(String tenantDomain) {
return StringUtils.isBlank(tenantDomain) ? MultitenantConstants.SUPER_TENANT_DOMAIN_NAME : tenantDomain;
}
private String validateLocale(String locale) throws IdentityRecoveryClientException {
// if the locale is blank, we go with the default locale
if (StringUtils.isBlank(locale)) {
locale = LOCALE_EN_US;
}
// validate locale input string
if (locale.matches(IdentityRecoveryConstants.Questions.BLACKLIST_REGEX)) {
log.error("Invalid locale value provided : " + locale);
throw new IdentityRecoveryClientException("Invalid Locale value provided : " + locale);
}
return locale;
}
private void validateUser(User user) throws IdentityRecoveryClientException {
if (user == null || StringUtils.isBlank(user.getUserName())) {
throw Utils.handleClientException(
IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_INVALID_USER, "Invalid User Data provided.");
}
}
private void validateChallengeQuestionAttributes(ChallengeQuestion question) throws IdentityRecoveryClientException {
String setId = question.getQuestionSetId();
String questionId = question.getQuestionId();
String questionText = question.getQuestion();
String questionLocale = question.getLocale();
if (StringUtils.isBlank(setId) || StringUtils.isBlank(questionId) || StringUtils.isBlank(questionText) ||
StringUtils.isBlank(questionLocale)) {
throw new IdentityRecoveryClientException
("Invalid Challenge Question. Attributes of Challenge question to be set cannot be empty.");
}
String challengeSetDir = Utils.getChallengeSetDirFromUri(setId);
String errorMsg = "%s contains non alpha-numeric characters.";
if (StringUtils.isBlank(challengeSetDir) || !StringUtils.isAlphanumeric(challengeSetDir)) {
throw new IdentityRecoveryClientException(String.format(errorMsg, "ChallengeSetId"));
}
if (!StringUtils.isAlphanumeric(questionId)) {
throw new IdentityRecoveryClientException(String.format(errorMsg, "QuestionId"));
}
}
private String getLocaleOfUser(User user, String tenantDomain) throws IdentityRecoveryException {
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(user.getUserName());
String locale = IdentityRecoveryConstants.LOCALE_EN_US;
try {
String userLocale =
Utils.getClaimFromUserStoreManager(user, IdentityRecoveryConstants.Questions.LOCALE_CLAIM);
if (StringUtils.isNotBlank(userLocale)) {
locale = userLocale;
}
} catch (UserStoreException e) {
String errorMsg = String.format("Error when retrieving the locale claim of user '%s' of '%s' domain.",
tenantAwareUserName, tenantDomain);
log.error(errorMsg);
throw new IdentityRecoveryServerException(errorMsg, e);
}
return locale;
}
}
| 42.914352
| 138
| 0.648471
|
610c6d36ae99361ef1f28f7f295a1b28eeb50ec4
| 180
|
package cn.xxt.designpattern.factorypattern;
/**
* 工厂模式中产品的基类
* @author zhq
* @date 2018/10/12 上午11:39
*/
public abstract class Product {
public abstract void method();
}
| 16.363636
| 44
| 0.7
|
8ef60cd49c88526fbd4fd2f5e982f6b77ce8cb31
| 4,078
|
package org.apache.maven.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Dependency
implements Serializable, Cloneable, InputLocationTracker
{
private String groupId;
private String artifactId;
private String version;
private String type = "jar";
private String classifier;
private String scope;
private String systemPath;
private List<Exclusion> exclusions;
private String optional;
private Map<Object, InputLocation> locations;
public Dependency() {}
public void addExclusion(Exclusion exclusion)
{
getExclusions().add(exclusion);
}
public Dependency clone()
{
try
{
Dependency copy = (Dependency)super.clone();
if (exclusions != null)
{
exclusions = new ArrayList();
for (Exclusion item : exclusions)
{
exclusions.add(item.clone());
}
}
if (locations != null)
{
locations = new LinkedHashMap(locations);
}
return copy;
}
catch (Exception ex)
{
throw ((RuntimeException)new UnsupportedOperationException(getClass().getName() + " does not support clone()").initCause(ex));
}
}
public String getArtifactId()
{
return artifactId;
}
public String getClassifier()
{
return classifier;
}
public List<Exclusion> getExclusions()
{
if (exclusions == null)
{
exclusions = new ArrayList();
}
return exclusions;
}
public String getGroupId()
{
return groupId;
}
public InputLocation getLocation(Object key)
{
return locations != null ? (InputLocation)locations.get(key) : null;
}
public String getOptional()
{
return optional;
}
public String getScope()
{
return scope;
}
public String getSystemPath()
{
return systemPath;
}
public String getType()
{
return type;
}
public String getVersion()
{
return version;
}
public void removeExclusion(Exclusion exclusion)
{
getExclusions().remove(exclusion);
}
public void setArtifactId(String artifactId)
{
this.artifactId = artifactId;
}
public void setClassifier(String classifier)
{
this.classifier = classifier;
}
public void setExclusions(List<Exclusion> exclusions)
{
this.exclusions = exclusions;
}
public void setGroupId(String groupId)
{
this.groupId = groupId;
}
public void setLocation(Object key, InputLocation location)
{
if (location != null)
{
if (locations == null)
{
locations = new LinkedHashMap();
}
locations.put(key, location);
}
}
public void setOptional(String optional)
{
this.optional = optional;
}
public void setScope(String scope)
{
this.scope = scope;
}
public void setSystemPath(String systemPath)
{
this.systemPath = systemPath;
}
public void setType(String type)
{
this.type = type;
}
public void setVersion(String version)
{
this.version = version;
}
public boolean isOptional()
{
return optional != null ? Boolean.parseBoolean(optional) : false;
}
public void setOptional(boolean optional)
{
this.optional = String.valueOf(optional);
}
public String toString()
{
return "Dependency {groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + ", type=" + type + "}";
}
public String getManagementKey()
{
return groupId + ":" + artifactId + ":" + type + (classifier != null ? ":" + classifier : "");
}
}
| 7.006873
| 132
| 0.568171
|
a702f36c2eaef1b45fa1ee00f777335006fc9c4c
| 656
|
package daggerok.rest;
import daggerok.client.model.FileItem;
import daggerok.service.FileService;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static java.util.stream.Collectors.toList;
@RestController
@RequiredArgsConstructor
public class FilesRestResource {
private final FileService fileService;
@GetMapping("/api/v1/files")
public List<FileItem> get() {
@Cleanup val stream = fileService.getDownloads();
return stream.collect(toList());
}
}
| 24.296296
| 62
| 0.797256
|
9b008b5c34140fedab67b4a42b95e11303e70b24
| 1,236
|
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> n = new ArrayList<>(){{
add(7);
add(5);
add(2);
add(12);
add(4);
add(8);
}};
/* Ex_1 */
int y = 200 * 600; // O(1)
int x = 800 *(700 / 200); // O(1)
System.out.println(x + y); // O(1) + O(1) = O(1)
/* Ex_2 */
double r = 800 * Math.PI; // O(1)
n.forEach((number) -> { //O(n)
System.out.println(number);
});
//Total: O(n)
/* Ex_3 */
for (int i = 0; i < n.size(); i++){ // O(n)
System.out.println(i);
System.out.println(n.get(i));
}
//todo countdown in the list
for (int i = n.size() -1; i > n.size(); i--); // O(n)
System.out.println();
// total: O(n) + O(n) = O(n)
/* Ex_4 */
for (int i = 0; i < n.size(); i++){ // O(n)
for (int j = 0; j < n.size(); j++){ // O(n^2)
System.out.println("How long");
}
}
// total: O(n^2)
}
}
| 23.769231
| 65
| 0.359223
|
fcdb4cdf2a37903b9dc2308b0a18ffe9ee3ad5fc
| 14,466
|
/*
* Copyright (c) 2019, 2021, Gluon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gluonhq;
import com.gluonhq.attach.AttachArtifactResolver;
import com.gluonhq.substrate.Constants;
import com.gluonhq.substrate.ProjectConfiguration;
import com.gluonhq.substrate.SubstrateDispatcher;
import com.gluonhq.substrate.model.Triplet;
import com.gluonhq.substrate.target.WebTargetConfiguration;
import com.gluonhq.utils.MavenArtifactResolver;
import org.apache.commons.exec.ProcessDestroyer;
import org.apache.commons.exec.ShutdownHookProcessDestroyer;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Repository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.graph.DependencyFilter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.gluonhq.attach.AttachArtifactResolver.DEPENDENCY_GROUP;
import static com.gluonhq.attach.AttachArtifactResolver.UTIL_ARTIFACT;
public abstract class NativeBaseMojo extends AbstractMojo {
private static final List<String> ALLOWED_DEPENDENCY_TYPES = Collections.singletonList("jar");
Path outputDir;
@Parameter(defaultValue = "${project}", readonly = true)
MavenProject project;
@Parameter(defaultValue = "${session}", readonly = true)
MavenSession session;
@Component
BuildPluginManager pluginManager;
@Parameter(readonly = true, required = true, defaultValue = "${basedir}")
File basedir;
@Parameter(property = "gluonfx.graalvmHome")
String graalvmHome;
@Parameter(property = "gluonfx.javaStaticSdkVersion")
String javaStaticSdkVersion;
@Parameter(property = "gluonfx.javafxStaticSdkVersion")
String javafxStaticSdkVersion;
@Parameter(property = "gluonfx.target", defaultValue = "host")
String target;
@Parameter(property = "gluonfx.bundlesList")
List<String> bundlesList;
@Parameter(property = "gluonfx.resourcesList")
List<String> resourcesList;
@Parameter(property = "gluonfx.reflectionList")
List<String> reflectionList;
@Parameter(property = "gluonfx.jniList")
List<String> jniList;
@Parameter(property = "gluonfx.nativeImageArgs")
List<String> nativeImageArgs;
@Parameter(property = "gluonfx.runtimeArgs")
List<String> runtimeArgs;
@Parameter(property = "gluonfx.mainClass", required = true)
String mainClass;
@Parameter(property = "gluonfx.executable", defaultValue = "java")
String executable;
@Parameter(property = "gluonfx.verbose", defaultValue = "false")
String verbose;
@Parameter(property = "gluonfx.attachList")
List<String> attachList;
@Parameter(property = "gluonfx.enableSWRendering", defaultValue = "false")
String enableSWRendering;
@Parameter(property = "gluonfx.remoteHostName")
String remoteHostName;
@Parameter(property = "gluonfx.remoteDir")
String remoteDir;
@Parameter(property = "gluonfx.appIdentifier")
String appIdentifier;
@Parameter(property = "gluonfx.releaseConfiguration")
ReleaseConfiguration releaseConfiguration;
private ProcessDestroyer processDestroyer;
public SubstrateDispatcher createSubstrateDispatcher() throws IOException, MojoExecutionException {
if (getGraalvmHome().isEmpty()) {
throw new MojoExecutionException("GraalVM installation directory not found." +
" Either set GRAALVM_HOME as an environment variable or" +
" set graalvmHome in gluonfx-plugin configuration");
}
outputDir = Path.of(project.getBuild().getDirectory(), Constants.GLUONFX_PATH);
ProjectConfiguration substrateConfiguration = createSubstrateConfiguration();
return new SubstrateDispatcher(outputDir, substrateConfiguration);
}
private ProjectConfiguration createSubstrateConfiguration() {
ProjectConfiguration clientConfig = new ProjectConfiguration(mainClass, getProjectClasspath());
clientConfig.setGraalPath(Path.of(getGraalvmHome().get()));
clientConfig.setJavaStaticSdkVersion(javaStaticSdkVersion);
clientConfig.setJavafxStaticSdkVersion(javafxStaticSdkVersion);
Triplet targetTriplet;
switch (target) {
case Constants.PROFILE_HOST:
targetTriplet = Triplet.fromCurrentOS();
break;
case Constants.PROFILE_IOS:
targetTriplet = new Triplet(Constants.Profile.IOS);
break;
case Constants.PROFILE_IOS_SIM:
targetTriplet = new Triplet(Constants.Profile.IOS_SIM);
break;
case Constants.PROFILE_ANDROID:
targetTriplet = new Triplet(Constants.Profile.ANDROID);
break;
case Constants.PROFILE_LINUX_AARCH64:
targetTriplet = new Triplet(Constants.Profile.LINUX_AARCH64);
break;
case Constants.PROFILE_WEB:
targetTriplet = new Triplet(Constants.Profile.WEB);
break;
default:
throw new RuntimeException("No valid target found for " + target);
}
if (releaseConfiguration != null) {
clientConfig.setReleaseConfiguration(releaseConfiguration.toSubstrate());
}
clientConfig.setTarget(targetTriplet);
clientConfig.setBundlesList(bundlesList);
clientConfig.setResourcesList(resourcesList);
clientConfig.setJniList(jniList);
clientConfig.setCompilerArgs(nativeImageArgs);
clientConfig.setRuntimeArgs(runtimeArgs);
clientConfig.setReflectionList(reflectionList);
clientConfig.setAppId(appIdentifier != null ? appIdentifier :
project.getGroupId() + "." + project.getArtifactId());
clientConfig.setAppName(project.getName());
clientConfig.setVerbose("true".equals(verbose));
clientConfig.setUsePrismSW("true".equals(enableSWRendering));
clientConfig.setRemoteHostName(remoteHostName);
clientConfig.setRemoteDir(remoteDir);
return clientConfig;
}
ProcessDestroyer getProcessDestroyer() {
if (processDestroyer == null) {
processDestroyer = new ShutdownHookProcessDestroyer();
}
return processDestroyer;
}
private String getProjectClasspath() {
List<File> classPath = getClasspathElements(project);
getLog().debug("classPath = " + classPath);
return classPath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator));
}
private List<File> getClasspathElements(MavenProject project) {
List<Repository> repositories = project.getRepositories();
Repository gluonRepository = new Repository();
gluonRepository.setId("Gluon");
gluonRepository.setUrl("https://nexus.gluonhq.com/nexus/content/repositories/releases");
repositories.add(gluonRepository);
MavenArtifactResolver.initRepositories(repositories);
List<Artifact> attachDependencies = getAttachDependencies();
List<File> list = Stream.concat(project.getArtifacts().stream(), attachDependencies.stream())
.filter(d -> ALLOWED_DEPENDENCY_TYPES.stream().anyMatch(t -> t.equals(d.getType())))
.sorted((a1, a2) -> {
int compare = a1.compareTo(a2);
if (compare == 0) {
// give precedence to classifiers
return a1.hasClassifier() ? 1 : (a2.hasClassifier() ? -1 : 0);
}
return compare;
})
.map(Artifact::getFile)
.collect(Collectors.toList());
list.add(0, new File(project.getBuild().getOutputDirectory()));
// include runtime dependencies
getRuntimeDependencies().stream()
.filter(d -> !list.contains(d))
.forEach(list::add);
// remove provided dependencies
getProvidedDependencies().stream()
.filter(list::contains)
.forEach(list::remove);
// WEB
if (Constants.PROFILE_WEB.equals(target)) {
project.getArtifacts().stream()
.filter(a -> "org.openjfx".equals(a.getGroupId()) && a.getClassifier() != null)
.map(a -> new DefaultArtifact(a.getGroupId(), a.getArtifactId(),
Constants.WEB_AOT_CLASSIFIER, "jar", Constants.DEFAULT_JAVAFX_JS_SDK_VERSION))
.flatMap(a -> {
DependencyFilter exclusions = (node, parents) ->
!node.getArtifact().getClassifier().equals(Constants.WEB_AOT_CLASSIFIER);
Set<Artifact> resolve = MavenArtifactResolver.getInstance().resolve(a, exclusions);
if (resolve == null) {
return Stream.empty();
}
return resolve.stream();
})
.distinct()
.map(Artifact::getFile)
.forEach(list::add);
WebTargetConfiguration.WEB_AOT_DEPENDENCIES.stream()
.map(s -> s.split(":"))
.map(a -> new DefaultArtifact(a[0], a[1],
a.length == 4 ? a[3] : null, "jar", a[2]))
.flatMap(a -> {
Set<Artifact> resolve = MavenArtifactResolver.getInstance().resolve(a);
if (resolve == null) {
return Stream.empty();
}
return resolve.stream();
})
.distinct()
.map(Artifact::getFile)
.forEach(list::add);
}
return list;
}
List<Artifact> getAttachDependencies() {
List<Dependency> dependencies = project.getDependencies();
// include dependencies from project artifacts (transitive dependencies)
project.getArtifacts().stream()
.filter(a -> DEPENDENCY_GROUP.equals(a.getGroupId()))
.map(a -> {
Dependency d = new Dependency();
d.setGroupId(a.getGroupId());
d.setArtifactId(a.getArtifactId());
d.setVersion(a.getVersion());
return d;
})
.forEach(dependencies::add);
Map<String, Artifact> attachMap = AttachArtifactResolver.findArtifactsForTarget(dependencies, target);
if (attachList != null) {
return Stream.concat(attachList.stream(), Stream.of(UTIL_ARTIFACT))
.distinct()
.map(attachMap::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
return new ArrayList<>();
}
private List<File> getRuntimeDependencies() {
return getDependencies("runtime");
}
private List<File> getProvidedDependencies() {
return getDependencies("provided");
}
private List<File> getDependencies(String scope) {
if (scope == null || scope.isEmpty()) {
return new ArrayList<>();
}
return project.getDependencies().stream()
.filter(d -> ALLOWED_DEPENDENCY_TYPES.stream().anyMatch(t -> t.equals(d.getType())))
.filter(d -> scope.equals(d.getScope()))
.map(d -> new DefaultArtifact(d.getGroupId(), d.getArtifactId(),
d.getClassifier(), d.getType(), d.getVersion()))
.flatMap(a -> {
Set<Artifact> resolve = MavenArtifactResolver.getInstance().resolve(a);
if (resolve == null) {
return Stream.empty();
}
return resolve.stream();
})
.distinct()
.map(Artifact::getFile)
.collect(Collectors.toList());
}
Optional<String> getGraalvmHome() {
return Optional.ofNullable(graalvmHome)
.or(() -> Optional.ofNullable(System.getenv("GRAALVM_HOME")));
}
}
| 40.634831
| 110
| 0.64102
|
885a35e4a1b692ef249cc748682a3ec88eba5750
| 683
|
package com.ssos.formengine.service;
import com.ssos.formengine.dto.FieldDTO;
import com.ssos.formengine.entity.Field;
import com.ssos.formengine.vo.FieldVO;
import java.util.List;
import java.util.Set;
/**
* @ClassName: FieldService
* @Description: 字段定义标准,一般添加之后就不能再去更改预留功能
* @Author: xwl
* @Date: 2019-05-10 18:00
* @Vsersion: 1.0
*/
public interface FieldService {
void add(FieldDTO fieldDTO);
List<FieldVO> findAll();
List<FieldVO> findByIds(Set<Long> ids);
/**
* 修改字段,对于已经动态生成的表无效
* @param field
*/
void update(Field field);
/**
* 批量删除字段
* @param ids
* @return
*/
Integer delete(List<Integer> ids);
}
| 17.973684
| 43
| 0.654466
|
34783511bc5163340e46eadfd4ec896e9c9fb197
| 1,712
|
package ddlog;
import org.junit.Test;
/**
* Tests using time, date, datetime.
*/
public class TimeTest extends BaseQueriesTest {
@Test
public void testYearExtract() {
String query = "create view v0 as SELECT DISTINCT EXTRACT(YEAR FROM t3.d) AS y FROM t3";
String program = this.header(false) +
"typedef TRtmp = TRtmp{y:signed<64>}\n" +
this.relations(false) +
"relation Rtmp[TRtmp]\n" +
"output relation Rv0[TRtmp]\n" +
"Rv0[v1] :- Rt3[v],var v0 = TRtmp{.y = sql_extract_year(v.d)},var v1 = v0.";
this.testTranslation(query, program);
}
@Test
public void testMonthExtract() {
String query = "create view v0 as SELECT DISTINCT EXTRACT(MONTH FROM t3.d) AS m FROM t3";
String program = this.header(false) +
"typedef TRtmp = TRtmp{m:signed<64>}\n" +
this.relations(false) +
"relation Rtmp[TRtmp]\n" +
"output relation Rv0[TRtmp]\n" +
"Rv0[v1] :- Rt3[v],var v0 = TRtmp{.m = sql_extract_month(v.d)},var v1 = v0.";
this.testTranslation(query, program);
}
@Test
public void testHourExtract() {
String query = "create view v0 as SELECT DISTINCT EXTRACT(HOUR FROM t3.t) AS h FROM t3";
String program = this.header(false) +
"typedef TRtmp = TRtmp{h:signed<64>}\n" +
this.relations(false) +
"relation Rtmp[TRtmp]\n" +
"output relation Rv0[TRtmp]\n" +
"Rv0[v1] :- Rt3[v],var v0 = TRtmp{.h = sql_extract_hour(v.t)},var v1 = v0.";
this.testTranslation(query, program);
}
}
| 38.044444
| 97
| 0.557827
|
707c48be348f40d3b3873f13849b79fa9a804e89
| 4,308
|
package com.lt.sisyphus.rpc.config.spring.context.annotation;
import com.lt.sisyphus.rpc.config.annotation.SisyphusReference;
import com.lt.sisyphus.rpc.config.spring.beans.factory.annotation.SisyphusReferenceAnnotationBPP;
import com.lt.sisyphus.rpc.config.spring.beans.factory.annotation.SisyphusServiceAnnotationBPP;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.*;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
public class SisyphusComponentScanRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
// 获取SisyphusComponentScan标签中的scan包名
Set<String> packagesToScan = getPackagesToScan(annotationMetadata);
// 注册@SisyphusService的BeanDefinitionRegistryPostProcessor-(SisyphusServiceAnnotationBPP)
registerSisyphusServiceAnnotationBeanPostProcessor(packagesToScan, beanDefinitionRegistry);
// 注册@SisyphusReference的BeanDefinitionRegistryPostProcessor-(SisyphusServiceAnnotationBPP)
registerSisyphusReferenceAnnotationBeanPostProcessor(beanDefinitionRegistry);
}
private void registerSisyphusServiceAnnotationBeanPostProcessor(Set<String> packagesToScan, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder builder = rootBeanDefinition(SisyphusServiceAnnotationBPP.class);
builder.addConstructorArgValue(packagesToScan);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);
}
private void registerSisyphusReferenceAnnotationBeanPostProcessor(BeanDefinitionRegistry registry) {
// Register @Reference Annotation Bean Processor
String beanName = SisyphusReferenceAnnotationBPP.BEAN_NAME;
if (!registry.containsBeanDefinition(beanName)) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(SisyphusReferenceAnnotationBPP.class);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
// TODO 验证一下这样操作SisyphusReference是否可以初始化SisyphusReference标签
// ConstructorArgumentValues.ValueHolder valueHolder =
new ConstructorArgumentValues.ValueHolder(SisyphusReference.class, Annotation.class.getName());
// ConstructorArgumentValues argumentValues = beanDefinition.getConstructorArgumentValues();
// argumentValues.addIndexedArgumentValue(argumentValues.getArgumentCount(), valueHolder);
registry.registerBeanDefinition(beanName, beanDefinition);
}
}
/*
* 处理scan的包名
* */
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
metadata.getAnnotationAttributes(SisyphusComponentScan.class.getName()));
String[] basePackages = attributes.getStringArray("basePackages");
Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
// String[] value = attributes.getStringArray("value");
// Appends value array attributes
Set<String> packagesToScan = new LinkedHashSet<String>(Arrays.asList(basePackages));
// packagesToScan.addAll(Arrays.asList(basePackages));
for (Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
}
if (packagesToScan.isEmpty()) {
return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
}
return packagesToScan;
}
}
| 53.85
| 130
| 0.780873
|
111d8073b1650ac74120d9632a052bc023f41459
| 16,141
|
/*
* Copyright 2015 Netflix, Inc.
*
* 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 io.reactivex.netty.events;
import io.reactivex.netty.RxNetty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscription;
import rx.exceptions.Exceptions;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Action2;
import rx.functions.Action3;
import rx.functions.Action4;
import rx.functions.Action5;
import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
/**
* A holder for storing {@link EventListener} providing utility methods for any {@link EventSource} implementation that
* requires storing and invoking listeners.
*
* @param <T> Type of listener to store.
*/
public final class ListenersHolder<T extends EventListener> implements EventSource<T>, EventPublisher {
private static final Logger logger = LoggerFactory.getLogger(ListenersHolder.class);
private final CopyOnWriteArraySet<ListenerHolder<T>> listeners;
public ListenersHolder() {
listeners = new CopyOnWriteArraySet<>();
}
public ListenersHolder(ListenersHolder<T> toCopy) {
listeners = new CopyOnWriteArraySet<>(toCopy.listeners);
for (final ListenerHolder<T> holder : listeners) {
// Add the subscription to the existing holder, so that on unsubscribe, it is also removed from this list.
holder.subscription.add(Subscriptions.create(new Action0() {
@Override
public void call() {
listeners.remove(holder);
}
}));
}
}
@Override
public Subscription subscribe(final T listener) {
final CompositeSubscription cs = new CompositeSubscription();
ListenerHolder.configureRemoval(cs, listener, listeners);
final ListenerHolder<T> holder = new ListenerHolder<>(listener, cs);
listeners.add(holder);
return cs;
}
@Override
public boolean publishingEnabled() {
return !RxNetty.isEventPublishingDisabled() && !listeners.isEmpty();
}
public void dispose() {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
try {
listener.onCompleted();
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
if (null != exception) {
exception.finish();
throw exception;
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
*/
public void invokeListeners(Action1<T> invocationAction) {
ListenerInvocationException exception = null;
for (final ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param duration Duration.
* @param timeUnit Time unit for the duration.
*/
public void invokeListeners(Action3<T, Long, TimeUnit> invocationAction, long duration, TimeUnit timeUnit) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, duration, timeUnit);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param duration Duration.
* @param timeUnit Time unit for the duration.
* @param throwable An error.
*/
public void invokeListeners(Action4<T, Long, TimeUnit, Throwable> invocationAction, long duration,
TimeUnit timeUnit, Throwable throwable) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, duration, timeUnit, throwable);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param duration Duration.
* @param timeUnit Time unit for the duration.
* @param arg Any arbitrary argument
*/
public <A> void invokeListeners(Action4<T, Long, TimeUnit, A> invocationAction, long duration,
TimeUnit timeUnit, A arg) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, duration, timeUnit, arg);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param duration Duration.
* @param timeUnit Time unit for the duration.
* @param throwable An error.
* @param arg Any arbitrary argument
*/
public <A> void invokeListeners(Action5<T, Long, TimeUnit, Throwable, A> invocationAction, long duration,
TimeUnit timeUnit, Throwable throwable, A arg) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, duration, timeUnit, throwable, arg);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param arg Any arbitrary argument
*/
public <A> void invokeListeners(Action2<T, A> invocationAction, A arg) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, arg);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
/**
* Invoke listeners with an action expressed by the passed {@code invocationAction}. This method does the necessary
* validations required for invoking a listener and also guards against a listener throwing exceptions on invocation.
*
* @param invocationAction The action to perform on all listeners.
* @param throwable An error.
* @param arg Any arbitrary argument
*/
public <A> void invokeListeners(Action3<T, Throwable, A> invocationAction, Throwable throwable, A arg) {
ListenerInvocationException exception = null;
for (ListenerHolder<T> listener : listeners) {
if (!listener.subscription.isUnsubscribed()) {
try {
invocationAction.call(listener.delegate, throwable, arg);
} catch (Throwable e) {
exception = handleListenerError(exception, listener, e);
}
}
}
if (null != exception) {
exception.finish();
/*Do not bubble event notification errors to the caller, event notifications are best effort.*/
logger.error("Error occured while invoking event listeners.", exception);
}
}
private ListenerInvocationException handleListenerError(ListenerInvocationException exception,
ListenerHolder<T> listener, Throwable e) {
Exceptions.throwIfFatal(e);
if (null == exception) {
exception = new ListenerInvocationException();
}
exception.addException(listener.delegate, e);
return exception;
}
public ListenersHolder<T> copy() {
return new ListenersHolder<>(this);
}
/*Visible for testing*/Collection<T> getAllListeners() {
final Collection<T> toReturn = new ArrayList<>();
for (ListenerHolder<T> listener : listeners) {
toReturn.add(listener.delegate);
}
return toReturn;
}
/*Visible for testing*/CopyOnWriteArraySet<ListenerHolder<T>> getActualListenersList() {
return listeners;
}
public void subscribeAllTo(EventSource<T> lazySource) {
for (ListenerHolder<T> listener : listeners) {
listener.subscription.add(lazySource.subscribe(listener.delegate));
}
}
private static class ListenerHolder<T extends EventListener> implements EventListener {
private static final CompositeSubscription EMPTY_SUB_FOR_REMOVAL = new CompositeSubscription();
private final T delegate;
private final CompositeSubscription subscription;
public ListenerHolder(T delegate, CompositeSubscription subscription) {
this.delegate = delegate;
this.subscription = subscription;
}
@Override
public void onCompleted() {
if (!subscription.isUnsubscribed()) {
try {
delegate.onCompleted();
} finally {
subscription.unsubscribe();
}
}
}
@Override
public void onCustomEvent(Object event) { }
@Override
public void onCustomEvent(Object event, long duration, TimeUnit timeUnit) { }
@Override
public void onCustomEvent(Object event, Throwable throwable) { }
@Override
public void onCustomEvent(Object event, long duration, TimeUnit timeUnit, Throwable throwable) { }
public static <X extends EventListener> ListenerHolder<X> forRemoval(X listenerToRemove) {
return new ListenerHolder<>(listenerToRemove, EMPTY_SUB_FOR_REMOVAL);
}
public static <X extends EventListener> void configureRemoval(CompositeSubscription cs,
final X listenerToRemove,
final CopyOnWriteArraySet<ListenerHolder<X>> removeFrom) {
cs.add(Subscriptions.create(new Action0() {
@Override
public void call() {
/**
* Why do we add {@link ListenerHolder} but remove {@link X}?
* Since {@link ListenerHolder} requires the associated {@link Subscription}, and then
* {@link Subscription} will require the {@link ListenerHolder}, there will be a circular dependency.
*
* Instead, by having {@link ListenerHolder} implement equals/hashcode to only look for the
* enclosing {@link X} instance, it is possible to add {@link ListenerHolder} but remove {@link X}
*/
removeFrom.remove(forRemoval(listenerToRemove));
}
}));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ListenerHolder)) {
return false;
}
@SuppressWarnings("rawtypes")
ListenerHolder that = (ListenerHolder) o;
return delegate.equals(that.delegate);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
}
| 39.658477
| 128
| 0.618611
|
2217b10044cbefc8e1d1393c7e151161bbd09cb1
| 4,149
|
package DataAggregator;
import org.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import dataItemClasses.Apertura;
import dataItemClasses.Data;
import dataItemClasses.DettaglioApertura;
import dataItemClasses.Dish;
import dataItemClasses.Mensa;
import dataItemClasses.Menu;
/**
* Classe CanteenStatusUpdateController.
*/
@RestController
public class CanteenStatusUpdateController {
/** The canteen update obj. */
CanteenStatusUpdateIF canteenUpdateObj = new CanteenStatusUpdateIMPL();
/**
* API per aggiornamento della capacità della mensa.
*
* @param nomeMensa nome mensa
* @param capacita nuova capacità della mensa
* @return file JSON di risposta
*/
/*
* localhost:8080/updateAvailableCapacity?nomeMensa=I sapori della
* terra&capacita=300
*/
@GetMapping("/updateAvailableCapacity")
@RequestMapping(value = "/updateAvailableCapacity", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String updateCanteenCapacityAPI(@RequestParam(value = "nomeMensa") String nomeMensa,
@RequestParam(value = "capacita") int capacita) {
Mensa mensa = new Mensa(0, nomeMensa, 0, null);
JSONObject response = new JSONObject();
try {
if (canteenUpdateObj.updateAvailableCapacity(capacita, mensa))
response.put("status", "aggiornamento avvenuto");
else
response.put("status", "impossibile effettuare aggiornamento");
} catch (Exception e) {
response.put("status", "errore invocazione API");
response.put("errorMessage", e.getMessage());
}
return response.toString(4);
}
/**
* API per aggiornamento della disponibilità delle porzioni di un piatto.
*
* @param nomeMensa nome mensa
* @param giornoSettimana giorno della settimana
* @param tipoPasto tipo pasto
* @param data data
* @param nomeMenu nome menu
* @param tipoMenu tipo menu
* @param nomePiatto nome piatto
* @param newAvailability nuova disponibilità di porzioni per il piatto
* @return file JSON di risposta
*/
/*
* localhost:8080/updateAvailablePortions?nomeMensa=I sapori della
* terra&giornoSettimana=Lunedì&tipoPasto=Cena&data=04-01-2021&nomeMenu=
* pranzoLunedì&tipoMenu=Mediterraneo&nomePiatto=Pasta al
* pomodoro&newAvailability=100
*/
@GetMapping("/updateAvailablePortions")
@RequestMapping(value = "/updateAvailablePortions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getDishPriceAPI(@RequestParam(value = "nomeMensa") String nomeMensa,
@RequestParam(value = "giornoSettimana") String giornoSettimana,
@RequestParam(value = "tipoPasto") String tipoPasto, @RequestParam(value = "data") String data,
@RequestParam(value = "nomeMenu") String nomeMenu, @RequestParam(value = "tipoMenu") String tipoMenu,
@RequestParam(value = "nomePiatto") String nomePiatto,
@RequestParam(value = "newAvailability") int newAvailability) {
Mensa mensa = new Mensa(0, nomeMensa, 0, null);
DettaglioApertura d1 = new DettaglioApertura(0, giornoSettimana, tipoPasto, null, null);
String[] giornoMeseAnno = data.split("-");
Data data1 = new Data(giornoMeseAnno[0], giornoMeseAnno[1], giornoMeseAnno[2]);
Apertura apertura = new Apertura(0, data1, 0, mensa, d1);
Menu menu = new Menu(0, nomeMenu, tipoMenu, apertura);
Dish piatto = new Dish(0, nomePiatto, null, 0, 0, newAvailability, menu);
JSONObject response = new JSONObject();
try {
if (canteenUpdateObj.updateAvailablePortions(newAvailability, piatto, menu, mensa, d1, apertura))
response.put("status", "aggiornamento avvenuto");
else
response.put("status", "impossibile effettuare aggiornamento");
} catch (Exception e) {
response.put("status", "errore invocazione API");
response.put("errorMessage", e.getMessage());
}
return response.toString(4);
}
}
| 37.378378
| 125
| 0.748132
|
87e10d06e6bacda7a1d3a444726722d0466f887f
| 1,229
|
/*
* Copyright (c) 2018, The Modern Way. All rights reserved.
*
* 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 com.themodernway.server.core;
import java.util.function.LongSupplier;
import com.themodernway.common.api.java.util.CommonOps;
@FunctionalInterface
public interface ITimeSupplier
{
public long getTime();
public static long now()
{
return CommonOps.getCurrentClock();
}
public static ITimeSupplier mills()
{
return CommonOps::getCurrentClock;
}
public static ITimeSupplier nanos()
{
return CommonOps::getCurrentNanos;
}
public static ITimeSupplier of(final LongSupplier time)
{
return time::getAsLong;
}
}
| 25.604167
| 75
| 0.70952
|
46a096478dbf4ec983139517dc81a77c34f816ed
| 1,915
|
package cs451;
import cs451.broadcast.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
// Represents a process that broadcasts and delivers messages, logging these events in an output file
public class Process implements Observer {
private int pid;
private int nbMessagesToBroadcast;
private LocalCausalBroadcast lcb;
private List<String> logs = new ArrayList<>();
private String output; // Name of output file
public Process(int pid, String ip, int port, List<Host> hosts,
int nbMessagesToBroadcast, Map<Integer, Set<Integer>> causality, String output) {
this.pid = pid;
this.nbMessagesToBroadcast = nbMessagesToBroadcast;
this.output = output;
// Make mapping from process ids to hosts
Map<Integer, Host> idToHost = new HashMap<>();
for (Host host : hosts) idToHost.put(host.getId(), host);
this.lcb = new LocalCausalBroadcast(pid, ip, port, hosts, idToHost, causality,this);
}
// Broadcast all required messages and log
public void broadcast() {
for (int i = 1; i <= nbMessagesToBroadcast; i++) {
Message broadcastMsg = new Message(pid, pid, i,false, null);
lcb.broadcast(broadcastMsg);
logs.add(String.format("b %d\n",i));
}
}
// Invoked whenever the underlying lcb instance delivers a message
// Log this event
@Override
public void deliver(Message message) {
logs.add(String.format("d %d %d\n", message.getFirstSenderId(), message.getSeqNum()));
}
public void writeLog() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
for (String log : logs) writer.write(log);
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
| 34.196429
| 101
| 0.640209
|
2294810ec6ec1649a1dbdaa0536ea46c29440062
| 670
|
package org.xmlcml.cml.converters.cif.filter;
import org.xmlcml.cml.base.CMLElement;
import org.xmlcml.cml.converters.filter.AbstractCMLFilter;
import org.xmlcml.cml.element.CMLMolecule;
import org.xmlcml.cml.tools.DisorderTool;
// i/mport org.xmlcml.cml.converters.filter.AbstractCMLFilter;
public class DisorderFilter implements AbstractCMLFilter {
public DisorderFilter() {
}
public boolean accept(CMLElement element) {
boolean accept = false;
if (element != null && element instanceof CMLMolecule) {
CMLMolecule molecule = (CMLMolecule) element;
accept = DisorderTool.isDisordered(molecule);
}
return accept;
}
}
| 25.769231
| 63
| 0.741791
|
526cd50866b931f6f2f72123599e84a56a659c3a
| 3,524
|
package mage.cards.o;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.DelayedTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.events.GameEvent.EventType;
import mage.game.events.ZoneChangeEvent;
import mage.game.permanent.token.EldraziHorrorToken;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author LevelX2
*/
public final class OtherworldlyOutburst extends CardImpl {
public OtherworldlyOutburst(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{R}");
// Target creature gets +1/+0 until end of turn. When that creature dies this turn, create a 3/2 colorless Eldrazi Horror creature token.
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
this.getSpellAbility().addEffect(new BoostTargetEffect(1, 0, Duration.EndOfTurn));
this.getSpellAbility().addEffect(new OtherworldlyOutburstEffect());
}
public OtherworldlyOutburst(final OtherworldlyOutburst card) {
super(card);
}
@Override
public OtherworldlyOutburst copy() {
return new OtherworldlyOutburst(this);
}
}
class OtherworldlyOutburstEffect extends OneShotEffect {
public OtherworldlyOutburstEffect() {
super(Outcome.UnboostCreature);
this.staticText = "When that creature dies this turn, create a 3/2 colorless Eldrazi Horror creature token";
}
public OtherworldlyOutburstEffect(final OtherworldlyOutburstEffect effect) {
super(effect);
}
@Override
public OtherworldlyOutburstEffect copy() {
return new OtherworldlyOutburstEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
game.addDelayedTriggeredAbility(new OtherworldlyOutburstDelayedTriggeredAbility(source.getFirstTarget()), source);
return true;
}
}
class OtherworldlyOutburstDelayedTriggeredAbility extends DelayedTriggeredAbility {
private final UUID target;
public OtherworldlyOutburstDelayedTriggeredAbility(UUID target) {
super(new CreateTokenEffect(new EldraziHorrorToken()), Duration.EndOfTurn);
this.target = target;
}
public OtherworldlyOutburstDelayedTriggeredAbility(OtherworldlyOutburstDelayedTriggeredAbility ability) {
super(ability);
this.target = ability.target;
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
return event.getType() == EventType.ZONE_CHANGE;
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
if (event.getTargetId().equals(target)) {
ZoneChangeEvent zEvent = (ZoneChangeEvent) event;
if (zEvent.isDiesEvent()) {
return true;
}
}
return false;
}
@Override
public OtherworldlyOutburstDelayedTriggeredAbility copy() {
return new OtherworldlyOutburstDelayedTriggeredAbility(this);
}
@Override
public String getRule() {
return "When that creature dies this turn, create a 3/2 colorless Eldrazi Horror creature token.";
}
}
| 31.747748
| 145
| 0.729285
|
7692d2fef12c7c427e935929df97097714d6e431
| 1,759
|
package com.ducks.goodsduck.commons.model.dto.post;
import com.ducks.goodsduck.commons.model.entity.Post;
import com.ducks.goodsduck.commons.model.entity.category.PostCategory;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Data
public class PostDetailResponse {
private PostDetailResponsePostOwner postOwner;
private Long postId;
private String content;
private Long idolGroupId;
private String idolGroupName;
private List<PostDetailResponseImage> images = new ArrayList<>();
private LocalDateTime postCreatedAt;
private PostCategoryDto postCategory;
private Integer viewCount;
private Integer likeCount;
private Integer commentCount;
private Boolean isLike;
private Boolean isOwner;
public PostDetailResponse(Post post) {
this.postOwner = new PostDetailResponsePostOwner(post.getUser());
this.postId = post.getId();
this.content = post.getContent();
this.idolGroupId = post.getIdolGroup().getId();
this.idolGroupName = post.getIdolGroup().getName();
this.images = post.getImages().stream()
.map(image -> new PostDetailResponseImage(image))
.collect(Collectors.toList());
this.postCreatedAt = post.getCreatedAt();
this.postCategory = new PostCategoryDto(post.getPostCategory());
this.viewCount = post.getViewCount();
this.likeCount = post.getLikeCount();
this.commentCount = post.getCommentCount();
this.isLike = false;
this.isOwner = false;
}
public void likesOfMe() {
isLike = true;
}
public void myItem() {
isOwner = true;
}
}
| 31.981818
| 73
| 0.693007
|
33f830f976f201c3dbafdcf0a3e2c070a370879b
| 1,469
|
package weclaw.domain;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
@Entity
public class ApplicationUser {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@JsonProperty(access = Access.READ_ONLY)
private Long id;
private String username;
private String password;
private String email;
private Boolean admin;
@OneToMany(mappedBy = "applicationUser")
private List<GameCharacter> gameCharacters;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<GameCharacter> getGameCharacters() {
return gameCharacters;
}
public void setGameCharacters(List<GameCharacter> gameCharacters) {
this.gameCharacters = gameCharacters;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
}
| 18.3625
| 68
| 0.749489
|
19ac561ab541d42cc82267be97e93ed666e80248
| 17,873
|
import java.awt.*;
/**
* The class represents a follower object with all its attributes and actions. It is only to be created through
* {@linkplain CardLib#getCard(String)}.
*/
public final class Follower extends Card implements Attackable, Trait {
private final int ORIGINAL_HEALTH, ORIGINAL_ATTACK, ORIGINAL_EVOLVE_ATTACK, ORIGINAL_EVOLVE_HEALTH;
private int health, attack;
private int evoHpAdd, evoAtkAdd;
private boolean isEvolved, hasBane, hasWard, hasDrain, hasAmbush, hasRush, hasStorm, hasUntargetable,
hasDamageImmune, hasWardPierce;
private Image evoImage;
private AttackStatus atkStatus;
private SwordCraftTrait swordCraftTrait;
private StringBuilder buffList;
/**
* The constructor initializes all default attributes for a follower instance
*
* @param nme name
* @param lead leader
* @param cst cost
* @param rar rarity
* @param handImg image when the follower is in hand
* @param fieldImg image when the follower is on field
* @param swordTrait follower's swordcraft trait
* @param hp health
* @param atk attack
* @param evolvedHpAdd the health increase upon evolving
* @param evolvedAtkAdd the attack increase upon evolving
* @param evoImg follower's image after evolving
* @param defaultAttackStatus follower's default attack status
* @param bane true if the follower has BANE effect
* @param ward true if the follower has WARD effect
* @param drain true if the follower has DRAIN effect
* @param ambush true if the follower has AMBUSH effect
* @param untargetable true if the follower has UNTARGETABLE effect
* @param efx the effect string for the follower, it is encoded and only to be interpreted by
* {@linkplain EffectLib}
* @param hasSpellBoost true if the follower has spellboost effect
* @see Trait.SwordCraftTrait
* @see AttackStatus
* @see SimpleEffects
*/
Follower(String nme, String lead, int cst, String rar, Image handImg, Image fieldImg,
String swordTrait, int hp, int atk, int evolvedHpAdd, int evolvedAtkAdd, Image evoImg,
String defaultAttackStatus, boolean bane, boolean ward, boolean drain, boolean ambush,
boolean untargetable, String efx, boolean hasSpellBoost) {
super("FOLLOWER", nme, lead, cst, rar, handImg, fieldImg, efx, hasSpellBoost);
swordCraftTrait = SwordCraftTrait.valueOf(swordTrait);
health = hp;
attack = atk;
evoHpAdd = evolvedHpAdd;
evoAtkAdd = evolvedAtkAdd;
ORIGINAL_HEALTH = hp;
ORIGINAL_ATTACK = atk;
ORIGINAL_EVOLVE_ATTACK = atk + evolvedAtkAdd;
ORIGINAL_EVOLVE_HEALTH = hp + evolvedHpAdd;
evoImage = evoImg;
buffList = new StringBuilder();
if (bane) hasBane = true;
if (ward) hasWard = true;
if (drain) hasDrain = true;
if (untargetable) hasUntargetable = true;
atkStatus = AttackStatus.valueOf(defaultAttackStatus);
if (atkStatus == AttackStatus.STORM) hasStorm = true;
if (atkStatus == AttackStatus.RUSH) hasRush = true;
isEvolved = false;
hasAmbush = ambush;
hasDamageImmune = false;
hasWardPierce = false;
}
/**
* @return the current attack status of the follower
*/
public AttackStatus getAtkStatus() {
return atkStatus;
}
/**
* @return true if the follower is alive, false otherwise
*/
@Override
public boolean isAlive() {
return health > 0;
}
/**
* Follower takes damage from an enemy follower. The damage taken is equal to the enemy follower's attack. If the
* follower has damage immune effect, no damage will be taken.
*
* @param attacker the attacker follower
*/
@Override
public void takeDamage(Follower attacker) {
if (!hasDamageImmune)
health -= attacker.getAttack();
}
/**
* Heal the follower for a certain amount of health. There is no limit for health value, so it can exceed follower's
* original health.
*
* @param heal the amount of health to be healed
*/
@Override
public void heal(int heal) {
health += heal;
}
/**
* @return the follower's current health
*/
@Override
public int getHealth() {
return health;
}
/**
* Follower takes a specific amount of damage unless it has damage immune.
*
* @param damage the amount of damage to be taken
*/
@Override
public void takeDamage(int damage) {
if (!hasDamageImmune)
health -= damage;
}
/**
* @return true if the follower has damage immune effect, false otherwise
*/
@Override
public boolean hasDamageImmune() {
return hasDamageImmune;
}
/**
* Instantly kills the follower by reducing the health to 0
*/
public void kill() {
health = 0;
}
/**
* @return a string contains all buffs' descriptions that the current follower has received
*/
public String getBuffListString() {
return buffList.toString();
}
/**
* @return the original health value of the follower before evolving
*/
public int getOrgHealth() {
return ORIGINAL_HEALTH;
}
/**
* @return the original attack value of the follower before evolving
*/
public int getOrgAttack() {
return ORIGINAL_ATTACK;
}
/**
* @return the original attack value of the follower after evolving
*/
public int getOrgEvoAttack() {
return ORIGINAL_EVOLVE_ATTACK;
}
/**
* @return the original health value of the follower after evolving
*/
public int getOrgEvoHealth() {
return ORIGINAL_EVOLVE_HEALTH;
}
/**
* @return the image of the follower after evolving
*/
public Image getEvolvedImage() {
return evoImage;
}
/**
* @return the current attack value of the follower
*/
public int getAttack() {
return attack;
}
/**
* @return true if the follower has evolved already, false otherwise
*/
public boolean hasEvolved() {
return isEvolved;
}
/**
* @return true if the follower has BANE effect, false otherwise
* @see SimpleEffects#BANE
*/
public boolean hasBane() {
return hasBane;
}
/**
* @return true if the follower has WARD effect, false otherwise
* @see SimpleEffects#WARD
*/
public boolean hasWard() {
return hasWard;
}
/**
* @return true if the follower has DRAIN effect, false otherwise
* @see SimpleEffects#DRAIN
*/
public boolean hasDrain() {
return hasDrain;
}
/**
* @return true if the follower has AMBUSH effect, false otherwise
* @see SimpleEffects#AMBUSH
*/
public boolean hasAmbush() {
return hasAmbush;
}
/**
* @return true if the follower has STORM effect, false otherwise
* @see SimpleEffects#STORM
*/
public boolean hasStorm() {
return hasStorm;
}
/**
* @return true if the follower has RUSH effect, false otherwise
* @see SimpleEffects#RUSH
*/
public boolean hasRush() {
return hasRush;
}
/**
* @return true if the follower has UNTARGETABLE effect, false otherwise
* @see SimpleEffects#UNTARGETABLE
*/
public boolean hasUntargetable() {
return hasUntargetable;
}
/**
* @return true if the follower has WARD_PIERCE effect, false otherwise
* @see SimpleEffects#WARD_PIERCE
*/
public boolean hasWardPierce() {
return hasWardPierce;
}
/**
* @return true if the follower can be selected as a target, false otherwise
*/
public boolean canBeTargeted() {
return !(hasUntargetable || hasAmbush);
}
/**
* Increases the follower's current attack and health by a specified amount, then add this buff action to the
* follower's buff log
*
* @param atk attack to be increased
* @param hp health to be increased
* @param sourceCard the card that gives this buff
*/
public void buff(int atk, int hp, Card sourceCard) {
attack += atk;
health += hp;
buffList.append('\n').append(sourceCard.getName()).append(" +").append(atk).append("/+").append(hp);
}
/**
* Grant this follower a simple effect.
*
* <p>All modifications related to the follower's {@linkplain #atkStatus} will not be valid if the current status is
* {@linkplain AttackStatus#DISABLED}. {@linkplain SimpleEffects#RUSH} will not override {@linkplain
* AttackStatus#STORM}. Besides, this method will override {@linkplain AttackStatus#ATTACKED}, which means granting
* either {@linkplain SimpleEffects#STORM} or {@linkplain SimpleEffects#RUSH} will allow this follower to attack
* even if it has already attacked this round.</p>
*
* @param simpleEffect the simple effect to be granted
* @throws IllegalArgumentException if the simple effect does not exist
* @see SimpleEffects
* @see AttackStatus
*/
public void grantSimpleEffect(SimpleEffects simpleEffect) {
switch (simpleEffect) {
case STORM:
if (atkStatus != AttackStatus.DISABLED)
atkStatus = AttackStatus.STORM;
break;
case RUSH:
if (atkStatus != AttackStatus.STORM && atkStatus != AttackStatus.DISABLED)
atkStatus = AttackStatus.RUSH;
break;
case DRAIN:
hasDrain = true;
break;
case WARD:
hasWard = true;
break;
case BANE:
hasBane = true;
break;
case AMBUSH:
hasAmbush = true;
break;
case ATTACKED:
if (atkStatus != AttackStatus.DISABLED)
atkStatus = AttackStatus.ATTACKED;
break;
case DAMAGE_IMMUNE:
hasDamageImmune = true;
break;
case UNTARGETABLE:
hasUntargetable = true;
break;
case WARD_PIERCE:
hasWardPierce = true;
break;
case DISABLED:
atkStatus = AttackStatus.DISABLED;
break;
default:
throw new IllegalArgumentException("No such effect found");
}
}
/**
* Revoke a simple effect from this follower
*
* <p>Only temporary effects are allowed to be removed.</p>
*
* @param simpleEffects the simple effect to be revoked
* @see SimpleEffects
*/
public void revokeSimpleEffect(SimpleEffects simpleEffects) {
switch (simpleEffects) {
case DAMAGE_IMMUNE:
hasDamageImmune = false;
break;
case DISABLED:
atkStatus = AttackStatus.ENTRY;
break;
}
}
/**
* Evolve the current follower. Its attack and health will increase according to its {@linkplain #evoAtkAdd} and
* {@linkplain #evoHpAdd}, and it will gain {@linkplain AttackStatus#RUSH} if it just entered field. One follower is
* only allowed to be evolved once.
*
* @throws IllegalStateException if the follower has already been evolved
*/
public void evolve() {
if (!isEvolved) {
attack += evoAtkAdd;
health += evoHpAdd;
isEvolved = true;
if (atkStatus == AttackStatus.ENTRY) {
atkStatus = AttackStatus.RUSH;
}
} else {
throw new IllegalStateException("Follower has already been evolved!");
}
}
/**
* Attack an enemy follower. Damage dealt to enemy follower equals the current attack value. Counterattack damage
* received equals to enemy follower's current attack value.
*
* <p>This method does not check if the follower's {@linkplain #atkStatus} is valid for attacking. Therefore, it is
* mandatory to perform such check by calling {@linkplain AttackStatus#canAttackFollower()} before invoking this
* method.</p>
*
* <p>If this follower is currently under {@linkplain SimpleEffects#AMBUSH}, this status will be removed after
* attacking.</p>
*
* @param enemy the enemy follower to attack
*/
public void attack(Follower enemy) {
if (enemy != null && enemy.isAlive()) {
enemy.takeDamage(this);
takeDamage(enemy);
if (hasAmbush) {
hasAmbush = false;
}
}
atkStatus = AttackStatus.ATTACKED;
}
/**
* Attack enemy leader. Damage dealt to enemy leader equals the current attack value.
*
* <p>This method does not check if the follower's {@linkplain #atkStatus} is valid for attacking. Therefore, it is
* mandatory to perform such check by calling {@linkplain AttackStatus#canAttackLeader()} before invoking this
* method.</p>
*
* <p>If this follower is currently under {@linkplain SimpleEffects#AMBUSH}, this status will be removed after
* attacking.</p>
*
* @param opponent the enemy leader to attack
*/
public void attack(Leader opponent) {
opponent.takeDamage(this);
if (hasAmbush) {
hasAmbush = false;
}
atkStatus = AttackStatus.ATTACKED;
}
/**
* @return the follower's swordcraft trait
* @see Trait.SwordCraftTrait
*/
@Override
public SwordCraftTrait getSwordCraftTrait() {
return swordCraftTrait;
}
/**
* Change the follower's attack to a specific value
*
* @param targetAttack the target attack value
*/
public void changeAttack(int targetAttack) {
attack = targetAttack;
}
/**
* Change the follower's health to a specific value
*
* @param targetHealth the target health value
*/
public void changeHealth(int targetHealth) {
health = targetHealth;
}
/**
* The library of all simple effects
*/
public enum SimpleEffects {
/**
* Followers with BANE effect will have a guaranteed kill if it deals damage to an enemy follower through
* attacking or counterattacking. This effect is valid even if the follower does 0 attack damage.
*/
BANE,
/**
* When selecting an attack target, if there is(are) follower(s) with WARD, they must be selected first. In
* other words, it it invalid to attack enemy follower without WARD or enemy leader when there is(are) enemy
* follower(s) with WARD on the enemy field.
*/
WARD,
/**
* Followers with DRAIN effect heals their leader upon dealing any attack damage. The heal amount equals the
* damage dealt.
*/
DRAIN,
/**
* Followers with AMBUSH effect can not be selected as effect or attack target. In other words, they will not be
* affected by any targeted spells, effects and enemy follower attack. This effect will no longer be valid if
* the follower attacks.
*/
AMBUSH,
/**
* Followers granted with RUSH effect will immediately be granted with {@linkplain AttackStatus#RUSH}. It
* enables the follower to attack any enemy follower but not the enemy leader.
*/
RUSH,
/**
* Followers granted with STORM effect will immediately be granted with {@linkplain AttackStatus#STORM}. It
* enables the follower to attack any enemy target.
*/
STORM,
/**
* Followers with UNTARGETABLE can not be selected as any targeted spell's target.
*/
UNTARGETABLE,
/**
* Followers granted with ATTACKED effect will immediately be granted with {@linkplain AttackStatus#ATTACKED}.
* It means that the follower has already attacked in this round and can no longer make any other attack.
*/
ATTACKED,
/**
* Followers with damage immune will not receive any spell or effect damage. Attack and counterattack damages
* still apply.
*/
DAMAGE_IMMUNE,
/**
* Followers with WARD_PIERCE are allowed to attack any enemy target even if there is(are) enemy follower(s)
* with WARD effect.
*/
WARD_PIERCE,
/**
* Followers granted with DISABLED effect will immediately be granted with {@linkplain AttackStatus#DISABLED}.
* It means that the follower is banned from making any attack unless this effect is removed.
*/
DISABLED
}
}
| 32.976015
| 121
| 0.584793
|
e146cbcc894fd90cab9a241bb96ce8c1d273a7d3
| 3,692
|
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Vector;
public class Server {
private final ServerSocket serverSocket;
private final Vector<Clients> List = new Vector<>();
public Server(int port) throws IOException {
this.serverSocket = new ServerSocket(port);
}
private void serverIsWaiting() throws IOException {
while (true) {
Socket socket = serverSocket.accept();
Clients newClients = new Clients(socket);
newClients.start();
List.add(newClients);
}
}
public static void main(String[] args) throws IOException {
Server server = new Server(1408);
System.out.println("Server is online.....");
server.serverIsWaiting();
}
public class Clients extends Thread {
private final Socket socket;
//private String userName = null;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
public Clients(Socket socket) throws IOException {
this.socket = socket;
this.dataInputStream = new DataInputStream(socket.getInputStream());
this.dataOutputStream = new DataOutputStream(socket.getOutputStream());
}
public void sendMessage(String Message) {
try {
dataOutputStream.writeUTF(Message);
} catch (IOException e) {
return;
}
}
public void sendToTheOther(String message){
for (Clients clientLoop : List) {
try {
if (!clientLoop.equals(this)) {
DataOutputStream newDataOutputStream = new DataOutputStream(clientLoop.socket.getOutputStream());
newDataOutputStream.writeUTF(message);
System.out.println(message);
}
} catch (Exception e) {
List.remove(clientLoop);
}
}
}
@Override
public void run() {
synchronized (this) {
try {
while (true) {
try {
String message ="";
while (true) {
try {
message= dataInputStream.readUTF();
break;
} catch (EOFException e) {
}
}
// if (userName == null) {
// userName = message;
// System.out.println(userName + " has join zoom");
// //sendMessage("hamanochiharu728");
// } else {
System.err.println(message);
sendToTheOther(message);
// }
} catch (SocketException e) {
System.err.println(" has left the zoom !");
this.socket.close();
List.remove(this);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
| 35.161905
| 121
| 0.459101
|
a338885cef0a90fad16adf3eb4b09f9c55a86ad6
| 1,016
|
package cz.esc.iot.cloudservice.persistance.model;
import java.util.Date;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference;
import com.google.gson.annotations.Expose;
@Entity
public class AccessToken {
@Id
private ObjectId id;
@Expose private String access_token;
@Indexed(expireAfterSeconds = 3600) // one hour
@Expose private final Date time = new Date();
@Reference
private UserEntity user;
public AccessToken() {
super();
}
public AccessToken(String at, UserEntity u) {
access_token = at;
user = u;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Date getTime() {
return time;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
}
| 21.166667
| 51
| 0.744094
|
d17b5d9aa1579827ff2cd6f6d2c0f9d49665ed29
| 1,345
|
package com.dream.easy.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Author: SuSong
* Email: 751971697@qq.com | susong0618@163.com
* Date: 15/10/6 下午9:40
* Description: EasyFrame
*/
public class BaseEntity implements Parcelable {
private String id;
private String name;
public BaseEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
}
protected BaseEntity(Parcel in) {
this.id = in.readString();
this.name = in.readString();
}
public static final Parcelable.Creator<BaseEntity> CREATOR = new Parcelable.Creator<BaseEntity>() {
public BaseEntity createFromParcel(Parcel source) {
return new BaseEntity(source);
}
public BaseEntity[] newArray(int size) {
return new BaseEntity[size];
}
};
}
| 21.349206
| 103
| 0.597026
|
b54009a5bb8a3125bdebdf15eca79dc716516a34
| 372
|
package com.sxi.e4t.lab.uber.repository;
import com.sxi.e4t.lab.uber.domain.entity.Trip;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.ZonedDateTime;
import java.util.List;
public interface TripRepository extends JpaRepository<Trip, Long> {
List<Trip> findAllByStartOnIsBetween(ZonedDateTime firstDate, ZonedDateTime secondDate);
}
| 31
| 92
| 0.819892
|
4cbca833f568ccf9ba61d830c7d779faa47f92e6
| 13,664
|
package cn.zhuhongqing.utils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
/**
* Some utilities for {@link Number}
*
*
* @author HongQing.Zhu
* <nl>
* <li>Mail:qwepoidjdj(a)gmail.com</li>
* <li>HomePage:www.zhuhongqing.cn</li>
* </nl>
*/
public class NumberUtil {
public static final BigInteger LONG_MIN = BigInteger
.valueOf(Long.MIN_VALUE);
public static final BigInteger LONG_MAX = BigInteger
.valueOf(Long.MAX_VALUE);
/**
* Convert {@link Number} to {@link String}.
*
* Use String type to keep.
*
* double 123456789.123456 == > String 123456789.123456
*/
public static String toString(Number number) {
if (number instanceof Float) {
return new BigDecimal(number.toString()).toString();
}
if (number instanceof Double) {
return new BigDecimal(number.toString()).toString();
}
return number.toString();
}
// ---------------------------------------------------------------- judge
/**
* <p>
* Checks whether the <code>String</code> contains only digit characters.
* </p>
*
* <p>
* <code>Null</code> and empty String will return <code>false</code>.
* </p>
*
* @param str
* the <code>String</code> to checkF
* @return <code>true</code> if str contains only unicode numeric
*/
public static boolean isDigits(String str) {
if (StringUtil.isEmpty(str)) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>
* Checks whether the String a valid Java number.
* </p>
*
* <p>
* Valid numbers include hexadecimal marked with the <code>0x</code>
* qualifier, scientific notation and numbers marked with a type qualifier
* (e.g. 123L).
* </p>
*
* <p>
* <code>Null</code> and empty String will return <code>false</code>.
* </p>
*
* @param str
* the <code>String</code> to check
* @return <code>true</code> if the string is a correctly formatted number
*/
public static boolean isNumber(String str) {
if (StringUtil.isEmpty(str)) {
return false;
}
char[] chars = str.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
boolean foundDigit = false;
// deal with any possible sign up front
int start = (chars[0] == '-') ? 1 : 0;
if (sz > start + 1) {
if (chars[start] == '0' && chars[start + 1] == 'x') {
int i = start + 2;
if (i == sz) {
return false; // str == "0x"
}
// checking hex (it can't be anything else)
for (; i < chars.length; i++) {
if ((chars[i] < '0' || chars[i] > '9')
&& (chars[i] < 'a' || chars[i] > 'f')
&& (chars[i] < 'A' || chars[i] > 'F')) {
return false;
}
}
return true;
}
}
sz--; // don't want to loop to the last char, check it afterwords
// for type qualifiers
int i = start;
// loop to the next to last char or to the last char if we need another
// digit to
// make a valid number (e.g. chars[0..5] = "1234E")
while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
if (chars[i] >= '0' && chars[i] <= '9') {
foundDigit = true;
allowSigns = false;
} else if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
hasDecPoint = true;
} else if (chars[i] == 'e' || chars[i] == 'E') {
// we've already taken care of hex.
if (hasExp) {
// two E's
return false;
}
if (!foundDigit) {
return false;
}
hasExp = true;
allowSigns = true;
} else if (chars[i] == '+' || chars[i] == '-') {
if (!allowSigns) {
return false;
}
allowSigns = false;
foundDigit = false; // we need a digit after the E
} else {
return false;
}
i++;
}
if (i < chars.length) {
if (chars[i] >= '0' && chars[i] <= '9') {
// no type qualifier, OK
return true;
}
if (chars[i] == 'e' || chars[i] == 'E') {
// can't have an E at the last byte
return false;
}
if (!allowSigns
&& (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {
return foundDigit;
}
if (chars[i] == 'l' || chars[i] == 'L') {
// not allowing L with an exponent
return foundDigit && !hasExp;
}
// last character is illegal
return false;
}
// allowSigns is true iff the val ends in 'E'
// found digit it to make sure weird stuff like '.' and '1E-' doesn't
// pass
return !allowSigns && foundDigit;
}
// ---------------------------------------------------------------- convert
/**
* Convert the given number into an instance of the given target class.
*
* @param number
* the number to convert
* @param targetClass
* the target class to convert to
* @return the converted number
* @throws IllegalArgumentException
* if the target class is not supported (i.e. not a standard
* Number subclass as included in the JDK)
* @see java.lang.Byte
* @see java.lang.Short
* @see java.lang.Integer
* @see java.lang.Long
* @see java.math.BigInteger
* @see java.lang.Float
* @see java.lang.Double
* @see java.math.BigDecimal
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T convertNumberToTargetClass(
Number number, Class<T> targetClass)
throws IllegalArgumentException {
if (targetClass.isInstance(number)) {
return (T) number;
} else if (targetClass.equals(Byte.class)) {
long value = number.longValue();
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Byte(number.byteValue());
} else if (targetClass.equals(Short.class)) {
long value = number.longValue();
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Short(number.shortValue());
} else if (targetClass.equals(Integer.class)) {
long value = number.longValue();
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
raiseOverflowException(number, targetClass);
}
return (T) new Integer(number.intValue());
} else if (targetClass.equals(Long.class)) {
BigInteger bigInt = null;
if (number instanceof BigInteger) {
bigInt = (BigInteger) number;
} else if (number instanceof BigDecimal) {
bigInt = ((BigDecimal) number).toBigInteger();
}
// Effectively analogous to JDK 8's BigInteger.longValueExact()
if (bigInt != null
&& (bigInt.compareTo(LONG_MIN) < 0 || bigInt
.compareTo(LONG_MAX) > 0)) {
raiseOverflowException(number, targetClass);
}
return (T) new Long(number.longValue());
} else if (targetClass.equals(BigInteger.class)) {
if (number instanceof BigDecimal) {
// do not lose precision - use BigDecimal's own conversion
return (T) ((BigDecimal) number).toBigInteger();
} else {
// original value is not a Big* number - use standard long
// conversion
return (T) BigInteger.valueOf(number.longValue());
}
} else if (targetClass.equals(Float.class)) {
return (T) new Float(number.floatValue());
} else if (targetClass.equals(Double.class)) {
return (T) new Double(number.doubleValue());
} else if (targetClass.equals(BigDecimal.class)) {
// always use BigDecimal(String) here to avoid unpredictability of
// BigDecimal(double)
// (see BigDecimal javadoc for details)
return (T) new BigDecimal(number.toString());
} else {
throw new IllegalArgumentException("Could not convert number ["
+ number + "] of type [" + number.getClass().getName()
+ "] to unknown target class [" + targetClass.getName()
+ "]");
}
}
/**
* Raise an overflow exception for the given number and target class.
*
* @param number
* the number we tried to convert
* @param targetClass
* the target class we tried to convert to
*/
private static void raiseOverflowException(Number number,
Class<?> targetClass) {
throw new IllegalArgumentException("Could not convert number ["
+ number + "] of type [" + number.getClass().getName()
+ "] to target class [" + targetClass.getName() + "]: overflow");
}
// ---------------------------------------------------------------- parse
/**
* Parse the given text into a number instance of the given target class,
* using the corresponding {@code decode} / {@code valueOf} methods.
* <p>
* Trims the input {@code String} before attempting to parse the number.
* Supports numbers in hex format (with leading "0x", "0X" or "#") as well.
*
* @param text
* the text to convert
* @param targetClass
* the target class to parse into
* @return the parsed number
* @throws IllegalArgumentException
* if the target class is not supported (i.e. not a standard
* Number subclass as included in the JDK)
* @see Byte#decode
* @see Short#decode
* @see Integer#decode
* @see Long#decode
* @see #decodeBigInteger(String)
* @see Float#valueOf
* @see Double#valueOf
* @see java.math.BigDecimal#BigDecimal(String)
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T parseNumber(String text,
Class<T> targetClass) {
String trimmed = StringUtil.trimAllWhitespace(text);
if (targetClass.equals(Byte.class)) {
return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte
.valueOf(trimmed));
} else if (targetClass.equals(Short.class)) {
return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short
.valueOf(trimmed));
} else if (targetClass.equals(Integer.class)) {
return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed)
: Integer.valueOf(trimmed));
} else if (targetClass.equals(Long.class)) {
return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long
.valueOf(trimmed));
} else if (targetClass.equals(BigInteger.class)) {
return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed)
: new BigInteger(trimmed));
} else if (targetClass.equals(Float.class)) {
return (T) Float.valueOf(trimmed);
} else if (targetClass.equals(Double.class)) {
return (T) Double.valueOf(trimmed);
} else if (targetClass.equals(BigDecimal.class)
|| targetClass.equals(Number.class)) {
return (T) new BigDecimal(trimmed);
} else {
throw new IllegalArgumentException("Cannot convert String [" + text
+ "] to target class [" + targetClass.getName() + "]");
}
}
/**
* Parse the given text into a number instance of the given target class,
* using the given NumberFormat. Trims the input {@code String} before
* attempting to parse the number.
*
* @param text
* the text to convert
* @param targetClass
* the target class to parse into
* @param numberFormat
* the NumberFormat to use for parsing (if {@code null}, this
* method falls back to {@code parseNumber(String, Class)})
* @return the parsed number
* @throws IllegalArgumentException
* if the target class is not supported (i.e. not a standard
* Number subclass as included in the JDK)
* @see java.text.NumberFormat#parse
* @see #convertNumberToTargetClass
* @see #parseNumber(String, Class)
*/
public static <T extends Number> T parseNumber(String text,
Class<T> targetClass, NumberFormat numberFormat) {
if (numberFormat != null) {
DecimalFormat decimalFormat = null;
boolean resetBigDecimal = false;
if (numberFormat instanceof DecimalFormat) {
decimalFormat = (DecimalFormat) numberFormat;
if (BigDecimal.class.equals(targetClass)
&& !decimalFormat.isParseBigDecimal()) {
decimalFormat.setParseBigDecimal(true);
resetBigDecimal = true;
}
}
try {
Number number = numberFormat.parse(StringUtil
.trimAllWhitespace(text));
return convertNumberToTargetClass(number, targetClass);
} catch (ParseException ex) {
throw new IllegalArgumentException("Could not parse number: "
+ ex.getMessage());
} finally {
if (resetBigDecimal) {
decimalFormat.setParseBigDecimal(false);
}
}
} else {
return parseNumber(text, targetClass);
}
}
/**
* Determine whether the given value String indicates a hex number, i.e.
* needs to be passed into {@code Integer.decode} instead of
* {@code Integer.valueOf} (etc).
*/
private static boolean isHexNumber(String value) {
int index = (value.startsWith("-") ? 1 : 0);
return (value.startsWith("0x", index) || value.startsWith("0X", index) || value
.startsWith("#", index));
}
/**
* Decode a {@link java.math.BigInteger} from a {@link String} value.
* Supports decimal, hex and octal notation.
*
* @see BigInteger#BigInteger(String, int)
*/
private static BigInteger decodeBigInteger(String value) {
int radix = 10;
int index = 0;
boolean negative = false;
// Handle minus sign, if present.
if (value.startsWith("-")) {
negative = true;
index++;
}
// Handle radix specifier, if present.
if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
index += 2;
radix = 16;
} else if (value.startsWith("#", index)) {
index++;
radix = 16;
} else if (value.startsWith("0", index) && value.length() > 1 + index) {
index++;
radix = 8;
}
BigInteger result = new BigInteger(value.substring(index), radix);
return (negative ? result.negate() : result);
}
}
| 30.984127
| 85
| 0.623536
|
e1a4f8967eef1fcd1feb067666898ca1cd8ebca7
| 737
|
package net.ibizsys.pswf.core;
/**
* 流程子流程模型接口
* @author Administrator
*
*/
public interface IWFProcSubWFModel
{
/**
* 初始化
* @param iWFInteractiveProcessModel
* @throws Exception
*/
void init(IWFEmbedWFProcessModelBase iWFEmbedWFProcessModelBase) throws Exception;
/**
* 获取嵌入流程处理模型
* @return
*/
IWFEmbedWFProcessModelBase getWFEmbedWFProcessModelBase();
/**
* 获取标识
* @return
*/
String getId();
/**
* 获取名称
* @return
*/
String getName();
/**
* 获取子流程模型
* @return
*/
IWFModel getWFModel();
/**
* 获取子流程标识
* @return
*/
String getWFId();
/**
* 获取实体名称
* @return
*/
String getDEName();
/**
* 获取实体数据集合名称
* @return
*/
String getDEDSName();
}
| 10.528571
| 83
| 0.597015
|
04ed5f83940c3b6c9498fb5135163e92aa7ca9e5
| 1,325
|
package project1E7.Controller;
import com.google.gson.Gson;
import project1E7.Model.*;
import project1E7.View.SaveView;
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
public class SaveController {
Scanner input = new Scanner(System.in);
Save model;
SaveView view;
Gson gson = new Gson();
public SaveController(Save model, SaveView view) {
this.model = model;
this.view = view;
}
public void saveGame(Game game) {
Gson gson = new Gson();
String theGame = gson.toJson(game);
try {
FileWriter fileWriter = new FileWriter("SavedGame.json");
fileWriter.write(theGame);
fileWriter.close();
view.printSave();
}
catch(Exception e) {
System.out.println("please delete existing file");
}
}
public void saveHighScore(User user) {
Formatter save;
try {
String name = user.getUserName();
String highScore = "";
highScore = Integer.toString(user.getHighScore());
save = new Formatter("HighScore.txt");
save.format("Username: %s HighScore: %s", name,highScore);
save.close();
} catch (IOException e) {
e.getMessage();
}
}
}
| 24.090909
| 70
| 0.580377
|
7454ff80b5e8dbe1d4cfc856786541ef76c2b472
| 1,705
|
/**
* Copyright 2012-2015 Niall Gallagher
*
* 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 com.googlecode.cqengine.examples.inheritance;
import com.googlecode.cqengine.attribute.Attribute;
import com.googlecode.cqengine.attribute.SimpleNullableAttribute;
import com.googlecode.cqengine.examples.introduction.Car;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.List;
/**
* @author Niall Gallagher
*/
public class SportsCar extends Car {
final int horsepower;
public SportsCar(int carId, String name, String description, List<String> features, int horsepower) {
super(carId, name, description, features);
this.horsepower = horsepower;
}
@Override
public String toString() {
return "SportsCar{carId=" + carId + ", name='" + name + "', description='" + description + "', features=" + features + ", horsepower=" + horsepower + "}";
}
public static final Attribute<Car, Integer> HORSEPOWER = new SimpleNullableAttribute<Car, Integer>("horsepower") {
public Integer getValue(Car car, QueryOptions queryOptions) { return car instanceof SportsCar ? ((SportsCar)car).horsepower : null; }
};
}
| 37.065217
| 162
| 0.7261
|
cee40ef93a07f15f4b59a354bd37cab38c3934de
| 1,320
|
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* 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 org.kurento.orion;
/**
* @author Ivan Gracia (igracia@kurento.org)
*
*/
public class OrionConnectorConfiguration {
private String orionHost = "130.206.85.186";
private int orionPort = 1026;
private String orionScheme = "http";
public String getOrionHost() {
return this.orionHost;
}
public void setOrionHost(String orionHost) {
this.orionHost = orionHost;
}
public int getOrionPort() {
return this.orionPort;
}
public void setOrionPort(int orionPort) {
this.orionPort = orionPort;
}
public String getOrionScheme() {
return this.orionScheme;
}
public void setOrionScheme(String orionSchema) {
this.orionScheme = orionSchema;
}
}
| 24.444444
| 75
| 0.712121
|
08e0e29593c576390f25f8d464ce6e39c5f07713
| 7,446
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.script.groovy;
import org.apache.lucene.util.Constants;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptException;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.test.ESIntegTestCase;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
/**
* Tests for the Groovy security permissions
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0)
// TODO: refactor into unit test, or, proper REST test
public class GroovySecurityTests extends ESIntegTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
assumeTrue("test requires security manager to be enabled", System.getSecurityManager() != null);
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singleton(GroovyPlugin.class);
}
public void testEvilGroovyScripts() throws Exception {
int nodes = randomIntBetween(1, 3);
Settings nodeSettings = Settings.builder()
.put("script.inline", true)
.put("script.indexed", true)
.build();
internalCluster().startNodesAsync(nodes, nodeSettings).get();
client().admin().cluster().prepareHealth().setWaitForNodes(nodes + "").get();
client().prepareIndex("test", "doc", "1").setSource("foo", 5, "bar", "baz").setRefresh(true).get();
// Plain test
assertSuccess("");
// numeric field access
assertSuccess("def foo = doc['foo'].value; if (foo == null) { return 5; }");
// string field access
assertSuccess("def bar = doc['bar'].value; if (bar == null) { return 5; }");
// List
assertSuccess("def list = [doc['foo'].value, 3, 4]; def v = list.get(1); list.add(10)");
// Ranges
assertSuccess("def range = 1..doc['foo'].value; def v = range.get(0)");
// Maps
assertSuccess("def v = doc['foo'].value; def m = [:]; m.put(\"value\", v)");
// Times
assertSuccess("def t = Instant.now().getMillis()");
// GroovyCollections
assertSuccess("def n = [1,2,3]; GroovyCollections.max(n)");
// Fail cases:
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")]
assertFailure("pr = Runtime.getRuntime().exec(\"touch /tmp/gotcha\"); pr.waitFor()");
// AccessControlException[access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.reflect")]
assertFailure("d = new DateTime(); d.getClass().getDeclaredMethod(\"year\").setAccessible(true)");
assertFailure("d = new DateTime(); d.\"${'get' + 'Class'}\"()." +
"\"${'getDeclared' + 'Method'}\"(\"year\").\"${'set' + 'Accessible'}\"(false)");
assertFailure("Class.forName(\"org.joda.time.DateTime\").getDeclaredMethod(\"year\").setAccessible(true)");
// AccessControlException[access denied ("groovy.security.GroovyCodeSourcePermission" "/groovy/shell")]
assertFailure("Eval.me('2 + 2')");
assertFailure("Eval.x(5, 'x + 2')");
// AccessControlException[access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")]
assertFailure("d = new Date(); java.lang.reflect.Field f = Date.class.getDeclaredField(\"fastTime\");" +
" f.setAccessible(true); f.get(\"fastTime\")");
// AccessControlException[access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")]
assertFailure("def methodName = 'ex'; Runtime.\"${'get' + 'Runtime'}\"().\"${methodName}ec\"(\"touch /tmp/gotcha2\")");
// AccessControlException[access denied ("java.lang.RuntimePermission" "modifyThreadGroup")]
assertFailure("t = new Thread({ println 3 });");
// test a directory we normally have access to, but the groovy script does not.
Path dir = createTempDir();
// TODO: figure out the necessary escaping for windows paths here :)
if (!Constants.WINDOWS) {
// access denied ("java.io.FilePermission" ".../tempDir-00N" "read")
assertFailure("new File(\"" + dir + "\").exists()");
}
}
private void assertSuccess(String script) {
logger.info("--> script: " + script);
SearchResponse resp = client()
.prepareSearch("test")
.setSource(
new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort(
SortBuilders.scriptSort(new Script(script + "; doc['foo'].value + 2", ScriptType.INLINE, "groovy", null),
"number"))).get();
assertNoFailures(resp);
assertEquals(1, resp.getHits().getTotalHits());
assertThat(resp.getHits().getAt(0).getSortValues(), equalTo(new Object[]{7.0}));
}
private void assertFailure(String script) {
logger.info("--> script: " + script);
SearchResponse resp = client()
.prepareSearch("test")
.setSource(
new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort(
SortBuilders.scriptSort(new Script(script + "; doc['foo'].value + 2", ScriptType.INLINE, "groovy", null),
"number"))).get();
assertEquals(0, resp.getHits().getTotalHits());
ShardSearchFailure fails[] = resp.getShardFailures();
// TODO: GroovyScriptExecutionException needs work:
// fix it to preserve cause so we don't do this flaky string-check stuff
for (ShardSearchFailure fail : fails) {
assertThat(fail.getCause(), instanceOf(ScriptException.class));
assertTrue("unexpected exception" + fail.getCause(),
// different casing, depending on jvm impl...
fail.getCause().toString().toLowerCase(Locale.ROOT).contains("[access denied"));
}
}
}
| 48.03871
| 137
| 0.644507
|
6e3e7cb36497485d96f79851f3073ebac10a46a7
| 2,424
|
package io.quarkus.cache.deployment;
import java.util.Arrays;
import java.util.List;
import org.jboss.jandex.DotName;
import io.quarkus.cache.CacheInvalidate;
import io.quarkus.cache.CacheInvalidateAll;
import io.quarkus.cache.CacheKey;
import io.quarkus.cache.CacheName;
import io.quarkus.cache.CacheResult;
import io.quarkus.cache.runtime.CacheInvalidateAllInterceptor;
import io.quarkus.cache.runtime.CacheInvalidateInterceptor;
import io.quarkus.cache.runtime.CacheKeyParameterPositions;
import io.quarkus.cache.runtime.CacheResultInterceptor;
import io.smallrye.mutiny.Multi;
public class CacheDeploymentConstants {
// API annotations names.
public static final DotName CACHE_NAME = dotName(CacheName.class);
public static final DotName CACHE_INVALIDATE_ALL = dotName(CacheInvalidateAll.class);
public static final DotName CACHE_INVALIDATE_ALL_LIST = dotName(CacheInvalidateAll.List.class);
public static final DotName CACHE_INVALIDATE = dotName(CacheInvalidate.class);
public static final DotName CACHE_INVALIDATE_LIST = dotName(CacheInvalidate.List.class);
public static final DotName CACHE_RESULT = dotName(CacheResult.class);
public static final DotName CACHE_KEY = dotName(CacheKey.class);
public static final List<DotName> INTERCEPTOR_BINDINGS = Arrays.asList(CACHE_RESULT, CACHE_INVALIDATE,
CACHE_INVALIDATE_ALL);
public static final List<DotName> INTERCEPTOR_BINDING_CONTAINERS = Arrays.asList(CACHE_INVALIDATE_LIST,
CACHE_INVALIDATE_ALL_LIST);
public static final List<DotName> INTERCEPTORS = Arrays.asList(dotName(CacheInvalidateAllInterceptor.class),
dotName(CacheInvalidateInterceptor.class), dotName(CacheResultInterceptor.class));
public static final DotName CACHE_KEY_PARAMETER_POSITIONS = dotName(CacheKeyParameterPositions.class);
// MicroProfile REST Client.
public static final DotName REGISTER_REST_CLIENT = DotName
.createSimple("org.eclipse.microprofile.rest.client.inject.RegisterRestClient");
// Mutiny.
public static final DotName MULTI = dotName(Multi.class);
// Annotations parameters.
public static final String CACHE_NAME_PARAM = "cacheName";
// Caffeine.
public static final String CAFFEINE_CACHE_TYPE = "caffeine";
private static DotName dotName(Class<?> annotationClass) {
return DotName.createSimple(annotationClass.getName());
}
}
| 44.888889
| 112
| 0.787954
|
ff46f9fae2e9c7cbab03005dfcfbfe03a62be5cf
| 1,860
|
package tree;
/**
*
* @author baesparza
*/
class Node {
public Node left, right;
public int val;
public Node (int val) {
this.val = val;
this.left = this.right = null;
}
}
class Tree {
private Node root;
public Tree() {
this.root = null;
}
public void addNode(int value){
// create fist node
if (this.root == null) {
this.root = new Node(value);
return;
}
// tree already has nodes
this.addNode(this.root, value);
}
public void addNode(Node tree, int value){
// when need to be added to the left
if (value <= tree.val) {
// create a new node
if (tree.left == null) {
tree.left = new Node(value);
return;
}
// go to left tree
this.addNode(tree.left, value);
return;
}
if (tree.right == null) {
tree.right = new Node(value);
return;
}
// go to right tree
this.addNode(tree.right, value);
}
public String printInOrder() {
if (this.root == null) return "void tree";
return "Tree: " + this.printInOrder(this.root);
}
public String printInOrder(Node tree) {
String res = "";
if (tree.left != null) res += this.printInOrder(tree.left);
res += " " + tree.val;
if (tree.right != null) res += this.printInOrder(tree.right);
return res;
}
}
class main {
public static void main(String[] args) {
Tree tree = new Tree();
tree.addNode(0);
tree.addNode(1);
tree.addNode(2);
tree.addNode(7);
tree.addNode(4);
tree.addNode(3);
System.out.println(tree.printInOrder());
}
}
| 22.962963
| 69
| 0.493548
|
12dfbb0a2dc24583eface8019033f48f97eefb58
| 4,882
|
/*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.crawler.selftest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
/**
* Tests that operators can manually assign precedence values to individual
* URLs.
*
* <p>This class crawls the same directory structure as
* {@link Precedence1SelfTest}, using the same number of sheets. However,
* insteading of creating groups of URIs using SURT prefixes, the HiPri and
* LoPri sheets are assigned to two individual URIs. The test then assures
* that the HiPri URI is crawled before anything else, and that the LoPri
* URL is crawled after everything else.
*
* @author pjack
*/
public class Precedence4SelfTest extends Precedence1SelfTest {
@Override
protected void verify() throws Exception {
File crawlLog = new File(getLogsDir(), "crawl.log");
BufferedReader br = null;
List<String> crawled = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(crawlLog));
for (String s = br.readLine(); s != null; s = br.readLine()) {
s = s.substring(42);
int i = s.indexOf(' ');
s = s.substring(0, i);
crawled.add(s);
}
} finally {
IOUtils.closeQuietly(br);
}
assertEquals("http://127.0.0.1:7777/robots.txt", crawled.get(0));
assertEquals("http://127.0.0.1:7777/five/a.html", crawled.get(1));
assertEquals("http://127.0.0.1:7777/five/b.html", crawled.get(crawled.size() - 1));
}
protected String getSeedsString() {
return "http://127.0.0.1:7777/seed.html\\n"+
"http://127.0.0.1:7777/one/a.html\\n"+
"http://127.0.0.1:7777/five/a.html\\n"+
"http://127.0.0.1:7777/ten/a.html\\n"+
"http://127.0.0.1:7777/ten/b.html\\n"+
"http://127.0.0.1:7777/five/b.html\\n"+
"http://127.0.0.1:7777/one/b.html\\n"+
"http://127.0.0.1:7777/five/c.html\\n"+
"http://127.0.0.1:7777/one/c.html\\n"+
"http://127.0.0.1:7777/ten/c.html";
}
protected String configureSheets(String config) {
// add sheets which overlay alternate precedence values for two
// specific URIs
String sheets =
"<bean class='org.archive.crawler.spring.SurtPrefixesSheetAssociation'>\n" +
" <property name='surtPrefixes'>\n" +
" <list>\n" +
" <value>http://(127.0.0.1:7777)/five/b.html</value>\n" +
" </list>\n" +
" </property>\n" +
" <property name='targetSheetNames'>\n" +
" <list>\n" +
" <value>loPri</value>\n" +
" </list>\n" +
" </property>\n" +
"</bean>\n" +
"<bean id='loPri' class='org.archive.spring.Sheet'>\n" +
" <property name='map'>\n" +
" <map>\n" +
" <entry key='preparer.uriPrecedencePolicy.basePrecedence' value='10'/>\n" +
" </map>\n" +
" </property>\n" +
"</bean>\n" +
"<bean class='org.archive.crawler.spring.SurtPrefixesSheetAssociation'>\n" +
" <property name='surtPrefixes'>\n" +
" <list>\n" +
" <value>http://(127.0.0.1:7777)/five/a.html</value>\n" +
" </list>\n" +
" </property>\n" +
" <property name='targetSheetNames'>\n" +
" <list>\n" +
" <value>hiPri</value>\n" +
" </list>\n" +
" </property>\n" +
"</bean>\n" +
"<bean id='hiPri' class='org.archive.spring.Sheet'>\n" +
" <property name='map'>\n" +
" <map>\n" +
" <entry key='preparer.uriPrecedencePolicy.basePrecedence' value='1'/>\n" +
" </map>\n" +
" </property>\n" +
"</bean>\n";
config = config.replace("</beans>", sheets+"</beans>");
return config;
}
}
| 37.844961
| 91
| 0.555305
|
b42994e51fa72f8cb78e8a4a9ebb83f72af916f9
| 1,705
|
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.mapreduce.*;
import data.City;
import data.CityKey;
import mapreduce.combiner.IntegerSumCombinerFactory;
import mapreduce.mapper.CountryCityPopulationMapper;
import mapreduce.reducer.IntegerSumReducerFactory;
import java.util.Map;
public class MapReduceCountryCityPopulation {
public static void main(String[] args) throws Exception {
Config conf = new Config();
HazelcastInstance hz = Hazelcast.newHazelcastInstance(conf);
IMap<CityKey, City> cities = hz.getMap("cities");
if (cities.isEmpty()) {
cities.put(new CityKey("London", "GB"),
new City("London", "GB", 8416535, 1572));
cities.put(new CityKey("Southampton", "GB"),
new City("Southampton", "GB", 242100, 51));
cities.put(new CityKey("Chicago", "US"),
new City("Chicago", "US", 2718782, 606));
cities.put(new CityKey("Washington DC", "US"),
new City("Washington DC", "US", 658893, 177));
cities.put(new CityKey("Seattle", "US"),
new City("Seattle", "US", 652405, 370));
}
JobTracker jobTracker = hz.getJobTracker("default");
KeyValueSource<CityKey, City> sourceData = KeyValueSource.fromMap(cities);
Job<CityKey, City> job = jobTracker.newJob(sourceData);
JobCompletableFuture<Map<String, Integer>> future = job
.mapper(new CountryCityPopulationMapper())
.combiner(new IntegerSumCombinerFactory())
.reducer(new IntegerSumReducerFactory())
.submit();
Map<String, Integer> result = future.get();
System.err.println(result);
}
}
| 34.795918
| 78
| 0.697947
|
d96a9449927c46e7c05570c0430b9deeec98e3c1
| 3,385
|
package com.fa;
import java.util.*;
public class Main {
//region STATIC
public static Scanner scanner = new Scanner(System.in);
public static Constant _ = new Constant();
public static HashSet<String> alphabets = new HashSet<>();
public static List<Grammar> grammars = new ArrayList<>();
//endregion
public static void main(String[] args) {
//region START STATE
System.out.println("Enter start state:\nNotice:\n\t* Enter this input in UPPER case");
String start = scanner.next().toUpperCase();
//endregion
//region ALPHABETS
System.out.println("Enter alphabets: \nNotice:\n\t* Separate them with ','\n\t* Enter this input in UPPER case");
String next = scanner.next().toUpperCase();
String[] points = next.replace(" ", "").split(",");
alphabets = new HashSet<>(Arrays.asList(points));
//endregion
//region INITIAL STATE NAMES
initialStateNames();
//endregion
//region GRAMMARS
System.out.println("Enter grammar.\nRules:\n\t* To enter grammar use this rules: S->aX\nNotice: \n\t* To quit enter q or Q\n\t* This program just accepts right linear or left linear grammar.\n\t* Use '?' for lambda.");
while (scanner.hasNextLine()) {
String grammar = scanner.nextLine();
if (grammar.equals(""))
continue;
if (grammar.toLowerCase().equals("q"))
break;
String[] productions = grammar.split("->");
String from = productions[0];
if (grammar.contains("|")) {
productions = productions[1].split("\\|");
for (String production : productions) {
grammars.add(GrammarToNfa.makeGrammar(from, production));
}
} else {
grammars.add(GrammarToNfa.makeGrammar(from, productions[1]));
}
}
//endregion
//region CREATE STATES
//region CONVERT LEFT LINEAR INTO RIGHT LINEAR GRAMMAR
GrammarToNfa.changeGrammarTypeToRightLinear(start, grammars);
//endregion
//region ADD MIDDLE STATES
GrammarToNfa.addMiddleStates(grammars);
//endregion
//region IMPORT VARIABLE TO VARIABLE PRODUCTIONS
GrammarToNfa.importVariableProductions(grammars);
//endregion
//region STANDARD STATES
GrammarToNfa.standardization(grammars);
//endregion
//region INITIAL STATES
Nfa.initialStates(start, grammars);
//endregion
//endregion
//region Transition function
Nfa.printNfaTransactions(start);
//endregion
//region String Test
boolean isContinue = true;
while (isContinue) {
System.out.println("> Enter the string: ");
String string = scanner.next();
Nfa.acceptor(string, start);
System.out.println("Press 'c' to continue ...");
string = scanner.next();
isContinue = string.equals("c");
}
//endregion
}
//region PRIVATE
private static void initialStateNames() {
for (String alphabet : alphabets) {
Constant.STATE_NAMES.put(alphabet, Constant.BASE_STATE_NAME + (Constant.STATE_NAMES.size()));
}
}
//endregion
}
| 31.933962
| 226
| 0.587297
|
ff8819f1909e363dec74f5f0e9d8b85f197b95fe
| 4,544
|
package com.basis.net;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.basis.BasisHelper;
import com.bcq.adapter.interfaces.DataObserver;
import com.bcq.adapter.interfaces.IAdapte;
import com.bcq.adapter.interfaces.IHolder;
import com.bcq.net.net.NetRefresher;
import com.bcq.net.net.Page;
import com.bcq.net.wrapper.interfaces.IPage;
import com.bcq.net.wrapper.interfaces.IResult;
import com.bcq.refresh.IRefresh;
import com.kit.UIKit;
import com.kit.utils.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* @param <ND> 适配器数据类型
* @param <AD> 接口数据类型
* @param <VH> 接口数据类型
* @author: BaiCQ
* @createTime: 2017/1/13 11:38
* @className: UIController
* @Description: 供列表显示页面使用的控制器
*/
public class Controller<ND, AD, VH extends IHolder> extends NetRefresher<ND> implements DataObserver {
private final String TAG = "Controller";
private IOperator<ND, AD, VH> operator;
//适配器使用功能集合 泛型不能使用 T 接口返回类型有可能和适配器使用的不一致
private List<AD> adapterList = new ArrayList<>();
private IAdapte<AD, VH> mAdapter;
private IRHolder holder;
protected RecyclerView.LayoutManager onSetLayoutManager() {
return new LinearLayoutManager(UIKit.getContext());
}
public Controller(IRHolder holder, Class<ND> tclazz, IOperator<ND, AD, VH> operator) {
this(holder, tclazz, operator, BasisHelper.getPage());
}
public Controller(IRHolder holder, Class<ND> tclazz, IOperator<ND, AD, VH> operator, Page page) {
super(tclazz, page, operator);
this.holder = holder;
this.operator = operator;
initialize();
}
private void initialize() {
holder.getRefresh().enableRefresh(true);
holder.getRefresh().enableLoad(true);
if (holder.getRefresh() instanceof RecyclerView) {
((RecyclerView) holder.getRefresh()).setLayoutManager(onSetLayoutManager());
}
mAdapter = operator.onSetAdapter();
mAdapter.setRefreshView((View) holder.getRefresh());
//注意此处一定要在setRefreshView后,否则别覆盖
mAdapter.setDataObserver(this);
holder.getRefresh().setLoadListener(new IRefresh.LoadListener() {
@Override
public void onRefresh() {
requestAgain(true, operator);
}
@Override
public void onLoad() {
requestAgain(false, operator);
}
});
holder.getNone().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestAgain(true, operator);
}
});
}
/**
* 重载:处理enable load
*
* @param result 结果集
*/
@Override
public void onResult(IResult.ObjResult<List<ND>> result) {
super.onResult(result);
IPage page = result.getExtra();
boolean loadfull = null == page ? false : (page.getPage() >= page.getTotal());
holder.getRefresh().enableLoad(loadfull);
}
@Override
public void onAfter() {
super.onAfter();
if (null != holder && null != holder.getRefresh()) {
holder.getRefresh().refreshComplete();
holder.getRefresh().loadComplete();
}
}
/**
* 设置适配器数据回调
*
* @param netData 接口放回数据
* @param isRefresh 是否刷新
*/
@Override
public void onRefreshData(List<ND> netData, boolean isRefresh) {
/* 当页数据转换处理 */
List<AD> preData = operator.onTransform(netData);
if (isRefresh) adapterList.clear();
if (null != preData) adapterList.addAll(preData);
/* 设置适配器前 */
List<AD> temp = operator.onPreSetData(adapterList);
if (null != temp && !temp.isEmpty()) {
if (null != holder) holder.showType(IRHolder.Type.show);
// 此处已有缓存,不能再使用adapter中的缓存
// 否则:load more 前的数据会叠加到adapter的数据集中
mAdapter.setData(temp, true);
} else {
if (null != holder) holder.showType(IRHolder.Type.none);
}
}
/**
* 因适配器 removeItem 导致数据从有到无是回调
* BsiAdapter.OnNoDataListeren 接口
*/
@Override
public void onObserve(int length) {
Logger.e(TAG, "onObserve: len = " + length);
if (null != holder) holder.showType(length == 0 ? IRHolder.Type.none : IRHolder.Type.show);
}
}
| 32.690647
| 103
| 0.610035
|
73f01c08322e458a77a519251a16e87d05524302
| 75
|
package net.hexogendev.hexogen.api.network;
public interface IPacket {
}
| 12.5
| 43
| 0.786667
|
c6df4c8faeff9cb4f24cf6d3523ca927d8c2da61
| 59
|
package org.epodia.enumeration;
public enum Category {
}
| 9.833333
| 31
| 0.762712
|
90520d3b025d58551f48177faa863cb529067938
| 2,247
|
package MVCpatten.view;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JTextField;
import MVCpatten.model.ProductDTO;
import MVCpatten.model.ProductDAO;
import MVCpatten.view.event.AppBtnEvent;
public class AppMain extends JFrame {
// member value
private final int WIDTH = 800, HEIGHT = 300;
private AppUIsetting appUIset;
private ProductDAO productDAO;
private ArrayList<ProductDTO> firstAllProduct = new ArrayList<ProductDTO>();
public AppMain() {
this.productDAO = new ProductDAO();
firstAllProduct= this.productDAO.getAll(); // same with the 'datas'!
this.startUI();
}
// UI 화면 구성 메서드
private void startUI() {
this.appUIset = new AppUIsetting(this, this.productDAO.getItems());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("MVC Patten Desgin");
this.setBackground(Color.WHITE);
this.setSize(WIDTH, HEIGHT);
this.setVisible(true);
// btn Action handdler
this.AppBtnEvent();
} // startUI()
// 각 메뉴에다 적절하게 이벤트 떄려박기
private void AppBtnEvent() {
AppBtnEvent btnAction = new AppBtnEvent(this);
int btnCounter = this.appUIset.getbtnPanel(3).getComponentCount();
for(int i = 0; i < btnCounter; i++) {
JButton jbtnTemp = (JButton) this.appUIset.getbtnPanel(3).getComponent(i);
jbtnTemp.addActionListener(btnAction);
} // for
} // AppBtnEvent
// 화면 로딩 및 리로딩 이벤트 처리 메서드
@SuppressWarnings("unchecked")
public void refreshData() {
this.appUIset.getTextArea().setText("관리번호\t상품명\t단가\t제조사\n");
this.appUIset.getComboBox().setModel(new DefaultComboBoxModel<String>(this.productDAO.getItems()));
this.clearField();
}
// 입력 양식 초기화 메서드
public void clearField() {
JPanel tempP = this.appUIset.getbtnPanel(2);
((JTextField) tempP.getComponent(1)).setText("");
((JTextField) tempP.getComponent(2)).setText("");
((JTextField) tempP.getComponent(3)).setText("");
}
public AppUIsetting getAppUIset() {
return this.appUIset;
}
public ProductDAO getProductDAO() {
return this.productDAO;
}
}
| 28.0875
| 102
| 0.70583
|
f3c03ef329d57c5eb355df8585d549bcd13c320d
| 1,107
|
package com.github.maddymakesgames.MysticalArts.recipes;
import com.github.maddymakesgames.MysticalArts.MysticalArts;
import com.github.maddymakesgames.MysticalArts.recipes.serializers.RitualTableRecipeSerializer;
import net.minecraft.recipe.Recipe;
import net.minecraft.recipe.RecipeSerializer;
import net.minecraft.recipe.RecipeType;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class MysticalRecipes {
public static RecipeType<RitualTableRecipe> RITUAL = buildRecipeType(new Identifier(MysticalArts.MODID, "ritual"));
public static RecipeSerializer<RitualTableRecipe> RITUAL_SERIALIZER = new RitualTableRecipeSerializer();
public static void init() {
Registry.register(Registry.RECIPE_TYPE, new Identifier(MysticalArts.MODID, "ritual"), RITUAL);
Registry.register(Registry.RECIPE_SERIALIZER, new Identifier(MysticalArts.MODID, "ritual"), RITUAL_SERIALIZER);
}
private static <T extends Recipe<?>> RecipeType<T> buildRecipeType(Identifier id) {
return new RecipeType<T>() {
public String toString() {
return id.getPath();
}
};
}
}
| 38.172414
| 116
| 0.803975
|
0e0b93d9c5502295d40a26cd36c24c3d11432e24
| 2,406
|
package org.ptolomeu.algebra.expression.parser;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.ptolomeu.algebra.expression.parser.Derivation.EXP_BY_INT_AND_OPER;
import static org.ptolomeu.algebra.expression.parser.Symbol.NTS_EXP;
import static org.ptolomeu.algebra.expression.parser.Symbol.NTS_INT;
import static org.ptolomeu.algebra.expression.parser.Symbol.NTS_OPER;
import org.junit.Test;
import org.ptolomeu.algebra.expression.parser.LogDerivationTableBuilder.Table;
import org.ptolomeu.util.Stack;
public class LogDerivationTableBuilderTest {
private LogDerivationTableBuilder tableBuilder = new LogDerivationTableBuilder();
private Stack<Symbol> stack = Stack.newInstance();
@Test
public void buildInnerStructure() throws Exception {
// 1st line of the table: 1 + 9 + 4 || EXP || EXP -> INT OPER
// given
Scanner tokens = Sentence.newInstance("1 + 9 + 4").tokenizer();
stack.push(NTS_EXP);
Derivation derivation = EXP_BY_INT_AND_OPER;
// when
Table table = tableBuilder.addLine(tokens, stack, derivation).table();
// then lines...
assertThat(table.numOfLines(), is(1));
// and columns...
assertThat(table.line(1).column(1), is("1+9+4"));
assertThat(table.line(1).column(2), is("EXP"));
assertThat(table.line(1).column(3), is("EXP -> INT OPER"));
assertThat(table.maxLengthOfColumn(1), is(5));
assertThat(table.maxLengthOfColumn(2), is(3));
assertThat(table.maxLengthOfColumn(3), is(15));
// 2st line of the table: 1 + 9 + 4 || OPER INT || INT -> 1
// given
stack.pop();
stack.push(NTS_OPER);
stack.push(NTS_INT);
derivation = Derivation.INT_BY_1;
// when
table = tableBuilder.addLine(tokens, stack, derivation).table();
// and columns...
assertThat(table.line(2).column(1), is("1+9+4"));
assertThat(table.line(2).column(2), is("OPER INT"));
assertThat(table.line(2).column(3), is("INT -> 1"));
assertThat(table.maxLengthOfColumn(1), is(5));
assertThat(table.maxLengthOfColumn(2), is(8)); // will increase columns maxLength
assertThat(table.maxLengthOfColumn(3), is(15));
}
}
| 37.59375
| 90
| 0.639235
|
0d28400ab619ede3b0101f0daf8181caeb051400
| 4,529
|
package com.jasonrobinson.racer.db;
import android.util.Log;
import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.jasonrobinson.racer.enumeration.RaceOptions;
import com.jasonrobinson.racer.model.Race;
import com.jasonrobinson.racer.model.Race.Rule;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class DatabaseManager {
private static final String TAG = DatabaseManager.class.getSimpleName();
@Inject
DatabaseHelper mHelper;
public List<Race> getRaces(RaceOptions option) {
switch (option) {
case FINISHED:
return getAllFinishedRaces();
case UNFINISHED:
return getAllUnfinishedRaces();
case IN_PROGRESS:
return getAllInProgressRaces();
case ALL:
default:
return getAllRaces();
}
}
private List<Race> getAllRaces() {
try {
return mHelper.getRaceDao().queryForAll();
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve all races", e);
return null;
}
}
private List<Race> getAllFinishedRaces() {
try {
QueryBuilder<Race, String> queryBuilder = mHelper.getRaceDao().queryBuilder();
queryBuilder.where().le("endAt", new Date(System.currentTimeMillis()));
queryBuilder.orderBy("startAt", false);
return queryBuilder.query();
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve all finished races", e);
return null;
}
}
private List<Race> getAllUnfinishedRaces() {
try {
QueryBuilder<Race, String> queryBuilder = mHelper.getRaceDao().queryBuilder();
queryBuilder.where().gt("endAt", new Date(System.currentTimeMillis()));
queryBuilder.orderBy("startAt", true);
return queryBuilder.query();
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve all finished races", e);
return null;
}
}
private List<Race> getAllInProgressRaces() {
Date now = new Date(System.currentTimeMillis());
try {
QueryBuilder<Race, String> queryBuilder = mHelper.getRaceDao().queryBuilder();
queryBuilder.where().gt("endAt", now).and().lt("startAt", now);
return queryBuilder.query();
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve all finished races", e);
return null;
}
}
public Race getRace(String id) {
try {
return mHelper.getRaceDao().queryForId(id);
} catch (SQLException e) {
Log.e(TAG, "Failed to retrieve race with id " + id, e);
return null;
}
}
public boolean addOrUpdateRace(Race race) {
try {
CreateOrUpdateStatus status = mHelper.getRaceDao().createOrUpdate(race);
for (Rule rule : race.getRules()) {
rule.setRace(race);
// Rules could have been added or removed, so remove persisted
// rules and add current rules
if (status.isUpdated()) {
DeleteBuilder<Rule, Long> deleteBuilder = mHelper.getRuleDao().deleteBuilder();
deleteBuilder.where().eq("ruleId", rule.getRuleId()).and().eq("race_id", race.getRaceId());
deleteBuilder.delete();
}
mHelper.getRuleDao().createOrUpdate(rule);
}
return true;
} catch (SQLException e) {
Log.e(TAG, "Failed to cache a race", e);
return false;
}
}
public int addOrUpdateRaceList(final List<Race> races) {
try {
return mHelper.getRaceDao().callBatchTasks(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int counter = 0;
for (Race race : races) {
counter += addOrUpdateRace(race) ? 1 : 0;
}
return counter;
}
});
} catch (Exception e) {
Log.e(TAG, "Failed to batch cache races", e);
}
return 0;
}
}
| 31.451389
| 111
| 0.568337
|
2e810c2067ddedc986016898db359a52863f89d6
| 424
|
package com.ushill.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum MovieSearchMatchType {
TITLE(1, "title"),
NICKNAME(2, "nickname"),
DIRECTORS(3, "directorsName"),
ACTORS(4, "actorsName");
private int matchType;
private String propertyName;
}
| 19.272727
| 34
| 0.747642
|
4708001a49a01f486d79369bfba8662ea32479f6
| 131
|
package com.kisan.BehavioralDesignPatterns.CommandPattern.ImplementationMosh.fx;
public interface Command {
void execute();
}
| 21.833333
| 80
| 0.80916
|
af2d73b24cba3d6a066747049a3ac04691e04122
| 298
|
package com.lingx;
/**
* @author www.lingx.com
* @version 创建时间:2017年4月21日 下午5:23:02
* 类说明
*/
public class Lingx {
public static final String VERSION="2.0.0";
public static final String HOME="http://www.lingx.com/";
public static final String LINK="283853318@qq.com";
}
| 19.866667
| 58
| 0.654362
|
c8afe050c791ba4ec10e7389cb85ff7b4e540a3c
| 13,904
|
package uk.ac.kcl.spiderbyte.view;
import android.support.test.espresso.ViewInteraction;
import android.support.test.filters.LargeTest;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.android21buttons.fragmenttestrule.FragmentTestRule;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import uk.ac.kcl.spiderbyte.R;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
/**
* Created by Dimitris on 29/03/2018.
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
public class AnnouncementDetailFragmentTest {
@Rule
public FragmentTestRule<?, AnnouncementListFragment> fragmentTestRule = FragmentTestRule.create(AnnouncementListFragment.class);
@Test
public void announcementDetail() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView = onView(
allOf(withText("General"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
0),
isDisplayed()));
tagView.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView2 = onView(
allOf(withText("General"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
0),
isDisplayed()));
tagView2.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView3 = onView(
allOf(withText("Important"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
1),
isDisplayed()));
tagView3.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView4 = onView(
allOf(withText("Important"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
1),
isDisplayed()));
tagView4.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView5 = onView(
allOf(withText("Careers"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
2),
isDisplayed()));
tagView5.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView6 = onView(
allOf(withText("Careers"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
2),
isDisplayed()));
tagView6.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView7 = onView(
allOf(withText("Modules"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
3),
isDisplayed()));
tagView7.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction tagView8 = onView(
allOf(withText("Modules"),
childAtPosition(
allOf(withId(R.id.tag_group),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
0)),
3),
isDisplayed()));
tagView8.perform(click());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction recyclerView = onView(
allOf(withId(R.id.announcementList),
childAtPosition(
withClassName(is("android.widget.LinearLayout")),
1)));
recyclerView.perform(actionOnItemAtPosition(0, click()));
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction floatingActionButton = onView(
allOf(childAtPosition(
allOf(withId(R.id.floating_menu),
childAtPosition(
withClassName(is("android.support.design.widget.CoordinatorLayout")),
2)),
2),
isDisplayed()));
floatingActionButton.perform(click());
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction floatingActionButton2 = onView(
allOf(withId(R.id.pdf_button),
childAtPosition(
allOf(withId(R.id.floating_menu),
childAtPosition(
withClassName(is("android.support.design.widget.CoordinatorLayout")),
2)),
1),
isDisplayed()));
floatingActionButton2.perform(click());
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pressBack();
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction floatingActionButton3 = onView(
allOf(childAtPosition(
allOf(withId(R.id.floating_menu),
childAtPosition(
withClassName(is("android.support.design.widget.CoordinatorLayout")),
2)),
2),
isDisplayed()));
floatingActionButton3.perform(click());
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
pressBack();
//
//
// ViewInteraction recyclerView = onView(
// allOf(withId(R.id.announcementList),
// childAtPosition(
// withClassName(is("android.widget.LinearLayout")),
// 1)));
// recyclerView.perform(actionOnItemAtPosition(1, click()));
//
// // Added a sleep statement to match the app's execution delay.
// // The recommended way to handle such scenarios is to use Espresso idling resources:
// // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// ViewInteraction floatingActionButton = onView(
// allOf(childAtPosition(
// allOf(withId(R.id.floating_menu),
// childAtPosition(
// withClassName(is("android.support.design.widget.CoordinatorLayout")),
// 2)),
// 1),
// isDisplayed()));
// floatingActionButton.perform(click());
//
// // Added a sleep statement to match the app's execution delay.
// // The recommended way to handle such scenarios is to use Espresso idling resources:
// // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
// try {
// Thread.sleep(150);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// ViewInteraction floatingActionButton2 = onView(
// allOf(withId(R.id.pdf_button),
// childAtPosition(
// allOf(withId(R.id.floating_menu),
// childAtPosition(
// withClassName(is("android.support.design.widget.CoordinatorLayout")),
// 2)),
// 1),
// isDisplayed()));
// floatingActionButton2.perform(click());
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
| 39.612536
| 132
| 0.49964
|
7e280276b2adbf03d2360df44ebec12a0c2a7a12
| 8,280
|
package io.vertx.up.uca.compare;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.core.json.JsonObject;
import io.vertx.up.eon.Strings;
import io.vertx.up.eon.Values;
import io.vertx.up.experiment.mixture.HTField;
import io.vertx.up.log.Annal;
import io.vertx.up.uca.cache.Cc;
import io.vertx.up.util.Ut;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* ## Diff Container ( New Version )
*
* ### 1. Intro
*
* Store definition of each model for diff ( comparing workflow )
*
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public class Vs implements Serializable {
private static final Annal LOGGER = Annal.get(Vs.class);
private static final Cc<String, Vs> CC_VS = Cc.open();
/**
* Here are new `typeMap` of name = HTField
*
* Because HTField contains `type, name, alias` and etc, it means that you can determine the format
* Elementary / JsonObject / JsonArray by `isComplex` here.
*
* When format = Elementary ( Not Complex )
*
* 1. name is the attribute name of model ( HAttribute ).
* 2. type is the java type that could be reflected ( stored in HTField )
*
* When format = JsonObject / JsonArray ( Complex )
*
* 1. name is the attribute name of model ( HAttribute ).
* 2. The data type is fixed: JsonObject / JsonArray.
* 3. And the HTField type contains `children` and isComplex = true
*/
private transient final ConcurrentMap<String, HTField> typeMap = new ConcurrentHashMap<>();
/**
* Ignored field that could be set from object.
*
* 1. Default ignore set
* 2. System ignore set that could not be compared.
* 3. The ignore fields that could be set by developer.
*/
private transient final Set<String> ignores = new HashSet<>();
private Vs(final ConcurrentMap<String, HTField> mapType) {
/*
* this reference following rules
* - mapType: stored current field = type
* - mapSubType: when current field is ( JsonObject / JsonArray ), complex
* the mapSubType stored ( field = HTField ) and here HTField is complex type
*/
if (Objects.nonNull(mapType) && !mapType.isEmpty()) {
// Tpl Solution
this.typeMap.putAll(mapType);
}
}
public static Vs create(final String identifier, final ConcurrentMap<String, HTField> mapType) {
return CC_VS.pick(() -> new Vs(mapType), identifier);
// Fn.po?l(POOL_VS, identifier, () -> new Vs(mapType));
}
// ============================ Static Comparing Change ===============================
public static boolean isValue(final Object value, final Class<?> type) {
// Fix Null Pointer Exception for Unknown Type comparing.
final VsSame same = VsSame.get(type);
return Objects.isNull(same) ? Objects.nonNull(value) : same.ok(value);
}
public static boolean isChange(final Object valueOld, final Object valueNew, final HTField htField) {
return !isSame(valueOld, valueNew, () -> VsSame.get(htField));
}
// ============================ Complex Comparing Change ===============================
public static <T, V> boolean isChange(final T left, final T right, final Function<T, V> fnGet) {
return !isSame(left, right, fnGet);
}
public static <T, V> boolean isSame(final T left, final T right, final Function<T, V> fnGet) {
if (Objects.nonNull(left) && Objects.nonNull(right)) {
// Both are not null
final V leftValue = fnGet.apply(left);
final V rightValue = fnGet.apply(right);
if (Objects.nonNull(leftValue) && Objects.nonNull(rightValue)) {
final Class<?> type = leftValue.getClass();
return isSame(leftValue, rightValue, () -> VsSame.get(type));
} else {
return Objects.isNull(leftValue) && Objects.isNull(rightValue);
}
} else {
return Objects.isNull(left) && Objects.isNull(right);
}
}
// ============================ Internal Comparing ===============================
private static boolean isSame(final Object valueOld, final Object valueNew, final Supplier<VsSame> supplier) {
if (Objects.isNull(valueOld) && Objects.isNull(valueNew)) {
/* ( Unchanged ) When `new` and `old` are both null */
return true;
} else {
/*
* 1. type
* 2. subset ( JsonArray Only )
* */
final VsSame same = supplier.get();
if (Objects.isNull(same)) {
final String strOld = Objects.nonNull(valueOld) ? valueOld.toString() : Strings.EMPTY;
final String strNew = Objects.nonNull(valueNew) ? valueNew.toString() : Strings.EMPTY;
return strOld.equals(strNew);
} else {
if (Objects.nonNull(valueOld) && Objects.nonNull(valueNew)) {
/*
* Standard workflow here
*/
return same.is(valueOld, valueNew);
} else {
/*
* Non-Standard workflow here
*/
return same.isXor(valueOld, valueNew);
}
}
}
}
@Fluent
public Vs ignores(final Set<String> ignoreSet) {
if (Objects.nonNull(ignoreSet) && !ignoreSet.isEmpty()) {
this.ignores.clear();
this.ignores.addAll(ignoreSet);
}
return this;
}
public Set<String> ignores() {
return this.ignores;
}
public boolean isChange(final JsonObject previous, final JsonObject current) {
// Copy each compared json object
final JsonObject oldCopy = Ut.valueJObject(previous).copy();
final JsonObject newCopy = Ut.valueJObject(current).copy();
/*
* Remove ignore fields, iterating once only, old code ( Twice iterating )
* 1. ignores.forEach(oldCopy::remove);
* 2. ignores.forEach(newCopy::remove);
*/
if (!this.ignores.isEmpty()) {
this.ignores.forEach(field -> {
oldCopy.remove(field);
newCopy.remove(field);
});
}
/*
* Function building here to call `VsInternal`
*/
final Function<String, Boolean> isSame = field -> {
/*
* Extract value here
*/
final Object valueOld = oldCopy.getValue(field);
final Object valueNew = newCopy.getValue(field);
return !this.isChange(valueOld, valueNew, field);
};
/*
* Get the final result of calculation.
* 1) From old Re-calculation
* 2) From new Re-calculation
*/
final boolean unchanged = oldCopy.fieldNames().stream().allMatch(isSame::apply);
final Set<String> newLefts = new HashSet<>(newCopy.fieldNames());
newLefts.removeAll(oldCopy.fieldNames());
final boolean additional = newLefts.stream().allMatch(isSame::apply);
return !(unchanged && additional);
}
public boolean isChange(final JsonObject twins) {
final JsonObject secure = Ut.valueJObject(twins);
return this.isChange(secure.getJsonObject(Values.VS.OLD), secure.getJsonObject(Values.VS.NEW));
}
public boolean isChange(final Object valueOld, final Object valueNew, final String attribute) {
final HTField fieldType = this.typeMap.getOrDefault(attribute, null);
final boolean isChanged = isChange(valueOld, valueNew, fieldType);
LOGGER.info("Field compared: name = {0}, type = {1}, result = {2}",
attribute, fieldType.type(), isChanged);
return isChanged;
}
public boolean isValue(final Object value, final String attribute) {
final HTField fieldType = this.typeMap.getOrDefault(attribute, null);
return isValue(value, fieldType.type());
}
}
| 38.873239
| 114
| 0.59215
|
508e044218e4b501bfc20a1e4eb769424bc3bdc6
| 30,400
|
// Generated by Haxe 3.4.2
package hxDaedalus.ai;
@SuppressWarnings(value={"rawtypes", "unchecked"})
public class AStar extends haxe.lang.HxObject
{
public AStar(haxe.lang.EmptyObject empty)
{
}
public AStar()
{
hxDaedalus.ai.AStar.__hx_ctor_hxDaedalus_ai_AStar(this);
}
public static void __hx_ctor_hxDaedalus_ai_AStar(hxDaedalus.ai.AStar __hx_this)
{
__hx_this.iterEdge = new hxDaedalus.iterators.FromFaceToInnerEdges();
}
public double _radius;
public hxDaedalus.data.Mesh _mesh;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> closedFaces;
public haxe.root.Array<hxDaedalus.data.Face> sortedOpenedFaces;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> openedFaces;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Edge> entryEdges;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> entryX;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> entryY;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> scoreF;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> scoreG;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> scoreH;
public haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Face> predecessor;
public hxDaedalus.iterators.FromFaceToInnerEdges iterEdge;
public double radiusSquared;
public double diameter;
public double diameterSquared;
public hxDaedalus.data.Face fromFace;
public hxDaedalus.data.Face toFace;
public hxDaedalus.data.Face curFace;
public void dispose()
{
this._mesh = null;
this.closedFaces = null;
this.sortedOpenedFaces = null;
this.openedFaces = null;
this.entryEdges = null;
this.entryX = null;
this.entryY = null;
this.scoreF = null;
this.scoreG = null;
this.scoreH = null;
this.predecessor = null;
}
public double get_radius()
{
return this._radius;
}
public double set_radius(double value)
{
this._radius = value;
this.radiusSquared = ( this._radius * this._radius );
this.diameter = ( this._radius * 2 );
this.diameterSquared = ( this.diameter * this.diameter );
return value;
}
public hxDaedalus.data.Mesh set_mesh(hxDaedalus.data.Mesh value)
{
this._mesh = value;
return value;
}
public void findPath(double fromX, double fromY, double toX, double toY, haxe.root.Array<hxDaedalus.data.Face> resultListFaces, haxe.root.Array<hxDaedalus.data.Edge> resultListEdges)
{
this.closedFaces = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.sortedOpenedFaces = new haxe.root.Array<hxDaedalus.data.Face>();
this.openedFaces = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) new haxe.ds.ObjectMap<hxDaedalus.data.Face, Object>());
this.entryEdges = new haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Edge>();
this.entryX = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.entryY = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.scoreF = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.scoreG = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.scoreH = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
this.predecessor = new haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Face>();
hxDaedalus.data.math.Intersection loc;
hxDaedalus.data.Edge locEdge;
hxDaedalus.data.Vertex locVertex;
double distance = 0.0;
hxDaedalus.data.math.Point2D p1 = null;
hxDaedalus.data.math.Point2D p2 = null;
hxDaedalus.data.math.Point2D p3 = null;
loc = hxDaedalus.data.math.Geom2D.locatePosition(fromX, fromY, this._mesh);
switch (loc.index)
{
case 0:
{
return ;
}
case 1:
{
hxDaedalus.data.Edge edge = ((hxDaedalus.data.Edge) (loc.params[0]) );
{
locEdge = edge;
if (locEdge.get_isConstrained())
{
return ;
}
this.fromFace = locEdge.get_leftFace();
}
break;
}
case 2:
{
this.fromFace = ((hxDaedalus.data.Face) (loc.params[0]) );
break;
}
case 3:
{
break;
}
}
loc = hxDaedalus.data.math.Geom2D.locatePosition(toX, toY, this._mesh);
switch (loc.index)
{
case 0:
{
hxDaedalus.data.Vertex vertex1 = ((hxDaedalus.data.Vertex) (loc.params[0]) );
{
locVertex = vertex1;
this.toFace = locVertex.get_edge().get_leftFace();
}
break;
}
case 1:
{
hxDaedalus.data.Edge edge1 = ((hxDaedalus.data.Edge) (loc.params[0]) );
{
locEdge = edge1;
this.toFace = locEdge.get_leftFace();
}
break;
}
case 2:
{
this.toFace = ((hxDaedalus.data.Face) (loc.params[0]) );
break;
}
case 3:
{
break;
}
}
this.sortedOpenedFaces.push(this.fromFace);
this.entryEdges.set(this.fromFace, null);
this.entryX.set(this.fromFace, fromX);
this.entryY.set(this.fromFace, fromY);
this.scoreG.set(this.fromFace, 0);
double dist = java.lang.Math.sqrt(( ( (( toX - fromX )) * (( toX - fromX )) ) + ( (( toY - fromY )) * (( toY - fromY )) ) ));
this.scoreH.set(this.fromFace, dist);
this.scoreF.set(this.fromFace, dist);
hxDaedalus.data.Edge innerEdge;
hxDaedalus.data.Face neighbourFace;
double f;
double g;
double h;
hxDaedalus.data.math.Point2D fromPoint = new hxDaedalus.data.math.Point2D(null, null);
hxDaedalus.data.math.Point2D entryPoint = new hxDaedalus.data.math.Point2D(null, null);
hxDaedalus.data.math.Point2D distancePoint = new hxDaedalus.data.math.Point2D(null, null);
boolean fillDatas;
while (true)
{
if (( this.sortedOpenedFaces.length == 0 ))
{
this.curFace = null;
break;
}
this.curFace = ((hxDaedalus.data.Face) (this.sortedOpenedFaces.pop()) );
if (( this.curFace == this.toFace ))
{
break;
}
this.iterEdge.set_fromFace(this.curFace);
while (true)
{
innerEdge = this.iterEdge.next();
if ( ! ((( innerEdge != null ))) )
{
break;
}
if (innerEdge.get_isConstrained())
{
continue;
}
neighbourFace = innerEdge.get_rightFace();
if (( ! (haxe.lang.Runtime.toBool(this.closedFaces.get(neighbourFace))) ))
{
if (( ( ( this.curFace != this.fromFace ) && ( this._radius > 0 ) ) && ! (this.isWalkableByRadius(((hxDaedalus.data.Edge) (this.entryEdges.get(this.curFace)) ), this.curFace, innerEdge)) ))
{
continue;
}
fromPoint.x = haxe.lang.Runtime.toDouble(this.entryX.get(this.curFace));
fromPoint.y = haxe.lang.Runtime.toDouble(this.entryY.get(this.curFace));
entryPoint.x = ( (( innerEdge.get_originVertex().get_pos().x + innerEdge.get_destinationVertex().get_pos().x )) / 2 );
entryPoint.y = ( (( innerEdge.get_originVertex().get_pos().y + innerEdge.get_destinationVertex().get_pos().y )) / 2 );
distancePoint.x = ( entryPoint.x - toX );
distancePoint.y = ( entryPoint.y - toY );
h = distancePoint.get_length();
distancePoint.x = ( fromPoint.x - entryPoint.x );
distancePoint.y = ( fromPoint.y - entryPoint.y );
g = haxe.lang.Runtime.toDouble(haxe.lang.Runtime.plus(this.scoreG.get(this.curFace), distancePoint.get_length()));
f = ( h + g );
fillDatas = false;
if (( haxe.lang.Runtime.eq(this.openedFaces.get(neighbourFace), null) || ( ! (haxe.lang.Runtime.toBool(this.openedFaces.get(neighbourFace))) ) ))
{
this.sortedOpenedFaces.push(neighbourFace);
this.openedFaces.set(neighbourFace, true);
fillDatas = true;
}
else
{
if (( haxe.lang.Runtime.compare(this.scoreF.get(neighbourFace), f) > 0 ))
{
fillDatas = true;
}
}
if (fillDatas)
{
this.entryEdges.set(neighbourFace, innerEdge);
{
double v = entryPoint.x;
this.entryX.set(neighbourFace, v);
}
{
double v1 = entryPoint.y;
this.entryY.set(neighbourFace, v1);
}
this.scoreF.set(neighbourFace, f);
this.scoreG.set(neighbourFace, g);
this.scoreH.set(neighbourFace, h);
{
hxDaedalus.data.Face v2 = this.curFace;
this.predecessor.set(neighbourFace, v2);
}
}
}
}
this.openedFaces.set(this.curFace, false);
this.closedFaces.set(this.curFace, true);
this.sortedOpenedFaces.sort(new haxe.lang.Closure(this, "sortingFaces"));
}
if (( this.curFace == null ))
{
return ;
}
resultListFaces.push(this.curFace);
while (( this.curFace != this.fromFace ))
{
resultListEdges.unshift(((hxDaedalus.data.Edge) (this.entryEdges.get(this.curFace)) ));
this.curFace = ((hxDaedalus.data.Face) (this.predecessor.get(this.curFace)) );
resultListFaces.unshift(this.curFace);
}
}
public int sortingFaces(hxDaedalus.data.Face a, hxDaedalus.data.Face b)
{
if (haxe.lang.Runtime.eq(this.scoreF.get(a), this.scoreF.get(b)))
{
return 0;
}
else
{
if (( haxe.lang.Runtime.compare(this.scoreF.get(a), this.scoreF.get(b)) < 0 ))
{
return 1;
}
else
{
return -1;
}
}
}
public boolean isWalkableByRadius(hxDaedalus.data.Edge fromEdge, hxDaedalus.data.Face throughFace, hxDaedalus.data.Edge toEdge)
{
hxDaedalus.data.Vertex vA = null;
hxDaedalus.data.Vertex vB = null;
hxDaedalus.data.Vertex vC = null;
if (( fromEdge.get_originVertex() == toEdge.get_originVertex() ))
{
vA = fromEdge.get_destinationVertex();
vB = toEdge.get_destinationVertex();
vC = fromEdge.get_originVertex();
}
else
{
if (( fromEdge.get_destinationVertex() == toEdge.get_destinationVertex() ))
{
vA = fromEdge.get_originVertex();
vB = toEdge.get_originVertex();
vC = fromEdge.get_destinationVertex();
}
else
{
if (( fromEdge.get_originVertex() == toEdge.get_destinationVertex() ))
{
vA = fromEdge.get_destinationVertex();
vB = toEdge.get_originVertex();
vC = fromEdge.get_originVertex();
}
else
{
if (( fromEdge.get_destinationVertex() == toEdge.get_originVertex() ))
{
vA = fromEdge.get_originVertex();
vB = toEdge.get_destinationVertex();
vC = fromEdge.get_destinationVertex();
}
}
}
}
double dot;
boolean result = false;
double distSquared;
dot = ( ( (( vC.get_pos().x - vA.get_pos().x )) * (( vB.get_pos().x - vA.get_pos().x )) ) + ( (( vC.get_pos().y - vA.get_pos().y )) * (( vB.get_pos().y - vA.get_pos().y )) ) );
if (( dot <= 0 ))
{
distSquared = ( ( (( vC.get_pos().x - vA.get_pos().x )) * (( vC.get_pos().x - vA.get_pos().x )) ) + ( (( vC.get_pos().y - vA.get_pos().y )) * (( vC.get_pos().y - vA.get_pos().y )) ) );
if (( distSquared >= this.diameterSquared ))
{
return true;
}
else
{
return false;
}
}
dot = ( ( (( vC.get_pos().x - vB.get_pos().x )) * (( vA.get_pos().x - vB.get_pos().x )) ) + ( (( vC.get_pos().y - vB.get_pos().y )) * (( vA.get_pos().y - vB.get_pos().y )) ) );
if (( dot <= 0 ))
{
distSquared = ( ( (( vC.get_pos().x - vB.get_pos().x )) * (( vC.get_pos().x - vB.get_pos().x )) ) + ( (( vC.get_pos().y - vB.get_pos().y )) * (( vC.get_pos().y - vB.get_pos().y )) ) );
if (( distSquared >= this.diameterSquared ))
{
return true;
}
else
{
return false;
}
}
hxDaedalus.data.Edge adjEdge;
if (( ( ( ( throughFace.get_edge() != fromEdge ) && ( throughFace.get_edge().get_oppositeEdge() != fromEdge ) ) && ( throughFace.get_edge() != toEdge ) ) && ( throughFace.get_edge().get_oppositeEdge() != toEdge ) ))
{
adjEdge = throughFace.get_edge();
}
else
{
if (( ( ( ( throughFace.get_edge().get_nextLeftEdge() != fromEdge ) && ( throughFace.get_edge().get_nextLeftEdge().get_oppositeEdge() != fromEdge ) ) && ( throughFace.get_edge().get_nextLeftEdge() != toEdge ) ) && ( throughFace.get_edge().get_nextLeftEdge().get_oppositeEdge() != toEdge ) ))
{
adjEdge = throughFace.get_edge().get_nextLeftEdge();
}
else
{
adjEdge = throughFace.get_edge().get_prevLeftEdge();
}
}
if (adjEdge.get_isConstrained())
{
hxDaedalus.data.math.Point2D proj = new hxDaedalus.data.math.Point2D(vC.get_pos().x, vC.get_pos().y);
hxDaedalus.data.math.Geom2D.projectOrthogonaly(proj, adjEdge);
distSquared = ( ( (( proj.x - vC.get_pos().x )) * (( proj.x - vC.get_pos().x )) ) + ( (( proj.y - vC.get_pos().y )) * (( proj.y - vC.get_pos().y )) ) );
if (( distSquared >= this.diameterSquared ))
{
return true;
}
else
{
return false;
}
}
else
{
double distSquaredA = ( ( (( vC.get_pos().x - vA.get_pos().x )) * (( vC.get_pos().x - vA.get_pos().x )) ) + ( (( vC.get_pos().y - vA.get_pos().y )) * (( vC.get_pos().y - vA.get_pos().y )) ) );
double distSquaredB = ( ( (( vC.get_pos().x - vB.get_pos().x )) * (( vC.get_pos().x - vB.get_pos().x )) ) + ( (( vC.get_pos().y - vB.get_pos().y )) * (( vC.get_pos().y - vB.get_pos().y )) ) );
if (( ( distSquaredA < this.diameterSquared ) || ( distSquaredB < this.diameterSquared ) ))
{
return false;
}
else
{
haxe.root.Array<hxDaedalus.data.Face> vFaceToCheck = new haxe.root.Array<hxDaedalus.data.Face>();
haxe.root.Array<hxDaedalus.data.Edge> vFaceIsFromEdge = new haxe.root.Array<hxDaedalus.data.Edge>();
haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object> facesDone = new haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>();
vFaceIsFromEdge.push(adjEdge);
if (( adjEdge.get_leftFace() == throughFace ))
{
vFaceToCheck.push(adjEdge.get_rightFace());
facesDone.set(adjEdge.get_rightFace(), true);
}
else
{
vFaceToCheck.push(adjEdge.get_leftFace());
facesDone.set(adjEdge.get_leftFace(), true);
}
hxDaedalus.data.Face currFace;
hxDaedalus.data.Edge faceFromEdge;
hxDaedalus.data.Edge currEdgeA;
hxDaedalus.data.Face nextFaceA;
hxDaedalus.data.Edge currEdgeB;
hxDaedalus.data.Face nextFaceB;
while (( vFaceToCheck.length > 0 ))
{
currFace = ((hxDaedalus.data.Face) (vFaceToCheck.shift()) );
faceFromEdge = ((hxDaedalus.data.Edge) (vFaceIsFromEdge.shift()) );
if (( ( currFace.get_edge() == faceFromEdge ) || ( currFace.get_edge() == faceFromEdge.get_oppositeEdge() ) ))
{
currEdgeA = currFace.get_edge().get_nextLeftEdge();
currEdgeB = currFace.get_edge().get_nextLeftEdge().get_nextLeftEdge();
}
else
{
if (( ( currFace.get_edge().get_nextLeftEdge() == faceFromEdge ) || ( currFace.get_edge().get_nextLeftEdge() == faceFromEdge.get_oppositeEdge() ) ))
{
currEdgeA = currFace.get_edge();
currEdgeB = currFace.get_edge().get_nextLeftEdge().get_nextLeftEdge();
}
else
{
currEdgeA = currFace.get_edge();
currEdgeB = currFace.get_edge().get_nextLeftEdge();
}
}
if (( currEdgeA.get_leftFace() == currFace ))
{
nextFaceA = currEdgeA.get_rightFace();
}
else
{
nextFaceA = currEdgeA.get_leftFace();
}
if (( currEdgeB.get_leftFace() == currFace ))
{
nextFaceB = currEdgeB.get_rightFace();
}
else
{
nextFaceB = currEdgeB.get_leftFace();
}
if (( ( ! (haxe.lang.Runtime.toBool(facesDone.get(nextFaceA))) ) && ( hxDaedalus.data.math.Geom2D.distanceSquaredVertexToEdge(vC, currEdgeA) < this.diameterSquared ) ))
{
if (currEdgeA.get_isConstrained())
{
return false;
}
else
{
vFaceToCheck.push(nextFaceA);
vFaceIsFromEdge.push(currEdgeA);
facesDone.set(nextFaceA, true);
}
}
if (( ( ! (haxe.lang.Runtime.toBool(facesDone.get(nextFaceB))) ) && ( hxDaedalus.data.math.Geom2D.distanceSquaredVertexToEdge(vC, currEdgeB) < this.diameterSquared ) ))
{
if (currEdgeB.get_isConstrained())
{
return false;
}
else
{
vFaceToCheck.push(nextFaceB);
vFaceIsFromEdge.push(currEdgeB);
facesDone.set(nextFaceB, true);
}
}
}
return true;
}
}
}
@Override public double __hx_setField_f(java.lang.String field, double value, boolean handleProperties)
{
{
boolean __temp_executeDef1 = true;
switch (field.hashCode())
{
case -2099968614:
{
if (field.equals("diameterSquared"))
{
this.diameterSquared = value;
return value;
}
break;
}
case -938578798:
{
if (field.equals("radius"))
{
this.set_radius(value);
return value;
}
break;
}
case -233204595:
{
if (field.equals("diameter"))
{
this.diameter = value;
return value;
}
break;
}
case 1769892273:
{
if (field.equals("_radius"))
{
this._radius = value;
return value;
}
break;
}
case -677179915:
{
if (field.equals("radiusSquared"))
{
this.radiusSquared = value;
return value;
}
break;
}
}
if (__temp_executeDef1)
{
return super.__hx_setField_f(field, value, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_setField(java.lang.String field, java.lang.Object value, boolean handleProperties)
{
{
boolean __temp_executeDef1 = true;
switch (field.hashCode())
{
case 1125625021:
{
if (field.equals("curFace"))
{
this.curFace = ((hxDaedalus.data.Face) (value) );
return value;
}
break;
}
case -938578798:
{
if (field.equals("radius"))
{
this.set_radius(haxe.lang.Runtime.toDouble(value));
return value;
}
break;
}
case -869293192:
{
if (field.equals("toFace"))
{
this.toFace = ((hxDaedalus.data.Face) (value) );
return value;
}
break;
}
case 1769892273:
{
if (field.equals("_radius"))
{
this._radius = haxe.lang.Runtime.toDouble(value);
return value;
}
break;
}
case -1245086425:
{
if (field.equals("fromFace"))
{
this.fromFace = ((hxDaedalus.data.Face) (value) );
return value;
}
break;
}
case 3347949:
{
if (field.equals("mesh"))
{
this.set_mesh(((hxDaedalus.data.Mesh) (value) ));
return value;
}
break;
}
case -2099968614:
{
if (field.equals("diameterSquared"))
{
this.diameterSquared = haxe.lang.Runtime.toDouble(value);
return value;
}
break;
}
case 91082444:
{
if (field.equals("_mesh"))
{
this._mesh = ((hxDaedalus.data.Mesh) (value) );
return value;
}
break;
}
case -233204595:
{
if (field.equals("diameter"))
{
this.diameter = haxe.lang.Runtime.toDouble(value);
return value;
}
break;
}
case 616703914:
{
if (field.equals("closedFaces"))
{
this.closedFaces = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -677179915:
{
if (field.equals("radiusSquared"))
{
this.radiusSquared = haxe.lang.Runtime.toDouble(value);
return value;
}
break;
}
case 63996880:
{
if (field.equals("sortedOpenedFaces"))
{
this.sortedOpenedFaces = ((haxe.root.Array<hxDaedalus.data.Face>) (value) );
return value;
}
break;
}
case 1181683957:
{
if (field.equals("iterEdge"))
{
this.iterEdge = ((hxDaedalus.iterators.FromFaceToInnerEdges) (value) );
return value;
}
break;
}
case 512628429:
{
if (field.equals("openedFaces"))
{
this.openedFaces = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -1925032183:
{
if (field.equals("predecessor"))
{
this.predecessor = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Face>) (value) );
return value;
}
break;
}
case -1989818108:
{
if (field.equals("entryEdges"))
{
this.entryEdges = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, hxDaedalus.data.Edge>) (value) );
return value;
}
break;
}
case -907766794:
{
if (field.equals("scoreH"))
{
this.scoreH = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -1298266586:
{
if (field.equals("entryX"))
{
this.entryX = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -907766795:
{
if (field.equals("scoreG"))
{
this.scoreG = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -1298266585:
{
if (field.equals("entryY"))
{
this.entryY = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
case -907766796:
{
if (field.equals("scoreF"))
{
this.scoreF = ((haxe.ds.ObjectMap<hxDaedalus.data.Face, java.lang.Object>) (value) );
return value;
}
break;
}
}
if (__temp_executeDef1)
{
return super.__hx_setField(field, value, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_getField(java.lang.String field, boolean throwErrors, boolean isCheck, boolean handleProperties)
{
{
boolean __temp_executeDef1 = true;
switch (field.hashCode())
{
case 1566142678:
{
if (field.equals("isWalkableByRadius"))
{
return new haxe.lang.Closure(this, "isWalkableByRadius");
}
break;
}
case -938578798:
{
if (field.equals("radius"))
{
return this.get_radius();
}
break;
}
case 96567954:
{
if (field.equals("sortingFaces"))
{
return new haxe.lang.Closure(this, "sortingFaces");
}
break;
}
case 1769892273:
{
if (field.equals("_radius"))
{
return this._radius;
}
break;
}
case -679327362:
{
if (field.equals("findPath"))
{
return new haxe.lang.Closure(this, "findPath");
}
break;
}
case 91082444:
{
if (field.equals("_mesh"))
{
return this._mesh;
}
break;
}
case 1415348138:
{
if (field.equals("set_mesh"))
{
return new haxe.lang.Closure(this, "set_mesh");
}
break;
}
case 616703914:
{
if (field.equals("closedFaces"))
{
return this.closedFaces;
}
break;
}
case -1216062705:
{
if (field.equals("set_radius"))
{
return new haxe.lang.Closure(this, "set_radius");
}
break;
}
case 63996880:
{
if (field.equals("sortedOpenedFaces"))
{
return this.sortedOpenedFaces;
}
break;
}
case 1142099355:
{
if (field.equals("get_radius"))
{
return new haxe.lang.Closure(this, "get_radius");
}
break;
}
case 512628429:
{
if (field.equals("openedFaces"))
{
return this.openedFaces;
}
break;
}
case 1671767583:
{
if (field.equals("dispose"))
{
return new haxe.lang.Closure(this, "dispose");
}
break;
}
case -1989818108:
{
if (field.equals("entryEdges"))
{
return this.entryEdges;
}
break;
}
case 1125625021:
{
if (field.equals("curFace"))
{
return this.curFace;
}
break;
}
case -1298266586:
{
if (field.equals("entryX"))
{
return this.entryX;
}
break;
}
case -869293192:
{
if (field.equals("toFace"))
{
return this.toFace;
}
break;
}
case -1298266585:
{
if (field.equals("entryY"))
{
return this.entryY;
}
break;
}
case -1245086425:
{
if (field.equals("fromFace"))
{
return this.fromFace;
}
break;
}
case -907766796:
{
if (field.equals("scoreF"))
{
return this.scoreF;
}
break;
}
case -2099968614:
{
if (field.equals("diameterSquared"))
{
return this.diameterSquared;
}
break;
}
case -907766795:
{
if (field.equals("scoreG"))
{
return this.scoreG;
}
break;
}
case -233204595:
{
if (field.equals("diameter"))
{
return this.diameter;
}
break;
}
case -907766794:
{
if (field.equals("scoreH"))
{
return this.scoreH;
}
break;
}
case -677179915:
{
if (field.equals("radiusSquared"))
{
return this.radiusSquared;
}
break;
}
case -1925032183:
{
if (field.equals("predecessor"))
{
return this.predecessor;
}
break;
}
case 1181683957:
{
if (field.equals("iterEdge"))
{
return this.iterEdge;
}
break;
}
}
if (__temp_executeDef1)
{
return super.__hx_getField(field, throwErrors, isCheck, handleProperties);
}
else
{
throw null;
}
}
}
@Override public double __hx_getField_f(java.lang.String field, boolean throwErrors, boolean handleProperties)
{
{
boolean __temp_executeDef1 = true;
switch (field.hashCode())
{
case -2099968614:
{
if (field.equals("diameterSquared"))
{
return this.diameterSquared;
}
break;
}
case -938578798:
{
if (field.equals("radius"))
{
return this.get_radius();
}
break;
}
case -233204595:
{
if (field.equals("diameter"))
{
return this.diameter;
}
break;
}
case 1769892273:
{
if (field.equals("_radius"))
{
return this._radius;
}
break;
}
case -677179915:
{
if (field.equals("radiusSquared"))
{
return this.radiusSquared;
}
break;
}
}
if (__temp_executeDef1)
{
return super.__hx_getField_f(field, throwErrors, handleProperties);
}
else
{
throw null;
}
}
}
@Override public java.lang.Object __hx_invokeField(java.lang.String field, haxe.root.Array dynargs)
{
{
boolean __temp_executeDef1 = true;
switch (field.hashCode())
{
case 1566142678:
{
if (field.equals("isWalkableByRadius"))
{
return this.isWalkableByRadius(((hxDaedalus.data.Edge) (dynargs.__get(0)) ), ((hxDaedalus.data.Face) (dynargs.__get(1)) ), ((hxDaedalus.data.Edge) (dynargs.__get(2)) ));
}
break;
}
case 1671767583:
{
if (field.equals("dispose"))
{
__temp_executeDef1 = false;
this.dispose();
}
break;
}
case 96567954:
{
if (field.equals("sortingFaces"))
{
return this.sortingFaces(((hxDaedalus.data.Face) (dynargs.__get(0)) ), ((hxDaedalus.data.Face) (dynargs.__get(1)) ));
}
break;
}
case 1142099355:
{
if (field.equals("get_radius"))
{
return this.get_radius();
}
break;
}
case -679327362:
{
if (field.equals("findPath"))
{
__temp_executeDef1 = false;
this.findPath(haxe.lang.Runtime.toDouble(dynargs.__get(0)), haxe.lang.Runtime.toDouble(dynargs.__get(1)), haxe.lang.Runtime.toDouble(dynargs.__get(2)), haxe.lang.Runtime.toDouble(dynargs.__get(3)), ((haxe.root.Array<hxDaedalus.data.Face>) (dynargs.__get(4)) ), ((haxe.root.Array<hxDaedalus.data.Edge>) (dynargs.__get(5)) ));
}
break;
}
case -1216062705:
{
if (field.equals("set_radius"))
{
return this.set_radius(haxe.lang.Runtime.toDouble(dynargs.__get(0)));
}
break;
}
case 1415348138:
{
if (field.equals("set_mesh"))
{
return this.set_mesh(((hxDaedalus.data.Mesh) (dynargs.__get(0)) ));
}
break;
}
}
if (__temp_executeDef1)
{
return super.__hx_invokeField(field, dynargs);
}
}
return null;
}
@Override public void __hx_getFields(haxe.root.Array<java.lang.String> baseArr)
{
baseArr.push("curFace");
baseArr.push("toFace");
baseArr.push("fromFace");
baseArr.push("diameterSquared");
baseArr.push("diameter");
baseArr.push("radiusSquared");
baseArr.push("iterEdge");
baseArr.push("predecessor");
baseArr.push("scoreH");
baseArr.push("scoreG");
baseArr.push("scoreF");
baseArr.push("entryY");
baseArr.push("entryX");
baseArr.push("entryEdges");
baseArr.push("openedFaces");
baseArr.push("sortedOpenedFaces");
baseArr.push("closedFaces");
baseArr.push("_mesh");
baseArr.push("mesh");
baseArr.push("_radius");
baseArr.push("radius");
super.__hx_getFields(baseArr);
}
}
| 20.85048
| 330
| 0.57102
|
14ef8bec431ac2b3925ad165df9bedaf41c75f65
| 762
|
/*
* Copyright (c) 2021 tecc
* This code is licenced under the MIT licence.
*/
package me.tecc.pluralcraft.bp.util;
import com.comphenix.protocol.ProtocolManager;
import me.tecc.pluralcraft.bp.PluralcraftBP;
import java.util.logging.Logger;
public interface IBP {
default PluralcraftBP pbp() {
return PluralcraftBP.get();
}
static PluralcraftBP getPBP() {
return PluralcraftBP.get();
}
default ProtocolManager protocolManager() {
return pbp().protocolManager();
}
static ProtocolManager getProtocolManager() {
return getPBP().protocolManager();
}
default Logger logger() {
return pbp().getLogger();
}
static Logger getLogger() {
return getPBP().logger();
}
}
| 23.090909
| 49
| 0.660105
|
5b009cdb0529214a9524cecf6f79fecaf4d3dae4
| 692
|
package com.google.android.gms.internal.ads;
import android.os.IInterface;
import android.os.RemoteException;
import com.google.android.gms.dynamic.IObjectWrapper;
/* compiled from: com.google.android.gms:play-services-ads-lite@@19.4.0 */
public interface zzgx extends IInterface {
void zza(IObjectWrapper iObjectWrapper, String str) throws RemoteException;
void zza(IObjectWrapper iObjectWrapper, String str, String str2) throws RemoteException;
void zza(int[] iArr) throws RemoteException;
void zzc(byte[] bArr) throws RemoteException;
void zzdx() throws RemoteException;
void zzs(int i) throws RemoteException;
void zzt(int i) throws RemoteException;
}
| 30.086957
| 92
| 0.768786
|
f40cf5643fbedc0d54b3a033303c7aec6351b6f2
| 3,356
|
package com.namelessmc.spigot;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.namelessmc.java_api.NamelessException;
import com.namelessmc.java_api.NamelessUser;
import com.namelessmc.java_api.UserFilter;
public class WhitelistRegistered implements Runnable {
public WhitelistRegistered() {
// Return if this feature is disabled
if (!Config.MAIN.getConfig().getBoolean("auto-whitelist-registered.enabled", false)) {
return;
}
this.run();
}
@Override
public void run() {
final boolean verified = Config.MAIN.getConfig().getBoolean("auto-whitelist-registered.verified");
final boolean log = Config.MAIN.getConfig().getBoolean("auto-whitelist-registered.log");
final Logger logger = NamelessPlugin.getInstance().getLogger();
Bukkit.getScheduler().runTaskAsynchronously(NamelessPlugin.getInstance(), () -> {
UserFilter<?>[] filters;
if (verified) {
filters = new UserFilter<?>[] {UserFilter.VERIFIED, UserFilter.UNBANNED};
} else {
filters = new UserFilter<?>[] {UserFilter.UNBANNED};
}
List<NamelessUser> users;
try {
users = NamelessPlugin.getApi().getRegisteredUsers(filters);
} catch (final NamelessException e) {
logger.warning(
"An error occured while getting a list of registered users from the website for the auto-whitelist-registered feature.");
e.printStackTrace();
return;
}
final Set<UUID> uuids = users.stream()
.map(user -> {
try {
return user.getUniqueId();
} catch (final NamelessException e) {
return null;
}
})
.filter(opt -> opt != null && opt.isPresent())
.map(opt -> opt.get())
.collect(Collectors.toSet());
// Use Set for O(1) contains()
final Set<String> excludes = new HashSet<>();
excludes.addAll(Config.MAIN.getConfig().getStringList("auto-whitelist-registered.log"));
Bukkit.getScheduler().runTask(NamelessPlugin.getInstance(), () -> {
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) {
final UUID uuid = player.getUniqueId();
final String name = player.getName() == null ? uuid.toString() : player.getName();
if (excludes.contains(uuid.toString())) {
continue;
}
if (uuids.contains(uuid) && !player.isWhitelisted()) {
if (log) {
logger.info("Added " + name + " to the whitelist.");
}
player.setWhitelisted(true);
} else if (!uuids.contains(uuid) && player.isWhitelisted()) {
if (log) {
logger.info("Removed " + name + " from the whitelist.");
}
player.setWhitelisted(false);
}
}
// All remaining UUIDs in the set are from players that are not on the whitelist yet
for (final UUID uuid : uuids) {
final OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
player.setWhitelisted(true);
if (log) {
logger.info("Added " + player.getName() + " to the whitelist.");
}
}
// Run again after wait time
final long pollInterval = Config.MAIN.getConfig().getInt("auto-whitelist-registered.poll-interval") * 20;
Bukkit.getScheduler().runTaskLater(NamelessPlugin.getInstance(), this, pollInterval);
});
});
}
}
| 31.660377
| 127
| 0.671037
|
5ec210f7c10a4e072ffd8374de972823b6d2a354
| 349
|
package musicTrack;
public class MusicTrack {
String artist;
String title;
public MusicTrack (String artist, String title) {
this.artist = artist;
this.title = title;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String toString() {
return title +" | "+artist;
}
}
| 13.423077
| 50
| 0.661891
|
d84188db1939521f916c5d08499512cf522c2919
| 1,674
|
package com.hongjolim.mfmanager.tools;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;
import java.util.Locale;
public class BigDecimalCalculator {
public static double roundValue(double value, String countryCode){
Locale locale = null;
switch(countryCode){
//country is set Canada
case "Canada":
locale = Locale.CANADA;
break;
case "US":
locale = Locale.US;
break;
case "China":
locale = Locale.CHINA;
break;
case "France":
locale = Locale.FRANCE;
break;
case "Germany":
locale = Locale.GERMANY;
break;
case "Japan":
locale = Locale.JAPAN;
break;
case "Korea":
locale = Locale.KOREA;
break;
default:
locale = Locale.CANADA;
}
Currency currency = Currency.getInstance(locale);
return Double.parseDouble(BigDecimal.valueOf(value).setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_UP).toString());
}
public static BigDecimal subtract(String value1, String value2){
BigDecimal big1 = new BigDecimal(value1);
BigDecimal big2 = new BigDecimal(value2);
return big1.subtract(big2);
}
public static BigDecimal add(String value1, String value2){
BigDecimal big1 = new BigDecimal(value1);
BigDecimal big2 = new BigDecimal(value2);
return big1.add(big2);
}
}
| 27
| 140
| 0.557945
|
022204b5e7608ad6ef0d45012092316fd8cb6269
| 1,778
|
/*
* SUDA2: An implementation of the SUDA2 algorithm for Java
* Copyright 2017 Fabian Prasser
*
* 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 de.linearbits.test;
import java.util.Arrays;
import de.linearbits.suda2.SUDA2StatisticsScores;
/**
* Test for DIS scores
*
* @author Fabian Prasser
* @author Raffael Bild
*/
public class Test10 extends AbstractTest {
/** Scores for testing */
private static final double[] SCORES = { 7d, 0d, 0d, 1.75d, 0d, 3.25d, 0d, 1.75d, 2.75d, 0d, 0d };
/** Expected results for testing */
private static final double[] DIS = { 0.028038903d, 0d, 0d,
0.005435918d, 0d, 0.011357785d,
0d, 0.005435918d, 0.009313862d, 0d, 0d};
/**
* Main method for testing
* @param args
*/
public static void main(String[] args) {
long numUniqueRecords = 5; // 5
long numDuplicateRecords = 6; // 6
int columns = 4;
double disFraction = 0.01d; // 0.01d;
System.out.println(Arrays.toString(SUDA2StatisticsScores.getScoreDIS(SCORES, numUniqueRecords, numDuplicateRecords, columns, disFraction)));
System.out.println(Arrays.toString(DIS));
}
}
| 33.54717
| 148
| 0.649606
|
7915709f6d5847f4702a7bc1fd9edf8fb84d9f28
| 1,086
|
package com.netsocks.associatefan.domain.customer;
import java.time.LocalDate;
public class UpdateCommand {
private final String correlationId;
private final String id;
private final String fullName;
private final String email;
private final LocalDate birthday;
private final String favoriteTeam;
public UpdateCommand(
final String correlationId, final String id, final String fullName,
final String email, final LocalDate birthday, final String favoriteTeam) {
this.correlationId = correlationId;
this.id = id;
this.fullName = fullName;
this.email = email;
this.birthday = birthday;
this.favoriteTeam = favoriteTeam;
}
String getCorrelationId() {
return correlationId;
}
String getId() {
return id;
}
String getFullName() {
return fullName;
}
String getEmail() {
return email;
}
LocalDate getBirthday() {
return birthday;
}
String getFavoriteTeam() {
return favoriteTeam;
}
}
| 22.625
| 86
| 0.639963
|
62d026590fbc31305ee47f8809de4409e00a7781
| 760
|
package com.expava.gpp.springcloud.repository;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.expava.gpp.springcloud.model.Product;
@Component
public class DatabaseInit {
@Value("${server.port}")
private String server_port;
@Autowired
private ProductRepository productRepository;
@PostConstruct
public void fillDatabase() {
productRepository.save(new Product("ProductA", "DescriptionA "+server_port));
productRepository.save(new Product("ProductB", "DescriptionB "+server_port));
productRepository.save(new Product("ProductC", "DescriptionC "+server_port));
}
}
| 28.148148
| 79
| 0.797368
|
cc7f41b0aa962b95d36a43def7bdd870bc5db7fe
| 8,235
|
package com.iigo.library;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
/**
* @author SamLeung
* @Emial 729717222@qq.com
* @date 2018/7/3 0003 15:44
*/
public class ChargingView extends View {
private int currentProgress; //当前进度
private int bgColor; //背景颜色
private int chargingColor; //充电中颜色
private int textColor;
private float textSize;
private Paint chargingPaint; //充电中效果画笔
private Paint backgroundPaint; //充电背景画笔
private Paint textPaint; //百分比画笔
private RectF chargingRectF = new RectF(); //充电矩形
private RectF headRectF = new RectF(); //充电头头矩形
private Path wavePath;//波浪轨迹
private Path clipPath; //要裁剪的轨迹
private float waveHeight; //波形高度,即峰值
private ValueAnimator waveAnimator; //用于执行波浪移动动画
private float waveAnimatorRatio = 0; //该值为三个波形的顺序三个波形分别为(-2 * width -> width -> 2 * width) width为chargingRectF的宽
private Rect textBound = new Rect();
public ChargingView(Context context) {
super(context);
init();
}
public ChargingView(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttr(attrs);
init();
}
public ChargingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
parseAttr(attrs);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ChargingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
parseAttr(attrs);
init();
}
private void parseAttr(AttributeSet attrs){
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ChargingView);
bgColor = a.getColor(R.styleable.ChargingView_bg_color, Color.GRAY);
chargingColor = a.getColor(R.styleable.ChargingView_chargingColor, Color.GREEN);
currentProgress = a.getInteger(R.styleable.ChargingView_progress, 0);
textSize = a.getDimension(R.styleable.ChargingView_progressTextSize, 20);
textColor = a.getColor(R.styleable.ChargingView_progressTextColor, Color.WHITE);
if (currentProgress > 100){
currentProgress = 100;
}
a.recycle();
}
private void init(){
chargingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
chargingPaint.setColor(chargingColor);
chargingPaint.setStyle(Paint.Style.FILL);
backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
backgroundPaint.setStyle(Paint.Style.FILL);
backgroundPaint.setColor(bgColor);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
wavePath = new Path();
clipPath = new Path();
waveAnimator = ValueAnimator.ofFloat(-2, 2);
waveAnimator.setDuration(4000);
waveAnimator.setRepeatCount(ValueAnimator.INFINITE);
waveAnimator.setInterpolator(new LinearInterpolator());
waveAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
waveAnimatorRatio = (float) animation.getAnimatedValue();
invalidate();
}
});
waveAnimator.start();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initRects(w, h);
}
/**
* 初始化充电矩形和头矩形
* */
private void initRects(int width, int height){
float headWidth = width / 3f;
float headHeight = height / 15f;
float chargingWidth = width;
float chargingHeight = height - headHeight;
headRectF.set((chargingWidth - headWidth) / 2, 0, chargingWidth - (chargingWidth - headWidth) / 2, headHeight);
chargingRectF.set(0, 0, chargingWidth, chargingHeight);
clipPath.moveTo(0, headHeight);
clipPath.lineTo(width / 2 - headWidth / 2, headHeight);
clipPath.lineTo(width / 2 - headWidth / 2, 0);
clipPath.lineTo(width / 2 + headWidth / 2, 0);
clipPath.lineTo(width / 2 + headWidth / 2, headHeight);
clipPath.lineTo(width, headHeight);
clipPath.lineTo(width, height);
clipPath.lineTo(0, height);
clipPath.close();
waveHeight = headHeight * 2; //这里设置波形峰值即为充电头的高
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//裁剪画笔
canvas.clipPath(clipPath);
//先画充电头矩形
canvas.drawRect(headRectF, backgroundPaint);
//画充电主体部分
canvas.save();
canvas.translate(0, headRectF.height());
canvas.drawRect(chargingRectF, backgroundPaint);
wavePath.reset();
float centerX = chargingRectF.width() / 2; //获取中心点X坐标
float centerY = chargingRectF.height() / 2; //获取中心点Y坐标
//根据当前progress得到的水位线高
float progressHeight = chargingRectF.height() - currentProgress / 100f * chargingRectF.height(); //根据百分比获取当前的水位线
//先移动至波形起点
wavePath.moveTo(-2 * chargingRectF.width() + waveAnimatorRatio * chargingRectF.width(), progressHeight);
//画波形
for (int i = (int) (-2 * chargingRectF.width()); i < 2 * chargingRectF.width(); i += chargingRectF.width()) {
wavePath.rQuadTo(chargingRectF.width() / 2, -waveHeight, chargingRectF.width(),0);
wavePath.rQuadTo(chargingRectF.width() / 2, waveHeight, chargingRectF.width(),0);
}
wavePath.lineTo(chargingRectF.width(), chargingRectF.height());
wavePath.lineTo(0, chargingRectF.height());
wavePath.close();
canvas.drawPath(wavePath, chargingPaint);
drawProgress(canvas, centerX, centerY);
canvas.restore();
}
/**
* 绘制进度
*
* @param canvas 画布
* @param centerX 中心点X
* @param centerY 中心点Y
* */
private void drawProgress(Canvas canvas, float centerX, float centerY){
//绘制百分比
String text = currentProgress + "%";
textPaint.getTextBounds(text, 0, text.length(), textBound);
canvas.drawText(text, centerX - textBound.width() / 2, centerY + textBound.height() / 2, textPaint);
}
/**
* 设置当前进度
*
* 0 - 100
* */
public void setProgress(int progress){
this.currentProgress = progress;
if (currentProgress > 100){
currentProgress = 100;
}
invalidate();
}
/**
* 获取当前进度
* */
public int getProgress() {
return currentProgress;
}
/**
* 设置充电矩形背景颜色
* */
public void setBgColor(int bgColor) {
this.bgColor = bgColor;
backgroundPaint.setColor(bgColor);
invalidate();
}
/**
* 获取充电矩形背景颜色
* */
public int getBgColor() {
return bgColor;
}
/**
* 获取进度text大小
* */
public float getTextSize() {
return textSize;
}
/**
* 设置进度text大小
* */
public void setTextSize(float textSize) {
this.textSize = textSize;
textPaint.setTextSize(textSize);
invalidate();
}
/**
* 获取进度text颜色
* */
public int getTextColor() {
return textColor;
}
/**
* 设置进度text颜色
* */
public void setTextColor(int textColor) {
this.textColor = textColor;
textPaint.setColor(textColor);
invalidate();
}
/**
* 获取充电矩形已充颜色
* */
public int getChargingColor() {
return chargingColor;
}
/**
* 设置充电矩形已充颜色
* */
public void setChargingColor(int chargingColor) {
this.chargingColor = chargingColor;
chargingPaint.setColor(chargingColor);
invalidate();
}
}
| 27.915254
| 120
| 0.629508
|
bf45888983ae2c672bf3b29190ec8765d2a243b3
| 51
|
/**
*
*/package org.nutz.mvc.adaptor.convertor;
| 12.75
| 42
| 0.647059
|
566b5c05e78d441124f4c89b5aba2660b3d7e5ba
| 18,244
|
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.xml.internal.stream.dtd;
import com.sun.xml.internal.stream.dtd.nonvalidating.DTDGrammar;
import com.sun.xml.internal.stream.dtd.nonvalidating.XMLAttributeDecl;
import com.sun.xml.internal.stream.dtd.nonvalidating.XMLElementDecl;
import com.sun.xml.internal.stream.dtd.nonvalidating.XMLSimpleType;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
import com.sun.org.apache.xerces.internal.util.XMLChar;
import com.sun.org.apache.xerces.internal.util.XMLSymbols;
import com.sun.org.apache.xerces.internal.xni.Augmentations;
import com.sun.org.apache.xerces.internal.xni.QName;
import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
import com.sun.org.apache.xerces.internal.xni.XMLString;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
import javax.xml.XMLConstants;
/*
* @author Eric Ye, IBM
* @author Andy Clark, IBM
* @author Jeffrey Rodriguez IBM
* @author Neil Graham, IBM
* @author Sunitha Reddy, Sun Microsystems
*/
public class DTDGrammarUtil {
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
protected static final String NAMESPACES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
/** Compile to true to debug attributes. */
private static final boolean DEBUG_ATTRIBUTES = false;
/** Compile to true to debug element children. */
private static final boolean DEBUG_ELEMENT_CHILDREN = false;
protected DTDGrammar fDTDGrammar = null;
/** Namespaces. */
protected boolean fNamespaces;
/** Symbol table. */
protected SymbolTable fSymbolTable = null;
/** Current element index. */
private int fCurrentElementIndex = -1;
/** Current content spec type. */
private int fCurrentContentSpecType = -1;
/** Content spec type stack. */
private boolean[] fElementContentState = new boolean[8];
/** Element depth. */
private int fElementDepth = -1;
/** True if inside of element content. */
private boolean fInElementContent = false;
/** Temporary atribute declaration. */
private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
/** Temporary qualified name. */
private QName fTempQName = new QName();
/** Temporary string buffers. */
private StringBuilder fBuffer = new StringBuilder();
private NamespaceContext fNamespaceContext = null;
/** Default constructor. */
public DTDGrammarUtil(SymbolTable symbolTable) {
fSymbolTable = symbolTable;
}
public DTDGrammarUtil(DTDGrammar grammar, SymbolTable symbolTable) {
fDTDGrammar = grammar;
fSymbolTable = symbolTable;
}
public DTDGrammarUtil(DTDGrammar grammar, SymbolTable symbolTable,
NamespaceContext namespaceContext) {
fDTDGrammar = grammar;
fSymbolTable = symbolTable;
fNamespaceContext = namespaceContext;
}
/*
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on finitialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
fDTDGrammar = null;
fInElementContent = false;
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fNamespaces = componentManager.getFeature(NAMESPACES, true);
fSymbolTable = (SymbolTable) componentManager.getProperty(
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY);
fElementDepth = -1;
}
/**
* The start of an element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes) throws XNIException {
handleStartElement(element, attributes);
}
/**
* The end of an element.
*
* @param element The name of the element.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element) throws XNIException {
handleEndElement(element);
}
/**
* The start of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA(Augmentations augs) throws XNIException {
}
/**
* The end of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA(Augmentations augs) throws XNIException {
}
/** Add default attributes and validate. */
public void addDTDDefaultAttrs(QName elementName, XMLAttributes attributes)
throws XNIException {
int elementIndex;
elementIndex = fDTDGrammar.getElementDeclIndex(elementName);
// is there anything to do?
if (elementIndex == -1 || fDTDGrammar == null) {
return;
}
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) add default attrs (FIXED and NOT_FIXED)
//
int attlistIndex = fDTDGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attlistIndex != -1) {
fDTDGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
if (DEBUG_ATTRIBUTES) {
if (fTempAttDecl != null) {
XMLElementDecl elementDecl = new XMLElementDecl();
fDTDGrammar.getElementDecl(elementIndex, elementDecl);
System.out.println("element: " + (elementDecl.name.localpart));
System.out.println("attlistIndex " + attlistIndex + "\n" +
"attName : '" + (fTempAttDecl.name.localpart) + "'\n"
+ "attType : " + fTempAttDecl.simpleType.type + "\n"
+ "attDefaultType : " + fTempAttDecl.simpleType.defaultType + "\n"
+ "attDefaultValue : '" + fTempAttDecl.simpleType.defaultValue + "'\n"
+ attributes.getLength() + "\n"
);
}
}
String attPrefix = fTempAttDecl.name.prefix;
String attLocalpart = fTempAttDecl.name.localpart;
String attRawName = fTempAttDecl.name.rawname;
String attType = getAttributeTypeName(fTempAttDecl);
int attDefaultType = fTempAttDecl.simpleType.defaultType;
String attValue = null;
if (fTempAttDecl.simpleType.defaultValue != null) {
attValue = fTempAttDecl.simpleType.defaultValue;
}
boolean specified = false;
boolean required = attDefaultType == XMLSimpleType.DEFAULT_TYPE_REQUIRED;
boolean cdata = attType == XMLSymbols.fCDATASymbol;
if (!cdata || required || attValue != null) {
//check whether attribute is a namespace declaration
if (fNamespaceContext != null && attRawName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
String prefix = "";
int pos = attRawName.indexOf(':');
if (pos != -1) {
prefix = attRawName.substring(0, pos);
} else {
prefix = attRawName;
}
prefix = fSymbolTable.addSymbol(prefix);
if (!((com.sun.org.apache.xerces.internal.util.
NamespaceSupport) fNamespaceContext).
containsPrefixInCurrentContext(prefix)) {
fNamespaceContext.declarePrefix(prefix, attValue);
}
specified = true;
} else {
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount; i++) {
if (attributes.getQName(i) == attRawName) {
specified = true;
break;
}
}
}
}
if (!specified) {
if (attValue != null) {
if (fNamespaces) {
int index = attRawName.indexOf(':');
if (index != -1) {
attPrefix = attRawName.substring(0, index);
attPrefix = fSymbolTable.addSymbol(attPrefix);
attLocalpart = attRawName.substring(index + 1);
attLocalpart = fSymbolTable.addSymbol(attLocalpart);
}
}
fTempQName.setValues(attPrefix, attLocalpart, attRawName,
fTempAttDecl.name.uri);
int newAttr = attributes.addAttribute(fTempQName, attType,
attValue);
}
}
attlistIndex = fDTDGrammar.getNextAttributeDeclIndex(attlistIndex);
}
// now iterate through the expanded attributes for
// 1. if every attribute seen is declared in the DTD
// 2. check if the VC: default_fixed holds
// 3. validate every attribute.
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount; i++) {
String attrRawName = attributes.getQName(i);
boolean declared = false;
int position =
fDTDGrammar.getFirstAttributeDeclIndex(elementIndex);
while (position != -1) {
fDTDGrammar.getAttributeDecl(position, fTempAttDecl);
if (fTempAttDecl.name.rawname == attrRawName) {
// found the match att decl,
declared = true;
break;
}
position = fDTDGrammar.getNextAttributeDeclIndex(position);
}
if (!declared) {
continue;
}
String type = getAttributeTypeName(fTempAttDecl);
attributes.setType(i, type);
boolean changedByNormalization = false;
if (attributes.isSpecified(i) && type != XMLSymbols.fCDATASymbol) {
changedByNormalization = normalizeAttrValue(attributes, i);
}
} // for all attributes
} // addDTDDefaultAttrsAndValidate(int,XMLAttrList)
/**
* Normalize the attribute value of a non CDATA attributes collapsing
* sequences of space characters (x20)
*
* @param attributes The list of attributes
* @param index The index of the attribute to normalize
*/
private boolean normalizeAttrValue(XMLAttributes attributes, int index) {
// vars
boolean leadingSpace = true;
boolean spaceStart = false;
boolean readingNonSpace = false;
int count = 0;
int eaten = 0;
String attrValue = attributes.getValue(index);
char[] attValue = new char[attrValue.length()];
fBuffer.setLength(0);
attrValue.getChars(0, attrValue.length(), attValue, 0);
for (int i = 0; i < attValue.length; i++) {
if (attValue[i] == ' ') {
// now the tricky part
if (readingNonSpace) {
spaceStart = true;
readingNonSpace = false;
}
if (spaceStart && !leadingSpace) {
spaceStart = false;
fBuffer.append(attValue[i]);
count++;
} else {
if (leadingSpace || !spaceStart) {
eaten++;
}
}
} else {
readingNonSpace = true;
spaceStart = false;
leadingSpace = false;
fBuffer.append(attValue[i]);
count++;
}
}
// check if the last appended character is a space.
if (count > 0 && fBuffer.charAt(count - 1) == ' ') {
fBuffer.setLength(count - 1);
}
String newValue = fBuffer.toString();
attributes.setValue(index, newValue);
return !attrValue.equals(newValue);
}
/** convert attribute type from ints to strings */
private String getAttributeTypeName(XMLAttributeDecl attrDecl) {
switch (attrDecl.simpleType.type) {
case XMLSimpleType.TYPE_ENTITY: {
return attrDecl.simpleType.list ? XMLSymbols.fENTITIESSymbol :
XMLSymbols.fENTITYSymbol;
}
case XMLSimpleType.TYPE_ENUMERATION: {
StringBuilder buffer = new StringBuilder();
buffer.append('(');
for (int i = 0; i < attrDecl.simpleType.enumeration.length; i++) {
if (i > 0) {
buffer.append("|");
}
buffer.append(attrDecl.simpleType.enumeration[i]);
}
buffer.append(')');
return fSymbolTable.addSymbol(buffer.toString());
}
case XMLSimpleType.TYPE_ID: {
return XMLSymbols.fIDSymbol;
}
case XMLSimpleType.TYPE_IDREF: {
return attrDecl.simpleType.list ? XMLSymbols.fIDREFSSymbol :
XMLSymbols.fIDREFSymbol;
}
case XMLSimpleType.TYPE_NMTOKEN: {
return attrDecl.simpleType.list ? XMLSymbols.fNMTOKENSSymbol :
XMLSymbols.fNMTOKENSymbol;
}
case XMLSimpleType.TYPE_NOTATION: {
return XMLSymbols.fNOTATIONSymbol;
}
}
return XMLSymbols.fCDATASymbol;
}
/** ensure element stack capacity */
private void ensureStackCapacity(int newElementDepth) {
if (newElementDepth == fElementContentState.length) {
boolean[] newStack = new boolean[newElementDepth * 2];
System.arraycopy(this.fElementContentState, 0, newStack, 0,
newElementDepth);
fElementContentState = newStack;
}
}
/** Handle element
* @return true if validator is removed from the pipeline
*/
protected void handleStartElement(QName element, XMLAttributes attributes) throws XNIException {
if (fDTDGrammar == null) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
return;
} else {
fCurrentElementIndex = fDTDGrammar.getElementDeclIndex(element);
fCurrentContentSpecType = fDTDGrammar.getContentSpecType(
fCurrentElementIndex);
//handleDTDDefaultAttrs(element,attributes);
addDTDDefaultAttrs(element, attributes);
}
fInElementContent = fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN;
fElementDepth++;
ensureStackCapacity(fElementDepth);
fElementContentState[fElementDepth] = fInElementContent;
}
/** Handle end element. */
protected void handleEndElement(QName element) throws XNIException {
if (fDTDGrammar == null) return;
fElementDepth--;
if (fElementDepth < -1) {
throw new RuntimeException("FWK008 Element stack underflow");
}
if (fElementDepth < 0) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
return;
}
fInElementContent = fElementContentState[fElementDepth];
}
public boolean isInElementContent() {
return fInElementContent;
}
public boolean isIgnorableWhiteSpace(XMLString text) {
if (isInElementContent()) {
for (int i = text.offset; i < text.offset + text.length; i++) {
if (!XMLChar.isSpace(text.ch[i])) {
return false;
}
}
return true;
}
return false;
}
}
| 36.856566
| 103
| 0.593455
|
a82736a65f19842068b0fb1f1c012147935307ba
| 3,719
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hitune.analysis.mapreduce;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Progressable;
/**
* Define CSF file output format. Each line of the file represents one record, and field contents are connected by COMMA mark.
*
*/
public class CSVFileOutputFormat<K, V> extends TextOutputFormat<K, V>{
static final String SEPEARATOR_COMMA =",";
static final String TEXT_SEPEARATOR_COMMA=";";
static class CSVFileWriter<K, V> implements RecordWriter<K, V>{
RecordWriter newWriter = null;
public CSVFileWriter(RecordWriter writer){
newWriter = writer;
}
private Text array2Text(ArrayWritable array){
String [] contents = array.toStrings();
StringBuilder sb = new StringBuilder();
for (String content : contents){
sb.append(content.replaceAll(SEPEARATOR_COMMA, TEXT_SEPEARATOR_COMMA)).append(SEPEARATOR_COMMA);
}
return new Text(sb.toString().substring(0,sb.length()-1));
}
@Override
public void close(Reporter reporter) throws IOException {
// TODO Auto-generated method stub
newWriter.close(reporter);
}
@Override
public void write(Object key, Object value) throws IOException {
// TODO Auto-generated method stub
if(value instanceof ArrayWritable){
newWriter.write(key,array2Text((ArrayWritable) value));
}
else {
newWriter.write(key,value);
}
}
}
/**
*
*/
public CSVFileOutputFormat() {
// TODO Auto-generated constructor stub
}
public RecordWriter<K, V> getRecordWriter(FileSystem fs,
JobConf job,
String name,
Progressable progress)
throws IOException {
job.set("mapred.textoutputformat.separator",SEPEARATOR_COMMA);
String filename = job.get(AnalysisProcessorConfiguration.outputfilename);
if(filename ==null || filename.equals("")){
filename = name;
}else{
filename += "-" + name;
//FileOutputFormat.setWorkOutputPath(job,new Path(job.get("mapred.output.dir")+"/" + filename));
}
return new CSVFileWriter(super.getRecordWriter(fs, job, filename, progress));
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| 33.809091
| 127
| 0.638613
|
f19e62ecc990cd7601bda926387f1490dd6499c8
| 5,341
|
package com.i906.mpt.settings.prayer;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.i906.mpt.R;
import com.i906.mpt.common.BaseDialogFragment;
import com.i906.mpt.prefs.NotificationPreferences;
import com.i906.mpt.settings.NotificationActivity;
import com.i906.mpt.settings.azanpicker.AzanPickerFragment;
import com.i906.mpt.util.RingtoneHelper;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* @author Noorzaini Ilhami
*/
public class ApplyAllDialogFragment extends BaseDialogFragment implements AzanPickerFragment.AzanListener {
private Unbinder unbinder;
private boolean mPrayerEnabled = true;
private boolean mNotificationEnabled = true;
private boolean mVibrationEnabled = true;
private String mNotificationTone;
private String mReminderTone;
@Inject
NotificationPreferences mNotificationPreferences;
@Inject
RingtoneHelper mRingtoneHelper;
@BindView(R.id.tv_prayer_name)
TextView mPrayerTextView;
@BindView(R.id.sw_prayer)
SwitchCompat mPrayerSwitch;
@BindView(R.id.cb_notification)
CheckBox mNotificationCheckBox;
@BindView(R.id.cb_vibrate)
CheckBox mVibrateCheckBox;
@BindView(R.id.btn_reminder)
Button mReminderButton;
@BindView(R.id.btn_notification)
Button mNotificationButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, 0);
activityGraph().inject(this);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_remarks, null);
unbinder = ButterKnife.bind(this, v);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setPositiveButton(R.string.label_apply, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
applyToAll();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.create();
}
@Override
public void onToneSelected(int prayer, String toneUri, boolean isNotification) {
if (isNotification) {
mNotificationTone = toneUri;
setToneName(mNotificationButton, toneUri, true);
} else {
mReminderTone = toneUri;
setToneName(mReminderButton, toneUri, false);
}
}
private void setToneName(Button b, String name, boolean isNotification) {
if (name != null) {
b.setText(mRingtoneHelper.getToneName(name));
} else {
b.setText(isNotification ? R.string.label_set_notification_tone :
R.string.label_set_reminder_tone);
}
}
@OnClick(R.id.sw_prayer)
void onPrayerChanged(CompoundButton v) {
mPrayerEnabled = v.isChecked();
mPrayerTextView.setEnabled(mPrayerEnabled);
mNotificationCheckBox.setEnabled(mPrayerEnabled);
mVibrateCheckBox.setEnabled(mPrayerEnabled);
mReminderButton.setEnabled(mPrayerEnabled);
mNotificationButton.setEnabled(mPrayerEnabled);
}
@OnClick(R.id.cb_notification)
void onNotificationChanged(CompoundButton v) {
mNotificationEnabled = v.isChecked();
}
@OnClick(R.id.cb_vibrate)
void onVibrateChanged(CompoundButton v) {
mVibrationEnabled = v.isEnabled();
}
@OnClick(R.id.btn_reminder)
void onReminderButtonClicked() {
showAzanPicker(false);
}
@OnClick(R.id.btn_notification)
void onNotificationButtonClicked() {
showAzanPicker(true);
}
private void showAzanPicker(boolean notifcation) {
AzanPickerFragment.newInstance(-1, null, notifcation)
.setListener(this)
.show(getFragmentManager(), "AZAN_PICKER");
}
private void applyToAll() {
for (int i = 0; i < 8; i++) {
mNotificationPreferences.setPrayerEnabled(i, mPrayerEnabled);
mNotificationPreferences.setNotificationEnabled(i, mNotificationEnabled);
mNotificationPreferences.setVibrationEnabled(i, mVibrationEnabled);
mNotificationPreferences.setReminderTone(i, mReminderTone);
mNotificationPreferences.setNotificationTone(i, mNotificationTone);
}
((NotificationActivity) getActivity()).refresh();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (unbinder != null) unbinder.unbind();
}
}
| 31.417647
| 107
| 0.681333
|
82332a7414962843fec3ffb793d02726577830af
| 5,344
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.gradle.nodes;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.modules.gradle.AbstractGradleProjectTestCase;
import org.netbeans.modules.gradle.NbGradleProjectImpl;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.LocalFileSystem;
import org.openide.nodes.Node;
/**
*
* @author lkishalmi
*/
public class BuildScriptsNodeTest extends AbstractGradleProjectTestCase {
private FileObject root;
public BuildScriptsNodeTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
super.setUp();
LocalFileSystem fs = new LocalFileSystem();
fs.setRootDirectory(getWorkDir());
root = fs.getRoot();
}
@Test
public void testGradleOnRoot() throws Exception {
FileObject a = createGradleProject("projectA",
"apply plugin: 'java'\n", "");
Project prjA = ProjectManager.getDefault().findProject(a);
BuildScriptsNode node = new BuildScriptsNode((NbGradleProjectImpl)prjA);
Node build = childNodeFor(node, a.getFileObject("build.gradle"));
assertNotNull(build);
assertEquals("build.gradle", build.getDisplayName());
Node settings = childNodeFor(node, a.getFileObject("settings.gradle"));
assertNotNull(settings);
assertEquals("settings.gradle", settings.getDisplayName());
assertNull(node.getChildren().findChild("buildSrc"));
}
@Test
public void testGradleWithBuildSrc() throws Exception {
FileObject a = createGradleProject("projectA",
"apply plugin: 'java'\n", "");
FileObject b = a.createFolder("buildSrc");
Project prjA = ProjectManager.getDefault().findProject(a);
BuildScriptsNode node = new BuildScriptsNode((NbGradleProjectImpl)prjA);
Node build = childNodeFor(node, a.getFileObject("build.gradle"));
assertNotNull(build);
assertEquals("build.gradle", build.getDisplayName());
Node settings = childNodeFor(node, a.getFileObject("settings.gradle"));
assertNotNull(settings);
assertEquals("settings.gradle", settings.getDisplayName());
Node buildSrc = childNodeFor(node, b);
assertNotNull(buildSrc);
}
@Test
public void testGradleOnBuildSrc() throws Exception {
FileObject a = createGradleProject("projectA",
"apply plugin: 'java'\n", "");
FileObject b = a.createFolder("buildSrc");
Project prjA = ProjectManager.getDefault().findProject(a);
Project prjB = ProjectManager.getDefault().findProject(b);
BuildScriptsNode node = new BuildScriptsNode((NbGradleProjectImpl)prjB);
assertNull(childNodeFor(node, b));
assertNull(childNodeFor(node, a.getFileObject("build.gradle")));
assertNull(childNodeFor(node, a.getFileObject("settings.gradle")));
}
@Test
public void testGradleWithSubProject() throws Exception {
FileObject a = createGradleProject("projectA",
"", "include 'projectB'");
FileObject gprops = a.createData("gradle.properties");
FileObject b = createGradleProject("projectA/projectB",
"apply plugin: 'java'\n", null);
Project prjA = ProjectManager.getDefault().findProject(a);
Project prjB = ProjectManager.getDefault().findProject(b);
BuildScriptsNode node = new BuildScriptsNode((NbGradleProjectImpl)prjB);
Node build = node.getChildren().findChild("build");
assertNotNull(build);
assertEquals("build.gradle [root]", build.getDisplayName());
Node settings = node.getChildren().findChild("settings");
assertNotNull(settings);
assertEquals("settings.gradle", settings.getDisplayName());
Node gradle = childNodeFor(node, gprops);
assertNotNull(gradle);
assertEquals("gradle.properties [root]", gradle.getDisplayName());
}
private static Node childNodeFor(Node node, FileObject fo) {
for (Node child : node.getChildren().getNodes(true)) {
FileObject cfo = child.getLookup().lookup(FileObject.class);
if (fo.equals(cfo)) {
return child;
}
}
return null;
}
}
| 40.180451
| 80
| 0.684506
|
13925e883c385fe5ba7bed8b7cd83898c04890db
| 3,261
|
/*
* Copyright 2016 The Closure Compiler Authors.
*
* 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 com.google.javascript.jscomp;
/**
* CompilerTestCase for passes that run after type checking and use type information.
* Allows us to test those passes with both type checkers.
*
* @author dimvar@google.com (Dimitris Vardoulakis)
*/
public abstract class TypeICompilerTestCase extends CompilerTestCase {
protected static enum TypeInferenceMode {
NEITHER,
OTI_ONLY,
NTI_ONLY,
BOTH;
boolean runsOTI() {
return this == OTI_ONLY || this == BOTH;
}
boolean runsNTI() {
return this == NTI_ONLY || this == BOTH;
}
boolean runsNeither() {
return this == NEITHER;
}
}
protected TypeInferenceMode mode = TypeInferenceMode.BOTH;
public TypeICompilerTestCase() {
super();
}
public TypeICompilerTestCase(String defaultExterns) {
super(defaultExterns);
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.mode = TypeInferenceMode.BOTH;
}
// NOTE(aravindpg): the idea with these selective overrides is that every `test` call
// in a subclass must go through one and exactly one of the overrides here, which are
// the ones that actually run the test twice (once under OTI and once under NTI).
// The `test` methods in CompilerTestCase overload each other in complicated ways,
// and this is the minimal set of overrides (of visible methods) that essentially
// "post-dominates" any `test` call.
@Override
protected void testInternal(
Externs externs,
Sources js,
Expected expected,
Diagnostic diagnotic) {
if (this.mode.runsOTI()) {
testOTI(externs, js, expected, diagnotic);
}
if (this.mode.runsNTI()) {
testNTI(externs, js, expected, diagnotic);
}
if (this.mode.runsNeither()) {
super.testInternal(externs, js, expected, diagnotic);
}
}
private void testOTI(
Externs externs,
Sources js,
Expected expected,
Diagnostic diagnotic) {
enableTypeCheck();
super.testInternal(externs, js, expected, diagnotic);
disableTypeCheck();
}
private void testNTI(
Externs externs,
Sources js,
Expected expected,
Diagnostic diagnotic) {
enableNewTypeInference();
super.testInternal(externs, js, expected, diagnotic);
disableNewTypeInference();
}
void testWarningOtiNti(
String js, DiagnosticType otiWarning, DiagnosticType ntiWarning) {
TypeInferenceMode saved = this.mode;
this.mode = TypeInferenceMode.OTI_ONLY;
testWarning(js, otiWarning);
this.mode = TypeInferenceMode.NTI_ONLY;
testWarning(js, ntiWarning);
this.mode = saved;
}
}
| 27.871795
| 87
| 0.692732
|
542aef31248f52e7b744ac3f5120ce4021861149
| 2,315
|
/*
* 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 Datos;
import Datos.Expresion;
/**
*
* @author carlo
*/
public class Mtd_Integracion {
Expresion e = new Expresion();
public double mtd_trapecio(double A, double B, int N, String fx) throws Exception {
if (N == 1) {
N = 2;
}
double h = (B - A) / N;
double h2 = h / 2;
double fa = e.Evaluar(fx, A);
double fb = e.Evaluar(fx, B);
double sm = 0;
double aux = A;
int i = 1;
do {
aux = aux + h;
sm = sm + e.Evaluar(fx, aux);
i++;
} while (i != (N));
double res = (h2) * (fa + fb + 2 * sm);
return res;
}
public double mtd_smps_1_3(double A, double B, int N, String fx) throws Exception {
if (N == 1) {
N = 2;
}
double h = (B - A) / N;
double h2 = h / 3;
double fa = e.Evaluar(fx, A);
double fb = e.Evaluar(fx, B);
double sm_imp = 0;
double sm_par = 0;
double aux = A;
int i = 1;
do {
aux = aux + h;
if (i % 2 == 0) {
sm_par = sm_par + e.Evaluar(fx, aux);
} else {
sm_imp = sm_imp + e.Evaluar(fx, aux);
}
i++;
} while (i != (N));
double res = (h2) * (fa + fb + 2 * sm_par + 4 * sm_imp);
return res;
}
public double mtd_smps_3_8(double A, double B, int N, String fx) throws Exception {
if (N == 1) {
N = 2;
}
double h = (B - A) / N;
double h2 = (3 * h) / 8;
double fa = e.Evaluar(fx, A);
double fb = e.Evaluar(fx, B);
double sm_3n = 0;
double sm_ord = 0;
double aux = A;
int i = 1;
do {
aux = aux + h;
if (i % 3 == 0) {
sm_3n = sm_3n + e.Evaluar(fx, aux);
} else {
sm_ord = sm_ord + e.Evaluar(fx, aux);
}
i++;
} while (i != (N));
double res = (h2) * (fa + fb + 2 * sm_3n + 3 * sm_ord);
return res;
}
}
| 25.722222
| 87
| 0.434989
|
c505b84983d8adea6bef7f11eddb9ad1c44cd91d
| 294
|
package com.kkuchar2.rose;
public class Subscription {
private final Action unsubscribeAction;
public Subscription(Action unsubscribeAction)
{
this.unsubscribeAction = unsubscribeAction;
}
public void unsubscribe()
{
unsubscribeAction.call();
}
}
| 18.375
| 51
| 0.683673
|
6750941741ac99b2e43c4cda5f67d9e3fca7c3e2
| 2,271
|
package baseCourse.classes.class03;
public class Address {
private String addressType;
private String addressStreetName;
private String addressNumber;
private String addressComplement;
private String addressNeighborhood;
private String addressUF;
private String addressZIPCode;
public Address(){
super();
}
public Address(String addressType, String addressStreetName,
String addressNumber, String addressComplement,
String addressNeighborhood, String addressUF,
String addressZIPCode) {
this.addressType = addressType;
this.addressStreetName = addressStreetName;
this.addressNumber = addressNumber;
this.addressComplement = addressComplement;
this.addressNeighborhood = addressNeighborhood;
this.addressUF = addressUF;
this.addressZIPCode = addressZIPCode;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddressStreetName() {
return addressStreetName;
}
public void setAddressStreetName(String addressStreetName) {
this.addressStreetName = addressStreetName;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getAddressComplement() {
return addressComplement;
}
public void setAddressComplement(String addressComplement) {
this.addressComplement = addressComplement;
}
public String getAddressNeighborhood() {
return addressNeighborhood;
}
public void setAddressNeighborhood(String addressNeighborhood) {
this.addressNeighborhood = addressNeighborhood;
}
public String getAddressUF() {
return addressUF;
}
public void setAddressUF(String addressUF) {
this.addressUF = addressUF;
}
public String getAddressZIPCode() {
return addressZIPCode;
}
public void setAddressZIPCode(String addressZIPCode) {
this.addressZIPCode = addressZIPCode;
}
}
| 26.717647
| 68
| 0.682078
|
22b0cf4cb966e60a2d6de41c51f93286be113cba
| 1,212
|
package starter.stepdefinitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.serenitybdd.screenplay.ensure.Ensure;
import net.thucydides.core.annotations.Managed;
import org.openqa.selenium.WebDriver;
import starter.navigation.LoginAsUser;
import starter.navigation.NavigateTo;
import starter.user_interface.imdbLoginPageElements;
public class IMDBLoginStepsDefinitions {
Actor actor = Actor.named("kemal");
@Managed
WebDriver webDriver;
@Given("user launch browser and open the main page")
public void user_launch_browser_and_open_the_main_page() {
actor.can(BrowseTheWeb.with(webDriver));
actor.attemptsTo(NavigateTo.theIMDBaHomePage());
}
@When("user logged in IMDB")
public void user_logged_in_ımdb() {
actor.attemptsTo(LoginAsUser.loginThePage("kemal","rajeevraj4184@gmail.com","tester97"));
}
@Then("user logged in successfully")
public void user_logged_in_successfully() {
actor.attemptsTo(Ensure.that(imdbLoginPageElements.IMG_FIELD).isDisplayed());
}
}
| 34.628571
| 97
| 0.765677
|
9204c3432efdaac55db694ea9221690b0ff8087d
| 16,598
|
package modeloDAO;
import java.awt.Component;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import modeloBO.RegistroGeneralBO;
import sizin.ClaseObjetoParaComboBox;
import sizin.Conexion;
import sizin.MyTableModel;
/**
* Clase que maneja los resultados para el analisis de brucelosis
*
* @author Erneski Coronado
*/
public class HemoparasitoDAO extends JTable {
Object[][] fila = new Object[][]{{"Nombre Científico", "Nombre Común", "Tipo de Muestra", "Identificación", "Edad", "Sexo", "F. Vacunación", "Observaciones", "ID", "", "Tipo de prueba", "Huevos y Larvas"}};
;// se le coloca el numero de columnas en el metodo columnastabla
//String sqltabla = "Select mu.idmuestrasgeneral, mu.Hierro, mu.IdAnimal, mu.IdEspecie, mu.IdRaza, mu.IdRaza, mu.Vacunado, mu.FechaVacuna, mu.Sexo, mu.Edad, mu.Observaciones, ang.Nombre, ane.Nombre, anr.Nombre, angr.Nombre FROM muestrasgeneral mu INNER JOIN animal ang ON mu.IdAnimal=ang.idAnimal INNER JOIN animalespecie ane ON mu.IdEspecie=ane.idanimalespecie INNER JOIN animalraza anr ON mu.IdRaza=anr.idanimalraza INNER JOIN animalgrupo angr ON mu.IdGrupo=angr.idanimalgrupo WHERE mu.idregistrogeneral=5";
String[] columnNames = new String[]{"Nombre Científico", "Nombre Común", "Tipo de Muestra", "Identificación", "Edad", "Sexo", "F. Vacunación", "Observaciones", "ID", "Taxon. Nº", "Resultado", "Tipo de prueba", "Descripción"};
//Object [][] data = new Object[][]{{"Bovino","Toro","Padrote","123","21 años","Macho","Si","12/06/2013","Ninguna","12",true} };
// MyTableModel modelo = new MyTableModel(columnNames, data);
public MyTableModel modelo;
int id = 0;
public ArrayList buscarAnalistas_Fecha(int id_registro_general) {
Conexion conex = new Conexion();
ArrayList analistas = new ArrayList();
boolean existe = false;
try {
//Statement estatuto = conex.getConnection().createStatement();
PreparedStatement consulta = conex.getConnection().prepareStatement("SELECT reg.id_personal, concat_ws(' ',per.cedula,per.nombre,per.apellido) as cedula, per.num_acreditacion FROM registro_procesado reg INNER join personal per ON reg.id_personal=per.id_personal WHERE reg.id_registro_general= ? ");
consulta.setInt(1, id_registro_general);
ResultSet res = consulta.executeQuery();
while (res.next()) {
ArrayList columnas = new ArrayList();
columnas.add(res.getInt(1));
columnas.add(res.getString(2));
columnas.add(res.getString(3));
analistas.add(columnas);
}
res.close();
conex.desconectar();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error, no se conecto");
System.out.println(e);
}
return analistas;
}
public RegistroGeneralBO buscarFecha_Procesado_Fecha(int id_registro_general) {
Conexion conex = new Conexion();
RegistroGeneralBO miRegistro = new RegistroGeneralBO();
try {
//Statement estatuto = conex.getConnection().createStatement();
PreparedStatement consulta = conex.getConnection().prepareStatement("SELECT fecha_procesado FROM registro_general WHERE id_registro_general= ? ");
consulta.setInt(1, id_registro_general);
ResultSet res = consulta.executeQuery();
while (res.next()) {
miRegistro.setFecha_procesado(res.getDate(1));
}
res.close();
conex.desconectar();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error, no se conecto");
System.out.println(e);
}
return miRegistro;
}
// esta funcion carga los datos de las muestras para llenar su resultado de brucelosis y carga los resultados si ya existen
public void llenar(int id_registro_general) {
Conexion conex = new Conexion();
Statement stmt3;
int numfilas = 0;
Vector idmuestrasgeneral = new Vector();
try {
PreparedStatement consulta = conex.getConnection().prepareStatement("select tax.nombre_completo, taxr.nombre_comun, tip.muestra_tipo, mu.identificacion, mu.edad_mes, mu.sexo, mu.fecha_vacunacion, mu.observacion, mu.id_registro_muestra from registro_muestra mu inner join taxonomia tax on mu.id_tsn_especie=tax.tsn left join taxonomia_rapida taxr on mu.id_tsn_especie=taxr.tsn_rapido inner join muestra_tipo tip on mu.id_muestra_tipo=tip.id_muestra_tipo where mu.id_registro_general = ? ");
consulta.setInt(1, id_registro_general);
try (ResultSet res = consulta.executeQuery()) {
while (res.next()) {
numfilas++;
idmuestrasgeneral.add("id_registro_muestra= " + res.getInt(9));
}
res.beforeFirst();//devuelvo el result a su estado original
//res.close();
//conex.desconectar();
//Cargamos los datos en el object para luego agregarlos al modelo de la tabla
Object[][] fila_muestras = new Object[numfilas][13];//guarda los valores para agregarlos a la tabla
int x = -1;
//comentarios
while (res.next()) {
x++;
//asignamos los valores para la fila a agregar en la tabla
fila_muestras[x][0] = res.getString(1);
fila_muestras[x][1] = res.getString(2);
fila_muestras[x][2] = res.getString(3);
fila_muestras[x][3] = res.getString(4);
fila_muestras[x][4] = res.getInt(5);
fila_muestras[x][5] = res.getString(6);
fila_muestras[x][6] = res.getDate(7);
fila_muestras[x][7] = res.getString(8);
fila_muestras[x][8] = res.getInt(9);
ArrayList a = new ArrayList();
a.add(0);
fila_muestras[x][9] = a;//id del taxonomia identificada
fila_muestras[x][10] = "[Sin organismos identificados]";//resultado
fila_muestras[x][11] = "";//tipo de prueba
fila_muestras[x][12] = "";//Descripcion del resultado
}
//cargamos los datos al modelo
modelo = new MyTableModel(columnNames, fila_muestras);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error, no se cargaron los datos de las muestras");
System.out.println(e);
}
//llenamos los resultados si existen de las muestras si ya existen o fueron llenados
try {
//Creamos el string para la consulta
String sqlmuestrasbru = "select hemo.id_resultado_hemoparasito, hemo.id_registro_muestra, hemo.id_analisis_prueba, hemo.observacion, pru.analisis_prueba from resultado_hemoparasito hemo inner join analisis_prueba pru on hemo.id_analisis_prueba=pru.id_analisis_prueba WHERE ";
for (int i = 0; i < numfilas; i++) {
//creo el string de la consulta
if (i < numfilas - 1) {
sqlmuestrasbru += idmuestrasgeneral.get(i).toString() + " or ";
} else {
sqlmuestrasbru += idmuestrasgeneral.get(i).toString();
}
}
//sqlmuestrasbru="Select * FROM resultadobrucelosis WHERE idmuestrasgeneral= 24 or idmuestrasgeneral= 25 or idmuestrasgeneral= 26 or idmuestrasgeneral= 27"; quedara algo asi
//Cargo los resultados
stmt3 = conex.getConnection().createStatement();
ResultSet rsmuestra;
rsmuestra = stmt3.executeQuery(sqlmuestrasbru);
int medir = 0;//compara con el numero de filas para cargar los resultados
while (rsmuestra.next()) {
if (medir < numfilas) {
//cargar los detalles
Statement stmt4 = conex.getConnection().createStatement();
ResultSet rsdetalle;
ArrayList tsn = new ArrayList();
ArrayList resultado = new ArrayList();
rsdetalle = stmt4.executeQuery("select det.id_tsn_especie, tax.nombre_completo from hemoparasito_detalle det inner join taxonomia tax on tax.tsn=det.id_tsn_especie where id_resultado_hemoparasito=" + rsmuestra.getInt(1));
while (rsdetalle.next()) {
tsn.add(rsdetalle.getInt(1));
resultado.add(rsdetalle.getString(2));
}
modelo.setValueAt(new ClaseObjetoParaComboBox(rsmuestra.getInt(3), rsmuestra.getString(5)), medir, 11);//cargar el tipo de prueba seleccionado
modelo.setValueAt(rsmuestra.getString(4), medir, 12);//cargar la descripcion del resultado
if (tsn.isEmpty()) {
ArrayList a = new ArrayList();
a.add(0);
modelo.setValueAt(a, medir, 9);
} else {
modelo.setValueAt(tsn, medir, 9);
}
if (resultado.isEmpty()) {
ArrayList b = new ArrayList();
b.add("Sin organismos identificados");
;
modelo.setValueAt(b, medir, 10);
} else {
modelo.setValueAt(resultado, medir, 10);
}
}
medir++;
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error, no se cargaron los datos de las muestras");
System.out.println(e);
}
conex.desconectar();
}
public boolean registrarResultado(ArrayList m, String procesado, ArrayList n) throws ParseException {
Conexion conex = new Conexion();
boolean realizado = false;
int id_registro = 0;
try {
conex.getConnection().setAutoCommit(false);
//eliminar los resultados
int cantidad_e = m.size();
for (int i = 0; i < cantidad_e; i++) {
CallableStatement cst = conex.getConnection().prepareCall("{call eliminar_hemoparasito (?)}");
ArrayList muestra = new ArrayList();
muestra = (ArrayList) m.get(i);
cst.setInt(1, Integer.parseInt(muestra.get(0).toString()));
cst.execute();
}
//guardar los resultados
int cantidad = m.size();
//int id_resultado = 0;
for (int i = 0; i < cantidad; i++) {
int id_resultado = 0;
PreparedStatement estatuto = null;
String sql = "INSERT into resultado_hemoparasito "
+ "(id_resultado_hemoparasito,id_registro_muestra,id_analisis_prueba,observacion)"
+ " values(null,?,?,?)";
estatuto = conex.getConnection().prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
ArrayList muestra = new ArrayList();
muestra = (ArrayList) m.get(i);
estatuto.setInt(1, Integer.parseInt(muestra.get(0).toString()));
estatuto.setInt(2, Integer.parseInt(muestra.get(1).toString()));
estatuto.setString(3, muestra.get(2).toString());
//cst2.execute();
if (estatuto.executeUpdate() == 1) {
ResultSet keyResultSet = estatuto.getGeneratedKeys();
if (keyResultSet.next()) {
id_resultado = keyResultSet.getInt(1);
}
//guardar los detalles
ArrayList r = new ArrayList();
r = (ArrayList) muestra.get(3);
int cantidad_ana = r.size();
for (int j = 0; j < cantidad_ana; j++) {
if (Integer.parseInt(r.get(j).toString()) > 0) {
CallableStatement cst3 = conex.getConnection().prepareCall("{call registro_hemoparasito_detalle (?,?)}");
cst3.setInt(1, id_resultado);
cst3.setInt(2, Integer.parseInt(r.get(j).toString()));
cst3.execute();
}
}
}
estatuto.close();
}
//eliminar los analistas
int cantidad_ana_e = n.size();
for (int i = 0; i < cantidad_ana_e; i++) {
CallableStatement cst2 = conex.getConnection().prepareCall("{call eliminar_analista_resultado (?)}");
ArrayList muestra = new ArrayList();
muestra = (ArrayList) n.get(i);
cst2.setInt(1, Integer.parseInt(muestra.get(0).toString()));
cst2.execute();
}
//guardar los analistas
int cantidad_ana = n.size();
for (int i = 0; i < cantidad_ana; i++) {
CallableStatement cst2 = conex.getConnection().prepareCall("{call registro_analista_resultado (?,?)}");
ArrayList muestra = new ArrayList();
muestra = (ArrayList) n.get(i);
id_registro = Integer.parseInt(muestra.get(0).toString());
cst2.setInt(1, Integer.parseInt(muestra.get(0).toString()));
cst2.setInt(2, Integer.parseInt(muestra.get(1).toString()));
cst2.execute();
}
CallableStatement cst3 = conex.getConnection().prepareCall("{call actualizar_fecha_procesado (?,?)}");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date fecha = sdf.parse(procesado);
cst3.setDate(1, new java.sql.Date(fecha.getTime()));
cst3.setInt(2, id_registro);
cst3.execute();
JOptionPane.showMessageDialog(null, "Se ha guardado Exitosamente los resultados", "Informacion", JOptionPane.INFORMATION_MESSAGE);
conex.getConnection().commit();
conex.desconectar();
realizado = true;
} catch (SQLException e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "No se Registro");
}
return realizado;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
//metodo para centrar los valores de una tabla
public void centrar_datos(JTable jT, int col) {
DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
modelocentrar.setHorizontalAlignment(SwingConstants.CENTER);
jT.getColumnModel().getColumn(col).setCellRenderer(modelocentrar);
}
//metodo para centrar contenido de una jtable
public TableCellRenderer render = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
l.setHorizontalAlignment(SwingConstants.CENTER);
return l;
}
//metodo para hacer una celda no editable
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
| 46.887006
| 514
| 0.57525
|
cc305b6608b2c118bbbf4af5051336522853ee79
| 7,670
|
/*
* The baseCode project
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.basecode.util;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author pavlidis
*/
public class StringUtil {
private static final Logger log = LoggerFactory.getLogger( StringUtil.class );
/**
* @param appendee The string to be added to
* @param appendant The string to add to the end of the appendee
* @param separator The string to put between the joined strings, if necessary.
* @return appendee + separator + separator unless appendee is empty, in which case the appendant is returned.
*/
public static String append( String appendee, String appendant, String separator ) {
if ( StringUtils.isBlank( appendee ) ) {
return appendant;
}
return appendee + separator + appendant;
}
/**
* Given a set of strings, identify any prefix they have in common.
*
* @param strings
* @return the common prefix, null if there isn't one.
*/
public static String commonPrefix( Collection<String> strings ) {
// find the shortest string; this is the maximum length of the prefix. It is itself the prefix to look for.
String shortest = shortestString( strings );
if ( shortest == null || shortest.length() == 0 ) return null;
String test = shortest;
while ( test.length() > 0 ) {
boolean found = true;
for ( String string : strings ) {
if ( !string.startsWith( test ) ) {
found = false;
break;
}
}
if ( found ) return test;
test = test.substring( 0, test.length() - 1 );
}
return null;
}
/**
* Given a set of strings, identify any suffix they have in common.
*
* @param strings
* @return the commons suffix, null if there isn't one.
*/
public static String commonSuffix( Collection<String> strings ) {
String shortest = shortestString( strings );
if ( shortest == null || shortest.length() == 0 ) return null;
String test = shortest;
while ( test.length() > 0 ) {
boolean found = true;
for ( String string : strings ) {
if ( !string.endsWith( test ) ) {
found = false;
break;
}
}
if ( found ) return test;
test = test.substring( 1 );
}
return null;
}
/**
* Checks a string to find "strange" character, used by phenocarta to check evidence description
*
* @param the string to check
* @return return false if something strange was found
* @author Nicolas?
*/
public static boolean containsValidCharacter( String s ) {
if ( s != null ) {
for ( int i = 0; i < s.length(); i++ ) {
Character cha = s.charAt( i );
if ( !( isLatinLetter( cha ) || Character.isDigit( cha ) || cha == '=' || cha == ',' || cha == '('
|| cha == ')' || cha == '\'' || Character.isWhitespace( cha ) || cha == '/' || cha == '?'
|| cha == '+' || cha == ':' || cha == '-' || cha == '<' || cha == '>' || cha == '"'
|| cha == '%' || cha == '.' || cha == '*' || cha == '[' || cha == ']' || cha == ';'
|| cha == '_' || cha == '\\' || cha == '|' || cha == '&' || cha == '^' || cha == '#'
|| cha == '{' || cha == '}' || cha == '!' || cha == '~' || cha == '@' || cha == '—'
|| cha == '×' || cha == '–' || cha == ' ' ) ) {
// new cha to be added, special Öö≤≥âμ etc... TODO and check later if found
log.warn( "Illegal character found: " + cha + " found on description: " + s );
return false;
}
}
}
return true;
}
/**
* @param numFields
* @param line
* @return
*/
public static String[] csvSplit( String line ) {
@SuppressWarnings("resource")
CSVReader reader = new CSVReader( new StringReader( line ) );
try {
return reader.readNext();
} catch ( IOException | CsvValidationException e ) {
throw new RuntimeException( e );
}
}
/**
* Made by Nicolas
*
* @param a line in a file cvs format
* @return the same line but in tsv format
*/
public static String cvs2tsv( String line ) {
StringBuffer newLine = new StringBuffer( line );
boolean change = true;
for ( int position = 0; position < newLine.length(); position++ ) {
if ( newLine.charAt( position ) == ',' && change ) {
newLine.setCharAt( position, '\t' );
} else if ( newLine.charAt( position ) == '"' ) {
if ( change ) {
change = false;
} else {
change = true;
}
}
}
return newLine.toString().replaceAll( "\"", "" );
}
public static boolean isLatinLetter( char c ) {
return ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' );
}
/**
* Mimics the make.names method in R (character.c) to make valid variables names; we use this for column headers in
* some output files. This doesn't give the exact sames results as R; we avoid repeated '.'.
*
* @param s
* @return modified string
* @author paul
*/
public static String makeValidForR( String s ) {
// If string starts with a digit or "." and then a digit, prepend an X.
if ( s.matches( "^\\.?[0-9].+" ) ) {
s = "X" + s;
}
// TODO: check for reserved words. https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html
// no dashes or white space or other punctuation. '.' is okay and so is "_", now.
return s.replaceAll( "[\\W]+", "." );
}
/**
* @param stringi
* @param stringj
* @return
*/
public static Long twoStringHashKey( String stringi, String stringj ) {
// use arbitrary but consistent method for ordering.
if ( stringi.hashCode() < stringj.hashCode() ) {
return new Long( stringi.hashCode() | ( long ) stringj.hashCode() << 32 );
}
return new Long( stringj.hashCode() | ( long ) stringi.hashCode() << 32 );
}
private static String shortestString( Collection<String> strings ) {
String shortest = null;
for ( String string : strings ) {
if ( shortest == null || string.length() < shortest.length() ) shortest = string;
}
return shortest;
}
}
| 33.203463
| 119
| 0.532464
|
ed4496a9b6d84c8762bb1d3389d53d5c64fe186d
| 13,866
|
package net.deeppay;
/*
* Copyright 2016 The Apache Software Foundation.
*
* 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.
*/
import net.deeppay.cqlAST2puml.CQL2Puml;
import net.deeppay.cqlparser.CQLSchemaParser;
import net.sourceforge.plantuml.*;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import scala.collection.Seq;
import scala.io.BufferedSource;
import scala.io.Source;
import scala.util.parsing.combinator.Parsers;
import troy.cql.ast.DataDefinition;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.plantuml.preproc.Defines;
import org.apache.maven.model.FileSet;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.FileUtils;
/**
* Goal which touches a timestamp file.
*
* @goal touch
*
* @phase process-sources
*/
public class CQL2PlantUMLMojo
extends AbstractMojo
{
private final Option option = new Option();
/**
* Fileset to search plantuml diagrams in.
* @parameter property="plantuml.sourceFiles"
* @required
* @since 7232
*/
private FileSet sourceFiles;
/**
* Directory where generated images are generated.
* @parameter property="plantuml.outputDirectory" default-value="${basedir}/target/plantuml"
* @required
*/
private File outputDirectory;
/**
* Whether or not to generate images in same directory as the source file.
* This is useful for using PlantUML diagrams in Javadoc,
* as described here:
* <a href="http://plantuml.sourceforge.net/javadoc.html">http://plantuml.sourceforge.net/javadoc.html</a>.
*
* If this is set to true then outputDirectory is ignored.
* @parameter property="plantuml.outputInSourceDirectory" default-value="false"
*/
private boolean outputInSourceDirectory;
/**
* Charset used during generation.
* @parameter property="plantuml.charset"
*/
private String charset;
/**
* External configuration file location.
* @parameter property="plantuml.config"
*/
private String config;
/**
* Wether or not to keep tmp files after generation.
* @parameter property="plantuml.keepTmpFiles" default-value="false"
*/
private boolean keepTmpFiles;
/**
* Specify output format. Supported values: xmi, xmi:argo, xmi:start, eps, pdf, eps:txt, svg, png, dot, txt and utxt.
* @parameter property="plantuml.format"
*/
private String format;
/**
* Fully qualified path to Graphviz home directory.
* @parameter property="plantuml.graphvizDot"
*/
private String graphvizDot;
/**
* Wether or not to output details during generation.
* @parameter property="plantuml.verbose" default-value="false"
*/
private boolean verbose;
/**
* Specify to include metadata in the output files.
* @parameter property="plantuml.withMetadata"
* @since 1.3
*/
private boolean withMetadata = false;
/**
* Specify to overwrite any output file, also if the target file is newer as the input file.
* @parameter property="plantuml.overwrite"
* @since 1.3
*/
private boolean overwrite = false;
/**
* Specify whether to also write the output puml file
* @parameter property="plantuml.outputPuml"
*/
private boolean outputPuml = false;
protected final void setFormat(final String format) {
if ("xmi".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.XMI_STANDARD);
} else if ("xmi:argo".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.XMI_ARGO);
} else if ("xmi:start".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.XMI_STAR);
} else if ("eps".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.EPS);
} else if ("eps:txt".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.EPS_TEXT);
} else if ("svg".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.SVG);
} else if ("txt".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.ATXT);
} else if ("utxt".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.UTXT);
} else if ("png".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.PNG);
} else if ("pdf".equalsIgnoreCase(format)) {
this.option.setFileFormat(FileFormat.PDF);
} else {
throw new IllegalArgumentException("Unrecognized format <"+format+">");
}
}
@Override
public void execute() throws MojoExecutionException {
// early exit if sourceFiles directory is not available
final String invalidSourceFilesDirectoryWarnMsg = this.sourceFiles.getDirectory() + " is not a valid path";
if( null == this.sourceFiles.getDirectory() || this.sourceFiles.getDirectory().isEmpty()) {
getLog().warn(invalidSourceFilesDirectoryWarnMsg);
return;
}
File baseDir = null;
try {
baseDir = new File(this.sourceFiles.getDirectory());
} catch (Exception e) {
getLog().debug(invalidSourceFilesDirectoryWarnMsg, e);
}
if( null == baseDir || !baseDir.exists() || !baseDir.isDirectory()) {
getLog().warn(invalidSourceFilesDirectoryWarnMsg);
return;
}
if (!this.outputInSourceDirectory) {
if (!this.outputDirectory.exists()) {
// If output directoy does not exist yet create it.
this.outputDirectory.mkdirs();
}
if (!this.outputDirectory.isDirectory()) {
throw new IllegalArgumentException("<" + this.outputDirectory + "> is not a valid directory.");
}
}
try {
if (!this.outputInSourceDirectory) {
this.option.setOutputDir(this.outputDirectory);
}
if (this.charset != null) {
this.option.setCharset(this.charset);
}
if (this.config != null) {
this.option.initConfig(this.config);
}
/*if (this.keepTmpFiles) {
//OptionFlags.getInstance().setKeepTmpFiles(this.keepTmpFiles);
}*/
if (this.graphvizDot != null) {
OptionFlags.getInstance().setDotExecutable(this.graphvizDot);
}
if (this.format != null) {
setFormat(this.format);
}
if (this.verbose) {
OptionFlags.getInstance().setVerbose(true);
}
final List<File> files = FileUtils.getFiles(
baseDir,
getCommaSeparatedList(this.sourceFiles.getIncludes()),
getCommaSeparatedList(this.sourceFiles.getExcludes())
);
for(final File file : files) {
File outDir;
if (this.outputInSourceDirectory) {
outDir = file.getParentFile();
} else {
outDir = outputDirectory.toPath().resolve(
baseDir.toPath().relativize(file.toPath().getParent())).toFile();
}
this.option.setOutputDir(outDir);
FileFormatOption fileFormatOption = getFileFormatOption();
if (!overwrite){
String newName = fileFormatOption.getFileFormat().changeName(file.getName(), 0);
File targetFile = new File(outDir, newName);
if (targetFile.exists() && targetFile.lastModified() > file.lastModified()){
getLog().debug("Skip file <"+file+"> because target <"+targetFile+"> is newer");
continue;
}
}
getLog().info("Processing file <"+file+">");
List<GeneratedImage> generatedImages;
if (file.getName().endsWith(".cql")) {
getLog().info("cqlfile : ["+file.getName()+"]");
BufferedSource bufferedSource = null;
// Read CQL file.
String cqlInput = null;
try {
bufferedSource = Source.fromFile(file, "UTF-8");
cqlInput = bufferedSource.mkString();
} finally {
if (bufferedSource != null) {
bufferedSource.close();
}
}
// Parse CQL file
Parsers.ParseResult<Seq<DataDefinition>> seqParseResult = CQLSchemaParser.parseSchema(cqlInput);
if (!seqParseResult.successful()) {
getLog().error("parse not successful for file [" + file.getName() + "] : " + seqParseResult);
} else {
// Transform CQL to PUML
CQL2Puml cql2Puml = new CQL2Puml();
StringWriter stringWriter = new StringWriter();
cql2Puml.output(seqParseResult.get(), stringWriter);
if (outputPuml) { // Write the PUML to disk ?
String fileName = file.getName();
String replacement = ".puml";
String pumlFilename = fileName.replaceAll("\\.\\w+$", replacement);
if (pumlFilename.equals(fileName)) {
pumlFilename = fileName + replacement;
}
File targetFile = new File(outDir, pumlFilename);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(targetFile);
fileWriter.write(stringWriter.toString());
} finally {
try {
fileWriter.close();
} catch (IOException e) {
getLog().info("IOException on close", e);
}
}
}
SourceStringReader sourceStringReader = new SourceStringReader(new Defines(), stringWriter.toString(), this.option.getCharset(), this.option.getConfig());
String newName = fileFormatOption.getFileFormat().changeName(file.getName(), 0);
File targetFile = new File(outDir, newName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(targetFile);
String result = sourceStringReader.generateImage(fileOutputStream, fileFormatOption);
getLog().debug(" result =["+result+"]");
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
getLog().info("IOException on close", e);
}
}
}
}
} else {
final SourceFileReader sourceFileReader =
new SourceFileReader(
new Defines(), file, this.option.getOutputDir(),
this.option.getConfig(), this.option.getCharset(),
fileFormatOption);
generatedImages = sourceFileReader.getGeneratedImages();
for (final GeneratedImage image : generatedImages) {
getLog().debug(image + " " + image.getDescription());
}
}
}
} catch (Exception e) {
throw new MojoExecutionException("Exception during plantuml process", e);
}
}
protected String getCommaSeparatedList(final List<String> list) {
final StringBuilder builder = new StringBuilder();
final Iterator it = list.iterator();
while(it.hasNext()) {
final Object object = it.next();
builder.append(object.toString());
if (it.hasNext()) {
builder.append(",");
}
}
return builder.toString();
}
private FileFormatOption getFileFormatOption() {
FileFormatOption formatOptions = new FileFormatOption(this.option.getFileFormat(), this.withMetadata);
if (formatOptions.isWithMetadata() != withMetadata){
// Workarround to error in plantUML where the withMetadata flag is not correctly applied.
return new FileFormatOption(this.option.getFileFormat());
}
return formatOptions;
}
}
| 40.425656
| 178
| 0.556974
|
7603a92d047c4e866c0f0356374eda5c5635a81d
| 1,840
|
package com.bai.account.shiro;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@Slf4j
public class CustomPathMatchingFilterChainResolver extends PathMatchingFilterChainResolver {
@Override
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
FilterChainManager filterChainManager = getFilterChainManager();
if (!filterChainManager.hasChains()) {
return null;
}
String currentPath = getPathWithinApplication(request);
for (String pathPattern : filterChainManager.getChainNames()) {
if (isHttpRequestMatched(pathPattern,currentPath,request)) {
if (log.isTraceEnabled()) {
log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + currentPath + "]. "
+ "Utilizing corresponding filter chain...");
}
return filterChainManager.proxy(originalChain, pathPattern);
}
}
return null;
}
private boolean isHttpRequestMatched(String chain, String currentPath, ServletRequest request) {
val array = chain.split("::");
val url = array[0];
boolean isHttpRequestMatched = true;
if (array.length > 1) {
val httpMethod = ((HttpServletRequest) request).getMethod();
val method = array[1];
isHttpRequestMatched = method.equals(httpMethod);
}
return pathMatches(url,currentPath) && isHttpRequestMatched;
}
}
| 39.148936
| 113
| 0.675
|
de9c729164795b64756776c0420231fbd4893a5e
| 531
|
package ru.job4j.search;
import java.util.LinkedList;
/**
* Created by Sergii.
*/
public class PriorityQueue {
private LinkedList<Task> tasks = new LinkedList<>();
public void put(Task task) {
int index = tasks.size();
for (int i = 0; i < index; i++) {
if (tasks.get(i).getPriority() >= task.getPriority()) {
index = i;
break;
}
}
tasks.add(index, task);
}
public Task take() {
return this.tasks.poll();
}
}
| 19.666667
| 67
| 0.514124
|
7d51b6a9f7e3b2fc4b937518d75a1562ba3550f4
| 2,424
|
package com.renanrest.model;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author renan
*/
@Entity
@Table(name = "Professor")
@XmlRootElement
public class Professor extends AbstractEntity {
@Column(length = 255, nullable = false)
private String nome;
@Column(length = 255, nullable = false)
private String telefone;
@Column(length = 255, nullable = false)
private String endereco;
@Column(length = 255, nullable = false)
private String conta;
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.nome);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Professor other = (Professor) obj;
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Professor{" + "nome=" + nome + ", telefone=" + telefone + ", endereco=" + endereco + ", conta=" + conta + '}';
}
public Professor() {
}
@Override
public void updateParameters(Object entity) {
final Professor Professor = (Professor) entity;
this.telefone = Professor.getTelefone();
this.endereco = Professor.getEndereco();
this.conta = Professor.getConta();
this.nome = Professor.getNome();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getConta() {
return conta;
}
public void setConta(String conta) {
this.conta = conta;
}
}
| 22.036364
| 126
| 0.589934
|
f383a7d2787d2ac4e88c7764c3ca56efc460846d
| 71,000
|
package buwai.android.androidmanifestfix;
import java.util.HashMap;
import java.util.Map;
public class AxmlNameHelper {
/**
* 名称空间。
*/
public static final String ns = "http://schemas.android.com/apk/res/android";
private static Map<Integer, AxmlName> mAxmlNameMap = new HashMap<Integer, AxmlName>();
static {
mAxmlNameMap.put(0x01010000, AxmlName.theme);
mAxmlNameMap.put(0x01010001, AxmlName.label);
mAxmlNameMap.put(0x01010002, AxmlName.icon);
mAxmlNameMap.put(0x01010003, AxmlName.name);
mAxmlNameMap.put(0x01010004, AxmlName.manageSpaceActivity);
mAxmlNameMap.put(0x01010005, AxmlName.allowClearUserData);
mAxmlNameMap.put(0x01010006, AxmlName.permission);
mAxmlNameMap.put(0x01010007, AxmlName.readPermission);
mAxmlNameMap.put(0x01010008, AxmlName.writePermission);
mAxmlNameMap.put(0x01010009, AxmlName.protectionLevel);
mAxmlNameMap.put(0x0101000a, AxmlName.permissionGroup);
mAxmlNameMap.put(0x0101000b, AxmlName.sharedUserId);
mAxmlNameMap.put(0x0101000c, AxmlName.hasCode);
mAxmlNameMap.put(0x0101000d, AxmlName.persistent);
mAxmlNameMap.put(0x0101000e, AxmlName.enabled);
mAxmlNameMap.put(0x0101000f, AxmlName.debuggable);
mAxmlNameMap.put(0x01010010, AxmlName.exported);
mAxmlNameMap.put(0x01010011, AxmlName.process);
mAxmlNameMap.put(0x01010012, AxmlName.taskAffinity);
mAxmlNameMap.put(0x01010013, AxmlName.multiprocess);
mAxmlNameMap.put(0x01010014, AxmlName.finishOnTaskLaunch);
mAxmlNameMap.put(0x01010015, AxmlName.clearTaskOnLaunch);
mAxmlNameMap.put(0x01010016, AxmlName.stateNotNeeded);
mAxmlNameMap.put(0x01010017, AxmlName.excludeFromRecents);
mAxmlNameMap.put(0x01010018, AxmlName.authorities);
mAxmlNameMap.put(0x01010019, AxmlName.syncable);
mAxmlNameMap.put(0x0101001a, AxmlName.initOrder);
mAxmlNameMap.put(0x0101001b, AxmlName.grantUriPermissions);
mAxmlNameMap.put(0x0101001c, AxmlName.priority);
mAxmlNameMap.put(0x0101001d, AxmlName.launchMode);
mAxmlNameMap.put(0x0101001e, AxmlName.screenOrientation);
mAxmlNameMap.put(0x0101001f, AxmlName.configChanges);
mAxmlNameMap.put(0x01010020, AxmlName.description);
mAxmlNameMap.put(0x01010021, AxmlName.targetPackage);
mAxmlNameMap.put(0x01010022, AxmlName.handleProfiling);
mAxmlNameMap.put(0x01010023, AxmlName.functionalTest);
mAxmlNameMap.put(0x01010024, AxmlName.value);
mAxmlNameMap.put(0x01010025, AxmlName.resource);
mAxmlNameMap.put(0x01010026, AxmlName.mimeType);
mAxmlNameMap.put(0x01010027, AxmlName.scheme);
mAxmlNameMap.put(0x01010028, AxmlName.host);
mAxmlNameMap.put(0x01010029, AxmlName.port);
mAxmlNameMap.put(0x0101002a, AxmlName.path);
mAxmlNameMap.put(0x0101002b, AxmlName.pathPrefix);
mAxmlNameMap.put(0x0101002c, AxmlName.pathPattern);
mAxmlNameMap.put(0x0101002d, AxmlName.action);
mAxmlNameMap.put(0x0101002e, AxmlName.data);
mAxmlNameMap.put(0x0101002f, AxmlName.targetClass);
mAxmlNameMap.put(0x01010030, AxmlName.colorForeground);
mAxmlNameMap.put(0x01010031, AxmlName.colorBackground);
mAxmlNameMap.put(0x01010032, AxmlName.backgroundDimAmount);
mAxmlNameMap.put(0x01010033, AxmlName.disabledAlpha);
mAxmlNameMap.put(0x01010034, AxmlName.textAppearance);
mAxmlNameMap.put(0x01010035, AxmlName.textAppearanceInverse);
mAxmlNameMap.put(0x01010036, AxmlName.textColorPrimary);
mAxmlNameMap.put(0x01010037, AxmlName.textColorPrimaryDisableOnly);
mAxmlNameMap.put(0x01010038, AxmlName.textColorSecondary);
mAxmlNameMap.put(0x01010039, AxmlName.textColorPrimaryInverse);
mAxmlNameMap.put(0x0101003a, AxmlName.textColorSecondaryInverse);
mAxmlNameMap.put(0x0101003b, AxmlName.textColorPrimaryNoDisable);
mAxmlNameMap.put(0x0101003c, AxmlName.textColorSecondaryNoDisable);
mAxmlNameMap.put(0x0101003d, AxmlName.textColorPrimaryInverseNoDisable);
mAxmlNameMap.put(0x0101003e, AxmlName.textColorSecondaryInverseNoDisable);
mAxmlNameMap.put(0x0101003f, AxmlName.textColorHintInverse);
mAxmlNameMap.put(0x01010040, AxmlName.textAppearanceLarge);
mAxmlNameMap.put(0x01010041, AxmlName.textAppearanceMedium);
mAxmlNameMap.put(0x01010042, AxmlName.textAppearanceSmall);
mAxmlNameMap.put(0x01010043, AxmlName.textAppearanceLargeInverse);
mAxmlNameMap.put(0x01010044, AxmlName.textAppearanceMediumInverse);
mAxmlNameMap.put(0x01010045, AxmlName.textAppearanceSmallInverse);
mAxmlNameMap.put(0x01010046, AxmlName.textCheckMark);
mAxmlNameMap.put(0x01010047, AxmlName.textCheckMarkInverse);
mAxmlNameMap.put(0x01010048, AxmlName.buttonStyle);
mAxmlNameMap.put(0x01010049, AxmlName.buttonStyleSmall);
mAxmlNameMap.put(0x0101004a, AxmlName.buttonStyleInset);
mAxmlNameMap.put(0x0101004b, AxmlName.buttonStyleToggle);
mAxmlNameMap.put(0x0101004c, AxmlName.galleryItemBackground);
mAxmlNameMap.put(0x0101004d, AxmlName.listPreferredItemHeight);
mAxmlNameMap.put(0x0101004e, AxmlName.expandableListPreferredItemPaddingLeft);
mAxmlNameMap.put(0x0101004f, AxmlName.expandableListPreferredChildPaddingLeft);
mAxmlNameMap.put(0x01010050, AxmlName.expandableListPreferredItemIndicatorLeft);
mAxmlNameMap.put(0x01010051, AxmlName.expandableListPreferredItemIndicatorRight);
mAxmlNameMap.put(0x01010052, AxmlName.expandableListPreferredChildIndicatorLeft);
mAxmlNameMap.put(0x01010053, AxmlName.expandableListPreferredChildIndicatorRight);
mAxmlNameMap.put(0x01010054, AxmlName.windowBackground);
mAxmlNameMap.put(0x01010055, AxmlName.windowFrame);
mAxmlNameMap.put(0x01010056, AxmlName.windowNoTitle);
mAxmlNameMap.put(0x01010057, AxmlName.windowIsFloating);
mAxmlNameMap.put(0x01010058, AxmlName.windowIsTranslucent);
mAxmlNameMap.put(0x01010059, AxmlName.windowContentOverlay);
mAxmlNameMap.put(0x0101005a, AxmlName.windowTitleSize);
mAxmlNameMap.put(0x0101005b, AxmlName.windowTitleStyle);
mAxmlNameMap.put(0x0101005c, AxmlName.windowTitleBackgroundStyle);
mAxmlNameMap.put(0x0101005d, AxmlName.alertDialogStyle);
mAxmlNameMap.put(0x0101005e, AxmlName.panelBackground);
mAxmlNameMap.put(0x0101005f, AxmlName.panelFullBackground);
mAxmlNameMap.put(0x01010060, AxmlName.panelColorForeground);
mAxmlNameMap.put(0x01010061, AxmlName.panelColorBackground);
mAxmlNameMap.put(0x01010062, AxmlName.panelTextAppearance);
mAxmlNameMap.put(0x01010063, AxmlName.scrollbarSize);
mAxmlNameMap.put(0x01010064, AxmlName.scrollbarThumbHorizontal);
mAxmlNameMap.put(0x01010065, AxmlName.scrollbarThumbVertical);
mAxmlNameMap.put(0x01010066, AxmlName.scrollbarTrackHorizontal);
mAxmlNameMap.put(0x01010067, AxmlName.scrollbarTrackVertical);
mAxmlNameMap.put(0x01010068, AxmlName.scrollbarAlwaysDrawHorizontalTrack);
mAxmlNameMap.put(0x01010069, AxmlName.scrollbarAlwaysDrawVerticalTrack);
mAxmlNameMap.put(0x0101006a, AxmlName.absListViewStyle);
mAxmlNameMap.put(0x0101006b, AxmlName.autoCompleteTextViewStyle);
mAxmlNameMap.put(0x0101006c, AxmlName.checkboxStyle);
mAxmlNameMap.put(0x0101006d, AxmlName.dropDownListViewStyle);
mAxmlNameMap.put(0x0101006e, AxmlName.editTextStyle);
mAxmlNameMap.put(0x0101006f, AxmlName.expandableListViewStyle);
mAxmlNameMap.put(0x01010070, AxmlName.galleryStyle);
mAxmlNameMap.put(0x01010071, AxmlName.gridViewStyle);
mAxmlNameMap.put(0x01010072, AxmlName.imageButtonStyle);
mAxmlNameMap.put(0x01010073, AxmlName.imageWellStyle);
mAxmlNameMap.put(0x01010074, AxmlName.listViewStyle);
mAxmlNameMap.put(0x01010075, AxmlName.listViewWhiteStyle);
mAxmlNameMap.put(0x01010076, AxmlName.popupWindowStyle);
mAxmlNameMap.put(0x01010077, AxmlName.progressBarStyle);
mAxmlNameMap.put(0x01010078, AxmlName.progressBarStyleHorizontal);
mAxmlNameMap.put(0x01010079, AxmlName.progressBarStyleSmall);
mAxmlNameMap.put(0x0101007a, AxmlName.progressBarStyleLarge);
mAxmlNameMap.put(0x0101007b, AxmlName.seekBarStyle);
mAxmlNameMap.put(0x0101007c, AxmlName.ratingBarStyle);
mAxmlNameMap.put(0x0101007d, AxmlName.ratingBarStyleSmall);
mAxmlNameMap.put(0x0101007e, AxmlName.radioButtonStyle);
mAxmlNameMap.put(0x0101007f, AxmlName.scrollbarStyle);
mAxmlNameMap.put(0x01010080, AxmlName.scrollViewStyle);
mAxmlNameMap.put(0x01010081, AxmlName.spinnerStyle);
mAxmlNameMap.put(0x01010082, AxmlName.starStyle);
mAxmlNameMap.put(0x01010083, AxmlName.tabWidgetStyle);
mAxmlNameMap.put(0x01010084, AxmlName.textViewStyle);
mAxmlNameMap.put(0x01010085, AxmlName.webViewStyle);
mAxmlNameMap.put(0x01010086, AxmlName.dropDownItemStyle);
mAxmlNameMap.put(0x01010087, AxmlName.spinnerDropDownItemStyle);
mAxmlNameMap.put(0x01010088, AxmlName.dropDownHintAppearance);
mAxmlNameMap.put(0x01010089, AxmlName.spinnerItemStyle);
mAxmlNameMap.put(0x0101008a, AxmlName.mapViewStyle);
mAxmlNameMap.put(0x0101008b, AxmlName.preferenceScreenStyle);
mAxmlNameMap.put(0x0101008c, AxmlName.preferenceCategoryStyle);
mAxmlNameMap.put(0x0101008d, AxmlName.preferenceInformationStyle);
mAxmlNameMap.put(0x0101008e, AxmlName.preferenceStyle);
mAxmlNameMap.put(0x0101008f, AxmlName.checkBoxPreferenceStyle);
mAxmlNameMap.put(0x01010090, AxmlName.yesNoPreferenceStyle);
mAxmlNameMap.put(0x01010091, AxmlName.dialogPreferenceStyle);
mAxmlNameMap.put(0x01010092, AxmlName.editTextPreferenceStyle);
mAxmlNameMap.put(0x01010093, AxmlName.ringtonePreferenceStyle);
mAxmlNameMap.put(0x01010094, AxmlName.preferenceLayoutChild);
mAxmlNameMap.put(0x01010095, AxmlName.textSize);
mAxmlNameMap.put(0x01010096, AxmlName.typeface);
mAxmlNameMap.put(0x01010097, AxmlName.textStyle);
mAxmlNameMap.put(0x01010098, AxmlName.textColor);
mAxmlNameMap.put(0x01010099, AxmlName.textColorHighlight);
mAxmlNameMap.put(0x0101009a, AxmlName.textColorHint);
mAxmlNameMap.put(0x0101009b, AxmlName.textColorLink);
mAxmlNameMap.put(0x0101009c, AxmlName.state_focused);
mAxmlNameMap.put(0x0101009d, AxmlName.state_window_focused);
mAxmlNameMap.put(0x0101009e, AxmlName.state_enabled);
mAxmlNameMap.put(0x0101009f, AxmlName.state_checkable);
mAxmlNameMap.put(0x010100a0, AxmlName.state_checked);
mAxmlNameMap.put(0x010100a1, AxmlName.state_selected);
mAxmlNameMap.put(0x010100a2, AxmlName.state_active);
mAxmlNameMap.put(0x010100a3, AxmlName.state_single);
mAxmlNameMap.put(0x010100a4, AxmlName.state_first);
mAxmlNameMap.put(0x010100a5, AxmlName.state_middle);
mAxmlNameMap.put(0x010100a6, AxmlName.state_last);
mAxmlNameMap.put(0x010100a7, AxmlName.state_pressed);
mAxmlNameMap.put(0x010100a8, AxmlName.state_expanded);
mAxmlNameMap.put(0x010100a9, AxmlName.state_empty);
mAxmlNameMap.put(0x010100aa, AxmlName.state_above_anchor);
mAxmlNameMap.put(0x010100ab, AxmlName.ellipsize);
mAxmlNameMap.put(0x010100ac, AxmlName.x);
mAxmlNameMap.put(0x010100ad, AxmlName.y);
mAxmlNameMap.put(0x010100ae, AxmlName.windowAnimationStyle);
mAxmlNameMap.put(0x010100af, AxmlName.gravity);
mAxmlNameMap.put(0x010100b0, AxmlName.autoLink);
mAxmlNameMap.put(0x010100b1, AxmlName.linksClickable);
mAxmlNameMap.put(0x010100b2, AxmlName.entries);
mAxmlNameMap.put(0x010100b3, AxmlName.layout_gravity);
mAxmlNameMap.put(0x010100b4, AxmlName.windowEnterAnimation);
mAxmlNameMap.put(0x010100b5, AxmlName.windowExitAnimation);
mAxmlNameMap.put(0x010100b6, AxmlName.windowShowAnimation);
mAxmlNameMap.put(0x010100b7, AxmlName.windowHideAnimation);
mAxmlNameMap.put(0x010100b8, AxmlName.activityOpenEnterAnimation);
mAxmlNameMap.put(0x010100b9, AxmlName.activityOpenExitAnimation);
mAxmlNameMap.put(0x010100ba, AxmlName.activityCloseEnterAnimation);
mAxmlNameMap.put(0x010100bb, AxmlName.activityCloseExitAnimation);
mAxmlNameMap.put(0x010100bc, AxmlName.taskOpenEnterAnimation);
mAxmlNameMap.put(0x010100bd, AxmlName.taskOpenExitAnimation);
mAxmlNameMap.put(0x010100be, AxmlName.taskCloseEnterAnimation);
mAxmlNameMap.put(0x010100bf, AxmlName.taskCloseExitAnimation);
mAxmlNameMap.put(0x010100c0, AxmlName.taskToFrontEnterAnimation);
mAxmlNameMap.put(0x010100c1, AxmlName.taskToFrontExitAnimation);
mAxmlNameMap.put(0x010100c2, AxmlName.taskToBackEnterAnimation);
mAxmlNameMap.put(0x010100c3, AxmlName.taskToBackExitAnimation);
mAxmlNameMap.put(0x010100c4, AxmlName.orientation);
mAxmlNameMap.put(0x010100c5, AxmlName.keycode);
mAxmlNameMap.put(0x010100c6, AxmlName.fullDark);
mAxmlNameMap.put(0x010100c7, AxmlName.topDark);
mAxmlNameMap.put(0x010100c8, AxmlName.centerDark);
mAxmlNameMap.put(0x010100c9, AxmlName.bottomDark);
mAxmlNameMap.put(0x010100ca, AxmlName.fullBright);
mAxmlNameMap.put(0x010100cb, AxmlName.topBright);
mAxmlNameMap.put(0x010100cc, AxmlName.centerBright);
mAxmlNameMap.put(0x010100cd, AxmlName.bottomBright);
mAxmlNameMap.put(0x010100ce, AxmlName.bottomMedium);
mAxmlNameMap.put(0x010100cf, AxmlName.centerMedium);
mAxmlNameMap.put(0x010100d0, AxmlName.id);
mAxmlNameMap.put(0x010100d1, AxmlName.tag);
mAxmlNameMap.put(0x010100d2, AxmlName.scrollX);
mAxmlNameMap.put(0x010100d3, AxmlName.scrollY);
mAxmlNameMap.put(0x010100d4, AxmlName.background);
mAxmlNameMap.put(0x010100d5, AxmlName.padding);
mAxmlNameMap.put(0x010100d6, AxmlName.paddingLeft);
mAxmlNameMap.put(0x010100d7, AxmlName.paddingTop);
mAxmlNameMap.put(0x010100d8, AxmlName.paddingRight);
mAxmlNameMap.put(0x010100d9, AxmlName.paddingBottom);
mAxmlNameMap.put(0x010100da, AxmlName.focusable);
mAxmlNameMap.put(0x010100db, AxmlName.focusableInTouchMode);
mAxmlNameMap.put(0x010100dc, AxmlName.visibility);
mAxmlNameMap.put(0x010100dd, AxmlName.fitsSystemWindows);
mAxmlNameMap.put(0x010100de, AxmlName.scrollbars);
mAxmlNameMap.put(0x010100df, AxmlName.fadingEdge);
mAxmlNameMap.put(0x010100e0, AxmlName.fadingEdgeLength);
mAxmlNameMap.put(0x010100e1, AxmlName.nextFocusLeft);
mAxmlNameMap.put(0x010100e2, AxmlName.nextFocusRight);
mAxmlNameMap.put(0x010100e3, AxmlName.nextFocusUp);
mAxmlNameMap.put(0x010100e4, AxmlName.nextFocusDown);
mAxmlNameMap.put(0x010100e5, AxmlName.clickable);
mAxmlNameMap.put(0x010100e6, AxmlName.longClickable);
mAxmlNameMap.put(0x010100e7, AxmlName.saveEnabled);
mAxmlNameMap.put(0x010100e8, AxmlName.drawingCacheQuality);
mAxmlNameMap.put(0x010100e9, AxmlName.duplicateParentState);
mAxmlNameMap.put(0x010100ea, AxmlName.clipChildren);
mAxmlNameMap.put(0x010100eb, AxmlName.clipToPadding);
mAxmlNameMap.put(0x010100ec, AxmlName.layoutAnimation);
mAxmlNameMap.put(0x010100ed, AxmlName.animationCache);
mAxmlNameMap.put(0x010100ee, AxmlName.persistentDrawingCache);
mAxmlNameMap.put(0x010100ef, AxmlName.alwaysDrawnWithCache);
mAxmlNameMap.put(0x010100f0, AxmlName.addStatesFromChildren);
mAxmlNameMap.put(0x010100f1, AxmlName.descendantFocusability);
mAxmlNameMap.put(0x010100f2, AxmlName.layout);
mAxmlNameMap.put(0x010100f3, AxmlName.inflatedId);
mAxmlNameMap.put(0x010100f4, AxmlName.layout_width);
mAxmlNameMap.put(0x010100f5, AxmlName.layout_height);
mAxmlNameMap.put(0x010100f6, AxmlName.layout_margin);
mAxmlNameMap.put(0x010100f7, AxmlName.layout_marginLeft);
mAxmlNameMap.put(0x010100f8, AxmlName.layout_marginTop);
mAxmlNameMap.put(0x010100f9, AxmlName.layout_marginRight);
mAxmlNameMap.put(0x010100fa, AxmlName.layout_marginBottom);
mAxmlNameMap.put(0x010100fb, AxmlName.listSelector);
mAxmlNameMap.put(0x010100fc, AxmlName.drawSelectorOnTop);
mAxmlNameMap.put(0x010100fd, AxmlName.stackFromBottom);
mAxmlNameMap.put(0x010100fe, AxmlName.scrollingCache);
mAxmlNameMap.put(0x010100ff, AxmlName.textFilterEnabled);
mAxmlNameMap.put(0x01010100, AxmlName.transcriptMode);
mAxmlNameMap.put(0x01010101, AxmlName.cacheColorHint);
mAxmlNameMap.put(0x01010102, AxmlName.dial);
mAxmlNameMap.put(0x01010103, AxmlName.hand_hour);
mAxmlNameMap.put(0x01010104, AxmlName.hand_minute);
mAxmlNameMap.put(0x01010105, AxmlName.format);
mAxmlNameMap.put(0x01010106, AxmlName.checked);
mAxmlNameMap.put(0x01010107, AxmlName.button);
mAxmlNameMap.put(0x01010108, AxmlName.checkMark);
mAxmlNameMap.put(0x01010109, AxmlName.foreground);
mAxmlNameMap.put(0x0101010a, AxmlName.measureAllChildren);
mAxmlNameMap.put(0x0101010b, AxmlName.groupIndicator);
mAxmlNameMap.put(0x0101010c, AxmlName.childIndicator);
mAxmlNameMap.put(0x0101010d, AxmlName.indicatorLeft);
mAxmlNameMap.put(0x0101010e, AxmlName.indicatorRight);
mAxmlNameMap.put(0x0101010f, AxmlName.childIndicatorLeft);
mAxmlNameMap.put(0x01010110, AxmlName.childIndicatorRight);
mAxmlNameMap.put(0x01010111, AxmlName.childDivider);
mAxmlNameMap.put(0x01010112, AxmlName.animationDuration);
mAxmlNameMap.put(0x01010113, AxmlName.spacing);
mAxmlNameMap.put(0x01010114, AxmlName.horizontalSpacing);
mAxmlNameMap.put(0x01010115, AxmlName.verticalSpacing);
mAxmlNameMap.put(0x01010116, AxmlName.stretchMode);
mAxmlNameMap.put(0x01010117, AxmlName.columnWidth);
mAxmlNameMap.put(0x01010118, AxmlName.numColumns);
mAxmlNameMap.put(0x01010119, AxmlName.src);
mAxmlNameMap.put(0x0101011a, AxmlName.antialias);
mAxmlNameMap.put(0x0101011b, AxmlName.filter);
mAxmlNameMap.put(0x0101011c, AxmlName.dither);
mAxmlNameMap.put(0x0101011d, AxmlName.scaleType);
mAxmlNameMap.put(0x0101011e, AxmlName.adjustViewBounds);
mAxmlNameMap.put(0x0101011f, AxmlName.maxWidth);
mAxmlNameMap.put(0x01010120, AxmlName.maxHeight);
mAxmlNameMap.put(0x01010121, AxmlName.tint);
mAxmlNameMap.put(0x01010122, AxmlName.baselineAlignBottom);
mAxmlNameMap.put(0x01010123, AxmlName.cropToPadding);
mAxmlNameMap.put(0x01010124, AxmlName.textOn);
mAxmlNameMap.put(0x01010125, AxmlName.textOff);
mAxmlNameMap.put(0x01010126, AxmlName.baselineAligned);
mAxmlNameMap.put(0x01010127, AxmlName.baselineAlignedChildIndex);
mAxmlNameMap.put(0x01010128, AxmlName.weightSum);
mAxmlNameMap.put(0x01010129, AxmlName.divider);
mAxmlNameMap.put(0x0101012a, AxmlName.dividerHeight);
mAxmlNameMap.put(0x0101012b, AxmlName.choiceMode);
mAxmlNameMap.put(0x0101012c, AxmlName.itemTextAppearance);
mAxmlNameMap.put(0x0101012d, AxmlName.horizontalDivider);
mAxmlNameMap.put(0x0101012e, AxmlName.verticalDivider);
mAxmlNameMap.put(0x0101012f, AxmlName.headerBackground);
mAxmlNameMap.put(0x01010130, AxmlName.itemBackground);
mAxmlNameMap.put(0x01010131, AxmlName.itemIconDisabledAlpha);
mAxmlNameMap.put(0x01010132, AxmlName.rowHeight);
mAxmlNameMap.put(0x01010133, AxmlName.maxRows);
mAxmlNameMap.put(0x01010134, AxmlName.maxItemsPerRow);
mAxmlNameMap.put(0x01010135, AxmlName.moreIcon);
mAxmlNameMap.put(0x01010136, AxmlName.max);
mAxmlNameMap.put(0x01010137, AxmlName.progress);
mAxmlNameMap.put(0x01010138, AxmlName.secondaryProgress);
mAxmlNameMap.put(0x01010139, AxmlName.indeterminate);
mAxmlNameMap.put(0x0101013a, AxmlName.indeterminateOnly);
mAxmlNameMap.put(0x0101013b, AxmlName.indeterminateDrawable);
mAxmlNameMap.put(0x0101013c, AxmlName.progressDrawable);
mAxmlNameMap.put(0x0101013d, AxmlName.indeterminateDuration);
mAxmlNameMap.put(0x0101013e, AxmlName.indeterminateBehavior);
mAxmlNameMap.put(0x0101013f, AxmlName.minWidth);
mAxmlNameMap.put(0x01010140, AxmlName.minHeight);
mAxmlNameMap.put(0x01010141, AxmlName.interpolator);
mAxmlNameMap.put(0x01010142, AxmlName.thumb);
mAxmlNameMap.put(0x01010143, AxmlName.thumbOffset);
mAxmlNameMap.put(0x01010144, AxmlName.numStars);
mAxmlNameMap.put(0x01010145, AxmlName.rating);
mAxmlNameMap.put(0x01010146, AxmlName.stepSize);
mAxmlNameMap.put(0x01010147, AxmlName.isIndicator);
mAxmlNameMap.put(0x01010148, AxmlName.checkedButton);
mAxmlNameMap.put(0x01010149, AxmlName.stretchColumns);
mAxmlNameMap.put(0x0101014a, AxmlName.shrinkColumns);
mAxmlNameMap.put(0x0101014b, AxmlName.collapseColumns);
mAxmlNameMap.put(0x0101014c, AxmlName.layout_column);
mAxmlNameMap.put(0x0101014d, AxmlName.layout_span);
mAxmlNameMap.put(0x0101014e, AxmlName.bufferType);
mAxmlNameMap.put(0x0101014f, AxmlName.text);
mAxmlNameMap.put(0x01010150, AxmlName.hint);
mAxmlNameMap.put(0x01010151, AxmlName.textScaleX);
mAxmlNameMap.put(0x01010152, AxmlName.cursorVisible);
mAxmlNameMap.put(0x01010153, AxmlName.maxLines);
mAxmlNameMap.put(0x01010154, AxmlName.lines);
mAxmlNameMap.put(0x01010155, AxmlName.height);
mAxmlNameMap.put(0x01010156, AxmlName.minLines);
mAxmlNameMap.put(0x01010157, AxmlName.maxEms);
mAxmlNameMap.put(0x01010158, AxmlName.ems);
mAxmlNameMap.put(0x01010159, AxmlName.width);
mAxmlNameMap.put(0x0101015a, AxmlName.minEms);
mAxmlNameMap.put(0x0101015b, AxmlName.scrollHorizontally);
mAxmlNameMap.put(0x0101015c, AxmlName.password);
mAxmlNameMap.put(0x0101015d, AxmlName.singleLine);
mAxmlNameMap.put(0x0101015e, AxmlName.selectAllOnFocus);
mAxmlNameMap.put(0x0101015f, AxmlName.includeFontPadding);
mAxmlNameMap.put(0x01010160, AxmlName.maxLength);
mAxmlNameMap.put(0x01010161, AxmlName.shadowColor);
mAxmlNameMap.put(0x01010162, AxmlName.shadowDx);
mAxmlNameMap.put(0x01010163, AxmlName.shadowDy);
mAxmlNameMap.put(0x01010164, AxmlName.shadowRadius);
mAxmlNameMap.put(0x01010165, AxmlName.numeric);
mAxmlNameMap.put(0x01010166, AxmlName.digits);
mAxmlNameMap.put(0x01010167, AxmlName.phoneNumber);
mAxmlNameMap.put(0x01010168, AxmlName.inputMethod);
mAxmlNameMap.put(0x01010169, AxmlName.capitalize);
mAxmlNameMap.put(0x0101016a, AxmlName.autoText);
mAxmlNameMap.put(0x0101016b, AxmlName.editable);
mAxmlNameMap.put(0x0101016c, AxmlName.freezesText);
mAxmlNameMap.put(0x0101016d, AxmlName.drawableTop);
mAxmlNameMap.put(0x0101016e, AxmlName.drawableBottom);
mAxmlNameMap.put(0x0101016f, AxmlName.drawableLeft);
mAxmlNameMap.put(0x01010170, AxmlName.drawableRight);
mAxmlNameMap.put(0x01010171, AxmlName.drawablePadding);
mAxmlNameMap.put(0x01010172, AxmlName.completionHint);
mAxmlNameMap.put(0x01010173, AxmlName.completionHintView);
mAxmlNameMap.put(0x01010174, AxmlName.completionThreshold);
mAxmlNameMap.put(0x01010175, AxmlName.dropDownSelector);
mAxmlNameMap.put(0x01010176, AxmlName.popupBackground);
mAxmlNameMap.put(0x01010177, AxmlName.inAnimation);
mAxmlNameMap.put(0x01010178, AxmlName.outAnimation);
mAxmlNameMap.put(0x01010179, AxmlName.flipInterval);
mAxmlNameMap.put(0x0101017a, AxmlName.fillViewport);
mAxmlNameMap.put(0x0101017b, AxmlName.prompt);
mAxmlNameMap.put(0x0101017c, AxmlName.startYear);
mAxmlNameMap.put(0x0101017d, AxmlName.endYear);
mAxmlNameMap.put(0x0101017e, AxmlName.mode);
mAxmlNameMap.put(0x0101017f, AxmlName.layout_x);
mAxmlNameMap.put(0x01010180, AxmlName.layout_y);
mAxmlNameMap.put(0x01010181, AxmlName.layout_weight);
mAxmlNameMap.put(0x01010182, AxmlName.layout_toLeftOf);
mAxmlNameMap.put(0x01010183, AxmlName.layout_toRightOf);
mAxmlNameMap.put(0x01010184, AxmlName.layout_above);
mAxmlNameMap.put(0x01010185, AxmlName.layout_below);
mAxmlNameMap.put(0x01010186, AxmlName.layout_alignBaseline);
mAxmlNameMap.put(0x01010187, AxmlName.layout_alignLeft);
mAxmlNameMap.put(0x01010188, AxmlName.layout_alignTop);
mAxmlNameMap.put(0x01010189, AxmlName.layout_alignRight);
mAxmlNameMap.put(0x0101018a, AxmlName.layout_alignBottom);
mAxmlNameMap.put(0x0101018b, AxmlName.layout_alignParentLeft);
mAxmlNameMap.put(0x0101018c, AxmlName.layout_alignParentTop);
mAxmlNameMap.put(0x0101018d, AxmlName.layout_alignParentRight);
mAxmlNameMap.put(0x0101018e, AxmlName.layout_alignParentBottom);
mAxmlNameMap.put(0x0101018f, AxmlName.layout_centerInParent);
mAxmlNameMap.put(0x01010190, AxmlName.layout_centerHorizontal);
mAxmlNameMap.put(0x01010191, AxmlName.layout_centerVertical);
mAxmlNameMap.put(0x01010192, AxmlName.layout_alignWithParentIfMissing);
mAxmlNameMap.put(0x01010193, AxmlName.layout_scale);
mAxmlNameMap.put(0x01010194, AxmlName.visible);
mAxmlNameMap.put(0x01010195, AxmlName.variablePadding);
mAxmlNameMap.put(0x01010196, AxmlName.constantSize);
mAxmlNameMap.put(0x01010197, AxmlName.oneshot);
mAxmlNameMap.put(0x01010198, AxmlName.duration);
mAxmlNameMap.put(0x01010199, AxmlName.drawable);
mAxmlNameMap.put(0x0101019a, AxmlName.shape);
mAxmlNameMap.put(0x0101019b, AxmlName.innerRadiusRatio);
mAxmlNameMap.put(0x0101019c, AxmlName.thicknessRatio);
mAxmlNameMap.put(0x0101019d, AxmlName.startColor);
mAxmlNameMap.put(0x0101019e, AxmlName.endColor);
mAxmlNameMap.put(0x0101019f, AxmlName.useLevel);
mAxmlNameMap.put(0x010101a0, AxmlName.angle);
mAxmlNameMap.put(0x010101a1, AxmlName.type);
mAxmlNameMap.put(0x010101a2, AxmlName.centerX);
mAxmlNameMap.put(0x010101a3, AxmlName.centerY);
mAxmlNameMap.put(0x010101a4, AxmlName.gradientRadius);
mAxmlNameMap.put(0x010101a5, AxmlName.color);
mAxmlNameMap.put(0x010101a6, AxmlName.dashWidth);
mAxmlNameMap.put(0x010101a7, AxmlName.dashGap);
mAxmlNameMap.put(0x010101a8, AxmlName.radius);
mAxmlNameMap.put(0x010101a9, AxmlName.topLeftRadius);
mAxmlNameMap.put(0x010101aa, AxmlName.topRightRadius);
mAxmlNameMap.put(0x010101ab, AxmlName.bottomLeftRadius);
mAxmlNameMap.put(0x010101ac, AxmlName.bottomRightRadius);
mAxmlNameMap.put(0x010101ad, AxmlName.left);
mAxmlNameMap.put(0x010101ae, AxmlName.top);
mAxmlNameMap.put(0x010101af, AxmlName.right);
mAxmlNameMap.put(0x010101b0, AxmlName.bottom);
mAxmlNameMap.put(0x010101b1, AxmlName.minLevel);
mAxmlNameMap.put(0x010101b2, AxmlName.maxLevel);
mAxmlNameMap.put(0x010101b3, AxmlName.fromDegrees);
mAxmlNameMap.put(0x010101b4, AxmlName.toDegrees);
mAxmlNameMap.put(0x010101b5, AxmlName.pivotX);
mAxmlNameMap.put(0x010101b6, AxmlName.pivotY);
mAxmlNameMap.put(0x010101b7, AxmlName.insetLeft);
mAxmlNameMap.put(0x010101b8, AxmlName.insetRight);
mAxmlNameMap.put(0x010101b9, AxmlName.insetTop);
mAxmlNameMap.put(0x010101ba, AxmlName.insetBottom);
mAxmlNameMap.put(0x010101bb, AxmlName.shareInterpolator);
mAxmlNameMap.put(0x010101bc, AxmlName.fillBefore);
mAxmlNameMap.put(0x010101bd, AxmlName.fillAfter);
mAxmlNameMap.put(0x010101be, AxmlName.startOffset);
mAxmlNameMap.put(0x010101bf, AxmlName.repeatCount);
mAxmlNameMap.put(0x010101c0, AxmlName.repeatMode);
mAxmlNameMap.put(0x010101c1, AxmlName.zAdjustment);
mAxmlNameMap.put(0x010101c2, AxmlName.fromXScale);
mAxmlNameMap.put(0x010101c3, AxmlName.toXScale);
mAxmlNameMap.put(0x010101c4, AxmlName.fromYScale);
mAxmlNameMap.put(0x010101c5, AxmlName.toYScale);
mAxmlNameMap.put(0x010101c6, AxmlName.fromXDelta);
mAxmlNameMap.put(0x010101c7, AxmlName.toXDelta);
mAxmlNameMap.put(0x010101c8, AxmlName.fromYDelta);
mAxmlNameMap.put(0x010101c9, AxmlName.toYDelta);
mAxmlNameMap.put(0x010101ca, AxmlName.fromAlpha);
mAxmlNameMap.put(0x010101cb, AxmlName.toAlpha);
mAxmlNameMap.put(0x010101cc, AxmlName.delay);
mAxmlNameMap.put(0x010101cd, AxmlName.animation);
mAxmlNameMap.put(0x010101ce, AxmlName.animationOrder);
mAxmlNameMap.put(0x010101cf, AxmlName.columnDelay);
mAxmlNameMap.put(0x010101d0, AxmlName.rowDelay);
mAxmlNameMap.put(0x010101d1, AxmlName.direction);
mAxmlNameMap.put(0x010101d2, AxmlName.directionPriority);
mAxmlNameMap.put(0x010101d3, AxmlName.factor);
mAxmlNameMap.put(0x010101d4, AxmlName.cycles);
mAxmlNameMap.put(0x010101d5, AxmlName.searchMode);
mAxmlNameMap.put(0x010101d6, AxmlName.searchSuggestAuthority);
mAxmlNameMap.put(0x010101d7, AxmlName.searchSuggestPath);
mAxmlNameMap.put(0x010101d8, AxmlName.searchSuggestSelection);
mAxmlNameMap.put(0x010101d9, AxmlName.searchSuggestIntentAction);
mAxmlNameMap.put(0x010101da, AxmlName.searchSuggestIntentData);
mAxmlNameMap.put(0x010101db, AxmlName.queryActionMsg);
mAxmlNameMap.put(0x010101dc, AxmlName.suggestActionMsg);
mAxmlNameMap.put(0x010101dd, AxmlName.suggestActionMsgColumn);
mAxmlNameMap.put(0x010101de, AxmlName.menuCategory);
mAxmlNameMap.put(0x010101df, AxmlName.orderInCategory);
mAxmlNameMap.put(0x010101e0, AxmlName.checkableBehavior);
mAxmlNameMap.put(0x010101e1, AxmlName.title);
mAxmlNameMap.put(0x010101e2, AxmlName.titleCondensed);
mAxmlNameMap.put(0x010101e3, AxmlName.alphabeticShortcut);
mAxmlNameMap.put(0x010101e4, AxmlName.numericShortcut);
mAxmlNameMap.put(0x010101e5, AxmlName.checkable);
mAxmlNameMap.put(0x010101e6, AxmlName.selectable);
mAxmlNameMap.put(0x010101e7, AxmlName.orderingFromXml);
mAxmlNameMap.put(0x010101e8, AxmlName.key);
mAxmlNameMap.put(0x010101e9, AxmlName.summary);
mAxmlNameMap.put(0x010101ea, AxmlName.order);
mAxmlNameMap.put(0x010101eb, AxmlName.widgetLayout);
mAxmlNameMap.put(0x010101ec, AxmlName.dependency);
mAxmlNameMap.put(0x010101ed, AxmlName.defaultValue);
mAxmlNameMap.put(0x010101ee, AxmlName.shouldDisableView);
mAxmlNameMap.put(0x010101ef, AxmlName.summaryOn);
mAxmlNameMap.put(0x010101f0, AxmlName.summaryOff);
mAxmlNameMap.put(0x010101f1, AxmlName.disableDependentsState);
mAxmlNameMap.put(0x010101f2, AxmlName.dialogTitle);
mAxmlNameMap.put(0x010101f3, AxmlName.dialogMessage);
mAxmlNameMap.put(0x010101f4, AxmlName.dialogIcon);
mAxmlNameMap.put(0x010101f5, AxmlName.positiveButtonText);
mAxmlNameMap.put(0x010101f6, AxmlName.negativeButtonText);
mAxmlNameMap.put(0x010101f7, AxmlName.dialogLayout);
mAxmlNameMap.put(0x010101f8, AxmlName.entryValues);
mAxmlNameMap.put(0x010101f9, AxmlName.ringtoneType);
mAxmlNameMap.put(0x010101fa, AxmlName.showDefault);
mAxmlNameMap.put(0x010101fb, AxmlName.showSilent);
mAxmlNameMap.put(0x010101fc, AxmlName.scaleWidth);
mAxmlNameMap.put(0x010101fd, AxmlName.scaleHeight);
mAxmlNameMap.put(0x010101fe, AxmlName.scaleGravity);
mAxmlNameMap.put(0x010101ff, AxmlName.ignoreGravity);
mAxmlNameMap.put(0x01010200, AxmlName.foregroundGravity);
mAxmlNameMap.put(0x01010201, AxmlName.tileMode);
mAxmlNameMap.put(0x01010202, AxmlName.targetActivity);
mAxmlNameMap.put(0x01010203, AxmlName.alwaysRetainTaskState);
mAxmlNameMap.put(0x01010204, AxmlName.allowTaskReparenting);
mAxmlNameMap.put(0x01010205, AxmlName.searchButtonText);
mAxmlNameMap.put(0x01010206, AxmlName.colorForegroundInverse);
mAxmlNameMap.put(0x01010207, AxmlName.textAppearanceButton);
mAxmlNameMap.put(0x01010208, AxmlName.listSeparatorTextViewStyle);
mAxmlNameMap.put(0x01010209, AxmlName.streamType);
mAxmlNameMap.put(0x0101020a, AxmlName.clipOrientation);
mAxmlNameMap.put(0x0101020b, AxmlName.centerColor);
mAxmlNameMap.put(0x0101020c, AxmlName.minSdkVersion);
mAxmlNameMap.put(0x0101020d, AxmlName.windowFullscreen);
mAxmlNameMap.put(0x0101020e, AxmlName.unselectedAlpha);
mAxmlNameMap.put(0x0101020f, AxmlName.progressBarStyleSmallTitle);
mAxmlNameMap.put(0x01010210, AxmlName.ratingBarStyleIndicator);
mAxmlNameMap.put(0x01010211, AxmlName.apiKey);
mAxmlNameMap.put(0x01010212, AxmlName.textColorTertiary);
mAxmlNameMap.put(0x01010213, AxmlName.textColorTertiaryInverse);
mAxmlNameMap.put(0x01010214, AxmlName.listDivider);
mAxmlNameMap.put(0x01010215, AxmlName.soundEffectsEnabled);
mAxmlNameMap.put(0x01010216, AxmlName.keepScreenOn);
mAxmlNameMap.put(0x01010217, AxmlName.lineSpacingExtra);
mAxmlNameMap.put(0x01010218, AxmlName.lineSpacingMultiplier);
mAxmlNameMap.put(0x01010219, AxmlName.listChoiceIndicatorSingle);
mAxmlNameMap.put(0x0101021a, AxmlName.listChoiceIndicatorMultiple);
mAxmlNameMap.put(0x0101021b, AxmlName.versionCode);
mAxmlNameMap.put(0x0101021c, AxmlName.versionName);
mAxmlNameMap.put(0x0101021d, AxmlName.marqueeRepeatLimit);
mAxmlNameMap.put(0x0101021e, AxmlName.windowNoDisplay);
mAxmlNameMap.put(0x0101021f, AxmlName.backgroundDimEnabled);
mAxmlNameMap.put(0x01010220, AxmlName.inputType);
mAxmlNameMap.put(0x01010221, AxmlName.isDefault);
mAxmlNameMap.put(0x01010222, AxmlName.windowDisablePreview);
mAxmlNameMap.put(0x01010223, AxmlName.privateImeOptions);
mAxmlNameMap.put(0x01010224, AxmlName.editorExtras);
mAxmlNameMap.put(0x01010225, AxmlName.settingsActivity);
mAxmlNameMap.put(0x01010226, AxmlName.fastScrollEnabled);
mAxmlNameMap.put(0x01010227, AxmlName.reqTouchScreen);
mAxmlNameMap.put(0x01010228, AxmlName.reqKeyboardType);
mAxmlNameMap.put(0x01010229, AxmlName.reqHardKeyboard);
mAxmlNameMap.put(0x0101022a, AxmlName.reqNavigation);
mAxmlNameMap.put(0x0101022b, AxmlName.windowSoftInputMode);
mAxmlNameMap.put(0x0101022c, AxmlName.imeFullscreenBackground);
mAxmlNameMap.put(0x0101022d, AxmlName.noHistory);
mAxmlNameMap.put(0x0101022e, AxmlName.headerDividersEnabled);
mAxmlNameMap.put(0x0101022f, AxmlName.footerDividersEnabled);
mAxmlNameMap.put(0x01010230, AxmlName.candidatesTextStyleSpans);
mAxmlNameMap.put(0x01010231, AxmlName.smoothScrollbar);
mAxmlNameMap.put(0x01010232, AxmlName.reqFiveWayNav);
mAxmlNameMap.put(0x01010233, AxmlName.keyBackground);
mAxmlNameMap.put(0x01010234, AxmlName.keyTextSize);
mAxmlNameMap.put(0x01010235, AxmlName.labelTextSize);
mAxmlNameMap.put(0x01010236, AxmlName.keyTextColor);
mAxmlNameMap.put(0x01010237, AxmlName.keyPreviewLayout);
mAxmlNameMap.put(0x01010238, AxmlName.keyPreviewOffset);
mAxmlNameMap.put(0x01010239, AxmlName.keyPreviewHeight);
mAxmlNameMap.put(0x0101023a, AxmlName.verticalCorrection);
mAxmlNameMap.put(0x0101023b, AxmlName.popupLayout);
mAxmlNameMap.put(0x0101023c, AxmlName.state_long_pressable);
mAxmlNameMap.put(0x0101023d, AxmlName.keyWidth);
mAxmlNameMap.put(0x0101023e, AxmlName.keyHeight);
mAxmlNameMap.put(0x0101023f, AxmlName.horizontalGap);
mAxmlNameMap.put(0x01010240, AxmlName.verticalGap);
mAxmlNameMap.put(0x01010241, AxmlName.rowEdgeFlags);
mAxmlNameMap.put(0x01010242, AxmlName.codes);
mAxmlNameMap.put(0x01010243, AxmlName.popupKeyboard);
mAxmlNameMap.put(0x01010244, AxmlName.popupCharacters);
mAxmlNameMap.put(0x01010245, AxmlName.keyEdgeFlags);
mAxmlNameMap.put(0x01010246, AxmlName.isModifier);
mAxmlNameMap.put(0x01010247, AxmlName.isSticky);
mAxmlNameMap.put(0x01010248, AxmlName.isRepeatable);
mAxmlNameMap.put(0x01010249, AxmlName.iconPreview);
mAxmlNameMap.put(0x0101024a, AxmlName.keyOutputText);
mAxmlNameMap.put(0x0101024b, AxmlName.keyLabel);
mAxmlNameMap.put(0x0101024c, AxmlName.keyIcon);
mAxmlNameMap.put(0x0101024d, AxmlName.keyboardMode);
mAxmlNameMap.put(0x0101024e, AxmlName.isScrollContainer);
mAxmlNameMap.put(0x0101024f, AxmlName.fillEnabled);
mAxmlNameMap.put(0x01010250, AxmlName.updatePeriodMillis);
mAxmlNameMap.put(0x01010251, AxmlName.initialLayout);
mAxmlNameMap.put(0x01010252, AxmlName.voiceSearchMode);
mAxmlNameMap.put(0x01010253, AxmlName.voiceLanguageModel);
mAxmlNameMap.put(0x01010254, AxmlName.voicePromptText);
mAxmlNameMap.put(0x01010255, AxmlName.voiceLanguage);
mAxmlNameMap.put(0x01010256, AxmlName.voiceMaxResults);
mAxmlNameMap.put(0x01010257, AxmlName.bottomOffset);
mAxmlNameMap.put(0x01010258, AxmlName.topOffset);
mAxmlNameMap.put(0x01010259, AxmlName.allowSingleTap);
mAxmlNameMap.put(0x0101025a, AxmlName.handle);
mAxmlNameMap.put(0x0101025b, AxmlName.content);
mAxmlNameMap.put(0x0101025c, AxmlName.animateOnClick);
mAxmlNameMap.put(0x0101025d, AxmlName.configure);
mAxmlNameMap.put(0x0101025e, AxmlName.hapticFeedbackEnabled);
mAxmlNameMap.put(0x0101025f, AxmlName.innerRadius);
mAxmlNameMap.put(0x01010260, AxmlName.thickness);
mAxmlNameMap.put(0x01010261, AxmlName.sharedUserLabel);
mAxmlNameMap.put(0x01010262, AxmlName.dropDownWidth);
mAxmlNameMap.put(0x01010263, AxmlName.dropDownAnchor);
mAxmlNameMap.put(0x01010264, AxmlName.imeOptions);
mAxmlNameMap.put(0x01010265, AxmlName.imeActionLabel);
mAxmlNameMap.put(0x01010266, AxmlName.imeActionId);
mAxmlNameMap.put(0x01010268, AxmlName.imeExtractEnterAnimation);
mAxmlNameMap.put(0x01010269, AxmlName.imeExtractExitAnimation);
mAxmlNameMap.put(0x0101026a, AxmlName.tension);
mAxmlNameMap.put(0x0101026b, AxmlName.extraTension);
mAxmlNameMap.put(0x0101026c, AxmlName.anyDensity);
mAxmlNameMap.put(0x0101026d, AxmlName.searchSuggestThreshold);
mAxmlNameMap.put(0x0101026e, AxmlName.includeInGlobalSearch);
mAxmlNameMap.put(0x0101026f, AxmlName.onClick);
mAxmlNameMap.put(0x01010270, AxmlName.targetSdkVersion);
mAxmlNameMap.put(0x01010271, AxmlName.maxSdkVersion);
mAxmlNameMap.put(0x01010272, AxmlName.testOnly);
mAxmlNameMap.put(0x01010273, AxmlName.contentDescription);
mAxmlNameMap.put(0x01010274, AxmlName.gestureStrokeWidth);
mAxmlNameMap.put(0x01010275, AxmlName.gestureColor);
mAxmlNameMap.put(0x01010276, AxmlName.uncertainGestureColor);
mAxmlNameMap.put(0x01010277, AxmlName.fadeOffset);
mAxmlNameMap.put(0x01010278, AxmlName.fadeDuration);
mAxmlNameMap.put(0x01010279, AxmlName.gestureStrokeType);
mAxmlNameMap.put(0x0101027a, AxmlName.gestureStrokeLengthThreshold);
mAxmlNameMap.put(0x0101027b, AxmlName.gestureStrokeSquarenessThreshold);
mAxmlNameMap.put(0x0101027c, AxmlName.gestureStrokeAngleThreshold);
mAxmlNameMap.put(0x0101027d, AxmlName.eventsInterceptionEnabled);
mAxmlNameMap.put(0x0101027e, AxmlName.fadeEnabled);
mAxmlNameMap.put(0x0101027f, AxmlName.backupAgent);
mAxmlNameMap.put(0x01010280, AxmlName.allowBackup);
mAxmlNameMap.put(0x01010281, AxmlName.glEsVersion);
mAxmlNameMap.put(0x01010282, AxmlName.queryAfterZeroResults);
mAxmlNameMap.put(0x01010283, AxmlName.dropDownHeight);
mAxmlNameMap.put(0x01010284, AxmlName.smallScreens);
mAxmlNameMap.put(0x01010285, AxmlName.normalScreens);
mAxmlNameMap.put(0x01010286, AxmlName.largeScreens);
mAxmlNameMap.put(0x01010287, AxmlName.progressBarStyleInverse);
mAxmlNameMap.put(0x01010288, AxmlName.progressBarStyleSmallInverse);
mAxmlNameMap.put(0x01010289, AxmlName.progressBarStyleLargeInverse);
mAxmlNameMap.put(0x0101028a, AxmlName.searchSettingsDescription);
mAxmlNameMap.put(0x0101028b, AxmlName.textColorPrimaryInverseDisableOnly);
mAxmlNameMap.put(0x0101028c, AxmlName.autoUrlDetect);
mAxmlNameMap.put(0x0101028d, AxmlName.resizeable);
mAxmlNameMap.put(0x0101028e, AxmlName.required);
mAxmlNameMap.put(0x0101028f, AxmlName.accountType);
mAxmlNameMap.put(0x01010290, AxmlName.contentAuthority);
mAxmlNameMap.put(0x01010291, AxmlName.userVisible);
mAxmlNameMap.put(0x01010292, AxmlName.windowShowWallpaper);
mAxmlNameMap.put(0x01010293, AxmlName.wallpaperOpenEnterAnimation);
mAxmlNameMap.put(0x01010294, AxmlName.wallpaperOpenExitAnimation);
mAxmlNameMap.put(0x01010295, AxmlName.wallpaperCloseEnterAnimation);
mAxmlNameMap.put(0x01010296, AxmlName.wallpaperCloseExitAnimation);
mAxmlNameMap.put(0x01010297, AxmlName.wallpaperIntraOpenEnterAnimation);
mAxmlNameMap.put(0x01010298, AxmlName.wallpaperIntraOpenExitAnimation);
mAxmlNameMap.put(0x01010299, AxmlName.wallpaperIntraCloseEnterAnimation);
mAxmlNameMap.put(0x0101029a, AxmlName.wallpaperIntraCloseExitAnimation);
mAxmlNameMap.put(0x0101029b, AxmlName.supportsUploading);
mAxmlNameMap.put(0x0101029c, AxmlName.killAfterRestore);
mAxmlNameMap.put(0x0101029d, AxmlName.restoreNeedsApplication);
mAxmlNameMap.put(0x0101029e, AxmlName.smallIcon);
mAxmlNameMap.put(0x0101029f, AxmlName.accountPreferences);
mAxmlNameMap.put(0x010102a0, AxmlName.textAppearanceSearchResultSubtitle);
mAxmlNameMap.put(0x010102a1, AxmlName.textAppearanceSearchResultTitle);
mAxmlNameMap.put(0x010102a2, AxmlName.summaryColumn);
mAxmlNameMap.put(0x010102a3, AxmlName.detailColumn);
mAxmlNameMap.put(0x010102a4, AxmlName.detailSocialSummary);
mAxmlNameMap.put(0x010102a5, AxmlName.thumbnail);
mAxmlNameMap.put(0x010102a6, AxmlName.detachWallpaper);
mAxmlNameMap.put(0x010102a7, AxmlName.finishOnCloseSystemDialogs);
mAxmlNameMap.put(0x010102a8, AxmlName.scrollbarFadeDuration);
mAxmlNameMap.put(0x010102a9, AxmlName.scrollbarDefaultDelayBeforeFade);
mAxmlNameMap.put(0x010102aa, AxmlName.fadeScrollbars);
mAxmlNameMap.put(0x010102ab, AxmlName.colorBackgroundCacheHint);
mAxmlNameMap.put(0x010102ac, AxmlName.dropDownHorizontalOffset);
mAxmlNameMap.put(0x010102ad, AxmlName.dropDownVerticalOffset);
mAxmlNameMap.put(0x010102ae, AxmlName.quickContactBadgeStyleWindowSmall);
mAxmlNameMap.put(0x010102af, AxmlName.quickContactBadgeStyleWindowMedium);
mAxmlNameMap.put(0x010102b0, AxmlName.quickContactBadgeStyleWindowLarge);
mAxmlNameMap.put(0x010102b1, AxmlName.quickContactBadgeStyleSmallWindowSmall);
mAxmlNameMap.put(0x010102b2, AxmlName.quickContactBadgeStyleSmallWindowMedium);
mAxmlNameMap.put(0x010102b3, AxmlName.quickContactBadgeStyleSmallWindowLarge);
mAxmlNameMap.put(0x010102b4, AxmlName.author);
mAxmlNameMap.put(0x010102b5, AxmlName.autoStart);
mAxmlNameMap.put(0x010102b6, AxmlName.expandableListViewWhiteStyle);
mAxmlNameMap.put(0x010102b7, AxmlName.installLocation);
mAxmlNameMap.put(0x010102b8, AxmlName.vmSafeMode);
mAxmlNameMap.put(0x010102b9, AxmlName.webTextViewStyle);
mAxmlNameMap.put(0x010102ba, AxmlName.restoreAnyVersion);
mAxmlNameMap.put(0x010102bb, AxmlName.tabStripLeft);
mAxmlNameMap.put(0x010102bc, AxmlName.tabStripRight);
mAxmlNameMap.put(0x010102bd, AxmlName.tabStripEnabled);
mAxmlNameMap.put(0x010102be, AxmlName.logo);
mAxmlNameMap.put(0x010102bf, AxmlName.xlargeScreens);
mAxmlNameMap.put(0x010102c0, AxmlName.immersive);
mAxmlNameMap.put(0x010102c1, AxmlName.overScrollMode);
mAxmlNameMap.put(0x010102c2, AxmlName.overScrollHeader);
mAxmlNameMap.put(0x010102c3, AxmlName.overScrollFooter);
mAxmlNameMap.put(0x010102c4, AxmlName.filterTouchesWhenObscured);
mAxmlNameMap.put(0x010102c5, AxmlName.textSelectHandleLeft);
mAxmlNameMap.put(0x010102c6, AxmlName.textSelectHandleRight);
mAxmlNameMap.put(0x010102c7, AxmlName.textSelectHandle);
mAxmlNameMap.put(0x010102c8, AxmlName.textSelectHandleWindowStyle);
mAxmlNameMap.put(0x010102c9, AxmlName.popupAnimationStyle);
mAxmlNameMap.put(0x010102ca, AxmlName.screenSize);
mAxmlNameMap.put(0x010102cb, AxmlName.screenDensity);
mAxmlNameMap.put(0x010102cc, AxmlName.allContactsName);
mAxmlNameMap.put(0x010102cd, AxmlName.windowActionBar);
mAxmlNameMap.put(0x010102ce, AxmlName.actionBarStyle);
mAxmlNameMap.put(0x010102cf, AxmlName.navigationMode);
mAxmlNameMap.put(0x010102d0, AxmlName.displayOptions);
mAxmlNameMap.put(0x010102d1, AxmlName.subtitle);
mAxmlNameMap.put(0x010102d2, AxmlName.customNavigationLayout);
mAxmlNameMap.put(0x010102d3, AxmlName.hardwareAccelerated);
mAxmlNameMap.put(0x010102d4, AxmlName.measureWithLargestChild);
mAxmlNameMap.put(0x010102d5, AxmlName.animateFirstView);
mAxmlNameMap.put(0x010102d6, AxmlName.dropDownSpinnerStyle);
mAxmlNameMap.put(0x010102d7, AxmlName.actionDropDownStyle);
mAxmlNameMap.put(0x010102d8, AxmlName.actionButtonStyle);
mAxmlNameMap.put(0x010102d9, AxmlName.showAsAction);
mAxmlNameMap.put(0x010102da, AxmlName.previewImage);
mAxmlNameMap.put(0x010102db, AxmlName.actionModeBackground);
mAxmlNameMap.put(0x010102dc, AxmlName.actionModeCloseDrawable);
mAxmlNameMap.put(0x010102dd, AxmlName.windowActionModeOverlay);
mAxmlNameMap.put(0x010102de, AxmlName.valueFrom);
mAxmlNameMap.put(0x010102df, AxmlName.valueTo);
mAxmlNameMap.put(0x010102e0, AxmlName.valueType);
mAxmlNameMap.put(0x010102e1, AxmlName.propertyName);
mAxmlNameMap.put(0x010102e2, AxmlName.ordering);
mAxmlNameMap.put(0x010102e3, AxmlName.fragment);
mAxmlNameMap.put(0x010102e4, AxmlName.windowActionBarOverlay);
mAxmlNameMap.put(0x010102e5, AxmlName.fragmentOpenEnterAnimation);
mAxmlNameMap.put(0x010102e6, AxmlName.fragmentOpenExitAnimation);
mAxmlNameMap.put(0x010102e7, AxmlName.fragmentCloseEnterAnimation);
mAxmlNameMap.put(0x010102e8, AxmlName.fragmentCloseExitAnimation);
mAxmlNameMap.put(0x010102e9, AxmlName.fragmentFadeEnterAnimation);
mAxmlNameMap.put(0x010102ea, AxmlName.fragmentFadeExitAnimation);
mAxmlNameMap.put(0x010102eb, AxmlName.actionBarSize);
mAxmlNameMap.put(0x010102ec, AxmlName.imeSubtypeLocale);
mAxmlNameMap.put(0x010102ed, AxmlName.imeSubtypeMode);
mAxmlNameMap.put(0x010102ee, AxmlName.imeSubtypeExtraValue);
mAxmlNameMap.put(0x010102ef, AxmlName.splitMotionEvents);
mAxmlNameMap.put(0x010102f0, AxmlName.listChoiceBackgroundIndicator);
mAxmlNameMap.put(0x010102f1, AxmlName.spinnerMode);
mAxmlNameMap.put(0x010102f2, AxmlName.animateLayoutChanges);
mAxmlNameMap.put(0x010102f3, AxmlName.actionBarTabStyle);
mAxmlNameMap.put(0x010102f4, AxmlName.actionBarTabBarStyle);
mAxmlNameMap.put(0x010102f5, AxmlName.actionBarTabTextStyle);
mAxmlNameMap.put(0x010102f6, AxmlName.actionOverflowButtonStyle);
mAxmlNameMap.put(0x010102f7, AxmlName.actionModeCloseButtonStyle);
mAxmlNameMap.put(0x010102f8, AxmlName.titleTextStyle);
mAxmlNameMap.put(0x010102f9, AxmlName.subtitleTextStyle);
mAxmlNameMap.put(0x010102fa, AxmlName.iconifiedByDefault);
mAxmlNameMap.put(0x010102fb, AxmlName.actionLayout);
mAxmlNameMap.put(0x010102fc, AxmlName.actionViewClass);
mAxmlNameMap.put(0x010102fd, AxmlName.activatedBackgroundIndicator);
mAxmlNameMap.put(0x010102fe, AxmlName.state_activated);
mAxmlNameMap.put(0x010102ff, AxmlName.listPopupWindowStyle);
mAxmlNameMap.put(0x01010300, AxmlName.popupMenuStyle);
mAxmlNameMap.put(0x01010301, AxmlName.textAppearanceLargePopupMenu);
mAxmlNameMap.put(0x01010302, AxmlName.textAppearanceSmallPopupMenu);
mAxmlNameMap.put(0x01010303, AxmlName.breadCrumbTitle);
mAxmlNameMap.put(0x01010304, AxmlName.breadCrumbShortTitle);
mAxmlNameMap.put(0x01010305, AxmlName.listDividerAlertDialog);
mAxmlNameMap.put(0x01010306, AxmlName.textColorAlertDialogListItem);
mAxmlNameMap.put(0x01010307, AxmlName.loopViews);
mAxmlNameMap.put(0x01010308, AxmlName.dialogTheme);
mAxmlNameMap.put(0x01010309, AxmlName.alertDialogTheme);
mAxmlNameMap.put(0x0101030a, AxmlName.dividerVertical);
mAxmlNameMap.put(0x0101030b, AxmlName.homeAsUpIndicator);
mAxmlNameMap.put(0x0101030c, AxmlName.enterFadeDuration);
mAxmlNameMap.put(0x0101030d, AxmlName.exitFadeDuration);
mAxmlNameMap.put(0x0101030e, AxmlName.selectableItemBackground);
mAxmlNameMap.put(0x0101030f, AxmlName.autoAdvanceViewId);
mAxmlNameMap.put(0x01010310, AxmlName.useIntrinsicSizeAsMinimum);
mAxmlNameMap.put(0x01010311, AxmlName.actionModeCutDrawable);
mAxmlNameMap.put(0x01010312, AxmlName.actionModeCopyDrawable);
mAxmlNameMap.put(0x01010313, AxmlName.actionModePasteDrawable);
mAxmlNameMap.put(0x01010314, AxmlName.textEditPasteWindowLayout);
mAxmlNameMap.put(0x01010315, AxmlName.textEditNoPasteWindowLayout);
mAxmlNameMap.put(0x01010316, AxmlName.textIsSelectable);
mAxmlNameMap.put(0x01010317, AxmlName.windowEnableSplitTouch);
mAxmlNameMap.put(0x01010318, AxmlName.indeterminateProgressStyle);
mAxmlNameMap.put(0x01010319, AxmlName.progressBarPadding);
mAxmlNameMap.put(0x0101031a, AxmlName.animationResolution);
mAxmlNameMap.put(0x0101031b, AxmlName.state_accelerated);
mAxmlNameMap.put(0x0101031c, AxmlName.baseline);
mAxmlNameMap.put(0x0101031d, AxmlName.homeLayout);
mAxmlNameMap.put(0x0101031e, AxmlName.opacity);
mAxmlNameMap.put(0x0101031f, AxmlName.alpha);
mAxmlNameMap.put(0x01010320, AxmlName.transformPivotX);
mAxmlNameMap.put(0x01010321, AxmlName.transformPivotY);
mAxmlNameMap.put(0x01010322, AxmlName.translationX);
mAxmlNameMap.put(0x01010323, AxmlName.translationY);
mAxmlNameMap.put(0x01010324, AxmlName.scaleX);
mAxmlNameMap.put(0x01010325, AxmlName.scaleY);
mAxmlNameMap.put(0x01010326, AxmlName.rotation);
mAxmlNameMap.put(0x01010327, AxmlName.rotationX);
mAxmlNameMap.put(0x01010328, AxmlName.rotationY);
mAxmlNameMap.put(0x01010329, AxmlName.showDividers);
mAxmlNameMap.put(0x0101032a, AxmlName.dividerPadding);
mAxmlNameMap.put(0x0101032b, AxmlName.borderlessButtonStyle);
mAxmlNameMap.put(0x0101032c, AxmlName.dividerHorizontal);
mAxmlNameMap.put(0x0101032d, AxmlName.itemPadding);
mAxmlNameMap.put(0x0101032e, AxmlName.buttonBarStyle);
mAxmlNameMap.put(0x0101032f, AxmlName.buttonBarButtonStyle);
mAxmlNameMap.put(0x01010330, AxmlName.segmentedButtonStyle);
mAxmlNameMap.put(0x01010331, AxmlName.staticWallpaperPreview);
mAxmlNameMap.put(0x01010332, AxmlName.allowParallelSyncs);
mAxmlNameMap.put(0x01010333, AxmlName.isAlwaysSyncable);
mAxmlNameMap.put(0x01010334, AxmlName.verticalScrollbarPosition);
mAxmlNameMap.put(0x01010335, AxmlName.fastScrollAlwaysVisible);
mAxmlNameMap.put(0x01010336, AxmlName.fastScrollThumbDrawable);
mAxmlNameMap.put(0x01010337, AxmlName.fastScrollPreviewBackgroundLeft);
mAxmlNameMap.put(0x01010338, AxmlName.fastScrollPreviewBackgroundRight);
mAxmlNameMap.put(0x01010339, AxmlName.fastScrollTrackDrawable);
mAxmlNameMap.put(0x0101033a, AxmlName.fastScrollOverlayPosition);
mAxmlNameMap.put(0x0101033b, AxmlName.customTokens);
mAxmlNameMap.put(0x0101033c, AxmlName.nextFocusForward);
mAxmlNameMap.put(0x0101033d, AxmlName.firstDayOfWeek);
mAxmlNameMap.put(0x0101033e, AxmlName.showWeekNumber);
mAxmlNameMap.put(0x0101033f, AxmlName.minDate);
mAxmlNameMap.put(0x01010340, AxmlName.maxDate);
mAxmlNameMap.put(0x01010341, AxmlName.shownWeekCount);
mAxmlNameMap.put(0x01010342, AxmlName.selectedWeekBackgroundColor);
mAxmlNameMap.put(0x01010343, AxmlName.focusedMonthDateColor);
mAxmlNameMap.put(0x01010344, AxmlName.unfocusedMonthDateColor);
mAxmlNameMap.put(0x01010345, AxmlName.weekNumberColor);
mAxmlNameMap.put(0x01010346, AxmlName.weekSeparatorLineColor);
mAxmlNameMap.put(0x01010347, AxmlName.selectedDateVerticalBar);
mAxmlNameMap.put(0x01010348, AxmlName.weekDayTextAppearance);
mAxmlNameMap.put(0x01010349, AxmlName.dateTextAppearance);
mAxmlNameMap.put(0x0101034a, AxmlName.solidColor);
mAxmlNameMap.put(0x0101034b, AxmlName.spinnersShown);
mAxmlNameMap.put(0x0101034c, AxmlName.calendarViewShown);
mAxmlNameMap.put(0x0101034d, AxmlName.state_multiline);
mAxmlNameMap.put(0x0101034e, AxmlName.detailsElementBackground);
mAxmlNameMap.put(0x0101034f, AxmlName.textColorHighlightInverse);
mAxmlNameMap.put(0x01010350, AxmlName.textColorLinkInverse);
mAxmlNameMap.put(0x01010351, AxmlName.editTextColor);
mAxmlNameMap.put(0x01010352, AxmlName.editTextBackground);
mAxmlNameMap.put(0x01010353, AxmlName.horizontalScrollViewStyle);
mAxmlNameMap.put(0x01010354, AxmlName.layerType);
mAxmlNameMap.put(0x01010355, AxmlName.alertDialogIcon);
mAxmlNameMap.put(0x01010356, AxmlName.windowMinWidthMajor);
mAxmlNameMap.put(0x01010357, AxmlName.windowMinWidthMinor);
mAxmlNameMap.put(0x01010358, AxmlName.queryHint);
mAxmlNameMap.put(0x01010359, AxmlName.fastScrollTextColor);
mAxmlNameMap.put(0x0101035a, AxmlName.largeHeap);
mAxmlNameMap.put(0x0101035b, AxmlName.windowCloseOnTouchOutside);
mAxmlNameMap.put(0x0101035c, AxmlName.datePickerStyle);
mAxmlNameMap.put(0x0101035d, AxmlName.calendarViewStyle);
mAxmlNameMap.put(0x0101035e, AxmlName.textEditSidePasteWindowLayout);
mAxmlNameMap.put(0x0101035f, AxmlName.textEditSideNoPasteWindowLayout);
mAxmlNameMap.put(0x01010360, AxmlName.actionMenuTextAppearance);
mAxmlNameMap.put(0x01010361, AxmlName.actionMenuTextColor);
mAxmlNameMap.put(0x01010362, AxmlName.textCursorDrawable);
mAxmlNameMap.put(0x01010363, AxmlName.resizeMode);
mAxmlNameMap.put(0x01010364, AxmlName.requiresSmallestWidthDp);
mAxmlNameMap.put(0x01010365, AxmlName.compatibleWidthLimitDp);
mAxmlNameMap.put(0x01010366, AxmlName.largestWidthLimitDp);
mAxmlNameMap.put(0x01010367, AxmlName.state_hovered);
mAxmlNameMap.put(0x01010368, AxmlName.state_drag_can_accept);
mAxmlNameMap.put(0x01010369, AxmlName.state_drag_hovered);
mAxmlNameMap.put(0x0101036a, AxmlName.stopWithTask);
mAxmlNameMap.put(0x0101036b, AxmlName.switchTextOn);
mAxmlNameMap.put(0x0101036c, AxmlName.switchTextOff);
mAxmlNameMap.put(0x0101036d, AxmlName.switchPreferenceStyle);
mAxmlNameMap.put(0x0101036e, AxmlName.switchTextAppearance);
mAxmlNameMap.put(0x0101036f, AxmlName.track);
mAxmlNameMap.put(0x01010370, AxmlName.switchMinWidth);
mAxmlNameMap.put(0x01010371, AxmlName.switchPadding);
mAxmlNameMap.put(0x01010372, AxmlName.thumbTextPadding);
mAxmlNameMap.put(0x01010373, AxmlName.textSuggestionsWindowStyle);
mAxmlNameMap.put(0x01010374, AxmlName.textEditSuggestionItemLayout);
mAxmlNameMap.put(0x01010375, AxmlName.rowCount);
mAxmlNameMap.put(0x01010376, AxmlName.rowOrderPreserved);
mAxmlNameMap.put(0x01010377, AxmlName.columnCount);
mAxmlNameMap.put(0x01010378, AxmlName.columnOrderPreserved);
mAxmlNameMap.put(0x01010379, AxmlName.useDefaultMargins);
mAxmlNameMap.put(0x0101037a, AxmlName.alignmentMode);
mAxmlNameMap.put(0x0101037b, AxmlName.layout_row);
mAxmlNameMap.put(0x0101037c, AxmlName.layout_rowSpan);
mAxmlNameMap.put(0x0101037d, AxmlName.layout_columnSpan);
mAxmlNameMap.put(0x0101037e, AxmlName.actionModeSelectAllDrawable);
mAxmlNameMap.put(0x0101037f, AxmlName.isAuxiliary);
mAxmlNameMap.put(0x01010380, AxmlName.accessibilityEventTypes);
mAxmlNameMap.put(0x01010381, AxmlName.packageNames);
mAxmlNameMap.put(0x01010382, AxmlName.accessibilityFeedbackType);
mAxmlNameMap.put(0x01010383, AxmlName.notificationTimeout);
mAxmlNameMap.put(0x01010384, AxmlName.accessibilityFlags);
mAxmlNameMap.put(0x01010385, AxmlName.canRetrieveWindowContent);
mAxmlNameMap.put(0x01010386, AxmlName.listPreferredItemHeightLarge);
mAxmlNameMap.put(0x01010387, AxmlName.listPreferredItemHeightSmall);
mAxmlNameMap.put(0x01010388, AxmlName.actionBarSplitStyle);
mAxmlNameMap.put(0x01010389, AxmlName.actionProviderClass);
mAxmlNameMap.put(0x0101038a, AxmlName.backgroundStacked);
mAxmlNameMap.put(0x0101038b, AxmlName.backgroundSplit);
mAxmlNameMap.put(0x0101038c, AxmlName.textAllCaps);
mAxmlNameMap.put(0x0101038d, AxmlName.colorPressedHighlight);
mAxmlNameMap.put(0x0101038e, AxmlName.colorLongPressedHighlight);
mAxmlNameMap.put(0x0101038f, AxmlName.colorFocusedHighlight);
mAxmlNameMap.put(0x01010390, AxmlName.colorActivatedHighlight);
mAxmlNameMap.put(0x01010391, AxmlName.colorMultiSelectHighlight);
mAxmlNameMap.put(0x01010392, AxmlName.drawableStart);
mAxmlNameMap.put(0x01010393, AxmlName.drawableEnd);
mAxmlNameMap.put(0x01010394, AxmlName.actionModeStyle);
mAxmlNameMap.put(0x01010395, AxmlName.minResizeWidth);
mAxmlNameMap.put(0x01010396, AxmlName.minResizeHeight);
mAxmlNameMap.put(0x01010397, AxmlName.actionBarWidgetTheme);
mAxmlNameMap.put(0x01010398, AxmlName.uiOptions);
mAxmlNameMap.put(0x01010399, AxmlName.subtypeLocale);
mAxmlNameMap.put(0x0101039a, AxmlName.subtypeExtraValue);
mAxmlNameMap.put(0x0101039b, AxmlName.actionBarDivider);
mAxmlNameMap.put(0x0101039c, AxmlName.actionBarItemBackground);
mAxmlNameMap.put(0x0101039d, AxmlName.actionModeSplitBackground);
mAxmlNameMap.put(0x0101039e, AxmlName.textAppearanceListItem);
mAxmlNameMap.put(0x0101039f, AxmlName.textAppearanceListItemSmall);
mAxmlNameMap.put(0x010103a0, AxmlName.targetDescriptions);
mAxmlNameMap.put(0x010103a1, AxmlName.directionDescriptions);
mAxmlNameMap.put(0x010103a2, AxmlName.overridesImplicitlyEnabledSubtype);
mAxmlNameMap.put(0x010103a3, AxmlName.listPreferredItemPaddingLeft);
mAxmlNameMap.put(0x010103a4, AxmlName.listPreferredItemPaddingRight);
mAxmlNameMap.put(0x010103a5, AxmlName.requiresFadingEdge);
mAxmlNameMap.put(0x010103a6, AxmlName.publicKey);
mAxmlNameMap.put(0x010103a7, AxmlName.parentActivityName);
mAxmlNameMap.put(0x010103a9, AxmlName.isolatedProcess);
mAxmlNameMap.put(0x010103aa, AxmlName.importantForAccessibility);
mAxmlNameMap.put(0x010103ab, AxmlName.keyboardLayout);
mAxmlNameMap.put(0x010103ac, AxmlName.fontFamily);
mAxmlNameMap.put(0x010103ad, AxmlName.mediaRouteButtonStyle);
mAxmlNameMap.put(0x010103ae, AxmlName.mediaRouteTypes);
mAxmlNameMap.put(0x010103af, AxmlName.supportsRtl);
mAxmlNameMap.put(0x010103b0, AxmlName.textDirection);
mAxmlNameMap.put(0x010103b1, AxmlName.textAlignment);
mAxmlNameMap.put(0x010103b2, AxmlName.layoutDirection);
mAxmlNameMap.put(0x010103b3, AxmlName.paddingStart);
mAxmlNameMap.put(0x010103b4, AxmlName.paddingEnd);
mAxmlNameMap.put(0x010103b5, AxmlName.layout_marginStart);
mAxmlNameMap.put(0x010103b6, AxmlName.layout_marginEnd);
mAxmlNameMap.put(0x010103b7, AxmlName.layout_toStartOf);
mAxmlNameMap.put(0x010103b8, AxmlName.layout_toEndOf);
mAxmlNameMap.put(0x010103b9, AxmlName.layout_alignStart);
mAxmlNameMap.put(0x010103ba, AxmlName.layout_alignEnd);
mAxmlNameMap.put(0x010103bb, AxmlName.layout_alignParentStart);
mAxmlNameMap.put(0x010103bc, AxmlName.layout_alignParentEnd);
mAxmlNameMap.put(0x010103bd, AxmlName.listPreferredItemPaddingStart);
mAxmlNameMap.put(0x010103be, AxmlName.listPreferredItemPaddingEnd);
mAxmlNameMap.put(0x010103bf, AxmlName.singleUser);
mAxmlNameMap.put(0x010103c0, AxmlName.presentationTheme);
mAxmlNameMap.put(0x010103c1, AxmlName.subtypeId);
mAxmlNameMap.put(0x010103c2, AxmlName.initialKeyguardLayout);
mAxmlNameMap.put(0x010103c4, AxmlName.widgetCategory);
mAxmlNameMap.put(0x010103c5, AxmlName.permissionGroupFlags);
mAxmlNameMap.put(0x010103c6, AxmlName.labelFor);
mAxmlNameMap.put(0x010103c7, AxmlName.permissionFlags);
mAxmlNameMap.put(0x010103c8, AxmlName.checkedTextViewStyle);
mAxmlNameMap.put(0x010103c9, AxmlName.showOnLockScreen);
mAxmlNameMap.put(0x010103ca, AxmlName.format12Hour);
mAxmlNameMap.put(0x010103cb, AxmlName.format24Hour);
mAxmlNameMap.put(0x010103cc, AxmlName.timeZone);
mAxmlNameMap.put(0x010103cd, AxmlName.mipMap);
mAxmlNameMap.put(0x010103ce, AxmlName.mirrorForRtl);
mAxmlNameMap.put(0x010103cf, AxmlName.windowOverscan);
mAxmlNameMap.put(0x010103d0, AxmlName.requiredForAllUsers);
mAxmlNameMap.put(0x010103d1, AxmlName.indicatorStart);
mAxmlNameMap.put(0x010103d2, AxmlName.indicatorEnd);
mAxmlNameMap.put(0x010103d3, AxmlName.childIndicatorStart);
mAxmlNameMap.put(0x010103d4, AxmlName.childIndicatorEnd);
mAxmlNameMap.put(0x010103d5, AxmlName.restrictedAccountType);
mAxmlNameMap.put(0x010103d6, AxmlName.requiredAccountType);
mAxmlNameMap.put(0x010103d7, AxmlName.canRequestTouchExplorationMode);
mAxmlNameMap.put(0x010103d8, AxmlName.canRequestEnhancedWebAccessibility);
mAxmlNameMap.put(0x010103d9, AxmlName.canRequestFilterKeyEvents);
mAxmlNameMap.put(0x010103da, AxmlName.layoutMode);
mAxmlNameMap.put(0x010103db, AxmlName.keySet);
mAxmlNameMap.put(0x010103dc, AxmlName.targetId);
mAxmlNameMap.put(0x010103dd, AxmlName.fromScene);
mAxmlNameMap.put(0x010103de, AxmlName.toScene);
mAxmlNameMap.put(0x010103df, AxmlName.transition);
mAxmlNameMap.put(0x010103e0, AxmlName.transitionOrdering);
mAxmlNameMap.put(0x010103e1, AxmlName.fadingMode);
mAxmlNameMap.put(0x010103e2, AxmlName.startDelay);
mAxmlNameMap.put(0x010103e3, AxmlName.ssp);
mAxmlNameMap.put(0x010103e4, AxmlName.sspPrefix);
mAxmlNameMap.put(0x010103e5, AxmlName.sspPattern);
mAxmlNameMap.put(0x010103e6, AxmlName.addPrintersActivity);
mAxmlNameMap.put(0x010103e7, AxmlName.vendor);
mAxmlNameMap.put(0x010103e8, AxmlName.category);
mAxmlNameMap.put(0x010103e9, AxmlName.isAsciiCapable);
mAxmlNameMap.put(0x010103ea, AxmlName.autoMirrored);
mAxmlNameMap.put(0x010103eb, AxmlName.supportsSwitchingToNextInputMethod);
mAxmlNameMap.put(0x010103ec, AxmlName.requireDeviceUnlock);
mAxmlNameMap.put(0x010103ed, AxmlName.apduServiceBanner);
mAxmlNameMap.put(0x010103ee, AxmlName.accessibilityLiveRegion);
mAxmlNameMap.put(0x010103ef, AxmlName.windowTranslucentStatus);
mAxmlNameMap.put(0x010103f0, AxmlName.windowTranslucentNavigation);
mAxmlNameMap.put(0x10103f1, AxmlName.advancedPrintOptionsActivity);
mAxmlNameMap.put(0x10103f2, AxmlName.banner);
mAxmlNameMap.put(0x10103f3, AxmlName.windowSwipeToDismiss);
mAxmlNameMap.put(0x10103f4, AxmlName.isGame);
mAxmlNameMap.put(0x10103f5, AxmlName.allowEmbedded);
mAxmlNameMap.put(0x10103f6, AxmlName.setupActivity);
mAxmlNameMap.put(0x010103f7, AxmlName.fastScrollStyle);
mAxmlNameMap.put(0x010103f8, AxmlName.windowContentTransitions);
mAxmlNameMap.put(0x010103f9, AxmlName.windowContentTransitionManager);
mAxmlNameMap.put(0x010103fa, AxmlName.translationZ);
mAxmlNameMap.put(0x010103fb, AxmlName.tintMode);
mAxmlNameMap.put(0x010103fc, AxmlName.controlX1);
mAxmlNameMap.put(0x010103fd, AxmlName.controlY1);
mAxmlNameMap.put(0x010103fe, AxmlName.controlX2);
mAxmlNameMap.put(0x010103ff, AxmlName.controlY2);
mAxmlNameMap.put(0x01010400, AxmlName.transitionName);
mAxmlNameMap.put(0x01010401, AxmlName.transitionGroup);
mAxmlNameMap.put(0x01010402, AxmlName.viewportWidth);
mAxmlNameMap.put(0x01010403, AxmlName.viewportHeight);
mAxmlNameMap.put(0x01010404, AxmlName.fillColor);
mAxmlNameMap.put(0x01010405, AxmlName.pathData);
mAxmlNameMap.put(0x01010406, AxmlName.strokeColor);
mAxmlNameMap.put(0x01010407, AxmlName.strokeWidth);
mAxmlNameMap.put(0x01010408, AxmlName.trimPathStart);
mAxmlNameMap.put(0x01010409, AxmlName.trimPathEnd);
mAxmlNameMap.put(0x0101040a, AxmlName.trimPathOffset);
mAxmlNameMap.put(0x0101040b, AxmlName.strokeLineCap);
mAxmlNameMap.put(0x0101040c, AxmlName.strokeLineJoin);
mAxmlNameMap.put(0x0101040d, AxmlName.strokeMiterLimit);
mAxmlNameMap.put(0x01010429, AxmlName.colorControlNormal);
mAxmlNameMap.put(0x0101042a, AxmlName.colorControlActivated);
mAxmlNameMap.put(0x0101042b, AxmlName.colorButtonNormal);
mAxmlNameMap.put(0x0101042c, AxmlName.colorControlHighlight);
mAxmlNameMap.put(0x0101042d, AxmlName.persistableMode);
mAxmlNameMap.put(0x0101042e, AxmlName.titleTextAppearance);
mAxmlNameMap.put(0x0101042f, AxmlName.subtitleTextAppearance);
mAxmlNameMap.put(0x01010430, AxmlName.slideEdge);
mAxmlNameMap.put(0x01010431, AxmlName.actionBarTheme);
mAxmlNameMap.put(0x01010432, AxmlName.textAppearanceListItemSecondary);
mAxmlNameMap.put(0x01010433, AxmlName.colorPrimary);
mAxmlNameMap.put(0x01010434, AxmlName.colorPrimaryDark);
mAxmlNameMap.put(0x01010435, AxmlName.colorAccent);
mAxmlNameMap.put(0x01010436, AxmlName.nestedScrollingEnabled);
mAxmlNameMap.put(0x01010437, AxmlName.windowEnterTransition);
mAxmlNameMap.put(0x01010438, AxmlName.windowExitTransition);
mAxmlNameMap.put(0x01010439, AxmlName.windowSharedElementEnterTransition);
mAxmlNameMap.put(0x0101043a, AxmlName.windowSharedElementExitTransition);
mAxmlNameMap.put(0x0101043b, AxmlName.windowAllowReturnTransitionOverlap);
mAxmlNameMap.put(0x0101043c, AxmlName.windowAllowEnterTransitionOverlap);
mAxmlNameMap.put(0x0101043d, AxmlName.sessionService);
mAxmlNameMap.put(0x0101043e, AxmlName.stackViewStyle);
mAxmlNameMap.put(0x0101043f, AxmlName.switchStyle);
mAxmlNameMap.put(0x01010440, AxmlName.elevation);
mAxmlNameMap.put(0x01010441, AxmlName.excludeId);
mAxmlNameMap.put(0x01010442, AxmlName.excludeClass);
mAxmlNameMap.put(0x01010443, AxmlName.hideOnContentScroll);
mAxmlNameMap.put(0x01010444, AxmlName.actionOverflowMenuStyle);
mAxmlNameMap.put(0x01010445, AxmlName.documentLaunchMode);
mAxmlNameMap.put(0x01010446, AxmlName.maxRecents);
mAxmlNameMap.put(0x01010447, AxmlName.autoRemoveFromRecents);
mAxmlNameMap.put(0x01010448, AxmlName.stateListAnimator);
mAxmlNameMap.put(0x01010449, AxmlName.toId);
mAxmlNameMap.put(0x0101044a, AxmlName.fromId);
mAxmlNameMap.put(0x0101044b, AxmlName.reversible);
mAxmlNameMap.put(0x0101044c, AxmlName.splitTrack);
mAxmlNameMap.put(0x0101044d, AxmlName.targetName);
mAxmlNameMap.put(0x0101044e, AxmlName.excludeName);
mAxmlNameMap.put(0x0101044f, AxmlName.matchOrder);
mAxmlNameMap.put(0x01010450, AxmlName.windowDrawsSystemBarBackgrounds);
mAxmlNameMap.put(0x01010451, AxmlName.statusBarColor);
mAxmlNameMap.put(0x01010452, AxmlName.navigationBarColor);
mAxmlNameMap.put(0x01010453, AxmlName.contentInsetStart);
mAxmlNameMap.put(0x01010454, AxmlName.contentInsetEnd);
mAxmlNameMap.put(0x01010455, AxmlName.contentInsetLeft);
mAxmlNameMap.put(0x01010456, AxmlName.contentInsetRight);
mAxmlNameMap.put(0x01010457, AxmlName.paddingMode);
mAxmlNameMap.put(0x01010458, AxmlName.layout_rowWeight);
mAxmlNameMap.put(0x01010459, AxmlName.layout_columnWeight);
mAxmlNameMap.put(0x0101045a, AxmlName.translateX);
mAxmlNameMap.put(0x0101045b, AxmlName.translateY);
mAxmlNameMap.put(0x0101045c, AxmlName.selectableItemBackgroundBorderless);
mAxmlNameMap.put(0x0101045d, AxmlName.elegantTextHeight);
mAxmlNameMap.put(0x0101045e, AxmlName.searchKeyphraseId);
mAxmlNameMap.put(0x0101045f, AxmlName.searchKeyphrase);
mAxmlNameMap.put(0x01010460, AxmlName.searchKeyphraseSupportedLocales);
mAxmlNameMap.put(0x01010461, AxmlName.windowTransitionBackgroundFadeDuration);
mAxmlNameMap.put(0x01010462, AxmlName.overlapAnchor);
mAxmlNameMap.put(0x01010463, AxmlName.progressTint);
mAxmlNameMap.put(0x01010464, AxmlName.progressTintMode);
mAxmlNameMap.put(0x01010465, AxmlName.progressBackgroundTint);
mAxmlNameMap.put(0x01010466, AxmlName.progressBackgroundTintMode);
mAxmlNameMap.put(0x01010467, AxmlName.secondaryProgressTint);
mAxmlNameMap.put(0x01010468, AxmlName.secondaryProgressTintMode);
mAxmlNameMap.put(0x01010469, AxmlName.indeterminateTint);
mAxmlNameMap.put(0x0101046a, AxmlName.indeterminateTintMode);
mAxmlNameMap.put(0x0101046b, AxmlName.backgroundTint);
mAxmlNameMap.put(0x0101046c, AxmlName.backgroundTintMode);
mAxmlNameMap.put(0x0101046d, AxmlName.foregroundTint);
mAxmlNameMap.put(0x0101046e, AxmlName.foregroundTintMode);
mAxmlNameMap.put(0x0101046f, AxmlName.buttonTint);
mAxmlNameMap.put(0x01010470, AxmlName.buttonTintMode);
mAxmlNameMap.put(0x01010471, AxmlName.thumbTint);
mAxmlNameMap.put(0x01010472, AxmlName.thumbTintMode);
mAxmlNameMap.put(0x01010473, AxmlName.fullBackupOnly);
mAxmlNameMap.put(0x01010474, AxmlName.propertyXName);
mAxmlNameMap.put(0x01010475, AxmlName.propertyYName);
mAxmlNameMap.put(0x01010476, AxmlName.relinquishTaskIdentity);
mAxmlNameMap.put(0x01010477, AxmlName.tileModeX);
mAxmlNameMap.put(0x01010478, AxmlName.tileModeY);
mAxmlNameMap.put(0x01010479, AxmlName.actionModeShareDrawable);
mAxmlNameMap.put(0x0101047a, AxmlName.actionModeFindDrawable);
mAxmlNameMap.put(0x0101047b, AxmlName.actionModeWebSearchDrawable);
mAxmlNameMap.put(0x0101047c, AxmlName.transitionVisibilityMode);
mAxmlNameMap.put(0x0101047d, AxmlName.minimumHorizontalAngle);
mAxmlNameMap.put(0x0101047e, AxmlName.minimumVerticalAngle);
mAxmlNameMap.put(0x0101047f, AxmlName.maximumAngle);
mAxmlNameMap.put(0x01010480, AxmlName.searchViewStyle);
mAxmlNameMap.put(0x01010481, AxmlName.closeIcon);
mAxmlNameMap.put(0x01010482, AxmlName.goIcon);
mAxmlNameMap.put(0x01010483, AxmlName.searchIcon);
mAxmlNameMap.put(0x01010484, AxmlName.voiceIcon);
mAxmlNameMap.put(0x01010485, AxmlName.commitIcon);
mAxmlNameMap.put(0x01010486, AxmlName.suggestionRowLayout);
mAxmlNameMap.put(0x01010487, AxmlName.queryBackground);
mAxmlNameMap.put(0x01010488, AxmlName.submitBackground);
mAxmlNameMap.put(0x01010489, AxmlName.buttonBarPositiveButtonStyle);
mAxmlNameMap.put(0x0101048a, AxmlName.buttonBarNeutralButtonStyle);
mAxmlNameMap.put(0x0101048b, AxmlName.buttonBarNegativeButtonStyle);
mAxmlNameMap.put(0x0101048c, AxmlName.popupElevation);
mAxmlNameMap.put(0x0101048d, AxmlName.actionBarPopupTheme);
mAxmlNameMap.put(0x0101048e, AxmlName.multiArch);
mAxmlNameMap.put(0x0101048f, AxmlName.touchscreenBlocksFocus);
mAxmlNameMap.put(0x01010490, AxmlName.windowElevation);
mAxmlNameMap.put(0x01010491, AxmlName.launchTaskBehindTargetAnimation);
mAxmlNameMap.put(0x01010492, AxmlName.launchTaskBehindSourceAnimation);
mAxmlNameMap.put(0x01010493, AxmlName.restrictionType);
mAxmlNameMap.put(0x01010494, AxmlName.dayOfWeekBackground);
mAxmlNameMap.put(0x01010495, AxmlName.dayOfWeekTextAppearance);
mAxmlNameMap.put(0x01010496, AxmlName.headerMonthTextAppearance);
mAxmlNameMap.put(0x01010497, AxmlName.headerDayOfMonthTextAppearance);
mAxmlNameMap.put(0x01010498, AxmlName.headerYearTextAppearance);
mAxmlNameMap.put(0x01010499, AxmlName.yearListItemTextAppearance);
mAxmlNameMap.put(0x0101049a, AxmlName.yearListSelectorColor);
mAxmlNameMap.put(0x0101049b, AxmlName.calendarTextColor);
mAxmlNameMap.put(0x0101049c, AxmlName.recognitionService);
mAxmlNameMap.put(0x0101049d, AxmlName.timePickerStyle);
mAxmlNameMap.put(0x0101049e, AxmlName.timePickerDialogTheme);
mAxmlNameMap.put(0x0101049f, AxmlName.headerTimeTextAppearance);
mAxmlNameMap.put(0x010104a0, AxmlName.headerAmPmTextAppearance);
mAxmlNameMap.put(0x010104a1, AxmlName.numbersTextColor);
mAxmlNameMap.put(0x010104a2, AxmlName.numbersBackgroundColor);
mAxmlNameMap.put(0x010104a3, AxmlName.numbersSelectorColor);
mAxmlNameMap.put(0x010104a4, AxmlName.amPmTextColor);
mAxmlNameMap.put(0x010104a5, AxmlName.amPmBackgroundColor);
mAxmlNameMap.put(0x010104a6, AxmlName.searchKeyphraseRecognitionFlags);
mAxmlNameMap.put(0x010104a7, AxmlName.checkMarkTint);
mAxmlNameMap.put(0x010104a8, AxmlName.checkMarkTintMode);
mAxmlNameMap.put(0x010104a9, AxmlName.popupTheme);
mAxmlNameMap.put(0x010104aa, AxmlName.toolbarStyle);
mAxmlNameMap.put(0x010104ab, AxmlName.windowClipToOutline);
mAxmlNameMap.put(0x010104ac, AxmlName.datePickerDialogTheme);
mAxmlNameMap.put(0x010104ad, AxmlName.showText);
mAxmlNameMap.put(0x010104ae, AxmlName.windowReturnTransition);
mAxmlNameMap.put(0x010104af, AxmlName.windowReenterTransition);
mAxmlNameMap.put(0x010104b0, AxmlName.windowSharedElementReturnTransition);
mAxmlNameMap.put(0x010104b1, AxmlName.windowSharedElementReenterTransition);
mAxmlNameMap.put(0x010104b2, AxmlName.resumeWhilePausing);
mAxmlNameMap.put(0x010104b3, AxmlName.datePickerMode);
mAxmlNameMap.put(0x010104b4, AxmlName.timePickerMode);
mAxmlNameMap.put(0x010104b5, AxmlName.inset);
mAxmlNameMap.put(0x010104b6, AxmlName.letterSpacing);
mAxmlNameMap.put(0x010104b7, AxmlName.fontFeatureSettings);
mAxmlNameMap.put(0x010104b8, AxmlName.outlineProvider);
mAxmlNameMap.put(0x010104b9, AxmlName.contentAgeHint);
mAxmlNameMap.put(0x010104ba, AxmlName.country);
mAxmlNameMap.put(0x010104bb, AxmlName.windowSharedElementsUseOverlay);
mAxmlNameMap.put(0x010104bc, AxmlName.reparent);
mAxmlNameMap.put(0x010104bd, AxmlName.reparentWithOverlay);
mAxmlNameMap.put(0x010104be, AxmlName.ambientShadowAlpha);
mAxmlNameMap.put(0x010104bf, AxmlName.spotShadowAlpha);
mAxmlNameMap.put(0x010104c0, AxmlName.navigationIcon);
mAxmlNameMap.put(0x010104c1, AxmlName.navigationContentDescription);
mAxmlNameMap.put(0x010104c2, AxmlName.fragmentExitTransition);
mAxmlNameMap.put(0x010104c3, AxmlName.fragmentEnterTransition);
mAxmlNameMap.put(0x010104c4, AxmlName.fragmentSharedElementEnterTransition);
mAxmlNameMap.put(0x010104c5, AxmlName.fragmentReturnTransition);
mAxmlNameMap.put(0x010104c6, AxmlName.fragmentSharedElementReturnTransition);
mAxmlNameMap.put(0x010104c7, AxmlName.fragmentReenterTransition);
mAxmlNameMap.put(0x010104c8, AxmlName.fragmentAllowEnterTransitionOverlap);
mAxmlNameMap.put(0x010104c9, AxmlName.fragmentAllowReturnTransitionOverlap);
mAxmlNameMap.put(0x010104ca, AxmlName.patternPathData);
mAxmlNameMap.put(0x010104cb, AxmlName.strokeAlpha);
mAxmlNameMap.put(0x010104cc, AxmlName.fillAlpha);
mAxmlNameMap.put(0x010104cd, AxmlName.windowActivityTransitions);
mAxmlNameMap.put(0x010104ce, AxmlName.colorEdgeEffect);
}
public static AxmlName get(int resourceId) {
return mAxmlNameMap.get(resourceId);
}
}
| 56.709265
| 87
| 0.828676
|
5f3d0ded7fc8671ed3b7d2cb57839e74e58afc4a
| 6,466
|
package de.dytanic.cloudnet.ext.syncproxy.bungee.util;
import com.google.common.base.Preconditions;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.ServerConnectRequest;
import net.md_5.bungee.api.SkinConfiguration;
import net.md_5.bungee.api.Title;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.PermissionCheckEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.api.score.Scoreboard;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
public class LoginProxiedPlayer implements ProxiedPlayer {
private final PendingConnection connection;
private final Collection<String> permissions = new ArrayList<>();
private final Collection<String> groups = new ArrayList<>();
public LoginProxiedPlayer(PendingConnection connection) {
this.connection = connection;
this.groups.addAll(ProxyServer.getInstance().getConfigurationAdapter().getGroups(connection.getName()));
for (String group : this.groups) {
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group)) {
this.setPermission(permission, true);
}
}
}
@Override
public String getDisplayName() {
return this.connection.getName();
}
@Override
public void setDisplayName(String name) {
}
@Override
public void sendMessage(ChatMessageType position, BaseComponent... message) {
}
@Override
public void sendMessage(ChatMessageType position, BaseComponent message) {
}
@Override
public void sendMessage(UUID sender, BaseComponent... message) {
}
@Override
public void sendMessage(UUID sender, BaseComponent message) {
}
@Override
public void connect(ServerInfo target) {
}
@Override
public void connect(ServerInfo target, ServerConnectEvent.Reason reason) {
}
@Override
public void connect(ServerInfo target, Callback<Boolean> callback) {
}
@Override
public void connect(ServerInfo target, Callback<Boolean> callback, ServerConnectEvent.Reason reason) {
}
@Override
public void connect(ServerConnectRequest request) {
}
@Override
public Server getServer() {
return null;
}
@Override
public int getPing() {
return 1337;
}
@Override
public void sendData(String channel, byte[] data) {
}
@Override
public PendingConnection getPendingConnection() {
return null;
}
@Override
public void chat(String message) {
}
@Override
public ServerInfo getReconnectServer() {
return null;
}
@Override
public void setReconnectServer(ServerInfo server) {
}
@Override
public String getUUID() {
return this.connection.getUniqueId().toString();
}
@Override
public UUID getUniqueId() {
return this.connection.getUniqueId();
}
@Override
public Locale getLocale() {
return null;
}
@Override
public byte getViewDistance() {
return 0;
}
@Override
public ChatMode getChatMode() {
return null;
}
@Override
public boolean hasChatColors() {
return false;
}
@Override
public SkinConfiguration getSkinParts() {
return null;
}
@Override
public MainHand getMainHand() {
return null;
}
@Override
public void setTabHeader(BaseComponent header, BaseComponent footer) {
}
@Override
public void setTabHeader(BaseComponent[] header, BaseComponent[] footer) {
}
@Override
public void resetTabHeader() {
}
@Override
public void sendTitle(Title title) {
}
@Override
public boolean isForgeUser() {
return false;
}
@Override
public Map<String, String> getModList() {
return null;
}
@Override
public Scoreboard getScoreboard() {
return null;
}
@Override
public String getName() {
return this.connection.getName();
}
@Override
public void sendMessage(String message) {
}
@Override
public void sendMessages(String... messages) {
}
@Override
public void sendMessage(BaseComponent... message) {
}
@Override
public void sendMessage(BaseComponent message) {
}
@Override
public Collection<String> getGroups() {
return this.groups;
}
@Override
public void addGroups(String... groups) {
}
@Override
public void removeGroups(String... groups) {
}
@Override
public boolean hasPermission(String permission) {
Preconditions.checkNotNull(permission);
return ProxyServer.getInstance().getPluginManager().callEvent(new PermissionCheckEvent(
this,
permission,
this.permissions.contains(permission.toLowerCase())
)).hasPermission();
}
@Override
public void setPermission(String permission, boolean value) {
Preconditions.checkNotNull(permission);
if (value) {
this.permissions.add(permission.toLowerCase());
} else {
this.permissions.remove(permission.toLowerCase());
}
}
@Override
public Collection<String> getPermissions() {
return this.permissions;
}
@Override
@Deprecated
public InetSocketAddress getAddress() {
return this.connection.getAddress();
}
@Override
public SocketAddress getSocketAddress() {
return this.connection.getSocketAddress();
}
@Override
public void disconnect(String reason) {
}
@Override
public void disconnect(BaseComponent... reason) {
}
@Override
public void disconnect(BaseComponent reason) {
}
@Override
public boolean isConnected() {
return true;
}
@Override
public Unsafe unsafe() {
return null;
}
}
| 20.462025
| 113
| 0.656511
|
b05b0bb2f3cce7095356d4ec9950a892657c6c62
| 22,971
|
package org.ea.sqrl.processors;
import android.app.Activity;
import android.util.Log;
import org.ea.sqrl.R;
import org.ea.sqrl.services.AskDialogService;
import org.ea.sqrl.utils.EncryptionUtils;
import org.ea.sqrl.utils.Utils;
import org.libsodium.jni.Sodium;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This handler creates different queries to servers and parses the response so we can talk over
* the SQRL protocol seamlessly.
*
* @author Daniel Persson
*/
public class CommunicationHandler {
private static final String TAG = "CommunicationHandler";
public static final Pattern sqrlPattern = Pattern.compile("^s*qrl://([^?/]+)(.*)$");
private static final Pattern sqrlQueryPattern = Pattern.compile("^([^?]+)\\?.*x=([0-9]+).*$");
private static CommunicationHandler instance = null;
private String communicationDomain;
private String cryptDomain;
private Map<String, String> lastResponse = new HashMap<>();
private String askButton;
private AskDialogService askDialogService;
private String response;
private boolean useSSL;
private boolean urlBasedLogin = false;
public static final int TIF_CURRENT_ID_MATCH = 0;
public static final int TIF_PREVIOUS_ID_MATCH = 1;
public static final int TIF_IP_MATCHED = 2;
public static final int TIF_SQRL_DISABLED = 3;
public static final int TIF_FUNCTION_NOT_SUPPORTED = 4;
public static final int TIF_TRANSIENT_ERROR = 5;
public static final int TIF_COMMAND_FAILED = 6;
public static final int TIF_CLIENT_FAILURE = 7;
public static final int TIF_BAD_ID_ASSOCIATION = 8;
private CommunicationHandler() {}
public static CommunicationHandler getInstance() {
if(instance == null) {
instance = new CommunicationHandler();
}
try {
TrustManager[] victimizedManager = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return myTrustedAnchors;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, victimizedManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return instance;
}
public void setUrlBasedLogin(boolean urlBasedLogin) {
this.urlBasedLogin = urlBasedLogin;
}
public boolean isUrlBasedLogin() {
return this.urlBasedLogin;
}
public void clearLastResponse() {
this.lastResponse = new HashMap<>();
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public void setDomain(String domain, String queryLink) throws Exception {
this.communicationDomain = domain;
int atSignIndex = domain.indexOf("@");
int portColon = domain.indexOf(":");
if (atSignIndex != -1) {
domain = domain.substring(atSignIndex + 1);
}
if (portColon != -1) {
domain = domain.substring(0, portColon);
}
atSignIndex = domain.indexOf("@");
portColon = domain.indexOf(":");
if (atSignIndex != -1 || portColon != -1) {
throw new Exception("Incorrect cryptDomain " + domain);
}
this.cryptDomain = domain;
Matcher queryMatcher = sqrlQueryPattern.matcher(queryLink);
if(queryMatcher.find()) {
String path = queryMatcher.group(1);
int sizeOfPath = Utils.getInteger(queryMatcher.group(2));
if(sizeOfPath > 0 && sizeOfPath < path.length() + 1) {
this.cryptDomain += path.substring(0, sizeOfPath);
}
}
}
private String getAskButtonAnswer() {
if(askButton == null) return "";
String askResponse = "btn=" + askButton + "\r\n";
askButton = null;
return askResponse;
}
public String createClientQuery(boolean noiptest, boolean requestServerUnlockKey) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=query\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, requestServerUnlockKey, false));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createClientDisable(boolean noiptest, boolean clientProvidedSession) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=disable\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, false, clientProvidedSession));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createClientEnable(boolean noiptest, boolean clientProvidedSession) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=enable\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, false, clientProvidedSession));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createClientRemove(boolean noiptest, boolean clientProvidedSession) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=remove\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, false, clientProvidedSession));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createClientCreateAccount(EntropyHarvester entropyHarvester, boolean noiptest, boolean clientProvidedSession) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=ident\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, false, clientProvidedSession));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append(storage.getServerUnlockKey(entropyHarvester));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createClientLogin(boolean noiptest, boolean clientProvidedSession) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("ver=1\r\n");
sb.append("cmd=ident\r\n");
sb.append(getAskButtonAnswer());
sb.append(storage.getOptions(noiptest, false, clientProvidedSession));
sb.append(storage.getSecretIndex(cryptDomain, lastResponse.get("sin")));
sb.append("idk=" + EncryptionUtils.encodeUrlSafe(storage.getPublicKey(cryptDomain)));
if(storage.hasPreviousKeys()) {
sb.append("\r\npidk=" + EncryptionUtils.encodeUrlSafe(storage.getPreviousPublicKey(cryptDomain)));
}
return sb.toString();
}
public String createPostParams(String client, String server) throws Exception {
return createPostParams(client, server, false);
}
public String createPostParams(String client, String server, boolean unlockServerKey) throws Exception {
SQRLStorage storage = SQRLStorage.getInstance();
storage.setProgressState(R.string.progress_state_prepare_query);
StringBuilder sb = new StringBuilder();
sb.append("client=");
sb.append(EncryptionUtils.encodeUrlSafe(client.getBytes()));
sb.append("&server=");
sb.append(EncryptionUtils.encodeUrlSafe(server.getBytes()));
byte[] message = EncryptionUtils.combine(
EncryptionUtils.encodeUrlSafe(client.getBytes()).getBytes(),
EncryptionUtils.encodeUrlSafe(server.getBytes()).getBytes()
);
byte[] signed_message = new byte[Sodium.crypto_sign_bytes() + message.length];
int[] signed_message_len = new int[1];
Sodium.crypto_sign(
signed_message,
signed_message_len,
message,
message.length,
storage.getPrivateKey(cryptDomain)
);
sb.append("&ids=");
sb.append(EncryptionUtils.encodeUrlSafe(Arrays.copyOfRange(signed_message, 0, Sodium.crypto_sign_bytes())));
if(storage.hasPreviousKeys()) {
Sodium.crypto_sign(
signed_message,
signed_message_len,
message,
message.length,
storage.getPreviousPrivateKey(cryptDomain)
);
sb.append("&pids=");
sb.append(EncryptionUtils.encodeUrlSafe(Arrays.copyOfRange(signed_message, 0, Sodium.crypto_sign_bytes())));
}
if(unlockServerKey) {
Sodium.crypto_sign(
signed_message,
signed_message_len,
message,
message.length,
storage.getUnlockRequestSigningKey(getServerUnlockKey(), this.isPreviousKeyValid())
);
sb.append("&urs=");
sb.append(EncryptionUtils.encodeUrlSafe(Arrays.copyOfRange(signed_message, 0, Sodium.crypto_sign_bytes())));
}
return sb.toString();
}
public void postRequest(String link, String data) throws Exception {
StringBuilder result = new StringBuilder();
SQRLStorage storage = SQRLStorage.getInstance();
storage.setProgressState(R.string.progresstate_contact_server);
String loginURL = (useSSL ? "https://" : "http://") + communicationDomain + link;
HttpURLConnection con = null;
DataOutputStream output = null;
DataInputStream input = null;
try {
URL myurl = new URL(loginURL);
con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Length", String.valueOf(data.length()));
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
output = new DataOutputStream(con.getOutputStream());
output.writeBytes(data);
output.close();
if(con.getResponseCode() != 200) {
throw new Exception("CONN_ERROR");
}
input = new DataInputStream(con.getInputStream());
String newLine = System.getProperty("line.separator");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
boolean flag = false;
while ((line = reader.readLine()) != null) {
result.append(flag ? newLine : "").append(line);
flag = true;
}
input.close();
setResponseData(result.toString());
if(!lastResponse.containsKey("tif")) {
throw new Exception("CONN_ERROR");
}
} catch (Exception e) {
throw e;
} finally {
closeQuietly(output);
closeQuietly(input);
if(con != null) con.disconnect();
}
}
private void closeQuietly(Closeable c) {
try {
if(c != null) {
c.close();
}
} catch (IOException ioe) {}
}
public static void debugPostData(String data) throws Exception{
String[] variables = data.split("&");
for(String s : variables) {
Log.d(TAG,s);
byte[] bytes = EncryptionUtils.decodeUrlSafe(s.split("=")[1]);
Log.d(TAG,Arrays.toString(bytes));
Log.d(TAG,new String(bytes));
}
}
private void setResponseData(String responseData) throws Exception {
this.response = new String(EncryptionUtils.decodeUrlSafe(responseData));
for(String param : response.split("\r\n")) {
int firstEqualSign = param.indexOf("=");
if(firstEqualSign == -1) continue;
lastResponse.put(param.substring(0, firstEqualSign), param.substring(firstEqualSign+1));
}
}
public void printParams() {
for(Map.Entry<String, String> entry : lastResponse.entrySet()) {
Log.i(TAG, entry.getKey() + "=" + entry.getValue());
}
}
public boolean isIdentityKnown(boolean disabled) {
return (this.isTIFBitSet(CommunicationHandler.TIF_CURRENT_ID_MATCH) ||
this.isTIFBitSet(CommunicationHandler.TIF_PREVIOUS_ID_MATCH)) &&
this.isTIFBitSet(CommunicationHandler.TIF_SQRL_DISABLED) == disabled;
}
public String getResponse() {
return response;
}
public int getTif() {
if(!lastResponse.containsKey("tif")) return -1;
return Integer.parseInt(lastResponse.get("tif"), 16);
}
public boolean isTIFBitSet(int k) {
if(!lastResponse.containsKey("tif")) return false;
int tif = Integer.parseInt(lastResponse.get("tif"), 16);
return (tif & 1 << k) != 0;
}
public boolean hasErrorMessage(boolean shouldUseCPSServer) {
return lastResponse.containsKey("tif") &&
(
shouldUseCPSServer &&
!isTIFBitSet(CommunicationHandler.TIF_IP_MATCHED)
) ||
(
isTIFBitSet(CommunicationHandler.TIF_BAD_ID_ASSOCIATION) ||
isTIFBitSet(CommunicationHandler.TIF_CLIENT_FAILURE) ||
isTIFBitSet(CommunicationHandler.TIF_COMMAND_FAILED) ||
isTIFBitSet(CommunicationHandler.TIF_FUNCTION_NOT_SUPPORTED) ||
isTIFBitSet(CommunicationHandler.TIF_TRANSIENT_ERROR)
);
}
public String getErrorMessage(Activity a, boolean shouldUseCPSServer) {
StringBuilder sb = new StringBuilder();
if(!lastResponse.containsKey("tif")) {
return a.getString(R.string.communication_incorrect_response);
} else if(shouldUseCPSServer && !isTIFBitSet(CommunicationHandler.TIF_IP_MATCHED)) {
sb.append(a.getString(R.string.communication_ip_mismatch));
} else if(
isTIFBitSet(CommunicationHandler.TIF_BAD_ID_ASSOCIATION) ||
isTIFBitSet(CommunicationHandler.TIF_CLIENT_FAILURE) ||
isTIFBitSet(CommunicationHandler.TIF_COMMAND_FAILED)
) {
sb.append(a.getString(R.string.error_message_login_failed));
} else if(isTIFBitSet(CommunicationHandler.TIF_FUNCTION_NOT_SUPPORTED)) {
sb.append(a.getString(R.string.communication_function_not_supported));
} else if(isTIFBitSet(CommunicationHandler.TIF_TRANSIENT_ERROR)) {
sb.append(a.getString(R.string.error_message_stale_page));
}
return sb.toString();
}
public static void main(String[] args) {
try {
/*
CommunicationHandler commHandler = CommunicationHandler.getInstance();
String sqrlLink = "sqrl://www.grc.com/sqrl?x=5&nut=Na2MOglf7NyyupQ8-dtj1g";
Matcher sqrlMatcher = CommunicationHandler.sqrlPattern.matcher(sqrlLink);
if(sqrlMatcher.find()) {
final String domain = sqrlMatcher.group(1);
String queryLink = sqrlMatcher.group(2);
commHandler.setDomain(domain, queryLink);
System.out.println(commHandler.cryptDomain);
}
*/
byte[] bytesArray = EncryptionUtils.hex2Byte("7371726c646174617d0001002d00b51fd99559b887d106a8d877c70133bb20a12fa1a7c829b194db94f309c5000000f30104050f000d174cc6e7b70baa158aa4ce75e2f2b99a02a40e4beb2e5d16c2f03442bd3e932035419a63885a663125a600e5486c42b38f708c1094ced1ab0b0050137f6df449caf78581fec678408a804caf74f91c490002005528fc85e3e36866a85574146fe7776d09cf0000004a4e12277dd48366fc1f335dd37188bbcba02bc32a12aef0188f5e83593665518483d638b80051c2b4b013491eb06835");
SQRLStorage storage = SQRLStorage.getInstance();
storage.setProgressionUpdater(new ProgressionUpdater());
storage.read(bytesArray);
storage.decryptIdentityKey("Testing1234", EntropyHarvester.getInstance(), false);
boolean didIt = storage.decryptUnlockKey("7276-0587-2230-1119-8559-3839");
System.out.println(didIt);
CommunicationHandler commHandler = CommunicationHandler.getInstance();
String sqrlLink = "sqrl://www.grc.com/sqrl?nut=Na2MOglf7NyyupQ8-dtj1g";
Matcher sqrlMatcher = CommunicationHandler.sqrlPattern.matcher(sqrlLink);
final String domain = sqrlMatcher.group(1);
String queryLink = sqrlMatcher.group(2);
commHandler.setDomain(domain, queryLink);
String postData = commHandler.createPostParams(commHandler.createClientQuery(true, true), sqrlLink);
commHandler.postRequest(queryLink, postData);
String serverData = commHandler.getResponse();
queryLink = commHandler.getQueryLink();
if(
(commHandler.isTIFBitSet(CommunicationHandler.TIF_CURRENT_ID_MATCH) ||
commHandler.isTIFBitSet(CommunicationHandler.TIF_PREVIOUS_ID_MATCH)) &&
!commHandler.isTIFBitSet(CommunicationHandler.TIF_SQRL_DISABLED)
) {
String postData2 = commHandler.createPostParams(commHandler.createClientDisable(true,false), serverData);
commHandler.postRequest(queryLink, postData2);
serverData = commHandler.getResponse();
queryLink = commHandler.getQueryLink();
String postData3 = commHandler.createPostParams(commHandler.createClientRemove(true,false), serverData, true);
commHandler.postRequest(queryLink, postData3);
} else {
String postData2 = commHandler.createPostParams(commHandler.createClientEnable(true,false), serverData, true);
commHandler.postRequest(queryLink, postData2);
}
commHandler.printParams();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getQueryLink() {
if(!lastResponse.containsKey("qry")) {
return "";
}
return lastResponse.get("qry");
}
public byte[] getServerUnlockKey() throws Exception{
if(!lastResponse.containsKey("suk")) {
return new byte[32];
}
return EncryptionUtils.decodeUrlSafe(lastResponse.get("suk"));
}
public void setAskButton(String askButton) {
this.askButton = askButton;
this.askDialogService.activateAskButton();
}
public void setAskDialogService(AskDialogService askDialogService) {
this.askDialogService = askDialogService;
}
public void setAskAction(Runnable askAction) {
this.askDialogService.setAskAction(askAction);
}
public boolean hasAskQuestion() {
return this.lastResponse.containsKey("ask");
}
public void showAskDialog() {
if(hasAskQuestion()) {
this.askDialogService.showDialog(this.lastResponse.get("ask"));
} else {
this.askDialogService.activateAskButton();
}
}
public boolean isPreviousKeyValid() {
return isTIFBitSet(CommunicationHandler.TIF_PREVIOUS_ID_MATCH);
}
public boolean hasCPSUrl() {
return this.lastResponse.containsKey("url");
}
public String getCPSUrl() {
return this.lastResponse.get("url");
}
public String getDomain() {
return this.cryptDomain;
}
public void setAlternativeId(String alternativeId) {
if(alternativeId == null || alternativeId.isEmpty()) return;
this.cryptDomain += alternativeId.replaceAll("[^A-Za-z0-9]", "");
}
}
| 39.132879
| 473
| 0.639546
|
be8965e84f5c24793c82240ade808a47d77e9a72
| 564
|
package com.virtualpairprogrammers.services.diary;
import java.util.List;
import com.virtualpairprogrammers.domain.Action;
/**
* This interface defines the functionality required in the Diary Management Service.
*
* @author Richard Chesterwood
*/
public interface DiaryManagementService
{
/**
* Records an action in the diary
*/
public void recordAction(Action action);
/**
* Gets all actions for a particular user that have not yet been complete
*/
public List<Action> getAllIncompleteActions(String requiredUser);
}
| 23.5
| 86
| 0.730496
|
4a0044e596d99a42a0470a4f31699a4e80d6bab0
| 531
|
import java.util.*;
class Magic_No
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
int c=n,s=0;
while(n<9)
{
while(c!=0)
{
int d=c%10;
s=s+d;
c=c/10;
}
}
if(n==1)
System.out.println("Magic number");
else
System.out.println("Not a Magic number");
}
}
| 22.125
| 53
| 0.425612
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.