text stringlengths 10 2.72M |
|---|
package com.tencent.mm.plugin.appbrand.appusage;
import com.tencent.mm.kernel.g;
class c$2 implements Runnable {
final /* synthetic */ c fld;
public c$2(c cVar) {
this.fld = cVar;
}
public final void run() {
if (g.Eg().Dx() && !b.acJ()) {
c.a(this.fld, 2, 7, 0, true, null);
}
}
}
|
package com.uwetrottmann.trakt5.entities;
import org.threeten.bp.LocalDate;
import java.util.List;
public class Movie extends BaseEntity {
public Integer year;
public MovieIds ids;
// extended info
public String certification;
public String tagline;
/** Date in UTC time. */
public LocalDate released;
public Integer runtime;
public String trailer;
public String homepage;
public String language;
public List<String> genres;
}
|
package com.Collections_PriorityQueue_HashMap_TreeMap;
import java.util.TreeMap;
//6. Write a Java program to delete all elements from a given Tree Map.
public class TreeMap_DeleteAllElement {
public static void main(String args[]) {
// Create a tree map
TreeMap<String, String> tree_map1 = new TreeMap<String, String>();
// Put elements to the map
tree_map1.put("C1", "Rahul");
tree_map1.put("C2", "Rohan");
tree_map1.put("C3", "Bhanu");
tree_map1.put("C4", "Shyam");
tree_map1.put("C5", "Rohit");
System.out.println("Orginal TreeMap content: " + tree_map1);
tree_map1.clear();
System.out.println("The New map: " + tree_map1);
}
}
|
package com.Stephanie;
public class CD extends Album{
public CD(String artist,String title,double price){
super(artist, title,price); //call the album constructor
}
@Override
public String toString() {
return "Format = CD, Artist = " + artist + ", Title= " +
title + ", Price $" + price;
}}
|
/*
* 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 math;
/**
* Creates an hexadecimal math expression
* @author fabio
*/
public class HexExpression extends Expression {
public HexExpression(){
super();
}
public HexExpression(HexExpression expression){
super(expression);
}
public static BinExpression toBinExpression(HexExpression expression){
BinExpression binExp = new BinExpression();
for (String value : expression) {
char last = value.charAt(value.length()-1);
try {
long hex = Long.parseLong(value,16);
value = Long.toBinaryString(hex);
} catch (NumberFormatException ex){}
binExp.add(value);
}
return binExp;
}
public static Expression toDecExpression(HexExpression expression){
DecExpression decExp = new DecExpression();
for (String value : expression) {
char last = value.charAt(value.length()-1);
try {
long hex = Long.parseLong(value,16);
value = ""+hex;
} catch (NumberFormatException ex){}
decExp.add(value);
}
return decExp;
}
@Override
public String computation(String op1, String op2, String operator) {
switch(operator){
case "*":
return Long.toHexString(Long.parseLong(op1,16)*Long.parseLong(op2,16));
case "/":
return Long.toHexString(Long.parseLong(op1,16)/Long.parseLong(op2,16));
case "^":
return Long.toHexString((int) Math.pow(Long.parseLong(op1,16),Long.parseLong(op2,16)));
case "RADQ":
return Long.toHexString((int) Math.sqrt(Long.parseLong(op2,16)));
case "+":
return Long.toHexString(Long.parseLong(op1,16)+Long.parseLong(op2,16));
case "-":
return Long.toHexString(Long.parseLong(op1,16)-Long.parseLong(op2,16));
default:
return "";
}
}
}
|
package com.lubarov.daniel.data.util;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
public class DigestUtilsTest {
@Test
public void testMd5Hex() {
String hex = DigestUtils.md5Hex("daniel@lubarov.com".getBytes(StandardCharsets.US_ASCII));
assertEquals("dcfb9e0cd502e1a8948a7ca30da1469a", hex);
}
}
|
package uo.sdi.clients.rest.menu;
import java.util.List;
public interface MenuItem {
String getMenuName();
List<MenuItem> execute();
}
|
package pl.cwanix.opensun.agentserver.packets.c2s.status;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import pl.cwanix.opensun.agentserver.packets.AgentServerPacketOPCode;
import pl.cwanix.opensun.commonserver.packets.Packet;
import pl.cwanix.opensun.commonserver.packets.annotations.IncomingPacket;
import pl.cwanix.opensun.utils.datatypes.FixedLengthField;
@SuppressWarnings("checkstyle:MagicNumber")
@Slf4j
@Getter
@IncomingPacket(category = AgentServerPacketOPCode.Status.CATEGORY, operation = AgentServerPacketOPCode.Status.Ask.STAT_SELECT)
public class C2SAskStatSelectPacket implements Packet {
private final FixedLengthField attributeCode;
public C2SAskStatSelectPacket(final byte[] value) {
this.attributeCode = new FixedLengthField(1, value);
}
}
|
package com.tencent.mm.plugin.wallet_core.id_verify;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.tencent.mm.g.a.sz;
import com.tencent.mm.plugin.wallet_core.b.b;
import com.tencent.mm.plugin.wallet_core.model.o;
import com.tencent.mm.plugin.wallet_core.ui.WalletBankcardIdUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletCheckPwdUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletPwdConfirmUI;
import com.tencent.mm.plugin.wallet_core.ui.WalletSetPasswordUI;
import com.tencent.mm.plugin.wxpay.a$i;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.wallet_core.c;
import com.tencent.mm.wallet_core.c.p;
import com.tencent.mm.wallet_core.d.g;
import com.tencent.mm.wallet_core.d.i;
public class a extends b {
private int bjW = 0;
private boolean hxu = false;
private String mActivityName = null;
private int mMode;
private String pjT = null;
private boolean pjU = false;
private int pjV = -1;
public final c a(Activity activity, Bundle bundle) {
boolean z;
y(new Object[]{"start", activity, bundle});
if (this.jfZ == null) {
this.jfZ = new Bundle();
}
if (bundle == null) {
bundle = this.jfZ;
}
if (bundle != null) {
this.mMode = bundle.getInt("real_name_verify_mode", 0);
} else {
this.mMode = 0;
}
this.pjV = this.mMode;
bundle.putBoolean("key_is_realname_verify_process", true);
this.pjT = bundle.getString("realname_verify_process_jump_plugin", "");
this.mActivityName = bundle.getString("realname_verify_process_jump_activity", "");
if (bundle.getInt("realname_verify_process_allow_idverify", 0) == 1) {
z = true;
} else {
z = false;
}
this.pjU = z;
x.i("MicroMsg.RealNameVerifyProcess", "mAllowIdVerify is mAllowIdVerify: %s,mPluginName %s, mActivityName %s ", new Object[]{Boolean.valueOf(this.pjU), this.pjT, this.mActivityName});
switch (this.mMode) {
case 0:
p.GZ(10);
c(activity, SwitchRealnameVerifyModeUI.class, bundle);
break;
case 1:
bundle.putBoolean("key_need_bind_response", true);
p.GZ(10);
super.a(activity, bundle);
break;
case 2:
c(activity, WalletRealNameVerifyUI.class, bundle);
break;
}
return this;
}
public final void c(Activity activity, int i) {
y(new Object[]{"back", activity, Integer.valueOf(i)});
p.cDe();
if (activity instanceof SwitchRealnameVerifyModeUI) {
if (i == 0) {
b(activity, this.jfZ);
}
} else if ((activity instanceof WalletRealNameVerifyUI) || (activity instanceof WalletBankcardIdUI)) {
if (this.pjV != 0) {
b(activity, this.jfZ);
}
} else if (activity instanceof WalletCheckPwdUI) {
b(activity, this.jfZ);
}
if (activity instanceof WalletPwdConfirmUI) {
a(activity, WalletSetPasswordUI.class, i);
}
}
public final void a(Activity activity, int i, Bundle bundle) {
y(new Object[]{"forward", activity, "actionCode:" + i, bundle});
int i2 = this.jfZ.getInt("real_name_verify_mode", this.mMode);
if (this.mMode != i2) {
this.mMode = i2;
}
if (this.mMode == 2) {
if (activity instanceof WalletRealNameVerifyUI) {
c(activity, WalletSetPasswordUI.class, bundle);
} else if (activity instanceof WalletSetPasswordUI) {
c(activity, WalletPwdConfirmUI.class, bundle);
} else if (!(activity instanceof WalletPwdConfirmUI) && (activity instanceof SwitchRealnameVerifyModeUI)) {
c(activity, WalletRealNameVerifyUI.class, bundle);
this.mMode = 2;
}
} else if (this.mMode == 1) {
if (activity instanceof SwitchRealnameVerifyModeUI) {
if (o.bOW().bPs()) {
c(activity, WalletCheckPwdUI.class, bundle);
} else {
c(activity, WalletBankcardIdUI.class, bundle);
}
} else if (activity instanceof WalletCheckPwdUI) {
c(activity, WalletBankcardIdUI.class, bundle);
} else {
super.a(activity, i, bundle);
}
} else if (activity instanceof WalletRealNameVerifyUI) {
c(activity, WalletBankcardIdUI.class, bundle);
this.mMode = 1;
} else {
super.a(activity, i, bundle);
}
}
public final void b(Activity activity, Bundle bundle) {
Bundle bundle2;
y(new Object[]{"end", activity, bundle});
p.cDe();
if (bundle == null) {
bundle2 = this.jfZ;
} else {
bundle2 = bundle;
}
if (bundle2 == null) {
bundle2 = new Bundle();
}
if (this.mMode == 1) {
cCV();
if (bundle2.getBoolean("intent_bind_end", false)) {
this.bjW = -1;
} else {
this.bjW = 0;
}
} else if (bundle2.containsKey("realname_verify_process_ret")) {
this.bjW = bundle2.getInt("realname_verify_process_ret", -1);
} else {
this.bjW = 0;
}
if (bundle2.containsKey("intent_bind_end")) {
bundle2.remove("intent_bind_end");
}
if (bundle2.containsKey("key_is_bind_reg_process")) {
bundle2.remove("key_is_bind_reg_process");
}
bundle2.putInt("realname_verify_process_ret", this.bjW);
Intent intent = new Intent();
intent.putExtras(bundle2);
if (this.bjW == -1) {
Toast.makeText(activity, activity.getString(a$i.realname_verify_succ), 0).show();
}
sz szVar = new sz();
if (this.bjW == -1) {
szVar.cdR.scene = 17;
} else if (this.bjW == 0) {
szVar.cdR.scene = 18;
} else {
szVar.cdR.scene = 0;
}
szVar.bJX = new 1(this, szVar, intent, activity);
szVar.bJX.run();
}
public final g a(MMActivity mMActivity, i iVar) {
if (!(mMActivity instanceof WalletPwdConfirmUI)) {
return mMActivity instanceof WalletRealNameVerifyUI ? new 3(this, mMActivity, iVar) : super.a(mMActivity, iVar);
} else {
if (this.mMode == 2) {
return new 2(this, mMActivity, iVar);
}
return super.a(mMActivity, iVar);
}
}
public final String aNK() {
return "realname_verify_process";
}
public final int a(MMActivity mMActivity, int i) {
return a$i.wallet_input_realname_finish_confirm;
}
}
|
package banking.services;
import framework.services.Message;
public class NotificationMessage implements Message {
String forr;
String from;
String msg;
String subject;
public NotificationMessage(String msg, String subject, String from, String forr) {
this.msg = msg;
this.subject = subject;
this.from = from;
this.forr = forr;
}
/* (non-Javadoc)
* @see service.Message#getMsg()
*/
@Override
public String getMsg() {
return msg;
}
/* (non-Javadoc)
* @see service.Message#getSubject()
*/
@Override
public String getSubject() {
return subject;
}
/* (non-Javadoc)
* @see service.Message#getFrom()
*/
@Override
public String getFrom() {
return from;
}
/* (non-Javadoc)
* @see service.Message#getForr()
*/
@Override
public String getForr() {
return forr;
}
@Override
public String toString() {
return "NotificationMessage [for=" + forr + ", from=" + from + ", msg=" + msg + ", subject=" + subject + "]";
}
}
|
package com.project.dropeditions.dao;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.project.dropeditions.entities.AppUser;
@Repository
public interface UserDao extends JpaRepository<AppUser, Long>{
public Optional<AppUser> findByEmail(String email);
}
|
package util;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* 字符串工具类
*
* @author Only You
* @version 1.0
* @date 2016年1月6日
*/
public class StringUtil {
public static final String EMPTY = "";
/**
* 判断字符串是否为空
*
* @param str
* @return true 不为空, false 为空
*/
public static boolean isNotEmpty(String str) {
return str != null && !"null".equals(str) && str.trim().length() != 0;
}
/**
* 是否要显示金额
*
* @param str
* @return
*/
public static boolean isShowMoney(String str) {
return str != null && !"null".equals(str) && str.trim().length() != 0 && !str.equals("0");
}
public static boolean isShowMoney(double str) {
return str != 0;
}
/**
* 判断字符串是否为空
*
* @param str
* @return true 为空,false 不为空
*/
public static boolean isEmpty(String str) {
return str == null || "null".equals(str) || str.trim().length() == 0;
}
public static final SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm", Locale.CHINA);
public static String getCurrentTime() {
return dateformat.format(new Date());
}
public static final SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
public static String formatDateTime(long millseconds) {
return sdformat.format(new Date(millseconds));
}
public static String getCurrentDateTime() {
return sdformat.format(new Date());
}
/**
* 判断集合是否为空
*/
public static <T> boolean isCollectionsNotEmpty(Collection<T> collection) {
return collection != null && collection.size() > 0;
}
/**
* 判断MAP是否为空
*/
public static <K, V> boolean isMapNotEmpty(Map<K, V> map) {
return map != null && map.size() > 0;
}
/**
* 判断List是否为空
*/
public static boolean isListEmpty(List<?> array) {
return array != null && array.size() == 0;
}
/**
* 判断JSON数组是否为空
*/
public static boolean isJSONArrayEmpty(JSONArray array) {
return array == null || array.length() == 0;
}
public static boolean isObjectNull(Object object) {
if (object != null && object.getClass().isArray()) {
// 如果是数组类型
throw new UnsupportedOperationException("isObjectNotNull not supported operation :" + object);
}
return object == null;
}
public static boolean isObjectNotNull(Object object) {
if (object != null && object.getClass().isArray()) {
// 如果是数组类型
throw new UnsupportedOperationException("isObjectNotNull not supported operation :" + object);
}
return object != null;
}
/**
* 判断JSON数据不空为
*/
public static boolean isJSONArrayNotEmpty(JSONArray array) {
return array != null && array.length() > 0;
}
/**
* 判断JSON数组是否为空
*/
public static boolean isJSONObjectEmpty(JSONObject object) {
return object == null || object.length() == 0;
}
/**
* 判断JSON数据不空为
*/
public static boolean isJSONObjectNotEmpty(JSONObject object) {
return object != null && object.length() > 0;
}
public static boolean isIntArrayNotEmpty(int[] array) {
return array != null && array.length > 0;
}
/**
* 判断List数据不空为
*/
public static boolean isListNotEmpty(List<?> array) {
return array != null && array.size() > 0;
}
/**
* 判断long数组不为空
*
* @param array
* @return
*/
public static boolean isLongArrayNotEmpty(long[] array) {
return array != null && array.length > 0;
}
/**
* 判断float数组不为空
*
* @param array
* @return
*/
public static boolean isFloatArrayNotEmpty(float[] array) {
return array != null && array.length > 0;
}
/**
* 判断double数组不为空
*
* @param array
* @return
*/
public static boolean isDoubleArrayNotEmpty(double[] array) {
return array != null && array.length > 0;
}
public static boolean isNotBlank(String str) {
return (str != null) && (str.length() != 0);
}
public static boolean isBlank(String str) {
return (str == null) || (str.length() == 0);
}
public static boolean isNotTrimBlank(String str) {
return (str != null) && (str.trim().length() != 0);
}
public static boolean isTrimBlank(String str) {
return (str == null) || (str.trim().length() == 0);
}
/**
* 判断是否为网址
*
* @param urlString url
* @return
*/
public static boolean isHttpUrl(String urlString) {
if (isEmpty(urlString)) {
return false;
}
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile(regex);
Matcher matcher = patt.matcher(urlString);
return matcher.matches();
}
/**
* 判断是否为淘口令
*
* @param result
* @return
*/
public static boolean isPromoterId(String result) {
if (isEmpty(result)) {
return false;
}
String regex = "^[0-9A-Z]{8}$";
Pattern httpPattern = Pattern.compile(regex);
if (httpPattern.matcher(result).matches()) {
return true;
} else {
return false;
}
}
/**
* 判断是否是身份证
*
* @param idNo
* @return
*/
public static boolean isIdNo(String idNo) {
if (isTrimBlank(idNo)) {
return false;
}
Pattern p = Pattern.compile("^([1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3})|([1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[X,x]))$");
Matcher matcher = p.matcher(idNo);
return matcher.find();
}
/**
* 判断是否为手机号
*
* @param mobile
* @return
*/
private boolean isMobileNo(String mobile) {
Pattern pattern = Pattern
.compile("^((1[358][0-9])|(14[57])|(17[0678]))\\d{8}$");
Matcher matcher = pattern.matcher(mobile);
return matcher.matches();
}
/**
* 判断是否为邮箱号
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
if (isTrimBlank(email)) {
return false;
}
String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* 在HTML特殊字符的处理
*
* @param source
* @return
*/
public static String htmlEscapeCharsToString(String source) {
return StringUtil.isEmpty(source) ? source : source.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("&", "&")
.replaceAll(""", "\"")
.replaceAll("©", "©")
.replaceAll("¥", "¥")
.replaceAll("÷", "÷")
.replaceAll("×", "×")
.replaceAll("®", "?")
.replaceAll("§", "§")
.replaceAll("£", "£")
.replaceAll("¢", "¢");
}
/**
* 验证用户名是否合法
*
* @param id
* @return
*/
public static boolean isNotUserName(String id) {
if (isTrimBlank(id)) {
return false;
}
// 字母开头,由字母,数字和下划线组成的长度为2到16的字符串
Pattern p = Pattern.compile("^[a-zA-Z0-9_-]{2,16}$");
Matcher m = p.matcher(id);
return !m.find();
}
/**
* 判断是否为密码
*
* @param password
* @return
*/
public static boolean isNotPassWord(String password) {
if (isTrimBlank(password)) {
return false;
}
// 就是以大小写字母开头,由大小写字母,数字和下划线组成的长度为6到18的字符串
Pattern p = Pattern.compile("^[a-zA-Z0-9_]{6,18}$");
Matcher m = p.matcher(password);
return !m.find();
}
/**
* 判断银行卡号是否合法
*
* @param bankCard
* @return
*/
public static boolean isNotBank(String bankCard) {
if (isTrimBlank(bankCard)) {
return false;
}
// 一共16或19位,都是数字。
Pattern p = Pattern.compile("^\\d{16}$|^\\d{19}$");
Matcher m = p.matcher(bankCard);
return !m.find();
}
/**
* 只允许字母、数字和汉字
*
* @param str
* @return
*/
public static boolean isStringFilter(String str) {
if (isTrimBlank(str)) {
return false;
}
Pattern p = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5]");
Matcher m = p.matcher(str);
return !m.find();
}
/**
* @param context
* @param resId
* @param str
* @return
*/
public static String isStringFormat(Context context, int resId, String str) {
return String.format(context.getResources().getString(resId), str);
}
/**
* 从Raw文件中读取
*
* @param context
* @param resId
* @return
*/
public static String getFromRaw(Context context, int resId) {
try {
InputStreamReader inputReader = new InputStreamReader(context.getResources().openRawResource(resId));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Result = "";
while ((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 直接从assets读取
public static String getFromAssets(Context context, String fileName) {
try {
InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Result = "";
while ((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将字符串转换成大写
*
* @param s
* @return
*/
public static String toUpperCase(String s) {
return s.toUpperCase(Locale.getDefault());
}
/**
* 判断当前应用程序处于前台还是后台
*/
public static boolean isApplicationBroughtToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
/*
* 若真实姓名为 张三
* 则返回 **三
*/
public static String realName(String realName) {
if (realName == null) return null;
char[] charArray = realName.toCharArray();
String x = "";
for (int i = 0; i < charArray.length - 1; i++) {
x += "*";
}
return charArray[0] + x;
}
/**
* 将字节自动转换为KB 或M
*
* @param byteLength 字节长度
* @return
*/
public static String byteChange(double byteLength) {
String str = "";
double kb = byteLength / 1024;//转换为KB
double m = kb / 1024;//转换为M
if (m < 1) {
//保留两位小数,并四色五入
BigDecimal b = new BigDecimal(kb);
kb = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
str = kb + "KB";
} else {
BigDecimal b = new BigDecimal(m);
m = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
str = m + "M";
}
return str;
}
/**
* 保留两位小数
*
* @param number
* @return
*/
public static String saveFloatTwo(float number) {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(number);
}
public static String saveFloatTwo(double number) {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(number);
}
/**
* @param number
* @return
*/
public static String saveFloatTwo(String number) {
try {
double money = Double.parseDouble(number);
DecimalFormat df = new DecimalFormat("0.00");
return df.format(money);
} catch (Exception e) {
return "0.00";
}
}
/**
* @param number
* @return
*/
public static String saveLevelPrice(String number) {
try {
double m = Double.parseDouble(number);
if (number.contains(".0")) {
int index = number.lastIndexOf(".");
String price = number.substring(0, index);
return price;
} else if (m <= 1) {
double money = Double.parseDouble(number);
DecimalFormat df = new DecimalFormat("0.0");
return df.format(money);
}
double money = Double.parseDouble(number);
DecimalFormat df = new DecimalFormat("0.00");
return df.format(money);
} catch (Exception e) {
return "0.00";
}
}
public static String subTimeDay(String time) {
if (StringUtil.isEmpty(time))
return "";
else {
if (time.length() >= 10)
return time.substring(0, 10);
else return time;
}
}
/**
* 是否是车牌
*
* @param value
* @return
*/
public static boolean matcherVehicleNumber(String value) {
String regex = "^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新渝]?[A-Z][A-HJ-NP-Z0-9学挂港澳练]{5}$";
return testRegex(regex, value.toUpperCase());
}
private static boolean testRegex(String regex, String inputValue) {
return Pattern.compile(regex).matcher(inputValue).matches();
}
/**
* 是否是车架号
*
* @param param
* @return
*/
public static boolean isIdentificationCode(String param) {
if (param.toUpperCase().matches("^[A-Z0-9]{6,17}$")) {
return true;
}
return false;
}
/**
* 是否为发动机号
*
* @param param
* @return
*/
public static boolean isVehicleEngineNo(String param) {
if (param.toUpperCase().matches("^[A-Z0-9]+$")) {
return true;
}
return false;
}
/**
* 该方法主要使用正则表达式来判断字符串中是否包含字母
*
* @param cardNum 待检验的原始卡号
* @return 返回是否包含
* @author fenggaopan 2015年7月21日 上午9:49:40
*/
public static boolean judgeContainsStr(String cardNum) {
String regex = ".*[a-zA-Z]+.*";
Matcher m = Pattern.compile(regex).matcher(cardNum);
return m.matches();
}
/**
* 定义script的正则表达式
*/
private static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>";
/**
* 定义style的正则表达式
*/
private static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>";
/**
* 定义HTML标签的正则表达式
*/
private static final String REGEX_HTML = "<[^>]+>";
/**
* 定义空格回车换行符
*/
private static final String REGEX_SPACE = "\\s*|\t|\r|\n";
/**
* 定义空格回车换行符
*
* @param htmlStr
* @return
*/
public static String delHTMLTag(String htmlStr) {
// 过滤script标签
Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll("");
// 过滤style标签
Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll("");
// 过滤html标签
Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll("");
// 过滤空格回车标签
Pattern p_space = Pattern.compile(REGEX_SPACE, Pattern.CASE_INSENSITIVE);
Matcher m_space = p_space.matcher(htmlStr);
htmlStr = m_space.replaceAll("");
return htmlStr.trim(); // 返回文本字符串
}
/**
* 判断电话号码长度是否为11位
*
* @param phone
* @return
*/
public static boolean isPhone(String phone) {
if (phone.length() == 11) {
return true;
} else {
return false;
}
}
/**
* 转换成待空格的电话号码
*
* @param text
* @return
*/
public static String replaceForPhone(String text) {
String newStr = text.replace(" ", "");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newStr.length(); i += 4) {
if (i == 0) {
sb.append(newStr.length() > 3 ? newStr.substring(0, 3) : newStr);
i += 3;
continue;
} else if (i > 0) {
sb.append(" ");
if (i + 4 <= newStr.length()) {
sb.append(newStr.substring(i, i + 4));
} else {
sb.append(newStr.substring(i, newStr.length()));
}
}
}
return sb.toString();
}
/**
* 转换成待分隔的卡号
*
* @param text
* @return
*/
public static String replaceForCardNo(String text) {
String newStr = text.replace(" ", "");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newStr.length(); i += 4) {
if (i > 0) {
sb.append(" ");
}
if (i + 4 <= newStr.length()) {
sb.append(newStr.substring(i, i + 4));
} else {
sb.append(newStr.substring(i, newStr.length()));
}
}
return sb.toString();
}
/**
* 验证URL地址
*
* @param url
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkURL(String url) {
String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?";
return Pattern.matches(regex, url);
}
/**
* 是否有汉字
*
* @param ChineseCharactersStr
* @return
*/
public static boolean isContainsChinese(String ChineseCharactersStr) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(ChineseCharactersStr);
if (m.find())
return true;
else
return false;
}
/**
* 获取利用反射获取类里面的值和名称
*
* @param obj
* @return
* @throws IllegalAccessException
*/
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
try {
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return map;
}
/**
* 截取字符串str中指定字符 strStart、strEnd之间的字符串
*
* @param str
* @param strStart
* @param strEnd
* @return
*/
public static String subString(String str, String strStart, String strEnd) {
/* 找出指定的2个字符在 该字符串里面的 位置 */
int strStartIndex = str.indexOf(strStart);
int strEndIndex = str.indexOf(strEnd);
/* index 为负数 即表示该字符串中 没有该字符 */
if (strStartIndex < 0) {
// "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
return "";
}
if (strEndIndex < 0) {
// "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
return "";
}
/* 开始截取 */
String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
return result;
}
public static <T> boolean notEmpty(List<T> list) {
return !isEmpty(list);
}
public static <T> boolean isEmpty(List<T> list) {
if (list == null || list.size() == 0) {
return true;
}
return false;
}
public static String toWhat(int what) {
//A0001
int length = String.valueOf(what).length();
StringBuilder sb = new StringBuilder();
sb.append("A");
for (int i = 0; i < 4 - length; i++) {
sb.append("0");
}
sb.append(what);
String result = "==========" + sb.toString() + "==========";
return result;
}
/**
* 替换、过滤特殊字符
*
* @param str
* @return
* @throws
*/
public static String StringFilter(String str) {
str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("!", "!");//替换中文标号
String regEx = "[『』]"; // 清除掉特殊字符
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
} |
package org.pismofinal.cma.tests;
import java.io.File;
import org.junit.Test;
import org.pismofinal.cma.files.XMLValidator;
public class Tests {
@Test
public void testXMLValidator() {
String schemaURI = null;
XMLValidator val = new XMLValidator(schemaURI);
File schemaFile = null;
XMLValidator val2 = new XMLValidator(schemaFile);
}
}
|
package xyz.kjh.pp.service.model.req;
import java.util.Locale;
import xyz.kjh.pp.BuildConfig;
import xyz.kjh.pp.service.Server;
/**
* Created by juniverse on 24/03/2017.
*/
public class JoinParams extends Server.ReqParams
{
public String clientVersionCode = BuildConfig.VERSION_NAME; // 클라이언트 버전(형식없음)
public int platform_type; // 플랫폼 타입(1:페이스북,2:GUEST,3:GameCenter(IOS),4:GooglePlus(AOS),99:구분 불가능)
public String platform_id; // 아이디
public String push_token; // 푸시 토큰
public int push_type; // push 수신 여부 (0:전체거부(항상), 1:야간만 허용, 2:주간만 허용, 3:수신허용(항상))
public int sms_type; // SMS 수신 여부 (0:전체거부(항상), 1:야간만 허용, 2:주간만 허용, 3:수신허용(항상))
public int join_os_type = Server.OS_TYPE_ANDRIOD;
public String join_country; // 국가코드(형식없음)
public int join_market_type = Server.MARKET_TYPE_ANDROID_PLAY_STORE;
public String phone_number; // 전화번호
public int age; // 나이대(0:비밀, 10:10대, 20:20대 ...)
public int status; // 0:비밀, 1:진보, 2:보수
public int party; // 정당(0:비밀, 1:민주당, 2:새누리, 3.국민의당, 4:바른정당, 5:정의당', 6:기타)
public int sex; // 남여구분(0:비밀, 1:남, 2:여)
public JoinParams()
{
join_country = Locale.getDefault().getCountry();
}
}
|
package mod.server.forgeservermod;
import java.util.UUID;
import com.mojang.authlib.GameProfile;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
public class EntityHuman extends PlayerEntity {
public EntityHuman(World world, String name) {
super(world, new GameProfile(UUID.randomUUID(), name));
// TODO Auto-generated constructor stub
}
@Override
public boolean isSpectator() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isCreative() {
// TODO Auto-generated method stub
return false;
}
}
|
package com.mingchu.positiondetaidemo.attention;
import java.io.Serializable;
/**
* 评论
*/
public class Comment implements Serializable {
private String commentuser; //发布评论人员名字
private String byreviewsuser;//被评论人员名字
private String content;//评论内容
public String getCommentuser() {
return commentuser;
}
public void setCommentuser(String commentuser) {
this.commentuser = commentuser;
}
public String getByreviewsuser() {
return byreviewsuser;
}
public void setByreviewsuser(String byreviewsuser) {
this.byreviewsuser = byreviewsuser;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
package com.pay.beans;
import com.pay.beans.rules.entity.ConvertNameBean;
import com.pay.beans.rules.entity.ConvertTypeBean;
import com.pay.beans.rules.FormatRule;
import com.pay.beans.rules.regulations.ConvertRegulations;
import com.pay.beans.test.UserBean;
import com.pay.beans.test.UserDtm;
import com.pay.beans.test.UserStatusDict;
import com.pay.pojo.entity.dtm.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestBeanUtils {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void testConvertSource2TargetByTypeWithOneRule(){
UserBean source = createUserBean();
UserDtm target = new UserDtm();
FormatRule dateRule = FormatRule.formatDateRule("yyyy年MM月dd日HH时mm分ss秒:SSS");
ConvertTypeBean bean = new ConvertTypeBean(Double.class,dateRule);
BeanUtils.copyBeanWithRuleByType(source,target,bean);
sayUserDtm(target);
}
@Test
public void testConvertSource2TargetByTypeWithRuleList(){
UserBean source = createUserBean();
UserDtm target = new UserDtm();
List<ConvertTypeBean> beanList = ConvertRegulations.MODEL_TO_DATA_MODEL_REGULATION;
BeanUtils.copyBeanWithRuleByType(source,target,beanList);
sayUserDtm(target);
}
@Test
public void testConvertSource2TargetByNameWithOneRule(){
UserDtm source = createUserDtm();
UserBean target = new UserBean();
FormatRule salaryRule = FormatRule.convertToDouble("#,###.####");
ConvertNameBean bean = new ConvertNameBean("salary",salaryRule);
BeanUtils.copyBeanWithRuleByName(source,target,bean);
sayUserBean(target);
}
@Test
public void testConvertSource2TargetByNameWithRuleList(){
UserDtm source = createUserDtm();
UserBean target = new UserBean();
List<ConvertNameBean> beanList = ConvertRegulations.VALUE_TO_MODEL_REGULATION;
BeanUtils.copyBeanWithRuleByName(source,target,beanList);
}
@Test
public void testConvertEnumToValue(){
UserBean source = createUserBean();
UserDtm target= new UserDtm();
// for(int i=0;i<100000;i++){
// BeanUtils.copyBeanBase(source,target);
// }
BeanUtils.copyBeanBase(source,target);
sayUserDtm(target);
}
@Test
public void testConvertValueToEnum(){
UserDtm source = createUserDtm();
UserBean target = new UserBean();
for(int i=0;i<100000;i++){
BeanUtils.copyBeanBase(source,target);
}
sayUserBean(target);
}
private UserBean createUserBean(){
UserBean userBean = new UserBean();
userBean.setPassword("1234");
userBean.setPhone("123456789");
userBean.setUserName("testAdmin");
userBean.setUserId(12345);
userBean.setBirthday(new Date());
userBean.setSalary(1233123.0);
userBean.setUserStatusDict(UserStatusDict.off);
List<User> list = new ArrayList<>();
User user = new User();
user.setUserId(1);
user.setPassword("1111");
user.setPhone("2222");
user.setUserName("3333");
list.add(user);
user = new User();
user.setUserId(2);
user.setPassword("4444");
user.setPhone("5555");
user.setUserName("6666");
list.add(user);
userBean.setUserList(list);
return userBean;
}
private UserDtm createUserDtm(){
UserDtm userDtm = new UserDtm();
userDtm.setPassword("1234");
userDtm.setPhone("123456789");
userDtm.setUserName("testAdmin");
userDtm.setUserId(12345);
userDtm.setBirthday("2013年06月12日07时28分33秒");
userDtm.setSalary("22,312,333.9812");
userDtm.setUserStatusDict("200");
List<User> list = new ArrayList<>();
User user = new User();
user.setUserId(1);
user.setPassword("1111");
user.setPhone("2222");
user.setUserName("3333");
list.add(user);
user = new User();
user.setUserId(2);
user.setPassword("4444");
user.setPhone("5555");
user.setUserName("6666");
list.add(user);
userDtm.setUserList(list);
return userDtm;
}
private void sayUserBean(UserBean userBean){
System.out.println(userBean.getPassword());
System.out.println(userBean.getPhone());
System.out.println(userBean.getUserName());
System.out.println(userBean.getUserId());
System.out.println(userBean.getBirthday());
System.out.println(userBean.getSalary());
System.out.println(userBean.getUserList().size());
System.out.println(userBean.getUserList().get(1).getUserName());
System.out.println(userBean.getUserStatusDict());
}
private void sayUserDtm(UserDtm userDtm){
System.out.println(userDtm.getPassword());
System.out.println(userDtm.getPhone());
System.out.println(userDtm.getUserName());
System.out.println(userDtm.getUserId());
System.out.println(userDtm.getBirthday());
System.out.println(userDtm.getSalary());
System.out.println(userDtm.getUserList().size());
System.out.println(userDtm.getUserList().get(1).getUserName());
System.out.println("userStatusDict:" + userDtm.getUserStatusDict());
}
}
|
/*
* 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 pe.gob.onpe.adan.dao.adan.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import pe.gob.onpe.adan.dao.adan.ReglaDao;
import pe.gob.onpe.adan.model.adan.Regla;
/**
*
* @author AQuispec
*/
@Repository("reglaDao")
public class ReglaDaoImpl extends AbstractDao<Integer, Regla> implements ReglaDao{
@Override
public List<Regla> finAllRegla() {
List<Regla> lst = getEntityManager()
.createQuery("SELECT R FROM Regla R")
.getResultList();
return lst;
}
}
|
package com.level01.제일작은수제거하기;
import java.util.*;
public class MTest {
public static void main(String[] args) {
int[] arr = {4, 3, 2, 1};
Solution solution = new Solution();
System.out.println(solution.solution(arr));
}
}
class Solution {
public int[] solution(int[] arr) {
int[] answer = new int [arr.length - 1];
int[] tmp = arr.clone();
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(tmp);
for(int i = 0; i < arr.length; i++){
if(arr[i] != tmp[0]){
list.add(arr[i]);
}
}
for(int i = 0; i < list.size(); i++){
answer[i] = list.get(i);
}
// 처음으로 주어진 배열의 길이가 1이면 무조건 -1 리턴
if(answer.length == 0){
answer = new int [1];
answer[0] = -1;
}
return answer;
}
} |
package test.nz.org.take.compiler.scenario13.generated;
/**
* Class generated by the take compiler.
* This class represents the predicate hasCategory
* @version Mon Feb 18 10:34:07 CET 2008
*/
public class HasCategory {
public test.nz.org.take.compiler.scenario13.Bean bean;
public java.lang.String name;
public HasCategory(test.nz.org.take.compiler.scenario13.Bean bean,
java.lang.String name) {
super();
this.bean = bean;
this.name = name;
}
public HasCategory() {
super();
}
}
|
package com.stackroute.activitystream.UserService.controller;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.stackroute.activitystream.servicesbackend.dao.UserDao;
import com.stackroute.activitystream.servicesbackend.model.User;
@RestController
@CrossOrigin(origins="http://localhost:4200")
public class UserController {
@Autowired
private UserDao userDao;
/*@RequestMapping(value="/",method = RequestMethod.GET)
public ResponseEntity<List<User>> getWelcome() {
List<User> users=userDao.getUsers();
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}*/
@GetMapping("/")
String hello() {
return "hello world";
}
@RequestMapping(value="/alluser",method = RequestMethod.GET)
public ResponseEntity<List<User>> getUsers() {
List<User> users=userDao.getUsers();
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
@RequestMapping(value="/signup",method= RequestMethod.POST)
public ResponseEntity<String> registerUser(@RequestBody User user){
if(userDao.registerUser(user))
{
return new ResponseEntity<String>("registered successfully!!..",HttpStatus.CREATED);
}
return new ResponseEntity<String>("mailid registered already,pls use new mailid",HttpStatus.NOT_ACCEPTABLE);
}
@RequestMapping(value="/signin",method= RequestMethod.POST)
public ResponseEntity<String> loginUser(@RequestBody User user){
//send email id and password to dao. it should return true or false
if(userDao.validateUser(user.getEmailId(), user.getUserPass()))
{
return new ResponseEntity<String>("welcome!!! ",HttpStatus.CREATED);
}
return new ResponseEntity<String>("oops wrong mailid or password...",HttpStatus.NOT_FOUND);
}
/*@RequestMapping(value="/admin/signin",method= RequestMethod.POST)
public ResponseEntity<String> loginUserAdmin(@RequestBody User user){
//send email id and password to dao. it should return true or false
if(userDao.validateUser(user.getEmailId(), user.getUserPass()))
{
return new ResponseEntity<String>("welcome!!! ",HttpStatus.CREATED);
}
return new ResponseEntity<String>("oops wrong mailid or password...",HttpStatus.NOT_FOUND);
}*/
@RequestMapping(value="/updateUser",method= RequestMethod.PUT)
public ResponseEntity<String> updateUser(@RequestBody User user){
if(userDao.updateUser(user)){
return new ResponseEntity<String>("updated successfully...",HttpStatus.OK);
}
return new ResponseEntity<String>("oops email id is not registerd...",HttpStatus.NOT_FOUND);
}
@DeleteMapping(value="/deleteUser/{id}")
public ResponseEntity<String> deleteUser(@PathVariable("id") String id){
if(userDao.deleteUser(id)){
return new ResponseEntity<String>("deleted successfully,,,",HttpStatus.OK);
}
return new ResponseEntity<String>("oops email id is not registerd...",HttpStatus.NOT_FOUND);
}
@RequestMapping(value="/userBy/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Resource<User> userById(@PathVariable("id") String mailId){
User user=userDao.getUserbyId(mailId);
Resource<User> userResource=new Resource<>(user);
userResource.add(linkTo(methodOn(UserController.class).allUser()).withRel("users"));
return userResource;
}
@RequestMapping(value="/users")
public List<Resource<User>> allUser(){
List<User> users=userDao.getUsers();
List<Resource<User>> userResources=new ArrayList<Resource<User>>();
for(User user:users){
userResources.add(getUserResource(user));
}
return userResources;
}
private Resource<User> getUserResource(User user){
Resource<User> userResource=new Resource<User>(user);
userResource.add(linkTo(methodOn(UserController.class).userById(user.getEmailId())).withSelfRel());
return userResource;
}
}
|
package se.gareth.swm;
public class WobbleBehavior extends Behavior {
private static final String TAG = WobbleBehavior.class.getName();
private long mRange;
private long mFrameCnt;
private final Vector2D mForce;
private long mChangeDirectionTime;
public WobbleBehavior(GameBase gameBase, double direction, double speed, long range) {
super(gameBase);
mRange = range;
mForce = new Vector2D();
mForce.setDirectionMagnitude(direction, speed);
}
@Override
public void wasAdded(ActiveObject activeObject) {
mChangeDirectionTime = System.currentTimeMillis() + (mRange / 2);
SLog.d(TAG, "Added wobble behavior to " + activeObject);
}
@Override
public void update(ActiveObject activeObject, final TimeStep timeStep) {
activeObject.addPosition(mForce.getX() * 0.016,
mForce.getY() * 0.016);
mFrameCnt ++;
if (mFrameCnt > mRange) {
mFrameCnt = 0;
mForce.invert();
mChangeDirectionTime = System.currentTimeMillis() + mRange;
SLog.d(TAG, "Force now " + mForce);
}
}
}
|
package com.ashoksm.thiraseela.dto;
public class AcademyListDTO {
/**
* id.
*/
private Integer id;
/**
* name.
*/
private String name;
/**
* place.
*/
private String place;
/**
* name.
*/
private String city;
/**
* @return the id
*/
public final Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public final void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public final String getName() {
return name;
}
/**
* @param name the name to set
*/
public final void setName(String name) {
this.name = name;
}
/**
* @return the place
*/
public final String getPlace() {
return place;
}
/**
* @param place the place to set
*/
public final void setPlace(String place) {
this.place = place;
}
/**
* @return the city
*/
public final String getCity() {
return city;
}
/**
* @param city the city to set
*/
public final void setCity(String city) {
this.city = city;
}
}
|
package elaundry.service;
import elaundry.domain.Customer;
import elaundry.domain.User;
public interface UserService {
public User login(User user);
public User checkUserName(String username);
}
|
//package Tests.day1;
//
//import Tests.AbstractTest;
//import day1.Task1;
//import day1.Task2;
//import day1.Task3;
//import day1.Task4;
//import day1.Task5;
//import org.junit.jupiter.api.Test;
//
//import static org.junit.jupiter.api.Assertions.assertEquals;
//
//public class Day1Test extends AbstractTest {
//
// @Test
// public void Task1() {
// final String resultString = "JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA ";
// Task1.main(new String[0]);
// assertEquals(resultString, getOutput(), "Количество повторений слова \"JAVA\", в строке, не равно десяти");
// }
//
// @Test
// public void Task2() {
// final String resultString = "JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA JAVA ";
// Task2.main(new String[0]);
// assertEquals(resultString, getOutput(), "Количество повторений слова \"JAVA\", в строке, не равно десяти");
// }
//
// @Test
// public void Task3() {
// final String resultString = "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator() +
// "JAVA" + System.lineSeparator();
// Task3.main(new String[0]);
// assertEquals(resultString, getOutput(), "Количество повторений слова \"JAVA\" не равно десяти строкам");
// }
//
// @Test
// public void Task4() {
// final String resultString =
// "Олимпиада 1980 года" + System.lineSeparator() +
// "Олимпиада 1984 года" + System.lineSeparator() +
// "Олимпиада 1988 года" + System.lineSeparator() +
// "Олимпиада 1992 года" + System.lineSeparator() +
// "Олимпиада 1996 года" + System.lineSeparator() +
// "Олимпиада 2000 года" + System.lineSeparator() +
// "Олимпиада 2004 года" + System.lineSeparator() +
// "Олимпиада 2008 года" + System.lineSeparator() +
// "Олимпиада 2012 года" + System.lineSeparator() +
// "Олимпиада 2016 года" + System.lineSeparator() +
// "Олимпиада 2020 года" + System.lineSeparator();
// Task4.main(new String[0]);
// assertEquals(resultString, getOutput(), "Не верное количество строк со словом JAVA");
// }
//
// @Test
// public void Task5() {
// final String resultString =
// "Олимпиада 1980 года" + System.lineSeparator() +
// "Олимпиада 1984 года" + System.lineSeparator() +
// "Олимпиада 1988 года" + System.lineSeparator() +
// "Олимпиада 1992 года" + System.lineSeparator() +
// "Олимпиада 1996 года" + System.lineSeparator() +
// "Олимпиада 2000 года" + System.lineSeparator() +
// "Олимпиада 2004 года" + System.lineSeparator() +
// "Олимпиада 2008 года" + System.lineSeparator() +
// "Олимпиада 2012 года" + System.lineSeparator() +
// "Олимпиада 2016 года" + System.lineSeparator() +
// "Олимпиада 2020 года" + System.lineSeparator();
// Task5.main(new String[0]);
// assertEquals(resultString, getOutput(), "Не верное количество строк со словом JAVA");
// }
//
//}
|
package uk.gov.hmcts.befta.data;
import java.util.Map;
import lombok.Data;
import uk.gov.hmcts.befta.util.JsonUtils;
@Data
public class RequestData {
private Map<String, Object> headers;
private Map<String, Object> pathVariables;
private Map<String, Object> queryParams;
private Map<String, Object> body;
public boolean isMultipart() {
return headers != null && headers.get("Content-Type") != null
&& headers.get("Content-Type").toString().toLowerCase().contains("multipart");
}
public RequestData() {
}
@SuppressWarnings("unchecked")
public RequestData(RequestData other) {
setHeaders((Map<String, Object>) JsonUtils.deepCopy(other.getHeaders()));
setPathVariables((Map<String, Object>) JsonUtils.deepCopy(other.getPathVariables()));
setQueryParams((Map<String, Object>) JsonUtils.deepCopy(other.getQueryParams()));
setBody((Map<String, Object>) JsonUtils.deepCopy(other.getBody()));
}
}
|
class car1{
private String brand, owner, company;
private int price;
public car1(String brand, String owner, String company, int price){
this.brand = brand;
this.owner=owner;
this.company = company;
this.price = price;
}
public car1(String owner, String company, int price){
this.owner=owner;
this.company = company;
this.price = price;
}
public car1(String owner, int price){
this.owner=owner;
this.price = price;
}
public String start(String time){
return time;
}
public String stop(String time){
return time;
}
public static void main(String ar[]){
car1 c1 = new car1("Sonata", "Mike", "hyundae", 210);
car1 c2 = new car1("Alice", "kia", 300);
car1 c3 = new car1("Tom", 350);
car1 c4 = new car1("Benz", "tomas", "mk", 500);
//c3의 멤버변수들 출력
System.out.println("제 이름은 "+ c3.owner+"이고 "+c3.price+"만원 짜리 차를 타고 다닙니다.");
//c4의 메서드 호출
System.out.println("제 이름은 "+c4.owner+"입니다. \n|→주로 "+c4.start("8:00")+"부터 "+c4.stop("21:00")+"까지 타고 다닙니다");
}
} |
package com.magicalcoder.youyaboot.model;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.math.*;
import java.io.Serializable;
import lombok.Data;
/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/
@Data
public class AllType implements Serializable{
private Long longId;//主键
private byte[] bytesBinary;//bytes_binary
private byte[] bytesBlob;//bytes_blob
private byte[] bytesMediumblob;//bytes_mediumblob
private byte[] bytesVarbinary;//bytes_varbinary
private byte[] bytesTinyblob;//bytes_tinyblob
private byte[] bytesLongblob;//bytes_longblob
private Boolean booleanBit;//boolean_bit
private Boolean booleanBool;//boolean_bool
private Boolean booleanBoolean;//boolean_boolean
private String stringEnum;//string_enum
private String stringChar;//string_char
private String stringLongtext;//string_longtext
private String stringMediumtext;//string_mediumtext
private String stringVarchar;//string_varchar
private String stringSet;//string_set
private String stringTinytext;//string_tinytext
private String stringText;//string_text
private Byte byteTinyint;//byte_tinyint
private Short shortSmallint;//short_smallint
private Integer integerInt;//integer_int
private Integer integerMediumint;//integer_mediumint
private Float floatFloat;//float_float
private Double doubleDouble;//double_double
private Double doubleReal;//double_real
private BigDecimal bigdecimalDecimal;//bigdecimal_decimal
private BigDecimal bigdecimalNumeric;//bigdecimal_numeric
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date dateDate;//date_date
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date dateYear;//date_year
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Time timeTime;//time_time
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Timestamp timestempDatetime;//timestemp_datetime
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Timestamp timestempTimestemp;//timestemp_timestemp
public Long getLongId(){
return longId;
}
public void setLongId(Long longId){
this.longId = longId;
}
public byte[] getBytesBinary(){
return bytesBinary;
}
public void setBytesBinary(byte[] bytesBinary){
this.bytesBinary = bytesBinary;
}
public byte[] getBytesBlob(){
return bytesBlob;
}
public void setBytesBlob(byte[] bytesBlob){
this.bytesBlob = bytesBlob;
}
public byte[] getBytesMediumblob(){
return bytesMediumblob;
}
public void setBytesMediumblob(byte[] bytesMediumblob){
this.bytesMediumblob = bytesMediumblob;
}
public byte[] getBytesVarbinary(){
return bytesVarbinary;
}
public void setBytesVarbinary(byte[] bytesVarbinary){
this.bytesVarbinary = bytesVarbinary;
}
public byte[] getBytesTinyblob(){
return bytesTinyblob;
}
public void setBytesTinyblob(byte[] bytesTinyblob){
this.bytesTinyblob = bytesTinyblob;
}
public byte[] getBytesLongblob(){
return bytesLongblob;
}
public void setBytesLongblob(byte[] bytesLongblob){
this.bytesLongblob = bytesLongblob;
}
public Boolean getBooleanBit(){
return booleanBit;
}
public void setBooleanBit(Boolean booleanBit){
this.booleanBit = booleanBit;
}
public Boolean getBooleanBool(){
return booleanBool;
}
public void setBooleanBool(Boolean booleanBool){
this.booleanBool = booleanBool;
}
public Boolean getBooleanBoolean(){
return booleanBoolean;
}
public void setBooleanBoolean(Boolean booleanBoolean){
this.booleanBoolean = booleanBoolean;
}
public String getStringEnum(){
return stringEnum;
}
public void setStringEnum(String stringEnum){
this.stringEnum = stringEnum;
}
public String getStringChar(){
return stringChar;
}
public void setStringChar(String stringChar){
this.stringChar = stringChar;
}
public String getStringLongtext(){
return stringLongtext;
}
public void setStringLongtext(String stringLongtext){
this.stringLongtext = stringLongtext;
}
public String getStringMediumtext(){
return stringMediumtext;
}
public void setStringMediumtext(String stringMediumtext){
this.stringMediumtext = stringMediumtext;
}
public String getStringVarchar(){
return stringVarchar;
}
public void setStringVarchar(String stringVarchar){
this.stringVarchar = stringVarchar;
}
public String getStringSet(){
return stringSet;
}
public void setStringSet(String stringSet){
this.stringSet = stringSet;
}
public String getStringTinytext(){
return stringTinytext;
}
public void setStringTinytext(String stringTinytext){
this.stringTinytext = stringTinytext;
}
public String getStringText(){
return stringText;
}
public void setStringText(String stringText){
this.stringText = stringText;
}
public Byte getByteTinyint(){
return byteTinyint;
}
public void setByteTinyint(Byte byteTinyint){
this.byteTinyint = byteTinyint;
}
public Short getShortSmallint(){
return shortSmallint;
}
public void setShortSmallint(Short shortSmallint){
this.shortSmallint = shortSmallint;
}
public Integer getIntegerInt(){
return integerInt;
}
public void setIntegerInt(Integer integerInt){
this.integerInt = integerInt;
}
public Integer getIntegerMediumint(){
return integerMediumint;
}
public void setIntegerMediumint(Integer integerMediumint){
this.integerMediumint = integerMediumint;
}
public Float getFloatFloat(){
return floatFloat;
}
public void setFloatFloat(Float floatFloat){
this.floatFloat = floatFloat;
}
public Double getDoubleDouble(){
return doubleDouble;
}
public void setDoubleDouble(Double doubleDouble){
this.doubleDouble = doubleDouble;
}
public Double getDoubleReal(){
return doubleReal;
}
public void setDoubleReal(Double doubleReal){
this.doubleReal = doubleReal;
}
public BigDecimal getBigdecimalDecimal(){
return bigdecimalDecimal;
}
public void setBigdecimalDecimal(BigDecimal bigdecimalDecimal){
this.bigdecimalDecimal = bigdecimalDecimal;
}
public BigDecimal getBigdecimalNumeric(){
return bigdecimalNumeric;
}
public void setBigdecimalNumeric(BigDecimal bigdecimalNumeric){
this.bigdecimalNumeric = bigdecimalNumeric;
}
public Date getDateDate(){
return dateDate;
}
public void setDateDate(Date dateDate){
this.dateDate = dateDate;
}
public Date getDateYear(){
return dateYear;
}
public void setDateYear(Date dateYear){
this.dateYear = dateYear;
}
public Time getTimeTime(){
return timeTime;
}
public void setTimeTime(Time timeTime){
this.timeTime = timeTime;
}
public Timestamp getTimestempDatetime(){
return timestempDatetime;
}
public void setTimestempDatetime(Timestamp timestempDatetime){
this.timestempDatetime = timestempDatetime;
}
public Timestamp getTimestempTimestemp(){
return timestempTimestemp;
}
public void setTimestempTimestemp(Timestamp timestempTimestemp){
this.timestempTimestemp = timestempTimestemp;
}
}
|
/*
* 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 bitcoinclient;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Date;
public class BitcoinPacket {
final static int MAINNET = 0xD9B4BEF9;
final static int TESTNET = 0xDAB5BFFA;
final static int TESTNET3 = 0x0709110B;
public static int NETWORK = MAINNET;
byte[] payload;
String command;
public BitcoinPacket(String command, byte[] payload) {
super();
this.command = command;
this.payload = payload;
}
/**
* Convert packet into bytes to be sent over socket
*
* @return bytes
*/
public byte[] pack() {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putInt(NETWORK);
buf.put(command.getBytes());
for (int i = command.length(); i < 12; i++) {
buf.put((byte) 0);
}
buf.putInt(payload.length);
buf.put(Arrays.copyOfRange(BitcoinClient.sha256twice(payload), 0, 4));
buf.put(payload);
buf.flip();
byte[] outbuf = new byte[buf.limit()];
buf.get(outbuf);
return outbuf;
}
/**
* Read a netaddr from a bytebuffer (advancing byte buffer) and return a
* peer address
*
* @param buf byte buffer
* @return
*/
public static PeerAddress from_netaddr(ByteBuffer buf) {
buf.order(ByteOrder.LITTLE_ENDIAN);
Date time = new Date((long) buf.getInt() * 1000L);
long services;
services = buf.getLong();
byte[] ipdata = new byte[16];
buf.get(ipdata);
buf.order(ByteOrder.BIG_ENDIAN);
int port = buf.getShort();
InetAddress ip = null;
try {
ip = InetAddress.getByAddress(ipdata);
// System.out.println("ip " + ip);
} catch (UnknownHostException e) {
}
buf.order(ByteOrder.LITTLE_ENDIAN);
return new PeerAddress(ip, port, time);
}
static int SERVICES = 1;
/**
* Convert ip and port into netaddr structure for incorporation into bitcoin
* packet
*
* @param ip
* @param port
* @return bytes to go into packet
*/
public static byte[] to_netaddr(InetAddress ip, int port) {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.putLong(SERVICES); // services
buf.putLong(0);
buf.putInt(0xFFFF0000);
byte ipbuf[] = new byte[4];
try {
InetAddress.getByAddress(ipbuf);
} catch (UnknownHostException e) {
throw new RuntimeException();
}
buf.put(ipbuf);
buf.order(ByteOrder.BIG_ENDIAN);
buf.putShort((short) port);
buf.flip();
byte out[] = new byte[buf.limit()];
buf.get(out);
return out;
}
/**
* Read varint from byte buffer advancing the byte buffer
*
* @param buf
* @return the value
*/
public static long from_varint(ByteBuffer buf) {
buf.order(ByteOrder.LITTLE_ENDIAN);
int type = buf.get() & 0xff;
buf.order(ByteOrder.LITTLE_ENDIAN);
if (type < 0xFD) {
return type;
} else if (type == 0xfd) {
return buf.getShort();
} else if (type == 0xfe) {
return buf.getInt();
} else {
return buf.getLong();
}
}
/**
* Long to varint bytes for incorporation into a packet
*
* @param in
* @return
*/
public static byte[] to_varint(long in) {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.order(ByteOrder.LITTLE_ENDIAN);
if (in < 0xFD) {
buf.put((byte) in);
} else if (in < 0xFFFF) {
buf.put((byte) 0xFD);
buf.putShort((short) in);
} else if (in < 0xFFFFFFFF) {
buf.put((byte) 0xFe);
buf.putInt((int) in);
} else {
buf.put((byte) 0xFF);
buf.putLong(in);
}
buf.flip();
byte out[] = new byte[buf.limit()];
buf.get(out);
return out;
}
/**
* String to varstr bytes for incorporation into packet
*
* @param str
* @return
*/
public static byte[] to_varstr(String str) {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(to_varint(str.length()));
buf.put(str.getBytes());
buf.flip();
byte out[] = new byte[buf.limit()];
buf.get(out);
return out;
}
}
|
package com.espendwise.manta.web.validator;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.validation.*;
import com.espendwise.manta.util.validation.resolvers.ValidationCodeResolver;
import com.espendwise.manta.web.forms.AbstractSimpleFilterForm;
import com.espendwise.manta.web.resolver.SearchByIdErrorResolver;
import com.espendwise.manta.web.resolver.TextErrorWebResolver;
import com.espendwise.manta.web.util.WebErrors;
import org.apache.log4j.Logger;
public class SimpleFilterFormFieldValidator extends AbstractFormFieldValidator {
private static final Logger logger = Logger.getLogger(SimpleFilterFormFieldValidator.class);
public SimpleFilterFormFieldValidator(String fieldKey) {
super(fieldKey, null, "filterValue");
}
public SimpleFilterFormFieldValidator(String fieldKey, String fieldIdKey) {
super(fieldKey, fieldIdKey, null, "filterValue");
}
public SimpleFilterFormFieldValidator(String fieldKey, String fieldIdKey, String fieldName) {
super(fieldKey, fieldIdKey, fieldName, "filterValue");
}
public SimpleFilterFormFieldValidator() {
super("admin.global.filterValue","admin.global.filterId", "Filter Value", "filterValue");
}
public ValidationResult validate(Object obj, ValidationCodeResolver resolver) {
AbstractSimpleFilterForm valueObj = (AbstractSimpleFilterForm) obj;
WebErrors errors = new WebErrors();
if (Constants.FILTER_TYPE.ID.equals(valueObj.getFilterType())) {
try {
IntegerValidator intValidator = Validators.getIntegerValidator();
ValidationResult vr;
if (resolver == null) {
vr = intValidator.validate(valueObj.getFilterValue(), new SearchByIdErrorResolver(getFieldKey(), getFieldName()));
} else {
vr = intValidator.validate(valueObj.getFilterValue(), resolver);
}
if (vr != null) {
errors.putErrors(vr.getResult());
}
} catch (ValidationException e) {
e.printStackTrace();
throw e;
}
} else if(Utility.isSet(valueObj.getFilterId())) {
try {
IntegerValidator intValidator = Validators.getIntegerValidator();
ValidationResult vr;
if (resolver == null) {
vr = intValidator.validate(valueObj.getFilterId(), new SearchByIdErrorResolver(getFieldIdKey(), getFieldName()));
} else {
vr = intValidator.validate(valueObj.getFilterId(), resolver);
}
if (vr != null) {
errors.putErrors(vr.getResult());
}
} catch (ValidationException e) {
e.printStackTrace();
throw e;
}
} else if(Utility.isSet(valueObj.getFilterValue())) {
TextValidator shortDescValidator = Validators.getTextValidator(Constants.VALIDATION_FIELD_CRITERIA.SHORT_DESC_LENGTH);
ValidationResult vr = shortDescValidator.validate(valueObj.getFilterValue(), new TextErrorWebResolver(getFieldKey(), getFieldName()));
if (vr != null) {
errors.putErrors(vr.getResult());
}
}
return new MessageValidationResult(errors.get());
}
public ValidationResult validate(Object obj) {
return validate(obj, (ValidationCodeResolver) null);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.panel.center;
import com.google.gwt.user.client.ui.Composite;
import com.openkm.frontend.client.util.Util;
import com.openkm.frontend.client.widget.searchin.SearchIn;
import com.openkm.frontend.client.widget.searchresult.SearchResult;
/**
* Search panel
*
* @author jllort
*
*/
public class SearchBrowser extends Composite {
private final static int PANEL_TOP_HEIGHT = 230;
public final static int SPLITTER_HEIGHT = 10;
private VerticalSplitLayoutExtended verticalSplitLayoutPanel;
public SearchIn searchIn;
public SearchResult searchResult;
public int width = 0;
public int height = 0;
public int topHeight = 0;
public int bottomHeight = 0;
private boolean loadFinish = false;
/**
* SearchBrowser
*/
public SearchBrowser() {
verticalSplitLayoutPanel = new VerticalSplitLayoutExtended(new VerticalResizeHandler() {
@Override
public void onResize(int topHeight, int bottomHeight) {
// loadFinish prevent resizing (leftWidht,rightWidth) = (0,0) at startup
if (loadFinish) {
resizePanels();
}
}
});
searchIn = new SearchIn();
searchResult = new SearchResult();
verticalSplitLayoutPanel.getSplitPanel().addNorth(searchIn,100);
verticalSplitLayoutPanel.getSplitPanel().add(searchResult);
searchIn.setStyleName("okm-Input");
initWidget(verticalSplitLayoutPanel);
}
/**
* Refresh language values
*/
public void langRefresh() {
searchIn.langRefresh();
searchResult.langRefresh();
}
/**
* Sets the size on initialization
*
* @param width The max width of the widget
* @param height The max height of the widget
*/
public void setSize(int width, int height) {
this.width = width;
this.height = height;
topHeight = PANEL_TOP_HEIGHT;
bottomHeight = height - (topHeight + SPLITTER_HEIGHT);
verticalSplitLayoutPanel.setSize(""+width+"px", ""+height+"px");
verticalSplitLayoutPanel.setSplitPosition(searchIn, topHeight, false);
// Solve minor ui defect on loading bottomHeight is +2 than should be while move splitter
if (!loadFinish) {
bottomHeight = bottomHeight+2;
}
resize();
}
/**
* resize
*/
private void resize() {
verticalSplitLayoutPanel.setWidth(""+width+"px");
searchIn.setPixelSize(width, topHeight);
// Resize the scroll panel on tab properties
// We substract 2 pixels for width and height generated by border line
int searchResultWidth = width-2;
int searchResultHeight = bottomHeight-2;
if (searchResultWidth < 0) {
searchResultWidth = 0;
}
if (searchResultHeight < 0) {
searchResultHeight = 0;
}
searchResult.setPixelSize(searchResultWidth, searchResultHeight);
// TODO:Solves minor bug with IE
if (Util.getUserAgent().startsWith("ie")) {
searchResult.setPixelSize(width, bottomHeight);
}
}
/**
* Sets the panel width on resizing
*/
private void resizePanels() {
topHeight = verticalSplitLayoutPanel.getTopHeight();
bottomHeight = verticalSplitLayoutPanel.getBottomHeight();
resize();
}
/**
* setWidth
*/
public void setWidth(int width) {
this.width = width;
resize();
}
/**
* setLoadFinish
*/
public void setLoadFinish() {
loadFinish = true;
searchIn.setLoadFinish();
}
} |
package chat.signa.net.pingfang.logging.entity;
/**
* 通知公告信息
* Created by Administrator on 2016/1/8.
*/
public class NoticeInfo {
private int id;
private String title;
private String massage;
private String time;
public NoticeInfo() {
}
public NoticeInfo(int id, String time, String massage, String title) {
this.id = id;
this.time = time;
this.massage = massage;
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
|
package com.tencent.mm.plugin.wallet_core.id_verify;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.wxpay.a$i;
import com.tencent.mm.ui.base.h;
import java.util.LinkedList;
import java.util.List;
class WalletRealNameVerifyUI$6 implements OnClickListener {
final /* synthetic */ WalletRealNameVerifyUI pkE;
WalletRealNameVerifyUI$6(WalletRealNameVerifyUI walletRealNameVerifyUI) {
this.pkE = walletRealNameVerifyUI;
}
public final void onClick(View view) {
List linkedList = new LinkedList();
List linkedList2 = new LinkedList();
linkedList.add(this.pkE.getString(a$i.wallet_card_aggreement_user));
linkedList2.add(Integer.valueOf(0));
if (WalletRealNameVerifyUI.e(this.pkE) != null && WalletRealNameVerifyUI.e(this.pkE).pnL) {
linkedList.add(this.pkE.getString(a$i.wallet_card_aggreement_bank));
linkedList2.add(Integer.valueOf(1));
}
h.a(this.pkE, "", linkedList, linkedList2, "", new 1(this));
}
}
|
package com.quoai.challenge.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown=true)
public class AuthorDto {
private String email;
private String name;
}
|
package com.example.androidtest.Common;
import java.security.MessageDigest;
public class ShortLinkUtils {
static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String shortUrl(String url) throws Exception {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
messagedigest.update(url.getBytes());
String result = bufferToHex(messagedigest.digest());
String resUrl = new String("");
for (int i = 0; i < 8; i++) {
String tmpString = result.substring(i * 4, i * 4 + 4);
long hexLong = 0x3FFFFFFF & Long.parseLong(tmpString, 16);
resUrl += hexDigits[Integer.valueOf((hexLong % 16) + "")] + "";
}
return resUrl;
}
private static String bufferToHex(byte bytes[]) {
return bufferToHex(bytes, 0, bytes.length);
}
private static String bufferToHex(byte bytes[], int m, int n) {
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++) {
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
char c0 = hexDigits[(bt & 0xf0) >> 4];
char c1 = hexDigits[bt & 0xf];
stringbuffer.append(c0);
stringbuffer.append(c1);
}
public static void main(String[] args) {
String sLongUrl = "<a href='http://weibo.com/taobaotianshui?wvr=5&wvr=5&lf=reg'>"
+ "http://weibo.com/taobaotianshui?wvr=5&wvr=5&lf=reg"
+ "</a>";
String shortUrl;
try {
shortUrl = shortUrl(sLongUrl);
System.out.println(sLongUrl + " ===> " + shortUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
/*
* Copyright 2015 Shinya Mochida
*
* Licensed under the Apache License,Version2.0(the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,software
* Distributed under the License is distributed on an"AS IS"BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mikeneck.gradle.plugin.model;
import org.gradle.model.ModelSet;
import java.util.Objects;
import java.util.StringJoiner;
public class ClassEntryPojo implements ClassEntry {
private String name;
private ClassType type;
private ModelSet<PropertyEntry> fields;
private ModelSet<EnumEntry> values;
public ClassEntryPojo() {
this.fields = new ModelSetImpl<>();
this.values = new ModelSetImpl<>();
}
public ClassEntryPojo(ClassEntry ce) {
this.name = ce.getName();
this.type = ce.getType();
this.fields = ce.getFields();
this.values = ce.getValues();
}
public ClassEntryPojo(String name, ClassType type, ModelSet<PropertyEntry> fields, ModelSet<EnumEntry> values) {
this.name = name;
this.type = type;
this.fields = fields;
this.values = values;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public ClassType getType() {
return type;
}
@Override
public void setType(ClassType type) {
this.type = type;
}
@Override
public ModelSet<PropertyEntry> getFields() {
return fields;
}
public void setFields(ModelSet<PropertyEntry> fields) {
this.fields = fields;
}
@Override
public ModelSet<EnumEntry> getValues() {
return values;
}
public void setValues(ModelSet<EnumEntry> values) {
this.values = values;
}
@Override
public String toString() {
return new StringJoiner(", ", "ClassEntryPojo:[", "]")
.add("name: [" + (name == null ? "null" : name) + "]")
.add("type: [" + (type == null ? "null" : type) + "]")
.add("fields: [" + (fields == null ? "null" : fields) + "]")
.add("values: [" + (values == null ? "null" : values) + "]")
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ClassEntry)) return false;
ClassEntry that = (ClassEntry) o;
return Objects.equals(name, that.getName()) &&
Objects.equals(type, that.getType()) &&
Objects.equals(fields, that.getFields()) &&
Objects.equals(values, that.getValues());
}
@Override
public int hashCode() {
return Objects.hash(name, type, fields, values);
}
}
|
package GUI;
import CSV.CSVCondition;
import Objects.Crossroad.Crossroad;
import Objects.CrossroadInfo.CrossroadInfo;
import Objects.Road.RoadCreator;
import Objects.Conditions.Conditions;
import SystemSTL.SystemSTL;
import Tools.Constants;
import Tools.Utils;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import SystemSTL.TrafficComputation.Lane.LaneInfo;
import SystemSTL.TrafficComputation.Car.CarInfo;
import Database.Database;
import Database.DatabaseConditions;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ProgramGUI {
private Scene windowHome, windowClientTypes, windowOptions, windowSimulation;
private Stage window;
private static boolean analyst;
private Conditions conditions;
private Pane simulation;
private CrossroadInfo crossroad_info_1;
private CrossroadInfo crossroad_info_2;
public ProgramGUI(Stage stage) {
stage.setOnCloseRequest(e -> {
e.consume();
boolean answer = ConfirmBox.display(Constants.exit_window_label, Constants.exit_text_label);
if (answer) {
System.exit(1);
}
});
window = stage;
window.setResizable(false);
createUI();
}
/**
* This function create:
* 2 crossroads and their information,
* Home Window,
* Client Types Window,
* Options Window,
* SimulationWindow
*/
private void createUI() {
// conditions = Utils.createStartConditions();
createHomeWindow();
}
/**
* This function create Home Window contains:
* Let's start button - go to window that allow to choose client types.
* About us button
*/
private void createHomeWindow() {
//Title
Label label = new Label(Constants.home_page_window_label);
HBox topMenu = new HBox();
topMenu.setMinHeight(80);
topMenu.setAlignment(Pos.CENTER);
topMenu.getChildren().addAll(label);
//Let's start button
Button buttonStart = new Button(Constants.lets_start_button_label);
buttonStart.setOnAction(e -> {
createClientTypesWindow();
window.setScene(windowClientTypes);
});
//About us button
Button buttonAboutUs = new Button(Constants.about_us_button_label);
buttonAboutUs.setOnAction(e -> AlertBox.display(Constants.about_us_window_label, Constants.about_us_text));
VBox leftMenu = new VBox();
leftMenu.setPadding(new Insets(50));
leftMenu.setSpacing(20);
leftMenu.getChildren().addAll(buttonStart, buttonAboutUs);
VBox rightMenu = new VBox();
Image image = new Image("file:images/others/main-image-3.jpg");
rightMenu.setPrefSize(400, 400);
BackgroundImage backgroundimage = new BackgroundImage(image,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
Background background = new Background(backgroundimage);
rightMenu.setBackground(background);
BorderPane borderPane = new BorderPane();
borderPane.getStylesheets().add("file:src/GUI/style.css");
borderPane.setTop(topMenu);
borderPane.setLeft(leftMenu);
borderPane.setRight(rightMenu);
windowHome = new Scene(borderPane, 600, 400);
}
/**
* Random -
* Database - user need to connect first to his local database, after that the user can choose which condition he want to run.
*/
@SuppressWarnings("Duplicates")
private void createOptionsWindow(boolean analyst) {
VBox centerMenu = new VBox(20);
//Crossroad 1
HBox crossroad_fields_1 = new HBox();
crossroad_fields_1.getStyleClass().add("options-container");
VBox label1 = new VBox(10);
label1.getStyleClass().add("options-column");
Label nameLabel1 = new Label(Constants.crossroad_1_label);
nameLabel1.getStyleClass().add("label-column");
label1.getChildren().addAll(nameLabel1);
VBox route1 = new VBox(10);
route1.getStyleClass().add("options-column");
Label routeLabel1 = new Label(Constants.route_label);
routeLabel1.getStyleClass().add("label-column");
Label northText1 = new Label(Constants.north_label);
Label eastText1 = new Label(Constants.east_label);
Label southText1 = new Label(Constants.south_label);
Label westText1 = new Label(Constants.west_label);
northText1.getStyleClass().add("label-direction");
eastText1.getStyleClass().add("label-direction");
southText1.getStyleClass().add("label-direction");
westText1.getStyleClass().add("label-direction");
route1.getChildren().addAll(routeLabel1, northText1, eastText1, southText1, westText1);
VBox cars1 = new VBox(10);
cars1.getStyleClass().add("options-column");
Label carsLabel1 = new Label(Constants.cars_count_label);
carsLabel1.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> cars_spinners_1 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
if (i != 1) {
cars_spinners_1.add(new Spinner<>(Constants.CARS_COUNT_MIN, Constants.CARS_COUNT_LONG_ROAD_MAX, Constants.CARS_COUNT_LONG_ROAD_DEFAULT));
} else {
cars_spinners_1.add(new Spinner<>(Constants.CARS_COUNT_MIN, Constants.CARS_COUNT_SHORT_ROAD_MAX, Constants.CARS_COUNT_SHORT_ROAD_DEFAULT));
}
if (!analyst) {
cars_spinners_1.get(i).setDisable(true);
} else {
cars_spinners_1.get(i).setDisable(false);
}
}
cars1.getChildren().addAll(carsLabel1, cars_spinners_1.get(0), cars_spinners_1.get(1), cars_spinners_1.get(2), cars_spinners_1.get(3));
VBox speedLimit1 = new VBox(10);
speedLimit1.getStyleClass().add("options-column");
Label speedLimitLabel1 = new Label(Constants.speed_limit_label);
speedLimitLabel1.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> limit_spinners_1 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
limit_spinners_1.add(new Spinner<>(Constants.SPEED_LIMIT_MIN, Constants.SPEED_LIMIT_MAX, Constants.SPEED_LIMIT_DEFAULT, 10));
if (!analyst) {
limit_spinners_1.get(i).setDisable(true);
} else {
limit_spinners_1.get(i).setDisable(false);
}
}
speedLimit1.getChildren().addAll(speedLimitLabel1, limit_spinners_1.get(0), limit_spinners_1.get(1), limit_spinners_1.get(2), limit_spinners_1.get(3));
VBox actualSpeed1 = new VBox(10);
actualSpeed1.getStyleClass().add("options-column");
Label actualSpeedLabel1 = new Label(Constants.actual_speed_label);
actualSpeedLabel1.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> actual_spinners_1 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
actual_spinners_1.add(new Spinner<>(Constants.ACTUAL_LIMIT_MIN, Constants.ACTUAL_LIMIT_MAX, Constants.ACTUAL_LIMIT_DEFAULT));
if (!analyst) {
actual_spinners_1.get(i).setDisable(true);
} else {
actual_spinners_1.get(i).setDisable(false);
}
}
actualSpeed1.getChildren().addAll(actualSpeedLabel1, actual_spinners_1.get(0), actual_spinners_1.get(1), actual_spinners_1.get(2), actual_spinners_1.get(3));
crossroad_fields_1.getChildren().addAll(label1, route1, cars1, speedLimit1, actualSpeed1);
//Crossroad 2
HBox crossroad_fields_2 = new HBox();
crossroad_fields_2.getStyleClass().add("options-container");
VBox boxLabel2 = new VBox(10);
boxLabel2.getStyleClass().add("options-column");
Label nameLabel2 = new Label(Constants.crossroad_2_label);
nameLabel2.getStyleClass().add("label-column");
boxLabel2.getChildren().addAll(nameLabel2);
VBox route2 = new VBox(10);
route2.getStyleClass().add("options-column");
Label routeLabel2 = new Label(Constants.route_label);
routeLabel2.getStyleClass().add("label-column");
Label northText2 = new Label(Constants.north_label);
Label eastText2 = new Label(Constants.east_label);
Label southText2 = new Label(Constants.south_label);
Label westText2 = new Label(Constants.west_label);
northText2.getStyleClass().add("label-direction");
eastText2.getStyleClass().add("label-direction");
southText2.getStyleClass().add("label-direction");
westText2.getStyleClass().add("label-direction");
route2.getChildren().addAll(routeLabel2, northText2, eastText2, southText2, westText2);
VBox cars2 = new VBox(10);
cars2.getStyleClass().add("options-column");
Label carsLabel2 = new Label(Constants.cars_count_label);
carsLabel2.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> cars_spinners_2 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
if (i != 3) {
cars_spinners_2.add(new Spinner<>(Constants.CARS_COUNT_MIN, Constants.CARS_COUNT_LONG_ROAD_MAX, Constants.CARS_COUNT_LONG_ROAD_DEFAULT));
} else {
cars_spinners_2.add(new Spinner<>(Constants.CARS_COUNT_MIN, Constants.CARS_COUNT_SHORT_ROAD_MAX, Constants.CARS_COUNT_SHORT_ROAD_DEFAULT));
}
if (!analyst) {
cars_spinners_2.get(i).setDisable(true);
} else {
cars_spinners_2.get(i).setDisable(false);
}
}
cars2.getChildren().addAll(carsLabel2, cars_spinners_2.get(0), cars_spinners_2.get(1), cars_spinners_2.get(2), cars_spinners_2.get(3));
VBox speedLimit2 = new VBox(10);
speedLimit2.getStyleClass().add("options-column");
Label speedLimitLabel2 = new Label(Constants.speed_limit_label);
speedLimitLabel2.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> limit_spinners_2 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
limit_spinners_2.add(new Spinner<>(Constants.SPEED_LIMIT_MIN, Constants.SPEED_LIMIT_MAX, Constants.SPEED_LIMIT_DEFAULT, 10));
if (!analyst) {
limit_spinners_2.get(i).setDisable(true);
} else {
limit_spinners_2.get(i).setDisable(false);
}
}
speedLimit2.getChildren().addAll(speedLimitLabel2, limit_spinners_2.get(0), limit_spinners_2.get(1), limit_spinners_2.get(2), limit_spinners_2.get(3));
VBox actualSpeed2 = new VBox(10);
actualSpeed2.getStyleClass().add("options-column");
Label actualSpeedLabel2 = new Label(Constants.actual_speed_label);
actualSpeedLabel2.getStyleClass().add("label-column");
ArrayList<Spinner<Integer>> actual_spinners_2 = new ArrayList<>();
for (int i = 0; i < 4; i++) {
actual_spinners_2.add(new Spinner<>(Constants.ACTUAL_LIMIT_MIN, Constants.ACTUAL_LIMIT_MAX, Constants.ACTUAL_LIMIT_DEFAULT));
if (!analyst) {
actual_spinners_2.get(i).setDisable(true);
} else {
actual_spinners_2.get(i).setDisable(false);
}
}
//Speed limit listeners - there are directions that go along the same road through two intersections,
//so the speed limit should be the same on them
Utils.createSameSpeedListeners(limit_spinners_1, limit_spinners_2);
Utils.createSameSpeedListeners(actual_spinners_1, actual_spinners_2);
//actual speed listeners - actual speed can't be more than speed limit
Utils.createActualSpeedListeners(actual_spinners_1, limit_spinners_1);
Utils.createActualSpeedListeners(actual_spinners_2, limit_spinners_2);
Utils.createSpeedLimitListeners(actual_spinners_1, limit_spinners_1);
Utils.createSpeedLimitListeners(actual_spinners_2, limit_spinners_2);
actualSpeed2.getChildren().addAll(actualSpeedLabel2, actual_spinners_2.get(0), actual_spinners_2.get(1), actual_spinners_2.get(2), actual_spinners_2.get(3));
crossroad_fields_2.getChildren().addAll(boxLabel2, route2, cars2, speedLimit2, actualSpeed2);
HBox phaseTimeOptions = new HBox();
phaseTimeOptions.getStyleClass().add("options-container");
VBox labelBox = new VBox(10);
labelBox.getStyleClass().add("options-column");
Label labelPhase = new Label("Select the initial time for one traffic light phase: ");
labelPhase.getStyleClass().add("label-column");
labelBox.getChildren().add(labelPhase);
VBox spinnerBox = new VBox(10);
Spinner<Integer> phaseTime = new Spinner<>(20, 30, 20, 2);
spinnerBox.getChildren().add(phaseTime);
phaseTimeOptions.getChildren().addAll(labelPhase, spinnerBox);
//Other options
HBox otherOptions = new HBox();
otherOptions.getStyleClass().add("options-container");
// VBox boxLabel3 = new VBox(10);
// boxLabel3.getStyleClass().add("options-column");
// Label nameLabel3 = new Label(Constants.other_features_label);
// nameLabel3.getStyleClass().add("label-column");
// boxLabel3.getChildren().addAll(nameLabel3);
VBox boxButtonOpenCSV = new VBox(10);
boxButtonOpenCSV.getStyleClass().add("options-column");
Button buttonOpenCSV = new Button(Constants.open_csv_button_label);
boxButtonOpenCSV.getChildren().add(buttonOpenCSV);
buttonOpenCSV.setOnAction(e -> {
String path = OpenBox.display();
if (path != null) {
CSVCondition csv_condition = Utils.createConditionsFromCSV(path);
if (csv_condition != null) {
//1
Utils.setCSVConditionsInSpinner(cars_spinners_1, limit_spinners_1, actual_spinners_1, csv_condition.getFirstCrossroad());
//2
Utils.setCSVConditionsInSpinner(cars_spinners_2, limit_spinners_2, actual_spinners_2, csv_condition.getSecondCrossroad());
} else {
AlertBox.display(Constants.fail_window_label, Constants.csv_fail_text_label);
}
}
});
VBox boxButtonRandom = new VBox(10);
boxButtonRandom.getStyleClass().add("options-column");
Button buttonRandom = new Button(Constants.random_button_label);
boxButtonRandom.getChildren().add(buttonRandom);
buttonRandom.setOnAction(e -> {
if (!analyst) {
AlertBox.display(Constants.fail_window_label, Constants.fail_text_label);
} else {
boolean answer = ConfirmBox.display(Constants.random_window_label, Constants.generate_random_data_label);
if (answer) {
//1
Utils.createRandomConditions(cars_spinners_1, limit_spinners_1, actual_spinners_1, 1);
//2
Utils.createRandomConditions(cars_spinners_2, limit_spinners_2, actual_spinners_2, 3);
//synchronize between same directions spinners
limit_spinners_1.get(1).getValueFactory().setValue(limit_spinners_2.get(1).getValue());
limit_spinners_1.get(3).getValueFactory().setValue(limit_spinners_2.get(3).getValue());
actual_spinners_1.get(1).getValueFactory().setValue(actual_spinners_2.get(1).getValue());
actual_spinners_1.get(3).getValueFactory().setValue(actual_spinners_2.get(3).getValue());
}
}
});
//Database
VBox boxButtonDatabase = new VBox(10);
boxButtonDatabase.getStyleClass().add("options-column");
Button buttonDatabase = new Button(Constants.database_button_label);
boxButtonDatabase.getChildren().add(buttonDatabase);
buttonDatabase.setOnAction(e -> {
try {
String condition_date = DatabaseBox.display();
if (condition_date != null && condition_date != "") {
Database db = Database.getInstance();
DatabaseConditions db_condition = db.getDatabaseConditions(condition_date);
if (db_condition != null) {
//1
Utils.setDatabaseConditionsInSpinner(
cars_spinners_1,
limit_spinners_1,
actual_spinners_1,
db_condition.getCarsFirstCrossroad(),
db_condition.getSpeedLimitFirstCrossroad(),
db_condition.getActualSpeedFirstCrossroad());
//2
Utils.setDatabaseConditionsInSpinner(
cars_spinners_2,
limit_spinners_2,
actual_spinners_2,
db_condition.getCarsSecondCrossroad(),
db_condition.getSpeedLimitSecondCrossroad(),
db_condition.getActualSpeedSecondCrossroad());
phaseTime.getValueFactory().setValue((int) db_condition.getPhaseTime());
ResultsBox.display(db_condition);
} else {
AlertBox.display(Constants.fail_window_label, Constants.csv_fail_text_label);
}
}
} catch (Exception ex) {
System.out.println("ERROR: Database failed...");
}
});
VBox boxButtonReset = new VBox(10);
boxButtonReset.getStyleClass().add("options-column");
Button buttonReset = new Button(Constants.reset_button_label);
boxButtonReset.getChildren().add(buttonReset);
buttonReset.setOnAction(e -> {
boolean answer = ConfirmBox.display(Constants.reset_button_label, Constants.reset_conditions_label);
if (answer) {
//1
Utils.resetConditions(cars_spinners_1, limit_spinners_1, actual_spinners_1, 1);
//2
Utils.resetConditions(cars_spinners_2, limit_spinners_2, actual_spinners_2, 3);
}
});
VBox boxButtonInfo = new VBox(10);
boxButtonInfo.getStyleClass().add("options-column");
Button buttonInfo = new Button(Constants.info_button_label);
boxButtonInfo.getChildren().add(buttonInfo);
buttonInfo.setOnAction(e -> {
InformationBox.display("Information");
});
otherOptions.getChildren().addAll(boxButtonOpenCSV, boxButtonDatabase, boxButtonRandom, boxButtonReset, boxButtonInfo);
centerMenu.getChildren().addAll(crossroad_fields_1, crossroad_fields_2, phaseTimeOptions, otherOptions);
// centerMenu.getChildren().addAll(crossroad_fields_1, crossroad_fields_2, otherOptions);
//Title
HBox topMenu = new HBox();
Label label = new Label(Constants.traffic_conditions_window_label);
topMenu.setMinHeight(80);
topMenu.setAlignment(Pos.CENTER);
topMenu.getChildren().addAll(label);
//Run
HBox bottomMenu = new HBox(20);
bottomMenu.setAlignment(Pos.CENTER);
Button buttonRun = new Button(Constants.run_button_label);
buttonRun.setOnAction(e -> {
//create crossroadInfo with fields data
//check if data correct
//continue to next window
Crossroad crossroad_1 = new Crossroad(RoadCreator.createRoads(54, 1));
Crossroad crossroad_2 = new Crossroad(RoadCreator.createRoads(433, 1));
if (phaseTime.getValue() != Constants.TRAFFIC_LIGHT_PHASE_TIME) {
crossroad_1.setPhaseTime(phaseTime.getValue());
crossroad_2.setPhaseTime(phaseTime.getValue());
}
crossroad_info_1 = new CrossroadInfo(crossroad_1);
crossroad_info_2 = new CrossroadInfo(crossroad_2);
int[] cars_inputs_1 = {cars_spinners_1.get(0).getValue(), cars_spinners_1.get(1).getValue(), cars_spinners_1.get(2).getValue(), cars_spinners_1.get(3).getValue()};
int[] actual_inputs_1 = {actual_spinners_1.get(0).getValue(), actual_spinners_1.get(1).getValue(), actual_spinners_1.get(2).getValue(), actual_spinners_1.get(3).getValue()};
int[] limit_inputs_1 = {limit_spinners_1.get(0).getValue(), limit_spinners_1.get(1).getValue(), limit_spinners_1.get(2).getValue(), limit_spinners_1.get(3).getValue()};
int[] cars_inputs_2 = {cars_spinners_2.get(0).getValue(), cars_spinners_2.get(1).getValue(), cars_spinners_2.get(2).getValue(), cars_spinners_2.get(3).getValue()};
int[] actual_inputs_2 = {actual_spinners_2.get(0).getValue(), actual_spinners_2.get(1).getValue(), actual_spinners_2.get(2).getValue(), actual_spinners_2.get(3).getValue()};
int[] limit_inputs_2 = {limit_spinners_2.get(0).getValue(), limit_spinners_2.get(1).getValue(), limit_spinners_2.get(2).getValue(), limit_spinners_2.get(3).getValue()};
crossroad_info_1.setCrossroadInfo(cars_inputs_1, limit_inputs_1, actual_inputs_1);
crossroad_info_2.setCrossroadInfo(cars_inputs_2, limit_inputs_2, actual_inputs_2);
conditions = new Conditions(crossroad_info_1, crossroad_info_2);
createSimulationWindow();
window.setScene(windowSimulation);
});
//Back
Button buttonBack = new Button(Constants.back_button_label);
buttonBack.setOnAction(e -> {
boolean goBack = ConfirmBox.display(Constants.go_to_previous_page_window_label,
Constants.go_to_previous_page_from_conditions_text);
if (goBack) window.setScene(windowClientTypes);
});
bottomMenu.getChildren().addAll(buttonBack, buttonRun);
BorderPane borderPane = new BorderPane();
borderPane.getStylesheets().add("file:src/GUI/style.css");
borderPane.setTop(topMenu);
borderPane.setCenter(centerMenu);
borderPane.setBottom(bottomMenu);
// Button buttonBackHome = new Button("Back home");
// buttonBackHome.setOnAction(e -> window.setScene(windowHome));
// String imgPath = "file:images/lights/red-s.png";
// Image img = new Image(imgPath);
// StackPane layout2 = new StackPane();
// layout2.getChildren().add(buttonBackHome);
// layout2.getChildren().add(new ImageView(img));
windowOptions = new Scene(borderPane, 1000, 740);
// windowOptions = new Scene(borderPane, 1000, 660);
}
/**
* This function allow to user choose his client type - Analyst/Observer.
* Analyst - go to window with all options.
* Observer - go to window with limited options.
*/
private void createClientTypesWindow() {
//Title
Label label = new Label(Constants.client_type_window_label);
HBox topMenu = new HBox();
topMenu.setMinHeight(80);
topMenu.setAlignment(Pos.CENTER);
topMenu.getChildren().addAll(label);
//Analyst button
VBox leftMenu = new VBox(20);
Button buttonAnalyst = new Button(Constants.analyst_button_label);
buttonAnalyst.setOnAction(e -> {
analyst = true;
createOptionsWindow(analyst);
window.setScene(windowOptions);
});
leftMenu.setAlignment(Pos.CENTER);
Image imageAnalyst = new Image("file:images/others/analyst.png");
ImageView imageViewAnalyst = new ImageView(imageAnalyst);
imageViewAnalyst.setFitHeight(236);
imageViewAnalyst.setFitWidth(250);
leftMenu.getChildren().addAll(imageViewAnalyst, buttonAnalyst);
//Observer button
VBox rightMenu = new VBox(20);
Button buttonObserver = new Button(Constants.observer_button_label);
buttonObserver.setOnAction(e -> {
analyst = false;
createOptionsWindow(analyst);
window.setScene(windowOptions);
});
rightMenu.setAlignment(Pos.CENTER);
Image imageObserver = new Image("file:images/others/observer.png");
ImageView imageViewObserver = new ImageView(imageObserver);
imageViewObserver.setFitHeight(236);
imageViewObserver.setFitWidth(250);
rightMenu.getChildren().addAll(imageViewObserver, buttonObserver);
BorderPane borderPane = new BorderPane();
borderPane.getStylesheets().add("file:src/GUI/style.css");
borderPane.setTop(topMenu);
borderPane.setRight(rightMenu);
borderPane.setLeft(leftMenu);
windowClientTypes = new Scene(borderPane, 600, 400);
}
@SuppressWarnings("Duplicates")
private void createSimulationWindow() {
Utils.printSimulationCreated();
ExecutorService executor = Executors.newFixedThreadPool(2);
SystemSTL systemSTL = new SystemSTL(conditions);
HBox topMenu = new HBox();
Label label = new Label(Constants.simulation_window_label);
topMenu.setMinHeight(60);
topMenu.setAlignment(Pos.CENTER);
topMenu.getChildren().addAll(label);
HBox bottomMenu = new HBox(20);
bottomMenu.setMinHeight(60);
bottomMenu.setAlignment(Pos.CENTER);
Button buttonSave = new Button(Constants.save_button_label);
buttonSave.setDisable(true);
buttonSave.setOnAction(e -> {
try {
//Login before saving
if (Database.getInstance().getConnection() == null) {
DatabaseBox.login();
//Save to database window
Database.getInstance().save(conditions);
//Disable button
buttonSave.setDisable(true);
} else {
//Save to database window
Database.getInstance().save(conditions);
//Disable button
buttonSave.setDisable(true);
}
} catch (Exception ex) {
System.err.println("ERROR: Saving to database failed...");
}
});
Button buttonBack = new Button(Constants.back_button_label);
buttonBack.setOnAction(e -> {
boolean goBack = ConfirmBox.display(Constants.go_to_previous_page_window_label,
Constants.go_to_previous_page_from_simulation_text);
if (goBack) {
systemSTL.stop();
window.setScene(windowOptions);
}
});
simulation = new Pane();
simulation.setPrefSize(990, 530);
updateSimulation();
BorderPane borderPane = new BorderPane();
Button buttonStart = new Button(Constants.start_button_label);
buttonStart.setOnAction(e -> {
buttonStart.setDisable(true);
buttonSave.setDisable(true);
Thread run_system = new Thread(new Runnable() {
@Override
public void run() {
systemSTL.run();
while (!systemSTL.getIsFinished() && !systemSTL.getIsStopped()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
Platform.runLater(new Runnable() {
@Override
public void run() {
if (systemSTL.getIsFinished()) {
DatabaseConditions database_conditions = Utils.createDatabaseConditions(conditions);
ResultsBox.display(database_conditions);
if (analyst) {
buttonSave.setDisable(false);
}
}
}
});
}
});
Thread update_simulation = new Thread(new Runnable() {
@Override
public void run() {
while (!systemSTL.getIsFinished() && !systemSTL.getIsStopped()) {
try {
Thread.sleep(30);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Platform.runLater(new Runnable() {
@Override
public void run() {
updateSimulation();
}
});
}
}
});
executor.execute(run_system);
executor.execute(update_simulation);
executor.shutdown();
});
bottomMenu.getChildren().addAll(buttonBack, buttonSave, buttonStart);
borderPane.getStylesheets().add("file:src/GUI/style.css");
borderPane.setTop(topMenu);
borderPane.setCenter(simulation);
borderPane.setBottom(bottomMenu);
windowSimulation = new Scene(borderPane, 1000, 660);
}
private synchronized void updateSimulation() {
simulation.getChildren().clear();
simulation.getStyleClass().add("simulation-container");
Image image_road = new Image("file:images/others/road.png");
ImageView imageViewRoad = new ImageView(image_road);
imageViewRoad.setFitHeight(530);
imageViewRoad.setFitWidth(990);
simulation.getChildren().addAll(imageViewRoad);
updateTrafficLights();
updateCars();
}
private synchronized void updateCars() {
Rectangle outputClip = new Rectangle(990, 530);
simulation.setClip(outputClip);
simulation.layoutBoundsProperty().addListener((ov, oldValue, newValue) -> {
outputClip.setWidth(newValue.getWidth());
outputClip.setHeight(newValue.getHeight());
});
updateNorthSouthCars();
updateWestEastCars();
}
private void updateWestEastCars() {
ArrayList<ImageView> east_crossroad_1 =
createCars(1, Constants.EAST_DIRECTION, conditions.getLanesInfoFirstCrossroad().get(1));
ArrayList<ImageView> east_crossroad_2 =
createCars(2, Constants.EAST_DIRECTION, conditions.getLanesInfoSecondCrossroad().get(1));
ArrayList<ImageView> west_crossroad_1 =
createCars(1, Constants.WEST_DIRECTION, conditions.getLanesInfoFirstCrossroad().get(3));
ArrayList<ImageView> west_crossroad_2 =
createCars(2, Constants.WEST_DIRECTION, conditions.getLanesInfoSecondCrossroad().get(3));
addCars(east_crossroad_1);
addCars(east_crossroad_2);
addCars(west_crossroad_1);
addCars(west_crossroad_2);
}
private synchronized void updateNorthSouthCars() {
ArrayList<ImageView> north_crossroad_1 =
createCars(1, Constants.NORTH_DIRECTION, conditions.getLanesInfoFirstCrossroad().get(0));
ArrayList<ImageView> north_crossroad_2 =
createCars(2, Constants.NORTH_DIRECTION, conditions.getLanesInfoSecondCrossroad().get(0));
ArrayList<ImageView> south_crossroad_1 =
createCars(1, Constants.SOUTH_DIRECTION, conditions.getLanesInfoFirstCrossroad().get(2));
ArrayList<ImageView> south_crossroad_2 =
createCars(2, Constants.SOUTH_DIRECTION, conditions.getLanesInfoSecondCrossroad().get(2));
addCars(north_crossroad_1);
addCars(north_crossroad_2);
addCars(south_crossroad_1);
addCars(south_crossroad_2);
}
private synchronized ArrayList<ImageView> createCars(int crossroad, int direction, LaneInfo lane_info) {
ArrayList<ImageView> cars = new ArrayList<>();
try {
for (CarInfo car_info : lane_info.getCarsInLane()) {
if (lane_info.getCarsInLane().size() == 0) {
break;
}
if (-40 < car_info.getDistanceFromCrossroad() && car_info.getDistanceFromCrossroad() < 40) {
cars.add(createCarOnMapByPlace(crossroad, direction, car_info));
}
}
} catch (ConcurrentModificationException e) {
}
return cars;
}
private ImageView createCarOnMapByPlace(int crossroad_number, int direction, CarInfo car) {
int[] place = generatePlace(crossroad_number, direction, car.getDistanceFromCrossroad());
return createCar(place[0], place[1], getRotateByDirection(direction), car);
}
private int[] generatePlace(int crossroad_number, int direction, double distance_from_crossroad) {
int x = 0;
int y = 0;
distance_from_crossroad *= Constants.METER_TO_PIXEL;
if (direction == Constants.NORTH_DIRECTION) {
x += 187;
y += 130;
y -= distance_from_crossroad;
} else if (direction == Constants.EAST_DIRECTION) {
x += 305;
y += 204;
x += distance_from_crossroad;
} else if (direction == Constants.SOUTH_DIRECTION) {
x += 237;
y += 315;
y += distance_from_crossroad;
} else if (direction == Constants.WEST_DIRECTION) {
x += 118;
y += 250;
x -= distance_from_crossroad;
}
if (crossroad_number == 2) {
x += 528;
}
int[] place = {x, y};
return place;
}
private int getRotateByDirection(int direction) {
switch (direction) {
case Constants.NORTH_DIRECTION:
return 180;
case Constants.EAST_DIRECTION:
return 270;
case Constants.SOUTH_DIRECTION:
return 0;
case Constants.WEST_DIRECTION:
return 90;
default:
throw new RuntimeException("Bad direction for car...");
}
}
private ImageView createCar(int x, int y, int rotate, CarInfo car) {
ImageView image_view = new ImageView(car.getCar().getImage());
image_view.setX(x);
image_view.setY(y);
image_view.setFitHeight(car.getCar().getLength() * Constants.METER_TO_PIXEL);
image_view.setFitWidth(car.getCar().getWidth() * Constants.METER_TO_PIXEL);
image_view.setRotate(rotate);
return image_view;
}
private void addCars(ArrayList<ImageView> cars) {
simulation.getChildren().addAll(cars);
}
private synchronized void updateTrafficLights() {
ImageView[] traffic_lights_crossroad_1 = createTrafficLights(1);
ImageView[] traffic_lights_crossroad_2 = createTrafficLights(2);
addTrafficLights(traffic_lights_crossroad_1);
addTrafficLights(traffic_lights_crossroad_2);
}
private ImageView[] createTrafficLights(int crossroad_number) {
ImageView[] views = new ImageView[4];
CrossroadInfo crossroad_info = null;
int x = 0, y = 170;
if (crossroad_number == 1) {
x = 150;
crossroad_info = crossroad_info_1;
} else if (crossroad_number == 2) {
x = 675;
crossroad_info = crossroad_info_2;
}
views[0] = createTrafficLight(x, y, 180,
crossroad_info.getCrossroad().getNorthTrafficLight().getTrafficLightImage());
views[1] = createTrafficLight(x + 150, y + 10, 270,
crossroad_info.getCrossroad().getEastTrafficLight().getTrafficLightImage());
views[2] = createTrafficLight(x + 140, y + 150, 0,
crossroad_info.getCrossroad().getSouthTrafficLight().getTrafficLightImage());
views[3] = createTrafficLight(x - 10, y + 150, 90,
crossroad_info.getCrossroad().getWestTrafficLight().getTrafficLightImage());
return views;
}
private ImageView createTrafficLight(int x, int y, int rotate, Image image) {
ImageView image_view = new ImageView(image);
image_view.setX(x);
image_view.setY(y);
image_view.setFitHeight(Constants.TRAFFIC_LIGHT_HEIGHT);
image_view.setFitWidth(Constants.TRAFFIC_LIGHT_WIDTH);
image_view.setRotate(rotate);
return image_view;
}
private void addTrafficLights(ImageView[] images) {
// simulation.getChildren().addAll(images[0], images[1], images[2], images[3]);
simulation.getChildren().addAll(images);
}
public Scene getScene() {
return windowHome;
}
} |
package com.tencent.mm.plugin.sns.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.i.j;
import com.tencent.mm.plugin.sns.ui.w.a;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PreviewImageView extends LinearLayout implements w {
private final Context context;
private List<String> list = new ArrayList();
private TableLayout nQm;
private final Map<Integer, View> nQn = new HashMap();
private final Map<Integer, TableRow> nQo = new HashMap();
private final int nQp = 4;
private HashMap<String, Bitmap> nQq = new HashMap();
private a nQr;
private boolean nQs = true;
private boolean nQt = false;
public PreviewImageView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.context = context;
init();
}
public PreviewImageView(Context context) {
super(context);
this.context = context;
init();
}
public void setIsShowAddImage(boolean z) {
this.nQs = z;
}
public View getView() {
return this;
}
public void setImageClick(a aVar) {
this.nQr = aVar;
}
private void init() {
this.nQm = (TableLayout) LayoutInflater.from(this.context).inflate(g.sns_preview_view, this, true).findViewById(f.content);
}
public int getCount() {
return this.nQn.size();
}
public final void clean() {
this.nQt = true;
for (Bitmap bitmap : this.nQq.values()) {
if (i.q(bitmap)) {
bitmap.recycle();
}
}
}
public final void setList$22875ea3(List<String> list) {
long currentTimeMillis = System.currentTimeMillis();
if (list != null) {
this.list = list;
int i = 0;
this.nQm.removeAllViews();
int size = list.size() + 1;
int i2 = 0;
while (i < size) {
View view;
View view2 = (TableRow) this.nQo.get(Integer.valueOf(i2));
if (view2 == null) {
view2 = new TableRow(this.context);
this.nQo.put(Integer.valueOf(i2), view2);
view = view2;
} else {
view = view2;
}
view.removeAllViews();
int i3 = 0;
while (true) {
int i4 = i3;
if (i4 >= 4 || i >= size) {
i3 = i;
} else if (i >= 9) {
i3 = i + 1;
break;
} else {
String str;
view2 = (View) this.nQn.get(Integer.valueOf(i));
if (view2 == null) {
view2 = View.inflate(this.context, g.sns_preview_view_item, null);
this.nQn.put(Integer.valueOf(i), view2);
}
View view3 = view2;
if (i == size - 1) {
str = "";
} else {
str = (String) list.get(i);
}
ImageView imageView = (ImageView) view3.findViewById(f.iv);
if (i != size - 1) {
imageView.setBackgroundDrawable(null);
imageView.setTag(str);
imageView.setContentDescription(getContext().getString(j.sns_img));
Bitmap bitmap = (Bitmap) this.nQq.get(str);
if (i.q(bitmap)) {
imageView.setImageBitmap(bitmap);
} else {
x.d("MicroMsg.PreviewImageView", "bm is null");
new a(this, imageView, str).o(new String[]{""});
}
} else if (this.nQs) {
imageView.setBackgroundResource(e.sns_add_item);
imageView.setContentDescription(getContext().getString(j.sns_add_photo));
imageView.setImageDrawable(null);
} else {
i3 = i4 + 1;
i++;
}
if (this.nQr != null) {
if (i == size - 1) {
view3.setTag(Integer.valueOf(-1));
view3.setOnClickListener(this.nQr.nNR);
view3.setClickable(true);
} else {
view3.setTag(Integer.valueOf(i));
view3.setOnClickListener(this.nQr.nNR);
view3.setClickable(true);
}
}
view3.setLayoutParams(new LayoutParams(-2, -2));
view.addView(view3);
i3 = i4 + 1;
i++;
}
}
i3 = i;
if (view.getChildCount() > 0) {
this.nQm.addView(view);
}
x.d("MicroMsg.PreviewImageView", "initlist time : " + (System.currentTimeMillis() - currentTimeMillis));
i2++;
i = i3;
}
}
}
}
|
package org.buaa.ly.MyCar.logic.impl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.buaa.ly.MyCar.entity.Order;
import org.buaa.ly.MyCar.entity.Store;
import org.buaa.ly.MyCar.entity.Vehicle;
import org.buaa.ly.MyCar.entity.VehicleInfo;
import org.buaa.ly.MyCar.logic.OrderLogic;
import org.buaa.ly.MyCar.logic.StoreLogic;
import org.buaa.ly.MyCar.logic.VehicleLogic;
import org.buaa.ly.MyCar.utils.StatusEnum;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@Data
public class AlgorithmLogic {
private Map<Integer, VehicleInfo> vehicleInfoMap = Maps.newHashMap();
private List<Vehicle> vehicles;
private List<Order> rentingOrders;
private List<Order> pendingOrders;
Integer sid;
Integer viid;
Timestamp begin;
Timestamp end;
private Map<Integer, String> sidCityMap = Maps.newHashMap();
private Map<Integer, Map<Integer, List<Vehicle>>> stockMap = Maps.newHashMap();
private Map<Integer, Map<Integer, Integer>> stockTransformMap = Maps.newHashMap();
private Map<Integer, Map<Integer, List<Order>>> needOrderMap = Maps.newHashMap();
private Map<String, Map<Integer, List<Vehicle>>> stockCityMap = Maps.newHashMap();;
private Map<String, Map<Integer, Integer>> stockCityTransformMap = Maps.newHashMap();;
private Map<String, Map<Integer, List<Order>>> needCityOrderMap = Maps.newHashMap();;
public AlgorithmLogic(String city, Integer sid,
Integer viid, Timestamp begin, Timestamp end,
StoreLogic storeLogic,
VehicleLogic vehicleLogic,
OrderLogic orderLogic) {
this.sid = sid;
this.viid = viid;
this.begin = begin;
this.end = end;
if ( city != null ) {
List<Store> stores = storeLogic.findByCity(city);
Set<Integer> sids = Sets.newHashSet();
for ( Store store : stores ) {
sids.add(store.getId());
sidCityMap.put(store.getId(), store.getCity());
}
this.vehicles = vehicleLogic.find(sids, viid, Lists.newArrayList(StatusEnum.DELETE.getStatus()), true);
this.rentingOrders = orderLogic.findRentingOrders(sids, viid, begin, null);
this.pendingOrders = orderLogic.findPendingOrders(sids, viid, null, end);
} else {
this.vehicles = vehicleLogic.find(sid, viid, Lists.newArrayList(StatusEnum.DELETE.getStatus()), true);
this.rentingOrders = orderLogic.findRentingOrders(sid, viid, begin, null);
this.pendingOrders = orderLogic.findPendingOrders(sid, viid, null, end);
}
simulate();
mergeList(stockMap, stockCityMap);
mergeInteger(stockTransformMap, stockCityTransformMap);
mergeList(needOrderMap, needCityOrderMap);
}
private <T> void mergeList(Map<Integer, Map<Integer, List<T>>> first, Map<String, Map<Integer, List<T>>> seconds) {
for ( Map.Entry<Integer, Map<Integer, List<T>>> entry : first.entrySet() ) {
if ( !sidCityMap.containsKey(entry.getKey()) ) continue;
String city = sidCityMap.get(entry.getKey());
if ( !seconds.containsKey(city) ) seconds.put(city, Maps.newHashMap(entry.getValue()));
else {
for ( Map.Entry<Integer, List<T>> orderEntry : entry.getValue().entrySet() ) {
if ( seconds.get(city).containsKey(orderEntry.getKey()) ) {
seconds.get(city).get(orderEntry.getKey()).addAll(orderEntry.getValue());
} else {
seconds.get(city).put(orderEntry.getKey(),orderEntry.getValue());
}
}
}
}
}
private <T> void mergeInteger(Map<Integer, Map<Integer, Integer>> first, Map<String, Map<Integer, Integer>> seconds) {
for ( Map.Entry<Integer, Map<Integer, Integer>> entry : first.entrySet() ) {
if ( !sidCityMap.containsKey(entry.getKey()) ) continue;
String city = sidCityMap.get(entry.getKey());
if ( !seconds.containsKey(city) ) seconds.put(city, Maps.newHashMap(entry.getValue()));
else {
for ( Map.Entry<Integer, Integer> orderEntry : entry.getValue().entrySet() ) {
if ( seconds.get(city).containsKey(orderEntry.getKey()) ) {
int count = seconds.get(city).get(orderEntry.getKey());
seconds.get(city).put(orderEntry.getKey(), count + orderEntry.getValue());
} else {
seconds.get(city).put(orderEntry.getKey(),orderEntry.getValue());
}
}
}
}
}
private <T> void put(int sid, int viid, T object, Map<Integer, Map<Integer, List<T>>> maps) {
if (!maps.containsKey(sid)) maps.put(sid, Maps.<Integer, List<T>>newHashMap());
if (!maps.get(sid).containsKey(viid)) maps.get(sid).put(viid, Lists.<T>newArrayList());
maps.get(sid).get(viid).add(object);
}
private <T> void transform(T fromCityOrSid, T toCityOrSid, int viid, Map<T, Map<Integer, Integer>> maps) {
if ( !maps.containsKey(fromCityOrSid) ) {
maps.put(fromCityOrSid, Maps.<Integer, Integer>newHashMap());
maps.get(fromCityOrSid).put(viid, -1);
} else if ( !maps.get(fromCityOrSid).containsKey(viid) ) {
maps.get(fromCityOrSid).put(viid, -1);
} else {
int count = maps.get(fromCityOrSid).get(viid);
maps.get(fromCityOrSid).put(viid, count+1);
}
if ( !maps.containsKey(toCityOrSid) ) {
maps.put(toCityOrSid, Maps.<Integer, Integer>newHashMap());
maps.get(toCityOrSid).put(viid, 1);
} else if ( !maps.get(toCityOrSid).containsKey(viid )) {
maps.get(toCityOrSid).put(viid, 1);
} else {
int count = maps.get(toCityOrSid).get(viid);
maps.get(toCityOrSid).put(viid, count+1);
}
}
private void simulate() {
for ( Vehicle vehicle : vehicles ) {
int status = vehicle.getStatus();
if ( !vehicleInfoMap.containsKey(vehicle.getViid()) ) vehicleInfoMap.put(vehicle.getViid(), vehicle.getVehicleInfo());
if ( status == StatusEnum.OK.getStatus() ) {
put(vehicle.getSid(), vehicle.getViid(), vehicle, stockMap);
}
// } else if ( (status == StatusEnum.FIXING.getStatus() || status == StatusEnum.VALIDATE.getStatus()) ) {
// if ( vehicle.getBeginTime() == null || vehicle.getEndTime() == null ) continue;
// if( (vehicle.getEndTime().compareTo(begin) < 0 || vehicle.getBeginTime().compareTo(end) > 0 ))
// put(vehicle.getSid(), vehicle.getViid(), vehicle, stockMap);
// }
}
for ( Order order : rentingOrders ) {
int sid = order.getReturnSid();
put(sid, order.getViid(), order.getVehicle(), stockMap);
}
for ( Order order : pendingOrders ) {
int rentId = order.getRentSid();
int returnId = order.getReturnSid();
if ( order.getEndTime().compareTo(begin) < 0 && rentId != returnId ) {
transform(rentId, returnId, order.getViid(), stockTransformMap);
}
if ( (order.getBeginTime().compareTo(end) < 0 && order.getEndTime().compareTo(begin) > 0) ) {
put(order.getRentSid(), order.getViid(), order, needOrderMap);
}
}
}
}
|
package com.jianglei.zhaopin.dao;
public interface BaseDao<Q, T> {
T selectByPrimaryKey(Integer id);
void deleteByPrimaryKey(Integer id);
void insert(T t);
void insertSelective(T t);
void updateByPrimaryKeySelective(T t);
void updateByPrimaryKey(T t);
}
|
/* Author name: Tiffany White
This is a budget calculator
Created date: September 8, 2015
Modified date: September 22, 2015
*/
public class P1A1_White_3663976
{
public static void main(String[] args)
{
// This line prints text to the screen
System.out.println("Welcome to Budget Calculator by Tiffany White. It will calculate your income and expenses.");
}
}
|
package com.e6soft.form.service;
import com.e6soft.core.service.BaseService;
import com.e6soft.form.model.BusinessFormType;
public interface BusinessFormTypeService extends BaseService<BusinessFormType,String> {
}
|
package com.tencent.tencentmap.mapsdk.a;
import com.tencent.tencentmap.mapsdk.a.hv.a;
import javax.microedition.khronos.opengles.GL10;
class hq$24 implements a {
final /* synthetic */ int a;
final /* synthetic */ int b;
final /* synthetic */ hq c;
hq$24(hq hqVar, int i, int i2) {
this.c = hqVar;
this.a = i;
this.b = i2;
}
public void a(GL10 gl10) {
hq.b(this.c).nativeSetCompassPosition(hq.a(this.c), this.a, this.b);
}
}
|
package com.ar.cmsistemas.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.ar.cmsistemas.db.DataSource;
import oracle.jdbc.OracleTypes;
public class UsuarioDao {
public Boolean loginUser(String usr, String passw) {
Connection connection = null;
CallableStatement cs = null;
Boolean b=null;
try {
connection = DataSource.getInstance().getConnection();
String call = "{ ? = call tp_dba.consultas_inmobiliaria.login_user(?,?)}";
cs = connection.prepareCall(call);
cs.registerOutParameter(1, OracleTypes.NUMBER);
cs.setString(2, usr);
cs.setString(3, passw);
cs.execute();
Integer existe = cs.getInt(1);
if(existe ==1){
b = true;
}
else
{
b=false;
}
} catch (SQLException s) {
System.out.println("Error: ");
s.printStackTrace();
} catch (Exception e) {
System.out.println("Error: ");
e.printStackTrace();
}finally {
if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();}
if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();}
}
return b;
}
public boolean existeUsuario(String usuario) {
Connection connection = null;
CallableStatement cs = null;
Boolean b=null;
try {
connection = DataSource.getInstance().getConnection();
String call = "{ ? = call tp_dba.consultas_inmobiliaria.existe_user(?)}";
cs = connection.prepareCall(call);
cs.registerOutParameter(1, OracleTypes.NUMBER);
cs.setString(2, usuario);
cs.execute();
Integer existe = cs.getInt(1);
if(existe ==0){
b = true;
System.out.println("Es valido");
}
else
{
b=false;
System.out.println("Ya existe el usuario");
}
} catch (SQLException s) {
System.out.println("Error: ");
s.printStackTrace();
} catch (Exception e) {
System.out.println("Error: ");
e.printStackTrace();
}finally {
if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();}
if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();}
}
return b;
}
public void saveUsuario(String usuario, String password) {
Connection connection = null;
CallableStatement cs = null;
try {
connection = DataSource.getInstance().getConnection();
String call = "{call tp_dba.abm_inmobiliaria.save_usuario(?,?)}";
cs = connection.prepareCall(call);
cs.setString(1, usuario);
cs.setString(2, password);
cs.execute();
} catch (SQLException s) {
System.out.println("Error: ");
s.printStackTrace();
} catch (Exception e) {
System.out.println("Error: ");
e.printStackTrace();
}finally {
if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();}
if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();}
}
}
}
|
package migdonio1.wifiswitch.models;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Device {
@SerializedName("_id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("status")
@Expose
private String status;
@SerializedName("__v")
@Expose
private Integer v;
@SerializedName("switchs")
@Expose
private List<Switch> switchs = null;
@SerializedName("sensors")
@Expose
private List<Sensor> sensors = null;
@SerializedName("position")
@Expose
private Position position;
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The _id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The status
*/
public String getStatus() {
return status;
}
/**
*
* @param status
* The status
*/
public void setStatus(String status) {
this.status = status;
}
/**
*
* @return
* The v
*/
public Integer getV() {
return v;
}
/**
*
* @param v
* The __v
*/
public void setV(Integer v) {
this.v = v;
}
/**
*
* @return
* The switchs
*/
public List<Switch> getSwitchs() {
return switchs;
}
/**
*
* @param switchs
* The switchs
*/
public void setSwitchs(List<Switch> switchs) {
this.switchs = switchs;
}
/**
*
* @return
* The sensors
*/
public List<Sensor> getSensors() {
return sensors;
}
/**
*
* @param sensors
* The sensors
*/
public void setSensors(List<Sensor> sensors) {
this.sensors = sensors;
}
/**
*
* @return
* The position
*/
public Position getPosition() {
return position;
}
/**
*
* @param position
* The position
*/
public void setPosition(Position position) {
this.position = position;
}
}
|
package com.diozero.internal.board.odroid;
/*
* #%L
* Organisation: diozero
* Project: diozero - Core
* Filename: OdroidC2SysFsPwmOutputDevice.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.tinylog.Logger;
import com.diozero.api.PinInfo;
import com.diozero.api.RuntimeIOException;
import com.diozero.internal.spi.AbstractDevice;
import com.diozero.internal.spi.DeviceFactoryInterface;
import com.diozero.internal.spi.InternalPwmOutputDeviceInterface;
/**
* <p>
* <a href="http://odroid.com/dokuwiki/doku.php?id=en:c2_hardware_pwm">Setting
* up</a>: 1 PWM Channel (GPIO 234; Pin 33):
* </p>
*
* <pre>
* {@code
*sudo modprobe pwm-meson
*sudo modprobe pwm-ctrl
*}
* </pre>
* <p>
* 2 PWM Channels (GPIO 234 & 235; Pins 33 / 19):
* </p>
*
* <pre>
* {@code
*sudo modprobe pwm-meson npwm=2
*sudo modprobe pwm-ctrl
*}
* </pre>
*/
public class OdroidC2SysFsPwmOutputDevice extends AbstractDevice implements InternalPwmOutputDeviceInterface {
private static Path PWM_ROOT = Paths.get("/sys/devices/platform/pwm-ctrl");
private int range;
private int gpio;
private int pwmNum;
private RandomAccessFile dutyFile;
public OdroidC2SysFsPwmOutputDevice(String key, DeviceFactoryInterface deviceFactory, PinInfo pinInfo,
int frequencyHz, float initialValue) {
super(key, deviceFactory);
this.range = 1023;
this.gpio = pinInfo.getDeviceNumber();
this.pwmNum = pinInfo.getPwmNum();
try {
dutyFile = new RandomAccessFile(PWM_ROOT.resolve("duty" + pwmNum).toFile(), "rw");
} catch (IOException e) {
throw new RuntimeIOException("Error opening duty file for PWM " + pwmNum, e);
}
setEnabled(pwmNum, true);
setPwmFrequency(frequencyHz);
setValue(initialValue);
}
@Override
protected void closeDevice() {
Logger.trace("closeDevice() {}", getKey());
try {
dutyFile.close();
} catch (IOException e) {
// Ignore
}
setEnabled(pwmNum, false);
}
@Override
public int getGpio() {
return gpio;
}
@Override
public int getPwmNum() {
return pwmNum;
}
@Override
public float getValue() throws RuntimeIOException {
try {
dutyFile.seek(0);
int raw_value = Integer.parseInt(dutyFile.readLine());
return raw_value / (float) range;
} catch (IOException e) {
closeDevice();
throw new RuntimeIOException("Error setting duty for PWM #" + pwmNum, e);
}
}
@Override
public void setValue(float value) throws RuntimeIOException {
if (value < 0 || value > 1) {
throw new IllegalArgumentException("Invalid value, must be 0..1");
}
try {
dutyFile.seek(0);
dutyFile.writeBytes(Integer.toString((int) Math.floor(value * range)));
} catch (IOException e) {
closeDevice();
throw new RuntimeIOException("Error setting duty for PWM #" + pwmNum, e);
}
}
@Override
public int getPwmFrequency() {
// freq value is in milli-Hz
return readFreq(pwmNum) / 1_000;
}
@Override
public void setPwmFrequency(int frequencyHz) {
// TODO Preserve the relative value of the duty
// freq value is in milli-Hz
writeFreq(pwmNum, frequencyHz * 1_000);
}
private static void setEnabled(int pwmNum, boolean enabled) {
File f = PWM_ROOT.resolve("enable" + pwmNum).toFile();
try (FileWriter writer = new FileWriter(f)) {
writer.write(enabled ? "1" : "0");
} catch (IOException e) {
throw new RuntimeIOException("Error enabling PWM on #" + pwmNum, e);
}
}
static int readFreq(int pwmNum) {
File f = PWM_ROOT.resolve("freq" + pwmNum).toFile();
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
return Integer.parseInt(reader.readLine());
} catch (IOException | NumberFormatException e) {
throw new RuntimeIOException("Error getting frequency for PWM #" + pwmNum, e);
}
}
static void writeFreq(int pwmNum, int value) throws RuntimeIOException {
File f = PWM_ROOT.resolve("freq" + pwmNum).toFile();
try (FileWriter writer = new FileWriter(f)) {
writer.write(Integer.toString(value));
} catch (IOException e) {
throw new RuntimeIOException("Error setting frequency (" + value + ") for PWM #" + pwmNum, e);
}
}
}
|
package menu;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class NewGame extends JPanel {
static MenuBackground newGame;
Window w = ScreenMenu.w;
private String[] infoMap;
private String[] infoSize;
private String[] infoDate;
private JLabel infoSizeDisplayed;
private JLabel infoMapDisplayed;
private JLabel infoDateDisplayed;
private JRadioButton human1;
private JRadioButton ai1;
private JRadioButton human2;
private JRadioButton ai2;
private File directory = new File("initialMaps");
private String[] saves = directory.list();
private JComboBox<String> levelSelection = new JComboBox<String>(saves);
private NewGame(){
JLabel levels = new JLabel("Start a new game");
levels.setForeground(Color.red);
levels.setFont(MenuButton.newFont.deriveFont((float) 55));
JPanel name = new JPanel();
name.setMaximumSize(new Dimension(500,60));
name.add(levels);
name.setOpaque(false);
levelSelection.setMaximumSize(new Dimension(660,40));
levelSelection.addActionListener(new LevelSelection());
MenuButton start = new MenuButton("Start",Color.getHSBColor((float)0.14, 1, 1));
start.addActionListener(new Start());
MenuButton back = new MenuButton("Back",Color.getHSBColor((float)0.14, 1, 1));
back.addActionListener(new Back());
back.setMinimumSize(new Dimension(300,40));
start.setMinimumSize(new Dimension(300,40));
JPanel buttons = new JPanel();
buttons.setOpaque(false);
buttons.setLayout(new BoxLayout(buttons,BoxLayout.LINE_AXIS));
buttons.setMaximumSize(new Dimension(545,50));
buttons.add(back);
buttons.add(Box.createRigidArea(new Dimension(50,0)));
buttons.add(start);
JPanel infos = new JPanel();
infos.setLayout(new BoxLayout(infos,BoxLayout.PAGE_AXIS));
infos.setMaximumSize(new Dimension(660,240));
infos.setOpaque(false);
JLabel pl1 = new JLabel("Player 1");
pl1.setFont(MenuButton.newFont.deriveFont((float) 30));
pl1.setForeground(Color.white);
JLabel pl2 = new JLabel("Player 2");
pl2.setFont(MenuButton.newFont.deriveFont((float) 30));
pl2.setForeground(Color.white);
human1 = new JRadioButton("Human");
human1.setOpaque(false);
human1.setForeground(Color.white);
human1.setSelected(true);
ai1 = new JRadioButton("AI");
ai1.setOpaque(false);
ai1.setForeground(Color.white);
human2 = new JRadioButton("Human");
human2.setOpaque(false);
human2.setForeground(Color.white);
human2.setSelected(true);
ai2 = new JRadioButton("AI");
ai2.setOpaque(false);
ai2.setForeground(Color.white);
ButtonGroup bg1 = new ButtonGroup();
ButtonGroup bg2 = new ButtonGroup();
bg1.add(human1);
bg1.add(ai1);
bg2.add(human2);
bg2.add(ai2);
JPanel infos4 = new JPanel();
infos4.setOpaque(false);
JPanel player1 = new JPanel();
player1.setOpaque(false);
JPanel player2 = new JPanel();
player2.setOpaque(false);
player1.setLayout(new BoxLayout(player1,BoxLayout.PAGE_AXIS));
player2.setLayout(new BoxLayout(player2,BoxLayout.PAGE_AXIS));
player1.add(pl1);
player1.add(human1);
player1.add(ai1);
player2.add(pl2);
player2.add(human2);
player2.add(ai2);
infos4.setLayout(new BoxLayout(infos4,BoxLayout.LINE_AXIS));
infos4.add(Box.createHorizontalGlue());
infos4.add(player1);
infos4.add(Box.createRigidArea(new Dimension(150,0)));
infos4.add(player2);
infos4.add(Box.createHorizontalGlue());
infos4.setMaximumSize(new Dimension(600,75));
JLabel infoMapLabel = new JLabel(" Map");
infoMapLabel.setForeground(Color.white);
infoMapLabel.setFont(MenuButton.font2.deriveFont((float) 45));
JLabel infoSizeLabel = new JLabel(" Size");
infoSizeLabel.setForeground(Color.white);
infoSizeLabel.setFont(MenuButton.font2.deriveFont((float) 45));
JLabel infoDateLabel = new JLabel(" Date of creation");
infoDateLabel.setForeground(Color.white);
infoDateLabel.setFont(MenuButton.font2.deriveFont((float) 45));
int numberParty = saves.length;
infoMap = new String[numberParty];
infoSize = new String[numberParty];
infoDate = new String[numberParty];
int iter = 0;
for (String party : saves){
try{
BufferedReader reader = new BufferedReader(new FileReader(new File(directory+"/"+party+"/Map.txt")));
infoMap[iter] = " "+reader.readLine()+" ";
infoSize[iter] = " "+reader.readLine()+" ";
reader = new BufferedReader(new FileReader(new File(directory+"/"+party+"/data.txt")));
infoDate[iter] = " "+reader.readLine();
} catch (Exception e){
e.printStackTrace();
infoMap[iter] = "N/A";
infoSize[iter] = "N/A";
infoDate[iter] = "N/A";
} finally {
iter++;
}
}
infoMapDisplayed = new JLabel(infoMap[0]);
infoMapDisplayed.setFont(MenuButton.font2.deriveFont((float) 35));
infoMapDisplayed.setForeground(Color.white);
infoSizeDisplayed = new JLabel(infoSize[0]);
infoSizeDisplayed.setFont(MenuButton.font2.deriveFont((float) 35));
infoSizeDisplayed.setForeground(Color.white);
infoDateDisplayed = new JLabel(infoDate[0]);
infoDateDisplayed.setFont(MenuButton.font2.deriveFont((float) 35));
infoDateDisplayed.setForeground(Color.white);
JPanel infos1 = new JPanel();
infos1.setLayout(new BoxLayout(infos1,BoxLayout.LINE_AXIS));
infos1.setMaximumSize(new Dimension(600,30));
infos1.add(infoMapLabel);
infos1.add(Box.createRigidArea(new Dimension(160,0)));
infos1.add(infoMapDisplayed);
infos1.setOpaque(false);
JPanel infos2 = new JPanel();
infos2.setLayout(new BoxLayout(infos2,BoxLayout.LINE_AXIS));
infos2.setMaximumSize(new Dimension(600,30));
infos2.add(infoSizeLabel);
infos2.add(Box.createRigidArea(new Dimension(160,0)));
infos2.add(infoSizeDisplayed);
infos2.setOpaque(false);
JPanel infos3 = new JPanel();
infos3.setLayout(new BoxLayout(infos3,BoxLayout.LINE_AXIS));
infos3.setMaximumSize(new Dimension(600,30));
infos3.add(infoDateLabel);
infos3.add(Box.createRigidArea(new Dimension(40,0)));
infos3.add(infoDateDisplayed);
infos3.setOpaque(false);
infos.add(Box.createRigidArea(new Dimension(0,10)));
infos.add(infos1);
infos.add(infos2);
infos.add(infos3);
infos.add(Box.createRigidArea(new Dimension(0,5)));
infos.add(infos4);
infos.add(Box.createRigidArea(new Dimension(0,10)));
infos.add(buttons);
JPanel levelContent = new JPanel();
levelContent.setLayout(new BoxLayout(levelContent,BoxLayout.PAGE_AXIS));
levelContent.add(name);
levelContent.add(Box.createRigidArea(new Dimension(0,20)));
levelContent.add(levelSelection);
levelContent.add(Box.createRigidArea(new Dimension(0,10)));
levelContent.add(infos);
levelContent.setPreferredSize(new Dimension(540,400));
levelContent.setOpaque(false);
JPanel centerLevels = new JPanel();
centerLevels.setLayout(new BoxLayout(centerLevels,BoxLayout.LINE_AXIS));
centerLevels.add(Box.createHorizontalGlue());
centerLevels.add(levelContent);
centerLevels.add(Box.createHorizontalGlue());
centerLevels.setOpaque(false);
newGame = new MenuBackground("img/longforest.jpg");
newGame.setLayout(new BoxLayout(newGame,BoxLayout.PAGE_AXIS));
newGame.add(Box.createVerticalGlue());
newGame.add(centerLevels);
newGame.add(Box.createVerticalGlue());
newGame.setOpaque(false);
}
class Start implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
class Back implements ActionListener{
public void actionPerformed(ActionEvent e) {
w.setContentPane(ScreenMenu.getScreenMenu(w));
}
}
class LevelSelection implements ActionListener{
public void actionPerformed(ActionEvent e) {
infoMapDisplayed.setText(infoMap[levelSelection.getSelectedIndex()]);
infoSizeDisplayed.setText(infoSize[levelSelection.getSelectedIndex()]);
infoDateDisplayed.setText(infoDate[levelSelection.getSelectedIndex()]);
}
}
private static NewGame screen = new NewGame();
public static MenuBackground getNewGame(){
return newGame;
}
} |
package lt.kaunascoding.web.model;
import lt.kaunascoding.web.model.mysql.classes.Category;
import lt.kaunascoding.web.model.mysql.classes.News;
import java.util.List;
public class NewsRow {
private Category kategorija;
private List<News> bignews;
private List<List<List<News>>> smallnews;
public NewsRow() {
}
public NewsRow(Category kategorija, List<News> bignews, List<List<List<News>>> smallnews) {
this.kategorija = kategorija;
this.bignews = bignews;
this.smallnews = smallnews;
}
public Category getKategorija() {
return kategorija;
}
public void setKategorija(Category kategorija) {
this.kategorija = kategorija;
}
public List<News> getBignews() {
return bignews;
}
public void setBignews(List<News> bignews) {
this.bignews = bignews;
}
public List<List<List<News>>> getSmallnews() {
return smallnews;
}
public void setSmallnews(List<List<List<News>>> smallnews) {
this.smallnews = smallnews;
}
}
|
package com.tencent.mm.plugin.appbrand.dynamic.ui;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.tencent.mm.ipcinvoker.f;
import com.tencent.mm.ipcinvoker.type.IPCString;
import com.tencent.mm.plugin.appbrand.collector.c;
import com.tencent.mm.plugin.appbrand.dynamic.ui.WxaWidgetPerformanceUI.e;
class WxaWidgetPerformanceUI$2 implements OnClickListener {
final /* synthetic */ WxaWidgetPerformanceUI fxY;
final /* synthetic */ TextView fxZ;
WxaWidgetPerformanceUI$2(WxaWidgetPerformanceUI wxaWidgetPerformanceUI, TextView textView) {
this.fxY = wxaWidgetPerformanceUI;
this.fxZ = textView;
}
public final void onClick(View view) {
String stringBuilder = c.rx("jsapi_draw_canvas").toString();
StringBuilder stringBuilder2 = new StringBuilder();
if (stringBuilder != null && stringBuilder.length() > 0) {
stringBuilder2.append("data size :").append(c.bb("jsapi_draw_canvas", "__invoke_jsapi_data_size")).append("\n").append(stringBuilder);
}
IPCString iPCString = (IPCString) f.a("com.tencent.mm:support", new IPCString("widget_launch"), e.class);
if (iPCString != null) {
stringBuilder2.append("\n\n").append(iPCString);
}
if (com.tencent.mm.plugin.appbrand.collector.f.ads()) {
stringBuilder2.append("\n\n").append(com.tencent.mm.plugin.appbrand.collector.f.adt());
}
this.fxZ.setText(stringBuilder2.toString());
}
}
|
package com.nuuedscore.domain;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import com.nuuedscore.refdata.RefBloom;
import com.nuuedscore.refdata.RefLearningPersonality;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
/**
* Teacher Resource
* Any Resource for a Teacher
*
* @author PATavares
* @since Feb 2021
*
*/
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@ToString
@Entity
public class TeacherResource extends BaseDomain {
private static final long serialVersionUID = -1713364144496580084L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
private String topic;
/*
@Enumerated(EnumType.STRING)
private RefScore score;
*/
@Enumerated(EnumType.STRING)
@Column(name = "learning_personality")
private RefLearningPersonality learningPersonality;
@Enumerated(EnumType.STRING)
private RefBloom bloom;
private String subject;
private String name;
private String resource;
@Column(name = "created_on")
private LocalDateTime createdOn;
public TeacherResource(String topic, /*String score,*/ String learningPersonality, String bloom, String subject, String name, String resource) {
this(topic, /*RefScore.get(score),*/ RefLearningPersonality.get(learningPersonality), RefBloom.get(bloom), subject, name, resource);
}
public TeacherResource(String topic, /*RefScore score,*/ RefLearningPersonality learningPersonality, RefBloom bloom, String subject, String name, String resource) {
this.topic = topic;
//this.score = score;
this.learningPersonality = learningPersonality;
this.bloom = bloom;
this.subject = subject;
this.name = name;
this.resource = resource;
}
/*
* LifeCycle
*/
@PrePersist
public void prePersist() {
log.info("prePersist...");
this.setCreatedOn(LocalDateTime.now());
}
} |
package com.webcloud.model;
public class Atom {
private String createTime;
private String iconUrl;
private String name;
private int type;
private String comments;
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
|
package com.scmaster.milanmall.member.vo;
public class MallMember {
private String member_id;
private String password;
private String name;
private String email;
private String address;
private String phonenum;
private String joindate;
private String outdate;
public MallMember() {
super();
}
public MallMember(String member_id, String password, String name, String email, String address, String phonenum,
String joindate, String outdate) {
super();
this.member_id = member_id;
this.password = password;
this.name = name;
this.email = email;
this.address = address;
this.phonenum = phonenum;
this.joindate = joindate;
this.outdate = outdate;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getJoindate() {
return joindate;
}
public void setJoindate(String joindate) {
this.joindate = joindate;
}
public String getOutdate() {
return outdate;
}
public void setOutdate(String outdate) {
this.outdate = outdate;
}
@Override
public String toString() {
return "MallMember [member_id=" + member_id + ", password=" + password + ", name=" + name + ", email=" + email
+ ", address=" + address + ", phonenum=" + phonenum + ", joindate=" + joindate + ", outdate=" + outdate
+ "]";
}
}
|
package mascfem;
import java.util.Scanner;
public class MascFem {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
String sexo;
String simnao;
double contM = 0.0d;
double contMs = 0.0d;
double contMn = 0.0d;
double contF = 0.0d;
double contFs = 0.0d;
double contFn = 0.0d;
double porcentF;
double porcentM;
double porcentFs;
double porcentMs;
for (int i=0;i<15;i++) {
System.out.println("M/F?");
sexo = entrada.nextLine();
if(sexo.equals("M")){
contM++;
System.out.println("S/N?");
simnao = entrada.nextLine();
if(simnao.equals("S")) {
contMs++;
}else if(simnao.equals("N")) {
contMn++;
}
}else if(sexo.equals("F")) {
contF++;
System.out.println("S/N?");
simnao = entrada.nextLine();
if(simnao.equals("S")) {
contFs++;
}else if(simnao.equals("N")) {
contFn++;
}
}
}
porcentF = contF/15.0*100.0;
porcentM = contM/15.0*100.0;
porcentFs = contFs/contF*100.0;
porcentMs = contMs/contM*100.0;
System.out.println("porcentagem fem "+contF+" "+porcentF+"%");
System.out.println("porcentagem masc "+contM+" "+porcentM+"%");
System.out.println("porcentagem fem sim "+contFs+" "+porcentFs+"%");
System.out.println("porcentagem masc sim "+contMs+" "+porcentMs+"%");
}
}
|
/*
* package com.br.springboot.webflux;
*
* import java.util.UUID;
*
* import org.springframework.boot.CommandLineRunner; import
* org.springframework.stereotype.Component;
*
* import com.br.springboot.webflux.document.Playlist; import
* com.br.springboot.webflux.repository.PlaylistRepository;
*
* import reactor.core.publisher.Flux;
*
* @Component public class DummyData implements CommandLineRunner{
*
* private final PlaylistRepository playlistRepository;
*
*
*
* public DummyData(PlaylistRepository playlistRepository) { super();
* this.playlistRepository = playlistRepository; }
*
*
*
* @Override public void run(String... args) throws Exception {
*
* playlistRepository.deleteAll() .thenMany( Flux.just("API REST Spring Boot",
* "Deploy de uma aplicação java no IBM Clould", "Java 11",
* "Web Service RESTFull", "Bean no Spring Framework") .map(name -> new
* Playlist(UUID.randomUUID().toString(), name))
* .flatMap(playlistRepository::save)).subscribe(System.out::println);
*
*
* }
*
* }
*/ |
package ru.solpro.smp.reports_excel;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
public class MainAppExcel extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Экспорт отчётов - СМП");
this.primaryStage.setMinWidth(1024);
this.primaryStage.setMinHeight(768);
this.primaryStage.getIcons().add(new Image("/img/icon_app.png"));
initRootLayout();
showMainOverview();
}
/**
* Добавляет в центральную часть основную часть приложения.
*/
private void showMainOverview() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAppExcel.class.getResource("/fxml/ViewBase.fxml"));
AnchorPane anchorPane = (AnchorPane) loader.load();
rootLayout.setCenter(anchorPane);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void stop() {
System.out.println("close app");
}
/**
* Инициализирует корневой макет.
* Создаёт сцену.
*/
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAppExcel.class.getResource("/fxml/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public BorderPane getRootLayout() {
return rootLayout;
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.zhouyi.business.core.model.xinzhen;
import lombok.Data;
import lombok.ToString;
/**
* @Author: first
* @Date: 下午2:28 2019/12/1
* @Description: 虹膜接收服务实体
**/
@Data
@ToString(callSuper = true)
public class IrisReceive extends IrisCommonsSecond{
/**
* 被采集人的人员类别
*/
private String bcjr_rylb;
/**
* 签发机关
*/
private String bcjr_zjqfjg;
/**
* 有效期限
*/
private String bcjr_zjyxqx;
/**
* 采集备注
*/
private String cjbz;
}
|
// Sun Certified Java Programmer
// Chapter 8; P665_1
// Inner Classes
class MyOuter {
class MyInner {
}
}
|
package com.philippe.app.service.files;
import java.io.IOException;
public interface FileService {
void deleteTxtFiles() throws IOException;
}
|
package cn.edu.zucc.music.service;
import cn.edu.zucc.music.model.AlbumComment;
public interface AlbumCommentService {
AlbumComment getById(int id);
}
|
package controllers;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import sample.Main;
public class DrawerController {
/**
* Different labels in the side drawer.
*/
@FXML
private Label lb_name, lb_uname, lb_mail, lb_cell;
/**
* Sets the correct text for each label.
*/
@FXML
public void initialize() {
lb_name.setText("Username: " + Main.loginData.getName());
lb_uname.setText("Name: " + Main.loginData.getUsername());
lb_mail.setText("Email address: " + Main.loginData.getMail());
lb_cell.setText("Phone number: " + Main.loginData.getCell());
}
}
|
package com.accenture.flowershop.fe.filters;
import com.accenture.flowershop.be.utils.SecurityUtils;
import com.accenture.flowershop.be.utils.UserRoleRequestWrapper;
import com.accenture.flowershop.fe.dto.UserDTO;
import com.accenture.flowershop.be.utils.MyUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "SecurityFilter", urlPatterns = "/*")
public class SecurityFilter implements Filter {
public SecurityFilter(){
}
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String servletPath = request.getServletPath();
UserDTO loginedUser = MyUtils.getLoginedUser(request.getSession());
if (servletPath.equals("/login") || servletPath.equals("/registration")) {
chain.doFilter(request, response);
return;
}
HttpServletRequest wrapRequest = request;
if (loginedUser == null) {
response.sendRedirect(wrapRequest.getContextPath() + "/login");
return;
}
if (loginedUser != null) {
String userName = loginedUser.getLogin();
String role = loginedUser.getRole();
wrapRequest = new UserRoleRequestWrapper(userName, role, request);
if (SecurityUtils.isSecurityPage(request)) {
boolean hasPermission = SecurityUtils.hasPermission(wrapRequest);
if (!hasPermission) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/view/accessDenied.jsp");
dispatcher.forward(request, response);
return;
}
}
chain.doFilter(request, response);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
|
package com.oneteam.graduationproject;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.oneteam.graduationproject.Utils.Constant;
import com.oneteam.graduationproject.Utils.NetworkUtils;
import com.oneteam.graduationproject.adapters.SkillsAdapter;
import com.oneteam.graduationproject.models.SkillModel;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import static com.oneteam.graduationproject.ProfileActivity.LOADER_ID;
public class SkillsActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private SkillsAdapter mAdapter;
@Bind(R.id.add_skill_btn)
Button addSkillBtn;
@Bind(R.id.add_skill_name_edt_txt)
EditText addSkillTitleEditTxt;
public static final int SKILLS_LOADER_ID = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skills);
ButterKnife.bind(this);
initViews();
getSupportLoaderManager().initLoader(SKILLS_LOADER_ID, null, userSkillsLoader);
addSkillBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addSkill(addSkillTitleEditTxt.getText().toString());
getSupportLoaderManager().restartLoader(SKILLS_LOADER_ID, null, userSkillsLoader);
addSkillTitleEditTxt.setText("");
}
});
}
private void addSkill(String skillName) {
JSONObject JS = new JSONObject();
try {
JS.put(Constant.SKILL_NAME, skillName);
JS.put(Constant.QUSERID, new UserSession(this).getUserDetails().get(UserSession.KEY_ID));
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, Constant.ADD_SKILL_URL, JS,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("ZOKA", "" + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("ZOKA", "" + error.toString());
}
}) {
/**
* Passing some request headers
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
getSupportLoaderManager().restartLoader(LOADER_ID, null, userSkillsLoader);
}
private void initViews() {
mRecyclerView = (RecyclerView) findViewById(R.id.skills_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
private LoaderManager.LoaderCallbacks<ArrayList<SkillModel>> userSkillsLoader =
new LoaderManager.LoaderCallbacks<ArrayList<SkillModel>>() {
@Override
public Loader<ArrayList<SkillModel>> onCreateLoader(int id, final Bundle args) {
return new AsyncTaskLoader<ArrayList<SkillModel>>(getApplicationContext()) {
ArrayList<SkillModel> briefSkillRateModelList = new ArrayList<>();
@Override
protected void onStartLoading() {
if (args != null)
deliverResult(briefSkillRateModelList);
else
forceLoad();
}
@Override
public ArrayList<SkillModel> loadInBackground() {
UserSession usersession = new UserSession(getContext());
URL skillsRequestUrl = NetworkUtils.getUserSkillsUrl(usersession.zPref.getString(usersession.KEY_ID, null));
try {
return Parser.getUSerSkills(NetworkUtils.getResponseFromHttpUrl(skillsRequestUrl));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void deliverResult(ArrayList<SkillModel> data) {
super.deliverResult(data);
}
};
}
@Override
public void onLoadFinished(Loader<ArrayList<SkillModel>> loader, final ArrayList<SkillModel> data) {
Collections.reverse(data);
mAdapter = new SkillsAdapter(data, new SkillsAdapter.onRecyclerLongClickListener() {
@Override
public void onClick(final int skillId) {
final AlertDialog dialog = new AlertDialog.Builder(SkillsActivity.this)
.create();
LayoutInflater layoutInflater = LayoutInflater.from(SkillsActivity.this);
dialog.setView(layoutInflater.inflate(R.layout.dialogue, null));
dialog.show();
Button okButton = (Button) dialog.findViewById(R.id.ok);
Button cancelButton = (Button) dialog.findViewById(R.id.cancel);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
deleteSkill(skillId);
getSupportLoaderManager().restartLoader(SKILLS_LOADER_ID, null, userSkillsLoader);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onLoaderReset(Loader<ArrayList<SkillModel>> loader) {
}
};
private void deleteSkill(int skillid) {
JSONObject JS = new JSONObject();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, Constant.REMOVE_SKILL_URL + skillid, JS,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("ZOKA", "" + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("ZOKA", "" + error.toString());
}
}) {
/**
* Passing some request headers
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
}
}
|
package com.github.astefanich.account;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import edu.uw.ext.framework.account.Account;
import edu.uw.ext.framework.account.AccountException;
import edu.uw.ext.framework.account.AccountManager;
import edu.uw.ext.framework.dao.AccountDao;
/**
* Implementation class for the {@link AccountManager} interface. The
* AccountManager is responsible for protecting account passwords as well as
* creating, deleting, authenticating, and persistence account related data.
* Instances of this class should be created via the factory.
*
* @author AndrewStefanich
*/
public class SimpleAccountManager implements AccountManager {
/**
* object utilized by account manager to get/set data from persistant memory
*/
private AccountDao accountDao;
/** holds an reference to an AccountFactory, for use in creating accounts */
private static final SimpleAccountFactory SIMPLE_ACCOUNT_FACTORY = new SimpleAccountFactory();
/** hashing algorithm for Account passwords */
private static final String HASHING_ALGORITHM = "SHA1";
/**
* Constructor for AccountManager, to utilize an AccountDao argument to
* persist/retrieve data.
*
* @param dao
* the DAO to use to persist and retrieve accounts
*/
SimpleAccountManager(final AccountDao dao) {
this.accountDao = dao;
}
/**
* Used to persist an account (updates Account info stored in the designated
* persistant memory location)
*
* @param account
* the Account to persist
* @throws AccountException
* if operation fails
*/
@Override
public void persist(final Account account) throws AccountException {
accountDao.setAccount(account);
}
/**
* Lookup an account based on account name.
*
* @param accountName
* the name of the desired Account
* @return the Account (if located).
* @throws AccountException
* if account is not found.
*/
@Override
public Account getAccount(String accountName) throws AccountException {
Account account = null;
account = accountDao.getAccount(accountName);
if (account == null) {
throw new AccountException(String.format("Unable to get Account %s; not found!", accountName));
}
account.registerAccountManager(this);
return account;
}
/**
* Remove the Account.
*
* @param accountName
* the name of the Account to remove
* @throws AccountException
* if operation fails
*/
@Override
public void deleteAccount(String accountName) throws AccountException {
accountDao.deleteAccount(accountName);
}
/**
* Creates an Account, hashes the password, registers the AccountManager,
* and persists the Account (via the DAO).
*
* @param accountName
* the name for Account to add
* @param password
* the password used to gain access to the Account
* @param balance
* the initial balance of the Account
* @return the newly created Account
* @throws AccountException
* if operation fails
*/
@Override
public Account createAccount(String accountName, String password, int balance) throws AccountException {
Account account = null;
if (accountDao.getAccount(accountName) == null) { //checks if our Account is already stored in memory
final byte[] hashedPassword = hashPassword(password);
account = SIMPLE_ACCOUNT_FACTORY.newAccount(accountName, hashedPassword, balance);
account.registerAccountManager(this);
persist(account);
return account;
} else {
throw new AccountException(String.format("Account: %s already registered..", accountName));
}
}
/**
* Hashes password, from String to byte[]
*
* @param password
* the password to hash
* @return the hashed password
*/
private static byte[] hashPassword(String password) throws AccountException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(HASHING_ALGORITHM);
messageDigest.update(password.getBytes()); //default encoding of Java 1.8 is UTF-8
return messageDigest.digest();
} catch (NoSuchAlgorithmException e) {
throw new AccountException("Unable to find hashing algorithm:", e);
}
}
/**
* Check whether a login is valid. An account must exist with the account
* name and the password must match.
*
* @param accountName
* name of Account the password is to be validated for
* @param password
* password is to be validated
* @return true if password is valid for account identified by accountName
* @throws AccountException
* if operation fails
*/
@Override
public boolean validateLogin(String accountName, String password) throws AccountException {
boolean isValid = false;
final Account account = getAccount(accountName);
if (account != null) {
final byte[] hashedPasswordArgument = hashPassword(password);
isValid = MessageDigest.isEqual(account.getPasswordHash(), hashedPasswordArgument);
}
return isValid;
}
/**
* Release any resources used by the AccountManager implementation. Once
* closed further operations on the AccountManager may fail.
*
* @throws AccountException
* if operation fails
*/
@Override
public void close() throws AccountException {
accountDao.close();
}
}
|
package com.controller;
import com.bean.CustomerMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author Feinik
* @Discription
* @Data 2018/12/25
* @Version 1.0.0
*/
@RestController
public class WebSocketController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@SubscribeMapping("/init")
public CustomerMessage init() {
System.out.println("WebSocketController.init");
CustomerMessage response = new CustomerMessage();
response.setMsg("系统初始化消息");
response.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
return response;
}
@MessageMapping("/getNotifications")
@SendTo(value = "/topic/notification")
public String notification() {
System.out.println("WebSocketController.notification");
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
return new String("系统广播消息:号外、号外..." + time);
}
@MessageMapping("/getUserInfo")
public void getUserInfo(CustomerMessage customerMessage) {
System.out.println("WebSocketController.getUserInfo");
Map<String, Object> map = new HashMap<>(1);
map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
CustomerMessage resp = new CustomerMessage(customerMessage.getUserName(), "用户详情信息", time);
messagingTemplate.convertAndSendToUser(customerMessage.getUserName(), "/queue/userInfo", resp, map);
}
@MessageMapping("/errorTest")
public void errorTest(CustomerMessage message) {
System.out.println("WebSocketController.errorTest:" + message.getUserName());
System.out.println(1/0);
}
/**
* 可将@MessageMapping、@SubscribeMapping等注解的方法中的参数
* 带入@MessageExceptionHandler注解的方法中
* @param exception
* @param message
* @return
*/
@MessageExceptionHandler
public void error(Throwable exception, CustomerMessage message) {
//如果提供了身份认证实现,可以通过在此方法上注解@SendToUser("/queue/error")即可
messagingTemplate.convertAndSendToUser(message.getUserName(), "/queue/error", exception.getMessage());
}
}
|
package com.wzy.class5;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author wzy
* @title: Test
* @description: TODO
* @date 2019/7/20 14:09
*/
public class Test {
/**
* spring默认自动装配策略是AUTOWIRE_NO,AUTOWIRE_NO自动装配策略采用的是byType技术
* spring自动装配策略:AUTOWIRE_NO AUTOWIRE_BY_NAME AUTOWIRE_BY_TYPE AUTOWIRE_CONSTRUCTOR
*/
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(Config.class);
OrderService orderService = (OrderService) context.getBean("order");
System.out.println(orderService.getName());
OrderService orderService1 = (OrderService) context.getBean("orderChild");
System.out.println(orderService1.getName());
/**
* 如果一个类指定了factory-method,那么spring实例化出来的对象就为factory-method返回的对象
*/
System.out.println(context.getBean("demoService").getClass().getName());
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.ep;
import org.overlord.rtgov.common.service.Service;
/**
* This interface provides services to the EventProcessor
* implementations that process the events.
*
*/
public interface EPContext {
/**
* This method is used to pass a result, obtained
* from processing an event, back to the environment
* managing the event processing.
*
* @param result The result
*/
public void handle(Object result);
/**
* This method logs information.
*
* @param info The information
*/
public void logInfo(String info);
/**
* This method logs the warning.
*
* @param warning The warning
*/
public void logWarning(String warning);
/**
* This method logs an error.
*
* @param error The error
*/
public void logError(String error);
/**
* This method logs debug information.
*
* @param debug The debug information
*/
public void logDebug(String debug);
/**
* This method returns the named service if available.
*
* @param name The service name
* @return The service, or null if not found
*/
public Service getService(String name);
/**
* This method returns the named parameter if available.
*
* @param name The parameter name
* @return The parameter value, or null if not found
*/
public Object getParameter(String name);
}
|
package org.idea.plugin.atg.psi.reference;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.idea.plugin.atg.index.AtgIndexService;
import org.idea.plugin.atg.util.AtgComponentUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public class PipelineLinkReference extends PsiPolyVariantReferenceBase<XmlAttributeValue> {
public PipelineLinkReference(@NotNull XmlAttributeValue element) {
super(element);
}
@Override
public Object @NotNull [] getVariants() {
return new String[0];
}
@Override
public ResolveResult @NotNull [] multiResolve(boolean incompleteCode) {
PsiFile containingFile = getElement().getContainingFile();
if (!(containingFile instanceof XmlFile)) return ResolveResult.EMPTY_ARRAY;
String seekingLinkName = getElement().getValue();
PsiElement pipelineChainTag;
PsiElement attribute = getElement().getParent();
if (attribute instanceof XmlAttribute && "headlink".equals(((XmlAttribute) attribute).getName())) {
pipelineChainTag = attribute.getParent();
} else if (attribute instanceof XmlAttribute && "name".equals(((XmlAttribute) attribute).getName())) {
PsiElement pipelineLinkTag = attribute.getParent();
pipelineChainTag = pipelineLinkTag.getParent();
} else {
PsiElement transitionTag = attribute.getParent();
PsiElement pipelineLinkTag = transitionTag.getParent();
pipelineChainTag = pipelineLinkTag.getParent();
}
if (!(pipelineChainTag instanceof XmlTag)) return ResolveResult.EMPTY_ARRAY;
String seekingChainName = ((XmlTag) pipelineChainTag).getAttributeValue("name");
if (seekingChainName == null) return ResolveResult.EMPTY_ARRAY;
Project project = containingFile.getProject();
Set<XmlFile> xmlFilesWithSamePath = new HashSet<>();
xmlFilesWithSamePath.add((XmlFile) containingFile);
AtgIndexService componentsService = ServiceManager.getService(project, AtgIndexService.class);
Optional<String> xmlRelativePath = AtgComponentUtil.getXmlRelativePath((XmlFile) containingFile);
xmlRelativePath.ifPresent(s -> xmlFilesWithSamePath.addAll(componentsService.getXmlsByName(s)));
return xmlFilesWithSamePath.stream()
.map(f -> findPipelineLinkByName(seekingLinkName, seekingChainName, f))
.filter(Objects::nonNull)
.map(attr -> new PsiElementResolveResult(attr, true))
.toArray(ResolveResult[]::new);
}
private XmlAttributeValue findPipelineLinkByName(@NotNull final String seekingLinkName, @NotNull final String seekingChainName, @NotNull final XmlFile xmlFile) {
XmlTag rootTag = xmlFile.getRootTag();
if (rootTag != null) {
for (XmlTag pipelineChain : rootTag.findSubTags("pipelinechain")) {
if (seekingChainName.equals(pipelineChain.getAttributeValue("name"))) {
for (XmlTag pipelineLink : pipelineChain.findSubTags("pipelinelink")) {
XmlAttribute pipelineNameAttribute = pipelineLink.getAttribute("name");
if (pipelineNameAttribute != null && seekingLinkName.equals(pipelineNameAttribute.getValue())) {
return pipelineNameAttribute.getValueElement();
}
}
}
}
}
return null;
}
} |
package com.example.demoaoplog.entity;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@ToString
public class User {
private String name;
private Integer age;
public User(){}
}
|
package cn.ssh.search.service;
import cn.ssh.common.utils.sshResult;
public interface SearchItemService {
sshResult importAllItems();
}
|
package com.mohammad.cryptography;
import com.mohammad.cryptography.AES.Tools;
public class GF_Calculator {
private int GF_degree = 8;// GF(2^8)
private String irrPoly = "100011011";//"101100011";// X^8 + X^4 + X^3 + X + 1
public static void main(String[] args) {
Tools tool = new Tools();
GF_Calculator gfc = new GF_Calculator(8);
//System.out.println(tool.mod("00001010", "00011011")[0]);
//System.out.println(gfc.GF8_mult("01010100", "00001101"));//(x6 + x4 + x + 1)(x7 + x6 + x3 + x)
//System.out.println(tool.polynomial_long_division("100011011", "010000011",8)[0]);
//1759 550
//String[] eca = gfc.ExtendedEculedAlgorithm_GF8("100011011", "010000011");
//System.out.println(eca[0]+"\n"+eca[1]);
System.out.println(gfc.GF8_mult("00001110", "00000010"));
}
public GF_Calculator(int gF_degree) {
GF_degree = gF_degree;
}
public int getGF_degree() {
return GF_degree;
}
public void setGF_degree(int gF_degree) {
GF_degree = gF_degree;
}
public String getIrrPoly() {
return irrPoly;
}
public void setIrrPoly(String irrPoly) {
this.irrPoly = irrPoly;
}
public String add(String a, String b) {
Tools tool = new Tools();
if (tool.getDegree(a) >= GF_degree) {
a = tool.polynomial_long_division(a, irrPoly, 8)[0];
}
if (tool.getDegree(b) >= GF_degree) {
b = tool.polynomial_long_division(b, irrPoly, 8)[0];
}
while (a.length() < GF_degree) {
a = "0" + a;
}
while (b.length() < GF_degree) {
b = "0" + b;
}
return tool.Xor(a, b);
}
public String subtract(String a, String b) {
return add(a,b);
}
/*
*
* Run the following loop eight times (once per bit). It is OK to stop when a or b are zero before an iteration:
1-If the rightmost bit of b is set, exclusive OR the product p by the value of a. This is polynomial addition.
2-Shift b one bit to the right, discarding the rightmost bit, and making the leftmost bit have a value of zero. This divides the polynomial by x, discarding the x0 term.
3-Keep track of whether the leftmost bit of a is set to one and call this value carry.
4-Shift a one bit to the left, discarding the leftmost bit, and making the new rightmost bit zero. This multiplies the polynomial by x, but we still need to take account of carry which represented the coefficient of x7.
5-If carry had a value of one, exclusive or a with the hexadecimal number 0x1b (00011011 in binary). 0x1b corresponds to the irreducible polynomial with the high term eliminated. Conceptually, the high term of the irreducible polynomial and carry add modulo 2 to 0.
p now has the product
*
* */
public String GF8_mult(String A, String B) {
String a = A, b = B;
String p = "00000000", zero = "00000000";
Tools tool = new Tools();
if (tool.getDegree(a) >= GF_degree) {
a = tool.polynomial_long_division(a, irrPoly, 8)[0];
}
if (tool.getDegree(b) >= GF_degree) {
b = tool.polynomial_long_division(b, irrPoly, 8)[0];
}
while (a.length() < 8) {
a = "0" + a;
}
while (b.length() < 8) {
b = "0" + b;
}
char carry ;
while (!a.equals(zero) && !b.equals(zero)) {
//System.out.println("\tP="+p+"\ta="+a+"\tb="+b+"\tirr="+ irrPoly.substring(1));
if (b.charAt(b.length() - 1) == '1') {
p = tool.Xor(p, a);
}
b = "0"+b.substring(0, b.length()-1);// right shift
carry = a.charAt(0) ;
a = a.substring(1) + "0";
if(carry == '1'){
// System.out.println("carry= 1 ==> "+a+"\t"+ irrPoly.substring(1));
a = tool.Xor(a, irrPoly.substring(1));
}
}
//System.out.println("RESULT = "+p);
return p;
}
///return [ gcd, inverse ] as String array
public String[] ExtendedEculedAlgorithm_GF8(String a, String b){
String r_tmp_prev = a, r_tmp_curr = b, v_tmp_prev = "00000001", w_tmp_prev = "00000000",v_tmp_curr = "00000000",w_tmp_curr = "00000001";
boolean done = false;
Tools tool = new Tools();
String[] mod_tmp;
while(!done){
mod_tmp = tool.polynomial_long_division(r_tmp_prev, r_tmp_curr, 8);//tool.longDiv(r_tmp_prev, r_tmp_curr);
//System.out.println("Q = "+mod_tmp[1]+"\tr= "+mod_tmp[1]);
String q=mod_tmp[1].length() > 8 ? mod_tmp[1].substring(mod_tmp[1].length() - 8):mod_tmp[1] ,r = mod_tmp[0].length() > 8 ? mod_tmp[0].substring(mod_tmp[0].length() - 8):mod_tmp[0],
v = tool.Xor(v_tmp_prev, GF8_mult(q, v_tmp_curr)),
w = tool.Xor(w_tmp_prev, GF8_mult(q, w_tmp_curr))
;
r_tmp_prev = r_tmp_curr;
r_tmp_curr = r;
v_tmp_prev = v_tmp_curr;
v_tmp_curr = v;
w_tmp_prev = w_tmp_curr;
w_tmp_curr = w;
if(r.equals("00000000"))
done = true;
//System.out.println("ITR:\nr= "+r+"\nv= "+v+"\nw= "+w+"\nq= "+q+"\n----------------\n");
}
//System.out.println("FINAL :\ngcd= "+r_tmp_prev+"\ninvers= "+w_tmp_prev+"\n----------------\n");
return new String[]{r_tmp_prev, w_tmp_prev};
}
}
|
package com.qihoo.finance.chronus.common;
/**
* Created by xiongpu on 2019/9/25.
*/
public final class SupportConstants {
public static final String SUPPORT_NAME_BOOTSTRAP = "BootstrapSupport";
public static final String SUPPORT_NAME_MASTER = "MasterSupport";
public static final String SUPPORT_NAME_WORKER = "WorkerSupport";
public static final String MAIN = "main";
public static final String SAVE_JOB_EXEC_LOG = "saveJobExecLog";
public static final String SEND_TASK_RUNTIME_HEARTBEAT = "sendTaskRuntimeHeartbeat";
public static final String REFRESH_TASK_ASSIGN_RESULT = "refreshTaskAssignResult";
}
|
package Schaltjahr;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner enterObj = new Scanner(System.in); //how to get a scanner
System.out.printf("Bitte Jahr eingeben: ");
int year = enterObj.nextInt();
enterObj.close();
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.printf("Das Jahr %d ist ein Schaltjahr.\n", year);
} else {
System.out.printf("Das Jahr %d ist kein Schaltjahr.\n", year);
}
}
}
|
package com.xaut.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xaut.dao.MagneticDao;
import com.xaut.daoimpl.MagneticDaoImpl;
@SuppressWarnings("serial")
public class MagneticServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
MagneticDao dao = new MagneticDaoImpl();
String szImei = request.getParameter("szImei");
double x = Double.parseDouble(request.getParameter("X"));
double y = Double.parseDouble(request.getParameter("Y"));
double z = Double.parseDouble(request.getParameter("Z"));
boolean result = dao.Sample(szImei, x, y, z);
out.print(result);
out.flush();//清理servlet容器的缓冲区
out.close();//关闭输出流对象,释放输出流资源
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
|
package br.com.controller;
public class Controller {
}
|
/*
* 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.
*/
/**
*
* @author missa
*/
public class DialogoIP extends javax.swing.JDialog {
Conexion conexion;
/**
* Creates new form DialogoIP
*/
public static Conexion mostrarIniciarServidor(java.awt.Frame parent) {
DialogoIP formulario = new DialogoIP(parent, true);
formulario.setVisible(true);
return formulario.conexion;
}
private DialogoIP(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(parent);
conexion = new Conexion();
lblIP.setText("Esta es tu direccion IP n\""+ conexion.obtenerIPsLocales());
Thread hilo = new Thread(new Runnable(){
@Override
public void run() {
conexion.esperarConexion(5000);
if(conexion.estado){
cerrar();
}
}
});
hilo.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
lblIP = new javax.swing.JLabel();
btnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Tu direccion IP es:");
btnCancelar.setText("Cancelar");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(91, 91, 91)
.addComponent(lblIP, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(btnCancelar)))
.addGap(135, 135, 135))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(lblIP, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addGap(79, 79, 79)
.addComponent(btnCancelar)
.addGap(99, 99, 99))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
this.dispose();
}//GEN-LAST:event_btnCancelarActionPerformed
public void cerrar(){
this.dispose();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel lblIP;
// End of variables declaration//GEN-END:variables
}
|
// Generated by view binder compiler. Do not edit!
package com.example.radio.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;
import com.example.radio.R;
import java.lang.NullPointerException;
import java.lang.Override;
import java.lang.String;
public final class ActivityEmployeDetailsBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final RecyclerView recyclerviewEmpDetails;
private ActivityEmployeDetailsBinding(@NonNull ConstraintLayout rootView,
@NonNull RecyclerView recyclerviewEmpDetails) {
this.rootView = rootView;
this.recyclerviewEmpDetails = recyclerviewEmpDetails;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ActivityEmployeDetailsBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ActivityEmployeDetailsBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_employe_details, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ActivityEmployeDetailsBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.recyclerviewEmpDetails;
RecyclerView recyclerviewEmpDetails = rootView.findViewById(id);
if (recyclerviewEmpDetails == null) {
break missingId;
}
return new ActivityEmployeDetailsBinding((ConstraintLayout) rootView, recyclerviewEmpDetails);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
|
package com.mytravels.flights.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
@Configuration
public class SkyScannerWebConfig {
@Value("${skyscanner.api.host}")
private String skyScannerApiHost;
@Value("${skyscanner.api.key}")
private String skyScannerApiKey;
@Bean
public RestTemplate skyScannerRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList((httpRequest, bytes, clientHttpRequestExecution) -> {
HttpHeaders headers = httpRequest.getHeaders();
headers.put("X-RapidAPI-Host", Collections.singletonList(skyScannerApiHost));
headers.put("X-RapidAPI-Key", Collections.singletonList(skyScannerApiKey));
return clientHttpRequestExecution.execute(httpRequest, bytes);
}));
return restTemplate;
}
}
|
package com.pedidovenda.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.pedidovenda.model.Cliente;
import com.pedidovenda.repository.ClienteRepository;
import com.pedidovenda.util.cdi.CDIServiceLocator;
@FacesConverter(forClass=Cliente.class)
public class ClienteConverter implements Converter {
private ClienteRepository clienteRepository;
public ClienteConverter() {
this.clienteRepository = CDIServiceLocator.getBean(ClienteRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return (value != null) ? clienteRepository.getById(new Long(value)) : null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value != null){
Cliente cliente = (Cliente) value;
return ( cliente.getId() == null ) ? null : cliente.getId().toString();
}
return "";
}
} |
package com.jlgproject.activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jlgproject.R;
import com.jlgproject.base.BaseActivity;
/**
* 我的佣金
*/
public class MyCommission extends BaseActivity implements View.OnClickListener {
private TextView mTv_Title_comm;
private ImageView mIv_Title_left_comm;
private LinearLayout mLl_ivParent_title_Wallet;
@Override
public int loadWindowLayout() {
return R.layout.activity_my_commission;
}
@Override
public void initViews() {
//动态设置标题
mTv_Title_comm = (TextView) findViewById(R.id.tv_title_name);
mTv_Title_comm.setText(getResources().getText(R.string.my_commission));
mIv_Title_left_comm = (ImageView) findViewById(R.id.iv_title_left);
mIv_Title_left_comm.setVisibility(View.VISIBLE);
mLl_ivParent_title_Wallet = (LinearLayout) findViewById(R.id.ll_ivParent_title);
mLl_ivParent_title_Wallet.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == mLl_ivParent_title_Wallet) {
finish();
}
}
}
|
package eiti.sag.facebookcrawler.accessor.jsoup;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import static java.util.stream.Collectors.joining;
class JsoupHtmlGetter implements HtmlPageGetter {
private final Map<String, String> cookies;
private final Locale locale;
JsoupHtmlGetter(Map<String, String> cookies, Locale locale) {
this.cookies = cookies;
this.locale = locale;
}
@Override
public String get(String url) throws IOException {
Connection connection = prepareConnection(url);
Document document = connection.get();
return prepareDocument(document);
}
private Connection prepareConnection(String url) {
return Jsoup.connect(url)
.ignoreContentType(true)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36")
.cookies(cookies)
.cookie("locale", locale.toString());
}
private String prepareDocument(Document document) {
return document.body().children().stream()
.filter(e -> !isScriptTag(e))
.map(Element::toString)
.map(this::removeHtmlComments)
.collect(joining());
}
private boolean isScriptTag(Element e) {
return e.tagName().equals("script");
}
private String removeHtmlComments(String text) {
return text.replaceAll("<!-- | -->", "");
}
}
|
package com.authenticationservice.db.repository;
import com.authenticationservice.db.entity.RoleEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RoleRepository extends CrudRepository<RoleEntity, Long> {
} |
package com.jack.jkbase.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jack.jkbase.entity.SysUser;
import com.jack.jkbase.entity.SysUserRole;
import com.jack.jkbase.entity.ViewSysUser;
import com.jack.jkbase.mapper.SysUserRoleMapper;
import com.jack.jkbase.service.ISysUserRoleService;
/**
* <p>
* 服务实现类
* </p>
*
* @author LIBO
* @since 2020-09-23
*/
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {
public boolean removeByKey(SysUserRole entity) {
return remove(Wrappers.lambdaQuery(entity));
}
public boolean deleteByUserid(int userid) {
return remove(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getrUserid, userid));
}
public boolean deleteByRoleid(int roleid) {
return remove(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getrRoleid, roleid));
}
/**
* 根据用户id查找角色id列表
*/
public List<SysUserRole> selectByUserid(int userid){
return list(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getrUserid, userid));
}
/**
* 批量添加某角色的用户列表
*/
public boolean insertbatchForRole(int[] users,int roleid) {
List<SysUserRole> list = new ArrayList<>();
for(int userid:users) {
list.add(new SysUserRole(userid, roleid));
}
return saveBatch(list);
}
/**
* 批量添加某用户的角色列表
*/
@Transactional
public boolean insertbatchForUser(int userid,int[] roleids) {
deleteByUserid(userid);//先删除
List<SysUserRole> list = new ArrayList<>();
for(int roleid:roleids) {
list.add(new SysUserRole(userid, roleid));
}
return saveBatch(list);
}
}
|
package com.sunsun.nbapic.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.kugou.framework.component.base.ImageAdapter;
import com.sunsun.nbapic.activity.ViewPagerZoomActivity;
import com.sunsun.nbapic.bean.ChinaMainPhotosTable;
import com.sunsun.nbaproject.R;
public class ChinaMainPhotosAdapter extends ImageAdapter<ChinaMainPhotosTable> {
public final int STYLE_ONE = 0;
public ChinaMainPhotosAdapter(Context context) {
super(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int itemViewType = getItemViewType(position);
if (convertView == null) {
convertView = getConvertView(itemViewType);
}
holder = (ViewHolder) convertView.getTag();
ChinaMainPhotosTable item = getItem(position);
updateCorner(holder, item, convertView);
return convertView;
}
private void updateCorner(ViewHolder holder, ChinaMainPhotosTable item,
View convertView) {
if (item == null) {
return;
}
displayImage(item.getPicUrl(), holder.imageview);
if (!TextUtils.isEmpty(item.getTitle())) {
holder.title.setText(item.getTitle());
}
if (!TextUtils.isEmpty(item.getDate())) {
holder.date.setText(item.getDate());
}
holder.view.setOnClickListener(new OnClickItem(item));
}
class OnClickItem implements OnClickListener {
ChinaMainPhotosTable item;
public OnClickItem(ChinaMainPhotosTable item) {
this.item = item;
}
@Override
public void onClick(View v) {
// Toast.makeText(mContext, item.getJumpUrl(), Toast.LENGTH_SHORT)
// .show();
if(item!=null&&!TextUtils.isEmpty(item.getJumpUrl())){
ViewPagerZoomActivity.startViewPagerZoomActivity(mContext,
item.getJumpUrl());
}
}
}
private View getConvertView(int itemViewType) {
ViewHolder holder = null;
View convertView = null;
switch (itemViewType) {
case STYLE_ONE:
convertView = mInflater.inflate(R.layout.china_main_photos_layout,
null);
holder = new ViewHolder();
holder.view = convertView;
holder.imageview = (ImageView) convertView
.findViewById(R.id.imageview);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.date = (TextView) convertView.findViewById(R.id.date);
break;
default:
break;
}
if (convertView != null) {
convertView.setTag(holder);
}
return convertView;
}
@Override
public int getItemViewType(int position) {
return 0;
}
public int getViewTypeCount() {
return 1;
}
private static class ViewHolder {
View view;
ImageView imageview;
TextView title;
TextView date;
}
}
|
package com.vilio.pcfs.service.inner;
import com.vilio.pcfs.dao.PushMessageDao;
import com.vilio.pcfs.exception.ErrorException;
import com.vilio.pcfs.glob.GlobParam;
import com.vilio.pcfs.glob.ReturnCode;
import com.vilio.pcfs.service.BaseService;
import com.vilio.pcfs.service.Pcfs000025;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 类名: Pcfs000027<br>
* 功能:接受内部推送消息批量插入数据库<br>
* 版本: 1.0<br>
* 日期: 2017年8月4日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
* 注:
*/
@Service
public class Pcfs000027 extends BaseService {
private static final Logger logger = Logger.getLogger(Pcfs000025.class);
@Resource
private PushMessageDao pushMessageDao;
/**
* 参数验证
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
if (body.get("messageList") == null || ((List) body.get("messageList")).size() <= 0) {
throw new ErrorException(ReturnCode.MESSAGE_LIST_FAIL, "");
}
}
/**
* 主业务流程
*
* @param head
* @param body
*/
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception {
List<Map> messageList = (List) body.get("messageList");
for (Map messageInfo : messageList) {
messageInfo.put(GlobParam.PARAM_SYSTEM_NO, head.get(GlobParam.PARAM_SYSTEM_NO));
}
int result = pushMessageDao.insertPushMessagesList(messageList);
if (result <= 0) {
throw new ErrorException(ReturnCode.UPDATE_FAIL, "");
}
}
}
|
package com.mogujie.videotest;
import android.view.View;
import android.view.ViewGroup;
/**
* @author zijiao
* @version 16/5/23
* @Mark
*/
public class ViewHolder {
private static View sView;
public static void attachView(View view) {
if (view == null) {
return;
}
if (view.getParent() != null) {
((ViewGroup)view.getParent()).removeView(view);
}
sView = view;
}
public static View detach() {
View view = sView;
sView = null;
return view;
}
}
|
package com.example.dataaccessmybatis.config;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource db = new DriverManagerDataSource();
db.setDriverClassName("org.postgresql.Driver");
db.setUrl("jdbc:postgresql://localhost:5432/mybatis");
db.setUsername("postgres");
db.setPassword("1234");
return db;
}
}
|
package sample;
import java.util.ArrayList;
import java.util.List;
public class Clazz {
private String stereotype; // class, enum, interface
private String nameSpace; // package
private String name; // class name
private List<String> metohds;
private List<String> variables;
private List<String> implementations;
private List<String> imports; // import + text from list + ;
private Clazz() {
}
public String getStereotype() {
return stereotype;
}
public void setStereotype(String stereotype) {
this.stereotype = stereotype;
}
public String getNameSpace() {
return nameSpace;
}
public void setNameSpace(String nameSpace) {
this.nameSpace = nameSpace;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getMetohds() {
return metohds;
}
public void setMetohds(List<String> metohds) {
this.metohds = metohds;
}
public List<String> getVariables() {
return variables;
}
public List<String> getImports() {
return imports;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
public void setVariables(List<String> variables) {
this.variables = variables;
}
public List<String> getImplementations() {
return implementations;
}
public void setImplementations(List<String> implementations) {
this.implementations = implementations;
}
public void addImplementation(String implementation) {
if (implementations == null) {
implementations = new ArrayList<>();
}
implementations.add(implementation);
}
public void addImport(String import_string) {
if (imports == null) {
imports = new ArrayList<>();
}
if(imports.contains(import_string))return;
imports.add(import_string);
}
@Override
public String toString() {
return "Clazz{" +
"stereotype='" + stereotype + '\'' +
", nameSpace='" + nameSpace + '\'' +
", name='" + name + '\'' +
", metohds=" + metohds +
", variables=" + variables +
", implementations=" + implementations +
", imports=" + imports +
'}';
}
public static class Builder {
private String stereotype;
private String nameSpace;
private String name;
private List<String> metohds;
private List<String> variables;
private List<String> implementations;
private List<String> imports;
private Builder() {
}
public static Builder aClazz() {
return new Builder();
}
public Builder withStereotype(String stereotype) {
this.stereotype = stereotype;
return this;
}
public Builder withNameSpace(String nameSpace) {
this.nameSpace = nameSpace;
return this;
}
public Builder withName(String name) {
this.name = name;
return this;
}
public String getName(){
return name;
}
public Builder withMetohds(List<String> metohds) {
this.metohds = metohds;
return this;
}
public Builder withVariables(List<String> variables) {
this.variables = variables;
return this;
}
public Builder withImplementations(List<String> implementations) {
this.implementations = implementations;
return this;
}
public Builder withImports(List<String> imports) {
this.imports = imports;
return this;
}
public Builder addImport(String imp){
if(imports == null) imports = new ArrayList<>();
imports.add(imp);
return this;
}
public Clazz build() {
Clazz clazz = new Clazz();
clazz.setStereotype(stereotype);
clazz.setNameSpace(nameSpace);
clazz.setName(name);
clazz.setMetohds(metohds);
clazz.setVariables(variables);
clazz.setImplementations(implementations);
clazz.setImports(imports);
return clazz;
}
}
}
|
package edu.gatech.cse6242;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.chain.ChainMapper;
import org.apache.hadoop.mapreduce.lib.chain.ChainReducer;
import org.apache.hadoop.util.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
public class Q4 {
private static final String TEMP_PATH = "difference_temp_output";
public static class differenceMapper extends Mapper<Object, Text, IntWritable, IntWritable>{
private final static IntWritable plusOne = new IntWritable(1);
private final static IntWritable minusOne = new IntWritable(-1);
private IntWritable source = new IntWritable();
private IntWritable target = new IntWritable();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString(), "\n");
while (itr.hasMoreTokens()) {
String record[] = itr.nextToken().split("\t");
source.set(Integer.parseInt(record[0]));
target.set(Integer.parseInt(record[1]));
context.write(source, plusOne);
context.write(target, minusOne);
}
}
}
public static class differenceReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(IntWritable key, Iterable<IntWritable> values, Context context
) throws IOException, InterruptedException {
int differenceValue = 0;
for (IntWritable value : values) {
differenceValue += value.get();
}
result.set(differenceValue);
context.write(key, result);
}
}
public static class countMapper extends Mapper<Object, Text, IntWritable, IntWritable>{
private IntWritable difference = new IntWritable();
private final static IntWritable plusOne = new IntWritable(1);
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString(), "\n");
while (itr.hasMoreTokens()) {
String record[] = itr.nextToken().split("\t");
difference.set(Integer.parseInt(record[1]));
context.write(difference, plusOne);
}
}
}
public static class countReducer extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(IntWritable key, Iterable<IntWritable> values, Context context
) throws IOException, InterruptedException {
int differenceCount = 0;
for (IntWritable value : values) {
differenceCount += value.get();
}
result.set(differenceCount);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Path inputPath = new Path(args[0]);
Path tempPath = new Path(TEMP_PATH);
Path outputPath = new Path(args[1]);
/* first mapreduce to get difference in degree */
Job diffJob = Job.getInstance(conf, "difference");
diffJob.setJarByClass(Q4.class);
FileInputFormat.addInputPath(diffJob, inputPath);
FileOutputFormat.setOutputPath(diffJob, tempPath);
diffJob.setMapperClass(differenceMapper.class);
diffJob.setCombinerClass(differenceReducer.class);
diffJob.setReducerClass(differenceReducer.class);
diffJob.setOutputKeyClass(IntWritable.class);
diffJob.setOutputValueClass(IntWritable.class);
if(!diffJob.waitForCompletion(true))
System.exit(1);
/* second mapreduce to get difference count */
Job countJob = Job.getInstance(conf, "count");
countJob.setJarByClass(Q4.class);
FileInputFormat.addInputPath(countJob, tempPath);
FileOutputFormat.setOutputPath(countJob, outputPath);
countJob.setMapperClass(countMapper.class);
countJob.setCombinerClass(countReducer.class);
countJob.setReducerClass(countReducer.class);
countJob.setOutputKeyClass(IntWritable.class);
countJob.setOutputValueClass(IntWritable.class);
boolean runningStatus = countJob.waitForCompletion(true);
FileSystem configuredFS = FileSystem.get(conf);
configuredFS.delete(tempPath, true);
System.exit(runningStatus ? 0 : 1);
}
} |
package com.example.jmchugh.rxmvp.weather.dagger;
import com.example.jmchugh.rxmvp.app.dagger.AppComponent;
import com.example.jmchugh.rxmvp.weather.WeatherActivity;
import com.example.jmchugh.rxmvp.weather.mvp.view.WeatherView;
import dagger.Component;
/**
* Created by jmchugh on 1/12/2018.
*/
@WeatherScope
@Component(modules = WeatherModule.class, dependencies = AppComponent.class)
public interface WeatherComponent {
void inject(WeatherActivity activity);
void inject(WeatherView view);
}
|
package plp.expressions1.util;
import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static plp.expressions1.util.ToStringProvider.listToString;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class ToStringProviderTest {
@Test
public void testListToString() {
List<Integer> list = asList(1, 2, 3);
assertThat(listToString(list, "{", "}", ";"), is("{1; 2; 3}"));
assertThat(listToString(new ArrayList(), "[", "]", ","), is("[]"));
assertThat(listToString(asList(""), "[", "]", ","), is("[]"));
}
}
|
package com.drzewo97.ballotbox.panel.controller.poll;
import com.drzewo97.ballotbox.core.dto.polldto.PollDto;
import com.drzewo97.ballotbox.core.model.candidate.CandidateRepository;
import com.drzewo97.ballotbox.core.model.country.CountryRepository;
import com.drzewo97.ballotbox.core.model.district.DistrictRepository;
import com.drzewo97.ballotbox.core.model.ward.WardRepository;
import com.drzewo97.ballotbox.core.service.pollservice.PollService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
@Controller
@RequestMapping(path = "/panel/poll/create")
public class PollCreationController {
@Autowired
private CountryRepository countryRepository;
@Autowired
private DistrictRepository districtRepository;
@Autowired
private WardRepository wardRepository;
@Autowired
private PollService pollService;
@Autowired
private CandidateRepository candidateRepository;
@ModelAttribute("poll")
private PollDto pollDto(){
return new PollDto();
}
@GetMapping
private String showPollCreate(Model model){
model.addAttribute("countries", countryRepository.findAll());
model.addAttribute("districts", districtRepository.findAll());
model.addAttribute("wards", wardRepository.findAll());
model.addAttribute("allCandidates", candidateRepository.findAll());
return "panel/poll_create";
}
@PostMapping
private String createPoll(@ModelAttribute("poll") @Valid PollDto pollDto, BindingResult result){
if(pollService.existsByName(pollDto.getName())){
result.rejectValue("name", "name.exist", "Poll already exists.");
}
if(result.hasErrors()){
return "panel/poll_create";
}
//Get username
String currentPrincipalName = SecurityContextHolder.getContext().getAuthentication().getName();
pollService.save(pollDto, currentPrincipalName);
return "redirect:create?success";
}
} |
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null)
{
return true;
}
return valid(root,null, null);
}
boolean valid(TreeNode node, Integer low, Integer high)
{
if(node == null)
{
return true;
}
if(low != null)
{
if(node.val <= low)
{
return false;
}
}
if(high != null)
{
if(node.val >= high)
{
return false;
}
}
return valid(node.left, low, node.val) && valid(node.right, node.val, high);
}
} |
package de.jmda.app.uml.diagram.type.nodemanager;
import de.jmda.app.uml.shape.type.TypeBox;
class NodeManagerAggregation
{
/** constructor injection */
private NodeManagerContext context;
/** delegate, lazy initialised in {@link #getAdder()} */
private NodeManagerAggregationAdder adder;
/** delegate, lazy initialised in {@link #getRemover()} */
private NodeManagerAggregationRemover remover;
NodeManagerAggregation(NodeManagerContext context) { this.context = context; }
/** Method being called <b>after</b> {@code typeBox} had been added to pane. */
void afterAdd(TypeBox typeBox) { getAdder().afterAdd(typeBox); }
/** Method being called <b>after</b> {@code typeBox} had been removed from pane. */
void afterRemove(TypeBox typeBox) { getRemover().afterRemove(typeBox); }
private NodeManagerAggregationAdder getAdder()
{
if (adder == null) adder = new NodeManagerAggregationAdder(context);
return adder;
}
private NodeManagerAggregationRemover getRemover()
{
if (remover == null) remover = new NodeManagerAggregationRemover(context);
return remover;
}
} |
/*
Copyright 2011 Software Freedom Conservatory.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.android.library;
import org.openqa.selenium.WebDriverException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Helper methods used for reflexion.
*/
/* package */ class ReflexionHelper {
private static Method getMethod(Object obj, String name, Class[] argsClazz) {
try {
return obj.getClass().getMethod(name, argsClazz);
} catch (NoSuchMethodException e) {
try {
return obj.getClass().getDeclaredMethod(name, argsClazz);
} catch (NoSuchMethodException ex) {
throw new WebDriverException(
"The object you are using does not have "
+ "a " + name + " method", ex);
}
}
}
/* package */ static Object invoke(Object obj, String name,
Class[] argsClazz, Object[] args) {
Method method = getMethod(obj, name, argsClazz);
try {
return method.invoke(obj, args);
} catch (IllegalAccessException e) {
throw new WebDriverException(e);
} catch (InvocationTargetException e) {
throw new WebDriverException(e);
}
}
}
|
package com.dezzmeister.cryptopix.main.activities;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.dezzmeister.cryptopix.R;
import com.dezzmeister.cryptopix.main.dialogs.DialogArgs;
import com.dezzmeister.cryptopix.main.dialogs.SetPasswordDialog;
import com.dezzmeister.cryptopix.main.exceptions.SizeLimitExceededException;
import com.dezzmeister.cryptopix.main.images.ImageData;
import com.dezzmeister.cryptopix.main.secret.EncodingOptions;
import com.dezzmeister.cryptopix.main.secret.PackageHandler;
import com.dezzmeister.cryptopix.main.secret.PackageHeader;
import com.dezzmeister.cryptopix.main.secret.Payload;
import com.dezzmeister.cryptopix.main.secret.Versions;
import com.dezzmeister.cryptopix.main.session.SessionObject;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import javassist.bytecode.ByteArray;
/**
* An activity to hide a file in an image.
*
* @author Joe Desmond
* @since 1.0.0
*/
public class EncodeMessageActivity extends AppCompatActivity {
public static final String ENCODED_IMAGE_FOLDER = "encoded";
private static final int REQUEST_OPEN_FILE = 1;
private static final int REQUEST_SAVE_FILE = 2;
private SessionObject sessionObject;
private PackageHeader packageHeader;
private PackageHandler packageHandler;
private Payload payload;
private EncodingOptions encodingOptions;
private CheckBox passwordCheckbox;
private TextView fileNameView;
private Button saveFileButton;
private Button sendFileButton;
/**
* A quick hack to ensure that the password checkbox is only checked when the user supplies a password
*/
private boolean ignorePasswordCheckboxLogic = false;
private ImageData imageToSave = null;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
sessionObject = (SessionObject) intent.getSerializableExtra(DialogArgs.SESSION_OBJECT_KEY);
sessionObject.resolveImagePath();
packageHeader = (PackageHeader) intent.getSerializableExtra(DialogArgs.PACKAGE_HEADER_KEY);
packageHandler = (PackageHandler) intent.getSerializableExtra(DialogArgs.PACKAGE_HANDLER_KEY);
setContentView(R.layout.activity_encode_message);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
final AdView adView = findViewById(R.id.adView);
final AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
encodingOptions = new EncodingOptions();
encodingOptions.versionCode = Versions.THIS_VERSION;
final Button selectFileButton = findViewById(R.id.select_file);
selectFileButton.setOnClickListener(this::onSelectFile);
passwordCheckbox = findViewById(R.id.set_password);
passwordCheckbox.setChecked(false);
passwordCheckbox.setOnCheckedChangeListener(this::onSetPasswordCheckboxChanged);
final CheckBox compressFileCheckbox = findViewById(R.id.compress_file);
compressFileCheckbox.setChecked(true);
compressFileCheckbox.setOnCheckedChangeListener(this::onCompressFileCheckboxChanged);
fileNameView = findViewById(R.id.filename);
saveFileButton = findViewById(R.id.save_file);
saveFileButton.setOnClickListener(this::onSaveButtonPressed);
sendFileButton = findViewById(R.id.send_file);
sendFileButton.setOnClickListener(this::onSendButtonPressed);
disableExportFunctions();
}
private final File encodeAndSaveExternal() {
final File filesDir = getApplicationContext().getExternalFilesDir(null);
final File encodedImageDir = new File(filesDir, EncodeMessageActivity.ENCODED_IMAGE_FOLDER);
try {
final ImageData encoded = encode();
final Bitmap bitmap = Bitmap.createBitmap(encoded.pixels, encoded.width, encoded.height, Bitmap.Config.ARGB_8888);
final String fileName = System.currentTimeMillis() + ".png";
final File file = new File(encodedImageDir, fileName);
final FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
return file;
} catch (IOException e) {
e.printStackTrace();
final Toast toast = Toast.makeText(this, "Unable to save encoded image to external storage!", Toast.LENGTH_LONG);
toast.show();
}
return null;
}
private final ImageData encode() {
// TODO: Show different messages for each exception
try {
final ImageData encoded = packageHandler.encodeSecret(sessionObject.getImage(), payload, encodingOptions);
return encoded;
} catch (SizeLimitExceededException e) {
e.printStackTrace();
final Toast toast = Toast.makeText(this, "Selected file is too large!", Toast.LENGTH_SHORT);
toast.show();
return null;
} catch (Exception e) {
e.printStackTrace();
final Toast toast = Toast.makeText(this, "An unknown error occurred", Toast.LENGTH_SHORT);
toast.show();
return null;
}
}
private final void onSaveButtonPressed(final View view) {
final ImageData encodedImage = encode();
imageToSave = encodedImage;
if (encodedImage == null) {
return;
}
final long timeStamp = System.currentTimeMillis();
final String fileName = timeStamp + ".png";
final Intent intent = new Intent();
intent.setAction(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(intent, REQUEST_SAVE_FILE);
}
/**
* Encodes the {@linkplain #payload} using {@link #encodingOptions}. Creates a chooser to select an app
* to send the secret file.
*
* @param view view
*/
private final void onSendButtonPressed(final View view) {
final File encodedImage = encodeAndSaveExternal();
final Uri imageURI = Uri.fromFile(encodedImage);
final Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, imageURI);
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Send to"));
}
/**
* Disables the buttons that export the encoded file. The buttons are disabled as long as no file
* has been selected.
*/
private final void disableExportFunctions() {
saveFileButton.setVisibility(View.GONE);
saveFileButton.setClickable(false);
sendFileButton.setVisibility(View.GONE);
sendFileButton.setClickable(false);
}
/**
* Enables the buttons that export the encoded file. The buttons are enabled when a file is selected.
*/
private final void enableExportFunctions() {
saveFileButton.setVisibility(View.VISIBLE);
saveFileButton.setClickable(true);
sendFileButton.setVisibility(View.VISIBLE);
sendFileButton.setClickable(true);
}
/**
* Runs when the "Select File" button is pressed. Creates an intent to select a file of any type
* and starts an activity.
*
* @param v view
*/
private final void onSelectFile(final View v) {
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_OPEN_FILE);
}
}
private final void onSetPasswordCheckboxChanged(final CompoundButton buttonView, final boolean isChecked) {
if (!ignorePasswordCheckboxLogic) {
if (!isChecked) {
encodingOptions.password = null;
} else {
final SetPasswordDialog dialog = new SetPasswordDialog();
dialog.setCallingActivity(this);
dialog.setCancelable(false);
passwordCheckbox.setChecked(false);
dialog.show(getSupportFragmentManager(), "setPassword");
}
}
ignorePasswordCheckboxLogic = false;
}
public void setPassword(final String password) {
encodingOptions.password = password;
ignorePasswordCheckboxLogic = true;
passwordCheckbox.setChecked(true);
}
/**
* Runs when the "Compress File" checkbox is toggled.
*
* @param buttonView checkbox view
* @param isChecked true if the checkbox is checked, false if unchecked
*/
private final void onCompressFileCheckboxChanged(final CompoundButton buttonView, final boolean isChecked) {
encodingOptions.compress = isChecked;
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_OPEN_FILE: {
if (resultCode == RESULT_OK) {
final Uri contentURI = data.getData();
try {
final InputStream is = getContentResolver().openInputStream(contentURI);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
int numRead;
byte[] buffer = new byte[1024];
while ((numRead = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, numRead);
}
final byte[] payloadData = baos.toByteArray();
final String mimeType = getContentResolver().getType(contentURI);
final MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
final String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
final String timeStamp = System.currentTimeMillis() + "";
final String fileName = timeStamp + "." + extension;
payload = packageHandler.getEmptyPayload();
payload.setFileName(fileName);
payload.setMimeType(mimeType);
payload.setData(payloadData);
fileNameView.setText(fileName);
enableExportFunctions();
} catch (Exception e) {
e.printStackTrace();
final Toast toast = Toast.makeText(this, "Unable to read file!", Toast.LENGTH_SHORT);
toast.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
return;
}
case REQUEST_SAVE_FILE: {
if (resultCode == RESULT_OK) {
try (final OutputStream outputStream = getContentResolver().openOutputStream(data.getData())) {
if (outputStream != null && imageToSave != null) {
final Bitmap bitmap = Bitmap.createBitmap(imageToSave.pixels, imageToSave.width, imageToSave.height, Bitmap.Config.ARGB_8888);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
}
} catch (Exception e) {
e.printStackTrace();
final Toast toast = Toast.makeText(this, "Unable to save encoded image!", Toast.LENGTH_SHORT);
toast.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
return;
}
}
}
}
|
package com.dahua.design.behavioral.memento;
public class MementoTest {
public static void main(String[] args) {
WfGamer wfGamer = new WfGamer();
wfGamer.playGame();
Integer recordId1 = wfGamer.saveGameRecord();
System.out.println("第一次保存游戏记录 i:" + recordId1);
wfGamer.playGame();
Integer record2 = wfGamer.saveGameRecord();
System.out.println("第二次保存游戏记录 i:" + record2);
WfGamer fromGameRecord = wfGamer.getFromGameRecord(record2);
System.out.println(fromGameRecord);
}
}
|
/*
* 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 gui.panels;
import glbank.Client;
import glbank.database.ConnectionProvider;
import gui.EditClientInfoDialog;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
/**
*
* @author Martin
*/
public class ClientInfoPanel extends javax.swing.JPanel {
private Client client;
private int idc;
/**
* Creates new form ClientInfoPanel
*/
public ClientInfoPanel(int idc) {
initComponents();
this.idc = idc;
setInformationAboutSelectedClient();
}
private void setInformationAboutSelectedClient() {
client = new ConnectionProvider().getClientById(idc);
lblCity.setText(client.getCity());
lblClientId.setText("" + client.getIdc());
lblDob.setText("" + client.getDob());
lblEmail.setText(client.getEmail());
lblFirstName.setText(client.getFirstName());
lblHouseNumber.setText("" + client.getHouseNumber());
lblLastName.setText(client.getLastName());
lblPostCode.setText(client.getPostCode());
lblStreet.setText(client.getStreet());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
lblClientId = new javax.swing.JLabel();
lblFirstName = new javax.swing.JLabel();
lblLastName = new javax.swing.JLabel();
lblEmail = new javax.swing.JLabel();
lblDob = new javax.swing.JLabel();
lblStreet = new javax.swing.JLabel();
lblHouseNumber = new javax.swing.JLabel();
lblCity = new javax.swing.JLabel();
lblPostCode = new javax.swing.JLabel();
btnEditClientInformation = new javax.swing.JButton();
jLabel1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel1.setText("First Name :");
jLabel2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel2.setText("id :");
jLabel3.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel3.setText("Last Name :");
jLabel5.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel5.setText("Adress");
jLabel6.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel6.setText("Email :");
jLabel7.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel7.setText("Street :");
jLabel8.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel8.setText("House Number :");
jLabel9.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel9.setText("City :");
jLabel10.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel10.setText("Post Code :");
jLabel4.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel4.setText("Personal Information");
jLabel11.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
jLabel11.setText("Birth Date :");
lblClientId.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblClientId.setText("clientid");
lblFirstName.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblFirstName.setText("firstname");
lblLastName.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblLastName.setText("lastname");
lblEmail.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblEmail.setText("email");
lblDob.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblDob.setText("birthdate");
lblStreet.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblStreet.setText("street");
lblHouseNumber.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblHouseNumber.setText("housenumber");
lblCity.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblCity.setText("city");
lblPostCode.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblPostCode.setText("postcode");
btnEditClientInformation.setText("Edit");
btnEditClientInformation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditClientInformationActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(jLabel11))))
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblClientId)
.addComponent(lblFirstName)
.addComponent(lblLastName)
.addComponent(lblEmail))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(lblDob))
.addGap(0, 233, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(lblStreet)
.addComponent(lblHouseNumber)
.addComponent(lblCity)
.addComponent(lblPostCode)
.addComponent(btnEditClientInformation, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(90, 90, 90))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel2)
.addComponent(lblClientId)
.addComponent(lblStreet))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(lblFirstName)
.addComponent(lblHouseNumber)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel3)
.addComponent(lblLastName)
.addComponent(lblCity))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jLabel6)
.addComponent(lblEmail)
.addComponent(lblPostCode))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(lblDob)))
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(btnEditClientInformation)))
.addContainerGap(40, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnEditClientInformationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditClientInformationActionPerformed
EditClientInfoDialog editClientDialog = new EditClientInfoDialog((JFrame) this.getRootPane().getParent(), true, client);
editClientDialog.addWindowListener(new WindowAdapter(){
@Override
public void windowClosed(WindowEvent e){
try{
setInformationAboutSelectedClient();
}
catch(Exception ex){
}
}
});
editClientDialog.setLocationRelativeTo(null);
editClientDialog.setVisible(true);
}//GEN-LAST:event_btnEditClientInformationActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnEditClientInformation;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel lblCity;
private javax.swing.JLabel lblClientId;
private javax.swing.JLabel lblDob;
private javax.swing.JLabel lblEmail;
private javax.swing.JLabel lblFirstName;
private javax.swing.JLabel lblHouseNumber;
private javax.swing.JLabel lblLastName;
private javax.swing.JLabel lblPostCode;
private javax.swing.JLabel lblStreet;
// End of variables declaration//GEN-END:variables
}
|
package com.example.weq498.testfragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.logging.Handler;
public class fragment1 extends Fragment {
TextView textView2;
EditText send_add;
Button send_btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ---Inflate the layout for this fragment---
View view = inflater.inflate(R.layout.fragment1, container, false);
textView2 = (TextView) getActivity().findViewById(R.id.textView2);
send_add = (EditText) view.findViewById(R.id.send_add);
send_btn = (Button) view.findViewById(R.id.send_btn);
send_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendtwo();
Bundle bundle = getArguments();
String[] outdata;
if ((outdata = bundle.getStringArray("data")) != null) {
textView2.setText(outdata[0] + send_add.getText().toString());
} else {
Toast.makeText(getActivity(), "data failed", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public void sendtwo() {
String aid = "123456789";
Toast.makeText(getActivity(),String.format("%02X",aid.length()/2), Toast.LENGTH_SHORT).show();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
}
} |
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
public final class kd extends a {
public String bWP;
public String poH;
public String pwk;
public String rlM;
public String rlN;
public int rlO;
public String title;
public int type;
public String url;
protected final int a(int i, Object... objArr) {
int fQ;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.type);
if (this.pwk != null) {
aVar.g(2, this.pwk);
}
if (this.bWP != null) {
aVar.g(3, this.bWP);
}
if (this.title != null) {
aVar.g(4, this.title);
}
if (this.poH != null) {
aVar.g(5, this.poH);
}
if (this.url != null) {
aVar.g(6, this.url);
}
if (this.rlM != null) {
aVar.g(7, this.rlM);
}
if (this.rlN != null) {
aVar.g(8, this.rlN);
}
aVar.fT(9, this.rlO);
return 0;
} else if (i == 1) {
fQ = f.a.a.a.fQ(1, this.type) + 0;
if (this.pwk != null) {
fQ += f.a.a.b.b.a.h(2, this.pwk);
}
if (this.bWP != null) {
fQ += f.a.a.b.b.a.h(3, this.bWP);
}
if (this.title != null) {
fQ += f.a.a.b.b.a.h(4, this.title);
}
if (this.poH != null) {
fQ += f.a.a.b.b.a.h(5, this.poH);
}
if (this.url != null) {
fQ += f.a.a.b.b.a.h(6, this.url);
}
if (this.rlM != null) {
fQ += f.a.a.b.b.a.h(7, this.rlM);
}
if (this.rlN != null) {
fQ += f.a.a.b.b.a.h(8, this.rlN);
}
return fQ + f.a.a.a.fQ(9, this.rlO);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) {
if (!super.a(aVar2, this, fQ)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
kd kdVar = (kd) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
kdVar.type = aVar3.vHC.rY();
return 0;
case 2:
kdVar.pwk = aVar3.vHC.readString();
return 0;
case 3:
kdVar.bWP = aVar3.vHC.readString();
return 0;
case 4:
kdVar.title = aVar3.vHC.readString();
return 0;
case 5:
kdVar.poH = aVar3.vHC.readString();
return 0;
case 6:
kdVar.url = aVar3.vHC.readString();
return 0;
case 7:
kdVar.rlM = aVar3.vHC.readString();
return 0;
case 8:
kdVar.rlN = aVar3.vHC.readString();
return 0;
case 9:
kdVar.rlO = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package com.lesson6.sorting;
import org.junit.Test;
public class Distinct {
@Test
public void Correctness(){
int [][] A = {
{2, 1, 1, 2, 3, 1} // 3
, {1, 2, 3, 4, 5, 6} // 6
, {1, 1, 1, 4, 1, 1} // 2
, {1} // 1
, {} // 0
};
for(int idx=0 ; idx<A.length ; idx++){
String str = "answer = "+new Distinct().solution(A[idx]);
System.out.println(str);
}
}
@Test
public void Performance(){
for(int N=0;N<=5;N++){
int [] A = new int[(int)Math.pow(10, N)];
for(int i=0;i<A.length;i++){
//A[i] = ((int)(Math.random()*1000000));
A[i] = i;
//if(A[i]%2==0) A[i]=A[i]*-1;
}
long sTime = System.currentTimeMillis();
new Distinct().solution(A);
System.out.println("N = "+A.length+"\ttime = "+(System.currentTimeMillis()-sTime)+" msec");
}
}
public int solution(int[] A){
int distinctCnt = 0;
int N = A.length;
java.util.HashMap<Integer, Integer> distinctMap = new java.util.HashMap<Integer, Integer>();
for(int i=0;i<N;i++){
int n = A[i];
if(distinctMap.get(n)!=null){
}else{
distinctMap.put(n,1);
distinctCnt++;
}
}
return distinctCnt;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.