text
stringlengths 10
2.72M
|
|---|
package windowChange1;
public class SingletonCls { //delegate
private static SingletonCls sc = null;
WIndowone one;
WindowTwo two;
private SingletonCls() {
one = new WIndowone();
two = new WindowTwo();
}
public static SingletonCls getInstance() {
if(sc == null) {
sc = new SingletonCls();
}
return sc;
}
}
|
package Sekcja4.Exercise;
public class Exercise1SpeedConverter {
public static long toMilesPerHour(double kilometersPerHour){
return kilometersPerHour >= 0 ? Math.round(kilometersPerHour/1.609) : -1;
}
public static void printConversion(double kilometersPerHour) {
System.out.println(toMilesPerHour(kilometersPerHour) < 0 ? "Invalid Value" :
(kilometersPerHour + " km/h = " + toMilesPerHour(kilometersPerHour) + " mi/h"));
}
/*
if (kilometersPerHour < 0){
System.out.println("Invalid Value");
}else
System.out.println(kilometersPerHour + " km/h = " + toMilesPerHour(kilometersPerHour) + " mil/h");
*/
public static void main(String[] args) {
printConversion(1.5);
printConversion(0);
printConversion(-1);
printConversion(-10);
}
}
|
package top.docstorm.documentstormcommon.service.impl;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import top.docstorm.documentstormcommon.constant.MessageConstants;
import top.docstorm.documentstormcommon.domain.FileInfo;
import top.docstorm.documentstormcommon.exception.LogicException;
import top.docstorm.documentstormcommon.service.MessageService;
import top.docstorm.documentstormcommon.service.TransService;
import javax.annotation.Resource;
import javax.jms.Topic;
/**
* @Description:
* @author: passer
* @version:2019/9/19
*/
@Service
public class MessageServiceImpl implements MessageService {
private static final Logger LOGGER = LoggerFactory.getLogger(MessageService.class);
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private GetTransService getTransService;
@Resource(name = MessageConstants.TRANS_FILE_MESSAGE_TOPIC_NAME)
private Topic topic;
@Override
public void sendMessage(Topic topic, String message) {
try {
jmsMessagingTemplate.convertAndSend(topic, message);
LOGGER.info("发送消息成功:" + message);
} catch (Exception e) {
throw new LogicException("发送文件转换消息失败: " + message);
}
}
@Override
public void dealTransFileTopicMessage(String message) {
FileInfo fileInfo = JSON.parseObject(message, FileInfo.class);
if (fileInfo == null) {
throw new LogicException("FileInfo为空!");
}
TransService transService = getTransService.getTransService(fileInfo.getFileFormatChangeType());
transService.trans(fileInfo);
}
@Override
public void sendTransFileTopicMessage(String message) {
try {
jmsMessagingTemplate.convertAndSend(topic, message);
LOGGER.info("发送消息成功:" + message);
} catch (Exception e) {
throw new LogicException("发送文件转换消息失败: " + message);
}
}
}
|
package com.thoughtworks.tdd.models;
public class ParkingGarage {
private final int capacity;
private final String name;
private int used;
public ParkingGarage(final String name, final int capacity) {
this.name = name;
this.capacity = capacity;
}
public int getCapacity() {
return capacity;
}
public String getName() {
return name;
}
public int getUsed() {
return used;
}
public void setUsed(int used) {
this.used = used;
}
}
|
package com.atguigu.zookeeper.test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
public class TestZookeeperWatcher {
// 可以使用逗号分割集群中多个服务实例的主机名和端口号
private String connectString="hadoop101:2181,hadoop102:2181,hadoop103:2181";
//sessionTimeout 必须在 最小和最大超时时间之内才有效,否则会自动根据就近原则选择合适的时间
private int sessionTimeout=30000;
private ZooKeeper zooKeeper;
private CountDownLatch cdl=new CountDownLatch(1);
/*
* zkCli.sh -server 主机名:2181
*/
@Before
public void testConnect() throws IOException, KeeperException, InterruptedException {
// 创建一个Zookeeper客户端对象,需要提供一个默认的观察者,当执行设置观察者时,不指定其他观察者,使用默认的
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
// process()就是当 监听的节点发生了指定的事件时,自动通知watcher,调用其process方法!
@Override
public void process(WatchedEvent event) {
/*System.out.println("执行了默认观察者的回调方法!");
System.out.println(event.getPath()+"发送了事件:"+event.getType());
// 重新读取节点的内容
try {
// 持续监听,在回调方法中继续设置观察者
List<String> newData = zooKeeper.getChildren("/hi", true);
System.out.println(newData);
} catch (KeeperException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
});
}
// | ls path watch | stat path watch
@Test
public void lsWatch() throws Exception {
List<String> children = zooKeeper.getChildren("/hi", true);
System.out.println(children);
//阻塞进程
while(true) {
Thread.sleep(5000);
System.out.println("我还没死....");
}
}
// get path watch: 错误师范
@Test
public void testGetWatch() throws Exception {
byte[] data = zooKeeper.getData("/hi", new Watcher() {
// Listener线程负责,不能阻塞Linstener线程
@Override
public void process(WatchedEvent event) {
System.out.println(event.getPath()+"发生了事件:"+event.getType());
//cdl.countDown();
try {
testGetWatch();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, null);
System.out.println("当前的数据是:"+new String(data));
// 阻塞线程,当前线程阻塞,直到cdl变为0
//cdl.await();
while(true) {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"我还没死....");
}
}
public String getDataSetWatcher(String path) throws KeeperException, InterruptedException{
byte[] data = zooKeeper.getData(path, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
String newData = getDataSetWatcher(path);
System.out.println("新的数据是:"+newData);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
}, null);
return new String(data);
}
// 调用目标方法的线程阻塞
@Test
public void testgetWatch2() throws Exception {
String path="/hi";
String data = getDataSetWatcher(path);
System.out.println("当前节点的数据是"+data);
while(true) {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"我还没死....");
}
}
@Test
public void close() throws Exception {
if (zooKeeper != null) {
zooKeeper.close();
}
}
}
|
package user.com.foodexuserui;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Date;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.BasicResponseHandler;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import user.com.Entities.SignUpBean;
import user.com.commons.DobDialog;
import user.com.commons.HttpHelper;
public class SignUp extends AppCompatActivity {
EditText firstName, lastName, emailId, phoneNumber, password, confirmPassword, dobDate, addressline1, addressline2, cityName, areaName, stateName, pincodeNumber;
Calendar mcurrentDate=Calendar.getInstance();
SignUpBean bean = new SignUpBean();
Button registerButton;
HttpResponse response;
Boolean passwordFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
firstName = (EditText) findViewById(R.id.fName);
lastName = (EditText) findViewById(R.id.lName);
emailId = (EditText) findViewById(R.id.email);
phoneNumber = (EditText) findViewById(R.id.phoneNumber);
password = (EditText) findViewById(R.id.pwd);
confirmPassword = (EditText) findViewById(R.id.confirmpwd);
dobDate = (EditText)findViewById(R.id.dob);
dobDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog(SignUp.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
dobDate.setText(date);
}
}, mYear, mMonth, mDay);
mDatePicker.getDatePicker().getSpinnersShown();
mDatePicker.getDatePicker().setMaxDate(mcurrentDate.getTimeInMillis());
mDatePicker.setTitle("Select Your Birthdate");
mDatePicker.show();
}
});
registerButton = (Button) findViewById(R.id.registerbtn);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String cred1 = phoneNumber.getText().toString();
String cred2 = password.getText().toString();
SharedPreferences prefs = getSharedPreferences("UserData", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userId", cred1);
editor.putString("password", cred2);
editor.commit();
String fNameBean = firstName.getText().toString();
if (fNameBean.length() == 0) {
firstName.setError("Please enter First Name!");
}
String lNameBean = lastName.getText().toString();
if (lNameBean.length() == 0) {
lastName.setError("Please enter Last Name!");
}
String emailBean = emailId.getText().toString();
if (emailBean.length() == 0) {
emailId.setError("Please enter Email ID!");
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailBean).matches()) {
emailId.setError("Enter a valid email address");
}
String phoneBean = String.valueOf(phoneNumber.getText().toString());
if (phoneBean.length() == 0) {
phoneNumber.setError("Please enter Phone Number!");
}
if (phoneBean.length() != 10) {
phoneNumber.setError("Enter a valid Phone Number");
}
String dobBean = dobDate.getText().toString();
String passwordBean = password.getText().toString();
if (passwordBean.length() == 0) {
password.setError("Please enter Password!");
} else if (passwordBean.length() > 20 || passwordBean.length() < 8) {
password.setError("Password must be 8 - 20 characters");
}
String confirmPasswordBean = confirmPassword.getText().toString();
if (confirmPasswordBean.length() == 0) {
confirmPassword.setError("Please Confirm password!");
} else if (confirmPasswordBean.length() > 20 || confirmPasswordBean.length() < 8) {
confirmPassword.setError("Password must be 8 - 20 characters");
}
if (!passwordBean.equals(confirmPasswordBean)) {
password.setError("Password Mismatch");
confirmPassword.setError("Password Mismatch");
password.setText("");
confirmPassword.setText("");
}
else
{
passwordFlag = true;
}
SharedPreferences signupInfo = getSharedPreferences("signUpInfo", 0);
SharedPreferences.Editor signUpeditor = signupInfo.edit();
signUpeditor.putString("firstName", fNameBean);
signUpeditor.putString("lastName", lNameBean);
signUpeditor.putString("phoneNumber", phoneBean);
signUpeditor.putString("emailId", emailBean);
signUpeditor.putString("password", passwordBean);
signUpeditor.commit();
if(!fNameBean.equals("") && !lNameBean.equals("") && !phoneBean.equals("") && !emailBean.equals("")
&& !passwordBean.equals("") && !confirmPasswordBean.equals("") && passwordFlag == true) {
int SDK_INT = android.os.Build.VERSION.SDK_INT;
try {
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String responseString = null;
HttpHelper helper = new HttpHelper();
response = helper.get(("verifymobilenum?loginId=" + phoneBean + ""), SignUp.this);
responseString = new BasicResponseHandler().handleResponse(response);
if(responseString.equalsIgnoreCase("Success")) {
Intent i = new Intent(SignUp.this, SignUpAddressInfo.class);
startActivity(i.putExtra("from", "SignUp"));
}
else
{
Toast.makeText(getApplicationContext(), "Mobile Number Already Regsitered !!!",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(SignUp.this, Login.class);
startActivity(i);
}
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
/*public void onStart(){
super.onStart();
EditText dobDate = (EditText)findViewById(R.id.dob);
dobDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
DobDialog dialog = new DobDialog(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialog.show(ft,"DatePicker");
}
}
});
}*/
/* addressline1 = (EditText) findViewById(R.id.address1);
addressline2 = (EditText) findViewById(R.id.address2);
//cityName = (EditText)findViewById(R.id.city);
final Spinner citydropdown = (Spinner) findViewById((R.id.city));
//final String citybean = String.valueOf(citydropdown.getSelectedItem());
//areaName = (EditText)findViewById(R.id.area);
final Spinner areadropdown = (Spinner) findViewById((R.id.area));
//final String areabean = String.valueOf(areadropdown.getSelectedItem());
//stateName = (EditText)findViewById(R.id.state);
final Spinner statedropdown = (Spinner) findViewById((R.id.state));
final String statebean = String.valueOf(statedropdown.getSelectedItem());
*/
/* String address1bean = addressline1.getText().toString();
if (address1bean.length() == 0) {
addressline1.setError("Please enter Address !");
}
String address2bean = addressline2.getText().toString();
if (address2bean.length() == 0) {
addressline2.setError("Please enter Address !");
}
String statebean = String.valueOf(statedropdown.getSelectedItem());
String citybean = String.valueOf(citydropdown.getSelectedItem());
String areabean = String.valueOf(areadropdown.getSelectedItem());
//String citybean = cityName.getText().toString();
if (citybean.length() == 0) {
cityName.setError("Please Select City !");
}
//String areabean = areaName.getText().toString();
if (areabean.length() == 0) {
areaName.setError("Please Select Area !");
}
//String statebean = stateName.getText().toString();
if (statebean.length() == 0) {
stateName.setError("Please Select State !");
}
String pincodebean = pincodeNumber.getText().toString();
if (pincodebean.length() == 0) {
pincodeNumber.setError("Please enter Pincode!");
}
if (pincodebean.length() != 6) {
pincodeNumber.setError("Enter a valid Pincode!");
}
*/
|
package Lector8.Task8_1;
public class MainTask8_1 {
public static void main(String[] args) {
new Menu().start();
}
}
|
package info.datacluster.common.lock;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
public class ZookeeperLock implements DistributedLock {
private static final int TIME_OUT = 5;
private static final int SLEEP_TIME_MS = 1000;
private static final int MAX_RETRIES = 3;
private CuratorFramework client;
private String zk;
private String ip;
private Map<String, InterProcessMutex> mutexMap = new ConcurrentHashMap<>();
private InterProcessMutex mutex;
public ZookeeperLock(String zk){
this.zk = zk;
this.ip = getHostIp();
this.client = CuratorFrameworkFactory.builder().connectString(zk).retryPolicy(new ExponentialBackoffRetry(SLEEP_TIME_MS, MAX_RETRIES)).build();
this.client.start();
}
public String getHostIp() {
String sIP = "";
InetAddress ip = null;
try {
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
if (bFindIP)
break;
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = ips.nextElement();
if (!ip.isLoopbackAddress()
&& ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
bFindIP = true;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (null != ip)
sIP = ip.getHostAddress();
return sIP;
}
@Override
public boolean lock(String message) {
return lock(message, TIME_OUT, TimeUnit.SECONDS);
}
@Override
public boolean lock(String message, int time, TimeUnit unit) {
InterProcessMutex mutex;
if (!this.mutexMap.containsKey(message)){
String path = message;
mutex = new InterProcessMutex(this.client, path);
this.mutexMap.put(message, mutex);
}else {
mutex = this.mutexMap.get(message);
}
try {
boolean success = mutex.acquire(time, unit);
if (success){
}
return success;
} catch (Exception e){
e.printStackTrace();
throw new RuntimeException("obtain lock error " + e.getMessage() + ", path " + message);
}
}
@Override
public void release(String message) {
if (mutexMap.containsKey(message)){
InterProcessMutex mutex = mutexMap.get(message);
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package com.zc.pivas.docteradvice.entity;
import com.zc.base.common.util.StrUtil;
import com.zc.base.sys.common.util.NumberUtil;
import java.io.Serializable;
import java.util.Map;
/**
*
* 其他规则bean
*
* @author cacabin
* @version 0.1
*/
public class OtherRule implements Serializable
{
/**
* 注释内容
*/
private static final long serialVersionUID = 1L;
public OtherRule()
{
}
public OtherRule(Map<String, Object> map)
{
orId = NumberUtil.getObjLong(map.get("orId"));
orType = NumberUtil.getObjInt(map.get("orType"));
orName = StrUtil.getObjStr(map.get("orName"));
orDesc = StrUtil.getObjStr(map.get("orDesc"));
orSort = NumberUtil.getObjInt(map.get("orSort"));
enabled = NumberUtil.getObjInt(map.get("enabled"));
}
/**
* 规则id
*/
Long orId;
/**
* 规则类型
*/
Integer orType;
/**
* 规则名称
*/
String orName;
/**
* 规则描述
*/
String orDesc;
/**
* 规则排序
*/
Integer orSort;
/**
* 是否启用
*/
Integer enabled;
/**
*
*/
public Long getOrId()
{
return orId;
}
public void setOrId(Long orId)
{
this.orId = orId;
}
public Integer getOrType()
{
return orType;
}
public void setOrType(Integer orType)
{
this.orType = orType;
}
public String getOrName()
{
return orName;
}
public void setOrName(String orName)
{
this.orName = orName;
}
public String getOrDesc()
{
return orDesc;
}
public void setOrDesc(String orDesc)
{
this.orDesc = orDesc;
}
public Integer getOrSort()
{
return orSort;
}
public void setOrSort(Integer orSort)
{
this.orSort = orSort;
}
public Integer getEnabled()
{
return enabled;
}
public void setEnabled(Integer enabled)
{
this.enabled = enabled;
}
}
|
package com.zc.pivas.app.service;
import com.zc.pivas.app.bean.ScanOutputParamBean;
/**
* 配置费计算服务接口
*
* @author kunkka
* @version 1.0
*/
public interface ScanBottleService {
/**
* 处理扫描
*
* @param bottleNum 瓶签号码
* @return 收费是否成功
* @throws Exception
*/
ScanOutputParamBean scanBottleAction(String bottleNum, String strUser) throws Exception;
}
|
package Italian;
public class MargeritaPizza extends Pizza {
@Override
public double cost() {
return 250.0;
}
@Override
public String getDescription() {
return "MargeritaPizza";
}
}
|
package solution;
import problem.Range;
import math.Vector2d;
import math.Vector3d;
import problem.Problem;
public class HillClimber
{
private Problem problem;
public void initialize(Problem problem) {
this.problem = problem;
}
public Vector3d findOptima(int iterations, double stepsize, int neighbours) {
if(problem == null) {
throw new IllegalStateException("The hill climber instance has not been initialized");
}
if(iterations <= 0) {
throw new IllegalArgumentException("Number of iterations has to be positive");
}
if(neighbours <= 0) {
throw new IllegalArgumentException("Number of neighbours has to be positive");
}
// ------------------------------------------------
Vector3d globalBestResult = null;
for(int i = 0; i < iterations; i++) {
// generate starting vector
Vector2d origin = startingVector();
// System.out.println("Starting point: " + origin);
Vector3d localBestResult = new Vector3d(origin.getX(), origin.getY(), problem.evaluate(origin));
if(globalBestResult == null) { // If first iteration
globalBestResult = new Vector3d(origin.getX(), origin.getY(), problem.evaluate(origin));
}
int stepsPerformed = 0;
boolean keepLooking = true;
while(keepLooking) {
// Vector2d neighbour = neighbour(argumentsVec, stepsize);
Vector2d neighbour = sampleNeighbourhood(origin, stepsize, neighbours);
stepsPerformed++;
double neighbourEval = problem.evaluate(neighbour);
if(problem.madeProgress(localBestResult.getZ(), neighbourEval)) {
origin = neighbour;
localBestResult = new Vector3d(neighbour.getX(), neighbour.getY(), neighbourEval);
}
else {
keepLooking = false;
}
}
if(problem.madeProgress(globalBestResult.getZ(), localBestResult.getZ())) {
globalBestResult = localBestResult;
}
// System.out.println("Global best result: f(" + globalBestResult.getX() + ", " + globalBestResult.getY() + ") = " + globalBestResult.getZ() + ", steps: " + stepsPerformed);
}
return globalBestResult;
}
private Vector2d startingVector() {
double randX = randomValueInRange(problem.getX().getRange());
double randY = randomValueInRange(problem.getY().getRange());
Vector2d r = new Vector2d(randX, randY);
return r;
}
/**
* Calculates random neighbouring point in regard to @origin
*
* Neighbour generation:
* - resize the unitVector by a given @stepsize
* - rotate the scaled vector by random angle
*
* @param origin
* @param stepsize
* @return
*/
private Vector2d neighbour(Vector2d origin, double stepsize) {
int angle = (int)(Math.random() * 360);
Vector2d unitVector = new Vector2d(1.0, 0.0); // Vector of lenght = 1, along X axis
Vector2d neighbour = origin.add(unitVector.resize(stepsize).rotate(angle));
neighbour = cropToBorder(neighbour);
return neighbour;
}
private Vector2d sampleNeighbourhood(Vector2d origin, double stepsize, int neighbours) {
Vector2d bestNeighbour = null;
for(int i = 0; i < neighbours; i++) {
Vector2d neighbour = neighbour(origin, stepsize);
if(i == 0) { // If first iteration
bestNeighbour = neighbour;
} else {
if(problem.madeProgress(problem.evaluate(bestNeighbour), problem.evaluate(neighbour))) {
// System.out.println("Better neighbour was found during neighbour sampling");
bestNeighbour = neighbour;
}
}
}
return bestNeighbour;
}
private double randomValueInRange(Range range) {
double min = range.getMin();
double max = range.getMax();
return min + Math.random() * (max - min);
}
private Vector2d cropToBorder(Vector2d vec) {
double xMin = problem.getX().getRange().getMin();
double xMax = problem.getX().getRange().getMax();
double yMin = problem.getY().getRange().getMin();
double yMax = problem.getY().getRange().getMax();
double x = vec.getX();
double y = vec.getY();
if(x < xMin) { x = xMin; }
else if(x > xMax) { x = xMax; }
if(y < yMin) { y = yMin; }
else if(y > yMax) { y = yMax; }
Vector2d cropped = new Vector2d(x, y);
return cropped;
}
}
|
package com.rubic.demo.work;
import com.lmax.disruptor.WorkHandler;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* LongEventHandler:元素处理类
*
* @author rubic
* @since 2018-07-17
*/
public class LongEventHandler implements WorkHandler<LongEvent> {
private List<LongEvent> list;
private AtomicInteger count;
public LongEventHandler(AtomicInteger count) {
this.count = count;
}
@Override
public void onEvent(LongEvent longEvent) throws Exception {
count.incrementAndGet();
list.add(longEvent);
if (count.get() % 50 == 0) {
list.clear();
}
System.out.println(Thread.currentThread().getName() + " 消费了 " + longEvent.getId());
}
public void handle(List<LongEvent> list) {
if (list.isEmpty()) {
System.out.println("");
}
}
}
|
/**
*
*/
package com.erasolon.config;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author operator_erasolon
*
*/
@Configuration
@EnableJpaRepositories(basePackages="com.erasolon.repository")
@EnableTransactionManagement
public class JpaConfig {
@Autowired
DataSource dataSource;
@Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory= new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceXmlLocation("classpath:META-INF/persistence.xml");
factory.setPersistenceUnitName("spring-mvc-httpsecurity-userservicedetails");
factory.setDataSource(dataSource);
//factory.setPackagesToScan("com.erasolon.entity");
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
|
package program.oops;
public class StudentInfo {
int rollno;
int mark1;
int mark2;
int mark3;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public int getMark1() {
return mark1;
}
public void setMark1(int mark1) {
this.mark1 = mark1;
}
public int getMark2() {
return mark2;
}
public void setMark2(int mark2) {
this.mark2 = mark2;
}
public int getMark3() {
return mark3;
}
public void setMark3(int mark3) {
this.mark3 = mark3;
}
}
|
package store;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Store {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static void main(String[] args) throws Exception{
int storePort = Integer.parseInt(args[0]);
InetAddress bankAddress = InetAddress.getByName(args[1]);
int bankPort = Integer.parseInt(args[2]);
Socket bankSocket = new Socket(bankAddress, bankPort);
System.out.println("Connected to bank server at " +
bankAddress.toString() + " at port " + bankPort );
PrintWriter bankPrintWriter = new PrintWriter( bankSocket.getOutputStream(), true );
BufferedReader bankBufferedReader = new BufferedReader( new InputStreamReader(
bankSocket.getInputStream()) );
ServerSocket storeServer = new ServerSocket(storePort);
System.out.println("Created store socket to port " + storePort);
while (true) {
Socket storeClientSocket = storeServer.accept();
System.out.println("Successfully connected to " + storeClientSocket.getInetAddress());
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(
storeClientSocket.getInputStream()) );
PrintWriter printWriter = new PrintWriter( storeClientSocket.getOutputStream(),true );
String message;
if ( (message = bufferedReader.readLine()) != null ) {
StoreFunctions storeFunctions = new StoreFunctions(message, printWriter, bufferedReader, bankPrintWriter);
System.out.println(ANSI_RED+message+ANSI_RESET);
String response = storeFunctions.analyseMessage();
System.out.println(ANSI_BLUE+response+ANSI_RESET);
storeClientSocket.close();
}
}
}
}
|
/**
* @author Coleman R. Lombard
* @file passmanGUI.java
* This file contains the passmanGUI class, used to display all components
* of the passman application.
*
* All member functions are documented in the javadoc style, each comment
* block is preceded by a tag "(#)" for ease of searching. To view documentation,
* simply search by this tag sequence.
*
* @date 11/4/2016
*/
package passman;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import javax.swing.border.*;
import javax.swing.text.JTextComponent;
public class passmanGUI extends JFrame{
//private static entryList fullList = new entryList(); //Class entryList variable for storing entry data.
private static passmanSQLite SQL = new passmanSQLite();
Passman main = new Passman();
//GUI objects and variables.
private static int pref_w = 500;
private static int pref_h = 300;
private JFrame removeGUI, modGUI;
private JLabel titleLabel, entryLabel, tagsLabel;
private JButton createButton;
private JButton modifyButton = new JButton("Modify");
private JButton removeButton = new JButton("Remove");
private JPanel buttons, labels, gui;
private DefaultListModel<String> model;
private JList<String> list;
private JScrollPane scrollPane;
private JTextArea entryText, tagsText, titleText;
private JTextArea newEntryText, newTagsText, newTitleText;
//private JTextField searchField;
private LinkedList<String> existingTags;
//private JComboBox tagAutocompleteSearchBox;
private AutocompleteJComboBox tagAutocompleteBox;
private int indexInList;
private boolean modMenuCreated = false;
private boolean removeMenuCreated = false;
private static String OS = System.getProperty("os.name").toLowerCase();
public passmanGUI() {
super("passmanGUI");
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Title"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Data"));
/***********************************************************************
* Populate buttons.
**********************************************************************/
//Create Buttons Panel
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
//Set modify and remove buttons invisible until selection.
modifyButton.setVisible(false);
removeButton.setVisible(false);
//Generate createButton. Calls a function to add an entry to the fullList.
createButton = new JButton("Create Entry");
generateCreateFunction();
/*
//Create searchField and add listener.
searchField = new JTextField();
searchField.setBackground(Color.DARK_GRAY);
searchField.setForeground(Color.WHITE);
searchField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
//searchField.addActionListener(action);
*/
//Stick searchfield inside JComboBox.
existingTags = main.loadTags();
StringSearchable searchable = new StringSearchable(existingTags);
tagAutocompleteBox = new AutocompleteJComboBox(searchable);
tagAutocompleteBox.setBackground(Color.GRAY);
tagAutocompleteBox.setForeground(Color.WHITE);
tagAutocompleteBox.setBorder(BorderFactory.createLineBorder(Color.GRAY));
/***********************************************************************
* Create JList to add to scrollpane.
**********************************************************************/
//Load titles from SQLite database passman.db table entryTable into ArrayList SQLTitles.
ArrayList<String> SQLTitles = main.loadTitles();
//Load all database titles into model, then into list to be displayed.
model = new DefaultListModel<String>();
for(int i = 0; i < SQLTitles.size(); i++)
{
model.addElement(SQLTitles.get(i));
}
list = new JList<String>(model);
//Create listener for the JList.
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ev) {
if(!ev.getValueIsAdjusting() && list.getSelectedIndex()>-1) {
//Delete old modify and remove frames if relevant.
if(modMenuCreated)
{
for(ActionListener act : modifyButton.getActionListeners())
{
modifyButton.removeActionListener(act);
}
modMenuCreated = false;
}
if(removeMenuCreated)
{
//removeGUI.dispose();
for(ActionListener act : removeButton.getActionListeners())
{
removeButton.removeActionListener(act);
}
removeMenuCreated = false;
}
modifyButton.setVisible(true);
removeButton.setVisible(true);
//Get the selected title from the scrollpane. Retrieve full entry from database.
String selectedTitle = "";
selectedTitle = list.getSelectedValue().toString();
indexInList = searchListByTitle(selectedTitle);
int indexInDatabase = main.searchByTitle(selectedTitle);
entry temp = main.get(indexInDatabase);
//Convert entry to char array.
char[] c = temp.getEntry();
/*
* THIS NEEDS TO BE FIXED TO AVOID ENTRY STORAGE AS STRING IF POSSIBLE.
*/
String str = new String(c); //Convert entry to string.
LinkedList<String> strArray = temp.getTags();
//Populate relevent GUI fields with retrieved entry data.
titleText.setText(selectedTitle);
entryText.setText(str);
tagsText.setText(strArray.toString());
//Generate modify button and functionality.
generateModifyFunction(indexInList);
modMenuCreated = true;
//Generate remove button and functionality.
generateRemoveFunction(indexInList);
removeMenuCreated = true;
}
}
});
/***********************************************************************
* Populate labels.
**********************************************************************/
/*
* Title JLabel. Upon selection of an entry in the scrollpane, this field
* will repopulate with the title data of the selected entry object.
*/
titleLabel = new JLabel("Title: ");
titleLabel.setBackground(Color.DARK_GRAY);
titleLabel.setForeground(Color.WHITE);
titleText = new JTextArea();
titleText.setBackground(Color.DARK_GRAY);
titleText.setForeground(Color.WHITE);
JPanel titleLabelPanel = new JPanel(new BorderLayout()); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane titlePane = new JScrollPane(titleLabelPanel);
//Add label
titlePane.setBorder(new TitledBorder("Title: "));
titlePane.setBackground(Color.GRAY);
//Add title to Panel
titleLabelPanel.add(titleText);
titleText.setEditable(false);
/*
* Entry JLabel. Upon selection of an entry in the scrollpane, this field
* will repopulate with the entry data of the selected entry object.
*/
entryLabel = new JLabel("Entry: ");
entryText = new JTextArea();
entryText.setBackground(Color.DARK_GRAY);
entryText.setForeground(Color.WHITE);
JPanel entryLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane entryPane = new JScrollPane(entryLabelPanel);
//Add label
entryPane.setBorder(new TitledBorder("Entry: "));
entryPane.setBackground(Color.GRAY);
//Add entry to Panel
entryLabelPanel.add(entryText);
entryText.setEditable(false);
entryText.setWrapStyleWord(true);
entryText.setLineWrap(true);
/*
* Tags JLabel. Upon selection of an entry in the scrollpane, this field
* will repopulate with the tag data of the selected entry object.
*/
tagsLabel = new JLabel("Tags: ");
tagsText = new JTextArea();
tagsText.setBackground(Color.DARK_GRAY);
tagsText.setForeground(Color.WHITE);
JPanel tagsLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane tagsPane = new JScrollPane(tagsLabelPanel);
//Add label
tagsPane.setBorder(new TitledBorder("Tags: "));
tagsPane.setBackground(Color.GRAY);
//Add tags to Panel
tagsLabelPanel.add(tagsText);
tagsText.setEditable(false);
//Place all components into JPanel.
JPanel lower = new JPanel(new BorderLayout(2,2));
lower.add(entryPane, BorderLayout.CENTER);
lower.add(tagsPane, BorderLayout.SOUTH);
lower.add(titlePane, BorderLayout.NORTH);
labels.add(lower, BorderLayout.CENTER);
//Allow selection of list entries.
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
/***********************************************************************
* Construct final GUI.
**********************************************************************/
//Color all buttons.
createButton.setBackground(Color.LIGHT_GRAY);
createButton.setBorder(new LineBorder(Color.DARK_GRAY));
createButton.setOpaque(true);
modifyButton.setBackground(Color.LIGHT_GRAY);
modifyButton.setBorder(new LineBorder(Color.DARK_GRAY));
modifyButton.setOpaque(true);
removeButton.setBackground(Color.LIGHT_GRAY);
removeButton.setBorder(new LineBorder(Color.DARK_GRAY));
removeButton.setOpaque(true);
//Add all buttons to button panel 'buttons'.
//buttons.add(searchField);
buttons.add(tagAutocompleteBox);
buttons.add(createButton);
buttons.add(modifyButton);
buttons.add(removeButton);
//Create scrollPane and populate with list.
scrollPane = new JScrollPane(list);
Dimension titleScrollPaneDimension = new Dimension(120,20);
scrollPane.setPreferredSize(titleScrollPaneDimension);
//Color major components.
gui.setBackground(Color.GRAY);
list.setBackground(Color.DARK_GRAY);
list.setForeground(Color.WHITE);
labels.setBackground(Color.GRAY);
buttons.setBackground(Color.GRAY);
//Add major objects to gui frame; labels, scrollPane, and buttons.
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
add(gui);
setVisible(true);
//Run empty search by tags to alphabetize initial list.
searchByTag("");
}
/*(#) searchListByTitle()
* This function returns the index of the title parameter in the JList
* list if it exists in the list.
***************************************************************************
* @param Title as String.
* @pre None.
* @post Index of title in GUI JList list if it exists in the list.
* @return int index of the title.
* @throws None.
*/
public int searchListByTitle(String title)
{
int titleIndex = 0;
for(int i = 0; i < list.getModel().getSize(); i++)
{
if(list.getModel().getElementAt(i).equals(title))
{
titleIndex = i;
break;
}
}
return titleIndex;
}
/*(#) searchByTag()
* This function updates the GUI display to include all entries
* containing the tag provided to the GUI search bar.
***************************************************************************
* @param String str to search by.
* @pre None.
* @post Index of all items in GUI JList list containing the tag.
* @return None.
* @throws None.
*/
public void searchByTag(String str)
{
ArrayList<Integer> tagIndexList = new ArrayList<Integer>();
try{
tagIndexList = main.searchByTag(str);
//Load titles from SQLite database passman.db table entryTable into ArrayList SQLTitles.
ArrayList<String> SQLTitles = main.loadTitles();
model.removeAllElements();
clearDataSelection();
for(int j = 0; j < tagIndexList.size(); j++)
{
//Update the JList to contain only the titles at these indices.
model.addElement(SQLTitles.get(tagIndexList.get(j)-1));
}
}catch(Exception p){
System.err.println(p.getClass().getName() +"Exception in searchfield.");
}
}
/*(#) generateCreateFunction()
* This generates the GUI tool needed to handle user addition of a new
* entry from the user. It will also call needed functionality from the
* main function to add data to the database, and handle other necessary
* functionality associated with entry creation.
***************************************************************************
* @param None.
* @pre None.
* @post JFrame is generated to handle user addition of new entry.
* @return None.
* @throws None.
*/
public void generateCreateFunction()
{
createButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Display GUI to read entry from user.
final JFrame searchGUI = new JFrame("passmanGUI - NewEntry");
JPanel newEntryPanel = new JPanel(new BorderLayout(2,2));
newEntryPanel.setBackground(Color.GRAY);
/*
* Title text area. Will allow for entry of title data.
*/
newTitleText = new JTextArea();
newTitleText.setBackground(Color.DARK_GRAY);
newTitleText.setForeground(Color.WHITE);
newTitleText.setCaretColor(Color.WHITE);
JPanel newTitleLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newTitlePane = new JScrollPane(newTitleLabelPanel);
//Add label
newTitlePane.setBorder(new TitledBorder("Title: "));
newTitlePane.setBackground(Color.GRAY);
//Add entry to Panel
newTitleLabelPanel.add(newTitleText);
/*
* newEntry text area. Will allow for entry of entry data.
*/
newEntryText = new JTextArea();
newEntryText.setBackground(Color.DARK_GRAY);
newEntryText.setForeground(Color.WHITE);
newEntryText.setCaretColor(Color.WHITE);
newEntryText.setWrapStyleWord(true);
newEntryText.setLineWrap(true);
JPanel newEntryLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newEntryPane = new JScrollPane(newEntryLabelPanel);
//Add label
newEntryPane.setBorder(new TitledBorder("Entry: "));
newEntryPane.setBackground(Color.GRAY);
//Add entry to Panel
newEntryLabelPanel.add(newEntryText);
/*
* Tags text area. Will allow for entry of tags data.
*/
newTagsText = new JTextArea();
newTagsText.setBackground(Color.DARK_GRAY);
newTagsText.setForeground(Color.WHITE);
newTagsText.setCaretColor(Color.WHITE);
JPanel newTagsLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newTagsPane = new JScrollPane(newTagsLabelPanel);
//Add label
newTagsPane.setBorder(new TitledBorder("Tags: (Separate with commas)"));
newTagsPane.setBackground(Color.GRAY);
//Add tags to Panel
newTagsLabelPanel.add(newTagsText);
//Add title, entry, and tag fields to newEntryPanel.
newEntryPanel.add(newTitlePane, BorderLayout.NORTH);
newEntryPanel.add(newEntryPane, BorderLayout.CENTER);
newEntryPanel.add(newTagsPane, BorderLayout.SOUTH);
/**
* Create submit button and listener to push data onto fullList
* once user is finished with their new entry.
*/
JButton submitNewEntryButton = new JButton("Submit");
submitNewEntryButton.setBackground(Color.LIGHT_GRAY);
submitNewEntryButton.setBorder(new LineBorder(Color.DARK_GRAY));
submitNewEntryButton.setOpaque(true);
submitNewEntryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Read data from text fields.
String title = newTitleText.getText(); //Get title.
String tags = newTagsText.getText(); //Get tags.
String str = newEntryText.getText(); //Get entry as string.
//If title has no entry, close window.
if(title.isEmpty()){
searchGUI.dispose();
}
else{
/*
* Else add new entry to database via passman.SQLInsert()
* and add title to model.
*/
char[] entry = str.toCharArray(); //Cast entry to char array.
entry newEntry = new entry(entry, title); //Create new entry in fullList.
//Parse tags to fullList tags.
char[] t = tags.toCharArray(); String s = "";
for(int i = 0; i < tags.length(); i++)
{
//All tag entries are separated by commas. Add tags, omit commas.
if(t[i] == ',')
{
newEntry.addTag(s);
s = "";
}
else
{
s += t[i];
}
}
newEntry.addTag(s);
//Populate JList list with new data loaded into model.
model.addElement(title);
//Push new data onto database.
try{
main.SQLInsert(newEntry);
main.SQLInsertCurrentIV(main.getDBSize());
}catch(SQLException f)
{
System.err.println("SQLInsert Exception thrown after submission of new entry.");
}
//Maintain alphabetical title sort by running blank tag search.
searchByTag("");
//Clear displayed data.
clearDataSelection();
//Close window.
searchGUI.dispose();
}
}
});
searchGUI.getPreferredSize();
searchGUI.add(newEntryPanel, BorderLayout.CENTER);
searchGUI.add(submitNewEntryButton, BorderLayout.SOUTH);
searchGUI.setSize(600, 600);
searchGUI.setVisible(true);
}
});
}
/*(#) generateRemoveFunction()
* This generates the GUI tool needed to handle user removal of an
* entry. It will also call needed functionality from the main function
* to remove data from the database, andhandle other necessary
* functionality associated with entry removal.
***************************************************************************
* @param None.
* @pre None.
* @post JFrame is generated to handle user removal of the entry selected
* in the GUI.
* @return None.
* @throws None.
*/
public void generateRemoveFunction(final int indexInList)
{
//Create remove button and add listener.
removeButton.setVisible(true);
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent removeButtonAction) {
//Display GUI to read entry from user.
//final JFrame removeGUI = new JFrame("passmanGUI - Confirm Removal");
removeGUI = new JFrame("passmanGUI - Confirm Removal");
JPanel newEntryPanel = new JPanel(new BorderLayout(2,2));
newEntryPanel.setBackground(Color.GRAY);
/*
* Title text area. Will allow for entry of title data.
*/
newTitleText = new JTextArea();
newTitleText.setBackground(Color.DARK_GRAY);
newTitleText.setForeground(Color.WHITE);
newTitleText.setCaretColor(Color.WHITE);
JPanel newTitleLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
/**
* Create submit button and listener to push data onto fullList
* once user is finished with their new entry.
*/
JButton confirmButton = new JButton("Confirm Removal?");
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent confirmRemoval) {
//Deselect entry
//int tempNumLabel = indexInList;
list.clearSelection();
//Get title of entry to remove.
String removedItemTitle = list.getModel().getElementAt(indexInList);
//Get index in database.
int indexInDatabase = main.searchByTitle(removedItemTitle);
//Remove entry from database.
main.remove(indexInDatabase);
//Refresh model by removing title.
int removedItemIndex = searchListByTitle(removedItemTitle);
model.removeElementAt(removedItemIndex);
clearDataSelection();
removeGUI.dispose();
}
});
removeGUI.getPreferredSize();
//removeGUI.add(newEntryPanel, BorderLayout.CENTER);
removeGUI.add(confirmButton, BorderLayout.SOUTH);
if(OS.contains("win"))
{
removeGUI.setSize(400, 60);
}
else
{
removeGUI.setSize(400, 55);
}
removeGUI.setLocationRelativeTo(gui);
removeGUI.setVisible(true);
}
});
}
/*(#) generateModifyFunction()
* This generates the GUI tool needed to handle user modification of an
* entry. It will also call needed functionality from the main function
* to modify data in the database, and handle other necessary
* functionality associated with entry modification.
***************************************************************************
* @param None.
* @pre None.
* @post JFrame is generated to handle user modification of the entry
* selected in the GUI.
* @return None.
* @throws None.
*/
public void generateModifyFunction(final int indexInList)
{
//Create modify button and add listener.
//modifyButton = new JButton("Modify");
modifyButton.setVisible(true);
modifyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent modButton) {
//Display GUI to read entry from user.
modGUI = new JFrame("passmanGUI - ModifyEntry");
JPanel newEntryPanel = new JPanel(new BorderLayout(2,2));
newEntryPanel.setBackground(Color.GRAY);
final int indexInModel = indexInList;
final int indexInDatabase = main.searchByTitle(list.getModel().getElementAt(indexInModel));
/*
* Title text area. Will allow for entry of title data.
*/
newTitleText = new JTextArea();
newTitleText.setBackground(Color.DARK_GRAY);
newTitleText.setForeground(Color.WHITE);
newTitleText.setCaretColor(Color.WHITE);
JPanel newTitleLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newTitlePane = new JScrollPane(newTitleLabelPanel);
//Add label
newTitlePane.setBorder(new TitledBorder("Title: "));
newTitlePane.setBackground(Color.GRAY);
//Add entry to Panel
newTitleLabelPanel.add(newTitleText);
/*
* newEntry text area. Will allow for entry of entry data.
*/
newEntryText = new JTextArea();
newEntryText.setBackground(Color.DARK_GRAY);
newEntryText.setForeground(Color.WHITE);
newEntryText.setCaretColor(Color.WHITE);
newEntryText.setWrapStyleWord(true);
newEntryText.setLineWrap(true);
JPanel newEntryLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newEntryPane = new JScrollPane(newEntryLabelPanel);
//Add label
newEntryPane.setBorder(new TitledBorder("Entry: "));
newEntryPane.setBackground(Color.GRAY);
//Add entry to Panel
newEntryLabelPanel.add(newEntryText);
/*
* Tags text area. Will allow for entry of tags data.
*/
newTagsText = new JTextArea();
newTagsText.setBackground(Color.DARK_GRAY);
newTagsText.setForeground(Color.WHITE);
newTagsText.setCaretColor(Color.WHITE);
JPanel newTagsLabelPanel = new JPanel(new BorderLayout(2,2)); //Transfer to new JPanel for beautification.
//Place beautified JPanel in scrollpane for scroll functionality with large size entry.
JScrollPane newTagsPane = new JScrollPane(newTagsLabelPanel);
//Add label
newTagsPane.setBorder(new TitledBorder("Tags: (Separate with commas)"));
newTagsPane.setBackground(Color.GRAY);
//Add tags to Panel
newTagsLabelPanel.add(newTagsText);
//Get selected entry and populate fields with existing data.
entry entryToMod = main.get(indexInDatabase);
char[] c = entryToMod.getEntry(); //Get entry as char array.
/*
* THIS NEEDS TO BE FIXED TO AVOID ENTRY STORAGE AS STRING IF POSSIBLE.
*/
String str = new String(c); //Convert to string.
LinkedList<String> strArray = entryToMod.getTags();
newTitleText.setText(list.getSelectedValue().toString());
newEntryText.setText(str);
//Process brackets out of tags text.
String strModify = strArray.toString();
String strModify2 = "";
for(int i = 0; i < strModify.length(); i++)
{
if((strModify.charAt(i) == '[') || (strModify.charAt(i) == ']'))
{
//Do nothing
}
else
{
strModify2 += strModify.charAt(i);
}
}
newTagsText.setText(strModify2);
//Add title, entry, and tag fields to newEntryPanel.
newEntryPanel.add(newTitlePane, BorderLayout.NORTH);
newEntryPanel.add(newEntryPane, BorderLayout.CENTER);
newEntryPanel.add(newTagsPane, BorderLayout.SOUTH);
/**
* Create submit button and listener to push data onto fullList
* once user is finished with their new entry.
*/
JButton submitNewEntryButton = new JButton("Submit");
submitNewEntryButton.setBackground(Color.LIGHT_GRAY);
submitNewEntryButton.setBorder(new LineBorder(Color.DARK_GRAY));
submitNewEntryButton.setOpaque(true);
submitNewEntryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent newEntryButtonAction) {
//Read data from text fields.
String title = newTitleText.getText(); //Get title.
String tags = newTagsText.getText(); //Get tags.
String str = newEntryText.getText(); //Get entry as string.
//If title has no entry, close window.
if(title.isEmpty()){
modGUI.dispose();
}
else{
/*
* Else add new entry to database via passman.SQLInsert()
* and add title to model.
*/
char[] entry = str.toCharArray(); //Cast entry to char array.
entry newEntry = new entry(entry, title); //Create new entry in fullList.
//Parse tags to fullList tags.
char[] t = tags.toCharArray(); String s = "";
for(int i = 0; i < tags.length(); i++)
{
//All tag entries are separated by commas. Add tags, omit commas.
if(t[i] == ',')
{
newEntry.addTag(s);
s = "";
}
else
{
s += t[i];
}
}
newEntry.addTag(s);
//Push new data onto database.
main.replace(indexInDatabase, newEntry);
//Refresh the sort with a blank tag sort.
searchByTag("");
//Refresh the selected entry's displayed data.
list.setSelectedIndex(indexInModel); //Reset selected entry, it was cleared from the list.
titleText.setText(newTitleText.getText());
entryText.setText(newEntryText.getText());
tagsText.setText(newTagsText.getText());
//Clear displayed data.
//clearDataSelection();
//Close window.
modGUI.dispose();
}
}
});
modGUI.getPreferredSize();
modGUI.add(newEntryPanel, BorderLayout.CENTER);
modGUI.add(submitNewEntryButton, BorderLayout.SOUTH);
modGUI.setSize(600, 600);
modGUI.setVisible(true);
}
});
}
/*(#) clearDataSelection()
* This function removes all data from the GUI displays.
***************************************************************************
* @param None.
* @pre None.
* @post GUI is cleared of all entry data.
* @return None.
* @throws None.
*/
private void clearDataSelection()
{
list.clearSelection();
titleText.setText("");
entryText.setText("");
tagsText.setText("");
modifyButton.setVisible(false);
removeButton.setVisible(false);
}
private interface Searchable<E, V>
{
public Collection<E> search(V value);
}
private class StringSearchable implements Searchable<String,String>
{
private LinkedList<String> terms = new LinkedList<String>();
public StringSearchable(LinkedList<String> newTerms){
terms.addAll(newTerms);
}
public Collection<String> search(String value) {
LinkedList<String> founds = new LinkedList<String>();
for (String s : terms)
{
if (s.indexOf(value) == 0)
{
founds.add(s);
}
}
return founds;
}
}
private class AutocompleteJComboBox extends JComboBox
{
private final Searchable<String,String> searchable;
public final JTextField tc = null;
public AutocompleteJComboBox(Searchable<String,String> s){
super();
this.searchable = s;
setEditable(true);
Component c = getEditor().getEditorComponent();
if (c instanceof JTextComponent)
{
final JTextField tc = (JTextField)c;
tc.setBackground(Color.DARK_GRAY);
tc.setForeground(Color.WHITE);
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
searchByTag(tc.getText());
}
};
tc.addActionListener(action);
tc.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent de) {}
@Override
public void insertUpdate(DocumentEvent de) {
update();
}
@Override
public void removeUpdate(DocumentEvent de) {
update();
}
public void update(){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
LinkedList<String> founds = new LinkedList<String>(searchable.search(tc.getText()));
HashSet<String> foundSet = new HashSet<String>();
for (String s : founds){
foundSet.add(s.toLowerCase());
}
Collections.sort(founds);//sort alphabetically
setEditable(false);
removeAllItems();
//if founds contains the search text, then only add once.
if (!foundSet.contains(tc.getText().toLowerCase()))
{
addItem(tc.getText());
}
for (String s : founds)
{
addItem(s);
}
setEditable(true);
setPopupVisible(true);
tc.requestFocus();
}
});
}
});
tc.addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent arg0) {
if ( tc.getText().length() > 0 ){
setPopupVisible(true);
}
}
@Override
public void focusLost(FocusEvent arg0) {
}
});
}else{
throw new IllegalStateException("Editing component is not a JTextComponent!");
}
}
}
}
|
package com.mtl.demo.serviceA.controller;
import com.mtl.demo.serviceA.service.HulkServiceA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HulkControllerA {
@Autowired
private HulkServiceA hulkServiceA;
@RequestMapping("/query")
public String getHulkServiceA() {
return hulkServiceA.getHulkServiceA(1111);
}
}
|
package constants;
public class IOConstants {
public static final int JOYSTICK_DRIVER = 0;
public static final int JOYSTICK_OPERATOR = 1;
public static final int DRIVE_MOTOR_FL = 8;
public static final int DRIVE_MOTOR_FR = 9;
public static final int DRIVE_MOTOR_BL = 6;
public static final int DRIVE_MOTOR_BR = 7;
public static final int DRIVE_COUNTER_FL = 8;
public static final int DRIVE_COUNTER_FR = 9;
public static final int DRIVE_COUNTER_BL = 6;
public static final int DRIVE_COUNTER_BR = 7;
}
|
package haw.ci.lib.nodes;
public class TypeDeclarationNode extends AbstractNode {
private static final long serialVersionUID = -1319709422716461088L;
private IdentNode ident;
private AbstractNode type;
public TypeDeclarationNode(IdentNode ident, AbstractNode type) {
this.ident = ident;
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ident == null) ? 0 : ident.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeDeclarationNode other = (TypeDeclarationNode) obj;
if (ident == null) {
if (other.ident != null)
return false;
} else if (!ident.equals(other.ident))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString(int indentation) {
String result = toString(indentation, this.getClass().getName() + "\n");
if(ident != null) {
result += ident.toString(indentation) + "\n";
}
if(type != null) {
result += type.toString(indentation) + "\n";
}
return result;
}
}
|
package com.github.it18monkey.current;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorsTest {
public static void main(String[] args) {
ExecutorService service = Executors.newScheduledThreadPool(1);
service.submit(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程1执行了");
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.submit(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程2执行了");
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
|
package com.example.ayaali.fastfoodfp;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.example.ayaali.fastfoodfp.activity.RecipesListActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.core.deps.guava.base.Predicates.instanceOf;
import static org.hamcrest.CoreMatchers.is;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<RecipesListActivity> mActivityRule = new ActivityTestRule<>(
RecipesListActivity.class);
@Test
public void GridViewTest()
{
onData(
is(instanceOf(String.class))
);
}
}
|
package com.demo.decorator.login;
import lombok.Data;
/**
* @author: Maniac Wen
* @create: 2020/4/6
* @update: 20:46
* @version: V1.0
* @detail:
**/
@Data
public class ResultMsg {
private int code;
private String msg;
private Object data;
public ResultMsg(int code,String msg,Object data){
this.code = code;
this.msg = msg;
this.data = data;
}
}
|
package ModeloRel;
/**
* Classe de informações das colunas
* @author Renan
*/
public class Coluna {
public boolean pk, auto_inc, nullable, fk = false;
public String nome, tipo, fk_nome_coluna, fk_nome_tabela;
public int tamanho_str;
public Coluna(boolean pk, boolean auto_inc, boolean nullable, String nome, String tipo, String fk_nome_coluna, String fk_nome_tabela, int tamanho_str, boolean fk) {
this.pk = pk;
this.auto_inc = auto_inc;
this.nullable = nullable;
this.nome = nome;
this.tipo = tipo;
this.fk_nome_coluna = fk_nome_coluna;
this.fk_nome_tabela = fk_nome_tabela;
this.tamanho_str = tamanho_str;
this.fk = fk;
}
public Coluna(){}
}
|
package br.com.ocjp7.classesInternas;
public class ClassesDentroDeMetoso {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
void put(){
int x;
class MyMethod{
//não pode acessar varivale do metodo que seja declarada antes.
final int x = 0; //ok funciona se final
void putAll(){
System.out.println(" Execute Pu All " + x );
}
}
}
}
|
package com.yc.education.service.impl.basic;
import com.github.pagehelper.PageHelper;
import com.yc.education.mapper.basic.EmployeeBasicMapper;
import com.yc.education.model.basic.EmployeeBasic;
import com.yc.education.service.basic.EmployeeBasicService;
import com.yc.education.service.impl.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName EmployeeBasicServiceImpl
* @Description TODO
* @Author QuZhangJing
* @Date 2018/8/31 16:25
* @Version 1.0
*/
@Service
public class EmployeeBasicServiceImpl extends BaseService<EmployeeBasic> implements EmployeeBasicService {
@Autowired
private EmployeeBasicMapper employeeBasicMapper;
@Override
public List<EmployeeBasic> listEmployeeBasic(String text, String stop, int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum,pageSize);
return employeeBasicMapper.listEmployeeBasic(text,stop);
} catch (Exception e) {
return null;
}
}
@Override
public String selectMaxIdnum() {
return employeeBasicMapper.selectMaxIdnum();
}
@Override
public List<EmployeeBasic> selectEmployeeBasic(int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum,pageSize);
return employeeBasicMapper.selectEmployeeBasic();
} catch (Exception e) {
return null;
}
}
@Override
public List<EmployeeBasic> selectEmployeeBasic() {
return employeeBasicMapper.selectEmployeeBasic();
}
@Override
public List<EmployeeBasic> selectEmployeeBasic(String idnumAndName, int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum,pageSize);
return employeeBasicMapper.selectEmployeeBasicByIdnumAndName(idnumAndName);
} catch (Exception e) {
return null;
}
}
@Override
public List<EmployeeBasic> selectEmployeeBasic(String idnumAndName) {
try {
return employeeBasicMapper.selectEmployeeBasicByIdnumAndName(idnumAndName);
} catch (Exception e) {
return null;
}
}
@Override
public List<EmployeeBasic> selectEmployeeBasicByIdnum(String idnum) {
try {
return employeeBasicMapper.selectEmployeeBasicByIdnum(idnum);
} catch (Exception e) {
return null;
}
}
@Override
public List<EmployeeBasic> selectEmployeeBasicByIdnum(String idnum, int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum, pageSize);
return employeeBasicMapper.selectEmployeeBasicByIdnum(idnum);
} catch (Exception e) {
return null;
}
}
@Override
public EmployeeBasic selectEmployeeBasicByIsnum(String idnum) {
return employeeBasicMapper.selectEmployeeBasicByIsnum(idnum);
}
@Override
public List<EmployeeBasic> selectEmployeeBasicNotStop(int types) {
return employeeBasicMapper.selectEmployeeBasicNotStop(types);
}
@Override
public List<EmployeeBasic> selectEmployeeBasicNotStop(int types,int pageNum, int pageSize) {
try {
PageHelper.startPage(pageNum,pageSize);
return employeeBasicMapper.selectEmployeeBasicNotStop(types);
} catch (Exception e) {
return null;
}
}
@Override
public EmployeeBasic selectEmployeeLogin(String idnum, String name, String password) {
try {
return employeeBasicMapper.selectEmployeeLogin(idnum, name, password);
} catch (Exception e) {
return null;
}
}
@Override
public EmployeeBasic selectEmployeeByUname(String uname) {
try {
return employeeBasicMapper.selectEmployeeByUname(uname);
} catch (Exception e) {
return null;
}
}
}
|
package br.com.guarulhosemdestaque.portalnoticia.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/admin")
public class AdminPanelController {
@GetMapping("")
public String index(){
return "admin/painel";
}
@GetMapping("/adicionar-noticia")
public ModelAndView adicionarNoticia(Model model){
ModelAndView mv = new ModelAndView("admin/form-noticia");
//mv.addObject()
}
}
|
package com.quickly.module.content;
import com.quickly.bean.ArticleItem;
import com.quickly.bean.news.NewsArticleItem;
import com.quickly.module.base.IBaseListView;
import com.quickly.module.base.IBasePresenter;
import com.quickly.module.base.IBaseView;
public interface INewsContent {
interface View extends IBaseView<Presenter> {
/**
* 加载网页
*/
void onSetWebView(String url,boolean flag);
}
interface Presenter extends IBasePresenter{
/**
* 请求数据
*/
void doLoadData(NewsArticleItem.DataBean.ListBean dataBean);
}
}
|
package com.thomson.dp.principle.zen.lsp.domain;
public class MachineGun extends AbstractGun {
@Override public void shoot() {
System.out.println("机枪扫射.......");
}
@Override public void setShape(String color) {
super.setShape("机枪的形状");
}
}
|
package com.tpg.brks.ms.expenses.web.resources;
import lombok.Getter;
import lombok.Setter;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport;
@Getter
@Setter
public abstract class IdentifiedResource<T> extends Resource<T> {
private Long resourceId;
protected IdentifiedResource(T content, Link... links) {
super(content, links);
}
}
|
package team.groupproject.entity;
import java.io.Serializable;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "cart_details")
@AssociationOverrides({
@AssociationOverride(name = "cartDetailsPK.cart", joinColumns = @JoinColumn(name = "cart_id")),
@AssociationOverride(name = "cartDetailsPK.product", joinColumns = @JoinColumn(name = "product_id"))})
@NamedQueries({
@NamedQuery(name = "CartDetails.findAll", query = "SELECT c FROM CartDetails c"),
@NamedQuery(name = "CartDetails.findByCart", query = "SELECT c FROM CartDetails c WHERE c.cartDetailsPK.cart = :cart"),
@NamedQuery(name = "CartDetails.findByProductId", query = "SELECT c FROM CartDetails c WHERE c.cartDetailsPK.product = :product"),
@NamedQuery(name = "CartDetails.findByQuantity", query = "SELECT c FROM CartDetails c WHERE c.quantity = :quantity")})
public class CartDetails implements Serializable {
private static final long serialVersionUID = 1L;
private CartDetailsPK cartDetailsPK = new CartDetailsPK();
private int quantity;
public CartDetails() {
}
public CartDetails(CartDetailsPK cartDetailsPK) {
this.cartDetailsPK = cartDetailsPK;
}
public CartDetails(CartDetailsPK cartDetailsPK, int quantity) {
this.cartDetailsPK = cartDetailsPK;
this.quantity = quantity;
}
@EmbeddedId
public CartDetailsPK getCartDetailsPK() {
return cartDetailsPK;
}
public void setCartDetailsPK(CartDetailsPK cartDetailsPK) {
this.cartDetailsPK = cartDetailsPK;
}
@Basic(optional = false)
@Column(name = "quantity")
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Transient
public Cart getCart() {
return getCartDetailsPK().getCart();
}
public void setCart(Cart cart) {
getCartDetailsPK().setCart(cart);
}
@Transient
public Product getProduct() {
return getCartDetailsPK().getProduct();
}
public void setProduct(Product product) {
getCartDetailsPK().setProduct(product);
}
}
|
/*
ASCII Signature: AJM
,. ,.
{^ \-"-/ ^}
" """ "
{ <O> _ <O> }
==_ .:Y:. _==
."" `--^--' "".
(,~-~."" "" ,~-~.)
------( )----( )-----
^-'-'-^ ^-'-'-^
_____________________________
|"""" /~.^.~\ """"|
hjw ,i-i-i(""( i-i-i.
`97 (o o o ))"")( o o o)
\(_) /(""( \ (_)/
`--' \""\ `--'
)"")
(""/
`"
********************************************************************************
* Programmer: Amber Murphy
* Course: CITP 190: Fall 2013
* Filename: Validator.java
* Assignment: Workbook 7-2 +
* Summary: Validator started in 7-2 and expanded as each additional assignment needs.
********************************************************************************
*/
package com.company;
import java.util.Scanner;
public class Validator
{
public static String getString(Scanner sc, String prompt)
{
String temp = null;
boolean isValid = false;
while (!isValid)
{
System.out.print(prompt);
temp = sc.nextLine();
if (temp.isEmpty())
System.out.println("Error! An entry is required. Try again.");
else
isValid = true;
}
return temp;
}
public static String getString(Scanner sc, String prompt, String yes, String no)
{
String temp = null;
boolean isValid = false;
while (!isValid)
{
temp = getString(sc,prompt);
if (temp.equalsIgnoreCase(yes) ||temp.equalsIgnoreCase(no))
isValid = true;
else
System.out.println("Error! Entry must be '"+yes+"' or '"+no+"'. Try again.");
}
return temp;
}
public static int getInt(Scanner sc, String prompt)
{
int guess = 0;
String temp;
boolean isValid = false;
while (!isValid)
{
System.out.print(prompt);
temp = sc.nextLine();
if (temp.isEmpty())
System.out.println("Error! An entry is required. Try again.");
else
{
try
{
guess = Integer.parseInt(temp);
isValid = true;
}
catch (NumberFormatException e)
{
System.out.println("Error! Entry must be an integer. try again.");
}
}
}
return guess;
}
public static int getInt(Scanner sc, String prompt,int min, int max)
{
int guess = 0;
boolean isValid = false;
while (!isValid)
{
guess = getInt(sc, prompt);
if (guess < min)
System.out.println("Error! Number must be greater than " + min + ".");
else if (guess > (max-1))
System.out.println("Error! Number must be less than " + max + ".");
else
isValid = true;
}
return guess;
}
public static double getDouble(Scanner sc, String prompt)
{
double guess = 0;
String temp;
boolean isValid = false;
while (!isValid)
{
System.out.print(prompt);
temp = sc.nextLine();
if (temp.isEmpty())
System.out.println("Error! An entry is required. Try again.");
else
{
try
{
guess = Double.parseDouble(temp);
isValid = true;
}
catch (NumberFormatException e)
{
System.out.println("Error! Entry must be a Double. try again.");
}
}
}
return guess;
}
public static double getDouble(Scanner sc, String prompt,int min, int max)
{
double guess = 0;
boolean isValid = false;
while (!isValid)
{
guess = getDouble(sc, prompt);
if (guess < min)
System.out.println("Error! Number must be greater than " + min + ".");
else if (guess > (max-1))
System.out.println("Error! Number must be less than " + max + ".");
else
isValid = true;
}
return guess;
}
public static String validateSsn(Scanner sc, String prompt)
{
String ssn = "";
int ssnLength;
boolean isValid = false;
while (!isValid)
{
ssnLength = getInt(sc,prompt);
ssn = String.valueOf(ssnLength);
if (ssn.length() == 9)
isValid = true;
else
System.out.println("Error! SSN must be 9 digits. Try again.");
}
return ssn;
}
public static String validateEmail(Scanner sc, String prompt)
{
String email = "";
boolean isValid = false;
while (!isValid)
{
email = getString(sc,prompt);
String castString = email.toLowerCase();
if (castString.contains("@") && (castString.endsWith(".com") || castString.endsWith(".edu") || castString.endsWith(".org")))
{
isValid = true;
}
else
System.out.println("Error! Email address must contain an '@' symbol. \n" +
"And end with .edu, .com, .org, .ca, or .us. Please try again. \n");
}
return email;
}
}
|
package com.what.yunbao.history;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.what.yunbao.R;
import com.what.yunbao.util.Notes.CollectColumns;
public class BusinessAdapter extends CursorAdapter{
private int resId=R.layout.history_business_item;
private ViewPagerFragment fragment;
public BusinessAdapter(Context context,ViewPagerFragment vf){
super(context,null);
this.fragment=vf;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=(ViewHolder)view.getTag();
holder.onbind(cursor);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup container) {
View view = LayoutInflater.from(context).inflate(resId, container,false);
new ViewHolder(view);
return view;
}
class ViewHolder{
public TextView name,address,minCost;
public ViewHolder(View view){
name= (TextView) view.findViewById(R.id.tv_business_item_name);
address = (TextView) view.findViewById(R.id.tv_business_item_addr);
minCost = (TextView) view.findViewById(R.id.tv_business_item_distance);
view.setTag(this);
}
public void onbind(Cursor cursor){
name.setText(cursor.getString(cursor.getColumnIndex(CollectColumns.MERNAME)));
address.setText(cursor.getString(cursor.getColumnIndex(CollectColumns.LOCATION)));
double minc=cursor.getDouble(cursor.getColumnIndex(CollectColumns.MINCOST));
minCost.setText(minc==0?"支持送货":"起送价:¥"+minCost);
}
}
@Override
protected void onContentChanged() {
super.onContentChanged();
if(getCount()==0){
fragment.showEmptyTip();
}
}
}
|
package Lector12.Task12_3;
public class MainTask12_3 {
public static void main(String[] args) {
try {
System.out.println("Введите слово");
String str = Other.ReadFromConsole.readFromConsoleStr();
checkExcep(str);
} catch (MyExcepcion e) {
e.printStackTrace();
}
}
public static void checkExcep(String str) throws MyExcepcion {
if ("fuck".equals(str)) {
str = "stacktrace";
throw new MyExcepcion("Ошибка " + str);
}
}
}
|
package com.jyn.masterroad.utils.dagger2.module;
import javax.inject.Inject;
/**
* Created by jiao on 2020/8/17.
*/
public class Car2 {
@Inject
Engine2 engine;
public Car2() {
}
public Engine2 getEngine() {
return this.engine;
}
}
|
package com.sitp.activities;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.duma.ld.mylibrary.SwitchView;
import com.sitp.cipherpart.R;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageButton;
public class PasswordLoginActivity extends AppCompatActivity {
private ImageButton mIbtnReturn;
private TextView mTvOrder;
private SwitchView mSvVisiable;
private EditText mEtPassword;
private Button mBtnSure;
private GifImageButton mGibSure;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password_login);
mIbtnReturn=(ImageButton)findViewById(R.id.ibtn_return);
mTvOrder=(TextView)findViewById(R.id.tv_order);
mSvVisiable=(SwitchView)findViewById(R.id.sv_visiable);
mEtPassword=(EditText)findViewById(R.id.et_password);
mGibSure=(GifImageButton)findViewById(R.id.gib_sure);
mBtnSure=(Button)findViewById(R.id.btn_sure);
mIbtnReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(PasswordLoginActivity.this,MainActivity.class);
startActivity(intent);
}
});
//切换密码是否可见
mSvVisiable.setOnClickCheckedListener(new SwitchView.onClickCheckedListener() {
@Override
public void onClick() {
int cursorPosition = mEtPassword.length();
if(mEtPassword.getInputType()== (InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_PASSWORD)){
mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
mEtPassword.setSelection(cursorPosition);
}
else{
mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_PASSWORD);
mEtPassword.setSelection(cursorPosition);
}
}
});
mGibSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
// 如果加载的是gif动图,第一步需要先将gif动图资源转化为GifDrawable
// 将gif图资源转化为GifDrawable
GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.btn_sure_chosen);
// gif1加载一个动态图gif
mGibSure.setBackground(gifDrawable);
} catch (Exception e) {
e.printStackTrace();
}
}
});
mBtnSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
Typeface typeFace = Typeface.createFromAsset(getAssets(),"font/debiao.ttf");
mTvOrder.setTypeface(typeFace);
mBtnSure.setTypeface(typeFace);
}
}
|
package Program;
import java.util.HashMap;
import java.util.Map;
/**
*
* La clase Mapa genera a traves de un HashMap una sucesion de puntos.
*
*/
public class Mapa {
protected HashMap<String,Coordenada> puntos = new HashMap<>();
public void setPunto (String nombre, Coordenada punto)
{
puntos.put(nombre, punto);
}
public Coordenada getPunto(String nombre)
{
Coordenada salida = null;
if (puntos.containsKey(nombre)) {
salida=puntos.get(nombre);
return salida;
}
return salida;
}
//No es una buena practica mostrar en una clase, pero me facilitaba en el Test.
public void mostrarMapa () {
for (Map.Entry<String, Coordenada> e : puntos.entrySet())
System.out.println(e.getKey() + " | Coordenada: " + e.getValue());
}
}
|
package com.egova.eagleyes.adapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.egova.eagleyes.R;
import com.egova.eagleyes.model.respose.PersonInfo;
import java.util.List;
import androidx.annotation.Nullable;
public class PersonSearchAdapter extends BaseQuickAdapter<PersonInfo, BaseViewHolder> {
public PersonSearchAdapter(int layoutResId, @Nullable List<PersonInfo> data) {
super(layoutResId, data);
}
@Override
protected void convert(BaseViewHolder helper, PersonInfo item) {
int position = helper.getLayoutPosition();
if (position == 0 || !mData.get(position - 1).getFirstLetter().equals(item.getFirstLetter())) {
helper.setText(R.id.letter, item.getFirstLetter());
helper.setVisible(R.id.letter, true);
} else {
helper.setVisible(R.id.letter, false);
}
helper.setText(R.id.name, item.getName());
}
}
|
package pacoteBase08.VIEW;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import pacoteBase08.CONTROL.ControlarAplicativo;
public class MontarPainelInicial {
private JFrame baseFrame;
private JPanel basePanel;
private JPanel outputPanel, outputPanelEsq, outputPanelCen, outputPanelDir;
private JPanel controlePanelAcao1;
private JPanel controlePanelAcao2;
private JPanel controlePanelAcao3;
private JPanel controlePanelVisualImagens;
private JPanel controlePanelAcao4;
private JButton btAcao3;
private JButton btAcao1;
private JButton btSalva;
private JButton btReset;
private JButton btAcao4;
private JRadioButton btAcao31;
private JRadioButton btAcao32;
private ButtonGroup btRdAcao3;
private JRadioButton btAcao11;
private JRadioButton btAcao12;
private JRadioButton btAcao13;
private JRadioButton btAcao14;
private JRadioButton btAcao15;
private ButtonGroup btRdAcao1;
private JRadioButton btAcao21;
private JRadioButton btAcao22;
private JRadioButton btAcao23;
private JRadioButton btAcao24;
private JRadioButton btAcao25;
private JRadioButton btAcao26;
private ButtonGroup btRdAcao2;
private JRadioButton btVisualNewImg;
private JRadioButton btVisualAllImg;
private ButtonGroup btRdVisualImg;
private JRadioButton btAcao41;
private JRadioButton btAcao42;
private ButtonGroup btRdAcao4;
private JLabel lbTheta;
private JLabel lbSigma;
private JLabel lbLambda;
private JLabel lbGamma;
private JLabel lbOffset;
private JLabel lbAngulo;
private JTextField tfTheta;
private JTextField tfSigma;
private JTextField tfGamma;
private JTextField tfLambda;
private JTextField tfOffset;
private JTextField tfAngulo;
private Graphics desenhoCen;
private Graphics desenhoDir;
//*******************************************************************************************
public MontarPainelInicial(ControlarAplicativo controlePrograma) {
JPanel buttonPanel;
JPanel titlePanel;
JPanel acao3Panel;
JPanel acao1Panel;
JPanel acao2Panel;
JPanel visualImagensPanel;
JPanel acao4Panel;
// LAYOUT
baseFrame = new JFrame();
baseFrame.setLayout(new BoxLayout(baseFrame.getContentPane(), BoxLayout.Y_AXIS));
baseFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); // FITS PANEL TO THE ACTUAL MONITOR SIZE
baseFrame.setUndecorated(true); // TURN OFF ALL THE PANEL BORDERS
basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
// TITLE PANEL
titlePanel = new JPanel();
titlePanel.setPreferredSize(new Dimension(0, 50));
titlePanel.setBackground(Color.gray);
// OUTPUT PANEL
outputPanel = new JPanel();
outputPanel.setLayout(new BorderLayout());
outputPanelEsq = new JPanel();
outputPanelEsq.setPreferredSize(new Dimension(130, 0));
outputPanelEsq.setLayout(new BoxLayout(outputPanelEsq, BoxLayout.Y_AXIS));
outputPanelEsq.setBackground(Color.lightGray);
outputPanelCen = new JPanel();
outputPanelCen.setBackground(new Color(220, 220, 210));
outputPanelCen.setLayout(new BorderLayout());
outputPanelDir = new JPanel();
outputPanelDir.setBackground(new Color(210, 200, 200));
outputPanelDir.setPreferredSize(new Dimension(580, 0));
outputPanelDir.setLayout(new BorderLayout());
// BUTTON PANEL
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setBackground(Color.gray);
// PANEL TITLE
JLabel titulo;
titulo = new JLabel("IMAGE LAB PROCESSING");
titulo.setForeground(Color.black);
titulo.setFont(new Font("Dialog", Font.BOLD, 25));
titlePanel.add(titulo);
// ADDING BUTTONS
addAButton("New Image", "botaoImagem", buttonPanel, true, controlePrograma);
btAcao1 = addAButton("Rotacionar", "botaoRotacionar", buttonPanel, false, controlePrograma);
btAcao3 = addAButton("Aplicar Filtro de Gabor", "botaoFiltroGabor", buttonPanel, false, controlePrograma);
btReset = addAButton("Reset", "botaoReset", buttonPanel, false, controlePrograma);
btSalva = addAButton("Save", "botaoSalva", buttonPanel, false, controlePrograma);
addAButton("END", "botaoFim", buttonPanel, true, controlePrograma);
// CONFIGURANDO A INTERFACE DOS PARÂMETROS DO FILTRO GABOR E DA ROTAÇÃO
//IINICIALIZANDO LABELS
lbTheta = new JLabel("θ:");
lbSigma = new JLabel("σ:");
lbLambda = new JLabel("λ:");
lbGamma = new JLabel("γ:");
lbOffset = new JLabel("φ:");
lbAngulo = new JLabel("Ângulo:");
//Adicionando tooltips
lbTheta.setToolTipText("Orientação do filtro em graus. Aceitável qualquer valor entre 0 e 360.");
lbSigma.setToolTipText("Desvio padrão do componente Gaussiano. Aceitável qualquer valor maior que zero e menor que o tamanho do kernel utilizado.");
lbLambda.setToolTipText("Comprimento de onda do componente cossenoidal do filtro. Especificado em pixels, aceitável qualquer valor maior que dois.");
lbGamma.setToolTipText("Relação de aspecto. Define o quão elíptica é a função. Aceitável qualquer valor maior que 0 e menor ou igual a 1.");
lbOffset.setToolTipText("Deslocamento da função cosseno. Zero por padrão, mas é aceitável qualquer valor.");
lbAngulo.setToolTipText("Ângulo, em graus, pelo qual a imagem será rotacionada utilizando interpolação pelo método do vizinho mais próximo.");
//INICIALIZANDO CAMPOS DE TEXTO
tfTheta = new JTextField("0");
tfSigma = new JTextField("1");
tfLambda = new JTextField("3");
tfGamma = new JTextField("0.5");
tfOffset = new JTextField("0");
tfAngulo = new JTextField("90");
controlePanelAcao3 = new JPanel();
controlePanelAcao3.setBackground(Color.lightGray);
controlePanelAcao3.setMaximumSize(new Dimension(200, 160));
outputPanelEsq.add(controlePanelAcao3);
acao3Panel = new JPanel();
acao3Panel.setPreferredSize(new Dimension(120, 150));
acao3Panel.setLayout(new GridLayout(5, 2));
acao3Panel.add(lbSigma);
acao3Panel.add(tfSigma);
acao3Panel.add(lbGamma);
acao3Panel.add(tfGamma);
acao3Panel.add(lbTheta);
acao3Panel.add(tfTheta);
acao3Panel.add(lbLambda);
acao3Panel.add(tfLambda);
acao3Panel.add(lbOffset);
acao3Panel.add(tfOffset);
acao3Panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Filtro Gabor"));
controlePanelAcao3.add(acao3Panel);
controlePanelAcao3.setVisible(false);
// CONFIGURANDO ÁREA DE CONTROLE DA ROTAÇÃO
controlePanelAcao1 = new JPanel();
controlePanelAcao1.setBackground(Color.lightGray);
controlePanelAcao1.setMaximumSize(new Dimension(130, 60));
controlePanelAcao1.setVisible(false);
acao1Panel = new JPanel();
acao1Panel.setPreferredSize(new Dimension(120, 45));
acao1Panel.setLayout(new GridLayout(1, 2));
acao1Panel.add(lbAngulo);
acao1Panel.add(tfAngulo);
acao1Panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Rotação"));
controlePanelAcao1.add(acao1Panel);
outputPanelEsq.add(controlePanelAcao1);
// ADDING RADIO BUTTON PARA CONTROLE DA VISUALIZACAO DAS IMAGENS
controlePanelVisualImagens = new JPanel();
controlePanelVisualImagens.setBackground(Color.lightGray);
controlePanelVisualImagens.setMaximumSize(new Dimension(130, 65));
outputPanelEsq.add(controlePanelVisualImagens);
btVisualNewImg = new JRadioButton(" new image", true);
btVisualAllImg = new JRadioButton("transitions", false);
btRdVisualImg = new ButtonGroup();
btRdVisualImg.add(btVisualNewImg);
btRdVisualImg.add(btVisualAllImg);
btVisualNewImg.addActionListener(controlePrograma);
btVisualAllImg.addActionListener(controlePrograma);
visualImagensPanel = new JPanel();
visualImagensPanel.setPreferredSize(new Dimension(120, 55));
visualImagensPanel.setLayout(new GridLayout(2, 1));
visualImagensPanel.add(btVisualNewImg);
visualImagensPanel.add(btVisualAllImg);
visualImagensPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Image Control"));
controlePanelVisualImagens.add(visualImagensPanel);
controlePanelVisualImagens.setVisible(false);
// VISIBLE PANELS
outputPanel.add(outputPanelEsq, BorderLayout.LINE_START);
outputPanel.add(outputPanelCen, BorderLayout.CENTER);
outputPanel.add(outputPanelDir, BorderLayout.LINE_END);
basePanel.add(titlePanel, BorderLayout.PAGE_START);
basePanel.add(outputPanel, BorderLayout.CENTER);
basePanel.add(buttonPanel, BorderLayout.PAGE_END);
baseFrame.add(basePanel);
baseFrame.setVisible(true);
}
//*******************************************************************************************
public void limpaPainelCen(Graphics desenho) {
outputPanelCen.removeAll();
outputPanelCen.update(desenho);
}
//*******************************************************************************************
public void limpaPainelDir(Graphics desenho) {
outputPanelDir.removeAll();
outputPanelDir.update(desenho);
}
//*******************************************************************************************
// METODO UTILIZADO PARA ADICIONAR UM BOTAO A UM CONTAINER DO PROGRAMA
private JButton addAButton(String textoBotao,
String textoControle,
Container container,
boolean estado,
ControlarAplicativo controlePrograma) {
JButton botao;
botao = new JButton(textoBotao);
botao.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(botao);
botao.setEnabled(estado);
botao.setActionCommand(textoControle);
botao.addActionListener(controlePrograma);
return (botao);
}
//*******************************************************************************************
public void mudarBotoes() {
System.out.println("estou no mudar botoes!");
btAcao3.setEnabled(true);
btAcao1.setEnabled(true);
btSalva.setEnabled(true);
btReset.setEnabled(true);
controlePanelAcao3.setVisible(true);
controlePanelAcao1.setVisible(true);
controlePanelVisualImagens.setVisible(true);
}
//*******************************************************************************************
// METODO PARA APRESENTAR O MENU DE ESCOLHA DE ARQUIVOS
// 1 - PARA LEITURA
// 2 - PARA GRAVACAO
public String escolherArquivo(int operacao) {
int retorno;
String caminhoArquivo;
JFileChooser arquivo;
retorno = 0;
arquivo = new JFileChooser(new File("."));
// TIPO DE OPERACAO A SER REALIZADA
switch (operacao) {
case 1:
retorno = arquivo.showOpenDialog(null);
break;
case 2:
retorno = arquivo.showSaveDialog(null);
}
// OPERACAO
caminhoArquivo = null;
if (retorno == JFileChooser.APPROVE_OPTION) {
try {
caminhoArquivo = arquivo.getSelectedFile().getAbsolutePath();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("erro: " + e);
}
}
return (caminhoArquivo);
}
//*******************************************************************************************
// METODO PARA MOSTRAR O FRAME BASICO
public void showPanel() {
basePanel.setVisible(true);
}
//*******************************************************************************************
public void ativarPainelAcao3() {
controlePanelAcao3.setVisible(true);
}
//*******************************************************************************************
public void desativarPainelAcao3() {
controlePanelAcao3.setVisible(false);
}
//*******************************************************************************************
public void ativarPainelAcao1() {
controlePanelAcao1.setVisible(true);
}
//*******************************************************************************************
public void desativarPainelAcao1() {
controlePanelAcao1.setVisible(false);
}
//*******************************************************************************************
public void iniciarGraphics() {
desenhoCen = outputPanelCen.getGraphics();
desenhoDir = outputPanelDir.getGraphics();
}
//*******************************************************************************************
public Graphics getDesenhoC() {
return (desenhoCen);
}
//*******************************************************************************************
public Graphics getDesenhoD() {
return (desenhoDir);
}
//******************************************************************************************
public int getTipoVisualImage() {
int tipo;
tipo = 1;
if (btVisualAllImg.isSelected()) {
tipo = 2;
}
return (tipo);
}
//******************************************************************************************
public void resetaSistema() {
btVisualNewImg.setSelected(true);
}
//******************************************************************************************
public float getAngulo() {
return Float.parseFloat(tfAngulo.getText());
}
public float getTheta() {
return (float) (Float.parseFloat(tfTheta.getText()) * Math.PI / 180);
}
public float getSigma() {
return Float.parseFloat(tfSigma.getText());
}
public float getGamma() {
return Float.parseFloat(tfGamma.getText());
}
public float getLambda() {
return Float.parseFloat(tfLambda.getText());
}
public float getOffset() {
return Float.parseFloat(tfOffset.getText());
}
}
|
package com.soa.interceptor;
import com.soa.domain.hero.Hero;
import com.soa.service.JMSService;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Tracked
@Interceptor
public class TrackedInterceptor {
@Inject
private JMSService jmsService;
@AroundInvoke
public Object invoke(InvocationContext ctx) throws Exception {
try {
return ctx.proceed();
}
finally {
jmsService.send((Hero) ctx.getParameters()[0]);
}
}
}
|
package nesto.base.widget;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
/**
* Created on 2017/3/23.
* By nesto
*/
public class Touch {
public static double calculateDistance(MotionEvent event) {
if (event.getPointerCount() < 2) return 0;
return Math.sqrt(pow2(event.getX(0) - event.getX(1))
+ pow2(event.getY(0) - event.getY(1)));
}
public static PointF center(MotionEvent event) {
if (event.getPointerCount() < 2) {
throw new IllegalArgumentException("not a multi-touch event");
}
return new PointF((event.getX(0) + event.getX(1)) / 2,
(event.getY(0) + event.getY(1)) / 2);
}
public static float adjustNumber(float min, float max, float number) {
return Math.min(max, Math.max(min, number));
}
private static double pow2(double num) {
return num * num;
}
public static float getMatrixValue(Matrix matrix, float[] values, int index) {
matrix.getValues(values);
return values[index];
}
}
|
package br.com.guisfco.onlineshopping.util;
public class RandomUtils {
public static int nextInt(final int minInclusive, final int maxExclusive) {
return minInclusive + (int) (Math.random() * (maxExclusive - minInclusive));
}
public static double nextDouble(final int min, final int max) {
return (Math.random() * (max - min)) + min;
}
}
|
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos;
import algo3.fiuba.modelo.jugador.Jugador;
import algo3.fiuba.modelo.cartas.Monstruo;
import algo3.fiuba.modelo.cartas.efectos.EfectoNulo;
import algo3.fiuba.modelo.cartas.estados_cartas.EnJuego;
import algo3.fiuba.modelo.cartas.modo_monstruo.ModoDeAtaque;
import algo3.fiuba.modelo.excepciones.SacrificiosIncorrectosExcepcion;
public class DragonDefinitivoDeOjosAzules extends Monstruo {
public DragonDefinitivoDeOjosAzules(Jugador jugador) {
super("Dragon Definitivo de Ojos Azules", 4500, 3800, 10, new EfectoNulo());
setJugador(jugador);
}
@Override
public void colocarEnCampo(Jugador jugador, EnJuego tipoEnJuego, Monstruo... sacrificios) {
if (!sacrificiosSuficientes(sacrificios))
throw new SacrificiosIncorrectosExcepcion("Se necesitan estrictamente 3 Dragones Blancos de Ojos Azules para invocarlo.");
realizarSacrificios(sacrificios);
modoMonstruo = new ModoDeAtaque();
estadoCarta = tipoEnJuego;
jugador.colocarCartaEnCampo(this, tipoEnJuego, sacrificios);
}
private boolean sacrificiosSuficientes(Monstruo... sacrificios) {
if (sacrificios.length != 3)
return false;
boolean sacrificioValido = true;
for (Monstruo sacrificio : sacrificios) {
sacrificioValido &= sacrificio instanceof DragonBlancoDeOjosAzules;
}
return sacrificioValido;
}
}
|
package com.xxglpt.sjjs.bean;
import java.io.Serializable;
import java.util.List;
/**
* 汇交测绘实体
* @author xnq
*
*/
public class JcchMx implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String jcchId;
private String xh;
private String sjlx;
private String sl;
private String zt;
private String zbx;
private String bz;
private List<JcchMx> list;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getJcchId() {
return jcchId;
}
public void setJcchId(String jcchId) {
this.jcchId = jcchId;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getSjlx() {
return sjlx;
}
public void setSjlx(String sjlx) {
this.sjlx = sjlx;
}
public String getSl() {
return sl;
}
public void setSl(String sl) {
this.sl = sl;
}
public String getZt() {
return zt;
}
public void setZt(String zt) {
this.zt = zt;
}
public String getZbx() {
return zbx;
}
public void setZbx(String zbx) {
this.zbx = zbx;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public List<JcchMx> getList() {
return list;
}
public void setList(List<JcchMx> list) {
this.list = list;
}
}
|
package net.nowtryz.mcutils.command.graph;
import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.nowtryz.mcutils.command.contexts.NodeSearchContext;
import net.nowtryz.mcutils.command.exceptions.ExecutorDuplicationException;
import net.nowtryz.mcutils.command.execution.Completer;
import net.nowtryz.mcutils.command.execution.Execution;
import net.nowtryz.mcutils.command.execution.Executor;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@Getter
@RequiredArgsConstructor
public class CommandNode {
private static final Pattern GENERIC_MATCHER = Execution.GENERIC_ARG;
@Getter(AccessLevel.NONE)
private final HashMap<String, CommandNode> children = new HashMap<>();
private final String key;
private GenericCommandNode genericNode;
private Executor executor;
@NotNull
public CommandNode children(String key) {
return this.children.computeIfAbsent(key, CommandNode::new);
}
private synchronized GenericCommandNode getOrCreateGenericNode(String argument) {
boolean varArgs = Execution.VAR_ARGS.matcher(argument).matches();
if (this.genericNode == null) this.genericNode = varArgs ? new VarArgsCommandNode() : new GenericCommandNode();
else if (varArgs && !(this.genericNode instanceof VarArgsCommandNode)) throw new IllegalStateException(
"Trying to register " + argument + "witch is a varargs, while the registered node does not support it. "
+ "If you fall into this issue and your system work lie this, please report this issue in order to find"
+ " a workaround"
);
return this.genericNode;
}
CommandNode findExecutor(NodeSearchContext context, Queue<String> remainingArgs) {
if (remainingArgs.isEmpty()) return this;
String command = remainingArgs.remove();
CommandNode child = this.children.getOrDefault(command, this.genericNode);
if (child != null) return child.findExecutor(context, remainingArgs);
else return null;
}
CommandNode findCompleter(NodeSearchContext context, Queue<String> remainingArgs) {
if (remainingArgs.isEmpty()) return null;
String command = remainingArgs.remove().toLowerCase();
return remainingArgs.isEmpty() ? this : Optional
.ofNullable(this.children.getOrDefault(command, this.genericNode))
.map(node -> node.findCompleter(context, remainingArgs))
.orElse(null);
}
List<String> complete(NodeSearchContext context) {
ArrayList<String> list = new ArrayList<>();
this.children.values()
.stream()
.filter(n -> n.getKey().startsWith(context.getLastArgument()))
.filter(context::checkPermission)
.map(CommandNode::getKey)
.forEach(list::add);
Optional.ofNullable(this.genericNode)
.map(node -> node.completeArgument(context))
.ifPresent(list::addAll);
return list;
}
void setCommand(Executor executor) {
if (this.executor != null) throw new ExecutorDuplicationException(this.executor, executor);
this.executor = executor;
}
void registerCommand(Queue<String> commandLine, Executor executor) {
if (commandLine.isEmpty()) {
this.setCommand(executor);
return;
}
String node = commandLine.remove();
CommandNode children = GENERIC_MATCHER.matcher(node).matches() ? this.getOrCreateGenericNode(node) : this.children(node.toLowerCase());
children.registerCommand(commandLine, executor);
}
void registerCompleter(Queue<String> commandLine, Completer completer) {
if (commandLine.isEmpty()) throw new IllegalStateException("Cannot register a completer for an empty command");
String node = commandLine.remove();
if (commandLine.isEmpty()) {
this.getOrCreateGenericNode(node).setCompleter(completer);
return;
}
CommandNode children = GENERIC_MATCHER.matcher(node).matches() ? this.getOrCreateGenericNode(node) : this.children(node.toLowerCase());
children.registerCompleter(commandLine, completer);
}
public String toStringGraph(int level) {
int nextLevel = level + 1;
String tabs = Strings.repeat(" ", level);
StringBuilder builder = new StringBuilder().append(tabs).append(this.key).append(" {\n");
this.appendToStringGraph(tabs, builder);
if (this.executor != null) builder.append(tabs).append(" executor: ").append(executor).append("\n");
if (this.genericNode != null) builder.append(this.genericNode.toStringGraph(nextLevel)).append("\n");
if (!this.children.isEmpty()) for (CommandNode node : this.children.values()) {
builder.append(node.toStringGraph(nextLevel)).append("\n");
}
return builder.append(tabs).append("}").toString();
}
/**
* Method that can be overridden to add information to the string visualisation the the graph
* @param tabs the number of tabs to display before outputs
* @param builder the string builder to which the output must be append
*/
protected void appendToStringGraph(String tabs, StringBuilder builder) {}
@Override
public String toString() {
return this.toStringGraph(0);
}
public Stream<Executor> listExecutors() {
return Stream.concat(
Stream.of(this.executor, Optional.ofNullable(this.genericNode)
.map(GenericCommandNode::getExecutor)
.orElse(null)).filter(Objects::nonNull),
this.children.values().stream().flatMap(CommandNode::listExecutors)
);
}
}
|
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author yuanqinglong
* @since 2021/2/18 9:15
*/
@Controller
public class TranslationController {
@Transactional(rollbackFor = Exception.class)
@RequestMapping("/test")
public Object test() {
System.out.println("事务目标方法...");
return "zzzzzzz";
}
}
|
package com.star.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
/**
* 编辑修改文章实体类
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class ShowBlog {
private Long id;
private String flag;
private String title;
private String content;
private Long typeId;
private String firstPicture;
private String description;
private boolean recommend;
private boolean published;
private boolean shareStatement;
private boolean appreciation;
private boolean commentabled;
private Date updateTime;
}
|
package com.reactnative.googlecast.types;
import android.graphics.Color;
import androidx.annotation.Nullable;
public class RNGCColor {
public static int fromJson(final @Nullable String color) {
if (color == null) return 0; // COLOR_UNSPECIFIED
try {
if (color.startsWith("#")) {
// Android's Color starts with alpha, e.g. "#AARRGGBB"
String rgb = color.substring(1, 7);
String a = color.substring(7);
return Color.parseColor("#" + a + rgb);
} else {
// try parsing color by name
return Color.parseColor(color);
}
} catch (IllegalArgumentException e) {
return 0;
}
}
public static @Nullable String toJson(final int color) {
if (color == 0) return null; // COLOR_UNSPECIFIED
String argb = String.format("%08X", color);
String a = argb.substring(0, 2);
String rgb = argb.substring(2);
return "#" + rgb + a;
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.network;
/**
* TCP服务器.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public interface TcpServer {
/**
* 开启服务.
*/
public void startup();
/**
* 停止服务.
*/
public void shutdown();
}
|
//среднее арифметическое всех цифр /3 в диапазоне от a до b
package Loop;
import java.util.Scanner;
public class Loop5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int i = 0;
int k = 0;
double sum = 0;
for(i = a; i <= b; i++) {
if(i % 3 == 0){
k++;
sum = sum + i;
}
}
System.out.println(sum / k);
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import dalvik.system.VMRuntime;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.function.Consumer;
public class ChildClass {
enum PrimitiveType {
TInteger('I', Integer.TYPE, Integer.valueOf(0)),
TLong('J', Long.TYPE, Long.valueOf(0)),
TFloat('F', Float.TYPE, Float.valueOf(0)),
TDouble('D', Double.TYPE, Double.valueOf(0)),
TBoolean('Z', Boolean.TYPE, Boolean.valueOf(false)),
TByte('B', Byte.TYPE, Byte.valueOf((byte) 0)),
TShort('S', Short.TYPE, Short.valueOf((short) 0)),
TCharacter('C', Character.TYPE, Character.valueOf('0'));
PrimitiveType(char shorty, Class klass, Object value) {
mShorty = shorty;
mClass = klass;
mDefaultValue = value;
}
public char mShorty;
public Class mClass;
public Object mDefaultValue;
}
enum Hiddenness {
Whitelist(PrimitiveType.TShort),
LightGreylist(PrimitiveType.TBoolean),
DarkGreylist(PrimitiveType.TByte),
Blacklist(PrimitiveType.TCharacter),
BlacklistAndCorePlatformApi(PrimitiveType.TInteger);
Hiddenness(PrimitiveType type) { mAssociatedType = type; }
public PrimitiveType mAssociatedType;
}
enum Visibility {
Public(PrimitiveType.TInteger),
Package(PrimitiveType.TFloat),
Protected(PrimitiveType.TLong),
Private(PrimitiveType.TDouble);
Visibility(PrimitiveType type) { mAssociatedType = type; }
public PrimitiveType mAssociatedType;
}
enum Behaviour {
Granted,
Warning,
Denied,
}
// This needs to be kept in sync with DexDomain in Main.
enum DexDomain {
CorePlatform,
Platform,
Application
}
private static final boolean booleanValues[] = new boolean[] { false, true };
public static void runTest(String libFileName, int parentDomainOrdinal,
int childDomainOrdinal, boolean everythingWhitelisted) throws Exception {
System.load(libFileName);
parentDomain = DexDomain.values()[parentDomainOrdinal];
childDomain = DexDomain.values()[childDomainOrdinal];
configMessage = "parentDomain=" + parentDomain.name() + ", childDomain=" + childDomain.name()
+ ", everythingWhitelisted=" + everythingWhitelisted;
// Check expectations about loading into boot class path.
boolean isParentInBoot = (ParentClass.class.getClassLoader().getParent() == null);
boolean expectedParentInBoot = (parentDomain != DexDomain.Application);
if (isParentInBoot != expectedParentInBoot) {
throw new RuntimeException("Expected ParentClass " +
(expectedParentInBoot ? "" : "not ") + "in boot class path");
}
boolean isChildInBoot = (ChildClass.class.getClassLoader().getParent() == null);
boolean expectedChildInBoot = (childDomain != DexDomain.Application);
if (isChildInBoot != expectedChildInBoot) {
throw new RuntimeException("Expected ChildClass " + (expectedChildInBoot ? "" : "not ") +
"in boot class path");
}
ChildClass.everythingWhitelisted = everythingWhitelisted;
boolean isSameBoot = (isParentInBoot == isChildInBoot);
boolean isDebuggable = VMRuntime.getRuntime().isJavaDebuggable();
// For compat reasons, meta-reflection should still be usable by apps if hidden api check
// hardening is disabled (i.e. target SDK is Q or earlier). The only configuration where this
// workaround used to work is for ChildClass in the Application domain and ParentClass in the
// Platform domain, so only test that configuration with hidden api check hardening disabled.
boolean testHiddenApiCheckHardeningDisabled =
(childDomain == DexDomain.Application) && (parentDomain == DexDomain.Platform);
// Run meaningful combinations of access flags.
for (Hiddenness hiddenness : Hiddenness.values()) {
final Behaviour expected;
final boolean invokesMemberCallback;
// Warnings are now disabled whenever access is granted, even for
// greylisted APIs. This is the behaviour for release builds.
if (everythingWhitelisted || hiddenness == Hiddenness.Whitelist) {
expected = Behaviour.Granted;
invokesMemberCallback = false;
} else if (parentDomain == DexDomain.CorePlatform && childDomain == DexDomain.Platform) {
expected = (hiddenness == Hiddenness.BlacklistAndCorePlatformApi)
? Behaviour.Granted : Behaviour.Denied;
invokesMemberCallback = false;
} else if (isSameBoot) {
expected = Behaviour.Granted;
invokesMemberCallback = false;
} else if (hiddenness == Hiddenness.Blacklist ||
hiddenness == Hiddenness.BlacklistAndCorePlatformApi) {
expected = Behaviour.Denied;
invokesMemberCallback = true;
} else {
expected = Behaviour.Warning;
invokesMemberCallback = true;
}
for (boolean isStatic : booleanValues) {
String suffix = (isStatic ? "Static" : "") + hiddenness.name();
for (Visibility visibility : Visibility.values()) {
// Test reflection and JNI on methods and fields
for (Class klass : new Class<?>[] { ParentClass.class, ParentInterface.class }) {
String baseName = visibility.name() + suffix;
checkField(klass, "field" + baseName, isStatic, visibility, expected,
invokesMemberCallback, testHiddenApiCheckHardeningDisabled);
checkMethod(klass, "method" + baseName, isStatic, visibility, expected,
invokesMemberCallback, testHiddenApiCheckHardeningDisabled);
}
// Check whether one can use a class constructor.
checkConstructor(ParentClass.class, visibility, hiddenness, expected,
testHiddenApiCheckHardeningDisabled);
// Check whether one can use an interface default method.
String name = "method" + visibility.name() + "Default" + hiddenness.name();
checkMethod(ParentInterface.class, name, /*isStatic*/ false, visibility, expected,
invokesMemberCallback, testHiddenApiCheckHardeningDisabled);
}
// Test whether static linking succeeds.
checkLinking("LinkFieldGet" + suffix, /*takesParameter*/ false, expected);
checkLinking("LinkFieldSet" + suffix, /*takesParameter*/ true, expected);
checkLinking("LinkMethod" + suffix, /*takesParameter*/ false, expected);
checkLinking("LinkMethodInterface" + suffix, /*takesParameter*/ false, expected);
}
// Check whether Class.newInstance succeeds.
checkNullaryConstructor(Class.forName("NullaryConstructor" + hiddenness.name()), expected);
}
}
static final class RecordingConsumer implements Consumer<String> {
public String recordedValue = null;
@Override
public void accept(String value) {
recordedValue = value;
}
}
private static void checkMemberCallback(Class<?> klass, String name,
boolean isPublic, boolean isField, boolean expectedCallback) {
try {
RecordingConsumer consumer = new RecordingConsumer();
VMRuntime.setNonSdkApiUsageConsumer(consumer);
try {
if (isPublic) {
if (isField) {
klass.getField(name);
} else {
klass.getMethod(name);
}
} else {
if (isField) {
klass.getDeclaredField(name);
} else {
klass.getDeclaredMethod(name);
}
}
} catch (NoSuchFieldException|NoSuchMethodException ignored) {
// We're not concerned whether an exception is thrown or not - we're
// only interested in whether the callback is invoked.
}
boolean actualCallback = consumer.recordedValue != null &&
consumer.recordedValue.contains(name);
if (expectedCallback != actualCallback) {
if (expectedCallback) {
throw new RuntimeException("Expected callback for member: " + name);
} else {
throw new RuntimeException("Did not expect callback for member: " + name);
}
}
} finally {
VMRuntime.setNonSdkApiUsageConsumer(null);
}
}
private static void checkField(Class<?> klass, String name, boolean isStatic,
Visibility visibility, Behaviour behaviour, boolean invokesMemberCallback,
boolean testHiddenApiCheckHardeningDisabled) throws Exception {
boolean isPublic = (visibility == Visibility.Public);
boolean canDiscover = (behaviour != Behaviour.Denied);
if (klass.isInterface() && (!isStatic || !isPublic)) {
// Interfaces only have public static fields.
return;
}
// Test discovery with reflection.
if (Reflection.canDiscoverWithGetDeclaredField(klass, name) != canDiscover) {
throwDiscoveryException(klass, name, true, "getDeclaredField()", canDiscover);
}
if (Reflection.canDiscoverWithGetDeclaredFields(klass, name) != canDiscover) {
throwDiscoveryException(klass, name, true, "getDeclaredFields()", canDiscover);
}
if (Reflection.canDiscoverWithGetField(klass, name) != (canDiscover && isPublic)) {
throwDiscoveryException(klass, name, true, "getField()", (canDiscover && isPublic));
}
if (Reflection.canDiscoverWithGetFields(klass, name) != (canDiscover && isPublic)) {
throwDiscoveryException(klass, name, true, "getFields()", (canDiscover && isPublic));
}
// Test discovery with JNI.
if (JNI.canDiscoverField(klass, name, isStatic) != canDiscover) {
throwDiscoveryException(klass, name, true, "JNI", canDiscover);
}
// Test discovery with MethodHandles.lookup() which is caller
// context sensitive.
final MethodHandles.Lookup lookup = MethodHandles.lookup();
if (JLI.canDiscoverWithLookupFindGetter(lookup, klass, name, int.class)
!= canDiscover) {
throwDiscoveryException(klass, name, true, "MethodHandles.lookup().findGetter()",
canDiscover);
}
if (JLI.canDiscoverWithLookupFindStaticGetter(lookup, klass, name, int.class)
!= canDiscover) {
throwDiscoveryException(klass, name, true, "MethodHandles.lookup().findStaticGetter()",
canDiscover);
}
// Test discovery with MethodHandles.publicLookup() which can only
// see public fields. Looking up setters here and fields in
// interfaces are implicitly final.
final MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
if (JLI.canDiscoverWithLookupFindSetter(publicLookup, klass, name, int.class)
!= canDiscover) {
throwDiscoveryException(klass, name, true, "MethodHandles.publicLookup().findSetter()",
canDiscover);
}
if (JLI.canDiscoverWithLookupFindStaticSetter(publicLookup, klass, name, int.class)
!= canDiscover) {
throwDiscoveryException(klass, name, true, "MethodHandles.publicLookup().findStaticSetter()",
canDiscover);
}
// Check for meta reflection.
// With hidden api check hardening enabled, only white and light greylisted fields should be
// discoverable.
if (Reflection.canDiscoverFieldWithMetaReflection(klass, name, true) != canDiscover) {
throwDiscoveryException(klass, name, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
if (testHiddenApiCheckHardeningDisabled) {
// With hidden api check hardening disabled, all fields should be discoverable.
if (Reflection.canDiscoverFieldWithMetaReflection(klass, name, false) != true) {
throwDiscoveryException(klass, name, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
}
if (canDiscover) {
// Test that modifiers are unaffected.
if (Reflection.canObserveFieldHiddenAccessFlags(klass, name)) {
throwModifiersException(klass, name, true);
}
// Test getters and setters when meaningful.
if (!Reflection.canGetField(klass, name)) {
throwAccessException(klass, name, true, "Field.getInt()");
}
if (!Reflection.canSetField(klass, name)) {
throwAccessException(klass, name, true, "Field.setInt()");
}
if (!JNI.canGetField(klass, name, isStatic)) {
throwAccessException(klass, name, true, "getIntField");
}
if (!JNI.canSetField(klass, name, isStatic)) {
throwAccessException(klass, name, true, "setIntField");
}
}
// Test that callbacks are invoked correctly.
checkMemberCallback(klass, name, isPublic, true /* isField */, invokesMemberCallback);
}
private static void checkMethod(Class<?> klass, String name, boolean isStatic,
Visibility visibility, Behaviour behaviour, boolean invokesMemberCallback,
boolean testHiddenApiCheckHardeningDisabled) throws Exception {
boolean isPublic = (visibility == Visibility.Public);
if (klass.isInterface() && !isPublic) {
// All interface members are public.
return;
}
boolean canDiscover = (behaviour != Behaviour.Denied);
// Test discovery with reflection.
if (Reflection.canDiscoverWithGetDeclaredMethod(klass, name) != canDiscover) {
throwDiscoveryException(klass, name, false, "getDeclaredMethod()", canDiscover);
}
if (Reflection.canDiscoverWithGetDeclaredMethods(klass, name) != canDiscover) {
throwDiscoveryException(klass, name, false, "getDeclaredMethods()", canDiscover);
}
if (Reflection.canDiscoverWithGetMethod(klass, name) != (canDiscover && isPublic)) {
throwDiscoveryException(klass, name, false, "getMethod()", (canDiscover && isPublic));
}
if (Reflection.canDiscoverWithGetMethods(klass, name) != (canDiscover && isPublic)) {
throwDiscoveryException(klass, name, false, "getMethods()", (canDiscover && isPublic));
}
// Test discovery with JNI.
if (JNI.canDiscoverMethod(klass, name, isStatic) != canDiscover) {
throwDiscoveryException(klass, name, false, "JNI", canDiscover);
}
// Test discovery with MethodHandles.lookup().
final MethodHandles.Lookup lookup = MethodHandles.lookup();
final MethodType methodType = MethodType.methodType(int.class);
if (JLI.canDiscoverWithLookupFindVirtual(lookup, klass, name, methodType) != canDiscover) {
throwDiscoveryException(klass, name, false, "MethodHandles.lookup().findVirtual()",
canDiscover);
}
if (JLI.canDiscoverWithLookupFindStatic(lookup, klass, name, methodType) != canDiscover) {
throwDiscoveryException(klass, name, false, "MethodHandles.lookup().findStatic()",
canDiscover);
}
// Check for meta reflection.
// With hidden api check hardening enabled, only white and light greylisted methods should be
// discoverable.
if (Reflection.canDiscoverMethodWithMetaReflection(klass, name, true) != canDiscover) {
throwDiscoveryException(klass, name, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
if (testHiddenApiCheckHardeningDisabled) {
// With hidden api check hardening disabled, all methods should be discoverable.
if (Reflection.canDiscoverMethodWithMetaReflection(klass, name, false) != true) {
throwDiscoveryException(klass, name, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
}
// Finish here if we could not discover the method.
if (canDiscover) {
// Test that modifiers are unaffected.
if (Reflection.canObserveMethodHiddenAccessFlags(klass, name)) {
throwModifiersException(klass, name, false);
}
// Test whether we can invoke the method. This skips non-static interface methods.
if (!klass.isInterface() || isStatic) {
if (!Reflection.canInvokeMethod(klass, name)) {
throwAccessException(klass, name, false, "invoke()");
}
if (!JNI.canInvokeMethodA(klass, name, isStatic)) {
throwAccessException(klass, name, false, "CallMethodA");
}
if (!JNI.canInvokeMethodV(klass, name, isStatic)) {
throwAccessException(klass, name, false, "CallMethodV");
}
}
}
// Test that callbacks are invoked correctly.
checkMemberCallback(klass, name, isPublic, false /* isField */, invokesMemberCallback);
}
private static void checkConstructor(Class<?> klass, Visibility visibility, Hiddenness hiddenness,
Behaviour behaviour, boolean testHiddenApiCheckHardeningDisabled) throws Exception {
boolean isPublic = (visibility == Visibility.Public);
String signature = "(" + visibility.mAssociatedType.mShorty +
hiddenness.mAssociatedType.mShorty + ")V";
String fullName = "<init>" + signature;
Class<?> args[] = new Class[] { visibility.mAssociatedType.mClass,
hiddenness.mAssociatedType.mClass };
Object initargs[] = new Object[] { visibility.mAssociatedType.mDefaultValue,
hiddenness.mAssociatedType.mDefaultValue };
MethodType methodType = MethodType.methodType(void.class, args);
boolean canDiscover = (behaviour != Behaviour.Denied);
// Test discovery with reflection.
if (Reflection.canDiscoverWithGetDeclaredConstructor(klass, args) != canDiscover) {
throwDiscoveryException(klass, fullName, false, "getDeclaredConstructor()", canDiscover);
}
if (Reflection.canDiscoverWithGetDeclaredConstructors(klass, args) != canDiscover) {
throwDiscoveryException(klass, fullName, false, "getDeclaredConstructors()", canDiscover);
}
if (Reflection.canDiscoverWithGetConstructor(klass, args) != (canDiscover && isPublic)) {
throwDiscoveryException(
klass, fullName, false, "getConstructor()", (canDiscover && isPublic));
}
if (Reflection.canDiscoverWithGetConstructors(klass, args) != (canDiscover && isPublic)) {
throwDiscoveryException(
klass, fullName, false, "getConstructors()", (canDiscover && isPublic));
}
// Test discovery with JNI.
if (JNI.canDiscoverConstructor(klass, signature) != canDiscover) {
throwDiscoveryException(klass, fullName, false, "JNI", canDiscover);
}
// Test discovery with MethodHandles.lookup()
final MethodHandles.Lookup lookup = MethodHandles.lookup();
if (JLI.canDiscoverWithLookupFindConstructor(lookup, klass, methodType) != canDiscover) {
throwDiscoveryException(klass, fullName, false, "MethodHandles.lookup().findConstructor",
canDiscover);
}
final MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
if (JLI.canDiscoverWithLookupFindConstructor(publicLookup, klass, methodType) != canDiscover) {
throwDiscoveryException(klass, fullName, false,
"MethodHandles.publicLookup().findConstructor",
canDiscover);
}
// Check for meta reflection.
// With hidden api check hardening enabled, only white and light greylisted constructors should
// be discoverable.
if (Reflection.canDiscoverConstructorWithMetaReflection(klass, args, true) != canDiscover) {
throwDiscoveryException(klass, fullName, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
if (testHiddenApiCheckHardeningDisabled) {
// With hidden api check hardening disabled, all constructors should be discoverable.
if (Reflection.canDiscoverConstructorWithMetaReflection(klass, args, false) != true) {
throwDiscoveryException(klass, fullName, false,
"Meta reflection with hidden api hardening enabled", canDiscover);
}
}
if (canDiscover) {
// Test whether we can invoke the constructor.
if (!Reflection.canInvokeConstructor(klass, args, initargs)) {
throwAccessException(klass, fullName, false, "invoke()");
}
if (!JNI.canInvokeConstructorA(klass, signature)) {
throwAccessException(klass, fullName, false, "NewObjectA");
}
if (!JNI.canInvokeConstructorV(klass, signature)) {
throwAccessException(klass, fullName, false, "NewObjectV");
}
}
}
private static void checkNullaryConstructor(Class<?> klass, Behaviour behaviour)
throws Exception {
boolean canAccess = (behaviour != Behaviour.Denied);
if (Reflection.canUseNewInstance(klass) != canAccess) {
throw new RuntimeException("Expected to " + (canAccess ? "" : "not ") +
"be able to construct " + klass.getName() + ". " + configMessage);
}
}
private static void checkLinking(String className, boolean takesParameter, Behaviour behaviour)
throws Exception {
boolean canAccess = (behaviour != Behaviour.Denied);
if (Linking.canAccess(className, takesParameter) != canAccess) {
throw new RuntimeException("Expected to " + (canAccess ? "" : "not ") +
"be able to verify " + className + "." + configMessage);
}
}
private static void throwDiscoveryException(Class<?> klass, String name, boolean isField,
String fn, boolean canAccess) {
throw new RuntimeException("Expected " + (isField ? "field " : "method ") + klass.getName() +
"." + name + " to " + (canAccess ? "" : "not ") + "be discoverable with " + fn + ". " +
configMessage);
}
private static void throwAccessException(Class<?> klass, String name, boolean isField,
String fn) {
throw new RuntimeException("Expected to be able to access " + (isField ? "field " : "method ") +
klass.getName() + "." + name + " using " + fn + ". " + configMessage);
}
private static void throwModifiersException(Class<?> klass, String name, boolean isField) {
throw new RuntimeException("Expected " + (isField ? "field " : "method ") + klass.getName() +
"." + name + " to not expose hidden modifiers");
}
private static DexDomain parentDomain;
private static DexDomain childDomain;
private static boolean everythingWhitelisted;
private static String configMessage;
}
|
/**
* Copyright (C) 2008 Atlassian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atlassian.theplugin.idea.ui.tree;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
public abstract class AtlassianTreeNode extends DefaultMutableTreeNode implements Comparable {
private AtlassianClickAction action;
protected AtlassianTreeNode(AtlassianClickAction action) {
this.action = action;
}
public void addNode(AtlassianTreeNode newChild) {
super.add(newChild);
}
@Override
public AtlassianTreeNode getChildAt(final int i) {
return (AtlassianTreeNode) super.getChildAt(i);
}
public abstract TreeCellRenderer getTreeCellRenderer();
public AtlassianClickAction getAtlassianClickAction() {
return action;
}
public abstract AtlassianTreeNode getClone();
public AtlassianTreeNode filter(final Filter filter) {
AtlassianTreeNode result = null;
if (filter.isValid(this)) {
AtlassianTreeNode tempResult = getClone();
boolean foundValidChild = false;
for (int i = 0; i < getChildCount(); i++) {
AtlassianTreeNode child = getChildAt(i).filter(filter);
if (child != null) {
foundValidChild = true;
tempResult.addNode(child);
}
}
if (foundValidChild || getChildCount() == 0) {
result = tempResult;
}
}
return result;
}
public static final AtlassianTreeNode EMPTY_NODE = new AtlassianTreeNode(AtlassianClickAction.EMPTY_ACTION) {
@Override
public TreeCellRenderer getTreeCellRenderer() {
return new TreeCellRenderer() {
public Component getTreeCellRendererComponent(final JTree jTree, final Object o, final boolean b,
final boolean b1, final boolean b2, final int i, final boolean b3) {
return new JLabel("<Empty>");
}
};
}
@Override
public AtlassianTreeNode getClone() {
return AtlassianTreeNode.EMPTY_NODE;
}
public int compareTo(Object o) {
// hmm, is it ok?
return -1;
}
};
}
|
package com.youkol.sms.core.exception;
/**
* 短信第三方账户余额不足
*
* @author jackiea
*/
public class SmsInsufficientException extends SmsException {
private static final long serialVersionUID = 1L;
public SmsInsufficientException(String msg) {
super(msg);
}
public SmsInsufficientException(String msg, Exception ex) {
super(msg, ex);
}
public SmsInsufficientException(Exception ex) {
super(ex);
}
}
|
package org.appsugar.service.account;
import static org.mockito.Mockito.when;
import org.appsugar.BaseServiceMockTestCase;
import org.appsugar.entity.account.User;
import org.appsugar.repository.account.UserRepository;
import org.appsugar.service.account.impl.UserServiceImpl;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
/**
*
* @author NewYoung
* 2016年2月26日下午2:25:46
*/
public class UserServiceMockTest extends BaseServiceMockTestCase {
private UserService userService;
@Mock
private UserRepository userRepository;
public UserServiceMockTest() {
userService = new UserServiceImpl().setUserRepository(userRepository);
}
@Test
public void testGetByName() {
String loginName = "admin";
User user = new User();
when(userRepository.findByLoginName(loginName)).thenReturn(user);
Assert.assertEquals(user, userService.getByLoginName(loginName));
}
}
|
package aula_0520.arvoresOO;
public class No {
}
|
package ziegler.concurrent;
public class Elevator {
private int currentFloor;
private int requestedFloor;
public boolean isInUse() {
return requestedFloor > 0;
}
//need to make method thread safe
public void setRequestedFloor(int requestedFloor) {
if(isInUse()){
return;
}
this.requestedFloor = requestedFloor;
}
}
|
package uchet.service.indocs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import uchet.models.*;
import uchet.repository.*;
import uchet.service.filter.*;
import uchet.utils.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@Service
public class InDocServiceImpl implements InDocService {
private static final int NUMBER_OF_DIGITS_IN_DOC_NUMBER = 10;
@Value("#{new Double('${value-added-tax}')}")
private double vatValue;
private InDocRepository inDocRepository;
private InDocDetailRepository inDocDetailRepository;
private SkuRepository skuRepository;
private ContractorRepository contractorRepository;
private InDocTypeRepository inDocTypeRepository;
private UserRepository userRepository;
@Override
public List<InDoc> getAllInLastMonth() {
List<InDoc> documents = inDocRepository.getAllInLastMonth();
return removeBackReferences(documents);
}
@Override
public List<InDoc> findByFilter(Map<String, String> filterParams, SpecificationConstructor<InDoc> constructor) {
Function<Specification<InDoc>, List<InDoc>> function = spc -> inDocRepository.findAll(spc);
FilterService<InDoc> filterService = new FilterServiceImpl<>(function, constructor);
return removeBackReferences(filterService.findEntriesByFilter(filterParams));
}
@Override
public InDoc getByInDocNumber(String inDocNumber) {
InDoc inDoc = inDocRepository.findByDocNumber(inDocNumber);
List<InDoc> documents = List.of(inDoc);
return removeBackReferences(documents).get(0);
}
@Transactional
@Override
public Map<String, String> addInDoc(InDoc inDoc) {
String resultMessage = "OK";
String docNumber = generateDocNumber();
String docDate = Util.generateCurrentTimeStamp();
InDocType type = inDocTypeRepository.findByDocType(inDoc.getType().getDocType());
Contractor contractor = contractorRepository.findByName(inDoc.getContractor().getName());
User owner = userRepository.findByLogin(inDoc.getOwner().getLogin());
InDoc newInDoc = new InDoc(docNumber, contractor, owner, type);
newInDoc.setDocDate(docDate);
inDocRepository.save(newInDoc);
InDoc savedInDoc = inDocRepository.findByDocNumber(docNumber);
if (savedInDoc != null) {
List<InDocDetail> details = getDetailsList(inDoc);
addDetails(details, savedInDoc);
} else {
resultMessage = "Возникла непредвиденная ошибка сохранения";
}
Map<String, String> result = new HashMap<>();
result.put("addResult", resultMessage);
return result;
}
@Transactional
@Override
public Map<String, String> updateInDoc(InDoc inDoc) {
return null;
}
@Transactional
@Override
public Map<String, String> deleteInDoc(String id) {
return null;
}
private List<InDocDetail> getDetailsList(InDoc inDoc) {
List<InDocDetail> details = new ArrayList<>();
List<InDocDetail> detailsFromClient = inDoc.getDetails();
for (InDocDetail eachDetail: detailsFromClient) {
InDocDetail inDocDetail = new InDocDetail();
Sku sku = skuRepository.findByCode(eachDetail.getSku().getCode());
inDocDetail.setSku(sku);
inDocDetail.setQty(eachDetail.getQty());
inDocDetail.setPrice(eachDetail.getPrice());
inDocDetail.setVatPrice(eachDetail.getPrice() * this.vatValue);
inDocDetail.setSerial(eachDetail.getSerial());
if (!eachDetail.getExpireDate().equals("")) {
inDocDetail.setExpireDate(Util.formatExpireDate(eachDetail.getExpireDate()));
}
details.add(inDocDetail);
}
return details;
}
private void addDetails(List<InDocDetail> details, InDoc inDoc) {
for (InDocDetail eachDetail: details) {
eachDetail.setInDoc(inDoc);
inDocDetailRepository.save(eachDetail);
}
}
private String generateDocNumber() {
int number = inDocRepository.findMaxDocNumber();
String lastNumber = String.valueOf(number + 1);
StringBuilder sb = new StringBuilder(lastNumber);
for (int i = NUMBER_OF_DIGITS_IN_DOC_NUMBER; i > lastNumber.length(); i--) {
sb.insert(0, "0");
}
return sb.toString();
}
private List<InDoc> removeBackReferences(List<InDoc> documents) {
documents.stream().forEach(each -> {
List<InDocDetail> details = each.getDetails();
details.stream().forEach(eachDetail -> eachDetail.setInDoc(null));
});
return documents;
}
@Autowired
public void setInDocRepository(InDocRepository inDocRepository) {
this.inDocRepository = inDocRepository;
}
@Autowired
public void setSkuRepository(SkuRepository skuRepository) {
this.skuRepository = skuRepository;
}
@Autowired
public void setContractorRepository(ContractorRepository contractorRepository) {
this.contractorRepository = contractorRepository;
}
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setInDocTypeRepository(InDocTypeRepository inDocTypeRepository) {
this.inDocTypeRepository = inDocTypeRepository;
}
@Autowired
public void setInDocDetailRepository(InDocDetailRepository inDocDetailRepository) {
this.inDocDetailRepository = inDocDetailRepository;
}
}
|
//package com.oa.email;
//
//import com.oa.email.entity.MailServer;
//import com.oa.email.service.MailService;
//import com.oa.email.service.MailServiceImpl;
//
//public class SendMailDemo {
// public static void main(String[] args) {
// // 设置邮件服务器信息
// MailServer mailInfo = new MailServer();
// mailInfo.setMailServerHost("smtp.163.com");
// mailInfo.setMailServerPort("25");
// mailInfo.setValidate(true);
//
// // 邮箱用户名
// mailInfo.setUserName("15216109743@163.com");
// // 邮箱密码
// mailInfo.setPassword("ab150156");
// // 发件人邮箱
// mailInfo.setFromAddress("15216109743@163.com");
// // 收件人邮箱
// mailInfo.setToAddress("815899718@qq.com");
// // 邮件标题
// mailInfo.setSubject("yuyanwenzi");
// // 邮件内容
// StringBuffer buffer = new StringBuffer();
// buffer.append("from 15216109743@163.com\n");
// buffer.append("to 344553788@qq.com");
// mailInfo.setContent(buffer.toString());
//
// // 发送邮件
// MailService sms = new MailServiceImpl();
// // 发送文体格式
// sms.sendTextMail(mailInfo);
// // 发送html格式
// sms.sendHtmlMail(mailInfo);
// System.out.println("邮件发送完毕");
// }
//}
|
package services;
import java.io.IOException;
import java.nio.channels.SelectionKey;
/**
* Интерфейс, отвечающий за приём подключений к серверу
*/
public interface ClientAcceptor {
/**
* Блок, отвечающий за принятие подключений
* @param key - ключ селектора
* @throws IOException - исключение ввода/вывода
*/
void accept(SelectionKey key) throws IOException;
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest;
import org.neuro4j.studio.core.ActionNode;
import org.neuro4j.studio.core.OperatorOutput;
import org.neuro4j.studio.core.diagram.edit.policies.Neuro4jBaseItemSemanticEditPolicy;
/**
* @generated
*/
public class OperatorOutputReorientCommand extends EditElementCommand {
/**
* @generated
*/
private final int reorientDirection;
/**
* @generated
*/
private final EObject oldEnd;
/**
* @generated
*/
private final EObject newEnd;
/**
* @generated
*/
public OperatorOutputReorientCommand(ReorientRelationshipRequest request) {
super(request.getLabel(), request.getRelationship(), request);
reorientDirection = request.getDirection();
oldEnd = request.getOldRelationshipEnd();
newEnd = request.getNewRelationshipEnd();
}
/**
* @generated
*/
public boolean canExecute() {
if (false == getElementToEdit() instanceof OperatorOutput) {
return false;
}
if (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) {
return canReorientSource();
}
if (reorientDirection == ReorientRelationshipRequest.REORIENT_TARGET) {
return canReorientTarget();
}
return false;
}
/**
* @generated
*/
protected boolean canReorientSource() {
if (!(oldEnd instanceof ActionNode && newEnd instanceof ActionNode)) {
return false;
}
ActionNode target = getLink().getTarget();
return Neuro4jBaseItemSemanticEditPolicy.getLinkConstraints()
.canExistOperatorOutput_4008(getLink(), getNewSource(), target);
}
/**
* @generated
*/
protected boolean canReorientTarget() {
if (!(oldEnd instanceof ActionNode && newEnd instanceof ActionNode)) {
return false;
}
if (!(getLink().eContainer() instanceof ActionNode)) {
return false;
}
ActionNode source = (ActionNode) getLink().eContainer();
return Neuro4jBaseItemSemanticEditPolicy.getLinkConstraints()
.canExistOperatorOutput_4008(getLink(), source, getNewTarget());
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor,
IAdaptable info) throws ExecutionException {
if (!canExecute()) {
throw new ExecutionException("Invalid arguments in reorient link command"); //$NON-NLS-1$
}
if (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) {
return reorientSource();
}
if (reorientDirection == ReorientRelationshipRequest.REORIENT_TARGET) {
return reorientTarget();
}
throw new IllegalStateException();
}
/**
* @generated
*/
protected CommandResult reorientSource() throws ExecutionException {
throw new UnsupportedOperationException();
}
/**
* @generated
*/
protected CommandResult reorientTarget() throws ExecutionException {
getLink().setTarget(getNewTarget());
return CommandResult.newOKCommandResult(getLink());
}
/**
* @generated
*/
protected OperatorOutput getLink() {
return (OperatorOutput) getElementToEdit();
}
/**
* @generated
*/
protected ActionNode getOldSource() {
return (ActionNode) oldEnd;
}
/**
* @generated
*/
protected ActionNode getNewSource() {
return (ActionNode) newEnd;
}
/**
* @generated
*/
protected ActionNode getOldTarget() {
return (ActionNode) oldEnd;
}
/**
* @generated
*/
protected ActionNode getNewTarget() {
return (ActionNode) newEnd;
}
}
|
package com.infohold.bdrp.authority.shiro.session.dao.impl;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
//@Component("cacheManager")
public class RedisCacheManagerImpl extends AbstractCacheManager implements InitializingBean {
private static final Logger log = LoggerFactory
.getLogger(RedisCacheManagerImpl.class);
@Autowired
private RedisConnectionFactory connectionFactory;
/**
* The wrapped Jedis instance.
*/
private RedisTemplate<Object, Object> redisTemplate;
private RedisSerializer<Object> defaultSerializer = new JdkSerializationRedisSerializer();
/**
* The Redis key prefix for the sessions
*/
@Value("${app.session.cache.redis.prefix:app:cache:}")
private String keyPrefix = "app:cache:";
@Override
protected Cache<Object, Object> createCache(String name) throws CacheException {
log.debug("获取名称为: " + name + " 的RedisCache实例");
return new RedisCache<Object, Object>(redisTemplate,keyPrefix);
}
private void initRedisTemplate() {
this.redisTemplate = new RedisTemplate<Object, Object>();
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
// this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
this.redisTemplate.setDefaultSerializer(this.defaultSerializer);
this.redisTemplate.setConnectionFactory(connectionFactory);
this.redisTemplate.afterPropertiesSet();
}
@Override
public void afterPropertiesSet() throws Exception {
this.initRedisTemplate();
}
}
|
package com.ibisek.outlanded.storage;
import java.util.List;
import com.ibisek.outlanded.R;
import android.content.Context;
public class TemplatesDao {
private static final String MESSAGE_TEMPLATES_FILENAME = "message-templates.bin";
private Context context;
private InternalStorage<Templates> storage;
public TemplatesDao(Context context) {
this.context = context;
storage = new InternalStorage<Templates>(MESSAGE_TEMPLATES_FILENAME, context);
}
/**
* Loads templates from internal storage file. In case the file does not exist
* (yet), populates it with default templates.
*
* @return
*/
public Templates loadTemplates() {
Templates templates = storage.load();
if (templates == null) { // populate with default templates
templates = new Templates();
List<String> list = templates.getTemplates();
list.add(context.getString(R.string.template_default_1));
list.add(context.getString(R.string.template_default_2));
list.add(context.getString(R.string.template_default_3));
templates.setSelectedIndex(0);
saveTemplates(templates);
}
return templates;
}
public void saveTemplates(Templates templates) {
storage.save(templates);
}
}
|
package com.example.ivan.memento;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import cz.msebera.android.httpclient.Header;
public class Registration extends AppCompatActivity {
private EditText usernameView;
private EditText passwordView;
private EditText emailView;
private EditText nameView;
private EditText surnameView;
private EditText date_of_birthView;
private String risposta;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Intent i = new Intent(getBaseContext(), MainActivity.class);
//assegnazione risorse
usernameView = (EditText) findViewById(R.id.username);
passwordView = (EditText) findViewById(R.id.password);
emailView = (EditText) findViewById(R.id.email);
nameView = (EditText) findViewById(R.id.name);
surnameView = (EditText) findViewById(R.id.surname);
date_of_birthView = (EditText) findViewById(R.id.date_of_birth);
Button signupButton = (Button) findViewById(R.id.signup);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registration();
startActivity(new Intent(Registration.this,MainActivity.class));
}
});
}
private void registration() {
String username = usernameView.getText().toString();
String password = passwordView.getText().toString();
String email = emailView.getText().toString();
String name = nameView.getText().toString();
String surname = surnameView.getText().toString();
String date_of_birth = date_of_birthView.getText().toString();
final AsyncHttpClient client = new AsyncHttpClient();
RequestParams ps = new RequestParams();
boolean cancel = false;
View focusView = null;
//controllo validità campi
try {
if (TextUtils.isEmpty(username)) {//il campo non deve essere vuoto
usernameView.setError(getString(R.string.error_field_required));
focusView = usernameView;
cancel = true;
} else if (!isUsernameValid(username)) {//username.length>4
usernameView.setError(getString(R.string.error_invalid_username));
focusView = usernameView;
cancel = true;
}
if (TextUtils.isEmpty(password)) {//il campo non deve essere vuoto
passwordView.setError(getString(R.string.error_field_required));
focusView = passwordView;
cancel = true;
} else if (!isPasswordValid(password)) {//password.length>8
passwordView.setError(getString(R.string.error_invalid_password));
focusView = usernameView;
cancel=true;
}
if (TextUtils.isEmpty(email)) {//il campo non deve essere vuoto
emailView.setError(getString(R.string.error_field_required));
focusView = emailView;
cancel = true;
}
if (TextUtils.isEmpty(name)) {//il campo non deve essere vuoto
nameView.setError(getString(R.string.error_field_required));
focusView = nameView;
cancel = true;
}
if (TextUtils.isEmpty(surname)) {//il campo non deve essere vuoto
surnameView.setError(getString(R.string.error_field_required));
focusView = surnameView;
cancel = true;
}
if (TextUtils.isEmpty(date_of_birth)) {//il campo non deve essere vuoto
date_of_birthView.setError(getString(R.string.error_field_required));
focusView = date_of_birthView;
cancel = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
ps.put("username", username);
ps.put("password", password);
ps.put("email", email);
ps.put("name", name);
ps.put("surname", surname);
ps.put("date_of_birth", date_of_birth);
//Invio JSON
client.post("http://192.168.1.99/memento/?action=auth", ps, new AsyncHttpResponseHandler() {
public void onStart() {
super.onStart();
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(getApplicationContext(), "Trasferimento avvenuto con successo", Toast.LENGTH_LONG).show();
try {
risposta = new String(responseBody, "UTF-8");
JSONObject main = new JSONObject(risposta);
Toast.makeText(getApplicationContext(), main.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Toast.makeText(getApplicationContext(), "Errore nel trasferimento", Toast.LENGTH_LONG).show();
}
});
}
}
private boolean isUsernameValid(String username) {
return username.length() > 4;
}
private boolean isPasswordValid(String password) {
return password.length() > 8;
}
}
|
package com.example.lbyanBack.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.lbyanBack.mapper.LjxxMapper;
import com.example.lbyanBack.pojo.Ljlx;
import com.example.lbyanBack.pojo.Ljxx;
import com.example.lbyanBack.pojo.DTO.LjxxDTO;
import com.example.lbyanBack.service.ILjxxService;
@Service
public class LjxxServiceImpl implements ILjxxService {
@Autowired
private LjxxMapper ljxxmaper;
@Override
public List<LjxxDTO> getAllLjxx() {
List<Ljxx> ljxx = ljxxmaper.getAllLjxx();
List<Ljlx> ljlx = ljxxmaper.getAllLjlx();
List<LjxxDTO> ljxxs = new ArrayList<>();
for (Ljlx lx : ljlx) {
LjxxDTO ljxxDTO = new LjxxDTO();
List<Ljxx> ljxxlist = new ArrayList<>();
for (Ljxx xx : ljxx) {
if (xx.getPid().equals(lx.getId())) {
ljxxlist.add(xx);
}
}
ljxxDTO.setLx(lx);
ljxxDTO.setLjxx(ljxxlist);
ljxxs.add(ljxxDTO);
}
return ljxxs;
}
}
|
package com.joy.tank;
import java.util.Random;
/**
* @author joy
* @date 2021/9/13
*/
public enum Dir {
L, U, R, D;
private static Random random = new Random();
public static Dir RamDir(){
return values()[random.nextInt(values().length)];
}
}
|
package com.rory.security.core.validate.code.sms;
import com.rory.security.core.validate.code.sms.sender.SmsCodeSender;
import com.rory.security.core.validate.code.support.ValidationCode;
import com.rory.security.core.validate.code.support.impl.AbstractValidationCodeProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
@Component("smsValidationCodeProcessor")
public class SmsValidationCodeProcessor extends AbstractValidationCodeProcessor<ValidationCode> {
@Autowired
private SmsCodeSender smsCodeSender;
@Override
public void sendCode(ServletWebRequest request, ValidationCode code) throws Exception {
smsCodeSender.send(ServletRequestUtils.getRequiredStringParameter(request.getRequest(), "mobile"), code.getCode());
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.config;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.google.protobuf.Message;
import jakarta.xml.bind.annotation.XmlRootElement;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.codec.StringDecoder;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlDecoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.bind.support.WebExchangeDataBinder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.handler.AbstractUrlHandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.resource.ResourceUrlProvider;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler;
import org.springframework.web.reactive.result.view.HttpMessageWriterView;
import org.springframework.web.reactive.result.view.View;
import org.springframework.web.reactive.result.view.ViewResolutionResultHandler;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.springframework.core.ResolvableType.forClass;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaType.APPLICATION_PROTOBUF;
import static org.springframework.http.MediaType.APPLICATION_XML;
import static org.springframework.http.MediaType.IMAGE_PNG;
import static org.springframework.http.MediaType.TEXT_PLAIN;
import static org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.get;
/**
* Unit tests for {@link WebFluxConfigurationSupport}.
*
* @author Rossen Stoyanchev
*/
public class WebFluxConfigurationSupportTests {
@Test
public void requestMappingHandlerMapping() {
ApplicationContext context = loadConfig(WebFluxConfig.class);
final Field field = ReflectionUtils.findField(PathPatternParser.class, "matchOptionalTrailingSeparator");
ReflectionUtils.makeAccessible(field);
String name = "requestMappingHandlerMapping";
RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
assertThat(mapping).isNotNull();
assertThat(mapping.getOrder()).isEqualTo(0);
PathPatternParser patternParser = mapping.getPathPatternParser();
assertThat(patternParser).isNotNull();
boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser);
assertThat(matchOptionalTrailingSlash).isFalse();
name = "webFluxContentTypeResolver";
RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
assertThat(mapping.getContentTypeResolver()).isSameAs(resolver);
ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON));
assertThat(resolver.resolveMediaTypes(exchange))
.isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON));
}
@Test
public void customPathMatchConfig() {
ApplicationContext context = loadConfig(CustomPatchMatchConfig.class);
String name = "requestMappingHandlerMapping";
RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class);
assertThat(mapping).isNotNull();
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
assertThat(map).hasSize(1);
assertThat(map.keySet().iterator().next().getPatternsCondition().getPatterns())
.isEqualTo(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")));
}
@Test
public void requestMappingHandlerAdapter() {
ApplicationContext context = loadConfig(WebFluxConfig.class);
String name = "requestMappingHandlerAdapter";
RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
assertThat(adapter).isNotNull();
List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
assertThat(readers).hasSize(17);
ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class);
assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
assertHasMessageReader(readers, forClass(String.class), TEXT_PLAIN);
assertHasMessageReader(readers, forClass(Resource.class), IMAGE_PNG);
assertHasMessageReader(readers, forClass(Message.class), APPLICATION_PROTOBUF);
assertHasMessageReader(readers, multiValueMapType, APPLICATION_FORM_URLENCODED);
assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_XML);
assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_JSON);
assertHasMessageReader(readers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
assertHasMessageReader(readers, forClass(TestBean.class), null);
WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
assertThat(bindingInitializer).isNotNull();
WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
bindingInitializer.initBinder(binder);
name = "webFluxConversionService";
ConversionService service = context.getBean(name, ConversionService.class);
assertThat(binder.getConversionService()).isSameAs(service);
name = "webFluxValidator";
Validator validator = context.getBean(name, Validator.class);
assertThat(binder.getValidator()).isSameAs(validator);
}
@Test
public void customMessageConverterConfig() {
ApplicationContext context = loadConfig(CustomMessageConverterConfig.class);
String name = "requestMappingHandlerAdapter";
RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
assertThat(adapter).isNotNull();
List<HttpMessageReader<?>> messageReaders = adapter.getMessageReaders();
assertThat(messageReaders).hasSize(2);
assertHasMessageReader(messageReaders, forClass(String.class), TEXT_PLAIN);
assertHasMessageReader(messageReaders, forClass(TestBean.class), APPLICATION_XML);
}
@Test
public void responseEntityResultHandler() {
ApplicationContext context = loadConfig(WebFluxConfig.class);
String name = "responseEntityResultHandler";
ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class);
assertThat(handler).isNotNull();
assertThat(handler.getOrder()).isEqualTo(0);
List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
assertThat(writers).hasSize(17);
assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
assertHasMessageWriter(writers, forClass(String.class), TEXT_PLAIN);
assertHasMessageWriter(writers, forClass(Resource.class), IMAGE_PNG);
assertHasMessageWriter(writers, forClass(Message.class), APPLICATION_PROTOBUF);
assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_XML);
assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_JSON);
assertHasMessageWriter(writers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
assertHasMessageWriter(writers, forClass(TestBean.class), MediaType.parseMediaType("text/event-stream"));
name = "webFluxContentTypeResolver";
RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
assertThat(handler.getContentTypeResolver()).isSameAs(resolver);
}
@Test
public void responseBodyResultHandler() {
ApplicationContext context = loadConfig(WebFluxConfig.class);
String name = "responseBodyResultHandler";
ResponseBodyResultHandler handler = context.getBean(name, ResponseBodyResultHandler.class);
assertThat(handler).isNotNull();
assertThat(handler.getOrder()).isEqualTo(100);
List<HttpMessageWriter<?>> writers = handler.getMessageWriters();
assertThat(writers).hasSize(17);
assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
assertHasMessageWriter(writers, forClass(String.class), TEXT_PLAIN);
assertHasMessageWriter(writers, forClass(Resource.class), IMAGE_PNG);
assertHasMessageWriter(writers, forClass(Message.class), APPLICATION_PROTOBUF);
assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_XML);
assertHasMessageWriter(writers, forClass(TestBean.class), APPLICATION_JSON);
assertHasMessageWriter(writers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
assertHasMessageWriter(writers, forClass(TestBean.class), null);
name = "webFluxContentTypeResolver";
RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
assertThat(handler.getContentTypeResolver()).isSameAs(resolver);
}
@Test
public void viewResolutionResultHandler() {
ApplicationContext context = loadConfig(CustomViewResolverConfig.class);
String name = "viewResolutionResultHandler";
ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class);
assertThat(handler).isNotNull();
assertThat(handler.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
List<ViewResolver> resolvers = handler.getViewResolvers();
assertThat(resolvers).hasSize(1);
assertThat(resolvers.get(0).getClass()).isEqualTo(FreeMarkerViewResolver.class);
List<View> views = handler.getDefaultViews();
assertThat(views).hasSize(1);
MimeType type = MimeTypeUtils.parseMimeType("application/json");
assertThat(views.get(0).getSupportedMediaTypes().get(0)).isEqualTo(type);
}
@Test
public void resourceHandler() {
ApplicationContext context = loadConfig(CustomResourceHandlingConfig.class);
String name = "resourceHandlerMapping";
AbstractUrlHandlerMapping handlerMapping = context.getBean(name, AbstractUrlHandlerMapping.class);
assertThat(handlerMapping).isNotNull();
assertThat(handlerMapping.getOrder()).isEqualTo((Ordered.LOWEST_PRECEDENCE - 1));
SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping;
WebHandler webHandler = (WebHandler) urlHandlerMapping.getUrlMap().get("/images/**");
assertThat(webHandler).isNotNull();
}
@Test
public void resourceUrlProvider() throws Exception {
ApplicationContext context = loadConfig(WebFluxConfig.class);
String name = "resourceUrlProvider";
ResourceUrlProvider resourceUrlProvider = context.getBean(name, ResourceUrlProvider.class);
assertThat(resourceUrlProvider).isNotNull();
}
private void assertHasMessageReader(List<HttpMessageReader<?>> readers, ResolvableType type, MediaType mediaType) {
assertThat(readers.stream().anyMatch(c -> mediaType == null || c.canRead(type, mediaType))).isTrue();
}
private void assertHasMessageWriter(List<HttpMessageWriter<?>> writers, ResolvableType type, MediaType mediaType) {
assertThat(writers.stream().anyMatch(c -> mediaType == null || c.canWrite(type, mediaType))).isTrue();
}
private ApplicationContext loadConfig(Class<?>... configurationClasses) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(configurationClasses);
context.refresh();
return context;
}
@EnableWebFlux
static class WebFluxConfig {
}
@Configuration
static class CustomPatchMatchConfig extends WebFluxConfigurationSupport {
@Override
public void configurePathMatching(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
}
@Bean
UserController userController() {
return new UserController();
}
}
@RestController
@RequestMapping("/user")
static class UserController {
@GetMapping("/{id}")
public Principal getUser() {
return mock();
}
}
@Configuration
static class CustomMessageConverterConfig extends WebFluxConfigurationSupport {
@Override
protected void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
configurer.registerDefaults(false);
configurer.customCodecs().register(StringDecoder.textPlainOnly());
configurer.customCodecs().register(new Jaxb2XmlDecoder());
configurer.customCodecs().register(CharSequenceEncoder.textPlainOnly());
configurer.customCodecs().register(new Jaxb2XmlEncoder());
}
}
@Configuration
@SuppressWarnings("unused")
static class CustomViewResolverConfig extends WebFluxConfigurationSupport {
@Override
protected void configureViewResolvers(ViewResolverRegistry registry) {
registry.freeMarker();
registry.defaultViews(new HttpMessageWriterView(new Jackson2JsonEncoder()));
}
@Bean
public FreeMarkerConfigurer freeMarkerConfig() {
return new FreeMarkerConfigurer();
}
}
@Configuration
static class CustomResourceHandlingConfig extends WebFluxConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
}
}
@XmlRootElement
static class TestBean {
}
}
|
package com.rubic.demo.value;
import com.lmax.disruptor.BatchEventProcessor;
import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.util.DaemonThreadFactory;
import java.util.concurrent.*;
/**
* 三个生产者一个消费者,测试并发量
* @author rubic
*/
public class Main{
private static final int NUM_PUBLISHERS = Runtime.getRuntime().availableProcessors();
private static final int BUFFER_SIZE = 1024 * 64;
private static final long ITERATIONS = 1000L *1000L *20L;
private final ExecutorService executor = Executors.newFixedThreadPool(NUM_PUBLISHERS + 1, DaemonThreadFactory.INSTANCE);
private final CyclicBarrier cyclicBarrier = new CyclicBarrier(NUM_PUBLISHERS +1);
private final RingBuffer ringBuffer = RingBuffer.createMultiProducer(ValueEvent.EVENT_FACTORY, BUFFER_SIZE, new BusySpinWaitStrategy());
private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
private final ValueAdditionEventHandler handler = new ValueAdditionEventHandler();
private final BatchEventProcessor batchEventProcessor = new BatchEventProcessor<>(ringBuffer, sequenceBarrier, handler);
private final ValueBatchPublisher[] valuePublishers = new ValueBatchPublisher[NUM_PUBLISHERS];
{
for(int i =0; i < NUM_PUBLISHERS; i++) {
valuePublishers[i] = new ValueBatchPublisher(cyclicBarrier, ringBuffer, ITERATIONS / NUM_PUBLISHERS,16);
}
ringBuffer.addGatingSequences(batchEventProcessor.getSequence());
}
public long runDisruptorPass() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
handler.reset(latch, batchEventProcessor.getSequence().get() + ((ITERATIONS / NUM_PUBLISHERS) * NUM_PUBLISHERS));
Future<?>[] futures = new Future[NUM_PUBLISHERS];
for(int i =0; i < NUM_PUBLISHERS; i++)
{
futures[i] = executor.submit(valuePublishers[i]);
}
executor.submit(batchEventProcessor);
long start = System.currentTimeMillis();
cyclicBarrier.await(); //start test
for(int i = 0; i < NUM_PUBLISHERS; i++) {
futures[i].get();
} //all published
latch.await(); //wait for all handled
long opsPerSecond = (ITERATIONS * 1000L) / (System.currentTimeMillis() - start);
batchEventProcessor.halt();
return opsPerSecond;
}
public static void main(String[] args) throws Exception
{
Main m = new Main();
System.out.println("opsPerSecond:"+ m.runDisruptorPass());
}
}
|
/**
* Copyright 2005 Sean J. Barbeau
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.barbeau.networks.bayes;
import Jama.Matrix;
import com.barbeau.networks.Node;
import com.barbeau.networks.astar.HeuristicsNode;
import java.util.ArrayList;
/**
* This class defines a node that contains properties that are used in Bayesian networks
*
* @author Sean Barbeau
*/
public class BayesNode extends HeuristicsNode {
/**
* Matrix used to hold probabilities
*/
Matrix matrix;
/**
* Names of the rows of the Matrix
*/
ArrayList rowNames;
public BayesNode(String label, int x, int y) {
super(label, x, y);
}
public ArrayList getRowNames() {
return rowNames;
}
public void setRowNames(ArrayList rowNames) {
this.rowNames = rowNames;
}
public Matrix getMatrix() {
return matrix;
}
public void setMatrix(Matrix matrix) {
this.matrix = matrix;
}
}
|
package com.sakthi.springmvc.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//http://websystique.com/springmvc/spring-4-mvc-helloworld-tutorial-full-example/
@Controller
@RequestMapping("/")
public class HelloWorldController extends WebMvcConfigurerAdapter{
@RequestMapping(method = RequestMethod.GET)
public String holaShakthi(ModelMap model) {
model.addAttribute("hola", "Hola Shakthi!");
model.addAttribute("greeting", "You are all set to go, Happy coding!");
model.addAttribute("buttonMessage", "Let's break some keys");
return "welcome";
}
@RequestMapping(value="/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Stop asking again, start working!");
return "welcome";
}
}
|
package com.wangzhu.spring.aware;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationAware implements ApplicationContextAware {
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("MyApplicationAware: "
+ applicationContext.getBean("myApplicationAware").hashCode());
}
}
|
/*
* $Header: /home/cvsroot/HelpDesk/src/com/aof/webapp/form/SecurityGroupForm.java,v 1.3 2004/11/30 04:09:21 shilei Exp $
* $Revision: 1.3 $
* $Date: 2004/11/30 04:09:21 $
*
* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ====================================================================
*/
package com.aof.webapp.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
/**
* Form bean for the user profile page. This form has the following fields,
* with default values in square brackets:
* <ul>
* <li><b>password</b> - Entered password value
* <li><b>username</b> - Entered username value
* </ul>
*
* @author XingPing Xu
* @version $Revision: 1.3 $ $Date: 2004/11/30 04:09:21 $
*/
public final class SecurityGroupForm extends ActionForm {
/**
* The password.
*/
private String groupId = null;
/**
* The username.
*/
private String description = null;
// --------------------------------------------------------- Public Methods
/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.groupId = null;
this.description = null;
}
/**
* Validate the properties that have been set from this HTTP request,
* and return an <code>ActionErrors</code> object that encapsulates any
* validation errors that have been found. If no errors are found, return
* <code>null</code> or an <code>ActionErrors</code> object with no
* recorded error messages.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((description == null) || (description.length() < 1))
errors.add("username", new ActionError("error.username.required"));
if ((groupId == null) || (groupId.length() < 1))
errors.add("password", new ActionError("error.password.required"));
return errors;
}
/**
* @return
*/
public String getDescription() {
return description;
}
/**
* @return
*/
public String getGroupId() {
return groupId;
}
/**
* @param string
*/
public void setDescription(String string) {
description = string;
}
/**
* @param string
*/
public void setGroupId(String string) {
groupId = string;
}
}
|
package com;
import java.util.Date;
public class UserInfo {
private Integer userId;
private String userName;
private String userSex;
private Date birthday;
public UserInfo(Integer userId, String userName, String userSex, Date birthday)
{
this.userId= userId;
this.userName = userName;
this.userSex = userSex;
this.birthday = birthday;
}
public Integer getUserId() {
return this.userId;
}
@Override
public String toString() {
return "UserInfo [userId=" + userId + ", userName=" + userName + ", userSex=" + userSex + ", birthday="
+ birthday + "]";
}
}
|
package java.com.kaizenmax.taikinys_icl.presenter;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Base64;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.kaizenmax.taikinys_icl.model.MobileDatabase;
import com.kaizenmax.taikinys_icl.pojo.FarmerDetailsPojo;
import com.kaizenmax.taikinys_icl.pojo.PromoFarmerMeetingPojo;
import com.kaizenmax.taikinys_icl.pojo.RetailerDetailsPojo;
import com.kaizenmax.taikinys_icl.presenter.IndividualFarmerContactActivityPresenterInterface;
import com.kaizenmax.taikinys_icl.util.SharedPreferenceUtil;
import com.kaizenmax.taikinys_icl.view.IndividualFarmerContactMainActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class IndividualFarmerContactActivityPresenter implements IndividualFarmerContactActivityPresenterInterface {
MobileDatabase dbHelper =new MobileDatabase(IndividualFarmerContactMainActivity.getInstance());
@Override
public List<String> getFirmNameList() throws Exception {
List<String> firmList= dbHelper.getFirmNameList();
return firmList;
}
@Override
public String getPropName(String firmName) throws Exception {
String propName= dbHelper.getPropName(firmName);
return propName;
}
@Override
public String getRetailerMobile(String firmName) throws Exception {
String retailerMobile=dbHelper.getRetailerMobile(firmName);
return retailerMobile;
}
@Override
public String getClientName() throws Exception {
String clientName = dbHelper.getClientName();
return clientName;
}
@Override
public String getStateName() throws Exception {
String faOfficeState=dbHelper.getStateName();
return faOfficeState;
}
@Override
public List<String> getProductFocusList(String clientName, String faOfficeState) {
List<String> productlist=dbHelper.getProductFocusList(clientName,faOfficeState);
return productlist;
}
@Override
public List<String> getVillageList() throws Exception {
List<String> villageList=dbHelper.getVillageList();
return villageList;
}
@Override
public List<String> getCropCategories() throws Exception {
List<String> cropCategories=dbHelper.getCropCategories();
return cropCategories;
}
@Override
public List<String> getCropFocus(String selectedCropCategory) throws Exception {
List<String > cropFocusList= dbHelper.getCropFocus(selectedCropCategory);
return cropFocusList;
}
@Override
public String getFaOfficeDistrict() throws Exception {
String faOfficeDistrict=dbHelper.getFaOfficeDistrict();
return faOfficeDistrict;
}
@Override
public String getMobileFromSharedpreference() throws Exception {
String createdby="";
SharedPreferences sharedpreferences = IndividualFarmerContactMainActivity.getInstance().getSharedPreferences(SharedPreferenceUtil.PREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences!=null)
{
if(sharedpreferences.getString(SharedPreferenceUtil.MOBILEKEY,null)==null)
{
}
else
{
createdby=sharedpreferences.getString(SharedPreferenceUtil.MOBILEKEY,null);
// Toast.makeText(IndividualFarmerContactActivity.this, "mob "+createdby+" createdOn "+createdOn
// +" district "+faOfficeDistrict
// +"clientName "+clientName, Toast.LENGTH_SHORT).show();
}
}
return createdby;
}
@Override
public void insertIFCdata(String ifc, String dateOfActivity_entered, String villageName_entered,
String cropFocus_entered, String cropCategory_entered,
String farmerName_entered, String farmerMobile_entered,
String landAcres_entered, String expenses_entered,
String observations_entered, String uploadFlagStatus,
List<RetailerDetailsPojo> retailerDetailsPojoList,
List<String> selectedProductsList, String createdOn_string,
String createdby, String clientName, String faOfficeDistrict) throws Exception {
dbHelper.insertIFCdata("IFC", dateOfActivity_entered, villageName_entered,
cropFocus_entered, cropCategory_entered, farmerName_entered, farmerMobile_entered, landAcres_entered,
expenses_entered, observations_entered, uploadFlagStatus, retailerDetailsPojoList, selectedProductsList,
createdOn_string,createdby,clientName,faOfficeDistrict);
}
@Override
public void sendingDataToWebService() throws Exception {
{
// Toast.makeText(instance, "RAM RAM", Toast.LENGTH_SHORT).show();
ArrayList<Integer> uploadedIds = new ArrayList<Integer>();
String url = "https://taikinys.kaizenmax.com/rest/service/meeting";
// String url = "https://raghav-rest-api.herokuapp.com/rest/json/raghav/post";
RequestQueue requestQueue = Volley.newRequestQueue(IndividualFarmerContactMainActivity.getInstance());
final JSONArray postparams = new JSONArray();
try {
JSONObject object = new JSONObject();
Cursor cursor = dbHelper.getPromoEntriesToBeUploaded();
if (cursor != null && cursor.getCount() != 0) {
// Toast.makeText(instance, "Uploading Data", Toast.LENGTH_SHORT).show();
if (cursor != null && cursor.moveToFirst()) {
do {
String chooseActivity = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CHOOSE_ACTIVITY));
String dateOfActivity = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_DATE_OF_ACTIVITY));
String cropCategory = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CROP_CATEGORY));
String cropFocus = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CROP_FOCUS));
// String focusProduct=cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CR))
String observations = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_OBSERVATIONS));
//String farmerName=cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.far))
String village = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_VILLAGE));
String expenses = cursor.getString(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_EXPENSES));
Integer id = cursor.getInt(cursor.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_ID));
String createdOn=cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CREATED_ON));
String createdby=cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CREATED_BY));
String clientName=cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CLIENT_NAME));
String faOfficeDistrict=cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_DISTRICT));
String numberOfFarmers = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_NUMBER_OF_FARMER));
String meetingPurpose = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_MEETING_PURPOSE));
String cropStage = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_CROP_STAGE));
String instructionsDose = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_INSTRUCTIONS_DOSE));
String problemCategory = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_PROBLEM_CATEGORY));
String problemSubCategory = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_PROBLEM_SUB_CATEGORY));
String description = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_DESCRIPTION));
String recommendation = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_RECOMMENDATION));
String nextVisitDate = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_NEXT_FIELD_VISIT_DATE));
String problemDescription = cursor.getString(cursor
.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_PROBLEM_DESCRIPTION));
// Toast.makeText(IndividualFarmerContactActivity.this, "District "+faOfficeDistrict, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "TOAST "+id+" Cursor Size "+cursor.getCount(), Toast.LENGTH_SHORT).show();
object = new JSONObject();
object.put("chooseActivity", chooseActivity);
object.put("dateOfActivity", dateOfActivity+" 00:00:00");
object.put("cropCategory", cropCategory);
object.put("cropFocus", cropFocus);
object.put("observations", observations);
object.put("village", village);
object.put("expenses", expenses);
object.put("expenses", expenses);
//
object.put("numberOfFarmers", numberOfFarmers);
object.put("meetingPurpose", meetingPurpose);
object.put("cropStage", cropStage);
object.put("instructionsDose",instructionsDose);
object.put("problemCategory", problemCategory);
object.put("problemSubCategory", problemSubCategory);
object.put("description", description);
object.put("recommendation",recommendation);
object.put("nextVisitDate", nextVisitDate+" 00:00:00");
object.put("problemDescription", problemDescription);
List<RetailerDetailsPojo> retailerDetailsPojoList = dbHelper.getRetailerDetails(id);
JSONArray retailerDetails_jsonArray = new JSONArray();
for (int i = 0; i < retailerDetailsPojoList.size(); i++) {
JSONObject retailerObject = new JSONObject();
RetailerDetailsPojo retailerDetailsPojo = retailerDetailsPojoList.get(i);
retailerObject.put("firmName", retailerDetailsPojo.getFirmName());
retailerObject.put("propreitorName", retailerDetailsPojo.getPropName());
retailerObject.put("retailerMobile", retailerDetailsPojo.getRetailerMobile());
retailerDetails_jsonArray.put(retailerObject);
}
object.put("retailerDetailsRests", retailerDetails_jsonArray);
//PRODUCT LIST
List<String> productsDetailsList = dbHelper.getProductDetails(id);
JSONArray productsDetails_jsonArray = new JSONArray();
for (int i = 0; i < productsDetailsList.size(); i++) {
JSONObject productObject = new JSONObject();
String productName = productsDetailsList.get(i);
productObject.put("productName", productName);
productsDetails_jsonArray.put(productObject);
}
object.put("productDetailsRests", productsDetails_jsonArray);
List<FarmerDetailsPojo> farmerDetailsPojoList = dbHelper.getFarmerDetails(id);
JSONArray farmerDetails_jsonArray = new JSONArray();
for (int i = 0; i < farmerDetailsPojoList.size(); i++) {
JSONObject farmerObject = new JSONObject();
FarmerDetailsPojo farmerDetailsPojo = farmerDetailsPojoList.get(i);
farmerObject.put("farmerName", farmerDetailsPojo.getFarmerName());
farmerObject.put("mobileNumber", farmerDetailsPojo.getFarmerMobile());
farmerObject.put("acres", farmerDetailsPojo.getFarmerLand());
farmerDetails_jsonArray.put(farmerObject);
}
object.put("farmerDetailsRests", farmerDetails_jsonArray);
//Attachment Details by vinod on 26/08/2019
List<byte[]> attachmentDetails = dbHelper.getAttachments(id);
JSONArray attachmentDetails_jsonArray = new JSONArray();
for (int i = 0; i < attachmentDetails.size(); i++) {
JSONObject attachmentObject = new JSONObject();
// RetailerDetailsPojo retailerDetailsPojo = retailerDetailsPojoList.get(i);
byte[] fileByteArray = attachmentDetails.get(i);
String encodedString = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
attachmentObject.put("atttachment",encodedString );
attachmentDetails_jsonArray.put(attachmentObject);
}
object.put("attachmentDetailsRests", attachmentDetails_jsonArray);
object.put("createdBy",createdby);
object.put("clientName",clientName);
object.put("district",faOfficeDistrict);
object.put("createdOn",createdOn);
/* Calendar calendar=Calendar.getInstance();
Date d = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
Date date = null;
String gg = new Date().toString();
date = format.parse(gg);
System.out.println("date hh-"+date);*/
// object.put("createdOn",date.toString());
// Toast.makeText(this, "New Date "+new Date(), Toast.LENGTH_SHORT).show();
postparams.put(object);
uploadedIds.add(id);
} while (cursor.moveToNext());
}
cursor.close();
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
@Override
public void onResponse(Object response) {
// Toast.makeText(IndividualFarmerContactActivity.this, "URL "+url, Toast.LENGTH_SHORT).show();
// Toast.makeText(IndividualFarmerContactActivity.this, "Success", Toast.LENGTH_SHORT).show();
//
// Toast.makeText(IndividualFarmerContactActivity.this, "RESPONSE "+response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
Toast.makeText(IndividualFarmerContactMainActivity.getInstance(), "Error " + error, Toast.LENGTH_SHORT).show();
}
});
//Adding the request to the queue along with a unique string tag
requestQueue.add(jsonObjReq);
dbHelper.updateMobileFlagPromoFarmerMeetingEntries(uploadedIds);
// Toast.makeText(this, "ENDINg DBCRETESTATUS "+dbCreateStatus+" DB INSERT STATUS "+dbInsertSTatus+" DB RETrieve STatus "+dbRetriveSTatus, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import test.Program;
public class DbUtil
{
static Properties prop;
static
{
try
{
InputStream inputStream = Program.class.getClassLoader().getResourceAsStream("Config.properties");
prop = new Properties();
prop.load(inputStream );
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static Connection getConnection( ) throws SQLException
{
return DriverManager.getConnection(prop.getProperty("URL"), prop.getProperty("USER"), prop.getProperty("PASSWORD"));
}
}
|
package attractions;
import org.junit.Before;
import org.junit.Test;
import people.Visitor;
import static org.junit.Assert.*;
public class PlaygroundTest {
Playground playground;
Visitor visitor15;
Visitor visitor8;
Visitor visitor19;
@Before
public void setUp() throws Exception {
playground = new Playground("Fun Zone", 7);
visitor15 = new Visitor(15,1.50, 20.00);
visitor8 = new Visitor(8,1.20, 15.00);
visitor19 = new Visitor(19,2.00, 30.00);
}
@Test
public void hasName() {
assertEquals("Fun Zone", playground.getName());
}
@Test
public void hasRating() {
assertEquals(7, playground.getRating());
}
@Test
public void hasVisitCount() {
assertEquals(0, playground.getVisitCount());
}
@Test
public void canUseThePlayground__BelowMaxAge() {
assertTrue(playground.isAllowedTo(visitor8));
}
@Test
public void canUseThePlayground__ExactMaxAge() {
assertTrue(playground.isAllowedTo(visitor15));
}
@Test
public void canUseThePlayground__OverMaxAge() {
assertFalse(playground.isAllowedTo(visitor19));
}
}
|
package com.stk123.common.util;
import com.thoughtworks.xstream.XStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class XmlUtils {
public static List<String> getList4Xml(String xml) throws Exception {
SAXBuilder sb=new SAXBuilder();
StringReader read = new StringReader(xml);
InputSource source = new InputSource(read);
Document doc =sb.build(source);
Element root = doc.getRootElement();
List<Element> list = root.getChildren();
List<String> result = new ArrayList<String>();
for(Element s : list){
result.add(s.getText());
}
return result;
}
public static Object getObject4Xml(String xml, Map<String,Class> clazz){
XStream xstream = new XStream();
for(Map.Entry<String,Class> entry : clazz.entrySet()){
xstream.alias(entry.getKey(),entry.getValue());
}
return xstream.fromXML(xml);
}
public static String getXml4Object(Object obj, Map<String,Class> clazz){
XStream xstream = new XStream();
for(Map.Entry<String,Class> entry : clazz.entrySet()){
xstream.alias(entry.getKey(),entry.getValue());
}
return xstream.toXML(obj);
}
public static void main(String[] args) throws Exception{
String page = CommonHttpUtils.get("http://www.webxml.com.cn/WebServices/ChinaStockWebService.asmx/getStockInfoByCode?theStockCode=sz002570", null, "GBK");
/*
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/">
<string>sz002570</string>
<string>贝因美</string>
<string>2013-08-13 15:05:49</string>
<string>33.98</string>
<string>34.37</string>
<string>34.40</string>
<string>-0.39</string>
<string>33.50</string>
</ArrayOfString>
*/
Map<String,Class> map = new HashMap<String,Class>();
map.put("ArrayOfString", List.class);
List<String> obj = (List<String>)getObject4Xml(page,map);
System.out.println(obj);
System.out.println(getXml4Object(obj, map));
}
}
|
/*
* Created on 2004-12-2
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.aof.component.helpdesk;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import com.aof.component.BaseServices;
import com.aof.webapp.action.ActionException;
import com.shcnc.hibernate.CompositeQuery;
import com.shcnc.hibernate.QueryCondition;
/**
* @author yech
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class StatusTypeService extends BaseServices {
public final static int STATUS_FLAG_OTHER=0;
public final static int STATUS_FLAG_RESPONSE=1;
public final static int STATUS_FLAG_SOLVED=2;
public final static int STATUS_FLAG_CLOSED=3;
public final static String QUERY_CONDITION_CALLTYPE="callType";
public final static String QUERY_CONDITION_DISABLED="disabled";
public int getCount(final Map conditions) throws HibernateException
{
Session sess=null;
try{
sess=this.getSession();
CompositeQuery query=new CompositeQuery(
"select count(statustype) from StatusType as statustype",
"",session);
appendConditions(query,conditions);
List result=query.list();
if(!result.isEmpty())
{
Integer count = (Integer) result.get(0);
if(count!=null) return count.intValue();
}
}
finally{
this.closeSession();
}
return 0;
}
public List findStatusType(final Map conditions,final int pageNo,final int pageSize ) throws HibernateException {
Session sess=null;
try{
sess=this.getSession();
CompositeQuery query=new CompositeQuery(
"select statustype from StatusType as statustype",
"statustype.callType,statustype.level",session);
appendConditions(query,conditions);
return query.list(pageNo*pageSize,pageSize);
}
finally
{
this.closeSession();
}
}
public List listStatusTypeGroupByCallType() throws HibernateException {
Session sess=null;
try{
sess=this.getSession();
List results=new ArrayList();
List listCallTypes=sess.find("from CallType as ct");
Iterator iterCallType=listCallTypes.iterator();
while (iterCallType.hasNext()) {
CallType callType=(CallType) iterCallType.next();
List listStatusTypes=sess.find("from StatusType as st where st.callType.type=? order by st.level",callType.getType(),Hibernate.STRING);
results.add(listStatusTypes);
}
return results;
}
finally
{
this.closeSession();
}
}
public List listStatusType(CallType callType) throws HibernateException {
Session sess=null;
try{
sess=this.getSession();
List results=sess.find("from StatusType as st where st.disabled=0 and st.callType.type=? order by st.level",callType.getType(),Hibernate.STRING);
return results;
}
finally
{
this.closeSession();
}
}
public List listAllStatusType(CallType callType) throws HibernateException {
Session sess=null;
try{
sess=this.getSession();
List results=sess.find("from StatusType as st where st.callType.type=? order by st.level",callType.getType(),Hibernate.STRING);
return results;
}
finally
{
this.closeSession();
}
}
public StatusType getStatusType(Session sess,int statusFlag) throws HibernateException {
StatusType responseStatus=null;
sess=this.getSession();
List results=sess.find("from StatusType as st where st.flag=?",new Integer(statusFlag),Hibernate.INTEGER);
Iterator iter=results.iterator();
if (iter.hasNext()) {
responseStatus=(StatusType) iter.next();
return responseStatus;
}
return null;
}
public StatusType getDefaultStatusType(CallType callType) throws HibernateException {
StatusType statusType=null;
List statusTypes=this.listStatusType(callType);
Iterator iter=statusTypes.iterator();
if (iter.hasNext()) {
statusType=(StatusType) iter.next();
}
return statusType;
}
public StatusType findStatusType(Integer id,Session session) throws HibernateException
{
return (StatusType) session.get(StatusType.class,id);
}
private void appendConditions(final CompositeQuery query, final Map conditions) {
final String simpleConds[][]={
{QUERY_CONDITION_CALLTYPE,
"statustype.callType.type=?"},
{QUERY_CONDITION_DISABLED,
"statustype.disabled=?"}
};
for(int i=0;i<simpleConds.length;i++)
{
Object value=conditions.get(simpleConds[i][0]);
if(value!=null)
{
if(value instanceof String &&!(((String)value).trim().equals("")))
{
this.makeSimpeCondition(query,simpleConds[i][1],value);
}
}
}
}
public StatusType findStatusType(Integer id)throws HibernateException
{
Session sess=null;
try{
sess=this.getSession();
return this.findStatusType(id,sess);
}
finally{
this.closeSession();
}
}
public boolean insert(StatusType statusType) throws HibernateException {
Session sess = this.getSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
int insertLevel=1;
CompositeQuery query=new CompositeQuery(
"select count(st) from StatusType as st",
"",session);
this.makeSimpeCondition(query,"st.level<?",statusType.getLevel());
this.makeSimpeCondition(query,"st.callType.type=?",statusType.getCallType().getType());
List result=query.list();
if(!result.isEmpty())
{
Integer count = (Integer) result.get(0);
if(count!=null) insertLevel=count.intValue()+1;
}
statusType.setLevel(new Integer(insertLevel));
List statusTypes=sess.find("from StatusType as st where st.callType.type=? order by st.level asc",statusType.getCallType().getType(),Hibernate.STRING);
Iterator iterStatusTypes=statusTypes.iterator();
int levelIndex=1;
while (iterStatusTypes.hasNext() ){
StatusType updateStatusType=(StatusType) iterStatusTypes.next();
if (levelIndex!=insertLevel) {
updateStatusType.setLevel(new Integer(levelIndex));
} else {
updateStatusType.setLevel(new Integer(++levelIndex));
}
levelIndex++;
sess.update(updateStatusType);
}
sess.save(statusType);
sess.flush();
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
this.closeSession();
}
return true;
}
public boolean update(StatusType statusType) throws HibernateException {
Session sess = this.getSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
int updateLevel=statusType.getLevel().intValue();
List result=sess.find("select count(st) from StatusType as st where st.callType.type=?",statusType.getCallType().getType(),Hibernate.STRING);
int recCount=0;
if(!result.isEmpty())
{
Integer count = (Integer) result.get(0);
if(count!=null) recCount=count.intValue();
}
if (recCount<statusType.getLevel().intValue()) {
statusType.setLevel(new Integer(recCount));
}
CompositeQuery query=new CompositeQuery(
"from StatusType as st",
"st.level asc",session);
this.makeSimpeCondition(query,"st.id<>?",statusType.getId());
this.makeSimpeCondition(query,"st.callType.type=?",statusType.getCallType().getType());
List statusTypes=query.list();
Iterator iterStatusTypes=statusTypes.iterator();
int levelIndex=1;
while (iterStatusTypes.hasNext() ){
StatusType updateStatusType=(StatusType) iterStatusTypes.next();
if (levelIndex!=statusType.getLevel().intValue()) {
updateStatusType.setLevel(new Integer(levelIndex));
} else {
updateStatusType.setLevel(new Integer(++levelIndex));
}
levelIndex++;
sess.update(updateStatusType);
}
sess.update(statusType);
sess.flush();
if (statusType.getFlag().intValue()>0) {
query=new CompositeQuery(
"from StatusType as st",
"",session);
QueryCondition qc=query.createQueryCondition("st.callType.type=? and st.flag>0 and ((st.flag>? and st.level<?) or (st.flag<? and st.level>?))");
qc.appendParameter(statusType.getCallType().getType());
qc.appendParameter(statusType.getFlag());
qc.appendParameter(statusType.getLevel());
qc.appendParameter(statusType.getFlag());
qc.appendParameter(statusType.getLevel());
List searchStatusTypes=query.list();
if (!searchStatusTypes.isEmpty()) {
List listResults=sess.find("from StatusType as st where st.flag>0 and st.callType.type=? order by st.flag",statusType.getCallType().getType(),Hibernate.STRING);
Iterator iter=listResults.iterator();
String preDefinedStatus="";
String preDefinedStatusOrder="";
while (iter.hasNext()) {
StatusType preDefinedStatusType=(StatusType) iter.next();
preDefinedStatus=preDefinedStatus+" "+preDefinedStatusType.getDesc();
preDefinedStatusOrder= preDefinedStatusOrder+"->"+preDefinedStatusType.getDesc();
}
preDefinedStatus=preDefinedStatus.substring(1);
preDefinedStatusOrder=preDefinedStatusOrder.substring(2);
tx.rollback();
throw new ActionException("helpdesk.statusType.error.order",preDefinedStatus,preDefinedStatusOrder);
}
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
this.closeSession();
}
return true;
}
public static boolean hasResponse(CallMaster call) {
return (call.getStatus().getFlag().intValue()==STATUS_FLAG_RESPONSE)?true:false;
}
public static boolean hasSolved(CallMaster call) {
return (call.getStatus().getFlag().intValue()==STATUS_FLAG_SOLVED)?true:false;
}
public static boolean hasClosed(CallMaster call) {
return (call.getStatus().getFlag().intValue()==STATUS_FLAG_CLOSED)?true:false;
}
}
|
/**
*
*/
package org.artifact.security.domain;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.artifact.base.domain.IdEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 角色实体类
* <p>
* 日期:2015年8月14日
*
* @version 0.1
* @author Netbug
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "sec_role")
public class Role extends IdEntity {
private String name;// 名称
private String desc;// 描述
@JsonIgnoreProperties(value = { "role" })
private List<UserRole> userRoleList;
@JsonIgnoreProperties(value = { "role" })
private List<RolePermission> rolePermissionList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = {
CascadeType.REFRESH, CascadeType.REMOVE })
public List<UserRole> getUserRoleList() {
return userRoleList;
}
public void setUserRoleList(List<UserRole> userRoleList) {
this.userRoleList = userRoleList;
}
@OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = {
CascadeType.REFRESH, CascadeType.REMOVE })
public List<RolePermission> getRolePermissionList() {
return rolePermissionList;
}
public void setRolePermissionList(List<RolePermission> rolePermissionList) {
this.rolePermissionList = rolePermissionList;
}
}
|
import java.util.ArrayList;
import com.sun.tools.javac.util.List;
/*
* [17] Letter Combinations of a Phone Number
*
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
*
* algorithms
* Medium (37.67%)
* Total Accepted: 264.8K
* Total Submissions: 702.9K
* Testcase Example: '"23"'
*
* Given a string containing digits from 2-9 inclusive, return all possible
* letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given
* below. Note that 1 does not map to any letters.
*
*
*
* Example:
*
*
* Input: "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
*
*
* Note:
*
* Although the above answer is in lexicographical order, your answer could be
* in any order you want.
*
*/
class Solution {
public List<String> letterCombinations(String digits) {
String[] mapping = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> resultList = new ArrayList<>();
letterCombinations(resultList, digits, "", 0, mapping);
return resultList;
}
private void letterCombinations(List<String> resultList,String digits,String curr,int index,String[] mapping){
if(index==digits.length()){
if(curr.length()!=0){
resultList.add(curr);
}
return;
}
String temp = mapping[digits.charAt(index)-'0'];
for(int i=0;i<temp.length();i++){
String next = curr + temp.charAt(i);
letterCombinations(resultList, digits, next, index+1, mapping);
}
}
}
|
package net.bdsc.service.impl;
import net.bdsc.entity.Member;
import net.bdsc.entity.MineMachine;
import net.bdsc.entity.MineMachineOrder;
import net.bdsc.entity.Sn;
import net.bdsc.service.MineMachineOrderService;
import net.bdsc.service.SnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
/**
* Service - 广告
*
* @author 好源++ Team
* @version 6.1
*/
@Service
public class MineMachineOrderServiceImpl extends BaseServiceImpl<MineMachineOrder, Long> implements MineMachineOrderService {
@Autowired
private SnService snService;
@Override
public MineMachineOrder create(Member member, MineMachine mineMachine,Integer quantity,Integer day) {
MineMachineOrder mineMachineOrder = new MineMachineOrder();
mineMachineOrder.init();
mineMachineOrder.setUserId(member.getId());
mineMachineOrder.setProductType(mineMachine.getType());
mineMachineOrder.setProductId(mineMachine.getId());
mineMachineOrder.setPrice(mineMachine.getPrice());
mineMachineOrder.setAmount(mineMachine.getPrice().multiply(new BigDecimal(quantity)));
mineMachineOrder.setQuantity(quantity);
mineMachineOrder.setMemo("系统赠送");
mineMachineOrder.setState(1);
mineMachineOrder.setPayType(3);
mineMachineOrder.setPayPrice("1349.80 元");
mineMachineOrder.setElectricType(1);
mineMachineOrder. setDay(day);
mineMachineOrder.setAddElectric(BigDecimal.ZERO);
mineMachineOrder.setElectricMoney(BigDecimal.valueOf(43.99));
mineMachineOrder.setRmbPrice(BigDecimal.valueOf(1349.81));
mineMachineOrder.setCoinType(mineMachine.getCoinType());
mineMachineOrder.setFromChannel("APP");
mineMachineOrder.setExpirationDate(new Date());
mineMachineOrder.setInvestTime("2021-01-01 00:00:00");
mineMachineOrder.setSn(snService.generate(Sn.Type.ORDER));
mineMachineOrder.setUserName(member.getUsername());
mineMachineOrder.setPhone(member.getPhone());
mineMachineOrder.setName(member.getName());
mineMachineOrder.setProductName(mineMachine.getName());
mineMachineOrder.setProductId(mineMachine.getId());
mineMachineOrder.setProductIcon(mineMachine.getIcon());
return super.save(mineMachineOrder);
}
}
|
package com.blog.util;
import org.apache.commons.codec.digest.DigestUtils;
public class MD5Coder {
/**
*
* @param data ¼ÓÃܵÄÊý¾Ý
* @return byte[]
*/
public static byte[] encodeMD5 (String data) {
return DigestUtils.md5(data);
}
public static String encodeMD5Hex(String data) {
return DigestUtils.md5Hex(data);
}
}
|
package hashing;
import java.util.HashMap;
import java.util.Map;
/**
* Created by gouthamvidyapradhan on 16/12/2017.
* Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
Solution: O(n) keep a count variable and increment count when a 1 is found and decrement count when a 0 is found.
Maintain a map of count and its corresponding index. if the count repeats itself then take the difference of the
current index and the index saved in the map. Max of the difference is the answer.
*/
public class ContiguousArray {
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
int[] A = {1, 1};
System.out.println(new ContiguousArray().findMaxLength(A));
}
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
int max = 0;
for(int i = 0; i < nums.length; i ++){
if(nums[i] == 0){
count--;
} else count++;
if(count == 0){
max = Math.max(max, i + 1);
} else {
if(map.containsKey(count)){
int index = map.get(count);
max = Math.max(max, i - index);
} else{
map.put(count, i);
}
}
}
return max;
}
}
|
package net.kkolyan.elements.engine.utils;
import java.util.ArrayDeque;
/**
* @author nplekhanov
*/
public class SimplePool<T> implements Pool<T> {
private ArrayDeque<T> pool = new ArrayDeque<>();
private ObjectProvider<T> initializer;
public SimplePool(ObjectProvider<T> initializer) {
this.initializer = initializer;
}
@Override
public T borrow() {
T t = pool.poll();
if (t == null) {
t = initializer.getObject();
}
return t;
}
@Override
public void release(T o) {
pool.offer(o);
}
}
|
package com.example.ahmadrizaldi.traveloka_retrofit.Adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.ahmadrizaldi.traveloka_retrofit.Model.User;
import com.example.ahmadrizaldi.traveloka_retrofit.R;
import java.util.ArrayList;
/**
* Created by ahmadrizaldi on 11/28/17.
*/
public class AdapterUser extends RecyclerView.Adapter<AdapterUser.ViewHolder> {
private Context context;
private ArrayList<User> rvData;
public AdapterUser(Context context, ArrayList<User> rvData) {
this.context = context;
this.rvData = rvData;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_list, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.email.setText(rvData.get(position).getEmail());
}
@Override
public int getItemCount() {
return rvData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView email;
public ViewHolder(View itemView) {
super(itemView);
email = (TextView)itemView.findViewById(R.id.email_text);
}
}
}
|
package com.hlx.view.option;
import com.hlx.config.SoundEnum;
import com.hlx.service.SoundService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static javax.swing.SwingConstants.CENTER;
/**
* A abstract panel that be used for building beautiful option view quickly
* @author hlx
* @version 1.0 2018-3-17
*/
public class TabPanel extends JPanel {
private JLabel numLabel;
private List<JLabel> controlLabel;
private Integer number;
private Timer plusTimer;
private Timer minusTimer;
private Integer minNum;
private SoundService soundService;
public TabPanel(Integer number, Integer minNum, SoundService soundService) {
super();
this.setLayout(null);
this.setSize(150,40);
this.number = number;
this.minNum = minNum;
this.soundService = soundService;
initNumLabel();
initControlLabel();
initTimer();
}
private void initTimer() {
ActionListener plusAction = e -> {
number = number + 1;
numLabel.setText("" + number);
};
plusTimer = new Timer(250, plusAction);
ActionListener minusAction = e -> {
if (number > minNum)
number = number - 1;
numLabel.setText("" + number);
};
minusTimer = new Timer(250, minusAction);
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
numLabel.setText(""+number);
}
private void initControlLabel() {
controlLabel = new ArrayList<>(Arrays.asList(
new JLabel("-", CENTER),
new JLabel("+", CENTER)
));
for (JLabel label : controlLabel) {
label.setSize(50, 40);
label.setOpaque(true);
label.setFont(new Font("sans-serif", Font.PLAIN, 25));
label.setBackground(new Color(240, 175, 211));
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
JLabel label = (JLabel) e.getSource();
label.setBackground(new Color(240, 161, 202));
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
JLabel label = (JLabel) e.getSource();
label.setBackground(new Color(240, 175, 211));
}
});
}
final JLabel minusLabel = controlLabel.get(0);
minusLabel.setLocation(0,0);
minusLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(number>minNum){
number = number - 1;
soundService.play(SoundEnum.CHANGE);
}
numLabel.setText(""+number);
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
minusTimer.start();
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
minusTimer.stop();
}
});
this.add(minusLabel);
final JLabel plusLabel = controlLabel.get(1);
plusLabel.setLocation(100,0);
plusLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
number = number + 1;
soundService.play(SoundEnum.CHANGE);
numLabel.setText(""+number);
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
plusTimer.start();
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
plusTimer.stop();
}
});
this.add(plusLabel);
}
private void initNumLabel() {
numLabel = new JLabel(""+number,CENTER);
numLabel.setFont(new Font("sans-serif",Font.PLAIN,25));
numLabel.setBounds(50, 0, 50, 40);
numLabel.setOpaque(true);
numLabel.setBackground(new Color(240, 157, 204));
this.add(numLabel);
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* IPv6 Address Record - maps a domain name to an IPv6 address
*
* @author Brian Wellington
* @see <a href="https://tools.ietf.org/html/rfc3596">RFC 3596: DNS Extensions to Support IP Version
* 6</a>
*/
public class AAAARecord extends Record {
private byte[] address;
AAAARecord() {}
/**
* Creates an AAAA Record from the given data
*
* @param address The address suffix
*/
public AAAARecord(Name name, int dclass, long ttl, InetAddress address) {
super(name, Type.AAAA, dclass, ttl);
if (Address.familyOf(address) != Address.IPv4 && Address.familyOf(address) != Address.IPv6) {
throw new IllegalArgumentException("invalid IPv4/IPv6 address");
}
this.address = address.getAddress();
}
@Override
protected void rrFromWire(DNSInput in) throws IOException {
address = in.readByteArray(16);
}
@Override
protected void rdataFromString(Tokenizer st, Name origin) throws IOException {
address = st.getAddressBytes(Address.IPv6);
}
/** Converts rdata to a String */
@Override
protected String rrToString() {
InetAddress addr;
try {
addr = InetAddress.getByAddress(null, address);
} catch (UnknownHostException e) {
return null;
}
if (addr.getAddress().length == 4) {
// Deal with Java's broken handling of mapped IPv4 addresses.
return "::ffff:" + addr.getHostAddress();
}
return addr.getHostAddress();
}
/** Returns the address */
public InetAddress getAddress() {
try {
if (name == null) {
return InetAddress.getByAddress(address);
} else {
return InetAddress.getByAddress(name.toString(), address);
}
} catch (UnknownHostException e) {
return null;
}
}
@Override
protected void rrToWire(DNSOutput out, Compression c, boolean canonical) {
out.writeByteArray(address);
}
}
|
package plugins.fmp.fmpTools;
import java.awt.Point;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import icy.gui.frame.progress.ProgressFrame;
import plugins.fmp.fmpSequence.Experiment;
import plugins.fmp.fmpSequence.SequencePlus;
import plugins.fmp.fmpSequence.XYTaSeries;
public class XLSExportCapillaryResults extends XLSExport {
public void exportToFile(String filename, XLSExportOptions opt) {
System.out.println("XLS capillary measures output");
options = opt;
ProgressFrame progress = new ProgressFrame("Export data to Excel");
try {
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
int col_max = 0;
int col_end = 0;
int iSeries = 0;
options.experimentList.readInfosFromAllExperiments();
expAll = options.experimentList.getStartAndEndFromAllExperiments();
expAll.step = options.experimentList.experimentList.get(0).vSequence.analysisStep;
listOfStacks = new ArrayList <XLSNameAndPosition> ();
progress.setMessage("Load measures...");
progress.setLength(options.experimentList.experimentList.size());
for (Experiment exp: options.experimentList.experimentList)
{
String charSeries = CellReference.convertNumToColString(iSeries);
if (options.topLevel) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.TOPLEVEL);
if (options.topLevelDelta) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.TOPLEVELDELTA);
if (options.bottomLevel) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.BOTTOMLEVEL);
if (options.derivative) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.DERIVEDVALUES);
if (options.consumption) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.SUMGULPS);
if (options.sum) {
if (options.topLevel) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.TOPLEVEL_LR);
if (options.topLevelDelta) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.TOPLEVELDELTA_LR);
if (options.consumption) col_end = getDataAndExport(exp, workbook, col_max, charSeries, EnumXLSExportItems.SUMGULPS_LR);
}
if (col_end > col_max)
col_max = col_end;
iSeries++;
progress.incPosition();
}
if (options.transpose && options.pivot) {
progress.setMessage( "Build pivot tables... ");
String sourceSheetName = null;
if (options.topLevel) sourceSheetName = EnumXLSExportItems.TOPLEVEL.toString();
else if (options.topLevelDelta) sourceSheetName = EnumXLSExportItems.TOPLEVELDELTA.toString();
else if (options.bottomLevel) sourceSheetName = EnumXLSExportItems.BOTTOMLEVEL.toString();
else if (options.derivative) sourceSheetName = EnumXLSExportItems.DERIVEDVALUES.toString();
else if (options.consumption) sourceSheetName = EnumXLSExportItems.SUMGULPS.toString();
else if (options.sum) sourceSheetName = EnumXLSExportItems.TOPLEVEL_LR.toString();
if (sourceSheetName != null)
xlsCreatePivotTables(workbook, sourceSheetName);
}
progress.setMessage( "Save Excel file to disk... ");
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
progress.close();
System.out.println("XLS output finished");
}
private int getDataAndExport(Experiment exp, XSSFWorkbook workbook, int col0, String charSeries, EnumXLSExportItems datatype)
{
ArrayList <XLSCapillaryResults> arrayList = getDataFromRois(exp, datatype, options.t0);
int colmax = xlsExportToWorkbook(exp, workbook, datatype.toString(), datatype, col0, charSeries, arrayList);
if (options.onlyalive) {
trimDeadsFromArrayList(exp, arrayList);
xlsExportToWorkbook(exp, workbook, datatype.toString()+"_alive", datatype, col0, charSeries, arrayList);
}
return colmax;
}
private ArrayList <XLSCapillaryResults> getDataFromRois(Experiment exp, EnumXLSExportItems xlsoption, boolean optiont0) {
ArrayList <XLSCapillaryResults> resultsArrayList = new ArrayList <XLSCapillaryResults> ();
for (SequencePlus seq: exp.kymographArrayList) {
XLSCapillaryResults results = new XLSCapillaryResults();
results.name = seq.getName();
switch (xlsoption) {
case TOPLEVELDELTA:
case TOPLEVELDELTA_LR:
results.data = seq.subtractTi(seq.getArrayListFromRois(EnumArrayListType.topLevel));
break;
case DERIVEDVALUES:
results.data = seq.getArrayListFromRois(EnumArrayListType.derivedValues);
break;
case SUMGULPS:
case SUMGULPS_LR:
results.data = seq.getArrayListFromRois(EnumArrayListType.cumSum);
break;
case BOTTOMLEVEL:
results.data = seq.getArrayListFromRois(EnumArrayListType.bottomLevel);
break;
case TOPLEVEL:
case TOPLEVEL_LR:
if (optiont0)
results.data = seq.subtractT0(seq.getArrayListFromRois(EnumArrayListType.topLevel));
else
results.data = seq.getArrayListFromRois(EnumArrayListType.topLevel);
break;
default:
break;
}
resultsArrayList.add(results);
}
return resultsArrayList;
}
private void trimDeadsFromArrayList(Experiment exp, ArrayList <XLSCapillaryResults> resultsArrayList) {
for (XYTaSeries flypos: exp.vSequence.cages.flyPositionsList) {
String cagenumberString = flypos.roi.getName().substring(4);
int cagenumber = Integer.parseInt(cagenumberString);
if (cagenumber == 0 || cagenumber == 9)
continue;
for (XLSCapillaryResults capillaryResult : resultsArrayList) {
if (getCageFromCapillaryName (capillaryResult.name) == cagenumber) {
int ilastalive = flypos.getLastIntervalAlive();
trimArrayLength(capillaryResult.data, ilastalive);
}
}
}
}
private void trimArrayLength (ArrayList<Integer> array, int ilastalive) {
if (array == null)
return;
int arraysize = array.size();
if (ilastalive < 0)
ilastalive = 0;
if (ilastalive > (arraysize-1))
ilastalive = arraysize-1;
array.subList(ilastalive, arraysize-1).clear();
}
private int xlsExportToWorkbook(Experiment exp, XSSFWorkbook workBook, String title, EnumXLSExportItems xlsExportOption, int col0, String charSeries, ArrayList <XLSCapillaryResults> arrayList) {
XSSFSheet sheet = workBook.getSheet(title );
if (sheet == null)
sheet = workBook.createSheet(title);
Point pt = new Point(col0, 0);
if (options.collateSeries) {
pt = getStackColumnPosition(exp, pt);
}
pt = writeGlobalInfos(exp, sheet, pt, options.transpose);
pt = writeHeader(exp, sheet, xlsExportOption, pt, options.transpose, charSeries);
pt = writeData(exp, sheet, xlsExportOption, pt, options.transpose, charSeries, arrayList);
return pt.x;
}
private Point writeGlobalInfos(Experiment exp, XSSFSheet sheet, Point pt, boolean transpose) {
int col0 = pt.x;
XLSUtils.setValue(sheet, pt, transpose, "expt");
pt.x++;
File file = new File(exp.vSequence.getFileName(0));
String path = file.getParent();
XLSUtils.setValue(sheet, pt, transpose, path);
pt.x++;
XLSUtils.setValue(sheet, pt, transpose, "Ál" );
pt.x++;
XLSUtils.setValue(sheet, pt, transpose, "pixels" );
pt.x++;
pt.y++;
pt.x = col0;
XLSUtils.setValue(sheet, pt, transpose, "scale");
pt.x++;
pt.x++;
XLSUtils.setValue(sheet, pt, transpose, exp.vSequence.capillaries.volume);
pt.x++;
XLSUtils.setValue(sheet, pt, transpose, exp.vSequence.capillaries.pixels);
pt.x = col0;
pt.y++;
return pt;
}
private Point writeHeader (Experiment exp, XSSFSheet sheet, EnumXLSExportItems option, Point pt, boolean transpose, String charSeries) {
int col0 = pt.x;
pt = writeGenericHeader(exp, sheet, option, pt, transpose, charSeries);
int colseries = pt.x;
for (SequencePlus seq: exp.kymographArrayList) {
int col = getColFromKymoSequenceName(seq.getName());
if (col >= 0)
pt.x = colseries + col;
XLSUtils.setValue(sheet, pt, transpose, seq.getName());
pt.x++;
}
pt.x = col0;
pt.y++;
return pt;
}
private Point writeData (Experiment exp, XSSFSheet sheet, EnumXLSExportItems option, Point pt, boolean transpose, String charSeries, ArrayList <XLSCapillaryResults> dataArrayList) {
double scalingFactorToPhysicalUnits = exp.vSequence.capillaries.volume / exp.vSequence.capillaries.pixels;
int col0 = pt.x;
int row0 = pt.y;
if (charSeries == null)
charSeries = "t";
int startFrame = (int) exp.vSequence.analysisStart;
int endFrame = (int) exp.vSequence.analysisEnd;
int step = expAll.step;
FileTime imageTime = exp.vSequence.getImageModifiedTime(startFrame);
long imageTimeMinutes = imageTime.toMillis()/ 60000;
long referenceFileTimeImageFirstMinutes = 0;
long referenceFileTimeImageLastMinutes = 0;
if (options.absoluteTime) {
referenceFileTimeImageFirstMinutes = expAll.fileTimeImageFirstMinutes;
referenceFileTimeImageLastMinutes = expAll.fileTimeImageLastMinutes;
}
else {
XLSNameAndPosition desc = getStackGlobalSeriesDescriptor(exp);
if (desc != null) {
referenceFileTimeImageFirstMinutes = desc.fileTimeImageFirstMinutes;
referenceFileTimeImageLastMinutes = desc.fileTimeImageLastMinutes;
}
else
{
referenceFileTimeImageFirstMinutes = exp.fileTimeImageFirstMinutes;
referenceFileTimeImageLastMinutes = exp.fileTimeImageLastMinutes;
}
}
pt.x =0;
imageTimeMinutes = referenceFileTimeImageLastMinutes;
long diff = getnearest(imageTimeMinutes-referenceFileTimeImageFirstMinutes, step)/ step;
imageTimeMinutes = referenceFileTimeImageFirstMinutes;
for (int i = 0; i<= diff; i++) {
long diff2 = getnearest(imageTimeMinutes-referenceFileTimeImageFirstMinutes, step);
pt.y = (int) (diff2/step + row0);
XLSUtils.setValue(sheet, pt, transpose, "t"+diff2);
imageTimeMinutes += step;
}
for (int currentFrame=startFrame; currentFrame < endFrame; currentFrame+= step * options.pivotBinStep) {
pt.x = col0;
imageTime = exp.vSequence.getImageModifiedTime(currentFrame);
imageTimeMinutes = imageTime.toMillis()/ 60000;
long diff_current = getnearest(imageTimeMinutes-referenceFileTimeImageFirstMinutes, step);
pt.y = (int) (diff_current/step + row0);
pt.x++;
XLSUtils.setValue(sheet, pt, transpose, imageTimeMinutes);
pt.x++;
if (exp.vSequence.isFileStack()) {
XLSUtils.setValue(sheet, pt, transpose, getShortenedName(exp.vSequence, currentFrame) );
}
pt.x++;
int colseries = pt.x;
switch (option) {
case TOPLEVEL_LR:
case TOPLEVELDELTA_LR:
case SUMGULPS_LR:
for (int idataArray=0; idataArray< dataArrayList.size(); idataArray+=2)
{
int colL = getColFromKymoSequenceName(dataArrayList.get(idataArray).name);
if (colL >= 0)
pt.x = colseries + colL;
ArrayList<Integer> dataL = dataArrayList.get(idataArray).data ;
ArrayList<Integer> dataR = dataArrayList.get(idataArray+1).data;
if (dataL != null && dataR != null) {
int j = (currentFrame - startFrame)/step;
if (j < dataL.size() && j < dataR.size()) {
double value = (dataL.get(j)+dataR.get(j))*scalingFactorToPhysicalUnits;
XLSUtils.setValue(sheet, pt, transpose, value);
Point pt0 = new Point(pt);
pt0.x ++;
int colR = getColFromKymoSequenceName(dataArrayList.get(idataArray+1).name);
if (colR >= 0)
pt0.x = colseries + colR;
value = (dataL.get(j)-dataR.get(j))*scalingFactorToPhysicalUnits/value;
XLSUtils.setValue(sheet, pt0, transpose, value);
}
}
pt.x++;
pt.x++;
}
break;
default:
for (int idataArray=0; idataArray< dataArrayList.size(); idataArray++)
{
int col = getColFromKymoSequenceName(dataArrayList.get(idataArray).name);
if (col >= 0)
pt.x = colseries + col;
ArrayList<Integer> data = dataArrayList.get(idataArray).data;
if (data != null) {
int j = (currentFrame - startFrame)/step;
if (j < data.size()) {
double value = data.get(j)*scalingFactorToPhysicalUnits;
XLSUtils.setValue(sheet, pt, transpose, value);
}
}
pt.x++;
}
break;
}
}
//pt.x = columnOfNextSeries(exp, option, col0);
return pt;
}
}
|
package com.pehom.deepvoidplayer;
import androidx.room.TypeConverter;
import java.util.ArrayList;
public class TracksConverter {
@TypeConverter
public String fromTracks(ArrayList<Track> tracks){
String s = "";
for (int i=0; i < tracks.size(); i++){
s=s+tracks.get(i).getArtist()+"%>"+tracks.get(i).getTitle()+"%>"+tracks.get(i).getDuration()+"%>"+
tracks.get(i).getData()+",";
}
return s;
}
@TypeConverter
public ArrayList<Track> toTracks(String s){
ArrayList<Track> arrayList = new ArrayList<>();
for (String parts : s.split(",")){
String[] trackString = parts.split("%>");
Track track = new Track();
for (int i = 0; i< 4; i++){
switch (i) {
case 0: track.setArtist(trackString[i]); break;
case 1: track.setTitle(trackString[i]); break;
case 2: track.setDuration(trackString[i]);break;
case 3: track.setData(trackString[i]);break;
}
}
arrayList.add(track);
}
return arrayList;
}
}
|
package com.unicom.patrolDoor.entity;
public class Recommend {
private Integer id;
private Integer questionId;
private String recommendTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
public String getRecommendTime() {
return recommendTime;
}
public void setRecommendTime(String recommendTime) {
this.recommendTime = recommendTime == null ? null : recommendTime.trim();
}
}
|
package kr.co.people_gram.app;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity2 extends AppCompatActivity {
public static AppCompatActivity mainActivity;
Toolbar toolbar;
//DrawerLayout dlDrawer;
//ActionBarDrawerToggle dtToggle;
private Intent intent;
private TextView txtTitle;
private android.support.v4.app.FragmentManager fragmentManager;
private android.support.v4.app.FragmentTransaction ft;
private Boolean openCheck = false;
private ImageView guide_content_1;
private ImageView menu_icon1, menu_icon2, menu_icon3, menu_icon4;
private LinearLayout menu1, menu2, menu3, menu4, menu_line1, menu_line2, menu_line3, menu_line4;
private LinearLayout searchbtn, settingbtn;
private String menuType = "people";
private DataProfileCount dpc;
private PopupWindow mPopupWindow;
final int SubPeopleListFragmentCode = 1;
final int SubPeopleTypeFragmentCode = 2;
final int SubPeopleTypeFragmentCode_new = 3;
private TextView menu_username, menu_point;
private ImageView menu_mytype;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
toolbar = (Toolbar) findViewById(R.id.toolbar);
txtTitle = (TextView) findViewById(R.id.txtTitle);
//dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
/*
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (null != ab) {
ab.setDisplayHomeAsUpEnabled(true);
}
*/
/*
dtToggle = new ActionBarDrawerToggle(this, dlDrawer, R.string.app_name, R.string.app_name) {
@Override
public void onDrawerClosed(View drawerView) {
openCheck = false;
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
openCheck = true;
super.onDrawerOpened(drawerView);
}
};
dlDrawer.setDrawerListener(dtToggle);
*/
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
txtTitle.setText("피플그램");
/*
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
menuItem.setChecked(true);
dlDrawer.closeDrawers();
mHandler = new Handler();
mHandler.removeCallbacks(mRunnable);
mRunnable = new Runnable() {
@Override
public void run() {
switch (menuItem.getItemId())
{
case R.id.navigation_item_point:
intent = new Intent(MainActivity2.this, SubGramPoint.class);
startActivityForResult(intent, SubPeopleListFragmentCode);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.navigation_item_type:
intent = new Intent(MainActivity2.this, SubTypeFragment.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
break;
case R.id.navigation_item_mypage:
intent = new Intent(MainActivity2.this, ProfileActivity.class);
startActivityForResult(intent, SubPeopleListFragmentCode);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
break;
case R.id.navigation_item_setting:
intent = new Intent(MainActivity2.this, SettingActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
break;
}
}
};
mHandler.postDelayed(mRunnable, 200);
return false;
}
});
*/
mainActivity = this;
dpc = new DataProfileCount();
menu_icon1 = (ImageView) findViewById(R.id.menu_icon1);
menu_icon2 = (ImageView) findViewById(R.id.menu_icon2);
menu_icon3 = (ImageView) findViewById(R.id.menu_icon3);
menu_icon4 = (ImageView) findViewById(R.id.menu_icon4);
menu_line1 = (LinearLayout) findViewById(R.id.menu_line1);
menu_line2 = (LinearLayout) findViewById(R.id.menu_line2);
menu_line3 = (LinearLayout) findViewById(R.id.menu_line3);
menu_line4 = (LinearLayout) findViewById(R.id.menu_line4);
menu1 = (LinearLayout) findViewById(R.id.menu1);
menu2 = (LinearLayout) findViewById(R.id.menu2);
menu3 = (LinearLayout) findViewById(R.id.menu3);
menu4 = (LinearLayout) findViewById(R.id.menu4);
//menu_username = (TextView) findViewById(R.id.menu_username);
//menu_username.setText(SharedPreferenceUtil.getSharedPreference(MainActivity2.this, "username"));
//menu_point = (TextView) findViewById(R.id.menu_point);
//menu_point.setText(Utilities.comma(Integer.parseInt(SharedPreferenceUtil.getSharedPreference(MainActivity2.this, "point"))) + "p");
//menu_mytype = (ImageView) findViewById(R.id.menu_mytype);
/*
switch (SharedPreferenceUtil.getSharedPreference(MainActivity2.this, "mytype")) {
case "A":
menu_mytype.setImageResource(R.mipmap.peoplelist_type_a);
break;
case "I":
menu_mytype.setImageResource(R.mipmap.peoplelist_type_i);
break;
case "D":
menu_mytype.setImageResource(R.mipmap.peoplelist_type_d);
break;
case "E":
menu_mytype.setImageResource(R.mipmap.peoplelist_type_e);
break;
default:
menu_mytype.setImageResource(R.mipmap.peoplelist_type_default);
break;
}
*/
if(dpc.get_user_count() > 0) {
menu_icon1.setImageResource(R.mipmap.top_01_on_new);
}
menu1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(menuType.equals("people") == false) {
if(dpc.get_user_count() > 0) {
menu_icon1.setImageResource(R.mipmap.top_01_on_new);
} else {
menu_icon1.setImageResource(R.mipmap.top_01_on);
}
menu_line1.setBackgroundColor(Color.rgb(50, 53, 77));
menu_icon2.setImageResource(R.mipmap.top_02_off);
menu_line2.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon3.setImageResource(R.mipmap.top_03_off);
menu_line3.setBackgroundColor(Color.rgb(220,220,221));
menu_icon4.setImageResource(R.mipmap.top_04_off);
menu_line4.setBackgroundColor(Color.rgb(220,220,221));
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubPeopleFragment subpeople_fragment = new SubPeopleFragment();
ft.replace(R.id.viewpager, subpeople_fragment);
ft.commit();
menuType = "people";
}
}
});
menu2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(menuType.equals("mytype") == false) {
dpc.set_user_count(0);
menu_icon1.setImageResource(R.mipmap.top_01_off);
menu_line1.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon2.setImageResource(R.mipmap.top_02_on);
menu_line2.setBackgroundColor(Color.rgb(50, 53, 77));
menu_icon3.setImageResource(R.mipmap.top_03_off);
menu_line3.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon4.setImageResource(R.mipmap.top_04_off);
menu_line4.setBackgroundColor(Color.rgb(220, 220, 221));
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubPeopleTypeFragment subpeopletype_fragment = new SubPeopleTypeFragment();
ft.replace(R.id.viewpager, subpeopletype_fragment);
ft.commit();
menuType = "mytype";
}
}
});
menu3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(menuType.equals("mypage") == false) {
dpc.set_user_count(0);
menu_icon1.setImageResource(R.mipmap.top_01_off);
menu_line1.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon2.setImageResource(R.mipmap.top_02_off);
menu_line2.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon3.setImageResource(R.mipmap.top_03_on);
menu_line3.setBackgroundColor(Color.rgb(50, 53, 77));
menu_icon4.setImageResource(R.mipmap.top_04_off);
menu_line4.setBackgroundColor(Color.rgb(220, 220, 221));
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubMypageFragment submypage_fragment = new SubMypageFragment();
ft.replace(R.id.viewpager, submypage_fragment);
ft.commit();
menuType = "mypage";
}
}
});
menu4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(menuType.equals("group") == false) {
dpc.set_user_count(0);
menu_icon1.setImageResource(R.mipmap.top_01_off);
menu_line1.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon2.setImageResource(R.mipmap.top_02_off);
menu_line2.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon3.setImageResource(R.mipmap.top_03_off);
menu_line3.setBackgroundColor(Color.rgb(220, 220, 221));
menu_icon4.setImageResource(R.mipmap.top_04_on);
menu_line4.setBackgroundColor(Color.rgb(50, 53, 77));
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubTypeFragment_new subgroup_fragment = new SubTypeFragment_new();
ft.replace(R.id.viewpager, subgroup_fragment);
ft.commit();
menuType = "group";
}
}
});
//viewPager = (ViewPager) findViewById(R.id.viewpager);
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubPeopleFragment subpeople_fragment = new SubPeopleFragment();
ft.replace(R.id.viewpager, subpeople_fragment);
ft.commit();
/*
setupViewPager(viewPager);
viewPager.setOffscreenPageLimit(1);
//viewPager.invalidate();
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
settingbtn = (LinearLayout) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
}
});
*/
searchbtn = (LinearLayout) findViewById(R.id.searchbtn);
searchbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity2.this, SubPeopleSearch_Activity.class);
startActivityForResult(intent, SubPeopleListFragmentCode);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
}
});
settingbtn = (LinearLayout) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity2.this, SettingActivity.class);
startActivityForResult(intent, 1);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
}
});
}
public void mainmenu_close_btn(View v) {
//dlDrawer.closeDrawer(Gravity.LEFT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
//dtToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//dtToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
//dlDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//menu_point.setText(Utilities.comma(Integer.parseInt(SharedPreferenceUtil.getSharedPreference(MainActivity2.this, "point"))) + "p");
/*
menu_mytype = (ImageView) findViewById(R.id.menu_mytype);
switch (SharedPreferenceUtil.getSharedPreference(MainActivity2.this, "mytype")) {
case "A":
menu_mytype.setImageResource(R.mipmap.people_type_a);
break;
case "I":
menu_mytype.setImageResource(R.mipmap.people_type_i);
break;
case "D":
menu_mytype.setImageResource(R.mipmap.people_type_d);
break;
case "E":
menu_mytype.setImageResource(R.mipmap.people_type_e);
break;
default:
menu_mytype.setImageResource(R.mipmap.people_type_default);
break;
}
*/
if (resultCode==RESULT_OK) {
if(requestCode == SubPeopleListFragmentCode) {
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubPeopleFragment subpeople_fragment = new SubPeopleFragment();
ft.replace(R.id.viewpager, subpeople_fragment);
ft.commit();
}
if(requestCode == SubPeopleTypeFragmentCode_new) {
fragmentManager = getSupportFragmentManager();
ft = fragmentManager.beginTransaction();
SubPeopleTypeFragment subpeopletype_fragment = new SubPeopleTypeFragment();
ft.replace(R.id.viewpager, subpeopletype_fragment);
ft.commit();
}
if (requestCode == SubPeopleTypeFragmentCode) {
String my_type = SharedPreferenceUtil.getSharedPreference(this, "mytype");
String people_type = data.getStringExtra("people_type");
String gubun1 = data.getStringExtra("gubun1");
String my_data1 = data.getStringExtra("my_data1");
String my_data2 = data.getStringExtra("my_data2");
String my_data3 = data.getStringExtra("my_data3");
String my_data4 = data.getStringExtra("my_data4");
String my_data5 = data.getStringExtra("my_data5");
String my_data6 = data.getStringExtra("my_data6");
String my_data7 = data.getStringExtra("my_data7");
String my_data8 = data.getStringExtra("my_data8");
String my_data9 = data.getStringExtra("my_data9");
String my_data10 = data.getStringExtra("my_data10");
String people_total = data.getStringExtra("people_total");
String people_data1 = data.getStringExtra("people_data1");
String people_data2 = data.getStringExtra("people_data2");
String people_data3 = data.getStringExtra("people_data3");
String people_data4 = data.getStringExtra("people_data4");
String people_data5 = data.getStringExtra("people_data5");
String people_data6 = data.getStringExtra("people_data6");
String people_data7 = data.getStringExtra("people_data7");
String people_data8 = data.getStringExtra("people_data8");
String people_data9 = data.getStringExtra("people_data9");
String people_data10 = data.getStringExtra("people_data10");
String my_speed = data.getStringExtra("my_speed");
String my_control = data.getStringExtra("my_control");
String people_speed = data.getStringExtra("people_speed");
String people_control = data.getStringExtra("people_control");
Log.d("people_gram", people_data1 + ":::" + people_data2);
Intent intent = new Intent(MainActivity2.this, SubPeopleTypeContents_Activity.class);
intent.putExtra("mytype", my_type);
intent.putExtra("people_type", people_type);
intent.putExtra("gubun1", gubun1);
intent.putExtra("my_data1", my_data1);
intent.putExtra("my_data2", my_data2);
intent.putExtra("my_data3", my_data3);
intent.putExtra("my_data4", my_data4);
intent.putExtra("my_data5", my_data5);
intent.putExtra("my_data6", my_data6);
intent.putExtra("my_data7", my_data7);
intent.putExtra("my_data8", my_data8);
intent.putExtra("my_data9", my_data9);
intent.putExtra("my_data10", my_data10);
intent.putExtra("people_total", people_total);
intent.putExtra("people_data1", people_data1);
intent.putExtra("people_data2", people_data2);
intent.putExtra("people_data3", people_data3);
intent.putExtra("people_data4", people_data4);
intent.putExtra("people_data5", people_data5);
intent.putExtra("people_data6", people_data6);
intent.putExtra("people_data7", people_data7);
intent.putExtra("people_data8", people_data8);
intent.putExtra("people_data9", people_data9);
intent.putExtra("people_data10", people_data10);
intent.putExtra("my_speed", my_speed);
intent.putExtra("my_control", my_control);
intent.putExtra("people_speed", people_speed);
intent.putExtra("people_control", people_control);
intent.putExtra("viewType", "my");
startActivityForResult(intent, SubPeopleTypeFragmentCode_new);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
switch (gubun1)
{
case "P":
SubPeopleTypeFragment.P_check = true;
break;
case "F":
SubPeopleTypeFragment.F_check = true;
break;
case "L":
SubPeopleTypeFragment.L_check = true;
break;
case "C":
SubPeopleTypeFragment.C_check = true;
break;
case "S":
SubPeopleTypeFragment.S_check = true;
break;
}
}
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(android.support.v4.app.FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(openCheck == false) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
new AlertDialog.Builder(this)
.setTitle("프로그램 종료")
.setMessage("프로그램을 종료 하시겠습니까?")
.setPositiveButton("예", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
//android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton("아니오", null)
.show();
break;
default:
break;
}
} else {
/* 좌측메뉴 CLOSE */
//dlDrawer.closeDrawer(Gravity.LEFT);
return false;
}
return super.onKeyDown(keyCode, event);
}
public void step1_close_btn(View v) {
if (mPopupWindow != null && mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
}
}
|
package com.example.pucp.Controller;
import com.example.pucp.Entity.Actividad;
import com.example.pucp.Entity.Area;
import com.example.pucp.Entity.Usuario;
import com.example.pucp.Repository.AreaRepository;
import com.example.pucp.Repository.UsuarioRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/area")
public class AreaController {
@Autowired
AreaRepository areaRepository;
@Autowired
UsuarioRepository usuarioRepository;
@GetMapping(value = {"/listar", ""})
public String lista(Model model) {
List<Area> lista = areaRepository.findAll();
model.addAttribute("arealista", lista);
return "proyecto/area/lista";
}
@GetMapping("/nuevo")
public String nuevo() {
return "proyecto/area/nuevo";
}
@GetMapping("/editar")
public String editar(Model model, @RequestParam("id") int id) {
Optional<Area> areaOptional = areaRepository.findById(id);
if (areaOptional.isPresent()) {
List<Usuario> listau = usuarioRepository.findByIdarea(id);
model.addAttribute("listausuarios",listau);
Area area = areaOptional.get();
model.addAttribute("area", area);
return "proyecto/area/editar";
} else {
return "redirect:proyecto/area/lista";
}
}
@PostMapping("guardar")
public String guardar(Area area, RedirectAttributes attr) {
if (area.getIdArea() == 0) {
attr.addFlashAttribute("msg", "Usuario creado exitosamente");
} else {
attr.addFlashAttribute("msg", "Usuario actualizado exitosamente");
}
areaRepository.save(area);
return "redirect:/area/listar";
}
@GetMapping("/borrar")
public String borrar(Model model, @RequestParam("id") int id,
RedirectAttributes attr) {
Optional<Area> areaOptional = areaRepository.findById(id);
if (areaOptional.isPresent()) {
areaRepository.deleteById(id);
attr.addFlashAttribute("msg", "Area eliminada exitosamente");
}
return "redirect:/area/listar";
}
}
|
package me.ivt.com.ui.tablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import me.ivt.com.ui.DividerDecoration;
import me.ivt.com.ui.R;
import me.ivt.com.ui.coordinatorlayout.CoordninatorRecyAdapter;
public class ItemFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item, container, false);
RecyclerView mRv = (RecyclerView) view.findViewById(R.id.rv);
ArrayList<String> mStrings = new ArrayList<>();
for (int i = 'A'; i <= 'Z'; i++) {
mStrings.add("当前是数据--------------->" + (char) i);
}
for (int i = 'A'; i <= 'Z'; i++) {
mStrings.add("当前是数据--------------->" + (char) i);
}
mRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
mRv.addItemDecoration(new DividerDecoration(getActivity(),LinearLayout.VERTICAL));
mRv.setAdapter(new CoordninatorRecyAdapter(mStrings));
return view;
}
}
|
package com.vicutu.op.query;
public interface QueryTemplateManager {
QueryTemplate getQueryTemplate(String name);
}
|
package com.biblio.api.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.biblio.api.core.Exemplaire;
@Repository
public interface ExemplaireRepository extends JpaRepository<Exemplaire, Long> {
public Iterable<Exemplaire> findByLivre_Id(long id);
}
|
package com.yc.education.service;
import com.yc.education.model.PermissionsEmployee;
import java.util.List;
/**
* @ClassName PermissionsEmployeeService
* @Description TODO
* @Author QuZhangJing
* @Date 2019/3/1 10:22
* @Version 1.0
*/
public interface PermissionsEmployeeService extends IService<PermissionsEmployee> {
List<PermissionsEmployee> findPermissionsEmployee();
PermissionsEmployee findPermissionsEmployeeByUname(String uname);
}
|
package example.lgcode.launchstatus.presenters;
import com.squareup.otto.Subscribe;
import example.lgcode.launchstatus.adapters.LaunchListAdapter;
import example.lgcode.launchstatus.dtos.LaunchDTO;
import example.lgcode.launchstatus.models.LaunchStatusModel;
import example.lgcode.launchstatus.utils.BusProvider;
import example.lgcode.launchstatus.views.LaunchStatusView;
/**
* Created by leojg on 1/20/17.
*/
public class LaunchStatusPresenter {
LaunchStatusView view;
LaunchStatusModel model;
public LaunchStatusPresenter(LaunchStatusView view, LaunchStatusModel model) {
this.view = view;
this.model = model;
this.view.setAdapter(new LaunchListAdapter(model.getLaunches(), BusProvider.getInstance()));
}
@Subscribe
public void onLaunchesRequested(LaunchStatusView.LaunchesRequestEvent event) {
model.fetchLaunchStatus();
}
@Subscribe
public void onLaunchesFetched(LaunchStatusModel.LaunchesFetchedEvent event) {
view.updateList(model.getCurrentCount());
}
@Subscribe
public void OnOpenLaunchDetail(LaunchListAdapter.OpenLaunchDetailEvent e) {
LaunchDTO launch = e.launch;
view.openLaunchDetailActivity(launch);
}
}
|
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.convert.support;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.lang.Nullable;
/**
* Simply calls {@link Object#toString()} to convert any supported object
* to a {@link String}.
*
* <p>Supports {@link CharSequence}, {@link StringWriter}, and any class
* with a String constructor or one of the following static factory methods:
* {@code valueOf(String)}, {@code of(String)}, {@code from(String)}.
*
* <p>Used by the {@link DefaultConversionService} as a fallback if there
* are no other explicit to-String converters registered.
*
* @author Keith Donald
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
* @see ObjectToObjectConverter
*/
final class FallbackObjectToStringConverter implements ConditionalGenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, String.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
Class<?> sourceClass = sourceType.getObjectType();
if (String.class == sourceClass) {
// no conversion required
return false;
}
return (CharSequence.class.isAssignableFrom(sourceClass) ||
StringWriter.class.isAssignableFrom(sourceClass) ||
ObjectToObjectConverter.hasConversionMethodOrConstructor(sourceClass, String.class));
}
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
return (source != null ? source.toString() : null);
}
}
|
package com.melusyn.sendgrid;
import org.vertx.java.core.json.JsonObject;
public class SendGridResponse {
private int code;
private String message;
private boolean status;
static SendGridResponse instance() {
return new SendGridResponse();
}
public SendGridResponse code(int code) {
this.code = code;
return this;
}
public SendGridResponse message(String message) {
this.message = message;
return this;
}
public SendGridResponse status(boolean status) {
this.status = status;
return this;
}
public JsonObject toJson() {
return new JsonObject()
.putNumber("code", code)
.putString("message", message)
.putBoolean("status", status);
}
}
|
package com.max.harrax.game.state;
import com.max.harrax.events.Event;
import com.max.harrax.layer.Layer;
import java.util.ArrayList;
public class State {
private ArrayList<Layer> layerStack;
public State() {
this.layerStack = new ArrayList<Layer>();
}
public void onUpdate(float delta) {
for (Layer layer : layerStack) {
layer.onUpdate(delta);
}
}
public void onEvent(Event event) {
for (int i = layerStack.size() - 1; i >= 0; i--) {
layerStack.get(i).onEvent(event);
}
}
public void addLayer(Layer layer) {
this.layerStack.add(layer);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.