text
stringlengths
10
2.72M
package com.telyo.trainassistant.entity; import android.os.Parcel; import android.os.Parcelable; /** * Created by Administrator on 2017/6/12. */ public class TrainDetailDatas implements Parcelable { //与车票相关 需要发送的请求数据 private String train_no; private String from_station_no; private String train_name; private String from_station; private String to_station; private String start_time; private String end_time; private String cast_time; private String isToday; private String isWz; private String to_station_no; private String seat_types; private String WZ; private String swz_num; private String ydz_num; private String yz_num; private String rw_num; private String rz_num; private String gjrw_num; private String yw_num; private String dw_num; private String wz_num; private String edz_num; private String qtxb_num; private String tdz_num; private String gjrw_price; private String yz_price; private String rz_price; private String ywz_price; private String dw_price; private String ydz_price; private String wz_price; private String tdz_price; private String dwx_price; private String edz_price; private String qtxb_price; private String yw_price; private String rw_price; private String ywx_price; private String gjrws_price; private String date; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTrain_type() { return train_type; } public void setTrain_type(String train_type) { this.train_type = train_type; } private String train_type; public String getArrive_days() { return arrive_days; } public void setArrive_days(String arrive_days) { this.arrive_days = arrive_days; } private String arrive_days; //private String WZ; 无座 //private String WZ; 无座 //private String WZ; 无座 public String getIsWz() { return isWz; } public void setIsWz(String isWz) { this.isWz = isWz; } public String getTrain_no() { return train_no; } public void setTrain_no(String train_no) { this.train_no = train_no; } public String getFrom_station_no() { return from_station_no; } public void setFrom_station_no(String from_station_no) { this.from_station_no = from_station_no; } public String getTo_station_no() { return to_station_no; } public void setTo_station_no(String to_station_no) { this.to_station_no = to_station_no; } public String getSeat_types() { return seat_types; } public void setSeat_types(String seat_types) { this.seat_types = seat_types; } public String getWZ() { return WZ; } public void setWZ(String WZ) { this.WZ = WZ; } public String getTrain_name() { return train_name; } public void setTrain_name(String train_name) { this.train_name = train_name; } public String getFrom_station() { return from_station; } public void setFrom_station(String from_station) { this.from_station = from_station; } public String getTo_station() { return to_station; } public void setTo_station(String to_station) { this.to_station = to_station; } public String getStart_time() { return start_time; } public void setStart_time(String start_time) { this.start_time = start_time; } public String getEnd_time() { return end_time; } public void setEnd_time(String end_time) { this.end_time = end_time; } public String getCast_time() { return cast_time; } public void setCast_time(String cast_time) { this.cast_time = cast_time; } public String getIsToday() { return isToday; } public void setIsToday(String isToday) { this.isToday = isToday; } public String getSwz_num() { return swz_num; } public void setSwz_num(String swz_num) { this.swz_num = swz_num; } public String getYdz_num() { return ydz_num; } public void setYdz_num(String ydz_num) { this.ydz_num = ydz_num; } public String getYz_num() { return yz_num; } public void setYz_num(String yz_num) { this.yz_num = yz_num; } public String getRw_num() { return rw_num; } public void setRw_num(String rw_num) { this.rw_num = rw_num; } public String getRz_num() { return rz_num; } public void setRz_num(String rz_num) { this.rz_num = rz_num; } public String getGjrw_num() { return gjrw_num; } public void setGjrw_num(String gjrw_num) { this.gjrw_num = gjrw_num; } public String getYw_num() { return yw_num; } public void setYw_num(String yw_num) { this.yw_num = yw_num; } public String getDw_num() { return dw_num; } public void setDw_num(String dw_num) { this.dw_num = dw_num; } public String getWz_num() { return wz_num; } public void setWz_num(String wz_num) { this.wz_num = wz_num; } public String getEdz_num() { return edz_num; } public void setEdz_num(String edz_num) { this.edz_num = edz_num; } public String getQtxb_num() { return qtxb_num; } public void setQtxb_num(String qtxb_num) { this.qtxb_num = qtxb_num; } public String getTdz_num() { return tdz_num; } public void setTdz_num(String tdz_num) { this.tdz_num = tdz_num; } public String getGjrw_price() { return gjrw_price; } public void setGjrw_price(String gjrw_price) { this.gjrw_price = gjrw_price; } public String getYz_price() { return yz_price; } public void setYz_price(String yz_price) { this.yz_price = yz_price; } public String getRz_price() { return rz_price; } public void setRz_price(String rz_price) { this.rz_price = rz_price; } public String getYwz_price() { return ywz_price; } public void setYwz_price(String ywz_price) { this.ywz_price = ywz_price; } public String getDw_price() { return dw_price; } public void setDw_price(String dw_price) { this.dw_price = dw_price; } public String getYdz_price() { return ydz_price; } public void setYdz_price(String ydz_price) { this.ydz_price = ydz_price; } public String getWz_price() { return wz_price; } public void setWz_price(String wz_price) { this.wz_price = wz_price; } public String getTdz_price() { return tdz_price; } public void setTdz_price(String tdz_price) { this.tdz_price = tdz_price; } public String getDwx_price() { return dwx_price; } public void setDwx_price(String dwx_price) { this.dwx_price = dwx_price; } public String getEdz_price() { return edz_price; } public void setEdz_price(String edz_price) { this.edz_price = edz_price; } public String getQtxb_price() { return qtxb_price; } public void setQtxb_price(String qtxb_price) { this.qtxb_price = qtxb_price; } public String getYw_price() { return yw_price; } public void setYw_price(String yw_price) { this.yw_price = yw_price; } public String getRw_price() { return rw_price; } public void setRw_price(String rw_price) { this.rw_price = rw_price; } public String getYwx_price() { return ywx_price; } public void setYwx_price(String ywx_price) { this.ywx_price = ywx_price; } public String getGjrws_price() { return gjrws_price; } public void setGjrws_price(String gjrws_price) { this.gjrws_price = gjrws_price; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(train_no); dest.writeString(from_station_no); dest.writeString(train_name); dest.writeString(from_station); dest.writeString(to_station); dest.writeString(start_time); dest.writeString(end_time); dest.writeString(cast_time); dest.writeString(isToday); dest.writeString(isWz); dest.writeString(to_station_no); dest.writeString(seat_types); dest.writeString(WZ); dest.writeString(swz_num); dest.writeString(ydz_num); dest.writeString(yz_num); dest.writeString(rw_num); dest.writeString(rz_num); dest.writeString(gjrw_num); dest.writeString(yw_num); dest.writeString(dw_num); dest.writeString(wz_num); dest.writeString(edz_num); dest.writeString(qtxb_num); dest.writeString(tdz_num); dest.writeString(gjrw_price); dest.writeString(yz_price); dest.writeString(rz_price); dest.writeString(ywz_price); dest.writeString(dw_price); dest.writeString(ydz_price); dest.writeString(wz_price); dest.writeString(tdz_price); dest.writeString(dwx_price); dest.writeString(edz_price); dest.writeString(qtxb_price); dest.writeString(yw_price); dest.writeString(rw_price); dest.writeString(ywx_price); dest.writeString(gjrws_price); dest.writeString(date); } public static final Parcelable.Creator<TrainDetailDatas> CREATOR = new Creator<TrainDetailDatas>(){ @Override public TrainDetailDatas createFromParcel(Parcel source) { TrainDetailDatas datas = new TrainDetailDatas(); datas.train_no = source.readString(); datas.from_station_no = source.readString(); datas.train_name = source.readString(); datas.from_station = source.readString(); datas.to_station = source.readString(); datas.start_time = source.readString(); datas.end_time = source.readString(); datas.cast_time = source.readString(); datas.isToday = source.readString(); datas.isWz = source.readString(); datas.to_station_no = source.readString(); datas.seat_types = source.readString(); datas.WZ = source.readString(); datas.swz_num = source.readString(); datas.ydz_num = source.readString(); datas.yz_num = source.readString(); datas.rw_num = source.readString(); datas.rz_num = source.readString(); datas.gjrw_num = source.readString(); datas.yw_num = source.readString(); datas.dw_num = source.readString(); datas.wz_num = source.readString(); datas.edz_num = source.readString(); datas.qtxb_num = source.readString(); datas.tdz_num = source.readString(); datas.gjrw_price = source.readString(); datas.yz_price = source.readString(); datas.rz_price = source.readString(); datas.ywz_price = source.readString(); datas.dw_price = source.readString(); datas.ydz_price = source.readString(); datas.wz_price = source.readString(); datas.tdz_price = source.readString(); datas.dwx_price = source.readString(); datas.edz_price = source.readString(); datas.qtxb_price = source.readString(); datas.yw_price = source.readString(); datas.rw_price = source.readString(); datas.ywx_price = source.readString(); datas.gjrws_price = source.readString(); datas.date = source.readString(); return datas; } @Override public TrainDetailDatas[] newArray(int size) { return new TrainDetailDatas[size]; } }; }
package com.example.dllo.notestudio.DemoEventBus; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.dllo.notestudio.R; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; /** * Created by dllo on 16/11/17. */ public class DemoEventBusFr2 extends Fragment { private TextView tv1 ; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //接收EventBus 必须在onCreatView生命周期 //注册 EventBus.getDefault().register(this); View view = inflater.inflate(R.layout.demo_event_bus_fr2,container,false); return view; } @Override public void onDestroy() { super.onDestroy(); //取消注册 EventBus.getDefault().unregister(this); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tv1 = (TextView) view.findViewById(R.id.demo_eve_tv1); } @Subscribe //获取EventBus传过来的值必须要写@Subs 相当于接头暗号!!!!! public void getEventBus (DemoEventBean bean){ String str = bean.getStr(); tv1.setText(str); } }
package com.appsnipp.homedesign2.Adapter; import android.content.Context; import android.net.Uri; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.appsnipp.homedesign2.Entity.News; import com.appsnipp.homedesign2.R; import com.bumptech.glide.Glide; import java.util.ArrayList; public class NewsArrayAdapter extends ArrayAdapter<News> { Context _context; int _newsRowLayoutId; ArrayList<News> _newsList; OnNewsClickInterface _myListener; public NewsArrayAdapter(@NonNull Context context, int resource, @NonNull ArrayList<News> objects) { super(context, resource, objects); _context = context; _newsRowLayoutId = resource; _newsList = objects; } public interface OnNewsClickInterface { void onNewsAdapterClick(News selectedNews); } public void setOnNewsClickInterface(OnNewsClickInterface callback) { _myListener = callback; } @Override public int getCount() { return _newsList.size(); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView == null) { LayoutInflater layoutInflater = LayoutInflater.from(_context); convertView = layoutInflater.inflate(_newsRowLayoutId, null); } final News curNews = getItem(position); ImageView newsImage = convertView.findViewById(R.id.newsImage); TextView newsTitle = convertView.findViewById(R.id.newsTitle); TextView newsDate = convertView.findViewById(R.id.newsDate); Glide.with(_context) .load(curNews.getBackgroundPhotoId()) .error(R.mipmap.ic_launcher_load) .override(200, 200) .centerCrop() .into(newsImage); newsTitle.setText(curNews.getTitle()); newsDate.setText(curNews.getDate()); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _myListener.onNewsAdapterClick(curNews); } }); return convertView; } }
package TestJava; public class multiplecatchblocks { public static void main(String[] args) { int a=5; int result=0; try { result=a/0; } catch(NullPointerException e) { System.out.println("nullPointerException"); } catch(ArithmeticException e) { System.out.println("arithmeticexception"); } catch(NumberFormatException e) { System.out.println("nameformatexception"); } catch(Exception e) { System.err.println("Exception"); } } }
package br.com.diegomelo.cleanparse.model; import java.util.List; public class CustomAttributeListPojo { private List<SimplePojo> listSimplePojo; public List<SimplePojo> getListSimplePojo() { return listSimplePojo; } public void setListSimplePojo(List<SimplePojo> listSimplePojo) { this.listSimplePojo = listSimplePojo; } }
package demo8.pizzas; import demo8.Pizza; public class ChicagoStylePepperoniPizza extends Pizza { public ChicagoStylePepperoniPizza() { name = "Chicago Style Pepperoni Pizza"; dough = "Thin Crust dough"; sauce = "Plum Sauce"; toppings.add("Shredded Lucas Cheese"); } }
package org.training.dao.connection; import org.training.dao.exception.DAOException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by nicko on 1/25/2017. */ public class ConnectionManager { private ConnectionManager() { } public static ConnectionManager getInstance() { return InstanceHolder.INSTANCE; } private static class InstanceHolder { private static final ConnectionManager INSTANCE = new ConnectionManager(); } public AbstractConnection getMySQLConnection() { InitialContext context = null; try { context = new InitialContext(); DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/RestDB"); return new MySQLConnection(dataSource.getConnection()); } catch (SQLException e) { throw new DAOException(); } catch (NamingException e) { throw new RuntimeException(); // todo } } }
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.StringObservable; import java.io.ByteArrayInputStream; import java.io.InputStream; public class RXTest { /** * StringObservable 이 InputStream 을 byteArray 로 변환하는 과정을 테스트. * * map 과 flatMap 의 차이를 알게됨. * * 동일 observable 에서 자료형 변환에는 map 을, * 하나의 observable 에서 다른 obvervable 을 생성하려면 flatMap 을 사용한다. * * @param args */ public static void main(String[] args) { byte[] input = (new String("ABCDEFGHIJKL")).getBytes(); InputStream in = new ByteArrayInputStream(input); StringObservable.from(in, 3) // .map(new Func1<byte[], ByteBuf>() { // @Override // public ByteBuf call(byte[] bytes) { // System.out.println(bytes); // return Unpooled.wrappedBuffer(bytes); // }}) .subscribe(new Action1<byte[]>() { @Override public void call(byte[] bytes) { System.out.println(new String(bytes)); } }); } }
import java.util.*; import java.lang.*; import java.io.*; class Integ { public static void main(String arg[]) { Scanner d=new Scanner(System.in); int num=Integer.parseInt(d.next()); System.out.println(num); } }
package com.tencent.mm.plugin.account.bind.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.bind.ui.BindMContactVerifyUI.2; import com.tencent.mm.plugin.account.friend.a.x; class BindMContactVerifyUI$2$1 implements OnCancelListener { final /* synthetic */ x eGH; final /* synthetic */ 2 eGI; BindMContactVerifyUI$2$1(2 2, x xVar) { this.eGI = 2; this.eGH = xVar; } public final void onCancel(DialogInterface dialogInterface) { g.DF().c(this.eGH); } }
package com.hyw.producer.rabbit.task; import com.alibaba.fastjson.JSON; import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.dataflow.DataflowJob; import com.hyw.producer.rabbit.broker.RabbitBroker; import com.hyw.producer.rabbit.constant.BrokerMessageStatusEnum; import com.hyw.producer.rabbit.entity.BrokerMessage; import com.hyw.producer.rabbit.service.MessageStoreService; import com.hyw.rabbit.api.Message; import com.hyw.task.rabbit.annotation.ElasticJobConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * Project:rabbit-parent @author 源伟 * DateTime:2020/3/23 22:12 * Description:可靠性投递消息补偿任务 */ @Component @ElasticJobConfig( name = "com.hyw.producer.rabbit.task.RetryMessageDataflowJob", cron= "0/10 * * * * ?", description = "可靠性投递消息补偿任务", overwrite = true, shardingTotalCount = 1 ) @Slf4j public class RetryMessageDataflowJob implements DataflowJob<BrokerMessage> { @Autowired private MessageStoreService messageStoreService; @Autowired private RabbitBroker rabbitBroker; private static final int MAX_RETRY_COUNT = 3; @Override public List<BrokerMessage> fetchData(ShardingContext shardingContext) { List<BrokerMessage> list = messageStoreService.fetchTimeOutMessage4Retry(BrokerMessageStatusEnum.SENDING); log.info("--------@@@@@ 抓取数据集合, 数量: {} @@@@@@-----------" , list.size()); return list; } @Override public void processData(ShardingContext shardingContext, List<BrokerMessage> dataList) { dataList.forEach( brokerMessage -> { String messageId = brokerMessage.getMessageId(); if(brokerMessage.getTryCount() >= MAX_RETRY_COUNT) { this.messageStoreService.failure(messageId); log.warn(" -----消息设置为最终失败,消息ID: {} -------", messageId); } else { // 每次重发的时候要更新一下try count字段 this.messageStoreService.updateTryCount(messageId); // 重发消息 this.rabbitBroker.reliantSend(JSON.parseObject(brokerMessage.getMessage(), Message.class)); } }); } }
package pl.cwanix.opensun.commonserver.properties; import lombok.Getter; import lombok.Setter; @Getter @Setter public class SUNServerExternalServerProperties { private String ip; private int port; public String getServerUrl() { return "http://" + ip + ":" + port; } }
import com.mongodb.client.MongoDatabase; import crdhn.sis.transport.SISMongoDBConnectorClient; import org.bson.Document; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namdv */ public class test { public static void main(String[] args) { // UserInfo userInfo = new UserInfo(); // userInfo.setUsername("namdv"); // userInfo.setPassword("123"); // userInfo.setAddress("address"); // userInfo.setBirthday(System.currentTimeMillis()); // userInfo.setDepartment("department"); // userInfo.setEmail("namdv@fpt.com.vn"); // userInfo.setFullName("Dang Nam"); // int addUser = SISMongoDBConnectorClient.getInstance().addUser(userInfo, mongoDatabase); // System.out.println("addUser=" + addUser); // UserInfo user = SISMongoDBConnectorClient.getInstance().getUser("namdv", mongoDatabase); // System.out.println(user); // Document checkLogin = SISMongoDBConnectorClient.getInstance().login("namdv", "123"); // System.out.println("Login="+checkLogin.getString("_id")); // String createSession = SISMongoDBConnectorClient.getInstance().createSession("namdv", mongoDatabase); // System.out.println("SessionKey=" + createSession); // String sessionKey = "DYcaADO10HXi5OBCwZh9M54PwKFvsX0ZTwjbk73C3XM=";// "as/3twM09vO3sl991RGiIpWV0RYDUpgGAdVJKhEMEsk="; // String username = SISMongoDBConnectorClient.getInstance().getUserNameBySessionId(sessionKey); // System.out.println("Login success " + username); System.out.println(System.currentTimeMillis()); } }
package javaStudy.thread; import java.util.Date; public class ThreadClock implements Runnable { public static void main(String[] args) { new ThreadClock(); } ThreadClock() { // thread 생성, start Thread t = new Thread(this, "나 시계"); t.start(); System.out.println(t.getName()); } @Override public void run() { // thread가 수행할 작업 내용. 화면에 1초 간격으로 시간을 표시 while (true) { Date d = new Date(); // 년 월 일 시분초... System.out.println(d); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.saven.batch.domain.util; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; /** * Created by nrege on 1/30/2017. */ public class DataTypeUtils { public static Instant instantOf(String pattern, String val) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalDateTime dateTime = LocalDateTime.parse(val, formatter); return dateTime.toInstant(ZoneOffset.UTC); } public static Integer integerOf(String number) { return Integer.valueOf(number); } public static Double doubleOf(String number) { return number.equals("Infinity") ? Double.POSITIVE_INFINITY : new Double(number); } }
package com.ido.zcsd.repo; import com.ido.zcsd.entity.Post; import com.ido.zcsd.entity.User; import org.springframework.data.jpa.repository.JpaRepository; public interface PostRepo extends JpaRepository<Post,Integer> { }
/** * */ package org.springangularexample.dto.support; import org.springangularexample.entities.support.BaseEntity; /** * @author INST * */ public interface BaseDTO<T extends BaseEntity> { }
package com.tencent.mm.plugin.fav.ui; import android.content.Intent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.fav.a.ae; import com.tencent.mm.sdk.platformtools.bi; import java.io.Serializable; import java.util.Iterator; class FavTagEditUI$3 implements OnMenuItemClickListener { final /* synthetic */ FavTagEditUI jaA; final /* synthetic */ long jaB; FavTagEditUI$3(FavTagEditUI favTagEditUI, long j) { this.jaA = favTagEditUI; this.jaB = j; } public final boolean onMenuItemClick(MenuItem menuItem) { if (FavTagEditUI.b(this.jaA)) { FavTagEditUI.c(this.jaA); } else { Serializable tagList = FavTagEditUI.d(this.jaA).getTagList(); String trim = FavTagEditUI.d(this.jaA).getEditText().trim(); if (!bi.oW(trim)) { tagList.remove(trim); tagList.add(trim); } FavTagEditUI.a(this.jaA, ((ae) g.n(ae.class)).getFavItemInfoStorage().dy(this.jaB)); Intent intent; if (FavTagEditUI.e(this.jaA) != null) { FavTagEditUI.a(FavTagEditUI.e(this.jaA), tagList, this.jaA.getIntent().getIntExtra("key_fav_scene", 1)); intent = new Intent(); intent.putExtra("key_fav_result_list", tagList); this.jaA.setResult(-1, intent); } else { String[] strArr = new String[tagList.size()]; Iterator it = tagList.iterator(); int i = 0; while (it.hasNext()) { int i2 = i + 1; strArr[i] = (String) it.next(); i = i2; } intent = new Intent(); intent.putExtra("key_fav_result_array", strArr); intent.putExtra("key_fav_result_list", tagList); this.jaA.setResult(-1, intent); } this.jaA.finish(); this.jaA.YC(); } return true; } }
package com.stackroute.pe1; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import static org.junit.Assert.*; public class GuessGameTest { GuessGame guessgame; private static final String INPUT="34"; private ByteArrayInputStream inputStream=new ByteArrayInputStream(INPUT.getBytes()); @Before public void setUp() throws Exception { guessgame =new GuessGame(); System.setIn(inputStream); } @Test public void guessNum() { int answer= guessgame.guessNum(34); assertEquals(34,answer); } @After public void tearDown() throws Exception { guessgame=null; } }
import java.io.IOException; import domain.FFT; import domain.SlidingWindow; import io.RGB; import io.MyImageIO; import util.Complex; import util.MyArrayList; import static util.Util.*; /** * Focus stacking implementation */ public class FocusStacking { private int windowSize; private RGB color; private MyImageIO imageIO = null; MyArrayList<double[][]> channels = null; int[][] maxL2Norm_indexes = null; public FocusStacking(RGB color, int windowSize) { this.windowSize = windowSize; this.color = color; } /** * Method to load images from disk * @param fileNames A String array containing names of the files to load. * The default directory for the files is /src/main/resources/. * The images should be of same size. * @throws IOException */ public void loadImages(String[] fileNames) throws IOException { this.imageIO = new MyImageIO(); this.imageIO.loadImages(fileNames, this.color); // Get the green channels this.channels = imageIO.getChannels(); // Normalize the channels for (int k = 0; k < this.channels.getSize(); k++) channels.set(k, normalize(channels.get(k), 0, 255)); } /** * Compute the shrarpest image for each pixel position. * Constructs an integer matrix of the same size as the images that contains * the index numbers of the sharpest images on each pixel position. */ public void computeSharpestPixels() { int width = this.imageIO.getWidth(); int height = this.imageIO.getHeight(); int n = this.channels.getSize(); maxL2Norm_indexes = new int[width][height]; SlidingWindow slidingWindow = new SlidingWindow(windowSize, width, height); while(slidingWindow.hasNext()) { double maxL2Norm = 0; for (int k = 0; k < n; k++) { // Get the double-mirrored window () double[][] window = slidingWindow.getDoublyMirroredWindow(channels.get(k)); int i = slidingWindow.getX(); int j = slidingWindow.getY(); // Compute FFT Complex[][] fft = FFT.fft2(window); // Compute L^2 norm of this window and compare double norm = l2Norm(fft); //double l2Norm = MaxL2Norm(fft); if (norm > maxL2Norm) { maxL2Norm = norm; maxL2Norm_indexes[i][j] = k; } } // Next window slidingWindow.moveNext(); } } /** * Constructs and saves the stacked image. * @param outputFileName Name of the output file * @throws IOException */ public void saveImage(String outputFileName) throws IOException { int width = maxL2Norm_indexes.length; int height = maxL2Norm_indexes[0].length; // Create an array of the sharpest pixels int[] sharpestPixels = new int[(width+1)*(height+1)]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { sharpestPixels[i+j*width] = imageIO.getPixels().get(maxL2Norm_indexes[i][j])[i][j]; } } // Save the image MyImageIO.saveImage(sharpestPixels, width, height, outputFileName); } /** * Prints out a 2D int array of the sharpest pixel indexes * Utility method for debugging */ public void printSharpestPixelIndexes() { for (int i = 0; i < maxL2Norm_indexes[0].length; i++) { System.out.print(maxL2Norm_indexes[0][i]); for (int j = 1; j < maxL2Norm_indexes.length; j++) { System.out.print(","+maxL2Norm_indexes[j][i]); } System.out.println(""); } } }
package hu.dobrosi.jenkinsnotifier; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; public class Main { private static String url = "/rssAll"; private static int delay = 10000; private static String jenkinsProjectUrl; private Boolean normal = null; public static void main(String[] args) { jenkinsProjectUrl = args[0]; new Main().start(); } private Object ptitleText; private void start() { new Timer().schedule(new TimerTask() { @Override public void run() { reload(); } }, 0, delay); } private void reload() { SAXBuilder builder = new SAXBuilder(); try { InputStream in = new URL(jenkinsProjectUrl + url).openStream(); Document document = (Document) builder.build(in); Element rootNode = document.getRootElement(); Namespace ns = rootNode.getNamespace(); Element feed = (Element) rootNode.getChildren("entry", ns).get(0); Element title = feed.getChild("title", ns); String titleText = title.getText(); System.out.println(titleText); if (!titleText.equals(ptitleText)) { String[] cmd = null; if (isStable(titleText)) { if (normal == null || !normal) { cmd = new String[] { "notify-send", "-t", "10000", titleText }; } normal = true; } else { cmd = new String[] { "notify-send", "-u", "critical", titleText }; normal = false; } if (cmd != null) { Runtime.getRuntime().exec(cmd); } } ptitleText = titleText; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.err.println( "URL not found: " + jenkinsProjectUrl + "\nPlease configure your project Jenknis URL in pom.xml (jenkinsProjectUrl), or add it as first execution parameter."); System.exit(-1); } } private boolean isStable(String titleText) { return titleText.contains("(back to normal)") || titleText.contains("(stable)"); } }
package web.inttest.objects.lib; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class AccessMenu { private WebDriver driver; public static WebElement LOGINLINK; public static WebElement CAREERSLINK; public AccessMenu(WebDriver driver) { this.driver = driver; System.out.print("FORMLINKTTT" + driver); LOGINLINK = driver.findElement(By.xpath("/html/body/app-root/app-default-layout/mat-sidenav-container/mat-sidenav-content/app-default-header/header/nav[2]/ul/li[4]/a")); CAREERSLINK = driver.findElement(By.xpath("/html/body/app-root/app-default-layout/mat-sidenav-container/mat-sidenav-content/app-default-header/header/nav[2]/ul/li[2]/a")); } public static enum MenuItem{ LOGIN, CAREERS } public static void NavigateTo(MenuItem item){ switch (item){ case LOGIN: LOGINLINK.click(); return; case CAREERS: CAREERSLINK.click(); return; } } }
package com.thomaster.ourcloud.services.request.read; import com.thomaster.ourcloud.model.filesystem.UploadedFolder; import com.thomaster.ourcloud.model.user.OCUser; import com.thomaster.ourcloud.services.FileService; import com.thomaster.ourcloud.services.OCUserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ReadRequestFactoryTest { @Mock private OCUserService userService; @Mock private FileService fileService; @InjectMocks private ReadRequestFactory requestFactory = new ReadRequestFactory(userService, fileService); @BeforeEach public void init() { MockitoAnnotations.initMocks(this); } @Test void test_createReadRequest_happyPath() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); UploadedFolder folder = new UploadedFolder(); folder.setParentFolderPath(""); folder.setFileSize(100L); folder.setOriginalName("Thomaster"); folder.setRelativePath("Thomaster"); folder.setOwner(ocUser); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.of(ocUser)); ReadRequest readRequest = requestFactory.createReadRequest(folder, "Thomaster"); verify(userService, times(1)).getCurrentlyLoggedInUser(); assertThat(readRequest.getFileToRead()).isEqualTo(folder); assertThat(readRequest.getFileToReadOwner()).isEqualTo(ocUser); assertThat(readRequest.getInitiatingUser().get()).isEqualTo(ocUser); } @Test void test_createReadRequest_userNotLoggedIn() { OCUser ocUser = new OCUser(); ocUser.setId(1L); ocUser.setUsername("Thomaster"); ocUser.setUsedBytes(100L); UploadedFolder folder = new UploadedFolder(); folder.setParentFolderPath(""); folder.setFileSize(100L); folder.setOriginalName("Thomaster"); folder.setRelativePath("Thomaster"); folder.setOwner(ocUser); when(userService.getCurrentlyLoggedInUser()).thenReturn(Optional.empty()); ReadRequest readRequest = requestFactory.createReadRequest(folder, "Thomaster"); verify(userService, times(1)).getCurrentlyLoggedInUser(); assertThat(readRequest.getFileToRead()).isEqualTo(folder); assertThat(readRequest.getFileToReadOwner()).isEqualTo(ocUser); assertThat(readRequest.getInitiatingUser()).isEmpty(); } }
package com.tencent.mm.plugin.h.a.b; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.content.Context; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.tencent.mm.plugin.exdevice.j.b; import com.tencent.mm.sdk.f.e; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.lang.ref.WeakReference; import java.util.LinkedList; import java.util.UUID; import junit.framework.Assert; @TargetApi(18) public final class d { private int aeo; BluetoothDevice fNN; private BluetoothAdapter heY; Context hfX; BluetoothGatt hfY; b hfZ; BluetoothGattCharacteristic hga; BluetoothGattCharacteristic hgb; a hgc; Runnable hgd; Runnable hge; Runnable hgf; d hgg; final LinkedList<byte[]> hgh; volatile boolean hgi; int hgj; final BluetoothGattCallback hgk; public ag mHandler; long mSessionId; private HandlerThread mThread; private static class a extends ag { private final WeakReference<d> hgm; public a(Looper looper, d dVar) { super(looper); this.hgm = new WeakReference(dVar); } public final void handleMessage(Message message) { boolean z = true; d dVar = (d) this.hgm.get(); if (dVar == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "null == BluetoothLESession"); return; } byte[] atL; int i; int i2; switch (message.what) { case 0: x.i("MicroMsg.exdevice.BluetoothLESession", "------connectImp------"); if (1 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Remote device is connected !!!"); return; } else if (dVar.hgj == 0) { x.w("MicroMsg.exdevice.BluetoothLESession", "Remote device is connecting !!!"); return; } else { dVar.atQ(); if (dVar.hfY == null) { dVar.hfY = dVar.fNN.connectGatt(dVar.hfX, false, dVar.hgk); if (dVar.hfY == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "mDevice.connectGatt Failed!!!"); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } dVar.hgj = 0; dVar.mHandler.postDelayed(dVar.hgf, 10000); return; } else if (dVar.hfY.connect()) { dVar.hgj = 0; dVar.mHandler.postDelayed(dVar.hgf, 10000); return; } else { x.e("MicroMsg.exdevice.BluetoothLESession", "mBluetoothGatt.connect() Failed!!!"); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } } case 1: x.i("MicroMsg.exdevice.BluetoothLESession", "------disconnectImp------"); if (3 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "diconnect or close is called aready, just leave"); return; } dVar.atQ(); if (dVar.hfY == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "disconnect:BluetoothGatt not found"); return; } dVar.hgj = 3; dVar.mHandler.removeCallbacks(dVar.hgf); dVar.mHandler.removeCallbacks(dVar.hge); dVar.hfY.disconnect(); return; case 2: x.i("MicroMsg.exdevice.BluetoothLESession", "------closeImp------"); if (3 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Close aready, Just leave"); return; } dVar.atQ(); if (dVar.hfY == null) { x.w("MicroMsg.exdevice.BluetoothLESession", "close:BluetoothGatt not found"); return; } dVar.hgj = 3; dVar.hfY.disconnect(); dVar.hfY.close(); dVar.hfY = null; return; case 3: x.i("MicroMsg.exdevice.BluetoothLESession", "------writeDataAsync------ length = %d", new Object[]{Integer.valueOf(((byte[]) message.obj).length)}); if (1 != dVar.hgj) { x.e("MicroMsg.exdevice.BluetoothLESession", "Not ready for write data, connectstate = %d", new Object[]{Integer.valueOf(dVar.hgj)}); if (dVar.hfZ != null) { dVar.hfZ.hfE.j(dVar.mSessionId, false); return; } return; } boolean z2 = (dVar.hfY == null || dVar.hgb == null) ? false : true; Assert.assertTrue(z2); dVar.hgh.add(atL); if (!dVar.hgi) { if (1 != dVar.hgh.size()) { z = false; } Assert.assertTrue(z); dVar.atR(); return; } return; case 4: i = message.arg1; String str = "MicroMsg.exdevice.BluetoothLESession"; String str2 = "------onConnectionStateChangeImp------ aState = %s"; Object[] objArr = new Object[1]; objArr[0] = i == 2 ? "Connected" : "Disconnected"; x.i(str, str2, objArr); if (i == 2) { x.i("MicroMsg.exdevice.BluetoothLESession", "PHY Connected is OK, mConnectState = %d", new Object[]{Integer.valueOf(dVar.hgj)}); if (3 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Close or disconnect is Called, Leave without discover Services"); dVar.mHandler.removeCallbacks(dVar.hgf); return; } else if (1 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Connected is done, Leave without discover Services"); dVar.mHandler.removeCallbacks(dVar.hgf); return; } else if (dVar.hfY.discoverServices()) { x.i("MicroMsg.exdevice.BluetoothLESession", "start discoverServices..."); return; } else { x.e("MicroMsg.exdevice.BluetoothLESession", "discover Services start failed!!!"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } } else if (i == 0) { x.w("MicroMsg.exdevice.BluetoothLESession", "Disconnected from GATT server."); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } else { return; } case 5: BluetoothGatt bluetoothGatt = (BluetoothGatt) message.obj; x.i("MicroMsg.exdevice.BluetoothLESession", "onServicesDiscoveredImp, status = %d", new Object[]{Integer.valueOf(message.arg1)}); if (3 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Close or disconnect is Called, Just Leave"); dVar.mHandler.removeCallbacks(dVar.hgf); return; } else if (1 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Connected is done, Just Leave"); dVar.mHandler.removeCallbacks(dVar.hgf); return; } else if (i != 0) { x.e("MicroMsg.exdevice.BluetoothLESession", "Discover services error"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } else { BluetoothGattService service = bluetoothGatt.getService(UUID.fromString(h.hgN)); if (service == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "Can't not find service(with UUID 0xfee7)"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } dVar.hga = service.getCharacteristic(UUID.fromString(h.hgP)); if (dVar.hga == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "Can't not find characteristic(with UUID 0xfec8)"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } dVar.hgb = service.getCharacteristic(UUID.fromString(h.hgO)); if (dVar.hgb == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "Can't not find characteristic(with UUID 0xfec7)"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } x.i("MicroMsg.exdevice.BluetoothLESession", "mRecvCharacteristic.getProperties = %d", new Object[]{Integer.valueOf(dVar.hga.getProperties())}); if ((dVar.hga.getProperties() & 32) == 0) { x.e("MicroMsg.exdevice.BluetoothLESession", "Read characteristic can not be indicated"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } x.i("MicroMsg.exdevice.BluetoothLESession", "Set read characteristic indicator"); d dVar2 = dVar.hgg; BluetoothGattCharacteristic bluetoothGattCharacteristic = dVar.hga; if (dVar2.hfY.setCharacteristicNotification(bluetoothGattCharacteristic, true)) { BluetoothGattDescriptor descriptor = bluetoothGattCharacteristic.getDescriptor(UUID.fromString(h.hgM)); if (descriptor == null) { x.e("MicroMsg.exdevice.BluetoothLESession", "Can not get configure descriptor"); z = false; } else { x.i("MicroMsg.exdevice.BluetoothLESession", "Configure descriptor permissions: " + descriptor.getPermissions()); if (!descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)) { x.e("MicroMsg.exdevice.BluetoothLESession", "Can not set configure descriptor value"); z = false; } else if (dVar2.hfY.writeDescriptor(descriptor)) { dVar2.mHandler.postDelayed(dVar2.hge, 5000); } else { x.e("MicroMsg.exdevice.BluetoothLESession", "Can not write configure descriptor value"); z = false; } } } else { x.e("MicroMsg.exdevice.BluetoothLESession", "Unable to set indicator for read characteristic"); z = false; } if (!z) { x.e("MicroMsg.exdevice.BluetoothLESession", "mSelfSession.setCharacteristicNotification Failed!!!"); dVar.hgj = 2; dVar.mHandler.removeCallbacks(dVar.hgf); if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } return; } case 6: Object obj = message.obj; x.i("MicroMsg.exdevice.BluetoothLESession", "------onDescriptorWriteImp------ status = %d", new Object[]{Integer.valueOf(message.arg1)}); dVar.mHandler.removeCallbacks(dVar.hge); dVar.mHandler.removeCallbacks(dVar.hgf); if (3 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Close or disconnect is Called, Just Leave"); return; } else if (1 == dVar.hgj) { x.w("MicroMsg.exdevice.BluetoothLESession", "Connected is done, Just Leave"); return; } else if (i2 != 0) { x.e("MicroMsg.exdevice.BluetoothLESession", "Write configure descriptor error"); dVar.hgj = 2; if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, false); return; } return; } else { dVar.hgj = 1; if (dVar.hfZ != null) { dVar.hfZ.hfE.i(dVar.mSessionId, true); } x.i("MicroMsg.exdevice.BluetoothLESession", "------BLE connect successfully------ mConnectState = %d", new Object[]{Integer.valueOf(dVar.hgj)}); return; } case 7: i2 = message.arg1; x.i("MicroMsg.exdevice.BluetoothLESession", "------onDataWriteCallbackImp------ status = %d", new Object[]{Integer.valueOf(i2)}); dVar.mHandler.removeCallbacks(dVar.hgd); if (i2 != 0) { x.e("MicroMsg.exdevice.BluetoothLESession", "write data error: " + i2); if (dVar.hfZ != null) { dVar.hfZ.hfE.j(dVar.mSessionId, false); } dVar.atR(); return; } atL = dVar.hgc.atL(); x.d("MicroMsg.exdevice.BluetoothLESession", "Out data dump = %s", new Object[]{b.aq(atL)}); if (atL == null) { x.i("MicroMsg.exdevice.BluetoothLESession", "write data complete"); if (dVar.hfZ != null) { dVar.hfZ.hfE.j(dVar.mSessionId, true); } dVar.atR(); return; } x.i("MicroMsg.exdevice.BluetoothLESession", "write next chunk..."); dVar.hgb.setValue(atL); dVar.hfY.writeCharacteristic(dVar.hgb); dVar.mHandler.postDelayed(dVar.hgd, 5000); return; case 8: atL = (byte[]) message.obj; x.i("MicroMsg.exdevice.BluetoothLESession", "------onDataReceiveImp------"); if (bi.bC(atL)) { x.e("MicroMsg.exdevice.BluetoothLESession", "Receive data is null or nil"); return; } String O = b.O(atL, atL.length); x.i("MicroMsg.exdevice.BluetoothLESession", "data length = %d", new Object[]{Integer.valueOf(atL.length)}); x.d("MicroMsg.exdevice.BluetoothLESession", "data dump = %s", new Object[]{O}); if (dVar.hfZ != null) { dVar.hfZ.hfE.b(dVar.mSessionId, atL); return; } return; default: return; } } } @TargetApi(18) public d(long j, Context context, b bVar) { this.hgh = new LinkedList(); this.hgi = false; this.hgk = new 1(this); this.aeo = -1; this.aeo = hashCode(); this.hgg = this; this.hfZ = bVar; this.hfX = context; this.heY = ((BluetoothManager) this.hfX.getSystemService("bluetooth")).getAdapter(); this.mSessionId = j; this.hgj = 3; this.fNN = this.heY.getRemoteDevice(com.tencent.mm.plugin.h.a.e.a.bZ(j)); this.hga = null; this.hgb = null; this.hgc = new a(); this.mThread = e.Xs("BluetoothLESession_handlerThread"); this.mThread.start(); this.mHandler = new a(this.mThread.getLooper(), this); this.hgd = new Runnable() { public final void run() { x.e("MicroMsg.exdevice.BluetoothLESession", "Write data timeout"); if (d.this.hfZ != null) { d.this.hfZ.hfE.j(d.this.mSessionId, false); } d.this.atR(); } }; this.hge = new 3(this); this.hgf = new 4(this); } public final boolean connect() { x.i("MicroMsg.exdevice.BluetoothLESession", "------connect------"); return this.mHandler.sendMessage(this.mHandler.obtainMessage(0)); } public final void close() { x.i("MicroMsg.exdevice.BluetoothLESession", "------close------"); if (!this.mHandler.sendMessage(this.mHandler.obtainMessage(2))) { x.e("MicroMsg.exdevice.BluetoothLESession", "SendMessage Failed!!! MessageWhat = %d", new Object[]{Integer.valueOf(2)}); } this.mThread.quitSafely(); } final void atQ() { this.hgi = false; this.hgh.clear(); } final void atR() { if (this.hgh.isEmpty()) { this.hgi = false; return; } this.hgc.setData((byte[]) this.hgh.pop()); x.d("MicroMsg.exdevice.BluetoothLESession", "Out data dump = %s", new Object[]{b.aq(this.hgc.atL())}); this.hgb.setValue(r0); this.mHandler.postDelayed(this.hgd, 5000); if (!this.hfY.writeCharacteristic(this.hgb)) { x.e("MicroMsg.exdevice.BluetoothLESession", "mBluetoothGatt.writeCharacteristic Failed!!!"); } this.hgi = true; } }
package com.fight.job.admin.dao; import com.fight.job.admin.entity.LogInfoEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * 任务日志操作类 * @author luo */ @Mapper @Repository public interface LogInfoDao { List<LogInfoEntity> selectAll(); List<LogInfoEntity> selectByGroupId(@Param("groupId") String groupId); int insert(LogInfoEntity entity); // 未更新任务执行信息 int update(LogInfoEntity entity); int updateTriggerInfoByLogId(@Param("triggerTime") Date triggerTime, @Param("triggerCode") int triggerCode, @Param("triggerMsg") String triggerMsg, @Param("logId") String logId); int updateHandleInfoByLogId(@Param("handleTime") Date handleTime, @Param("handleCode") int handleCode, @Param("handleMsg") String handleMsg, @Param("logId") String logId); }
import java.util.Scanner; public class JavaSession2Assignment4 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter a number"); int month = s.nextInt(); switch (month) { case 1 : System.out.println("31 Days");break; case 2: System.out.println("28 Days");break; case 3 : System.out.println("31 Days");break; case 4 : System.out.println("30 Days");break; case 5 : System.out.println("31 Days");break; case 6 : System.out.println("30 Days");break; case 7 : System.out.println("31 Days");break; case 8 : System.out.println("31 Days");break; case 9 : System.out.println("30 Days");break; case 10 : System.out.println("31 Days");break; case 11 : System.out.println("30 Days");break; case 12 : System.out.println("31 Days");break; } } }
package main.java.com; import java.net.UnknownHostException; /** * Created by joseluisdelacruz */ public interface AddressService { String getServerAddress() throws Exception; }
package io.ygg.tcp; import io.ygg.common.Log; import io.ygg.common.Session; import io.ygg.packet.Packet; import io.ygg.packet.PacketNotFoundException; import io.ygg.packet.PacketOpcode; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; /* * Copyright (c) 2015 * Christian Tucker. All rights reserved. * * The use of OGServer is free of charge for personal and commercial use. * * * THIS SOFTWARE IS PROVIDED 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * * * Policy subject to change. */ /** * The {@link TcpProcessor} class implements the {@link Runnable} interface * to aid in the concurrent asynchronous design. * * @author Christian Tucker */ public class TcpProcessor implements Runnable { private Selector selector; private ServerSocketChannel serverSocket; public TcpProcessor() throws IOException { selector = Selector.open(); serverSocket = ServerSocketChannel.open(); } public TcpProcessor(Selector selector, ServerSocketChannel serverSocket) { this.selector = selector; this.serverSocket = serverSocket; } public void run() { if ((serverSocket.isOpen()) && (selector.isOpen())) { try { serverSocket.configureBlocking(false); serverSocket.bind(new InetSocketAddress("0.0.0.0", TcpServer.getPort())); serverSocket.register(selector, SelectionKey.OP_ACCEPT); Log.info("waiting for connections..."); while (!Thread.interrupted()) { selector.select(); Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) { continue; } try { if (key.isAcceptable()) { acceptKey(key, selector); } else if (key.isReadable()) { processData(key); } } catch (IOException e) { if (e.getMessage().equals("An existing connection was forcibly closed by the remote host")) { Log.info("A connection has been lost for key: " + key); if ((key.attachment() != null)) { ((Session) key.attachment()).close(); } else { key.channel().close(); } key.cancel(); continue; } e.printStackTrace(); } } } if (Thread.interrupted()) { selector.close(); serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { selector.close(); serverSocket.close(); } catch (IOException ignored) { } } } else { Log.error("Failure to initialize the server, perhaps the socket or selector is closed?"); Log.info("Socket state: " + ((serverSocket.isOpen() ? "Open" : "Closed")) + " || Selector state: " + ((selector.isOpen() ? "Open" : "Closed"))); } } /** * Called by the {@link TcpProcessor} logic thread whenever a {@link SelectionKey}'s * {@link SelectionKey#isAcceptable()} value is set to true. The primary function of * this method is to accept a connection and prepare it for future network communication. * * @param key The {@link SelectionKey} relative to the connection. * @param selector The {@link Selector} being used by the server. * @throws IOExcepton if something goes wrong with low level io processing */ private void acceptKey(SelectionKey key, Selector selector) throws IOException { ServerSocketChannel serverSocket = (ServerSocketChannel) key.channel(); SocketChannel clientSocket = serverSocket.accept(); clientSocket.configureBlocking(false); Log.info("Incoming connection from " + clientSocket.getRemoteAddress()); SelectionKey clientKey = clientSocket.register(selector, SelectionKey.OP_READ); clientKey.attach(new Session(clientKey)); } /** * Called by the {@link TcpProcessor} logic thread whenever a {@link SelectionKey}'s * {@link SelectionKey#isReadable()} value is set to true. The primary function of this * method is to process the incoming {@link PacketOpcode} and locate the correct method * to call with the available data. * * @param key The {@link SelectionKey} relative to the connection. * @throws IOException if something goes wrong with low level io processing */ private void processData(SelectionKey key) throws IOException { Session session = (Session) key.attachment(); if (session == null) { Log.error("processData was called using a SelectionKey that contains no attacment."); key.cancel(); } int bytesReceived = 0; boolean endOfStream; try { assert session != null; endOfStream = ((bytesReceived = session.getChannel().read(session.getInputBuffer())) == -1); if (endOfStream) { session.segment(); key.cancel(); return; } } catch (IOException e) { session.close(); } Session.bytesIn += bytesReceived; Session.bytesInCurrent += bytesReceived; bytesReceived += session.mark(); // The header that we're sending with our data is 4 bytes long, which is an Integer // containing the length of the packet in bytes, if the data that we have available // is not at least 4 bytes we will not read anything and wait until the next cycle. if (bytesReceived < 4) { return; } if (!session.segmented() && !session.header()) { ByteBuffer buffer = session.getInputBuffer().duplicate(); buffer.flip(); session.setBlockSize(buffer.getInt()); session.getInputBuffer().mark(); session.prime(); Log.debug("[TCP] - Incoming packet size(in bytes): " + session.blockSize()); } // Verify that we have enough data to process the entire packet. // Subtract 4 from the amount of bytes read so we don't process the // byte-size of the integer for the packet-length. if ((bytesReceived - 4) < session.blockSize()) { // Not enough data was received from the network, so we nBecaueed to reset the // Buffer's mark to the previous mark, so we can read this data again during // the next iteration. Log.debug("[TCP] - Current data received: ( " + (bytesReceived - 4) + " / " + session.blockSize() + " )"); session.mark(bytesReceived); session.getInputBuffer().mark(); } else { session.mark(bytesReceived); try { Packet._decode(session); } catch (PacketNotFoundException e) { e.printStackTrace(); } session.release(); } } }
package Tugas; /** * * @author Master */ public class Laptop extends Komputer{ public String jnsBaterai; public Laptop() { } public Laptop(String jnsBaterai, String merk, String jnsProcessor, int kecProcessor, int sizeMemory) { super(merk, jnsProcessor, kecProcessor, sizeMemory); this.jnsBaterai = jnsBaterai; } public void tampilLaptop(){ super.tampilData(); System.out.println("Jenis Baterai\t\t: " + jnsBaterai); } }
package com.lspring.step2; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class PersonDao { @Test public void injectTest(){ @SuppressWarnings("resource") ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans_step2.xml"); System.out.println(applicationContext.getBean("person")); System.out.println(applicationContext.getBean("person_c")); Person person = (Person) applicationContext.getBean("person"); //Spring 会把集合类型,初始化时统一使用某种类型 System.out.println(person.getSchool().getClass()); System.out.println("person_null:"+applicationContext.getBean("person_null")); } }
package com.company; import java.awt.*; import java.util.ArrayList; public class Zeichnung { private ArrayList<Figur> figuren; public Zeichnung() { this.figuren = new ArrayList<>(); } // Zeichnet alle Figuren public void zeichneFiguren(Graphics g) { for (Figur f : figuren) { f.zeichne(g); } } public void hinzufuegen(Figur figur) { figuren.add(figur); } public void allesLoeschen() { figuren.clear(); } }
package org.zwj.mywebapp.test.service; import javax.annotation.Resource; import org.zwj.mywebapp.core.feature.test.TestSupport; import org.zwj.mywebapp.web.service.UserService; public class UserServiceTest extends TestSupport { @Resource private UserService userService; }
/* * Copyright 2002-2013 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 * * 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.springframework.integration.aws.core; import java.net.URI; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.integration.test.util.TestUtils; import com.amazonaws.AmazonWebServiceClient; /** * The abstract test class for Amazon WebService client factory tests * @author Amol Nayak * * @since 0.5 * */ public abstract class AbstractAWSClientFactoryTests<T extends AmazonWebServiceClient> { protected AbstractAWSClientFactory<T> factory; @Before public final void setup() { factory = getFactory(); } /** * The subclass is responsible for returning the appropriate factory implementation */ protected abstract AbstractAWSClientFactory<T> getFactory(); /** * Gets the endpoint for the service in US-EAST-1 region */ protected abstract String getUSEast1Endpoint(); /** * Gets the endpoint for the service in US-EAST-1 region */ protected abstract String getEUWest1Endpoint(); /** * Gets the Suffix for the endpoint URL which is service specific */ protected abstract String getSuffix(); /** * The test case for giving a US east endpoint without protocol */ @Test public void withUSEast1EndpointWithoutProtocol() { String usEast1 = getUSEast1Endpoint(); factory.clear(); T client = factory.getClient(usEast1 + getSuffix()); Map<String, T> map = factory.getClientMap(); Assert.assertNotNull(map); Assert.assertEquals(1, map.size()); Assert.assertTrue("Expected one key with value https://" + usEast1, map.containsKey("https://" + usEast1)); URI endpoint = TestUtils.getPropertyValue(client, "endpoint", URI.class); Assert.assertNotNull(endpoint); Assert.assertEquals(usEast1,endpoint.getHost()); Assert.assertEquals("https",endpoint.getScheme()); } /** * Tests the factory by providing an endpoint in US east with protocol as http */ @Test public void withUSEast1EndpointWithProtocol() { String usEast1 = getUSEast1Endpoint(); factory.clear(); T client = factory.getClient("http://" + usEast1 + getSuffix()); Map<String, T> map = factory.getClientMap(); Assert.assertNotNull(map); Assert.assertEquals(1, map.size()); Assert.assertTrue("Expected one key with value http://" + usEast1, map.containsKey("http://" + usEast1)); URI endpoint = TestUtils.getPropertyValue(client, "endpoint", URI.class); Assert.assertNotNull(endpoint); Assert.assertEquals(usEast1,endpoint.getHost()); Assert.assertEquals("http",endpoint.getScheme()); } /** * Calls the getClient multiple times to get the same client instance on each invocation */ @Test public void withMultipleCallsToSameEndpoint() { String usEast1 = getUSEast1Endpoint(); factory.clear(); T client = factory.getClient("https://" + usEast1 + getSuffix()); Map<String, T> map = factory.getClientMap(); Assert.assertNotNull(map); Assert.assertEquals(1, map.size()); Assert.assertTrue("Expected one key with value http://" + usEast1, map.containsKey("https://" + usEast1)); //default to https T client1 = factory.getClient(usEast1 + getSuffix()); map = factory.getClientMap(); Assert.assertEquals(1, map.size()); Assert.assertTrue("Expected one key with value http://" + usEast1, map.containsKey("https://" + usEast1)); Assert.assertTrue("Expecting to get the same instance of the client, but was not", client == client1); } /** *Calls to different endpoints on the same client, expected to return a client with *appropriate endpoint URI set */ @Test public void withMultipleCallsToDifferentEndpoints() { String usEast1 = getUSEast1Endpoint(); String euWest1 = getEUWest1Endpoint(); factory.clear(); T client = factory.getClient(usEast1 + getSuffix()); Map<String, T> map = factory.getClientMap(); Assert.assertNotNull(map); Assert.assertEquals(1, map.size()); Assert.assertTrue("Expected one key with value https://" + usEast1, map.containsKey("https://" + usEast1)); URI endpoint = TestUtils.getPropertyValue(client, "endpoint", URI.class); Assert.assertNotNull(endpoint); Assert.assertEquals(usEast1,endpoint.getHost()); Assert.assertEquals("https",endpoint.getScheme()); client = factory.getClient(euWest1 + getSuffix()); map = factory.getClientMap(); Assert.assertNotNull(map); Assert.assertEquals(2, map.size()); Assert.assertTrue("Expected one key with value https://" + euWest1, map.containsKey("https://" + euWest1)); endpoint = TestUtils.getPropertyValue(client, "endpoint", URI.class); Assert.assertNotNull(endpoint); Assert.assertEquals(euWest1,endpoint.getHost()); Assert.assertEquals("https",endpoint.getScheme()); } }
package com.bjstudio.blog.login.Service; import com.bjstudio.blog.login.model.Member; import com.bjstudio.blog.login.model.SecurityUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * UserDetailsService는 DB로부터 user의 정보를 불러오는 일을 함.(DAO역할) * 그렇기에 메소드에 userName(id 값)만 파라미터로 존재하는 것임. * 즉 인증과정은 이미 다른 서드파티 시스템을 이용하고, 인증 후 데이터가 필요시 * 이 클래스를 사용하여 유저 데이터를 가져오는 것임. */ @Service public class CustomSecurityUserService implements UserDetailsService { @Autowired private MemberService memberService; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { return this.memberService.findByEmail(email).filter(m -> m != null).map(m -> new SecurityUser(m)).get(); } }
package superintendent.apis.discord; import java.util.List; import superintendent.apis.discord.channels.DiscordTextChannel; public interface DiscordUser { /** * Gets the full username of the user represented by this object. * * @return the user's username */ public String getUsername(); /** * Gets the nickname used by the user in a given DiscordServer. * * @param server the server in which to check the user's nickname * @return the user's nickname */ public String getNickname(DiscordServer server); /** * Gets the string used to tag the user in a message. * * @return the string used to tag the user */ public String getTag(); /** * Gets a DiscordChannel object representing the private message channel * between the bot and the user. * * @return the DiscordChannel representing PMs between the bot and user * @throws InsufficientPermissionsException if the user does not accept PMs */ public DiscordTextChannel getPmChannel() throws InsufficientPermissionsException; /** * Gets a list of DiscordServer objects representing all the servers that the * user and bot are both simultaneously in. * * @return a list of DiscordServers that both the bot and user are in */ public List<DiscordServer> getCommonServers(); /** * Gets a list of DiscordRoles representing the roles that the user has on a * given server. * * @param server the server to check * @return a list of DiscordRoles that the user has */ public List<DiscordRole> getRoles(DiscordServer server); /** * Returns true if and only if the user is the owner of the bot. * * @return true iff the user is the bot's owner */ public boolean isBotOwner(); /** * Returns true if and only if the user is a bot. * * @return true iff the user is a bot */ public boolean isBot(); /** * Returns true if and only if the user is an admin on the given * DiscordServer. * * @return true iff the user is an admin on the server */ public boolean isAdminOnServer(DiscordServer server); }
package com.szcinda.express.persistence; import com.szcinda.express.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.Entity; import javax.validation.constraints.NotNull; @EqualsAndHashCode(callSuper = true) @Data @Entity public class Profile extends BaseEntity { @NotNull(message = "名称不能为空") private String name; @NotNull(message = "行政区域不能为空") private String district; private String province; private String city; private String street; private String fullAddress; private String contactMan; private String contactPhone; private String company; }
package com.worldchip.advertising.client.activity; import java.util.Timer; import java.util.TimerTask; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import com.worldchip.advertising.client.adapter.AdListAdapter; import com.worldchip.advertising.client.adapter.BasicListAdapter; import com.worldchip.advertising.client.adapter.CaptionListAdapter; import com.worldchip.advertising.client.adapter.FunctionListAdapter; import com.worldchip.advertising.client.adapter.OtherListAdapter; import com.worldchip.advertising.client.adapter.TimeListAdapter; import com.worldchip.advertising.client.utils.SetupUtils; import com.worldchip.advertisingclient.R; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.text.InputType; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; //import android.view.DisplayManagerAw; //import android.os.IPowerManager; import android.os.RemoteException; //import android.os.ServiceManager; import android.content.ContentResolver; import android.provider.Settings; //import android.os.SystemProperties; import android.media.AudioManager; //import com.softwinner.Gpio; public class SetupActivity extends Activity { private static final String PROP_DISPLAY_ROTATE = "persist.sys.displayrot"; private ListView menuListView; private BasicListAdapter basicListAdapter; private CaptionListAdapter captionListAdapter; private FunctionListAdapter functionListAdapter; private OtherListAdapter otherListAdapter; private TimeListAdapter timeListAdapter; private AdListAdapter adListAdapter; private ImageView menu0Img; private ImageView menu1Img; private ImageView menu2Img; private ImageView menu3Img; private TextView topMenuText; private int menuIndex = 0; int selectedPosition = 0; private final static String POWER_DELAY_TIME = "/data/misc/user/0/delay_boot.txt"; private final static int ROATION = 0xff; private Timer checkIOTimer; private boolean isRoationChange = false; private static final char PORT_TYPE = 'B'; private static final int PORT_NUM_20 = 20; private static final int PORT_NUM_21 = 21; private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case BasicListAdapter.SET_TIME: switchMenu(4); break; case BasicListAdapter.RESET_MENU: showResetMenuDialog(); break; case BasicListAdapter.CLICK_LANGUAGE: refreshList(); //this.finish(); SetupActivity.this.recreate(); break; case FunctionListAdapter.AD_SET: switchMenu(5); break; case FunctionListAdapter.REMOTE_CONTROL: startActivity("com.worldchip.advertisingclient", "com.worldchip.advertising.client.activity.RemoteControlMainActivity"); break; case OtherListAdapter.OPEN_FILE_MANAGER: startActivity("com.softwinner.TvdFileManager", "com.softwinner.TvdFileManager.MainUI"); break; case OtherListAdapter.REFRESH_LIST: refreshList(); break; case TimeListAdapter.RESET_TIME_MENU: switchMenu(4); break; case ROATION: SetupActivity.this.recreate(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup); SetupUtils.setupSystemLangue(this); initMenuImg(); initAllAdapter(); recoverLastState(); } @Override protected void onResume() { // TODO Auto-generated method stub SetupUtils.setupSystemLangue(this); if (SetupUtils.isAutoRotation(this)) { startCheckRotion(); } super.onResume(); } // 每隔3s监测IO口。 private void startCheckRotion() { checkIOTimer = new Timer(); checkIOTimer.schedule(new TimerTask() { @Override public void run() { //by zhang Log.d("zhang","Not suuport !!!"); //checkAndAutoRotation(); } }, 0, 5000); } /*private void checkAndAutoRotation() { // io20 状态 int io20 = Gpio.readGpio(PORT_TYPE, PORT_NUM_20); // io21 状态 int io21 = Gpio.readGpio(PORT_TYPE, PORT_NUM_21); isRoationChange = checkRoation(io20, io21); if (!isRoationChange) { if (io20 == 1 && io21 == 1) { getSharedPreferences("function_menu", 0).edit().putInt("rotation_index", 0).commit(); Settings.System.putInt(getContentResolver(), Settings.System.BD_FOLDER_PLAY_MODE, 0); SystemProperties.set(PROP_DISPLAY_ROTATE, "0"); } else if (io20 == 0 && io21 == 1) { getSharedPreferences("function_menu", 0).edit().putInt("rotation_index", 1).commit(); Settings.System.putInt(getContentResolver(), Settings.System.BD_FOLDER_PLAY_MODE, 1); SystemProperties.set(PROP_DISPLAY_ROTATE, "90"); } else if (io20 == 0 && io21 == 0) { getSharedPreferences("function_menu", 0).edit().putInt("rotation_index", 2).commit(); Settings.System.putInt(getContentResolver(), Settings.System.BD_FOLDER_PLAY_MODE, 2); SystemProperties.set(PROP_DISPLAY_ROTATE, "180"); } else if (io20 == 1 && io21 == 0) { getSharedPreferences("function_menu", 0).edit().putInt("rotation_index", 3).commit(); Settings.System.putInt(getContentResolver(), Settings.System.BD_FOLDER_PLAY_MODE, 3); SystemProperties.set(PROP_DISPLAY_ROTATE, "270"); } mHandler.sendEmptyMessage(ROATION); } }*/ private boolean checkRoation(int PB20, int PB21) { int roation = 0; if (PB20 == 1 && PB21 == 1) { roation = 0; } if (PB20 == 0 && PB21 == 1) { roation = 1; } if (PB20 == 0 && PB21 == 0) { roation = 2; } if (PB20 == 1 && PB21 == 0) { roation = 3; } return roation == getSharedPreferences("function_menu", 0).getInt("rotation_index", 0); } private void recoverLastState() { menuIndex = getSharedPreferences("id_prefer", 0).getInt("menuIn", 0); switchMenu(menuIndex); setFocusImgAndText(menuIndex); } private void initAllAdapter() { menuListView = (ListView) findViewById(R.id.menu_list); menuListView.setOnItemSelectedListener(new MenuListSelectListener()); topMenuText = (TextView) findViewById(R.id.top_menu_text); basicListAdapter = new BasicListAdapter(this, mHandler); captionListAdapter = new CaptionListAdapter(this); functionListAdapter = new FunctionListAdapter(this, mHandler); otherListAdapter = new OtherListAdapter(this,mHandler); timeListAdapter = new TimeListAdapter(this, mHandler); adListAdapter = new AdListAdapter(this); } private void initMenuImg() { menu0Img = (ImageView) findViewById(R.id.menu0_image); menu0Img.setOnClickListener(new MenuImgClickListener()); menu1Img = (ImageView) findViewById(R.id.menu1_image); menu1Img.setOnClickListener(new MenuImgClickListener()); menu2Img = (ImageView) findViewById(R.id.menu2_image); menu2Img.setOnClickListener(new MenuImgClickListener()); menu3Img = (ImageView) findViewById(R.id.menu3_image); menu3Img.setOnClickListener(new MenuImgClickListener()); } private void resetAllMenuImg() { menu0Img.setImageDrawable(getResources().getDrawable(R.drawable.menu0)); menu1Img.setImageDrawable(getResources().getDrawable(R.drawable.menu1)); menu2Img.setImageDrawable(getResources().getDrawable(R.drawable.menu2)); menu3Img.setImageDrawable(getResources().getDrawable(R.drawable.menu3)); } private void setFocusImgAndText(int menuIndex) { resetAllMenuImg(); if (menuIndex == 0) { topMenuText.setText(R.string.menu_0); menu0Img.setImageDrawable(getResources().getDrawable(R.drawable.menu0_focus)); } else if (menuIndex == 1) { topMenuText.setText(R.string.menu_1); menu1Img.setImageDrawable(getResources().getDrawable(R.drawable.menu1_focus)); } else if (menuIndex == 2) { topMenuText.setText(R.string.menu_2); menu2Img.setImageDrawable(getResources().getDrawable(R.drawable.menu2_focus)); } else if (menuIndex == 3) { topMenuText.setText(R.string.menu_3); menu3Img.setImageDrawable(getResources().getDrawable(R.drawable.menu3_focus)); } } public class MenuListSelectListener implements ListView.OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedPosition = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } } public class MenuImgClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.menu0_image: setFocusImgAndText(0); switchMenu(0); // 保存本次菜单Index getSharedPreferences("id_prefer", 0).edit().putInt("menuIn", 0).commit(); break; case R.id.menu1_image: setFocusImgAndText(1); switchMenu(1); // 保存本次菜单Index getSharedPreferences("id_prefer", 0).edit().putInt("menuIn", 1).commit(); break; case R.id.menu2_image: setFocusImgAndText(2); switchMenu(2); // 保存本次菜单Index getSharedPreferences("id_prefer", 0).edit().putInt("menuIn", 2).commit(); break; case R.id.menu3_image: setFocusImgAndText(3); switchMenu(3); // 保存本次菜单Index getSharedPreferences("id_prefer", 0).edit().putInt("menuIn", 3).commit(); break; default: break; } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (menuListView.getAdapter().equals(timeListAdapter)) { switchMenu(0); menuListView.setSelection(4); break; } if (menuListView.getAdapter().equals(adListAdapter)) { switchMenu(2); menuListView.setSelection(2); break; } finish(); break; case KeyEvent.KEYCODE_MENU: // 获取至上次菜单Index menuIndex = getSharedPreferences("id_prefer", 0).getInt("menuIn", 0); menuIndex++; if (menuIndex >= 4) { menuIndex = 0; } // 保存本次菜单Index getSharedPreferences("id_prefer", 0).edit().putInt("menuIn", menuIndex).commit(); switchMenu(menuIndex); setFocusImgAndText(menuIndex); break; case 21: // 左 handleLeftRightKey(menuIndex, false); break; case 22: // 右 handleLeftRightKey(menuIndex, true); break; default: break; } return false; } // 切换相应的菜单。 private void switchMenu(int menuIndex) { switch (menuIndex) { case 0: menuListView.setAdapter(basicListAdapter); break; case 1: menuListView.setAdapter(captionListAdapter); break; case 2: menuListView.setAdapter(functionListAdapter); break; case 3: menuListView.setAdapter(otherListAdapter); break; case 4: menuListView.setAdapter(timeListAdapter); break; case 5: menuListView.setAdapter(adListAdapter); break; default: menuListView.setAdapter(basicListAdapter); break; } } private void handleLeftRightKey(int menuIndex, boolean isRightKey) { switch (menuIndex) { case 0: if (menuListView.getAdapter().equals(timeListAdapter)) { setTimeAndAd(4, isRightKey); setFocusImgAndText(0); menuListView.setSelection(selectedPosition); return; } else { if (selectedPosition == 0) { basicListAdapter.handleKeyEvent(selectedPosition, isRightKey); refreshList(); //this.finish(); this.recreate(); return; } if (selectedPosition == 5) { // 定时开关机 // startActivity("com.adtv", "com.adtv.setting.PowerOnOffSettings"); startActivity("com.worldchip.advertisingclient", "com.worldchip.advertising.client.activity.PowerOnOffActivity"); return; } if (selectedPosition == 4) { // 时间设置 switchMenu(4); return; } if (selectedPosition == 10) { // 重置菜单 showResetMenuDialog(); return; } basicListAdapter.handleKeyEvent(selectedPosition, isRightKey); // 重新来加载一遍,让焦点回到上次的位置。不然的话显示会错乱的。 refreshList(); } break; case 1: captionListAdapter.handleKeyEvent(selectedPosition, isRightKey); // 重新来加载一遍,让焦点回到上次的位置。不然的话显示会错乱的。 refreshList(); break; case 2: if (menuListView.getAdapter().equals(adListAdapter)) { setTimeAndAd(5, isRightKey); // switchMenu(5); setFocusImgAndText(2); menuListView.setSelection(selectedPosition); return; } else { if (selectedPosition == 2) { setTimeAndAd(5, isRightKey); return; } if (selectedPosition == 5) { // 遥控加密。 //com.worldchip.advertisingclient //RemoteControlMainActivity.class startActivity("com.worldchip.advertisingclient", "com.worldchip.advertising.client.activity.RemoteControlMainActivity"); return; } functionListAdapter.handleKeyEvent(this, selectedPosition, isRightKey); // 重新来加载一遍,让焦点回到上次的位置。不然的话显示会错乱的。 refreshList(); } break; case 3: if (selectedPosition == 1) { // 打开文件管理 startActivity("com.softwinner.TvdFileManager", "com.softwinner.TvdFileManager.MainUI"); return; } otherListAdapter.handleKeyEvent(selectedPosition, isRightKey); // 重新来加载一遍,让焦点回到上次的位置。不然的话显示会错乱的。 refreshList(); break; default: break; } } private void setTimeAndAd(int index, boolean isRightKey) { switch (index) { case 4: switchMenu(4); timeListAdapter.handleKeyEvent(selectedPosition, isRightKey); break; case 5: switchMenu(5); adListAdapter.handleKeyEvent(selectedPosition, isRightKey); break; default: break; } } private void refreshList() { switchMenu(menuIndex); setFocusImgAndText(menuIndex); menuListView.setSelection(selectedPosition); } // 通过包名和类名来开启活动。 private void startActivity(String packageName, String className) { try { Intent intent = new Intent(); intent.setComponent(new ComponentName(packageName, className)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } catch (Exception err) { Toast.makeText(getApplicationContext(), "The App not found!", Toast.LENGTH_LONG).show(); err.printStackTrace(); } } // 显示重置菜单对话框 protected void showResetMenuDialog() { AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); builder.setMessage(R.string.confirm_reset_menu); builder.setPositiveButton(this.getResources().getString(R.string.confirm_reset_menu_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); clearSharePre(); // mHandler.sendEmptyMessage(REFRESH_AFTER_RESET_MENU); try { writeFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } refreshList(); } }); builder.setNegativeButton(this.getResources().getString(R.string.confirm_reset_menu_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.dismiss(); } }); builder.create().show(); } // 写入0 public void writeFile() throws IOException { String write_str = "0"; File file = new File(POWER_DELAY_TIME); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = write_str.getBytes(); fos.write(bytes); fos.close(); } // 清除菜单数据。 private void clearSharePre() { getSharedPreferences("basic_menu", 0).edit().clear().commit(); getSharedPreferences("caption_menu", 0).edit().clear().commit(); getSharedPreferences("function_menu", 0).edit().clear().commit(); getSharedPreferences("other_menu", 0).edit().clear().commit(); getSharedPreferences("time_set", 0).edit().clear().commit(); getSharedPreferences("ad_set", 0).edit().clear().commit(); getSharedPreferences("id_prefer", 0).edit().clear().commit(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); mHandler.removeMessages(FunctionListAdapter.AUTO_HIDE_POP); } }
package eu.rethink.globalregistry.Controller; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; import io.jsonwebtoken.impl.Base64UrlCodec; import net.tomp2p.peers.PeerAddress; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import eu.rethink.globalregistry.configuration.Config; import eu.rethink.globalregistry.dht.DHTManager; import eu.rethink.globalregistry.dht.GUIDNotFoundException; import eu.rethink.globalregistry.model.Dataset; import eu.rethink.globalregistry.model.DatasetIntegrityException; import eu.rethink.globalregistry.util.ECDSAKeyPairManager; import eu.rethink.globalregistry.util.IntegrityException; import java.io.IOException; import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.List; /** * Main class for GlobalRegistry daemon * * @date 03.02.2017 * @version 2 * @author Sebastian Göndör, Parth Singh */ @RestController @RequestMapping("/") public class RestService { private static final Logger LOGGER = LoggerFactory.getLogger(RestService.class); @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> index() throws URISyntaxException { LOGGER.info("Incoming request: GET /"); List<PeerAddress> AllNeighbors = DHTManager.getInstance().getAllNeighbors(); JSONArray connectedNodes = new JSONArray(); for (PeerAddress neighbor : AllNeighbors) { connectedNodes.put(neighbor.inetAddress().getHostAddress()); } JSONObject version = new JSONObject(); version.put("date", Config.getInstance().getVersionDate()); version.put("version", Config.getInstance().getVersionName()); version.put("build", Config.getInstance().getVersionNumber()); JSONObject response = new JSONObject(); response.put("Code", 200); response.put("Description", "OK"); response.put("Value", ""); response.put("version", version); response.put("connectedNodes", connectedNodes); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } //STATUS: Index Function is working absolutely fine. @RequestMapping(value = "guid/{GUID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<String> getEntitybyGUID(@PathVariable("GUID") String GUID) { LOGGER.info("Incoming request: GET /guid/" + GUID); if(GUID == null) { // received get request for path /guid/, but no guid. JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "GUID not specified in request URL"); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } else //if(GUID != null) { String jwt = null; try { // get JWT from DHT try { jwt = DHTManager.getInstance().get(GUID); } catch (GUIDNotFoundException e) { // tried to get dataset from dht, caught an exception JSONObject response = new JSONObject(); response.put("Code", 404); response.put("Description", "Not found"); response.put("Explanation", "GUID not found"); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.NOT_FOUND); } if(jwt == null) { // tried to get dataset from dht, found null. this should NEVER happen! JSONObject response = new JSONObject(); response.put("Code", 404); response.put("Description", "Not found"); response.put("Explanation", "GUID not found. DHT returned NULL."); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.NOT_FOUND); } else //if(jwt != null) { // decode JWT JSONObject jwtPayload = new JSONObject(new String(Base64UrlCodec.BASE64URL.decodeToString(jwt.split("\\.")[1]))); JSONObject data = new JSONObject(Base64UrlCodec.BASE64URL.decodeToString(jwtPayload.get("data").toString())); LOGGER.info("decoded JWT payload: " + data.toString()); // verify dataset integrity try { Dataset.checkDatasetValidity(data); } catch (DatasetIntegrityException e) { // read jwt from dht, integrity check for the enclosed json failed LOGGER.error("Integrity Exception found for JWT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } // decode key PublicKey publicKey; try { publicKey = ECDSAKeyPairManager.decodePublicKey(data.getString("publicKey")); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // got jwt from dht, tried to extract public key, failed while doing so LOGGER.error("Malformed public key found in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed public key found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } // verify jwt try { Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jwt); } catch (MalformedJwtException | UnsupportedJwtException e) { // got jwt from dht, jwt seems to be malformed LOGGER.error("Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (SignatureException e) { // got jwt from dht, jwt signature check failed LOGGER.error("Malformed JWT found in DHT: " + jwt + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed signature for JWT found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } LOGGER.info("JWT for GUID " + GUID + " verified"); JSONObject response = new JSONObject(); response.put("Code", 200); response.put("Description", "OK"); response.put("Value", jwt); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } catch(JSONException e) { // somewhere, a json exception was thrown LOGGER.error("Faulty JSON data in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Faulty JSON data in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } /*catch (IOException | ClassNotFoundException e) { // somewhere, a more severe exception was thrown LOGGER.error("Internal Server Error: " + jwt + " e: "+ e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal server error"); response.put("Explanation", "Internal Server Error: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); }*/ } } @RequestMapping(value = "guid/{GUID}", method = RequestMethod.PUT) public ResponseEntity<String> putdata(@RequestBody String jwt, @PathVariable("GUID") String GUID) { LOGGER.info("Incoming request: PUT /guid/" + GUID + " - JWT: " + jwt); JSONObject newData; // the new version of the jwt JSONObject existingData; // the already existing version (if there is any) PublicKey newDatasetPublicKey; // the public key of the NEW version try { // decode JWT JSONObject jwtPayload = new JSONObject(new String(Base64UrlCodec.BASE64URL.decodeToString(jwt.split("\\.")[1]))); newData = new JSONObject(Base64UrlCodec.BASE64URL.decodeToString(jwtPayload.get("data").toString())); //LOGGER.info("decoded JWT payload: " + newData.toString()); // verify dataset integrity try { Dataset.checkDatasetValidity(newData); } catch (DatasetIntegrityException e) { LOGGER.error("Integrity Exception found for received JWT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "JWT is malformed: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } // decode key try { newDatasetPublicKey = ECDSAKeyPairManager.decodePublicKey(newData.getString("publicKey")); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { LOGGER.error("Malformed public key found in JWT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "Malformed public key found in JWT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } // verify jwt try { Jwts.parser().setSigningKey(newDatasetPublicKey).parseClaimsJws(jwt); } catch (MalformedJwtException | UnsupportedJwtException e) { LOGGER.error("Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "Malformed JWT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } catch (SignatureException e) { LOGGER.error("Malformed JWT found in DHT: " + jwt + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "Malformed signature for JWT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } LOGGER.info("JWT for GUID " + GUID + " verified"); // match new JWT to existing JWT String existingJWT = null; try { existingJWT = DHTManager.getInstance().get(GUID); // GUID found. Ergo, we are updating an existing dataset JSONObject jwtPayloadFromDHT = new JSONObject(new String(Base64UrlCodec.BASE64URL.decodeToString(existingJWT.split("\\.")[1]))); existingData = new JSONObject(Base64UrlCodec.BASE64URL.decodeToString(jwtPayloadFromDHT.get("data").toString())); //--- // verify the existing dataset's integrity try { Dataset.checkDatasetValidity(existingData); } catch (DatasetIntegrityException e) { // tried to write dataset. found an existing one. the existing one failed the integrity test LOGGER.error("Integrity exception found for existing dataset: " + existingJWT + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed JWT found in DHT: " + existingJWT + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } // decode key PublicKey existingDatasetPublicKey; try { existingDatasetPublicKey = ECDSAKeyPairManager.decodePublicKey(existingData.getString("publicKey")); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // tried to write dataset. found an existing one. the public key of the existing one couldnt be extracted LOGGER.error("Malformed public key found in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed public key found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } // verify jwt try { Jwts.parser().setSigningKey(existingDatasetPublicKey).parseClaimsJws(jwt); } catch (MalformedJwtException | UnsupportedJwtException e) { // tried to write dataset. found an existing one. the existing one seems to be malformed jwt LOGGER.error("Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed JWT found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (SignatureException e) { // tried to write dataset. found an existing one. the signature check of the existing one failed LOGGER.error("Malformed JWT found in DHT: " + jwt + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Malformed signature for JWT found in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } try { // verify that GUIDs are matching if(!newData.getString("guid").equals(existingData.getString("guid"))) throw new IntegrityException("GUIDs are not matching!"); } catch (IntegrityException e) { // tried to write dataset, found an existing one. GUIDs do not match. Should NEVER happen! JSONObject response = new JSONObject(); response.put("Code", 400); response.put("Description", "Bad Request"); response.put("Explanation", "GUIDs do not match: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST); } // everything is fine. overwrite existing dataset with new one LOGGER.info("Dataset for GUID " + GUID + " updated: \n" + jwt); try { DHTManager.getInstance().put(GUID, jwt); } catch (IOException e) { // tried to write dataset, found an existing one. Encountered an IO error while overwriting the existing one JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Error while writing to DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } LOGGER.info("Dataset for [" + GUID + "] written to DHT: \n" + jwt); JSONObject response = new JSONObject(); response.put("Code", 200); response.put("Description", "OK"); response.put("Explanation", "Dataset for GUID " + GUID + " updated: " + jwt); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } catch (GUIDNotFoundException e) { // GUID not found. Ergo, we are writing a new dataset to the DHT // TODO try/catch with error handling here! try { DHTManager.getInstance().put(GUID, jwt); } catch (IOException e1) { // tried to write dataset, found an existing one. Encountered an IO error while overwriting the existing one JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Error while writing to DHT: " + jwt + " e: " + e1.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } LOGGER.info("Dataset for [" + GUID + "] written to DHT: \n" + jwt); JSONObject response = new JSONObject(); response.put("Code", 200); response.put("Description", "OK"); response.put("Explanation", "Dataset for GUID " + GUID + " written to DHT: \n" + jwt); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } catch(JSONException e) { // somewhere, a json exception was thrown LOGGER.error("Faulty JSON data in DHT: " + jwt + " e: " + e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal Server Error"); response.put("Explanation", "Faulty JSON data in DHT: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } /*catch (IOException | ClassNotFoundException e) { // somewhere, a more severe exception was thrown LOGGER.error("Internal Server Error: " + jwt + " e: "+ e.getMessage()); JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal server error"); response.put("Explanation", "Internal Server Error: " + jwt + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); }*/ } /** * DELETE * @throws JSONException * */ @RequestMapping(value = "guid/{GUID}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> deleteData(@PathVariable("GUID") String GUID) throws URISyntaxException { LOGGER.info("Incoming request: DELETE /guid/" + GUID); try { DHTManager.getInstance().delete(GUID); } catch(IOException e) { JSONObject response = new JSONObject(); response.put("Code", 500); response.put("Description", "Internal server error"); response.put("Explanation", "Internal Server Error: " + GUID + " e: " + e.getMessage()); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } JSONObject response = new JSONObject(); response.put("Code", 200); response.put("Description", "OK"); response.put("Explanation", "deleted GUID " + GUID); response.put("Value", ""); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } /** * Easteregg. Just returning "I'm a teapot" as of RFC #2324 * @throws JSONException * */ @RequestMapping(value = "teapot", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> teapot() throws URISyntaxException { LOGGER.info("Incoming request: GET /teapot"); JSONObject response = new JSONObject(); response.put("Code", 418); response.put("Description", "I'm a teapot"); response.put("Value", "See RFC #2324"); return new ResponseEntity<String>(response.toString(), HttpStatus.I_AM_A_TEAPOT); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rest; import com.google.gson.Gson; import com.google.gson.JsonObject; import java.util.Random; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * REST Web Service * * @author perlt */ @Path("joke") public class JokeResource { private final String[] jokes = {"Haha", "Funnny", "Insert joke"}; @Context private UriInfo context; @GET @Produces(MediaType.APPLICATION_JSON) public Response getJoke() { String joke = jokes[new Random().nextInt(jokes.length)]; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("joke", joke); Gson gson = new Gson(); String json = gson.toJson(jsonObject); System.out.println(json); return Response.ok().entity(json) .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD") .header("Access-Control-Allow-Credentials", "true") .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization") .type(MediaType.APPLICATION_JSON) .build(); } }
package com.trust.demo.code.bluetooth; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.trust.demo.R; import com.trust.demo.tool.bean.BlueDeviceBean; import com.trust.demo.code.perssion.PermissionUtils; import com.trust.demo.ui.cardrotation.tool.swipebacklayout.app.SwipeBackActivity; import com.trust.demo.tool.Config; import com.trust.demo.tool.L; import com.trust.demo.tool.T; import java.util.ArrayList; import java.util.List; public class BlueToothActivity extends SwipeBackActivity implements View.OnClickListener{ private RecyclerView recyclerView; private BlueToothadapter blueToothadapter; private List<BlueDeviceBean> ml = new ArrayList<>(); private Button startFound,closeFound; private BluetoothManager bluetoothManager; private BluetoothAdapter bluetoothAdapter; private final int BLEUETOOTH_REQUEST = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blue_tooth); init(); } private void init() { initView(); // initDate(); initBlueTooth(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private void initBlueTooth() { PermissionUtils.requestPermission(this,PermissionUtils.CODE_ACCESS_COARSE_LOCATION, mPermissionGrant); bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); if(bluetoothAdapter == null){ T.showToast(this,"yours phone is no BlueTooth!"); return; } if(!bluetoothAdapter.isEnabled()){ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent,BLEUETOOTH_REQUEST); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Config.BlueClose){ L.d("blue close "); return; } } private void initView() { recyclerView = (RecyclerView) findViewById(R.id.activity_blue_tooth_recycler); blueToothadapter = new BlueToothadapter(); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(blueToothadapter); // recyclerView.addItemDecoration(new RecyclerViewDivider(this, // LinearLayoutManager.HORIZONTAL)); blueToothadapter.blueRecyclerOnclik = new BlueToothadapter.BlueRecyclerOnclik(){ @Override public void callBack(View v, BlueDeviceBean blueDeviceBean) { L.d("you click"); bluetoothAdapter.cancelDiscovery(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(blueDeviceBean. getAddress()); Intent intent = new Intent(); intent.putExtra(Config.BlueeDeviceName,blueDeviceBean.getName()); intent.putExtra(Config.BlueeDeviceAddress,blueDeviceBean.getAddress()); intent.setClass(BlueToothActivity.this,BlueDeviceActivity.class); startActivity(intent); } }; startFound = (Button) findViewById(R.id.activity_blue_tooth_found_blue); closeFound = (Button) findViewById(R.id.activity_blue_tooth_close_blue); startFound.setOnClickListener(this); closeFound.setOnClickListener(this); } public void ext(View v){ finish(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.activity_blue_tooth_found_blue: startFound.setVisibility(View.GONE); closeFound.setVisibility(View.VISIBLE); startFoundBlue(); break; case R.id.activity_blue_tooth_close_blue: startFound.setVisibility(View.VISIBLE); closeFound.setVisibility(View.GONE); bluetoothAdapter.cancelDiscovery(); break; } } public void startFoundBlue(){ IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(blueToothBrocastReceiver,filter); bluetoothAdapter.startDiscovery(); } public BroadcastReceiver blueToothBrocastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(BluetoothDevice.ACTION_FOUND)){ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); ml.add(new BlueDeviceBean(deviceName,device.getAddress())); blueToothadapter.setMl(ml); blueToothadapter.notifyDataSetChanged(); } } }; public PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() { @Override public void onPermissionGranted(int requestCode) { switch (requestCode) { case PermissionUtils.CODE_RECORD_AUDIO: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_RECORD_AUDIO", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_GET_ACCOUNTS: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_GET_ACCOUNTS", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_READ_PHONE_STATE: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_READ_PHONE_STATE", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_CALL_PHONE: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_CALL_PHONE", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_CAMERA: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_CAMERA", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_ACCESS_FINE_LOCATION: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_ACCESS_FINE_LOCATION", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_ACCESS_COARSE_LOCATION: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_ACCESS_COARSE_LOCATION", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_READ_EXTERNAL_STORAGE: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_READ_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show(); break; case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE: Toast.makeText(BlueToothActivity.this, "Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show(); break; default: L.d("sucess"); break; } } }; }
package com.qa.def; public class Mechanic { // Instantiated the method Car c = new Car(); //Can now directly access c.exhausts from the other class public int readExhausts() { return c.exhausts; } }
package dir.gestionarcredenciales.forms; import java.util.List; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import dir.gestioncredenciales.modelo.Rol; import dir.gestioncredenciales.modelo.Usuario; import dir.gestioncredenciales.servicios.ServiciosLocator; public class UsuariosTableModel implements TableModel { private List<Usuario> usuarios; private TableModelListener listener; public UsuariosTableModel(){ this.usuarios = ServiciosLocator.getGestionarUsuarios().obtenerUsuarios(); } @Override public void addTableModelListener(TableModelListener l) { listener = l; } public List<Usuario> getUsuarios() { return usuarios; } public void setUsuarios(List<Usuario> usuarios) { this.usuarios = usuarios; } public void actualizarModelo(){ this.usuarios = ServiciosLocator.getGestionarUsuarios().obtenerUsuarios(); listener.tableChanged(new TableModelEvent(this)); } //Retorna la Clase a la que pertenece el tipo de dato que almacena cada columna. @Override public Class<?> getColumnClass(int columIndex) { switch (columIndex){ case 0: return Integer.class; case 3: return Boolean.class; case 4: return Rol.class; default : return String.class; } } //Numero de columnas del JTable @Override public int getColumnCount() { return 5; } //Devuelve el nombre de las columnas seg�n columIndex. @Override public String getColumnName(int columIndex) { switch (columIndex){ case 0: return "Id"; case 1: return "Nombre"; case 2: return "Password"; case 3: return "Bloqueado"; default: return "Rol"; } } @Override public int getRowCount() { return usuarios.size(); } @Override public Object getValueAt(int rowIndex, int columIndex) { Object tmp = null; if (usuarios.isEmpty()){ tmp = this.getUserByColumn(rowIndex,columIndex); } return tmp; } private Object getUserByColumn(int rowIndex,int columIndex){ Usuario user = usuarios.get(rowIndex); switch (columIndex){ case 0: return user.getId(); case 1: return user.getNombre(); case 2: return user.getPassword(); case 3: return user.getBloqueado(); default: return user.getRol().getNombre(); } } @Override public boolean isCellEditable(int rowIndex, int columIndex) { if(columIndex == 0){ return false; } return true; } @Override public void removeTableModelListener(TableModelListener arg0) { //TODO remoe table model listener } @Override public void setValueAt(Object value, int rowIndex, int columnIndex) { Usuario user = usuarios.get(rowIndex); switch (columnIndex){ case 1: user.setNombre(value.toString()); break; case 2: user.setPassword((String)value); break; case 3: user.setBloqueado((Boolean)value); break; default: user.setRol((Rol)value); break; } } }
package littleservantmod.client.gui.sidetab; import littleservantmod.client.gui.inventory.GuiSideTabContainer; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.item.ItemStack; /** * 現在の職業を表示する * @author shift02 */ public class SideTabProfession extends SideTabBase { GuiSideTabContainer guiSideTabContainer; public SideTabProfession(GuiSideTabContainer guiSideTabContainer) { super(guiSideTabContainer); this.guiSideTabContainer = guiSideTabContainer; this.name = "sidetab.profession_info.name"; this.backgroundColor = 0x088A08; } @Override public ItemStack getTabIconFromItem() { return null; } @Override public TextureAtlasSprite getTabIcon() { return guiSideTabContainer.servant.getProfession().getIcon(guiSideTabContainer.servant); } @Override public void draw() { if (this.open) { int i = 1; this.elementFontRenderer.drawString(this.guiSideTabContainer.localize(getName()), posX + 24, posY + 8 + i, 0xFFD700, true); this.elementFontRenderer.drawString(this.guiSideTabContainer.localize("sidetab.profession_name.name"), posX + 24, posY + 21 + i, 0xFFFFFF, true); String professionName = guiSideTabContainer.servant.getProfession().getProfessionDisplayName(guiSideTabContainer.servant); this.elementFontRenderer.drawString(professionName, posX + 30, posY + 33 + i, 0x000000); } } }
package app.integro.sjbhs.fragments; import android.graphics.Bitmap; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import app.integro.sjbhs.R; public class WebSiteFragment extends Fragment { String url = "https://sjbhs.edu.in/"; WebView webView; ProgressBar progressBar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_web_site, container, false); webView=(WebView)view.findViewById(R.id.webFragment); progressBar = (ProgressBar) view.findViewById(R.id.progressBar1); webView.loadUrl(url); openWebView(); webView.canGoBack(); webView.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP && webView.canGoBack()) { webView.goBack(); return true; } return false; } }); return view; } public void openWebView() { webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(false); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setDisplayZoomControls(false); webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); progressBar.setVisibility(View.VISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); } }); } }
package pl.whirly.recruitment.businesscontext.repository; import org.springframework.stereotype.Service; import pl.whirly.recruitment.businesscontext.model.User; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; @Service public class UserRepository { private List<User> users = new LinkedList<>(); public UserRepository() { this.users.add(new User("adult", Instant.now().minus(19 * 31556952, ChronoUnit.SECONDS), "PL")); this.users.add(new User("kid", Instant.now().minus(4 * 31556952, ChronoUnit.SECONDS), "DE")); } public User getUserById(String id) { return this.users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null); } public List<User> getAllUsers() { return this.users; } public boolean addUser(User user) { return users.add(user); } public boolean updateUser(String id, User user) { User updatedUser = getUserById(id); if (updatedUser == null) { throw new NoSuchElementException(); } users.remove(updatedUser); return users.add(user); } public boolean delete(String id) { return this.users.removeIf(element -> element.getId().equals(id)); } }
package it.polimi.ingsw.GC_21.CLIENT; import java.util.Scanner; import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevCardType; import it.polimi.ingsw.GC_21.GAMECOMPONENTS.Possession; import it.polimi.ingsw.GC_21.VIEW.InputForm; import it.polimi.ingsw.GC_21.VIEW.TakeCardInput; import it.polimi.ingsw.GC_21.fx.FXMLGameController; public class TakeCardMessage extends MessageToClient{ private DevCardType devCardType; private int actionValueInfluencer; private Possession discount; private int selectedFloor; public TakeCardMessage(DevCardType devCardType, int actionValueInfluencer, Possession discount) { super(true, true, "Hey sgangherato, you can take another Card!\nYour new action value is " + actionValueInfluencer); this.devCardType = devCardType; this.actionValueInfluencer = actionValueInfluencer; this.discount = discount; } @Override public InputForm executeCLI(Object lOCK) throws InterruptedException { inputForm = new TakeCardInput(devCardType, actionValueInfluencer, discount); return super.executeCLI(lOCK); } @Override public void executeGUI(FXMLGameController gameController) { gameController.takeNewCard(devCardType, actionValueInfluencer, discount); } }
package testFunction; public class TestVarargs1 { static void vaTest(int ... no) { System.out.println("vaTest(int ...): 参数个数:" + no.length + "内容:"); for(int n : no) System.out.print(n + " "); System.out.println(); } static void vaTest(boolean ... bl) { System.out.print("vaTest(boolean ...)参数个数: " + bl.length + " 内容:"); for(boolean b : bl) System.out.print(b + " "); System.out.println(); } static void vaTest(String msg,int ... no) { System.out.print("vaTest(String,int ...): 参数个数: " + no.length + "内容:"); for(int n : no) System.out.print(n + " "); System.out.println(); } public static void main(String args[]) { vaTest(1,2,3); vaTest("测试:",10,20); vaTest(true,false,false); } }
package org.arthur.review.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.arthur.review.service.AdminRankingService; /** * Servlet implementation class CompareSolutions */ @WebServlet("/CompareSolutions") public class CompareSolutions extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CompareSolutions() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String lhsSampleKey = request.getParameter("leftProblemSolutionPair"); String rhsSampleKey = request.getParameter("rightProblemSolutionPair"); String pairSampleKey = lhsSampleKey + "-" + rhsSampleKey; String lhsSolutionGoodAspects = request.getParameter("leftGoodAspects"); String rhsSolutionGoodAspects = request.getParameter("rightGoodAspects"); String lhsSolutionBadAspects = request.getParameter("leftBadAspects"); String rhsSolutionBadAspects = request.getParameter("rightBadAspects"); String leftSolutionUploadPath = request.getParameter("leftUploadLocation"); String rightSolutionUploadPath = request.getParameter("rightUploadLocation"); String rankingJudgement = request.getParameter("betterSolution"); String rankingJustification = request.getParameter("justifyBetterSolution"); AdminRankingService adminRanker = new AdminRankingService(); //run first query to add review/ranking record to AdminReviewTable adminRanker.addAdminReviewRecord(lhsSampleKey, rhsSampleKey, pairSampleKey, leftSolutionUploadPath, rightSolutionUploadPath, rankingJudgement, rankingJustification, lhsSolutionGoodAspects, rhsSolutionGoodAspects, lhsSolutionBadAspects, rhsSolutionBadAspects); //run second query to update good and bad aspects of required samplesolutions //in adminTable adminRanker.updateAspects(lhsSampleKey, lhsSolutionGoodAspects, lhsSolutionBadAspects); adminRanker.updateAspects(rhsSampleKey, rhsSolutionGoodAspects, rhsSolutionBadAspects); //redirect page to admin ranks already done which is a tabular view response.sendRedirect("viewAdminRankingList.jsp"); } }
package test.nz.org.take.compiler.scenario8.generated; /** * Class generated by the take compiler. * This class represents the predicate is_father_of * @version Fri Feb 01 11:32:07 NZDT 2008 */ public class IsFatherOf { public test.nz.org.take.compiler.scenario8.Person son; public test.nz.org.take.compiler.scenario8.Person father; public IsFatherOf(test.nz.org.take.compiler.scenario8.Person son, test.nz.org.take.compiler.scenario8.Person father) { super(); this.son = son; this.father = father; } public IsFatherOf() { super(); } }
package com.action; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.struts2.ServletActionContext; import com.core.common.PageInfo; import com.core.common.Params; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport { //分页 public PageInfo page = new PageInfo(); //参数 public Params params = new Params(); /** * 获取客户端IP地址 * @param request * @return */ public String getIpAddr(HttpServletRequest request){ String ipAddress = request.getHeader("x-forwarded-for"); if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){ //根据网卡取本机配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress= inet.getHostAddress(); } } //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15 if(ipAddress.indexOf(",")>0){ ipAddress = ipAddress.substring(0,ipAddress.indexOf(",")); } } return ipAddress; } public Map getRequest() { return (Map)ActionContext.getContext().get("request"); } public Map getSession() { return (Map)ActionContext.getContext().getSession(); } /** * 发送短信 * @param randCheckCode 验证码 * @param mobile 手机号 * @return */ public String out(String randCheckCode,String mobile){ try { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://sh.ipyy.com:8888/smsGBK.aspx"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk"); NameValuePair[] data = { new NameValuePair("userid","3531"), new NameValuePair("account", "sh100846"), new NameValuePair("password", "tklh362014"), new NameValuePair("mobile", mobile), new NameValuePair("action", "send"), new NameValuePair("content", "【天矿联合】尊敬的客户。您好,您在天矿联合信息平台注册的手机验证码是:"+ randCheckCode+"感谢您对我们工作的配合。") }; post.setRequestBody(data); client.executeMethod(post); Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); post.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } return randCheckCode; } /** * URL编码转成汉子 * @param s 编码 * @return */ public static String unescape(String s) { StringBuffer sbuf = new StringBuffer(); int l = s.length(); int ch = -1; int b, sumb = 0; for (int i = 0, more = -1; i < l; i++) { /* Get next byte b from URL segment s */ switch (ch = s.charAt(i)) { case '%': ch = s.charAt(++i); int hb = (Character.isDigit((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF; ch = s.charAt(++i); int lb = (Character.isDigit((char) ch) ? ch - '0' : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF; b = (hb << 4) | lb; break; case '+': b = ' '; break; default: b = ch; } /* Decode byte b as UTF-8, sumb collects incomplete chars */ if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte) sumb = (sumb << 6) | (b & 0x3f); // Add 6 bits to sumb if (--more == 0) sbuf.append((char) sumb); // Add char to sbuf } else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits) sbuf.append((char) b); // Store in sbuf } else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits) sumb = b & 0x1f; more = 1; // Expect 1 more byte } else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits) sumb = b & 0x0f; more = 2; // Expect 2 more bytes } else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits) sumb = b & 0x07; more = 3; // Expect 3 more bytes } else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits) sumb = b & 0x03; more = 4; // Expect 4 more bytes } else /*if ((b & 0xfe) == 0xfc)*/{ // 1111110x (yields 1 bit) sumb = b & 0x01; more = 5; // Expect 5 more bytes } /* We don't test if the UTF-8 encoding is well-formed */ } return sbuf.toString(); } /** * Excel导出 * @param title * @param headers * @param content * @param out * @throws Exception */ public static void exportExcel(String title, String[] headers,List<Object[]> content, OutputStream out) throws Exception{ //声明一个工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); //生成一个表格 HSSFSheet sheet = workbook.createSheet(title); //设置表格默认列宽度为20个字节 sheet.setDefaultColumnWidth((short) 20); //生成一个字体 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 生成一个样式 HSSFCellStyle style = workbook.createCellStyle(); // 设置这些样式 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //产生表格标题行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell((short) i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } //遍历集合数据,产生数据行 int index=1; for (int i = 0;i < content.size(); i++) { //创建一行 row = sheet.createRow(index); Object[] o=content.get(i); System.out.println(content.get(i)); for (int j = 0; j < o.length; j++) { HSSFCell cell = row.createCell((short)j);//得到要插入的每一条记录 HSSFRichTextString text =null; if(o[j]!=null&&!o[j].toString().equals("")){ text=new HSSFRichTextString(o[j].toString()); } cell.setCellValue(text); } index++; } try{ workbook.write(out); }catch(IOException e){ e.printStackTrace(); } } //根据ID获得所在地 public String getAddresses(String content, String encodingString) throws UnsupportedEncodingException { // 这里调用pconline的接口 String urlStr = "http://ip.taobao.com/service/getIpInfo.php"; // 从http://whois.pconline.com.cn取得IP所在的省市区信息 String returnStr = this.getResult(urlStr, content, encodingString); if (returnStr != null) { // 处理返回的省市区信息 System.out.println(returnStr); String[] temp = returnStr.split(","); if(temp.length<3){ return "0";//无效IP,局域网测试 } String region = (temp[5].split(":"))[1].replaceAll("\"", ""); region = decodeUnicode(region);// 省份 String country = ""; String area = ""; // String region = ""; String city = ""; String county = ""; String isp = ""; for (int i = 0; i < temp.length; i++) { switch (i) { case 1: country = (temp[i].split(":"))[2].replaceAll("\"", ""); country = decodeUnicode(country);// 国家 break; case 3: area = (temp[i].split(":"))[1].replaceAll("\"", ""); area = decodeUnicode(area);// 地区 break; case 5: region = (temp[i].split(":"))[1].replaceAll("\"", ""); region = decodeUnicode(region);// 省份 break; case 7: city = (temp[i].split(":"))[1].replaceAll("\"", ""); city = decodeUnicode(city);// 市区 break; case 9: county = (temp[i].split(":"))[1].replaceAll("\"", ""); county = decodeUnicode(county);// 地区 break; case 11: isp = (temp[i].split(":"))[1].replaceAll("\"", ""); isp = decodeUnicode(isp); // ISP公司 break; } } System.out.println(country+"="+area+"="+region+"="+city+"="+county+"="+isp); String r=area+"-"+region+"-"+city+"-"+county+"-"+isp; if(r.equals("----")){ return ""; }else { return r; } } return null; } /** * @param urlStr * 请求的地址 * @param content * 请求的参数 格式为:name=xxx&pwd=xxx * @param encoding * 服务器端请求编码。如GBK,UTF-8等 * @return */ private String getResult(String urlStr, String content, String encoding) { URL url = null; HttpURLConnection connection = null; try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection();// 新建连接实例 connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒 connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒 connection.setDoOutput(true);// 是否打开输出流 true|false connection.setDoInput(true);// 是否打开输入流true|false connection.setRequestMethod("POST");// 提交方法POST|GET connection.setUseCaches(false);// 是否缓存true|false connection.connect();// 打开连接端口 DataOutputStream out = new DataOutputStream(connection .getOutputStream());// 打开输出流往对端服务器写数据 out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx out.flush();// 刷新 out.close();// 关闭输出流 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 // ,以BufferedReader流来读取 StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect();// 关闭连接 } } return null; } /** * unicode 转换成 中文 * * @author fanhui 2007-3-15 * @param theString * @return */ public static String decodeUnicode(String theString) { char aChar; int len = theString.length(); StringBuffer outBuffer = new StringBuffer(len); for (int x = 0; x < len;) { aChar = theString.charAt(x++); if (aChar == '\\') { aChar = theString.charAt(x++); if (aChar == 'u') { int value = 0; for (int i = 0; i < 4; i++) { aChar = theString.charAt(x++); switch (aChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = (value << 4) + aChar - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': value = (value << 4) + 10 + aChar - 'a'; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': value = (value << 4) + 10 + aChar - 'A'; break; default: throw new IllegalArgumentException( "Malformed encoding."); } } outBuffer.append((char) value); } else { if (aChar == 't') { aChar = '\t'; } else if (aChar == 'r') { aChar = '\r'; } else if (aChar == 'n') { aChar = '\n'; } else if (aChar == 'f') { aChar = '\f'; } outBuffer.append(aChar); } } else { outBuffer.append(aChar); } } return outBuffer.toString(); } //获取参数名值 public String getParam(String name){ return ServletActionContext.getRequest().getParameter(name); } //response对象 public HttpServletResponse getResponse() { return ServletActionContext.getResponse(); } protected void outStringData(String result){ PrintWriter out = null; try { getResponse().setContentType("text/html; charset=utf-8"); getResponse().setHeader("Cache-Control", "no-cache"); out = getResponse().getWriter(); out.write(result); out.flush(); } catch (Exception e) { }finally{ if(out != null){ out.close(); } } } /*********************************华丽的分割线******************************/ public PageInfo getPage() { return page; } public void setPage(PageInfo page) { this.page = page; } public Params getParams() { return params; } public void setParams(Params params) { this.params = params; } }
import javax.websocket.server.ServerEndpoint; import javax.websocket.Session; import javax.websocket.OnOpen; import javax.websocket.OnMessage; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.CloseReason; import java.util.logging.Logger; import java.util.logging.Level; import java.util.*; import java.io.*; @ServerEndpoint("/chat") public class ChatServer { private static final Logger LOGGER = Logger.getLogger(ChatServer.class.getName()); private static Set<Session> existing_sessions = new HashSet<Session>(); @OnOpen public void onOpen(Session session) throws IOException { LOGGER.info(String.format("Establishing connection with SESSION ID: %s", session.getId())); existing_sessions.add(session); LOGGER.info(String.format("Connection ESTABLISHED. Session ID: %s", session.getId())); } @OnMessage public void onMessage(String message, Session session) throws IOException { for (Session peer : existing_sessions) { peer.getBasicRemote().sendText(message); } } @OnClose public void onClose(Session session) throws IOException { LOGGER.info(String.format("Connection with SESSION ID %s being CLOSED", session.getId())); existing_sessions.remove(session); LOGGER.info("Connection CLOSED"); } @OnError public void onError(Session session, Throwable throwable) { LOGGER.info(String.format("ERROR occured: %s", throwable)); try { LOGGER.info(String.format("CLOSING connection for SESSION ID %s.", session.getId())); session.close(new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, "Exception occurred: " + throwable.toString())); LOGGER.info("Connection CLOSED."); } catch (IOException ex) { LOGGER.info("FAILED. AN EXCEPTION HAS OCCURED: ", ex); } } }
package com.daveayan.fuzzyavenger.providers.akka; class Message_AL2_to_AL1 { public int sequenceNumber; public Object data; public Object newValue; public Message_AL2_to_AL1(int sequenceNumber, Object data, Object newValue) { this.sequenceNumber = sequenceNumber; this.data = data; this.newValue = newValue; } }
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data; /** * <p> * Contains constant definitions for the standard {@link Format} instances supported * by the library. {@link #AVRO} is the default format. * </p> * * @since 0.2.0 */ public class Formats { private Formats() { } /** * AVRO: the * <a href="http://avro.apache.org/docs/current/spec.html#Object+Container+Files">Avro * row-oriented format</a> */ public static final Format AVRO = new Format("avro"); /** * PARQUET: the <a href="http://parquet.io/">Parquet columnar format</a> */ public static final Format PARQUET = new Format("parquet"); /** * CSV: comma-separated values (read-only). * * @since 0.9.0 */ public static final Format CSV = new Format("csv"); /** * Return a {@link Format} for the format name specified. If {@code formatName} * is not a valid name, an IllegalArgumentException is thrown. Currently the * formats <q>avro</q>, <q>csv</q>, and <q>parquet</q> are supported. Format names are * case sensitive. * * @since 0.9.0 * @return an appropriate instance of Format * @throws IllegalArgumentException if {@code formatName} is not a valid format. */ public static Format fromString(String formatName) { if (formatName.equals("avro")) { return AVRO; } else if (formatName.equals("parquet")) { return PARQUET; } else if (formatName.equals("csv")) { return CSV; } else { throw new IllegalArgumentException("Unknown format type: " + formatName); } } }
package mechanics; import mechanics.simulation.Ground; import mechanics.simulation.Block; import mechanics.simulation.Vector; import mechanics.utilities.PositiveRealNumberFormat; import mechanics.utilities.RealNumberFormat; import java.awt.*; import java.awt.event.*; import java.io.*; import java.nio.charset.*; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import static mechanics.MechanicsSimulator.*; import static mechanics.Simulation.*; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; public class Controls extends JPanel implements ActionListener, ChangeListener { JButton load, save; String loadtext = rb.getString("load.text"), savetext = rb.getString("save.text"); JCheckBox dofriction; String dofrictiontext = rb.getString("friction.do.text"); JLabel staticfclabel; JFormattedTextField staticfc; String staticfctext = rb.getString("friction.staticc.text"); JLabel kineticfclabel; JFormattedTextField kineticfc; String kineticfctext = rb.getString("friction.kineticc.text"); JLabel restitutionclabel; JSlider restitutionc; String restitutionctext = rb.getString("restitution.c.text"); JCheckBox addgravity; String addgravitytext = rb.getString("addgravity.text"); JCheckBox gravitybounce; String gravitybouncetext = rb.getString("gravitybounce.text"); JButton pause; String pausetext = rb.getString("pause.text"); String play = rb.getString("pause.play"); JButton defaultspeed; String defaultspeedtext = rb.getString("defaultspeed.text"); JSlider sspeed; JLabel xyJL; String xyJLtext = rb.getString("xyJL.text"); JFormattedTextField xJTF, yJTF; JLabel whlabel; String whlabeltext = rb.getString("wh.text"); JFormattedTextField wJTF, hJTF; JLabel aJL; String aJLtext = rb.getString("aJL.text"); JFormattedTextField aJTF; JLabel athetaJL; String athetaJLtext = rb.getString("athetaJL.text"); JFormattedTextField athetaJTF; JLabel mJL; String mJLtext = rb.getString("mJL.text"); JFormattedTextField mJTF; JButton addBlock; String addBlocktext = rb.getString("addBlock.text"); //JToggleButton removeBlock; String removeBlockBlocktext = rb.getString("removeBlock.text"); //Click on Block to remove it JButton clear; String cleartext = rb.getString("clear.text"); JCheckBox showF; String showFtext = rb.getString("showF.text"); //Show Vector(simulation) JCheckBox RCl; String RCltext = rb.getString("RCl.text"); //Random Color line(Forces) JCheckBox shownF; String shownFtext = rb.getString("shownF.text"); //show net force JCheckBox showarrows; String showarrowstext = rb.getString("showarrows.text"); //Show arrows JCheckBox showparellelogram; String showparellelogramtext = rb.getString("showparellelogram.text"); //Show parellelogram JCheckBox showmass; String showmasstext = rb.getString("showmass.text"); //Show Block mass JCheckBox showlabels; String showlabelstext = rb.getString("showlabels.text"); //Show Block mass JCheckBox previewForce; String previewForcetext = rb.getString("show.Forcepreview"); /*JCheckBox shownumbers; String shownumberstext = rb.getString("shownumbers.text"); //Show Vector(simulation) in numbers //JLabel uptodigitsJL; String uptodigitsJLtext = rb.getString("uptodigits.text"); JSlider uptodigits; //Show Vector(simulation) in numbers up to specified digits int lastuptodigitsvalue = 16; */ JCheckBox a; String atext = rb.getString("a.text"); //allow acceleration JCheckBox drawa; String drawatext = rb.getString("drawa.text"); JCheckBox drawv; String drawvtext = rb.getString("v.draw.text"); JLabel onedgea; String onedgeatext = rb.getString("ahm.text"); JComboBox ahm; String[] ahmitems = { //Block acceleration handling mode items rb.getString("ahm.keep"), rb.getString("ahm.reverse"), rb.getString("ahm.reset") }; JLabel onedge; String onedgetext = rb.getString("ehm.text"); JComboBox edgehandlingmode; String[] ehmitems = { //edgehandlingmode items rb.getString("ehm.unlimited"), rb.getString("ehm.bounce")/*, rb.getString("ehm.wrap"),*/ }; JLabel onBlock; String onBlocktext = rb.getString("chm.text"); JComboBox collisionhandlingmode; String[] chmitems = { //collisionhandlingmode items rb.getString("chm.ignore"), rb.getString("chm.bounce") }; JTabbedPane concepts; JPanel fo; JPanel nefo; JPanel ac; JPanel gr; JLabel themel; String themelt = rb.getString("themes"); JComboBox themes; String[] themenames = { rb.getString("themes.default"), rb.getString("themes.dark"), rb.getString("themes.brighter") }; String[] themefilenames = { "default.json", "dark.json", "brighter.json" }; JLabel playforl; String playfort = rb.getString("playfor.t"); JFormattedTextField playfor; //Simulate for a specific amount of seconds (very useful!) JLabel moveforl; String movefort = rb.getString("moveuntil.t"); JFormattedTextField movefor; //Simulate until the block moves that much meters public Controls() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.ipady = 2; JPanel sp = new JPanel(new GridBagLayout()); String sptext = rb.getString("sp.text");{ pause = newJButton(pausetext, "p"); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; sp.add(pause,c); defaultspeed = newJButton(defaultspeedtext,"dspeed"); c.gridx = 1; c.gridy = 0; sp.add(defaultspeed,c); sspeed = new JSlider(JSlider.HORIZONTAL, 1, 1000, lsleept); sspeed.setMajorTickSpacing(100); sspeed.setMinorTickSpacing(10); sspeed.setPaintTicks(true); sspeed.setSnapToTicks(true); sspeed.addChangeListener((ChangeEvent e) -> { lsleept = sspeed.getValue(); }); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; sp.add(sspeed,c); } sp.setBorder(BorderFactory.createTitledBorder(sptext)); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; add(sp,c); JPanel state = new JPanel(new GridBagLayout()); String statetext = rb.getString("state.text"); { save = newJButton(savetext,"save"); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; state.add(save); load = newJButton(loadtext,"load"); c.gridx = 1; c.gridy = 0; state.add(load); } state.setBorder(BorderFactory.createTitledBorder(statetext)); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; add(state,c); JPanel Blockp = new JPanel(new GridBagLayout()); //Block panel String Blockptext = rb.getString("Blockp.Border.text");{ xyJL = new JLabel(xyJLtext); xyJL.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; Blockp.add(xyJL,c); JPanel coordinates = new JPanel(new GridLayout(1,2));{ xJTF = newJFormattedTextField("xJTF", blockx, Double.MIN_VALUE, Double.MAX_VALUE, new RealNumberFormat(), 6); yJTF = newJFormattedTextField("yJTF", blocky, Double.MIN_VALUE, Double.MAX_VALUE, new RealNumberFormat(), 6); coordinates.add(xJTF); coordinates.add(yJTF); } c.gridx = 1; c.gridy = 0; c.ipadx = 80; Blockp.add(coordinates,c); whlabel = new JLabel(whlabeltext); whlabel.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 1; c.ipadx = 0; Blockp.add(whlabel,c); JPanel dimensions = new JPanel(new GridLayout(1,2));{ wJTF = newJFormattedTextField("wJTF", Block.dw, 0, Double.MAX_VALUE, new RealNumberFormat(), 6); hJTF = newJFormattedTextField("hJTF", Block.dh, 0, Double.MAX_VALUE, new RealNumberFormat(), 6); dimensions.add(wJTF); dimensions.add(hJTF); } c.gridx = 1; c.gridy = 1; Blockp.add(dimensions,c); JPanel initialap = new JPanel(new GridBagLayout()); //acceleration panel String accelerationptext = rb.getString("accelerationp.Border.text");{ aJL = new JLabel(aJLtext); aJL.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 0; initialap.add(aJL,c); aJTF = newJFormattedTextField("aJTF", initialv, 0d, Double.MAX_VALUE, new PositiveRealNumberFormat(), 4); c.gridx = 1; c.gridy = 0; initialap.add(aJTF,c); athetaJL = new JLabel(athetaJLtext); athetaJL.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 1; initialap.add(athetaJL,c); athetaJTF = newJFormattedTextField("athetaJTF", initialvtheta, Double.MIN_VALUE, Double.MAX_VALUE, new RealNumberFormat(), 4); c.gridx = 1; c.gridy = 1; initialap.add(athetaJTF,c); } initialap.setBorder(BorderFactory.createTitledBorder(accelerationptext)); c.gridx = 0; c.gridy = 2; c.ipady = 0; c.gridwidth = 2; Blockp.add(initialap,c); c.ipady = -1; mJL = new JLabel(mJLtext); mJL.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 3; c.gridwidth = 1; Blockp.add(mJL,c); mJTF = newJFormattedTextField("mJTF", blockm, 0d, Double.MAX_VALUE, new PositiveRealNumberFormat(), 5); c.gridx = 1; c.gridy = 3; Blockp.add(mJTF,c); moveforl = new JLabel(movefort); moveforl.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 4; Blockp.add(moveforl,c); movefor = newJFormattedTextField("movefor", 0d, 0d, Double.MAX_VALUE, new PositiveRealNumberFormat(), 3); c.gridx = 1; c.gridy = 4; Blockp.add(movefor,c); playforl = new JLabel(playfort); playforl.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 5; c.gridwidth = 1; Blockp.add(playforl,c); playfor = newJFormattedTextField("playfor", 0d, 0d, Double.MAX_VALUE, new PositiveRealNumberFormat(), 3); c.gridx = 1; c.gridy = 5; Blockp.add(playfor,c); addBlock = newJButton(addBlocktext, "New Block"); c.gridx = 0; c.gridy = 6; c.gridwidth = 2; Blockp.add(addBlock,c); clear = newJButton(cleartext, "clear"); c.gridx = 0; c.gridy = 7; c.gridwidth = 2; Blockp.add(clear,c); } Blockp.setBorder(BorderFactory.createTitledBorder(Blockptext)); c.gridx = 0; c.gridy = 2; add(Blockp,c); JPanel Fp = new JPanel(new GridBagLayout()); String Fptext = rb.getString("Fp.text");{ showF = newJCheckBox(showFtext, "Show force(s)", true); RCl = newJCheckBox(RCltext, "Color force(s)", false); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; Fp.add(showF,c); c.gridx = 1; c.gridy = 0; Fp.add(RCl,c); shownF = newJCheckBox(shownFtext, "Show net force", false); c.gridx = 0; c.gridy = 1; Fp.add(shownF,c); showarrows = newJCheckBox(showarrowstext, "Show arrows", true); c.gridx = 1; c.gridy = 1; Fp.add(showarrows,c); showparellelogram = newJCheckBox(showparellelogramtext, "Show parellelogram", true); c.gridx = 0; c.gridy = 2; c.gridwidth = 2; Fp.add(showparellelogram,c); showlabels = newJCheckBox(showlabelstext, "Show labels", true); c.gridx = 0; c.gridy = 3; c.gridwidth = 1; Fp.add(showlabels,c); showmass = newJCheckBox(showmasstext, "Show mass", true); c.gridx = 1; c.gridy = 3; Fp.add(showmass,c); previewForce = newJCheckBox(previewForcetext, "previewForce", true); c.gridx = 0; c.gridy = 4; c.gridwidth = 2; Fp.add(previewForce,c); /* uptodigits = new JSlider(JSlider.HORIZONTAL, 0, 16, 0); uptodigits.setMinorTickSpacing(1); uptodigits.setPaintTicks(true); uptodigits.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent CE) { //if(!uptodigits.getValueIsAdjusting()){ if(uptodigits.getValue() == 0){ shownumbers.setSelected(false); drawnumbers = false; } else { shownumbers.setSelected(true); drawnumbers = true; digits = uptodigits.getValue(); lastuptodigitsvalue = uptodigits.getValue(); } //} simulation.repaint(); } }); controls.gridx = 0; controls.gridy = 4; Fp.add(uptodigits,controls); */ } Fp.setBorder(BorderFactory.createTitledBorder(Fptext)); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; add(Fp,c); JPanel ap = new JPanel(new GridBagLayout()); String aptext = rb.getString("ap.text");{ a = newJCheckBox(atext, "a", true); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; ap.add(a,c); drawa = newJCheckBox(drawatext, "drawa", true); c.gridx = 1; c.gridy = 0; ap.add(drawa,c); onedgea = new JLabel(onedgeatext); onedgea.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 1; ap.add(onedgea,c); ahm = newJComboBox(ahmitems, "ahm"); c.gridx = 1; c.gridy = 1; ap.add(ahm,c); } ap.setBorder(BorderFactory.createTitledBorder(aptext)); c.gridx = 0; c.gridy = 4; c.gridwidth = 2; add(ap,c); JPanel vp = new JPanel(new GridBagLayout()); String vptext = rb.getString("v"); { drawv = newJCheckBox(drawvtext, "drawv", true); c.gridx = 0; c.gridy = 0; vp.add(drawv, c); } vp.setBorder(BorderFactory.createTitledBorder(vptext)); c.gridwidth = 2; c.gridx = 0; c.gridy = 5; add(vp,c); JPanel frictionp = new JPanel(new GridBagLayout()); String frictionptext = rb.getString("friction.text"); { dofriction = newJCheckBox(dofrictiontext, "friction", true); dofriction.setAlignmentY(JComponent.CENTER_ALIGNMENT); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; frictionp.add(dofriction,c); c.gridwidth = 1; staticfclabel = new JLabel(staticfctext); staticfclabel.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 1; frictionp.add(staticfclabel,c); staticfc = newJFormattedTextField("staticfc", simulation.cosf, 0d, 1d, new PositiveRealNumberFormat(), 6); c.gridx = 1; c.gridy = 1; c.ipadx = 40; frictionp.add(staticfc,c); kineticfclabel = new JLabel(kineticfctext); kineticfclabel.setHorizontalAlignment(SwingConstants.RIGHT); c.ipadx = 0; c.gridx = 0; c.gridy = 2; frictionp.add(kineticfclabel,c); kineticfc = newJFormattedTextField("kineticfc", simulation.cokf, 0d, 1d, new PositiveRealNumberFormat(), 6); c.gridx = 1; c.gridy = 2; c.ipadx = 40; frictionp.add(kineticfc,c); } c.gridx = 0; c.gridy = 6; c.gridwidth = 2; c.ipadx = 0; frictionp.setBorder(BorderFactory.createTitledBorder(frictionptext)); add(frictionp,c); JPanel restitutionp = new JPanel(new GridBagLayout()); String restitutionptext = rb.getString("restitution.text"); { restitutionclabel = new JLabel(restitutionctext); restitutionclabel.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 0; restitutionp.add(restitutionclabel,c); restitutionc = new JSlider(JSlider.HORIZONTAL, 0, 100, 100); restitutionc.setMinorTickSpacing(10); restitutionc.setPaintTicks(true); restitutionc.addChangeListener((ChangeEvent e) -> { simulation.cor = (double)restitutionc.getValue()/100; }); c.gridx = 0; c.gridy = 1; restitutionp.add(restitutionc,c); } c.gridx = 0; c.gridy = 7; c.ipadx = 0; restitutionp.setBorder(BorderFactory.createTitledBorder(restitutionptext)); add(restitutionp,c); JPanel Grp = new JPanel(); String Grptext = rb.getString("Grp.text"); { addgravity = newJCheckBox(addgravitytext, "Gravity", false); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; Grp.add(addgravity); gravitybounce = newJCheckBox(gravitybouncetext, "Bounce in Gravity", false); Grp.add(gravitybounce); } c.gridx = 0; c.gridy = 8; c.gridwidth = 2; Grp.setBorder(BorderFactory.createTitledBorder(Grptext)); add(Grp,c); onedge = new JLabel(onedgetext); c.gridx = 0; c.gridy = 9; c.gridwidth = 1; onedge.setHorizontalAlignment(SwingConstants.RIGHT); add(onedge,c); edgehandlingmode = newJComboBox(ehmitems, "ehm"); edgehandlingmode.setSelectedIndex(1); c.gridx = 1; c.gridy = 9; add(edgehandlingmode,c); c.gridx = 0; c.gridy = 10; onBlock = new JLabel(onBlocktext); onBlock.setHorizontalAlignment(SwingConstants.RIGHT); add(onBlock,c); collisionhandlingmode = newJComboBox(chmitems, "chm"); collisionhandlingmode.setSelectedIndex(1); c.gridx = 1; c.gridy = 10; add(collisionhandlingmode,c); //<editor-fold defaultstate="collapsed" desc="concepts"> /* concepts = new JTabbedPane(); fo = new JPanel(); fo.add(new JLabel(rb.getString("concepts.fo.text"))); concepts.addTab(rb.getString("concepts.fo.title"),fo); nefo = new JPanel(); nefo.add(new JLabel(rb.getString("concepts.nefo.text"))); concepts.addTab(rb.getString("concepts.nefo.title"),nefo); ac = new JPanel(); ac.add(new JLabel(rb.getString("concepts.ac.text"))); concepts.addTab(rb.getString("concepts.ac.title"),ac); gr = new JPanel(); gr.add(new JLabel(rb.getString("concepts.gr.text"))); concepts.addTab(rb.getString("concepts.gr.title"),gr); controls.gridx = 0; controls.gridy = 8; controls.gridwidth = 2; concepts.setBorder(BorderFactory.createTitledBorder(rb.getString("concepts.title"))); add(concepts,controls);*/ //</editor-fold> themel = new JLabel(themelt); themel.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = 11; add(themel,c); themes = newJComboBox(themenames, "theme"); c.gridx = 1; c.gridy = 11; add(themes,c); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.BLACK), new EmptyBorder(0, 10, 0, 10))); } private JButton newJButton(String text, String ActionCommand) { JButton jb = new JButton(text); jb.setActionCommand(ActionCommand); jb.addActionListener(this); return jb; } private JTextField newJTextField(String name, String initial, int length) { JTextField jtf = new JTextField(initial, length); jtf.setActionCommand(name); jtf.addActionListener(this); return jtf; } private JFormattedTextField newJFormattedTextField(String name, double initial, double Minimum, double Maximum, Object Format, int length){ JFormattedTextField jftf = new JFormattedTextField(Format); jftf.setActionCommand(name); jftf.addActionListener(this); jftf.setValue(initial); //jftf.setColumns(length); jftf.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { clearjtf(e); }}); return jftf; } private JCheckBox newJCheckBox(String text, String ActionCommand, boolean selected) { JCheckBox jcb = new JCheckBox(text, selected); jcb.setActionCommand(ActionCommand); jcb.addActionListener(this); return jcb; } private JComboBox newJComboBox(String[] items, String ActionCommand) { JComboBox jcb = new JComboBox(items); jcb.setActionCommand(ActionCommand); jcb.addActionListener(this); return jcb; } private void clearjtf(MouseEvent e){ ((JTextField)e.getSource()).setText(""); } public double blockx = Block.dx; public double blocky = Block.dy; int blockw = Block.dw, blockh = Block.dh; public double blockm = Block.dm; public double initialv = 0d; public double initialvtheta = 0d; public double moveford = 0d; public double playford = 0d; @Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()){ case "Gravity": gravitymode = addgravity.isSelected(); simulation.calculaten(); if(addgravity.isSelected()){ Bedgehandlingmode = -1; edgehandlingmode.setEnabled(false); simulation.Gr = new Ground(); simulation.Gr.update(); gravitybounce.setEnabled(true); } else { simulation.bulldozegravity(); Bedgehandlingmode = edgehandlingmode.getSelectedIndex(); edgehandlingmode.setEnabled(true); gravitybounce.setEnabled(false); } break; case "Bounce in Gravity": bounceingravity = gravitybounce.isSelected(); break; case "friction": addfriction = dofriction.isSelected(); simulation.calculaten(); break; case "staticfc": if(Double.parseDouble(staticfc.getText()) >= 0d){ simulation.cosf = Double.parseDouble(staticfc.getText()); simulation.calculaten(); } break; case "kineticfc": if(Double.parseDouble(kineticfc.getText()) >= 0d){ simulation.cokf = Double.parseDouble(kineticfc.getText()); simulation.calculaten(); } break; case "save": save(); break; case "load": load(); break; case "dspeed": sspeed.setValue(30); lsleept = 30; break; case "xJTF": if(Double.parseDouble(xJTF.getText()) >= 0d){ blockx = Double.parseDouble(xJTF.getText()); } break; case "wJTF": blockw = Integer.parseInt(wJTF.getText()); break; case "hJTF": blockh = Integer.parseInt(hJTF.getText()); break; case "yJTF": if(Double.parseDouble(yJTF.getText()) >= 0d){ blocky = Double.parseDouble(yJTF.getText()); } break; case "aJTF": initialv = Double.parseDouble(aJTF.getText()); break; case "athetaJTF": initialvtheta = Double.parseDouble(athetaJTF.getText()); initialvtheta = initialvtheta*Math.PI/180; break; case "mJTF": if(Double.parseDouble(mJTF.getText()) > 0d){ blockm = Double.parseDouble(mJTF.getText()); } break; case "New Block": simulation.addBlock(blockx,blocky, blockw,blockh, new Vector(initialv, initialvtheta), blockm, moveford, playford); break; case "clear": simulation.clear(); break; case "p": if(simulation.isPaused){ simulation.isPaused = false; simulation.play(); pause.setText(pausetext); } else { simulation.isPaused = true; simulation.pause(); pause.setText(play); } break; case "a": if(a.isSelected()){ if(showF.isSelected()){ drawa.setEnabled(true); } ahm.setEnabled(true); allowacceleration = true; } else { drawa.setEnabled(false); ahm.setEnabled(false); allowacceleration = false; } break; case "drawa": drawacceleration = drawa.isSelected(); break; case "ahm": Bahandlingmode = ahm.getSelectedIndex(); break; case "Show force(s)": if(showF.isSelected()){ drawLine = true; RCl.setEnabled(true); shownF.setEnabled(true); showarrows.setEnabled(true); showlabels.setEnabled(true); if(a.isSelected()){ drawa.setEnabled(true); } RandomColorline = RCl.isSelected(); drawnF = shownF.isSelected(); drawarrow = showarrows.isSelected(); //drawnumbers = showlabels.isSelected(); drawacceleration = drawa.isSelected(); } else { drawLine = false; RCl.setEnabled(false); shownF.setEnabled(false); showarrows.setEnabled(false); showlabels.setEnabled(false); //uptodigits.setEnabled(false); drawa.setEnabled(false); RandomColorline = RCl.isSelected(); drawnF = false; drawarrow = false; //drawnumbers = false; drawacceleration = false; } break; case "Color force(s)": RandomColorline = RCl.isSelected(); break; case "Show net force": drawnF = shownF.isSelected(); break; case "Show arrows": drawarrow = showarrows.isSelected(); break; case "Show parellelogram": drawParellelogram = showparellelogram.isSelected(); break; case "Show labels": drawlabels = showlabels.isSelected(); break; case "Show mass": drawmass = showmass.isSelected(); break; case "previewForce": previewForcemagnitude = previewForce.isSelected(); break; case "drawv": drawvelocity = drawv.isSelected(); break; case "ehm": Bedgehandlingmode = edgehandlingmode.getSelectedIndex(); switch(edgehandlingmode.getSelectedIndex()){ case 0: ahm.setEnabled(false); break; case 1: ahm.setEnabled(true); break; } break; case "chm": Bcollisionhandlingmode = collisionhandlingmode.getSelectedIndex(); break; case "theme": currenttheme = themes.getSelectedIndex(); changetheme(currenttheme); break; case "playfor": if(Double.parseDouble(playfor.getText()) >= 0d){ playford = Double.parseDouble(playfor.getText()); /*actionPerformed(new ActionEvent(this, -1, "dspeed")); //Comment only for absolute timing sspeed.setEnabled(false); } else { sspeed.setEnabled(true);*/ } break; case "movefor": if(Double.parseDouble(movefor.getText()) >= 0d){ moveford = Double.parseDouble(movefor.getText()); } break; } simulation.repaint(); } public void changetheme(int i){ try { InputStream is = getClass().getResource("simulation/themes/"+themefilenames[i]).openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); JSONObject jo = new JSONObject(new JSONTokener(br)); simulation.backc = new Color(Integer.parseInt(jo.getString("background"))); simulation.blockc = new Color(Integer.parseInt(jo.getString("blockc"))); simulation.linec = new Color(Integer.parseInt(jo.getString("linec"))); simulation.accc = new Color(Integer.parseInt(jo.getString("accc"))); simulation.iaccc = new Color(Integer.parseInt(jo.getString("iaccc"))); simulation.textc = new Color(Integer.parseInt(jo.getString("textc"))); simulation.gc = new Color(Integer.parseInt(jo.getString("gc"))); simulation.fc = new Color(Integer.parseInt(jo.getString("fc"))); simulation.nc = new Color(Integer.parseInt(jo.getString("nc"))); simulation.vc = new Color(Integer.parseInt(jo.getString("vc"))); simulation.setBackground(simulation.backc); simulation.repaint(); } catch(IOException e){ Logger.getLogger(Controls.class.getName()).log(Level.SEVERE, null, e); } } public void save(){ boolean pisPaused = simulation.isPaused; if(!pisPaused) actionPerformed(new ActionEvent(this, -1, "p")); FileDialog FD = new FileDialog(new JFrame(), "Save to file", FileDialog.SAVE); FD.setFile("*.json"); FD.setVisible(true); File F = new File(FD.getDirectory()+"/"+FD.getFile()); try (FileWriter FW = new FileWriter(F.getAbsolutePath())) { FW.write(simulation.toJSONString()); FW.flush(); } catch (IOException IOE) { Logger.getLogger(Controls.class.getName()).log(Level.SEVERE, null, IOE); } if(!pisPaused) actionPerformed(new ActionEvent(this, -1, "p")); } public void load(){ boolean pisPaused = simulation.isPaused; if(!pisPaused) actionPerformed(new ActionEvent(this, -1, "p")); FileDialog FD = new FileDialog(new JFrame(), "Open file", FileDialog.LOAD); FD.setFile("*.json"); FD.setVisible(true); File F = new File(FD.getDirectory()+"/"+FD.getFile()); if(FD.getFile() != null){ try { simulation.clear(); JSONObject loads = new JSONObject(new JSONTokener(new FileReader(F))); simulation.isPaused = loads.getBoolean("isPaused"); showarrows.setSelected(loads.getBoolean("drawarrow")); showF.setSelected(loads.getBoolean("drawLine")); shownF.setSelected(loads.getBoolean("drawnF")); //digits = loads.getInt("digits"); showparellelogram.setSelected(loads.getBoolean("drawParellelogram")); RCl.setSelected(loads.getBoolean("RandomColorline")); previewForce.setSelected(loads.getBoolean("previewForcemagnitude")); a.setSelected(loads.getBoolean("allowacceleration")); drawa.setSelected(loads.getBoolean("drawacceleration")); drawv.setSelected(loads.getBoolean("drawvelocity")); edgehandlingmode.setSelectedIndex(loads.getInt("Bedgehandlingmode")); collisionhandlingmode.setSelectedIndex(loads.getInt("Bcollisionhandlingmode")); ahm.setSelectedIndex(loads.getInt("Bahandlingmode")); addgravity.setSelected(loads.getBoolean("gravitymode")); gravitybounce.setSelected(loads.getBoolean("bounceingravity")); dofriction.setSelected(loads.getBoolean("addfriction")); JSONArray jsonblocks = loads.getJSONArray("blocks"); for(int i = 0; i < jsonblocks.length(); ++i){ JSONObject iBlock = jsonblocks.getJSONObject(i); simulation.addBlock(iBlock.getDouble("x"), iBlock.getDouble("y"), iBlock.getInt("w"), iBlock.getInt("h"), new Vector(0,0), iBlock.getDouble("mass"), iBlock.getDouble("moveford"), iBlock.getDouble("playford")); int workingi = simulation.bindex-1; simulation.blocks[workingi].load(new Vector(iBlock.getJSONObject("n")), new Vector(iBlock.getJSONObject("a")), new Vector(iBlock.getJSONObject("v")), iBlock.getLong("starttime"), iBlock.getLong("elapsedt"), iBlock.getDouble("moved"), iBlock.getDouble("work"), iBlock.getDouble("totalwork"), iBlock.getDouble("power"), iBlock.getDouble("totalpower"), iBlock.getBoolean("keycontrolledForces"), iBlock.getDouble("px"), iBlock.getDouble("py"), iBlock.getDouble("pv"), iBlock.getDouble("ppv"), iBlock.getBoolean("iskineticf")); JSONArray jsonforces = iBlock.getJSONArray("forces"); JSONArray jsonforcesColor = iBlock.getJSONArray("forcesColor"); for(int j = 0; j < jsonforces.length(); ++j) simulation.blocks[workingi].addForce(new Vector(jsonforces.getJSONObject(j)), new Color(jsonforcesColor.getInt(j))); } JSONArray jsonmovingclub = loads.getJSONArray("movingclub"); for(int i = 0; i < jsonmovingclub.length(); ++i){ simulation.movingclub.add((Block)jsonmovingclub.get(i)); } if(simulation.hascablock = loads.getBoolean("hascablock")){ simulation.cablock = loads.getInt("cablock"); } else simulation.cablock = -1; if(simulation.hascfblock = loads.getBoolean("hascfblock")){ simulation.cfblock = loads.getInt("cfblock"); } else simulation.cfblock = -1; usecamera = loads.getBoolean("usecamera"); SwingUtilities.invokeLater(() -> { refreshControls(); simulation.repaint(); }); } catch(FileNotFoundException e){ Logger.getLogger(Controls.class.getName()).log(Level.SEVERE, null, e); } if(!pisPaused) actionPerformed(new ActionEvent(this, -1, "p")); } } public void refreshControls(){ ArrayList<Component> components = new ArrayList<>(Arrays.asList(getComponents())); for(int i = 0; i < components.size(); ++i){ System.out.println(components.get(i)); if(components.get(i) instanceof JCheckBox) actionPerformed(new ActionEvent(this,-1,((JCheckBox)components.get(i)).getActionCommand())); else if(components.get(i) instanceof JComboBox) actionPerformed(new ActionEvent(this,-1,((JComboBox)components.get(i)).getActionCommand())); else if(components.get(i) instanceof JPanel) components.addAll(getComponentsof((JPanel)components.get(i))); } repaint(); revalidate(); } public static ArrayList<Component> getComponentsof(JPanel tp){ ArrayList<Component> components = new ArrayList<>(Arrays.asList(tp.getComponents())); for(int i = 0; i < components.size(); ++i){ if(components.get(i) instanceof JPanel) components.addAll(getComponentsof((JPanel)components.get(i))); } return components; } @Override public void stateChanged(ChangeEvent e){ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
import biuoop.DrawSurface; import java.awt.Color; /** * Created by user on 02/06/2017. */ public class LevelName implements Sprite { private String string; /** *construct a LevelName using string. * @param string the name of the level. */ public LevelName(String string) { this.string = string; } /** *draw the Sprite. * @param surface the surface which we draw on. */ public void drawOn(DrawSurface surface) { surface.setColor(Color.lightGray); surface.fillRectangle(600, 0, 300, 20); surface.setColor(Color.black); surface.drawText(500, 0 + 13, "Level Name:" + this.string, 15); } /** *we don't use it. * @param dt dt. */ public void timePassed(double dt) { } /** * * @param g a Game. */ public void addToGame(GameLevel g) { g.addSprite(this); } }
package littleservantmod.entity.ai; import littleservantmod.entity.EntityLittleServant; import littleservantmod.profession.ServantToolManager; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class EntityAIUseTorch extends EntityAIBase { private final EntityLittleServant servant; public EntityAIUseTorch(EntityLittleServant servant) { this.servant = servant; this.setMutexBits(4); } @Override public boolean shouldExecute() { if (servant.world.rand.nextInt(8) != 0) { return false; } return shouldUse(servant.world, servant.getPosition().down()); } @Override public void updateTask() { BlockPos target = servant.getPosition().down(); if (this.shouldUse(servant.world, target)) { World world = this.servant.world; BlockPos blockpos = target.up(); IBlockState iblockstate = world.getBlockState(blockpos); Block block = iblockstate.getBlock(); if (iblockstate.getMaterial() == Material.AIR && ServantToolManager.getInstance().isTool(ServantToolManager.torcher, this.servant.getHeldItemMainhand())) { ItemStack itemstack = this.servant.getHeldItemMainhand(); if (itemstack.getItem() instanceof ItemBlock) { ItemBlock itemBlock = (ItemBlock) itemstack.getItem(); IBlockState state = Block.getBlockFromItem(itemBlock).getStateForPlacement(world, blockpos, EnumFacing.UP, 0.5f, 1.0f, 0.5f, itemstack.getMetadata(), this.servant, EnumHand.MAIN_HAND); world.setBlockState(blockpos, state, 3); this.servant.swingArm(EnumHand.MAIN_HAND); itemstack.shrink(1); if (itemstack.isEmpty()) { this.servant.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); } } } } } protected boolean shouldUse(World worldIn, BlockPos pos) { Block block = worldIn.getBlockState(pos).getBlock(); if (worldIn.getLightFromNeighbors(pos.up()) < 8) { pos = pos.up(); IBlockState iblockstate = worldIn.getBlockState(pos); block = iblockstate.getBlock(); if (iblockstate.getMaterial() == Material.AIR) { return true; } } return false; } }
package com.jvmless.threecardgame.domain.game; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.stream.Collectors; @Slf4j public class MongoGameRepositoryAdapter implements GamesRepository { private final MongoGameRepository mongoGameRepository; public MongoGameRepositoryAdapter(MongoGameRepository mongoGameRepository) { this.mongoGameRepository = mongoGameRepository; } @Override public Game findActiveGamesByHostId(HostId hostId) { return mongoGameRepository.findAllByHostIs(new Host(hostId)) .stream() .filter(Game::isActive) .findFirst() .orElse(null); } @Override public Game findActiveGamesByGamerId(GamerId gamerId) { return mongoGameRepository.findAllByPlayersContains(new Gamer(gamerId)) .stream() .filter(Game::isActive) .findFirst() .orElse(null); } @Override public Game findByGameId(GameId gameId) { return mongoGameRepository.findByGameId(gameId); } @Override public void save(Game newGame) { try {mongoGameRepository.save(newGame);} catch (Exception ex) { log.error("CANNOT SAVE GAME!",ex); } } @Override public List<Game> findAllActive() { return mongoGameRepository.findAll().stream().filter(Game::isActive).collect(Collectors.toList()); } }
/******************************************************************************* * Copyright (c) 2016 Chen Chao(cnfree2000@hotmail.com). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chen Chao - initial API and implementation *******************************************************************************/ package org.sf.feeling.mars.mpc.ui.commands; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.epp.internal.mpc.core.MarketplaceClientCore; import org.eclipse.epp.internal.mpc.ui.CatalogRegistry; import org.eclipse.epp.internal.mpc.ui.MarketplaceClientUi; import org.eclipse.epp.internal.mpc.ui.MarketplaceClientUiPlugin; import org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog; import org.eclipse.epp.internal.mpc.ui.catalog.ResourceProvider; import org.eclipse.epp.internal.mpc.ui.wizards.AbstractTagFilter; import org.eclipse.epp.internal.mpc.ui.wizards.ComboTagFilter; import org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceCatalogConfiguration; import org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceFilter; import org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard; import org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.WizardState; import org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizardDialog; import org.eclipse.epp.mpc.core.model.ICatalog; import org.eclipse.epp.mpc.core.model.ICategory; import org.eclipse.epp.mpc.core.model.IMarket; import org.eclipse.epp.mpc.core.service.ICatalogService; import org.eclipse.epp.mpc.core.service.ServiceHelper; import org.eclipse.epp.mpc.ui.CatalogDescriptor; import org.eclipse.epp.mpc.ui.IMarketplaceClientConfiguration; import org.eclipse.epp.mpc.ui.Operation; import org.eclipse.equinox.internal.p2.discovery.DiscoveryCore; import org.eclipse.equinox.internal.p2.discovery.model.Tag; import org.eclipse.equinox.internal.p2.ui.discovery.util.WorkbenchUtil; import org.eclipse.equinox.internal.p2.ui.discovery.wizards.CatalogFilter; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.statushandlers.StatusManager; import org.sf.feeling.mars.mpc.ui.market.client.DecompilerMarketWizard; /** * @author David Green * @author Carsten Reckord */ public class MarketplaceWizardCommand extends AbstractHandler implements IHandler { private List<CatalogDescriptor> catalogDescriptors; private CatalogDescriptor selectedCatalogDescriptor; private String wizardState; private Map<String, Operation> operations; private WizardState wizardDialogState; public Object execute( ExecutionEvent event ) throws ExecutionException { final MarketplaceCatalog catalog = new MarketplaceCatalog( ); catalog.setEnvironment( DiscoveryCore.createEnvironment( ) ); catalog.setVerifyUpdateSiteAvailability( false ); MarketplaceCatalogConfiguration configuration = new MarketplaceCatalogConfiguration( ); configuration.setVerifyUpdateSiteAvailability( false ); if ( catalogDescriptors == null || catalogDescriptors.isEmpty( ) ) { final IStatus remoteCatalogStatus = installRemoteCatalogs( ); configuration.getCatalogDescriptors( ).addAll( CatalogRegistry.getInstance( ).getCatalogDescriptors( ) ); if ( configuration.getCatalogDescriptors( ).isEmpty( ) ) { // doesn't make much sense to continue without catalogs. // nothing will work and no way to recover later IStatus cause; if ( !remoteCatalogStatus.isOK( ) ) { cause = remoteCatalogStatus; } else { cause = new Status( IStatus.ERROR, MarketplaceClientUi.BUNDLE_ID, Messages.MarketplaceWizardCommand_noRemoteCatalogs ); } IStatus exitStatus = new Status( IStatus.ERROR, MarketplaceClientUi.BUNDLE_ID, cause.getCode( ), Messages.MarketplaceWizardCommand_cannotOpenMarketplace, new CoreException( cause ) ); try { MarketplaceClientUi.handle( exitStatus, StatusManager.SHOW | StatusManager.BLOCK | ( exitStatus.getSeverity( ) == IStatus.CANCEL ? 0 : StatusManager.LOG ) ); } catch ( Exception ex ) { // HOTFIX for bug 477269 - Display might get disposed during // call to handle due to workspace shutdown or similar. // In that case, just log... MarketplaceClientUi.getLog( ).log( exitStatus ); } return null; } else if ( !remoteCatalogStatus.isOK( ) ) { MarketplaceClientUi.handle( remoteCatalogStatus, StatusManager.LOG ); } } else { configuration.getCatalogDescriptors( ).addAll( catalogDescriptors ); } if ( selectedCatalogDescriptor != null ) { if ( selectedCatalogDescriptor.getLabel( ).equals( "org.eclipse.epp.mpc.descriptorHint" ) ) //$NON-NLS-1$ { CatalogDescriptor resolvedDescriptor = CatalogRegistry.getInstance( ) .findCatalogDescriptor( selectedCatalogDescriptor.getUrl( ).toExternalForm( ) ); if ( resolvedDescriptor == null ) { IStatus status = new Status( IStatus.ERROR, MarketplaceClientUi.BUNDLE_ID, Messages.MarketplaceWizardCommand_CouldNotFindMarketplaceForSolution, new ExecutionException( selectedCatalogDescriptor.getUrl( ).toExternalForm( ) ) ); MarketplaceClientUi.handle( status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG ); return null; } else { configuration.setCatalogDescriptor( resolvedDescriptor ); } } else { configuration.setCatalogDescriptor( selectedCatalogDescriptor ); } } configuration.getFilters( ).clear( ); final ComboTagFilter marketFilter = new ComboTagFilter( ) { @Override public void catalogUpdated( boolean wasCancelled ) { List<Tag> choices = new ArrayList<Tag>( ); List<IMarket> markets = catalog.getMarkets( ); for ( IMarket market : markets ) { Tag marketTag = new Tag( IMarket.class, market.getId( ), market.getName( ) ); marketTag.setData( market ); choices.add( marketTag ); } setChoices( choices ); } }; marketFilter.setSelectAllOnNoSelection( true ); marketFilter.setNoSelectionLabel( Messages.MarketplaceWizardCommand_allMarkets ); marketFilter.setTagClassification( ICategory.class ); marketFilter.setChoices( new ArrayList<Tag>( ) ); final ComboTagFilter marketCategoryTagFilter = new ComboTagFilter( ) { @Override public void catalogUpdated( boolean wasCancelled ) { updateCategoryChoices( this, marketFilter ); } }; marketCategoryTagFilter.setSelectAllOnNoSelection( true ); marketCategoryTagFilter.setNoSelectionLabel( Messages.MarketplaceWizardCommand_allCategories ); marketCategoryTagFilter.setTagClassification( ICategory.class ); marketCategoryTagFilter.setChoices( new ArrayList<Tag>( ) ); final IPropertyChangeListener marketListener = new IPropertyChangeListener( ) { public void propertyChange( PropertyChangeEvent event ) { final String property = event.getProperty( ); if ( AbstractTagFilter.PROP_SELECTED.equals( property ) ) { updateCategoryChoices( marketCategoryTagFilter, marketFilter ); } } }; marketFilter.addPropertyChangeListener( marketListener ); configuration.getFilters( ).add( marketFilter ); configuration.getFilters( ).add( marketCategoryTagFilter ); configuration.setInitialState( wizardState ); if ( operations != null && !operations.isEmpty( ) ) { configuration.setInitialOperations( operations ); } for ( CatalogFilter filter : configuration.getFilters( ) ) { ( (MarketplaceFilter) filter ).setCatalog( catalog ); } MarketplaceWizard wizard = new DecompilerMarketWizard( catalog, configuration ); wizard.setInitialState( wizardDialogState ); wizard.setWindowTitle( Messages.MarketplaceWizardCommand_eclipseMarketplace ); WizardDialog dialog = new MarketplaceWizardDialog( WorkbenchUtil.getShell( ), wizard ); dialog.open( ); return null; } private void updateCategoryChoices( final ComboTagFilter marketCategoryTagFilter, final ComboTagFilter marketFilter ) { Set<Tag> newChoices = new HashSet<Tag>( ); List<Tag> choices = new ArrayList<Tag>( ); Set<IMarket> selectedMarkets = new HashSet<IMarket>( ); for ( Tag marketTag : marketFilter.getSelected( ) ) { selectedMarkets.add( (IMarket) marketTag.getData( ) ); } final MarketplaceCatalog catalog = (MarketplaceCatalog) marketCategoryTagFilter.getCatalog( ); List<IMarket> markets = catalog.getMarkets( ); for ( IMarket market : markets ) { if ( selectedMarkets.isEmpty( ) || selectedMarkets.contains( market ) ) { for ( ICategory marketCategory : market.getCategory( ) ) { Tag categoryTag = new Tag( ICategory.class, marketCategory.getId( ), marketCategory.getName( ) ); categoryTag.setData( marketCategory ); if ( newChoices.add( categoryTag ) ) { choices.add( categoryTag ); } } } } Collections.sort( choices, new Comparator<Tag>( ) { public int compare( Tag o1, Tag o2 ) { return o1.getLabel( ).compareTo( o2.getLabel( ) ); } } ); marketCategoryTagFilter.setChoices( choices ); } public void setCatalogDescriptors( List<CatalogDescriptor> catalogDescriptors ) { this.catalogDescriptors = catalogDescriptors; } public void setSelectedCatalogDescriptor( CatalogDescriptor selectedCatalogDescriptor ) { this.selectedCatalogDescriptor = selectedCatalogDescriptor; } public void setWizardState( String wizardState ) { this.wizardState = wizardState; } public void setWizardDialogState( WizardState wizardState ) { this.wizardDialogState = wizardState; } /** * @deprecated use {@link #setOperations(Map)} instead */ @Deprecated public void setOperationByNodeId( Map<String, org.eclipse.epp.internal.mpc.ui.wizards.Operation> operationByNodeId ) { this.operations = org.eclipse.epp.internal.mpc.ui.wizards.Operation.mapAllBack( operationByNodeId ); } public void setOperations( Map<String, Operation> operationByNodeId ) { this.operations = operationByNodeId; } public void setConfiguration( IMarketplaceClientConfiguration configuration ) { setCatalogDescriptors( configuration.getCatalogDescriptors( ) ); setOperations( configuration.getInitialOperations( ) ); setWizardState( (String) configuration.getInitialState( ) ); setSelectedCatalogDescriptor( configuration.getCatalogDescriptor( ) ); } public IStatus installRemoteCatalogs( ) { try { final AtomicReference<List<? extends ICatalog>> result = new AtomicReference<List<? extends ICatalog>>( ); PlatformUI.getWorkbench( ).getProgressService( ).busyCursorWhile( new IRunnableWithProgress( ) { public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException { try { ICatalogService catalogService = ServiceHelper.getMarketplaceServiceLocator( ) .getCatalogService( ); final List<? extends ICatalog> catalogs = catalogService.listCatalogs( monitor ); result.set( catalogs ); } catch ( CoreException e ) { if ( e.getStatus( ).getSeverity( ) == IStatus.CANCEL ) { throw new InterruptedException( ); } throw new InvocationTargetException( e ); } } } ); List<? extends ICatalog> catalogs = result.get( ); for ( ICatalog catalog : catalogs ) { ResourceProvider resourceProvider = MarketplaceClientUiPlugin.getInstance( ).getResourceProvider( ); String catalogName = catalog.getName( ); String requestSource = NLS.bind( Messages.MarketplaceWizardCommand_requestCatalog, catalogName, catalog.getId( ) ); String catalogImageUrl = catalog.getImageUrl( ); if ( catalogImageUrl != null ) { try { resourceProvider.retrieveResource( requestSource, catalogImageUrl ); } catch ( Exception e ) { MarketplaceClientUi.log( IStatus.WARNING, Messages.MarketplaceWizardCommand_FailedRetrievingCatalogImage, catalogName, catalogImageUrl, e ); } } if ( catalog.getBranding( ) != null && catalog.getBranding( ).getWizardIcon( ) != null ) { String wizardIconUrl = catalog.getBranding( ).getWizardIcon( ); try { resourceProvider.retrieveResource( requestSource, wizardIconUrl ); } catch ( Exception e ) { MarketplaceClientUi.log( IStatus.WARNING, Messages.MarketplaceWizardCommand_FailedRetrievingCatalogWizardIcon, catalogName, wizardIconUrl, e ); } } CatalogDescriptor descriptor = new CatalogDescriptor( catalog ); registerOrOverrideCatalog( descriptor ); } } catch ( InterruptedException ie ) { return Status.CANCEL_STATUS; } catch ( Exception e ) { IStatus status = MarketplaceClientCore.computeStatus( e, Messages.MarketplaceWizardCommand_CannotInstallRemoteLocations ); return status; } return Status.OK_STATUS; } private void registerOrOverrideCatalog( CatalogDescriptor descriptor ) { CatalogRegistry catalogRegistry = CatalogRegistry.getInstance( ); List<CatalogDescriptor> descriptors = catalogRegistry.getCatalogDescriptors( ); for ( CatalogDescriptor catalogDescriptor : descriptors ) { if ( catalogDescriptor.getUrl( ).toExternalForm( ).equals( descriptor.getUrl( ).toExternalForm( ) ) ) { catalogRegistry.unregister( catalogDescriptor ); } } catalogRegistry.register( descriptor ); } }
class Mushrooms extends DecoratedPizza{ private final DecoratedPizza pizza; public Mushrooms(DecoratedPizza pizza){ this.pizza = pizza; } public double pizzaCost(){ return (pizza.pizzaCost() + 0.79); } public String getImage(){ return pizza.getImage() + "M"; } public String toString(){ return pizza.toString() + "Mushrooms\n"; } }
package org.five.ticket.entity.location; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class DisplayLocation { private String uuid; private String province; private String city; private String name; private String locationInfo; }
package com.pine.template.demo.old.dagger2; import dagger.Component; /** * Created by tanghongfeng on 2017/8/10. */ @Component(modules = {NormalModule.class}) public interface NormalComponent { void inject(NormalInjectee normalInjectee); }
package com.ias.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ias.model.Example; import com.ias.repos.ExampleRepo; @Controller @RequestMapping("/") public class ExampleController { private static final Logger LOG = LoggerFactory.getLogger(ExampleController.class); @Autowired private ExampleRepo exampleRepo; @RequestMapping(produces = MediaType.TEXT_PLAIN_VALUE) public @ResponseBody String doSomething() { return "SUCCESS!"; } @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody List<Example> listAll() { return exampleRepo.findAll(); } @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Example add(@RequestBody Example ex) throws Exception{ return exampleRepo.saveAndFlush(ex); } }
package com.kais.bean; import java.beans.PropertyChangeSupport; public class Kais implements Listenable { protected int valeur = 2; PropertyChangeSupport changeSupport; public Kais() { changeSupport = new PropertyChangeSupport(this); } @Override public PropertyChangeSupport getPropertyChangeSupport() { return changeSupport; } public int getValeur() { return valeur; } public void setValeur(int valeur) { //this.valeur = valeur; int oldValeur = this.valeur; this.valeur = valeur; changeSupport.firePropertyChange("valeur", oldValeur, this.valeur); } }
package com.sample.mall.service; import com.sample.mall.repository.OrderRepository; import com.sample.mall.repository.ProductRepository; import com.sample.mall.repository.UserRepository; import com.sample.mall.vo.Item; import com.sample.mall.vo.Order; import com.sample.mall.vo.Product; import com.sample.mall.vo.User; public class MallService { private OrderRepository orderRepo = new OrderRepository(); private ProductRepository productRepo = new ProductRepository(); private UserRepository userRepo = new UserRepository(); /** * 모든 상품정보를 화면에 표시한다.<br/> * 출력내용 :: 상품번호, 상품명, 가격, 할인가격 정보를 표시한다.<br /> * <br /> * * ProductRepository의 모든 상품정보 조회기능을 실행해서 상품정보 배열(Product가 저장된 배열)을 제공받아서 표시한다. */ public void displayAllProducts() { Product[] products = productRepo.getAllProducts(); System.out.println("=================================================="); System.out.println("[상품번호]\t[상 품 명]\t[가 격]\t[할인가격]\t[판매지수]"); System.out.println("=================================================="); for (Product product : products) { if (product == null) { break; } System.out.print(product.no + "\t"); System.out.print(product.name + "\t"); System.out.print(product.price + "\t"); System.out.print(product.discountPrice+"\t"); System.out.println(product.score); } } /** * 상품번호를 전달받아서 그 상품번호에 해당하는 상품의 상세정보를 화면에 표시한다.<br/> * 출력내용 :: 상품번호, 상품명, 가격, 할인가격, 재고, 판매지수 정보를 표시한다.<br /> * <br /> * * ProductRepository의 상품상세정보 조회 기능에 상품번호를 전달해서 상품정보(Product객체)를 제공받아서 표시한다. * * @param productNo 상세정보를 조회할 상품번호 */ public void displayProductDetail(int productNo) { Product product = productRepo.getProductByNo(productNo); if (product == null) { System.out.println("해당 번호와 일치하는 상품이 없습니다."); return; } System.out.println("=============================="); System.out.println("[상품 상세 정보]"); System.out.println("=============================="); System.out.println("상품번호: " + product.no); System.out.println("상품명: " + product.name); System.out.println("가격: " + product.price); System.out.println("할인가격: " + product.discountPrice); System.out.println("재고: " + product.stock); System.out.println("판매지수: " + product.score); System.out.println("=============================="); } /** * 사용자 아이디와 상품번호를 전달받아서 해당 사용자의 장바구니에 상품정보를 저장한다.<br/> * 사용자의 장바구니에 동일한 상품이 존재하는 경우는 장바구니에 추가되지 않는다.<br/> * 상품의 재고가 0개인 경우는 장바구니에 추가되지 않는다.<br /> * <br /> * * UserRepository의 사용자정보 조회 기능에 사용자 아이디를 전달해서 사용자정보(User객체)를 제공받는다.<br/> * Item객체를 생성해서 상품번호, 상품명, 구매가격을 저장한다.<br/> * User객체의 장바구니 아이템 추가 기능에 생성된 Item을 전달해서 장바구니에 추가한다.<br/> * ProductRepository의 상품상제정보 조회기능을 실행해서 상품정보(Product객체)를 제공받는다. 상품의 재고를 1감소시킨다. * * @param userId 사용자 아이디 * @param productNo 장바구니에 추가할 상품번호 */ public void addCartItem(String userId, int productNo) { User user = userRepo.getUserById(userId); if(user == null) { System.out.println("회원번호와 일치하는 회원의 정보가 없습니다."); return; } Product product = productRepo.getProductByNo(productNo); if (product == null) { System.out.println("상품번호와 일치하는 상품이 없습니다."); return; } if(product.stock ==0) { System.out.println("재고가 없습니다."); return; } Item[] items = user.getItems(); for(Item item : items) { if (item==null) { break; } if (item.productNo == productNo) { System.out.println("이미 장바구니에 해당 상품이 존재합니다."); } } Item item = new Item(); item.productNo = product.no; item.name = product.name; item.orderPrice = product.discountPrice; user.addItem(item); product.stock--; System.out.println("장바구니에 [" + product.name + "] 상품이 추가되었습니다."); } /** * 사용자 아이디를 전달받아서 그 사용자의 장바구니에 저장된 모든 상품정보를 화면에 출력한다.<br /> * 표시내용 :: 아이템번호, 상품번호, 상품명, 구매가격 정보를 표시한다.<br /> * <br /> * * UserRepository의 사용자정보 조회 기능에 사용자 아이디를 전달해서 사용자정보(User객체)를 제공받는다.<br /> * User객체의 장바구니 아이템조회기능을 사용해서 모든 Item정보를 제공받고 화면에 출력한다. * * @param userId 장바구니에 저장될 상품 정보를 조회할 사용자 아이디 */ public void displayMyCart(String userId) { User user = userRepo.getUserById(userId); if (user == null) { System.out.println("아이디와 일치하는 회원정보가 없습니다."); return; } Item[] items = user.getItems(); System.out.println("=================================================="); System.out.println("[번호]\t[상품번호]\t[상 품 명]\t[구매가격]"); System.out.println("--------------------------------------------------"); for (Item item : items) { if (item == null) { break; } System.out.print(item.no+"\t"); System.out.print(item.productNo+"\t"); System.out.print(item.name+"\t"); System.out.println(item.orderPrice); } System.out.println("=================================================="); } /** * 사용자 아이디를 전달받아서 그 사용자의 장바구니에 저장된 모든 상품을 주문한다.<br /> * <br /> * * UserRepository의 사용자정보 조회 기능에 사용자 아이디를 전달해서 사용자정보(User객체)를 제공받는다.<br /> * <ol> * <li>Order객체를 생성하고, 사용자 아이디를 저장한다.</li> * <li>위에서 조회된 User객체의 장바구니에서 Item객체를 하나씩 꺼낸다. * <ol> * <li>Item객체에서 구매가격를 꺼낸다.</li> * <li>구매가격의 1%만큼 포인트를 위에서 조회한 User객체의 포인트에 적립한다.</li> * <li>Item객체를 Order객체의 items배열에 저장한다.</li> * </ol> * </li> * <li>위에서 생성한 Order객체를 OrderRepository의 주문저장기능에 전달해서 저장되게 한다.</li> * <li>User객체의 장바구니 비우기 기능을 실행한다.</li> * </ol> * * @param userId 장바구니에 저장된 모든 상품정보를 주문하고 싶어하는 사용자 아이디 */ public void cartToOrder(String userId) { User user = userRepo.getUserById(userId); if(user==null) { System.out.println("아이디와 일치하는 회원 정보가 없습니다."); return; } Order order = new Order(); order.userId = userId; Item[] items = user.items; for(Item item : items) { if(item==null) { break; } user.point += (int) (item.orderPrice*0.01); order.addItem(item); System.out.println("장바구니에 담긴 ["+item.name+"] 상품을 주문합니다."); } orderRepo.insertOrder(order); user.clearItems(); System.out.println("### 장바구니에 담긴 모든 상품의 주문이 완료되었습니다."); } /** * 사용자 아이디를 전달받아서 그 사용자의 모든 주문내역을 화면에 출력한다.<br/> * <br/> * * OrderRepository의 주문내역조회 기능에 사용자 아이디를 전달해서 그 사용자의 모든 주문정보(Order배열)를 제공받아서 * 출력한다. * * @param userId */ public void displayMyOrders(String userId) { Order[] orders = orderRepo.getOrderByUserId(userId); if(orders==null) { System.out.println("입력하신 아이디와 일치하는 구매 내역이 없습니다."); return; } System.out.println("============================"); System.out.println("[주문번호]\t[상 품 명]\t[주문가격]"); System.out.println("----------------------------"); for (Order order : orders) { if(order == null) { break; } Item[] items = order.items; for (Item item : items) { if(item==null) { break; } System.out.print(order.no+"\t"); System.out.print(item.name+"\t"); System.out.println(item.orderPrice); } } User user = userRepo.getUserById(userId); System.out.println("----------------------------"); System.out.println("누적된 적립금: "+user.point); System.out.println("============================"); } }
package com.deltastuido.payment.port.alipay.api.model; /** * @author */ public enum RefundStatus { REFUND_SUCCESS,// 退款成功。 全额退款情况:trade_status= TRADE_CLOSED,而refund_status=REFUND_SUCCESS; 非全额退款情况:trade_status= TRADE_SUCCESS,而refund_status=REFUND_SUCCESS REFUND_CLOSED,// 退款关闭 }
package clientserver; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerApp { public static void main(String[] args) { try { ServerSocket server = new ServerSocket(4444); while (true) { Socket socket = null; socket = server.accept(); System.out.println("[+] New client connected >> " + socket); Thread th = new ClientHandler(socket); th.start(); } } catch (IOException e ) { System.out.println("[-] Error accepting client!"); e.printStackTrace(); } } }
import java.util.Arrays; import java.util.Random; public class GeneticAlgo { //variables to allow for manipulating the genetic algorithm. //default to 17 queens private static int queens = 17; //rate of mutation in the population private double mutation = 0.33; //size of the population private int pop = 50; Random rng = new Random(); Board[] popVec = new Board[pop]; //Constructors public GeneticAlgo(int q){ queens = q; } public GeneticAlgo(int q, int m){ queens = q; mutation = m; } public GeneticAlgo(int q, int m, int p){ queens = q; mutation = m; pop = p; } //End constructors //generate initial population of random boards.= public Board generatePop(){ //keep generating until population size is reached for(int i = 0; i < pop; i++){ int[] tempArray = new int[queens]; //generate 1 random individual for(int j = 0; j < queens; j++){ tempArray[j] = rng.nextInt(queens); } Board temp = new Board(tempArray); //if the board is a solution the exit and return that board if(temp.fitness == 0) return temp; popVec[i] = temp; } //sort the population based on fitness Arrays.sort(popVec); //no solution found during creation of population return null; } public Board generateNextGen(){ //cross over the top half of the population, and kill off the lower half (fastest) int count1 = 0; int count2 = 1; for(int i = pop/2; i < pop; i++){ Board child = new Board(crossOver(popVec[count1], popVec[count2])); popVec[i] = child; count1++; count2++; } //cross over the most fit individual with the rest of the population (slower) // Board parent1 = popVec[0]; // for(int i = 1; i < pop - 1; i++){ // Board parent2 = popVec[i]; // // Board child = new Board(crossOver(parent1, parent2)); // // popVec[i] = child; // } //chance to mutate a part of the population for(int i = 1; i < pop; i++){ int toMutate = rng.nextInt((int)(1 / mutation)); if(toMutate == 0){ popVec[i].mutate(); } if(popVec[i].fitness == 0){ return popVec[i]; } } //sort the population based on fitness Arrays.sort(popVec); //no solution is found so continue return null; } //perform cross over on 2 boards. public int[] crossOver(Board parent1, Board parent2){ int[] child = new int[queens]; //put first half of first array into a new individual for(int i = 0; i < queens/2; i++){ child[i] = parent1.state[i]; } //put seonds half of second array into a new individual for(int i = queens/2; i < queens; i++){ child[i] = parent2.state[i]; } //return newly created individual return child; } }
package com.guli.acl.service; import com.guli.acl.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 用户表 服务类 * </p> * * @author dtt * @since 2021-04-06 */ public interface UserService extends IService<User> { }
package com.bfchengnuo.security.app; import com.bfchengnuo.security.app.social.AppSingUpUtils; import com.bfchengnuo.security.core.social.support.SocialUserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.social.connect.Connection; import org.springframework.social.connect.web.ProviderSignInUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.ServletWebRequest; import javax.servlet.http.HttpServletRequest; /** * 处理 App 第三方信息登陆 * 大体流程: * 用户使用第三方登陆,在数据库中没有查到相关绑定信息,于是重定向到 /social/signUp * 并且保存信息到 redis 中,返回相关第三方信息。 * 客户端根据返回到信息提示用户注册或者绑定,然后请求 /register 完成绑定 * * @see SpringSocialConfigurerPostProcessor * @author 冰封承諾Andy * @date 2019-11-16 */ @RestController public class AppSecurityController { @Autowired private ProviderSignInUtils providerSignInUtils; @Autowired private AppSingUpUtils appSingUpUtils; /** * 参考 BrowserSecurityController#buildSocialUserInfo * @param request * @return */ @GetMapping("/social/signUp") @ResponseStatus(HttpStatus.UNAUTHORIZED) public SocialUserInfo getSocialUserInfo(HttpServletRequest request) { SocialUserInfo userInfo = new SocialUserInfo(); Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request)); userInfo.setProviderId(connection.getKey().getProviderId()); userInfo.setProviderUserId(connection.getKey().getProviderUserId()); userInfo.setNickname(connection.getDisplayName()); userInfo.setHeadimg(connection.getImageUrl()); appSingUpUtils.saveConnectionData(new ServletWebRequest(request), connection.createData()); return userInfo; } }
package com.lec.ex10Test; import java.util.Scanner; public class LibMain { public static void main(String[] args) { BookLib[] books = { new BookLib("300ㄱ100", "Physics", "김지원"), new BookLib("300ㄱ101", "Chemistry", "김지원"), new BookLib("300ㄱ102", "Biology", "김지원"), new BookLib("300ㄱ103", "Psychology", "김지원"), new BookLib("300ㄱ104", "Economics", "김지원") }; Scanner sc = new Scanner(System.in); int fn, idx = 0; String bTitle, borrower, checkOutDate; do { System.out.println("1:대출| 2:반납|3:도서현황 |0.종료 "); fn = sc.nextInt(); switch (fn) { case 1: System.out.println("대출할 책이름을 입력하십시오."); bTitle = sc.next(); for (idx = 0; idx < books.length; idx++) { if (bTitle.equals(books[idx].getBookTitle())) { break; } } // 책조회에서 책을 찾았는지 못찾았는지 보고 대출 진행 if (idx == books.length) { System.out.println("본 도서관에는 해당 도서가 존재하지 않습니다"); } else if (books[idx].getState() == Ilendable.STATE_BORROWED) { System.out.println(bTitle + "도서는 대출중입니다"); } else { // 대출 가능이니 대출인, 대출일 입력받고 대출진행 System.out.println("대출인을 입력하십시오"); borrower = sc.next(); System.out.println("대출일을 입력하십시오"); checkOutDate = sc.next(); books[idx].checkOut(borrower, checkOutDate); } break; case 2: // 책이름->책조회->반납 System.out.println("반납할 책이름을 입력하십시오"); bTitle = sc.next(); for (idx = 0; idx < books.length; idx++) { if (bTitle.equals(books[idx].getBookTitle())) { break; } } if (idx == books.length) { System.out.println("본 도서관에는 해당 도서가 존재하지 않습니다"); } else { books[idx].checkIn(); } break; case 3: // for문을 이용해서 도서상태 출력 for (BookLib book : books) { book.printState(); } } } while (fn != 0); System.out.println("시스템종료"); } }
package com.kingfish.show.interceptor; import com.kingfish.show.bean.UserVO; import com.kingfish.show.constants.Cookies; import com.kingfish.show.mybatis.model.User; import com.kingfish.show.utils.CookieUtil; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; @Component public class RenderContextHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception { if (modelAndView == null) { return; } Map<String, Object> model = modelAndView.getModel(); //登录用户信息 Cookie uuid = CookieUtil.getCookieByName(request, Cookies.USER_TOKEN_ID); if (StringUtils.isEmpty(uuid)) { //未登录 model.put("isLogin", false); } else { User user = (User) request.getSession().getAttribute(uuid.getValue()); if (user == null) { model.put("isLogin", false); } else { model.put("isLogin", true); model.put("user", conver2VO(user)); } } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception { } private UserVO conver2VO(User user) { UserVO userVO = new UserVO(); userVO.setId(user.getId()); userVO.setUserName(user.getUsername()); userVO.setHeaderPicUrl(user.getHeaderPicUrl()); userVO.setSex(user.getSex().toString()); userVO.setEmail(user.getEmail()); userVO.setMobilePhoneNumber(user.getMobilePhoneNumber()); userVO.setSignature(user.getSignature()); userVO.setHideNickName(user.getHideNickName()); return userVO; } }
package com.example.rodoggx.deltachallenge.data; import com.example.rodoggx.deltachallenge.model.Post; import java.util.List; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by RodoggX on 2/2/2018. */ public class RemoteDataSource { public static final String BASE_URL = "https://jsonplaceholder.typicode.com/"; public static Retrofit create(){ return new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static Call<List<Post>> getResponse(){ Retrofit retrofit = create(); RemoteService remoteService = retrofit.create(RemoteService.class); return remoteService.getResponse(); } }
package com.library.bexam.common.pojo.model; /** * @Description 返回结果实体对象 * @Author sunchao * @Date: 2017-11-29 14:43 * @Mender: libing */ //@JsonInclude(NON_NULL) public final class Result { private int code = 0; private String msg; private Object result; public Result(){} /** * 构造方法 * @param statusCode 错误码 * @param msgInfo 提示信息 */ public Result(int statusCode,String msgInfo) { this.msg = msgInfo; this.code = statusCode; } public Result(int statusCode , Object result) { this(statusCode , result, ""); } public Result(int statusCode) { this(statusCode, "", ""); } public Result(Object result) { this(0,result, ""); } public Result( int statusCode,Object result, String msgInfo) { this.msg=msgInfo; this.code = statusCode; this.result = result; } public String getMsg() { return msg; } public void setMsg(String msg) { if(msg==null){ msg=""; }else { this.msg = msg; } } public int getCode() { return code; } public void setCode(int statusCode) { this.code = statusCode; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public enum Code{ NoSuchMethod(-2), Success(0), ParamError(-1), UnKnowError(-3); private Code(int value){ this.value = value; } private int value = 0; public int value(){ return value; } } }
package org.b.f; import java.util.Random; public final class d implements c { private a vKU = new a(); public final String getNonce() { return String.valueOf(cKF().longValue() + ((long) Integer.valueOf(new Random().nextInt()).intValue())); } public final String cKE() { return String.valueOf(cKF()); } private static Long cKF() { return Long.valueOf(Long.valueOf(System.currentTimeMillis()).longValue() / 1000); } }
package thsst.calvis.configuration.model.exceptions; /** * Created by Goodwin Chua on 2/21/2016. */ public class MissingSizeDirectiveException extends Exception { public MissingSizeDirectiveException(String address, int line) { super("Missing size directive for memory token: [" + address + "] at line number: " + line); } }
package com.csi.csi_organiser; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.android.gms.auth.api.Auth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class MainActivity extends AppCompatActivity { private Button mSignUpBtn; private Button mAlready; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSignUpBtn = (Button) findViewById(R.id.SignUpBtn); mAlready = (Button)findViewById(R.id.button); mSignUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent DataEntry = new Intent(MainActivity.this,HomeActivity.class); startActivity(DataEntry); } }); mAlready.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent Signin = new Intent(MainActivity.this,GSignin.class); startActivity(Signin); } }); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.core.Config; import com.openkm.core.DatabaseException; import com.openkm.core.MimeTypeConfig; import com.openkm.dao.CronTabDAO; import com.openkm.dao.bean.CronTab; import com.openkm.module.common.CommonAuthModule; import com.openkm.principal.PrincipalAdapterException; public class CronTabUtils { private static Logger log = LoggerFactory.getLogger(CronTabUtils.class); /** * Create internal cron tasks */ public static void createOrUpdate(String name, String expression, String content) throws DatabaseException, PrincipalAdapterException { log.debug("createOrUpdate({}, {}, {})", new Object[] { name, expression, content }); CronTab ct = CronTabDAO.findByName(name); if (ct == null) { String mail = CommonAuthModule.getMail(Config.ADMIN_USER); ct = new CronTab(); ct.setActive(true); ct.setExpression(expression); ct.setFileContent(SecureStore.b64Encode(content.getBytes())); ct.setFileMime(MimeTypeConfig.MIME_BSH); ct.setFileName(toFileName(name) + ".bsh"); ct.setName(name); if (mail != null && !mail.equals("")) { ct.setMail(mail); } else { ct.setMail(Config.DEFAULT_CRONTAB_MAIL); } CronTabDAO.create(ct); } else { ct.setFileContent(SecureStore.b64Encode(content.getBytes())); ct.setFileMime(MimeTypeConfig.MIME_BSH); ct.setFileName(toFileName(name) + ".bsh"); CronTabDAO.update(ct); } log.debug("createOrUpdate: void"); } /** * Change "Text Extractor Worker" or "Text extractor worker" to "TextExtractorWorker". */ private static String toFileName(String str) { StringBuilder sb = new StringBuilder(); boolean toUpper = true; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == ' ') { toUpper = true; continue; } else if (toUpper) { sb.append(Character.toUpperCase(c)); toUpper = false; } else { sb.append(c); } } return sb.toString(); } }
package com.greenglobal.eoffice.domain.application.congvandi.commands.update; import com.greenglobal.eoffice.domain.core.entities.ItemCommand; /** * Ký duyệt công văn đi */ public class KyDuyetCongVanDiCmd extends ItemCommand { /** * Trạng thái ký duyệt */ private int trangThai; /** * Get trangThai ký duyệt. * @return * 2: Lãnh đạo phòng ban chủ trì ký duyệt. * 3: Lãnh đạo phòng ban phối hợp ký duyệt. * 4: Thư ký ký duyệt. * 5: Lãnh đạo đơn vị ký duyệt. */ public int getTrangThai() { return this.trangThai; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package core.fuzzy; import java.util.List; import java.util.Random; /** * * @author Rogerio */ public class InputFuzzy { private int id_review; private double autor_reputation; private double padroes; private double corretude; private String avaliacaoManual; private double valorFuzzy; public double getValorFuzzy() { return valorFuzzy; } public void setValorFuzzy(double valorFuzzy) { this.valorFuzzy = valorFuzzy; } public InputFuzzy(String input, boolean autorAleatorio) { String[] splited = input.split("\t"); // this.autor_reputation = Double.parseDouble(splited[0]); if (autorAleatorio) { Random gerador = new Random(); this.autor_reputation = gerador.nextDouble() * 9; // [0,100[; } else { this.autor_reputation = Double.parseDouble(splited[0]); } this.padroes = Double.parseDouble(splited[1]); this.corretude = Double.parseDouble(splited[2].replace(',', '.')); } public InputFuzzy(String input) { String[] splited = input.split("\t"); // this.autor_reputation = Double.parseDouble(splited[0]); this.id_review = Integer.parseInt(splited[0]); this.autor_reputation = Double.parseDouble(splited[1]); this.padroes = Double.parseDouble(splited[2]); this.corretude = Double.parseDouble(splited[3].replace(',', '.')); this.avaliacaoManual = splited[4]; } public InputFuzzy(double autor_reputation, double padroes, double corretude) { this.autor_reputation = autor_reputation; this.padroes = padroes; this.corretude = corretude; } public InputFuzzy(){} public int getId_review() { return id_review; } public void setId_review(int id_review) { this.id_review = id_review; } /** * @return the autor_reputation */ public double getAutor_reputation() { return autor_reputation; } /** * @param autor_reputation the autor_reputation to set */ public void setAutor_reputation(double autor_reputation) { this.autor_reputation = autor_reputation; } /** * @return the padroes */ public double getPadroes() { return padroes; } /** * @param padroes the padroes to set */ public void setPadroes(double padroes) { this.padroes = padroes; } /** * @return the corretude */ public double getCorretude() { return corretude; } /** * @param corretude the corretude to set */ public void setCorretude(double corretude) { this.corretude = corretude; } public static String toARFF(List<InputFuzzy> valores) { String cabecalho = "@relation Opinions\n\n " + "@attribute autor numeric\n" + "@attribute padroes numeric\n" + "@attribute corretude numeric\n" + "@attribute class {IF,SF,BM,PL}\n" + "@data\n"; String data = ""; for(InputFuzzy ipf: valores){ data = data + ipf.getAutor_reputation() +","+ipf.getPadroes() + ","+ipf.getCorretude() + "," +ipf.getAvaliacaoManual()+"\n"; } return cabecalho + data; } @Override public String toString() { return this.autor_reputation + "\t" + this.padroes + "\t" + this.corretude; } public String getAvaliacaoManual() { return avaliacaoManual; } public void setAvaliacaoManual(String avaliacaoManual) { this.avaliacaoManual = avaliacaoManual; } }
package com.steatoda.commons.fields.demo.model.person; import com.steatoda.commons.fields.service.async.Batcher; /** Base class for all person batchers */ public class PersonBatcherBase extends Batcher<String, Person, Person.Field> { public PersonBatcherBase(PersonAsyncService service) { super(service); } }
package com.ds.weatherapp.control; import com.ds.weatherapp.bean.IWeatherModel; import com.ds.weatherapp.bean.Weather; import com.ds.weatherapp.bean.WeatherModelImpl; import com.ds.weatherapp.view.IWeatherView; public class WeatherControlImpl implements IWeatherControl,OnWeatherListener { private IWeatherView weatherView; private IWeatherModel weatherModel; public WeatherControlImpl(IWeatherView weatherView) { this.weatherView = weatherView; this.weatherModel = new WeatherModelImpl(); } @Override public void OnSuccess(Weather weather) { // TODO Auto-generated method stub weatherView.hideLoading(); weatherView.setWeatherInfo(weather); } @Override public void OnError() { // TODO Auto-generated method stub weatherView.hideLoading(); weatherView.showError(); } @Override public void getWeather(String cityNo) { // TODO Auto-generated method stub weatherView.showLoading(); weatherModel.loadWeather(cityNo, this); } }
package vms; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; import org.springframework.http.MediaType; import org.springframework.web.util.UriComponentsBuilder; /** * @author sasa */ public class MethodRT { public static List<City> getCities() { List<City> toReturn = new ArrayList<>(); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://api.meetup.com/2/cities") .queryParam("country", "rs"); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> response = restTemplate.exchange( builder.toUriString(), HttpMethod.GET, entity, String.class); return toReturn; } }
package com.module.helpers; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import net.coobird.thumbnailator.Thumbnails; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ImageConverter { public static Image convertBytesToImage(byte[] imageBytes) { if (imageBytes != null) { ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes); return new Image(bis); } return null; } public static byte[] convertImageToBytes(Image image) { if (image != null) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { BufferedImage originalImage = SwingFXUtils.fromFXImage(image, null); BufferedImage bImage = Thumbnails.of(originalImage) .size(150, 200) .outputQuality(0.8) .asBufferedImage(); ImageIO.write(bImage, "png", byteArrayOutputStream); byte[] res = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); return res; } catch (IOException e) { } } return null; } }
package com.dyny.gms.db.pojo; import java.math.BigDecimal; import java.util.Date; public class Basis { private Integer id; private String machNo; private Boolean state; private Integer sysMode; private Boolean proMode; private BigDecimal lankLevel; private BigDecimal cabinetTemperature; private BigDecimal stCurrent; private BigDecimal externalTemperature; private BigDecimal stVoltage; private BigDecimal alVoltage; private Boolean cityElectricity; private Boolean cabinetState; private Date stTime; private String startTime; private String endTime; private String verNo; private BigDecimal startVoltage; private BigDecimal sumPower; private String numTime; private String onTime; private String maintainTime; private BigDecimal mainboardTemperature; private Date interTime; private BigDecimal stCo; private String stCoordinate; private BigDecimal outputVoltage; private Boolean loadMode; private String item3; private String item4; private String item5; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMachNo() { return machNo; } public void setMachNo(String machNo) { this.machNo = machNo == null ? null : machNo.trim(); } public Boolean getState() { return state; } public void setState(Boolean state) { this.state = state; } public Integer getSysMode() { return sysMode; } public void setSysMode(Integer sysMode) { this.sysMode = sysMode; } public Boolean getProMode() { return proMode; } public void setProMode(Boolean proMode) { this.proMode = proMode; } public BigDecimal getLankLevel() { return lankLevel; } public void setLankLevel(BigDecimal lankLevel) { this.lankLevel = lankLevel; } public BigDecimal getCabinetTemperature() { return cabinetTemperature; } public void setCabinetTemperature(BigDecimal cabinetTemperature) { this.cabinetTemperature = cabinetTemperature; } public BigDecimal getStCurrent() { return stCurrent; } public void setStCurrent(BigDecimal stCurrent) { this.stCurrent = stCurrent; } public BigDecimal getExternalTemperature() { return externalTemperature; } public void setExternalTemperature(BigDecimal externalTemperature) { this.externalTemperature = externalTemperature; } public BigDecimal getStVoltage() { return stVoltage; } public void setStVoltage(BigDecimal stVoltage) { this.stVoltage = stVoltage; } public BigDecimal getAlVoltage() { return alVoltage; } public void setAlVoltage(BigDecimal alVoltage) { this.alVoltage = alVoltage; } public Boolean getCityElectricity() { return cityElectricity; } public void setCityElectricity(Boolean cityElectricity) { this.cityElectricity = cityElectricity; } public Boolean getCabinetState() { return cabinetState; } public void setCabinetState(Boolean cabinetState) { this.cabinetState = cabinetState; } public Date getStTime() { return stTime; } public void setStTime(Date stTime) { this.stTime = stTime; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime == null ? null : startTime.trim(); } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime == null ? null : endTime.trim(); } public String getVerNo() { return verNo; } public void setVerNo(String verNo) { this.verNo = verNo == null ? null : verNo.trim(); } public BigDecimal getStartVoltage() { return startVoltage; } public void setStartVoltage(BigDecimal startVoltage) { this.startVoltage = startVoltage; } public BigDecimal getSumPower() { return sumPower; } public void setSumPower(BigDecimal sumPower) { this.sumPower = sumPower; } public String getNumTime() { return numTime; } public void setNumTime(String numTime) { this.numTime = numTime == null ? null : numTime.trim(); } public String getOnTime() { return onTime; } public void setOnTime(String onTime) { this.onTime = onTime == null ? null : onTime.trim(); } public String getMaintainTime() { return maintainTime; } public void setMaintainTime(String maintainTime) { this.maintainTime = maintainTime == null ? null : maintainTime.trim(); } public BigDecimal getMainboardTemperature() { return mainboardTemperature; } public void setMainboardTemperature(BigDecimal mainboardTemperature) { this.mainboardTemperature = mainboardTemperature; } public Date getInterTime() { return interTime; } public void setInterTime(Date interTime) { this.interTime = interTime; } public BigDecimal getStCo() { return stCo; } public void setStCo(BigDecimal stCo) { this.stCo = stCo; } public String getStCoordinate() { return stCoordinate; } public void setStCoordinate(String stCoordinate) { this.stCoordinate = stCoordinate == null ? null : stCoordinate.trim(); } public BigDecimal getOutputVoltage() { return outputVoltage; } public void setOutputVoltage(BigDecimal outputVoltage) { this.outputVoltage = outputVoltage; } public Boolean getLoadMode() { return loadMode; } public void setLoadMode(Boolean loadMode) { this.loadMode = loadMode; } public String getItem3() { return item3; } public void setItem3(String item3) { this.item3 = item3 == null ? null : item3.trim(); } public String getItem4() { return item4; } public void setItem4(String item4) { this.item4 = item4 == null ? null : item4.trim(); } public String getItem5() { return item5; } public void setItem5(String item5) { this.item5 = item5 == null ? null : item5.trim(); } }
package com.basicNLP.tf_idf; import com.basicNLP.preprocesser.PreprocessorBasic; import com.basicNLP.preprocesser.Preprocessor; import com.basicNLP.domain.SingularDocument; import com.basicNLP.stemmers.PorterStem; import com.basicNLP.stemmers.Stemmer; import java.io.IOException; import java.util.*; public class TfIdf { private Double cutoffParameter = 0.0; //This can be set to different values for different selectivity (more or less keywords) private HashMap<String, Integer> corpusFrequency = new HashMap<>(); public TfIdf(Double cutoff) { cutoffParameter=cutoff; } private Map<String, Integer> tf(List<String> doc) { Map<String, Integer> frequency = new HashMap<>(); for (String s : doc) { if (frequency.containsKey(s)) frequency.put(s, frequency.get(s) + 1); else { frequency.put(s, 1); if (corpusFrequency.containsKey(s)) corpusFrequency.put(s, corpusFrequency.get(s) + 1); else corpusFrequency.put(s, 1); } } return frequency; } private double idf(Integer size, Integer frequency) { return Math.log(size.doubleValue() / frequency.doubleValue() + 1.0); } private List<String> analyze(String text, Stemmer stemmer, Preprocessor preprocessor) throws IOException { text = preprocessText(text, preprocessor); List<String> auxText= new ArrayList<>(); for (String s:text.split(" ")) { auxText.add(stemmer.stem(s)+" "); } return auxText; } public Map<String, Map<String, Double>> computeTFIDF(List<SingularDocument> corpus, Stemmer stemmer, Preprocessor preprocessor) throws IOException { List<List<String>> docs = new ArrayList<>(); for (SingularDocument r : corpus) { docs.add(analyze(r.getText(),stemmer, preprocessor)); } List<Map<String, Double>> res = tfIdf(docs); int counter = 0; return tfIdfMatrix(corpus, res, counter); } private Map<String, Map<String, Double>> tfIdfMatrix(List<SingularDocument> corpus, List<Map<String, Double>> res, int counter) { Map<String, Map<String, Double>> ret = new HashMap<>(); for (SingularDocument r : corpus) { ret.put(r.getId(), res.get(counter)); counter++; } return ret; } private List<Map<String, Double>> tfIdf(List<List<String>> docs) { List<Map<String, Double>> tfidfComputed = new ArrayList<>(); List<Map<String, Integer>> wordBag = new ArrayList<>(); for (List<String> doc : docs) { wordBag.add(tf(doc)); } int i = 0; for (List<String> doc : docs) { HashMap<String, Double> aux = new HashMap<>(); for (String s : doc) { Double idf = idf(docs.size(), corpusFrequency.get(s)); Integer tf = wordBag.get(i).get(s); Double tfidf = idf * tf; if (tfidf >= cutoffParameter && s.length() > 1) aux.put(s, tfidf); } tfidfComputed.add(aux); ++i; } return tfidfComputed; } private String preprocessText(String text, Preprocessor preprocessor) throws IOException { text = preprocessor.preprocess(text); return text; } public HashMap<String, Integer> getCorpusFrequency() { return corpusFrequency; } public void setCorpusFrequency(HashMap<String, Integer> corpusFrequency) { this.corpusFrequency = corpusFrequency; } public Double getCutoffParameter() { return cutoffParameter; } public void setCutoffParameter(Double cutoffParameter) { this.cutoffParameter = cutoffParameter; } // To test the algorithm and basic usage public static void main(String[] args) throws IOException { List<SingularDocument> sing=new ArrayList<>(); sing.add(new SingularDocument("1","This is example phrase 1")); sing.add(new SingularDocument("2","I am a new example")); sing.add(new SingularDocument("3","The following phrase is also an [word] example")); TfIdf tfidf=new TfIdf(1.0); Map<String, Map<String, Double>> result=tfidf.computeTFIDF(sing,new PorterStem(),new PreprocessorBasic()); for (String aux:result.get("3").keySet()) { System.out.println(aux+" "+result.get("3").get(aux)); } } }
package com.udacity.gradle.builditbigger; import android.support.test.runner.AndroidJUnit4; import android.support.test.rule.ActivityTestRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.core.IsNot.not; @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public final ActivityTestRule<MainActivity> mainActivityActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void asyncTest() { onView(withId(R.id.joke_button)).perform(click()); //test to confirm textView isn't an empty string //inspired by https://stackoverflow.com/questions/46598149/test-a-textview-value-is-not-empty-using-espresso-and-fail-if-a-textview-value-i/46598289#46598289 onView(withId(R.id.joke_text_view)).check(matches(not(withText("")))); } }
/** * @file: com.innovail.trouble.graphics - GameColor.java * @date: Jun 20, 2013 * @author: berndmicweber */ package com.innovail.trouble.graphics; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.badlogic.gdx.graphics.Color; /** * */ public class GameColor extends Color { private static final Map <String, Color> _ColorMap; static { _ColorMap = new HashMap <String, Color> (); _ColorMap.put ("black", Color.BLACK); _ColorMap.put ("blue", Color.BLUE); _ColorMap.put ("clear", Color.CLEAR); _ColorMap.put ("cyan", Color.CYAN); _ColorMap.put ("dark_blue", new Color (0.0f, 0.0f, 0.25f, 1.0f)); _ColorMap.put ("dark_clear_blue", new Color (0.0f, 0.0f, 0.25f, 0.5f)); _ColorMap.put ("dark_cyan", new Color (0.0f, 0.25f, 0.25f, 1.0f)); _ColorMap.put ("dark_green", new Color (0.0f, 0.25f, 0.0f, 1.0f)); _ColorMap.put ("dark_grey", Color.DARK_GRAY); _ColorMap.put ("dark_magenta", new Color (0.25f, 0.0f, 0.25f, 1.0f)); _ColorMap.put ("dark_red", new Color (0.25f, 0.0f, 0.0f, 1.0f)); _ColorMap.put ("dark_yellow", new Color (0.25f, 0.25f, 0.0f, 1.0f)); _ColorMap.put ("gray", Color.GRAY); _ColorMap.put ("green", Color.GREEN); _ColorMap.put ("light_grey", Color.LIGHT_GRAY); _ColorMap.put ("magenta", Color.MAGENTA); _ColorMap.put ("orange", Color.ORANGE); _ColorMap.put ("pink", Color.PINK); _ColorMap.put ("red", Color.RED); _ColorMap.put ("white", Color.WHITE); _ColorMap.put ("yellow", Color.YELLOW); } public static Color getColor (final String name) { if (_ColorMap.containsKey (name.toLowerCase ())) { return _ColorMap.get (name.toLowerCase ()); } return Color.BLACK; } public static Map <String, Color> getColorMap () { return _ColorMap; } public static String getColorName (final Color color) { for (final Entry <String, Color> entry : _ColorMap.entrySet ()) { final Color currentColor = entry.getValue (); if (color.equals (currentColor)) { return entry.getKey (); } } return null; } /** * */ public GameColor () { super (); } /** * @param color */ public GameColor (final Color color) { super (color); } /** * @param r * @param g * @param b * @param a */ public GameColor (final float r, final float g, final float b, final float a) { super (r, g, b, a); } public GameColor (final String name) { super (getColor (name)); } @Override public boolean equals (final Object o) { if (this == o) { return true; } if (o == null || (getClass () != o.getClass () && Color.class != o.getClass ())) { return false; } final Color color = (Color) o; return toIntBits () == color.toIntBits (); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package photoorganizer; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * * @author LJ */ //Classe que contiene toda la informacion de la imagen: la imagen, su nombre, fecha, etc public class ImageInfo extends ImageView{ private File filePath; public ImageInfo(File filePath) throws FileNotFoundException { super(new Image(new FileInputStream(filePath))); this.filePath = filePath; } public File getFile(){ return this.filePath; } }
package com.weique.commonres.utils; import android.app.Activity; import android.content.pm.ActivityInfo; import com.luck.picture.lib.PictureSelector; import com.luck.picture.lib.config.PictureConfig; import com.luck.picture.lib.config.PictureMimeType; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.listener.OnResultCallbackListener; import com.luck.picture.lib.style.PictureWindowAnimationStyle; import com.luck.picture.lib.tools.PictureFileUtils; import java.util.List; import me.jessyan.armscomponent.commonres.R; /** * 跳转到相册 或 相机 * * @author Administrator */ public class PictureSelectorUtils { /** * 跳转到 相册界面 需要 控制的 属性 自己拉到 参数中 或再创建一个 静态方法 * * @param activity activity * @param pictureMimeType 先择的资源类型 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio() * @param max max 最大数量 * @param previewVideo 是否可预览video * @param enableCrop 是否可裁剪 * @param medias 已选择的图片列表 * @param onResultCallbackListener onResultCallbackListener */ public static void gotoPhoto(Activity activity, int pictureMimeType, int max, boolean previewVideo, boolean enableCrop, List<LocalMedia> medias, OnResultCallbackListener onResultCallbackListener) { try { PictureSelector.create(activity) //全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio() .openGallery(pictureMimeType) //主题样式(不设置为默认样式) 也可参考demo values/styles下 例如:R.style.picture.white.style .theme(R.style.picture_default_style) // 动态自定义相册主题 注意:此方法最好不要与.theme();同时存在, 二选一 .setPictureStyle(SelectStyleUtil.getDefaultStyle(activity)) // 动态自定义裁剪主题 .setPictureCropStyle(SelectStyleUtil.getPictureCropParameterStyle(activity, SelectStyleUtil.getDefaultStyle(activity))) // 自定义相册启动退出动画 .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle()) // 外部传入图片加载引擎,必传项 参考Demo MainActivity中代码 .imageEngine(GlideEngine.createGlideEngine()) // 图片和视频是否可以同选,只在ofAll模式下有效 .isWithVideoImage(false) // 是否使用自定义相机,5.0以下请不要使用,可能会出现兼容性问题 .isUseCustomCamera(false) // 设置相册Activity方向,不设置默认使用系统 .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 是否显示原图控制按钮,如果用户勾选了 压缩、裁剪功能将会失效 .isOriginalImageControl(true) // 是否开启微信图片选择风格,此开关开启了才可使用微信主题!!! .isWeChatStyle(true) // 是否需要处理Android Q 拷贝至应用沙盒的操作,只针对compress(false); && .isAndroidQTransform(false) //有效 .isEnableCrop(enableCrop) // 自定义播放回调控制,用户可以使用自己的视频播放界面 //.bindCustomPlayVideoCallback(callback) // 多图裁剪时是否支持跳过,默认支持 .isMultipleSkipCrop(false) // 多图裁剪底部列表显示动画效果 .isMultipleRecyclerAnimation(false) // 设置语言,默认中文 //.setLanguage(language) // 最大图片选择数量 int .maxSelectNum(max) // 最小选择数量 int .minSelectNum(1) // 视频最小选择数量,如果没有单独设置的需求则可以不设置,同用minSelectNum字段 .minVideoSelectNum(1) // 视频最大选择数量,如果没有单独设置的需求则可以不设置,同用maxSelectNum字段 .maxVideoSelectNum(max) // 每行显示个数 int .imageSpanCount(4) // 未选择数据时点击按钮是否可以返回 .isReturnEmpty(true) // 预览图片长按是否可以下载 .isNotPreviewDownload(false) // 只查多少M以内的图片、视频、音频 单位M .queryMaxFileSize(25) //.querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源 //.cameraFileName("test.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用 //.renameCompressFile("test.png")// 重命名压缩文件名、 注意这个不要重复,只适用于单张图压缩使用 //.renameCropFileName("test.png")// 重命名裁剪文件名、 注意这个不要重复,只适用于单张图裁剪使用 //.isSingleDirectReturn(false)// 单选模式下是否直接返回,PictureConfig.SINGLE模式下有效 //.setTitleBarBackgroundColor()//相册标题栏背景色 //.isChangeStatusBarFontColor()// 是否关闭白色状态栏字体颜色 //.setStatusBarColorPrimaryDark()// 状态栏背景色 //.setUpArrowDrawable()// 设置标题栏右侧箭头图标 //.setDownArrowDrawable()// 设置标题栏右侧箭头图标 //.isOpenStyleCheckNumMode()// 是否开启数字选择模式 类似QQ相册 // 多选 or 单选 PictureCo.036nfig.MULTIPLE or PictureConfig.SINGLE .selectionMode(PictureConfig.MULTIPLE) // 是否可预览图片 true or false .isPreviewImage(true) // 是否可预览视频 true or false .isPreviewVideo(previewVideo) // 是否可播放音频 true or false .isEnablePreviewAudio(previewVideo) // 是否显示拍照按钮 true or false .isCamera(true) // 拍照保存图片格式后缀,默认jpeg .imageFormat(PictureMimeType.PNG) // 图片列表点击 缩放效果 默认true .isZoomAnim(true) // glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 //.sizeMultiplier(0.5f) // 设置圆形裁剪背景色值 //.setCircleDimmedColor() // 设置圆形裁剪边框色值 //.setCircleDimmedBorderColor() // 设置圆形裁剪边框粗细 //.setCircleStrokeWidth(3) // 是否压缩 true or false .isCompress(true) // int glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度 //.glideOverride(400, 400) // int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义 .withAspectRatio(1, 1) // 是否显示uCrop工具栏,默认不显示 true or false .hideBottomControls(true) // 是否显示gif图片 true or false .isGif(false) //压缩图片保存地址 //.compressSavePath(getPath()) // 裁剪框是否可拖拽 true or false .freeStyleCropEnabled(true) // 是否圆形裁剪 true or false .circleDimmedLayer(false) // 是否显示裁剪矩形边框 圆形裁剪时建议设为false true or false .showCropFrame(false) // 是否显示裁剪矩形网格 圆形裁剪时建议设为false true or false .showCropGrid(false) // 是否开启点击声音 true or false .isOpenClickSound(false) // // 是否传入已选图片 List<LocalMedia> list .selectionData(medias) // 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false .isPreviewEggs(true) // 废弃 改用cutOutQuality() //.cropCompressQuality(90) // 裁剪输出质量 默认100 .cutOutQuality(80) .compressQuality(60) // 小于100kb的图片不压缩 .minimumCompressSize(100) //同步true或异步false 压缩 默认同步 .synOrAsy(true) // 裁剪宽高比,设置如果大于图片本身宽高则无效 //.cropImageWideHigh(1,1) // 裁剪是否可旋转图片 true or false //.rotateEnabled(true) // 裁剪是否可放大缩小图片 true or false //.scaleEnabled(true) // 视频录制质量 0 or 1 int .videoQuality(1) // 显示多少秒以内的视频or音频也可适用 int .videoMaxSecond(20) // 显示多少秒以内的视频or音频也可适用 int .videoMinSecond(5) //视频秒数录制 默认60s int .recordVideoSecond(19) // 是否可拖动裁剪框(固定) .isDragFrame(false) .forResult(PictureConfig.CHOOSE_REQUEST, onResultCallbackListener); } catch (Exception e) { e.printStackTrace(); } } /** * 单独拍照 * * @param activity activity * @param onResultCallbackListener onResultCallbackListener */ public static void justTakePhotos(Activity activity, OnResultCallbackListener onResultCallbackListener) { PictureSelector.create(activity) .openCamera(PictureMimeType.ofImage()) .imageEngine(GlideEngine.createGlideEngine()) .forResult(onResultCallbackListener); } /** * 缓存清除 */ public static void cacheClearAll(Activity activity) { //包括裁剪和压缩后的缓存,要在上传成功后调用,type 指的是图片or视频缓存取决于你设置的ofImage或ofVideo 注意:需要系统sd卡权限 // PictureFileUtils.deleteCacheDirFile(activity, type); // 清除所有缓存 例如:压缩、裁剪、视频、音频所生成的临时文件 PictureFileUtils.deleteAllCacheDirFile(activity); } }
package io.dashapp.dashembed; import android.app.Fragment; public interface DASHFragmentEventListener { /** * Called each time an error occurs in the DASH fragment * * @param dashFragment The DASH fragment that had the error * @param errorCode The errorCode (passed through from WebViewClient) * @param errorDescription A description of the error */ void onReceivedError(Fragment dashFragment, int errorCode, String errorDescription); }
package pl.edu.pw.mini.gapso.optimizer.restart; import org.junit.Test; import pl.edu.pw.mini.gapso.function.Function; import pl.edu.pw.mini.gapso.function.SingleStepFunction; import pl.edu.pw.mini.gapso.optimizer.restart.threshold.FunctionValueSpreadRestartManager; public class FunctionValueSpreadRestartManagerTest { @Test public void shouldBeRestarted() { Function function = new SingleStepFunction(); boolean[] restarts = new boolean[]{ false, true, true, true, true, false }; RestartManager observer = new FunctionValueSpreadRestartManager(RestartScheme.BORDERLINE_CASE_THRESHOLD); RestartScheme.ValidateRestartManagerAgainstRestartsScheme(function, RestartScheme.samples, restarts, observer); } }
package kr.co.jboard2.service; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import kr.co.jboard2.dao.ArticleDao; import kr.co.jboard2.vo.ArticleVO; public class WriteService implements CommonService { private String path = null; @Override public String requestProc(HttpServletRequest req, HttpServletResponse resp) { if(req.getMethod().equals("GET")) { // Get return "/write.jsp"; }else { // Post MultipartRequest mRequest = getMultipartRequest(req); String uid = mRequest.getParameter("uid"); String title = mRequest.getParameter("title"); String content = mRequest.getParameter("content"); String fname = mRequest.getFilesystemName("fname"); String regip = req.getRemoteAddr(); ArticleVO vo = new ArticleVO(); vo.setTitle(title); vo.setContent(content); vo.setFile(fname == null ? 0 : 1); vo.setUid(uid); vo.setRegip(regip); int seq = ArticleDao.getInstance().insertArticle(vo); setFile(seq, fname, uid); return "redirect:/JBoard2/list.do"; } }// requestProc end... public MultipartRequest getMultipartRequest(HttpServletRequest req) { MultipartRequest mRequest = null; try { // Multipart 객체 생성 path = req.getServletContext().getRealPath("/file"); int maxSize = 1024 * 1024 * 10; // 최대 파일 허용 용량 10MB mRequest = new MultipartRequest(req, path, maxSize, "UTF-8", new DefaultFileRenamePolicy()); }catch (Exception e) { e.printStackTrace(); } return mRequest; }// getMultipartRequest end... public void setFile(int seq, String fname, String uid) { if(fname != null){ // 고유한 파일 이름 생성하기 int i = fname.lastIndexOf("."); String ext = fname.substring(i); SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss_"); String now = sdf.format(new Date()); String newName = now+uid+ext; // 파일명 수정 스트림 작업 File oriFile = new File(path+"/"+fname); File newFile = new File(path+"/"+newName); oriFile.renameTo(newFile); // 파일 테이블 INSERT 작업 ArticleDao.getInstance().insertFile(seq, fname, newName); } } }// WriteService end...
package com.khachik.explore.Adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.khachik.explore.Activities.ArticleActivity; import com.khachik.explore.Models.ArticlesModel; import com.khachik.explore.R; import com.khachik.explore.Requests.Requests; import com.khachik.explore.utils.AddToTheSharedPrefs; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; import static com.khachik.explore.R.id.fab; public class ArticlesAdapter extends RecyclerView.Adapter<ArticlesAdapter.ViewHolder> { private AddToTheSharedPrefs addToTheSharedPrefs; private Requests request; private Context context; private ArrayList<ArticlesModel> adapterItems; private ArrayList<String> favoritesList; public static class ViewHolder extends RecyclerView.ViewHolder { CardView cardView; private final TextView artycleTitle; private final TextView artycleCity; private final TextView artycleCountry; private ImageView favorite; private final CircleImageView artycleImage; public ViewHolder(View view) { super(view); cardView = (CardView) view.findViewById(R.id.card_view); artycleTitle = (TextView) view.findViewById(R.id.artycle_title); artycleCity = (TextView) view.findViewById(R.id.artycle_city); artycleCountry = (TextView) view.findViewById(R.id.artycle_country); artycleImage = (CircleImageView) view.findViewById(R.id.artycle_image); favorite = (ImageView) view.findViewById(R.id.favorite); } } public ArticlesAdapter(ArrayList<ArticlesModel> adapterItems, Context context) { this.request = new Requests(context); this.context = context; this.adapterItems = adapterItems; } @Override public ArticlesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.artycles_card, parent, false); return new ArticlesAdapter.ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { this.addToTheSharedPrefs = AddToTheSharedPrefs.getInstance(); this.favoritesList = this.addToTheSharedPrefs.getFavorites(context); holder.artycleTitle.setText(adapterItems.get(position).getTitle()); holder.artycleCity.setText(adapterItems.get(position).getCity()); holder.artycleCountry.setText(adapterItems.get(position).getCountry()); if (!adapterItems.get(position).getWallpaper_image().isEmpty()) { request.getArticleWallpaper((ImageView)holder.artycleImage, adapterItems.get(position).getWallpaper_image()); } else { holder.artycleImage.setImageResource(R.mipmap.ic_launcher); } final String id = adapterItems.get(position).getId(); setFavButtonBackground(holder.favorite, id); holder.favorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(favoritesList.contains(id)) { addToTheSharedPrefs.removeFavorite(context, id); favoritesList.remove(id); holder.favorite.setImageResource(R.drawable.ic_heart); } else { addToTheSharedPrefs.addFavorite(context, id); favoritesList.add(id); holder.favorite.setImageResource(R.drawable.ic_fill_heart); } } }); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, "click", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, ArticleActivity.class); String res = "[{" + "'id': '" + adapterItems.get(position).getId() + "','title': '" + adapterItems.get(position).getTitle() + "','data':'" + adapterItems.get(position).getData() + "', 'wallpaper_image': '" + adapterItems.get(position).getWallpaper_image() + "', 'images_folder': '" + adapterItems.get(position).getImages_folder() + "','building_date':'" + adapterItems.get(position).getBuilding_date() + "', 'city': '" + adapterItems.get(position).getCity() + "','country':'" + adapterItems.get(position).getCountry() + "','latitude':'" + adapterItems.get(position).getLatitude() + "','longitude':'" + adapterItems.get(position).getLongitude() + "'}]"; intent.putExtra("respons", res); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } @Override public int getItemCount() { return adapterItems.size(); } private void setFavButtonBackground(ImageView favorit, String id) { System.out.println("FAB - " + id); if(this.favoritesList.contains(id)) { favorit.setImageResource(R.drawable.ic_fill_heart); } } public void callOnCreate(){ System.out.println("Caaled"); } }
package com.h2o.db; /** * This class is a single parsed object. * * @author Marcos Zalacain * @version 1.0 * Date created: 15/10/2013 * Last modified: 15/10/2013 18:30 * * TODO: */ public class XMLParserObject { private int QUESTION_NUMBER ; private String QUESTION_ENG; private String QUESTION_SPA; private String ANSWER1_ENG; private String ANSWER2_ENG; private String ANSWER3_ENG; private String ANSWER1_SPA; private String ANSWER2_SPA; private String ANSWER3_SPA; private int WRIGHT_ANSWER; //private int PLAYER_ANSWER; //private int TIME_TO_ANSWER; private int QUESTION_GRADE; //private int MESSAGE_TIME; public int getQUESTION_NUMBER() { return QUESTION_NUMBER; } public void setQUESTION_NUMBER(int qUESTION_NUMBER) { QUESTION_NUMBER = qUESTION_NUMBER; } public String getQUESTION_ENG() { return QUESTION_ENG; } public void setQUESTION_ENG(String qUESTION_ENG) { QUESTION_ENG = qUESTION_ENG; } public String getQUESTION_SPA() { return QUESTION_SPA; } public void setQUESTION_SPA(String qUESTION_SPA) { QUESTION_SPA = qUESTION_SPA; } public String getANSWER1_ENG() { return ANSWER1_ENG; } public void setANSWER1_ENG(String aNSWER1_ENG) { ANSWER1_ENG = aNSWER1_ENG; } public String getANSWER2_ENG() { return ANSWER2_ENG; } public void setANSWER2_ENG(String aNSWER2_ENG) { ANSWER2_ENG = aNSWER2_ENG; } public String getANSWER3_ENG() { return ANSWER3_ENG; } public void setANSWER3_ENG(String aNSWER3_ENG) { ANSWER3_ENG = aNSWER3_ENG; } public String getANSWER1_SPA() { return ANSWER1_SPA; } public void setANSWER1_SPA(String aNSWER1_SPA) { ANSWER1_SPA = aNSWER1_SPA; } public String getANSWER2_SPA() { return ANSWER2_SPA; } public void setANSWER2_SPA(String aNSWER2_SPA) { ANSWER2_SPA = aNSWER2_SPA; } public String getANSWER3_SPA() { return ANSWER3_SPA; } public void setANSWER3_SPA(String aNSWER3_SPA) { ANSWER3_SPA = aNSWER3_SPA; } public int getWRIGHT_ANSWER() { return WRIGHT_ANSWER; } public void setWRIGHT_ANSWER(int wRIGHT_ANSWER) { WRIGHT_ANSWER = wRIGHT_ANSWER; } public int getQUESTION_GRADE() { return QUESTION_GRADE; } public void setQUESTION_GRADE(int qUESTION_GRADE) { QUESTION_GRADE = qUESTION_GRADE; } @Override public String toString() { return QUESTION_ENG; } }
/** * Created by 204026705 on 11/11/2016. */ import java.util.Collection; import java.util.HashMap; /** * Created by 212590934 on 11/11/2016. */ public class Customer { private String ownerDuns; private String ownerName; private HashMap<Double, Plant> plants = new HashMap<>(); public String getOwnerDuns() { return ownerDuns; } public void setOwnerDuns(String ownerDuns) { this.ownerDuns = ownerDuns; } public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public HashMap<Double, Plant> retrievePlantsMap() { return plants; } public Collection<Plant> getPlants() { return plants.values(); } public void setPlants(HashMap<Double, Plant> plants) { this.plants = plants; } }
package dailyPractice.jianzhi; public class Q11 { public int minArray1(int[] numbers) { int size = numbers.length; if (size == 1) return numbers[0]; for (int i = 0; i + 1 < size; i++) { if (numbers[i] > numbers[i + 1]) { return numbers[i + 1]; } } return numbers[0]; } // binary search public int minArray(int[] numbers) { int left = 0, right = numbers.length - 1; while (left < right) { int m = left + (right - left) / 2; if (numbers[m] > numbers[right]) left = m + 1; else if (numbers[m] < numbers[right]) right = m; else right--; } return numbers[left]; } }
/** * */ package fi.jjc.graphics.image; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; import fi.jjc.util.BundleHandler; /** * * @author Jens ┼kerblom */ public enum TextureWrap { /** Wrapping constant for GL_CLAMP. */ WRAP_CLAMP(GL11.GL_CLAMP, BundleHandler.getName("WRAP_CLAMP")), //$NON-NLS-1$ /** Wrapping constant for GL_REPEAT (standard for all coordinates). */ WRAP_REPEAT(GL11.GL_REPEAT, BundleHandler.getName("WRAP_REPEAT")), //$NON-NLS-1$ /** Wrapping constant for GL_CLAMP_TO_EDGE. */ WRAP_CLAMP_TO_EDGE(GL12.GL_CLAMP_TO_EDGE, BundleHandler.getName("WRAP_CLAMP_TO_EDGE")), //$NON-NLS-1$ /** Wrapping constant for GL_CLAMP_TO_BORDER. */ WRAP_CLAMP_TO_BORDER(GL13.GL_CLAMP_TO_BORDER, BundleHandler.getName("WRAP_CLAMP_TO_BORDER")), //$NON-NLS-1$ /** Wrapping constant for GL_MIRRORED_REPEAT. */ WRAP_MIRRORED_REPEAT(GL14.GL_MIRRORED_REPEAT, BundleHandler.getName("WRAP_MIRRORED_REPEAT")); //$NON-NLS-1$ /** * OpenGL's integer version of this constant. */ private final int glConstant; /** * Locale specific name. */ private final String name; /** * Constructor. * * @param glConstant * OpenGL's version. * @param name * locale specific name. */ private TextureWrap(int glConstant, String name) { this.glConstant = glConstant; this.name = name; } /** * @return OpenGL's integer constant for this. */ public int getGlConstant() { return this.glConstant; } /** * @see java.lang.Enum#toString() */ @Override public String toString() { return this.name; } /** * Gets the buffer constant representing the OpenGL's integer constant. * * @param glIntConstant * OpenGL's integer constant. * @return the constant or null if not valid OpenGL constant. */ public static TextureWrap fromGL(int glIntConstant) { switch (glIntConstant) { case GL11.GL_CLAMP: return WRAP_CLAMP; case GL11.GL_REPEAT: return WRAP_REPEAT; case GL12.GL_CLAMP_TO_EDGE: return WRAP_CLAMP_TO_EDGE; case GL13.GL_CLAMP_TO_BORDER: return WRAP_CLAMP_TO_BORDER; case GL14.GL_MIRRORED_REPEAT: return WRAP_MIRRORED_REPEAT; default: return null; } } }
package com.baitap; import java.sql.Array; import java.util.Scanner; public class NumberToString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); String string = String.valueOf(number); int arr[] = new int[string.length()]; int out = number; int count = 0; while (out != 0){ int temp = out%10; arr[count] = temp; count++; out = out / 10; } int first = 0; int last = arr.length-1; while(first < last){ int temp = arr[first]; arr[first] = arr[last]; arr[last] = temp; first++; last--; } String donvi[] = {"one","two","three","four","five","six","seven","eight","nine"}; String chuc[] = {"ten","eleven","Twen", "thir", "four", "fif", "six","seven", "eigh", "nine"}; if(arr.length == 1) { System.out.println(donvi[arr[0]-1]); } else if(arr.length == 2 && number < 20) { if(number>=10 && number < 12){ System.out.println(chuc[arr[1]]); } else if(number == 12){ System.out.println("twelve"); } else { System.out.println(chuc[arr[1]] + "teen"); } } else if(arr.length == 2 && number >= 20){ if(number ==20){ System.out.println("Twenty"); } else if(arr[1] !=0 ) { System.out.println((chuc[arr[0]]) + "ty" + " " + donvi[arr[1]-1]); } else { System.out.println((chuc[arr[0]]) + "ty"); } } else if(arr.length == 3 && number >= 100){ if(arr[1] == 0 && arr[2] !=0 ){ System.out.println(donvi[arr[0]-1] + " hundred" + " and " +donvi[arr[2]-1] ); } else if(arr[1] == 1){ if(arr[2] == 0 || arr[2] == 1){ System.out.println(donvi[arr[0]-1] + " hundred" + " and " +chuc[arr[2]] ); } else if(arr[2] == 2){ System.out.println(donvi[arr[0]-1] + " hundred" + " and "+ " Twelve "); } else { System.out.println(donvi[arr[0]-1] + " hundred" + " and " + chuc[arr[2]] + "teen"); } } else if(arr[1] ==0 && arr[2] ==0){ System.out.println(donvi[arr[0]-1] + " hundred"); } else { if(arr[2] !=0 ) { System.out.println(donvi[arr[0] - 1] + " hundred" + " and " + (chuc[arr[1]]) + "ty" + " " + donvi[arr[2] - 1]); } else { System.out.println(donvi[arr[0] - 1] + " hundred" + " and " + (chuc[arr[1]]) + "ty" ); } } } } }
package be.thomaswinters.goofer.data.exceptions; import be.thomaswinters.goofer.data.Template; public class UnextractableStringException extends RuntimeException { /** * */ private static final long serialVersionUID = -8465421598659417081L; public UnextractableStringException(String argument, Template template) { super("Given string \"" + argument + "\" can be converted to template values of template " + template); } public UnextractableStringException(String message) { super(message); } public UnextractableStringException(String message, Exception otherException) { super(message, otherException); } }
package controller.cart; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.jdo.PersistenceManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; import controller.PMF; import model.entity.Cart; @SuppressWarnings("serial") public class CartControllerAdd extends HttpServlet{ @SuppressWarnings("unchecked") public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { User user = UserServiceFactory.getUserService().getCurrentUser(); PersistenceManager pm = PMF.get().getPersistenceManager(); if (user == null) { resp.sendRedirect("/user/login"); } else { String idUser = user.getUserId(); Long idProduct = new Long(req.getParameter("idproduct")).longValue(); String query = "SELECT FROM " + Cart.class.getName(); List<Cart> carts = (List<Cart>)pm.newQuery(query).execute(); List<Cart> cartUser=new ArrayList<Cart>(); for (Cart cart : carts) { if(cart.getIdUser().equals(idUser)){ cartUser.add(cart); } } boolean seAņadio=false; if (!cartUser.isEmpty()) { for (int i = 0; i < cartUser.size(); i++) { if(cartUser.get(i).getIdProduct().equals(idProduct)){ cartUser.get(i).addingProduct(); seAņadio=true; } } } if(!seAņadio){ Cart cart = new Cart(idProduct, idUser); cart.addingProduct(); pm.makePersistent(cart); } } pm.close(); resp.sendRedirect("/cart"); } }