text
stringlengths 10
2.72M
|
|---|
package leetCode;
/**
* Created by gengyu.bi on 2014/12/31.
*/
public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
if (head == null)
return null;
ListNode fast = head;
ListNode slow = head;
while (true) {
if (fast.next == null)
return null;
fast = fast.next;
if (fast.next == null)
return null;
fast = fast.next;
slow = slow.next;
if (fast == slow)
break;
}
while (head != slow) {
slow = slow.next;
head = head.next;
}
return head;
}
public static void main(String[] args) {
LinkedListCycleII linkedListCycleII = new LinkedListCycleII();
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
ListNode l6 = new ListNode(6);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6;
//l6.next = l3;
ListNode r = linkedListCycleII.detectCycle(l1);
System.out.println(r.val);
}
}
|
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
public class MathClass {
public static void main(String[] args) {
int max = Math.max(1,2);
int min = Math.min(1,2);
var sqrt = Math.sqrt(64);
var abs = Math.abs(-10);
var abs1 = Math.abs(10);
var a = Math.random() * 10; // a number of 0 to 10
LocalDate dateNow = LocalDate.now();
LocalTime timeNow = LocalTime.now();
LocalDateTime dateTimeNow = LocalDateTime.now();
var year = dateNow.getYear();
ArrayList<String> strArrList = new ArrayList<String>();
strArrList.add("This is a sample string...");
System.out.println("just for Break Point");
}
}
|
package org.hpin.webservice.bean;
import java.util.Date;
/**
*
* @description: erp_customer_receive表;
* create by henry.xu 2016年12月2日
*/
public class ErpCustomerReceive {
private String id; //主键ID
private String batchNo;//批次号(年月日时分秒,此接口被调用一次,不管接口有多少人,此批次号都是一样的)
private String serviceCode;//条形码
private String userName;//姓名
private String sex;//性别
private String birthday;//出生日期
private String companyId;//支公司id
private String companyName;//支公司名称
private String ownerCompanyId;//总公司id
private String ownerCompanyName;//总公司名称
private String examDate;//检测日期
private String examTime;//检测时间
private String eventsType;//场次类型(上午场:6:00-15:00/下午场:15:00-18:00/晚场:18:00-23:00)
private String isMatch;//是否匹配 1匹配, 0 未匹配;
private String returnFlag; //“Yes”—信息是否回传(Yes:通过公司二维码扫描进入的客户需要晚上回推给远盟,No:通过场次二维码扫描进入的客户信息不需要晚上回推给远盟/通过知情同意书直接在无创检测设备
private String other; //备用字段; 无创传过来的支公司Id;
private String sourceFrom; //数据来源;
private String projectType; //项目类型编码
private Date createTime;
private Date updateTime;
private String reportType; //设备套餐名称;
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getSourceFrom() {
return sourceFrom;
}
public void setSourceFrom(String sourceFrom) {
this.sourceFrom = sourceFrom;
}
public String getProjectType() {
return projectType;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
public String getReturnFlag() {
return returnFlag;
}
public void setReturnFlag(String returnFlag) {
this.returnFlag = returnFlag;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getServiceCode() {
return serviceCode;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getOwnerCompanyId() {
return ownerCompanyId;
}
public void setOwnerCompanyId(String ownerCompanyId) {
this.ownerCompanyId = ownerCompanyId;
}
public String getOwnerCompanyName() {
return ownerCompanyName;
}
public void setOwnerCompanyName(String ownerCompanyName) {
this.ownerCompanyName = ownerCompanyName;
}
public String getExamDate() {
return examDate;
}
public void setExamDate(String examDate) {
this.examDate = examDate;
}
public String getExamTime() {
return examTime;
}
public void setExamTime(String examTime) {
this.examTime = examTime;
}
public String getEventsType() {
return eventsType;
}
public void setEventsType(String eventsType) {
this.eventsType = eventsType;
}
public String getIsMatch() {
return isMatch;
}
public void setIsMatch(String isMatch) {
this.isMatch = isMatch;
}
}
|
/**
* @author dp0470
*
*/
package com.codigo.smartstore.timeline.range;
|
package com.trump.auction.back.sys.dao.read;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.trump.auction.back.sys.model.Role;
import com.trump.auction.back.sys.model.ZTree;
@Repository
public interface RoleReadDao {
public List<Role> findAdminAll(HashMap<String, Object> params);
public List<Role> findUserAll(HashMap<String, Object> params);
public List<ZTree> findAdminRoleTree(HashMap<String, Object> params);
public List<ZTree> findUserRoleTree(HashMap<String, Object> params);
public Role findById(Integer id);
public List<String> findIdsByParentId(Integer id);
public List<String> showUserListByRoleId(Integer roleId);
public List<ZTree> getTreeByRoleId(@Param("roleId") Integer roleId, @Param("parentId") Integer parentId);
}
|
package com.gjm.file_cloud.service;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationService {
public String getUsernameOfLoggedInUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth.getName();
}
public boolean isUserLoggedIn() {
return !(SecurityContextHolder.getContext()
.getAuthentication() instanceof AnonymousAuthenticationToken);
}
}
|
package com.cqut.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl;
/**
* 系统常量
* @author zzk
* */
public class SystemConstants {
/**
* 回拨IP
* */
public static final String CALLBACKIP="118.178.143.5";
/**
* 回拨流量代理ID
* */
//public static final String CALLBACKID="141";
public static final String CALLBACKID="108";//5G全网通
/**
* 回拨appkey
* */
//public static final String CALLBACK_APPKEY="63e73c8d86274b6d648921b3d2fcd43a";
public static final String CALLBACK_APPKEY="5fb41265bc142d3b2b111a379f783fd2";//5G全网通
/**
* 回拨相关服务地址
*/
public static final String CALLBACKADDRESS="http://ht.hbyxyj.cn/wap/";
/**
* 学生基础角色id
* */
public static final String ST_ROLE_ID = "0001";
/**
* 操作员基础角色id
* */
public static final String OP_ROLE_ID = "0002";
/**
* 评委基础角色id
* */
public static final String JD_ROLE_ID = "0003";
/**
*公司管理员角色id
*/
public static final String MA_ROLE_ID ="0005";
/**
* 商铺id
*/
public static final String SP_ROLE_ID="0004";
/**
* 运营中心id
*/
public static final String OC_ROLE_ID="0003";
/**
* 代理商id
*/
public static final String AT_ROLE_ID = "0002";
/**
* app用户id
*/
public static final String AP_ROLE_ID= "0001";
/**
* 没有注册
*/
public static final int NOT_REGISTER = 0;
/**
* 已经注册
*/
public static final int ALREADY_REGISTER = 11;
/**
* 密码或验证码错误
*/
public static final int PW_OR_SMS_WRONG = 1;
/**
* 验证码发送错误
*/
public static final int SMS_SEND_WRONG = 2;
/**
* 验证码发送成功
*/
public static final int SMS_SEND_SUCCESS= 3;
/**
* 注册成功
*/
public static final int REGISTER_SUCCESS = 1;
/**
* 注册短信
*/
public static final int REGISTER_SMS = 0;
/**
* 登录短信
*/
public static final int LOGIN_SMS = 1;
/**
* 改密码短信
*/
public static final int CHANGE_PW_SMS = 2;
/**
* 短信超过每小时条数
*/
public static final int SMS_OUT_OF_PER_HOUR = 5;
/**
* 以角色id为键,角色类型为值的map
* */
public static final Map<String, String> ROLE_TYPES = new HashMap<String, String>();
/**
* 学生角色类型
* */
public static final String ST_ROLE_TYPE = "ST";
/**
* 操作员角色类型
* */
public static final String OP_ROLE_TYPE = "OP";
/**
* 评委角色类型
* */
public static final String JD_ROLE_TYPE = "JD";
/**
* 标注为基础角色
* */
public static final Byte BASE_ROLE_TYPE = 0;
/**
* 标注为用户新增的额外角色
* */
public static final Byte EXTRA_ROLE_TYPE = 1;
/**
* 以角色类型为键,角色id为值的map
* */
public static final Map<String, String> ROLE_IDS = new HashMap<String, String>();
// 初始化roleids与roletypes
static {
ROLE_TYPES.put(ST_ROLE_ID, ST_ROLE_TYPE);
ROLE_IDS.put(ST_ROLE_TYPE, ST_ROLE_ID);
ROLE_TYPES.put(OP_ROLE_ID, OP_ROLE_TYPE);
ROLE_IDS.put(OP_ROLE_TYPE, OP_ROLE_ID);
ROLE_TYPES.put(JD_ROLE_ID, JD_ROLE_TYPE);
ROLE_IDS.put(JD_ROLE_TYPE, JD_ROLE_ID);
}
/**
* 根据角色类型获取角色id
* */
public static String getRoleId(String roleType) {
return ROLE_IDS.get(roleType);
}
/**
* 根据角色id获取角色类型
* */
public static String getRoleType(String roleId) {
return ROLE_TYPES.get(roleId);
}
/**
* 当前用户id的键
* */
public static final String CUR_USER_ID_KEY = "curUserid";
/**
* 当前用户类型的键
* */
public static final String CUR_ROLE_TYPE_KEY = "curRoleType";
/**
* 当前用户所属组织结构的键
* */
public static final String CUR_ORG_ID_KEY = "curOrgId";
/**
* 当前用户所属组织结构的code
* */
public static final String CUR_ORG_CODE_KEY = "curOrgCode";
/**
* 标注权限分配中,拥有者类型为角色
* */
public static final String OWNER_TYPE_IN_PA_IS_ROLE = "123";
/**
* 标注权限分配中,拥有者类型为组织结构
* */
public static final String OWNER_TYPE_IN_PA_IS_ORG = "456";
/**
* 用于区分数据库中值为0或1的字段,包括是否有下级、是否有效等等
* */
public static final Byte FALSE_0 = 0;
public static final Byte TRUE_1 = 1;
/**
* 四个顶层结构的code值
* */
/**
* student
* */
public static final String ST_ORG_CODE = "00000001";
/**
* operator
* */
public static final String OP_ORG_CODE = "00000002";
/**
* judger
* */
public static final String JD_ORG_CODE = "00000003";
/**
* 初始密码
* */
public static final String INIT_PASSWORD = "123456";
/**
* 标注操作类型为新增
* */
public static final byte ADD_OP_TYPE = 0;
/**
* 标注操作类型为更新
* */
public static final byte UPDATE_OP_TYPE = 1;
/**
* 车辆状态值
* */
/**
* 可用状态
* */
public static final String AVAILABLE_STATE_FOR_VEHICLE = "2";
public static final String LEASEUSER_ORGCODE = "00000003";
public static final int LEVEL0 = 2;
/**
* 通知类型
* */
/**
* 一般通知类型
* */
public static final String COMMON_NOTICE_TYPE = "0000000100000001";
/**
* 紧急通知类型
* */
public static final String URGENCY_NOTICE_TYPE = "0000000100000002";
/**
* 超级管理员的uid
* */
public static final String ADMIN_UID = "2623502869319762";
public static final Byte INIT_STATE = 1;
}
|
package Printer;
import Logic.Game;
import Utils.MyStringUtils;
public class ReleasePrinter extends BoardPrinter{
private void encodeGame(Game game) {
board = new String[dimX][dimY];
for(int i = 0; i < dimX; i++) {
for(int j = 0; j < dimY; j++) {
board[i][j] = space;
board[i][j] = game.elementoTablero(i, j); //Compara cada coordenada del tablero con las posiciones de todas las listas
}
}
}
public void printGame(Game game) {
encodeGame(game);
String tablero = toString();
System.out.println(tablero);
}
public String toString() {
int cellSize = 7;
int marginSize = 2;
String vDelimiter = "|";
String hDelimiter = "-";
String rowDelimiter = MyStringUtils.repeat(hDelimiter, (dimY * (cellSize + 1)) - 1);
String margin = MyStringUtils.repeat(space, marginSize);
String lineDelimiter = String.format("%n%s%s%n", margin + space, rowDelimiter);
StringBuilder str = new StringBuilder();
str.append(lineDelimiter);
for(int i=0; i<dimX; i++) {
str.append(margin).append(vDelimiter);
for (int j=0; j<dimY; j++) {
str.append( MyStringUtils.centre(board[i][j], cellSize)).append(vDelimiter);
}
str.append(lineDelimiter);
}
return str.toString();
}
}
|
package com.corejava.basic;
public class MethodLocalOuterClass {
public void outerMethod() {
int x=10;
//final int x=10;
//Method Local Inner class
class Inner{
void innerMethod() {
System.out.println("Inside Inner Method..");
//in jdk 1.8 possible,upto jdk 1.7 error
System.out.println("Accessing local variable of outer class method::"+x);
}
}
Inner inner=new Inner();
inner.innerMethod();
}
}
|
package com.mpowa.android.powapos.apps.powatools.util;
import java.io.UnsupportedEncodingException;
/**
* Created by Powa on 11/4/15.
*/
public class StringUtil {
public static String byteArrayToHexString(byte[] data){
StringBuilder sb = new StringBuilder();
for(byte b : data){
String hex = Integer.toHexString(b & 0xff);
if(hex.length() == 1){
hex = "0" + hex;
}
sb.append(hex);
sb.append(" ");
}
return sb.toString();
}
public static String byteArrayToUtf8String(byte[] data){
try {
return new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static byte[] hexStringToByteArray(String cmd){
cmd = cmd.replaceAll("\\s","");
try{
int len = cmd.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(cmd.charAt(i), 16) << 4)
+ Character.digit(cmd.charAt(i+1), 16));
}
return data;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static byte[] utf8StringToByteArray(String cmd){
try {
return cmd.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
|
package kr.co.ehr.user.web;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import kr.co.ehr.user.service.UserService;
import kr.co.ehr.user.service.UserVO;
import kr.co.ehr.user.service.impl.UserServiceImpl;
@Controller
public class UserController {
public final Logger LOG = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@RequestMapping("user/get_selectone_view.do")
public String get_selectOneView() {
LOG.debug("*****************");
LOG.debug("*@Controller get_selectOneView*");
LOG.debug("*****************");
return "user/user_mng";
}
//http://localhost:8080/ehr/user/get_selectone.do?name=ehr&age=8&sex=m&tel=010-8888-8888
@RequestMapping(value="user/get_selectone.do",method = RequestMethod.GET)
public String get_selectOne(UserVO inVO,Model model) {
LOG.debug("*****************");
LOG.debug("*@Controller param*"+inVO);
LOG.debug("*****************");
model.addAttribute("vo", userService.get_selectOne(inVO)) ;
return "user/user_mng";
}
//http://localhost:8080/ehr/user/get_selectone.do?name=ehr&age=8&sex=m&tel=010-8888-8888
// @RequestMapping(value="user/get_selectone.do",method = RequestMethod.GET)
// public String get_selectOne(HttpServletRequest req,Model model) {
//
// UserVO inVO=new UserVO();
// inVO.setName(req.getParameter("name"));
// inVO.setAge(req.getParameter("age"));
// inVO.setSex(req.getParameter("sex"));
// inVO.setTel(req.getParameter("tel"));
// LOG.debug("*****************");
// LOG.debug("*@Controller param*"+inVO);
// LOG.debug("*****************");
//
// model.addAttribute("vo", userService.get_selectOne(inVO)) ;
//
// return "user/user_mng";
// }
}
|
// package com.document.feed;
//
// import com.document.feed.model.Article;
// import com.document.feed.service.NewsService;
// import com.fasterxml.jackson.annotation.JsonInclude.Include;
// import com.fasterxml.jackson.core.JsonProcessingException;
// import com.fasterxml.jackson.databind.ObjectMapper;
// import com.kwabenaberko.newsapilib.NewsApiClient;
// import com.kwabenaberko.newsapilib.models.request.SourcesRequest;
// import com.kwabenaberko.newsapilib.models.response.SourcesResponse;
// import org.junit.jupiter.api.Test;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.context.SpringBootTest;
//
// @SpringBootTest
// public class NewsServiceTest {
// @Autowired NewsService newsService;
//
// @Test
// public void testBasic() throws InterruptedException {
// // var r = newsService.mimicNewsAPIOrg("v2/top-headlines",
// // Map.of("country", "in", "category", "business"));
// // r.block().getArticles().forEach(article -> System.out.println(article.getTitle()));
// // var r = newsService.mimicNewsAPIOrg("v2/everything",
// // Map.of("q", "bitcoin"));
// // r.block().getArticles().forEach(article -> System.out.println(article.getTitle()));
// var newsApiClient = new NewsApiClient("7bca7fe0b1cf411082fc45d8d78b4dd4");
//
// newsApiClient.getSources(
// new SourcesRequest.Builder().category("business").language("en").build(),
// new NewsApiClient.SourcesCallback() {
// @Override
// public void onSuccess(SourcesResponse response) {
// System.out.println(response.getSources().get(0).getName());
// }
//
// @Override
// public void onFailure(Throwable throwable) {
// System.out.println(throwable.getMessage());
// }
// });
// Thread.sleep(10000);
// }
//
// @Test
// public void whenNotHidden_thenCorrect() throws JsonProcessingException {
// var article = new Article();
// article.setCountry("in");
// article.setCategory("sports");
// article.setCategory("sports");
//
// var mapper = new ObjectMapper();
// mapper.setSerializationInclusion(Include.NON_NULL);
//
// System.out.println(mapper.writeValueAsString(article));
// }
// }
|
package com.myvodafone.android.front.usage;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.BundlesManager;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.business.managers.PrePayServiceManager;
import com.myvodafone.android.front.VFGRFragment;
import com.myvodafone.android.front.helpers.Dialogs;
import com.myvodafone.android.front.home.FragmentHome;
import com.myvodafone.android.front.home.GaugeState;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.front.soasta.TealiumHelper;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.business.VFMobileAccount;
import com.myvodafone.android.model.business.VFMobileXGAccount;
import com.myvodafone.android.model.service.PPBalance;
import com.myvodafone.android.model.service.PostPayBundle;
import com.myvodafone.android.model.service.PostPayBundlesResult;
import com.myvodafone.android.utils.StaticTools;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
/**
* Created by p.koutsias on 2/11/2016.
*/
public class FragmentPrepayUsageWrapper extends VFGRFragment implements PrePayServiceManager.PrePayBalanceListener {
public static final String TAG_SELECTED_CATEGORY = "TAG_SELECTED_CATEGORY";
public static final String AUTO_FOCUS_BUCKET = "AUTO_FOCUS_BUCKET";
TextView tariffDescription, phoneNumber;
FrameLayout usage_container;
ImageView profileIcon;
private PPBalance ppBalance;
private int selectedCategory = -1;
private String autoFocusBucket;
public static FragmentPrepayUsageWrapper newInstance(int selectedCategory) {
FragmentPrepayUsageWrapper fragment = new FragmentPrepayUsageWrapper();
Bundle args = new Bundle();
args.putInt(TAG_SELECTED_CATEGORY, selectedCategory);
fragment.setArguments(args);
return fragment;
}
public static FragmentPrepayUsageWrapper newInstance(int selectedCategory, String autoFocusBucket) {
FragmentPrepayUsageWrapper fragment = new FragmentPrepayUsageWrapper();
Bundle args = new Bundle();
args.putInt(TAG_SELECTED_CATEGORY, selectedCategory);
args.putString(AUTO_FOCUS_BUCKET, autoFocusBucket);
fragment.setArguments(args);
return fragment;
}
@Override
public BackFragment getPreviousFragment() {
return BackFragment.FragmentHome;
}
@Override
public String getFragmentTitle() {
return activity.getString(R.string.usage_analysis_label);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_prepay_usage_wrapper, container, false);
VFAccount selectedAccount = MemoryCacheManager.getSelectedAccount();
if (selectedAccount != null && selectedAccount.isHybrid()) {
OmnitureHelper.trackView("Usage analysis hybrid");
} else {
OmnitureHelper.trackView("Usage analysis prepay");
}
initElements(v);
return v;
}
@Override
public void onResume() {
super.onResume();
if(selectedCategory == -1 && getArguments().containsKey(TAG_SELECTED_CATEGORY)) {
selectedCategory = getArguments().getInt(TAG_SELECTED_CATEGORY);
}
if(getArguments().containsKey(AUTO_FOCUS_BUCKET)){
autoFocusBucket = getArguments().getString(AUTO_FOCUS_BUCKET);
}
activity.sideMenuHelper.setToggle(getView().findViewById(R.id.toggleDrawer));
activity.sideMenuHelper.setBackButton(getView().findViewById(R.id.back), activity);
getPrePayBundles();
setFragmentTitle();
VFAccount selectedAccount = MemoryCacheManager.getSelectedAccount();
String msisdn = "";
if (selectedAccount != null) {
if (StaticTools.isBizAdmin(selectedAccount)) {
msisdn = MemoryCacheManager.getSelectedBizMsisdn();
} else {
msisdn = selectedAccount.getSelectedAccountNumber();
}
}
phoneNumber.setText(msisdn != null ? msisdn : "");
String tariffDesc = "";
if (MemoryCacheManager.getSelectedAccount() != null && StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())) {
tariffDesc = StaticTools.getBizMsisdnTarif(msisdn);
} else if (MemoryCacheManager.getSelectedAccount() != null
&& MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_MOBILE
&& ((VFMobileAccount) MemoryCacheManager.getSelectedAccount()).getMobileAccount() != null) {
if (MemoryCacheManager.getSelectedAccount().isHybrid()) {
tariffDesc = StaticTools.getMsisdnTarif(msisdn);
}
if (StaticTools.isNullOrEmpty(tariffDesc)) {
tariffDesc = ((VFMobileAccount) MemoryCacheManager.getSelectedAccount()).getMobileAccount().getCosdesc();
}
} else if (MemoryCacheManager.getSelectedAccount() != null
&& MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_MOBILE_VF3G
&& ((VFMobileXGAccount) MemoryCacheManager.getSelectedAccount()).getMobileAccount() != null) {
tariffDesc = ((VFMobileXGAccount) MemoryCacheManager.getSelectedAccount()).getMobileAccount().getCosDesc();
}
if (!StaticTools.isNullOrEmpty(tariffDesc)) {
tariffDescription.setText(tariffDesc);
} else {
tariffDescription.setText("");
}
StaticTools.loadProfileImage(profileIcon, R.drawable.profile_icon, msisdn != null ? msisdn : "", activity);
//BG
StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null);
}
private void initElements(View v) {
header = (TextView) v.findViewById(R.id.headerTitle);
tariffDescription = (TextView) v.findViewById(R.id.tariff_description);
phoneNumber = (TextView) v.findViewById(R.id.txtPhonenumber);
usage_container = (FrameLayout) v.findViewById(R.id.bundles_container);
profileIcon = (ImageView) v.findViewById(R.id.profile_icon);
}
protected void getPrePayBundles() {
VFAccount selectedAccount = MemoryCacheManager.getSelectedAccount();
if (selectedAccount != null
&& (selectedAccount.getAccountType() == VFAccount.TYPE_MOBILE || selectedAccount.getAccountType() == VFAccount.TYPE_MOBILE_VF3G)
&& (selectedAccount.getAccountSegment() == VFAccount.TYPE_MOBILE_PREPAY || selectedAccount.isHybrid())) {
Dialogs.showProgress(activity);
PrePayServiceManager.getPrepayBalance(activity, MemoryCacheManager.getSelectedAccount(), new WeakReference<PrePayServiceManager.PrePayBalanceListener>(this));
}
}
private boolean isFlexy(PPBalance ppBalance, VFAccount selectedAccount) {
if (!selectedAccount.isHybrid()
|| ppBalance == null
|| ppBalance.getExtendedBundles() == null
|| ppBalance.getDestinationList() == null) {
return false;
}
int[] dataTypes = new int[]{BundlesManager.BUNDLE_POSTPAY_TYPE_SMS,
BundlesManager.BUNDLE_POSTPAY_TYPE_VOICE,
BundlesManager.BUNDLE_POSTPAY_TYPE_DATA};
boolean allEmpty = true;
VFGRFragment.BundlesResult[] results = new VFGRFragment.BundlesResult[3];
int index = 0;
for (int dataType : dataTypes) {
results[index] = FragmentHome.getPrepayUsageResults(dataType, FragmentHome.getBundles(ppBalance.getExtendedBundles(), ppBalance.getDestinationList(), dataType));
if ((results[index].bundleUsage != VFGRFragment.BundlesResult.BundleUsage.EmptyBundles
&& results[index].bundleUsage != VFGRFragment.BundlesResult.BundleUsage.AnyConsumed)
|| results[index].sum > 0) {
allEmpty = false;
}
}
return allEmpty;
}
@Override
public void onSuccessPrepayBalance(PPBalance ppBalance) {
VFAccount selectedAccount = MemoryCacheManager.getSelectedAccount();
this.ppBalance = ppBalance;
if (activity != null) {
if (isFlexy(ppBalance, selectedAccount)) {
activity.getSupportFragmentManager().beginTransaction().replace(R.id.bundles_container, FragmentPrepayUsageFlexy.newInstance()).commitAllowingStateLoss();
} else {
activity.getSupportFragmentManager().beginTransaction().replace(R.id.bundles_container, FragmentPrepayUsage.newInstance(selectedCategory, autoFocusBucket)).commitAllowingStateLoss();
}
}
if (selectedAccount != null) {
if (selectedAccount.isHybrid()) {
// Tealium
TealiumHelper.trackTealiumEvent("Usage Analysis", "Usage analysis screen Hybrid", "Usage", "Usage", "Usage data loaded");
} else {
// Tealium
TealiumHelper.trackTealiumEvent("Usage Analysis", "Usage analysis screen Prepay", "Usage", "Usage", "Usage data loaded");
}
// Omniture
OmnitureHelper.trackJourneyEndEvent("Usage Analysis", "Usage");
}
Dialogs.closeProgress();
}
@Override
public void onErrorPrepayBalance(String message, String msisdn) {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, message);
}
@Override
public void onGenericErrorPrepayBalance() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, null);
}
public int getSelectedCategory() {
return selectedCategory;
}
public void setSelectedCategory(int selectedCategory) {
this.selectedCategory = selectedCategory;
}
public PPBalance getPpBalance() {
return ppBalance;
}
}
|
package com.example.asus.taskapp.AccountUtils;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.asus.taskapp.Config;
import com.example.asus.taskapp.FilePath;
import com.example.asus.taskapp.FormDataPost;
import com.example.asus.taskapp.MainActivity;
import com.example.asus.taskapp.Model.Users;
import com.example.asus.taskapp.R;
import com.example.asus.taskapp.Utils.FetchData;
import com.example.asus.taskapp.Utils.JSON_POST;
import com.example.asus.taskapp.Utils.UserAvailable;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class ProfileActivity extends AppCompatActivity implements FetchData.OnUsersListener {
public Button btnSunting , btnOK;
public Spinner kelamin_teks;
public ImageView imageView;
public String sourcePath = null;
public ProgressDialog dialogs = null;
public SharedPreferences preferences;
public FetchData fetchData;
public int id = 0;
public SharedPreferences.Editor editor;
public String token = null;
public TextInputEditText email_teks , name_teks , password_teks , sekolah_teks , image_path_teks;
public FloatingActionButton profile_fab;
public String original_image = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_activity);
if(new UserAvailable(ProfileActivity.this).check_user_exist() == true){
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
builder.setMessage("Akun Anda Telah Dihapus / Ada Kesalahan Aplikasi \n Anda Akan Logout Otomatis");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
preferences = getSharedPreferences("user_data",0);
editor = preferences.edit();
editor.clear();
Intent intent = new Intent(ProfileActivity.this,LoginActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
Toolbar toolbar = findViewById(R.id.toolbar_profile);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
preferences = getSharedPreferences("user_data",0);
if(preferences.getString("token",null) != null){
token = preferences.getString("token",null);
}
profile_fab = findViewById(R.id.profile_fab);
profile_fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK , MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent , "Choose image"),10);
}
});
btnSunting = findViewById(R.id.btnEdit);
btnOK = findViewById(R.id.btnOk);
imageView = findViewById(R.id.profile_image);
preferences = getSharedPreferences("user_data",0);
if(preferences.getString("token",null) != null && preferences.getInt("id",0) != 0){
String token = preferences.getString("token",null);
id = preferences.getInt("id",0);
fetchData = new FetchData(ProfileActivity.this,new Config().getServerAddress() + "/users/" + String.valueOf(id), FetchData.FetchType.USERS_FIND_BY_ID,token,false);
fetchData.setUsersListener(this);
fetchData.execute();
}
btnSunting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
email_teks.setEnabled(true);
name_teks.setEnabled(true);
password_teks.setEnabled(true);
sekolah_teks.setEnabled(true);
kelamin_teks.setEnabled(true);
}
});
btnOK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final JSONObject object = new JSONObject();
try {
object.put("id",id);
object.put("email",email_teks.getText().toString());
object.put("name",name_teks.getText().toString());
object.put("password",password_teks.getText().toString());
object.put("sekolah",sekolah_teks.getText().toString());
object.put("kelamin",kelamin_teks.getSelectedItem().toString());
if(sourcePath != null){
object.put("image_path",String.valueOf(id) + new File(sourcePath).getName());
object.put("original_image_path",new File(sourcePath).getName());
}
} catch(JSONException e){
e.printStackTrace();
}
if(sourcePath != null){
Post post = new Post(new Config().getServerAddress() + "/users" , sourcePath , "upload_image" , "json_data",object.toString(),"PUT");
post.execute();
} else {
JsonPost posts = new JsonPost(new Config().getServerAddress() + "/users",object.toString());
posts.execute();
}
}
});
ArrayAdapter<String> items = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,new String[]{"Laki-Laki","Perempuan"});
items.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kelamin_teks = findViewById(R.id.kelamin_teks);
kelamin_teks.setAdapter(items);
email_teks = findViewById(R.id.email_teks);
name_teks = findViewById(R.id.name_teks);
password_teks = findViewById(R.id.password_teks);
sekolah_teks = findViewById(R.id.sekolah_teks);
image_path_teks = findViewById(R.id.image_path_teks);
email_teks.setEnabled(false);
name_teks.setEnabled(false);
password_teks.setEnabled(false);
sekolah_teks.setEnabled(false);
image_path_teks.setEnabled(false);
kelamin_teks.setEnabled(false);
initCollapsingToolbar();
}
public class Post extends AsyncTask<String , Void , Integer> {
public String uri;
public String fileName;
public String fileField;
public String fieldString;
public String data;
public String requestType;
public ProgressDialog dialog;
public Post(String uri , String fileName , String fileField , String fieldString , String data , String requestType){
this.uri = uri;
this.fileName = fileName;
this.fileField = fileField;
this.fieldString = fieldString;
this.data = data;
this.requestType = requestType;
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(ProfileActivity.this);
dialog.setMessage("Updating...");
dialog.show();
super.onPreExecute();
}
@Override
protected Integer doInBackground(String... strings) {
return UploadMultipart(uri , fileName , fileField , fieldString , data , requestType);
}
@Override
protected void onPostExecute(Integer integer) {
dialog.dismiss();
startActivity(new Intent(ProfileActivity.this,MainActivity.class));
finish();
super.onPostExecute(integer);
}
}
public class JsonPost extends AsyncTask<String , Void , Integer> {
public ProgressDialog progressDialog;
public String uri;
public String data;
public JsonPost(String uri , String data){
this.uri = uri;
this.data = data;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProfileActivity.this);
progressDialog.setMessage("Updating....");
progressDialog.show();
super.onPreExecute();
}
@Override
protected Integer doInBackground(String... strings) {
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("PUT");
connection.setRequestProperty("x-token",token);
connection.setRequestProperty("x-image","no image");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
int code = connection.getResponseCode();
return code;
} catch(Exception e){
e.printStackTrace();
}
return 0;
}
@Override
protected void onPostExecute(Integer integer) {
progressDialog.dismiss();
startActivity(new Intent(ProfileActivity.this,MainActivity.class));
finish();
super.onPostExecute(integer);
}
}
public int UploadMultipart(String uri , String fileName , String fieldName , String fieldString, String data , String requestType){
HttpURLConnection connection;
DataOutputStream outputStream;
String lineEnd = "\r\n";
String boundary = "*****";
String two = "--";
int maxBufferSize = 2 * 2048 * 2048;
int bytesRead , bytesAvailable , bufferSize;
byte[] buffer;
File selectedFile = new File(fileName);
int responseCode = 0;
if(!selectedFile.exists()){
Log.e("Error","Not A File");
return 0;
} else {
try {
FileInputStream fis = new FileInputStream(selectedFile);
URL url = new URL(uri);
connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod(requestType);
connection.setRequestProperty("x-token",token);
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
connection.setRequestProperty(fieldName , fileName);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(two + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldString + "\"" + lineEnd + lineEnd);
outputStream.writeBytes(data + lineEnd + two + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable , maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fis.read(buffer , 0 , bufferSize);
while(bytesRead > 0){
outputStream.write(buffer , 0 , bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable , maxBufferSize);
bytesRead = fis.read(buffer , 0 ,bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(two + boundary + two + lineEnd);
fis.close();
outputStream.flush();
outputStream.close();
responseCode = connection.getResponseCode();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(MalformedURLException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
return responseCode;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK , MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"choose image file"),10);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 10){
if(resultCode == RESULT_OK && data != null){
sourcePath = FilePath.getPath(ProfileActivity.this,data.getData());
image_path_teks.setText(sourcePath);
Glide.with(this)
.load(sourcePath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.error(R.mipmap.ic_persons)
.into(imageView);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void initCollapsingToolbar(){
final CollapsingToolbarLayout collapsing = findViewById(R.id.collapsing);
AppBarLayout appBar = findViewById(R.id.appbar);
appBar.setExpanded(true);
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
boolean isShow = false;
int scrollRange = -1;
if(scrollRange == -1){
scrollRange = appBarLayout.getTotalScrollRange();
}
if(verticalOffset + scrollRange == 0){
collapsing.setTitle("Profile");
isShow = true;
} else if(isShow){
collapsing.setTitle("");
isShow = false;
}
}
});
}
@Override
public void onUsersData(List<Users> usersList) {
Users users = usersList.get(0);
email_teks.setText(users.getEmail());
name_teks.setText(users.getName());
password_teks.setText(users.getPassword());
sekolah_teks.setText(users.getSekolah());
original_image = users.getOriginalImagePath();
if(users.getKelamin().equalsIgnoreCase("laki laki")){
kelamin_teks.setSelection(0);
} else {
kelamin_teks.setSelection(1);
}
image_path_teks.setText(users.getImagePath());
Glide.with(this)
.load(new Config().getServerAddress() + "/" + users.getImagePath())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.error(R.mipmap.ic_persons)
.into(imageView);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
|
package me.draimgoose.draimmenu.commandtags;
public enum PaywallOutput {
Blocked,
Passed,
NotApplicable
}
|
package org.eclipse.wb.swt;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class OpeningScreen extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OpeningScreen frame = new OpeningScreen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public OpeningScreen() {
setTitle("Java Quiz");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJavaQuiz = new JLabel("JAVA QUIZ");
lblJavaQuiz.setForeground(new Color(70, 130, 180));
lblJavaQuiz.setBounds(124, 48, 188, 85);
lblJavaQuiz.setFont(new Font("Bebas Neue", Font.PLAIN, 60));
contentPane.add(lblJavaQuiz);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
QuestionOne q = new QuestionOne();
q.setVisible(true);
}
});
btnStart.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnStart.setBounds(172, 142, 89, 23);
contentPane.add(btnStart);
}
}
|
package dogs;
public class Newfoundland implements DogCharacteristics {
@Override
public String breedPurpose(){
return("Working, Rescue");
}
@Override
public String coat() {
return("Thick");
}
@Override
public String size() {
return("Large");
}
@Override
public String description() {
return("As the name suggests this breed originates from Newfoundland, it was orginally used for hauling nets of fishermen, with a loveable disposition which is great for children aswell as being anintelligent breed.");
}
}
|
package com.zxt.compplatform.formengine.service;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import com.zxt.compplatform.datasource.entity.DataSource;
import com.zxt.compplatform.formengine.entity.dataset.FieldDefVO;
import com.zxt.compplatform.formengine.entity.dataset.TableVO;
import com.zxt.compplatform.formengine.entity.dataset.WhereVO;
import com.zxt.compplatform.formengine.entity.view.Button;
import com.zxt.compplatform.formengine.entity.view.ColumnRoles;
import com.zxt.compplatform.formengine.entity.view.EditColumn;
import com.zxt.compplatform.formengine.entity.view.EditMode;
import com.zxt.compplatform.formengine.entity.view.EditRulesEngin;
import com.zxt.compplatform.formengine.entity.view.Group;
import com.zxt.compplatform.formengine.entity.view.ListColumn;
import com.zxt.compplatform.formengine.entity.view.Pagination;
import com.zxt.compplatform.formengine.entity.view.Param;
import com.zxt.compplatform.formengine.entity.view.QueryColumn;
import com.zxt.compplatform.formengine.entity.view.Tab;
import com.zxt.compplatform.formengine.entity.view.TextColumn;
import com.zxt.compplatform.formengine.entity.view.TitleColumn;
import com.zxt.compplatform.formengine.entity.view.ViewColumn;
/**
* xml解析
*
* @author 007
*/
public interface IResolveXmlService {
/**
* 解析数据源
*
* @param dataSourceElement
* @param dataSourcevo
* @return
* @throws Exception
*/
public List resolveDataSource(Element dataSourceElement,
DataSource dataSourcevo) throws Exception;
/**
* 解析Table
*
* @param table
* @param tableVO
* @throws Exception
*/
public TableVO resolveTable(Element table, TableVO tableVO,
List dataSource, Document doc) throws Exception;
/**
* 解析FieldDef
*
* @param fieldDef
* @param table
* @throws Exception
*/
public TableVO resolveFieldDef(Element fieldDef, TableVO table,
List dataSource) throws Exception;
/**
* 解析FieldName
*
* @param fieldName
* @throws Exception
*/
public FieldDefVO resolveFieldName(Element fieldName) throws Exception;
/**
* 解析TalbeName
*
* @param tableName
* @throws Exception
*/
public TableVO resolveTableName(Element tableName) throws Exception;
/**
* 解析getTable
*
* @param getTable
* @param tableVO
* @throws Exception
*/
public TableVO resolveGetTable(Element getTable, TableVO tableVO,
List dataSource) throws Exception;
/**
* 解析Condition条件
*
* @param condition
* @param tableVO
* @throws Exception
*/
public TableVO resolveTableCondition(Element condition, TableVO tableVO,
List dataSource, int type, String preJoinType) throws Exception;
/**
* 解析oprValue
*
* @param operand
* @param tableVO
* @throws Exception
*/
public WhereVO splitOpr(Element operate, List dataSource, TableVO tableVO)
throws Exception;
public TableVO resolveOprValue(Element operand, TableVO tableVO)
throws Exception;
/**
* 解析fromTable
*
* @param fromTables
* @param tableVO
* @throws Exception
*/
public TableVO resolveTableFrom(List fromTables, TableVO tableVO,
List dataSource) throws Exception;
/**
* 解析Group
*
* @param group
* @param groupvo
* @return
* @throws Exception
*/
public Group resloveGroup(Element group, Group groupvo) throws Exception;
/**
* 解析参数
*
* @param param
* @param paramvo
* @return
* @throws Exception
*/
public Param resloveParam(Element param, Param paramvo) throws Exception;
/**
* 解析参数文本
*
* @param columnText
* @param columnvo
* @return
* @throws Exception
*/
public TextColumn resolveViewColumnText(Element columnText,
TextColumn columnvo) throws Exception;
public ViewColumn resolveViewDataColumn(Element viewDataColumn,
ViewColumn viewDataColumnvo) throws Exception;
/**
* 解析Tab
*
* @param page
* @param tabvo
* @return
* @throws Exception
*/
public Tab resloveTab(Element page, Tab tabvo) throws Exception;
/**
* 解析pagination
*
* @param pagination
* @param paginationvo
* @return
* @throws Exception
*/
public Pagination resolvePagination(Element pagination,
Pagination paginationvo) throws Exception;
/**
* 解析button
*
* @param button
* @param buttonvo
* @throws Exception
*/
public Button resolveButton(Element button, Button buttonvo)
throws Exception;
/**
* 解析queryZone
*
* @param queryColumns
* @param queryZonevo
* @throws Exception
*/
public QueryColumn resolveQueryColumn(Element queryColumn,
QueryColumn queryColumnvo) throws Exception;
/**
* 解析editMode
*
* @param editMode
* @param editModevo
* @throws Exception
*/
public EditMode resolveEditMode(Element editMode, EditMode editModevo)
throws Exception;
/**
* 解析TitleColumn
*
* @param titleColumn
* @param titleColumnvo
* @throws Exception
*/
public ListColumn resolveDataColumn(Element dataColumn,
ListColumn lsitColumnvo) throws Exception;
/**
* 解析编辑列
*
* @param dataColumn
* @param lsitColumnvo
* @return
* @throws Exception
*/
public EditColumn resolveEditDataColumn(Element dataColumn,
EditColumn lsitColumnvo) throws Exception;
/**
* 解析ListColumn
*
* @param listColumn
* @param lsitColumnvo
* @throws Exception
*/
public TitleColumn resolveColumnText(Element columnText,
TitleColumn columnvo) throws Exception;
/**
* @param columnText
* @param columnvo
* @return
* @throws Exception
*/
public TextColumn resolveEditColumnText(Element columnText,
TextColumn columnvo) throws Exception;
/**
* 解析编辑页
*
* @param editColumn
* @param editColumnvo
* @throws Exception
*/
public List resolveEditColumnText(Element textElement,
EditColumn editColumnTextvo) throws Exception;
/**
* @param inputElement
* @param editColumnInputvo
* @throws Exception
*/
public List resolveEditColumnInput(Element inputElement,
EditColumn editColumnInputvo) throws Exception;
/**
* 拼接sql查询语句
*
* @param tableList
* @return
* @throws Exception
*/
public TableVO spellSqlQuery(TableVO table) throws Exception;
/**
* 拼接where
*
* @param whereList
* @return
* @throws Exception
*/
public String toWhereString(List whereList) throws Exception;
/**
* 解析规则
*
* @param rulesEngin
* @param editRulesEngin
* @return
* @throws Exception
*/
public EditRulesEngin resolveEditRulesEngin(Element rulesEngin,
EditRulesEngin editRulesEngin) throws Exception;
/**
* 解析column角色
*
* @param rolesEle
* @param roles
* @return
* @throws Exception
*/
public ColumnRoles resolveColumnRoles(Element rolesEle, ColumnRoles roles)
throws Exception;
}
|
package a50;
import java.util.*;
/**
* @author 方康华
* @title FourSum
* @projectName leetcode
* @description No.18 Medium
* @date 2019/7/29 22:15
*/
// 与前面的2Sum,3Sum不同,这里采用Set对结果去重
public class FourSum {
private Set<List<Integer>> set = new HashSet<>();
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
for(int i = 0; i < nums.length - 3; i++) {
for(int j = i + 1; j < nums.length - 2; j++) {
twoSum(nums, j + 1, nums.length - 1, target - nums[i] - nums[j], i, j);
}
}
for (List<Integer> item : set) {
result.add(item);
}
return result;
}
public void twoSum(int[] nums, int id1, int id2, int target, int i, int j) {
while(id1 < id2) {
if(nums[id1] + nums[id2] < target) {
id1++;
}
else if(nums[id1] + nums[id2] > target) {
id2--;
}
else {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[id1]);
temp.add(nums[id2]);
id1++;
id2--;
set.add(temp);
}
}
}
public static void main(String[] args) {
int[] nums = new int[] {-498,-492,-473,-455,-441,-412,-390,-378,-365,-359,-358,-326,-311,-305,-277,-265,-264,
-256,-254,-240,-237,-234,-222,-211,-203,-201,-187,-172,-164,-134,-131,-91,-84,-55,-54,-52,-50,-27,-23,
-4,0,4,20,39,45,53,53,55,60,82,88,89,89,98,101,111,134,136,209,214,220,221,224,254,281,288,289,301,304,
308,318,321,342,348,354,360,383,388,410,423,442,455,457,471,488,488};
List<List<Integer>> result = new FourSum().fourSum(nums, -2808);
System.out.println(result.size());
}
}
|
/*
* Copyright 2002-2023 the original author or 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 org.springframework.expression.spel.ast;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.springframework.asm.Label;
import org.springframework.asm.MethodVisitor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.CompilablePropertyAccessor;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
* Represents a simple property or field reference.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Clark Duplichien
* @author Sam Brannen
* @since 3.0
*/
public class PropertyOrFieldReference extends SpelNodeImpl {
private final boolean nullSafe;
private final String name;
@Nullable
private String originalPrimitiveExitTypeDescriptor;
@Nullable
private volatile PropertyAccessor cachedReadAccessor;
@Nullable
private volatile PropertyAccessor cachedWriteAccessor;
public PropertyOrFieldReference(boolean nullSafe, String propertyOrFieldName, int startPos, int endPos) {
super(startPos, endPos);
this.nullSafe = nullSafe;
this.name = propertyOrFieldName;
}
public boolean isNullSafe() {
return this.nullSafe;
}
public String getName() {
return this.name;
}
@Override
public ValueRef getValueRef(ExpressionState state) throws EvaluationException {
return new AccessorLValue(this, state.getActiveContextObject(), state.getEvaluationContext(),
state.getConfiguration().isAutoGrowNullReferences());
}
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
TypedValue tv = getValueInternal(state.getActiveContextObject(), state.getEvaluationContext(),
state.getConfiguration().isAutoGrowNullReferences());
PropertyAccessor accessorToUse = this.cachedReadAccessor;
if (accessorToUse instanceof CompilablePropertyAccessor compilablePropertyAccessor) {
setExitTypeDescriptor(CodeFlow.toDescriptor(compilablePropertyAccessor.getPropertyType()));
}
return tv;
}
private TypedValue getValueInternal(TypedValue contextObject, EvaluationContext evalContext,
boolean isAutoGrowNullReferences) throws EvaluationException {
TypedValue result = readProperty(contextObject, evalContext, this.name);
// Dynamically create the objects if the user has requested that optional behavior
if (result.getValue() == null && isAutoGrowNullReferences &&
nextChildIs(Indexer.class, PropertyOrFieldReference.class)) {
TypeDescriptor resultDescriptor = result.getTypeDescriptor();
Assert.state(resultDescriptor != null, "No result type");
// Create a new collection or map ready for the indexer
if (List.class == resultDescriptor.getType()) {
if (isWritableProperty(this.name, contextObject, evalContext)) {
List<?> newList = new ArrayList<>();
writeProperty(contextObject, evalContext, this.name, newList);
result = readProperty(contextObject, evalContext, this.name);
}
}
else if (Map.class == resultDescriptor.getType()) {
if (isWritableProperty(this.name,contextObject, evalContext)) {
Map<?,?> newMap = new HashMap<>();
writeProperty(contextObject, evalContext, this.name, newMap);
result = readProperty(contextObject, evalContext, this.name);
}
}
else {
// 'simple' object
try {
if (isWritableProperty(this.name,contextObject, evalContext)) {
Class<?> clazz = result.getTypeDescriptor().getType();
Object newObject = ReflectionUtils.accessibleConstructor(clazz).newInstance();
writeProperty(contextObject, evalContext, this.name, newObject);
result = readProperty(contextObject, evalContext, this.name);
}
}
catch (InvocationTargetException ex) {
throw new SpelEvaluationException(getStartPosition(), ex.getTargetException(),
SpelMessage.UNABLE_TO_DYNAMICALLY_CREATE_OBJECT, result.getTypeDescriptor().getType());
}
catch (Throwable ex) {
throw new SpelEvaluationException(getStartPosition(), ex,
SpelMessage.UNABLE_TO_DYNAMICALLY_CREATE_OBJECT, result.getTypeDescriptor().getType());
}
}
}
return result;
}
@Override
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
throws EvaluationException {
TypedValue typedValue = valueSupplier.get();
writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, typedValue.getValue());
return typedValue;
}
@Override
public boolean isWritable(ExpressionState state) throws EvaluationException {
return isWritableProperty(this.name, state.getActiveContextObject(), state.getEvaluationContext());
}
@Override
public String toStringAST() {
return this.name;
}
/**
* Attempt to read the named property from the current context object.
* @return the value of the property
* @throws EvaluationException if any problem accessing the property, or if it cannot be found
*/
private TypedValue readProperty(TypedValue contextObject, EvaluationContext evalContext, String name)
throws EvaluationException {
Object targetObject = contextObject.getValue();
if (targetObject == null && this.nullSafe) {
return TypedValue.NULL;
}
PropertyAccessor accessorToUse = this.cachedReadAccessor;
if (accessorToUse != null) {
if (evalContext.getPropertyAccessors().contains(accessorToUse)) {
try {
return accessorToUse.read(evalContext, contextObject.getValue(), name);
}
catch (Exception ex) {
// This is OK - it may have gone stale due to a class change,
// let's try to get a new one and call it before giving up...
}
}
this.cachedReadAccessor = null;
}
List<PropertyAccessor> accessorsToTry =
getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
// Go through the accessors that may be able to resolve it. If they are a cacheable accessor then
// get the accessor and use it. If they are not cacheable but report they can read the property
// then ask them to read it
try {
for (PropertyAccessor accessor : accessorsToTry) {
if (accessor.canRead(evalContext, contextObject.getValue(), name)) {
if (accessor instanceof ReflectivePropertyAccessor reflectivePropertyAccessor) {
accessor = reflectivePropertyAccessor.createOptimalAccessor(
evalContext, contextObject.getValue(), name);
}
this.cachedReadAccessor = accessor;
return accessor.read(evalContext, contextObject.getValue(), name);
}
}
}
catch (Exception ex) {
throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_DURING_PROPERTY_READ, name, ex.getMessage());
}
if (contextObject.getValue() == null) {
throw new SpelEvaluationException(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL, name);
}
else {
throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, name,
FormatHelper.formatClassNameForMessage(getObjectClass(contextObject.getValue())));
}
}
private void writeProperty(
TypedValue contextObject, EvaluationContext evalContext, String name, @Nullable Object newValue)
throws EvaluationException {
if (contextObject.getValue() == null && this.nullSafe) {
return;
}
if (contextObject.getValue() == null) {
throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, name);
}
PropertyAccessor accessorToUse = this.cachedWriteAccessor;
if (accessorToUse != null) {
if (evalContext.getPropertyAccessors().contains(accessorToUse)) {
try {
accessorToUse.write(evalContext, contextObject.getValue(), name, newValue);
return;
}
catch (Exception ex) {
// This is OK - it may have gone stale due to a class change,
// let's try to get a new one and call it before giving up...
}
}
this.cachedWriteAccessor = null;
}
List<PropertyAccessor> accessorsToTry =
getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
try {
for (PropertyAccessor accessor : accessorsToTry) {
if (accessor.canWrite(evalContext, contextObject.getValue(), name)) {
this.cachedWriteAccessor = accessor;
accessor.write(evalContext, contextObject.getValue(), name, newValue);
return;
}
}
}
catch (AccessException ex) {
throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE,
name, ex.getMessage());
}
throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE, name,
FormatHelper.formatClassNameForMessage(getObjectClass(contextObject.getValue())));
}
public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext evalContext)
throws EvaluationException {
Object value = contextObject.getValue();
if (value != null) {
List<PropertyAccessor> accessorsToTry =
getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
for (PropertyAccessor accessor : accessorsToTry) {
try {
if (accessor.canWrite(evalContext, value, name)) {
return true;
}
}
catch (AccessException ex) {
// let others try
}
}
}
return false;
}
/**
* Determines the set of property resolvers that should be used to try and access a property
* on the specified target type. The resolvers are considered to be in an ordered list,
* however in the returned list any that are exact matches for the input target type (as
* opposed to 'general' resolvers that could work for any type) are placed at the start of the
* list. In addition, there are specific resolvers that exactly name the class in question
* and resolvers that name a specific class but it is a supertype of the class we have.
* These are put at the end of the specific resolvers set and will be tried after exactly
* matching accessors but before generic accessors.
* @param contextObject the object upon which property access is being attempted
* @return a list of resolvers that should be tried in order to access the property
*/
private List<PropertyAccessor> getPropertyAccessorsToTry(
@Nullable Object contextObject, List<PropertyAccessor> propertyAccessors) {
Class<?> targetType = (contextObject != null ? contextObject.getClass() : null);
List<PropertyAccessor> specificAccessors = new ArrayList<>();
List<PropertyAccessor> generalAccessors = new ArrayList<>();
for (PropertyAccessor resolver : propertyAccessors) {
Class<?>[] targets = resolver.getSpecificTargetClasses();
if (targets == null) {
// generic resolver that says it can be used for any type
generalAccessors.add(resolver);
}
else if (targetType != null) {
for (Class<?> clazz : targets) {
if (clazz == targetType) {
specificAccessors.add(resolver);
break;
}
else if (clazz.isAssignableFrom(targetType)) {
generalAccessors.add(resolver);
}
}
}
}
List<PropertyAccessor> resolvers = new ArrayList<>(specificAccessors);
generalAccessors.removeAll(specificAccessors);
resolvers.addAll(generalAccessors);
return resolvers;
}
@Override
public boolean isCompilable() {
return (this.cachedReadAccessor instanceof CompilablePropertyAccessor compilablePropertyAccessor &&
compilablePropertyAccessor.isCompilable());
}
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
PropertyAccessor accessorToUse = this.cachedReadAccessor;
if (!(accessorToUse instanceof CompilablePropertyAccessor compilablePropertyAccessor)) {
throw new IllegalStateException("Property accessor is not compilable: " + accessorToUse);
}
Label skipIfNull = null;
if (this.nullSafe) {
mv.visitInsn(DUP);
skipIfNull = new Label();
Label continueLabel = new Label();
mv.visitJumpInsn(IFNONNULL, continueLabel);
CodeFlow.insertCheckCast(mv, this.exitTypeDescriptor);
mv.visitJumpInsn(GOTO, skipIfNull);
mv.visitLabel(continueLabel);
}
compilablePropertyAccessor.generateCode(this.name, mv, cf);
cf.pushDescriptor(this.exitTypeDescriptor);
if (this.originalPrimitiveExitTypeDescriptor != null) {
// The output of the accessor is a primitive but from the block above it might be null,
// so to have a common stack element type at skipIfNull target it is necessary
// to box the primitive
CodeFlow.insertBoxIfNecessary(mv, this.originalPrimitiveExitTypeDescriptor);
}
if (skipIfNull != null) {
mv.visitLabel(skipIfNull);
}
}
void setExitTypeDescriptor(String descriptor) {
// If this property or field access would return a primitive - and yet
// it is also marked null safe - then the exit type descriptor must be
// promoted to the box type to allow a null value to be passed on
if (this.nullSafe && CodeFlow.isPrimitive(descriptor)) {
this.originalPrimitiveExitTypeDescriptor = descriptor;
this.exitTypeDescriptor = CodeFlow.toBoxedDescriptor(descriptor);
}
else {
this.exitTypeDescriptor = descriptor;
}
}
private static class AccessorLValue implements ValueRef {
private final PropertyOrFieldReference ref;
private final TypedValue contextObject;
private final EvaluationContext evalContext;
private final boolean autoGrowNullReferences;
public AccessorLValue(PropertyOrFieldReference propertyOrFieldReference, TypedValue activeContextObject,
EvaluationContext evalContext, boolean autoGrowNullReferences) {
this.ref = propertyOrFieldReference;
this.contextObject = activeContextObject;
this.evalContext = evalContext;
this.autoGrowNullReferences = autoGrowNullReferences;
}
@Override
public TypedValue getValue() {
TypedValue value =
this.ref.getValueInternal(this.contextObject, this.evalContext, this.autoGrowNullReferences);
if (this.ref.cachedReadAccessor instanceof CompilablePropertyAccessor compilablePropertyAccessor) {
this.ref.setExitTypeDescriptor(CodeFlow.toDescriptor(compilablePropertyAccessor.getPropertyType()));
}
return value;
}
@Override
public void setValue(@Nullable Object newValue) {
this.ref.writeProperty(this.contextObject, this.evalContext, this.ref.name, newValue);
}
@Override
public boolean isWritable() {
return this.ref.isWritableProperty(this.ref.name, this.contextObject, this.evalContext);
}
}
}
|
package com.privilege.app.models.controller;
public class DescripcionRestController {
}
|
package gluglu;
public class InfoPribadi {
private String nama;
private String nomor;
private String email;
private String alamat;
private String jeniskelamin;
public InfoPribadi(String nama, String nomor, String email, String alamat, String jeniskelamin){
setNama(nama);
setNomor(nomor);
setEmail(email);
setAlamat(alamat);
setJenisKelamin(jeniskelamin);
}
public String getJenisKelamin(){
return jeniskelamin;
}
public String getNama(){
return nama;
}
public String getNomor(){
return nomor;
}
public String getEmail(){
return email;
}
public String getAlamat(){
return alamat;
}
public void setJenisKelamin(String jk){
jeniskelamin=jk;
}
public void setNama(String nama){
this.nama=nama;
}
public void setNomor(String nomor){
this.nomor=nomor;
}
public void setEmail(String email){
this.email=email;
}
public void setAlamat(String alamat){
this.alamat=alamat;
}
}
|
package BrazilCenter.models;
/***
* Taks type, new file or failed file,
* NewTask: It's the first time we deal with it;
* LocalFailedTask: the error records that stored in errRecords directory.
* RemoteTask: the task that generated by the reupload service.
* @author Fuli Ma
*
*/
public enum TASKTYPE {
NewTask, //new tasks
SubFailedTask, // one of the transfer threads failed to transfer the file.
LocalFailedTask, // tasks generated acccording to the records in errRecords directory.
RemoteTask // tasks generate by reupload service.
}
|
package com.zserg.dao;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.zserg.model.Car;
@Repository
public class CarDAOImpl implements CarDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addCar(Car car) {
getCurrentSession().save(car);
}
@SuppressWarnings("unchecked")
public List<Car> getCar() {
return getCurrentSession().createQuery("from Car").list();
}
}
|
package pocketserver.packets;
import java.net.DatagramPacket;
import java.nio.ByteBuffer;
import pocketserver.PacketHandler;
public class Packet84LoginStatusPacket {
private int unknown;
Packet84LoginStatusPacket(byte[] data) {
ByteBuffer bb = ByteBuffer.wrap(data);
bb.get(unknown);
}
public DatagramPacket getPacket() {
return null;
}
byte[] response(PacketHandler handler) {
return null; // getPacket().getData();
}
}
|
package sudoku13.interfaces;
import java.util.List;
import sudoku13.*;
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
List<Integer> getState();
}
|
package delegation;
import com.danube.scrumworks.api2.client.ScrumWorksAPIService;
/**
* This class will be responsible for getting
* and returning all data associated with
* the User Activity requests.
*
* @author James Manes (JAM38220)
*/
public class KanbanActivityDelegate {
private ScrumWorksAPIService apiService;
public KanbanActivityDelegate(ScrumWorksAPIService apiService) {
this.apiService = apiService;
}
}
|
/*
* Copyright 2002-2022 the original author or 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 org.springframework.messaging.handler.invocation.reactive;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Scannable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.util.context.Context;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* ----------------------
* <p><strong>NOTE:</strong> This class was copied from
* {@code org.springframework.http.server.reactive.ChannelSendOperator} and is
* identical to it. It's used for the same purpose, i.e. the ability to switch to
* alternate handling via annotated exception handler methods if the output
* publisher starts with an error.
* <p>----------------------<br>
*
* <p>Given a write function that accepts a source {@code Publisher<T>} to write
* with and returns {@code Publisher<Void>} for the result, this operator helps
* to defer the invocation of the write function, until we know if the source
* publisher will begin publishing without an error. If the first emission is
* an error, the write function is bypassed, and the error is sent directly
* through the result publisher. Otherwise the write function is invoked.
*
* @author Rossen Stoyanchev
* @author Stephane Maldini
* @since 5.2
* @param <T> the type of element signaled
*/
class ChannelSendOperator<T> extends Mono<Void> implements Scannable {
private final Function<Publisher<T>, Publisher<Void>> writeFunction;
private final Flux<T> source;
public ChannelSendOperator(Publisher<? extends T> source, Function<Publisher<T>, Publisher<Void>> writeFunction) {
this.source = Flux.from(source);
this.writeFunction = writeFunction;
}
@Override
@Nullable
@SuppressWarnings("rawtypes")
public Object scanUnsafe(Attr key) {
if (key == Attr.PREFETCH) {
return Integer.MAX_VALUE;
}
if (key == Attr.PARENT) {
return this.source;
}
return null;
}
@Override
public void subscribe(CoreSubscriber<? super Void> actual) {
this.source.subscribe(new WriteBarrier(actual));
}
private enum State {
/** No emissions from the upstream source yet. */
NEW,
/**
* At least one signal of any kind has been received; we're ready to
* call the write function and proceed with actual writing.
*/
FIRST_SIGNAL_RECEIVED,
/**
* The write subscriber has subscribed and requested; we're going to
* emit the cached signals.
*/
EMITTING_CACHED_SIGNALS,
/**
* The write subscriber has subscribed, and cached signals have been
* emitted to it; we're ready to switch to a simple pass-through mode
* for all remaining signals.
**/
READY_TO_WRITE
}
/**
* A barrier inserted between the write source and the write subscriber
* (i.e. the HTTP server adapter) that pre-fetches and waits for the first
* signal before deciding whether to hook in to the write subscriber.
*
* <p>Acts as:
* <ul>
* <li>Subscriber to the write source.
* <li>Subscription to the write subscriber.
* <li>Publisher to the write subscriber.
* </ul>
*
* <p>Also uses {@link WriteCompletionBarrier} to communicate completion
* and detect cancel signals from the completion subscriber.
*/
private class WriteBarrier implements CoreSubscriber<T>, Subscription, Publisher<T> {
/* Bridges signals to and from the completionSubscriber */
private final WriteCompletionBarrier writeCompletionBarrier;
/* Upstream write source subscription */
@Nullable
private Subscription subscription;
/** Cached data item before readyToWrite. */
@Nullable
private T item;
/** Cached error signal before readyToWrite. */
@Nullable
private Throwable error;
/** Cached onComplete signal before readyToWrite. */
private boolean completed = false;
/** Recursive demand while emitting cached signals. */
private long demandBeforeReadyToWrite;
/** Current state. */
private State state = State.NEW;
/** The actual writeSubscriber from the HTTP server adapter. */
@Nullable
private Subscriber<? super T> writeSubscriber;
WriteBarrier(CoreSubscriber<? super Void> completionSubscriber) {
this.writeCompletionBarrier = new WriteCompletionBarrier(completionSubscriber, this);
}
// Subscriber<T> methods (we're the subscriber to the write source)..
@Override
public final void onSubscribe(Subscription s) {
if (Operators.validate(this.subscription, s)) {
this.subscription = s;
this.writeCompletionBarrier.connect();
s.request(1);
}
}
@Override
public final void onNext(T item) {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onNext(item);
return;
}
//FIXME revisit in case of reentrant sync deadlock
synchronized (this) {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onNext(item);
}
else if (this.state == State.NEW) {
this.item = item;
this.state = State.FIRST_SIGNAL_RECEIVED;
Publisher<Void> result;
try {
result = writeFunction.apply(this);
}
catch (Throwable ex) {
this.writeCompletionBarrier.onError(ex);
return;
}
result.subscribe(this.writeCompletionBarrier);
}
else {
if (this.subscription != null) {
this.subscription.cancel();
}
this.writeCompletionBarrier.onError(new IllegalStateException("Unexpected item."));
}
}
}
private Subscriber<? super T> requiredWriteSubscriber() {
Assert.state(this.writeSubscriber != null, "No write subscriber");
return this.writeSubscriber;
}
@Override
public final void onError(Throwable ex) {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onError(ex);
return;
}
synchronized (this) {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onError(ex);
}
else if (this.state == State.NEW) {
this.state = State.FIRST_SIGNAL_RECEIVED;
this.writeCompletionBarrier.onError(ex);
}
else {
this.error = ex;
}
}
}
@Override
public final void onComplete() {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onComplete();
return;
}
synchronized (this) {
if (this.state == State.READY_TO_WRITE) {
requiredWriteSubscriber().onComplete();
}
else if (this.state == State.NEW) {
this.completed = true;
this.state = State.FIRST_SIGNAL_RECEIVED;
Publisher<Void> result;
try {
result = writeFunction.apply(this);
}
catch (Throwable ex) {
this.writeCompletionBarrier.onError(ex);
return;
}
result.subscribe(this.writeCompletionBarrier);
}
else {
this.completed = true;
}
}
}
@Override
public Context currentContext() {
return this.writeCompletionBarrier.currentContext();
}
// Subscription methods (we're the Subscription to the writeSubscriber)..
@Override
public void request(long n) {
Subscription s = this.subscription;
if (s == null) {
return;
}
if (this.state == State.READY_TO_WRITE) {
s.request(n);
return;
}
synchronized (this) {
if (this.writeSubscriber != null) {
if (this.state == State.EMITTING_CACHED_SIGNALS) {
this.demandBeforeReadyToWrite = n;
return;
}
try {
this.state = State.EMITTING_CACHED_SIGNALS;
if (emitCachedSignals()) {
return;
}
n = n + this.demandBeforeReadyToWrite - 1;
if (n == 0) {
return;
}
}
finally {
this.state = State.READY_TO_WRITE;
}
}
}
s.request(n);
}
private boolean emitCachedSignals() {
if (this.error != null) {
try {
requiredWriteSubscriber().onError(this.error);
}
finally {
releaseCachedItem();
}
return true;
}
T item = this.item;
this.item = null;
if (item != null) {
requiredWriteSubscriber().onNext(item);
}
if (this.completed) {
requiredWriteSubscriber().onComplete();
return true;
}
return false;
}
@Override
public void cancel() {
Subscription s = this.subscription;
if (s != null) {
this.subscription = null;
try {
s.cancel();
}
finally {
releaseCachedItem();
}
}
}
private void releaseCachedItem() {
synchronized (this) {
Object item = this.item;
if (item instanceof DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
}
this.item = null;
}
}
// Publisher<T> methods (we're the Publisher to the writeSubscriber)..
@Override
public void subscribe(Subscriber<? super T> writeSubscriber) {
synchronized (this) {
Assert.state(this.writeSubscriber == null, "Only one write subscriber supported");
this.writeSubscriber = writeSubscriber;
if (this.error != null || this.completed) {
this.writeSubscriber.onSubscribe(Operators.emptySubscription());
emitCachedSignals();
}
else {
this.writeSubscriber.onSubscribe(this);
}
}
}
}
/**
* We need an extra barrier between the WriteBarrier itself and the actual
* completion subscriber.
*
* <p>The completionSubscriber is subscribed initially to the WriteBarrier.
* Later after the first signal is received, we need one more subscriber
* instance (per spec can only subscribe once) to subscribe to the write
* function and switch to delegating completion signals from it.
*/
private class WriteCompletionBarrier implements CoreSubscriber<Void>, Subscription {
/* Downstream write completion subscriber */
private final CoreSubscriber<? super Void> completionSubscriber;
private final WriteBarrier writeBarrier;
@Nullable
private Subscription subscription;
public WriteCompletionBarrier(CoreSubscriber<? super Void> subscriber, WriteBarrier writeBarrier) {
this.completionSubscriber = subscriber;
this.writeBarrier = writeBarrier;
}
/**
* Connect the underlying completion subscriber to this barrier in order
* to track cancel signals and pass them on to the write barrier.
*/
public void connect() {
this.completionSubscriber.onSubscribe(this);
}
// Subscriber methods (we're the subscriber to the write function)..
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(Void aVoid) {
}
@Override
public void onError(Throwable ex) {
try {
this.completionSubscriber.onError(ex);
}
finally {
this.writeBarrier.releaseCachedItem();
}
}
@Override
public void onComplete() {
this.completionSubscriber.onComplete();
}
@Override
public Context currentContext() {
return this.completionSubscriber.currentContext();
}
@Override
public void request(long n) {
// Ignore: we don't produce data
}
@Override
public void cancel() {
this.writeBarrier.cancel();
Subscription subscription = this.subscription;
if (subscription != null) {
subscription.cancel();
}
}
}
}
|
package com.cg.test.repository;
import com.cg.test.model.Country;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ICountryRepository extends JpaRepository<Country, Long> {
}
|
/* $Id$ */
package djudge.utils.xmlrpc;
import java.net.URL;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
public class RPCClientFactory
{
final static int defaultConnectionTimeout = 10000;
final static int defaultReplyTimeout = 10000;
XmlRpcClient client;
public static XmlRpcClient getRPCClient(String serverURL, int connectionTimeout, int replyTimeout)
{
XmlRpcClient client = null;
try
{
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(serverURL));
config.setEnabledForExtensions(true);
config.setConnectionTimeout(connectionTimeout);
config.setReplyTimeout(replyTimeout);
client = new XmlRpcClient();
// use Commons HttpClient as transport
client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
// set configuration
client.setConfig(config);
}
catch (Exception ex)
{
System.out.println("Exception in RPCClientFactory.getRPCClient:");
ex.printStackTrace();
}
return client;
}
public static XmlRpcClient getRPCClient(String serverURL)
{
return getRPCClient(serverURL, defaultConnectionTimeout, defaultReplyTimeout);
}
}
|
package com.google.android.libraries.photoeditor.filterparameters;
public class UPointParameter extends FilterParameter {
private static final int[] UPOINT_PARAM_TYPE = new int[]{0, 1, 2, 501, 502, 4, 201, 202, 203};
protected int[] getAutoParams() {
return UPOINT_PARAM_TYPE;
}
public int getDefaultValue(int param) {
return param == 4 ? 50 : 0;
}
public int getMaxValue(int param) {
switch (param) {
case 201:
return Integer.MAX_VALUE;
case 501:
case 502:
return 65535;
default:
return 100;
}
}
public int getMinValue(int param) {
switch (param) {
case 201:
return Integer.MIN_VALUE;
case 501:
case 502:
return 0;
default:
return -100;
}
}
public int getDefaultParameter() {
return 0;
}
public int getFilterType() {
return 300;
}
public int getX() {
return getParameterValueOld(501);
}
public int getY() {
return getParameterValueOld(502);
}
public void setCenterSize(int size) {
setParameterValueOld(4, size);
}
public int getCenterSize() {
return getParameterValueOld(4);
}
public void setRGBA(int rgba) {
setParameterValueOld(201, rgba);
}
public int getRGBA() {
return getParameterValueOld(201);
}
public void setInking(boolean inkingOn) {
setParameterValueOld(202, inkingOn ? 1 : 0);
}
public boolean isInking() {
return getParameterValueOld(202) != 0;
}
public void setSelected(boolean isSelected) {
setParameterValueOld(203, isSelected ? 1 : 0);
}
public boolean isSelected() {
return getParameterValueOld(203) != 0;
}
}
|
package br.com.rca.apkRevista.bancoDeDados.beans;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import br.com.rca.apkRevista.Parametros;
import br.com.rca.apkRevista.bancoDeDados.beans.interfaces.Bean;
import br.com.rca.apkRevista.bancoDeDados.beans.interfaces.Persistente;
import br.com.rca.apkRevista.bancoDeDados.dao.DAORevista;
import br.com.rca.apkRevista.bancoDeDados.excessoes.RevistaNaoEncontrada;
@Entity
public class Cliente implements Persistente,Bean{
@Id
@GeneratedValue
private int id;
private String user;
private String password;
private String email;
//TODO Implementar tratamentos para estas colunas
//@MapKey(name = "situacao_cliente")
//@Enumerated(EnumType.STRING)
//public Situacao situacao = Situacao.ATIVO;
//TODO Nao Implementado
//Neste caso será necessário criar um controle de permissão por usuario
//private int nivel = 1;
//TODO: private Date dataDeCadastro;
public Cliente(){
super();
}
public Cliente(String user, String password, String email) {
this.user = user;
this.password = password;
this.email = email;
}
public int getId(){
return id;
}
public String getUser() {
return user;
}
private String encryptPassword(String password)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : crypt.digest()) {
sb.append(String.format("%02x", b));
}
sha1 = sb.toString();
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
public boolean senhaCorreta(String senha){
String sha1 = encryptPassword(senha);
return password.equals(sha1);
}
public List<Revista> getRevistas(String where, String[] paramns) throws RevistaNaoEncontrada{
try {
/*TODO extrair este trecho, pois é usado tambem em Revista.getPagina() getCliente()*/
int lengthParamns2 = paramns.length + (where == "" ? 0 : 1);
lengthParamns2 += lengthParamns2 == 0 ? 1 : 0;
String[] paramns2 = new String[lengthParamns2];
paramns2[0] = getId() + "";
for (int i = 1; i < paramns2.length ; i++) {
paramns2[i] = paramns[i-1];
}
if(where == "")
where = "1 = 1";
List<Revista> retorno = DAORevista.getInstance().get(" cliente_id = ? and " + where, paramns2);
if(retorno.isEmpty()){
/*TODO Encontrar uma forma de extrair do where o nome da revista*/
throw new RevistaNaoEncontrada("", this);
}else{
return retorno;
}
} catch (Exception e) {
if(e instanceof RevistaNaoEncontrada)
throw (RevistaNaoEncontrada) e;
else{
e.printStackTrace();
return null;
}
}
}
public String getFolder() {
return Parametros.PASTA_RAIZ + File.separator + getUser();
}
public String getEmail(){
return email;
}
}
|
package com.example.dam.recetario;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.dam.recetario.ingrediente.GestorIngrediente;
import com.example.dam.recetario.ingrediente.Ingrediente;
import com.example.dam.recetario.receta.Receta;
import com.example.dam.recetario.receta_ingrediente.GestorRecetaIngrediente;
import com.example.dam.recetario.receta_ingrediente.RecetaIngrediente;
import java.util.ArrayList;
import java.util.List;
public class EditarIngredientes extends AppCompatActivity{
private GestorIngrediente gestorI;
private List<Ingrediente> lista;
private LinearLayout vl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incluir_ingredientes);
this.init();
}
public void init() {
Receta miReceta = (Receta) getIntent().getSerializableExtra("receta");
gestorI = new GestorIngrediente(this);
gestorI.openWrite();
GestorRecetaIngrediente gestorC = new GestorRecetaIngrediente(this);
gestorC.openRead();
List<RecetaIngrediente> recetaIngredientes = gestorC.selectCantidadesReceta(miReceta);
List<String> cantidades= new ArrayList<>();
for (RecetaIngrediente cant : recetaIngredientes) {
cantidades.add(cant.getCantidad());
}
vl = (LinearLayout) findViewById(R.id.lVerticalIngredientes);
lista = gestorI.selectIngredientes();
for (Ingrediente ing : lista) {
LinearLayout horizontal = new LinearLayout(this);
CheckBox check = new CheckBox(this);
check.setText("");
if(searchid(ing.getId(), recetaIngredientes))
check.setChecked(true);
TextView tv = new TextView(this);
tv.setText(ing.getNombre());
EditText et = new EditText(this);
et.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
et.setText(searchCantidad(ing.getId(),recetaIngredientes));
horizontal.addView(check);
horizontal.addView(tv);
horizontal.addView(et);
vl.addView(horizontal);
}
}
private boolean searchid(long idIngrediente, List<RecetaIngrediente> recing){
for (RecetaIngrediente cant : recing) {
if(cant.getIdIngrediente()==idIngrediente)
return true;
}
return false;
}
private String searchCantidad(long idIngrediente, List<RecetaIngrediente> recing){
for (RecetaIngrediente cant : recing) {
if(cant.getIdIngrediente()==idIngrediente)
return cant.getCantidad();
}
return "";
}
public void nuevoIngrediente(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Nuevo ingrediente");
final View view = LayoutInflater.from(this).inflate(R.layout.dialog_nuevo_ingrediente, null);
alert.setView(view);
DialogInterface.OnClickListener listenerSearch = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText et = (EditText) view.findViewById(R.id.etNew);
String nuevo = et.getText().toString();
Ingrediente ingre = new Ingrediente(nuevo);
gestorI.insert(ingre);
LinearLayout vl = (LinearLayout) findViewById(R.id.lVerticalIngredientes);
LinearLayout horizontal = new LinearLayout(EditarIngredientes.this);
CheckBox check = new CheckBox(EditarIngredientes.this);
TextView tv = new TextView(EditarIngredientes.this);
EditText edit = new EditText(EditarIngredientes.this);
edit.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
check.setText("");
tv.setText(nuevo);
horizontal.addView(check);
horizontal.addView(tv);
horizontal.addView(edit);
vl.addView(horizontal);
}
};
alert.setPositiveButton("Agregar", listenerSearch);
alert.setNegativeButton("Cancelar", null);
alert.show();
}
public void incluir(View v) {
int children = vl.getChildCount();
String[] ingredientes = new String[0];
for (int i = 0; i < children; i++) {
LinearLayout hl = (LinearLayout) vl.getChildAt(i);
CheckBox cb = (CheckBox) hl.getChildAt(0);
TextView tv = (TextView) hl.getChildAt(1);
EditText et = (EditText) hl.getChildAt(2);
if (cb.isChecked()) {
String[] masingredientes = new String[ingredientes.length + 2];
int j = 0;
if (ingredientes.length != 0) {
for (j = 0; j < ingredientes.length; j++) {
masingredientes[j] = ingredientes[j];
}
}
masingredientes[j] = tv.getText().toString();
masingredientes[j+1] = et.getText().toString();
ingredientes= masingredientes;
}
}
gestorI.close();
this.getIntent().putExtra("ingre", ingredientes);
setResult(RESULT_OK, this.getIntent());
finish();
}
public void cancel(View v){
finish();
}
}
|
package sr.hakrinbank.intranet.api.service;
import sr.hakrinbank.intranet.api.model.NewsPv;
import java.util.List;
/**
* Created by clint on 8/3/17.
*/
public interface NewsPvService {
List<NewsPv> findAllNewsPv();
NewsPv findById(long id);
void updateNewsPv(NewsPv module);
List<NewsPv> findAllActiveNewsPv();
NewsPv findByName(String name);
List<NewsPv> findAllActiveNewsPvBySearchQuery(String qry);
int countNewsPvOfTheWeek();
List<NewsPv> findAllActiveNewsPvOrderedByDate();
List<NewsPv> findAllActiveNewsPvBySearchQueryOrDate(String byTitle, String byDate);
}
|
package io.gtrain.router;
import io.gtrain.handler.EmailVerificationHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
/**
* @author William Gentry
*/
@Configuration
public class EmailVerificationRouter {
private final EmailVerificationHandler emailVerificationHandler;
public EmailVerificationRouter(EmailVerificationHandler emailVerificationHandler) {
this.emailVerificationHandler = emailVerificationHandler;
}
@Bean
public RouterFunction<ServerResponse> emailVerificationRouterBean() {
return RouterFunctions.route(GET("/verify/email"), emailVerificationHandler::handleEmailVerification);
}
}
|
package com.toda.consultant;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.toda.consultant.util.Ikeys;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by yangwei on 2016/12/8.
*/
public class PositionPeripheryMapActivity extends BaseActivity {
@BindView(R.id.map)
MapView map;
private double latitude;
private double longitude;
private AMap aMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_periphery_map);
initView();
map.onCreate(savedInstanceState);
getData();
setUi();
}
private void setUi() {
setTitle("项目位置");
aMap = map.getMap();
aMap.getUiSettings().setZoomControlsEnabled(false);
//绘制marker
aMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
.decodeResource(getResources(), R.mipmap.ic_location)))
.draggable(true));
aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(
latitude, longitude)));
}
private void getData() {
Bundle bd = getIntentData();
if (bd == null) return;
latitude = bd.getDouble(Ikeys.KEY_LATITUDE);
longitude = bd.getDouble(Ikeys.KEY_LONGITUDE);
}
@Override
public void initView() {
ButterKnife.bind(this);
}
}
|
package com.clouway.task2;
public class TreeNode {
private Object data = null;
private TreeNode parent = null;
private TreeNode [] children = {null, null};
/**
* Constructor setting a parent
* @param parent
*/
public TreeNode(TreeNode parent){
this.parent = parent;
}
/**
* Constructor setting a parent and initial data
* @param parent
* @param data
*/
public TreeNode(TreeNode parent, Object data){
this.parent = parent;
this.data = data;
}
/**
* Set the node data object
* @param data
*/
public void setData(Object data){
this.data = data;
}
/**
* Return the node data object
* @return
*/
public Object getData(){
return this.data;
}
/**
* Return the parent node
* @return
*/
public TreeNode getParent(){
return this.parent;
}
/**
* Return an array of all valid(non-null) children
* @return
*/
public TreeNode [] getChildren(){
int validInd = 0;
TreeNode [] validChildren = new TreeNode[childrenCount()];
for(TreeNode child : this.children){
if(child != null){
validChildren[validInd] = child;
validInd ++;
}
}
return validChildren;
}
/**
* Return the number of valid(non-null) children
* @return
*/
public int childrenCount(){
int count = 0;
for(TreeNode child : this.children){
if(child != null){
count ++;
}
}
return count;
}
/**
* Add a child node. Returns true on success or false if
* no more children can be added.
* @param child
* @return
*/
public boolean addChild(TreeNode child){
int childrenCnt = childrenCount();
if(childrenCnt >= this.children.length){
return false;
}
this.children[childrenCnt] = child;
return true;
}
}
|
import java.util.Vector;
public class triangolo extends poligono{
private static double numeroFisso = 0.289;
public triangolo(int i , Vector<punto> p){
super(i,p);
}
public triangolo() {
super(0);
}
public double getfisso(){
return numeroFisso;
}
public double perimetro(){
return (pt.get(0)).distancefromtwopoints(pt.get(1)) + (pt.get(1)).distancefromtwopoints(pt.get(2)) + (pt.get(0)).distancefromtwopoints(pt.get(2));
}
public double area(){
double base = (pt.get(0)).distancefromtwopoints(pt.get(1)) ;
double h = ((pt.get(0)).rettafromtwopoints(pt.get(1))).distancePuntoRetta(pt.get(2));
return (base*h)/2;
}
public double lato(){
double a = ((pt.get(1)).distancefromtwopoints(pt.get(2)));
double b = ((pt.get(0)).distancefromtwopoints(pt.get(2)));
double c = ((pt.get(0)).distancefromtwopoints(pt.get(1)));
if(a == b ){
if(a == c)
return (pt.get(1)).distancefromtwopoints(pt.get(2));
}
return 0; //non regolare
}
}
|
package org.dajlab.mondialrelayapi.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Classe Java pour ret_WSI2_AdressePointRelais complex type.
*
* <p>
* Le fragment de schéma suivant indique le contenu attendu figurant dans cette
* classe.
*
* <pre>
* <complexType name="ret_WSI2_AdressePointRelais">
* <complexContent>
* <extension base="{http://www.mondialrelay.fr/webservice/}ret_">
* <sequence>
* <element name="LgAdr1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="LgAdr2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="LgAdr3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="LgAdr4" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CP" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Ville" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ret_WSI2_AdressePointRelais", propOrder = { "lgAdr1", "lgAdr2", "lgAdr3", "lgAdr4", "cp", "ville" })
public class RetWSI2AdressePointRelais extends Ret {
@XmlElement(name = "LgAdr1")
protected String lgAdr1;
@XmlElement(name = "LgAdr2")
protected String lgAdr2;
@XmlElement(name = "LgAdr3")
protected String lgAdr3;
@XmlElement(name = "LgAdr4")
protected String lgAdr4;
@XmlElement(name = "CP")
protected String cp;
@XmlElement(name = "Ville")
protected String ville;
/**
* Obtient la valeur de la propriété lgAdr1.
*
* @return possible object is {@link String }
*
*/
public String getLgAdr1() {
return lgAdr1;
}
/**
* Définit la valeur de la propriété lgAdr1.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLgAdr1(String value) {
this.lgAdr1 = value;
}
/**
* Obtient la valeur de la propriété lgAdr2.
*
* @return possible object is {@link String }
*
*/
public String getLgAdr2() {
return lgAdr2;
}
/**
* Définit la valeur de la propriété lgAdr2.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLgAdr2(String value) {
this.lgAdr2 = value;
}
/**
* Obtient la valeur de la propriété lgAdr3.
*
* @return possible object is {@link String }
*
*/
public String getLgAdr3() {
return lgAdr3;
}
/**
* Définit la valeur de la propriété lgAdr3.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLgAdr3(String value) {
this.lgAdr3 = value;
}
/**
* Obtient la valeur de la propriété lgAdr4.
*
* @return possible object is {@link String }
*
*/
public String getLgAdr4() {
return lgAdr4;
}
/**
* Définit la valeur de la propriété lgAdr4.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLgAdr4(String value) {
this.lgAdr4 = value;
}
/**
* Obtient la valeur de la propriété cp.
*
* @return possible object is {@link String }
*
*/
public String getCP() {
return cp;
}
/**
* Définit la valeur de la propriété cp.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCP(String value) {
this.cp = value;
}
/**
* Obtient la valeur de la propriété ville.
*
* @return possible object is {@link String }
*
*/
public String getVille() {
return ville;
}
/**
* Définit la valeur de la propriété ville.
*
* @param value
* allowed object is {@link String }
*
*/
public void setVille(String value) {
this.ville = value;
}
}
|
package com.git.cloud.policy.model.po;
import com.git.cloud.common.model.base.BaseBO;
/**
* @Title RmVmRulesPo.java
* @Package com.git.cloud.policy.model.po
* @author yangzhenhai
* @date 2014-9-11 下午4:29:58
* @version 1.0.0
* @Description
*
*/
public class RmVmRulesPo extends BaseBO implements java.io.Serializable{
// Fields
private String rulesId;//主键
private String sortObject;//排序对象
private String sortType;//排序方式
private String isActive;//是否有效
// Constructors
/** default constructor */
public RmVmRulesPo() {
}
/** full constructor */
public RmVmRulesPo(String rulesId, String sortObject, String sortType,
String isActive) {
this.rulesId = rulesId;
this.sortObject = sortObject;
this.sortType = sortType;
this.isActive = isActive;
}
// Property accessors
public String getRulesId() {
return this.rulesId;
}
public void setRulesId(String rulesId) {
this.rulesId = rulesId;
}
public String getSortObject() {
return this.sortObject;
}
public void setSortObject(String sortObject) {
this.sortObject = sortObject;
}
public String getSortType() {
return this.sortType;
}
public void setSortType(String sortType) {
this.sortType = sortType;
}
public String getIsActive() {
return this.isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
/* (non-Javadoc)
* @see com.git.cloud.common.model.base.BaseBO#getBizId()
*/
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.kueblearn.user_service.service;
import com.kueblearn.user_service.domain.Role;
import com.kueblearn.user_service.domain.User;
import com.kueblearn.user_service.model.UserDTO;
import com.kueblearn.user_service.repos.RoleRepository;
import com.kueblearn.user_service.repos.UserRepository;
import java.util.List;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
@Transactional
@Service
public class UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
public UserService(final UserRepository userRepository, final RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
public List<UserDTO> findAll() {
return userRepository.findAll()
.stream()
.map(user -> mapToDTO(user, new UserDTO()))
.collect(Collectors.toList());
}
public UserDTO get(final Long id) {
return userRepository.findById(id)
.map(user -> mapToDTO(user, new UserDTO()))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
public Long create(final UserDTO userDTO) {
final User user = new User();
mapToEntity(userDTO, user);
return userRepository.save(user).getId();
}
public void update(final Long id, final UserDTO userDTO) {
final User user = userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
mapToEntity(userDTO, user);
userRepository.save(user);
}
public void delete(final Long id) {
userRepository.deleteById(id);
}
private UserDTO mapToDTO(final User user, final UserDTO userDTO) {
userDTO.setId(user.getId());
userDTO.setName(user.getName());
userDTO.setLoginName(user.getLoginName());
userDTO.setUserRoless(user.getUserRolesRoles() == null ? null : user.getUserRolesRoles().stream()
.map((role) -> role.getId())
.collect(Collectors.toList()));
return userDTO;
}
private User mapToEntity(final UserDTO userDTO, final User user) {
user.setName(userDTO.getName());
user.setLoginName(userDTO.getLoginName());
if (userDTO.getUserRoless() != null) {
final List<Role> userRoless = roleRepository.findAllById(userDTO.getUserRoless());
if (userRoless.size() != userDTO.getUserRoless().size()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "one of userRoless not found");
}
user.setUserRolesRoles(userRoless.stream().collect(Collectors.toSet()));
}
return user;
}
}
|
package com.ws.serlvet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ws.bean.Student;
/**
* 测试 gt-grid组件的复杂使用
* @author whn
* @date 2014-03-13
*/
public class GtgridServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("开始执行gt-grid");
/*ObjectMapper objectMapper = new ObjectMapper();
JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
jsonGenerator.writeObject(this.getStus());*/
List<Student> stus = this.getStus();
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0;i<stus.size();i++){
if(i==stus.size()-1){
sb.append( "{ no :"+ stus.get(i).getNo()+", name :'"+stus.get(i).getName()+"', age :"+stus.get(i).getAge()+", gender : '"+stus.get(i).getGender()+"' , english : "+stus.get(i).getEnglish()+" , math :"+stus.get(i).getMath()+" }");
}else{
sb.append( "{ no :"+ stus.get(i).getNo()+", name :'"+stus.get(i).getName()+"', age :"+stus.get(i).getAge()+", gender : '"+stus.get(i).getGender()+"' , english : "+stus.get(i).getEnglish()+" , math :"+stus.get(i).getMath()+" },");
}
}
sb.append("]");
PrintWriter out = resp.getWriter();
String result = sb.toString();
System.out.println(result);
out.print(result.trim());
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
//获取100个学生
public List<Student> getStus(){
DecimalFormat df=new DecimalFormat("#.00");
List<Student> list = new ArrayList<Student>();
for (int i=0;i<10;i++){
Student stu = new Student();
stu.setAge((int)(Math.random()*80));
stu.setGender(-1*i+"");
stu.setEnglish(Double.parseDouble(df.format(Math.random()*120+10)));
stu.setMath(Double.parseDouble(df.format(Math.random()*120+10)));
stu.setNo(i);
stu.setName("stu"+i);
list.add(stu);
}
return list;
}
}
|
package com.krish.thread;
public class DeadLockTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
firstThread();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
secondThread();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
public static Object lock1 = new Object();
public static Object lock2 = new Object();
public static void firstThread() throws InterruptedException {
synchronized (lock1) {
System.out.println("Thread 1 has aquired lock 1");
Thread.sleep(10);
System.out.println("Thread 1 is waiting to aquired lock 2");
synchronized (lock2) {
System.out.println("Thread 1 has aquired lock 2");
}
}
}
public static void secondThread() throws InterruptedException {
synchronized (lock2) {
System.out.println("Thread 2 has aquired lock 2");
Thread.sleep(10);
System.out.println("Thread 2 is waiting to aquired lock 1");
synchronized (lock1) {
System.out.println("Thread 2 has aquired lock 1");
}
}
}
}
|
package heylichen.sort.pq;
public interface PriorityComparator<T> {
/**
* compare the priority of a to b
* @param a
* @param b
* @return true if priority of a is higher than b,
* false if priority of a is less than or equal to b
*/
boolean higherThan(T a, T b);
}
|
package vazkii.morphtool;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.block.BlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Rotation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import vazkii.arl.item.BasicItem;
import vazkii.arl.util.TooltipHandler;
public class MorphToolItem extends BasicItem {
public MorphToolItem() {
super("morphtool:tool", new Properties().maxStackSize(1).group(ItemGroup.TOOLS));
}
@Override
public ActionResultType onItemUse(ItemUseContext context) {
BlockState block = context.getWorld().getBlockState(context.getPos());
block.rotate(context.getWorld(), context.getPos(), Rotation.CLOCKWISE_90);
return super.onItemUse(context);
}
@Override
public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag advanced) {
if(!stack.hasTag() || !stack.getTag().contains(MorphingHandler.TAG_MORPH_TOOL_DATA))
return;
CompoundNBT data = stack.getTag().getCompound(MorphingHandler.TAG_MORPH_TOOL_DATA);
if(data.keySet().size() == 0)
return;
List<String> tooltipList = new ArrayList<>();
TooltipHandler.tooltipIfShift(tooltipList, () -> {
for(String s : data.keySet()) {
CompoundNBT cmp = data.getCompound(s);
if(cmp != null) {
ItemStack modStack = ItemStack.read(cmp);
if(!stack.isEmpty()) {
String name = modStack.getDisplayName().getString();
if(modStack.hasTag() && modStack.getTag().contains(MorphingHandler.TAG_MORPH_TOOL_DISPLAY_NAME))
name = ((CompoundNBT) modStack.getTag().get(MorphingHandler.TAG_MORPH_TOOL_DISPLAY_NAME)).getString("text");
String mod = MorphingHandler.getModFromStack(modStack);
tooltip.add(new StringTextComponent(" " + mod + " : " + name));
}
}
}
}
);
tooltipList.forEach(tip -> tooltip.add(new StringTextComponent(tip)));
}
}
|
package com.jd.ipc.mapreduce.r;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.log4j.Logger;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import com.jd.ipc.mapreduce.r.util.RConnectionUtil;
public class RMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
private Logger log = Logger.getLogger(getClass().getName());
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
RConnection c = null;
try {
c = RConnectionUtil.getRConnection();
double[] i = { 1, 2, 4, 0, 1, 3, 1, 11, 1, 12, 1, 7, 1, 9, 17 };
c.assign("xw", i);
c.eval(" fit<-arima(xw,order=c(1,1,1)) ");
c.eval("lh.pred<- predict(fit,n.ahead=7)");
@SuppressWarnings("unused")
RList x = c.eval("lh.pred[1]").asList();
} catch (Exception e) {
log.error(e);
throw new RuntimeException(e);
} finally {
RConnectionUtil.returnRConnection(c);
}
}
}
|
import java.util.*;
import java.io.*;
import java.lang.*;
public class QuestionNo1
{
public static int maxActivities(int start[], int end[], int total)
{
int count;
if(total>0){
Arrays.sort(end);
int i=0, j;
count = 1;
for (j = 1; j < total; j++)
{
if (start[j] >= end[i])
{
count++;
i = j;
}
}
return count;
}
else{
return count = 0;
}
}
public static void main(String[] args)
{
int start[] = {2, 1};
int end[] = {2, 2};
int total = start.length;
int result = maxActivities(start, end, total);
System.out.println(result);
}
}
|
package Iterators;
public class NumberPyramid3 {
public static void main(String[] args) {
for(int count = 1; count<=5;count++) {
for(int count2 = 5; count2>=count; count2--) {
System.out.print("*");
}
for(int count3 = 1; count3 <= count; count3++) {
System.out.print(count - count3 + 1);
}
for(int count4 = 2; count4 <= count; count4++) {
System.out.print(count4);
}
System.out.println();
}
}
}
|
package se.avelon.daidalos.fragments;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import se.avelon.daidalos.Debug;
import se.avelon.daidalos.R;
import se.avelon.daidalos.Utilities;
public class MediaFragment2 extends AbstractFragment {
private static final String TAG = MediaFragment2.class.getSimpleName();
private MediaCodec encoder;
public String getTitle() {return "Medida";};
public int getIcon() {return R.drawable.media;};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.media, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/* DISPLAYS */
DisplayManager manager = (DisplayManager)this.getContext().getSystemService(Context.DISPLAY_SERVICE);
Debug.e(TAG, "manager=" + manager);
/* CODECS */
ArrayList codecList = new ArrayList();
codecList.add("Codecs:");
MediaCodecList codecs = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
for(MediaCodecInfo info : codecs.getCodecInfos()) {
for(String type : info.getSupportedTypes()) {
codecList.add("" + type + " (" + info.getName() + ")");
}
}
Utilities.spinner(view, R.id.mediaCodecs, codecList);
/* VIDEO FORMAT */
MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1280, 720);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 15); //fps
format.setInteger(MediaFormat.KEY_CAPTURE_RATE, 30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10); //seconds
ArrayList formatList = new ArrayList();;
formatList.add("Format:");
formatList.add("KEY_MIME=" + format.getString(MediaFormat.KEY_MIME));
formatList.add("KEY_COLOR_FORMAT=" + format.getInteger(MediaFormat.KEY_COLOR_FORMAT));
formatList.add("KEY_BIT_RATE=" + format.getInteger(MediaFormat.KEY_BIT_RATE));
formatList.add("KEY_FRAME_RATE=" + format.getInteger(MediaFormat.KEY_FRAME_RATE));
formatList.add("KEY_I_FRAME_INTERVAL=" + format.getInteger(MediaFormat.KEY_I_FRAME_INTERVAL));
formatList.add("KEY_WIDTH=" + format.getInteger(MediaFormat.KEY_WIDTH));
formatList.add("KEY_HEIGHT=" + format.getInteger(MediaFormat.KEY_HEIGHT));
formatList.add("KEY_CAPTURE_RATE=" + format.getInteger(MediaFormat.KEY_CAPTURE_RATE));
Utilities.spinner(view, R.id.mediaFormat, formatList);
/* SELECT A CODEC THAT FITS */
String codec = codecs.findEncoderForFormat(format);
Debug.e(TAG, "codec=" + codec);
try {
encoder = MediaCodec.createByCodecName(codec);
encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
Debug.e(TAG, "encorder=" + encoder.getCodecInfo());
final Surface surface = encoder.createInputSurface();
Debug.e(TAG, "surface=" + surface);
VirtualDisplay display = manager.createVirtualDisplay("MyVirtualDevice", 640, 400, DisplayMetrics.DENSITY_HIGH, surface, 0);
encoder.setCallback(new MediaCodec.Callback() {
@Override
public void onInputBufferAvailable(@NonNull MediaCodec codec, int index) {
Debug.e(TAG, "onInputBufferAvailable");
ByteBuffer inputBuffer = codec.getInputBuffer(index);
//codec.queueInputBuffer(index, -1);
}
@Override
public void onOutputBufferAvailable(@NonNull MediaCodec codec, int index, @NonNull MediaCodec.BufferInfo info) {
Debug.e(TAG, "onOutputBufferAvailable");
Debug.e(TAG, "index=" + index);
Debug.e(TAG, "info=" + info.size);
MediaFormat format = codec.getOutputFormat(index); // option A
Debug.e(TAG, "format=" + format);
ByteBuffer buffer = codec.getOutputBuffer(index);
ShortBuffer samples = buffer.asShortBuffer();
//encoder.flush();
//encoder.dequeueInputBuffer(-1);
// for(int i = 0 ; i < info.size; i++) {
// Debug.e(TAG, "array["+ i + "] = " + buffer.get());
// }
}
// 3618 = 2 * 3 * 3 * 3 * 67
@Override
public void onError(@NonNull MediaCodec codec, @NonNull MediaCodec.CodecException e) {
Debug.e(TAG, "onError");
}
@Override
public void onOutputFormatChanged(@NonNull MediaCodec codec, @NonNull MediaFormat format) {
Debug.e(TAG, "onOutputFormatChanged");
Debug.e(TAG, "format=" + format);
}
});
encoder.start();
//Canvas canvas = surface.lockHardwareCanvas();
//Paint paint = new Paint();
//paint.setStyle(Paint.Style.FILL);
//canvas.drawCircle(100, 100, 50, paint);
Debug.e(TAG, "Here we leave");
Camera camera = Camera.open();
camera.setPreviewCallback(new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
Debug.e(TAG, "Camera " + data.length);
Camera.Parameters parameters = camera.getParameters();
Debug.e(TAG, "size=" + parameters.getPictureSize().height + ":" + parameters.getPictureSize().width);
Debug.e(TAG, "flatten=" + parameters.flatten());
encode(null);
}
});
camera.startPreview();
//encoder.stop();
//encoder.release();
//display.release();
}
catch(IOException e) {
Debug.e(TAG, "exception=" + e);
}
ArrayList displayList = new ArrayList();
displayList.add("Displays:");
VirtualDisplay vDisplay = manager.createVirtualDisplay("me", 640, 400, 16, null, 0);
for(Display display : manager.getDisplays()) {
for(Display.Mode mode : display.getSupportedModes()) {
displayList.add("" + display.getDisplayId() + ". " + display.getName() + " (" + mode.getPhysicalWidth() + "x" + mode.getPhysicalHeight() + " " + mode.getRefreshRate() + " fps)");
}
}
Utilities.spinner(view, R.id.mediaDisplays, displayList);
}
public synchronized void encode(byte[] bytes) {
Debug.e(TAG, "encode()");
//ByteBuffer[] ob = encoder.getOutputBuffers();
//ByteBuffer[] ib = encoder.getInputBuffers();
}
}
|
package org.tempuri;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GetAllBasisRolesResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"getAllBasisRolesResult"
})
@XmlRootElement(name = "GetAllBasisRolesResponse")
public class GetAllBasisRolesResponse {
@XmlElement(name = "GetAllBasisRolesResult")
protected String getAllBasisRolesResult;
/**
* Gets the value of the getAllBasisRolesResult property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGetAllBasisRolesResult() {
return getAllBasisRolesResult;
}
/**
* Sets the value of the getAllBasisRolesResult property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGetAllBasisRolesResult(String value) {
this.getAllBasisRolesResult = value;
}
}
|
package com.gsccs.sme.plat.svg.dao;
import com.gsccs.sme.plat.svg.model.SitemT;
import com.gsccs.sme.plat.svg.model.SitemTExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SitemTMapper {
int countByExample(SitemTExample example);
int deleteByExample(SitemTExample example);
int deleteByPrimaryKey(Long id);
int insert(SitemT record);
int insertSelective(SitemT record);
List<SitemT> selectByExampleWithBLOBs(SitemTExample example);
List<SitemT> selectByExample(SitemTExample example);
SitemT selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") SitemT record, @Param("example") SitemTExample example);
int updateByExampleWithBLOBs(@Param("record") SitemT record, @Param("example") SitemTExample example);
int updateByExample(@Param("record") SitemT record, @Param("example") SitemTExample example);
int updateByPrimaryKeySelective(SitemT record);
int updateByPrimaryKeyWithBLOBs(SitemT record);
int updateByPrimaryKey(SitemT record);
List<SitemT> selectPageByExample(SitemTExample example);
}
|
/**
* The classes in this package represent the JPA implementation
* of ContainerBank's persistence layer.
*/
package org.hackathon.packapp.containerbank.repository.jpa;
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.LuckyDraw;
@Repository("luckyDrawDAO")
public class LuckyDrawDAO extends GenericDAO<LuckyDraw>{
}
|
package com.konew.musicapp.model.response;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import java.util.List;
@Builder
@Getter
@Setter
public class TrackResponse
{
private Long id;
private String title;
private String artist;
private int deezerRanking;
private String deezerLink;
private Date releaseDate;
private String mp3Url;
private Long deezerId;
}
|
package com.factory.factorydeletedetails;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FactoryDeleteDetailsApplication {
public static void main(String[] args) {
SpringApplication.run(FactoryDeleteDetailsApplication.class, args);
}
}
|
package com.worldchip.bbpaw.bootsetting.util;
import java.util.List;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.util.Log;
import com.worldchip.bbpaw.bootsetting.R;
public class WifiUtils {
public static final int SINGAL_NONE_INDEX = 0;
public static final int SINGAL_WEAK_INDEX = 1;
public static final int SINGAL_GENERAL_INDEX = 2;
public static final int SINGAL_GOOD_INDEX = 3;
public static final int SECURITY_NONE = 0;
public static final int SECURITY_WEP = 1;
public static final int SECURITY_PSK = 2;
public static final int SECURITY_EAP = 3;
public static final int[] SINGAL_IMG_RES = {
R.drawable.wifi_signal0,R.drawable.wifi_signal1,
R.drawable.wifi_signal2,R.drawable.wifi_signal3};
/** Anything worse than or equal to this will show 0 bars. */
private static final int MIN_RSSI = -100;
/** Anything better than or equal to this will show the max bars. */
private static final int MAX_RSSI = -55;
/**
* 获取信号强度图标
* @return
*/
public static int getWifiSingalImgRes(int singalNum) {
int numLevels = SINGAL_IMG_RES.length;
int level = 0;
if (singalNum <= MIN_RSSI) {
level = 0;
} else if (singalNum >= MAX_RSSI) {
level = numLevels - 1;
} else {
int partitionSize = (MAX_RSSI - MIN_RSSI) / (numLevels - 1);
level = (singalNum - MIN_RSSI) / partitionSize;
}
return SINGAL_IMG_RES[level];
}
/**
* 判断此wifi是否加密
* @return
*/
public static boolean isSecurity(ScanResult result) {
if (result.capabilities.equals("NONE")) {
return false;
}
return true;
}
/**
* 按强度排序wifi列表
*/
public static void sortResultListForWifiSignal(List<ScanResult> scanResultList) {
for (int i = 0; i < scanResultList.size() - 1; i++) {
for (int j = i + 1; j < scanResultList.size(); j++) {
if (scanResultList.get(i).level < scanResultList.get(j).level) {
ScanResult temp = null;
temp = scanResultList.get(i);
scanResultList.set(i, scanResultList.get(j));
scanResultList.set(j, temp);
}
}
}
}
public static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
public static int getSecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
}
|
package com.cht.training.Lab11;
public abstract class Employee {
public int getSalary(){
return 0;
}
abstract void working(); //若 class下有方法被宣告為abstract,calss也必須為abstract
}
|
package threadtest;
public class ThreadYieldDemo {
public static void main( String[] args )
{
MyThreadYield t = new MyThreadYield();
t.start();
for( int i = 0; i<10; i++)
{
System.out.println("Main thread");
}
}
}
class MyThreadYield extends Thread{
public void run()
{
for( int i = 0; i<10; i++)
{
System.out.println("Child Thread");
//Thread.yield();
}
}
}
|
/*
* Written by Erhan Sezerer
* Contact <erhansezerer@iyte.edu.tr> for comments and bug reports
*
* Copyright (C) 2014 Erhan Sezerer
*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.darg.NLPOperations.dictionary;
import java.util.ArrayList;
import com.darg.NLPOperations.dictionary.model.WordNet;
import com.darg.NLPOperations.dictionary.model.WordNetSense;
import com.darg.NLPOperations.dictionary.model.WordNetWord;
import com.darg.NLPOperations.pos.util.POSTagWordNet;
public class WordNetParser
{
private WordNet version;
public WordNetParser(final WordNet version)
{
this.version = version;
}
/*---------------------------------------------------------------------------*/
// FUNCTIONS
/*---------------------------------------------------------------------------*/
/**parses the index files of the WordNet dictionary. and return all of the elements
* in an array. Compatible with WordNet 3.0
*
*
*
* @author erhan sezerer
*
* @param text - a String instance corresponding to a text that is read from an index file
* (index.noun, index.adverb etc.)
*
* @return ArrayList<WordNetWord> - a list of words contained in that text. returns null if there is any error
* concerning the input such ass wrong file structure.
*/
public synchronized ArrayList<WordNetWord> parseWordNetIndex(final String text)
{
ArrayList<WordNetWord> tempList = null;
switch(version)
{
case VERSION_30: tempList = parseWordNetIndex30(text);
break;
default: tempList = null;
}
return tempList;
}
/**parses the sense file of the WordNet dictionary. and return all of the elements
* in an array. Compatible with WordNet 3.0
*
*
*
* @author erhan sezerer
*
* @param text - a String instance corresponding to a text that is read from a sense file (index.sense)
*
* @return ArrayList<WordNetWord> - a list of words contained in that text. returns null if there is any error
* concerning the input such ass wrong file structure. */
public synchronized ArrayList<WordNetSense> parseWordNetSense(final String text)
{
ArrayList<WordNetSense> tempList = null;
switch(version)
{
case VERSION_30: tempList = parseWordNetSense30(text);
break;
default: tempList = null;
}
return tempList;
}
/**parses the index files of the WordNet dictionary. and return all of the elements
* in an array.
* For version 3.0
*
*
*
* @author erhan sezerer
*
* @param text - a String instance corresponding to a text that is read from an index file
* (index.noun, index.adverb etc.)
*
* @return ArrayList<WordNetWord> - a list of words contained in that text. returns null if there is any error
* concerning the input such ass wrong file structure.
*/
private synchronized ArrayList<WordNetWord> parseWordNetIndex30(final String text)
{
WordNetWord wordNetWord = null;
ArrayList<WordNetWord> words = new ArrayList<WordNetWord>();
String word = null;
POSTagWordNet pos;
try
{
if(text != null && text.length() >= 2)//if the text is acceptable
{
String[] lines = text.split("\n");
for(String line: lines)//for each line
{
String[] tempWords = line.split(" ");
if(tempWords[0].length() >= 1)//if it is a comment line it will be empty string
{
word = tempWords[0];
if(tempWords[1].length() == 1)//check for pos tag
{
pos = POSTagWordNet.getPosType(tempWords[1].charAt(0));
if(pos == POSTagWordNet.OTHER)
{
throw new IllegalArgumentException("Illegal pos tag: " + tempWords[1]);
}
}
else
{
throw new IllegalArgumentException("Unexpected argument: " + tempWords[1]);
}
int count = tempWords.length-1;
String tempid = tempWords[count];
wordNetWord = new WordNetWord(word, pos);
while(tempid.length() == 8)//check for corresponding id's
{
wordNetWord.addId(Integer.parseInt(tempid));
count--;
tempid = tempWords[count];
}
words.add(wordNetWord);
}
}
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
words = null;
}
return words;
}
/**parses the sense file of the WordNet dictionary. and return all of the elements
* in an array.
* For version 3.0
*
*
*
* @author erhan sezerer
*
* @param text - a String instance corresponding to a text that is read from a sense file (index.sense)
*
* @return ArrayList<WordNetWord> - a list of words contained in that text. returns null if there is any error
* concerning the input such ass wrong file structure. */
private synchronized ArrayList<WordNetSense> parseWordNetSense30(final String text)
{
ArrayList<WordNetSense> words = new ArrayList<WordNetSense>();
String word = null;
POSTagWordNet pos;
int id = 0;
int senseNumber = 0;
try
{
if(text != null && text.length() >= 2)//if the text is acceptable
{
String[] lines = text.split("\n");
for(String line: lines)//for each line
{
String[] tempWords = line.split(":");
if(tempWords[0].length() >= 1)
{
String[] temp = tempWords[0].split("%");
if(temp.length != 2)
{
throw new IllegalArgumentException("illegal arguments at: " + line);
}
else
{
word = temp[0];
switch(Integer.parseInt(temp[1]))
{
case 1: pos = POSTagWordNet.NOUN;
break;
case 2: pos = POSTagWordNet.VERB;
break;
case 3: pos = POSTagWordNet.ADJECTIVE;
break;
case 4: pos = POSTagWordNet.ADVERB;
break;
case 5: pos = POSTagWordNet.ADJECTIVE;
break;
default: throw new IllegalArgumentException("illegal pos tag at: " + line);
}
}
}
else
{
throw new IllegalArgumentException("illegal argument at: " + line);
}
String tempString = tempWords[tempWords.length-1];
if(tempString.length() >= 8)
{
tempWords = tempString.trim().split(" ");
//get the id
tempString = tempWords[tempWords.length-3];
if(tempString == null || tempString.length() != 8)
{
throw new IllegalArgumentException("illegal argument at: " + line);
}
id = Integer.parseInt(tempString);
//get the sense number
tempString = tempWords[tempWords.length-2];
if(tempString == null || tempString.length() >= 3)
{
throw new IllegalArgumentException("illegal sense number at: " + line);
}
senseNumber = Integer.parseInt(tempString);
if(senseNumber >= 100 || senseNumber <=0)
{
throw new IllegalArgumentException("illegal sense number at: " + line);
}
}
else
{
throw new IllegalArgumentException("illegal argument at: " + line);
}
words.add(new WordNetSense(word, id, pos, senseNumber));
}
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
words = null;
}
return words;
}
}
|
package by.orion.onlinertasks.di.modules.presentation;
import dagger.Module;
@Module
public class TasksPresenterModule {
}
|
package top.ysccx.myfirstapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table users (id integer primary key,name varchar(50),time varchar(50),date varchar(50))");
ContentValues cv = new ContentValues();
cv.put("name","JOJO");
cv.put("time","0");
cv.put("date","2020/10/10");
db.insert("users",null,cv);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
package com.wipro.arrays;
public class Ex13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] a=new int[2][2];
int[][] b=new int[2][2];
int k=0;
if(args.length!=4)
System.out.println("Please enter 4 integer numbers");
else
{
System.out.println("The given array is :");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
a[i][j]=Integer.parseInt(args[k]);
b[j][i]=a[i][j];
k++;
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(int i=1;i>=0;i--)
for(int j=1;j>=0;j--)
b[2-i-1][2-j-1]=a[i][j];
System.out.println("The reverse of the array is :");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
System.out.print(b[i][j]+" ");
System.out.println();
}
}
}
}
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.bvt.sql.oracle.select;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.OracleTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser;
import com.alibaba.druid.sql.repository.SchemaRepository;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
public class OracleSelectTest107 extends OracleTest {
//xml 解析 暂不支持,明宣 反馈的
public void test_0() throws Exception {
// String sql = //
// "SELECT xmlagg(xmlelement(\"operation\", XMLATTRIBUTES (operation AS \"name\", OPTIONS AS \"options\", id AS \"id\", depth AS\n"
// + " \"depth\", position AS \"pos\"), nvl2(object_name, xmlelement(\"object\", object_name), NULL),\n"
// + " DECODE(:rowFormat, 'BASIC', NULL, nvl2(cardinality, xmlelement(\"card\", cardinality), NULL)),\n"
// + " DECODE(:rowFormat, 'BASIC', NULL, nvl2(bytes, xmlelement(\"bytes\", bytes), NULL)),\n"
// + " nvl2(temp_space, xmlelement(\"temp_space\", temp_space), NULL),\n"
// + " DECODE(:rowFormat, 'BASIC', NULL, nvl2(cost, xmlelement(\"cost\", cost), NULL)),\n"
// + " nvl2(io_cost, xmlelement(\"io_cost\", io_cost), NULL),\n"
// + " nvl2(cpu_cost, xmlelement(\"cpu_cost\", cpu_cost), NULL), DECODE(:rowFormat, 'BASIC', NULL,\n"
// + " nvl2(TIME, xmlelement(\"time\",\n"
// + " sys.dbms_xplan.format_time_s(\n"
// + " TIME)),\n"
// + " NULL)),\n"
// + " nvl2(partition_start,\n"
// + " xmlelement(\"partition\", XMLATTRIBUTES (partition_start AS \"start\", partition_stop AS\n"
// + " \"stop\")), NULL), nvl2(object_node, xmlelement(\"node\", object_node), NULL),\n"
// + " nvl2(distribution, xmlelement(\"distrib\", distribution), NULL), nvl2(projection, xmlelement(\n"
// + " \"project\", projection), NULL), nvl2(access_predicates, xmlelement(\"predicates\", XMLATTRIBUTES (\n"
// + " DECODE(SUBSTR(OPTIONS, 1, 8), 'STORAGE ',\n"
// + " 'storage', 'access') AS \"type\"),\n"
// + " access_predicates), NULL), nvl2(filter_predicates,\n"
// + " xmlelement(\n"
// + " \"predicates\",\n"
// + " XMLATTRIBUTES\n"
// + " ('filter' AS\n"
// + " \"type\"),\n"
// + " filter_predicates),\n"
// + " NULL),\n"
// + " nvl2(qblock_name, xmlelement(\"qblock\", qblock_name), NULL),\n"
// + " nvl2(object_alias, xmlelement(\"object_alias\", object_alias), NULL), (\n"
// + " CASE\n" + " WHEN other_xml IS NULL\n"
// + " THEN NULL\n" + " ELSE xmltype(other_xml)\n"
// + " END))) plan\n" + "FROM\n" + " (SELECT\n"
// + " /*+ opt_param('parallel_execution_enabled','false') */\n" + " /* EXEC_FROM_DBMS_XPLAN */\n"
// + " id,\n" + " position,\n" + " depth,\n" + " operation,\n" + " OPTIONS,\n"
// + " object_name,\n" + " cardinality,\n" + " bytes,\n" + " temp_space,\n"
// + " cost,\n" + " io_cost,\n" + " cpu_cost,\n" + " TIME,\n" + " partition_start,\n"
// + " partition_stop,\n" + " object_node,\n" + " other_tag,\n" + " distribution,\n"
// + " projection,\n" + " access_predicates,\n" + " filter_predicates,\n" + " other,\n"
// + " qblock_name,\n" + " object_alias,\n" + " NVL(other_xml, remarks) other_xml,\n"
// + " NULL sql_profile,\n" + " NULL sql_plan_baseline,\n"
// + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n"
// + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL,\n"
// + " NULL,\n" + " NULL,\n" + " NULL,\n" + " NULL\n" + " FROM PLAN_TABLE\n"
// + " WHERE plan_id =\n" + " (SELECT MAX(plan_id)\n" + " FROM PLAN_TABLE\n"
// + " WHERE id = 0\n" + " )\n" + " ORDER BY id\n" + " )";
//
// System.out.println(sql);
//
// OracleStatementParser parser = new OracleStatementParser(sql);
// List<SQLStatement> statementList = parser.parseStatementList();
// SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
// System.out.println(stmt.toString());
//
// assertEquals(1, statementList.size());
//
// SchemaRepository repository = new SchemaRepository(DbType.oracle);
// repository.resolve(stmt);
//
// SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.oracle);
// stmt.accept(visitor);
//
// TableStat.Column cid = visitor.getColumn("a", "cid");
// assertNotNull(cid);
// assertTrue(cid.isWhere());
//
// TableStat.Condition condition = visitor.getConditions().get(2);
// assertTrue(condition.getColumn().isWhere());
// assertSame(cid, condition.getColumn());
//
// {
// String text = SQLUtils.toOracleString(stmt);
//
// assertEquals("SELECT *\n" +
// "FROM a\n" +
// "\tJOIN b ON a.id = b.aid \n" +
// "WHERE a.cid = 1", text);
// }
//
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("relationships : " + visitor.getRelationships());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
//
// assertEquals(2, visitor.getTables().size());
// assertEquals(3, visitor.getColumns().size());
// assertEquals(3, visitor.getConditions().size());
// assertEquals(1, visitor.getRelationships().size());
// assertEquals(0, visitor.getOrderByColumns().size());
//
//
}
}
|
package functions;
/*
* Created by pavel on 04.10.16.
*/
public class Ackey1 implements IFunction
{
public float getLimit() { return 500; }
public float getValue(int D, float[] values)
{
float sum = 0;
for (int i = 0; i < D - 1; i++)
{
float x0 = values[i];
float x1 = values[i + 1];
sum += (float)( (1 / Math.pow(Math.E, 5)) * Math.sqrt (x0 * x0 + x1 * x1) + 3 * Math.cos(2 * x0) + Math.sin(2 * x1) );
}
return sum;
}
}
|
package practica4;
/**
*
* @author FranBarbosa
*/
public class Practica4 {
public static void main(String[] args) {
ManejaExperto me = new ManejaExperto();
me.obtenCasos();
}
}
|
package com.kingnode.gou.dao;
import java.util.List;
import com.kingnode.gou.entity.ActivityProduct;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
@SuppressWarnings("ALL") public interface ActivityProductDao extends PagingAndSortingRepository<ActivityProduct,Long>, JpaSpecificationExecutor<ActivityProduct>{
@Query("select u from ActivityProduct u where u.activity.id=?1") List<ActivityProduct> findActivityProduct(Long activityId);
// @Query("select a from KnSalseActive a, KnActiveScope b where a.id=b.activeId and b.shopId=?1 group by b.activeId ") List<Activity> queryKnSalseActive(Long shopId);
// @Query("select a from KnSalseActive a, KnActiveScope b where a.id=b.activeId and b.shopId in (?1) group by b.activeId ") List<Activity> queryKnSalseActive(List<Long> list);
}
|
package com.zhongyp.advanced.pattern.bridge;
/**
* project: demo
* author: zhongyp
* date: 2018/3/27
* mail: zhongyp001@163.com
*/
public class Test {
public static void main(String[] args){
Shape shape = new Circular();
Color color = new Red();
shape.draw(color);
Shape shape1 = new Square();
Color color1 = new Green();
shape1.draw(color1);
}
}
|
package org.maple.jdk8.stream;
import java.util.Arrays;
import java.util.List;
/**
* @Author Mapleins
* @Date 2019-04-07 11:41
* @Description
*/
public class Test12 {
public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world", "hello world");
// 找出列表中长度为5的单词,打出长度
// list.stream().filter( x -> x.length() == 5).limit(1).forEach(System.out::println); //wrong
// list.stream().map(String::length).filter(x -> x == 5).limit(1).findFirst().ifPresent(System.out::println); //right
// 思考打印结果,反思流的操作
list.stream().mapToInt(item->{
int result = item.length();
System.out.println(item);
return result;
}).filter(x->x==5).limit(1).findFirst().ifPresent(System.out::println);
}
}
|
package algorithms.fundamentals.sub2_dataabs.exercises;
import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Chen Li on 2017/1/6.
* <p>
* 1.2.2 Write an Interval1D client that takes an int value N as command-line argument,
* reads N intervals (each defined by a pair of double values) from standard input,
* and prints all pairs that intersect.
*
* 遍历寻找相交区间
* 返回的数据结构有冗余
*/
public class SimpleIntersectedIntervals1DScanner {
private static final double RANGE_MIN = 0;
private static final double RANGE_MAX = 10000;
public static void main(String[] args) {
if (args.length == 0) {
StdOut.println("give a number");
return;
}
//generating
int count = Integer.parseInt(args[0]);
List<Interval1D> intervals = new ArrayList<>();
double tmp;
for (int i = 0; i < count; i++) {
double left = StdRandom.uniform(RANGE_MIN, RANGE_MAX);
double right = StdRandom.uniform(RANGE_MIN, RANGE_MAX);
if (left > right) {
tmp = left;
left = right;
right = tmp;
}
intervals.add(new Interval1D(left, right));
}
//computing
SimpleIntersectedIntervals1DScanner scanner = new SimpleIntersectedIntervals1DScanner();
long start = System.currentTimeMillis();
List<Pair<Interval1D, Interval1D>> intersectedPairs = scanner.findIntersectedIntervals(intervals);
long end = System.currentTimeMillis();
//report
long ms = end - start;
reportIntersected(intersectedPairs, ms);
}
public List<Pair<Interval1D, Interval1D>> findIntersectedIntervals(List<Interval1D> intervals) {
List<Pair<Interval1D, Interval1D>> intersectedList = new ArrayList<>();
for (int i = 0; i < intervals.size(); i++) {
Interval1D a = intervals.get(i);
List<Interval1D> list = new ArrayList<>();
for (int j = i + 1; j < intervals.size(); j++) {
Interval1D b = intervals.get(j);
if (a.intersects(b)) {
intersectedList.add(Pair.of(a, b));
}
}
}
return intersectedList;
}
public static void reportIntersected(List<Pair<Interval1D, Interval1D>> intersectedList, long ms) {
if (!intersectedList.isEmpty()) {
StdOut.printf("intersected interval pairs:%s, using %s ms.\n", intersectedList.size(), ms);
// for (Pair<Interval1D, Interval1D> intersectedPair : intersectedPairs) {
// StdOut.printf("%s, %s\n",
// PointStringWrapper.wrap(intersectedPair.getKey(), 2),
// PointStringWrapper.wrap(intersectedPair.getValue(), 2));
// }
} else {
StdOut.printf("no intersected intervals found, using %s ms.", ms);
}
}
}
|
package br.com.zolp.estudozolp.bean;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* Classe responsável pelas informacoes de UnidadePesquisa.
*
* @author mamede
* @version 0.0.1-SNAPSHOT
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class UnidadePesquisa implements Serializable{
private static final long serialVersionUID = 1288214482724547066L;
private Long idUnidadePesquisa;
private String dsUnidade;
private String siglaUnidade;
private String telUnidade;
private String endereco;
private String cidade;
private String uf;
private String cep;
private String investigador;
private String coordenador;
private String email;
private Integer nuUnidade;
public UnidadePesquisa() {
}
/**
* Obtem o valor corrente de idUnidadePesquisa.
*
* @return O valor corrente de idUnidadePesquisa.
*/
public Long getIdUnidadePesquisa() {
return idUnidadePesquisa;
}
/**
* Define um novo valor para idUnidadePesquisa.
*
* @param idUnidadePesquisa O novo valor para idUnidadePesquisa.
*/
public void setIdUnidadePesquisa(final Long idUnidadePesquisa) {
this.idUnidadePesquisa = idUnidadePesquisa;
}
/**
* Obtem o valor corrente de dsUnidade.
*
* @return O valor corrente de dsUnidade.
*/
public String getDsUnidade() {
return dsUnidade;
}
/**
* Define um novo valor para dsUnidade.
*
* @param dsUnidade O novo valor para dsUnidade.
*/
public void setDsUnidade(final String dsUnidade) {
this.dsUnidade = dsUnidade;
}
/**
* Obtem o valor corrente de siglaUnidade.
*
* @return O valor corrente de siglaUnidade.
*/
public String getSiglaUnidade() {
return siglaUnidade;
}
/**
* Define um novo valor para siglaUnidade.
*
* @param siglaUnidade O novo valor para siglaUnidade.
*/
public void setSiglaUnidade(final String siglaUnidade) {
this.siglaUnidade = siglaUnidade;
}
/**
* Obtem o valor corrente de telUnidade.
*
* @return O valor corrente de telUnidade.
*/
public String getTelUnidade() {
return telUnidade;
}
/**
* Define um novo valor para telUnidade.
*
* @param telUnidade O novo valor para telUnidade.
*/
public void setTelUnidade(final String telUnidade) {
this.telUnidade = telUnidade;
}
/**
* Obtem o valor corrente de endereco.
*
* @return O valor corrente de endereco.
*/
public String getEndereco() {
return endereco;
}
/**
* Define um novo valor para endereco.
*
* @param endereco O novo valor para endereco.
*/
public void setEndereco(final String endereco) {
this.endereco = endereco;
}
/**
* Obtem o valor corrente de cidade.
*
* @return O valor corrente de cidade.
*/
public String getCidade() {
return cidade;
}
/**
* Define um novo valor para cidade.
*
* @param cidade O novo valor para cidade.
*/
public void setCidade(final String cidade) {
this.cidade = cidade;
}
/**
* Obtem o valor corrente de uf.
*
* @return O valor corrente de uf.
*/
public String getUf() {
return uf;
}
/**
* Define um novo valor para uf.
*
* @param uf O novo valor para uf.
*/
public void setUf(final String uf) {
this.uf = uf;
}
/**
* Obtem o valor corrente de cep.
*
* @return O valor corrente de cep.
*/
public String getCep() {
return cep;
}
/**
* Define um novo valor para cep.
*
* @param cep O novo valor para cep.
*/
public void setCep(final String cep) {
this.cep = cep;
}
/**
* Obtem o valor corrente de investigador.
*
* @return O valor corrente de investigador.
*/
public String getInvestigador() {
return investigador;
}
/**
* Define um novo valor para investigador.
*
* @param investigador O novo valor para investigador.
*/
public void setInvestigador(final String investigador) {
this.investigador = investigador;
}
/**
* Obtem o valor corrente de coordenador.
*
* @return O valor corrente de coordenador.
*/
public String getCoordenador() {
return coordenador;
}
/**
* Define um novo valor para coordenador.
*
* @param coordenador O novo valor para coordenador.
*/
public void setCoordenador(final String coordenador) {
this.coordenador = coordenador;
}
/**
* Obtem o valor corrente de email.
*
* @return O valor corrente de email.
*/
public String getEmail() {
return email;
}
/**
* Define um novo valor para email.
*
* @param email O novo valor para email.
*/
public void setEmail(final String email) {
this.email = email;
}
/**
* Obtem o valor corrente de nuUnidade.
*
* @return O valor corrente de nuUnidade.
*/
public Integer getNuUnidade() {
return nuUnidade;
}
/**
* Define um novo valor para nuUnidade.
*
* @param nuUnidade O novo valor para nuUnidade.
*/
public void setNuUnidade(final Integer nuUnidade) {
this.nuUnidade = nuUnidade;
}
@Override
public final String toString() {
return "UnidadePesquisa{" +
"idUnidadePesquisa=" + idUnidadePesquisa +
", dsUnidade='" + dsUnidade + '\'' +
", siglaUnidade='" + siglaUnidade + '\'' +
", telUnidade='" + telUnidade + '\'' +
", endereco='" + endereco + '\'' +
", cidade='" + cidade + '\'' +
", uf='" + uf + '\'' +
", cep='" + cep + '\'' +
", investigador='" + investigador + '\'' +
", coordenador='" + coordenador + '\'' +
", email='" + email + '\'' +
", nuUnidade=" + nuUnidade +
'}';
}
}
|
package com.zl.mapper;
import com.zl.pojo.LogDO;
import com.zl.pojo.logDOExample;
import java.util.List;
import com.zl.util.AjaxPutPage;
import org.apache.ibatis.annotations.Param;
public interface LogMapper {
int countByExample(logDOExample example);
int deleteByExample(logDOExample example);
int deleteByPrimaryKey(String logId);
int insert(LogDO record);
int insertSelective(LogDO record);
List<LogDO> selectByExample(logDOExample example);
LogDO selectByPrimaryKey(String logId);
int updateByExampleSelective(@Param("record") LogDO record, @Param("example") logDOExample example);
int updateByExample(@Param("record") LogDO record, @Param("example") logDOExample example);
int updateByPrimaryKeySelective(LogDO record);
int updateByPrimaryKey(LogDO record);
/**
* @Description: 分页获取所有日志记录
* @Param: [ajaxPutPage]
* @return: java.util.List<com.zl.pojo.LogDO>
* @Author: ZhuLin
* @Date: 2019/1/10
*/
List<LogDO> listLogDO(AjaxPutPage<LogDO> ajaxPutPage);
/**
* @Description: 返回日志表总条数
* @Param: []
* @return: java.lang.Long
* @Author: ZhuLin
* @Date: 2019/1/18
*/
Integer getLogCount();
/***
* @Description: 清除超过五天日志记录
* @Param: []
* @return: int
* @Author: ZhuLin
* @Date: 2019/1/21
*/
int deleteLogBySevenday();
}
|
/*--------------------------------
* Author: Jeremy Dalcin
* Class: Creates a linked list that can be traversed in both directions
*/
public class MyLink {
public String familyMember; // value variable
public int age; // value variable
public MyLink forward; // reference variable goes forward in list
public MyLink next; //reference variable goes back in list
//constructor defining our node
public MyLink(String familyMember, int age){
this.familyMember = familyMember;
this.age = age;
}
public void display(){
System.out.println(familyMember + ": " + age + " years old");
}
public String toString(){
return familyMember;
}
public static void main(String[] args) {
}
}
class MyLinkedList {
public MyLink firstLink;
MyLinkedList(){
firstLink = null;
}
MyLinkedList(MyLink newLink){
this.firstLink = newLink;
}
public boolean isEmpty(){
return(firstLink == null);
}
//inserts new object
public void insertNewLink(String familyMember, int age){
MyLink newLink = new MyLink(familyMember, age);
newLink.next = firstLink;
firstLink = newLink;
if (firstLink.next != null){
firstLink.next.forward = newLink;
}
}
//removes object last inputted
public void removeLast(){
firstLink = firstLink.next;
}
//counts size of LinkedList
public int counter(){
int count = 0;
MyLink tempFirstLink = firstLink;
while(tempFirstLink != null){
tempFirstLink = tempFirstLink.next;
count++;
}
return count;
}
// find specific object (start from first element inputed) and combines the rest of the list back together
public void findSpecific(int index){
MyLink tempFirstLink = firstLink;
int count = this.counter();
for(int i = count; i > index; i--){
firstLink = firstLink.next;
}
firstLink.display();
for (int i = index; i < count; i++){
firstLink = firstLink.forward;
}
}
//displays last object inputed up to first object inputed
public void displayLinkedList(){
MyLink tempFirstLink = firstLink;
while (tempFirstLink != null){
tempFirstLink.display();
tempFirstLink = tempFirstLink.next;
}
}
}
|
package com.weightgraph;
/*
* 用于图中两个节点之间添加连接(包含了稀疏图和稠密图)
*/
public interface Graph<W> {
public void addEdge(int v, int w,W weight);
public void show();
public int getN();
public int getM();
public GraphIterator<W> getIterator(int v);
}
|
package web.id.azammukhtar.subico.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
public class SessionManager {
private static final String TAG = "SessionManager";
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private static SessionManager singleTonInstance = null;
private static final int PRIVATE_MODE = 0;
private static final String PREF_NAME = "SessionManager";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
private static final String USER_TOKEN = "userToken";
public static SessionManager getInstance() {
if (singleTonInstance == null) {
singleTonInstance = new SessionManager(MyApplication.getInstance().getApplicationContext());
}
return singleTonInstance;
}
private SessionManager(Context context) {
super();
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setLogin(boolean isLoggedIn, String userToken) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.putString(USER_TOKEN, userToken);
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String getUserToken(){
return pref.getString(USER_TOKEN, null);
}
public void clearData() {
editor.clear().commit();
}
}
|
package com.seedo.ligerui.action.dining.diningstatistics;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;
import com.seedo.dining.service.diningstatistics.StatisticsService;
import com.seedo.dining.vo.StatisticsVo;
import com.seedo.platform.action.struts.LigerJsonHelperAction;
import com.seedo.platform.config.ConfigFactory;
import com.seedo.platform.dataobject.PageResultInfo;
import com.seedo.platform.model.BasTsParameter;
import com.seedo.platform.model.BasTsUser;
import com.seedo.platform.service.base.ParameterService;
import com.seedo.platform.service.base.UserService;
import com.seedo.platform.utils.AppContextUtil;
import com.seedo.platform.utils.DateUtil;
import com.seedo.platform.utils.Report2ExcelUtil;
public class StatisticsAction extends LigerJsonHelperAction {
@Autowired
private ParameterService parameterService;
@Autowired
private StatisticsService statisticsService;
@Autowired
private UserService userService;
private StatisticsVo statisticsVo;
public StatisticsVo getStatisticsVo() {
return statisticsVo;
}
public void setStatisticsVo(StatisticsVo statisticsVo) {
this.statisticsVo = statisticsVo;
}
private String resInfo[]=new String[3];
public String[] getResInfo() {
String userId=AppContextUtil.getUserInfo().getId();
BasTsUser user=userService.doFindByIdNoWaitLock(userId);
this.resInfo[0]=user.getDepartmentId();
this.resInfo[1]=user.getDepartmentId()== null?null:user.getBasTsDepartment().getDepartmentName();
this.resInfo[2]=AppContextUtil.getUserInfo().getRoles();
return resInfo;
}
private String restName;
public String getRestName() {
this.restName=getResInfo()[1];
return restName;
}
/**
* 是否生成报表
*/
private Boolean isExcl=false;
public Boolean getIsExcl() {
return isExcl;
}
public void setIsExcl(Boolean isExcl) {
this.isExcl = isExcl;
}
/**
* 是否对比分析
*/
private Boolean isCont=false;
public Boolean getIsCont() {
return isCont;
}
public void setIsCont(Boolean isCont) {
this.isCont = isCont;
}
private Map<Boolean, String> sf = new HashMap<Boolean, String>();
public Map<Boolean, String> getSf() {
sf.put(true, "是");
sf.put(false, "否");
return sf;
}
/**
* 菜品类型
*/
private String dishType;
public String getDishType() {
return dishType;
}
public void setDishType(String dishType) {
this.dishType = dishType;
}
/**
* 菜品类型信息
*/
private Map<String, String> dishTInfo=new HashMap<String, String>();
public Map<String, String> getDishTInfo() {
String dishId=ConfigFactory.getDefaultProvider().getProperty("Parameter.paramName.dishType", "configs-application-parameter.properties");
List<BasTsParameter> l=parameterService.doFindSubNodeById(dishId);
for(int i=0 ;i<l.size() ;i++){
dishTInfo.put(l.get(i).getParamName(), l.get(i).getValue());
}
return dishTInfo;
}
/**
* 时间间隔
* 本日,本周,本月,本年度
*/
private String timeInfo[] = new String[4];
public String[] getTimeInfo() {
return timeInfo;
}
public void setTimeInfo(Integer number) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// cal.set(Calendar.HOUR_OF_DAY, 0);
//// cal.set(Calendar.HOUR, 12);
//// cal.set(Calendar.AM_PM, 0);
// cal.set(Calendar.MINUTE, 0);
// cal.set(Calendar.SECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal.setTime(new Date());
// cal.set(Calendar.HOUR, 11);
// cal.set(Calendar.AM_PM, 1);
// cal.set(Calendar.MINUTE, 59);
// cal.set(Calendar.SECOND, 59);
// cal2.setTime(cal.getTime());
// cal2.add(Calendar.DAY_OF_MONTH, 1);
// cal2.add(Calendar.SECOND, -1);
/*
* (1, "本日");
* (2, "本周");
* (3, "本月");
* (4, "本年度");
*/
switch (number) {
case 4:
cal.set(Calendar.DAY_OF_YEAR, 1);
cal2.set(Calendar.DAY_OF_YEAR, cal2.getActualMaximum(Calendar.DAY_OF_YEAR));
this.timeInfo[0] = DateUtil.formatDate(cal.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
this.timeInfo[1] = DateUtil.formatDate(cal2.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
cal.add(Calendar.YEAR, -1);
break;
case 3:
cal.set(Calendar.DAY_OF_MONTH, 1);
cal2.set(Calendar.DAY_OF_MONTH, cal2.getActualMaximum(Calendar.DAY_OF_MONTH));
this.timeInfo[0] = DateUtil.formatDate(cal.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
this.timeInfo[1] = DateUtil.formatDate(cal2.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
break;
case 2:
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal2.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// 增加一个星期,才是我们中国人理解的本周日的日期
cal2.add(Calendar.WEEK_OF_YEAR, 1);
this.timeInfo[0] = DateUtil.formatDate(cal.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
this.timeInfo[1] = DateUtil.formatDate(cal2.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
break;
case 1:
this.timeInfo[0] = DateUtil.formatDate(cal.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
this.timeInfo[1] = DateUtil.formatDate(cal2.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
break;
default:
this.timeInfo[0] = DateUtil.formatDate(cal.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
this.timeInfo[1] = DateUtil.formatDate(cal2.getTime(), DateUtil.FORMAT_DATE_DEFAULT);
break;
}
}
/**
* 页面显示
* 与timeInfo相关联
*/
private Map<Integer, String> timeIn = new HashMap<Integer, String>();
public Map<Integer, String> getTimeIn() {
timeIn.put(1, "本日");
timeIn.put(2, "本周");
timeIn.put(3, "本月");
timeIn.put(4, "本年度");
return timeIn;
}
@Action("list-statistics")
public String listStatistics(){
return SUCCESS;
}
@Action("list-dish-statistics")
public String listDishStatistics(){
setStatisticsVo(statisticsVo);
return SUCCESS;
}
@Action("ajax-list-statistics")
public String ajaxListStatistics(){
//
// String userId=AppContextUtil.getUserInfo().getId();
// BasTsUser user=userService.doFindByIdNoWaitLock(userId);
// this.resInfo[0]=user.getDepartmentId();
// this.resInfo[1]=user.getBasTsDepartment().getDepartmentName();
String dt = dishType ==null?null:getDishType();
if(isExcl && dt!=null){
PageResultInfo<StatisticsVo> l = statisticsService.doDiningStatistics(getResInfo(), dt, getTimeInfo(),0,0);
Map<String,Object> result=new HashMap<String, Object>();
//注意:key=supsInfo,supsInfo是一般pojo类
result.put("l", l.getContent());
//特别说明:以上excel模板所需要数据已经做好,如何在excel模板中单元格应用EL表达式绑定到这些数据呢?请认真看完下面说明
// 如果要在某个单元格显示对应到某个pojo类的某个属性只需在所在单元格对应位置加上EL表达式(假设数据如上面的):
// #{supsInfo.supplier.supplFaxNo1}这样即可绑定到supsInfo对象中的supplier属性中(此属性也是pojo对象)的suppliFaxNo1属性
// 如果是列表这种情况则必须对应到List对象使用方法同一般pojo对象
// 如:#{plist.partNo},plist是map中的key名称不是变量称,pojo形式的也是一样这个很重要!
String tXls="C:\\Users\\Administrator\\Desktop\\Folder\\upload\\exl\\SuppTemplate.xls";
FileInputStream fis;
FileOutputStream fos = null;
Report2ExcelUtil r2e=new Report2ExcelUtil();
try {
// String templateXls=URLDecoder.decode(tXls, "UTF-8").replace("file:/", "");
// FileInputStream template = new FileInputStream(templateXls);
fis = new FileInputStream(tXls);
fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Folder\\upload\\exl\\supp.xls");
r2e.print2Excel(fis, "supp", result, fos);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return queryResultToGrid(l);
}else if(dt!=null){
PageResultInfo<StatisticsVo> l = statisticsService.doDiningStatistics(getResInfo(), dt, getTimeInfo(),page,pagesize);
return queryResultToGrid(l);
}
return writeJson2Client(null);
}
}
|
package com.skrebtsov.xxtedixx.aprofitalibrary;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import io.branch.referral.Branch;
import io.branch.referral.BranchError;
import static com.skrebtsov.xxtedixx.aprofitalibrary.Constans.APP_PREFERENCES;
import static com.skrebtsov.xxtedixx.aprofitalibrary.Constans.APP_PREFERENCES_USERID;
public class BranchActivity extends AppCompatActivity {
SharedPreferences mSettings;
public static String USER_ID = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
readingManifest(); //чтение данных из manifest /reading data from manifest
CreateJSON.ANDROID_ID = identification(); //индефикация устройства/device identification
branchInit(); // получение данных userId из branch /getting userId data from a branch
finish();
}
@Override
public void onNewIntent(Intent intent) {
this.setIntent(intent);
}
//индефикация устройства/device identification
public String identification() {
String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
return androidId;
}
class ProgressTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... unused) {
new ServerPost().request();
return(null);
}
@Override
protected void onProgressUpdate(Integer... items) {
}
@Override
protected void onPostExecute(Void unused) {
super.onPreExecute();
}
}
//чтение данных из manifest /reading data from manifest
public void readingManifest(){
ApplicationInfo appInfo;
try {
appInfo = this.getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null) {
CreateJSON.API_KEY = appInfo.metaData.getString("com.skrebtsov.xxtedixx.aprofitalibrary.API_KEY");
CreateJSON.APP_ID = appInfo.metaData.getString("com.skrebtsov.xxtedixx.aprofitalibrary.APP_ID");
CreateJSON.APP_VERSION = appInfo.metaData.getString("com.skrebtsov.xxtedixx.aprofitalibrary.APP_VERSION");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.d("PackageManager", e.getMessage());
}
}
// получение данных userId из branch /getting userId data from a branch
public void branchInit (){
// Branch init
Branch.getInstance().initSession(new Branch.BranchReferralInitListener() {
@Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if ( error == null) {
try {
USER_ID = referringParams.getString("userId");
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(APP_PREFERENCES_USERID, USER_ID);
editor.apply();
Log.d("user 2", USER_ID);// Retrieve deeplink keys from 'referringParams' and evaluate the values to determine where to route the user
} catch (JSONException e) {
e.printStackTrace();
Log.d("BRANCH SDK JSON", e.getMessage());
}
if(mSettings.contains(APP_PREFERENCES_USERID)) {
USER_ID = mSettings.getString(APP_PREFERENCES_USERID, "");
Log.d("user 3", USER_ID);
new ProgressTask().execute();
}// Check '+clicked_branch_link' before deciding whether to use your Branch routing logic
} else {
Log.d("BRANCH SDK", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
}
|
package com.tt.rendezvous.core.graph.facade.impl;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.tt.rendezvous.core.beans.Relation;
public class FuzzyRelation extends Relation {
@Override
public byte[] getKey() {
byte[] thedigest = null;
String key = getOrigin().getKey().toString() + getDestination().getKey().toString();
try {
byte[] bytesOfMessage = key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
thedigest = md.digest(bytesOfMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return thedigest;
}
}
|
package com.buddybank.mdw.dataobject.domain;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class Attributes implements Serializable {
private static final long serialVersionUID = 8741076501760554366L;
private final Map<String, Serializable> attributes = new HashMap<String, Serializable>();
public void add(final AttributesKey key, final Serializable value)
{
attributes.put(key.name(), value);
}
public Serializable get(final AttributesKey key)
{
return attributes.get(key.name());
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.pmm.sdgc.ws.model;
import com.pmm.sdgc.model.PortariaRelacao;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author setinf
*/
public class ModelPortariaWs {
private String nomePortaria;
private LocalDate dataPublicacao;
//private Boolean ativo;
private String tpa;
private String transmissao;
private String copiaDigital;
public ModelPortariaWs(String nomePortaria, LocalDate dataPublicacao, String tpa, String transmissao, String copiaDigital) {
this.nomePortaria = nomePortaria;
this.dataPublicacao = dataPublicacao;
this.tpa = tpa;
this.transmissao = transmissao;
this.copiaDigital = copiaDigital;
}
public static List<ModelPortariaWs> toModelPortariaWs(List<PortariaRelacao> portarias) {
List<ModelPortariaWs> mpw = new ArrayList();
for (PortariaRelacao pr : portarias) {
ModelPortariaWs prw = new ModelPortariaWs(
pr.getPortaria().getNome(),
pr.getPortaria().getDataPublicacao(),
pr.getPortariaTpa().getNome(),
pr.getPortariaTransmissao().getNome(),
pr.getPortaria().getArquivoNome()
);
mpw.add(prw);
}
return mpw;
}
public LocalDate getDataPublicacao() {
return dataPublicacao;
}
public void setDataPublicacao(LocalDate dataPublicacao) {
this.dataPublicacao = dataPublicacao;
}
public String getTpa() {
return tpa;
}
public void setTpa(String tpa) {
this.tpa = tpa;
}
public String getTransmissao() {
return transmissao;
}
public void setTransmissao(String transmissao) {
this.transmissao = transmissao;
}
public String getCopiaDigital() {
return copiaDigital;
}
public void setCopiaDigital(String copiaDigital) {
this.copiaDigital = copiaDigital;
}
public String getNomePortaria() {
return nomePortaria;
}
public void setNomePortaria(String nomePortaria) {
this.nomePortaria = nomePortaria;
}
}
|
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.app.noan.R;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.content.Context.LOCATION_SERVICE;
/**
* Created by smn on 9/5/17.
*/
public class MyUtility implements Serializable {
String MAIN_TAG = MyUtility.class.getSimpleName();
public static int onResumeScreenType = 0;
public static int onResumeSellerScreenType = 0;
public static int onSelleScreen = 0;
public static int screenType = 0;
public static int screenFilterType = 0;
//filter count
public static int selectFilterCount = 0;
public static int selectSearchFilterCount = 0;
public static int selectSearchFilterCategoryCount = 0;
public static List<String> seletedBrandList = new ArrayList<>();
public static List<String> seletedSizeList = new ArrayList<>();
public static List<String> seletedCategoryList = new ArrayList<>();
public static List<String> selectedTypeList = new ArrayList<>();
public static List<String> selectedColorList = new ArrayList<>();
//search
public static List<String> seletedSearchBrandList = new ArrayList<>();
public static List<String> seletedSearchSizeList = new ArrayList<>();
public static List<String> seletedSearchCategoryList = new ArrayList<>();
public static List<String> selectedSearchTypeList = new ArrayList<>();
public static List<String> selectedSearchColorList = new ArrayList<>();
//cateigory
public static List<String> seletedSearchCategoryBrandList = new ArrayList<>();
public static List<String> seletedSearchCategorySizeList = new ArrayList<>();
public static List<String> seletedSearchCategoryCategoryList = new ArrayList<>();
public static List<String> selectedSearchCategoryTypeList = new ArrayList<>();
public static List<String> selectedSearchCategoryColorList = new ArrayList<>();
public Activity mActivity;
public static Dialog customDialog, customDialogValidation;
// GPS
LocationManager locationManager;
public boolean isGPSEnable = false;
// Display Size of Width & Height
Display display;
Point size;
int width, height;
// const
public static final int MY_PERMISSION_REQUEST = 1;
public static final int REQUEST_CHECK_SETTINGS = 0x1;
public static boolean location_Success = false;
public MyUtility(Activity mActivity) {
this.mActivity = mActivity;
}
// Checking Whole App Permission Above23
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public boolean checkSelfPermission() {
int AccessNetworkStat = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_WIFI_STATE);
int AccessCorasLocation = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION);
int AccessFineLocation = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION);
int AccessCamera = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA);
int AccessWrite = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int AccessRead = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE);
int Call = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CALL_PHONE);
List<String> permissionNeeded = new ArrayList<>();
if (AccessNetworkStat != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.ACCESS_WIFI_STATE);
}
if (AccessFineLocation != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (AccessCorasLocation != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (AccessRead != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (AccessWrite != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (AccessCamera != PackageManager.PERMISSION_GRANTED) {
permissionNeeded.add(Manifest.permission.CAMERA);
}
if (!permissionNeeded.isEmpty()) {
ActivityCompat.requestPermissions(mActivity,
permissionNeeded.toArray(new String[permissionNeeded.size()]), MY_PERMISSION_REQUEST);
return false;
}
return true;
}
// Checking GPS
public boolean isGPSEnable() {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return isGPSEnable;
}
public boolean displayLocationSettingsRequest() {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(mActivity)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(MAIN_TAG, "All location settings are satisfied.");
location_Success = true;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(MAIN_TAG, "Location settings are not satisfied. " +
"Show the user a Dialog to upgrade location settings ");
location_Success = false;
try {
// Show the Dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(mActivity, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(MAIN_TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(MAIN_TAG, "Location settings are inadequate, " +
"and cannot be fixed here. Dialog not created.");
location_Success = false;
break;
}
}
});
return location_Success;
}
// Screen Size
public int getDeviceScreen_Width() {
display = mActivity.getWindowManager().getDefaultDisplay();
size = new Point();
display.getSize(size);
width = size.x;
return width;
}
public int getDeviceScreen_height() {
display = mActivity.getWindowManager().getDefaultDisplay();
size = new Point();
display.getSize(size);
height = size.y;
return height;
}
// Checking Interenet
public boolean isInternetConnect() {
boolean isConnect = false;
ConnectivityManager cm = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
isConnect = ni != null && ni.isConnectedOrConnecting();
return isConnect;
}
public static boolean isNetworkAvailable(Context context) {
boolean isNetAvailable = false;
if (context != null) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnectivityManager != null) {
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
final NetworkInfo mobileInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final NetworkInfo wifiInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileInfo != null) {
mobileNetwork = mobileInfo.isAvailable();
}
if (wifiInfo != null) {
wifiNetwork = wifiInfo.isAvailable();
}
if (wifiNetwork || mobileNetwork) {
if (mobileInfo != null)
mobileNetworkConnecetd = mobileInfo
.isConnectedOrConnecting();
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
}
isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
}
/*
* if (!isNetAvailable) { Util.displayDialog(context,
* context.getString(R.string.common_internet), false); }
*/
}
return isNetAvailable;
}
// Preferences
public static void savePreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSavedPreferences(Context context, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(key, "");
}
public static void romove(Context context, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key);
editor.commit();
}
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
// Validation
public boolean isValidMobile(String mobile) {
String phone = "[0-9]{10}";
Pattern pattern = Pattern.compile(phone);
Matcher matcher = pattern.matcher(mobile);
return matcher.matches();
}
public boolean isValidEmail(String mailId) {
String email = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
Pattern pattern = Pattern.compile(email);
Matcher matcher = pattern.matcher(mailId);
return matcher.matches();
}
public void editTextError(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText.setError(null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public void textInputEditText(final TextInputEditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText.setError(null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// Date Convert Formate
public static Date currentDate() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
public static String getConvertDate(String date) {
try {
SimpleDateFormat yyyymmm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = yyyymmm.parse(date);
SimpleDateFormat retriveDate = new SimpleDateFormat("dd-MM-yyyy h:mm:s");
return retriveDate.format(newDate);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public static String getConvertCustomDate(String date) {
try {
SimpleDateFormat yyyymmm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = yyyymmm.parse(date);
SimpleDateFormat retriveDate = new SimpleDateFormat("dd-MM-yyyy");
return retriveDate.format(newDate);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public static String getConvertDate1(String date) {
try {
SimpleDateFormat yyyymmm = new SimpleDateFormat("dd-MM-yyyy");
Date newDate = yyyymmm.parse(date);
SimpleDateFormat retriveDate = new SimpleDateFormat("yyyy-MM-dd");
return retriveDate.format(newDate);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private static int getTimeDistanceInMinutes(long time) {
long timeDistance = currentDate().getTime() - time;
return Math.round((Math.abs(timeDistance) / 1000) / 60);
}
// Image related
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String getRealPathFromURI(Uri uri, Context context) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
public static Bitmap getBitmap(String filepath) {
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(filepath);
return bitmap;
}
// ListView Scroll Issue Solve
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
// Location
@SuppressLint("LongLogTag")
public String getCompleteAddressString(Context context, LatLng LATITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE.latitude, LATITUDE.longitude, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
strAdd = strReturnedAddress.toString();
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
public List<Address> getGeocoderAddress(Context context, LatLng latLng) {
if (latLng != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
Log.d(MAIN_TAG, String.valueOf(addresses));
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(MAIN_TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
public String getLocality(Context context, LatLng latLng) {
List<Address> addresses = getGeocoderAddress(context, latLng);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
Log.e(MAIN_TAG, locality);
return locality;
} else {
return null;
}
}
//custom Toast
public void setMessage(String message, int duration) {
Toast.makeText(mActivity, message, duration).show();
}
// Hash Key
public static String printKeyHash(Activity context) {
PackageInfo packageInfo;
String key = null;
try {
//getting application package name, as defined in manifest
String packageName = context.getApplicationContext().getPackageName();
//Retriving package info
packageInfo = context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
Log.e("Package Name=", context.getApplicationContext().getPackageName());
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
key = new String(Base64.encode(md.digest(), 0));
// String key = new String(Base64.encodeBytes(md.digest()));
Log.e("Key Hash=", key);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("Name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("No such an algorithm", e.toString());
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return key;
}
public static void showCustomMeassge(final Context activity, String btntext, String title, String msg) {
final TextView dialogTitle, dialogMsg;
final Button btnCancel;
customDialog = new Dialog(activity);
customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
customDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
customDialog.setContentView(R.layout.custom_dialog_msg);
customDialog.setCanceledOnTouchOutside(true);
customDialog.setCancelable(true);
dialogTitle = customDialog.findViewById(R.id.txt_dialogTitle);
dialogMsg = customDialog.findViewById(R.id.txt_dialogMsg);
btnCancel = customDialog.findViewById(R.id.btnCancel);
dialogTitle.setText(title);
dialogMsg.setText(msg);
btnCancel.setText(btntext);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnCancel.getText().toString().equals("Ok")) {
customDialog.dismiss();
} else {
customDialog.dismiss();
showCustomMeassge(activity, "Ok", "Authentication Failed ", "Authentication was canceled by the user");
}
}
});
if (!((Activity) activity).isFinishing()) {
//show custome_deleteDialog
customDialog.show();
}
}
}
|
package se.avelon.daidalos;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
public class Utilities {
public static String float2String(float[] floats) {
String msg = "";
for(float f : floats) {
msg += String.format("%.4f", f) + " ";
}
return msg;
}
public static void spinner(View view, int res, ArrayList<String> list) {
Spinner spinner = (Spinner)view.findViewById(res);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
|
/**
*
*/
package com.PIM.persistence;
import com.PIM.API.fields.FieldType;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author Henrik Lundin
*
*/
public class FieldTypePersistenceService implements
IFieldTypePersistenceService {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
@Override
public void CreateFieldType(FieldType fieldType) {
java.sql.Connection con;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/PIM",
"root", "goju-rye");
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public FieldType getFieldType(int ID) {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
// preparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
// you need to close all three to make sure
private void close() {
close(resultSet);
close(statement);
close(connect);
}
private void close(Closeable c) {
try {
if (c != null) {
c.close();
}
} catch (Exception e) {
// don't throw now as it might leave following closables in
// undefined state
}
}
}
|
package com.liuyufei.bmc_android.admin;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.liuyufei.bmc_android.R;
import com.liuyufei.bmc_android.data.BMCContract;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class BarChartFragment extends Fragment {
public static final int days = 7;
public BarChartFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("Visitor Statistic");
List<Entry> newVisitors = new ArrayList<>();
List<Entry> oldVisitors = new ArrayList<>();
// Inflate the layout for this fragment
com.github.mikephil.charting.charts.LineChart mLineChart = new com.github.mikephil.charting.charts.LineChart(this.getActivity());
String selectionNewVisitors = BMCContract.VisitorEntry.COLUMN_LASTLOGIN_TIME + " == " + BMCContract.VisitorEntry.COLUMN_CREATION_TIME + " GROUP BY lasttime";
String selectionOldVisitors = BMCContract.VisitorEntry.COLUMN_LASTLOGIN_TIME + " != " + BMCContract.VisitorEntry.COLUMN_CREATION_TIME + " GROUP BY lasttime";
String[] selectArgs = null;
String[] projection = {
"count(" + BMCContract.VisitorEntry.TABLE_NAME + "._id)",
"strftime('%d-%m-%Y', " + BMCContract.VisitorEntry.COLUMN_LASTLOGIN_TIME + ") as lasttime"
};
//show new visitors last 7 days
Cursor cursor_new = getActivity().getContentResolver()
.query(BMCContract.VisitorEntry.CONTENT_URI, projection, selectionNewVisitors, selectArgs, "lasttime desc limit "+days);
//show old visitors 7 days
Cursor cursor_old = getActivity().getContentResolver()
.query(BMCContract.VisitorEntry.CONTENT_URI, projection, selectionOldVisitors, selectArgs, "lasttime desc limit "+days);
DateFormat dateFormat = new SimpleDateFormat("dd/MM");
Calendar calendar = Calendar.getInstance();
final List<String> xAxisValues = new ArrayList<>();
for (int i = 0; i < days; i++) {
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_YEAR,-i);
xAxisValues.add(dateFormat.format(calendar.getTime()));
if (cursor_new.moveToNext()) {
newVisitors.add(new Entry(i, Integer.parseInt(cursor_new.getString(0))));
} else {
newVisitors.add(new Entry(i, 0));
}
if (cursor_old.moveToNext()) {
oldVisitors.add(new Entry(i, Integer.parseInt(cursor_old.getString(0))));
} else {
oldVisitors.add(new Entry(i, 0));
}
}
LineDataSet newVisitorSet = new LineDataSet(newVisitors, "New Visitors");
newVisitorSet.setAxisDependency(YAxis.AxisDependency.LEFT);
LineDataSet oldVisitorSet = new LineDataSet(oldVisitors, "Old Visitors");
oldVisitorSet.setAxisDependency(YAxis.AxisDependency.LEFT);
IAxisValueFormatter formatter = new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xAxisValues.get((int) value);
}
};
XAxis xAxis = mLineChart.getXAxis();
xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
xAxis.setValueFormatter(formatter);
YAxis left = mLineChart.getAxisLeft();
left.setDrawAxisLine(false); // no axis line
left.setDrawGridLines(false);
left.setGranularity(1f); // interval 1
mLineChart.getAxisRight().setEnabled(false); // no right axis
newVisitorSet.setColors(new int[]{
R.color.red,
}, mLineChart.getContext());
oldVisitorSet.setColors(new int[]{
R.color.blue,
}, mLineChart.getContext());
// use the interface ILineDataSet
List<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(newVisitorSet);
dataSets.add(oldVisitorSet);
LineData data = new LineData(dataSets);
mLineChart.setData(data);
mLineChart.invalidate(); // refresh
return mLineChart;
}
}
// new visitors in last week
// select count(*),strftime("%Y-%m-%d",last_login_time) as lastTime from bmc_visitor where creation_time == last_login_time group by lastTime limit 7
// old visitors in last week
// select count(*),strftime("%Y-%m-%d",last_login_time) as lastTime from bmc_visitor where creation_time != last_login_time group by lastTime limit 7
|
/**
* Main package for mbogo-java-getopt.
*
* @author Mike Bogochow
* @version 1.0.0, Feb 9, 2015
*/
package mbogo.getopt;
|
package Problem_7569;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String buf = br.readLine();
int N = Integer.parseInt(buf.split(" ")[0]);
int M = Integer.parseInt(buf.split(" ")[1]);
int H = Integer.parseInt(buf.split(" ")[2]);
// 위, 아래, 왼쪽, 오른쪽, 앞, 뒤
int[] dx = {0,0,-1,0,1,0};
int[] dy = {0,0,0,1,0,-1};
int[] dz = {1,-1,0,0,0,0};
int[][][] arr = new int[H][M][N];
Queue<int[]> q = new LinkedList<>();
StringTokenizer st;
for(int i = H-1; i>=0;i--) {
for(int j = 0; j<M;j++){
st = new StringTokenizer(br.readLine());
for(int k = 0;k<N;k++) {
arr[i][j][k] = Integer.parseInt(st.nextToken());
if(arr[i][j][k] == 1) {
q.add(new int[]{i,j,k});
}
}
}
}
if(q.size() == M*N*H) {
System.out.println(0);
return;
}
while(!q.isEmpty()) {
int size = q.size();
for(int k = 0; k<size; k++){
int[] data = q.poll();
for(int i = 0; i<6; i++) {
int x_ = data[0] + dx[i];
int y_ = data[1] + dy[i];
int z_ = data[2] + dz[i];
if(x_ >= H || x_ < 0 || y_ >= M || y_ < 0 || z_ >= N || z_ < 0) continue;
if(arr[x_][y_][z_] == 0) {
arr[x_][y_][z_] = arr[data[0]][data[1]][data[2]] + 1;
q.add(new int[]{x_,y_,z_});
}
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0; i<H; i++) {
for(int j = 0; j<M;j++) {
for(int k = 0; k<N;k++) {
if(arr[i][j][k] == 0) {
System.out.println(-1);
return;
}
if(arr[i][j][k] > max) {
max = arr[i][j][k];
}
}
}
}
System.out.println(max-1);
}
}
|
package Herencia;
public class Practicante extends Persona {
// tipo se refiere a profesional o no//
private String tipo;
public Practicante(String nombre, int edad, float sueldo, String tipo) {
super(nombre, edad, sueldo);
this.tipo = tipo;
}
public void sueldopracticante() {
if (getTipo()=="profesional") {
sueldo=900000;
}
else {
sueldo=450000;
}
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
|
package cs455.overlay.wireformats;
import java.io.*;
public class RegistryRequestsTrafficSummary extends Event {
public byte getType() {
return Protocol.REGISTRY_REQUESTS_TRAFFIC_SUMMARY;
}
public byte[] getBytes() throws IOException {
ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(baOutputStream));
dout.writeByte(getType());
dout.flush();
byte[] marshalledBytes = baOutputStream.toByteArray();
baOutputStream.close();
dout.close();
return marshalledBytes;
}
public RegistryRequestsTrafficSummary() { }
public RegistryRequestsTrafficSummary(ByteArrayInputStream baInputStream, DataInputStream din) throws IOException {
baInputStream.close();
din.close();
}
}
|
package cn.vaf714.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.vaf714.entity.CartList;
import cn.vaf714.entity.GeneralUser;
import cn.vaf714.service.UserService;
public class ShowShoppingCartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GeneralUser user = (GeneralUser) request.getSession().getAttribute("generalUser");
// 1.得到 List
List<CartList> shoppingCart = new UserService().getCart(user);
request.setAttribute("shoppingCart", shoppingCart);
request.setAttribute("shoppingCartPrice", new UserService().countShoppingCartPrice(shoppingCart));
request.setAttribute("shoppingCartNum", new UserService().countShoppingCartNum(shoppingCart));
// 2.反馈
request.getRequestDispatcher("/show_shopping_cart.jsp").forward(request, response);
}
}
|
package main.java.commands;
/**
* Created by Allin on 5/25/2016.
*/
import main.java.GeneralCommands;
import main.java.ICommand;
import sx.blah.discord.Discord4J;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.HTTP429Exception;
import sx.blah.discord.util.MessageBuilder;
import sx.blah.discord.util.MissingPermissionsException;
public class Hype implements ICommand {
/***
* Gets the name of the command
* @return the name of the command
*/
@Override
public String getName() {
return "hype";
}
/***
* Gets the role of the command
* @return the role of the command
*/
@Override
public String getRole() {
return "For when the train simply cannot be stopped";
}
/**
* Gets whether or not the triggering message is deleted
* @return whether or not the triggering message is deleted
*/
@Override
public boolean deletesMessage() {
return true;
}
/**
* Posts a hype message to the triggering messages channel
* @param message the message that triggered the command
* @param args the space separated values that followed the command
*/
@Override
public void handle(IMessage message, String[] args) {
try {
// Post a new message with HYPE!!!!!
new MessageBuilder(GeneralCommands.client).withChannel(message.getChannel()).withContent("༼ つ ◕\\_◕ ༽つHYPE༼ つ ◕\\_◕ ༽つ").build();
} catch (HTTP429Exception | MissingPermissionsException | DiscordException e) {
Discord4J.LOGGER.error("Exception", e);
}
}
/***
* Gets the name and role of the command
* @return the name and role of the command
*/
@Override
public String toString() {
return this.getName() + ": " + this.getRole();
}
}
|
package ua.siemens.dbtool.service;
import ua.siemens.dbtool.model.entities.ProjectManager;
import java.util.Collection;
/**
* Service interface for {@link ProjectManager}
*
* @author Perevoznyk Pavlo
* creation date 30 August 2017
* @version 1.0
*/
public interface ProjectManagerService {
void save(ProjectManager projectManager);
void update(ProjectManager projectManager);
void delete(Long id);
ProjectManager findById(Long id);
Collection<ProjectManager> findAll();
Collection<ProjectManager> findByKeyword(String keyWord);
}
|
/*
* Copyright 2002-2023 the original author or 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 org.springframework.aop.scope;
import java.util.Properties;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import javax.lang.model.element.Modifier;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aot.generate.MethodReference;
import org.springframework.aot.generate.MethodReference.ArgumentCodeGenerator;
import org.springframework.aot.test.generate.TestGenerationContext;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.aot.AotServices;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.aot.TestBeanRegistrationsAotProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.factory.aot.MockBeanFactoryInitializationCode;
import org.springframework.beans.testfixture.beans.factory.generator.factory.NumberHolder;
import org.springframework.core.ResolvableType;
import org.springframework.core.test.tools.Compiled;
import org.springframework.core.test.tools.TestCompiler;
import org.springframework.javapoet.CodeBlock;
import org.springframework.javapoet.MethodSpec;
import org.springframework.javapoet.ParameterizedTypeName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link ScopedProxyBeanRegistrationAotProcessor}.
*
* @author Stephane Nicoll
* @author Phillip Webb
* @since 6.0
*/
class ScopedProxyBeanRegistrationAotProcessorTests {
private final DefaultListableBeanFactory beanFactory;
private final TestBeanRegistrationsAotProcessor processor;
private final TestGenerationContext generationContext;
private final MockBeanFactoryInitializationCode beanFactoryInitializationCode;
ScopedProxyBeanRegistrationAotProcessorTests() {
this.beanFactory = new DefaultListableBeanFactory();
this.processor = new TestBeanRegistrationsAotProcessor();
this.generationContext = new TestGenerationContext();
this.beanFactoryInitializationCode = new MockBeanFactoryInitializationCode(this.generationContext);
}
@Test
void scopedProxyBeanRegistrationAotProcessorIsRegistered() {
assertThat(AotServices.factoriesAndBeans(this.beanFactory).load(BeanRegistrationAotProcessor.class))
.anyMatch(ScopedProxyBeanRegistrationAotProcessor.class::isInstance);
}
@Test
void getBeanRegistrationCodeGeneratorWhenNotScopedProxy() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(PropertiesFactoryBean.class).getBeanDefinition();
this.beanFactory.registerBeanDefinition("test", beanDefinition);
compile((freshBeanFactory, compiled) -> {
Object bean = freshBeanFactory.getBean("test");
assertThat(bean).isInstanceOf(Properties.class);
});
}
@Test
void getBeanRegistrationCodeGeneratorWhenScopedProxyWithoutTargetBeanName() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ScopedProxyFactoryBean.class).getBeanDefinition();
this.beanFactory.registerBeanDefinition("test", beanDefinition);
compile((freshBeanFactory, compiled) ->
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
freshBeanFactory.getBean("test")).withMessageContaining("'targetBeanName' is required"));
}
@Test
void getBeanRegistrationCodeGeneratorWhenScopedProxyWithInvalidTargetBeanName() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ScopedProxyFactoryBean.class)
.addPropertyValue("targetBeanName", "testDoesNotExist")
.getBeanDefinition();
this.beanFactory.registerBeanDefinition("test", beanDefinition);
compile((freshBeanFactory, compiled) ->
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
freshBeanFactory.getBean("test")).withMessageContaining("No bean named 'testDoesNotExist'"));
}
@Test
void getBeanRegistrationCodeGeneratorWhenScopedProxyWithTargetBeanName() {
RootBeanDefinition targetBean = new RootBeanDefinition();
targetBean.setTargetType(
ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class));
targetBean.setScope("custom");
this.beanFactory.registerBeanDefinition("numberHolder", targetBean);
BeanDefinition scopedBean = BeanDefinitionBuilder
.rootBeanDefinition(ScopedProxyFactoryBean.class)
.addPropertyValue("targetBeanName", "numberHolder").getBeanDefinition();
this.beanFactory.registerBeanDefinition("test", scopedBean);
compile((freshBeanFactory, compiled) -> {
Object bean = freshBeanFactory.getBean("test");
assertThat(bean).isInstanceOf(NumberHolder.class).isInstanceOf(AopInfrastructureBean.class);
});
}
@SuppressWarnings("unchecked")
private void compile(BiConsumer<DefaultListableBeanFactory, Compiled> result) {
BeanFactoryInitializationAotContribution contribution = this.processor.processAheadOfTime(this.beanFactory);
assertThat(contribution).isNotNull();
contribution.applyTo(this.generationContext, this.beanFactoryInitializationCode);
MethodReference methodReference = this.beanFactoryInitializationCode
.getInitializers().get(0);
this.beanFactoryInitializationCode.getTypeBuilder().set(type -> {
CodeBlock methodInvocation = methodReference.toInvokeCodeBlock(
ArgumentCodeGenerator.of(DefaultListableBeanFactory.class, "beanFactory"),
this.beanFactoryInitializationCode.getClassName());
type.addModifiers(Modifier.PUBLIC);
type.addSuperinterface(ParameterizedTypeName.get(Consumer.class, DefaultListableBeanFactory.class));
type.addMethod(MethodSpec.methodBuilder("accept").addModifiers(Modifier.PUBLIC)
.addParameter(DefaultListableBeanFactory.class, "beanFactory")
.addStatement(methodInvocation)
.build());
});
this.generationContext.writeGeneratedContent();
TestCompiler.forSystem().with(this.generationContext).compile(compiled -> {
DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory();
freshBeanFactory.setBeanClassLoader(compiled.getClassLoader());
compiled.getInstance(Consumer.class).accept(freshBeanFactory);
result.accept(freshBeanFactory, compiled);
});
}
}
|
/**
* @developer: WangY
* @时间:2016年10月14日 下午8:52:15
* @项目名:platformData
* 高弗特 goFirst
*/
package cn.com.hy.service;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import cn.com.hy.util.PropertiesUtils;
import cn.com.dimensoft.esb.query.QueryFwzxService;
@Service
public class GetPlatformDataService {
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
private final static String userInfo = "{'account':'040708','password':'szzhzx'}";
private static ClassPathXmlApplicationContext consumerContext = null;
private static QueryFwzxService queryService = null;
// 20170822 wangyong 增加用户新增资源代码查询
private Properties properties = null;
///系統初始化函数,配置文件读取,获取bean等
public void platformDataInit() {
consumerContext = new ClassPathXmlApplicationContext(this.getClass().getResource("/") + "consumer.xml");
queryService = (QueryFwzxService) consumerContext.getBean("query");
properties = new PropertiesUtils().getProperties();
}
//关闭系统
public void platformDataClosed() {
if (consumerContext != null) {
consumerContext.close();
}
}
public String query(String dataObjectCode, String conditions, String returnFields, int pageSize) {
String dataObjectCodesStr = dataObjectCode;
///
/// 初始化
this.platformDataInit();
String newUserInfo ="";
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
if (conditions.matches("(.*)JJBH(.*)")) {
if (dataObjectCodesStr.equals("DWD_DPTJCJ_JJXX")) {
dataObjectCodesStr = "DWD_DPT_JCJ_JJXX_ONEDAY";
}
if (dataObjectCodesStr.equals("DWD_DPTJCJ_CJXX")) {
dataObjectCodesStr = "DWD_DPT_JCJ_CJXX_ONEDAY";
}
if (dataObjectCodesStr.equals("DWD_DPT_AJ_JBXX")) {
dataObjectCodesStr = "DWD_DPT_AJ_JBXX_ONEDAY";
}
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
list = queryService.query(dataObjectCodesStr, conditions, returnFields, pageSize,newUserInfo);
if (null == list || 0 == list.size() ) {
dataObjectCodesStr = dataObjectCode;
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
list = queryService.query(dataObjectCodesStr, conditions, returnFields, pageSize,newUserInfo);
}
}else{
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
list = queryService.query(dataObjectCodesStr, conditions, returnFields, pageSize,newUserInfo);
}
/***
* 20170307 wangyong 待解决
* List<Map<String, String>> listOneDay = new ArrayList<Map<String,String>>();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay.clear();
if (conditions.indexOf("JJRQSJ") > 0) {
int JJRQSJindex = conditions.indexOf("JJRQSJ");
conditions = conditions.substring(0,JJRQSJindex-4);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_JJXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_CJXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_AJ_JBXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
}
///添加今天数据
if (listOneDay != null && listOneDay.size() >0) {
list.addAll(listOneDay);
}*/
String queryResult = "";
queryResult = new Gson().toJson(list);
/*
//测试使用
System.out.println("========开始***===========");
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
/// 初始化的結束
this.platformDataClosed();
return queryResult;
}
public String query(String dataObjectCode, String conditions, String returnFields, int pageSize, Boolean formatted, String resultStyle) {
String dataObjectCodesStr = dataObjectCode;
/// 初始化
this.platformDataInit();
String newUserInfo = "";
String queryResult = "";
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
queryResult = queryService.query(dataObjectCodesStr, conditions, returnFields, pageSize, formatted, resultStyle,newUserInfo);
/* //测试使用
System.out.println("========开始***===========");
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/* String listOneDay = "";
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
if (conditions.indexOf("JJRQSJ") > 0) {
int JJRQSJindex = conditions.indexOf("JJRQSJ");
conditions = conditions.substring(0,JJRQSJindex);
}
listOneDay="";
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_JJXX_ONEDAY", conditions, returnFields, pageSize, formatted, resultStyle,userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_CJXX_ONEDAY", conditions, returnFields, pageSize, formatted, resultStyle,
userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_AJ_JBXX_ONEDAY", conditions, returnFields, pageSize, formatted, resultStyle,
userInfo);
}
}*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
this.platformDataClosed();
return queryResult;
}
/// 接警信息
public String queryJJXX(String dataObjectCode, String conditions, String returnFields, int pageSize) {
String queryResult = "";
String dataObjectCodesStr = dataObjectCode;
String newUserInfo = "";
if (!dataObjectCode.equals("DWD_DPTJCJ_JJXX")) {
return queryResult;
}
this.platformDataInit();
///增加REQ_ID 王勇 201700820
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
int queryCounts = queryService.count(dataObjectCodesStr, conditions, newUserInfo);
// System.out.println(queryCounts);
List<Map<String, String>> list = queryService.query(dataObjectCode, conditions, returnFields, queryCounts, newUserInfo);
/*List<Map<String, String>> listOneDay = new ArrayList<Map<String,String>>();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
if (conditions.indexOf("JJRQSJ") > 0) {
int JJRQSJindex = conditions.indexOf("JJRQSJ");
conditions = conditions.substring(0,JJRQSJindex);
}
listOneDay.clear();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_JJXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_CJXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_AJ_JBXX_ONEDAY", conditions, returnFields, pageSize, userInfo);
}
}
///添加今天数据
if (listOneDay != null&&listOneDay.size() > 0) {
list.addAll(listOneDay);
}*/
listMapSort(list);
List<Map<String, String>> frontSubList = list.subList(0, 50);
if (queryCounts <= 50) {
frontSubList.clear();
frontSubList = list.subList(0, queryCounts);
}
queryResult = (new Gson()).toJson(frontSubList);
/* //测试使用
System.out.println("========开始***===========");
// System.out.println("查询条数:" + queryCounts);
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
this.platformDataClosed();
return queryResult;
}
/// list 排序
public void listMapSort(List<Map<String, String>> list) {
Collections.sort(list, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> o1, Map<String, String> o2) {
int objSortResult = o2.get("JJRQSJ").compareTo(o1.get("JJRQSJ"));
return objSortResult;
}
});
}
/// 总条数
public String count(String dataObjectCode, String conditions) {
String dataObjectCodesStr = dataObjectCode;
String newUserInfo ="";
this.platformDataInit();
///增加REQ_ID 王勇 201700820
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
int counts = queryService.count(dataObjectCode, conditions, newUserInfo);
/*int listOneDay = 0;
if (dataObjectCodesStr.matches("(.*)DWD_DPT_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPT_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_JBXX(.*)")) {
if (conditions.indexOf("JJRQSJ") > 0) {
int JJRQSJindex = conditions.indexOf("JJRQSJ");
conditions = conditions.substring(0,JJRQSJindex);
}
listOneDay = 0;
if (dataObjectCodesStr.matches("(.*)DWD_DPT_JJXX(.*)")) {
listOneDay = queryService.count("DWD_DPT_JJXX_ONEDAY",conditions, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_CJXX(.*)")) {
listOneDay = queryService.count("DWD_DPT_CJXX_ONEDAY",conditions, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_JBXX(.*)")) {
listOneDay = queryService.count("DWD_DPT_JBXX_ONEDAY",conditions, userInfo);
}
}
if(listOneDay>0)
{
counts += listOneDay;
}*/
String queryResult = "";
queryResult = counts + "";
/* //测试使用
System.out.println("========开始***===========");
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
this.platformDataClosed();
return queryResult;
}
public String pageQuery(String dataObjectCode, String conditions, String returnFields, int pageSize,int pageNumber) {
String dataObjectCodesStr = dataObjectCode;
String newUserInfo ="";
this.platformDataInit();
///增加REQ_ID 王勇 201700820
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCodesStr)+"','account':'040708','password':'szzhzx'}";
List<Map<String, String>> list = queryService.pageQuery(dataObjectCodesStr, conditions, returnFields, pageSize, pageNumber, newUserInfo);
//List<Map<String, String>> list = queryService.query(dataObjectCode, conditions, returnFields, queryCounts, userInfo);
List<Map<String, String>> listOneDay = new ArrayList<Map<String,String>>();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
if (conditions.indexOf("JJRQSJ") > 0) {
int JJRQSJindex = conditions.indexOf("JJRQSJ");
conditions = conditions.substring(0,JJRQSJindex);
}
listOneDay.clear();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)")) {
listOneDay = queryService.pageQuery("DWD_DPT_JCJ_JJXX_ONEDAY",conditions, returnFields, pageSize,
pageNumber, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")) {
listOneDay = queryService.pageQuery("DWD_DPT_JCJ_CJXX_ONEDAY",conditions, returnFields, pageSize,
pageNumber, userInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay = queryService.pageQuery("DWD_DPT_AJ_JBXX_ONEDAY", conditions, returnFields, pageSize,
pageNumber, userInfo);
}
}
if (listOneDay.size()>0) {
list.addAll(listOneDay);
}
String queryResult = "";
queryResult = (new Gson()).toJson(list);
/* //测试使用
System.out.println("========开始***===========");
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
this.platformDataClosed();
return queryResult;
}
public String pageQuery(String dataObjectCode, String conditions, String returnFields, int pageSize, int pageNumber,Boolean formatted, String resultStyle) {
this.platformDataInit();
///增加REQ_ID 王勇 201700820
String newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCode)+"','account':'040708','password':'szzhzx'}";
String queryResult = "";
queryResult = queryService.pageQuery(dataObjectCode, conditions, returnFields, pageSize, pageNumber, formatted,
resultStyle, newUserInfo);
/* //测试使用
System.out.println("========开始***===========");
System.out.println("结果是:" + queryResult);
System.out.println("========**end***===========");*/
/// 出现接口问题报0
if (queryResult.equals("null")) {
queryResult = "0";
}
this.platformDataClosed();
return queryResult;
}
// 根据资源代码
/*
* public void getData(String dataObjectCode, int a) {
*
* ClassPathXmlApplicationContext consumerContext = new
* ClassPathXmlApplicationContext( this.getClass().getResource("/") +
* "consumer.xml");
*
* QueryService queryService = (QueryService)
* consumerContext.getBean("query");
*
* List<Map<String, String>> list = queryService.pageQuery(dataObjectCode,
* "", "", 20, 1); for (Map<String, String> map : list) {
* System.out.println(map); }
*
* consumerContext.close(); }
*/
/*
* ***接口名称*** dataObjectCode名称 1 苏州流动人口信息( 资源代码:DWD_RG_ZZRK_SJ)
*
* 2 住宿信息 (资源代码:DWD_ZAGUEST )
*
* 3 社区平台重点人员 (资源代码:DWD_PCS_T_RY_ZDRY)
*
* 4 盘查人员 (资源代码:DWD_PCK_ZAPC_RYXX)
*
* 5 看守所人员 (暂无,稍后再补)
*
* 6 上网信息2016(资源代码:DWD_ZCPTSWRY2016)
*
* 7 苏州常控预警表(资源代码:DWD_QB_ZDRY_SZCKYJ)
*
* 8 案件处理信息(资源代码:DWD_DPT_AJ_CLCS_JGZXB)
*/
// 暂住人口的
/*
* String dataObjectCode ="DWD_RG_ZZRK_SJ";
*
* QueryService queryService = (QueryService)
* consumerContext.getBean("query");
*/
/**
* 获取资源信息数据
*/
/**
* dataObjectCode 资源代码 conditions where 条件 例如 : and xx='' and ddd='dd'
* returnFields 返回的字段 默认全部字段 startIndex 不包含 endIndex 包含
*
*/
/**
* 分页查询
*
* @param dataObjectCode
* 资源代码
* @param conditions
* where 条件 例如 : and xx='' and ddd='dd'
* @param returnFields
* 返回的字段 默认全部字段
* @param pageSize
* 每页大小
* @param pageNumber
* 当前页
* @return
*/
/*
* List<Map<String,String>> list = queryService.pageQuery(dataObjectCode,
* "", "", 20, 1); for(Map<String,String> map : list) {
* System.out.println(map); }
*/
public void DisplayPage(String json, HttpServletResponse response) {
response.setCharacterEncoding("gbk");
PrintWriter pWriter = null;
try {
pWriter = (PrintWriter) response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
pWriter.print(json);
pWriter.flush();
}
public List<Map<String, String>> getOneDayList(String dataObjectCode,String conditions, String returnFields, int pageSize )
{
String dataObjectCodesStr = dataObjectCode;
List<Map<String, String>> listOneDay = new ArrayList<Map<String,String>>();
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)") ||dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")|| dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay.clear();
String newUserInfo ="";
this.platformDataInit();
///增加REQ_ID 王勇 201700820
newUserInfo = "{'REQ_ID':'"+properties.getProperty(dataObjectCode)+"','account':'040708','password':'szzhzx'}";
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_JJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_JJXX_ONEDAY", conditions, returnFields, pageSize, newUserInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPTJCJ_CJXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_JCJ_CJXX_ONEDAY", conditions, returnFields, pageSize, newUserInfo);
}
if (dataObjectCodesStr.matches("(.*)DWD_DPT_AJ_JBXX(.*)")) {
listOneDay = queryService.query("DWD_DPT_AJ_JBXX_ONEDAY", conditions, returnFields, pageSize, newUserInfo);
}
}
return listOneDay;
}
}
|
package serve.serveup.utils.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
import serve.serveup.R;
import serve.serveup.dataholder.RestaurantInfo;
import serve.serveup.utils.ContentStore;
import serve.serveup.utils.Utils;
import serve.serveup.views.restaurant.RestaurantActivity;
public class DiscoveryRecyclerAdapter
extends RecyclerView.Adapter<DiscoveryRecyclerAdapter.DiscoveryRecyclerHolder> {
// Contains the data from which the adapter will build the cards
private List<RestaurantInfo> restaurantsHome;
@NonNull
private RestaurantInfo currentRestaurant;
// Define the View Holder
static class DiscoveryRecyclerHolder extends RecyclerView.ViewHolder {
// Parameters based on the layout of the Card that will be used in the Adapter
// In this case layout/card_discovery.xml
int restaurantID;
CardView cardDiscoveryView;
ImageView cardDiscoveryImage;
TextView cardDiscoveryTitle;
TextView cardDiscoveryType;
RatingBar cardDiscoveryRating;
DiscoveryRecyclerHolder(final View itemView) {
super(itemView);
// Initialize the parameters based on the Card layout names
cardDiscoveryView = itemView.findViewById(R.id.cardDiscoveryView);
cardDiscoveryImage = itemView.findViewById(R.id.cardDiscoveryImage);
cardDiscoveryTitle = itemView.findViewById(R.id.cardDiscoveryTitle);
cardDiscoveryType = itemView.findViewById(R.id.cardDiscoveryType);
cardDiscoveryRating = itemView.findViewById(R.id.cardDiscoveryRating);
}
}
// Adapter constructor
public DiscoveryRecyclerAdapter(List<RestaurantInfo> restaurantsHome) {
this.restaurantsHome = restaurantsHome;
}
/*
onCreateViewHolder, onBindViewHolder and getItemCount() HAVE to be defined in order to get rid
of the errors!
*/
@NonNull
@Override
public DiscoveryRecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// Find and inflate the appropriate card layout.
// In this case layout/card_discovery.xml
View cardDiscoveryView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_discovery, parent, false);
return new DiscoveryRecyclerHolder(cardDiscoveryView);
}
@Override
public void onBindViewHolder(@NonNull final DiscoveryRecyclerHolder holder, int position) {
// Get the restaurant home info for the appropriate restaurant
RestaurantInfo restInfo = this.restaurantsHome.get(position);
Context myContext = holder.cardDiscoveryTitle.getContext();
ContentStore cntStore = new ContentStore(myContext);
// Set the Holder (card) values based on the values from the data list
holder.restaurantID = restInfo.getIdRestavracija();
holder.cardDiscoveryTitle.setText(restInfo.getImeRestavracije());
holder.cardDiscoveryType.setText(restInfo.getTip());
holder.cardDiscoveryRating.setRating(restInfo.getOcena());
if (myContext != null) {
Bitmap restBitmap = Utils.parseBitmapFromBase64(myContext, restInfo.getSlika());
holder.cardDiscoveryImage.setImageBitmap(restBitmap);
}
holder.cardDiscoveryView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle myBundle = new Bundle();
currentRestaurant = restaurantsHome.get(holder.getAdapterPosition());
Utils.logInfo("current restaurant position: " + holder.getAdapterPosition());
myBundle.putSerializable("restaurant_info", currentRestaurant);
if (view.getContext() != null) {
Intent myIntent = new Intent(view.getContext(), RestaurantActivity.class);
myIntent.putExtras(myBundle);
view.getContext().startActivity(myIntent);
}
}
});
}
@Override
public int getItemCount() {
return restaurantsHome.size();
}
// In case the adapter needs to be refreshed. A simple implementation
public void refreshAdapter(List<RestaurantInfo> RestaurantInfosNew) {
this.restaurantsHome.clear();
this.restaurantsHome.addAll(RestaurantInfosNew);
notifyDataSetChanged();
}
private void enableView(View myView) {
myView.setEnabled(true);
myView.setAlpha(1f);
}
private void disableView(View myView) {
myView.setEnabled(false);
myView.setAlpha(.5f);
}
}
|
package net.maizegenetics.analysis.clustering;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import net.maizegenetics.dna.snp.NucleotideAlignmentConstants;
/**
* HaplotypeClusterer clusters haplotypes by distance as defined in the Haplotype class.
* This class can be extended to apply different clustering rules.
* @author Peter Bradbury
*/
public class HaplotypeClusterer {
ArrayList<Haplotype> haplotypeList;
int numberOfHaplotypes;
int nsites;
static final byte N = NucleotideAlignmentConstants.getNucleotideDiploidByte("N");
ArrayList<HaplotypeCluster> clusterList;
public static enum TYPE {whole, partial}
/**
* @param haplotypes a List of haplotype or genotype sequence to be clustered
*/
public HaplotypeClusterer(List<byte[]> haplotypes) {
numberOfHaplotypes = haplotypes.size();
nsites = haplotypes.get(0).length;
haplotypeList = new ArrayList<Haplotype> ();
for (byte[] hap:haplotypes) haplotypeList.add(new Haplotype(hap));
Collections.sort(haplotypeList);
}
/**
* @param haplotypes a List of Haplotypes to be clustered
*/
public HaplotypeClusterer(ArrayList<Haplotype> haplotypes) {
numberOfHaplotypes = haplotypes.size();
nsites = haplotypes.get(0).seqlen;
haplotypeList = haplotypes;
Collections.sort(haplotypeList);
}
/**
* Groups a list of Haplotypes into clusters.
* Clusters are created so that all Haplotypes in a cluster have 0 pairwise distance.
* Because of missing data a Haplotype can be assigned to more than one cluster.
*/
public void makeClusters() {
LinkedList<Haplotype> tmpHapList = new LinkedList<Haplotype>(haplotypeList);
clusterList = new ArrayList<HaplotypeCluster>();
HaplotypeCluster cluster = new HaplotypeCluster(tmpHapList.removeFirst(), 1.0);
clusterList.add(cluster);
Iterator<Haplotype> hit = tmpHapList.iterator();
while (hit.hasNext()) {
boolean inCluster = false;
Haplotype hap = hit.next();
for (HaplotypeCluster clus : clusterList) {
if (clus.get(0).distanceFrom(hap) == 0) {
inCluster = true;
break;
}
}
if (!inCluster) {
HaplotypeCluster newCluster = new HaplotypeCluster(hap, 1.0);
clusterList.add(newCluster);
hit.remove();
}
}
int nclusters = clusterList.size();
for (Haplotype hap:tmpHapList) {
boolean[] incluster = new boolean[nclusters];
Arrays.fill(incluster,true);
int count = 0;
for (int c = 0; c < nclusters; c++) {
HaplotypeCluster clus = clusterList.get(c);
Iterator<Haplotype> clusIt = clus.getIterator();
while(clusIt.hasNext() && incluster[c]) {
Haplotype member = clusIt.next();
if (member.distanceFrom(hap) > 0) {
incluster[c] = false;
}
}
if (incluster[c]) {
count++;
clus.add(hap);
}
}
double hapscore = 1.0 / ((double) count);
for (int c = 0; c < nclusters; c++) {
if (incluster[c]) clusterList.get(c).incrementScore(hapscore);
}
}
}
/**
* Removes all haplotypes within maxdistance of the haplotype of the first cluster.
* After the haplotypes have been removed clusters are remade and sorted.
* @param maxdistance all haplotypes within maxdistance or less of the haplotype of the first cluster are removed from the haplotypeList
*/
public HaplotypeCluster removeFirstHaplotypes(int maxdistance) {
//remove all haplotypes maxdistance or less from the haplotype of cluster 0
Iterator<Haplotype> hapit = haplotypeList.listIterator();
byte[] firstHaplotype = clusterList.get(0).getHaplotype();
ArrayList<Haplotype> haplist = new ArrayList<Haplotype>();
while (hapit.hasNext()) {
Haplotype testhap = hapit.next();
if (Haplotype.getDistance(firstHaplotype, testhap.seq) <= maxdistance) {
haplist.add(testhap);
hapit.remove();
}
}
makeClusters();
sortClusters();
return new HaplotypeCluster(haplist, haplist.size());
}
/**
* Sorts clusters according to HaplotypeCluster sort order.
*/
public void sortClusters() {
Collections.sort(clusterList);
}
/**
* @return the number of clusters
*/
public int getNumberOfClusters() {
return clusterList.size();
}
/**
* @return the number of Haplotypes contained in each cluster
*/
public int[] getClusterSizes() {
int nclusters = clusterList.size();
int[] sizes = new int[nclusters];
for (int i = 0; i < nclusters; i++) sizes[i] = clusterList.get(i).getSize();
return sizes;
}
/**
* After the initial cluster formation a Haplotype score equals the 1 / (number of clusters to which it belongs).
* Merging does not update the cluster score.
* @return the score for each cluster.
*/
public double[] getClusterScores() {
int n = clusterList.size();
double[] scores = new double[n];
for (int i = 0; i < n; i++) {
scores[i] = clusterList.get(i).getScore();
}
return scores;
}
/**
* @return List of clusters
*/
public ArrayList<HaplotypeCluster> getClusterList() { return clusterList; }
/**
* @param cluster0
* @param cluster1
* @return the minimum of the number of haplotypes in cluster0 not in cluster1 and the number of haplotypes in cluster 1 not in cluster0
*/
public static int clusterDistanceDistinctHaplotypes(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
int count0 = cluster0.getCountOfHaplotypesNotInThisCluster(cluster1);
int count1 = cluster1.getCountOfHaplotypesNotInThisCluster(cluster0);
return Math.min(count0, count1);
}
/**
* @param cluster0
* @param cluster1
* @return the minimum of the number of haplotypes in cluster0 not in cluster1 and the number of haplotypes in cluster 1 not in cluster0 divided my the minimum number of haplotypes in the two clusters
*/
public static double clusterDistanceDistinctHaplotypeProportion(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
int count0 = cluster0.getCountOfHaplotypesNotInThisCluster(cluster1);
int count1 = cluster1.getCountOfHaplotypesNotInThisCluster(cluster0);
double minNumber = Math.min(cluster0.getSize(), cluster1.getSize());
return Math.min(count0, count1) / minNumber;
}
/**
* @param cluster0
* @param cluster1
* @return the number of alleles difference between the cluster haplotypes
*/
public static int clusterDistanceClusterHaplotypeDiff(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
byte[] hap0 = cluster0.getHaplotype();
byte[] hap1 = cluster1.getHaplotype();
return Haplotype.getDistance(hap0, hap1);
}
/**
* @param cluster0
* @param cluster1
* @return the number of alleles difference between the cluster haplotypes divided by the number of nonmissing sites
*/
public static double clusterDistanceClusterDiffProportion(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
byte[] hap0 = cluster0.getHaplotype();
byte[] hap1 = cluster1.getHaplotype();
int n = hap0.length;
double notmissing = 0;
double notmatching = 0;
byte N = NucleotideAlignmentConstants.getNucleotideDiploidByte('N');
for (int i = 0; i < n; i++) {
if (hap0[i] != N && hap1[i] != N) {
notmissing++;
if (hap0[i] != hap1[i]) notmatching++;
}
}
return notmatching/notmissing;
}
/**
* @param cluster0
* @param cluster1
* @return the maximum of the pairwise difference between individual haplotypes in the two clusters
*/
public static int clusterDistanceMaxPairDiff(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
HaplotypeCluster subCluster0 = cluster0.copy();
subCluster0.removeAll(cluster1);;
HaplotypeCluster subCluster1 = cluster1.copy();
subCluster1.removeAll(cluster0);
int maxdiff = 0;
Iterator<Haplotype> hit0 = subCluster0.getIterator();
while (hit0.hasNext()) {
Haplotype h0 = hit0.next();
Iterator<Haplotype> hit1 = subCluster1.getIterator();
while (hit1.hasNext()) {
Haplotype h1 = hit1.next();
maxdiff = Math.max(maxdiff, Haplotype.getDistance(h0, h1));
}
}
return maxdiff;
}
/**
* @param cluster0
* @param cluster1
* @return the average of the pairwise differences between the haplotypes that are not shared between clusters
*/
public static double clusterDistanceAveragePairDiff(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
HaplotypeCluster subCluster0 = cluster0.copy();
subCluster0.removeAll(cluster1);;
HaplotypeCluster subCluster1 = cluster1.copy();
subCluster1.removeAll(cluster0);
int totaldiff = 0;
int count = 0;
Iterator<Haplotype> hit0 = subCluster0.getIterator();
while (hit0.hasNext()) {
Haplotype h0 = hit0.next();
Iterator<Haplotype> hit1 = subCluster1.getIterator();
while (hit1.hasNext()) {
Haplotype h1 = hit1.next();
totaldiff += Haplotype.getDistance(h0, h1);
count++;
}
}
return ((double) totaldiff) / ((double) count);
}
/**
* @param cluster0
* @param cluster1
* @return the total of the pairwise differences between the haplotypes that are not shared between clusters
*/
public static int clusterDistanceTotalPairDiff(HaplotypeCluster cluster0, HaplotypeCluster cluster1){
HaplotypeCluster subCluster0 = cluster0.copy();
subCluster0.removeAll(cluster1);;
HaplotypeCluster subCluster1 = cluster1.copy();
subCluster1.removeAll(cluster0);
int totaldiff = 0;
Iterator<Haplotype> hit0 = subCluster0.getIterator();
while (hit0.hasNext()) {
Haplotype h0 = hit0.next();
Iterator<Haplotype> hit1 = subCluster1.getIterator();
while (hit1.hasNext()) {
Haplotype h1 = hit1.next();
totaldiff += Haplotype.getDistance(h0, h1);
}
}
return totaldiff;
}
/**
* Merges clusters whose maximum pairwise difference is less than maxdiff. Clusters are tested sequentially.
* That is, if two clusters are merged, they become the new head cluster against which remaining clusters are tested for merging.
* @param candidateClusters an ArrayList of HaplotypeClusters
* @param maxdiff
* @return merges clusters whose maximum pairwise difference is less or equal to maxdiff
*/
public static ArrayList<HaplotypeCluster> getMergedClusters(ArrayList<HaplotypeCluster> candidateClusters, int maxdiff) {
ArrayList<HaplotypeCluster> candidates = new ArrayList<HaplotypeCluster>(candidateClusters);
Collections.sort(candidates);
ArrayList<HaplotypeCluster> mergedClusterList = new ArrayList<HaplotypeCluster>();
while (candidates.size() > 0) {
HaplotypeCluster headCluster = candidates.remove(0);
mergedClusterList.add(headCluster);
Iterator<HaplotypeCluster> cit = candidates.iterator();
while (cit.hasNext()) {
HaplotypeCluster candidate = cit.next();
boolean mergePair = doMerge(headCluster, candidate, maxdiff);
if (mergePair) {
cit.remove();
mergeTwoClusters(headCluster, candidate);
}
}
}
return mergedClusterList;
}
/**
* Tests whether two clusters are less than or equal to maxdiff distant.
* Uses clusterDistanceMaxPairDiff() to calculate distance.
* @param c0 a cluster
* @param c1 another cluster
* @param maxdiff
* @return true if clusters are maxdiff or less distant, false otherwise
*/
public static boolean doMerge(HaplotypeCluster c0, HaplotypeCluster c1, int maxdiff) {
int diff = clusterDistanceMaxPairDiff(c0, c1);
return diff <= maxdiff;
}
/**
* Merges two clusters, c0 and c1.
* @param c0
* @param c1
*/
public static void mergeTwoClusters(HaplotypeCluster c0, HaplotypeCluster c1) {
c1.removeAll(c0);
c0.addAll(c1);
}
}
|
package io.cde.account.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import io.cde.account.dao.impl.AccountDaoImpl;
import io.cde.account.domain.Account;
import io.cde.account.domain.Email;
import io.cde.account.domain.i18n.Error;
import io.cde.account.domain.i18n.SystemError;
import io.cde.account.exception.BizException;
import io.cde.account.service.AccountService;
import io.cde.account.tools.AccountCheck;
import io.cde.account.tools.ErrorMessageSourceHandler;
/**
* @author lcl
*/
@Service
public class AccountServiceImpl implements AccountService {
/**
* ErrorMessageSourceHandler对象.
*/
private ErrorMessageSourceHandler errorHandler;
/**
* AccountCheck对象.
*/
private AccountCheck accountCheck;
/**
* AccountDaoImpl对象.
*/
private AccountDaoImpl accountDao;
/**
* 通过构造器注入对象.
*
* @param errorHandler errorHandler对象
* @param accountCheck accountCheck对象
* @param accountDao accountDao对象
*/
@Autowired
public AccountServiceImpl(final ErrorMessageSourceHandler errorHandler, final AccountCheck accountCheck, final AccountDaoImpl accountDao) {
this.errorHandler = errorHandler;
this.accountCheck = accountCheck;
this.accountDao = accountDao;
}
/* (non-Javadoc)
* @see io.cde.account.service.impl.AccountService#createAccount(io.cde.account.domain.Account)
*/
@Override
public void createAccount(final Account account) throws BizException {
final Email email = new Email();
final String hashed;
final List<Email> emails = new ArrayList<>();
accountCheck.checkAccountExistedByName(account.getName());
accountCheck.checkEmailExistedByEmail(account.getEmail());
email.setEmailId(new ObjectId().toString());
email.setEmail(account.getEmail());
emails.add(email);
account.setEmails(emails);
hashed = BCrypt.hashpw(account.getPassword(), BCrypt.gensalt());
account.setPassword(hashed);
account.setTimestamp(new Date());
final int createAccount = accountDao.createAccount(account);
if (createAccount <= 0) {
throw new BizException(SystemError.INSERT_FAILED.getCode(), errorHandler.getMessage(SystemError.INSERT_FAILED.toString()));
}
}
/* (non-Javadoc)
* @see io.cde.account.service.impl.AccountService#getAccountInfo(java.lang.String)
*/
@Override
@Cacheable(cacheNames = {"accounts"}, key = "'account:' + #accountId")
public Account getAccountInfo(final String accountId) {
return accountDao.findById(accountId);
}
/* (non-Javadoc)
* @see io.cde.account.service.impl.AccountService#updateAccount(io.cde.account.domain.Account)
*/
@Override
@Caching(evict = {@CacheEvict(cacheNames = "accounts", key = "'account:' + #account.id"),
@CacheEvict(cacheNames = "emails", key = "'email:' + #account.id"),
@CacheEvict(cacheNames = "mobiles", key = "'mobile:' + #account.id")})
public void updateAccount(final Account account) throws BizException {
accountCheck.checkAccountExistedById(account.getId());
final int updateAccount = accountDao.updateAccount(account);
if (updateAccount <= 0) {
throw new BizException(SystemError.UPDATE_FAILED.getCode(), errorHandler.getMessage(SystemError.UPDATE_FAILED.toString()));
}
}
/* (non-Javadoc)
* @see io.cde.account.service.impl.AccountService#updateName(java.lang.String, java.lang.String)
*/
@Override
@CacheEvict(cacheNames = {"accounts"}, key = "'account:' + #accountId")
public void updateName(final String accountId, final String name) throws BizException {
accountCheck.checkAccountExistedById(accountId);
accountCheck.checkAccountExistedByName(name);
final int updateResult = accountDao.updateName(accountId, name);
if (updateResult <= 0) {
throw new BizException(SystemError.UPDATE_FAILED.getCode(), errorHandler.getMessage(SystemError.UPDATE_FAILED.toString()));
}
}
/* (non-Javadoc)
* @see io.cde.account.service.impl.AccountService#updatePassword(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
@CacheEvict(cacheNames = {"accounts"}, key = "'account:' + #accountId")
public void updatePassword(final String accountId, final String oldPassword, final String newPassword) throws BizException {
final Account account = accountCheck.checkAccountExistedById(accountId);
if (!BCrypt.checkpw(oldPassword, account.getPassword())) {
throw new BizException(Error.UNMATCHED_ACCOUNT_AND_PASSWORD.getCode(), errorHandler.getMessage(Error.UNMATCHED_ACCOUNT_AND_PASSWORD.toString()));
}
final int updatePassword = accountDao.updatePassword(accountId, BCrypt.hashpw(newPassword, BCrypt.gensalt()));
if (updatePassword <= 0) {
throw new BizException(SystemError.UPDATE_FAILED.getCode(), errorHandler.getMessage(SystemError.UPDATE_FAILED.toString()));
}
}
}
|
package team21.pylonconstructor;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class ViewTaggedMoodActivity extends AppCompatActivity {
private TaggedMoodAdapter adapter;
private List<Mood> moodList;
ElasticSearch elasticSearch;
Profile profile;
Context context = this;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_tagged_mood);
String moodid = getIntent().getExtras().getString("mood_id");
Mood mood = null;
SharedPreferences sharedPreferences = getSharedPreferences("userinfo", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
//TODO: replace these with notification query to populate moodList
elasticSearch = new ElasticSearch();
try {
mood = elasticSearch.getmoodfromid(moodid);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
moodList = new ArrayList<Mood>();
moodList.add(mood);
adapter = new TaggedMoodAdapter(this, moodList);
recyclerView = (RecyclerView) findViewById(R.id.prf_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
|
/**
* This is a class that calculates compound interest rates.
* @author Jake Petroules
* @version 1.0 final
*/
public class Account
{
private int initialBalance;
private float interestRate;
/**
* Creates an account with given initial balance and interest rate.
* @param initialBalance The starting balance.
* @param interestRate The interest rate.
*/
public Account(int initialBalance, float interestRate)
{
this.initialBalance = initialBalance;
this.interestRate = interestRate;
}
/**
* Gets the account balance after the specified number of years.
* @param years The number of years that interest has accrued.
* @return The balance after the specified number of years.
*/
public double getBalance(int years)
{
return (this.initialBalance * Math.pow(1 + (this.interestRate / 100), years));
}
}
|
import javax.swing.JFrame;
/**
* Created by Гамзат on 04.06.2017.
*
* Урок 53 - GUI - JFrame, JOptionPane, JTextField, JPasswordField (часть 3)
*/
public class Bender {
public static void main(String[] args) {
Fry okno = new Fry();
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setSize(400, 200);
okno.setVisible(true);
}
}
|
package com.gxjtkyy.standardcloud.common.aop;
import com.alibaba.fastjson.JSON;
import com.gxjtkyy.standardcloud.common.annotation.LogAction;
import com.gxjtkyy.standardcloud.common.domain.vo.RequestVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* 日志切面
*
* @Package com.gxjtkyy.quality.aop
* @Author lizhenhua
* @Date 2018/6/6 15:56
*/
@Aspect
@Component
@Slf4j
@Order(1)
public class LogAspect {
@Autowired
private HttpServletRequest httpRequest;
@Around("@annotation(logAction)")
public Object addActionLog(ProceedingJoinPoint joinPoint, LogAction logAction){
Object[] args = joinPoint.getArgs();
Object request = null;
for (Object obj : args) {
if (obj instanceof RequestVO) {
request = obj;
break;
}
}
Object obj = null;
try {
obj = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log.info("path-->{},\n ip-->{}, \n request-->{},\n response-->{}",httpRequest.getRequestURI(), httpRequest.getRemoteAddr(), JSON.toJSON(request), JSON.toJSON(obj));
return obj;
}
}
|
package com.github.bartimaeusnek.bettervoidworlds.common.tileentities;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.ITeleporter;
public class UniversalTeleportTE extends TileEntity implements ITeleporter {
public UniversalTeleportTE() {
}
@Override
public void placeEntity(World world, Entity entity, float yaw) {
if (world.isRemote)
return;
int id = this.getTileData().getInteger("DIM_ID");
int[] pos = this.getTileData().getIntArray("RETURNPOS");
Pteleporter tteleporter = new Pteleporter(DimensionManager.getWorld(id, true), pos);
tteleporter.placeEntity(world, entity, yaw);
}
@Override
public boolean isVanilla() {
return false;
}
class Pteleporter extends Teleporter {
int[] pos;
public Pteleporter(WorldServer worldIn, int[] pos) {
super(worldIn);
this.pos = pos;
}
@Override
public boolean makePortal(Entity par1Entity) {
return true;
}
@Override
public void placeInPortal(Entity entityIn, float rotationYaw) {
if (pos.length == 3) {
entityIn.setPositionAndUpdate(pos[0] + 1, pos[1], pos[2]);
} else {
entityIn.setPositionAndUpdate(world.getSpawnPoint().getX() + 1, world.getSpawnPoint().getY(), world.getSpawnPoint().getZ());
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.