text stringlengths 10 2.72M |
|---|
package boletin75;
/**
*
* @author mgonzalezlorenzo
*/
public class Boletin75 {
public static void main(String[] args) {
int num1, num2, num3;
Comparacion obx=new Comparacion();
num1=obx.pedirNumero();
num2=obx.pedirNumero();
num3=obx.pedirNumero();
obx.compararNumeros(num1, num2, num3);
}
}
|
package com.example.sypark9646.item20.interface_default_method;
public class Cat implements Animal {
@Override
public String jump() {
return "cat is jumping";
}
}
|
package com.example.hyunyoungpark.imagedownloadasynctask;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
EditText selectiontext;
ListView chooseImageList;
String[] listofImages;
ProgressBar downloadImageProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedownload);
selectiontext = (EditText) findViewById(R.id.urlselectionText);
chooseImageList = (ListView) findViewById(R.id.chooseImageList);
downloadImageProgress = (ProgressBar) findViewById(R.id.downloadProgress);
listofImages = getResources().getStringArray(R.array.imageuris);
chooseImageList.setOnItemClickListener(this);
}
public void downloadImage(View view) {
if (selectiontext.getText().toString() != null
&& (selectiontext.getText().toString().length()) > 0) {
// create instance of subClass (MyTask).
MyTask1 task1 = new MyTask1();
// call method execute() on it and it accepts text read from textview as parameter.
task1.execute(selectiontext.getText().toString());
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectiontext.setText(listofImages[position]);
}
class MyTask1 extends AsyncTask<String,Integer,Boolean> {
@Override
protected void onPreExecute() {
downloadImageProgress.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(String... params) {
// Ceate an instance of URL, HttpURLConnection, InputStream, FileOutputStream,File class
URL url = null;
HttpURLConnection urlCon = null;
InputStream input = null;
FileOutputStream output = null;
String saveFileName = new SimpleDateFormat("yyyyMMddHHmm'.png'").format(new Date());
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/" + saveFileName);
boolean success = false;
try {
url = new URL(params[0].toString());
urlCon = (HttpURLConnection) url.openConnection();
urlCon.connect();
// Create a boolean variable successfull and set its intial value to false
if(urlCon.getResponseCode() != HttpURLConnection.HTTP_OK) {
return false;
}
int fileLength = urlCon.getContentLength();
input = urlCon.getInputStream();
output = openFileOutput(file.getName(), Context.MODE_APPEND);
byte[] b = new byte[2048];
int length;
long total = 0;
while ((length = input.read(b)) != -1) {
total += length;
if(fileLength > 0) {
publishProgress((int)(total * 100/ fileLength));
}
output.write(b, 0, length);
}
input.close();
output.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
success = false;
}
// if image download succesfully set it to true. return a boolean value of success
// Write a code that download the image from internet
// count how many bytes are downloded for that image and use this count to show the progress
return success;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//calculate the progress and show it on progressbar
downloadImageProgress.setProgress(values[0]);
}
@Override
protected void onPostExecute(Boolean aBoolean) {
//set visibility of progessbar to gone
downloadImageProgress.setVisibility(View.GONE);
}
}
} |
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddPromotionGoodsCouponListGetResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddPromotionGoodsCouponListGetRequest extends PopBaseHttpRequest<PddPromotionGoodsCouponListGetResponse>{
/**
* 页码,默认1
*/
@JsonProperty("page")
private Integer page;
/**
* 每页数量,默认100
*/
@JsonProperty("page_size")
private Integer pageSize;
/**
* 商品ID
*/
@JsonProperty("goods_id")
private Long goodsId;
/**
* 查询范围 0 全部,1 多多进宝券,2 无门槛商品券;默认1
*/
@JsonProperty("query_range")
private Integer queryRange;
/**
* 批次状态 1 领取中,2 已领完,3 已结束,4 已暂停
*/
@JsonProperty("batch_status")
private Integer batchStatus;
/**
* 排序 1 创建时间正序,2 创建时间倒序,3 开始时间正序,4 开始时间倒序,5 初始数量正序, 6 初始数量倒序,7 领取数量正序,8 领取数量倒序;默认2
*/
@JsonProperty("sort_by")
private Integer sortBy;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.promotion.goods.coupon.list.get";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddPromotionGoodsCouponListGetResponse> getResponseClass() {
return PddPromotionGoodsCouponListGetResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(page != null) {
paramsMap.put("page", page.toString());
}
if(pageSize != null) {
paramsMap.put("page_size", pageSize.toString());
}
if(goodsId != null) {
paramsMap.put("goods_id", goodsId.toString());
}
if(queryRange != null) {
paramsMap.put("query_range", queryRange.toString());
}
if(batchStatus != null) {
paramsMap.put("batch_status", batchStatus.toString());
}
if(sortBy != null) {
paramsMap.put("sort_by", sortBy.toString());
}
return paramsMap;
}
public void setPage(Integer page) {
this.page = page;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public void setQueryRange(Integer queryRange) {
this.queryRange = queryRange;
}
public void setBatchStatus(Integer batchStatus) {
this.batchStatus = batchStatus;
}
public void setSortBy(Integer sortBy) {
this.sortBy = sortBy;
}
} |
package com.apress.prospring.ch3;
import com.apress.prospring.ch3.DemoBean;
import com.apress.prospring.ch3.MyHelper;
//This class uses Method Injection for getting instance of MyHelper
public abstract class AbstractLookupDemoBean implements DemoBean {
public abstract MyHelper getMyHelper();
public void someOperation() {
getMyHelper().doSomethingHelpful();
}
}
|
package servlet;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import domain.Customer;
import domain.Order;
import domain.Receptionist;
import domain.Room;
import domain.TimeRange;
import service.OrderService;
import utils.DateValidator;
import utils.IdentityMap;
public class StaffEditOrderCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
String method = request.getParameter("method");
if (method.equals("search")) {
Order order = new Order();
order.setOrderId(Long.parseLong(request.getParameter("orderId")));
OrderService os = new OrderService();
List<Order> result = os.findOrder(order);
if (order.getStatus().equals("finish") &&
request.getSession().getAttribute("loggedUser").getClass()
==Receptionist.class) {
request.setAttribute("errorMsg", "Receptionist can only edit unfinished orders.");
forward("/jsp/staff/staffError.jsp");
return;
}
if (result.size() > 0) {
order = result.get(0);
request.setAttribute("order", order);
}
forward("/jsp/staff/staffManageCurrentOrders.jsp");
return;
}
else if (method.equals("update")) {
try {
Long orderId = Long.parseLong(request.getParameter("orderId"));
int customerId = Integer.parseInt(request.getParameter("customerId"));
int roomId = Integer.parseInt(request.getParameter("roomId"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date checkInTime = sdf.parse(request.getParameter("checkInTime"));
Date checkOutTime = sdf.parse(request.getParameter("checkOutTime"));
Date createTime = sdf.parse(request.getParameter("createTime"));
float sum = Float.parseFloat(request.getParameter("sum"));
String status = request.getParameter("status");
if (status.equals("cancel")) {
redirect("frontServlet?command=CancelOrder?orderId="+orderId);
return;
}
Order order = new Order();
order.setCreateTime(createTime);
Customer customer = new Customer();
customer.setCustomerId(customerId);
order.setCustomer(customer);
order.setOrderId(orderId);
Room room = new Room();
room.setRoomId(roomId);
order.setRoom(room);
order.setStatus(status);
order.setSum(sum);
TimeRange timerange = new TimeRange(checkInTime, checkOutTime);
order.setTimerange(timerange);
OrderService os = new OrderService();
boolean result = os.updateOrder(order, request.getSession().getId());
if (result) {
IdentityMap map = IdentityMap.getInstance(order);
map.put(order.getOrderId(), order);
request.setAttribute("successReason", "updated the order.");
forward("/jsp/staff/staffSuccess.jsp");
}
else {
request.setAttribute("errorMsg",
"Something going wrong when updating the order.");
forward("/jsp/staff/staffError.jsp");
}
} catch (ParseException e) {
request.setAttribute("errorMsg", e.getMessage());
forward("/jsp/staff/staffError.jsp");
}
}
else {
request.setAttribute("errorMsg", "Invalid method.");
forward("/jsp/staff/staffError.jsp");
}
}
}
|
package productManager.controller;
import net.minidev.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureDataJpa;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import productManager.service.evaluation.Evaluation;
import productManager.service.evaluation.EvaluationService;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(EvaluationController.class)
@AutoConfigureDataJpa
public class EvaluationControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private EvaluationService service;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void givenProducts_whenGetProducts_thenReturnJsonArray() throws Exception {
Evaluation evaluation= new Evaluation(11L,"Comentário",8);
List<Evaluation> allEvaluations = Arrays.asList(evaluation);
given(service.getAllEvaluations()).willReturn(allEvaluations);
mvc.perform(get("/evaluations/")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].commentary").value("Comentário"));
}
@Test
public void whenpostProduct_thenReturnCreated() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("commentary", "Comentário");
jsonObject.put("score", 10.0);
mvc.perform(post("/evaluations/")
.contentType("application/json;charset=UTF-8")
.content(String.valueOf(jsonObject)))
.andDo(print())
.andExpect(status().isCreated());
}
@Test
public void whenputProduct_thenReturnOk() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("commentary", "Comentário");
jsonObject.put("score", 10.0);
mvc.perform(put("/evaluations/{id}", 1L)
.contentType("application/json;charset=UTF-8")
.content(String.valueOf(jsonObject)))
.andExpect(status().isOk());
}
@Test
public void whendeleteProduct_thenReturnOk() throws Exception {
mvc.perform(delete("/evaluations/{id}", 1l))
.andExpect(status().isOk());
}
}
|
package scenario_villa;
import java.io.Serializable;
import core.Ambiente;
import core.CoreInputControl;
import core.Stanza;
@SuppressWarnings("serial")
class CorridoioQuadriNord extends Ambiente implements Stanza, Serializable {
protected CorridoioQuadriNord() {
this.nomeAmbiente = "Corridoio dei Quadri (Lato Nord)";
this.setCoords(2, 0, 2);
}
@Override
public void decodifica(String comando) {
CoreInputControl.getInstance().mancatoMatch();
}
@Override
public void guarda() {
System.out.println("\nSei nel corridoio dei quadri, non c'è nulla di interessante\n");
}
@Override
public void vaiOvest() {
System.out.println("\nDa questo lato ci sono solo dei quadri, non c'è nulla di interessante\n");
}
}
|
package com.heihei.login;
import android.os.Bundle;
import com.base.host.ActivityManager;
import com.base.host.BaseActivity;
import com.heihei.fragment.login.GuideFragment;
public class LoginActivity extends BaseActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
ActivityManager.getInstance().finishAllActivitysBefore();
}
@Override
protected String initFragmentClassName() {
return GuideFragment.class.getName();
}
}
|
package general.store;
import general.GeneralEvent;
import general.EventQueue;
import general.State;
public class PickEvent extends GeneralEvent {
// this event might not need the event que?
public PickEvent(EventQueue q) {
// generate time here somehow
this.occurenceTime = -1; // TODO
this.queue = q;
}
@Override
public void execute(State state) {
if(state.freeCashRegisters == 0) {
// no open registers
// add customer to queue of customers
// maybe return here?
}
// customer goes to the register
state.freeCashRegisters -= 1;
}
@Override
public double getTime() {
return this.occurenceTime;
}
}
|
package com.pwq.mavenT;
/**
* Created by BF100500 on 2017/7/12.
*/
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder MyStringBuilder = new StringBuilder("pwqagwt");
MyStringBuilder.append("day");
System.out.println(MyStringBuilder);
MyStringBuilder.insert(3,"1314");
System.out.println(MyStringBuilder);
System.out.println(MyStringBuilder.length());
}
}
|
package com.mycompany.intregavellinguagemprogramacao;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Cesar
*/
public class Monitoramento extends javax.swing.JFrame {
public Monitoramento() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lbAtualizar = new javax.swing.JLabel();
lbMemoria = new javax.swing.JLabel();
lbDisco = new javax.swing.JLabel();
lbCPU = new javax.swing.JLabel();
pbCPU = new javax.swing.JProgressBar();
pbMemoria = new javax.swing.JProgressBar();
pbDisco = new javax.swing.JProgressBar();
lbPercentCPU = new javax.swing.JLabel();
lbPercentMemoria = new javax.swing.JLabel();
lbPercentDisco = new javax.swing.JLabel();
rbGerarAuto = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setResizable(false);
setSize(new java.awt.Dimension(0, 0));
lbAtualizar.setIcon(new javax.swing.ImageIcon("C:\\Users\\César\\Documents\\NetBeansProjects\\IntregavelLinguagemProgramacao\\src\\main\\img\\refrescar.png")); // NOI18N
lbAtualizar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
lbAtualizar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbAtualizarMouseClicked(evt);
}
});
lbMemoria.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
lbMemoria.setText("Memória");
lbMemoria.setName(""); // NOI18N
lbDisco.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
lbDisco.setText("Disco");
lbCPU.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
lbCPU.setText("CPU");
lbPercentCPU.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbPercentCPU.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
lbPercentCPU.setText("0%");
lbPercentMemoria.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbPercentMemoria.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
lbPercentMemoria.setText("0%");
lbPercentDisco.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbPercentDisco.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
lbPercentDisco.setText("0%");
rbGerarAuto.setText("Gerar Automatico");
jLabel1.setBackground(new java.awt.Color(255, 0, 51));
jLabel1.setToolTipText("");
jLabel1.setMaximumSize(new java.awt.Dimension(100, 100));
jLabel1.setOpaque(true);
jLabel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setOpaque(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lbPercentCPU)
.addComponent(lbCPU)))
.addComponent(rbGerarAuto))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbMemoria)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbPercentMemoria))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbDisco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbPercentDisco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(74, 74, 74))
.addGroup(layout.createSequentialGroup()
.addComponent(pbCPU, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(pbMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(pbDisco, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(43, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pbCPU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(pbDisco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(pbMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbCPU, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbDisco, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbPercentCPU)
.addComponent(lbPercentMemoria)
.addComponent(lbPercentDisco))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rbGerarAuto)))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(33, Short.MAX_VALUE))
);
lbPercentDisco.getAccessibleContext().setAccessibleName("10%");
pack();
}// </editor-fold>//GEN-END:initComponents
private void lbAtualizarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbAtualizarMouseClicked
Random gerador = new Random();
Integer pcCPU, pcDisco, pcMemoria;
Timer timer = new Timer();
pcCPU = gerador.nextInt(101);
pcMemoria = gerador.nextInt(101);
pcDisco = gerador.nextInt(101);
// TimerTask gerarAuto = new TimerTask(){
//
// @Override
// public void run(){
// System.out.println("tatata");
//
// }
// };
// timer.cancel();
// timer.scheduleAtFixedRate(gerarAuto, 0, 1000);
//
// if(rbGerarAuto.isSelected()){
//
//
//
//
// } else {
// System.out.println("não to ativo");
// timer.cancel();
// }
System.out.println(jLabel1.getSize());
jLabel1.setSize(1, 1);
jLabel1.setText("fdvgdfdbrd");
pbCPU.setValue(pcCPU);
pbMemoria.setValue(pcMemoria);
pbDisco.setValue(pcDisco);
lbPercentCPU.setText(pcCPU+"%");
lbPercentMemoria.setText(pcMemoria+"%");
lbPercentDisco.setText(pcDisco+"%");
}//GEN-LAST:event_lbAtualizarMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Monitoramento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Monitoramento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Monitoramento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Monitoramento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Monitoramento().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lbAtualizar;
private javax.swing.JLabel lbCPU;
private javax.swing.JLabel lbDisco;
private javax.swing.JLabel lbMemoria;
private javax.swing.JLabel lbPercentCPU;
private javax.swing.JLabel lbPercentDisco;
private javax.swing.JLabel lbPercentMemoria;
private javax.swing.JProgressBar pbCPU;
private javax.swing.JProgressBar pbDisco;
private javax.swing.JProgressBar pbMemoria;
private javax.swing.JRadioButton rbGerarAuto;
// End of variables declaration//GEN-END:variables
}
|
package com.ats.communication_admin.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.ats.communication_admin.R;
import com.ats.communication_admin.adapter.FranchiseListAdapter;
import com.ats.communication_admin.adapter.MessageAdapter;
import com.ats.communication_admin.bean.FranchiseData;
import com.ats.communication_admin.bean.FranchiseeList;
import com.ats.communication_admin.bean.Info;
import com.ats.communication_admin.bean.MessageData;
import com.ats.communication_admin.bean.User;
import com.ats.communication_admin.common.CommonDialog;
import com.ats.communication_admin.constants.Constants;
import com.ats.communication_admin.util.PermissionUtil;
import com.google.gson.Gson;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AFEIVisitActivity extends AppCompatActivity {
RecyclerView rvFranchise;
int userId;
String userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afeivisit);
setTitle("AFE Visit");
rvFranchise = findViewById(R.id.rvFranchise);
if (PermissionUtil.checkAndRequestPermissions(this)) {
}
SharedPreferences pref = getApplicationContext().getSharedPreferences(Constants.MY_PREF, MODE_PRIVATE);
Gson gson = new Gson();
String json2 = pref.getString("User", "");
User userBean = gson.fromJson(json2, User.class);
Log.e("User Bean : ", "---------------" + userBean);
try {
if (userBean != null) {
userId = userBean.getId();
userName = userBean.getUsername();
} else {
startActivity(new Intent(AFEIVisitActivity.this, LoginActivity.class));
finish();
}
} catch (Exception e) {
Log.e("HomeActivity : ", " Exception : " + e.getMessage());
e.printStackTrace();
}
getAllFranchise();
}
public void getAllFranchise() {
if (Constants.isOnline(this)) {
final CommonDialog commonDialog = new CommonDialog(this, "Loading", "Please Wait...");
commonDialog.show();
Call<FranchiseData> franchiseDataCall = Constants.myInterface.getAllFranchise();
franchiseDataCall.enqueue(new Callback<FranchiseData>() {
@Override
public void onResponse(Call<FranchiseData> call, Response<FranchiseData> response) {
try {
if (response.body() != null) {
FranchiseData data = response.body();
if (data.getErrorMessage().getError()) {
commonDialog.dismiss();
Toast.makeText(AFEIVisitActivity.this, "No Franchise Found", Toast.LENGTH_SHORT).show();
} else {
commonDialog.dismiss();
Log.e("getAllFranchise : ", "-----------------------" + data);
ArrayList<FranchiseeList> franchiseeLists = new ArrayList<>();
for (int i = 0; i < data.getFranchiseeList().size(); i++) {
franchiseeLists.add(data.getFranchiseeList().get(i));
}
FranchiseListAdapter adapter = new FranchiseListAdapter(franchiseeLists, AFEIVisitActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(AFEIVisitActivity.this);
rvFranchise.setLayoutManager(mLayoutManager);
rvFranchise.setItemAnimator(new DefaultItemAnimator());
rvFranchise.setAdapter(adapter);
}
} else {
commonDialog.dismiss();
Toast.makeText(AFEIVisitActivity.this, "No Franchise Found", Toast.LENGTH_SHORT).show();
Log.e("getAllFranchise : ", " NULL");
}
} catch (Exception e) {
commonDialog.dismiss();
Toast.makeText(AFEIVisitActivity.this, "No Franchise Found", Toast.LENGTH_SHORT).show();
Log.e("getAllFranchise : ", " Exception : " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void onFailure(Call<FranchiseData> call, Throwable t) {
commonDialog.dismiss();
Toast.makeText(AFEIVisitActivity.this, "No Franchise Found", Toast.LENGTH_SHORT).show();
Log.e("getAllFranchise : ", " onFailure : " + t.getMessage());
t.printStackTrace();
}
});
} else {
Toast.makeText(this, "No Internet Connection !", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reports_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_all_reports) {
Intent intent = new Intent(AFEIVisitActivity.this, AfeDateWiseReportActivity.class);
intent.putExtra("FrId", 0);
startActivity(intent);
}else if (id == R.id.menu_logout) {
AlertDialog.Builder builder = new AlertDialog.Builder(AFEIVisitActivity.this, R.style.AlertDialogTheme);
builder.setTitle("Logout");
builder.setMessage("Are You Sure You Want To Logout?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
updateUserToken(userId, "");
SharedPreferences pref = getApplicationContext().getSharedPreferences(Constants.MY_PREF, MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(AFEIVisitActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(AFEIVisitActivity.this, R.style.AlertDialogTheme);
builder.setTitle("Exit Application?");
builder.setMessage("");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void updateUserToken(int userId, String token) {
if (Constants.isOnline(this)) {
final CommonDialog commonDialog = new CommonDialog(AFEIVisitActivity.this, "Loading", "Please Wait...");
commonDialog.show();
Call<Info> infoCall = Constants.myInterface.updateFCMToken(1, userId, token);
infoCall.enqueue(new Callback<Info>() {
@Override
public void onResponse(Call<Info> call, Response<Info> response) {
Log.e("Response : ", "--------------------" + response.body());
commonDialog.dismiss();
}
@Override
public void onFailure(Call<Info> call, Throwable t) {
commonDialog.dismiss();
Log.e("Failure : ", "---------------------" + t.getMessage());
t.printStackTrace();
}
});
}
}
}
|
/**
* Kaydee Gilson
* Final Project
* SimpleHoldPlayer Class: This class holds the auto isRolling method that uses the best hold value found in the simulations class.
*/
public class SimpleHoldPlayer extends PigPlayer {
//instance data
private int holdValue;
public static final int HOLDVALUE = 25;
//constructors
//default constructor
public SimpleHoldPlayer() {
super("player");
this.holdValue = HOLDVALUE;
}
//constructor with name
public SimpleHoldPlayer(String name) {
super(name);
this.holdValue = HOLDVALUE;
}
//constructor with name and holdValue
public SimpleHoldPlayer(String name, int holdValue) {
super(name);
this.holdValue = holdValue;
}
//automated isRolling method
public boolean isRolling(int turnTotal, int opponentScore) {
if (this.won() == false && (turnTotal + this.getScore()) < PigGame.GOAL) {
if (turnTotal < holdValue) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
} |
package objetos.aeronaves;
import objetos.aeronaves.civiles.*;
import objetos.aeronaves.enemigos.*;
/*
* Factory de las aeronaves no controladas
*/
public class FabricaAeronaves {
public FabricaAeronaves() {
}
public static Caza crearCaza() {
return new Caza();
}
public static GrupoCaza crearGrupoCaza() {
return new GrupoCaza();
}
public static Bomber crearBomber() {
return new Bomber();
}
public static Scout crearScout() {
return new Scout();
}
public static Avioneta crearAvioneta() {
return new Avioneta();
}
public static Helicoptero crearHelicoptero() {
return new Helicoptero();
}
public static AvionCivil crearAvionCivil() {
return new AvionCivil();
}
public static AvionGuia crearAvionGuia() {
return new AvionGuia();
}
}
|
package edu.ufl.cise.logParser;
import java.sql.SQLException;
public class QueryLog {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
ConnectionManager cm = new ConnectionManager();
cm.whereSenderOrReceiver("Supervisor");
}
}
|
package utils;
/**
* author {yhh1056}
* Create by {2020/07/13}
*/
public class NameIndexOutOfBoundsExceptionHandler extends Exception {
public NameIndexOutOfBoundsExceptionHandler(String message) {
super(message);
}
} |
package net.imglib2.trainable_segmention.pixel_feature.filter.dog2;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.test.ImgLib2Assert;
import net.imglib2.trainable_segmention.Utils;
import net.imglib2.trainable_segmention.pixel_feature.calculator.FeatureCalculator;
import net.imglib2.trainable_segmention.pixel_feature.filter.SingleFeatures;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import net.imglib2.view.Views;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SingleDifferenceOfGaussianTest {
private double sigma1 = 2.0;
private double sigma2 = 4.0;
private FeatureCalculator calculator = FeatureCalculator.default2d()
.addFeatures(SingleFeatures.differenceOfGaussians(sigma1, sigma2))
.build();
@Test
public void testDifferenceOfGaussians() {
RandomAccessible<FloatType> dirac = Utils.dirac2d();
FinalInterval interval = Intervals.createMinMax(-10, -10, 10, 10);
RandomAccessibleInterval<FloatType> result = Views.hyperSlice(calculator.apply(dirac, interval),
2, 0);
RandomAccessibleInterval<FloatType> expected = Utils.create2dImage(interval, (x, y) -> Utils
.gauss(sigma1, x, y) - Utils.gauss(sigma2, x, y));
ImgLib2Assert.assertImageEqualsRealType(expected, result, 0.001);
}
@Test
public void testAttribute() {
List<String> attributeLabels = calculator.attributeLabels();
List<String> expected = Collections.singletonList(
"difference of gaussians sigma1=2.0 sigma2=4.0");
assertEquals(expected, attributeLabels);
}
}
|
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/*
* 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 a80052136
*/
public class addEmail extends javax.swing.JFrame {
protected ArrayList<Subcontractor> conList;
private Subcontractor theSubcon;
/**
* Creates new form addEmail
*/
public addEmail(Subcontractor theSubcon) {
initComponents();
this.theSubcon = theSubcon;
SubcontractorDA da = new SubcontractorDA();
conList = da.getAllSubcontractor();
setResizable(false);
setTF(theSubcon);
centreWindow(this);
}
// change the "add" button to "update" when user choose to update
private void setTF (Subcontractor theSubcon) {
if (theSubcon != null) {
subconNameTF.setText(theSubcon.getName());
emailTF.setText(theSubcon.getEmail());
addBtn.setText("Update");
}
}
// This function will centre the window
private void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
subconNameTF = new javax.swing.JTextField();
emailTF = new javax.swing.JTextField();
addBtn = new javax.swing.JButton();
cancelBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Subcontractor Name: ");
jLabel2.setText("Email:");
addBtn.setText("Add");
addBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addBtnActionPerformed(evt);
}
});
cancelBtn.setText("Cancel");
cancelBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(subconNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
.addComponent(emailTF)))
.addGroup(layout.createSequentialGroup()
.addGap(167, 167, 167)
.addComponent(addBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(49, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(subconNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(emailTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addBtn)
.addComponent(cancelBtn))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBtnActionPerformed
String name = subconNameTF.getText();
String email = emailTF.getText();
boolean emailHasExisted = checkEmailExist(email, theSubcon);
SubcontractorDA da = new SubcontractorDA();
if (theSubcon == null && !name.equals("") && !email.equals("")) {
ArrayList <Subcontractor> conList = da.getAllSubcontractor();
if (email.contains("@")) {
if (!emailHasExisted) {
Subcontractor con = new Subcontractor(name, email);
da.save(con);
this.dispose();
MaintainEmail me = new MaintainEmail();
me.setVisible(true);
}
else {
JOptionPane.showMessageDialog(this, "This email is already exist",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(this, "Please enter a valid email address.",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (theSubcon != null && !name.equals("") && !email.equals("")){
if (!emailHasExisted) {
da.setSubcontractor(theSubcon.getEmail(), theSubcon.getName(), email, name);
this.dispose();
MaintainEmail me = new MaintainEmail();
me.setVisible(true);
}
else if (emailHasExisted) {
JOptionPane.showMessageDialog(this, "This email is already exists.",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(this, "Please fill in all the information required.",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_addBtnActionPerformed
// check whether the email exist
private boolean checkEmailExist(String email, Subcontractor theSubcon) {
boolean hasExisted = false;
for (Subcontractor s: conList) {
if (s.getEmail().equals(email)) {
hasExisted = true;
}
}
if (theSubcon != null && theSubcon.getEmail().equalsIgnoreCase(email)) {
hasExisted = false;
}
return hasExisted;
}
private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed
this.dispose();
MaintainEmail me = new MaintainEmail();
me.setVisible(true);
}//GEN-LAST:event_cancelBtnActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addBtn;
private javax.swing.JButton cancelBtn;
private javax.swing.JTextField emailTF;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField subconNameTF;
// End of variables declaration//GEN-END:variables
}
|
import java.io.Serializable;
import java.util.Date;
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
private String nombre;
private String apellido;
private Date fechaNacimiento;
private int puntos;
public Usuario(String nombre, String apellido, Date fechaNacimiento, int puntos) {
this.nombre = nombre;
this.apellido = apellido;
this.fechaNacimiento = fechaNacimiento;
this.puntos = puntos;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public int getPuntos() {
return puntos;
}
public void setPuntos(int puntos) {
this.puntos = puntos;
}
}
|
package ex15_interface_extends;
public class SmartPhone extends Phone implements Computable {
// Computable의 palyApp()을 반드시 오버라이드 해야합니다.
@Override
public void playApp() {
System.out.println("앱을 실행한다.");
}
}
|
package com.ms.module.wechat.clear.activity.clear;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.provider.BaseNodeProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ms.module.wechat.clear.R;
import com.ms.module.wechat.clear.activity.emoji.EmojiDetailsActivity;
import com.ms.module.wechat.clear.activity.file.FileDetailsActivity;
import com.ms.module.wechat.clear.activity.image.ImageDetailsActivity;
import com.ms.module.wechat.clear.activity.video.VideoDetailsActivity;
import com.ms.module.wechat.clear.activity.voice.VoiceDetailsActivity;
import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils;
import org.jetbrains.annotations.NotNull;
public class DownChildProvider extends BaseNodeProvider {
@Override
public int getItemViewType() {
return 4;
}
@Override
public int getLayoutId() {
return R.layout.provider_wechat_clear_down_child;
}
@Override
public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) {
ImageView imageViewIcon = baseViewHolder.findView(R.id.imageViewIcon);
TextView textViewName = baseViewHolder.findView(R.id.textViewName);
TextView textViewSize = baseViewHolder.findView(R.id.textViewSize);
ImageView imageViewEnter = baseViewHolder.findView(R.id.imageViewEnter);
if (baseNode instanceof DownChildNode) {
DownChildNode downChildNode = (DownChildNode) baseNode;
Glide.with(getContext()).load(downChildNode.getIcon()).into(imageViewIcon);
textViewName.setText(downChildNode.getName());
textViewSize.setText(ByteSizeToStringUnitUtils.byteToStringUnit(downChildNode.getSize()));
}
baseViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("聊天图片".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, ImageDetailsActivity.class));
} else if ("聊天表情包".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, EmojiDetailsActivity.class));
} else if ("文件".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, FileDetailsActivity.class));
} else if ("聊天语音".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, VoiceDetailsActivity.class));
} else if ("聊天小视频".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, VideoDetailsActivity.class));
}
}
});
imageViewEnter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("聊天图片".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, ImageDetailsActivity.class));
} else if ("聊天表情包".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, EmojiDetailsActivity.class));
} else if ("文件".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, FileDetailsActivity.class));
} else if ("聊天语音".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, VoiceDetailsActivity.class));
} else if ("聊天小视频".equals(textViewName.getText().toString())) {
context.startActivity(new Intent(context, VideoDetailsActivity.class));
}
}
});
}
}
|
package com.source.getbus1;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity {
String[] driver={"pipit","haris","randi"};
String[] pw={"123","123","123"};
EditText nama,password;
Button masuk,saklar;
TextView gmail,keterangan;
TextView waktu,halte,rute,asal,tujuan;
Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/*login=getParent().findViewById(R.id.login);
waktu=getParent().findViewById(R.id.waktu);
halte=getParent().findViewById(R.id.halte);
rute=getParent().findViewById(R.id.rute);
asal=getParent().findViewById(R.id.asal);
tujuan=getParent().findViewById(R.id.tujuan);
saklar=getParent().findViewById(R.id.button);*/
nama=findViewById(R.id.textNama);
password=findViewById(R.id.textPassword);
masuk=findViewById(R.id.buttonMasuk);
gmail=findViewById(R.id.textGmail);
keterangan=findViewById(R.id.keterangan);
keterangan.setVisibility(View.INVISIBLE);
masuk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!(nama.getText().toString().matches("")||password.getText().toString().matches(""))){
boolean ada=false;
for(int i=0;i<driver.length;i++){
if (driver[i].matches(nama.getText().toString()) && pw[i].matches(password.getText().toString())) {
ada=true;
break;
}
}
if(ada==true){
/*login.setText("LOGOUT");
saklar.setVisibility(View.VISIBLE);
saklar.setText("OFF");
waktu.setText("15 : 30");
rute.setText("Merah");
halte.setText("Berlin");
asal.setText("Fapeta");
tujuan.setText(halte.getText());*/
keterangan.setVisibility(View.INVISIBLE);
finish();
}
else{keterangan.setVisibility(View.VISIBLE);}
}
else {
keterangan.setVisibility(View.VISIBLE);
}
}
});
}
}
|
package br.com.furb.repository;
import br.com.furb.domain.EstoqueProduto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface EstoqueProdutoRepository extends JpaRepository<EstoqueProduto, Long> {
@Query("select epr from EstoqueProduto epr where epr.produto.id = :codProduto and epr.codEmpresa = :codEmpresa")
Optional<EstoqueProduto> findByProdutoAndCodEmpresa(@Param("codProduto") Long codProduto, @Param("codEmpresa") Integer codEmpresa);
}
|
package bakery;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.Map.Entry;
/**
* High level store operations and data storage
*
* @author rcj, anhtran9
* @version 06/17/14
*
*/
public class Store {
/** The store inventory, indexed by id */
private HashMap<Integer, Item> inventory = new HashMap<Integer, Item>();
/** Client orders, indexed by id */
private HashMap<Integer, Order> orders = new HashMap<Integer, Order>();
/** Customer records, indexed by id */
private HashMap<Integer, Client> customers = new HashMap<Integer, Client>();
/**
* Default constructor
*/
Store() {
// Empty constructor
}
/**
* Constructor for loading from file
*
* @param inventoryData
* File containing inventory data
* @param orderData
* File containing order data
*/
public Store(File inventoryData, File orderData) {
this.parseInventory(inventoryData);
this.parseOrder(orderData);
}
/**
* Read in the inventory file
*
* @param data
* The inventory file
*/
private void parseInventory(File data) {
try {
Scanner scan = new Scanner(data);
scan.nextLine();
while (scan.hasNextLine()) {
String s = scan.nextLine();
String[] fields = s.split("\t");
Item inputItem = new Item(Integer.parseInt(fields[0]),
fields[1], fields[2], Double.parseDouble(fields[3]), 1);
this.addItem(inputItem);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Read in the order file
*
* @param data
* The order file
*/
private void parseOrder(File data) {
try {
Scanner scan = new Scanner(data);
scan.nextLine();
while (scan.hasNextLine()) {
String s = scan.nextLine();
String[] fields = s.split("\t");
LoyaltyCard cardInput = new LoyaltyCard(true,
Double.parseDouble(fields[19]),
Double.parseDouble(fields[18]));
Client clientInput = new Client(Integer.parseInt(fields[0]),
fields[1], fields[2], fields[3], fields[4], fields[5],
cardInput);
if (this.getClient(clientInput.getId()) == null) {
this.addClient(clientInput);
}
HashMap<Item, Integer> itemInput = new HashMap<Item, Integer>();
Order orderInput = new Order(clientInput,
Integer.parseInt(fields[6]), fields[8], fields[9],
itemInput, Store.convertPaid(fields[7]),
Store.convertDiscount(fields[16]), "");
if (this.getOrder(orderInput.getId()) == null) {
this.addOrder(orderInput);
}
Integer id = Integer.parseInt(fields[10]);
Item item = this.getItem(id);
Order realOrder = this.getOrder(Integer.parseInt(fields[6]));
itemInput = realOrder.getItems();
itemInput.put(item, Integer.parseInt(fields[13]));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* Convert a yes/no string to boolean true/false
*
* @param s
* The string "yes" or the string "no"
* @return True if the string was "yes", false if it was "no"
*/
public static boolean convertPaid(String s) {
return s.equalsIgnoreCase("yes");
}
/**
* Convert a discount to a boolean
*
* @param s
* A discount amount
* @return False if the discount equals "0", true otherwise
*/
public static boolean convertDiscount(String s) {
return !s.equals("0");
}
/**
* Add a client to the customer records
*
* @param c
* The client to add
*/
public void addClient(Client c) {
this.customers.put(c.getId(), c);
}
/**
* Add an order to the order records
*
* @param o
* The order to add
*/
public void addOrder(Order o) {
this.orders.put(o.getId(), o);
}
/**
* Add an item to the inventory
*
* @param i
* The item to add
*/
public void addItem(Item i) {
this.inventory.put(i.getId(), i);
}
/**
* Get client by id
*
* @param id
* The client id to look up
* @return The client with this id or null if the client does not exist
*/
public Client getClient(int id) {
return this.customers.get(id);
}
/**
* Get order by id
*
* @param id
* The order id to look up
* @return The order with this id or null if the order does not exist
*/
public Order getOrder(int id) {
return this.orders.get(id);
}
/**
* Get item by id
*
* @param id
* The item id to look up
* @return The item with this id or null if the item does not exist
*/
public Item getItem(int id) {
return this.inventory.get(id);
}
/**
* Get orders by client id
*
* @param id
* A client id
* @return Orders placed by the client represented by the given id
*/
public ArrayList<Order> getOrdersByClient(int id) {
ArrayList<Order> clientOrders = new ArrayList<Order>();
for (Entry<Integer, Order> entry : this.orders.entrySet()) {
if (entry.getValue().getClient().getId() == id) {
clientOrders.add(entry.getValue());
}
}
return clientOrders;
}
/**
* Get orders by order date
*
* @param date
* The date we are concerned with
* @return Orders placed on the given date
*/
public ArrayList<Order> getOrdersByOrderDate(String date) {
ArrayList<Order> clientOrders = new ArrayList<Order>();
for (Entry<Integer, Order> entry : this.orders.entrySet()) {
if (entry.getValue().getOrderDate().equals(date)) {
clientOrders.add(entry.getValue());
}
}
return clientOrders;
}
/**
* Get orders by pickup date
*
* @param date
* The date we are concerned with
* @return Orders to be picked up on the given date
*/
public ArrayList<Order> getOrdersByPickupDate(String date) {
ArrayList<Order> clientOrders = new ArrayList<Order>();
for (Entry<Integer, Order> entry : this.orders.entrySet()) {
if (entry.getValue().getPickupDate().equals(date)) {
clientOrders.add(entry.getValue());
}
}
return clientOrders;
}
/**
* Get orders by item id
*
* @param id
* An item id
* @return Orders containing the given item
*/
public ArrayList<Order> getOrdersByItem(int id) {
ArrayList<Order> clientOrders = new ArrayList<Order>();
for (Entry<Integer, Order> entry : this.orders.entrySet()) {
for (Entry<Item, Integer> itemEntry : entry.getValue().getItems()
.entrySet()) {
if (itemEntry.getKey().getId() == id) {
clientOrders.add(entry.getValue());
break;
}
}
}
return clientOrders;
}
/**
* Get orders that have not been paid for
*
* @return List of orders that have not been paid for
*/
public ArrayList<Order> getUnpaidOrders() {
ArrayList<Order> clientOrders = new ArrayList<Order>();
for (Entry<Integer, Order> entry : this.orders.entrySet()) {
if (!entry.getValue().getPaid()) {
clientOrders.add(entry.getValue());
}
}
return clientOrders;
}
/**
* Get a string representation of available items
*
* @return A string representation of available items
*/
public String getMenu() {
HashMap<String, ArrayList<Item>> menu =
new HashMap<String, ArrayList<Item>>();
String output = "";
for (Entry<Integer, Item> entry : this.inventory.entrySet()) {
String cat = entry.getValue().getCategory();
if (menu.containsKey(entry.getValue().getCategory())) {
ArrayList<Item> newList = menu.get(cat);
newList.add(entry.getValue());
menu.put(cat, newList);
}
else {
ArrayList<Item> newList = new ArrayList<Item>();
newList.add(entry.getValue());
menu.put(cat, newList);
}
}
for (String cat : menu.keySet()) {
output += cat + ": \n";
for (Item i : menu.get(cat)) {
output += i.getName() + "\n";
}
output += "\n";
}
return output;
}
/**
* Generate the next available client id
*
* @return A new valid client id
*/
public Integer generateClientId() {
ArrayList<Integer> ids = new ArrayList<Integer>();
for (Entry<Integer, Client> e : this.customers.entrySet()) {
ids.add(e.getKey());
}
Collections.sort(ids);
return ids.get(ids.size() - 1) + 1;
}
/**
* Generate the next available item id
*
* @return A new valid item id
*/
public Integer generateItemId() {
ArrayList<Integer> ids = new ArrayList<Integer>();
for (Entry<Integer, Item> e : this.inventory.entrySet()) {
ids.add(e.getKey());
}
Collections.sort(ids);
return ids.get(ids.size() - 1) + 1;
}
/**
* Generate the next available order id
*
* @return A new valid order id
*/
public Integer generateOrderId() {
ArrayList<Integer> ids = new ArrayList<Integer>();
for (Entry<Integer, Order> e : this.orders.entrySet()) {
ids.add(e.getKey());
}
Collections.sort(ids);
return ids.get(ids.size() - 1) + 1;
}
/**
* Get the inventory
*
* @return The hashmap containing the inventory
*/
public HashMap<Integer, Item> getInventories() {
return this.inventory;
}
/**
* Get the order records
*
* @return The hashmap containing order records
*/
public HashMap<Integer, Order> getOrders() {
return this.orders;
}
/**
* Get the client records
*
* @return The hashmap containing order records
*/
public HashMap<Integer, Client> getCustomers() {
return this.customers;
}
/**
* Convert a boolean into a "yes" or a "no"
*
* @param b
* A boolean
* @return "Yes" if b is true, "No" if b is false
*/
public static String convertToString(Boolean b) {
if (b) {
return "yes";
}
else {
return "no";
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.io.Serializable;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Spring's default implementation of the {@link MessageSourceResolvable} interface.
* Offers an easy way to store all the necessary values needed to resolve
* a message via a {@link org.springframework.context.MessageSource}.
*
* @author Juergen Hoeller
* @since 13.02.2004
* @see org.springframework.context.MessageSource#getMessage(MessageSourceResolvable, java.util.Locale)
*/
@SuppressWarnings("serial")
public class DefaultMessageSourceResolvable implements MessageSourceResolvable, Serializable {
@Nullable
private final String[] codes;
@Nullable
private final Object[] arguments;
@Nullable
private final String defaultMessage;
/**
* Create a new DefaultMessageSourceResolvable.
* @param code the code to be used to resolve this message
*/
public DefaultMessageSourceResolvable(String code) {
this(new String[] {code}, null, null);
}
/**
* Create a new DefaultMessageSourceResolvable.
* @param codes the codes to be used to resolve this message
*/
public DefaultMessageSourceResolvable(String[] codes) {
this(codes, null, null);
}
/**
* Create a new DefaultMessageSourceResolvable.
* @param codes the codes to be used to resolve this message
* @param defaultMessage the default message to be used to resolve this message
*/
public DefaultMessageSourceResolvable(String[] codes, String defaultMessage) {
this(codes, null, defaultMessage);
}
/**
* Create a new DefaultMessageSourceResolvable.
* @param codes the codes to be used to resolve this message
* @param arguments the array of arguments to be used to resolve this message
*/
public DefaultMessageSourceResolvable(String[] codes, Object[] arguments) {
this(codes, arguments, null);
}
/**
* Create a new DefaultMessageSourceResolvable.
* @param codes the codes to be used to resolve this message
* @param arguments the array of arguments to be used to resolve this message
* @param defaultMessage the default message to be used to resolve this message
*/
public DefaultMessageSourceResolvable(
@Nullable String[] codes, @Nullable Object[] arguments, @Nullable String defaultMessage) {
this.codes = codes;
this.arguments = arguments;
this.defaultMessage = defaultMessage;
}
/**
* Copy constructor: Create a new instance from another resolvable.
* @param resolvable the resolvable to copy from
*/
public DefaultMessageSourceResolvable(MessageSourceResolvable resolvable) {
this(resolvable.getCodes(), resolvable.getArguments(), resolvable.getDefaultMessage());
}
/**
* Return the default code of this resolvable, that is,
* the last one in the codes array.
*/
@Nullable
public String getCode() {
return (this.codes != null && this.codes.length > 0 ? this.codes[this.codes.length - 1] : null);
}
@Override
@Nullable
public String[] getCodes() {
return this.codes;
}
@Override
@Nullable
public Object[] getArguments() {
return this.arguments;
}
@Override
@Nullable
public String getDefaultMessage() {
return this.defaultMessage;
}
/**
* Indicate whether the specified default message needs to be rendered for
* substituting placeholders and/or {@link java.text.MessageFormat} escaping.
* @return {@code true} if the default message may contain argument placeholders;
* {@code false} if it definitely does not contain placeholders or custom escaping
* and can therefore be simply exposed as-is
* @since 5.1.7
* @see #getDefaultMessage()
* @see #getArguments()
* @see AbstractMessageSource#renderDefaultMessage
*/
public boolean shouldRenderDefaultMessage() {
return true;
}
/**
* Build a default String representation for this MessageSourceResolvable:
* including codes, arguments, and default message.
*/
protected final String resolvableToString() {
StringBuilder result = new StringBuilder(64);
result.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ","));
result.append("]; arguments [").append(StringUtils.arrayToDelimitedString(this.arguments, ","));
result.append("]; default message [").append(this.defaultMessage).append(']');
return result.toString();
}
/**
* The default implementation exposes the attributes of this MessageSourceResolvable.
* <p>To be overridden in more specific subclasses, potentially including the
* resolvable content through {@code resolvableToString()}.
* @see #resolvableToString()
*/
@Override
public String toString() {
return getClass().getName() + ": " + resolvableToString();
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MessageSourceResolvable that &&
ObjectUtils.nullSafeEquals(getCodes(), that.getCodes()) &&
ObjectUtils.nullSafeEquals(getArguments(), that.getArguments()) &&
ObjectUtils.nullSafeEquals(getDefaultMessage(), that.getDefaultMessage())));
}
@Override
public int hashCode() {
int hashCode = ObjectUtils.nullSafeHashCode(getCodes());
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(getArguments());
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(getDefaultMessage());
return hashCode;
}
}
|
package net.notfab.dimensionchanger;
import lombok.Getter;
import net.notfab.dimensionchanger.listener.Listeners;
import net.notfab.spigot.simpleconfig.SimpleConfig;
import net.notfab.spigot.simpleconfig.SimpleConfigManager;
import net.notfab.spigot.simpleconfig.spigot.SpigotConfigManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class DimensionChanger extends JavaPlugin {
@Getter
private static DimensionChanger Instance;
@Getter
private SimpleConfigManager simpleConfigManager;
@Getter
private NMSHandler nmsHandler;
@Getter
private Listeners listeners;
@Getter
private SimpleConfig simpleConfig;
@Override
public void onEnable() {
Instance = this;
this.simpleConfigManager = new SpigotConfigManager(this);
this.nmsHandler = new NMSHandler(getLogger());
this.simpleConfig = this.setupConfig();
this.listeners = new Listeners(this.simpleConfig, this.nmsHandler);
getCommand("dc").setExecutor(new DimensionCommand(this.simpleConfig, this.nmsHandler));
getServer().getPluginManager().registerEvents(this.listeners, this);
}
@Override
public void onDisable() {
this.listeners.onDisable();
}
/**
* Setups the config files.
*
* @return SimpleConfig.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
private SimpleConfig setupConfig() {
File file = new File("config.yml");
if (!file.exists()) {
try {
file.createNewFile();
InputStream stream = getClass().getResourceAsStream("/config.yml");
this.simpleConfigManager.copyResource(stream, file);
} catch (IOException e) {
getLogger().severe(e.getMessage());
}
}
return this.simpleConfigManager.getNewConfig("config.yml");
}
} |
package riomaissaude.felipe.com.br.riosaude;
import android.support.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static org.junit.Assert.fail;
import riomaissaude.felipe.com.br.riosaude.db.DatabaseHandler;
import riomaissaude.felipe.com.br.riosaude.models.Estabelecimento;
import riomaissaude.felipe.com.br.riosaude.models.StatusEstabelecimento;
import riomaissaude.felipe.com.br.riosaude.utils.LeitorArquivoEstabelecimentos;
/**
* Testes unitários da camada de persistência.
*
* Created by felipe on 3/6/16.
*/
@RunWith(AndroidJUnit4.class)
public class DatabaseHandlerTest {
private DatabaseHandler database;
private Estabelecimento estabelecimento;
private LeitorArquivoEstabelecimentos leitorArquivo;
@Before
public void setUp() throws Exception {
getTargetContext().deleteDatabase(DatabaseHandler.DATABASE_NAME);
this.database = new DatabaseHandler(getTargetContext());
this.leitorArquivo = new LeitorArquivoEstabelecimentos(getTargetContext());
}
@After
public void tearDown() throws Exception {
this.database.close();
}
@Test
public void testLerArquivo() {
try {
this.leitorArquivo.lerArquivo();
} catch (IOException e) {
fail("Teste testLerArquivo falhou.");
}
}
@Test
public void testAdicionarEstabelecimento() {
this.estabelecimento = new Estabelecimento
(1, "1", "", "", "", "Estabelecimento Teste", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
this.database.addEstabelecimento(this.estabelecimento);
List<Estabelecimento> estabelecimentos = this.database.getAllEstabelecimentos();
assertThat(estabelecimentos.size(), is(1));
}
@Test
public void testAdicionarEstabelecimentos() throws IOException {
this.leitorArquivo.lerArquivo();
this.database.addEstabelecimentos(this.leitorArquivo.getEstabelecimentos());
List<Estabelecimento> estabelecimentos = this.database.getAllEstabelecimentos();
assertThat(estabelecimentos.size(), is(4466));
}
@Test
public void testAdicionarEstabelecimentosErrado() throws IOException {
this.leitorArquivo.lerArquivo();
this.database.addEstabelecimentos(this.leitorArquivo.getEstabelecimentos());
List<Estabelecimento> estabelecimentos = this.database.getAllEstabelecimentos();
assertNotEquals(estabelecimentos.size(), is(4465));
}
@Test
public void testGetByPrimaryKey() {
this.estabelecimento = new Estabelecimento
(1, "1", "", "", "", "Estabelecimento Teste", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
this.database.addEstabelecimento(this.estabelecimento);
Estabelecimento e = this.database.getByPrimaryKey(1);
assertThat(e.getNomeFantasia(), is("Estabelecimento Teste"));
}
@Test
public void testFindByNome() {
this.estabelecimento = new Estabelecimento
(1, "1", "", "", "", "Estabelecimento Teste", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
this.database.addEstabelecimento(this.estabelecimento);
List<Estabelecimento> estabelecimentos = this.database.findByNome("Estabelecimento Teste");
assertNotEquals(estabelecimentos.size(), 0);
}
@Test
public void testUpdateStatus() {
this.estabelecimento = new Estabelecimento
(1, "1", "", "", "", "Estabelecimento Teste", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", StatusEstabelecimento.SEM_INFORMACAO, "");
this.database.addEstabelecimento(this.estabelecimento);
this.database.updateStatusEstabelecimento(1, StatusEstabelecimento.FUNCIONANDO_BEM);
assertThat(this.database.getByPrimaryKey(1).getStatusEstabelecimento(), is(StatusEstabelecimento.FUNCIONANDO_BEM));
}
}
|
package com.myth.springboot.dao;
import com.myth.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoginMapper {
//查找用户
User selectUser(String name);
int updatePassword(String u_password,String u_name);
}
|
import packets.CommandPacket;
import packets.*;
import packets.UserPacket;
import packets.User;
import services.*;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Главный класс клиента
*/
public class Client {
/**
* Пользователь
*/
private static User user;
/**
* Поле времени
*/
private static LocalDateTime time;
/**
* Сокет
*/
private static Socket socket;
/**
* Интерпретатор команд
*/
private static ClientInterpreter interpreter;
/**
* Менеджер работы клиента
*/
private static ClientManager clientManager;
/**
* Главный метод клиента
* @param args - аргументы командной строки
*/
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
try {
log("INFO: Клиент запускается...");
log("INFO: Введите порт:");
int port = getPort(scanner);
InetAddress host = InetAddress.getLocalHost();
log("INFO: Попытка подключения...");
socket = new Socket(host, port);
log("INFO: Клиент запущен. Подключение прошло успешно.");
interpreter = new ClientInterpreter(scanner);
clientManager = new ClientManager(scanner);
boolean isDone = false;
log("INFO: Происходит авторизация. Для регистрации введите register.");
log("INFO: Для авторизации введите login:");
log("Для выхода введите exit.");
try {
user = authorization();
}
catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}
interpreter.setUser(user);
log("INFO: Авторизация прошла успешно. Вы в системе. Начало работы.");
do{
System.out.println(">>>>>>>");
try {
CommandPacket clientCommand = interpreter.readLine(scanner.nextLine(),false);
if (clientCommand.getCommand() == CommandType.exit) {
isDone = true;
}
else if (clientCommand.getCommand() == CommandType.execute_script){
//Наведём шороху
try {
ArrayList<CommandPacket> commandArrayList = new ArrayList<>();
Scanner localScanner = new Scanner(new File(clientCommand.getStringField()));
do {
CommandPacket command = interpreter.readLine(localScanner.nextLine(),true);
if (command.getCommand() == CommandType.null_command){
throw new NullPointerException();
}
else{
commandArrayList.add(command);
}
} while (localScanner.hasNextLine());
for (CommandPacket command: commandArrayList){
log("INFO: Попытка выслать команду серверу...");
socket.getOutputStream().write(clientManager.serialize(command));
log("INFO: Команда успешно отправлена. Получение сообщения...");
byte[] buffer = new byte[10000];
socket.getInputStream().read(buffer);
clientManager.showResult(clientManager.deserialize(buffer));
//log("INFO: Получено сообщение. Зачитываю: "+command.getCommand());
}
}
catch (NullPointerException e){
log("INFO: Скрипт написан неправильно. Исправьте скрипт.");
}
catch (Exception e){
e.printStackTrace();
}
}
else if (clientCommand.getCommand() != CommandType.null_command){
log("INFO: Попытка выслать команду серверу...");
socket.getOutputStream().write(clientManager.serialize(clientCommand));
log("INFO: Команда успешно отправлена. Получение сообщения...");
byte[] buffer = new byte[10000];
socket.getInputStream().read(buffer);
clientManager.showResult(clientManager.deserialize(buffer));
}
}
catch(SocketException e){
log("ERROR: Проблемы с подключением к серверу.");
log("SOLUTION: Перезапустите клиент: воспользуйтесь командой exit");
}
catch (Exception e){
e.printStackTrace();
}
} while (!isDone);
}
catch (ConnectException e){
log("ERROR: Нет подключения к серверу.");
log(" Завершение работы.");
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* Метод для логирования
* @param message - сообщение
*/
private static void log(String message){
time = LocalDateTime.now();
System.out.println(time.format(DateTimeFormatter.ofPattern("dd.MM.yyyy-HH:mm:ss ")) + message);
}
/**
* Метод для авторизации пользователя
* @throws IOException - исключение ввода/вывода
* @throws ClassNotFoundException - исключение ненайденного класса
*/
private static User authorization() throws IOException, ClassNotFoundException {
boolean isOnline = false;
while (true){
System.out.println(">>>>>>>");
UserPacket userPacket = interpreter.authorize();
String status = userPacket.getMessageText();
if (status.equals("login") | status.equals("register")){
log("INFO: Попытка авторизации...");
socket.getOutputStream().write(clientManager.serialize(userPacket));
log("INFO: Запрос успешно отправлен. Получение результата...");
byte[] buffer = new byte[10000];
socket.getInputStream().read(buffer);
UserPacket answer = (UserPacket) clientManager.deserialize(buffer);
clientManager.showResult(answer);
if (answer.getMessageText().equals("Success")){
return answer.getUser();
}
}
}
}
/**
* Статический метод для ввода порта для подключения
* @param scanner - сканер
* @return возвращает порт
*/
private static int getPort(Scanner scanner){
int port = -1;
do {
try {
port = Integer.parseInt(scanner.nextLine());
if (port < 0) {
System.out.println("Порт не может быть меньше 0.");
System.out.println("Повторите ввод:");
}
else{
break;
}
}
catch (NumberFormatException ex) {
System.out.println("Неправильный формат ввода. Вводите число без пробелов и разделителей.");
System.out.println("Повторите ввод:");
}
}while (port < 0);
return port;
}
}
|
package com.example.calendar_02;
import java.util.Calendar;
public class SpecialCalendar {
/**
* 判断year是否为闰年
* 是:返回true,否:返回false
* @param year
* @return
*/
public static boolean isLeapYear(int year) {
if (year % 100 == 0 && year % 400 == 0) {
return true;
} else if (year % 100 != 0 && year % 4 == 0) {
return true;
}
return false;
}
/**
* 计算某月多少天
*
* @param isLeapyear :是否闰年
* @param month:月份
* @return :返回month月多少天
*/
public static int getDaysOfMonth(boolean isLeapyear, int month) {
int daysOfMonth = 0; //某月的天数
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysOfMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysOfMonth = 30;
break;
case 2:
if (isLeapyear) {
daysOfMonth = 29;
} else {
daysOfMonth = 28;
}
}
return daysOfMonth;
}
/**
* 确定某年某月的第一天星期几
* @param year
* @param month
* @return
*/
public static int getWeekdayOfMonth(int year, int month){
int dayOfWeek = 0; //某年某月第一天是星期几
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, 1);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
/**
* 判断某年某月某日是 当月的第几周
* @param year
* @param month
* @param day
*/
public static int getTheDayIsWhichWeekOfTheMonth(int year, int month, int day){
int week_c;
int dayOfWeek = SpecialCalendar.getWeekdayOfMonth(year, month); //某年某月第一天星期几
if (dayOfWeek == 7) {
week_c = day / 7 + 1;
} else {
if (day <= (7 - dayOfWeek)) {
week_c = 1;
} else {
if ((day - (7 - dayOfWeek)) % 7 == 0) {
week_c = (day - (7 - dayOfWeek)) / 7 + 1;
} else {
week_c = (day - (7 - dayOfWeek)) / 7 + 2;
}
}
}
return week_c;
}
/**
* 判断某年某月所有的星期数
*
* @param year
* @param month
*/
public static int getWeeksOfMonth(int year, int month) {
int weeksOfMonth; //当前月有多周
// 先判断某月的第一天为星期几
int preMonthRelax = 0;
int dayFirst = SpecialCalendar.getWeekdayOfMonth(year, month);
int days = SpecialCalendar.getDaysOfMonth(SpecialCalendar.isLeapYear(year), month);
if (dayFirst != 7) {
preMonthRelax = dayFirst;
}
if ((days + preMonthRelax) % 7 == 0) {
weeksOfMonth = (days + preMonthRelax) / 7;
} else {
weeksOfMonth = (days + preMonthRelax) / 7 + 1;
}
return weeksOfMonth;
}
/**
* 确定某年某月某日是星期几
* @param year
* @param month
* @param day
* @return
*/
public static int getDayOfWeek(int year,int month,int day){
int eachDayOfWeek;
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, day);
eachDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
return eachDayOfWeek;
}
}
|
package irix.convertor.sections;
import irix.measurement.service.DoseRateImp;
import irix.measurement.service.LocationMeasurementAttributesImp;
import irix.measurement.service.LocationMeasurementImp;
import irix.measurement.service.MeasurementImp;
import irix.measurement.service.MeasurementsImp;
import irix.measurement.service.MeasuringPeriodImp;
import irix.measurement.service.ValueAttributesImp;
import irix.measurement.service.ValueImp;
import irix.measurement.structure.DoseRate;
import irix.measurement.structure.LocationMeasurement;
import irix.measurement.structure.LocationMeasurementAttributes;
import irix.measurement.structure.Measurement;
import irix.measurement.structure.Measurements;
import irix.measurement.structure.MeasurementsSectionalAttributes;
import irix.measurement.structure.MeasuringPeriod;
import irix.measurement.structure.Value;
import irix.measurement.structure.ValueAttributes;
public class MeasurementsSectional implements DoseRateImp, MeasuringPeriodImp, MeasurementsImp, MeasurementImp, LocationMeasurementImp, LocationMeasurementAttributesImp, ValueImp, ValueAttributesImp, Comparable<MeasurementsSectional> {
private DoseRate doseRate;
private MeasurementsSectionalAttributes measurementsSectionalAttributes;
public MeasurementsSectional() {
}
public MeasurementsSectional(DoseRate doseRate, MeasurementsSectionalAttributes measurementsSectionalAttributes) {
this.doseRate = doseRate;
this.measurementsSectionalAttributes = measurementsSectionalAttributes;
}
public DoseRate getDoseRate() {
return doseRate;
}
public void setDoseRate(DoseRate doseRate) {
this.doseRate = doseRate;
}
public MeasurementsSectionalAttributes getMeasurementsSectionalAttributes() {
return measurementsSectionalAttributes;
}
public void setMeasurementsSectionalAttributes(MeasurementsSectionalAttributes measurementsSectionalAttributes) {
this.measurementsSectionalAttributes = measurementsSectionalAttributes;
}
@Override
public String toString() {
return "doseRate=" + doseRate + ", "
+ "measurementsAttributes=" + measurementsSectionalAttributes;
}
@Override
public int hashCode() {
final int prime = 53;
int hash = 7;
hash = prime * hash + ((doseRate == null) ? 0 : doseRate.hashCode());
return hash;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MeasurementsSectional)) return false;
return this.doseRate == ((MeasurementsSectional)obj).getDoseRate();
}
@Override
public int compareTo(MeasurementsSectional o) {
return doseRate.compareTo(o.getDoseRate());
}
@Override
public MeasuringPeriod getMeasuringPeriod() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Measurements getMeasurements() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getStartTime() {
return this.getDoseRate().getMeasuringPeriod().getStartTime();
}
@Override
public String getEndTime() {
return this.getDoseRate().getMeasuringPeriod().getEndTime();
}
@Override
public Measurement getMeasurement() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public LocationMeasurement getLocationMeasurement() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Value getValue() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getValidated() {
return this.getDoseRate().getMeasurements().getMeasurement().getValidated();
}
@Override
public LocationMeasurementAttributes getLocationMeasurementAttributes() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getRef() {
return this.getDoseRate().getMeasurements().getMeasurement().getLocationMeasurement().getLocationMeasurementAttributes().getRef();
}
@Override
public Double getDosePhantom() {
return this.getDoseRate().getMeasurements().getMeasurement().getValue().getDosePhantom();
}
@Override
public ValueAttributes getValueAttributes() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getUnit() {
return this.getDoseRate().getMeasurements().getMeasurement().getValue().getValueAttributes().getUnit();
}
@Override
public String getDoseRateType() {
return this.getDoseRate().getDoseRateType();
}
public String getValidAt() {
return this.getMeasurementsSectionalAttributes().getValidAt();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bookstore.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Andrea
*/
public class CrearLibro extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
//El parámetro enviado a getParameter() deberá coincidir con la propiedad name del elemento de HTML
//Ejemplo: <input type="text" name="variable" /> coincide con la siguiente línea:
String variable = request.getParameter("variable");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Información del Libro</title>");
out.println("<link href=\"static/bookstore.css\" rel=\"stylesheet\" type=\"text/css\"/>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Se a creado un libro</h1>");
out.println("<p>Nombre: " + request.getParameter("txt-nombre") + " </p>");
out.println("<p>ISBN: " + request.getParameter("txt-isbn") + " </p>");
out.println("<p>Fecha de Publicación: " + request.getParameter("txt-fechaP") + " </p>");
out.println("<p>Género: " + request.getParameter("genero") + " </p>");
out.println("<p>Editorial: " + request.getParameter("txt-editorial") + " </p>");
out.println("<p>Autor: " + request.getParameter("txt-autor") + " </p>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package str;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Convert class provides convenient static methods to convert
* strings to integers, etc. */
public class Convert
{
// regular expressions
public static final String
COMPASS_DEGREES = "[-]?([0-9]|[0-9][0-9]|[0-2][0-9][0-9]|3[0-5][0-9])";
public static final String
COMPASS_HEADING = "[NSEW]|[NS][EW]|NN[EW]|SS[EW]|E[NS]E|W[NS]W|NORTH|SOUTH|EAST|WEST|NO|SO|EA|WE";
private static final Pattern IntPattern = Pattern.compile ("(-?\\d+)");
public static int toInt (String s)
{
return toInt (s, -1);
}
public static int toInt (String s, int defaultValue)
{
int value = defaultValue;
if ((s != null) && !s.trim().equals (""))
{
try
{
value = (int) Math.round (toDbl (s, defaultValue));
}
catch (NumberFormatException nfe)
{
System.out.println ("NumberFormatException: toInt (" + s + ")");
}
}
return value;
}
/**
* Convert a string contain multiple integers into an array of int
* values (using regular expression matching).
*/
public static List<Integer> toInts (String integers)
{
List<Integer> list = new ArrayList<Integer>();
if (integers != null)
{
Matcher matcher = IntPattern.matcher (integers);
while (matcher.find())
list.add (toInt (matcher.group (1)));
}
return list;
}
/**
* static method returns a String to represent the int constant
* passed as a parameter.
*
* @return String representation of constant.
*/
public static String toString (int i)
{
String strVal = null;
try
{
String s = Integer.toString (i);
if (s != null && s.length() > 0)
strVal = s;
}
catch (NumberFormatException nfe)
{
System.out.println ("NumberFormatException: toString (" + i + ")");
}
return strVal;
}
public static double toDbl (String s)
{
return toDbl (s, -1.0);
}
public static double toDbl (String s, double defaultValue)
{
double value = defaultValue;
if ((s != null) && !s.trim().equals (""))
{
try
{
value = Double.parseDouble (s.trim());
}
catch (NumberFormatException nfe)
{
System.out.println ("NumberFormatException: toDbl (" + s + ")");
}
}
return value;
}
/**
* static method returns a String to represent the double constant
* passed as a parameter.
*
* @return String representation of constant.
*/
public static String toString (double d)
{
String strVal = null;
try
{
String s = Double.toString (d);
if (s != null && s.length() > 0)
strVal = s;
}
catch (NumberFormatException nfe)
{
System.out.println ("NumberFormatException: toString (" + d + ")");
}
return strVal;
}
/**
* static method returns a String to represent the Double constant
* passed as a parameter.
*
* @return String representation of constant.
*/
public static String toString (Double d)
{
if (d != null)
return toString (d.doubleValue());
return null;
}
/**
* static method returns an RGB int from a Color
*
* @param color Color
* @return intVal int - RGB int value of Color
*/
public static int toRGB (Color color)
{
int intVal = 0;
if (color != null)
intVal = color.getRGB();
return intVal;
}
/**
* static method returns an RGB int from a Color. If the
* color parameter is null, use the default color
*
* @return RGB int value of Color
*/
public static int toRGB (Color color, Color defaultColor)
{
int intVal = 0;
if (color != null)
intVal = color.getRGB();
else if (defaultColor != null)
intVal = defaultColor.getRGB();
return intVal;
}
/**
* static method returns a Color from an RGB int
*
* @param rgb RGB int value of Color
* @return Color
*/
public static Color toColor (int rgb)
{
Color color = null;
if (rgb != 0)
color = new Color (rgb);
return color;
}
/**
* static method returns a Color from an RGB int
* if the RGB int value is 0, use the default
*
* @param rgb RGB int value of Color
* @return Color
*/
public static Color toColor (int rgb, Color defaultColor)
{
Color color = defaultColor;
if (rgb != 0)
color = new Color (rgb);
return color;
}
public static int toDegrees (String heading, int defaultDegrees)
{
int compassDegrees = defaultDegrees;
if (heading != null)
{
heading = heading.trim().toUpperCase();
if (RegExp.matches (COMPASS_DEGREES, heading))
{
compassDegrees = Integer.parseInt (heading);
if (compassDegrees < 0)
compassDegrees += 360;
}
else if (RegExp.matches (COMPASS_HEADING, heading))
{
if (heading.equals ("N")) compassDegrees = 0;
else if (heading.equals ("NO")) compassDegrees = 0;
else if (heading.equals ("NORTH")) compassDegrees = 0;
else if (heading.equals ("NNE")) compassDegrees = 22;
else if (heading.equals ("NE")) compassDegrees = 45;
else if (heading.equals ("ENE")) compassDegrees = 67;
else if (heading.equals ("E")) compassDegrees = 90;
else if (heading.equals ("EA")) compassDegrees = 90;
else if (heading.equals ("EAST")) compassDegrees = 90;
else if (heading.equals ("ESE")) compassDegrees = 112;
else if (heading.equals ("SE")) compassDegrees = 135;
else if (heading.equals ("SSE")) compassDegrees = 157;
else if (heading.equals ("S")) compassDegrees = 180;
else if (heading.equals ("SO")) compassDegrees = 180;
else if (heading.equals ("SOUTH")) compassDegrees = 180;
else if (heading.equals ("SSW")) compassDegrees = 202;
else if (heading.equals ("SW")) compassDegrees = 225;
else if (heading.equals ("WSW")) compassDegrees = 247;
else if (heading.equals ("W")) compassDegrees = 270;
else if (heading.equals ("WE")) compassDegrees = 270;
else if (heading.equals ("WEST")) compassDegrees = 270;
else if (heading.equals ("WNW")) compassDegrees = 292;
else if (heading.equals ("NW")) compassDegrees = 315;
else if (heading.equals ("NNW")) compassDegrees = 337;
}
else if (heading.length() > 0)
System.out.println ("Invalid heading: [" + heading + "]");
}
return compassDegrees;
}
public static void main (String[] args)
{
System.out.println ("Convert.toString (12): " + toString (12));
String s = "012.7";
System.out.println ("Convert.toDbl (" + s + "): " + toDbl (s));
System.out.println ("Convert.toInt (" + s + "): " + toInt (s));
s = "abc";
System.out.println ("Convert.toInt (" + s + "): " + toInt (s));
System.out.println ("Convert.toInt (" + s + ", 0): " + toInt (s, 0));
s = "1 2 x 3y";
System.out.print ("Convert.toInts (" + s + "): ");
for (int i : toInts (s))
System.out.print (i + ", ");
System.out.println();
}
}
|
package StellarisDK.FileClasses;
import java.util.regex.Pattern;
public class DataPattern {
/*
Groups are always defined as follows:
1 : Key
2 : Modifier specific for conditions
3 : Value
4 : Comments, if applicable
*/
// Pattern matches for single value variable
// i.e. key, size, power
public static final Pattern kv = Pattern.compile("(?m)^\\t?(\\w+)(\\s?[=<>]+\\s?)([^\\{#\\n]+)(#.+)*$");
// Pattern matches for single lines objects
// Group 1-3: Special match for color
// Group 4-6: Recursion Pattern
// Group 7-9: Standard key value pair
// Group 10-12: String literal pair
// Group 13: Special match for tags
public static final Pattern sLre = Pattern.compile("([\\w:]+)(\\s*[=><]+\\s*)((?:hsv|rgb)\\s*\\{.+?\\})|([\\w:]+)(\\s*[=><]+\\s*)\\{(.+?\\})|([\\w:]+)(\\s*[=><]+\\s*)([^\"]+?)\\s|([\\w:]+)(\\s*[=><]+\\s*)(.+?\")\\s*|([\\w\"]+)");
public static final Pattern color = Pattern.compile("^(hsv|rgb)\\s*\\{\\s*([\\d.]+)\\s*([\\d.]+)\\s*([\\d.]+)\\s*([\\d.]+)?\\s*\\}\\s?");
// Pattern matches for main data structure
// Group 1-4: Multi line recursion
// Group 5-8: Single line
public static final Pattern newCombine = Pattern.compile("(?m)^\\s?([\\w:]+)(\\s*[=<>]+\\s*)\\{\\s*(#.*)?[\\r\\n]([\\W\\D\\S]+?)^\\s?\\}|^\\s?(\\w+)(\\s*[=<>]+\\s*)([^#\\r\\n]+)(#.+)?");
// Mod Descriptor Specific Pattern
public static final Pattern mDSpec = Pattern.compile("(?s)(?m)^\\t?(\\w+)=\\{[\\r\\n](.+?)^\\}");
} |
package com.demo.entities;
import java.util.HashSet;
import java.util.Set;
import org.apache.ibatis.type.Alias;
/**
* 用户表
*
* @author Administrator
*
*/
@Alias("User")
public class User extends BaseEntity {
private static final long serialVersionUID = -1547458917316008286L;
/**
* 用户ID
*/
private int user_id;
/**
* 用户名
*/
private String user_name;
/**
* 用户密码
*/
private String password;
/**
* 用户类型(1:普通用户,2:管理员)
*/
private int user_type;
/**
* 用户锁定(1:未锁定,2:锁定)
*/
private int locked;
/**
* 积分
*/
private int credit = 0;
/**
* 用户管理版块
*/
private Set<Board> manBoards = new HashSet<Board>();
/**
* 最后登录信息
*/
private LoginLog loginLog = new LoginLog();
public User() {
}
public int getUser_id() {
return user_id;
}
public User setUser_id(int user_id) {
this.user_id = user_id;
return this;
}
public String getUser_name() {
return user_name;
}
public User setUser_name(String user_name) {
this.user_name = user_name;
return this;
}
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public int getUser_type() {
return user_type;
}
public User setUser_type(int user_type) {
this.user_type = user_type;
return this;
}
public int getLocked() {
return locked;
}
public User setLocked(int locked) {
this.locked = locked;
return this;
}
public int getCredit() {
return credit;
}
public User setCredit(int credit) {
this.credit = credit;
return this;
}
public Set<Board> getManBoards() {
return manBoards;
}
public User setManBoards(Set<Board> manBoards) {
this.manBoards = manBoards;
return this;
}
public LoginLog getLoginLog() {
return loginLog;
}
public User setLoginLog(LoginLog loginLog) {
this.loginLog = loginLog;
return this;
}
}
|
package io.dcbn.backend.password_reset.models;
import io.dcbn.backend.authentication.models.DcbnUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.EnumSet;
@Component
public enum MailType {
PASSWORD_RESET {
@Override
public String generateMailBody(DcbnUser user) {
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, resetTokenDurationInMinutes);
String token = Jwts.builder()
.signWith(Keys.hmacShaKeyFor(secret.getBytes()), SignatureAlgorithm.HS512)
.setSubject("" + user.getId())
.setExpiration(now.getTime())
.compact();
return passwordResetTemplate.replace("{key}", token);
}
};
@Component
public static class MailTypeInjector {
@Value("${jwt.secret}")
private String secret;
@Value("${jtw.reset.duration}")
private int resetTokenDurationInMinutes;
@Value("${reset.template}")
private String resetPasswordTemplateFilename;
@PostConstruct
public void postConstruct() throws URISyntaxException, IOException {
Path path = Paths.get("src", "main", "resources", resetPasswordTemplateFilename);
byte[] bytes = Files.readAllBytes(path);
String passwordResetTemplate = new String(bytes, StandardCharsets.UTF_8);
for (MailType mt : EnumSet.allOf(MailType.class)) {
mt.setSecret(secret);
mt.setResetTokenDurationInMinutes(resetTokenDurationInMinutes);
mt.setPasswordResetTemplate(passwordResetTemplate);
}
}
}
@Setter
protected String secret;
@Setter
protected int resetTokenDurationInMinutes = 30;
@Setter
protected String passwordResetTemplate;
public abstract String generateMailBody(DcbnUser user);
}
|
package com.lenovohit.hcp.finance.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.lenovohit.core.model.BaseIdModel;
import com.lenovohit.hcp.base.annotation.RedisSequence;
import com.lenovohit.hcp.base.model.Department;
@Entity
@Table(name = "OC_INVOICEINFO_DETAIL") // 发票信息详情表
public class InvoiceInfoDetail extends BaseIdModel {
private static final long serialVersionUID = 1L;
private String regId;
private String hosId;
private Integer plusMinus; // 正负类型|1正-1负
private String invoiceNo;
private String recipeId;
private String feeCode; // 费用分类|FEE_CODE
private BigDecimal totCost;
private Department recipeDept;
private Department exeDept;
private String cancelFlag; // 停用标志|0-停1启
private String cancelOper;
private Date cancelTime;
@ManyToOne
@JoinColumn(name = "RECIPE_DEPT")
public Department getRecipeDept() {
return recipeDept;
}
public void setRecipeDept(Department recipeDept) {
this.recipeDept = recipeDept;
}
public String getRegId() {
return regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
public void setPlusMinus(Integer plusMinus) {
this.plusMinus = plusMinus;
}
public Integer getPlusMinus() {
return plusMinus;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
@RedisSequence
public String getRecipeId() {
return recipeId;
}
public void setRecipeId(String recipeId) {
this.recipeId = recipeId;
}
public String getFeeCode() {
return feeCode;
}
public void setFeeCode(String feeCode) {
this.feeCode = feeCode;
}
public BigDecimal getTotCost() {
return totCost;
}
public void setTotCost(BigDecimal totCost) {
this.totCost = totCost;
}
public String getCancelFlag() {
return cancelFlag;
}
public void setCancelFlag(String cancelFlag) {
this.cancelFlag = cancelFlag;
}
public String getHosId() {
return hosId;
}
public void setHosId(String hosId) {
this.hosId = hosId;
}
public String getCancelOper() {
return cancelOper;
}
public void setCancelOper(String cancelOper) {
this.cancelOper = cancelOper;
}
public Date getCancelTime() {
return cancelTime;
}
public void setCancelTime(Date cancelTime) {
this.cancelTime = cancelTime;
}
@ManyToOne
@JoinColumn(name = "EXE_DEPT")
public Department getExeDept() {
return exeDept;
}
public void setExeDept(Department exeDept) {
this.exeDept = exeDept;
}
} |
package com.track.common.trans;
/**
* Rpc响应
*
* @author zap
* @version 1.0, 2017/11/20
*/
public class RpcResponse {
private String id;
private Throwable error;
private Object result;
public boolean isError() {
return null != this.error;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Throwable getError() {
return error;
}
public void setError(Throwable error) {
this.error = error;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
|
package com.lab.androidalarm;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String KEY_NOTIFY = "key_notify";
private static final String KEY_INTERVAL = "key_interval";
private static final String KEY_HOUR = "key_hour";
private static final String KEY_MINUTE = "key_minute";
private TimePicker timePicker;
private Button btnNotify;
private EditText editMinutes;
private int interval;
private int hour;
private int minute;
private boolean isActivated;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.time_picker);
btnNotify = findViewById(R.id.btn_notify);
editMinutes = findViewById(R.id.edit_number_interval);
final SharedPreferences storage = getSharedPreferences("storage", Context.MODE_PRIVATE);
isActivated = storage.getBoolean(KEY_NOTIFY, false);
if(isActivated) {
btnNotify.setText(R.string.pause);
btnNotify.setBackgroundColor(ContextCompat.getColor(MainActivity.this, android.R.color.holo_green_light));
editMinutes.setText(String.valueOf(storage.getInt(KEY_INTERVAL, 0)));
timePicker.setCurrentHour(storage.getInt(KEY_HOUR, timePicker.getCurrentHour()));
timePicker.setCurrentMinute(storage.getInt(KEY_MINUTE, timePicker.getCurrentMinute()));
} else {
btnNotify.setText(R.string.notify);
btnNotify.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
}
timePicker.setIs24HourView(true);
btnNotify.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(!isActivated){
String sInterval = editMinutes.getText().toString();
if (sInterval.isEmpty()){
Toast.makeText(MainActivity.this, R.string.toastMessage, Toast.LENGTH_SHORT).show();
return;
}
interval = Integer.parseInt(sInterval);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
Log.d("Test", String.format("%d, %d, %d", interval, hour, minute));
btnNotify.setText(R.string.pause);
btnNotify.setBackgroundColor(ContextCompat.getColor(MainActivity.this, android.R.color.holo_green_light));
SharedPreferences.Editor edit = storage.edit();
edit.putBoolean(KEY_NOTIFY, true);
edit.putInt(KEY_INTERVAL, interval);
edit.putInt(KEY_HOUR, hour);
edit.putInt(KEY_MINUTE, minute);
edit.apply();
isActivated = true;
} else {
btnNotify.setText(R.string.notify);
btnNotify.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
SharedPreferences.Editor edit = storage.edit();
edit.putBoolean(KEY_NOTIFY, false);
edit.remove(KEY_INTERVAL);
edit.remove(KEY_HOUR);
edit.remove(KEY_MINUTE);
edit.apply();
isActivated = false;
}
}
});
}
} |
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.eao.gis.impl;
import java.util.List;
import org.inbio.ara.eao.gis.*;
import javax.ejb.Stateless;
import javax.persistence.Query;
import org.inbio.ara.dto.gis.GeographicLayerDTO;
import org.inbio.ara.eao.BaseEAOImpl;
import org.inbio.ara.persistence.gis.Country;
/**
*
* @author esmata
*/
@Stateless
public class CountryEAOImpl extends BaseEAOImpl<Country,Long> implements CountryEAOLocal {
@Deprecated
public List<GeographicLayerDTO> getAllCountries() {
Query query = em.createQuery("select new org.inbio.ara.dto.gis.GeographicLayerDTO(c.value,c.countryId) from Country as c");
return query.getResultList();
}
public List<Country> allCountryOrderByValue(){
Query q = em.createQuery("from Country order by value");
return (List<Country>)q.getResultList();
}
public List<Country> listAll(){
Query q = em .createQuery("select c from Country as c order by c.value asc");
return q.getResultList();
}
}
|
package com.microsoft.bingads.v10.api.test.entities.ad_extension.review;
import com.microsoft.bingads.v10.api.test.entities.PerformanceDataTestHelper;
import com.microsoft.bingads.v10.bulk.entities.BulkAdGroupReviewAdExtension;
import org.junit.Test;
public class BulkAdGroupReviewAdExtensionReadWriteTest {
@Test
public void bulkAdGroupReviewAdExtension_ReadPerfData_WriteToFile() {
PerformanceDataTestHelper.testPerformanceDataReadWrite(new BulkAdGroupReviewAdExtension());
}
} |
package main;
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class GL3dObject {
ArrayList<Vertex> vertexes = new ArrayList<>();
ArrayList<Face> faces = new ArrayList<>();
public int[] VAO = new int[1];
private float[] position = new float[3];
public GL3dObject() {
position[0] = 0;
position[1] = 0.3f;
position[2] = 0.0f;
}
public float[] getPosition(){
return position;
}
public void addVertex(String string, String string2, String string3) {
Vertex newVertex = new Vertex(Float.parseFloat(string),Float.parseFloat(string2),Float.parseFloat(string3));
vertexes.add(newVertex);
}
public void addFace(String string, String string2, String string3) {
Face newFace = new Face(Integer.parseInt(string),Integer.parseInt(string2),Integer.parseInt(string3));
faces.add(newFace);
}
public class Vertex{
float vert1;
float vert2;
float vert3;
public Vertex(float one, float two,float three){
vert1 = one;
vert2 = two;
vert3 = three;
}
public float getVertex(int vertex) {
if(vertex == 0){
return vert1;
}
else if(vertex == 1){
return vert2;
}
else if(vertex == 2){
return vert3;
}
return -1;
}
}
public class Face{
int firstVertex,secondVertex,thirdVertex;
public Face(int first,int second,int third){
firstVertex = first-1;
secondVertex = second-1;
thirdVertex = third-1;
}
public int getVertex(int vertex) {
if(vertex == 0){
return firstVertex;
}
else if(vertex == 1){
return secondVertex;
}
else if(vertex == 2){
return thirdVertex;
}
return -1;
}
}
public ArrayList<Face> getFaces() {
return faces;
}
public ArrayList<Vertex> getVertexes() {
return vertexes;
}
}
|
package com.pe.sanpedro.mybatis.mapper;
import java.util.List;
import com.pe.sanpedro.model.Especialidad;
public interface EspecialidadMapper {
public List<Especialidad> listaEspecialidades() throws Exception;
}
|
package bd.ac.du.iit.bsse0516;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CodeReader {
private String filePath;
public CodeReader(String filePath) {
this.filePath = filePath;
}
public String getCode() {
String data = "";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
StringBuilder stringBuilder = new StringBuilder();
String leachLine = reader.readLine();
while (leachLine != null) {
stringBuilder.append(leachLine);
stringBuilder.append(System.lineSeparator());
leachLine = reader.readLine();
}
data = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
|
package ru.skillfactory;
import ru.skillfactory.actions.*;
/**
* Класс, который запускает общение с пользователем.
*/
public class StartUI {
/**
* Здесь будет происходить инициализация меню, вы
* 1. Авторизовываете пользователя.
* 2. Печатаете меню.
* 3. В зависимости от введённого числа запускаете нужную функцию.
*
* @param bankService BankService объект.
* @param actions массив с действиями.
* @param input Input объект.
*/
public void init(BankService bankService, UserAction[] actions, Input input) {
String requisite = authorization(bankService, input);
showMenu(actions);
boolean run = true;
while (run) {
int select = input.askInt("Выберите пункт меню: ");
// Здесь такой if, который не даст выйти в ArrayIndexOutOfBoundsException.
if (select >= 0 && select <= actions.length - 1) {
// Мы по индексу массива вызываем метод execute нашего Action-объекта.
run = actions[select].execute(bankService, input, requisite);
} else {
System.out.println("Такого пункта нету...");
}
}
}
/**
* Метод должен работать пока пользователь не авторизуется (пока отключил цикл!).
*
* @param bankService BankService объект.
* @param input Input объект.
* @return возвращает реквизиты аккаунта, под которым авторизовался пользователь.
* Получайте их вызывом метода getRequisiteIfPresent, класса BankService.
*/
private String authorization(BankService bankService, Input input) {
String rsl = null;
boolean authComplete = true;
while (!authComplete) { // цикл отключён!!!
/*
* Запрашиваете у пользователя логин, пароль пока он не пройдёт авторизацию.
* Авторизация пройдена при условие что в BankService есть пользователь с
* данным логином и паролем (работайте только с теми пользователями что есть).
*/
String login = input.askStr("Ваш логин: ");
String password = input.askStr("Ваш password: ");
}
return rsl;
}
/**
* Печатается меню пользователя (только печатается, общения с пользователем нету).
*
* @param actions массив с действиями.
*/
private void showMenu(UserAction[] actions) {
System.out.println("Menu.");
for (int index = 0; index < actions.length; index++) {
System.out.println(index + ". " + actions[index].getTitle());
}
}
public static void main(String[] args) {
BankService bankService = new BankService();
// здесь создадите несколько аккаунтов на проверку
// данные осмысленно заполните, не просто пустые строки
bankService.addAccount(new BankAccount("", "", ""));
// Ещё аккаунты
// В массиве хранятся объекты, которые представляют наши действия.
UserAction[] actions = {
new ShowBalanceAction(),
new TopUpBalanceAction(),
new TransferToAction(),
new Exit()
};
// Наш Input можно менять на нужную реализацию (ValidateInput доделайте)
Input input = new ValidateInput();
// Запускаем наш UI передавая аргументами банковский сервис, экшены и Input.
new StartUI().init(bankService, actions, input);
}
}
|
package com.novakivska.app.classwork.lesson16;
/**
* Created by Tas_ka on 5/12/2017.
*/
public class ACMEBicycle implements Bicycle, PartsStandard, Maintenance {
int cadence = 0;
int gear = 10;
int speed = 5;
@Override
public void changeGear(int newValue) {
this.gear = newValue;
}
@Override
public void changeCadence(int newValue) {
this.cadence = newValue;
}
public void printStates(){
System.out.println("Speed is " + speed);
}
@Override
public void useEcoItems() {
System.out.println("Use eco items!");
}
@Override
public void clean() {
System.out.println("We will clean you!");
}
public String toString(){
return "ACMEBicycle{"+
"cadence=" + cadence +
", gear=" + gear +
", speed=" + speed +
'}';
}
}
|
package com.okayboom.particlesim.physics;
import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;
public class VectorGen extends Generator<Vector> {
private static final double chanceOfZero = 0.1;
private static final double rangeMax = 1e6;
public VectorGen() {
super(Vector.class);
}
@Override
public Vector generate(SourceOfRandomness random, GenerationStatus status) {
return new Vector(withChanceOfZero(random), withChanceOfZero(random));
}
double withChanceOfZero(SourceOfRandomness random) {
return (random.nextDouble() < chanceOfZero) ? 0.0 : random.nextDouble(
-rangeMax, rangeMax);
}
}
|
package by.orion.onlinertasks.common.triple;
public final class ImmutableTriple<L, M, R> extends Triple<L, M, R> {
/** Serialization version */
private static final long serialVersionUID = 1L;
/** Left object */
private final L left;
/** Middle object */
private final M middle;
/** Right object */
private final R right;
/**
* <p>Obtains an immutable triple of from three objects inferring the generic types.</p>
*
* <p>This factory allows the triple to be created using inference to
* obtain the generic types.</p>
*
* @param <L> the left element type
* @param <M> the middle element type
* @param <R> the right element type
* @param left the left element, may be null
* @param middle the middle element, may be null
* @param right the right element, may be null
* @return a triple formed from the three parameters, not null
*/
public static <L, M, R> ImmutableTriple<L, M, R> of(final L left, final M middle, final R right) {
return new ImmutableTriple<>(left, middle, right);
}
/**
* Create a new triple instance.
*
* @param left the left value, may be null
* @param middle the middle value, may be null
* @param right the right value, may be null
*/
public ImmutableTriple(final L left, final M middle, final R right) {
super();
this.left = left;
this.middle = middle;
this.right = right;
}
//-----------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public L getLeft() {
return left;
}
/**
* {@inheritDoc}
*/
@Override
public M getMiddle() {
return middle;
}
/**
* {@inheritDoc}
*/
@Override
public R getRight() {
return right;
}
} |
package carbase.connection;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Operations {
public static boolean isLogin(String username, String password, JFrame frame)
{
try {
Connection myConn = MySQLConnection.getConnection();
String mySqlQuery = "SELECT UID, Nickname from login where Username = '" + username + "' AND Password = '" + password + "'";
PreparedStatement preparedStatement = myConn.prepareStatement(mySqlQuery);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
LoginSession.UID = resultSet.getInt("UID");
LoginSession.Nickname = resultSet.getString("Nickname");
return true;
}
}catch (Exception exception)
{
JOptionPane.showMessageDialog(frame, "Database error: " + exception.getMessage());
}
return false;
}
}
|
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 12/03/13
* Time: 14:33
* To change this template use File | Settings | File Templates.
*/
import com.sun.corba.se.impl.logging.ORBUtilSystemException;
import java.math.*;
public class SortTest {
public static void main (String[] args) {
int[] myArray;
myArray=new int[10];
for (int i=0; i<myArray.length; i++) {
myArray[i]= (int) (Math.random()*100);
System.out.printf("Element %d Equals %d\n",i,myArray[i]);
}
Sort srt=new Sort();
srt.bSort(myArray);
for (int i=0; i<myArray.length; i++) {
System.out.printf("Element %d Equals %d\n",i,myArray[i]);
}
}
}
|
package cn.kgc.service;
import cn.kgc.domain.Accountes;
import java.util.List;
public interface NewOrderService {
//查询最新订单
public List<Accountes> findneworder();
}
|
package com.gestion.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
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.hibernate.Session;
import com.gestion.entity.Client;
import com.gestion.entity.Livraison;
import com.gestion.service.ServiceClientCortex2i;
import com.gestion.service.ServiceLivraison;
import com.gestion.service.date.Formatter;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ServletAddlivraison
*/
@WebServlet("/ServletAddlivraison")
public class ServletAddlivraison extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletAddlivraison() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Session s = HibernateUtils.getSession();
String message = null ;
String nomcl = request.getParameter("client");
String dateliv = request.getParameter("dateLiv");
String article = request.getParameter("article");
String designation = request.getParameter("designation");
String quantite = request.getParameter("quantite");
String nserie = request.getParameter("nserie");
Client client = new Client();
client.setNom(nomcl);
client = ServiceClientCortex2i.rechercheClientCortex2iByName(s, client);
if(client!=null)
{
Livraison livraison = new Livraison (client , Formatter.converteStrDate(dateliv , new SimpleDateFormat("dd-MM-yyyy")) , article , designation , quantite , nserie );
message = ServiceLivraison.addLivraison(s, livraison);
s.close();
s = HibernateUtils.getSession();
Livraison liv = ServiceLivraison.LastLivraison(s , livraison);
ServiceLivraison.update(s, liv);
}
else
{
message = "Ce client n'existe pas !";
}
request.setAttribute("message", message);
request.getServletContext().getRequestDispatcher("/ServletGestionLivraison").forward(request, response);
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
package cz.dix.alg.genetics.strategy.impl;
import cz.dix.alg.genetics.Population;
import cz.dix.alg.genetics.PopulationMember;
import cz.dix.alg.genetics.strategy.ReplacementStrategy;
/**
* Simple replacement strategy that replaces the old member by the new member (1:1).
*
* @author Zdenek Obst, zdenek.obst-at-gmail.com
*/
public class OneToOneReplacementStrategy implements ReplacementStrategy {
/**
* {@inheritDoc}
*/
public void replace(Population population, PopulationMember oldMember, PopulationMember newMember) {
population.replaceMember(oldMember, newMember);
}
}
|
package com.androidvoyage.bmc.utils;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtils {
/**
* Represents the end-of-file (or stream).
*
* @since 2.5 (made public)
*/
public static final int EOF = -1;
/**
* The default buffer size ({@value}) to use for
* {@link #copyLarge(InputStream, OutputStream)}
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/* Get uri related content real local file path. */
public static String getPath(Context ctx, Uri uri) {
String ret;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Android OS above sdk version 19.
ret = getUriRealPathAboveKitkat(ctx, uri);
} else {
// Android OS below sdk version 19
ret = getRealPath(ctx.getContentResolver(), uri, null);
}
} catch (Exception e) {
e.printStackTrace();
Log.d("DREG", "FilePath Catch: " + e);
ret = getFilePathFromURI(ctx, uri);
}
return ret;
}
private static String getFilePathFromURI(Context context, Uri contentUri) {
//copy file and send new file path
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
String TEMP_DIR_PATH = ImageLoader.getPathName();
File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName);
Log.d("DREG", "FilePath copyFile: " + copyFile);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
copy(inputStream, outputStream); // org.apache.commons.io
inputStream.close();
outputStream.close();
} catch (Exception e) { // IOException
e.printStackTrace();
}
}
/**
* Copies bytes from an <code>InputStream</code> to an
* <code>OutputStream</code>.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
* <p>
* Large streams (over 2GB) will return a bytes copied value of
* <code>-1</code> after the copy has completed since the correct
* number of bytes cannot be returned as an int. For large streams
* use the <code>copyLarge(InputStream, OutputStream)</code> method.
*
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @return the number of bytes copied, or -1 if > Integer.MAX_VALUE
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 1.1
*/
public static int copy(final InputStream input, final OutputStream output) throws IOException {
final long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
/**
* Copies bytes from a large (over 2GB) <code>InputStream</code> to an
* <code>OutputStream</code>.
* <p>
* This method buffers the input internally, so there is no need to use a
* <code>BufferedInputStream</code>.
* <p>
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @return the number of bytes copied
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 1.3
*/
private static long copyLarge(final InputStream input, final OutputStream output)
throws IOException {
return copy(input, output, DEFAULT_BUFFER_SIZE);
}
/**
* Copies bytes from an <code>InputStream</code> to an <code>OutputStream</code> using an internal buffer of the
* given size.
* <p>
* This method buffers the input internally, so there is no need to use a <code>BufferedInputStream</code>.
* <p>
*
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param bufferSize the bufferSize used to copy from the input to the output
* @return the number of bytes copied
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 2.5
*/
private static long copy(final InputStream input, final OutputStream output, final int bufferSize)
throws IOException {
return copyLarge(input, output, new byte[bufferSize]);
}
/**
* Copies bytes from a large (over 2GB) <code>InputStream</code> to an
* <code>OutputStream</code>.
* <p>
* This method uses the provided buffer, so there is no need to use a
* <code>BufferedInputStream</code>.
* <p>
*
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param buffer the buffer to use for the copy
* @return the number of bytes copied
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 2.2
*/
private static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
throws IOException {
long count = 0;
int n;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static String getUriRealPathAboveKitkat(Context ctx, Uri uri) {
String ret = "";
if (ctx != null && uri != null) {
if (isContentUri(uri)) {
if (isGooglePhotoDoc(uri.getAuthority())) {
ret = uri.getLastPathSegment();
} else {
ret = getRealPath(ctx.getContentResolver(), uri, null);
}
} else if (isFileUri(uri)) {
ret = uri.getPath();
} else if (isDocumentUri(ctx, uri)) {
// Get uri related document _id.
String documentId = DocumentsContract.getDocumentId(uri);
// Get uri authority.
String uriAuthority = uri.getAuthority();
if (isMediaDoc(uriAuthority)) {
String idArr[] = documentId.split(":");
if (idArr.length == 2) {
// First item is document type.
String docType = idArr[0];
// Second item is document real _id.
String realDocId = idArr[1];
// Get content uri by document type.
Uri mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
if ("image".equals(docType)) {
mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(docType)) {
mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(docType)) {
mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
// Get where clause with real document _id.
String whereClause = MediaStore.Images.Media._ID + " = " + realDocId;
ret = getRealPath(ctx.getContentResolver(), mediaContentUri, whereClause);
}
} else if (isDownloadDoc(uriAuthority)) {
// Build download uri.
Uri downloadUri = Uri.parse("content://downloads/public_downloads");
// Append download document _id at uri end.
Uri downloadUriAppendId = ContentUris.withAppendedId(downloadUri, Long.valueOf(documentId));
ret = getRealPath(ctx.getContentResolver(), downloadUriAppendId, null);
} else if (isExternalStoreDoc(uriAuthority)) {
String idArr[] = documentId.split(":");
if (idArr.length == 2) {
String type = idArr[0];
String realDocId = idArr[1];
if ("primary".equalsIgnoreCase(type)) {
ret = Environment.getExternalStorageDirectory() + "/" + realDocId;
}
}
}
}
}
return ret;
}
/* Check whether this uri represent a document or not. */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static boolean isDocumentUri(Context ctx, Uri uri) {
boolean ret = false;
if (ctx != null && uri != null) {
ret = DocumentsContract.isDocumentUri(ctx, uri);
}
return ret;
}
/* Check whether this uri is a content uri or not.
* content uri like content://media/external/images/media/1302716
* */
private static boolean isContentUri(Uri uri) {
boolean ret = false;
if (uri != null) {
String uriSchema = uri.getScheme();
if ("content".equalsIgnoreCase(uriSchema)) {
ret = true;
}
}
return ret;
}
/* Check whether this uri is a file uri or not.
* file uri like file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg
* */
private static boolean isFileUri(Uri uri) {
boolean ret = false;
if (uri != null) {
String uriSchema = uri.getScheme();
if ("file".equalsIgnoreCase(uriSchema)) {
ret = true;
}
}
return ret;
}
/* Check whether this document is provided by ExternalStorageProvider. */
private static boolean isExternalStoreDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.externalstorage.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by DownloadsProvider. */
private static boolean isDownloadDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.providers.downloads.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by MediaProvider. */
private static boolean isMediaDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.providers.media.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by google photos. */
private static boolean isGooglePhotoDoc(String uriAuthority) {
boolean ret = false;
if ("com.google.android.apps.photos.content".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Return uri represented document file real local path.*/
@SuppressLint("Recycle")
private static String getRealPath(ContentResolver contentResolver, Uri uri, String whereClause) {
String ret = "";
// Query the uri with condition.
Cursor cursor = contentResolver.query(uri, null, whereClause, null, null);
if (cursor != null) {
boolean moveToFirst = cursor.moveToFirst();
if (moveToFirst) {
// Get columns name by uri type.
String columnName = MediaStore.Images.Media.DATA;
if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Images.Media.DATA;
} else if (uri == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Audio.Media.DATA;
} else if (uri == MediaStore.Video.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Video.Media.DATA;
}
// Get column index.
int columnIndex = cursor.getColumnIndex(columnName);
// Get column value which is the uri related file local path.
ret = cursor.getString(columnIndex);
}
}
return ret;
}
} |
package com.barrunner.model;
import com.badlogic.gdx.Gdx;
public class HeadsUpDisplay {
/* Variables */
private float timeElapsed;
private World world;
/* Constructors */
public HeadsUpDisplay(World world)
{
this.world = world;
InitializeHUD();
}
/* Methods */
public void update() {
timeElapsed += Gdx.graphics.getDeltaTime();
}
public float GetTimeElapsed() {
return timeElapsed;
}
public int GetDrunkPercentage() {
return world.GetDrunkPercentage();
}
/* Helper Methods */
private void InitializeHUD() {
timeElapsed = 0f;
}
}
|
package com.lzm.KnittingHelp.db.exceptions;
public class PartException extends Exception {
public PartException(String message) {
super(message);
}
}
|
package structural.flyweight;
/**
* @author Renat Kaitmazov
*/
/**
* A class whose instances need to be created in a huge amount.
* Such a class must have intrinsic attributes which are shared amongst
* other instances, and extrinsic attributes which are unique to each
* instance. The intrinsic attributes are used by a factory class that creates
* new instances only if such an instance with that intrinsic attribute
* has not been created before.
* The extrinsic attributes are set by the client.
*/
public final class MusicBox implements Toy {
/*--------------------------------------------------------*/
/* Static variables
/*--------------------------------------------------------*/
// For testing purposes
private static int INSTANCES_CREATED = 0;
/*--------------------------------------------------------*/
/* Instance variables
/*--------------------------------------------------------*/
// Intrinsic attributes
private final String color;
// Extrinsic attributes
private String tuneName;
/*--------------------------------------------------------*/
/* Constructors
/*--------------------------------------------------------*/
MusicBox(String color) {
this.color = color;
System.out.println("MusicBox instance is created.");
++INSTANCES_CREATED;
}
/*--------------------------------------------------------*/
/* Setters
/*--------------------------------------------------------*/
public final void setTuneName(String tuneName) {
this.tuneName = tuneName;
}
/*--------------------------------------------------------*/
/* API
/*--------------------------------------------------------*/
public static int getCreatedInstancesAmount() {
return INSTANCES_CREATED;
}
@Override
public final void entertain() {
// Doing some stuff to entertain people.
}
}
|
/*
COPYRIGHT NOTICE
Copyright 2017 Intellect Design Arena Limited. All rights reserved.
These materials are confidential and proprietary to
Intellect Design Arena Limited and no part of these materials should
be reproduced, published, transmitted or distributed in any form or
by any means, electronic, mechanical, photocopying, recording or
otherwise, or stored in any information storage or retrieval system
of any nature nor should the materials be disclosed to third parties
or used in any other manner for which this is not authorized, without
the prior express written authorization of Intellect Design Arena Limited.
*/
/*******************************************************************************************
*
* Module Name : PaymentsValidation
*
* File Name : SupportingDocUploadValidationAPI.java
*
* Description : ************************
*
* Version Control Block
*
* Date Version Author Description
* --------- -------- --------------- ---------------------------
* 22-June-2017 0.1 Kiran Barik First version
*******************************************************************************************/
package com.intellect.ipsh.stpframework.cbx.actionapi;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellect.igtb.ipsh.api.model.response.StandardResponse;
public class SupportingDocUploadValidationAPI {
public String validation(String jsonInString) {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper();
System.out.println(".........ValidateSingleTransaction.....................");
String strJson=null;
try {
StandardResponse s = new StandardResponse();
s.setResCode("200");
s.setDevMsg("OK");
s.setResMsg("OK");
strJson = mapper.writeValueAsString(s);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(".........ValidateSingleTransaction....end.................");
return strJson;
}
}
|
package cn.org.metter.hitogether_android.useclass;
/**
* Created by Administrator on 2016/1/1.
*/
public class ActInformation {
}
|
package bnogent.m;
public class Value {
private boolean animation = false;
private double initValue;
private double finalValue;
private double currentValue;
private long startTime;
private int delay;
public Object easing;
public Value(double v) {
setVal(v);
}
public void setVal(double v) {
currentValue = v;
animation = false;
}
public void setVal(double v, int ms) {
animation = true;
delay = ms;
startTime = System.currentTimeMillis();
initValue = currentValue;
finalValue = v;
}
public double getVal() {
long currentTime = System.currentTimeMillis();
if (animation == false) {
return currentValue;
}
long msEllapsed = Math.abs(currentTime - startTime);
if (msEllapsed >= delay) {
animation = false;
currentValue = finalValue;
return currentValue;
} else {
double f = (double) msEllapsed / (double) delay;
currentValue = initValue + (finalValue - initValue)
//* Easing.easeInOutQuint(f);
* Easing.easeInOutCubic(f);
return currentValue;
}
}
}
|
package usaco;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
class UsacoTest {
public UsacoTest() {
}
@Test
public void tttt_bronze_open18() throws IOException {
String dataPath = "C:\\Users\\kenneth.choe\\Downloads\\tttt_bronze_open18";
prepareData(dataPath);
UsacoTemplate.main(new String[] {});
validateResult(dataPath);
}
private void prepareData(String sourcePath) throws IOException {
String targetPath = System.getProperty("user.dir");
File source = new File(sourcePath);
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
for (final File file : source.listFiles()) {
if (file.getName().endsWith(".in")) {
Files.copy(file.toPath(), Paths.get(targetPath + "\\" + file.getName()), options);
}
}
}
private void validateResult(String sourcePath) throws IOException {
String targetPath = System.getProperty("user.dir");
File path = new File(sourcePath);
for (final File file : path.listFiles()) {
if (file.getName().endsWith(".out")) {
List<String> sourceContent = Files.readAllLines(file.toPath());
List<String> targetContent = Files.readAllLines(Paths.get(targetPath + "\\" + file.getName()));
Assert.assertThat(targetContent, is(sourceContent));
}
}
}
}
|
package practicedemo;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter age");
Scanner sc= new Scanner(System.in);
int age = sc.nextInt();
if(age > 18)
System.out.println("adult");
else
System.out.println("not an adult");
}
}
|
public class Main {
public static void main(String[] args) {
HorseManager horseManager = new HorseManager();
horseManager.setHorseScreen(new ConsoleScreen());
horseManager.addHorse(HorseFactory.create(HorseType.Jeju));
horseManager.addHorse(HorseFactory.create(HorseType.My));
horseManager.addHorse(HorseFactory.create(HorseType.Black));
horseManager.playGame();
}
}
|
package com.atguigu.java;
class PrintHeart{
public static void main(String[] args){
System.out.print("\t");
System.out.print("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.println("*");
System.out.print("*");
System.out.print("\t");
//System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("I love java");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.println("*");
System.out.print("\t");
System.out.print("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.println("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.println("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.println("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
System.out.print("*");
System.out.print("\t");
System.out.println("*");
System.out.print("\t");
System.out.print("\t");
System.out.print("\t");
//System.out.print("\t");
System.out.print(" ");
System.out.print("*");
}
} |
package edu.ktu.ds.lab1b.stasaitis;
public class CPU_Select {
public CPU_Data Current_Data = new CPU_Data();
public CPU_Data getCpuByBase(int min, int max)
{
CPU_Data data = new CPU_Data();
for (CPU cpu: Current_Data
) {
if(cpu.Get_Cpu_Base_Min() >= min && cpu.Get_Cpu_Base_Max() <= max)
{
data.add(cpu);
}
}
return data;
}
public CPU_Data getCpuByPrice(boolean lessOr, double price)
{
CPU_Data data = new CPU_Data();
for(CPU cpu : Current_Data)
{
if(lessOr ? cpu.Get_Cpu_Price() <= price : cpu.Get_Cpu_Price() >= price)
{
data.add(cpu);
}
}
return data;
}
}
|
package br.com.saulofarias.customerapi.constants;
public class MessagesConst {
public static String CUSTOMER_NOT_FOUND = "Could not find customer ";
public static String CITY_NOT_FOUND = "Could not find city ";
public static String ID_NOT_NULL = "Id cannot be null";
public static String NAME_NOT_EMPTY = "The name cannot be empty";
public static String CITY_NOT_EMPTY = "The City cannot be empty";
public static String STATE_NOT_EMPTY = "The State cannot be empty";
}
|
package com.wipro.exceptionhandling;
import java.util.Scanner;
@SuppressWarnings("serial")
class InvalidCountryException extends Exception
{
InvalidCountryException()
{
super("User Outside India cannot be registered");
}
}
public class UserRegistration
{
public void registerUser(String username,String userCountry) throws InvalidCountryException
{
if(userCountry.equalsIgnoreCase("India"))
System.out.println("User registration done successfully");
else
throw new InvalidCountryException();
}
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
UserRegistration u1=new UserRegistration();
String userName=scan.nextLine();
String userCountry=scan.nextLine();
try
{
u1.registerUser(userName,userCountry);
}
catch (InvalidCountryException e)
{
System.out.println(e);
}
finally
{
scan.close();
; }
}
}
|
package cn.edu.nju.software.timemachine.service;
import java.util.List;
import cn.edu.nju.software.timemachine.entity.User;
import cn.edu.nju.software.timemachine.util.Constraint;
public interface IUserService<T extends User> extends IService<T> {
public boolean addUser(T user);
public T getUser(long id);
public T getUser(String email,String password);
public List<T> searchUserByName(String name);
public T searchUserByEmail(String email);
public List<T> serchUser(Constraint constraint);
public T getUser(String email);
}
|
package com.neo.listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
/**
* ApplicationReadyEvent is sent after any application and command-line runners have been called.
* It indicates that the application is ready to service requests.
*/
@Slf4j
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("onApplicationEvent(event={})", event);
}
}
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.hive;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import junit.framework.TestCase;
import java.util.List;
public class HiveSelectTest_45_issue_3987 extends TestCase {
public void test_0() throws Exception {
String sql = "select id,number_id,parent_id,layer_id,alias,name \n" +
"from (select id,number_id,parent_id,layer_id,alias,name,row_number() over(distribute by number_id sort by create_time desc,id desc) rownum from hdw_ods.ods_my_coredata__dts_device_category where pdate ='') m where m.rownum = 1";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, DbType.hive);
SQLStatement stmt = statementList.get(0);
assertEquals("SELECT id, number_id, parent_id, layer_id, alias\n" +
"\t, name\n" +
"FROM (\n" +
"\tSELECT id, number_id, parent_id, layer_id, alias\n" +
"\t\t, name, row_number() OVER (DISTRIBUTE BY number_id SORT BY create_time DESC, id DESC) AS rownum\n" +
"\tFROM hdw_ods.ods_my_coredata__dts_device_category\n" +
"\tWHERE pdate = ''\n" +
") m\n" +
"WHERE m.rownum = 1", stmt.toString());
}
}
|
package com.geniusgithub.lookaround.test;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.geniusgithub.lookaround.R;
import com.geniusgithub.lookaround.adapter.InfoContentAdapter;
import com.geniusgithub.lookaround.model.BaseType;
import com.geniusgithub.lookaround.model.PublicType;
import com.geniusgithub.lookaround.model.PublicTypeBuilder;
import com.geniusgithub.lookaround.network.BaseRequestPacket;
import com.geniusgithub.lookaround.network.ClientEngine;
import com.geniusgithub.lookaround.network.IRequestContentCallback;
import com.geniusgithub.lookaround.network.IRequestDataPacketCallback;
import com.geniusgithub.lookaround.network.ResponseDataPacket;
import com.geniusgithub.lookaround.proxy.InfoRequestProxy;
import com.geniusgithub.lookaround.util.CommonLog;
import com.geniusgithub.lookaround.util.CommonUtil;
import com.geniusgithub.lookaround.util.LogFactory;
import com.geniusgithub.lookaround.widget.RefreshListView;
public class TestMainActivity extends Activity implements OnClickListener,
InfoRequestProxy.IRequestResult,
RefreshListView.IOnRefreshListener, RefreshListView.IOnLoadMoreListener{
private static final CommonLog log = LogFactory.createLog();
private Button mBtnGetinfo;
private RefreshListView mListView;
private InfoContentAdapter mAdapter;
private List<BaseType.InfoItem> mData = new ArrayList<BaseType.InfoItem>();
private InfoRequestProxy mInfoRequestProxy;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setupViews();
initData();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private void setupViews(){
setContentView(R.layout.test_main_layout);
mBtnGetinfo = (Button) findViewById(R.id.btnGetInfo);
mBtnGetinfo.setOnClickListener(this);
mListView = (RefreshListView) findViewById(R.id.listview);
}
private void initData(){
mAdapter = new InfoContentAdapter(this, mData);
mListView.setAdapter(mAdapter);
mListView.setOnRefreshListener(this);
mListView.setOnLoadMoreListener(this);
BaseType.ListItem item = new BaseType.ListItem();
item.mTypeID = "1";
mInfoRequestProxy = new InfoRequestProxy(this, item, this);
}
private void updateUI(){
mAdapter.refreshData(mData);
}
@Override
public void OnRefresh() {
mInfoRequestProxy.requestRefreshInfo();
}
@Override
public void OnLoadMore() {
mInfoRequestProxy.requestMoreInfo();
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnGetInfo:
mInfoRequestProxy.requestRefreshInfo();
}
}
@Override
public void onSuccess(boolean isLoadMore) {
mData = mInfoRequestProxy.getData();
mAdapter.refreshData(mData);
if (isLoadMore){
mListView.onLoadMoreComplete(false);
}else{
mListView.onRefreshComplete();
}
}
@Override
public void onRequestFailure(boolean isLoadMore) {
CommonUtil.showToast(R.string.toast_getdata_fail, this);
if (isLoadMore){
mListView.onLoadMoreComplete(false);
}else{
mListView.onRefreshComplete();
}
}
@Override
public void onAnylizeFailure(boolean isLoadMore) {
CommonUtil.showToast(R.string.toast_getdata_fail, this);
if (isLoadMore){
mListView.onLoadMoreComplete(false);
}else{
mListView.onRefreshComplete();
}
}
} |
package com.gsccs.sme.plat.svg.dao;
import com.gsccs.sme.api.domain.StatistGroup;
import com.gsccs.sme.plat.svg.model.SclassT;
import com.gsccs.sme.plat.svg.model.SclassTExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SclassTMapper {
int countByExample(SclassTExample example);
int deleteByExample(SclassTExample example);
int deleteByPrimaryKey(Long id);
int insert(SclassT record);
List<SclassT> selectByExample(SclassTExample example);
List<SclassT> selectByPageExample(SclassTExample example);
SclassT selectByPrimaryKey(Long id);
int updateByExample(@Param("record") SclassT record,
@Param("example") SclassTExample example);
int updateByPrimaryKey(SclassT record);
List<StatistGroup> selectTopicNumGroup();
} |
package com.beike.service.background.goods;
import java.util.List;
import com.beike.entity.background.goods.Goods;
import com.beike.form.background.goods.GoodsForm;
import com.beike.form.background.top.TopForm;
/**
* Title : GoodsService
* <p/>
* Description :商品信息服务接口类
* <p/>
* CopyRight : CopyRight (c) 2011
* </P>
* Company : Sinobo
* </P>
* JDK Version Used : JDK 5.0 +
* <p/>
* Modification History :
* <p/>
* <pre>NO. Date Modified By Why & What is modified</pre>
* <pre>1 2011-06-03 lvjx Created<pre>
* <p/>
*
* @author lvjx
* @version 1.0.0.2011-06-14
*/
public interface GoodsService {
/**
* Description : 新增商品
* @param goodsForm
* @return
* @throws Exception
*/
public String addGoods(GoodsForm goodsForm) throws Exception;
/**
* Description : 查询商品
* @param goodsForm
* @param startRow
* @param pageSize
* @return
* @throws Exception
*/
public List<Goods> queryGoods(GoodsForm goodsForm,int startRow,int pageSize) throws Exception;
/**
* Description : 查询商品数量
* @param goodsForm
* @return
*/
public int queryGoodsCount(GoodsForm goodsForm);
/**
* Description : 根据商品id查询商品
* @param goodsId
* @return
* @throws Exception
*/
public Goods queryGoodsById(String goodsId) throws Exception;
/**
* Description : 修改商品
* @param goodsForm
* @return
* @throws Exception
*/
public String editGoods(GoodsForm goodsForm) throws Exception;
/**
* Description : 下架商品
* @param goodsForm
* @return
* @throws Exception
*/
public String downGoods(GoodsForm goodsForm) throws Exception;
/**
* Description : 置顶
* @param goodsForm
* @return
* @throws Exception
*/
public String editGoodsTop(GoodsForm goodsForm) throws Exception;
/**
* Description : 修改商品置顶
* @param goodsForm
* @return
* @throws Exception
*/
public String editGoodsIsTop(GoodsForm goodsForm) throws Exception ;
/**
* @param topForm
* @return
* @throws Exception
*/
public String addGoodsTop(TopForm topForm) throws Exception;
/**
* Description : 修改top置顶
* @param topForm
* @return
* @throws Exception
*/
public String updateGoodsTop(TopForm topForm) throws Exception;
/**
* Description : 查看置顶项是否存在
* @param topForm
* @return
* @throws Exception
*/
public boolean queryTopIsExist(int topOldGoods) throws Exception;
}
|
package com.sirma.itt.javacourse.intro.task5.arrayReverse;
import java.util.ArrayList;
import java.util.List;
import com.sirma.itt.javacourse.InputUtils;
/**
* Class for reversing arrays of Integers.
*
* @author simeon
*/
public class ReverseArray {
/**
* Reverses an array of objects.
*
* @param arrayOfInts
* array to be reversed
* @return the reversed array
*/
public List<Integer> reverseArray(List<Integer> arrayOfInts) {
if (InputUtils.isNull(arrayOfInts)) {
List<Integer> res = new ArrayList<Integer>();
res.add(-1);
return res;
}
for (int i = 0; i < arrayOfInts.size() / 2; i++) {
int tmp = arrayOfInts.get(i);
arrayOfInts.set(i, arrayOfInts.get(arrayOfInts.size() - 1 - i));
arrayOfInts.set(arrayOfInts.size() - 1 - i, tmp);
}
return arrayOfInts;
}
}
|
package com.xld.core.dao.user;
import com.xld.core.entity.DO.UserDO;
import com.xld.core.entity.VO.UserVO;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 企业用户数据层
* @author xld
*/
@Repository
public interface IUserMapper {
/**
* 获取用户信息
* @return 用户信息
*/
List<UserVO> listUser();
/**
* 新增实体
* @param userDO 待新增实体
* @return 成功:返回1 失败:返回 0
*/
int insert(UserDO userDO);
/**
* 根据主键获取用户信息
* @param userId 用户Id
* @return 返回 获取的实体
*/
UserDO selectByPrimaryKey(Integer userId);
/**
* 根据主键更新用户信息
* @param updateUser 修改的实体
* @return 成功:返回1 失败:返回 0
*/
int updateByPrimaryKeySelective(UserDO updateUser);
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import webuters.com.geet_uttarakhand20aprilpro.R;
import webuters.com.geet_uttarakhand20aprilpro.adapter.See_all_catagory_Adapter;
import webuters.com.geet_uttarakhand20aprilpro.bean.CategoryGetSetUrl;
import webuters.com.geet_uttarakhand20aprilpro.holder.Holder;
//import com.google.analytics.tracking.android.EasyTracker;
//import com.google.analytics.tracking.android.MapBuilder;
//import com.google.analytics.tracking.android.StandardExceptionParser;
/**
* Created by Tushar on 2/28/2016.
*/
public class See_all_catagory extends Activity {
ListView see_all_cat_list;
ProgressDialog pDialog;
String id, CatagoryName;
TextView cat_text;
ArrayList<CategoryGetSetUrl> catagory_array_list = new ArrayList<CategoryGetSetUrl>();
// private EasyTracker easyTracker = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.see_all_catagory);
// easyTracker = EasyTracker.getInstance(See_all_catagory.this);
// easyTracker.send(MapBuilder.createEvent("your_action", "envet_name", "button_name/id", null).build());
//
// try {
// int a[] = new int[2];
// int num = a[4];
// } catch (ArrayIndexOutOfBoundsException e) {
// easyTracker.send(MapBuilder.createException(
// new StandardExceptionParser(See_all_catagory.this, null)
// .getDescription(Thread.currentThread().getName(), e), false).build());
// }
cat_text=(TextView)findViewById(R.id.cat_text);
cat_text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i= new Intent(See_all_catagory.this,AlbumList.class);
startActivity(i);
}
});
new CatagoryUrlAsynTask().execute();
}
private class CatagoryUrlAsynTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String content = HttpULRConnect.getData(Holder.SINGERS_DETAILES);
Log.e("Category Url Response ---->", String.valueOf(content));
return content;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(See_all_catagory.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onPostExecute(String s) {
catagory_array_list.clear();
try {
pDialog.dismiss();
Log.e("Post Method Call ....", "Method ...");
JSONArray ar = new JSONArray(s);
System.out.println("Array response is ---" + ar);
Log.e("Array response ids---", String.valueOf(ar));
for (int i = 0; i < ar.length(); i++) {
System.out.println("Array response is ---" + ar.length());
JSONObject jsonobject = ar.getJSONObject(i);
CategoryGetSetUrl categoryGetSetUrl = new CategoryGetSetUrl();
id = jsonobject.getString("id");
categoryGetSetUrl.setId(id);
Log.e("cat id ====================>>>>>", id);
CatagoryName = jsonobject.getString("CatagoryName");
categoryGetSetUrl.setCatagoryName(CatagoryName);
Log.e("CatagoryName is ======================>>>>>", CatagoryName);
catagory_array_list.add(categoryGetSetUrl);
Log.e("catagory array is -----+", String.valueOf(catagory_array_list));
}
} catch (JSONException e)
{
e.printStackTrace();
}
See_all_catagory_Adapter catagoryAdapter = new See_all_catagory_Adapter(See_all_catagory.this, R.layout.see_all_catagory, catagory_array_list);
Log.e("Adapter Set here ----->>>", "Adapter set ");
see_all_cat_list = (ListView) findViewById(R.id.see_all_cat_list);
see_all_cat_list.setAdapter(catagoryAdapter);
see_all_cat_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("catagory lis", "item clicked");
Intent i = new Intent(See_all_catagory.this, CatagoryClass.class);
String ID = catagory_array_list.get(position).getId();
i.putExtra("ID", ID);
Log.e("CAt id put ",ID);
String CAT_Name=catagory_array_list.get(position).getCatagoryName();
i.putExtra("CAT_Name",CAT_Name);
Log.e("CAT_Name ----put ",CAT_Name);
// i.putExtra("ID",id);
// Log.e("put cat id -----", String.valueOf(id));
startActivity(i);
}
});
}
}
// @Override
// public void onStart() {
// super.onStart();
// EasyTracker.getInstance(this).activityStart(this);
// }
//
// @Override
// public void onStop() {
// super.onStop();
// EasyTracker.getInstance(this).activityStop(this);
// }
} |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileToList {
public static List<Kid> readFileToKidList (File file) {
List<Kid> chosenListName = new ArrayList<>();
try{
FileReader myFileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(myFileReader);
bufferedReader.readLine();
String fileLine;
while ((fileLine = bufferedReader.readLine()) != null) {
String[] cildrenArray = fileLine.split(";");
for (int i = 0; i < cildrenArray.length; i++) {
Kid temp = new Kid(cildrenArray[0], cildrenArray[1],
cildrenArray[2], cildrenArray[3], cildrenArray[4]);
chosenListName.add(temp);
}
}
return chosenListName;
}catch (IOException e){
e.printStackTrace();
return null;
}
}
public static List readFileToToyList (File file) {
List<Toy> listToys = new ArrayList<>();
try{
FileReader myFileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(myFileReader);
bufferedReader.readLine();
String fileLine;
while ((fileLine = bufferedReader.readLine()) != null) {
String[] toyArray = fileLine.split(";");
for (int i = 0; i < toyArray.length; i++) {
Toy temp = new Toy(toyArray[0], toyArray[1], toyArray[2],
toyArray[3]);
listToys.add(temp);
}
}
return listToys;
}catch (IOException e){
e.printStackTrace();
return null;
}
}
}
|
/*
**********************************************************************************
* MIT License *
* *
* Copyright (c) 2017 Josh Larson *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in all *
* copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *
* SOFTWARE. *
**********************************************************************************
*/
package me.joshlarson.json.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;
import me.joshlarson.json.JSONArray;
import me.joshlarson.json.JSONException;
import me.joshlarson.json.JSONInputStream;
import me.joshlarson.json.JSONObject;
import me.joshlarson.json.JSONOutputStream;
public class SimpleJson {
public static void main(String [] args) throws IOException, JSONException {
JSONObject obj = createObject();
long start = System.nanoTime();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONOutputStream out = new JSONOutputStream(baos);
out.setCompact(true);
out.writeObject(obj);
long end = System.nanoTime();
System.out.print(baos.toString());
System.out.printf("%n%.6fms%n", (end-start)/1E6);
start = System.nanoTime();
System.out.print(obj.toString());
end = System.nanoTime();
System.out.printf("%n%.6fms%n", (end-start)/1E6);
String json = obj.toString();
try (JSONInputStream reader = new JSONInputStream(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))) {
start = System.nanoTime();
Map<String, Object> readObj = reader.readObject();
end = System.nanoTime();
for (Entry<String, Object> e : readObj.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
System.out.printf("%.6fms%n", (end-start)/1E6);
}
out.close();
}
private static JSONObject createObject() {
JSONObject obj = new JSONObject();
obj.put("from", "thephpdev");
obj.put("text", "This is some long chunk of text!");
obj.put("time", System.currentTimeMillis());
obj.put("invalid_double", Double.NaN);
JSONArray array = new JSONArray();
array.add(true);
array.add(1234);
array.add("testing!");
array.add(null);
obj.put("array", array);
obj.put("my_null", null);
return obj;
}
}
|
package com.example.ssandbox_testing;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import ai.djl.Model;
import ai.djl.inference.Predictor;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.transform.Normalize;
import ai.djl.modality.cv.transform.Resize;
import ai.djl.modality.cv.transform.ToTensor;
import ai.djl.translate.Pipeline;
import ai.djl.translate.Translator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import tech.gusavila92.websocketclient.WebSocketClient;
import org.pytorch.Module;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import ai.djl.modality.Classifications;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.translator.ImageClassificationTranslator;
import ai.djl.repository.zoo.Criteria;
import androidx.fragment.app.Fragment;
public class localInferenceFragment extends Fragment {
View view;
private WebSocketClient webSocketClient;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_localinference,container,false);
// createWebSocketClient();
Button send_button = view.findViewById(R.id.sendButton);
send_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
sendMessage(v);
}
});
Button load_button = view.findViewById(R.id.loadImage);
load_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
loadImage(v);
}
});
Button next_button = view.findViewById(R.id.next_button);
next_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
loadImage(v);
}
});
Button prev_button = view.findViewById(R.id.prev_button);
prev_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
loadImage(v);
}
});
Button predict = view.findViewById(R.id.Predict);
predict.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
predict();
}
});
return view;
}
private void createWebSocketClient() {
URI uri;
try {
// Connect to local host
uri = new URI("ws://192.168.1.149:8765");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
webSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen() {
Log.i("WebSocket", "Session is starting");
}
@Override
public void onTextReceived(String s) {
Log.i("WebSocket", "Message received");
}
@Override
public void onBinaryReceived(byte[] data) {
try {
File file = new File(Environment.getExternalStorageDirectory().toString()+"/testing","model.pt");
FileOutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
Module module = Module.load(Environment.getExternalStorageDirectory().toString()+"/testing/model.pt");
} catch (IOException e) {
e.printStackTrace();
}
TextView textView = view.findViewById(R.id.textView);
textView.setText("received!");
}
@Override
public void onPingReceived(byte[] data) {
}
@Override
public void onPongReceived(byte[] data) {
}
@Override
public void onException(Exception e) {
System.out.println(e.getMessage());
}
@Override
public void onCloseReceived() {
Log.i("WebSocket", "Closed ");
System.out.println("onCloseReceived");
}
};
webSocketClient.setConnectTimeout(10000);
webSocketClient.setReadTimeout(60000);
webSocketClient.enableAutomaticReconnection(5000);
webSocketClient.connect();
}
//we tag the button to this function
public void sendMessage(View view) {
Log.i("WebSocket", "Button was clicked");
// Send button id string to WebSocket Server
switch(view.getId()){
case(R.id.sendButton):
webSocketClient.send("Save");
break;
}
}
private int page = 0;
private int pageItem = 6;
private int fileNumber = 0;
public void imageload_function(int page,int pageItem){
File image_folder = new File(Environment.getExternalStorageDirectory().toString()+"/Pictures/AS_testing/MyCameraApp");
fileNumber = image_folder.listFiles().length;
Log.i("image","number of files is : "+fileNumber);
for (int i = page*pageItem ; i <(page*pageItem)+pageItem; i ++){
if (i < fileNumber) {
Log.i("image","file number : "+i);
File image_file = new File(Environment.getExternalStorageDirectory().toString() + "/Pictures/AS_testing/MyCameraApp"+File.separator + i + ".jpg");
String filePath = image_file.getAbsolutePath();
Bitmap bmImg = BitmapFactory.decodeFile(filePath);
int id = getResources().getIdentifier("imageView" + i%pageItem, "id", this.getContext().getPackageName());
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bmImg, 0, 0, bmImg.getWidth(), bmImg.getHeight(), matrix, true);
ImageView imview = view.findViewById(id);
imview.setImageBitmap(rotatedBitmap);
//Reset the predictions to 0
int Pid = getResources().getIdentifier("Prediction" + i%pageItem, "id", this.getContext().getPackageName());
EditText EditT = view.findViewById(Pid);
EditT.setText("None");
}
else{
//Reset the images to null
int id = getResources().getIdentifier("imageView" + i%pageItem, "id", this.getContext().getPackageName());
ImageView imview = view.findViewById(id);
imview.setImageBitmap(null);
//Reset the predictions to 0
int Pid = getResources().getIdentifier("Prediction" + i%pageItem, "id", this.getContext().getPackageName());
EditText EditT = view.findViewById(Pid);
EditT.setText("None");
}
}
}
//load image button
public void loadImage(View view){
Log.i("image","loading images");
//load images from the saved folder
switch(view.getId()){
//load image
case(R.id.loadImage):
imageload_function(page,pageItem);
break;
//load next page of images
case(R.id.next_button):
page++;
imageload_function(page,pageItem);
break;
//load prev page of images
case(R.id.prev_button):
page--;
imageload_function(page,pageItem);
break;
}
}
//predict image button
public void predict(){
//set directory to search for models
System.setProperty("ai.djl.repository.zoo.location",Environment.getExternalStorageDirectory().toString() + "/testing");
Log.i("model","predict images");
Criteria<Image, Classifications> criteria = Criteria.builder()
.setTypes(Image.class,Classifications.class)
.optArtifactId("ai.djl.localmodelzoo:model")
.build();
try {
//load model directly without the use of model zoo
Path modelDir = Paths.get(Environment.getExternalStorageDirectory().toString() + "/testing");
Model model = Model.newInstance("model");
model.load(modelDir,"model");
//create a translator to translate to output labels
Pipeline pipeline = new Pipeline();
pipeline.add(new Resize(224,224)).add(new ToTensor()).add(new Normalize(
new float[] {0.485f, 0.456f, 0.406f},
new float[] {0.229f, 0.224f, 0.225f}));
Translator<Image,Classifications> translator = ImageClassificationTranslator.builder()
.setPipeline(pipeline)
.optApplySoftmax(true)
.build();
Predictor<Image,Classifications> predictor = model.newPredictor(translator);
// if (fileNumber == 0){
// //display popup to load image first
// Log.i("Prediction","Pop up to load images first" + classification);
// }
for (int i = page*pageItem ; i <(page*pageItem)+pageItem; i ++){
if (i < fileNumber) {
Log.i("image","file number : "+i);
File image_file = new File(Environment.getExternalStorageDirectory().toString() + "/Pictures/AS_testing/MyCameraApp/" + i + ".jpg");
Log.i("image",Environment.getExternalStorageDirectory().toString() + "/Pictures/AS_testing/MyCameraApp/" + i + ".jpg");
String filePath = image_file.getAbsolutePath();
Path img_path = Paths.get(filePath);
Image img = ImageFactory.getInstance().fromFile(img_path);
img.getWrappedImage();
Classifications classification = predictor.predict(img);
int id = getResources().getIdentifier("Prediction" + i%pageItem, "id", this.getContext().getPackageName());
String result = classification.best().getClassName();
Log.i("image",result);
EditText EditT = view.findViewById(id);
EditT.setText("Class : %s".format(result));
}
else{
int id = getResources().getIdentifier("Prediction" + i%pageItem, "id", this.getContext().getPackageName());
EditText EditT = view.findViewById(id);
EditT.setText("None");
}
}
}catch(Exception e){
Log.i("model","loading model failed");
e.printStackTrace();
}
}
}
|
package com.psing.professional_streaming.dataobject;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
*专业
*/
@Entity
@Data
public class Major {
@Id
private String majorId;
/**
* 专业负责人
*/
private String charge;
/**
* 学院
*/
private String institute;
/**
* 分流专业
*/
private String major;
/**
* 大类专业
*/
private String majorCategories;
}
|
package Keywords;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import com.sun.mail.handlers.text_html;
import AdditionalSetup.Objects;
import AdditionalSetup.ResultUpdation;
import Common.Information;
import Running.Final;
//import sun.awt.www.content.image.jpeg;
public class TableValidation implements Information {
WebDriver driver;
boolean cond = false;
Objects obj;
ResultUpdation ru;
String displayResult = "";
public TableValidation(WebDriver driver, ExtentTest test) throws Exception {
this.driver = driver;
obj = new Objects(driver, test);
ru = new ResultUpdation(obj);
}
public String testing(Properties p, String[] record, int row, String sh, int resultRow, String[] imp)
throws Exception {
try {
obj.getJavaScript().scroll(
driver.findElement(obj.getLocators().getObject(p, record[OBJECTNAME], record[OBJECTTYPE])), "up");
int fail = 0;
String[] elements = record[VALUE].split(",");
List<WebElement> tableRowsElements = driver
.findElements(obj.getLocators().getObject(p, record[OBJECTNAME], record[OBJECTTYPE]));
System.out.println(tableRowsElements.size());
List<WebElement> headers = ELEMENTS_LIST.get(elements[0].trim());
List<WebElement> planningVersions = ELEMENTS_LIST.get(elements[1].trim());
String reportCondition=elements[2].trim();
System.out.println("Report Condition(True/False:"+reportCondition);
List<String> versionValues = new ArrayList<>();
for (WebElement versionElement : planningVersions) {
versionValues.add(obj.getJavaScript().getInnerText(versionElement));
}
System.out.println("versionValues :: " + versionValues);
ArrayList<String> headerName = new ArrayList<String>();
for (WebElement element : headers)
headerName.add(element.getText());
ArrayList<Map<String, Double>> month_values = new ArrayList<>();
for (int i = 1; i <= tableRowsElements.size(); i++) {
WebElement tableRow = driver.findElement(By.xpath(p.getProperty(record[OBJECTNAME]) + "[" + i + "]"));
List<WebElement> cells = tableRow.findElements(By.tagName("td"));
Map<String, Double> months = new LinkedHashMap<String, Double>();
int count = 0;
double d = 0.0;
for (WebElement cell : cells) {
if (!cell.getAttribute("class").equals("dummyCell")) {
String valueFromCell;
if (obj.getJavaScript().getInnerHTML(cell).trim().contains("<input")) {
WebElement input = cell.findElement(By.tagName("input"));
valueFromCell = obj.getJavaScript().getInputText(input);
} else
valueFromCell = cell.getText().replace(",", "").trim();
valueFromCell = valueFromCell.replaceAll("%", "");
// System.out.println("valueFromCell :: "+valueFromCell);
double convertedValue;
if (valueFromCell.equals("-") || valueFromCell.equals(" "))
convertedValue = 0;
else {
if (valueFromCell != null && valueFromCell.contains("(")) {
System.out.println("Before paranthesis removal :: " + valueFromCell);
valueFromCell = valueFromCell.replaceAll("\\(", "");
valueFromCell = valueFromCell.replaceAll("\\)", "");
valueFromCell = "-" + valueFromCell;
System.out.println("After paranthesis removal :: " + valueFromCell);
}
convertedValue = Double.parseDouble(valueFromCell);
}
months.put(headerName.get(count), convertedValue);
count++;
}
}
month_values.add(months);
System.out.println("Month values:" + month_values);
int month = 1;
if (i == 1) {
month = Integer.parseInt(versionValues.get(0).split("-")[1]);
} else {
month = Integer.parseInt(versionValues.get(0).split("-")[1]);
System.out.println("month is " + month);
}
double q1addition = months.get("Jan") + months.get("Feb") + months.get("Mar");
double q2addition = months.get("Apr") + months.get("May") + months.get("Jun");
double q3addition = months.get("Jul") + months.get("Aug") + months.get("Sep");
double q4addition = months.get("Oct") + months.get("Nov") + months.get("Dec");
double ytd = 0;
for (int k = 1; k < month; k++) {
// SimpleDateFormat sdf1 = new SimpleDateFormat("M");
// SimpleDateFormat sdf2 = new SimpleDateFormat("MMM");
// System.out.println(sdf2.format(sdf1.parse(String.valueOf(k))));
ytd = ytd + months.get(headerName.get(k - 1));
}
double ltg = 0;
for (int c = month; c <= 12; c++) {
ltg = ltg + months.get(headerName.get(c - 1));
}
System.out.println("Q1 value:" + q1addition + " -> " + months.get("Q1"));
System.out.println("Q2 value:" + q2addition + " -> " + months.get("Q2"));
System.out.println("Q3 value:" + q3addition + " -> " + months.get("Q3"));
System.out.println("Q4 value:" + q4addition + " -> " + months.get("Q4"));
System.out.println("YTD value:" + ytd + " ->" + months.get("YTD"));
System.out.println("LTG value:" + ltg + " ->" + months.get("LTG"));
double total = q1addition + q2addition + q3addition + q4addition;
System.out.println("Full year:" + total + " -> " + months.get("Full Year"));
if(reportCondition.equalsIgnoreCase("True")) {
displayResult = displayResult + "<br>Row-" + i;
fail = fail + validateValues(q1addition, months.get("Q1"), "Q1",reportCondition);
fail = fail + validateValues(q2addition, months.get("Q2"), "Q2",reportCondition);
fail = fail + validateValues(q3addition, months.get("Q3"), "Q3",reportCondition);
fail = fail + validateValues(q4addition, months.get("Q4"), "Q4",reportCondition);
fail = fail + validateValues(total, months.get("Full Year"), "Full Year",reportCondition);
fail = fail + validateValues(ytd, months.get("YTD"), "YTD",reportCondition);
fail = fail + validateValues(ltg, months.get("LTG"), "LTG",reportCondition);
}
}
if (fail == 0) {
cond = true;
obj.getExcelResult().setData(cond, row, sh, resultRow, Information.PASS, imp);
obj.getExtentTest().log(LogStatus.PASS, record[STEPNUMBER],
"Description: " + record[DESCRIPTION] + "\n" + displayResult);
} else {
cond = false;
obj.getExcelResult().setData(cond, row, sh, resultRow, Information.FAIL, imp);
obj.getExtentTest().log(LogStatus.FAIL, record[STEPNUMBER], "Description: " + record[DESCRIPTION]
+ "\nPlease check below rows. " + fail + " are failed<br>" + displayResult);
}
TABLE_VALUES.put(record[OBJECTNAME], month_values);
return cond ? Information.PASS : Information.FAIL;
} catch (Exception ne) {
ne.printStackTrace();
return Information.FAIL;
}
}
private int validateValues(double actual, double expected, String label, String check) {
int condition=1;
try {
System.out.println("entered checking condition loop");
if(!(Math.floor(actual) == Math.floor(expected) || Math.ceil(actual) == Math.ceil(expected))) {
//condition =1;
displayResult = displayResult + "<br><span style='color:red'>"+label+" value:"+actual+" -> "+expected+"</span>";
}
else {
condition =0;
displayResult = displayResult + "<br>"+label+" value:"+actual+" -> "+expected;
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return condition;
}
}
/*
* public String ContributionPercentage(Properties p,String[] record,int row,
* String sh, int resultRow,String[] imp) throws Exception{
*
* try{
* obj.getJavaScript().scroll(driver.findElement(obj.getLocators().getObject(p,
* record[OBJECTNAME],record[OBJECTTYPE])), "up");
*
* int fail =0; String[] elements = record[VALUE].split(","); List<WebElement>
* tableRowsElements =
* driver.findElements(obj.getLocators().getObject(p,record[OBJECTNAME],record[
* OBJECTTYPE])); System.out.println(tableRowsElements.size()); List<WebElement>
* headers = ELEMENTS_LIST.get(elements[0].trim()); List<WebElement>
* planningVersions = ELEMENTS_LIST.get(elements[1].trim()); List<String>
* versionValues = new ArrayList<>(); for(WebElement versionElement :
* planningVersions) {
* versionValues.add(obj.getJavaScript().getInnerText(versionElement)); }
* System.out.println("versionValues :: "+versionValues); ArrayList<String>
* headerName = new ArrayList<String>(); for(WebElement element: headers)
* headerName.add(element.getText()); ArrayList<Map<String, Double>>
* month_values = new ArrayList<>();
*
* for(int i=1; i<=tableRowsElements.size(); i++) { WebElement tableRow =
* driver.findElement(By.xpath(p.getProperty(record[OBJECTNAME])+"["+i+"]"));
* List<WebElement> cells = tableRow.findElements(By.tagName("td")); Map<String,
* Double> months = new LinkedHashMap<String, Double>(); int count =0; double d
* =0.0; for(WebElement cell: cells) {
* if(!cell.getAttribute("class").equals("dummyCell")) { String valueFromCell =
* cell.getText().replace(",", "").trim(); valueFromCell =
* valueFromCell.replaceAll("%", "");
*
* //System.out.println("valueFromCell :: "+valueFromCell); double
* convertedValue; if(valueFromCell.equals("-") || valueFromCell.equals(" "))
* convertedValue =0; else { if(valueFromCell != null &&
* valueFromCell.contains("(")) {
* System.out.println("Before paranthesis removal :: "+valueFromCell);
* valueFromCell = valueFromCell.replaceAll("\\(", ""); valueFromCell =
* valueFromCell.replaceAll("\\)", ""); valueFromCell = "-"+valueFromCell;
* System.out.println("After paranthesis removal :: "+valueFromCell); }
*
* convertedValue = Double.parseDouble(valueFromCell); }
* months.put(headerName.get(count), convertedValue); count++; } }
* month_values.add(months); System.out.println("Month values:"+month_values);
* int month = 1; if(i ==1) { month =
* Integer.parseInt(versionValues.get(0).split("-")[1]); } else { month =
* Integer.parseInt(versionValues.get(0).split("-")[1]);
* System.out.println("month is "+month); }
*
* double q1addition = (months.get("Jan")+ months.get("Feb")+
* months.get("Mar"))/3; double q2addition = (months.get("Apr")+
* months.get("May")+ months.get("Jun"))/3; double q3addition =
* (months.get("Jul")+ months.get("Aug")+ months.get("Sep"))/3; double
* q4addition = (months.get("Oct")+ months.get("Nov")+ months.get("Dec"))/3;
* double ytd=0; for(int k=1;k<month;k++) { //SimpleDateFormat sdf1 = new
* SimpleDateFormat("M"); //SimpleDateFormat sdf2 = new SimpleDateFormat("MMM");
* // System.out.println(sdf2.format(sdf1.parse(String.valueOf(k))));
* ytd=ytd+months.get(headerName.get(k-1)); } ytd=ytd/(month-1); double ltg=0;
* for(int c=month;c<=12;c++) { ltg=ltg+months.get(headerName.get(c-1)); }
* ltg=ltg/(12-(month-1));
* System.out.println("Q1 value:"+q1addition+" -> "+months.get("Q1"));
* System.out.println("Q2 value:"+q2addition+" -> "+months.get("Q2"));
* System.out.println("Q3 value:"+q3addition+" -> "+months.get("Q3"));
* System.out.println("Q4 value:"+q4addition+" -> "+months.get("Q4"));
* System.out.println("YTD value:"+ytd+" ->"+months.get("YTD"));
* System.out.println("LTG value:"+ltg+" ->"+months.get("LTG")); double total =
* q1addition + q2addition + q3addition + q4addition;
* System.out.println("Full year:"+total+" -> "+months.get("Full Year"));
* displayResult= displayResult + "<br>Row-"+i;
*
* fail = fail + validateValues(q1addition, months.get("Q1"), "Q1"); fail = fail
* + validateValues(q2addition, months.get("Q2"), "Q2"); fail = fail +
* validateValues(q3addition, months.get("Q3"), "Q3"); fail = fail +
* validateValues(q4addition, months.get("Q4"), "Q4"); fail = fail +
* validateValues(total, months.get("Full Year"), "Full Year"); fail = fail +
* validateValues(ytd, months.get("YTD"), "YTD"); fail = fail +
* validateValues(ltg, months.get("LTG"), "LTG"); if(!(Math.floor(q1addition) ==
* Math.floor(months.get("Q1")) || Math.ceil(q1addition) ==
* Math.ceil(months.get("Q1")))) fail++; if(!(Math.floor(q2addition) ==
* Math.floor(months.get("Q2")) || Math.ceil(q2addition) ==
* Math.ceil(months.get("Q2")))) fail++; if(!(Math.floor(q3addition) ==
* Math.floor(months.get("Q3")) || Math.ceil(q3addition) ==
* Math.ceil(months.get("Q3")))) fail++; if(!(Math.floor(q4addition) ==
* Math.floor( months.get("Q4")) || Math.ceil(q4addition) ==
* Math.ceil(months.get("Q4")))) fail++; if(!(Math.floor(total) ==
* Math.floor(months.get("Full Year")) || Math.ceil(total) ==
* Math.ceil(months.get("Full Year")))) fail++; if(!(Math.floor(ytd) ==
* Math.floor(months.get("YTD")) || Math.ceil(ytd) ==
* Math.ceil(months.get("YTD")))) fail++; if(!(Math.floor(ltg) ==
* Math.floor(months.get("LTG")) || Math.ceil(ltg) ==
* Math.ceil(months.get("LTG")))) fail++; }
*
* if(fail ==0 ) { cond = true; obj.getExcelResult().setData(cond, row, sh,
* resultRow, Information.PASS, imp); obj.getExtentTest().log(LogStatus.PASS,
* record[STEPNUMBER], "Description: " + record[DESCRIPTION] + "\n" +
* displayResult); } else { cond = false; obj.getExcelResult().setData(cond,
* row, sh, resultRow, Information.FAIL, imp);
*
* obj.getExtentTest().log(LogStatus.FAIL, record[STEPNUMBER], "Description: " +
* record[DESCRIPTION] + "\nPlease check below rows. "+fail+" are failed<br>" +
* displayResult);
*
* }
*
* TABLE_VALUES.put(record[OBJECTNAME], month_values);
*
*
*
* return cond ? Information.PASS: Information.FAIL; } catch(Exception ne){
*
* ne.printStackTrace(); return Information.FAIL; }
*
* } }
*/ |
package classes;
public class Customer {
private int ID;
private static int counter = 1;
private int meat;
private int vegetables;
private int fruits;
private Till till;
public Customer(int meat, int vegetables, int fruits, Till till) {
this.ID = counter;
counter++;
this.meat = meat;
this.vegetables = vegetables;
this.fruits = fruits;
this.till = till;
}
public int getID() {
return this.ID;
}
public int getMeat() {
return this.meat;
}
public int getVegetables() {
return this.vegetables;
}
public int getFruits() {
return this.fruits;
}
public Till getTill() {
return this.till;
}
@Override
public String toString() {
return "Customer {" + " ID='" + getID() + "'" + ", meat='" + getMeat() + "'" + ", vegetables='" + getVegetables()
+ "'" + ", fruits='" + getFruits() + "'" + "}";
}
} |
package models;
/*
Oferta
---
status {Nowa OR Odrzucona OR Zakońcozna}
typ {Sprzedaż OR Kupno}
prowizja od wystawienia oferty
prowizja od zawarcia transakcji
---
wyświetl()
wylistuj oferty()
*/
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.Setter;
import utils.FileUtils;
import utils.JSON;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Offer {
public enum Type {PURCHASE, SALE};
public enum Status {NEW, REJECTED, CLOSED};
private final static String OFFERS_LIST_DATA_FILE_NAME = "data-offers-list.json";
@Getter private static List<Offer> offersList; //MAS1: ekstensja, atrybut powtarzalny
@Setter public static float IssuingCommision; //MAS1: atrybut klasowy
@Setter public static float TransactionCommision;
@Getter private AuthorizedUser owner; //MAS2: Asocjacja binarna
@Getter @Setter private AuthorizedUser participant;
@Getter @Setter private Status status = Status.NEW;
@Getter private Type type;
@Getter private Money fromMoney;
@Getter private Money toMoney;
private List<Transaction> transactionList;
public Offer(Type type, AuthorizedUser owner, Money fromMoney, Money toMoney) {
this.type = type;
this.owner = owner;
this.fromMoney = fromMoney;
this.toMoney = toMoney;
this.transactionList = new ArrayList<>();
Offer.addToOffersList(this);
}
public void addToTransactionsList(Transaction tx) {
this.transactionList.add(tx);
}
public List<Transaction> getLastTransactions(int transactionsNumber) {
List<Transaction> lastTransactions = new ArrayList<>();
for (int i = this.transactionList.size(); i > transactionsNumber; i--) {
lastTransactions.add(this.transactionList.get(i));
}
return lastTransactions;
}
public Transaction getLastTransaction() {
return this.transactionList.get(this.transactionList.size());
}
public static void addToOffersList(Offer offer) {
if (Offer.offersList == null) {
Offer.offersList = new ArrayList<>();
}
Offer.offersList.add(offer);
}
public static List<Offer> findOffersByUser(String login) {
List<Offer> result = new ArrayList<>();
for (Offer offer: offersList) {
if (offer.getOwner().getLogin() == login) {
result.add(offer);
}
}
return result;
}
public static List<Offer> findOffersByUser(AuthorizedUser user) {
return findOffersByUser(user.getLogin());
}
public static void printOffers() { //MAS: metoda klasowa
StringBuilder stringBuilder = new StringBuilder();
for (Offer offer : Offer.offersList) {
stringBuilder.append(offer.toString());
}
System.out.println(stringBuilder.toString());
}
private static String serializeOffersList() {
return JSON.toJSON(Offer.offersList);
}
private static List<Offer> jsonToOffersList(String json) {
List<Offer> offersList = JSON.parse(json, new TypeToken<List<Offer>>(){}.getType());
return offersList;
}
public static void saveOffersList() throws IOException { //MAS: ekstensja - trwałość
String serialized = serializeOffersList();
FileUtils.write(OFFERS_LIST_DATA_FILE_NAME, serialized);
}
public static void loadOffersList() throws IOException {
String json = FileUtils.read(OFFERS_LIST_DATA_FILE_NAME);
List<Offer> offerList = jsonToOffersList(json);
Offer.offersList = offerList;
}
@Override
public String toString() {
return String.format(
"Offer: { type: %s, owner: %s, from: %s, to: %s", this.type, this.owner, this.fromMoney, this.toMoney);
}
}
|
package game.states;
import java.awt.Graphics2D;
import game.core.GameTracker;
import game.input.GameInput;
import game.worlds.World;
public class GameState extends State {
private GameTracker tracker;
private World world;
public GameState(GameTracker tracker, GameInput input) {
world = new World();
world.setGameState(this);
world.setInput(input);
world.loadMap("/res/worlds/tiles.txt", "/res/worlds/powerUps.txt");
this.tracker = tracker;
}
public void update() {
world.update(tracker.getSeconds());
}
@Override
public void draw(Graphics2D g) {
world.draw(g);
}
}
|
package symap.contig;
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.PopupMenuEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import symap.SyMAPConstants;
import symap.drawingpanel.DrawingPanel;
import symap.marker.MarkerFilter;
import symap.marker.MarkerTrack;
import number.GenomicsNumber;
/**
* The filter window for a contig view.
*
* @author Austin Shoemaker
*/
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
public class ContigFilter extends MarkerFilter {
private static final int VISIBLE_CLONE_REMARKS = 4;
private static final int MAX_WIDTH = 3500;
private JTextField cloneNameText;
private JTextField startText;
private JTextField endText;
private JTextField contigText;
private JComboBox cloneNameCombo;
private JSlider widthSlider;
private JCheckBox showCloneNamesBox;
private JCheckBox showOnly2BESHitClonesBox, showOnly2BESCurrentHitClonesBox;
private JComboBox cloneRemarksCombo;
private JList cloneRemarksList;
private JCheckBoxMenuItem showCloneNamesPopupBox; // mdb added 3/15/07 #104
private JCheckBoxMenuItem showOnly2BESHitClonesPopupBox; // mdb added 3/15/07 #104
private JCheckBoxMenuItem showOnly2BESCurrentHitClonesPopupBox; // mdb added 3/15/07 #104
private Contig contig;
private String cloneFilter;
private boolean showCloneNames;
private boolean showOnly2BESHitClones, showOnly2BESCurrentHitClones;
private String startStr, endStr;
private int width, contigNum, cloneFilterInd;
private int[] selectedRemarkIndices;
private int cloneRemarksInd;
private boolean noChange = false;
public ContigFilter(Frame owner, DrawingPanel dp, AbstractButton helpButton, Contig contig) {
super(owner,dp,"Contig Filter",helpButton,(MarkerTrack)contig);
this.contig = contig;
String[] showHideHighlight = new String[3];
showHideHighlight[Contig.CLONE_SHOW] = "Show";
showHideHighlight[Contig.CLONE_HIDE] = "Hide";
showHideHighlight[Contig.CLONE_HIGHLIGHT] = "Highlight";
Container contentPane = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
cloneRemarksCombo = new JComboBox(showHideHighlight);
cloneRemarksCombo.setSelectedIndex(Contig.CLONE_HIGHLIGHT);
cloneRemarksCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!noChange) {
Object[] objs = cloneRemarksList.getSelectedValues();
if (objs != null && objs.length > 0) {
int[] remarks = new int[objs.length];
for (int i = 0; i < objs.length; ++i) remarks[i] = ((CloneRemarks.CloneRemark)objs[i]).getID();
ContigFilter.this.contig.setSelectedRemarks(remarks,cloneRemarksCombo.getSelectedIndex());
refresh();
}
}
}
});
cloneRemarksList = new JList();
cloneRemarksList.setLayoutOrientation(JList.VERTICAL);
cloneRemarksList.setVisibleRowCount(VISIBLE_CLONE_REMARKS);
cloneRemarksList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!noChange) { //&& !e.getValueIsAdjusting()) {
Object[] objs = cloneRemarksList.getSelectedValues();
int[] remarks = new int[objs.length];
for (int i = 0; i < objs.length; ++i) remarks[i] = ((CloneRemarks.CloneRemark)objs[i]).getID();
ContigFilter.this.contig.setSelectedRemarks(remarks,cloneRemarksCombo.getSelectedIndex());
refresh();
}
}
});
JScrollPane scrollPane = new JScrollPane(cloneRemarksList);
cloneNameText = new JTextField("", 10);
startText = new JTextField("", 4);
endText = new JTextField("", 4);
contigText = new JTextField(new Integer(contig.getContig()).toString(), 3);
cloneNameCombo = new JComboBox(showHideHighlight);
widthSlider = new JSlider(JSlider.HORIZONTAL, 0, MAX_WIDTH, width);
showCloneNamesBox = new JCheckBox("Show Clone Names");
showOnly2BESHitClonesBox = new JCheckBox("Show Only Clones With BES Paired Hits");
showOnly2BESCurrentHitClonesBox = new JCheckBox("Show Only Clones With Visible BES Paired Hits");
widthSlider.addChangeListener(this);
showCloneNamesBox.addChangeListener(this);
showOnly2BESHitClonesBox.addChangeListener(this);
showOnly2BESCurrentHitClonesBox.addChangeListener(this);
contentPane.setLayout(gridbag);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(1,1,1,1);
constraints.gridheight = 1;
constraints.ipadx = 5;
constraints.ipady = 8;
addToGrid(contentPane,gridbag,constraints,new JLabel("Change Contig:"),1);
addToGrid(contentPane,gridbag,constraints,contigText,1);
addToGrid(contentPane,gridbag,constraints,new JLabel(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JSeparator(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JLabel("Clone Name:"),1);
addToGrid(contentPane,gridbag,constraints,cloneNameText,1);
addToGrid(contentPane,gridbag,constraints,cloneNameCombo,1);
addToGrid(contentPane,gridbag,constraints,new JLabel(),GridBagConstraints.REMAINDER);
addMarkerNameFilterToGrid(contentPane,gridbag,constraints);
addToGrid(contentPane,gridbag,constraints,cloneRemarksCombo,1);
addToGrid(contentPane,gridbag,constraints,new JLabel(" Clones with Remarks:"),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,scrollPane,GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JSeparator(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JLabel("Start:"),1);
addToGrid(contentPane,gridbag,constraints,startText,1);
addToGrid(contentPane,gridbag,constraints,new JLabel(GenomicsNumber.CB),1);
addToGrid(contentPane,gridbag,constraints,new JLabel(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JLabel("End:"),1);
addToGrid(contentPane,gridbag,constraints,endText,1);
addToGrid(contentPane,gridbag,constraints,new JLabel(GenomicsNumber.CB),1);
addToGrid(contentPane,gridbag,constraints,new JLabel(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JLabel("Width of Contig:"),1);
addToGrid(contentPane,gridbag,constraints,widthSlider,GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,showCloneNamesBox,2);
addToGrid(contentPane,gridbag,constraints,getFlippedBox(),GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,new JSeparator(),GridBagConstraints.REMAINDER);
constraints.anchor = GridBagConstraints.CENTER;
addMarkerFilterToGrid(contentPane,gridbag,constraints);
addToGrid(contentPane,gridbag,constraints,new JSeparator(),GridBagConstraints.REMAINDER);
constraints.anchor = GridBagConstraints.CENTER;
addToGrid(contentPane,gridbag,constraints,showOnly2BESHitClonesBox,GridBagConstraints.REMAINDER);
constraints.anchor = GridBagConstraints.CENTER;
addToGrid(contentPane,gridbag,constraints,showOnly2BESCurrentHitClonesBox,GridBagConstraints.REMAINDER);
addToGrid(contentPane,gridbag,constraints,buttonPanel,GridBagConstraints.REMAINDER);
pack();
setResizable(false);
// mdb added 3/15/07 #104 -- BEGIN
//popupTitle.setLabel("Contig Options:"); // mdb removed 7/2/07 #118
popupTitle.setText("Contig Options:"); // mdb added 7/2/07 #118
//SyMAP.enableHelpOnButton(showNavigationHelp,"contigcontrols"); // mdb removed 4/30/09 #162
//SyMAP.enableHelpOnButton(showTrackHelp,"contigtrack"); // mdb removed 4/30/09 #162
showCloneNamesPopupBox = new JCheckBoxMenuItem("Show Clone Names");
showOnly2BESHitClonesPopupBox = new JCheckBoxMenuItem("Show Only Clones With BES Paired Hits");
showOnly2BESCurrentHitClonesPopupBox = new JCheckBoxMenuItem("Show Only Clones With Visible BES Paired Hits");
popup.add(showCloneNamesPopupBox);
popup.add(showOnly2BESHitClonesPopupBox);
popup.add(showOnly2BESCurrentHitClonesPopupBox);
ActionListener pmnl = new ActionListener() {
public void actionPerformed(ActionEvent event) {
setCursor(SyMAPConstants.WAIT_CURSOR);
if (event.getSource() == showCloneNamesPopupBox) {
showCloneNamesBox.setSelected(showCloneNamesPopupBox.getState());
stateChanged(new ChangeEvent(showCloneNamesBox));
}
if (event.getSource() == showOnly2BESHitClonesPopupBox) {
showOnly2BESHitClonesBox.setSelected(showOnly2BESHitClonesPopupBox.getState());
stateChanged(new ChangeEvent(showOnly2BESHitClonesBox));
}
if (event.getSource() == showOnly2BESCurrentHitClonesPopupBox) {
showOnly2BESCurrentHitClonesBox.setSelected(showOnly2BESCurrentHitClonesPopupBox.getState());
stateChanged(new ChangeEvent(showOnly2BESCurrentHitClonesBox));
}
try { okAction(); }
catch (Exception e) { }
drawingPanel.smake();
setCursor(SyMAPConstants.DEFAULT_CURSOR);
}
};
showCloneNamesPopupBox.addActionListener(pmnl);
showOnly2BESHitClonesPopupBox.addActionListener(pmnl);
showOnly2BESCurrentHitClonesPopupBox.addActionListener(pmnl);
// mdb added 3/15/07 #104 -- END
}
public String getHelpID() {
return "contigfilter";//Filter.CONTIG_FILTER_ID;
}
protected void setDefault() {
contigText.setText(new Integer(contig.contig).toString());
widthSlider.setValue(contig.getBaseWidth());
showOnly2BESHitClonesBox.setSelected(false);
showOnly2BESCurrentHitClonesBox.setSelected(false);
showCloneNamesBox.setSelected(Contig.DEFAULT_SHOW_CLONE_NAMES);
cloneNameCombo.setSelectedIndex(Contig.CLONE_SHOW);
cloneNameText.setText("");
startText.setText("0");
endText.setText(new Long(contig.getTrackSize()).toString());
super.setDefault();
}
// mdb moved out of show() 3/15/07 #104
private void setupShow() {
noChange = true;
setStart();
setEnd();
startStr = startText.getText();
endStr = endText.getText();
contigNum = contig.contig;
width = contig.getContigWidth();
showCloneNames = contig.showCloneNames;
cloneFilter = contig.cloneFilterPattern;
cloneFilterInd = contig.cloneFilterShow;
showOnly2BESHitClones = contig.showBothBESFilter == Clone.BOTH_BES_COND_FILTERED;
showOnly2BESCurrentHitClones = contig.showBothBESFilter == Clone.BOTH_BES_CURRENT_COND_FILTERED;
contigText.setText(new Integer(contigNum).toString());
widthSlider.setValue(width);
showCloneNamesBox.setSelected(showCloneNames);
showOnly2BESHitClonesBox.setSelected(showOnly2BESHitClones);
showOnly2BESCurrentHitClonesBox.setSelected(showOnly2BESCurrentHitClones);
cloneNameCombo.setSelectedIndex(cloneFilterInd);
cloneNameText.setText(cloneFilter);
cloneRemarksInd = contig.cloneRemarkShow;
cloneRemarksCombo.setSelectedIndex(cloneRemarksInd);
cloneRemarksList.setListData(contig.getCloneRemarks());
selectedRemarkIndices = contig.getSelectedRemarkIndices();
Arrays.sort(selectedRemarkIndices);
cloneRemarksList.setSelectedIndices(contig.getSelectedRemarkIndices());
cloneRemarksList.setVisibleRowCount(VISIBLE_CLONE_REMARKS);
pack();
noChange = false;
}
public void show() {
if (!isShowing()) setupShow();
super.show();
}
/**
* Method <code>canShow</code> returns true if the Contig has been initialized.
*
* @return a <code>boolean</code> value
*/
public boolean canShow() {
if (contig == null) return false;
return contig.hasInit();
}
private void setStart() {
if (contig != null)
startText.setText(new Long(contig.getStart()).toString());
}
private void setEnd() {
if (contig != null)
endText.setText(new Long(contig.getEnd()).toString());
}
protected void didFlip() {
setStart();
setEnd();
}
protected boolean okAction() throws Exception {
if (contig == null) return false;
long number;
long tstart, tend;
boolean changed = false;
if (!contigText.getText().equals(new Integer(contigNum).toString())) {
int tContigNum;
try {
tContigNum = new Integer(contigText.getText()).intValue();
} catch (NumberFormatException nfe) {
throw new Exception("Contig value entered is not valid.");
}
if (tContigNum < 0) throw new Exception("Contig number entered is negative.");
if (!contig.isContig(tContigNum)) throw new Exception("Contig "+tContigNum+" does not exist.");
contigNum = tContigNum;
if (contigNum != contig.getContig()) {
contig.clearWidth();
contig.setContig(contigNum);
if (!contig.hasInit()) throw new Exception("Problem initializing Contig");
contig.resetStart();
contig.resetEnd();
setStart();
setEnd();
cloneNameText.setText("");
cloneNameCombo.setSelectedIndex(Contig.CLONE_SHOW);
widthSlider.setValue(contig.getBaseWidth());
}
}
if (widthSlider.getValue() != width) {
width = widthSlider.getValue();
changed = true;
}
if (!cloneFilter.equals(cloneNameText.getText()) || cloneFilterInd != cloneNameCombo.getSelectedIndex()) {
cloneFilter = cloneNameText.getText();
cloneFilterInd = cloneNameCombo.getSelectedIndex();
contig.filterCloneNames(cloneFilter,cloneFilterInd);
}
tstart = contig.getStart();
tend = contig.getEnd();
if (startText.getText().trim().length() > 0) {
try {
number = (long)Math.round((new Double(startText.getText())).doubleValue());
} catch (NumberFormatException nfe) {
throw new Exception("Start value entered is not a number.");
}
try {
contig.setStart(number);
} catch (IllegalArgumentException e) {
setStart();
throw new Exception("Invalid start value entered.");
}
} else {
contig.resetStart();
startText.setText(new Long(contig.getStart()).toString());
}
if (endText.getText().trim().length() > 0) {
try {
number = (long)Math.round((new Double(endText.getText())).doubleValue());
} catch (NumberFormatException nfe) {
throw new Exception("End value entered is not a number.");
}
long newNum;
try {
newNum = contig.setEnd(number);
} catch (IllegalArgumentException e) {
setEnd();
throw new Exception("Invalid end value entered.");
}
if (newNum != number) endText.setText(new Long(newNum).toString());
} else {
contig.resetEnd();
endText.setText((new Long(contig.getEnd())).toString());
}
if (contig.getStart() == contig.getEnd()) {
contig.setStart(tstart);
contig.setEnd(tend);
throw new Exception("The start and end value must be different.");
}
startStr = startText.getText();
endStr = endText.getText();
if (super.okAction()) changed = true;
if (showCloneNames != showCloneNamesBox.isSelected()) {
showCloneNames = !showCloneNames;
changed = true;
}
if (showOnly2BESHitClones != showOnly2BESHitClonesBox.isSelected()) {
showOnly2BESHitClones = !showOnly2BESHitClones;
//if (showOnly2BESHitClones) drawingPanel.downloadAllHits(contig);
changed = true;
}
if (showOnly2BESCurrentHitClones != showOnly2BESCurrentHitClonesBox.isSelected()) {
showOnly2BESCurrentHitClones = !showOnly2BESCurrentHitClones;
changed = true;
}
if (cloneRemarksInd != cloneRemarksCombo.getSelectedIndex() && cloneRemarksList.getSelectedIndices() != null &&
cloneRemarksList.getSelectedIndices().length > 0) changed = true;
if (!Arrays.equals(selectedRemarkIndices,cloneRemarksList.getSelectedIndices())) changed = true;
return (changed || !contig.hasBuilt());
}
/**
* Handles the width slider, showing clone names, showing relevant marker names, showing all marker names
* (super.stateChanged(ChangeEvent)), and refreshing the view.
*
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent event) {
if (contig != null && !noChange) {
if (event.getSource() == widthSlider) {
contig.setWidth(widthSlider.getValue());
}
else if (event.getSource() == showCloneNamesBox) {
contig.showCloneNames(showCloneNamesBox.isSelected());
}
else if (event.getSource() == showOnly2BESCurrentHitClonesBox) {
if (showOnly2BESCurrentHitClonesBox.isSelected()) {
contig.showBothBESFilter(Clone.BOTH_BES_CURRENT_COND_FILTERED);
showOnly2BESHitClonesBox.setSelected(false);
}
else if (showOnly2BESHitClonesBox.isSelected()) {
contig.showBothBESFilter(Clone.BOTH_BES_COND_FILTERED);
}
else {
contig.showBothBESFilter(Contig.NO_BOTH_BES_FILTER);
}
}
else if (event.getSource() == showOnly2BESHitClonesBox) {
if (showOnly2BESHitClonesBox.isSelected()) {
contig.showBothBESFilter(Clone.BOTH_BES_COND_FILTERED);
showOnly2BESCurrentHitClonesBox.setSelected(false);
}
else if (showOnly2BESCurrentHitClonesBox.isSelected()) {
contig.showBothBESFilter(Clone.BOTH_BES_CURRENT_COND_FILTERED);
}
else {
contig.showBothBESFilter(Contig.NO_BOTH_BES_FILTER);
}
}
else {
super.stateChanged(event);
return ; /* !!!!!! refresh() is handled in MarkerFilter !!!!!! */
}
refresh();
}
}
// mdb added 3/15/07 #104
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
setupShow();
showCloneNamesPopupBox.setState(showCloneNames);
showOnly2BESHitClonesPopupBox.setState(showOnly2BESHitClones);
showOnly2BESCurrentHitClonesPopupBox.setState(showOnly2BESCurrentHitClones);
super.popupMenuWillBecomeVisible(event);
}
protected void cancelAction() {
super.cancelAction();
cloneNameText.setText(cloneFilter);
cloneNameCombo.setSelectedIndex(cloneFilterInd);
startText.setText(startStr);
endText.setText(endStr);
widthSlider.setValue(width);
showCloneNamesBox.setSelected(showCloneNames);
contigText.setText(new Integer(contigNum).toString());
}
}
|
/**
*
*/
package TestContent;
import org.junit.Test;
/**
* Test of the Content class
*
* @author Alex Dalencourt
* @author Sellenia Chikhoune
*
*/
public interface TestContent {
@Test
public void test_getDescription();
}
|
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Collections;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
Contact contact = new Contact("Rocket", "https://github.com/VitRocket", "");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfo("Api", "Api Documentation", "1.0.0", "", contact, "", "", Collections.emptyList()))
.select()
.paths(PathSelectors.regex("(/products.*)|(/actuator.*)"))
.build();
}
}
|
package com.esum.common.exception;
import com.esum.framework.core.exception.SystemException;
/**
* XTrusException은 xTrus에서 발생하는 모든 exception의 최상위를 나타낸다.
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class XTrusException extends SystemException {
public XTrusException(String location, Throwable exception) {
super(location, exception);
}
public XTrusException(String location, String message) {
super(location, message);
}
public XTrusException(String code, String location, String message) {
super(code, location, message);
}
public XTrusException(String location, String message, Throwable cause) {
super(location, message, cause);
}
public XTrusException(String code, String location, Throwable exception, Throwable cause) {
super(code, location, exception, cause);
}
public XTrusException(String code, String location, String message, Throwable cause) {
super(code, location, message, cause);
}
}
|
package mypack;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JTable;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
public class Allemployeedetail extends JDialog implements ActionListener
{
private JTable table;
public Allemployeedetail()
{
getContentPane().setLayout(null);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
},
new String[] {
"New column", "New column", "New column", "New column", "New column", "New column"
}
));
table.setBorder(new LineBorder(new Color(0, 0, 0)));
table.setBounds(81, 361, 409, -222);
getContentPane().add(table);
JButton click = new JButton("Click Here to See");
click.setBounds(139, 22, 174, 50);
getContentPane().add(click);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
}
|
package test.freelancer.com.fltest.guides.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import test.freelancer.com.fltest.R;
import test.freelancer.com.fltest.data.entity.Guide;
/**
* Created by Android 18 on 5/11/2016.
*/
public class GuideViewHolder extends RecyclerView.ViewHolder {
TextView mTextViewName;
TextView mTextViewStartTime;
TextView mTextViewEndTime;
TextView mTextViewChannel;
TextView mTextViewRating;
public GuideViewHolder(View itemView) {
super(itemView);
}
public static GuideViewHolder create(LayoutInflater inflater, ViewGroup parent) {
GuideViewHolder viewHolder =
new GuideViewHolder(inflater.inflate(R.layout.fragment_list_item_guide, parent, false));
viewHolder.mTextViewName = (TextView) viewHolder.itemView
.findViewById(R.id.fragment_list_item_guide_text_view_name);
viewHolder.mTextViewStartTime = (TextView) viewHolder.itemView
.findViewById(R.id.fragment_list_item_guide_text_view_start_date);
viewHolder.mTextViewEndTime = (TextView) viewHolder.itemView
.findViewById(R.id.fragment_list_item_guide_text_view_end_date);
viewHolder.mTextViewChannel = (TextView) viewHolder.itemView
.findViewById(R.id.fragment_list_item_guide_text_view_channel);
viewHolder.mTextViewRating = (TextView) viewHolder.itemView
.findViewById(R.id.fragment_list_item_guide_text_view_rating);
return viewHolder;
}
public void bind(Guide guide) {
mTextViewName.setText(guide.getName());
mTextViewStartTime.setText(guide.getStartTime());
mTextViewEndTime.setText(guide.getEndTime());
mTextViewChannel.setText(guide.getChannel());
mTextViewRating.setText(guide.getRating());
}
}
|
package com.romens.yjkgrab;
/**
* Created by myq on 15-12-11.
*/
public class Constant {
public static final String OBJECT_ID="objectId";
public static final String STATUS_WAITING_GRAB="待抢";
public static final String STATUS_WAITING_TAKE="待取";
public static final String STATUS_WAITING_SEND="待送";
public static final String STATUS_FINISH="完成";
public static final String STATUS_INVALID="失效";
}
|
package tests;
import controller.OperationFailedException;
import integration.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import util.Amount;
import util.ItemIdentifier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class DbHandlerTest {
private DbHandler dbhandler;
@BeforeEach
void setup() {
ExternalAccounting ea = new ExternalAccounting();
ExternalInventory ei = new ExternalInventory();
dbhandler = new DbHandler(ei, ea);
}
@AfterEach
void tearDown() {
dbhandler = null;
}
/**
*
* @throws OperationFailedException
*/
@Test
void testGetItemDTO() throws OperationFailedException {
try {
ItemIdentifier getBanana = new ItemIdentifier("100");
ItemDTO actual = dbhandler.getItemDTO(getBanana);
ItemDTO expected = new ItemDTO("banana", "yellow", new Amount(20), new Amount(12));
assertEquals(expected.getName(), actual.getName(), "getItemDTO() fails!");
} catch (DatabaseConnectionFailureException | NoSuchItemIdentifierException e) {
throw new OperationFailedException(e.getMessage());
}
}
@Test
void testItemDoesNotExist() throws OperationFailedException {
ItemIdentifier getBanana = new ItemIdentifier("1001");
try {
ItemDTO actual = dbhandler.getItemDTO(getBanana);
ItemDTO expected = new ItemDTO("banana", "yellow", new Amount(20), new Amount(12));
fail("Could not find the ID");
} catch (DatabaseConnectionFailureException | NoSuchItemIdentifierException e) {
assertTrue(e.getMessage().contains(getBanana.toString()), "Wrong exception message");
}
}
@Test
void testUpdateExternalSystems(){
SaleDTO saleDTO = new SaleDTO(null, null, null, null);
dbhandler.updateExternalSystems(saleDTO);
}
}
|
package com.lenovohit.ssm.treat.transfer.manager;
import java.util.List;
import com.lenovohit.ssm.treat.transfer.dao.RestResponse;
public class HisListResponse<T> extends HisResponse {
public HisListResponse(){
}
public HisListResponse(RestResponse reponse){
super(reponse);
}
private List<T> hisList;
public List<T> getList() {
return hisList;
}
public void setList(List<T> hisList) {
this.hisList = hisList;
}
}
|
package rimabegum.example.com.quizrima;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
public class GenaralKnowledge extends AppCompatActivity {
private Button Solutionhomebutton;
ScrollView scrollView;
TextView Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8,Q9,Q10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.genaralknowlege_solution);
Solutionhomebutton = (Button) findViewById(R.id.Solutionhomebutton);
scrollView = (ScrollView) findViewById(R.id.Sv);
Q1 = (TextView) findViewById(R.id.Q1);
Q2 = (TextView) findViewById(R.id.Q2);
Q3 = (TextView) findViewById(R.id.Q3);
Q4 = (TextView) findViewById(R.id.Q4);
Q5 = (TextView) findViewById(R.id.Q5);
Solutionhomebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GenaralKnowledge.this, SolutionCatagory.class);
startActivity(intent);
finish();
}
});
}
}
|
package pecia.socialmap;
import java.util.Date;
/**
* Created by Francesco on 15/06/17.
*/
public class ChatMess {
private String messText;
private String messUser;
private long messTime;
private String topic;
private String UserId;
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public ChatMess(String messText, String messUser, String userId, String topic) {
this.messText = messText;
this.messUser = messUser;
this.topic = topic;
this.UserId = userId;
messTime = new Date().getTime();
}
public ChatMess() {
}
public String getMessText() {
return messText;
}
public void setMessText(String messText) {
this.messText = messText;
}
public String getMessUser() {
return messUser;
}
public void setMessUser(String messUser) {
this.messUser = messUser;
}
public long getMessTime() {
return messTime;
}
public void setMessTime(long messTime) {
this.messTime = messTime;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
}
|
package com.openfarmanager.android.filesystem.actions.multi.network;
import android.content.Context;
import com.openfarmanager.android.filesystem.actions.OnActionListener;
import com.openfarmanager.android.fragments.BaseFileSystemPanel;
import com.openfarmanager.android.fragments.NetworkPanel;
import com.openfarmanager.android.model.NetworkEnum;
import com.openfarmanager.android.model.TaskStatusEnum;
import org.apache.commons.io.FileDeleteStrategy;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.openfarmanager.android.model.TaskStatusEnum.ERROR_DELETE_FILE;
import static com.openfarmanager.android.model.TaskStatusEnum.ERROR_FILE_NOT_EXISTS;
/**
* @author Vlad Namashko
*/
public class MoveToNetworkMultiTask extends CopyToNetworkMultiTask {
public MoveToNetworkMultiTask(NetworkPanel panel, List<File> items, String destination) {
super(panel, items, destination);
}
@Override
public TaskStatusEnum doAction() {
FileDeleteStrategy strategy = FileDeleteStrategy.FORCE;
for (File file : mItems) {
try {
strategy.delete(file);
} catch (NullPointerException e) {
return ERROR_FILE_NOT_EXISTS;
} catch (IOException e) {
return ERROR_DELETE_FILE;
} catch (Exception e) {
return ERROR_DELETE_FILE;
}
}
return TaskStatusEnum.OK;
}
protected Runnable getActionRunnable() {
return mActionRunnable;
}
private Runnable mActionRunnable = () -> {
calculateSize();
TaskStatusEnum status = MoveToNetworkMultiTask.super.doAction();
if (hasSubTasks() && handleSubTasks(status)) {
return;
}
onTaskDone(doAction());
};
}
|
package psoft.backend.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import psoft.backend.model.Comentario;
import java.io.Serializable;
import java.util.List;
public interface ComentarioDAO<T, ID extends Serializable> extends JpaRepository<Comentario, Long> {
Comentario save(Comentario comentario);
Comentario findById(long id);
List<Comentario> findAll();
}
|
package structural.decorator;
/**
* @author Renat Kaitmazov
*/
public class SportsCar extends CarDecorator {
/*--------------------------------------------------------*/
/* Constructors
/*--------------------------------------------------------*/
public SportsCar(Car car) {
super(car);
}
/*--------------------------------------------------------*/
/* API
/*--------------------------------------------------------*/
@Override
public final void assemble() {
super.assemble();
System.out.println("Adding capabilities of a sports car.");
}
}
|
package cn.com.finn.util;
/**
*
* @author Finn Zhao
* @version 2017年2月15日
*/
public class HashCodeUtils {
/**
* The default initial value to use in reflection hash code building.
*/
private static final int DEFAULT_INITIAL_VALUE = 17;
/**
* The default multipler value to use in reflection hash code building.
*/
private static final int DEFAULT_MULTIPLIER_VALUE = 31;
// private HashCodeHolder holder;
private HashCodeUtils() {
}
public static HashCodeHolder getInstance() {
return new HashCodeHolder(DEFAULT_INITIAL_VALUE);
}
public static HashCodeHolder getInstance(int initialHashcode) {
return new HashCodeHolder(initialHashcode);
}
public static class HashCodeHolder {
private int hashcode;
public HashCodeHolder(int initialHashcode) {
this.hashcode = initialHashcode;
}
public int getHashcode() {
return hashcode;
}
public HashCodeHolder append(String hashcode) {
return this.appendInt(hashcode.hashCode());
}
public HashCodeHolder append(byte hashcode) {
return this.appendInt(hashcode);
}
public HashCodeHolder append(short hashcode) {
return this.appendInt(hashcode);
}
public HashCodeHolder append(char hashcode) {
return this.appendInt(hashcode);
}
public HashCodeHolder append(long hashcode) {
return this.appendInt((int) (hashcode ^ (hashcode >>> 32)));
}
public HashCodeHolder append(float hashcode) {
return this.appendInt(Float.floatToIntBits(hashcode));
}
public HashCodeHolder append(double hashcode) {
return this.append(Double.doubleToLongBits(hashcode));
}
public HashCodeHolder append(boolean hashcode) {
return this.appendInt(hashcode ? 1 : 0);
}
public HashCodeHolder appendInt(int hashcode) {
this.hashcode = this.hashcode * DEFAULT_MULTIPLIER_VALUE + hashcode;
return this;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.